use of org.apache.http.message.BasicHttpRequest in project android_frameworks_base by ParanoidAndroid.
the class SSLConnectionClosedByUserException method openConnection.
/**
* Opens the connection to a http server or proxy.
*
* @return the opened low level connection
* @throws IOException if the connection fails for any reason.
*/
@Override
AndroidHttpClientConnection openConnection(Request req) throws IOException {
SSLSocket sslSock = null;
if (mProxyHost != null) {
// If we have a proxy set, we first send a CONNECT request
// to the proxy; if the proxy returns 200 OK, we negotiate
// a secure connection to the target server via the proxy.
// If the request fails, we drop it, but provide the event
// handler with the response status and headers. The event
// handler is then responsible for cancelling the load or
// issueing a new request.
AndroidHttpClientConnection proxyConnection = null;
Socket proxySock = null;
try {
proxySock = new Socket(mProxyHost.getHostName(), mProxyHost.getPort());
proxySock.setSoTimeout(60 * 1000);
proxyConnection = new AndroidHttpClientConnection();
HttpParams params = new BasicHttpParams();
HttpConnectionParams.setSocketBufferSize(params, 8192);
proxyConnection.bind(proxySock, params);
} catch (IOException e) {
if (proxyConnection != null) {
proxyConnection.close();
}
String errorMessage = e.getMessage();
if (errorMessage == null) {
errorMessage = "failed to establish a connection to the proxy";
}
throw new IOException(errorMessage);
}
StatusLine statusLine = null;
int statusCode = 0;
Headers headers = new Headers();
try {
BasicHttpRequest proxyReq = new BasicHttpRequest("CONNECT", mHost.toHostString());
// 400 Bad Request
for (Header h : req.mHttpRequest.getAllHeaders()) {
String headerName = h.getName().toLowerCase();
if (headerName.startsWith("proxy") || headerName.equals("keep-alive") || headerName.equals("host")) {
proxyReq.addHeader(h);
}
}
proxyConnection.sendRequestHeader(proxyReq);
proxyConnection.flush();
// a loop is a standard way of dealing with them
do {
statusLine = proxyConnection.parseResponseHeader(headers);
statusCode = statusLine.getStatusCode();
} while (statusCode < HttpStatus.SC_OK);
} catch (ParseException e) {
String errorMessage = e.getMessage();
if (errorMessage == null) {
errorMessage = "failed to send a CONNECT request";
}
throw new IOException(errorMessage);
} catch (HttpException e) {
String errorMessage = e.getMessage();
if (errorMessage == null) {
errorMessage = "failed to send a CONNECT request";
}
throw new IOException(errorMessage);
} catch (IOException e) {
String errorMessage = e.getMessage();
if (errorMessage == null) {
errorMessage = "failed to send a CONNECT request";
}
throw new IOException(errorMessage);
}
if (statusCode == HttpStatus.SC_OK) {
try {
sslSock = (SSLSocket) getSocketFactory().createSocket(proxySock, mHost.getHostName(), mHost.getPort(), true);
} catch (IOException e) {
if (sslSock != null) {
sslSock.close();
}
String errorMessage = e.getMessage();
if (errorMessage == null) {
errorMessage = "failed to create an SSL socket";
}
throw new IOException(errorMessage);
}
} else {
// if the code is not OK, inform the event handler
ProtocolVersion version = statusLine.getProtocolVersion();
req.mEventHandler.status(version.getMajor(), version.getMinor(), statusCode, statusLine.getReasonPhrase());
req.mEventHandler.headers(headers);
req.mEventHandler.endData();
proxyConnection.close();
// request needs to be dropped
return null;
}
} else {
// if we do not have a proxy, we simply connect to the host
try {
sslSock = (SSLSocket) getSocketFactory().createSocket(mHost.getHostName(), mHost.getPort());
sslSock.setSoTimeout(SOCKET_TIMEOUT);
} catch (IOException e) {
if (sslSock != null) {
sslSock.close();
}
String errorMessage = e.getMessage();
if (errorMessage == null) {
errorMessage = "failed to create an SSL socket";
}
throw new IOException(errorMessage);
}
}
// do handshake and validate server certificates
SslError error = CertificateChainValidator.getInstance().doHandshakeAndValidateServerCertificates(this, sslSock, mHost.getHostName());
// Inform the user if there is a problem
if (error != null) {
// need to.
synchronized (mSuspendLock) {
mSuspended = true;
}
// don't hold the lock while calling out to the event handler
boolean canHandle = req.getEventHandler().handleSslErrorRequest(error);
if (!canHandle) {
throw new IOException("failed to handle " + error);
}
synchronized (mSuspendLock) {
if (mSuspended) {
try {
// Put a limit on how long we are waiting; if the timeout
// expires (which should never happen unless you choose
// to ignore the SSL error dialog for a very long time),
// we wake up the thread and abort the request. This is
// to prevent us from stalling the network if things go
// very bad.
mSuspendLock.wait(10 * 60 * 1000);
if (mSuspended) {
// mSuspended is true if we have not had a chance to
// restart the connection yet (ie, the wait timeout
// has expired)
mSuspended = false;
mAborted = true;
if (HttpLog.LOGV) {
HttpLog.v("HttpsConnection.openConnection():" + " SSL timeout expired and request was cancelled!!!");
}
}
} catch (InterruptedException e) {
// ignore
}
}
if (mAborted) {
// The user decided not to use this unverified connection
// so close it immediately.
sslSock.close();
throw new SSLConnectionClosedByUserException("connection closed by the user");
}
}
}
// All went well, we have an open, verified connection.
AndroidHttpClientConnection conn = new AndroidHttpClientConnection();
BasicHttpParams params = new BasicHttpParams();
params.setIntParameter(HttpConnectionParams.SOCKET_BUFFER_SIZE, 8192);
conn.bind(sslSock, params);
return conn;
}
use of org.apache.http.message.BasicHttpRequest in project platform_external_apache-http by android.
the class DefaultRequestDirector method createConnectRequest.
/**
* Creates the CONNECT request for tunnelling.
* Called by {@link #createTunnelToTarget createTunnelToTarget}.
*
* @param route the route to establish
* @param context the context for request execution
*
* @return the CONNECT request for tunnelling
*/
protected HttpRequest createConnectRequest(HttpRoute route, HttpContext context) {
// see RFC 2817, section 5.2 and
// INTERNET-DRAFT: Tunneling TCP based protocols through
// Web proxy servers
HttpHost target = route.getTargetHost();
String host = target.getHostName();
int port = target.getPort();
if (port < 0) {
Scheme scheme = connManager.getSchemeRegistry().getScheme(target.getSchemeName());
port = scheme.getDefaultPort();
}
StringBuilder buffer = new StringBuilder(host.length() + 6);
buffer.append(host);
buffer.append(':');
buffer.append(Integer.toString(port));
String authority = buffer.toString();
ProtocolVersion ver = HttpProtocolParams.getVersion(params);
HttpRequest req = new BasicHttpRequest("CONNECT", authority, ver);
return req;
}
use of org.apache.http.message.BasicHttpRequest in project lucene-solr by apache.
the class TestPKIAuthenticationPlugin method test.
public void test() throws Exception {
AtomicReference<Principal> principal = new AtomicReference<>();
String nodeName = "node_x_233";
final MockPKIAuthenticationPlugin mock = new MockPKIAuthenticationPlugin(null, nodeName);
LocalSolrQueryRequest localSolrQueryRequest = new LocalSolrQueryRequest(null, new ModifiableSolrParams()) {
@Override
public Principal getUserPrincipal() {
return principal.get();
}
};
PublicKey correctKey = CryptoKeys.deserializeX509PublicKey(mock.getPublicKey());
mock.remoteKeys.put(nodeName, correctKey);
principal.set(new BasicUserPrincipal("solr"));
mock.solrRequestInfo = new SolrRequestInfo(localSolrQueryRequest, new SolrQueryResponse());
BasicHttpRequest request = new BasicHttpRequest("GET", "http://localhost:56565");
mock.setHeader(request);
final AtomicReference<Header> header = new AtomicReference<>();
header.set(request.getFirstHeader(PKIAuthenticationPlugin.HEADER));
assertNotNull(header.get());
assertTrue(header.get().getValue().startsWith(nodeName));
final AtomicReference<ServletRequest> wrappedRequestByFilter = new AtomicReference<>();
HttpServletRequest mockReq = createMockRequest(header);
FilterChain filterChain = (servletRequest, servletResponse) -> wrappedRequestByFilter.set(servletRequest);
mock.doAuthenticate(mockReq, null, filterChain);
assertNotNull(wrappedRequestByFilter.get());
assertEquals("solr", ((HttpServletRequest) wrappedRequestByFilter.get()).getUserPrincipal().getName());
//test 2
// no user
principal.set(null);
header.set(null);
//
wrappedRequestByFilter.set(null);
request = new BasicHttpRequest("GET", "http://localhost:56565");
mock.setHeader(request);
assertNull(request.getFirstHeader(PKIAuthenticationPlugin.HEADER));
mock.doAuthenticate(mockReq, null, filterChain);
assertNotNull(wrappedRequestByFilter.get());
assertNull(((HttpServletRequest) wrappedRequestByFilter.get()).getUserPrincipal());
//test 3 . No user request . Request originated from Solr
//create pub key in advance because it can take time and it should be
//created before the header is set
PublicKey key = new CryptoKeys.RSAKeyPair().getPublicKey();
mock.solrRequestInfo = null;
header.set(null);
wrappedRequestByFilter.set(null);
request = new BasicHttpRequest("GET", "http://localhost:56565");
mock.setHeader(request);
header.set(request.getFirstHeader(PKIAuthenticationPlugin.HEADER));
assertNotNull(header.get());
assertTrue(header.get().getValue().startsWith(nodeName));
mock.doAuthenticate(mockReq, null, filterChain);
assertNotNull(wrappedRequestByFilter.get());
assertEquals("$", ((HttpServletRequest) wrappedRequestByFilter.get()).getUserPrincipal().getName());
/*test4 mock the restart of a node*/
MockPKIAuthenticationPlugin mock1 = new MockPKIAuthenticationPlugin(null, nodeName) {
int called = 0;
@Override
PublicKey getRemotePublicKey(String nodename) {
try {
return called == 0 ? key : correctKey;
} finally {
called++;
}
}
};
mock1.doAuthenticate(mockReq, null, filterChain);
assertNotNull(wrappedRequestByFilter.get());
assertEquals("$", ((HttpServletRequest) wrappedRequestByFilter.get()).getUserPrincipal().getName());
}
use of org.apache.http.message.BasicHttpRequest in project lucene-solr by apache.
the class ConnectionReuseTest method headerRequest.
public void headerRequest(HttpHost target, HttpRoute route, HttpClientConnection conn, PoolingHttpClientConnectionManager cm) throws IOException, HttpException {
HttpRequest req = new BasicHttpRequest("OPTIONS", "*", HttpVersion.HTTP_1_1);
req.addHeader("Host", target.getHostName());
if (!conn.isOpen()) {
// establish connection based on its route info
cm.connect(conn, route, 1000, context);
// and mark it as route complete
cm.routeComplete(conn, route, context);
}
conn.sendRequestHeader(req);
conn.flush();
conn.receiveResponseHeader();
}
use of org.apache.http.message.BasicHttpRequest in project sling by apache.
the class AbstractSlingClient method doRawRequest.
/**
* <p>Executes a raw HTTP request, WITHOUT consuming the entity in the response. The caller is responsible for consuming the entity or
* closing the response's InputStream in order to release the connection.
* Otherwise, the client might run out of connections and will block</p>
*
* <p><b>Use this with caution and only if necessary for custom methods or for paths that must not be encoded</b>,
* otherwise use the safe method {@link #doRequest(HttpUriRequest, List, int...)}</p>
*
* <p>It behaves as {@link #doStreamRequest(HttpUriRequest, List, int...)}, so the entity is not consumed.</p>
* <p>Adds the headers and checks the response against expected status</p>
*
* @param method the request to be executed
* @param uri the uri to be sent as it is (will not prepend the context path)
* @param headers optional headers to be added to the request
* @param expectedStatus if passed, the response status is checked against it/them, and has to match at least one of them
* @return the response, with the entity not consumed
* @throws ClientException if the request could not be executed
*/
public SlingHttpResponse doRawRequest(String method, String uri, List<Header> headers, int... expectedStatus) throws ClientException {
// create context from config
HttpClientContext context = createHttpClientContextFromConfig();
HttpHost host = new HttpHost(getUrl().getHost(), getUrl().getPort(), getUrl().getScheme());
HttpRequest request = new BasicHttpRequest(method, uri);
// add headers
if (headers != null) {
request.setHeaders(headers.toArray(new Header[headers.size()]));
}
try {
log.debug("request {} {}", method, uri);
SlingHttpResponse response = new SlingHttpResponse(this.execute(host, request, context));
log.debug("response {}", HttpUtils.getHttpStatus(response));
// Check the status and throw a ClientException if it doesn't match expectedStatus, but close the entity before
if (expectedStatus != null && expectedStatus.length > 0) {
try {
HttpUtils.verifyHttpStatus(response, expectedStatus);
} catch (ClientException e) {
// catch the exception to make sure we close the entity before re-throwing it
response.close();
throw e;
}
}
return response;
} catch (IOException e) {
throw new ClientException("Could not execute http request", e);
}
}
Aggregations