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

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: Fixing default cert_ value. Created 5 years, 1 month 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:
87 enum Type {
88 TYPE_HTTP,
89 TYPE_HTTPS,
90 };
91
92 enum ServerCertificate {
93 CERT_OK,
94
95 CERT_MISMATCHED_NAME,
96 CERT_EXPIRED,
97
98 // A certificate with invalid notBefore and notAfter times. Windows'
99 // certificate library will not parse this certificate.
100 CERT_BAD_VALIDITY,
101
102 // Cross-signed certificate to test PKIX path building. Contains an
103 // intermediate cross-signed by an unknown root, while the client (via
104 // TestRootStore) is expected to have a self-signed version of the
105 // intermediate.
106 CERT_CHAIN_WRONG_ROOT,
107
108 // Causes the testserver to use a hostname that is a domain
109 // instead of an IP.
110 CERT_COMMON_NAME_IS_DOMAIN,
111 };
112
85 typedef base::Callback<scoped_ptr<HttpResponse>( 113 typedef base::Callback<scoped_ptr<HttpResponse>(
86 const HttpRequest& request)> HandleRequestCallback; 114 const HttpRequest& request)> HandleRequestCallback;
87 115
88 // Creates a http test server. InitializeAndWaitUntilReady() must be called 116 // Creates a http test server. Start() must be called to start the server.
89 // to start the server. 117 // |type| indicates the protocol type of the server. (HTTP/HTTPS)
davidben 2015/10/26 21:30:08 Nit: |type| indicates the protocol type of the ser
svaldez 2015/10/26 21:37:57 Done.
90 EmbeddedTestServer(); 118 EmbeddedTestServer();
119 explicit EmbeddedTestServer(Type type);
91 ~EmbeddedTestServer(); 120 ~EmbeddedTestServer();
92 121
93 // Sets a connection listener, that would be notified when various connection 122 // Sets a connection listener, that would be notified when various connection
94 // events happen. May only be called before the server is started. Caller 123 // events happen. May only be called before the server is started. Caller
95 // maintains ownership of the listener. 124 // maintains ownership of the listener.
96 void SetConnectionListener(EmbeddedTestServerConnectionListener* listener); 125 void SetConnectionListener(EmbeddedTestServerConnectionListener* listener);
97 126
98 // Initializes and waits until the server is ready to accept requests. 127 // Initializes and waits until the server is ready to accept requests.
99 // This is the equivalent of calling InitializeAndListen() followed by 128 // This is the equivalent of calling InitializeAndListen() followed by
100 // StartAcceptingConnections(). 129 // StartAcceptingConnections().
101 // Returns whether a listening socket has been succesfully created. 130 // Returns whether a listening socket has been successfully created.
131 bool Start();
132
133 // Deprecated method that calls Start().
134 // TODO(svaldez): Remove and replace with Start().
102 bool InitializeAndWaitUntilReady() WARN_UNUSED_RESULT; 135 bool InitializeAndWaitUntilReady() WARN_UNUSED_RESULT;
103 136
104 // Starts listening for incoming connections but will not yet accept them. 137 // Starts listening for incoming connections but will not yet accept them.
105 // Returns whether a listening socket has been succesfully created. 138 // Returns whether a listening socket has been succesfully created.
106 bool InitializeAndListen() WARN_UNUSED_RESULT; 139 bool InitializeAndListen() WARN_UNUSED_RESULT;
107 140
108 // Starts the Accept IO Thread and begins accepting connections. 141 // Starts the Accept IO Thread and begins accepting connections.
109 void StartAcceptingConnections(); 142 void StartAcceptingConnections();
110 143
111 // Shuts down the http server and waits until the shutdown is complete. 144 // Shuts down the http server and waits until the shutdown is complete.
112 bool ShutdownAndWaitUntilComplete() WARN_UNUSED_RESULT; 145 bool ShutdownAndWaitUntilComplete() WARN_UNUSED_RESULT;
113 146
114 // Checks if the server has started listening for incoming connections. 147 // Checks if the server has started listening for incoming connections.
115 bool Started() const { 148 bool Started() const {
116 return listen_socket_.get() != NULL; 149 return listen_socket_.get() != NULL;
117 } 150 }
118 151
152 HostPortPair host_port_pair() const {
153 return HostPortPair::FromURL(base_url_);
154 }
155
119 // Returns the base URL to the server, which looks like 156 // 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 157 // http://127.0.0.1:<port>/, where <port> is the actual port number used by
121 // the server. 158 // the server.
122 const GURL& base_url() const { return base_url_; } 159 const GURL& base_url() const { return base_url_; }
123 160
124 // Returns a URL to the server based on the given relative URL, which 161 // Returns a URL to the server based on the given relative URL, which
125 // should start with '/'. For example: GetURL("/path?query=foo") => 162 // should start with '/'. For example: GetURL("/path?query=foo") =>
126 // http://127.0.0.1:<port>/path?query=foo. 163 // http://127.0.0.1:<port>/path?query=foo.
127 GURL GetURL(const std::string& relative_url) const; 164 GURL GetURL(const std::string& relative_url) const;
128 165
129 // Similar to the above method with the difference that it uses the supplied 166 // 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 167 // |hostname| for the URL instead of 127.0.0.1. The hostname should be
131 // resolved to 127.0.0.1. 168 // resolved to 127.0.0.1.
132 GURL GetURL(const std::string& hostname, 169 GURL GetURL(const std::string& hostname,
133 const std::string& relative_url) const; 170 const std::string& relative_url) const;
134 171
135 // Returns the address list needed to connect to the server. 172 // Returns the address list needed to connect to the server.
136 bool GetAddressList(net::AddressList* address_list) const WARN_UNUSED_RESULT; 173 bool GetAddressList(AddressList* address_list) const WARN_UNUSED_RESULT;
137 174
138 // Returns the port number used by the server. 175 // Returns the port number used by the server.
139 uint16 port() const { return port_; } 176 uint16 port() const { return port_; }
140 177
178 // Returns whether we are using SSL.
179 bool is_using_ssl() const { return is_using_ssl_; }
180
181 void SetSSLConfig(ServerCertificate cert, const SSLServerConfig& ssl_config);
182 void SetSSLConfig(ServerCertificate cert);
183
184 // Returns the file name of the certificate the server is using.
davidben 2015/10/26 21:30:08 Nit: I'd maybe mention that the certificate may be
svaldez 2015/10/26 21:37:57 Done.
185 std::string GetCertificateName() const;
186
187 // Returns the certificate that the server is using.
188 scoped_refptr<X509Certificate> GetCertificate() const;
189
141 // Registers request handler which serves files from |directory|. 190 // Registers request handler which serves files from |directory|.
142 // For instance, a request to "/foo.html" is served by "foo.html" under 191 // 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 192 // |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|). 193 // (i.e. "/foo/bar.html" is served by "foo/bar.html" under |directory|).
194 // TODO(svaldez): Merge ServeFilesFromDirectory and
195 // ServeFilesFromSourceDirectory.
145 void ServeFilesFromDirectory(const base::FilePath& directory); 196 void ServeFilesFromDirectory(const base::FilePath& directory);
146 197
198 // Serves files relative to DIR_SOURCE_ROOT.
199 void ServeFilesFromSourceDirectory(const std::string& relative);
200 void ServeFilesFromSourceDirectory(const base::FilePath& relative);
201
202 // Registers the default handlers and serve additional files from the
203 // |directory| directory, relative to DIR_SOURCE_ROOT.
204 void AddDefaultHandlers(const base::FilePath& directory);
205
147 // The most general purpose method. Any request processing can be added using 206 // The most general purpose method. Any request processing can be added using
148 // this method. Takes ownership of the object. The |callback| is called 207 // this method. Takes ownership of the object. The |callback| is called
149 // on UI thread. 208 // on UI thread.
150 void RegisterRequestHandler(const HandleRequestCallback& callback); 209 void RegisterRequestHandler(const HandleRequestCallback& callback);
151 210
211 // Adds default handlers, including those added by AddDefaultHandlers, to be
212 // tried after all other user-specified handlers have been tried.
213 void RegisterDefaultHandler(const HandleRequestCallback& callback);
214
152 private: 215 private:
153 // Shuts down the server. 216 // Shuts down the server.
154 void ShutdownOnIOThread(); 217 void ShutdownOnIOThread();
155 218
219 // Upgrade the TCP connection to one over SSL.
220 scoped_ptr<StreamSocket> DoSSLUpgrade(scoped_ptr<StreamSocket> connection);
221 // Handles async callback when the SSL handshake has been completed.
222 void OnHandshakeDone(HttpConnection* connection, int rv);
223
156 // Begins accepting new client connections. 224 // Begins accepting new client connections.
157 void DoAcceptLoop(); 225 void DoAcceptLoop();
158 // Handles async callback when there is a new client socket. |rv| is the 226 // Handles async callback when there is a new client socket. |rv| is the
159 // return value of the socket Accept. 227 // return value of the socket Accept.
160 void OnAcceptCompleted(int rv); 228 void OnAcceptCompleted(int rv);
161 // Adds the new |socket| to the list of clients and begins the reading 229 // Adds the new |socket| to the list of clients and begins the reading
162 // data. 230 // data.
163 void HandleAcceptResult(scoped_ptr<StreamSocket> socket); 231 void HandleAcceptResult(scoped_ptr<StreamSocket> socket);
164 232
165 // Attempts to read data from the |connection|'s socket. 233 // Attempts to read data from the |connection|'s socket.
(...skipping 11 matching lines...) Expand all
177 // request handlers and sends a http response. 245 // request handlers and sends a http response.
178 void HandleRequest(HttpConnection* connection, 246 void HandleRequest(HttpConnection* connection,
179 scoped_ptr<HttpRequest> request); 247 scoped_ptr<HttpRequest> request);
180 248
181 HttpConnection* FindConnection(StreamSocket* socket); 249 HttpConnection* FindConnection(StreamSocket* socket);
182 250
183 // Posts a task to the |io_thread_| and waits for a reply. 251 // Posts a task to the |io_thread_| and waits for a reply.
184 bool PostTaskToIOThreadAndWait( 252 bool PostTaskToIOThreadAndWait(
185 const base::Closure& closure) WARN_UNUSED_RESULT; 253 const base::Closure& closure) WARN_UNUSED_RESULT;
186 254
255 const bool is_using_ssl_;
256
187 scoped_ptr<base::Thread> io_thread_; 257 scoped_ptr<base::Thread> io_thread_;
188 258
189 scoped_ptr<TCPServerSocket> listen_socket_; 259 scoped_ptr<TCPServerSocket> listen_socket_;
190 scoped_ptr<StreamSocket> accepted_socket_; 260 scoped_ptr<StreamSocket> accepted_socket_;
191 261
192 EmbeddedTestServerConnectionListener* connection_listener_; 262 EmbeddedTestServerConnectionListener* connection_listener_;
193 uint16 port_; 263 uint16 port_;
194 GURL base_url_; 264 GURL base_url_;
195 IPEndPoint local_endpoint_; 265 IPEndPoint local_endpoint_;
196 266
197 // Owns the HttpConnection objects. 267 // Owns the HttpConnection objects.
198 std::map<StreamSocket*, HttpConnection*> connections_; 268 std::map<StreamSocket*, HttpConnection*> connections_;
199 269
200 // Vector of registered request handlers. 270 // Vector of registered and default request handlers.
201 std::vector<HandleRequestCallback> request_handlers_; 271 std::vector<HandleRequestCallback> request_handlers_;
272 std::vector<HandleRequestCallback> default_request_handlers_;
202 273
203 base::ThreadChecker thread_checker_; 274 base::ThreadChecker thread_checker_;
204 275
276 net::SSLServerConfig ssl_config_;
277 ServerCertificate cert_;
278
205 DISALLOW_COPY_AND_ASSIGN(EmbeddedTestServer); 279 DISALLOW_COPY_AND_ASSIGN(EmbeddedTestServer);
206 }; 280 };
207 281
208 } // namespace test_server 282 } // namespace test_server
283
284 // TODO(svaldez): Refactor EmbeddedTestServer to be in the net namespace.
285 using test_server::EmbeddedTestServer;
286
209 } // namespace net 287 } // namespace net
210 288
211 #endif // NET_TEST_EMBEDDED_TEST_SERVER_EMBEDDED_TEST_SERVER_H_ 289 #endif // NET_TEST_EMBEDDED_TEST_SERVER_EMBEDDED_TEST_SERVER_H_
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698