HttpsConnection.java revision c2ad241504fcaa12d4579d3b0b4038d1ca8d08c9
1/*
2 * Copyright (C) 2007 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
17package android.net.http;
18
19import android.content.Context;
20import android.util.Log;
21import org.apache.harmony.xnet.provider.jsse.FileClientSessionCache;
22import org.apache.harmony.xnet.provider.jsse.SSLClientSessionCache;
23import org.apache.harmony.xnet.provider.jsse.SSLContextImpl;
24import org.apache.http.Header;
25import org.apache.http.HttpException;
26import org.apache.http.HttpHost;
27import org.apache.http.HttpStatus;
28import org.apache.http.ParseException;
29import org.apache.http.ProtocolVersion;
30import org.apache.http.StatusLine;
31import org.apache.http.message.BasicHttpRequest;
32import org.apache.http.params.BasicHttpParams;
33import org.apache.http.params.HttpConnectionParams;
34import org.apache.http.params.HttpParams;
35
36import javax.net.ssl.SSLException;
37import javax.net.ssl.SSLSocket;
38import javax.net.ssl.SSLSocketFactory;
39import javax.net.ssl.TrustManager;
40import javax.net.ssl.X509TrustManager;
41import java.io.File;
42import java.io.IOException;
43import java.net.InetSocketAddress;
44import java.net.Socket;
45import java.security.KeyManagementException;
46import java.security.cert.X509Certificate;
47
48/**
49 * A Connection connecting to a secure http server or tunneling through
50 * a http proxy server to a https server.
51 *
52 * @hide
53 */
54public class HttpsConnection extends Connection {
55
56    /**
57     * SSL socket factory
58     */
59    private static SSLSocketFactory mSslSocketFactory = null;
60
61    static {
62        // This intiialization happens in the zygote. It triggers some
63        // lazy initialization that can will benefit later invocations of
64        // initializeEngine().
65        initializeEngine(null);
66    }
67
68    /**
69     * @hide
70     *
71     * @param sessionDir directory to cache SSL sessions
72     */
73    public static void initializeEngine(File sessionDir) {
74        try {
75            SSLClientSessionCache cache = null;
76            if (sessionDir != null) {
77                Log.d("HttpsConnection", "Caching SSL sessions in "
78                        + sessionDir + ".");
79                cache = FileClientSessionCache.usingDirectory(sessionDir);
80            }
81
82            SSLContextImpl sslContext = new SSLContextImpl();
83
84            // here, trust managers is a single trust-all manager
85            TrustManager[] trustManagers = new TrustManager[] {
86                new X509TrustManager() {
87                    public X509Certificate[] getAcceptedIssuers() {
88                        return null;
89                    }
90
91                    public void checkClientTrusted(
92                        X509Certificate[] certs, String authType) {
93                    }
94
95                    public void checkServerTrusted(
96                        X509Certificate[] certs, String authType) {
97                    }
98                }
99            };
100
101            sslContext.engineInit(null, trustManagers, null, cache, null);
102
103            synchronized (HttpsConnection.class) {
104                mSslSocketFactory = sslContext.engineGetSocketFactory();
105            }
106        } catch (KeyManagementException e) {
107            throw new RuntimeException(e);
108        } catch (IOException e) {
109            throw new RuntimeException(e);
110        }
111    }
112
113    private synchronized static SSLSocketFactory getSocketFactory() {
114        return mSslSocketFactory;
115    }
116
117    /**
118     * Object to wait on when suspending the SSL connection
119     */
120    private Object mSuspendLock = new Object();
121
122    /**
123     * True if the connection is suspended pending the result of asking the
124     * user about an error.
125     */
126    private boolean mSuspended = false;
127
128    /**
129     * True if the connection attempt should be aborted due to an ssl
130     * error.
131     */
132    private boolean mAborted = false;
133
134    /**
135     * Contructor for a https connection.
136     */
137    HttpsConnection(Context context, HttpHost host,
138                    RequestQueue.ConnectionManager connectionManager,
139                    RequestFeeder requestFeeder) {
140        super(context, host, connectionManager, requestFeeder);
141    }
142
143    /**
144     * Sets the server SSL certificate associated with this
145     * connection.
146     * @param certificate The SSL certificate
147     */
148    /* package */ void setCertificate(SslCertificate certificate) {
149        mCertificate = certificate;
150    }
151
152    /**
153     * Opens the connection to a http server or proxy.
154     *
155     * @return the opened low level connection
156     * @throws IOException if the connection fails for any reason.
157     */
158    @Override
159    AndroidHttpClientConnection openConnection(Request req) throws IOException {
160        SSLSocket sslSock = null;
161
162        HttpHost proxyHost = mConnectionManager.getProxyHost();
163        if (proxyHost != null) {
164            // If we have a proxy set, we first send a CONNECT request
165            // to the proxy; if the proxy returns 200 OK, we negotiate
166            // a secure connection to the target server via the proxy.
167            // If the request fails, we drop it, but provide the event
168            // handler with the response status and headers. The event
169            // handler is then responsible for cancelling the load or
170            // issueing a new request.
171            AndroidHttpClientConnection proxyConnection = null;
172            Socket proxySock = null;
173            try {
174                proxySock = new Socket
175                    (proxyHost.getHostName(), proxyHost.getPort());
176
177                proxySock.setSoTimeout(60 * 1000);
178
179                proxyConnection = new AndroidHttpClientConnection();
180                HttpParams params = new BasicHttpParams();
181                HttpConnectionParams.setSocketBufferSize(params, 8192);
182
183                proxyConnection.bind(proxySock, params);
184            } catch(IOException e) {
185                if (proxyConnection != null) {
186                    proxyConnection.close();
187                }
188
189                String errorMessage = e.getMessage();
190                if (errorMessage == null) {
191                    errorMessage =
192                        "failed to establish a connection to the proxy";
193                }
194
195                throw new IOException(errorMessage);
196            }
197
198            StatusLine statusLine = null;
199            int statusCode = 0;
200            Headers headers = new Headers();
201            try {
202                BasicHttpRequest proxyReq = new BasicHttpRequest
203                    ("CONNECT", mHost.toHostString());
204
205                // add all 'proxy' headers from the original request
206                for (Header h : req.mHttpRequest.getAllHeaders()) {
207                    String headerName = h.getName().toLowerCase();
208                    if (headerName.startsWith("proxy") || headerName.equals("keep-alive")) {
209                        proxyReq.addHeader(h);
210                    }
211                }
212
213                proxyConnection.sendRequestHeader(proxyReq);
214                proxyConnection.flush();
215
216                // it is possible to receive informational status
217                // codes prior to receiving actual headers;
218                // all those status codes are smaller than OK 200
219                // a loop is a standard way of dealing with them
220                do {
221                    statusLine = proxyConnection.parseResponseHeader(headers);
222                    statusCode = statusLine.getStatusCode();
223                } while (statusCode < HttpStatus.SC_OK);
224            } catch (ParseException e) {
225                String errorMessage = e.getMessage();
226                if (errorMessage == null) {
227                    errorMessage =
228                        "failed to send a CONNECT request";
229                }
230
231                throw new IOException(errorMessage);
232            } catch (HttpException e) {
233                String errorMessage = e.getMessage();
234                if (errorMessage == null) {
235                    errorMessage =
236                        "failed to send a CONNECT request";
237                }
238
239                throw new IOException(errorMessage);
240            } catch (IOException e) {
241                String errorMessage = e.getMessage();
242                if (errorMessage == null) {
243                    errorMessage =
244                        "failed to send a CONNECT request";
245                }
246
247                throw new IOException(errorMessage);
248            }
249
250            if (statusCode == HttpStatus.SC_OK) {
251                try {
252                    sslSock = (SSLSocket) getSocketFactory().createSocket(
253                            proxySock, mHost.getHostName(), mHost.getPort(), true);
254                } catch(IOException e) {
255                    if (sslSock != null) {
256                        sslSock.close();
257                    }
258
259                    String errorMessage = e.getMessage();
260                    if (errorMessage == null) {
261                        errorMessage =
262                            "failed to create an SSL socket";
263                    }
264                    throw new IOException(errorMessage);
265                }
266            } else {
267                // if the code is not OK, inform the event handler
268                ProtocolVersion version = statusLine.getProtocolVersion();
269
270                req.mEventHandler.status(version.getMajor(),
271                                         version.getMinor(),
272                                         statusCode,
273                                         statusLine.getReasonPhrase());
274                req.mEventHandler.headers(headers);
275                req.mEventHandler.endData();
276
277                proxyConnection.close();
278
279                // here, we return null to indicate that the original
280                // request needs to be dropped
281                return null;
282            }
283        } else {
284            // if we do not have a proxy, we simply connect to the host
285            try {
286                sslSock = (SSLSocket) getSocketFactory().createSocket();
287
288                sslSock.setSoTimeout(SOCKET_TIMEOUT);
289                sslSock.connect(new InetSocketAddress(mHost.getHostName(),
290                        mHost.getPort()));
291            } catch(IOException e) {
292                if (sslSock != null) {
293                    sslSock.close();
294                }
295
296                String errorMessage = e.getMessage();
297                if (errorMessage == null) {
298                    errorMessage = "failed to create an SSL socket";
299                }
300
301                throw new IOException(errorMessage);
302            }
303        }
304
305        // do handshake and validate server certificates
306        SslError error = CertificateChainValidator.getInstance().
307            doHandshakeAndValidateServerCertificates(this, sslSock, mHost.getHostName());
308
309        EventHandler eventHandler = req.getEventHandler();
310
311        // Update the certificate info (to be consistent, it is better to do it
312        // here, before we start handling SSL errors, if any)
313        eventHandler.certificate(mCertificate);
314
315        // Inform the user if there is a problem
316        if (error != null) {
317            // handleSslErrorRequest may immediately unsuspend if it wants to
318            // allow the certificate anyway.
319            // So we mark the connection as suspended, call handleSslErrorRequest
320            // then check if we're still suspended and only wait if we actually
321            // need to.
322            synchronized (mSuspendLock) {
323                mSuspended = true;
324            }
325            // don't hold the lock while calling out to the event handler
326            eventHandler.handleSslErrorRequest(error);
327            synchronized (mSuspendLock) {
328                if (mSuspended) {
329                    try {
330                        // Put a limit on how long we are waiting; if the timeout
331                        // expires (which should never happen unless you choose
332                        // to ignore the SSL error dialog for a very long time),
333                        // we wake up the thread and abort the request. This is
334                        // to prevent us from stalling the network if things go
335                        // very bad.
336                        mSuspendLock.wait(10 * 60 * 1000);
337                        if (mSuspended) {
338                            // mSuspended is true if we have not had a chance to
339                            // restart the connection yet (ie, the wait timeout
340                            // has expired)
341                            mSuspended = false;
342                            mAborted = true;
343                            if (HttpLog.LOGV) {
344                                HttpLog.v("HttpsConnection.openConnection():" +
345                                          " SSL timeout expired and request was cancelled!!!");
346                            }
347                        }
348                    } catch (InterruptedException e) {
349                        // ignore
350                    }
351                }
352                if (mAborted) {
353                    // The user decided not to use this unverified connection
354                    // so close it immediately.
355                    sslSock.close();
356                    throw new SSLConnectionClosedByUserException("connection closed by the user");
357                }
358            }
359        }
360
361        // All went well, we have an open, verified connection.
362        AndroidHttpClientConnection conn = new AndroidHttpClientConnection();
363        BasicHttpParams params = new BasicHttpParams();
364        params.setIntParameter(HttpConnectionParams.SOCKET_BUFFER_SIZE, 8192);
365        conn.bind(sslSock, params);
366
367        return conn;
368    }
369
370    /**
371     * Closes the low level connection.
372     *
373     * If an exception is thrown then it is assumed that the connection will
374     * have been closed (to the extent possible) anyway and the caller does not
375     * need to take any further action.
376     *
377     */
378    @Override
379    void closeConnection() {
380        // if the connection has been suspended due to an SSL error
381        if (mSuspended) {
382            // wake up the network thread
383            restartConnection(false);
384        }
385
386        try {
387            if (mHttpClientConnection != null && mHttpClientConnection.isOpen()) {
388                mHttpClientConnection.close();
389            }
390        } catch (IOException e) {
391            if (HttpLog.LOGV)
392                HttpLog.v("HttpsConnection.closeConnection():" +
393                          " failed closing connection " + mHost);
394            e.printStackTrace();
395        }
396    }
397
398    /**
399     * Restart a secure connection suspended waiting for user interaction.
400     */
401    void restartConnection(boolean proceed) {
402        if (HttpLog.LOGV) {
403            HttpLog.v("HttpsConnection.restartConnection():" +
404                      " proceed: " + proceed);
405        }
406
407        synchronized (mSuspendLock) {
408            if (mSuspended) {
409                mSuspended = false;
410                mAborted = !proceed;
411                mSuspendLock.notify();
412            }
413        }
414    }
415
416    @Override
417    String getScheme() {
418        return "https";
419    }
420}
421
422/**
423 * Simple exception we throw if the SSL connection is closed by the user.
424 *
425 * {@hide}
426 */
427class SSLConnectionClosedByUserException extends SSLException {
428
429    public SSLConnectionClosedByUserException(String reason) {
430        super(reason);
431    }
432}
433