1 // Copyright 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 package org.chromium.net.test.util;
7 import android.util.Base64;
8 import android.util.Log;
9 import android.util.Pair;
11 import org.apache.http.HttpException;
12 import org.apache.http.HttpRequest;
13 import org.apache.http.HttpResponse;
14 import org.apache.http.HttpStatus;
15 import org.apache.http.HttpVersion;
16 import org.apache.http.RequestLine;
17 import org.apache.http.StatusLine;
18 import org.apache.http.entity.ByteArrayEntity;
19 import org.apache.http.impl.DefaultHttpServerConnection;
20 import org.apache.http.impl.cookie.DateUtils;
21 import org.apache.http.message.BasicHttpResponse;
22 import org.apache.http.params.BasicHttpParams;
23 import org.apache.http.params.CoreProtocolPNames;
24 import org.apache.http.params.HttpParams;
26 import java.io.ByteArrayInputStream;
27 import java.io.IOException;
28 import java.io.InputStream;
29 import java.net.MalformedURLException;
30 import java.net.ServerSocket;
31 import java.net.Socket;
34 import java.net.URLConnection;
35 import java.security.KeyManagementException;
36 import java.security.KeyStore;
37 import java.security.NoSuchAlgorithmException;
38 import java.security.cert.X509Certificate;
39 import java.util.ArrayList;
40 import java.util.Date;
41 import java.util.HashMap;
42 import java.util.Hashtable;
43 import java.util.List;
46 import javax.net.ssl.HostnameVerifier;
47 import javax.net.ssl.HttpsURLConnection;
48 import javax.net.ssl.KeyManager;
49 import javax.net.ssl.KeyManagerFactory;
50 import javax.net.ssl.SSLContext;
51 import javax.net.ssl.SSLSession;
52 import javax.net.ssl.X509TrustManager;
55 * Simple http test server for testing.
57 * This server runs in a thread in the current process, so it is convenient
58 * for loopback testing without the need to setup tcp forwarding to the
61 * Based heavily on the CTSWebServer in Android.
63 public final class TestWebServer {
64 private static final String TAG = "TestWebServer";
66 public static final String SHUTDOWN_PREFIX = "/shutdown";
68 private static TestWebServer sInstance;
69 private static TestWebServer sSecureInstance;
70 private static Hashtable<Integer, String> sReasons;
72 private final ServerThread mServerThread;
73 private String mServerUri;
74 private final boolean mSsl;
76 private static class Response {
77 final byte[] mResponseData;
78 final List<Pair<String, String>> mResponseHeaders;
79 final boolean mIsRedirect;
80 final Runnable mResponseAction;
81 final boolean mIsNotFound;
83 Response(byte[] responseData, List<Pair<String, String>> responseHeaders,
84 boolean isRedirect, boolean isNotFound, Runnable responseAction) {
85 mIsRedirect = isRedirect;
86 mIsNotFound = isNotFound;
87 mResponseData = responseData;
88 mResponseHeaders = responseHeaders == null ?
89 new ArrayList<Pair<String, String>>() : responseHeaders;
90 mResponseAction = responseAction;
94 // The Maps below are modified on both the client thread and the internal server thread, so
95 // need to use a lock when accessing them.
96 private final Object mLock = new Object();
97 private final Map<String, Response> mResponseMap = new HashMap<String, Response>();
98 private final Map<String, Integer> mResponseCountMap = new HashMap<String, Integer>();
99 private final Map<String, HttpRequest> mLastRequestMap = new HashMap<String, HttpRequest>();
102 * Create and start a local HTTP server instance.
103 * @param ssl True if the server should be using secure sockets.
106 public TestWebServer(boolean ssl) throws Exception {
109 mServerUri = "https:";
110 if (sSecureInstance != null) {
111 sSecureInstance.shutdown();
114 mServerUri = "http:";
115 if (sInstance != null) {
116 sInstance.shutdown();
120 setInstance(this, mSsl);
121 mServerThread = new ServerThread(this, mSsl);
122 mServerThread.start();
123 mServerUri += "//localhost:" + mServerThread.mSocket.getLocalPort();
127 * Terminate the http server.
129 public void shutdown() {
131 // Avoid a deadlock between two threads where one is trying to call
132 // close() and the other one is calling accept() by sending a GET
133 // request for shutdown and having the server's one thread
134 // sequentially call accept() and close().
135 URL url = new URL(mServerUri + SHUTDOWN_PREFIX);
136 URLConnection connection = openConnection(url);
137 connection.connect();
139 // Read the input from the stream to send the request.
140 InputStream is = connection.getInputStream();
143 // Block until the server thread is done shutting down.
144 mServerThread.join();
146 } catch (MalformedURLException e) {
147 throw new IllegalStateException(e);
148 } catch (InterruptedException e) {
149 throw new RuntimeException(e);
150 } catch (IOException e) {
151 throw new RuntimeException(e);
152 } catch (NoSuchAlgorithmException e) {
153 throw new IllegalStateException(e);
154 } catch (KeyManagementException e) {
155 throw new IllegalStateException(e);
158 setInstance(null, mSsl);
161 private static void setInstance(TestWebServer instance, boolean isSsl) {
163 sSecureInstance = instance;
165 sInstance = instance;
169 private static final int RESPONSE_STATUS_NORMAL = 0;
170 private static final int RESPONSE_STATUS_MOVED_TEMPORARILY = 1;
171 private static final int RESPONSE_STATUS_NOT_FOUND = 2;
173 private String setResponseInternal(
174 String requestPath, byte[] responseData,
175 List<Pair<String, String>> responseHeaders, Runnable responseAction,
177 final boolean isRedirect = (status == RESPONSE_STATUS_MOVED_TEMPORARILY);
178 final boolean isNotFound = (status == RESPONSE_STATUS_NOT_FOUND);
180 synchronized (mLock) {
181 mResponseMap.put(requestPath, new Response(
182 responseData, responseHeaders, isRedirect, isNotFound, responseAction));
183 mResponseCountMap.put(requestPath, Integer.valueOf(0));
184 mLastRequestMap.put(requestPath, null);
186 return getResponseUrl(requestPath);
190 * Gets the URL on the server under which a particular request path will be accessible.
192 * This only gets the URL, you still need to set the response if you intend to access it.
194 * @param requestPath The path to respond to.
195 * @return The full URL including the requestPath.
197 public String getResponseUrl(String requestPath) {
198 return mServerUri + requestPath;
202 * Sets a 404 (not found) response to be returned when a particular request path is passed in.
204 * @param requestPath The path to respond to.
205 * @return The full URL including the path that should be requested to get the expected
208 public String setResponseWithNotFoundStatus(
209 String requestPath) {
210 return setResponseInternal(requestPath, "".getBytes(), null, null,
211 RESPONSE_STATUS_NOT_FOUND);
215 * Sets a response to be returned when a particular request path is passed
216 * in (with the option to specify additional headers).
218 * @param requestPath The path to respond to.
219 * @param responseString The response body that will be returned.
220 * @param responseHeaders Any additional headers that should be returned along with the
221 * response (null is acceptable).
222 * @return The full URL including the path that should be requested to get the expected
225 public String setResponse(
226 String requestPath, String responseString,
227 List<Pair<String, String>> responseHeaders) {
228 return setResponseInternal(requestPath, responseString.getBytes(), responseHeaders, null,
229 RESPONSE_STATUS_NORMAL);
233 * Sets a response to be returned when a particular request path is passed
234 * in with the option to specify additional headers as well as an arbitrary action to be
235 * executed on each request.
237 * @param requestPath The path to respond to.
238 * @param responseString The response body that will be returned.
239 * @param responseHeaders Any additional headers that should be returned along with the
240 * response (null is acceptable).
241 * @param responseAction The action to be performed when fetching the response. This action
242 * will be executed for each request and will be handled on a background
244 * @return The full URL including the path that should be requested to get the expected
247 public String setResponseWithRunnableAction(
248 String requestPath, String responseString, List<Pair<String, String>> responseHeaders,
249 Runnable responseAction) {
250 return setResponseInternal(
251 requestPath, responseString.getBytes(), responseHeaders, responseAction,
252 RESPONSE_STATUS_NORMAL);
258 * @param requestPath The path to respond to.
259 * @param targetPath The path to redirect to.
260 * @return The full URL including the path that should be requested to get the expected
263 public String setRedirect(
264 String requestPath, String targetPath) {
265 List<Pair<String, String>> responseHeaders = new ArrayList<Pair<String, String>>();
266 responseHeaders.add(Pair.create("Location", targetPath));
268 return setResponseInternal(requestPath, targetPath.getBytes(), responseHeaders, null,
269 RESPONSE_STATUS_MOVED_TEMPORARILY);
273 * Sets a base64 encoded response to be returned when a particular request path is passed
274 * in (with the option to specify additional headers).
276 * @param requestPath The path to respond to.
277 * @param base64EncodedResponse The response body that is base64 encoded. The actual server
278 * response will the decoded binary form.
279 * @param responseHeaders Any additional headers that should be returned along with the
280 * response (null is acceptable).
281 * @return The full URL including the path that should be requested to get the expected
284 public String setResponseBase64(
285 String requestPath, String base64EncodedResponse,
286 List<Pair<String, String>> responseHeaders) {
287 return setResponseInternal(
288 requestPath, Base64.decode(base64EncodedResponse, Base64.DEFAULT),
289 responseHeaders, null, RESPONSE_STATUS_NORMAL);
293 * Get the number of requests was made at this path since it was last set.
295 public int getRequestCount(String requestPath) {
296 Integer count = null;
297 synchronized (mLock) {
298 count = mResponseCountMap.get(requestPath);
300 if (count == null) throw new IllegalArgumentException("Path not set: " + requestPath);
301 return count.intValue();
305 * Returns the last HttpRequest at this path. Can return null if it is never requested.
307 public HttpRequest getLastRequest(String requestPath) {
308 synchronized (mLock) {
309 if (!mLastRequestMap.containsKey(requestPath))
310 throw new IllegalArgumentException("Path not set: " + requestPath);
311 return mLastRequestMap.get(requestPath);
315 public String getBaseUrl() {
316 return mServerUri + "/";
319 private URLConnection openConnection(URL url)
320 throws IOException, NoSuchAlgorithmException, KeyManagementException {
322 // Install hostname verifiers and trust managers that don't do
323 // anything in order to get around the client not trusting
324 // the test server due to a lack of certificates.
326 HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
327 connection.setHostnameVerifier(new TestHostnameVerifier());
329 SSLContext context = SSLContext.getInstance("TLS");
330 TestTrustManager trustManager = new TestTrustManager();
331 context.init(null, new TestTrustManager[] {trustManager}, null);
332 connection.setSSLSocketFactory(context.getSocketFactory());
336 return url.openConnection();
341 * {@link X509TrustManager} that trusts everybody. This is used so that
342 * the client calling {@link TestWebServer#shutdown()} can issue a request
343 * for shutdown by blindly trusting the {@link TestWebServer}'s
346 private static class TestTrustManager implements X509TrustManager {
348 public void checkClientTrusted(X509Certificate[] chain, String authType) {
349 // Trust the TestWebServer...
353 public void checkServerTrusted(X509Certificate[] chain, String authType) {
354 // Trust the TestWebServer...
358 public X509Certificate[] getAcceptedIssuers() {
364 * {@link HostnameVerifier} that verifies everybody. This permits
365 * the client to trust the web server and call
366 * {@link TestWebServer#shutdown()}.
368 private static class TestHostnameVerifier implements HostnameVerifier {
370 public boolean verify(String hostname, SSLSession session) {
375 private void servedResponseFor(String path, HttpRequest request) {
376 synchronized (mLock) {
377 mResponseCountMap.put(path, Integer.valueOf(
378 mResponseCountMap.get(path).intValue() + 1));
379 mLastRequestMap.put(path, request);
384 * Generate a response to the given request.
386 * <p>Always executed on the background server thread.
388 * <p>If there is an action associated with the response, it will be executed inside of
391 * @throws InterruptedException
393 private HttpResponse getResponse(HttpRequest request) throws InterruptedException {
394 assert Thread.currentThread() == mServerThread
395 : "getResponse called from non-server thread";
397 RequestLine requestLine = request.getRequestLine();
398 HttpResponse httpResponse = null;
399 Log.i(TAG, requestLine.getMethod() + ": " + requestLine.getUri());
400 String uriString = requestLine.getUri();
401 URI uri = URI.create(uriString);
402 String path = uri.getPath();
404 Response response = null;
405 synchronized (mLock) {
406 response = mResponseMap.get(path);
408 if (path.equals(SHUTDOWN_PREFIX)) {
409 httpResponse = createResponse(HttpStatus.SC_OK);
410 } else if (response == null) {
411 httpResponse = createResponse(HttpStatus.SC_NOT_FOUND);
412 } else if (response.mIsNotFound) {
413 httpResponse = createResponse(HttpStatus.SC_NOT_FOUND);
414 servedResponseFor(path, request);
415 } else if (response.mIsRedirect) {
416 httpResponse = createResponse(HttpStatus.SC_MOVED_TEMPORARILY);
417 for (Pair<String, String> header : response.mResponseHeaders) {
418 httpResponse.addHeader(header.first, header.second);
420 servedResponseFor(path, request);
422 if (response.mResponseAction != null) response.mResponseAction.run();
424 httpResponse = createResponse(HttpStatus.SC_OK);
425 ByteArrayEntity entity = createEntity(response.mResponseData);
426 httpResponse.setEntity(entity);
427 httpResponse.setHeader("Content-Length", "" + entity.getContentLength());
428 for (Pair<String, String> header : response.mResponseHeaders) {
429 httpResponse.addHeader(header.first, header.second);
431 servedResponseFor(path, request);
433 StatusLine sl = httpResponse.getStatusLine();
434 Log.i(TAG, sl.getStatusCode() + "(" + sl.getReasonPhrase() + ")");
435 setDateHeaders(httpResponse);
439 private void setDateHeaders(HttpResponse response) {
440 response.addHeader("Date", DateUtils.formatDate(new Date(), DateUtils.PATTERN_RFC1123));
444 * Create an empty response with the given status.
446 private HttpResponse createResponse(int status) {
447 HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_0, status, null);
448 String reason = null;
450 // This synchronized silences findbugs.
451 synchronized (TestWebServer.class) {
452 if (sReasons == null) {
453 sReasons = new Hashtable<Integer, String>();
454 sReasons.put(HttpStatus.SC_UNAUTHORIZED, "Unauthorized");
455 sReasons.put(HttpStatus.SC_NOT_FOUND, "Not Found");
456 sReasons.put(HttpStatus.SC_FORBIDDEN, "Forbidden");
457 sReasons.put(HttpStatus.SC_MOVED_TEMPORARILY, "Moved Temporarily");
459 // Fill in error reason. Avoid use of the ReasonPhraseCatalog, which is
461 reason = sReasons.get(status);
464 if (reason != null) {
465 StringBuffer buf = new StringBuffer("<html><head><title>");
467 buf.append("</title></head><body>");
469 buf.append("</body></html>");
470 ByteArrayEntity entity = createEntity(buf.toString().getBytes());
471 response.setEntity(entity);
472 response.setHeader("Content-Length", "" + entity.getContentLength());
478 * Create a string entity for the given content.
480 private ByteArrayEntity createEntity(byte[] data) {
481 ByteArrayEntity entity = new ByteArrayEntity(data);
482 entity.setContentType("text/html");
486 private static class ServerThread extends Thread {
487 private TestWebServer mServer;
488 private ServerSocket mSocket;
489 private boolean mIsSsl;
490 private boolean mIsCancelled;
491 private SSLContext mSslContext;
494 * Defines the keystore contents for the server, BKS version. Holds just a
495 * single self-generated key. The subject name is "Test Server".
497 private static final String SERVER_KEYS_BKS =
498 "AAAAAQAAABQDkebzoP1XwqyWKRCJEpn/t8dqIQAABDkEAAVteWtleQAAARpYl20nAAAAAQAFWC41" +
499 "MDkAAAJNMIICSTCCAbKgAwIBAgIESEfU1jANBgkqhkiG9w0BAQUFADBpMQswCQYDVQQGEwJVUzET" +
500 "MBEGA1UECBMKQ2FsaWZvcm5pYTEMMAoGA1UEBxMDTVRWMQ8wDQYDVQQKEwZHb29nbGUxEDAOBgNV" +
501 "BAsTB0FuZHJvaWQxFDASBgNVBAMTC1Rlc3QgU2VydmVyMB4XDTA4MDYwNTExNTgxNFoXDTA4MDkw" +
502 "MzExNTgxNFowaTELMAkGA1UEBhMCVVMxEzARBgNVBAgTCkNhbGlmb3JuaWExDDAKBgNVBAcTA01U" +
503 "VjEPMA0GA1UEChMGR29vZ2xlMRAwDgYDVQQLEwdBbmRyb2lkMRQwEgYDVQQDEwtUZXN0IFNlcnZl" +
504 "cjCBnzANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEA0LIdKaIr9/vsTq8BZlA3R+NFWRaH4lGsTAQy" +
505 "DPMF9ZqEDOaL6DJuu0colSBBBQ85hQTPa9m9nyJoN3pEi1hgamqOvQIWcXBk+SOpUGRZZFXwniJV" +
506 "zDKU5nE9MYgn2B9AoiH3CSuMz6HRqgVaqtppIe1jhukMc/kHVJvlKRNy9XMCAwEAATANBgkqhkiG" +
507 "9w0BAQUFAAOBgQC7yBmJ9O/eWDGtSH9BH0R3dh2NdST3W9hNZ8hIa8U8klhNHbUCSSktZmZkvbPU" +
508 "hse5LI3dh6RyNDuqDrbYwcqzKbFJaq/jX9kCoeb3vgbQElMRX8D2ID1vRjxwlALFISrtaN4VpWzV" +
509 "yeoHPW4xldeZmoVtjn8zXNzQhLuBqX2MmAAAAqwAAAAUvkUScfw9yCSmALruURNmtBai7kQAAAZx" +
510 "4Jmijxs/l8EBaleaUru6EOPioWkUAEVWCxjM/TxbGHOi2VMsQWqRr/DZ3wsDmtQgw3QTrUK666sR" +
511 "MBnbqdnyCyvM1J2V1xxLXPUeRBmR2CXorYGF9Dye7NkgVdfA+9g9L/0Au6Ugn+2Cj5leoIgkgApN" +
512 "vuEcZegFlNOUPVEs3SlBgUF1BY6OBM0UBHTPwGGxFBBcetcuMRbUnu65vyDG0pslT59qpaR0TMVs" +
513 "P+tcheEzhyjbfM32/vwhnL9dBEgM8qMt0sqF6itNOQU/F4WGkK2Cm2v4CYEyKYw325fEhzTXosck" +
514 "MhbqmcyLab8EPceWF3dweoUT76+jEZx8lV2dapR+CmczQI43tV9btsd1xiBbBHAKvymm9Ep9bPzM" +
515 "J0MQi+OtURL9Lxke/70/MRueqbPeUlOaGvANTmXQD2OnW7PISwJ9lpeLfTG0LcqkoqkbtLKQLYHI" +
516 "rQfV5j0j+wmvmpMxzjN3uvNajLa4zQ8l0Eok9SFaRr2RL0gN8Q2JegfOL4pUiHPsh64WWya2NB7f" +
517 "V+1s65eA5ospXYsShRjo046QhGTmymwXXzdzuxu8IlnTEont6P4+J+GsWk6cldGbl20hctuUKzyx" +
518 "OptjEPOKejV60iDCYGmHbCWAzQ8h5MILV82IclzNViZmzAapeeCnexhpXhWTs+xDEYSKEiG/camt" +
519 "bhmZc3BcyVJrW23PktSfpBQ6D8ZxoMfF0L7V2GQMaUg+3r7ucrx82kpqotjv0xHghNIm95aBr1Qw" +
520 "1gaEjsC/0wGmmBDg1dTDH+F1p9TInzr3EFuYD0YiQ7YlAHq3cPuyGoLXJ5dXYuSBfhDXJSeddUkl" +
521 "k1ufZyOOcskeInQge7jzaRfmKg3U94r+spMEvb0AzDQVOKvjjo1ivxMSgFRZaDb/4qw=";
523 private static final String PASSWORD = "android";
526 * Loads a keystore from a base64-encoded String. Returns the KeyManager[]
529 private KeyManager[] getKeyManagers() throws Exception {
530 byte[] bytes = Base64.decode(SERVER_KEYS_BKS, Base64.DEFAULT);
531 InputStream inputStream = new ByteArrayInputStream(bytes);
533 KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
534 keyStore.load(inputStream, PASSWORD.toCharArray());
537 String algorithm = KeyManagerFactory.getDefaultAlgorithm();
538 KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(algorithm);
539 keyManagerFactory.init(keyStore, PASSWORD.toCharArray());
541 return keyManagerFactory.getKeyManagers();
545 public ServerThread(TestWebServer server, boolean ssl) throws Exception {
546 super("ServerThread");
553 mSslContext = SSLContext.getInstance("TLS");
554 mSslContext.init(getKeyManagers(), null, null);
555 mSocket = mSslContext.getServerSocketFactory().createServerSocket(0);
557 mSocket = new ServerSocket(0);
560 } catch (IOException e) {
565 // sleep in case server socket is still being closed
573 HttpParams params = new BasicHttpParams();
574 params.setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_0);
575 while (!mIsCancelled) {
577 Socket socket = mSocket.accept();
578 DefaultHttpServerConnection conn = new DefaultHttpServerConnection();
579 conn.bind(socket, params);
581 // Determine whether we need to shutdown early before
582 // parsing the response since conn.close() will crash
583 // for SSL requests due to UnsupportedOperationException.
584 HttpRequest request = conn.receiveRequestHeader();
585 if (isShutdownRequest(request)) {
589 HttpResponse response = mServer.getResponse(request);
590 conn.sendResponseHeader(response);
591 conn.sendResponseEntity(response);
594 } catch (IOException e) {
595 // normal during shutdown, ignore
597 } catch (HttpException e) {
599 } catch (InterruptedException e) {
601 } catch (UnsupportedOperationException e) {
602 // DefaultHttpServerConnection's close() throws an
603 // UnsupportedOperationException.
609 } catch (IOException ignored) {
614 private boolean isShutdownRequest(HttpRequest request) {
615 RequestLine requestLine = request.getRequestLine();
616 String uriString = requestLine.getUri();
617 URI uri = URI.create(uriString);
618 String path = uri.getPath();
619 return path.equals(SHUTDOWN_PREFIX);