forked from ning/async-http-client
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathNettyAsyncHttpProvider.java
1905 lines (1614 loc) · 79.7 KB
/
NettyAsyncHttpProvider.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
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright 2010 Ning, Inc.
*
* Ning licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package com.ning.http.client.providers.netty;
import com.ning.http.client.AsyncHandler;
import com.ning.http.client.AsyncHandler.STATE;
import com.ning.http.client.AsyncHttpClientConfig;
import com.ning.http.client.AsyncHttpProvider;
import com.ning.http.client.Body;
import com.ning.http.client.ConnectionsPool;
import com.ning.http.client.Cookie;
import com.ning.http.client.FluentCaseInsensitiveStringsMap;
import com.ning.http.client.HttpResponseBodyPart;
import com.ning.http.client.HttpResponseHeaders;
import com.ning.http.client.HttpResponseStatus;
import com.ning.http.client.ListenableFuture;
import com.ning.http.client.MaxRedirectException;
import com.ning.http.client.PerRequestConfig;
import com.ning.http.client.ProgressAsyncHandler;
import com.ning.http.client.ProxyServer;
import com.ning.http.client.RandomAccessBody;
import com.ning.http.client.Realm;
import com.ning.http.client.Request;
import com.ning.http.client.RequestBuilder;
import com.ning.http.client.Response;
import com.ning.http.client.filter.FilterContext;
import com.ning.http.client.filter.FilterException;
import com.ning.http.client.filter.IOExceptionFilter;
import com.ning.http.client.filter.ResponseFilter;
import com.ning.http.client.listener.TransferCompletionHandler;
import com.ning.http.client.ntlm.NTLMEngine;
import com.ning.http.client.ntlm.NTLMEngineException;
import com.ning.http.client.providers.netty.spnego.SpnegoEngine;
import com.ning.http.multipart.MultipartRequestEntity;
import com.ning.http.util.AsyncHttpProviderUtils;
import com.ning.http.util.AuthenticatorUtils;
import com.ning.http.util.CleanupChannelGroup;
import com.ning.http.util.ProxyUtils;
import com.ning.http.util.SslUtils;
import com.ning.http.util.UTF8UrlEncoder;
import org.jboss.netty.bootstrap.ClientBootstrap;
import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.buffer.ChannelBufferOutputStream;
import org.jboss.netty.buffer.ChannelBuffers;
import org.jboss.netty.channel.Channel;
import org.jboss.netty.channel.ChannelFuture;
import org.jboss.netty.channel.ChannelFutureProgressListener;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.channel.ChannelPipeline;
import org.jboss.netty.channel.ChannelPipelineFactory;
import org.jboss.netty.channel.ChannelStateEvent;
import org.jboss.netty.channel.DefaultChannelFuture;
import org.jboss.netty.channel.ExceptionEvent;
import org.jboss.netty.channel.FileRegion;
import org.jboss.netty.channel.MessageEvent;
import org.jboss.netty.channel.SimpleChannelUpstreamHandler;
import org.jboss.netty.channel.group.ChannelGroup;
import org.jboss.netty.channel.socket.ClientSocketChannelFactory;
import org.jboss.netty.channel.socket.nio.NioClientSocketChannelFactory;
import org.jboss.netty.channel.socket.oio.OioClientSocketChannelFactory;
import org.jboss.netty.handler.codec.http.CookieEncoder;
import org.jboss.netty.handler.codec.http.DefaultCookie;
import org.jboss.netty.handler.codec.http.DefaultHttpChunkTrailer;
import org.jboss.netty.handler.codec.http.DefaultHttpRequest;
import org.jboss.netty.handler.codec.http.HttpChunk;
import org.jboss.netty.handler.codec.http.HttpChunkTrailer;
import org.jboss.netty.handler.codec.http.HttpClientCodec;
import org.jboss.netty.handler.codec.http.HttpContentCompressor;
import org.jboss.netty.handler.codec.http.HttpContentDecompressor;
import org.jboss.netty.handler.codec.http.HttpHeaders;
import org.jboss.netty.handler.codec.http.HttpMethod;
import org.jboss.netty.handler.codec.http.HttpRequest;
import org.jboss.netty.handler.codec.http.HttpResponse;
import org.jboss.netty.handler.codec.http.HttpVersion;
import org.jboss.netty.handler.ssl.SslHandler;
import org.jboss.netty.handler.stream.ChunkedFile;
import org.jboss.netty.handler.stream.ChunkedWriteHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.net.ssl.SSLEngine;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.net.ConnectException;
import java.net.InetSocketAddress;
import java.net.MalformedURLException;
import java.net.URI;
import java.nio.channels.ClosedChannelException;
import java.nio.channels.FileChannel;
import java.nio.channels.WritableByteChannel;
import java.security.GeneralSecurityException;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.Map.Entry;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import static com.ning.http.util.AsyncHttpProviderUtils.DEFAULT_CHARSET;
import static org.jboss.netty.channel.Channels.pipeline;
public class NettyAsyncHttpProvider extends SimpleChannelUpstreamHandler implements AsyncHttpProvider<HttpResponse> {
private final static String HTTP_HANDLER = "httpHandler";
final static String SSL_HANDLER = "sslHandler";
private final static String HTTPS = "https";
private final static String HTTP = "http";
private final static Logger log = LoggerFactory.getLogger(NettyAsyncHttpProvider.class);
private final ClientBootstrap plainBootstrap;
private final ClientBootstrap secureBootstrap;
private final static int MAX_BUFFERED_BYTES = 8192;
private final AsyncHttpClientConfig config;
private final AtomicBoolean isClose = new AtomicBoolean(false);
private final ClientSocketChannelFactory socketChannelFactory;
private final ChannelGroup openChannels = new
CleanupChannelGroup("asyncHttpClient") {
@Override
public boolean remove(Object o) {
boolean removed = super.remove(o);
if( removed ) {
maxConnections.decrementAndGet();
}
return removed;
}
};
private final ConnectionsPool<String, Channel> connectionsPool;
private final AtomicInteger maxConnections = new AtomicInteger();
private final NettyAsyncHttpProviderConfig asyncHttpProviderConfig;
private boolean executeConnectAsync = false;
public static final ThreadLocal<Boolean> IN_IO_THREAD = new ThreadLocalBoolean();
private final boolean trackConnections;
private final static NTLMEngine ntlmEngine = new NTLMEngine();
private final static SpnegoEngine spnegoEngine = new SpnegoEngine();
public NettyAsyncHttpProvider(AsyncHttpClientConfig config) {
if (config.getAsyncHttpProviderConfig() != null
&& NettyAsyncHttpProviderConfig.class.isAssignableFrom(config.getAsyncHttpProviderConfig().getClass())) {
asyncHttpProviderConfig = NettyAsyncHttpProviderConfig.class.cast(config.getAsyncHttpProviderConfig());
} else {
asyncHttpProviderConfig = new NettyAsyncHttpProviderConfig();
}
if (asyncHttpProviderConfig != null && asyncHttpProviderConfig.getProperty(NettyAsyncHttpProviderConfig.USE_BLOCKING_IO) != null) {
socketChannelFactory = new OioClientSocketChannelFactory(config.executorService());
} else {
socketChannelFactory = new NioClientSocketChannelFactory(
Executors.newCachedThreadPool(),
config.executorService());
}
plainBootstrap = new ClientBootstrap(socketChannelFactory);
secureBootstrap = new ClientBootstrap(socketChannelFactory);
this.config = config;
// This is dangerous as we can't catch a wrong typed ConnectionsPool
ConnectionsPool<String, Channel> cp = (ConnectionsPool<String, Channel>) config.getConnectionsPool();
if (cp == null && config.getAllowPoolingConnection()) {
cp = new NettyConnectionsPool(this);
} else if (cp == null) {
cp = new NonConnectionsPool();
}
this.connectionsPool = cp;
configureNetty();
trackConnections = (config.getMaxTotalConnections() != -1);
}
@Override
public String toString() {
return String.format("NettyAsyncHttpProvider:\n\t- maxConnections: %d\n\t- openChannels: %s\n\t- connectionPools: %s",
maxConnections.get(),
openChannels.toString(),
connectionsPool.toString());
}
void configureNetty() {
if (asyncHttpProviderConfig != null) {
for (Entry<String, Object> entry : asyncHttpProviderConfig.propertiesSet()) {
plainBootstrap.setOption(entry.getKey(), entry.getValue());
}
}
plainBootstrap.setPipelineFactory(new ChannelPipelineFactory() {
/* @Override */
public ChannelPipeline getPipeline() throws Exception {
ChannelPipeline pipeline = pipeline();
pipeline.addLast(HTTP_HANDLER, new HttpClientCodec());
if (config.getRequestCompressionLevel() > 0) {
pipeline.addLast("deflater", new HttpContentCompressor(config.getRequestCompressionLevel()));
}
if (config.isCompressionEnabled()) {
pipeline.addLast("inflater", new HttpContentDecompressor());
}
pipeline.addLast("chunkedWriter", new ChunkedWriteHandler());
pipeline.addLast("httpProcessor", NettyAsyncHttpProvider.this);
return pipeline;
}
});
DefaultChannelFuture.setUseDeadLockChecker(false);
if (asyncHttpProviderConfig != null) {
if (asyncHttpProviderConfig.getProperty(NettyAsyncHttpProviderConfig.EXECUTE_ASYNC_CONNECT) != null) {
executeConnectAsync = true;
} else if (asyncHttpProviderConfig.getProperty(NettyAsyncHttpProviderConfig.DISABLE_NESTED_REQUEST) != null) {
DefaultChannelFuture.setUseDeadLockChecker(true);
}
}
}
void constructSSLPipeline(final NettyConnectListener<?> cl) {
secureBootstrap.setPipelineFactory(new ChannelPipelineFactory() {
/* @Override */
public ChannelPipeline getPipeline() throws Exception {
ChannelPipeline pipeline = pipeline();
try {
pipeline.addLast(SSL_HANDLER, new SslHandler(createSSLEngine()));
} catch (Throwable ex) {
abort(cl.future(), ex);
}
pipeline.addLast(HTTP_HANDLER, new HttpClientCodec());
if (config.isCompressionEnabled()) {
pipeline.addLast("inflater", new HttpContentDecompressor());
}
pipeline.addLast("chunkedWriter", new ChunkedWriteHandler());
pipeline.addLast("httpProcessor", NettyAsyncHttpProvider.this);
return pipeline;
}
});
if (asyncHttpProviderConfig != null) {
for (Entry<String, Object> entry : asyncHttpProviderConfig.propertiesSet()) {
secureBootstrap.setOption(entry.getKey(), entry.getValue());
}
}
}
private Channel lookupInCache(URI uri) {
final Channel channel = connectionsPool.poll(AsyncHttpProviderUtils.getBaseUrl(uri));
if (channel != null) {
log.debug("Using cached Channel {}\n for uri {}\n", channel, uri);
try {
// Always make sure the channel who got cached support the proper protocol. It could
// only occurs when a HttpMethod.CONNECT is used agains a proxy that require upgrading from http to
// https.
return verifyChannelPipeline(channel, uri.getScheme());
} catch (Exception ex) {
log.debug(ex.getMessage(), ex);
}
}
return null;
}
private SSLEngine createSSLEngine() throws IOException, GeneralSecurityException {
SSLEngine sslEngine = config.getSSLEngineFactory().newSSLEngine();
if (sslEngine == null) {
sslEngine = SslUtils.getSSLEngine();
}
return sslEngine;
}
private Channel verifyChannelPipeline(Channel channel, String scheme) throws IOException, GeneralSecurityException {
if (channel.getPipeline().get(SSL_HANDLER) != null && HTTP.equalsIgnoreCase(scheme)) {
channel.getPipeline().remove(SSL_HANDLER);
} else if (channel.getPipeline().get(HTTP_HANDLER) != null && HTTP.equalsIgnoreCase(scheme)) {
return channel;
} else if (channel.getPipeline().get(SSL_HANDLER) == null && HTTPS.equalsIgnoreCase(scheme)) {
channel.getPipeline().addFirst(SSL_HANDLER, new SslHandler(createSSLEngine()));
}
return channel;
}
protected final <T> void writeRequest(final Channel channel,
final AsyncHttpClientConfig config,
final NettyResponseFuture<T> future,
final HttpRequest nettyRequest) {
try {
/**
* If the channel is dead because it was pooled and the remote server decided to close it,
* we just let it go and the closeChannel do it's work.
*/
if (!channel.isOpen() || !channel.isConnected()) {
return;
}
Body body = null;
if (!future.getNettyRequest().getMethod().equals(HttpMethod.CONNECT)) {
if (future.getRequest().getBodyGenerator() != null) {
try {
body = future.getRequest().getBodyGenerator().createBody();
} catch (IOException ex) {
throw new IllegalStateException(ex);
}
long length = body.getContentLength();
if (length >= 0) {
nettyRequest.setHeader(HttpHeaders.Names.CONTENT_LENGTH, length);
} else {
nettyRequest.setHeader(HttpHeaders.Names.TRANSFER_ENCODING, HttpHeaders.Values.CHUNKED);
}
} else {
body = null;
}
}
if (TransferCompletionHandler.class.isAssignableFrom(future.getAsyncHandler().getClass())) {
FluentCaseInsensitiveStringsMap h = new FluentCaseInsensitiveStringsMap();
for (String s : future.getNettyRequest().getHeaderNames()) {
for (String header : future.getNettyRequest().getHeaders(s)) {
h.add(s, header);
}
}
TransferCompletionHandler.class.cast(future.getAsyncHandler()).transferAdapter(
new NettyTransferAdapter(h, nettyRequest.getContent(), future.getRequest().getFile()));
}
// Leave it to true.
if (future.getAndSetWriteHeaders(true)) {
try {
channel.write(nettyRequest).addListener(new ProgressListener(true, future.getAsyncHandler(), future));
} catch (Throwable cause) {
log.debug(cause.getMessage(), cause);
try {
channel.close();
} catch (RuntimeException ex) {
log.debug(ex.getMessage(), ex);
}
return;
}
}
if (future.getAndSetWriteBody(true)) {
if (!future.getNettyRequest().getMethod().equals(HttpMethod.CONNECT)) {
if (future.getRequest().getFile() != null) {
final File file = future.getRequest().getFile();
long fileLength = 0;
final RandomAccessFile raf = new RandomAccessFile(file, "r");
try {
fileLength = raf.length();
ChannelFuture writeFuture;
if (channel.getPipeline().get(SslHandler.class) != null) {
writeFuture = channel.write(new ChunkedFile(raf, 0, fileLength, 8192));
writeFuture.addListener(new ProgressListener(false, future.getAsyncHandler(), future));
} else {
final FileRegion region = new OptimizedFileRegion(raf, 0, fileLength);
writeFuture = channel.write(region);
writeFuture.addListener(new ProgressListener(false, future.getAsyncHandler(), future));
}
} catch (IOException ex) {
if (raf != null) {
try {
raf.close();
} catch (IOException e) {
}
}
throw ex;
}
} else if (body != null) {
ChannelFuture writeFuture;
if (channel.getPipeline().get(SslHandler.class) == null && (body instanceof RandomAccessBody)) {
writeFuture = channel.write(new BodyFileRegion((RandomAccessBody) body));
} else {
writeFuture = channel.write(new BodyChunkedInput(body));
}
final Body b = body;
writeFuture.addListener(new ProgressListener(false, future.getAsyncHandler(), future) {
public void operationComplete(ChannelFuture cf) {
try {
b.close();
} catch (IOException e) {
log.warn("Failed to close request body: {}", e.getMessage(), e);
}
super.operationComplete(cf);
}
});
}
}
}
} catch (Throwable ioe) {
try {
channel.close();
} catch (RuntimeException ex) {
log.debug(ex.getMessage(), ex);
}
}
try {
future.touch();
int delay = requestTimeout(config, future.getRequest().getPerRequestConfig());
if (delay != -1) {
ReaperFuture reaperFuture = new ReaperFuture(channel, future);
Future scheduledFuture = config.reaper().scheduleAtFixedRate(reaperFuture, delay, 500, TimeUnit.MILLISECONDS);
reaperFuture.setScheduledFuture(scheduledFuture);
future.setReaperFuture(reaperFuture);
}
} catch (RejectedExecutionException ex) {
abort(future, ex);
}
}
protected final static HttpRequest buildRequest(AsyncHttpClientConfig config, Request request, URI uri,
boolean allowConnect, ChannelBuffer buffer) throws IOException {
String method = request.getMethod();
if (allowConnect && ((request.getProxyServer() != null || config.getProxyServer() != null) && HTTPS.equalsIgnoreCase(uri.getScheme()))) {
method = HttpMethod.CONNECT.toString();
}
return construct(config, request, new HttpMethod(method), uri, buffer);
}
@SuppressWarnings("deprecation")
private static HttpRequest construct(AsyncHttpClientConfig config,
Request request,
HttpMethod m,
URI uri,
ChannelBuffer buffer) throws IOException {
String host = uri.getHost();
if (request.getVirtualHost() != null) {
host = request.getVirtualHost();
}
HttpRequest nettyRequest;
if (m.equals(HttpMethod.CONNECT)) {
nettyRequest = new DefaultHttpRequest(HttpVersion.HTTP_1_0, m, AsyncHttpProviderUtils.getAuthority(uri));
} else if (config.getProxyServer() != null || request.getProxyServer() != null) {
nettyRequest = new DefaultHttpRequest(HttpVersion.HTTP_1_1, m, uri.toString());
} else {
StringBuilder path = new StringBuilder(uri.getRawPath());
if (uri.getQuery() != null) {
path.append("?").append(uri.getRawQuery());
}
nettyRequest = new DefaultHttpRequest(HttpVersion.HTTP_1_1, m, path.toString());
}
if (host != null) {
if (uri.getPort() == -1) {
nettyRequest.setHeader(HttpHeaders.Names.HOST, host);
} else {
nettyRequest.setHeader(HttpHeaders.Names.HOST, host + ":" + uri.getPort());
}
} else {
host = "127.0.0.1";
}
if (!m.equals(HttpMethod.CONNECT)) {
FluentCaseInsensitiveStringsMap h = request.getHeaders();
if (h != null) {
for (String name : h.keySet()) {
if (!"host".equalsIgnoreCase(name)) {
for (String value : h.get(name)) {
nettyRequest.addHeader(name, value);
}
}
}
}
if (config.isCompressionEnabled()) {
nettyRequest.setHeader(HttpHeaders.Names.ACCEPT_ENCODING, HttpHeaders.Values.GZIP);
}
}
ProxyServer proxyServer = request.getProxyServer() != null ? request.getProxyServer() : config.getProxyServer();
Realm realm = request.getRealm() != null ? request.getRealm() : config.getRealm();
if (realm != null && realm.getUsePreemptiveAuth()) {
switch (realm.getAuthScheme()) {
case BASIC:
nettyRequest.setHeader(HttpHeaders.Names.AUTHORIZATION,
AuthenticatorUtils.computeBasicAuthentication(realm));
break;
case DIGEST:
if (realm.getNonce() != null && !realm.getNonce().equals("")) {
try {
nettyRequest.setHeader(HttpHeaders.Names.AUTHORIZATION,
AuthenticatorUtils.computeDigestAuthentication(realm));
} catch (NoSuchAlgorithmException e) {
throw new SecurityException(e);
}
}
break;
case NTLM:
try {
nettyRequest.setHeader(HttpHeaders.Names.AUTHORIZATION,
ntlmEngine.generateType1Msg("NTLM " + realm.getNtlmDomain(), realm.getNtlmHost()));
} catch (NTLMEngineException e) {
IOException ie = new IOException();
ie.initCause(e);
throw ie;
}
break;
case KERBEROS:
case SPNEGO:
String challengeHeader = null;
String authServer = proxyServer == null ? AsyncHttpProviderUtils.getBaseUrl(uri) : proxyServer.getHost();
try {
challengeHeader = spnegoEngine.generateToken(authServer);
} catch (Throwable e) {
IOException ie = new IOException();
ie.initCause(e);
throw ie;
}
nettyRequest.setHeader(HttpHeaders.Names.AUTHORIZATION, "Negotiate " + challengeHeader);
break;
default:
throw new IllegalStateException(String.format("Invalid Authentication %s", realm.toString()));
}
}
if (!request.getHeaders().containsKey(HttpHeaders.Names.CONNECTION)) {
nettyRequest.setHeader(HttpHeaders.Names.CONNECTION, "keep-alive");
}
boolean avoidProxy = ProxyUtils.avoidProxy(proxyServer, request);
if (!avoidProxy) {
if (!request.getHeaders().containsKey("Proxy-Connection")) {
nettyRequest.setHeader("Proxy-Connection", "keep-alive");
}
if (proxyServer.getPrincipal() != null) {
nettyRequest.setHeader(HttpHeaders.Names.PROXY_AUTHORIZATION,
AuthenticatorUtils.computeBasicAuthentication(proxyServer));
}
}
// Add default accept headers.
if (request.getHeaders().getFirstValue("Accept") == null) {
nettyRequest.setHeader(HttpHeaders.Names.ACCEPT, "*/*");
}
if (request.getHeaders().getFirstValue("User-Agent") == null && config.getUserAgent() != null) {
nettyRequest.setHeader("User-Agent", config.getUserAgent());
} else if (config.getUserAgent() != null) {
nettyRequest.setHeader("User-Agent", config.getUserAgent());
} else if (request.getHeaders().getFirstValue("User-Agent") != null) {
nettyRequest.setHeader("User-Agent", request.getHeaders().getFirstValue("User-Agent"));
} else {
nettyRequest.setHeader("User-Agent", AsyncHttpProviderUtils.constructUserAgent(NettyAsyncHttpProvider.class));
}
if (!m.equals(HttpMethod.CONNECT)) {
if (request.getCookies() != null && !request.getCookies().isEmpty()) {
CookieEncoder httpCookieEncoder = new CookieEncoder(false);
Iterator<Cookie> ic = request.getCookies().iterator();
Cookie c;
org.jboss.netty.handler.codec.http.Cookie cookie;
while (ic.hasNext()) {
c = ic.next();
cookie = new DefaultCookie(c.getName(), c.getValue());
cookie.setPath(c.getPath());
cookie.setMaxAge(c.getMaxAge());
cookie.setDomain(c.getDomain());
httpCookieEncoder.addCookie(cookie);
}
nettyRequest.setHeader(HttpHeaders.Names.COOKIE, httpCookieEncoder.encode());
}
String reqType = request.getMethod();
if (!"GET".equals(reqType) && !"HEAD".equals(reqType) && !"OPTION".equals(reqType) && !"TRACE".equals(reqType)) {
String bodyCharset = request.getBodyEncoding() == null ? DEFAULT_CHARSET : request.getBodyEncoding();
// We already have processed the body.
if (buffer != null && buffer.writerIndex() != 0) {
nettyRequest.setHeader(HttpHeaders.Names.CONTENT_LENGTH, buffer.writerIndex());
nettyRequest.setContent(buffer);
} else if (request.getByteData() != null) {
nettyRequest.setHeader(HttpHeaders.Names.CONTENT_LENGTH, String.valueOf(request.getByteData().length));
nettyRequest.setContent(ChannelBuffers.copiedBuffer(request.getByteData()));
} else if (request.getStringData() != null) {
nettyRequest.setHeader(HttpHeaders.Names.CONTENT_LENGTH, String.valueOf(request.getStringData().getBytes(bodyCharset).length));
nettyRequest.setContent(ChannelBuffers.copiedBuffer(request.getStringData(), bodyCharset));
} else if (request.getStreamData() != null) {
int[] lengthWrapper = new int[1];
byte[] bytes = AsyncHttpProviderUtils.readFully(request.getStreamData(), lengthWrapper);
int length = lengthWrapper[0];
nettyRequest.setHeader(HttpHeaders.Names.CONTENT_LENGTH, String.valueOf(length));
nettyRequest.setContent(ChannelBuffers.copiedBuffer(bytes, 0, length));
} else if (request.getParams() != null) {
StringBuilder sb = new StringBuilder();
for (final Entry<String, List<String>> paramEntry : request.getParams()) {
final String key = paramEntry.getKey();
for (final String value : paramEntry.getValue()) {
if (sb.length() > 0) {
sb.append("&");
}
UTF8UrlEncoder.appendEncoded(sb, key);
sb.append("=");
UTF8UrlEncoder.appendEncoded(sb, value);
}
}
nettyRequest.setHeader(HttpHeaders.Names.CONTENT_LENGTH, String.valueOf(sb.length()));
nettyRequest.setContent(ChannelBuffers.copiedBuffer(sb.toString().getBytes(bodyCharset)));
if (!request.getHeaders().containsKey(HttpHeaders.Names.CONTENT_TYPE)) {
nettyRequest.setHeader(HttpHeaders.Names.CONTENT_TYPE, "application/x-www-form-urlencoded");
}
} else if (request.getParts() != null) {
int lenght = computeAndSetContentLength(request, nettyRequest);
if (lenght == -1) {
lenght = MAX_BUFFERED_BYTES;
}
MultipartRequestEntity mre = AsyncHttpProviderUtils.createMultipartRequestEntity(request.getParts(), request.getParams());
nettyRequest.setHeader(HttpHeaders.Names.CONTENT_TYPE, mre.getContentType());
nettyRequest.setHeader(HttpHeaders.Names.CONTENT_LENGTH, String.valueOf(mre.getContentLength()));
ChannelBuffer b = ChannelBuffers.dynamicBuffer(lenght);
mre.writeRequest(new ChannelBufferOutputStream(b));
nettyRequest.setContent(b);
} else if (request.getEntityWriter() != null) {
int lenght = computeAndSetContentLength(request, nettyRequest);
if (lenght == -1) {
lenght = MAX_BUFFERED_BYTES;
}
ChannelBuffer b = ChannelBuffers.dynamicBuffer(lenght);
request.getEntityWriter().writeEntity(new ChannelBufferOutputStream(b));
nettyRequest.setHeader(HttpHeaders.Names.CONTENT_LENGTH, b.writerIndex());
nettyRequest.setContent(b);
} else if (request.getFile() != null) {
File file = request.getFile();
if (!file.isFile()) {
throw new IOException(String.format("File %s is not a file or doesn't exist", file.getAbsolutePath()));
}
nettyRequest.setHeader(HttpHeaders.Names.CONTENT_LENGTH, file.length());
}
}
}
return nettyRequest;
}
public void close() {
isClose.set(true);
try {
connectionsPool.destroy();
openChannels.close();
for(Channel channel: openChannels) {
ChannelHandlerContext ctx = channel.getPipeline().getContext(NettyAsyncHttpProvider.class);
if (ctx.getAttachment() instanceof NettyResponseFuture<?>) {
NettyResponseFuture<?> future = (NettyResponseFuture<?>) ctx.getAttachment();
future.setReaperFuture(null);
}
}
config.executorService().shutdown();
config.reaper().shutdown();
socketChannelFactory.releaseExternalResources();
plainBootstrap.releaseExternalResources();
secureBootstrap.releaseExternalResources();
} catch (Throwable t) {
log.warn("Unexpected error on close", t);
}
}
/* @Override */
public Response prepareResponse(final HttpResponseStatus status,
final HttpResponseHeaders headers,
final Collection<HttpResponseBodyPart> bodyParts) {
return new NettyResponse(status, headers, bodyParts);
}
/* @Override */
public <T> ListenableFuture<T> execute(Request request, final AsyncHandler<T> asyncHandler) throws IOException {
return doConnect(request, asyncHandler, null, true, executeConnectAsync, false);
}
private <T> void execute(final Request request, final NettyResponseFuture<T> f, boolean useCache, boolean asyncConnect) throws IOException {
doConnect(request, f.getAsyncHandler(), f, useCache, asyncConnect, false);
}
private <T> void execute(final Request request, final NettyResponseFuture<T> f, boolean useCache, boolean asyncConnect, boolean reclaimCache) throws IOException {
doConnect(request, f.getAsyncHandler(), f, useCache, asyncConnect, reclaimCache);
}
private <T> ListenableFuture<T> doConnect(final Request request, final AsyncHandler<T> asyncHandler, NettyResponseFuture<T> f,
boolean useCache, boolean asyncConnect, boolean reclaimCache) throws IOException {
if (isClose.get()) {
throw new IOException("Closed");
}
ProxyServer proxyServer = request.getProxyServer() != null ? request.getProxyServer() : config.getProxyServer();
URI uri = AsyncHttpProviderUtils.createUri(request.getUrl());
Channel channel = null;
if (useCache) {
if (f != null && f.reuseChannel() && f.channel() != null) {
channel = f.channel();
} else {
channel = lookupInCache(uri);
}
}
ChannelBuffer bufferedBytes = null;
if (f != null && f.getRequest().getFile() == null &&
!f.getNettyRequest().getMethod().getName().equals(HttpMethod.CONNECT.getName())) {
bufferedBytes = f.getNettyRequest().getContent();
}
boolean useSSl = uri.getScheme().compareToIgnoreCase(HTTPS) == 0 && proxyServer == null;
if (channel != null && channel.isOpen() && channel.isConnected()) {
HttpRequest nettyRequest = buildRequest(config, request, uri, false, bufferedBytes);
if (f == null) {
f = newFuture(uri, request, asyncHandler, nettyRequest, config, this);
} else {
f.setNettyRequest(nettyRequest);
}
f.setState(NettyResponseFuture.STATE.POOLED);
f.attachChannel(channel, false);
log.debug("\nUsing cached Channel {}\n for request \n{}\n", channel, nettyRequest);
channel.getPipeline().getContext(NettyAsyncHttpProvider.class).setAttachment(f);
try {
writeRequest(channel, config, f, nettyRequest);
} catch (IllegalStateException ex) {
log.debug("writeRequest failure", ex);
if (useSSl && ex.getMessage() != null && ex.getMessage().contains("SSLEngine")) {
log.debug("SSLEngine failure", ex);
f = null;
} else {
throw ex;
}
}
return f;
}
// Do not throw an exception when we need an extra connection for a redirect.
if (!reclaimCache && (!connectionsPool.canCacheConnection() ||
(config.getMaxTotalConnections() > -1 && (maxConnections.get() + 1) > config.getMaxTotalConnections()))) {
IOException ex = new IOException(String.format("Too many connections %s", config.getMaxTotalConnections()));
try {
asyncHandler.onThrowable(ex);
} catch (Throwable t) {
log.warn("!connectionsPool.canCacheConnection()",t);
}
throw ex;
}
NettyConnectListener<T> c = new NettyConnectListener.Builder<T>(config, request, asyncHandler, f, this, bufferedBytes).build(uri);
boolean avoidProxy = ProxyUtils.avoidProxy(proxyServer, uri.getHost());
if (useSSl) {
constructSSLPipeline(c);
}
if (trackConnections) {
maxConnections.incrementAndGet();
}
ChannelFuture channelFuture;
ClientBootstrap bootstrap = useSSl ? secureBootstrap : plainBootstrap;
bootstrap.setOption("connectTimeoutMillis", config.getConnectionTimeoutInMs());
// Do no enable this with win.
if (System.getProperty("os.name").toLowerCase().indexOf("win") == -1) {
bootstrap.setOption("reuseAddress", asyncHttpProviderConfig.getProperty(NettyAsyncHttpProviderConfig.REUSE_ADDRESS));
}
try {
if (proxyServer == null || avoidProxy) {
channelFuture = bootstrap.connect(new InetSocketAddress(uri.getHost(), AsyncHttpProviderUtils.getPort(uri)));
} else {
channelFuture = bootstrap.connect(new InetSocketAddress(proxyServer.getHost(), proxyServer.getPort()));
}
} catch (Throwable t) {
abort(c.future(), t.getCause() == null ? t : t.getCause());
return c.future();
}
boolean directInvokation = true;
if (IN_IO_THREAD.get() && DefaultChannelFuture.isUseDeadLockChecker()) {
directInvokation = false;
}
if (directInvokation && !asyncConnect && request.getFile() == null) {
int timeOut = config.getConnectionTimeoutInMs() > 0 ? config.getConnectionTimeoutInMs() : Integer.MAX_VALUE;
if (!channelFuture.awaitUninterruptibly(timeOut, TimeUnit.MILLISECONDS)) {
abort(c.future(), new ConnectException("Connect times out"));
}
try {
c.operationComplete(channelFuture);
} catch (Exception e) {
IOException ioe = new IOException(e.getMessage());
ioe.initCause(e);
throw ioe;
}
} else {
channelFuture.addListener(c);
}
log.debug("\nNon cached request \n{}\n\nusing Channel \n{}\n", c.future().getNettyRequest(), channelFuture.getChannel());
if (!c.future().isCancelled() || !c.future().isDone()) {
openChannels.add(channelFuture.getChannel());
c.future().attachChannel(channelFuture.getChannel(), false);
}
return c.future();
}
protected static int requestTimeout(AsyncHttpClientConfig config, PerRequestConfig perRequestConfig) {
int result;
if (perRequestConfig != null) {
int prRequestTimeout = perRequestConfig.getRequestTimeoutInMs();
result = (prRequestTimeout != 0 ? prRequestTimeout : config.getRequestTimeoutInMs());
} else {
result = config.getRequestTimeoutInMs();
}
return result;
}
private void closeChannel(final ChannelHandlerContext ctx) {
connectionsPool.removeAll(ctx.getChannel());
finishChannel(ctx);
}
private void finishChannel(final ChannelHandlerContext ctx) {
log.debug("Closing Channel {} ", ctx.getChannel());
ctx.setAttachment(new DiscardEvent());
// The channel may have already been removed if a timeout occurred, and this method may be called just after.
if (ctx.getChannel() == null) {
return;
}
try {
ctx.getChannel().close();
} catch (Throwable t) {
log.debug("Error closing a connection", t);
}
openChannels.remove(ctx.getChannel());
}
@Override
public void messageReceived(final ChannelHandlerContext ctx, MessageEvent e) throws Exception {
//call super to reset the read timeout
super.messageReceived(ctx, e);
IN_IO_THREAD.set(Boolean.TRUE);
if (ctx.getAttachment() == null) {
log.debug("ChannelHandlerContext wasn't having any attachment");
}
if (ctx.getAttachment() instanceof DiscardEvent) {
return;
} else if (ctx.getAttachment() instanceof AsyncCallable) {
if (e.getMessage() instanceof HttpChunk) {
HttpChunk chunk = (HttpChunk) e.getMessage();
if (chunk.isLast()) {
AsyncCallable ac = (AsyncCallable) ctx.getAttachment();
ac.call();
}
} else {
AsyncCallable ac = (AsyncCallable) ctx.getAttachment();
ac.call();
}
return;
} else if (!(ctx.getAttachment() instanceof NettyResponseFuture<?>)) {
// The IdleStateHandler times out and he is calling us.
// We already closed the channel in IdleStateHandler#channelIdle
// so we have nothing to do
return;
}
final NettyResponseFuture<?> future = (NettyResponseFuture<?>) ctx.getAttachment();
future.touch();
HttpRequest nettyRequest = future.getNettyRequest();
AsyncHandler<?> handler = future.getAsyncHandler();
Request request = future.getRequest();
HttpResponse response = null;
try {
if (e.getMessage() instanceof HttpResponse) {
response = (HttpResponse) e.getMessage();
log.debug("\n\nRequest {}\n\nResponse {}\n", nettyRequest, response);
// Required if there is some trailing headers.
future.setHttpResponse(response);
int statusCode = response.getStatus().getCode();
String ka = response.getHeader(HttpHeaders.Names.CONNECTION);
future.setKeepAlive(ka == null || ka.toLowerCase().equals("keep-alive"));
List<String> wwwAuth = getWwwAuth(response.getHeaders());
Realm realm = request.getRealm() != null ? request.getRealm() : config.getRealm();
HttpResponseStatus status = new ResponseStatus(future.getURI(), response, this);
FilterContext fc = new FilterContext.FilterContextBuilder().asyncHandler(handler).request(request).responseStatus(status).build();
for (ResponseFilter asyncFilter : config.getResponseFilters()) {
try {
fc = asyncFilter.filter(fc);
if (fc == null) {
throw new NullPointerException("FilterContext is null");
}
} catch (FilterException efe) {
abort(future, efe);
}
}
// The request has changed
if (fc.replayRequest()) {
replayRequest(future, fc, response, ctx);
return;
}
if (statusCode == 401
&& wwwAuth.size() > 0
&& realm != null
&& !future.getAndSetAuth(true)) {
final RequestBuilder builder = new RequestBuilder(future.getRequest());
future.setState(NettyResponseFuture.STATE.NEW);
if (!future.getURI().getPath().equalsIgnoreCase(realm.getUri())) {
builder.setUrl(future.getURI().toString());
}
Realm newRealm = null;
final FluentCaseInsensitiveStringsMap headers = request.getHeaders();
ProxyServer proxyServer = request.getProxyServer() != null ? request.getProxyServer() : config.getProxyServer();
// TODO: Refactor and put this code out of here.
// NTLM
if (wwwAuth.get(0).startsWith("NTLM") || (wwwAuth.get(0).startsWith("Negotiate")
&& realm.getAuthScheme() == Realm.AuthScheme.NTLM)) {
String ntlmDomain = proxyServer == null ? realm.getNtlmDomain() : proxyServer.getNtlmDomain();
String ntlmHost = proxyServer == null ? realm.getNtlmHost() : proxyServer.getHost();
String prinicipal = proxyServer == null ? realm.getPrincipal() : proxyServer.getPrincipal();
String password = proxyServer == null ? realm.getPassword() : proxyServer.getPassword();
if (!realm.isNtlmMessageType2Received()) {
String challengeHeader = ntlmEngine.generateType1Msg(ntlmDomain, ntlmHost);