Home | History | Annotate | Download | only in cts
      1 /*
      2  * Copyright (C) 2009 The Android Open Source Project
      3  *
      4  * Licensed under the Apache License, Version 2.0 (the "License");
      5  * you may not use this file except in compliance with the License.
      6  * You may obtain a copy of the License at
      7  *
      8  *      http://www.apache.org/licenses/LICENSE-2.0
      9  *
     10  * Unless required by applicable law or agreed to in writing, software
     11  * distributed under the License is distributed on an "AS IS" BASIS,
     12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     13  * See the License for the specific language governing permissions and
     14  * limitations under the License.
     15  */
     16 package android.webkit.cts;
     17 
     18 import libcore.io.Base64;
     19 import org.apache.http.Header;
     20 import org.apache.http.HttpException;
     21 import org.apache.http.HttpRequest;
     22 import org.apache.http.HttpResponse;
     23 import org.apache.http.HttpStatus;
     24 import org.apache.http.HttpVersion;
     25 import org.apache.http.NameValuePair;
     26 import org.apache.http.RequestLine;
     27 import org.apache.http.StatusLine;
     28 import org.apache.http.client.utils.URLEncodedUtils;
     29 import org.apache.http.entity.ByteArrayEntity;
     30 import org.apache.http.entity.FileEntity;
     31 import org.apache.http.entity.InputStreamEntity;
     32 import org.apache.http.entity.StringEntity;
     33 import org.apache.http.impl.DefaultHttpServerConnection;
     34 import org.apache.http.impl.cookie.DateUtils;
     35 import org.apache.http.message.BasicHttpResponse;
     36 import org.apache.http.params.BasicHttpParams;
     37 import org.apache.http.params.CoreProtocolPNames;
     38 import org.apache.http.params.HttpParams;
     39 
     40 import android.content.Context;
     41 import android.content.res.AssetManager;
     42 import android.net.Uri;
     43 import android.os.Environment;
     44 import android.util.Log;
     45 import android.webkit.MimeTypeMap;
     46 
     47 import java.io.BufferedOutputStream;
     48 import java.io.ByteArrayInputStream;
     49 import java.io.File;
     50 import java.io.FileOutputStream;
     51 import java.io.IOException;
     52 import java.io.InputStream;
     53 import java.io.UnsupportedEncodingException;
     54 import java.net.MalformedURLException;
     55 import java.net.ServerSocket;
     56 import java.net.Socket;
     57 import java.net.URI;
     58 import java.net.URL;
     59 import java.net.URLConnection;
     60 import java.security.KeyManagementException;
     61 import java.security.KeyStore;
     62 import java.security.NoSuchAlgorithmException;
     63 import java.security.cert.X509Certificate;
     64 import java.util.Date;
     65 import java.util.Hashtable;
     66 import java.util.List;
     67 import java.util.concurrent.Callable;
     68 import java.util.concurrent.ExecutorService;
     69 import java.util.concurrent.Executors;
     70 import java.util.concurrent.TimeUnit;
     71 import java.util.regex.Matcher;
     72 import java.util.regex.Pattern;
     73 
     74 import javax.net.ssl.HostnameVerifier;
     75 import javax.net.ssl.HttpsURLConnection;
     76 import javax.net.ssl.KeyManager;
     77 import javax.net.ssl.KeyManagerFactory;
     78 import javax.net.ssl.SSLContext;
     79 import javax.net.ssl.SSLSession;
     80 import javax.net.ssl.X509TrustManager;
     81 
     82 /**
     83  * Simple http test server for testing webkit client functionality.
     84  */
     85 public class CtsTestServer {
     86     private static final String TAG = "CtsTestServer";
     87     private static final int SERVER_PORT = 4444;
     88     private static final int SSL_SERVER_PORT = 4445;
     89 
     90     public static final String FAVICON_PATH = "/favicon.ico";
     91     public static final String USERAGENT_PATH = "/useragent.html";
     92 
     93     public static final String TEST_DOWNLOAD_PATH = "/download.html";
     94     private static final String DOWNLOAD_ID_PARAMETER = "downloadId";
     95     private static final String NUM_BYTES_PARAMETER = "numBytes";
     96 
     97     public static final String ASSET_PREFIX = "/assets/";
     98     public static final String FAVICON_ASSET_PATH = ASSET_PREFIX + "webkit/favicon.png";
     99     public static final String APPCACHE_PATH = "/appcache.html";
    100     public static final String APPCACHE_MANIFEST_PATH = "/appcache.manifest";
    101     public static final String REDIRECT_PREFIX = "/redirect";
    102     public static final String DELAY_PREFIX = "/delayed";
    103     public static final String BINARY_PREFIX = "/binary";
    104     public static final String COOKIE_PREFIX = "/cookie";
    105     public static final String AUTH_PREFIX = "/auth";
    106     public static final String SHUTDOWN_PREFIX = "/shutdown";
    107     public static final String NOLENGTH_POSTFIX = "nolength";
    108     public static final int DELAY_MILLIS = 2000;
    109 
    110     public static final String AUTH_REALM = "Android CTS";
    111     public static final String AUTH_USER = "cts";
    112     public static final String AUTH_PASS = "secret";
    113     // base64 encoded credentials "cts:secret" used for basic authentication
    114     public static final String AUTH_CREDENTIALS = "Basic Y3RzOnNlY3JldA==";
    115 
    116     public static final String MESSAGE_401 = "401 unauthorized";
    117     public static final String MESSAGE_403 = "403 forbidden";
    118     public static final String MESSAGE_404 = "404 not found";
    119 
    120     private static CtsTestServer sInstance;
    121     private static Hashtable<Integer, String> sReasons;
    122 
    123     private ServerThread mServerThread;
    124     private String mServerUri;
    125     private AssetManager mAssets;
    126     private Context mContext;
    127     private boolean mSsl;
    128     private MimeTypeMap mMap;
    129     private String mLastQuery;
    130     private int mRequestCount;
    131     private long mDocValidity;
    132     private long mDocAge;
    133 
    134     /**
    135      * Create and start a local HTTP server instance.
    136      * @param context The application context to use for fetching assets.
    137      * @throws IOException
    138      */
    139     public CtsTestServer(Context context) throws Exception {
    140         this(context, false);
    141     }
    142 
    143     public static String getReasonString(int status) {
    144         if (sReasons == null) {
    145             sReasons = new Hashtable<Integer, String>();
    146             sReasons.put(HttpStatus.SC_UNAUTHORIZED, "Unauthorized");
    147             sReasons.put(HttpStatus.SC_NOT_FOUND, "Not Found");
    148             sReasons.put(HttpStatus.SC_FORBIDDEN, "Forbidden");
    149             sReasons.put(HttpStatus.SC_MOVED_TEMPORARILY, "Moved Temporarily");
    150         }
    151         return sReasons.get(status);
    152     }
    153 
    154     /**
    155      * Create and start a local HTTP server instance.
    156      * @param context The application context to use for fetching assets.
    157      * @param ssl True if the server should be using secure sockets.
    158      * @throws Exception
    159      */
    160     public CtsTestServer(Context context, boolean ssl) throws Exception {
    161         if (sInstance != null) {
    162             // attempt to start a new instance while one is still running
    163             // shut down the old instance first
    164             sInstance.shutdown();
    165         }
    166         sInstance = this;
    167         mContext = context;
    168         mAssets = mContext.getAssets();
    169         mSsl = ssl;
    170         if (mSsl) {
    171             mServerUri = "https://localhost:" + SSL_SERVER_PORT;
    172         } else {
    173             mServerUri = "http://localhost:" + SERVER_PORT;
    174         }
    175         mMap = MimeTypeMap.getSingleton();
    176         mServerThread = new ServerThread(this, mSsl);
    177         mServerThread.start();
    178     }
    179 
    180     /**
    181      * Terminate the http server.
    182      */
    183     public void shutdown() {
    184         try {
    185             // Avoid a deadlock between two threads where one is trying to call
    186             // close() and the other one is calling accept() by sending a GET
    187             // request for shutdown and having the server's one thread
    188             // sequentially call accept() and close().
    189             URL url = new URL(mServerUri + SHUTDOWN_PREFIX);
    190             URLConnection connection = openConnection(url);
    191             connection.connect();
    192 
    193             // Read the input from the stream to send the request.
    194             InputStream is = connection.getInputStream();
    195             is.close();
    196 
    197             // Block until the server thread is done shutting down.
    198             mServerThread.join();
    199 
    200         } catch (MalformedURLException e) {
    201             throw new IllegalStateException(e);
    202         } catch (InterruptedException e) {
    203             throw new RuntimeException(e);
    204         } catch (IOException e) {
    205             throw new RuntimeException(e);
    206         } catch (NoSuchAlgorithmException e) {
    207             throw new IllegalStateException(e);
    208         } catch (KeyManagementException e) {
    209             throw new IllegalStateException(e);
    210         }
    211 
    212         sInstance = null;
    213     }
    214 
    215     private URLConnection openConnection(URL url)
    216             throws IOException, NoSuchAlgorithmException, KeyManagementException {
    217         if (mSsl) {
    218             // Install hostname verifiers and trust managers that don't do
    219             // anything in order to get around the client not trusting
    220             // the test server due to a lack of certificates.
    221 
    222             HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
    223             connection.setHostnameVerifier(new CtsHostnameVerifier());
    224 
    225             SSLContext context = SSLContext.getInstance("TLS");
    226             CtsTrustManager trustManager = new CtsTrustManager();
    227             context.init(null, new CtsTrustManager[] {trustManager}, null);
    228             connection.setSSLSocketFactory(context.getSocketFactory());
    229 
    230             return connection;
    231         } else {
    232             return url.openConnection();
    233         }
    234     }
    235 
    236     /**
    237      * {@link X509TrustManager} that trusts everybody. This is used so that
    238      * the client calling {@link CtsTestServer#shutdown()} can issue a request
    239      * for shutdown by blindly trusting the {@link CtsTestServer}'s
    240      * credentials.
    241      */
    242     private static class CtsTrustManager implements X509TrustManager {
    243         public void checkClientTrusted(X509Certificate[] chain, String authType) {
    244             // Trust the CtSTestServer...
    245         }
    246 
    247         public void checkServerTrusted(X509Certificate[] chain, String authType) {
    248             // Trust the CtSTestServer...
    249         }
    250 
    251         public X509Certificate[] getAcceptedIssuers() {
    252             return null;
    253         }
    254     }
    255 
    256     /**
    257      * {@link HostnameVerifier} that verifies everybody. This permits
    258      * the client to trust the web server and call
    259      * {@link CtsTestServer#shutdown()}.
    260      */
    261     private static class CtsHostnameVerifier implements HostnameVerifier {
    262         public boolean verify(String hostname, SSLSession session) {
    263             return true;
    264         }
    265     }
    266 
    267     /**
    268      * Return the URI that points to the server root.
    269      */
    270     public String getBaseUri() {
    271         return mServerUri;
    272     }
    273 
    274     /**
    275      * Return the absolute URL that refers to the given asset.
    276      * @param path The path of the asset. See {@link AssetManager#open(String)}
    277      */
    278     public String getAssetUrl(String path) {
    279         StringBuilder sb = new StringBuilder(getBaseUri());
    280         sb.append(ASSET_PREFIX);
    281         sb.append(path);
    282         return sb.toString();
    283     }
    284 
    285     /**
    286      * Return an artificially delayed absolute URL that refers to the given asset. This can be
    287      * used to emulate a slow HTTP server or connection.
    288      * @param path The path of the asset. See {@link AssetManager#open(String)}
    289      */
    290     public String getDelayedAssetUrl(String path) {
    291         StringBuilder sb = new StringBuilder(getBaseUri());
    292         sb.append(DELAY_PREFIX);
    293         sb.append(ASSET_PREFIX);
    294         sb.append(path);
    295         return sb.toString();
    296     }
    297 
    298     /**
    299      * Return an absolute URL that refers to the given asset and is protected by
    300      * HTTP authentication.
    301      * @param path The path of the asset. See {@link AssetManager#open(String)}
    302      */
    303     public String getAuthAssetUrl(String path) {
    304         StringBuilder sb = new StringBuilder(getBaseUri());
    305         sb.append(AUTH_PREFIX);
    306         sb.append(ASSET_PREFIX);
    307         sb.append(path);
    308         return sb.toString();
    309     }
    310 
    311 
    312     /**
    313      * Return an absolute URL that indirectly refers to the given asset.
    314      * When a client fetches this URL, the server will respond with a temporary redirect (302)
    315      * referring to the absolute URL of the given asset.
    316      * @param path The path of the asset. See {@link AssetManager#open(String)}
    317      */
    318     public String getRedirectingAssetUrl(String path) {
    319         return getRedirectingAssetUrl(path, 1);
    320     }
    321 
    322     /**
    323      * Return an absolute URL that indirectly refers to the given asset.
    324      * When a client fetches this URL, the server will respond with a temporary redirect (302)
    325      * referring to the absolute URL of the given asset.
    326      * @param path The path of the asset. See {@link AssetManager#open(String)}
    327      * @param numRedirects The number of redirects required to reach the given asset.
    328      */
    329     public String getRedirectingAssetUrl(String path, int numRedirects) {
    330         StringBuilder sb = new StringBuilder(getBaseUri());
    331         for (int i = 0; i < numRedirects; i++) {
    332             sb.append(REDIRECT_PREFIX);
    333         }
    334         sb.append(ASSET_PREFIX);
    335         sb.append(path);
    336         return sb.toString();
    337     }
    338 
    339     public String getBinaryUrl(String mimeType, int contentLength) {
    340         StringBuilder sb = new StringBuilder(getBaseUri());
    341         sb.append(BINARY_PREFIX);
    342         sb.append("?type=");
    343         sb.append(mimeType);
    344         sb.append("&length=");
    345         sb.append(contentLength);
    346         return sb.toString();
    347     }
    348 
    349     public String getCookieUrl(String path) {
    350         StringBuilder sb = new StringBuilder(getBaseUri());
    351         sb.append(COOKIE_PREFIX);
    352         sb.append("/");
    353         sb.append(path);
    354         return sb.toString();
    355     }
    356 
    357     public String getUserAgentUrl() {
    358         StringBuilder sb = new StringBuilder(getBaseUri());
    359         sb.append(USERAGENT_PATH);
    360         return sb.toString();
    361     }
    362 
    363     public String getAppCacheUrl() {
    364         StringBuilder sb = new StringBuilder(getBaseUri());
    365         sb.append(APPCACHE_PATH);
    366         return sb.toString();
    367     }
    368 
    369     /**
    370      * @param downloadId used to differentiate the files created for each test
    371      * @param numBytes of the content that the CTS server should send back
    372      * @return url to get the file from
    373      */
    374     public String getTestDownloadUrl(String downloadId, int numBytes) {
    375         return Uri.parse(getBaseUri())
    376                 .buildUpon()
    377                 .path(TEST_DOWNLOAD_PATH)
    378                 .appendQueryParameter(DOWNLOAD_ID_PARAMETER, downloadId)
    379                 .appendQueryParameter(NUM_BYTES_PARAMETER, Integer.toString(numBytes))
    380                 .build()
    381                 .toString();
    382     }
    383 
    384     public synchronized String getLastRequestUrl() {
    385         return mLastQuery;
    386     }
    387 
    388     public synchronized int getRequestCount() {
    389         return mRequestCount;
    390     }
    391 
    392     /**
    393      * Set the validity of any future responses in milliseconds. If this is set to a non-zero
    394      * value, the server will include a "Expires" header.
    395      * @param timeMillis The time, in milliseconds, for which any future response will be valid.
    396      */
    397     public synchronized void setDocumentValidity(long timeMillis) {
    398         mDocValidity = timeMillis;
    399     }
    400 
    401     /**
    402      * Set the age of documents served. If this is set to a non-zero value, the server will include
    403      * a "Last-Modified" header calculated from the value.
    404      * @param timeMillis The age, in milliseconds, of any document served in the future.
    405      */
    406     public synchronized void setDocumentAge(long timeMillis) {
    407         mDocAge = timeMillis;
    408     }
    409 
    410     /**
    411      * Generate a response to the given request.
    412      * @throws InterruptedException
    413      * @throws IOException
    414      */
    415     private HttpResponse getResponse(HttpRequest request) throws InterruptedException, IOException {
    416         RequestLine requestLine = request.getRequestLine();
    417         HttpResponse response = null;
    418         Log.i(TAG, requestLine.getMethod() + ": " + requestLine.getUri());
    419         String uriString = requestLine.getUri();
    420 
    421         synchronized (this) {
    422             mRequestCount += 1;
    423             mLastQuery = uriString;
    424         }
    425 
    426         URI uri = URI.create(uriString);
    427         String path = uri.getPath();
    428         String query = uri.getQuery();
    429         if (path.equals(FAVICON_PATH)) {
    430             path = FAVICON_ASSET_PATH;
    431         }
    432         if (path.startsWith(DELAY_PREFIX)) {
    433             try {
    434                 Thread.sleep(DELAY_MILLIS);
    435             } catch (InterruptedException ignored) {
    436                 // ignore
    437             }
    438             path = path.substring(DELAY_PREFIX.length());
    439         }
    440         if (path.startsWith(AUTH_PREFIX)) {
    441             // authentication required
    442             Header[] auth = request.getHeaders("Authorization");
    443             if ((auth.length > 0 && auth[0].getValue().equals(AUTH_CREDENTIALS))
    444                 // This is a hack to make sure that loads to this url's will always
    445                 // ask for authentication. This is what the test expects.
    446                  && !path.endsWith("embedded_image.html")) {
    447                 // fall through and serve content
    448                 path = path.substring(AUTH_PREFIX.length());
    449             } else {
    450                 // request authorization
    451                 response = createResponse(HttpStatus.SC_UNAUTHORIZED);
    452                 response.addHeader("WWW-Authenticate", "Basic realm=\"" + AUTH_REALM + "\"");
    453             }
    454         }
    455         if (path.startsWith(BINARY_PREFIX)) {
    456             List <NameValuePair> args = URLEncodedUtils.parse(uri, "UTF-8");
    457             int length = 0;
    458             String mimeType = null;
    459             try {
    460                 for (NameValuePair pair : args) {
    461                     String name = pair.getName();
    462                     if (name.equals("type")) {
    463                         mimeType = pair.getValue();
    464                     } else if (name.equals("length")) {
    465                         length = Integer.parseInt(pair.getValue());
    466                     }
    467                 }
    468                 if (length > 0 && mimeType != null) {
    469                     ByteArrayEntity entity = new ByteArrayEntity(new byte[length]);
    470                     entity.setContentType(mimeType);
    471                     response = createResponse(HttpStatus.SC_OK);
    472                     response.setEntity(entity);
    473                     response.addHeader("Content-Disposition", "attachment; filename=test.bin");
    474                 } else {
    475                     // fall through, return 404 at the end
    476                 }
    477             } catch (Exception e) {
    478                 // fall through, return 404 at the end
    479                 Log.w(TAG, e);
    480             }
    481         } else if (path.startsWith(ASSET_PREFIX)) {
    482             path = path.substring(ASSET_PREFIX.length());
    483             // request for an asset file
    484             try {
    485                 InputStream in = mAssets.open(path);
    486                 response = createResponse(HttpStatus.SC_OK);
    487                 InputStreamEntity entity = new InputStreamEntity(in, in.available());
    488                 String mimeType =
    489                     mMap.getMimeTypeFromExtension(MimeTypeMap.getFileExtensionFromUrl(path));
    490                 if (mimeType == null) {
    491                     mimeType = "text/html";
    492                 }
    493                 entity.setContentType(mimeType);
    494                 response.setEntity(entity);
    495                 if (query == null || !query.contains(NOLENGTH_POSTFIX)) {
    496                     response.setHeader("Content-Length", "" + entity.getContentLength());
    497                 }
    498             } catch (IOException e) {
    499                 response = null;
    500                 // fall through, return 404 at the end
    501             }
    502         } else if (path.startsWith(REDIRECT_PREFIX)) {
    503             response = createResponse(HttpStatus.SC_MOVED_TEMPORARILY);
    504             String location = getBaseUri() + path.substring(REDIRECT_PREFIX.length());
    505             Log.i(TAG, "Redirecting to: " + location);
    506             response.addHeader("Location", location);
    507         } else if (path.startsWith(COOKIE_PREFIX)) {
    508             /*
    509              * Return a page with a title containing a list of all incoming cookies,
    510              * separated by '|' characters. If a numeric 'count' value is passed in a cookie,
    511              * return a cookie with the value incremented by 1. Otherwise, return a cookie
    512              * setting 'count' to 0.
    513              */
    514             response = createResponse(HttpStatus.SC_OK);
    515             Header[] cookies = request.getHeaders("Cookie");
    516             Pattern p = Pattern.compile("count=(\\d+)");
    517             StringBuilder cookieString = new StringBuilder(100);
    518             int count = 0;
    519             for (Header cookie : cookies) {
    520                 String value = cookie.getValue();
    521                 if (cookieString.length() > 0) {
    522                     cookieString.append("|");
    523                 }
    524                 cookieString.append(value);
    525                 Matcher m = p.matcher(value);
    526                 if (m.find()) {
    527                     count = Integer.parseInt(m.group(1)) + 1;
    528                 }
    529             }
    530 
    531             response.addHeader("Set-Cookie", "count=" + count + "; path=" + COOKIE_PREFIX);
    532             response.setEntity(createEntity("<html><head><title>" + cookieString +
    533                     "</title></head><body>" + cookieString + "</body></html>"));
    534         } else if (path.equals(USERAGENT_PATH)) {
    535             response = createResponse(HttpStatus.SC_OK);
    536             Header agentHeader = request.getFirstHeader("User-Agent");
    537             String agent = "";
    538             if (agentHeader != null) {
    539                 agent = agentHeader.getValue();
    540             }
    541             response.setEntity(createEntity("<html><head><title>" + agent + "</title></head>" +
    542                     "<body>" + agent + "</body></html>"));
    543         } else if (path.equals(TEST_DOWNLOAD_PATH)) {
    544             response = createTestDownloadResponse(Uri.parse(uriString));
    545         } else if (path.equals(SHUTDOWN_PREFIX)) {
    546             response = createResponse(HttpStatus.SC_OK);
    547             // We cannot close the socket here, because we need to respond.
    548             // Status must be set to OK, or else the test will fail due to
    549             // a RunTimeException.
    550         } else if (path.equals(APPCACHE_PATH)) {
    551             response = createResponse(HttpStatus.SC_OK);
    552             response.setEntity(createEntity("<!DOCTYPE HTML>" +
    553                     "<html manifest=\"appcache.manifest\">" +
    554                     "  <head>" +
    555                     "    <title>Waiting</title>" +
    556                     "    <script>" +
    557                     "      function updateTitle() { document.title = \"Done\"; }" +
    558                     "      window.applicationCache.onnoupdate = updateTitle;" +
    559                     "      window.applicationCache.oncached = updateTitle;" +
    560                     "      window.applicationCache.onupdateready = updateTitle;" +
    561                     "      window.applicationCache.onobsolete = updateTitle;" +
    562                     "      window.applicationCache.onerror = updateTitle;" +
    563                     "    </script>" +
    564                     "  </head>" +
    565                     "  <body>AppCache test</body>" +
    566                     "</html>"));
    567         } else if (path.equals(APPCACHE_MANIFEST_PATH)) {
    568             response = createResponse(HttpStatus.SC_OK);
    569             try {
    570                 StringEntity entity = new StringEntity("CACHE MANIFEST");
    571                 // This entity property is not used when constructing the response, (See
    572                 // AbstractMessageWriter.write(), which is called by
    573                 // AbstractHttpServerConnection.sendResponseHeader()) so we have to set this header
    574                 // manually.
    575                 // TODO: Should we do this for all responses from this server?
    576                 entity.setContentType("text/cache-manifest");
    577                 response.setEntity(entity);
    578                 response.setHeader("Content-Type", "text/cache-manifest");
    579             } catch (UnsupportedEncodingException e) {
    580                 Log.w(TAG, "Unexpected UnsupportedEncodingException");
    581             }
    582         }
    583         if (response == null) {
    584             response = createResponse(HttpStatus.SC_NOT_FOUND);
    585         }
    586         StatusLine sl = response.getStatusLine();
    587         Log.i(TAG, sl.getStatusCode() + "(" + sl.getReasonPhrase() + ")");
    588         setDateHeaders(response);
    589         return response;
    590     }
    591 
    592     private void setDateHeaders(HttpResponse response) {
    593         long time = System.currentTimeMillis();
    594         synchronized (this) {
    595             if (mDocValidity != 0) {
    596                 String expires = DateUtils.formatDate(new Date(time + mDocValidity),
    597                         DateUtils.PATTERN_RFC1123);
    598                 response.addHeader("Expires", expires);
    599             }
    600             if (mDocAge != 0) {
    601                 String modified = DateUtils.formatDate(new Date(time - mDocAge),
    602                         DateUtils.PATTERN_RFC1123);
    603                 response.addHeader("Last-Modified", modified);
    604             }
    605         }
    606         response.addHeader("Date", DateUtils.formatDate(new Date(), DateUtils.PATTERN_RFC1123));
    607     }
    608 
    609     /**
    610      * Create an empty response with the given status.
    611      */
    612     private static HttpResponse createResponse(int status) {
    613         HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_0, status, null);
    614 
    615         // Fill in error reason. Avoid use of the ReasonPhraseCatalog, which is Locale-dependent.
    616         String reason = getReasonString(status);
    617         if (reason != null) {
    618             StringBuffer buf = new StringBuffer("<html><head><title>");
    619             buf.append(reason);
    620             buf.append("</title></head><body>");
    621             buf.append(reason);
    622             buf.append("</body></html>");
    623             response.setEntity(createEntity(buf.toString()));
    624         }
    625         return response;
    626     }
    627 
    628     /**
    629      * Create a string entity for the given content.
    630      */
    631     private static StringEntity createEntity(String content) {
    632         try {
    633             StringEntity entity = new StringEntity(content);
    634             entity.setContentType("text/html");
    635             return entity;
    636         } catch (UnsupportedEncodingException e) {
    637             Log.w(TAG, e);
    638         }
    639         return null;
    640     }
    641 
    642     private static HttpResponse createTestDownloadResponse(Uri uri) throws IOException {
    643         String downloadId = uri.getQueryParameter(DOWNLOAD_ID_PARAMETER);
    644         int numBytes = uri.getQueryParameter(NUM_BYTES_PARAMETER) != null
    645                 ? Integer.parseInt(uri.getQueryParameter(NUM_BYTES_PARAMETER))
    646                 : 0;
    647         HttpResponse response = createResponse(HttpStatus.SC_OK);
    648         response.setHeader("Content-Length", Integer.toString(numBytes));
    649         response.setEntity(createFileEntity(downloadId, numBytes));
    650         return response;
    651     }
    652 
    653     private static FileEntity createFileEntity(String downloadId, int numBytes) throws IOException {
    654         String storageState = Environment.getExternalStorageState();
    655         if (Environment.MEDIA_MOUNTED.equalsIgnoreCase(storageState)) {
    656             File storageDir = Environment.getExternalStorageDirectory();
    657             File file = new File(storageDir, downloadId + ".bin");
    658             BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(file));
    659             byte data[] = new byte[1024];
    660             for (int i = 0; i < data.length; i++) {
    661                 data[i] = 1;
    662             }
    663             try {
    664                 for (int i = 0; i < numBytes / data.length; i++) {
    665                     stream.write(data);
    666                 }
    667                 stream.write(data, 0, numBytes % data.length);
    668                 stream.flush();
    669             } finally {
    670                 stream.close();
    671             }
    672             return new FileEntity(file, "application/octet-stream");
    673         } else {
    674             throw new IllegalStateException("External storage must be mounted for this test!");
    675         }
    676     }
    677 
    678     private static class ServerThread extends Thread {
    679         private CtsTestServer mServer;
    680         private ServerSocket mSocket;
    681         private boolean mIsSsl;
    682         private boolean mIsCancelled;
    683         private SSLContext mSslContext;
    684         private ExecutorService mExecutorService = Executors.newFixedThreadPool(20);
    685 
    686         /**
    687          * Defines the keystore contents for the server, BKS version. Holds just a
    688          * single self-generated key. The subject name is "Test Server".
    689          */
    690         private static final String SERVER_KEYS_BKS =
    691             "AAAAAQAAABQDkebzoP1XwqyWKRCJEpn/t8dqIQAABDkEAAVteWtleQAAARpYl20nAAAAAQAFWC41" +
    692             "MDkAAAJNMIICSTCCAbKgAwIBAgIESEfU1jANBgkqhkiG9w0BAQUFADBpMQswCQYDVQQGEwJVUzET" +
    693             "MBEGA1UECBMKQ2FsaWZvcm5pYTEMMAoGA1UEBxMDTVRWMQ8wDQYDVQQKEwZHb29nbGUxEDAOBgNV" +
    694             "BAsTB0FuZHJvaWQxFDASBgNVBAMTC1Rlc3QgU2VydmVyMB4XDTA4MDYwNTExNTgxNFoXDTA4MDkw" +
    695             "MzExNTgxNFowaTELMAkGA1UEBhMCVVMxEzARBgNVBAgTCkNhbGlmb3JuaWExDDAKBgNVBAcTA01U" +
    696             "VjEPMA0GA1UEChMGR29vZ2xlMRAwDgYDVQQLEwdBbmRyb2lkMRQwEgYDVQQDEwtUZXN0IFNlcnZl" +
    697             "cjCBnzANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEA0LIdKaIr9/vsTq8BZlA3R+NFWRaH4lGsTAQy" +
    698             "DPMF9ZqEDOaL6DJuu0colSBBBQ85hQTPa9m9nyJoN3pEi1hgamqOvQIWcXBk+SOpUGRZZFXwniJV" +
    699             "zDKU5nE9MYgn2B9AoiH3CSuMz6HRqgVaqtppIe1jhukMc/kHVJvlKRNy9XMCAwEAATANBgkqhkiG" +
    700             "9w0BAQUFAAOBgQC7yBmJ9O/eWDGtSH9BH0R3dh2NdST3W9hNZ8hIa8U8klhNHbUCSSktZmZkvbPU" +
    701             "hse5LI3dh6RyNDuqDrbYwcqzKbFJaq/jX9kCoeb3vgbQElMRX8D2ID1vRjxwlALFISrtaN4VpWzV" +
    702             "yeoHPW4xldeZmoVtjn8zXNzQhLuBqX2MmAAAAqwAAAAUvkUScfw9yCSmALruURNmtBai7kQAAAZx" +
    703             "4Jmijxs/l8EBaleaUru6EOPioWkUAEVWCxjM/TxbGHOi2VMsQWqRr/DZ3wsDmtQgw3QTrUK666sR" +
    704             "MBnbqdnyCyvM1J2V1xxLXPUeRBmR2CXorYGF9Dye7NkgVdfA+9g9L/0Au6Ugn+2Cj5leoIgkgApN" +
    705             "vuEcZegFlNOUPVEs3SlBgUF1BY6OBM0UBHTPwGGxFBBcetcuMRbUnu65vyDG0pslT59qpaR0TMVs" +
    706             "P+tcheEzhyjbfM32/vwhnL9dBEgM8qMt0sqF6itNOQU/F4WGkK2Cm2v4CYEyKYw325fEhzTXosck" +
    707             "MhbqmcyLab8EPceWF3dweoUT76+jEZx8lV2dapR+CmczQI43tV9btsd1xiBbBHAKvymm9Ep9bPzM" +
    708             "J0MQi+OtURL9Lxke/70/MRueqbPeUlOaGvANTmXQD2OnW7PISwJ9lpeLfTG0LcqkoqkbtLKQLYHI" +
    709             "rQfV5j0j+wmvmpMxzjN3uvNajLa4zQ8l0Eok9SFaRr2RL0gN8Q2JegfOL4pUiHPsh64WWya2NB7f" +
    710             "V+1s65eA5ospXYsShRjo046QhGTmymwXXzdzuxu8IlnTEont6P4+J+GsWk6cldGbl20hctuUKzyx" +
    711             "OptjEPOKejV60iDCYGmHbCWAzQ8h5MILV82IclzNViZmzAapeeCnexhpXhWTs+xDEYSKEiG/camt" +
    712             "bhmZc3BcyVJrW23PktSfpBQ6D8ZxoMfF0L7V2GQMaUg+3r7ucrx82kpqotjv0xHghNIm95aBr1Qw" +
    713             "1gaEjsC/0wGmmBDg1dTDH+F1p9TInzr3EFuYD0YiQ7YlAHq3cPuyGoLXJ5dXYuSBfhDXJSeddUkl" +
    714             "k1ufZyOOcskeInQge7jzaRfmKg3U94r+spMEvb0AzDQVOKvjjo1ivxMSgFRZaDb/4qw=";
    715 
    716         private String PASSWORD = "android";
    717 
    718         /**
    719          * Loads a keystore from a base64-encoded String. Returns the KeyManager[]
    720          * for the result.
    721          */
    722         private KeyManager[] getKeyManagers() throws Exception {
    723             byte[] bytes = Base64.decode(SERVER_KEYS_BKS.getBytes());
    724             InputStream inputStream = new ByteArrayInputStream(bytes);
    725 
    726             KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
    727             keyStore.load(inputStream, PASSWORD.toCharArray());
    728             inputStream.close();
    729 
    730             String algorithm = KeyManagerFactory.getDefaultAlgorithm();
    731             KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(algorithm);
    732             keyManagerFactory.init(keyStore, PASSWORD.toCharArray());
    733 
    734             return keyManagerFactory.getKeyManagers();
    735         }
    736 
    737 
    738         public ServerThread(CtsTestServer server, boolean ssl) throws Exception {
    739             super("ServerThread");
    740             mServer = server;
    741             mIsSsl = ssl;
    742             int retry = 3;
    743             while (true) {
    744                 try {
    745                     if (mIsSsl) {
    746                         mSslContext = SSLContext.getInstance("TLS");
    747                         mSslContext.init(getKeyManagers(), null, null);
    748                         mSocket = mSslContext.getServerSocketFactory().createServerSocket(
    749                                 SSL_SERVER_PORT);
    750                     } else {
    751                         mSocket = new ServerSocket(SERVER_PORT);
    752                     }
    753                     return;
    754                 } catch (IOException e) {
    755                     Log.w(TAG, e);
    756                     if (--retry == 0) {
    757                         throw e;
    758                     }
    759                     // sleep in case server socket is still being closed
    760                     Thread.sleep(1000);
    761                 }
    762             }
    763         }
    764 
    765         public void run() {
    766             while (!mIsCancelled) {
    767                 try {
    768                     Socket socket = mSocket.accept();
    769 
    770                     DefaultHttpServerConnection conn = new DefaultHttpServerConnection();
    771                     HttpParams params = new BasicHttpParams();
    772                     params.setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_0);
    773                     conn.bind(socket, params);
    774 
    775                     // Determine whether we need to shutdown early before
    776                     // parsing the response since conn.close() will crash
    777                     // for SSL requests due to UnsupportedOperationException.
    778                     HttpRequest request = conn.receiveRequestHeader();
    779                     if (isShutdownRequest(request)) {
    780                         mIsCancelled = true;
    781                     }
    782                     mExecutorService.submit(new HandleResponseTask(conn, request));
    783                 } catch (IOException e) {
    784                     // normal during shutdown, ignore
    785                     Log.w(TAG, e);
    786                 } catch (HttpException e) {
    787                     Log.w(TAG, e);
    788                 } catch (UnsupportedOperationException e) {
    789                     // DefaultHttpServerConnection's close() throws an
    790                     // UnsupportedOperationException.
    791                     Log.w(TAG, e);
    792                 }
    793             }
    794             try {
    795                 mExecutorService.shutdown();
    796                 mExecutorService.awaitTermination(1L, TimeUnit.MINUTES);
    797                 mSocket.close();
    798             } catch (IOException ignored) {
    799                 // safe to ignore
    800             } catch (InterruptedException e) {
    801                 Log.e(TAG, "Shutting down threads", e);
    802             }
    803         }
    804 
    805         private static boolean isShutdownRequest(HttpRequest request) {
    806             RequestLine requestLine = request.getRequestLine();
    807             String uriString = requestLine.getUri();
    808             URI uri = URI.create(uriString);
    809             String path = uri.getPath();
    810             return path.equals(SHUTDOWN_PREFIX);
    811         }
    812 
    813         private class HandleResponseTask implements Callable<Void> {
    814 
    815             private DefaultHttpServerConnection mConnection;
    816 
    817             private HttpRequest mRequest;
    818 
    819             public HandleResponseTask(DefaultHttpServerConnection connection,
    820                     HttpRequest request) {
    821                 this.mConnection = connection;
    822                 this.mRequest = request;
    823             }
    824 
    825             @Override
    826             public Void call() throws IOException, InterruptedException, HttpException {
    827                 HttpResponse response = mServer.getResponse(mRequest);
    828                 mConnection.sendResponseHeader(response);
    829                 mConnection.sendResponseEntity(response);
    830                 mConnection.close();
    831                 return null;
    832             }
    833         }
    834     }
    835 }
    836