This repository has been archived by the owner on Sep 29, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 285
/
Copy pathHttpURLConnection.java
3790 lines (3435 loc) · 144 KB
/
HttpURLConnection.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 (c) 1995, 2019, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package sun.net.www.protocol.http;
import java.security.PrivilegedAction;
import java.util.Arrays;
import java.net.URL;
import java.net.URLConnection;
import java.net.ProtocolException;
import java.net.HttpRetryException;
import java.net.PasswordAuthentication;
import java.net.Authenticator;
import java.net.HttpCookie;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.net.SocketTimeoutException;
import java.net.SocketPermission;
import java.net.Proxy;
import java.net.ProxySelector;
import java.net.URI;
import java.net.InetSocketAddress;
import java.net.CookieHandler;
import java.net.ResponseCache;
import java.net.CacheResponse;
import java.net.SecureCacheResponse;
import java.net.CacheRequest;
import java.net.URLPermission;
import java.net.Authenticator.RequestorType;
import java.security.AccessController;
import java.security.PrivilegedExceptionAction;
import java.security.PrivilegedActionException;
import java.io.*;
import java.net.*;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.Map;
import java.util.List;
import java.util.Locale;
import java.util.StringTokenizer;
import java.util.Iterator;
import java.util.HashSet;
import java.util.HashMap;
import java.util.Set;
import sun.net.*;
import sun.net.util.IPAddressUtil;
import sun.net.www.*;
import sun.net.www.http.HttpClient;
import sun.net.www.http.PosterOutputStream;
import sun.net.www.http.ChunkedInputStream;
import sun.net.www.http.ChunkedOutputStream;
import sun.util.logging.PlatformLogger;
import java.text.SimpleDateFormat;
import java.util.TimeZone;
import java.net.MalformedURLException;
import java.nio.ByteBuffer;
import static sun.net.www.protocol.http.AuthScheme.BASIC;
import static sun.net.www.protocol.http.AuthScheme.DIGEST;
import static sun.net.www.protocol.http.AuthScheme.NTLM;
import static sun.net.www.protocol.http.AuthScheme.NEGOTIATE;
import static sun.net.www.protocol.http.AuthScheme.KERBEROS;
import static sun.net.www.protocol.http.AuthScheme.UNKNOWN;
/**
* A class to represent an HTTP connection to a remote object.
*/
public class HttpURLConnection extends java.net.HttpURLConnection {
static String HTTP_CONNECT = "CONNECT";
static final String version;
public static final String userAgent;
/* max # of allowed re-directs */
static final int defaultmaxRedirects = 20;
static final int maxRedirects;
/* Not all servers support the (Proxy)-Authentication-Info headers.
* By default, we don't require them to be sent
*/
static final boolean validateProxy;
static final boolean validateServer;
/** A, possibly empty, set of authentication schemes that are disabled
* when proxying plain HTTP ( not HTTPS ). */
static final Set<String> disabledProxyingSchemes;
/** A, possibly empty, set of authentication schemes that are disabled
* when setting up a tunnel for HTTPS ( HTTP CONNECT ). */
static final Set<String> disabledTunnelingSchemes;
private StreamingOutputStream strOutputStream;
private final static String RETRY_MSG1 =
"cannot retry due to proxy authentication, in streaming mode";
private final static String RETRY_MSG2 =
"cannot retry due to server authentication, in streaming mode";
private final static String RETRY_MSG3 =
"cannot retry due to redirection, in streaming mode";
/*
* System properties related to error stream handling:
*
* sun.net.http.errorstream.enableBuffering = <boolean>
*
* With the above system property set to true (default is false),
* when the response code is >=400, the HTTP handler will try to
* buffer the response body (up to a certain amount and within a
* time limit). Thus freeing up the underlying socket connection
* for reuse. The rationale behind this is that usually when the
* server responds with a >=400 error (client error or server
* error, such as 404 file not found), the server will send a
* small response body to explain who to contact and what to do to
* recover. With this property set to true, even if the
* application doesn't call getErrorStream(), read the response
* body, and then call close(), the underlying socket connection
* can still be kept-alive and reused. The following two system
* properties provide further control to the error stream
* buffering behaviour.
*
* sun.net.http.errorstream.timeout = <int>
* the timeout (in millisec) waiting the error stream
* to be buffered; default is 300 ms
*
* sun.net.http.errorstream.bufferSize = <int>
* the size (in bytes) to use for the buffering the error stream;
* default is 4k
*/
/* Should we enable buffering of error streams? */
private static boolean enableESBuffer = false;
/* timeout waiting for read for buffered error stream;
*/
private static int timeout4ESBuffer = 0;
/* buffer size for buffered error stream;
*/
private static int bufSize4ES = 0;
/*
* Restrict setting of request headers through the public api
* consistent with JavaScript XMLHttpRequest2 with a few
* exceptions. Disallowed headers are silently ignored for
* backwards compatibility reasons rather than throwing a
* SecurityException. For example, some applets set the
* Host header since old JREs did not implement HTTP 1.1.
* Additionally, any header starting with Sec- is
* disallowed.
*
* The following headers are allowed for historical reasons:
*
* Accept-Charset, Accept-Encoding, Cookie, Cookie2, Date,
* Referer, TE, User-Agent, headers beginning with Proxy-.
*
* The following headers are allowed in a limited form:
*
* Connection: close
*
* See http://www.w3.org/TR/XMLHttpRequest2.
*/
private static final boolean allowRestrictedHeaders;
private static final Set<String> restrictedHeaderSet;
private static final String[] restrictedHeaders = {
/* Restricted by XMLHttpRequest2 */
//"Accept-Charset",
//"Accept-Encoding",
"Access-Control-Request-Headers",
"Access-Control-Request-Method",
"Connection", /* close is allowed */
"Content-Length",
//"Cookie",
//"Cookie2",
"Content-Transfer-Encoding",
//"Date",
//"Expect",
"Host",
"Keep-Alive",
"Origin",
// "Referer",
// "TE",
"Trailer",
"Transfer-Encoding",
"Upgrade",
//"User-Agent",
"Via"
};
private static String getNetProperty(String name) {
PrivilegedAction<String> pa = () -> NetProperties.get(name);
return AccessController.doPrivileged(pa);
}
private static Set<String> schemesListToSet(String list) {
if (list == null || list.isEmpty())
return Collections.emptySet();
Set<String> s = new HashSet<>();
String[] parts = list.split("\\s*,\\s*");
for (String part : parts)
s.add(part.toLowerCase(Locale.ROOT));
return s;
}
static {
maxRedirects = java.security.AccessController.doPrivileged(
new sun.security.action.GetIntegerAction(
"http.maxRedirects", defaultmaxRedirects)).intValue();
version = java.security.AccessController.doPrivileged(
new sun.security.action.GetPropertyAction("java.version"));
String agent = java.security.AccessController.doPrivileged(
new sun.security.action.GetPropertyAction("http.agent"));
if (agent == null) {
agent = "Java/"+version;
} else {
agent = agent + " Java/"+version;
}
userAgent = agent;
// A set of net properties to control the use of authentication schemes
// when proxing/tunneling.
String p = getNetProperty("jdk.http.auth.tunneling.disabledSchemes");
disabledTunnelingSchemes = schemesListToSet(p);
p = getNetProperty("jdk.http.auth.proxying.disabledSchemes");
disabledProxyingSchemes = schemesListToSet(p);
validateProxy = java.security.AccessController.doPrivileged(
new sun.security.action.GetBooleanAction(
"http.auth.digest.validateProxy")).booleanValue();
validateServer = java.security.AccessController.doPrivileged(
new sun.security.action.GetBooleanAction(
"http.auth.digest.validateServer")).booleanValue();
enableESBuffer = java.security.AccessController.doPrivileged(
new sun.security.action.GetBooleanAction(
"sun.net.http.errorstream.enableBuffering")).booleanValue();
timeout4ESBuffer = java.security.AccessController.doPrivileged(
new sun.security.action.GetIntegerAction(
"sun.net.http.errorstream.timeout", 300)).intValue();
if (timeout4ESBuffer <= 0) {
timeout4ESBuffer = 300; // use the default
}
bufSize4ES = java.security.AccessController.doPrivileged(
new sun.security.action.GetIntegerAction(
"sun.net.http.errorstream.bufferSize", 4096)).intValue();
if (bufSize4ES <= 0) {
bufSize4ES = 4096; // use the default
}
allowRestrictedHeaders = java.security.AccessController.doPrivileged(
new sun.security.action.GetBooleanAction(
"sun.net.http.allowRestrictedHeaders")).booleanValue();
if (!allowRestrictedHeaders) {
restrictedHeaderSet = new HashSet<String>(restrictedHeaders.length);
for (int i=0; i < restrictedHeaders.length; i++) {
restrictedHeaderSet.add(restrictedHeaders[i].toLowerCase());
}
} else {
restrictedHeaderSet = null;
}
}
static final String httpVersion = "HTTP/1.1";
static final String acceptString =
"text/html, image/gif, image/jpeg, *; q=.2, */*; q=.2";
// the following http request headers should NOT have their values
// returned for security reasons.
private static final String[] EXCLUDE_HEADERS = {
"Proxy-Authorization",
"Authorization"
};
// also exclude system cookies when any might be set
private static final String[] EXCLUDE_HEADERS2= {
"Proxy-Authorization",
"Authorization",
"Cookie",
"Cookie2"
};
protected HttpClient http;
protected Handler handler;
protected Proxy instProxy;
private CookieHandler cookieHandler;
private final ResponseCache cacheHandler;
// the cached response, and cached response headers and body
protected CacheResponse cachedResponse;
private MessageHeader cachedHeaders;
private InputStream cachedInputStream;
/* output stream to server */
protected PrintStream ps = null;
/* buffered error stream */
private InputStream errorStream = null;
/* User set Cookies */
private boolean setUserCookies = true;
private String userCookies = null;
private String userCookies2 = null;
/* We only have a single static authenticator for now.
* REMIND: backwards compatibility with JDK 1.1. Should be
* eliminated for JDK 2.0.
*/
@Deprecated
private static HttpAuthenticator defaultAuth;
/* all the headers we send
* NOTE: do *NOT* dump out the content of 'requests' in the
* output or stacktrace since it may contain security-sensitive
* headers such as those defined in EXCLUDE_HEADERS.
*/
private MessageHeader requests;
/* The headers actually set by the user are recorded here also
*/
private MessageHeader userHeaders;
/* Headers and request method cannot be changed
* once this flag is set in :-
* - getOutputStream()
* - getInputStream())
* - connect()
* Access synchronized on this.
*/
private boolean connecting = false;
/* The following two fields are only used with Digest Authentication */
String domain; /* The list of authentication domains */
DigestAuthentication.Parameters digestparams;
/* Current credentials in use */
AuthenticationInfo currentProxyCredentials = null;
AuthenticationInfo currentServerCredentials = null;
boolean needToCheck = true;
private boolean doingNTLM2ndStage = false; /* doing the 2nd stage of an NTLM server authentication */
private boolean doingNTLMp2ndStage = false; /* doing the 2nd stage of an NTLM proxy authentication */
/* try auth without calling Authenticator. Used for transparent NTLM authentication */
private boolean tryTransparentNTLMServer = true;
private boolean tryTransparentNTLMProxy = true;
private boolean useProxyResponseCode = false;
/* Used by Windows specific code */
private Object authObj;
/* Set if the user is manually setting the Authorization or Proxy-Authorization headers */
boolean isUserServerAuth;
boolean isUserProxyAuth;
String serverAuthKey, proxyAuthKey;
/* Progress source */
protected ProgressSource pi;
/* all the response headers we get back */
private MessageHeader responses;
/* the stream _from_ the server */
private InputStream inputStream = null;
/* post stream _to_ the server, if any */
private PosterOutputStream poster = null;
/* Indicates if the std. request headers have been set in requests. */
private boolean setRequests=false;
/* Indicates whether a request has already failed or not */
private boolean failedOnce=false;
/* Remembered Exception, we will throw it again if somebody
calls getInputStream after disconnect */
private Exception rememberedException = null;
/* If we decide we want to reuse a client, we put it here */
private HttpClient reuseClient = null;
/* Tunnel states */
public enum TunnelState {
/* No tunnel */
NONE,
/* Setting up a tunnel */
SETUP,
/* Tunnel has been successfully setup */
TUNNELING
}
private TunnelState tunnelState = TunnelState.NONE;
/* Redefine timeouts from java.net.URLConnection as we need -1 to mean
* not set. This is to ensure backward compatibility.
*/
private int connectTimeout = NetworkClient.DEFAULT_CONNECT_TIMEOUT;
private int readTimeout = NetworkClient.DEFAULT_READ_TIMEOUT;
/* A permission converted from a URLPermission */
private SocketPermission socketPermission;
/* Logging support */
private static final PlatformLogger logger =
PlatformLogger.getLogger("sun.net.www.protocol.http.HttpURLConnection");
/*
* privileged request password authentication
*
*/
private static PasswordAuthentication
privilegedRequestPasswordAuthentication(
final String host,
final InetAddress addr,
final int port,
final String protocol,
final String prompt,
final String scheme,
final URL url,
final RequestorType authType) {
return java.security.AccessController.doPrivileged(
new java.security.PrivilegedAction<PasswordAuthentication>() {
public PasswordAuthentication run() {
if (logger.isLoggable(PlatformLogger.Level.FINEST)) {
logger.finest("Requesting Authentication: host =" + host + " url = " + url);
}
PasswordAuthentication pass = Authenticator.requestPasswordAuthentication(
host, addr, port, protocol,
prompt, scheme, url, authType);
if (logger.isLoggable(PlatformLogger.Level.FINEST)) {
logger.finest("Authentication returned: " + (pass != null ? pass.toString() : "null"));
}
return pass;
}
});
}
private boolean isRestrictedHeader(String key, String value) {
if (allowRestrictedHeaders) {
return false;
}
key = key.toLowerCase();
if (restrictedHeaderSet.contains(key)) {
/*
* Exceptions to restricted headers:
*
* Allow "Connection: close".
*/
if (key.equals("connection") && value.equalsIgnoreCase("close")) {
return false;
}
return true;
} else if (key.startsWith("sec-")) {
return true;
}
return false;
}
/*
* Checks the validity of http message header and whether the header
* is restricted and throws IllegalArgumentException if invalid or
* restricted.
*/
private boolean isExternalMessageHeaderAllowed(String key, String value) {
checkMessageHeader(key, value);
if (!isRestrictedHeader(key, value)) {
return true;
}
return false;
}
/* Logging support */
public static PlatformLogger getHttpLogger() {
return logger;
}
/* Used for Windows NTLM implementation */
public Object authObj() {
return authObj;
}
public void authObj(Object authObj) {
this.authObj = authObj;
}
/*
* checks the validity of http message header and throws
* IllegalArgumentException if invalid.
*/
private void checkMessageHeader(String key, String value) {
char LF = '\n';
int index = key.indexOf(LF);
int index1 = key.indexOf(':');
if (index != -1 || index1 != -1) {
throw new IllegalArgumentException(
"Illegal character(s) in message header field: " + key);
}
else {
if (value == null) {
return;
}
index = value.indexOf(LF);
while (index != -1) {
index++;
if (index < value.length()) {
char c = value.charAt(index);
if ((c==' ') || (c=='\t')) {
// ok, check the next occurrence
index = value.indexOf(LF, index);
continue;
}
}
throw new IllegalArgumentException(
"Illegal character(s) in message header value: " + value);
}
}
}
public synchronized void setRequestMethod(String method)
throws ProtocolException {
if (connecting) {
throw new IllegalStateException("connect in progress");
}
super.setRequestMethod(method);
}
/* adds the standard key/val pairs to reqests if necessary & write to
* given PrintStream
*/
private void writeRequests() throws IOException {
/* print all message headers in the MessageHeader
* onto the wire - all the ones we've set and any
* others that have been set
*/
// send any pre-emptive authentication
if (http.usingProxy && tunnelState() != TunnelState.TUNNELING) {
setPreemptiveProxyAuthentication(requests);
}
if (!setRequests) {
/* We're very particular about the order in which we
* set the request headers here. The order should not
* matter, but some careless CGI programs have been
* written to expect a very particular order of the
* standard headers. To name names, the order in which
* Navigator3.0 sends them. In particular, we make *sure*
* to send Content-type: <> and Content-length:<> second
* to last and last, respectively, in the case of a POST
* request.
*/
if (!failedOnce) {
checkURLFile();
requests.prepend(method + " " + getRequestURI()+" " +
httpVersion, null);
}
if (!getUseCaches()) {
requests.setIfNotSet ("Cache-Control", "no-cache");
requests.setIfNotSet ("Pragma", "no-cache");
}
requests.setIfNotSet("User-Agent", userAgent);
int port = url.getPort();
String host = url.getHost();
if (port != -1 && port != url.getDefaultPort()) {
host += ":" + String.valueOf(port);
}
String reqHost = requests.findValue("Host");
if (reqHost == null ||
(!reqHost.equalsIgnoreCase(host) && !checkSetHost()))
{
requests.set("Host", host);
}
requests.setIfNotSet("Accept", acceptString);
/*
* For HTTP/1.1 the default behavior is to keep connections alive.
* However, we may be talking to a 1.0 server so we should set
* keep-alive just in case, except if we have encountered an error
* or if keep alive is disabled via a system property
*/
// Try keep-alive only on first attempt
if (!failedOnce && http.getHttpKeepAliveSet()) {
if (http.usingProxy && tunnelState() != TunnelState.TUNNELING) {
requests.setIfNotSet("Proxy-Connection", "keep-alive");
} else {
requests.setIfNotSet("Connection", "keep-alive");
}
} else {
/*
* RFC 2616 HTTP/1.1 section 14.10 says:
* HTTP/1.1 applications that do not support persistent
* connections MUST include the "close" connection option
* in every message
*/
requests.setIfNotSet("Connection", "close");
}
// Set modified since if necessary
long modTime = getIfModifiedSince();
if (modTime != 0 ) {
Date date = new Date(modTime);
//use the preferred date format according to RFC 2068(HTTP1.1),
// RFC 822 and RFC 1123
SimpleDateFormat fo =
new SimpleDateFormat ("EEE, dd MMM yyyy HH:mm:ss 'GMT'", Locale.US);
fo.setTimeZone(TimeZone.getTimeZone("GMT"));
requests.setIfNotSet("If-Modified-Since", fo.format(date));
}
// check for preemptive authorization
AuthenticationInfo sauth = AuthenticationInfo.getServerAuth(url);
if (sauth != null && sauth.supportsPreemptiveAuthorization() ) {
// Sets "Authorization"
requests.setIfNotSet(sauth.getHeaderName(), sauth.getHeaderValue(url,method));
currentServerCredentials = sauth;
}
if (!method.equals("PUT") && (poster != null || streaming())) {
requests.setIfNotSet ("Content-type",
"application/x-www-form-urlencoded");
}
boolean chunked = false;
if (streaming()) {
if (chunkLength != -1) {
requests.set ("Transfer-Encoding", "chunked");
chunked = true;
} else { /* fixed content length */
if (fixedContentLengthLong != -1) {
requests.set ("Content-Length",
String.valueOf(fixedContentLengthLong));
} else if (fixedContentLength != -1) {
requests.set ("Content-Length",
String.valueOf(fixedContentLength));
}
}
} else if (poster != null) {
/* add Content-Length & POST/PUT data */
synchronized (poster) {
/* close it, so no more data can be added */
poster.close();
requests.set("Content-Length",
String.valueOf(poster.size()));
}
}
if (!chunked) {
if (requests.findValue("Transfer-Encoding") != null) {
requests.remove("Transfer-Encoding");
if (logger.isLoggable(PlatformLogger.Level.WARNING)) {
logger.warning(
"use streaming mode for chunked encoding");
}
}
}
// get applicable cookies based on the uri and request headers
// add them to the existing request headers
setCookieHeader();
setRequests=true;
}
if (logger.isLoggable(PlatformLogger.Level.FINE)) {
logger.fine(requests.toString());
}
http.writeRequests(requests, poster, streaming());
if (ps.checkError()) {
String proxyHost = http.getProxyHostUsed();
int proxyPort = http.getProxyPortUsed();
disconnectInternal();
if (failedOnce) {
throw new IOException("Error writing to server");
} else { // try once more
failedOnce=true;
if (proxyHost != null) {
setProxiedClient(url, proxyHost, proxyPort);
} else {
setNewClient (url);
}
ps = (PrintStream) http.getOutputStream();
connected=true;
responses = new MessageHeader();
setRequests=false;
writeRequests();
}
}
}
private boolean checkSetHost() {
SecurityManager s = System.getSecurityManager();
if (s != null) {
String name = s.getClass().getName();
if (name.equals("sun.plugin2.applet.AWTAppletSecurityManager") ||
name.equals("sun.plugin2.applet.FXAppletSecurityManager") ||
name.equals("com.sun.javaws.security.JavaWebStartSecurity") ||
name.equals("sun.plugin.security.ActivatorSecurityManager"))
{
int CHECK_SET_HOST = -2;
try {
s.checkConnect(url.toExternalForm(), CHECK_SET_HOST);
} catch (SecurityException ex) {
return false;
}
}
}
return true;
}
private void checkURLFile() {
SecurityManager s = System.getSecurityManager();
if (s != null) {
String name = s.getClass().getName();
if (name.equals("sun.plugin2.applet.AWTAppletSecurityManager") ||
name.equals("sun.plugin2.applet.FXAppletSecurityManager") ||
name.equals("com.sun.javaws.security.JavaWebStartSecurity") ||
name.equals("sun.plugin.security.ActivatorSecurityManager"))
{
int CHECK_SUBPATH = -3;
try {
s.checkConnect(url.toExternalForm(), CHECK_SUBPATH);
} catch (SecurityException ex) {
throw new SecurityException("denied access outside a permitted URL subpath", ex);
}
}
}
}
/**
* Create a new HttpClient object, bypassing the cache of
* HTTP client objects/connections.
*
* @param url the URL being accessed
*/
protected void setNewClient (URL url)
throws IOException {
setNewClient(url, false);
}
/**
* Obtain a HttpsClient object. Use the cached copy if specified.
*
* @param url the URL being accessed
* @param useCache whether the cached connection should be used
* if present
*/
protected void setNewClient (URL url, boolean useCache)
throws IOException {
http = HttpClient.New(url, null, -1, useCache, connectTimeout, this);
http.setReadTimeout(readTimeout);
}
/**
* Create a new HttpClient object, set up so that it uses
* per-instance proxying to the given HTTP proxy. This
* bypasses the cache of HTTP client objects/connections.
*
* @param url the URL being accessed
* @param proxyHost the proxy host to use
* @param proxyPort the proxy port to use
*/
protected void setProxiedClient (URL url, String proxyHost, int proxyPort)
throws IOException {
setProxiedClient(url, proxyHost, proxyPort, false);
}
/**
* Obtain a HttpClient object, set up so that it uses per-instance
* proxying to the given HTTP proxy. Use the cached copy of HTTP
* client objects/connections if specified.
*
* @param url the URL being accessed
* @param proxyHost the proxy host to use
* @param proxyPort the proxy port to use
* @param useCache whether the cached connection should be used
* if present
*/
protected void setProxiedClient (URL url,
String proxyHost, int proxyPort,
boolean useCache)
throws IOException {
proxiedConnect(url, proxyHost, proxyPort, useCache);
}
protected void proxiedConnect(URL url,
String proxyHost, int proxyPort,
boolean useCache)
throws IOException {
http = HttpClient.New (url, proxyHost, proxyPort, useCache,
connectTimeout, this);
http.setReadTimeout(readTimeout);
}
protected HttpURLConnection(URL u, Handler handler)
throws IOException {
// we set proxy == null to distinguish this case with the case
// when per connection proxy is set
this(u, null, handler);
}
private static String checkHost(String h) throws IOException {
if (h != null) {
if (h.indexOf('\n') > -1) {
throw new MalformedURLException("Illegal character in host");
}
}
return h;
}
public HttpURLConnection(URL u, String host, int port) throws IOException {
this(u, new Proxy(Proxy.Type.HTTP,
InetSocketAddress.createUnresolved(checkHost(host), port)));
}
/** this constructor is used by other protocol handlers such as ftp
that want to use http to fetch urls on their behalf.*/
public HttpURLConnection(URL u, Proxy p) throws IOException {
this(u, p, new Handler());
}
private static URL checkURL(URL u) throws IOException {
if (u != null) {
if (u.toExternalForm().indexOf('\n') > -1) {
throw new MalformedURLException("Illegal character in URL");
}
}
String s = IPAddressUtil.checkAuthority(u);
if (s != null) {
throw new MalformedURLException(s);
}
return u;
}
protected HttpURLConnection(URL u, Proxy p, Handler handler)
throws IOException {
super(checkURL(u));
requests = new MessageHeader();
responses = new MessageHeader();
userHeaders = new MessageHeader();
this.handler = handler;
instProxy = p;
if (instProxy instanceof sun.net.ApplicationProxy) {
/* Application set Proxies should not have access to cookies
* in a secure environment unless explicitly allowed. */
try {
cookieHandler = CookieHandler.getDefault();
} catch (SecurityException se) { /* swallow exception */ }
} else {
cookieHandler = java.security.AccessController.doPrivileged(
new java.security.PrivilegedAction<CookieHandler>() {
public CookieHandler run() {
return CookieHandler.getDefault();
}
});
}
cacheHandler = java.security.AccessController.doPrivileged(
new java.security.PrivilegedAction<ResponseCache>() {
public ResponseCache run() {
return ResponseCache.getDefault();
}
});
}
/**
* @deprecated. Use java.net.Authenticator.setDefault() instead.
*/
@Deprecated
public static void setDefaultAuthenticator(HttpAuthenticator a) {
defaultAuth = a;
}
/**
* opens a stream allowing redirects only to the same host.
*/
public static InputStream openConnectionCheckRedirects(URLConnection c)
throws IOException
{
boolean redir;
int redirects = 0;
InputStream in;
do {
if (c instanceof HttpURLConnection) {
((HttpURLConnection) c).setInstanceFollowRedirects(false);
}
// We want to open the input stream before
// getting headers, because getHeaderField()
// et al swallow IOExceptions.
in = c.getInputStream();
redir = false;
if (c instanceof HttpURLConnection) {
HttpURLConnection http = (HttpURLConnection) c;
int stat = http.getResponseCode();
if (stat >= 300 && stat <= 307 && stat != 306 &&
stat != HttpURLConnection.HTTP_NOT_MODIFIED) {
URL base = http.getURL();
String loc = http.getHeaderField("Location");
URL target = null;
if (loc != null) {
target = new URL(base, loc);
}
http.disconnect();
if (target == null
|| !base.getProtocol().equals(target.getProtocol())
|| base.getPort() != target.getPort()
|| !hostsEqual(base, target)
|| redirects >= 5)
{
throw new SecurityException("illegal URL redirect");
}
redir = true;
c = target.openConnection();
redirects++;
}
}
} while (redir);
return in;
}
//
// Same as java.net.URL.hostsEqual
//
private static boolean hostsEqual(URL u1, URL u2) {
final String h1 = u1.getHost();
final String h2 = u2.getHost();
if (h1 == null) {
return h2 == null;
} else if (h2 == null) {
return false;
} else if (h1.equalsIgnoreCase(h2)) {
return true;
}
// Have to resolve addresses before comparing, otherwise
// names like tachyon and tachyon.eng would compare different
final boolean result[] = {false};
java.security.AccessController.doPrivileged(
new java.security.PrivilegedAction<Void>() {
public Void run() {
try {
InetAddress a1 = InetAddress.getByName(h1);
InetAddress a2 = InetAddress.getByName(h2);
result[0] = a1.equals(a2);
} catch(UnknownHostException | SecurityException e) {
}
return null;
}
});
return result[0];
}
// overridden in HTTPS subclass
public void connect() throws IOException {
synchronized (this) {
connecting = true;
}
plainConnect();
}
private boolean checkReuseConnection () {
if (connected) {
return true;
}
if (reuseClient != null) {
http = reuseClient;
http.setReadTimeout(getReadTimeout());
http.reuse = false;