-
Notifications
You must be signed in to change notification settings - Fork 1.6k
/
HttpProtocol.java
executable file
·502 lines (416 loc) · 21.5 KB
/
HttpProtocol.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
/*
* Copyright (c) 2014 AsyncHttpClient Project. All rights reserved.
*
* This program is licensed to you under the Apache License Version 2.0,
* and you may not use this file except in compliance with the Apache License Version 2.0.
* You may obtain a copy of the Apache License Version 2.0 at
* http://www.apache.org/licenses/LICENSE-2.0.
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the Apache License Version 2.0 is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the Apache License Version 2.0 for the specific language governing permissions and limitations there under.
*/
package org.asynchttpclient.netty.handler;
import static io.netty.handler.codec.http.HttpResponseStatus.*;
import static org.asynchttpclient.ntlm.NtlmUtils.getNTLM;
import io.netty.buffer.ByteBuf;
import io.netty.channel.Channel;
import io.netty.handler.codec.http.HttpContent;
import io.netty.handler.codec.http.HttpHeaders;
import io.netty.handler.codec.http.HttpMethod;
import io.netty.handler.codec.http.HttpRequest;
import io.netty.handler.codec.http.HttpResponse;
import io.netty.handler.codec.http.LastHttpContent;
import java.io.IOException;
import java.security.GeneralSecurityException;
import java.util.List;
import org.asynchttpclient.AdvancedConfig;
import org.asynchttpclient.AsyncHandler;
import org.asynchttpclient.AsyncHandler.State;
import org.asynchttpclient.AsyncHttpClientConfig;
import org.asynchttpclient.Realm;
import org.asynchttpclient.Request;
import org.asynchttpclient.RequestBuilder;
import org.asynchttpclient.channel.pool.ConnectionStrategy;
import org.asynchttpclient.handler.StreamedAsyncHandler;
import org.asynchttpclient.netty.Callback;
import org.asynchttpclient.netty.NettyResponseBodyPart;
import org.asynchttpclient.netty.NettyResponseFuture;
import org.asynchttpclient.netty.NettyResponseHeaders;
import org.asynchttpclient.netty.NettyResponseStatus;
import org.asynchttpclient.netty.channel.ChannelManager;
import org.asynchttpclient.netty.channel.Channels;
import org.asynchttpclient.netty.request.NettyRequestSender;
import org.asynchttpclient.ntlm.NtlmEngine;
import org.asynchttpclient.proxy.ProxyServer;
import org.asynchttpclient.spnego.SpnegoEngine;
import org.asynchttpclient.spnego.SpnegoEngineException;
import org.asynchttpclient.uri.Uri;
public final class HttpProtocol extends Protocol {
private final ConnectionStrategy connectionStrategy;
public HttpProtocol(ChannelManager channelManager, AsyncHttpClientConfig config, AdvancedConfig advancedConfig, NettyRequestSender requestSender) {
super(channelManager, config, advancedConfig, requestSender);
connectionStrategy = advancedConfig.getConnectionStrategy();
}
private Realm kerberosChallenge(Channel channel,//
List<String> authHeaders,//
Request request,//
HttpHeaders headers,//
Realm realm,//
NettyResponseFuture<?> future) {
Uri uri = request.getUri();
String host = request.getVirtualHost() == null ? uri.getHost() : request.getVirtualHost();
try {
String challengeHeader = SpnegoEngine.instance().generateToken(host);
headers.remove(HttpHeaders.Names.AUTHORIZATION);
headers.add(HttpHeaders.Names.AUTHORIZATION, "Negotiate " + challengeHeader);
return new Realm.RealmBuilder().clone(realm)//
.setUri(uri)//
.setMethodName(request.getMethod())//
.setScheme(Realm.AuthScheme.KERBEROS)//
.build();
} catch (SpnegoEngineException throwable) {
String ntlmAuthenticate = getNTLM(authHeaders);
if (ntlmAuthenticate != null) {
return ntlmChallenge(ntlmAuthenticate, request, headers, realm, future);
}
requestSender.abort(channel, future, throwable);
return null;
}
}
private Realm kerberosProxyChallenge(Channel channel,//
List<String> proxyAuth,//
Request request,//
ProxyServer proxyServer,//
HttpHeaders headers,//
NettyResponseFuture<?> future) {
try {
String challengeHeader = SpnegoEngine.instance().generateToken(proxyServer.getHost());
headers.set(HttpHeaders.Names.PROXY_AUTHORIZATION, "Negotiate " + challengeHeader);
return proxyServer.getRealm();
} catch (SpnegoEngineException throwable) {
String ntlmAuthenticate = getNTLM(proxyAuth);
if (ntlmAuthenticate != null) {
return ntlmProxyChallenge(ntlmAuthenticate, request, proxyServer, headers, future);
}
requestSender.abort(channel, future, throwable);
return null;
}
}
private String authorizationHeaderName(boolean proxyInd) {
return proxyInd ? HttpHeaders.Names.PROXY_AUTHORIZATION : HttpHeaders.Names.AUTHORIZATION;
}
private void addNTLMAuthorizationHeader(HttpHeaders headers, String challengeHeader, boolean proxyInd) {
headers.add(authorizationHeaderName(proxyInd), "NTLM " + challengeHeader);
}
private Realm ntlmChallenge(String authenticateHeader,//
Request request,//
HttpHeaders headers,//
Realm realm,//
NettyResponseFuture<?> future) {
if (authenticateHeader.equals("NTLM")) {
// server replied bare NTLM => we didn't preemptively sent Type1Msg
String challengeHeader = NtlmEngine.INSTANCE.generateType1Msg();
addNTLMAuthorizationHeader(headers, challengeHeader, false);
future.getAndSetAuth(false);
} else {
addType3NTLMAuthorizationHeader(authenticateHeader, headers, realm, false);
}
return new Realm.RealmBuilder().clone(realm)//
.setUri(request.getUri())//
.setMethodName(request.getMethod())//
.build();
}
private Realm ntlmProxyChallenge(String authenticateHeader,//
Request request,//
ProxyServer proxyServer,//
HttpHeaders headers,//
NettyResponseFuture<?> future) {
future.getAndSetAuth(false);
headers.remove(HttpHeaders.Names.PROXY_AUTHORIZATION);
// FIXME we should probably check that the scheme is NTLM
Realm realm = proxyServer.getRealm();
addType3NTLMAuthorizationHeader(authenticateHeader, headers, realm, true);
return realm;
}
private void addType3NTLMAuthorizationHeader(String authenticateHeader, HttpHeaders headers, Realm realm, boolean proxyInd) {
headers.remove(authorizationHeaderName(proxyInd));
if (authenticateHeader.startsWith("NTLM ")) {
String serverChallenge = authenticateHeader.substring("NTLM ".length()).trim();
String challengeHeader = NtlmEngine.INSTANCE.generateType3Msg(realm.getPrincipal(), realm.getPassword(), realm.getNtlmDomain(), realm.getNtlmHost(), serverChallenge);
addNTLMAuthorizationHeader(headers, challengeHeader, proxyInd);
}
}
private void finishUpdate(final NettyResponseFuture<?> future, Channel channel, boolean expectOtherChunks) throws IOException {
future.cancelTimeouts();
boolean keepAlive = future.isKeepAlive();
if (expectOtherChunks && keepAlive)
channelManager.drainChannelAndOffer(channel, future);
else
channelManager.tryToOfferChannelToPool(channel, future.getAsyncHandler(), keepAlive, future.getPartitionKey());
try {
future.done();
} catch (Exception t) {
// Never propagate exception once we know we are done.
logger.debug(t.getMessage(), t);
}
}
private boolean updateBodyAndInterrupt(NettyResponseFuture<?> future, AsyncHandler<?> handler, NettyResponseBodyPart bodyPart) throws Exception {
boolean interrupt = handler.onBodyPartReceived(bodyPart) != State.CONTINUE;
if (bodyPart.isUnderlyingConnectionToBeClosed())
future.setKeepAlive(false);
return interrupt;
}
private boolean exitAfterHandling401(//
final Channel channel,//
final NettyResponseFuture<?> future,//
HttpResponse response,//
final Request request,//
int statusCode,//
Realm realm,//
ProxyServer proxyServer) throws Exception {
if (statusCode == UNAUTHORIZED.code() && realm != null && !future.getAndSetAuth(true)) {
List<String> wwwAuthHeaders = response.headers().getAll(HttpHeaders.Names.WWW_AUTHENTICATE);
if (!wwwAuthHeaders.isEmpty()) {
future.setState(NettyResponseFuture.STATE.NEW);
Realm newRealm = null;
boolean negociate = wwwAuthHeaders.contains("Negotiate");
String ntlmAuthenticate = getNTLM(wwwAuthHeaders);
if (!wwwAuthHeaders.contains("Kerberos") && ntlmAuthenticate != null) {
// NTLM
newRealm = ntlmChallenge(ntlmAuthenticate, request, request.getHeaders(), realm, future);
} else if (negociate) {
newRealm = kerberosChallenge(channel, wwwAuthHeaders, request, request.getHeaders(), realm, future);
// SPNEGO KERBEROS
if (newRealm == null)
return true;
} else {
// BASIC or DIGEST
newRealm = new Realm.RealmBuilder()//
.clone(realm)//
.setUri(request.getUri())//
.setMethodName(request.getMethod())//
.setUsePreemptiveAuth(true)//
.parseWWWAuthenticateHeader(wwwAuthHeaders.get(0))//
.build();
}
final Request nextRequest = new RequestBuilder(future.getRequest()).setHeaders(request.getHeaders()).setRealm(newRealm).build();
logger.debug("Sending authentication to {}", request.getUri());
if (future.isKeepAlive() && !HttpHeaders.isTransferEncodingChunked(response)) {
future.setReuseChannel(true);
requestSender.drainChannelAndExecuteNextRequest(channel, future, nextRequest);
} else {
channelManager.closeChannel(channel);
requestSender.sendNextRequest(nextRequest, future);
}
return true;
}
}
return false;
}
private boolean exitAfterHandling100(final Channel channel, final NettyResponseFuture<?> future, int statusCode) {
if (statusCode == CONTINUE.code()) {
future.setHeadersAlreadyWrittenOnContinue(true);
future.setDontWriteBodyBecauseExpectContinue(false);
// directly send the body
Channels.setAttribute(channel, new Callback(future) {
@Override
public void call() throws IOException {
Channels.setAttribute(channel, future);
requestSender.writeRequest(future, channel);
}
});
return true;
}
return false;
}
private boolean exitAfterHandling407(//
Channel channel,//
NettyResponseFuture<?> future,//
HttpResponse response,//
Request request,//
int statusCode,//
ProxyServer proxyServer) throws Exception {
if (statusCode == PROXY_AUTHENTICATION_REQUIRED.code() && proxyServer != null && !future.getAndSetAuth(true)) {
List<String> proxyAuthHeaders = response.headers().getAll(HttpHeaders.Names.PROXY_AUTHENTICATE);
if (!proxyAuthHeaders.isEmpty()) {
logger.debug("Sending proxy authentication to {}", request.getUri());
future.setState(NettyResponseFuture.STATE.NEW);
Realm newRealm = null;
HttpHeaders requestHeaders = request.getHeaders();
boolean negociate = proxyAuthHeaders.contains("Negotiate");
String ntlmAuthenticate = getNTLM(proxyAuthHeaders);
if (!proxyAuthHeaders.contains("Kerberos") && ntlmAuthenticate != null) {
// NTLM
newRealm = ntlmProxyChallenge(ntlmAuthenticate, request, proxyServer, requestHeaders, future);
} else if (negociate) {
// SPNEGO KERBEROS
newRealm = kerberosProxyChallenge(channel, proxyAuthHeaders, request, proxyServer, requestHeaders, future);
if (newRealm == null)
return true;
} else {
// BASIC or DIGEST
newRealm = new Realm.RealmBuilder().clone(proxyServer.getRealm())
.setUri(request.getUri())//
.setOmitQuery(true)//
.setMethodName(request.getMethod())//
.setUsePreemptiveAuth(true)//
.parseProxyAuthenticateHeader(proxyAuthHeaders.get(0))//
.build();
}
final Request nextRequest = new RequestBuilder(future.getRequest()).setHeaders(request.getHeaders()).setRealm(newRealm).build();
logger.debug("Sending proxy authentication to {}", request.getUri());
if (future.isKeepAlive() && !HttpHeaders.isTransferEncodingChunked(response)) {
future.setConnectAllowed(true);
future.setReuseChannel(true);
requestSender.drainChannelAndExecuteNextRequest(channel, future, nextRequest);
} else {
channelManager.closeChannel(channel);
requestSender.sendNextRequest(nextRequest, future);
}
return true;
}
}
return false;
}
private boolean exitAfterHandlingConnect(//
final Channel channel,//
final NettyResponseFuture<?> future,//
final Request request,//
ProxyServer proxyServer,//
int statusCode,//
HttpRequest httpRequest) throws IOException {
if (statusCode == OK.code() && httpRequest.getMethod() == HttpMethod.CONNECT) {
if (future.isKeepAlive())
future.attachChannel(channel, true);
Uri requestUri = request.getUri();
logger.debug("Connecting to proxy {} for scheme {}", proxyServer, requestUri.getScheme());
try {
channelManager.upgradeProtocol(channel.pipeline(), requestUri);
future.setReuseChannel(true);
future.setConnectAllowed(false);
requestSender.drainChannelAndExecuteNextRequest(channel, future, new RequestBuilder(future.getRequest()).build());
} catch (GeneralSecurityException ex) {
requestSender.abort(channel, future, ex);
}
return true;
}
return false;
}
private boolean exitAfterHandlingStatus(Channel channel, NettyResponseFuture<?> future, HttpResponse response, AsyncHandler<?> handler, NettyResponseStatus status)
throws IOException, Exception {
if (!future.getAndSetStatusReceived(true) && handler.onStatusReceived(status) != State.CONTINUE) {
finishUpdate(future, channel, HttpHeaders.isTransferEncodingChunked(response));
return true;
}
return false;
}
private boolean exitAfterHandlingHeaders(Channel channel, NettyResponseFuture<?> future, HttpResponse response, AsyncHandler<?> handler, NettyResponseHeaders responseHeaders)
throws IOException, Exception {
if (!response.headers().isEmpty() && handler.onHeadersReceived(responseHeaders) != State.CONTINUE) {
finishUpdate(future, channel, HttpHeaders.isTransferEncodingChunked(response));
return true;
}
return false;
}
private boolean exitAfterHandlingReactiveStreams(Channel channel, NettyResponseFuture<?> future, HttpResponse response, AsyncHandler<?> handler) throws IOException {
if (handler instanceof StreamedAsyncHandler) {
StreamedAsyncHandler<?> streamedAsyncHandler = (StreamedAsyncHandler<?>) handler;
StreamedResponsePublisher publisher = new StreamedResponsePublisher(channel.eventLoop(), channelManager, future, channel);
channel.pipeline().addLast(channel.eventLoop(), "streamedAsyncHandler", publisher);
Channels.setAttribute(channel, publisher);
if (streamedAsyncHandler.onStream(publisher) != State.CONTINUE) {
finishUpdate(future, channel, HttpHeaders.isTransferEncodingChunked(response));
return true;
}
}
return false;
}
private boolean handleHttpResponse(final HttpResponse response, final Channel channel, final NettyResponseFuture<?> future, AsyncHandler<?> handler) throws Exception {
HttpRequest httpRequest = future.getNettyRequest().getHttpRequest();
ProxyServer proxyServer = future.getProxyServer();
logger.debug("\n\nRequest {}\n\nResponse {}\n", httpRequest, response);
// store the original headers so we can re-send all them to
// the handler in case of trailing headers
future.setHttpHeaders(response.headers());
future.setKeepAlive(connectionStrategy.keepAlive(httpRequest, response));
NettyResponseStatus status = new NettyResponseStatus(future.getUri(), config, response, channel);
int statusCode = response.getStatus().code();
Request request = future.getRequest();
Realm realm = request.getRealm() != null ? request.getRealm() : config.getRealm();
NettyResponseHeaders responseHeaders = new NettyResponseHeaders(response.headers());
return exitAfterProcessingFilters(channel, future, handler, status, responseHeaders)
|| exitAfterHandling401(channel, future, response, request, statusCode, realm, proxyServer) || //
exitAfterHandling407(channel, future, response, request, statusCode, proxyServer) || //
exitAfterHandling100(channel, future, statusCode) || //
exitAfterHandlingRedirect(channel, future, response, request, statusCode, realm) || //
exitAfterHandlingConnect(channel, future, request, proxyServer, statusCode, httpRequest) || //
exitAfterHandlingStatus(channel, future, response, handler, status) || //
exitAfterHandlingHeaders(channel, future, response, handler, responseHeaders) || exitAfterHandlingReactiveStreams(channel, future, response, handler);
}
private void handleChunk(HttpContent chunk,//
final Channel channel,//
final NettyResponseFuture<?> future,//
AsyncHandler<?> handler) throws IOException, Exception {
boolean interrupt = false;
boolean last = chunk instanceof LastHttpContent;
// Netty 4: the last chunk is not empty
if (last) {
LastHttpContent lastChunk = (LastHttpContent) chunk;
HttpHeaders trailingHeaders = lastChunk.trailingHeaders();
if (!trailingHeaders.isEmpty()) {
NettyResponseHeaders responseHeaders = new NettyResponseHeaders(future.getHttpHeaders(), trailingHeaders);
interrupt = handler.onHeadersReceived(responseHeaders) != State.CONTINUE;
}
}
ByteBuf buf = chunk.content();
if (!interrupt && !(handler instanceof StreamedAsyncHandler) && (buf.readableBytes() > 0 || last)) {
NettyResponseBodyPart part = advancedConfig.getBodyPartFactory().newResponseBodyPart(buf, last);
interrupt = updateBodyAndInterrupt(future, handler, part);
}
if (interrupt || last)
finishUpdate(future, channel, !last);
}
@Override
public void handle(final Channel channel, final NettyResponseFuture<?> future, final Object e) throws Exception {
future.touch();
// future is already done because of an exception or a timeout
if (future.isDone()) {
// FIXME isn't the channel already properly closed?
channelManager.closeChannel(channel);
return;
}
AsyncHandler<?> handler = future.getAsyncHandler();
try {
if (e instanceof HttpResponse) {
if (handleHttpResponse((HttpResponse) e, channel, future, handler))
return;
} else if (e instanceof HttpContent) {
handleChunk((HttpContent) e, channel, future, handler);
}
} catch (Exception t) {
// e.g. an IOException when trying to open a connection and send the
// next request
if (hasIOExceptionFilters//
&& t instanceof IOException//
&& requestSender.applyIoExceptionFiltersAndReplayRequest(future, IOException.class.cast(t), channel)) {
return;
}
try {
requestSender.abort(channel, future, t);
} catch (Exception abortException) {
logger.debug("Abort failed", abortException);
} finally {
finishUpdate(future, channel, false);
}
throw t;
}
}
@Override
public void onError(NettyResponseFuture<?> future, Throwable error) {
}
@Override
public void onClose(NettyResponseFuture<?> future) {
}
}