TestWebServer.java revision 1320f92c476a1ad9d19dba2a48c72b75566198e9
17d4cd473f85ac64c3747c96c277f9e506a0d2246Torne (Richard Coles)// Copyright 2012 The Chromium Authors. All rights reserved.
27d4cd473f85ac64c3747c96c277f9e506a0d2246Torne (Richard Coles)// Use of this source code is governed by a BSD-style license that can be
37d4cd473f85ac64c3747c96c277f9e506a0d2246Torne (Richard Coles)// found in the LICENSE file.
47d4cd473f85ac64c3747c96c277f9e506a0d2246Torne (Richard Coles)
57d4cd473f85ac64c3747c96c277f9e506a0d2246Torne (Richard Coles)package org.chromium.net.test.util;
67d4cd473f85ac64c3747c96c277f9e506a0d2246Torne (Richard Coles)
77d4cd473f85ac64c3747c96c277f9e506a0d2246Torne (Richard Coles)import android.util.Base64;
87d4cd473f85ac64c3747c96c277f9e506a0d2246Torne (Richard Coles)import android.util.Log;
97d4cd473f85ac64c3747c96c277f9e506a0d2246Torne (Richard Coles)import android.util.Pair;
107d4cd473f85ac64c3747c96c277f9e506a0d2246Torne (Richard Coles)
117d4cd473f85ac64c3747c96c277f9e506a0d2246Torne (Richard Coles)import org.apache.http.HttpException;
127d4cd473f85ac64c3747c96c277f9e506a0d2246Torne (Richard Coles)import org.apache.http.HttpRequest;
13a36e5920737c6adbddd3e43b760e5de8431db6e0Torne (Richard Coles)import org.apache.http.HttpResponse;
147d4cd473f85ac64c3747c96c277f9e506a0d2246Torne (Richard Coles)import org.apache.http.HttpStatus;
157d4cd473f85ac64c3747c96c277f9e506a0d2246Torne (Richard Coles)import org.apache.http.HttpVersion;
167d4cd473f85ac64c3747c96c277f9e506a0d2246Torne (Richard Coles)import org.apache.http.RequestLine;
177d4cd473f85ac64c3747c96c277f9e506a0d2246Torne (Richard Coles)import org.apache.http.StatusLine;
187d4cd473f85ac64c3747c96c277f9e506a0d2246Torne (Richard Coles)import org.apache.http.entity.ByteArrayEntity;
197d4cd473f85ac64c3747c96c277f9e506a0d2246Torne (Richard Coles)import org.apache.http.impl.DefaultHttpServerConnection;
207d4cd473f85ac64c3747c96c277f9e506a0d2246Torne (Richard Coles)import org.apache.http.impl.cookie.DateUtils;
217d4cd473f85ac64c3747c96c277f9e506a0d2246Torne (Richard Coles)import org.apache.http.message.BasicHttpResponse;
22a36e5920737c6adbddd3e43b760e5de8431db6e0Torne (Richard Coles)import org.apache.http.params.BasicHttpParams;
23a36e5920737c6adbddd3e43b760e5de8431db6e0Torne (Richard Coles)import org.apache.http.params.CoreProtocolPNames;
24a36e5920737c6adbddd3e43b760e5de8431db6e0Torne (Richard Coles)import org.apache.http.params.HttpParams;
25a36e5920737c6adbddd3e43b760e5de8431db6e0Torne (Richard Coles)
26a36e5920737c6adbddd3e43b760e5de8431db6e0Torne (Richard Coles)import java.io.ByteArrayInputStream;
27a36e5920737c6adbddd3e43b760e5de8431db6e0Torne (Richard Coles)import java.io.IOException;
28a36e5920737c6adbddd3e43b760e5de8431db6e0Torne (Richard Coles)import java.io.InputStream;
29a36e5920737c6adbddd3e43b760e5de8431db6e0Torne (Richard Coles)import java.net.MalformedURLException;
30eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdochimport java.net.ServerSocket;
317d4cd473f85ac64c3747c96c277f9e506a0d2246Torne (Richard Coles)import java.net.Socket;
32424c4d7b64af9d0d8fd9624f381f469654d5e3d2Torne (Richard Coles)import java.net.URI;
33424c4d7b64af9d0d8fd9624f381f469654d5e3d2Torne (Richard Coles)import java.net.URL;
34eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdochimport java.net.URLConnection;
35424c4d7b64af9d0d8fd9624f381f469654d5e3d2Torne (Richard Coles)import java.security.KeyManagementException;
36eb525c5499e34cc9c4b825d6d9e75bb07cc06aceBen Murdochimport java.security.KeyStore;
37a36e5920737c6adbddd3e43b760e5de8431db6e0Torne (Richard Coles)import java.security.NoSuchAlgorithmException;
387d4cd473f85ac64c3747c96c277f9e506a0d2246Torne (Richard Coles)import java.security.cert.X509Certificate;
397d4cd473f85ac64c3747c96c277f9e506a0d2246Torne (Richard Coles)import java.util.ArrayList;
407d4cd473f85ac64c3747c96c277f9e506a0d2246Torne (Richard Coles)import java.util.Date;
417d4cd473f85ac64c3747c96c277f9e506a0d2246Torne (Richard Coles)import java.util.HashMap;
427d4cd473f85ac64c3747c96c277f9e506a0d2246Torne (Richard Coles)import java.util.Hashtable;
437d4cd473f85ac64c3747c96c277f9e506a0d2246Torne (Richard Coles)import java.util.List;
447d4cd473f85ac64c3747c96c277f9e506a0d2246Torne (Richard Coles)import java.util.Map;
4558537e28ecd584eab876aee8be7156509866d23aTorne (Richard Coles)
4658537e28ecd584eab876aee8be7156509866d23aTorne (Richard Coles)import javax.net.ssl.HostnameVerifier;
47a36e5920737c6adbddd3e43b760e5de8431db6e0Torne (Richard Coles)import javax.net.ssl.HttpsURLConnection;
487d4cd473f85ac64c3747c96c277f9e506a0d2246Torne (Richard Coles)import javax.net.ssl.KeyManager;
497d4cd473f85ac64c3747c96c277f9e506a0d2246Torne (Richard Coles)import javax.net.ssl.KeyManagerFactory;
507d4cd473f85ac64c3747c96c277f9e506a0d2246Torne (Richard Coles)import javax.net.ssl.SSLContext;
517d4cd473f85ac64c3747c96c277f9e506a0d2246Torne (Richard Coles)import javax.net.ssl.SSLSession;
527d4cd473f85ac64c3747c96c277f9e506a0d2246Torne (Richard Coles)import javax.net.ssl.X509TrustManager;
537d4cd473f85ac64c3747c96c277f9e506a0d2246Torne (Richard Coles)
547dbb3d5cf0c15f500944d211057644d6a2f37371Ben Murdoch/**
557d4cd473f85ac64c3747c96c277f9e506a0d2246Torne (Richard Coles) * Simple http test server for testing.
567d4cd473f85ac64c3747c96c277f9e506a0d2246Torne (Richard Coles) *
577d4cd473f85ac64c3747c96c277f9e506a0d2246Torne (Richard Coles) * This server runs in a thread in the current process, so it is convenient
587d4cd473f85ac64c3747c96c277f9e506a0d2246Torne (Richard Coles) * for loopback testing without the need to setup tcp forwarding to the
597d4cd473f85ac64c3747c96c277f9e506a0d2246Torne (Richard Coles) * host computer.
607d4cd473f85ac64c3747c96c277f9e506a0d2246Torne (Richard Coles) *
617d4cd473f85ac64c3747c96c277f9e506a0d2246Torne (Richard Coles) * Based heavily on the CTSWebServer in Android.
627d4cd473f85ac64c3747c96c277f9e506a0d2246Torne (Richard Coles) */
637d4cd473f85ac64c3747c96c277f9e506a0d2246Torne (Richard Coles)public final class TestWebServer {
647d4cd473f85ac64c3747c96c277f9e506a0d2246Torne (Richard Coles)    private static final String TAG = "TestWebServer";
657d4cd473f85ac64c3747c96c277f9e506a0d2246Torne (Richard Coles)
667d4cd473f85ac64c3747c96c277f9e506a0d2246Torne (Richard Coles)    public static final String SHUTDOWN_PREFIX = "/shutdown";
677d4cd473f85ac64c3747c96c277f9e506a0d2246Torne (Richard Coles)
687d4cd473f85ac64c3747c96c277f9e506a0d2246Torne (Richard Coles)    private static TestWebServer sInstance;
697d4cd473f85ac64c3747c96c277f9e506a0d2246Torne (Richard Coles)    private static TestWebServer sSecureInstance;
707d4cd473f85ac64c3747c96c277f9e506a0d2246Torne (Richard Coles)    private static Hashtable<Integer, String> sReasons;
717d4cd473f85ac64c3747c96c277f9e506a0d2246Torne (Richard Coles)
727d4cd473f85ac64c3747c96c277f9e506a0d2246Torne (Richard Coles)    private final ServerThread mServerThread;
737d4cd473f85ac64c3747c96c277f9e506a0d2246Torne (Richard Coles)    private String mServerUri;
747d4cd473f85ac64c3747c96c277f9e506a0d2246Torne (Richard Coles)    private final boolean mSsl;
757d4cd473f85ac64c3747c96c277f9e506a0d2246Torne (Richard Coles)
767d4cd473f85ac64c3747c96c277f9e506a0d2246Torne (Richard Coles)    private static class Response {
777d4cd473f85ac64c3747c96c277f9e506a0d2246Torne (Richard Coles)        final byte[] mResponseData;
787d4cd473f85ac64c3747c96c277f9e506a0d2246Torne (Richard Coles)        final List<Pair<String, String>> mResponseHeaders;
797d4cd473f85ac64c3747c96c277f9e506a0d2246Torne (Richard Coles)        final boolean mIsRedirect;
807d4cd473f85ac64c3747c96c277f9e506a0d2246Torne (Richard Coles)        final Runnable mResponseAction;
817d4cd473f85ac64c3747c96c277f9e506a0d2246Torne (Richard Coles)        final boolean mIsNotFound;
827d4cd473f85ac64c3747c96c277f9e506a0d2246Torne (Richard Coles)
837d4cd473f85ac64c3747c96c277f9e506a0d2246Torne (Richard Coles)        Response(byte[] responseData, List<Pair<String, String>> responseHeaders,
847d4cd473f85ac64c3747c96c277f9e506a0d2246Torne (Richard Coles)                boolean isRedirect, boolean isNotFound, Runnable responseAction) {
857d4cd473f85ac64c3747c96c277f9e506a0d2246Torne (Richard Coles)            mIsRedirect = isRedirect;
86d0247b1b59f9c528cb6df88b4f2b9afaf80d181eTorne (Richard Coles)            mIsNotFound = isNotFound;
877d4cd473f85ac64c3747c96c277f9e506a0d2246Torne (Richard Coles)            mResponseData = responseData;
887d4cd473f85ac64c3747c96c277f9e506a0d2246Torne (Richard Coles)            mResponseHeaders = responseHeaders == null ?
897d4cd473f85ac64c3747c96c277f9e506a0d2246Torne (Richard Coles)                    new ArrayList<Pair<String, String>>() : responseHeaders;
907d4cd473f85ac64c3747c96c277f9e506a0d2246Torne (Richard Coles)            mResponseAction = responseAction;
917d4cd473f85ac64c3747c96c277f9e506a0d2246Torne (Richard Coles)        }
927d4cd473f85ac64c3747c96c277f9e506a0d2246Torne (Richard Coles)    }
937d4cd473f85ac64c3747c96c277f9e506a0d2246Torne (Richard Coles)
947d4cd473f85ac64c3747c96c277f9e506a0d2246Torne (Richard Coles)    // The Maps below are modified on both the client thread and the internal server thread, so
957d4cd473f85ac64c3747c96c277f9e506a0d2246Torne (Richard Coles)    // need to use a lock when accessing them.
967d4cd473f85ac64c3747c96c277f9e506a0d2246Torne (Richard Coles)    private final Object mLock = new Object();
977d4cd473f85ac64c3747c96c277f9e506a0d2246Torne (Richard Coles)    private final Map<String, Response> mResponseMap = new HashMap<String, Response>();
987d4cd473f85ac64c3747c96c277f9e506a0d2246Torne (Richard Coles)    private final Map<String, Integer> mResponseCountMap = new HashMap<String, Integer>();
997d4cd473f85ac64c3747c96c277f9e506a0d2246Torne (Richard Coles)    private final Map<String, HttpRequest> mLastRequestMap = new HashMap<String, HttpRequest>();
1007d4cd473f85ac64c3747c96c277f9e506a0d2246Torne (Richard Coles)
1017d4cd473f85ac64c3747c96c277f9e506a0d2246Torne (Richard Coles)    /**
1027dbb3d5cf0c15f500944d211057644d6a2f37371Ben Murdoch     * Create and start a local HTTP server instance.
1037dbb3d5cf0c15f500944d211057644d6a2f37371Ben Murdoch     * @param ssl True if the server should be using secure sockets.
1047dbb3d5cf0c15f500944d211057644d6a2f37371Ben Murdoch     * @throws Exception
1057dbb3d5cf0c15f500944d211057644d6a2f37371Ben Murdoch     */
1067dbb3d5cf0c15f500944d211057644d6a2f37371Ben Murdoch    public TestWebServer(boolean ssl) throws Exception {
1077dbb3d5cf0c15f500944d211057644d6a2f37371Ben Murdoch        mSsl = ssl;
1087d4cd473f85ac64c3747c96c277f9e506a0d2246Torne (Richard Coles)        if (mSsl) {
1097d4cd473f85ac64c3747c96c277f9e506a0d2246Torne (Richard Coles)            mServerUri = "https:";
1107d4cd473f85ac64c3747c96c277f9e506a0d2246Torne (Richard Coles)            if (sSecureInstance != null) {
111d0247b1b59f9c528cb6df88b4f2b9afaf80d181eTorne (Richard Coles)                sSecureInstance.shutdown();
112d0247b1b59f9c528cb6df88b4f2b9afaf80d181eTorne (Richard Coles)            }
1137d4cd473f85ac64c3747c96c277f9e506a0d2246Torne (Richard Coles)        } else {
1147d4cd473f85ac64c3747c96c277f9e506a0d2246Torne (Richard Coles)            mServerUri = "http:";
1157d4cd473f85ac64c3747c96c277f9e506a0d2246Torne (Richard Coles)            if (sInstance != null) {
1167d4cd473f85ac64c3747c96c277f9e506a0d2246Torne (Richard Coles)                sInstance.shutdown();
1177d4cd473f85ac64c3747c96c277f9e506a0d2246Torne (Richard Coles)            }
1187d4cd473f85ac64c3747c96c277f9e506a0d2246Torne (Richard Coles)        }
1197d4cd473f85ac64c3747c96c277f9e506a0d2246Torne (Richard Coles)
1207d4cd473f85ac64c3747c96c277f9e506a0d2246Torne (Richard Coles)        setInstance(this, mSsl);
1217d4cd473f85ac64c3747c96c277f9e506a0d2246Torne (Richard Coles)        mServerThread = new ServerThread(this, mSsl);
1227d4cd473f85ac64c3747c96c277f9e506a0d2246Torne (Richard Coles)        mServerThread.start();
1237d4cd473f85ac64c3747c96c277f9e506a0d2246Torne (Richard Coles)        mServerUri += "//localhost:" + mServerThread.mSocket.getLocalPort();
1247d4cd473f85ac64c3747c96c277f9e506a0d2246Torne (Richard Coles)    }
1257d4cd473f85ac64c3747c96c277f9e506a0d2246Torne (Richard Coles)
1267d4cd473f85ac64c3747c96c277f9e506a0d2246Torne (Richard Coles)    /**
1277d4cd473f85ac64c3747c96c277f9e506a0d2246Torne (Richard Coles)     * Terminate the http server.
1287d4cd473f85ac64c3747c96c277f9e506a0d2246Torne (Richard Coles)     */
1297d4cd473f85ac64c3747c96c277f9e506a0d2246Torne (Richard Coles)    public void shutdown() {
1307d4cd473f85ac64c3747c96c277f9e506a0d2246Torne (Richard Coles)        try {
131ba5b9a6411cb1792fd21f0a078d7a25cd1ceec16Ben Murdoch            // Avoid a deadlock between two threads where one is trying to call
132ba5b9a6411cb1792fd21f0a078d7a25cd1ceec16Ben Murdoch            // close() and the other one is calling accept() by sending a GET
133ba5b9a6411cb1792fd21f0a078d7a25cd1ceec16Ben Murdoch            // request for shutdown and having the server's one thread
134c2db58bd994c04d98e4ee2cd7565b71548655fe3Ben Murdoch            // sequentially call accept() and close().
135c2db58bd994c04d98e4ee2cd7565b71548655fe3Ben Murdoch            URL url = new URL(mServerUri + SHUTDOWN_PREFIX);
136c2db58bd994c04d98e4ee2cd7565b71548655fe3Ben Murdoch            URLConnection connection = openConnection(url);
137424c4d7b64af9d0d8fd9624f381f469654d5e3d2Torne (Richard Coles)            connection.connect();
138424c4d7b64af9d0d8fd9624f381f469654d5e3d2Torne (Richard Coles)
139424c4d7b64af9d0d8fd9624f381f469654d5e3d2Torne (Richard Coles)            // Read the input from the stream to send the request.
1407d4cd473f85ac64c3747c96c277f9e506a0d2246Torne (Richard Coles)            InputStream is = connection.getInputStream();
1417d4cd473f85ac64c3747c96c277f9e506a0d2246Torne (Richard Coles)            is.close();
1427d4cd473f85ac64c3747c96c277f9e506a0d2246Torne (Richard Coles)
143            // Block until the server thread is done shutting down.
144            mServerThread.join();
145
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);
156        }
157
158        setInstance(null, mSsl);
159    }
160
161    private static void setInstance(TestWebServer instance, boolean isSsl) {
162        if (isSsl) {
163            sSecureInstance = instance;
164        } else {
165            sInstance = instance;
166        }
167    }
168
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;
172
173    private String setResponseInternal(
174            String requestPath, byte[] responseData,
175            List<Pair<String, String>> responseHeaders, Runnable responseAction,
176            int status) {
177        final boolean isRedirect = (status == RESPONSE_STATUS_MOVED_TEMPORARILY);
178        final boolean isNotFound = (status == RESPONSE_STATUS_NOT_FOUND);
179
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);
185        }
186        return getResponseUrl(requestPath);
187    }
188
189    /**
190     * Gets the URL on the server under which a particular request path will be accessible.
191     *
192     * This only gets the URL, you still need to set the response if you intend to access it.
193     *
194     * @param requestPath The path to respond to.
195     * @return The full URL including the requestPath.
196     */
197    public String getResponseUrl(String requestPath) {
198        return mServerUri + requestPath;
199    }
200
201    /**
202     * Sets a 404 (not found) response to be returned when a particular request path is passed in.
203     *
204     * @param requestPath The path to respond to.
205     * @return The full URL including the path that should be requested to get the expected
206     *         response.
207     */
208    public String setResponseWithNotFoundStatus(
209            String requestPath) {
210        return setResponseInternal(requestPath, "".getBytes(), null, null,
211                RESPONSE_STATUS_NOT_FOUND);
212    }
213
214    /**
215     * Sets a response to be returned when a particular request path is passed
216     * in (with the option to specify additional headers).
217     *
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
223     *         response.
224     */
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);
230    }
231
232    /**
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.
236     *
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
243     *                       thread.
244     * @return The full URL including the path that should be requested to get the expected
245     *         response.
246     */
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);
253    }
254
255    /**
256     * Sets a redirect.
257     *
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
261     *         response.
262     */
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));
267
268        return setResponseInternal(requestPath, targetPath.getBytes(), responseHeaders, null,
269                RESPONSE_STATUS_MOVED_TEMPORARILY);
270    }
271
272    /**
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).
275     *
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
282     *         response.
283     */
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);
290    }
291
292    /**
293     * Get the number of requests was made at this path since it was last set.
294     */
295    public int getRequestCount(String requestPath) {
296        Integer count = null;
297        synchronized (mLock) {
298            count = mResponseCountMap.get(requestPath);
299        }
300        if (count == null) throw new IllegalArgumentException("Path not set: " + requestPath);
301        return count.intValue();
302    }
303
304    /**
305     * Returns the last HttpRequest at this path. Can return null if it is never requested.
306     */
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);
312        }
313    }
314
315    public String getBaseUrl() {
316        return mServerUri + "/";
317    }
318
319    private URLConnection openConnection(URL url)
320            throws IOException, NoSuchAlgorithmException, KeyManagementException {
321        if (mSsl) {
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.
325
326            HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
327            connection.setHostnameVerifier(new TestHostnameVerifier());
328
329            SSLContext context = SSLContext.getInstance("TLS");
330            TestTrustManager trustManager = new TestTrustManager();
331            context.init(null, new TestTrustManager[] {trustManager}, null);
332            connection.setSSLSocketFactory(context.getSocketFactory());
333
334            return connection;
335        } else {
336            return url.openConnection();
337        }
338    }
339
340    /**
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
344     * credentials.
345     */
346    private static class TestTrustManager implements X509TrustManager {
347        @Override
348        public void checkClientTrusted(X509Certificate[] chain, String authType) {
349            // Trust the TestWebServer...
350        }
351
352        @Override
353        public void checkServerTrusted(X509Certificate[] chain, String authType) {
354            // Trust the TestWebServer...
355        }
356
357        @Override
358        public X509Certificate[] getAcceptedIssuers() {
359            return null;
360        }
361    }
362
363    /**
364     * {@link HostnameVerifier} that verifies everybody. This permits
365     * the client to trust the web server and call
366     * {@link TestWebServer#shutdown()}.
367     */
368    private static class TestHostnameVerifier implements HostnameVerifier {
369        @Override
370        public boolean verify(String hostname, SSLSession session) {
371            return true;
372        }
373    }
374
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);
380        }
381    }
382
383    /**
384     * Generate a response to the given request.
385     *
386     * <p>Always executed on the background server thread.
387     *
388     * <p>If there is an action associated with the response, it will be executed inside of
389     * this function.
390     *
391     * @throws InterruptedException
392     */
393    private HttpResponse getResponse(HttpRequest request) throws InterruptedException {
394        assert Thread.currentThread() == mServerThread
395                : "getResponse called from non-server thread";
396
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();
403
404        Response response = null;
405        synchronized (mLock) {
406            response = mResponseMap.get(path);
407        }
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);
419            }
420            servedResponseFor(path, request);
421        } else {
422            if (response.mResponseAction != null) response.mResponseAction.run();
423
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);
430            }
431            servedResponseFor(path, request);
432        }
433        StatusLine sl = httpResponse.getStatusLine();
434        Log.i(TAG, sl.getStatusCode() + "(" + sl.getReasonPhrase() + ")");
435        setDateHeaders(httpResponse);
436        return httpResponse;
437    }
438
439    private void setDateHeaders(HttpResponse response) {
440        response.addHeader("Date", DateUtils.formatDate(new Date(), DateUtils.PATTERN_RFC1123));
441    }
442
443    /**
444     * Create an empty response with the given status.
445     */
446    private HttpResponse createResponse(int status) {
447        HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_0, status, null);
448        String reason = null;
449
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");
458            }
459            // Fill in error reason. Avoid use of the ReasonPhraseCatalog, which is
460            // Locale-dependent.
461            reason = sReasons.get(status);
462        }
463
464        if (reason != null) {
465            StringBuffer buf = new StringBuffer("<html><head><title>");
466            buf.append(reason);
467            buf.append("</title></head><body>");
468            buf.append(reason);
469            buf.append("</body></html>");
470            ByteArrayEntity entity = createEntity(buf.toString().getBytes());
471            response.setEntity(entity);
472            response.setHeader("Content-Length", "" + entity.getContentLength());
473        }
474        return response;
475    }
476
477    /**
478     * Create a string entity for the given content.
479     */
480    private ByteArrayEntity createEntity(byte[] data) {
481        ByteArrayEntity entity = new ByteArrayEntity(data);
482        entity.setContentType("text/html");
483        return entity;
484    }
485
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;
492
493        /**
494         * Defines the keystore contents for the server, BKS version. Holds just a
495         * single self-generated key. The subject name is "Test Server".
496         */
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=";
522
523        private static final String PASSWORD = "android";
524
525        /**
526         * Loads a keystore from a base64-encoded String. Returns the KeyManager[]
527         * for the result.
528         */
529        private KeyManager[] getKeyManagers() throws Exception {
530            byte[] bytes = Base64.decode(SERVER_KEYS_BKS, Base64.DEFAULT);
531            InputStream inputStream = new ByteArrayInputStream(bytes);
532
533            KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
534            keyStore.load(inputStream, PASSWORD.toCharArray());
535            inputStream.close();
536
537            String algorithm = KeyManagerFactory.getDefaultAlgorithm();
538            KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(algorithm);
539            keyManagerFactory.init(keyStore, PASSWORD.toCharArray());
540
541            return keyManagerFactory.getKeyManagers();
542        }
543
544
545        public ServerThread(TestWebServer server, boolean ssl) throws Exception {
546            super("ServerThread");
547            mServer = server;
548            mIsSsl = ssl;
549            int retry = 3;
550            while (true) {
551                try {
552                    if (mIsSsl) {
553                        mSslContext = SSLContext.getInstance("TLS");
554                        mSslContext.init(getKeyManagers(), null, null);
555                        mSocket = mSslContext.getServerSocketFactory().createServerSocket(0);
556                    } else {
557                        mSocket = new ServerSocket(0);
558                    }
559                    return;
560                } catch (IOException e) {
561                    Log.w(TAG, e);
562                    if (--retry == 0) {
563                        throw e;
564                    }
565                    // sleep in case server socket is still being closed
566                    Thread.sleep(1000);
567                }
568            }
569        }
570
571        @Override
572        public void run() {
573            HttpParams params = new BasicHttpParams();
574            params.setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_0);
575            while (!mIsCancelled) {
576                try {
577                    Socket socket = mSocket.accept();
578                    DefaultHttpServerConnection conn = new DefaultHttpServerConnection();
579                    conn.bind(socket, params);
580
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)) {
586                        mIsCancelled = true;
587                    }
588
589                    HttpResponse response = mServer.getResponse(request);
590                    conn.sendResponseHeader(response);
591                    conn.sendResponseEntity(response);
592                    conn.close();
593
594                } catch (IOException e) {
595                    // normal during shutdown, ignore
596                    Log.w(TAG, e);
597                } catch (HttpException e) {
598                    Log.w(TAG, e);
599                } catch (InterruptedException e) {
600                    Log.w(TAG, e);
601                } catch (UnsupportedOperationException e) {
602                    // DefaultHttpServerConnection's close() throws an
603                    // UnsupportedOperationException.
604                    Log.w(TAG, e);
605                }
606            }
607            try {
608                mSocket.close();
609            } catch (IOException ignored) {
610                // safe to ignore
611            }
612        }
613
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);
620        }
621    }
622}
623