HttpsConnection.java revision 5e8a587d49f014fdd42403f51bbe877855e4a6b3
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.OpenSSLContextImpl; 23import org.apache.harmony.xnet.provider.jsse.SSLClientSessionCache; 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 initialization 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 OpenSSLContextImpl sslContext = new OpenSSLContextImpl(); 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 // Used when connecting through a proxy. 135 private HttpHost mProxyHost; 136 137 /** 138 * Contructor for a https connection. 139 */ 140 HttpsConnection(Context context, HttpHost host, HttpHost proxy, 141 RequestFeeder requestFeeder) { 142 super(context, host, requestFeeder); 143 mProxyHost = proxy; 144 } 145 146 /** 147 * Sets the server SSL certificate associated with this 148 * connection. 149 * @param certificate The SSL certificate 150 */ 151 /* package */ void setCertificate(SslCertificate certificate) { 152 mCertificate = certificate; 153 } 154 155 /** 156 * Opens the connection to a http server or proxy. 157 * 158 * @return the opened low level connection 159 * @throws IOException if the connection fails for any reason. 160 */ 161 @Override 162 AndroidHttpClientConnection openConnection(Request req) throws IOException { 163 SSLSocket sslSock = null; 164 165 if (mProxyHost != null) { 166 // If we have a proxy set, we first send a CONNECT request 167 // to the proxy; if the proxy returns 200 OK, we negotiate 168 // a secure connection to the target server via the proxy. 169 // If the request fails, we drop it, but provide the event 170 // handler with the response status and headers. The event 171 // handler is then responsible for cancelling the load or 172 // issueing a new request. 173 AndroidHttpClientConnection proxyConnection = null; 174 Socket proxySock = null; 175 try { 176 proxySock = new Socket 177 (mProxyHost.getHostName(), mProxyHost.getPort()); 178 179 proxySock.setSoTimeout(60 * 1000); 180 181 proxyConnection = new AndroidHttpClientConnection(); 182 HttpParams params = new BasicHttpParams(); 183 HttpConnectionParams.setSocketBufferSize(params, 8192); 184 185 proxyConnection.bind(proxySock, params); 186 } catch(IOException e) { 187 if (proxyConnection != null) { 188 proxyConnection.close(); 189 } 190 191 String errorMessage = e.getMessage(); 192 if (errorMessage == null) { 193 errorMessage = 194 "failed to establish a connection to the proxy"; 195 } 196 197 throw new IOException(errorMessage); 198 } 199 200 StatusLine statusLine = null; 201 int statusCode = 0; 202 Headers headers = new Headers(); 203 try { 204 BasicHttpRequest proxyReq = new BasicHttpRequest 205 ("CONNECT", mHost.toHostString()); 206 207 // add all 'proxy' headers from the original request, we also need 208 // to add 'host' header unless we want proxy to answer us with a 209 // 400 Bad Request 210 for (Header h : req.mHttpRequest.getAllHeaders()) { 211 String headerName = h.getName().toLowerCase(); 212 if (headerName.startsWith("proxy") || headerName.equals("keep-alive") 213 || headerName.equals("host")) { 214 proxyReq.addHeader(h); 215 } 216 } 217 218 proxyConnection.sendRequestHeader(proxyReq); 219 proxyConnection.flush(); 220 221 // it is possible to receive informational status 222 // codes prior to receiving actual headers; 223 // all those status codes are smaller than OK 200 224 // a loop is a standard way of dealing with them 225 do { 226 statusLine = proxyConnection.parseResponseHeader(headers); 227 statusCode = statusLine.getStatusCode(); 228 } while (statusCode < HttpStatus.SC_OK); 229 } catch (ParseException e) { 230 String errorMessage = e.getMessage(); 231 if (errorMessage == null) { 232 errorMessage = 233 "failed to send a CONNECT request"; 234 } 235 236 throw new IOException(errorMessage); 237 } catch (HttpException e) { 238 String errorMessage = e.getMessage(); 239 if (errorMessage == null) { 240 errorMessage = 241 "failed to send a CONNECT request"; 242 } 243 244 throw new IOException(errorMessage); 245 } catch (IOException e) { 246 String errorMessage = e.getMessage(); 247 if (errorMessage == null) { 248 errorMessage = 249 "failed to send a CONNECT request"; 250 } 251 252 throw new IOException(errorMessage); 253 } 254 255 if (statusCode == HttpStatus.SC_OK) { 256 try { 257 sslSock = (SSLSocket) getSocketFactory().createSocket( 258 proxySock, mHost.getHostName(), mHost.getPort(), true); 259 } catch(IOException e) { 260 if (sslSock != null) { 261 sslSock.close(); 262 } 263 264 String errorMessage = e.getMessage(); 265 if (errorMessage == null) { 266 errorMessage = 267 "failed to create an SSL socket"; 268 } 269 throw new IOException(errorMessage); 270 } 271 } else { 272 // if the code is not OK, inform the event handler 273 ProtocolVersion version = statusLine.getProtocolVersion(); 274 275 req.mEventHandler.status(version.getMajor(), 276 version.getMinor(), 277 statusCode, 278 statusLine.getReasonPhrase()); 279 req.mEventHandler.headers(headers); 280 req.mEventHandler.endData(); 281 282 proxyConnection.close(); 283 284 // here, we return null to indicate that the original 285 // request needs to be dropped 286 return null; 287 } 288 } else { 289 // if we do not have a proxy, we simply connect to the host 290 try { 291 sslSock = (SSLSocket) getSocketFactory().createSocket(); 292 293 sslSock.setSoTimeout(SOCKET_TIMEOUT); 294 sslSock.connect(new InetSocketAddress(mHost.getHostName(), 295 mHost.getPort())); 296 } catch(IOException e) { 297 if (sslSock != null) { 298 sslSock.close(); 299 } 300 301 String errorMessage = e.getMessage(); 302 if (errorMessage == null) { 303 errorMessage = "failed to create an SSL socket"; 304 } 305 306 throw new IOException(errorMessage); 307 } 308 } 309 310 // do handshake and validate server certificates 311 SslError error = CertificateChainValidator.getInstance(). 312 doHandshakeAndValidateServerCertificates(this, sslSock, mHost.getHostName()); 313 314 // Inform the user if there is a problem 315 if (error != null) { 316 // handleSslErrorRequest may immediately unsuspend if it wants to 317 // allow the certificate anyway. 318 // So we mark the connection as suspended, call handleSslErrorRequest 319 // then check if we're still suspended and only wait if we actually 320 // need to. 321 synchronized (mSuspendLock) { 322 mSuspended = true; 323 } 324 // don't hold the lock while calling out to the event handler 325 boolean canHandle = req.getEventHandler().handleSslErrorRequest(error); 326 if(!canHandle) { 327 throw new IOException("failed to handle "+ error); 328 } 329 synchronized (mSuspendLock) { 330 if (mSuspended) { 331 try { 332 // Put a limit on how long we are waiting; if the timeout 333 // expires (which should never happen unless you choose 334 // to ignore the SSL error dialog for a very long time), 335 // we wake up the thread and abort the request. This is 336 // to prevent us from stalling the network if things go 337 // very bad. 338 mSuspendLock.wait(10 * 60 * 1000); 339 if (mSuspended) { 340 // mSuspended is true if we have not had a chance to 341 // restart the connection yet (ie, the wait timeout 342 // has expired) 343 mSuspended = false; 344 mAborted = true; 345 if (HttpLog.LOGV) { 346 HttpLog.v("HttpsConnection.openConnection():" + 347 " SSL timeout expired and request was cancelled!!!"); 348 } 349 } 350 } catch (InterruptedException e) { 351 // ignore 352 } 353 } 354 if (mAborted) { 355 // The user decided not to use this unverified connection 356 // so close it immediately. 357 sslSock.close(); 358 throw new SSLConnectionClosedByUserException("connection closed by the user"); 359 } 360 } 361 } 362 363 // All went well, we have an open, verified connection. 364 AndroidHttpClientConnection conn = new AndroidHttpClientConnection(); 365 BasicHttpParams params = new BasicHttpParams(); 366 params.setIntParameter(HttpConnectionParams.SOCKET_BUFFER_SIZE, 8192); 367 conn.bind(sslSock, params); 368 369 return conn; 370 } 371 372 /** 373 * Closes the low level connection. 374 * 375 * If an exception is thrown then it is assumed that the connection will 376 * have been closed (to the extent possible) anyway and the caller does not 377 * need to take any further action. 378 * 379 */ 380 @Override 381 void closeConnection() { 382 // if the connection has been suspended due to an SSL error 383 if (mSuspended) { 384 // wake up the network thread 385 restartConnection(false); 386 } 387 388 try { 389 if (mHttpClientConnection != null && mHttpClientConnection.isOpen()) { 390 mHttpClientConnection.close(); 391 } 392 } catch (IOException e) { 393 if (HttpLog.LOGV) 394 HttpLog.v("HttpsConnection.closeConnection():" + 395 " failed closing connection " + mHost); 396 e.printStackTrace(); 397 } 398 } 399 400 /** 401 * Restart a secure connection suspended waiting for user interaction. 402 */ 403 void restartConnection(boolean proceed) { 404 if (HttpLog.LOGV) { 405 HttpLog.v("HttpsConnection.restartConnection():" + 406 " proceed: " + proceed); 407 } 408 409 synchronized (mSuspendLock) { 410 if (mSuspended) { 411 mSuspended = false; 412 mAborted = !proceed; 413 mSuspendLock.notify(); 414 } 415 } 416 } 417 418 @Override 419 String getScheme() { 420 return "https"; 421 } 422} 423 424/** 425 * Simple exception we throw if the SSL connection is closed by the user. 426 * 427 * {@hide} 428 */ 429class SSLConnectionClosedByUserException extends SSLException { 430 431 public SSLConnectionClosedByUserException(String reason) { 432 super(reason); 433 } 434} 435