-
Notifications
You must be signed in to change notification settings - Fork 735
Expand file tree
/
Copy pathClientToProxyConnection.java
More file actions
1455 lines (1295 loc) · 58.5 KB
/
ClientToProxyConnection.java
File metadata and controls
1455 lines (1295 loc) · 58.5 KB
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
package org.littleshoot.proxy.impl;
import com.google.common.io.BaseEncoding;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelPipeline;
import io.netty.handler.codec.http.DefaultHttpRequest;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.FullHttpResponse;
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.HttpObject;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpRequest;
import io.netty.handler.codec.http.HttpRequestDecoder;
import io.netty.handler.codec.http.HttpResponse;
import io.netty.handler.codec.http.HttpResponseEncoder;
import io.netty.handler.codec.http.HttpResponseStatus;
import io.netty.handler.codec.http.HttpVersion;
import io.netty.handler.timeout.IdleStateHandler;
import io.netty.handler.traffic.GlobalTrafficShapingHandler;
import io.netty.util.concurrent.Future;
import io.netty.util.concurrent.GenericFutureListener;
import org.apache.commons.lang3.StringUtils;
import org.littleshoot.proxy.ActivityTracker;
import org.littleshoot.proxy.FlowContext;
import org.littleshoot.proxy.FullFlowContext;
import org.littleshoot.proxy.HttpFilters;
import org.littleshoot.proxy.HttpFiltersAdapter;
import org.littleshoot.proxy.ProxyAuthenticator;
import org.littleshoot.proxy.SslEngineSource;
import javax.net.ssl.SSLSession;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.UnknownHostException;
import java.nio.charset.Charset;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.regex.Pattern;
import static org.littleshoot.proxy.impl.ConnectionState.AWAITING_CHUNK;
import static org.littleshoot.proxy.impl.ConnectionState.AWAITING_INITIAL;
import static org.littleshoot.proxy.impl.ConnectionState.AWAITING_PROXY_AUTHENTICATION;
import static org.littleshoot.proxy.impl.ConnectionState.DISCONNECT_REQUESTED;
import static org.littleshoot.proxy.impl.ConnectionState.NEGOTIATING_CONNECT;
/**
* <p>
* Represents a connection from a client to our proxy. Each
* ClientToProxyConnection can have multiple {@link ProxyToServerConnection}s,
* at most one per outbound host:port.
* </p>
*
* <p>
* Once a ProxyToServerConnection has been created for a given server, it is
* continually reused. The ProxyToServerConnection goes through its own
* lifecycle of connects and disconnects, with different underlying
* {@link Channel}s, but only a single ProxyToServerConnection object is used
* per server. The one exception to this is CONNECT tunneling - if a connection
* has been used for CONNECT tunneling, that connection will never be reused.
* </p>
*
* <p>
* As the ProxyToServerConnections receive responses from their servers, they
* feed these back to the client by calling
* {@link #respond(ProxyToServerConnection, HttpFilters, HttpRequest, HttpResponse, HttpObject)}
* .
* </p>
*/
public class ClientToProxyConnection extends ProxyConnection<HttpRequest> {
private static final HttpResponseStatus CONNECTION_ESTABLISHED = new HttpResponseStatus(
200, "Connection established");
/**
* Used for case-insensitive comparisons when parsing Connection header values.
*/
private static final String LOWERCASE_TRANSFER_ENCODING_HEADER = HttpHeaders.Names.TRANSFER_ENCODING.toLowerCase(Locale.US);
/**
* Used for case-insensitive comparisons when checking direct proxy request.
*/
private static final Pattern HTTP_SCHEME = Pattern.compile("^http://.*", Pattern.CASE_INSENSITIVE);
/**
* Keep track of all ProxyToServerConnections by host+port.
*/
private final Map<String, ProxyToServerConnection> serverConnectionsByHostAndPort = new ConcurrentHashMap<String, ProxyToServerConnection>();
/**
* Keep track of how many servers are currently in the process of
* connecting.
*/
private final AtomicInteger numberOfCurrentlyConnectingServers = new AtomicInteger(
0);
/**
* Keep track of how many servers are currently connected.
*/
private final AtomicInteger numberOfCurrentlyConnectedServers = new AtomicInteger(
0);
/**
* Keep track of how many times we were able to reuse a connection.
*/
private final AtomicInteger numberOfReusedServerConnections = new AtomicInteger(
0);
/**
* This is the current server connection that we're using while transferring
* chunked data.
*/
private volatile ProxyToServerConnection currentServerConnection;
/**
* The current filters to apply to incoming requests/chunks.
*/
private volatile HttpFilters currentFilters = HttpFiltersAdapter.NOOP_FILTER;
private volatile SSLSession clientSslSession;
/**
* Tracks whether or not this ClientToProxyConnection is current doing MITM.
*/
private volatile boolean mitming = false;
private AtomicBoolean authenticated = new AtomicBoolean();
private final GlobalTrafficShapingHandler globalTrafficShapingHandler;
/**
* The current HTTP request that this connection is currently servicing.
*/
private volatile HttpRequest currentRequest;
ClientToProxyConnection(
final DefaultHttpProxyServer proxyServer,
SslEngineSource sslEngineSource,
boolean authenticateClients,
ChannelPipeline pipeline,
GlobalTrafficShapingHandler globalTrafficShapingHandler) {
super(AWAITING_INITIAL, proxyServer, false);
initChannelPipeline(pipeline);
if (sslEngineSource != null) {
LOG.debug("Enabling encryption of traffic from client to proxy");
encrypt(pipeline, sslEngineSource.newSslEngine(),
authenticateClients)
.addListener(
new GenericFutureListener<Future<? super Channel>>() {
@Override
public void operationComplete(
Future<? super Channel> future)
throws Exception {
if (future.isSuccess()) {
clientSslSession = sslEngine
.getSession();
recordClientSSLHandshakeSucceeded();
}
}
});
}
this.globalTrafficShapingHandler = globalTrafficShapingHandler;
LOG.debug("Created ClientToProxyConnection");
}
/***************************************************************************
* Reading
**************************************************************************/
@Override
protected ConnectionState readHTTPInitial(HttpRequest httpRequest) {
LOG.debug("Received raw request: {}", httpRequest);
// if we cannot parse the request, immediately return a 400 and close the connection, since we do not know what state
// the client thinks the connection is in
if (httpRequest.getDecoderResult().isFailure()) {
LOG.debug("Could not parse request from client. Decoder result: {}", httpRequest.getDecoderResult().toString());
FullHttpResponse response = ProxyUtils.createFullHttpResponse(HttpVersion.HTTP_1_1,
HttpResponseStatus.BAD_REQUEST,
"Unable to parse HTTP request");
HttpHeaders.setKeepAlive(response, false);
respondWithShortCircuitResponse(response);
return DISCONNECT_REQUESTED;
}
boolean authenticationRequired = authenticationRequired(httpRequest);
if (authenticationRequired) {
LOG.debug("Not authenticated!!");
return AWAITING_PROXY_AUTHENTICATION;
} else {
return doReadHTTPInitial(httpRequest);
}
}
/**
* <p>
* Reads an {@link HttpRequest}.
* </p>
*
* <p>
* If we don't yet have a {@link ProxyToServerConnection} for the desired
* server, this takes care of creating it.
* </p>
*
* <p>
* Note - the "server" could be a chained proxy, not the final endpoint for
* the request.
* </p>
*
* @param httpRequest
* @return
*/
private ConnectionState doReadHTTPInitial(HttpRequest httpRequest) {
// Make a copy of the original request
this.currentRequest = copy(httpRequest);
// Set up our filters based on the original request. If the HttpFiltersSource returns null (meaning the request/response
// should not be filtered), fall back to the default no-op filter source.
HttpFilters filterInstance = proxyServer.getFiltersSource().filterRequest(currentRequest, ctx);
if (filterInstance != null) {
currentFilters = filterInstance;
} else {
currentFilters = HttpFiltersAdapter.NOOP_FILTER;
}
// Send the request through the clientToProxyRequest filter, and respond with the short-circuit response if required
HttpResponse clientToProxyFilterResponse = currentFilters.clientToProxyRequest(httpRequest);
if (clientToProxyFilterResponse != null) {
LOG.debug("Responding to client with short-circuit response from filter: {}", clientToProxyFilterResponse);
boolean keepAlive = respondWithShortCircuitResponse(clientToProxyFilterResponse);
if (keepAlive) {
return AWAITING_INITIAL;
} else {
return DISCONNECT_REQUESTED;
}
}
// if origin-form requests are not explicitly enabled, short-circuit requests that treat the proxy as the
// origin server, to avoid infinite loops
if (!proxyServer.isAllowRequestsToOriginServer() && isRequestToOriginServer(httpRequest)) {
boolean keepAlive = writeBadRequest(httpRequest);
if (keepAlive) {
return AWAITING_INITIAL;
} else {
return DISCONNECT_REQUESTED;
}
}
// Identify our server and chained proxy
String serverHostAndPort = identifyHostAndPort(httpRequest);
LOG.debug("Ensuring that hostAndPort are available in {}",
httpRequest.getUri());
if (serverHostAndPort == null || StringUtils.isBlank(serverHostAndPort)) {
LOG.warn("No host and port found in {}", httpRequest.getUri());
boolean keepAlive = writeBadGateway(httpRequest);
if (keepAlive) {
return AWAITING_INITIAL;
} else {
return DISCONNECT_REQUESTED;
}
}
LOG.debug("Finding ProxyToServerConnection for: {}", serverHostAndPort);
currentServerConnection = isMitming() || isTunneling() ?
this.currentServerConnection
: this.serverConnectionsByHostAndPort.get(serverHostAndPort);
boolean newConnectionRequired = false;
if (ProxyUtils.isCONNECT(httpRequest)) {
LOG.debug(
"Not reusing existing ProxyToServerConnection because request is a CONNECT for: {}",
serverHostAndPort);
newConnectionRequired = true;
} else if (currentServerConnection == null) {
LOG.debug("Didn't find existing ProxyToServerConnection for: {}",
serverHostAndPort);
newConnectionRequired = true;
}
if (newConnectionRequired) {
try {
currentServerConnection = ProxyToServerConnection.create(
proxyServer,
this,
serverHostAndPort,
currentFilters,
httpRequest,
globalTrafficShapingHandler);
if (currentServerConnection == null) {
LOG.debug("Unable to create server connection, probably no chained proxies available");
boolean keepAlive = writeBadGateway(httpRequest);
resumeReading();
if (keepAlive) {
return AWAITING_INITIAL;
} else {
return DISCONNECT_REQUESTED;
}
}
// Remember the connection for later
serverConnectionsByHostAndPort.put(serverHostAndPort,
currentServerConnection);
} catch (UnknownHostException uhe) {
LOG.info("Bad Host {}", httpRequest.getUri());
boolean keepAlive = writeBadGateway(httpRequest);
resumeReading();
if (keepAlive) {
return AWAITING_INITIAL;
} else {
return DISCONNECT_REQUESTED;
}
}
} else {
LOG.debug("Reusing existing server connection: {}",
currentServerConnection);
numberOfReusedServerConnections.incrementAndGet();
}
modifyRequestHeadersToReflectProxying(httpRequest);
HttpResponse proxyToServerFilterResponse = currentFilters.proxyToServerRequest(httpRequest);
if (proxyToServerFilterResponse != null) {
LOG.debug("Responding to client with short-circuit response from filter: {}", proxyToServerFilterResponse);
boolean keepAlive = respondWithShortCircuitResponse(proxyToServerFilterResponse);
if (keepAlive) {
return AWAITING_INITIAL;
} else {
return DISCONNECT_REQUESTED;
}
}
LOG.debug("Writing request to ProxyToServerConnection");
currentServerConnection.write(httpRequest, currentFilters);
// Figure out our next state
if (ProxyUtils.isCONNECT(httpRequest)) {
return NEGOTIATING_CONNECT;
} else if (ProxyUtils.isChunked(httpRequest)) {
return AWAITING_CHUNK;
} else {
return AWAITING_INITIAL;
}
}
/**
* Returns true if the specified request is a request to an origin server, rather than to a proxy server. If this
* request is being MITM'd, this method always returns false. The format of requests to a proxy server are defined
* in RFC 7230, section 5.3.2 (all other requests are considered requests to an origin server):
<pre>
When making a request to a proxy, other than a CONNECT or server-wide
OPTIONS request (as detailed below), a client MUST send the target
URI in absolute-form as the request-target.
[...]
An example absolute-form of request-line would be:
GET http://www.example.org/pub/WWW/TheProject.html HTTP/1.1
To allow for transition to the absolute-form for all requests in some
future version of HTTP, a server MUST accept the absolute-form in
requests, even though HTTP/1.1 clients will only send them in
requests to proxies.
</pre>
*
* @param httpRequest the request to evaluate
* @return true if the specified request is a request to an origin server, otherwise false
*/
private boolean isRequestToOriginServer(HttpRequest httpRequest) {
// while MITMing, all HTTPS requests are requests to the origin server, since the client does not know
// the request is being MITM'd by the proxy
if (httpRequest.getMethod() == HttpMethod.CONNECT || isMitming()) {
return false;
}
// direct requests to the proxy have the path only without a scheme
String uri = httpRequest.getUri();
return !HTTP_SCHEME.matcher(uri).matches();
}
@Override
protected void readHTTPChunk(HttpContent chunk) {
currentFilters.clientToProxyRequest(chunk);
currentFilters.proxyToServerRequest(chunk);
currentServerConnection.write(chunk);
}
@Override
protected void readRaw(ByteBuf buf) {
currentServerConnection.write(buf);
}
/***************************************************************************
* Writing
**************************************************************************/
/**
* Send a response to the client.
*
* @param serverConnection
* the ProxyToServerConnection that's responding
* @param filters
* the filters to apply to the response
* @param currentHttpRequest
* the HttpRequest that prompted this response
* @param currentHttpResponse
* the HttpResponse corresponding to this data (when doing
* chunked transfers, this is the initial HttpResponse object
* that came in before the other chunks)
* @param httpObject
* the data with which to respond
*/
void respond(ProxyToServerConnection serverConnection, HttpFilters filters,
HttpRequest currentHttpRequest, HttpResponse currentHttpResponse,
HttpObject httpObject) {
// we are sending a response to the client, so we are done handling this request
this.currentRequest = null;
httpObject = filters.serverToProxyResponse(httpObject);
if (httpObject == null) {
forceDisconnect(serverConnection);
return;
}
if (httpObject instanceof HttpResponse) {
HttpResponse httpResponse = (HttpResponse) httpObject;
// if this HttpResponse does not have any means of signaling the end of the message body other than closing
// the connection, convert the message to a "Transfer-Encoding: chunked" HTTP response. This avoids the need
// to close the client connection to indicate the end of the message. (Responses to HEAD requests "must be" empty.)
if (!ProxyUtils.isHEAD(currentHttpRequest) && !ProxyUtils.isResponseSelfTerminating(httpResponse)) {
// if this is not a FullHttpResponse, duplicate the HttpResponse from the server before sending it to
// the client. this allows us to set the Transfer-Encoding to chunked without interfering with netty's
// handling of the response from the server. if we modify the original HttpResponse from the server,
// netty will not generate the appropriate LastHttpContent when it detects the connection closure from
// the server (see HttpObjectDecoder#decodeLast). (This does not apply to FullHttpResponses, for which
// netty already generates the empty final chunk when Transfer-Encoding is chunked.)
if (!(httpResponse instanceof FullHttpResponse)) {
HttpResponse duplicateResponse = ProxyUtils.duplicateHttpResponse(httpResponse);
// set the httpObject and httpResponse to the duplicated response, to allow all other standard processing
// (filtering, header modification for proxying, etc.) to be applied.
httpObject = httpResponse = duplicateResponse;
}
HttpHeaders.setTransferEncodingChunked(httpResponse);
}
fixHttpVersionHeaderIfNecessary(httpResponse);
modifyResponseHeadersToReflectProxying(httpResponse);
}
httpObject = filters.proxyToClientResponse(httpObject);
if (httpObject == null) {
forceDisconnect(serverConnection);
return;
}
write(httpObject);
if (ProxyUtils.isLastChunk(httpObject)) {
writeEmptyBuffer();
}
closeConnectionsAfterWriteIfNecessary(serverConnection,
currentHttpRequest, currentHttpResponse, httpObject);
}
/***************************************************************************
* Connection Lifecycle
**************************************************************************/
/**
* Tells the Client that its HTTP CONNECT request was successful.
*/
ConnectionFlowStep RespondCONNECTSuccessful = new ConnectionFlowStep(
this, NEGOTIATING_CONNECT) {
@Override
boolean shouldSuppressInitialRequest() {
return true;
}
protected Future<?> execute() {
LOG.debug("Responding with CONNECT successful");
HttpResponse response = ProxyUtils.createFullHttpResponse(HttpVersion.HTTP_1_1,
CONNECTION_ESTABLISHED);
response.headers().set(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.KEEP_ALIVE);
ProxyUtils.addVia(response, proxyServer.getProxyAlias());
return writeToChannel(response);
};
};
/**
* On connect of the client, start waiting for an initial
* {@link HttpRequest}.
*/
@Override
protected void connected() {
super.connected();
become(AWAITING_INITIAL);
recordClientConnected();
}
void timedOut(ProxyToServerConnection serverConnection) {
if (currentServerConnection == serverConnection && this.lastReadTime > currentServerConnection.lastReadTime) {
// the idle timeout fired on the active server connection. send a timeout response to the client.
LOG.warn("Server timed out: {}", currentServerConnection);
currentFilters.serverToProxyResponseTimedOut();
writeGatewayTimeout(currentRequest);
}
}
@Override
protected void timedOut() {
// idle timeout fired on the client channel. if we aren't waiting on a response from a server, hang up
if (currentServerConnection == null || this.lastReadTime <= currentServerConnection.lastReadTime) {
super.timedOut();
}
}
/**
* On disconnect of the client, disconnect all server connections.
*/
@Override
protected void disconnected() {
super.disconnected();
for (ProxyToServerConnection serverConnection : serverConnectionsByHostAndPort
.values()) {
serverConnection.disconnect();
}
recordClientDisconnected();
}
/**
* Called when {@link ProxyToServerConnection} starts its connection flow.
*
* @param serverConnection
*/
protected void serverConnectionFlowStarted(
ProxyToServerConnection serverConnection) {
stopReading();
this.numberOfCurrentlyConnectingServers.incrementAndGet();
}
/**
* If the {@link ProxyToServerConnection} completes its connection lifecycle
* successfully, this method is called to let us know about it.
*
* @param serverConnection
* @param shouldForwardInitialRequest
*/
protected void serverConnectionSucceeded(
ProxyToServerConnection serverConnection,
boolean shouldForwardInitialRequest) {
LOG.debug("Connection to server succeeded: {}",
serverConnection.getRemoteAddress());
resumeReadingIfNecessary();
become(shouldForwardInitialRequest ? getCurrentState()
: AWAITING_INITIAL);
numberOfCurrentlyConnectedServers.incrementAndGet();
}
/**
* If the {@link ProxyToServerConnection} fails to complete its connection
* lifecycle successfully, this method is called to let us know about it.
*
* <p>
* After failing to connect to the server, one of two things can happen:
* </p>
*
* <ol>
* <li>If the server was a chained proxy, we fall back to connecting to the
* ultimate endpoint directly.</li>
* <li>If the server was the ultimate endpoint, we return a 502 Bad Gateway
* to the client.</li>
* </ol>
*
* @param serverConnection
* @param lastStateBeforeFailure
* @param cause
* what caused the failure
*
* @return true if we're falling back to a another chained proxy (or direct
* connection) and trying again
*/
protected boolean serverConnectionFailed(
ProxyToServerConnection serverConnection,
ConnectionState lastStateBeforeFailure,
Throwable cause) {
resumeReadingIfNecessary();
HttpRequest initialRequest = serverConnection.getInitialRequest();
try {
boolean retrying = serverConnection.connectionFailed(cause);
if (retrying) {
LOG.debug("Failed to connect to upstream server or chained proxy. Retrying connection. Last state before failure: {}",
lastStateBeforeFailure, cause);
return true;
} else {
LOG.debug(
"Connection to upstream server or chained proxy failed: {}. Last state before failure: {}",
serverConnection.getRemoteAddress(),
lastStateBeforeFailure,
cause);
connectionFailedUnrecoverably(initialRequest, serverConnection);
return false;
}
} catch (UnknownHostException uhe) {
connectionFailedUnrecoverably(initialRequest, serverConnection);
return false;
}
}
private void connectionFailedUnrecoverably(HttpRequest initialRequest, ProxyToServerConnection serverConnection) {
// the connection to the server failed, so disconnect the server and remove the ProxyToServerConnection from the
// map of open server connections
serverConnection.disconnect();
this.serverConnectionsByHostAndPort.remove(serverConnection.getServerHostAndPort());
boolean keepAlive = writeBadGateway(initialRequest);
if (keepAlive) {
become(AWAITING_INITIAL);
} else {
become(DISCONNECT_REQUESTED);
}
}
private void resumeReadingIfNecessary() {
if (this.numberOfCurrentlyConnectingServers.decrementAndGet() == 0) {
LOG.debug("All servers have finished attempting to connect, resuming reading from client.");
resumeReading();
}
}
/***************************************************************************
* Other Lifecycle
**************************************************************************/
/**
* On disconnect of the server, track that we have one fewer connected
* servers and then disconnect the client if necessary.
*
* @param serverConnection
*/
protected void serverDisconnected(ProxyToServerConnection serverConnection) {
numberOfCurrentlyConnectedServers.decrementAndGet();
// for non-SSL connections, do not disconnect the client from the proxy, even if this was the last server connection.
// this allows clients to continue to use the open connection to the proxy to make future requests. for SSL
// connections, whether we are tunneling or MITMing, we need to disconnect the client because there is always
// exactly one ClientToProxyConnection per ProxyToServerConnection, and vice versa.
if (isTunneling() || isMitming()) {
disconnect();
}
}
/**
* When the ClientToProxyConnection becomes saturated, stop reading on all
* associated ProxyToServerConnections.
*/
@Override
synchronized protected void becameSaturated() {
super.becameSaturated();
for (ProxyToServerConnection serverConnection : serverConnectionsByHostAndPort
.values()) {
synchronized (serverConnection) {
if (this.isSaturated()) {
serverConnection.stopReading();
}
}
}
}
/**
* When the ClientToProxyConnection becomes writable, resume reading on all
* associated ProxyToServerConnections.
*/
@Override
synchronized protected void becameWritable() {
super.becameWritable();
for (ProxyToServerConnection serverConnection : serverConnectionsByHostAndPort
.values()) {
synchronized (serverConnection) {
if (!this.isSaturated()) {
serverConnection.resumeReading();
}
}
}
}
/**
* When a server becomes saturated, we stop reading from the client.
*
* @param serverConnection
*/
synchronized protected void serverBecameSaturated(
ProxyToServerConnection serverConnection) {
if (serverConnection.isSaturated()) {
LOG.info("Connection to server became saturated, stopping reading");
stopReading();
}
}
/**
* When a server becomes writeable, we check to see if all servers are
* writeable and if they are, we resume reading.
*
* @param serverConnection
*/
synchronized protected void serverBecameWriteable(
ProxyToServerConnection serverConnection) {
boolean anyServersSaturated = false;
for (ProxyToServerConnection otherServerConnection : serverConnectionsByHostAndPort
.values()) {
if (otherServerConnection.isSaturated()) {
anyServersSaturated = true;
break;
}
}
if (!anyServersSaturated) {
LOG.info("All server connections writeable, resuming reading");
resumeReading();
}
}
@Override
protected void exceptionCaught(Throwable cause) {
try {
if (cause instanceof IOException) {
// IOExceptions are expected errors, for example when a browser is killed and aborts a connection.
// rather than flood the logs with stack traces for these expected exceptions, we log the message at the
// INFO level and the stack trace at the DEBUG level.
LOG.info("An IOException occurred on ClientToProxyConnection: " + cause.getMessage());
LOG.debug("An IOException occurred on ClientToProxyConnection", cause);
} else if (cause instanceof RejectedExecutionException) {
LOG.info("An executor rejected a read or write operation on the ClientToProxyConnection (this is normal if the proxy is shutting down). Message: " + cause.getMessage());
LOG.debug("A RejectedExecutionException occurred on ClientToProxyConnection", cause);
} else {
LOG.error("Caught an exception on ClientToProxyConnection", cause);
}
} finally {
// always disconnect the client when an exception occurs on the channel
disconnect();
}
}
/***************************************************************************
* Connection Management
**************************************************************************/
/**
* Initialize the {@link ChannelPipeline} for the client to proxy channel.
* LittleProxy acts like a server here.
*
* A {@link ChannelPipeline} invokes the read (Inbound) handlers in
* ascending ordering of the list and then the write (Outbound) handlers in
* descending ordering.
*
* Regarding the Javadoc of {@link HttpObjectAggregator} it's needed to have
* the {@link HttpResponseEncoder} or {@link io.netty.handler.codec.http.HttpRequestEncoder} before the
* {@link HttpObjectAggregator} in the {@link ChannelPipeline}.
*
* @param pipeline
*/
private void initChannelPipeline(ChannelPipeline pipeline) {
LOG.debug("Configuring ChannelPipeline");
pipeline.addLast("bytesReadMonitor", bytesReadMonitor);
pipeline.addLast("bytesWrittenMonitor", bytesWrittenMonitor);
pipeline.addLast("encoder", new HttpResponseEncoder());
// We want to allow longer request lines, headers, and chunks
// respectively.
pipeline.addLast("decoder", new HttpRequestDecoder(
proxyServer.getMaxInitialLineLength(),
proxyServer.getMaxHeaderSize(),
proxyServer.getMaxChunkSize()));
// Enable aggregation for filtering if necessary
int numberOfBytesToBuffer = proxyServer.getFiltersSource()
.getMaximumRequestBufferSizeInBytes();
if (numberOfBytesToBuffer > 0) {
aggregateContentForFiltering(pipeline, numberOfBytesToBuffer);
}
pipeline.addLast("requestReadMonitor", requestReadMonitor);
pipeline.addLast("responseWrittenMonitor", responseWrittenMonitor);
pipeline.addLast(
"idle",
new IdleStateHandler(0, 0, proxyServer
.getIdleConnectionTimeout()));
pipeline.addLast("handler", this);
}
/**
* This method takes care of closing client to proxy and/or proxy to server
* connections after finishing a write.
*/
private void closeConnectionsAfterWriteIfNecessary(
ProxyToServerConnection serverConnection,
HttpRequest currentHttpRequest, HttpResponse currentHttpResponse,
HttpObject httpObject) {
boolean closeServerConnection = shouldCloseServerConnection(
currentHttpRequest, currentHttpResponse, httpObject);
boolean closeClientConnection = shouldCloseClientConnection(
currentHttpRequest, currentHttpResponse, httpObject);
if (closeServerConnection) {
LOG.debug("Closing remote connection after writing to client");
serverConnection.disconnect();
}
if (closeClientConnection) {
LOG.debug("Closing connection to client after writes");
disconnect();
}
}
private void forceDisconnect(ProxyToServerConnection serverConnection) {
LOG.debug("Forcing disconnect");
serverConnection.disconnect();
disconnect();
}
/**
* Determine whether or not the client connection should be closed.
*
* @param req
* @param res
* @param httpObject
* @return
*/
private boolean shouldCloseClientConnection(HttpRequest req,
HttpResponse res, HttpObject httpObject) {
if (ProxyUtils.isChunked(res)) {
// If the response is chunked, we want to return false unless it's
// the last chunk. If it is the last chunk, then we want to pass
// through to the same close semantics we'd otherwise use.
if (httpObject != null) {
if (!ProxyUtils.isLastChunk(httpObject)) {
String uri = null;
if (req != null) {
uri = req.getUri();
}
LOG.debug("Not closing client connection on middle chunk for {}", uri);
return false;
} else {
LOG.debug("Handling last chunk. Using normal client connection closing rules.");
}
}
}
if (!HttpHeaders.isKeepAlive(req)) {
LOG.debug("Closing client connection since request is not keep alive: {}", req);
// Here we simply want to close the connection because the
// client itself has requested it be closed in the request.
return true;
}
// ignore the response's keep-alive; we can keep this client connection open as long as the client allows it.
LOG.debug("Not closing client connection for request: {}", req);
return false;
}
/**
* Determines if the remote connection should be closed based on the request
* and response pair. If the request is HTTP 1.0 with no keep-alive header,
* for example, the connection should be closed.
*
* This in part determines if we should close the connection. Here's the
* relevant section of RFC 2616:
*
* "HTTP/1.1 defines the "close" connection option for the sender to signal
* that the connection will be closed after completion of the response. For
* example,
*
* Connection: close
*
* in either the request or the response header fields indicates that the
* connection SHOULD NOT be considered `persistent' (section 8.1) after the
* current request/response is complete."
*
* @param req
* The request.
* @param res
* The response.
* @param msg
* The message.
* @return Returns true if the connection should close.
*/
private boolean shouldCloseServerConnection(HttpRequest req,
HttpResponse res, HttpObject msg) {
if (ProxyUtils.isChunked(res)) {
// If the response is chunked, we want to return false unless it's
// the last chunk. If it is the last chunk, then we want to pass
// through to the same close semantics we'd otherwise use.
if (msg != null) {
if (!ProxyUtils.isLastChunk(msg)) {
String uri = null;
if (req != null) {
uri = req.getUri();
}
LOG.debug("Not closing server connection on middle chunk for {}", uri);
return false;
} else {
LOG.debug("Handling last chunk. Using normal server connection closing rules.");
}
}
}
// ignore the request's keep-alive; we can keep this server connection open as long as the server allows it.
if (!HttpHeaders.isKeepAlive(res)) {
LOG.debug("Closing server connection since response is not keep alive: {}", res);
// In this case, we want to honor the Connection: close header
// from the remote server and close that connection. We don't
// necessarily want to close the connection to the client, however
// as it's possible it has other connections open.
return true;
}
LOG.debug("Not closing server connection for response: {}", res);
return false;
}
/***************************************************************************
* Authentication
**************************************************************************/
/**
* <p>
* Checks whether the given HttpRequest requires authentication.
* </p>
*
* <p>
* If the request contains credentials, these are checked.
* </p>
*
* <p>
* If authentication is still required, either because no credentials were
* provided or the credentials were wrong, this writes a 407 response to the
* client.
* </p>
*
* @param request
* @return
*/
private boolean authenticationRequired(HttpRequest request) {
if (authenticated.get()) {
return false;
}
final ProxyAuthenticator authenticator = proxyServer
.getProxyAuthenticator();
if (authenticator == null)
return false;
if (!request.headers().contains(HttpHeaders.Names.PROXY_AUTHORIZATION)) {
writeAuthenticationRequired(authenticator.getRealm());
return true;
}
List<String> values = request.headers().getAll(
HttpHeaders.Names.PROXY_AUTHORIZATION);
String fullValue = values.iterator().next();
String value = StringUtils.substringAfter(fullValue, "Basic ").trim();
byte[] decodedValue = BaseEncoding.base64().decode(value);
String decodedString = new String(decodedValue, Charset.forName("UTF-8"));
String userName = StringUtils.substringBefore(decodedString, ":");
String password = StringUtils.substringAfter(decodedString, ":");
if (!authenticator.authenticate(userName, password)) {
writeAuthenticationRequired(authenticator.getRealm());
return true;
}
LOG.debug("Got proxy authorization!");
// We need to remove the header before sending the request on.
String authentication = request.headers().get(