Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(266)

Side by Side Diff: net/test/embedded_test_server/embedded_test_server.h

Issue 1376593007: SSL in EmbeddedTestServer (Closed) Base URL: https://chromium.googlesource.com/chromium/src.git@master
Patch Set: Rebase. Created 5 years, 2 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch
OLDNEW
1 // Copyright (c) 2012 The Chromium Authors. All rights reserved. 1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be 2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file. 3 // found in the LICENSE file.
4 4
5 #ifndef NET_TEST_EMBEDDED_TEST_SERVER_EMBEDDED_TEST_SERVER_H_ 5 #ifndef NET_TEST_EMBEDDED_TEST_SERVER_EMBEDDED_TEST_SERVER_H_
6 #define NET_TEST_EMBEDDED_TEST_SERVER_EMBEDDED_TEST_SERVER_H_ 6 #define NET_TEST_EMBEDDED_TEST_SERVER_EMBEDDED_TEST_SERVER_H_
7 7
8 #include <map> 8 #include <map>
9 #include <string> 9 #include <string>
10 #include <vector> 10 #include <vector>
11 11
12 #include "base/basictypes.h" 12 #include "base/basictypes.h"
13 #include "base/callback.h" 13 #include "base/callback.h"
14 #include "base/compiler_specific.h" 14 #include "base/compiler_specific.h"
15 #include "base/files/file_path.h"
15 #include "base/memory/ref_counted.h" 16 #include "base/memory/ref_counted.h"
16 #include "base/memory/scoped_ptr.h" 17 #include "base/memory/scoped_ptr.h"
17 #include "base/threading/thread.h" 18 #include "base/threading/thread.h"
18 #include "base/threading/thread_checker.h" 19 #include "base/threading/thread_checker.h"
20 #include "crypto/rsa_private_key.h"
19 #include "net/base/address_list.h" 21 #include "net/base/address_list.h"
22 #include "net/base/host_port_pair.h"
20 #include "net/base/ip_endpoint.h" 23 #include "net/base/ip_endpoint.h"
24 #include "net/cert/x509_certificate.h"
25 #include "net/socket/stream_socket.h"
26 #include "net/socket/tcp_server_socket.h"
27 #include "net/ssl/ssl_server_config.h"
21 #include "url/gurl.h" 28 #include "url/gurl.h"
22 29
23 namespace base {
24 class FilePath;
25 }
26
27 namespace net { 30 namespace net {
28 31
29 class StreamSocket; 32 class StreamSocket;
30 class TCPServerSocket; 33 class TCPServerSocket;
31 34
32 namespace test_server { 35 namespace test_server {
33 36
34 class EmbeddedTestServerConnectionListener; 37 class EmbeddedTestServerConnectionListener;
35 class HttpConnection; 38 class HttpConnection;
36 class HttpResponse; 39 class HttpResponse;
37 struct HttpRequest; 40 struct HttpRequest;
38 41
39 // Class providing an HTTP server for testing purpose. This is a basic server 42 // Class providing an HTTP server for testing purpose. This is a basic server
40 // providing only an essential subset of HTTP/1.1 protocol. Especially, 43 // providing only an essential subset of HTTP/1.1 protocol. Especially,
41 // it assumes that the request syntax is correct. It *does not* support 44 // it assumes that the request syntax is correct. It *does not* support
42 // a Chunked Transfer Encoding. 45 // a Chunked Transfer Encoding.
43 // 46 //
44 // The common use case for unit tests is below: 47 // The common use case for unit tests is below:
45 // 48 //
46 // void SetUp() { 49 // void SetUp() {
47 // test_server_.reset(new EmbeddedTestServer()); 50 // test_server_.reset(new EmbeddedTestServer());
48 // ASSERT_TRUE(test_server_.InitializeAndWaitUntilReady()); 51 // ASSERT_TRUE(test_server_.Start());
49 // test_server_->RegisterRequestHandler( 52 // test_server_->RegisterRequestHandler(
50 // base::Bind(&FooTest::HandleRequest, base::Unretained(this))); 53 // base::Bind(&FooTest::HandleRequest, base::Unretained(this)));
51 // } 54 // }
52 // 55 //
53 // scoped_ptr<HttpResponse> HandleRequest(const HttpRequest& request) { 56 // scoped_ptr<HttpResponse> HandleRequest(const HttpRequest& request) {
54 // GURL absolute_url = test_server_->GetURL(request.relative_url); 57 // GURL absolute_url = test_server_->GetURL(request.relative_url);
55 // if (absolute_url.path() != "/test") 58 // if (absolute_url.path() != "/test")
56 // return scoped_ptr<HttpResponse>(); 59 // return scoped_ptr<HttpResponse>();
57 // 60 //
58 // scoped_ptr<BasicHttpResponse> http_response(new BasicHttpResponse()); 61 // scoped_ptr<BasicHttpResponse> http_response(new BasicHttpResponse());
59 // http_response->set_code(test_server::SUCCESS); 62 // http_response->set_code(test_server::SUCCESS);
60 // http_response->set_content("hello"); 63 // http_response->set_content("hello");
61 // http_response->set_content_type("text/plain"); 64 // http_response->set_content_type("text/plain");
62 // return http_response.Pass(); 65 // return http_response.Pass();
63 // } 66 // }
64 // 67 //
65 // For a test that spawns another process such as browser_tests, it is 68 // For a test that spawns another process such as browser_tests, it is
66 // suggested to call InitializeAndWaitUntilReady in SetUpOnMainThread after 69 // suggested to call Start in SetUpOnMainThread after the process is spawned.
67 // the process is spawned. If you have to do it before the process spawns, 70 // If you have to do it before the process spawns, you need to first setup the
68 // you need to first setup the listen socket so that there is no no other 71 // listen socket so that there is no no other threads running while spawning
69 // threads running while spawning the process. To do so, please follow 72 // the process. To do so, please follow the following example:
70 // the following example:
71 // 73 //
72 // void SetUp() { 74 // void SetUp() {
73 // ASSERT_TRUE(embedded_test_server()->InitializeAndListen()); 75 // ASSERT_TRUE(embedded_test_server()->InitializeAndListen());
74 // ... 76 // ...
75 // InProcessBrowserTest::SetUp(); 77 // InProcessBrowserTest::SetUp();
76 // } 78 // }
77 // 79 //
78 // void SetUpOnMainThread() { 80 // void SetUpOnMainThread() {
79 // // Starts the accept IO thread. 81 // // Starts the accept IO thread.
80 // embedded_test_server()->StartAcceptingConnections(); 82 // embedded_test_server()->StartAcceptingConnections();
81 // } 83 // }
82 // 84 //
83 class EmbeddedTestServer { 85 class EmbeddedTestServer {
84 public: 86 public:
85 typedef base::Callback<scoped_ptr<HttpResponse>( 87 typedef base::Callback<scoped_ptr<HttpResponse>(
86 const HttpRequest& request)> HandleRequestCallback; 88 const HttpRequest& request)> HandleRequestCallback;
87 89
88 // Creates a http test server. InitializeAndWaitUntilReady() must be called 90 // Creates a http test server. Start() must be called to start the server.
89 // to start the server. 91 // |use_ssl| indicates whether the server should use SSL for all connections.
90 EmbeddedTestServer(); 92 explicit EmbeddedTestServer(bool use_ssl = false);
davidben 2015/10/13 19:43:48 This should be an enum of some sort.
svaldez 2015/10/13 20:54:44 Done.
91 ~EmbeddedTestServer(); 93 ~EmbeddedTestServer();
92 94
93 // Sets a connection listener, that would be notified when various connection 95 // Sets a connection listener, that would be notified when various connection
94 // events happen. May only be called before the server is started. Caller 96 // events happen. May only be called before the server is started. Caller
95 // maintains ownership of the listener. 97 // maintains ownership of the listener.
96 void SetConnectionListener(EmbeddedTestServerConnectionListener* listener); 98 void SetConnectionListener(EmbeddedTestServerConnectionListener* listener);
97 99
98 // Initializes and waits until the server is ready to accept requests. 100 // Initializes and waits until the server is ready to accept requests.
99 // This is the equivalent of calling InitializeAndListen() followed by 101 // This is the equivalent of calling InitializeAndListen() followed by
100 // StartAcceptingConnections(). 102 // StartAcceptingConnections().
101 // Returns whether a listening socket has been succesfully created. 103 // Returns whether a listening socket has been successfully created.
104 bool Start();
105
106 // Deprecated method that calls Start().
107 // TODO(svaldez): Remove and replace with Start().
102 bool InitializeAndWaitUntilReady() WARN_UNUSED_RESULT; 108 bool InitializeAndWaitUntilReady() WARN_UNUSED_RESULT;
103 109
104 // Starts listening for incoming connections but will not yet accept them. 110 // Starts listening for incoming connections but will not yet accept them.
105 // Returns whether a listening socket has been succesfully created. 111 // Returns whether a listening socket has been succesfully created.
106 bool InitializeAndListen() WARN_UNUSED_RESULT; 112 bool InitializeAndListen() WARN_UNUSED_RESULT;
107 113
108 // Starts the Accept IO Thread and begins accepting connections. 114 // Starts the Accept IO Thread and begins accepting connections.
109 void StartAcceptingConnections(); 115 void StartAcceptingConnections();
110 116
111 // Shuts down the http server and waits until the shutdown is complete. 117 // Shuts down the http server and waits until the shutdown is complete.
112 bool ShutdownAndWaitUntilComplete() WARN_UNUSED_RESULT; 118 bool ShutdownAndWaitUntilComplete() WARN_UNUSED_RESULT;
113 119
114 // Checks if the server has started listening for incoming connections. 120 // Checks if the server has started listening for incoming connections.
115 bool Started() const { 121 bool Started() const {
116 return listen_socket_.get() != NULL; 122 return listen_socket_.get() != NULL;
117 } 123 }
118 124
125 const net::HostPortPair host_port_pair() const {
126 return net::HostPortPair::FromURL(base_url_);
127 }
128
119 // Returns the base URL to the server, which looks like 129 // Returns the base URL to the server, which looks like
120 // http://127.0.0.1:<port>/, where <port> is the actual port number used by 130 // http://127.0.0.1:<port>/, where <port> is the actual port number used by
121 // the server. 131 // the server.
122 const GURL& base_url() const { return base_url_; } 132 const GURL& base_url() const { return base_url_; }
123 133
124 // Returns a URL to the server based on the given relative URL, which 134 // Returns a URL to the server based on the given relative URL, which
125 // should start with '/'. For example: GetURL("/path?query=foo") => 135 // should start with '/'. For example: GetURL("/path?query=foo") =>
126 // http://127.0.0.1:<port>/path?query=foo. 136 // http://127.0.0.1:<port>/path?query=foo.
127 GURL GetURL(const std::string& relative_url) const; 137 GURL GetURL(const std::string& relative_url) const;
128 138
129 // Similar to the above method with the difference that it uses the supplied 139 // Similar to the above method with the difference that it uses the supplied
130 // |hostname| for the URL instead of 127.0.0.1. The hostname should be 140 // |hostname| for the URL instead of 127.0.0.1. The hostname should be
131 // resolved to 127.0.0.1. 141 // resolved to 127.0.0.1.
132 GURL GetURL(const std::string& hostname, 142 GURL GetURL(const std::string& hostname,
133 const std::string& relative_url) const; 143 const std::string& relative_url) const;
134 144
135 // Returns the address list needed to connect to the server. 145 // Returns the address list needed to connect to the server.
136 bool GetAddressList(net::AddressList* address_list) const WARN_UNUSED_RESULT; 146 bool GetAddressList(net::AddressList* address_list) const WARN_UNUSED_RESULT;
137 147
138 // Returns the port number used by the server. 148 // Returns the port number used by the server.
139 uint16 port() const { return port_; } 149 uint16 port() const { return port_; }
140 150
151 // Returns whether we are using SSL.
152 bool UsesSSL() const { return use_ssl_; }
davidben 2015/10/13 19:43:48 Nit: use_ssl()
svaldez 2015/10/13 20:54:44 Done.
153
154 void SetSSLConfig(net::SSLServerConfig ssl_config) {
davidben 2015/10/13 19:43:48 Nit: set_ssl_config()
svaldez 2015/10/13 20:54:44 Done.
155 ssl_config_ = ssl_config;
156 }
davidben 2015/10/13 19:43:48 The spawned test server makes this a constructor p
svaldez 2015/10/13 20:54:44 It seemed neater. This also allows you to reuse a
157
158 // Returns the file name of the certificate the server is using.
159 std::string GetCertificateName() const;
160
161 // Returns the certificate that the server is using.
162 scoped_refptr<X509Certificate> GetCertificate() const;
163
141 // Registers request handler which serves files from |directory|. 164 // Registers request handler which serves files from |directory|.
142 // For instance, a request to "/foo.html" is served by "foo.html" under 165 // For instance, a request to "/foo.html" is served by "foo.html" under
143 // |directory|. Files under sub directories are also handled in the same way 166 // |directory|. Files under sub directories are also handled in the same way
144 // (i.e. "/foo/bar.html" is served by "foo/bar.html" under |directory|). 167 // (i.e. "/foo/bar.html" is served by "foo/bar.html" under |directory|).
145 void ServeFilesFromDirectory(const base::FilePath& directory); 168 void ServeFilesFromDirectory(const base::FilePath& directory);
146 169
170 // Serves files relative to DIR_SOURCE_ROOT.
171 void ServeFilesFromSourceDirectory(const std::string relative);
172 void ServeFilesFromSourceDirectory(const base::FilePath& relative);
173
174 // Registers the default handlers from request_helpers.h.
davidben 2015/10/13 19:43:48 What is directory here?
svaldez 2015/10/13 20:54:44 Done.
175 void AddDefaultHandlers(const base::FilePath& directory);
176
147 // The most general purpose method. Any request processing can be added using 177 // The most general purpose method. Any request processing can be added using
148 // this method. Takes ownership of the object. The |callback| is called 178 // this method. Takes ownership of the object. The |callback| is called
149 // on UI thread. 179 // on UI thread.
150 void RegisterRequestHandler(const HandleRequestCallback& callback); 180 void RegisterRequestHandler(const HandleRequestCallback& callback);
181 void RegisterDefaultHandler(const HandleRequestCallback& callback);
davidben 2015/10/13 19:43:48 What does RegisterDefaultHandler do? (Document.)
svaldez 2015/10/13 20:54:44 Done.
151 182
152 private: 183 private:
153 // Shuts down the server. 184 // Shuts down the server.
154 void ShutdownOnIOThread(); 185 void ShutdownOnIOThread();
155 186
187 // Load the root for the certs being used in testing.
188 void LoadTestSSLRoot();
189 // Upgrade the TCP connection to one over SSL.
190 scoped_ptr<StreamSocket> DoSSLUpgrade(scoped_ptr<StreamSocket> connection);
191 // Handles async callback when we've finished performing the SSL handshake.
192 void OnHandshakeDone(HttpConnection* connection, int rv);
193
156 // Begins accepting new client connections. 194 // Begins accepting new client connections.
157 void DoAcceptLoop(); 195 void DoAcceptLoop();
158 // Handles async callback when there is a new client socket. |rv| is the 196 // Handles async callback when there is a new client socket. |rv| is the
159 // return value of the socket Accept. 197 // return value of the socket Accept.
160 void OnAcceptCompleted(int rv); 198 void OnAcceptCompleted(int rv);
161 // Adds the new |socket| to the list of clients and begins the reading 199 // Adds the new |socket| to the list of clients and begins the reading
162 // data. 200 // data.
163 void HandleAcceptResult(scoped_ptr<StreamSocket> socket); 201 void HandleAcceptResult(scoped_ptr<StreamSocket> socket);
164 202
165 // Attempts to read data from the |connection|'s socket. 203 // Attempts to read data from the |connection|'s socket.
(...skipping 11 matching lines...) Expand all
177 // request handlers and sends a http response. 215 // request handlers and sends a http response.
178 void HandleRequest(HttpConnection* connection, 216 void HandleRequest(HttpConnection* connection,
179 scoped_ptr<HttpRequest> request); 217 scoped_ptr<HttpRequest> request);
180 218
181 HttpConnection* FindConnection(StreamSocket* socket); 219 HttpConnection* FindConnection(StreamSocket* socket);
182 220
183 // Posts a task to the |io_thread_| and waits for a reply. 221 // Posts a task to the |io_thread_| and waits for a reply.
184 bool PostTaskToIOThreadAndWait( 222 bool PostTaskToIOThreadAndWait(
185 const base::Closure& closure) WARN_UNUSED_RESULT; 223 const base::Closure& closure) WARN_UNUSED_RESULT;
186 224
225 bool use_ssl_;
226
187 scoped_ptr<base::Thread> io_thread_; 227 scoped_ptr<base::Thread> io_thread_;
188 228
189 scoped_ptr<TCPServerSocket> listen_socket_; 229 scoped_ptr<TCPServerSocket> listen_socket_;
190 scoped_ptr<StreamSocket> accepted_socket_; 230 scoped_ptr<StreamSocket> accepted_socket_;
191 231
192 EmbeddedTestServerConnectionListener* connection_listener_; 232 EmbeddedTestServerConnectionListener* connection_listener_;
193 uint16 port_; 233 uint16 port_;
194 GURL base_url_; 234 GURL base_url_;
195 IPEndPoint local_endpoint_; 235 IPEndPoint local_endpoint_;
196 236
197 // Owns the HttpConnection objects. 237 // Owns the HttpConnection objects.
198 std::map<StreamSocket*, HttpConnection*> connections_; 238 std::map<StreamSocket*, HttpConnection*> connections_;
199 239
200 // Vector of registered request handlers. 240 // List of registered and default request handlers.
201 std::vector<HandleRequestCallback> request_handlers_; 241 std::vector<HandleRequestCallback> request_handlers_;
242 std::vector<HandleRequestCallback> default_request_handlers_;
202 243
203 base::ThreadChecker thread_checker_; 244 base::ThreadChecker thread_checker_;
204 245
246 net::SSLServerConfig ssl_config_;
247
205 DISALLOW_COPY_AND_ASSIGN(EmbeddedTestServer); 248 DISALLOW_COPY_AND_ASSIGN(EmbeddedTestServer);
206 }; 249 };
207 250
208 } // namespace test_server 251 } // namespace test_server
252
253 // TODO(svaldez): Refactor EmbeddedTestServer to be in the net namespace.
254 using test_server::EmbeddedTestServer;
255
209 } // namespace net 256 } // namespace net
210 257
211 #endif // NET_TEST_EMBEDDED_TEST_SERVER_EMBEDDED_TEST_SERVER_H_ 258 #endif // NET_TEST_EMBEDDED_TEST_SERVER_EMBEDDED_TEST_SERVER_H_
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698