author | jccollet |
Wed, 05 Mar 2008 17:16:14 +0100 | |
changeset 78 | 65353d0d0e31 |
parent 74 | 068494063b1b |
child 94 | 842a7d676774 |
permissions | -rw-r--r-- |
2 | 1 |
/* |
2 |
* Copyright 1995-2007 Sun Microsystems, Inc. All Rights Reserved. |
|
3 |
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. |
|
4 |
* |
|
5 |
* This code is free software; you can redistribute it and/or modify it |
|
6 |
* under the terms of the GNU General Public License version 2 only, as |
|
7 |
* published by the Free Software Foundation. Sun designates this |
|
8 |
* particular file as subject to the "Classpath" exception as provided |
|
9 |
* by Sun in the LICENSE file that accompanied this code. |
|
10 |
* |
|
11 |
* This code is distributed in the hope that it will be useful, but WITHOUT |
|
12 |
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or |
|
13 |
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License |
|
14 |
* version 2 for more details (a copy is included in the LICENSE file that |
|
15 |
* accompanied this code). |
|
16 |
* |
|
17 |
* You should have received a copy of the GNU General Public License version |
|
18 |
* 2 along with this work; if not, write to the Free Software Foundation, |
|
19 |
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. |
|
20 |
* |
|
21 |
* Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, |
|
22 |
* CA 95054 USA or visit www.sun.com if you need additional information or |
|
23 |
* have any questions. |
|
24 |
*/ |
|
25 |
||
26 |
package sun.net.www.protocol.http; |
|
27 |
||
28 |
import java.net.URL; |
|
29 |
import java.net.URLConnection; |
|
30 |
import java.net.ProtocolException; |
|
31 |
import java.net.HttpRetryException; |
|
32 |
import java.net.PasswordAuthentication; |
|
33 |
import java.net.Authenticator; |
|
34 |
import java.net.InetAddress; |
|
35 |
import java.net.UnknownHostException; |
|
36 |
import java.net.SocketTimeoutException; |
|
37 |
import java.net.Proxy; |
|
38 |
import java.net.ProxySelector; |
|
39 |
import java.net.URI; |
|
40 |
import java.net.InetSocketAddress; |
|
41 |
import java.net.CookieHandler; |
|
42 |
import java.net.ResponseCache; |
|
43 |
import java.net.CacheResponse; |
|
44 |
import java.net.SecureCacheResponse; |
|
45 |
import java.net.CacheRequest; |
|
46 |
import java.net.Authenticator.RequestorType; |
|
47 |
import java.io.*; |
|
48 |
import java.util.Date; |
|
49 |
import java.util.Map; |
|
50 |
import java.util.List; |
|
51 |
import java.util.Locale; |
|
52 |
import java.util.StringTokenizer; |
|
53 |
import java.util.Iterator; |
|
54 |
import java.util.Set; |
|
55 |
import java.util.logging.Level; |
|
56 |
import java.util.logging.Logger; |
|
57 |
import sun.net.*; |
|
58 |
import sun.net.www.*; |
|
59 |
import sun.net.www.http.HttpClient; |
|
60 |
import sun.net.www.http.PosterOutputStream; |
|
61 |
import sun.net.www.http.ChunkedInputStream; |
|
62 |
import sun.net.www.http.ChunkedOutputStream; |
|
63 |
import java.text.SimpleDateFormat; |
|
64 |
import java.util.TimeZone; |
|
65 |
import java.net.MalformedURLException; |
|
66 |
import java.nio.ByteBuffer; |
|
67 |
import java.lang.reflect.*; |
|
68 |
||
69 |
/** |
|
70 |
* A class to represent an HTTP connection to a remote object. |
|
71 |
*/ |
|
72 |
||
73 |
||
74 |
public class HttpURLConnection extends java.net.HttpURLConnection { |
|
75 |
||
76 |
private static Logger logger = Logger.getLogger("sun.net.www.protocol.http.HttpURLConnection"); |
|
77 |
||
78 |
static final String version; |
|
79 |
public static final String userAgent; |
|
80 |
||
81 |
/* max # of allowed re-directs */ |
|
82 |
static final int defaultmaxRedirects = 20; |
|
83 |
static final int maxRedirects; |
|
84 |
||
85 |
/* Not all servers support the (Proxy)-Authentication-Info headers. |
|
86 |
* By default, we don't require them to be sent |
|
87 |
*/ |
|
88 |
static final boolean validateProxy; |
|
89 |
static final boolean validateServer; |
|
90 |
||
91 |
private StreamingOutputStream strOutputStream; |
|
92 |
private final static String RETRY_MSG1 = |
|
93 |
"cannot retry due to proxy authentication, in streaming mode"; |
|
94 |
private final static String RETRY_MSG2 = |
|
95 |
"cannot retry due to server authentication, in streaming mode"; |
|
96 |
private final static String RETRY_MSG3 = |
|
97 |
"cannot retry due to redirection, in streaming mode"; |
|
98 |
||
99 |
/* |
|
100 |
* System properties related to error stream handling: |
|
101 |
* |
|
102 |
* sun.net.http.errorstream.enableBuffering = <boolean> |
|
103 |
* |
|
104 |
* With the above system property set to true (default is false), |
|
105 |
* when the response code is >=400, the HTTP handler will try to |
|
106 |
* buffer the response body (up to a certain amount and within a |
|
107 |
* time limit). Thus freeing up the underlying socket connection |
|
108 |
* for reuse. The rationale behind this is that usually when the |
|
109 |
* server responds with a >=400 error (client error or server |
|
110 |
* error, such as 404 file not found), the server will send a |
|
111 |
* small response body to explain who to contact and what to do to |
|
112 |
* recover. With this property set to true, even if the |
|
113 |
* application doesn't call getErrorStream(), read the response |
|
114 |
* body, and then call close(), the underlying socket connection |
|
115 |
* can still be kept-alive and reused. The following two system |
|
116 |
* properties provide further control to the error stream |
|
117 |
* buffering behaviour. |
|
118 |
* |
|
119 |
* sun.net.http.errorstream.timeout = <int> |
|
120 |
* the timeout (in millisec) waiting the error stream |
|
121 |
* to be buffered; default is 300 ms |
|
122 |
* |
|
123 |
* sun.net.http.errorstream.bufferSize = <int> |
|
124 |
* the size (in bytes) to use for the buffering the error stream; |
|
125 |
* default is 4k |
|
126 |
*/ |
|
127 |
||
128 |
||
129 |
/* Should we enable buffering of error streams? */ |
|
130 |
private static boolean enableESBuffer = false; |
|
131 |
||
132 |
/* timeout waiting for read for buffered error stream; |
|
133 |
*/ |
|
134 |
private static int timeout4ESBuffer = 0; |
|
135 |
||
136 |
/* buffer size for buffered error stream; |
|
137 |
*/ |
|
138 |
private static int bufSize4ES = 0; |
|
139 |
||
140 |
static { |
|
141 |
maxRedirects = java.security.AccessController.doPrivileged( |
|
142 |
new sun.security.action.GetIntegerAction("http.maxRedirects", |
|
143 |
defaultmaxRedirects)).intValue(); |
|
144 |
version = java.security.AccessController.doPrivileged( |
|
145 |
new sun.security.action.GetPropertyAction("java.version")); |
|
146 |
String agent = java.security.AccessController.doPrivileged( |
|
147 |
new sun.security.action.GetPropertyAction("http.agent")); |
|
148 |
if (agent == null) { |
|
149 |
agent = "Java/"+version; |
|
150 |
} else { |
|
151 |
agent = agent + " Java/"+version; |
|
152 |
} |
|
153 |
userAgent = agent; |
|
154 |
validateProxy = java.security.AccessController.doPrivileged( |
|
155 |
new sun.security.action.GetBooleanAction( |
|
156 |
"http.auth.digest.validateProxy")).booleanValue(); |
|
157 |
validateServer = java.security.AccessController.doPrivileged( |
|
158 |
new sun.security.action.GetBooleanAction( |
|
159 |
"http.auth.digest.validateServer")).booleanValue(); |
|
160 |
||
161 |
enableESBuffer = java.security.AccessController.doPrivileged( |
|
162 |
new sun.security.action.GetBooleanAction( |
|
163 |
"sun.net.http.errorstream.enableBuffering")).booleanValue(); |
|
164 |
timeout4ESBuffer = java.security.AccessController.doPrivileged( |
|
165 |
new sun.security.action.GetIntegerAction( |
|
166 |
"sun.net.http.errorstream.timeout", 300)).intValue(); |
|
167 |
if (timeout4ESBuffer <= 0) { |
|
168 |
timeout4ESBuffer = 300; // use the default |
|
169 |
} |
|
170 |
||
171 |
bufSize4ES = java.security.AccessController.doPrivileged( |
|
172 |
new sun.security.action.GetIntegerAction( |
|
173 |
"sun.net.http.errorstream.bufferSize", 4096)).intValue(); |
|
174 |
if (bufSize4ES <= 0) { |
|
175 |
bufSize4ES = 4096; // use the default |
|
176 |
} |
|
177 |
||
178 |
||
179 |
} |
|
180 |
||
181 |
static final String httpVersion = "HTTP/1.1"; |
|
182 |
static final String acceptString = |
|
183 |
"text/html, image/gif, image/jpeg, *; q=.2, */*; q=.2"; |
|
184 |
||
185 |
// the following http request headers should NOT have their values |
|
186 |
// returned for security reasons. |
|
187 |
private static final String[] EXCLUDE_HEADERS = { |
|
188 |
"Proxy-Authorization", |
|
189 |
"Authorization" |
|
190 |
}; |
|
191 |
protected HttpClient http; |
|
192 |
protected Handler handler; |
|
193 |
protected Proxy instProxy; |
|
194 |
||
195 |
private CookieHandler cookieHandler; |
|
196 |
private ResponseCache cacheHandler; |
|
197 |
||
198 |
// the cached response, and cached response headers and body |
|
199 |
protected CacheResponse cachedResponse; |
|
200 |
private MessageHeader cachedHeaders; |
|
201 |
private InputStream cachedInputStream; |
|
202 |
||
203 |
/* output stream to server */ |
|
204 |
protected PrintStream ps = null; |
|
205 |
||
206 |
||
207 |
/* buffered error stream */ |
|
208 |
private InputStream errorStream = null; |
|
209 |
||
210 |
/* User set Cookies */ |
|
211 |
private boolean setUserCookies = true; |
|
212 |
private String userCookies = null; |
|
213 |
||
214 |
/* We only have a single static authenticator for now. |
|
215 |
* REMIND: backwards compatibility with JDK 1.1. Should be |
|
216 |
* eliminated for JDK 2.0. |
|
217 |
*/ |
|
218 |
private static HttpAuthenticator defaultAuth; |
|
219 |
||
220 |
/* all the headers we send |
|
221 |
* NOTE: do *NOT* dump out the content of 'requests' in the |
|
222 |
* output or stacktrace since it may contain security-sensitive |
|
223 |
* headers such as those defined in EXCLUDE_HEADERS. |
|
224 |
*/ |
|
225 |
private MessageHeader requests; |
|
226 |
||
227 |
/* The following two fields are only used with Digest Authentication */ |
|
228 |
String domain; /* The list of authentication domains */ |
|
229 |
DigestAuthentication.Parameters digestparams; |
|
230 |
||
231 |
/* Current credentials in use */ |
|
232 |
AuthenticationInfo currentProxyCredentials = null; |
|
233 |
AuthenticationInfo currentServerCredentials = null; |
|
234 |
boolean needToCheck = true; |
|
235 |
private boolean doingNTLM2ndStage = false; /* doing the 2nd stage of an NTLM server authentication */ |
|
236 |
private boolean doingNTLMp2ndStage = false; /* doing the 2nd stage of an NTLM proxy authentication */ |
|
237 |
/* try auth without calling Authenticator */ |
|
238 |
private boolean tryTransparentNTLMServer = NTLMAuthentication.supportsTransparentAuth(); |
|
239 |
private boolean tryTransparentNTLMProxy = NTLMAuthentication.supportsTransparentAuth(); |
|
240 |
Object authObj; |
|
241 |
||
242 |
/* Set if the user is manually setting the Authorization or Proxy-Authorization headers */ |
|
243 |
boolean isUserServerAuth; |
|
244 |
boolean isUserProxyAuth; |
|
245 |
||
246 |
/* Progress source */ |
|
247 |
protected ProgressSource pi; |
|
248 |
||
249 |
/* all the response headers we get back */ |
|
250 |
private MessageHeader responses; |
|
251 |
/* the stream _from_ the server */ |
|
252 |
private InputStream inputStream = null; |
|
253 |
/* post stream _to_ the server, if any */ |
|
254 |
private PosterOutputStream poster = null; |
|
255 |
||
256 |
/* Indicates if the std. request headers have been set in requests. */ |
|
257 |
private boolean setRequests=false; |
|
258 |
||
259 |
/* Indicates whether a request has already failed or not */ |
|
260 |
private boolean failedOnce=false; |
|
261 |
||
262 |
/* Remembered Exception, we will throw it again if somebody |
|
263 |
calls getInputStream after disconnect */ |
|
264 |
private Exception rememberedException = null; |
|
265 |
||
266 |
/* If we decide we want to reuse a client, we put it here */ |
|
267 |
private HttpClient reuseClient = null; |
|
268 |
||
269 |
/* Redefine timeouts from java.net.URLConnection as we nee -1 to mean |
|
270 |
* not set. This is to ensure backward compatibility. |
|
271 |
*/ |
|
272 |
private int connectTimeout = -1; |
|
273 |
private int readTimeout = -1; |
|
274 |
||
275 |
/* |
|
276 |
* privileged request password authentication |
|
277 |
* |
|
278 |
*/ |
|
279 |
private static PasswordAuthentication |
|
280 |
privilegedRequestPasswordAuthentication( |
|
281 |
final String host, |
|
282 |
final InetAddress addr, |
|
283 |
final int port, |
|
284 |
final String protocol, |
|
285 |
final String prompt, |
|
286 |
final String scheme, |
|
287 |
final URL url, |
|
288 |
final RequestorType authType) { |
|
289 |
return (PasswordAuthentication) |
|
290 |
java.security.AccessController.doPrivileged( |
|
291 |
new java.security.PrivilegedAction() { |
|
292 |
public Object run() { |
|
293 |
return Authenticator.requestPasswordAuthentication( |
|
294 |
host, addr, port, protocol, |
|
295 |
prompt, scheme, url, authType); |
|
296 |
} |
|
297 |
}); |
|
298 |
} |
|
299 |
||
300 |
/* |
|
301 |
* checks the validity of http message header and throws |
|
302 |
* IllegalArgumentException if invalid. |
|
303 |
*/ |
|
304 |
private void checkMessageHeader(String key, String value) { |
|
305 |
char LF = '\n'; |
|
306 |
int index = key.indexOf(LF); |
|
307 |
if (index != -1) { |
|
308 |
throw new IllegalArgumentException( |
|
309 |
"Illegal character(s) in message header field: " + key); |
|
310 |
} |
|
311 |
else { |
|
312 |
if (value == null) { |
|
313 |
return; |
|
314 |
} |
|
315 |
||
316 |
index = value.indexOf(LF); |
|
317 |
while (index != -1) { |
|
318 |
index++; |
|
319 |
if (index < value.length()) { |
|
320 |
char c = value.charAt(index); |
|
321 |
if ((c==' ') || (c=='\t')) { |
|
322 |
// ok, check the next occurrence |
|
323 |
index = value.indexOf(LF, index); |
|
324 |
continue; |
|
325 |
} |
|
326 |
} |
|
327 |
throw new IllegalArgumentException( |
|
328 |
"Illegal character(s) in message header value: " + value); |
|
329 |
} |
|
330 |
} |
|
331 |
} |
|
332 |
||
333 |
/* adds the standard key/val pairs to reqests if necessary & write to |
|
334 |
* given PrintStream |
|
335 |
*/ |
|
336 |
private void writeRequests() throws IOException { |
|
337 |
/* print all message headers in the MessageHeader |
|
338 |
* onto the wire - all the ones we've set and any |
|
339 |
* others that have been set |
|
340 |
*/ |
|
341 |
// send any pre-emptive authentication |
|
342 |
if (http.usingProxy) { |
|
343 |
setPreemptiveProxyAuthentication(requests); |
|
344 |
} |
|
345 |
if (!setRequests) { |
|
346 |
||
347 |
/* We're very particular about the order in which we |
|
348 |
* set the request headers here. The order should not |
|
349 |
* matter, but some careless CGI programs have been |
|
350 |
* written to expect a very particular order of the |
|
351 |
* standard headers. To name names, the order in which |
|
352 |
* Navigator3.0 sends them. In particular, we make *sure* |
|
353 |
* to send Content-type: <> and Content-length:<> second |
|
354 |
* to last and last, respectively, in the case of a POST |
|
355 |
* request. |
|
356 |
*/ |
|
357 |
if (!failedOnce) |
|
358 |
requests.prepend(method + " " + http.getURLFile()+" " + |
|
359 |
httpVersion, null); |
|
360 |
if (!getUseCaches()) { |
|
361 |
requests.setIfNotSet ("Cache-Control", "no-cache"); |
|
362 |
requests.setIfNotSet ("Pragma", "no-cache"); |
|
363 |
} |
|
364 |
requests.setIfNotSet("User-Agent", userAgent); |
|
365 |
int port = url.getPort(); |
|
366 |
String host = url.getHost(); |
|
367 |
if (port != -1 && port != url.getDefaultPort()) { |
|
368 |
host += ":" + String.valueOf(port); |
|
369 |
} |
|
370 |
requests.setIfNotSet("Host", host); |
|
371 |
requests.setIfNotSet("Accept", acceptString); |
|
372 |
||
373 |
/* |
|
374 |
* For HTTP/1.1 the default behavior is to keep connections alive. |
|
375 |
* However, we may be talking to a 1.0 server so we should set |
|
376 |
* keep-alive just in case, except if we have encountered an error |
|
377 |
* or if keep alive is disabled via a system property |
|
378 |
*/ |
|
379 |
||
380 |
// Try keep-alive only on first attempt |
|
381 |
if (!failedOnce && http.getHttpKeepAliveSet()) { |
|
382 |
if (http.usingProxy) { |
|
383 |
requests.setIfNotSet("Proxy-Connection", "keep-alive"); |
|
384 |
} else { |
|
385 |
requests.setIfNotSet("Connection", "keep-alive"); |
|
386 |
} |
|
387 |
} else { |
|
388 |
/* |
|
389 |
* RFC 2616 HTTP/1.1 section 14.10 says: |
|
390 |
* HTTP/1.1 applications that do not support persistent |
|
391 |
* connections MUST include the "close" connection option |
|
392 |
* in every message |
|
393 |
*/ |
|
394 |
requests.setIfNotSet("Connection", "close"); |
|
395 |
} |
|
396 |
// Set modified since if necessary |
|
397 |
long modTime = getIfModifiedSince(); |
|
398 |
if (modTime != 0 ) { |
|
399 |
Date date = new Date(modTime); |
|
400 |
//use the preferred date format according to RFC 2068(HTTP1.1), |
|
401 |
// RFC 822 and RFC 1123 |
|
402 |
SimpleDateFormat fo = |
|
403 |
new SimpleDateFormat ("EEE, dd MMM yyyy HH:mm:ss 'GMT'", Locale.US); |
|
404 |
fo.setTimeZone(TimeZone.getTimeZone("GMT")); |
|
405 |
requests.setIfNotSet("If-Modified-Since", fo.format(date)); |
|
406 |
} |
|
407 |
// check for preemptive authorization |
|
408 |
AuthenticationInfo sauth = AuthenticationInfo.getServerAuth(url); |
|
409 |
if (sauth != null && sauth.supportsPreemptiveAuthorization() ) { |
|
410 |
// Sets "Authorization" |
|
411 |
requests.setIfNotSet(sauth.getHeaderName(), sauth.getHeaderValue(url,method)); |
|
412 |
currentServerCredentials = sauth; |
|
413 |
} |
|
414 |
||
415 |
if (!method.equals("PUT") && (poster != null || streaming())) { |
|
416 |
requests.setIfNotSet ("Content-type", |
|
417 |
"application/x-www-form-urlencoded"); |
|
418 |
} |
|
419 |
||
420 |
if (streaming()) { |
|
421 |
if (chunkLength != -1) { |
|
422 |
requests.set ("Transfer-Encoding", "chunked"); |
|
423 |
} else { |
|
424 |
requests.set ("Content-Length", String.valueOf(fixedContentLength)); |
|
425 |
} |
|
426 |
} else if (poster != null) { |
|
427 |
/* add Content-Length & POST/PUT data */ |
|
428 |
synchronized (poster) { |
|
429 |
/* close it, so no more data can be added */ |
|
430 |
poster.close(); |
|
431 |
requests.set("Content-Length", |
|
432 |
String.valueOf(poster.size())); |
|
433 |
} |
|
434 |
} |
|
435 |
||
436 |
// get applicable cookies based on the uri and request headers |
|
437 |
// add them to the existing request headers |
|
438 |
setCookieHeader(); |
|
439 |
||
440 |
setRequests=true; |
|
441 |
} |
|
442 |
if(logger.isLoggable(Level.FINEST)) { |
|
443 |
logger.fine(requests.toString()); |
|
444 |
} |
|
445 |
http.writeRequests(requests, poster); |
|
446 |
if (ps.checkError()) { |
|
447 |
String proxyHost = http.getProxyHostUsed(); |
|
448 |
int proxyPort = http.getProxyPortUsed(); |
|
449 |
disconnectInternal(); |
|
450 |
if (failedOnce) { |
|
451 |
throw new IOException("Error writing to server"); |
|
452 |
} else { // try once more |
|
453 |
failedOnce=true; |
|
454 |
if (proxyHost != null) { |
|
455 |
setProxiedClient(url, proxyHost, proxyPort); |
|
456 |
} else { |
|
457 |
setNewClient (url); |
|
458 |
} |
|
459 |
ps = (PrintStream) http.getOutputStream(); |
|
460 |
connected=true; |
|
461 |
responses = new MessageHeader(); |
|
462 |
setRequests=false; |
|
463 |
writeRequests(); |
|
464 |
} |
|
465 |
} |
|
466 |
} |
|
467 |
||
468 |
||
469 |
/** |
|
470 |
* Create a new HttpClient object, bypassing the cache of |
|
471 |
* HTTP client objects/connections. |
|
472 |
* |
|
473 |
* @param url the URL being accessed |
|
474 |
*/ |
|
475 |
protected void setNewClient (URL url) |
|
476 |
throws IOException { |
|
477 |
setNewClient(url, false); |
|
478 |
} |
|
479 |
||
480 |
/** |
|
481 |
* Obtain a HttpsClient object. Use the cached copy if specified. |
|
482 |
* |
|
483 |
* @param url the URL being accessed |
|
484 |
* @param useCache whether the cached connection should be used |
|
485 |
* if present |
|
486 |
*/ |
|
487 |
protected void setNewClient (URL url, boolean useCache) |
|
488 |
throws IOException { |
|
489 |
http = HttpClient.New(url, null, -1, useCache, connectTimeout); |
|
490 |
http.setReadTimeout(readTimeout); |
|
491 |
} |
|
492 |
||
493 |
||
494 |
/** |
|
495 |
* Create a new HttpClient object, set up so that it uses |
|
496 |
* per-instance proxying to the given HTTP proxy. This |
|
497 |
* bypasses the cache of HTTP client objects/connections. |
|
498 |
* |
|
499 |
* @param url the URL being accessed |
|
500 |
* @param proxyHost the proxy host to use |
|
501 |
* @param proxyPort the proxy port to use |
|
502 |
*/ |
|
503 |
protected void setProxiedClient (URL url, String proxyHost, int proxyPort) |
|
504 |
throws IOException { |
|
505 |
setProxiedClient(url, proxyHost, proxyPort, false); |
|
506 |
} |
|
507 |
||
508 |
/** |
|
509 |
* Obtain a HttpClient object, set up so that it uses per-instance |
|
510 |
* proxying to the given HTTP proxy. Use the cached copy of HTTP |
|
511 |
* client objects/connections if specified. |
|
512 |
* |
|
513 |
* @param url the URL being accessed |
|
514 |
* @param proxyHost the proxy host to use |
|
515 |
* @param proxyPort the proxy port to use |
|
516 |
* @param useCache whether the cached connection should be used |
|
517 |
* if present |
|
518 |
*/ |
|
519 |
protected void setProxiedClient (URL url, |
|
520 |
String proxyHost, int proxyPort, |
|
521 |
boolean useCache) |
|
522 |
throws IOException { |
|
523 |
proxiedConnect(url, proxyHost, proxyPort, useCache); |
|
524 |
} |
|
525 |
||
526 |
protected void proxiedConnect(URL url, |
|
527 |
String proxyHost, int proxyPort, |
|
528 |
boolean useCache) |
|
529 |
throws IOException { |
|
530 |
http = HttpClient.New (url, proxyHost, proxyPort, useCache, connectTimeout); |
|
531 |
http.setReadTimeout(readTimeout); |
|
532 |
} |
|
533 |
||
534 |
protected HttpURLConnection(URL u, Handler handler) |
|
535 |
throws IOException { |
|
536 |
// we set proxy == null to distinguish this case with the case |
|
537 |
// when per connection proxy is set |
|
538 |
this(u, null, handler); |
|
539 |
} |
|
540 |
||
541 |
public HttpURLConnection(URL u, String host, int port) { |
|
542 |
this(u, new Proxy(Proxy.Type.HTTP, InetSocketAddress.createUnresolved(host, port))); |
|
543 |
} |
|
544 |
||
545 |
/** this constructor is used by other protocol handlers such as ftp |
|
546 |
that want to use http to fetch urls on their behalf.*/ |
|
547 |
public HttpURLConnection(URL u, Proxy p) { |
|
548 |
this(u, p, new Handler()); |
|
549 |
} |
|
550 |
||
551 |
protected HttpURLConnection(URL u, Proxy p, Handler handler) { |
|
552 |
super(u); |
|
553 |
requests = new MessageHeader(); |
|
554 |
responses = new MessageHeader(); |
|
555 |
this.handler = handler; |
|
556 |
instProxy = p; |
|
557 |
cookieHandler = (CookieHandler)java.security.AccessController.doPrivileged( |
|
558 |
new java.security.PrivilegedAction() { |
|
559 |
public Object run() { |
|
560 |
return CookieHandler.getDefault(); |
|
561 |
} |
|
562 |
}); |
|
563 |
cacheHandler = (ResponseCache)java.security.AccessController.doPrivileged( |
|
564 |
new java.security.PrivilegedAction() { |
|
565 |
public Object run() { |
|
566 |
return ResponseCache.getDefault(); |
|
567 |
} |
|
568 |
}); |
|
569 |
} |
|
570 |
||
571 |
/** |
|
572 |
* @deprecated. Use java.net.Authenticator.setDefault() instead. |
|
573 |
*/ |
|
574 |
public static void setDefaultAuthenticator(HttpAuthenticator a) { |
|
575 |
defaultAuth = a; |
|
576 |
} |
|
577 |
||
578 |
/** |
|
579 |
* opens a stream allowing redirects only to the same host. |
|
580 |
*/ |
|
581 |
public static InputStream openConnectionCheckRedirects(URLConnection c) |
|
582 |
throws IOException |
|
583 |
{ |
|
584 |
boolean redir; |
|
585 |
int redirects = 0; |
|
586 |
InputStream in = null; |
|
587 |
||
588 |
do { |
|
589 |
if (c instanceof HttpURLConnection) { |
|
590 |
((HttpURLConnection) c).setInstanceFollowRedirects(false); |
|
591 |
} |
|
592 |
||
593 |
// We want to open the input stream before |
|
594 |
// getting headers, because getHeaderField() |
|
595 |
// et al swallow IOExceptions. |
|
596 |
in = c.getInputStream(); |
|
597 |
redir = false; |
|
598 |
||
599 |
if (c instanceof HttpURLConnection) { |
|
600 |
HttpURLConnection http = (HttpURLConnection) c; |
|
601 |
int stat = http.getResponseCode(); |
|
602 |
if (stat >= 300 && stat <= 307 && stat != 306 && |
|
603 |
stat != HttpURLConnection.HTTP_NOT_MODIFIED) { |
|
604 |
URL base = http.getURL(); |
|
605 |
String loc = http.getHeaderField("Location"); |
|
606 |
URL target = null; |
|
607 |
if (loc != null) { |
|
608 |
target = new URL(base, loc); |
|
609 |
} |
|
610 |
http.disconnect(); |
|
611 |
if (target == null |
|
612 |
|| !base.getProtocol().equals(target.getProtocol()) |
|
613 |
|| base.getPort() != target.getPort() |
|
614 |
|| !hostsEqual(base, target) |
|
615 |
|| redirects >= 5) |
|
616 |
{ |
|
617 |
throw new SecurityException("illegal URL redirect"); |
|
618 |
} |
|
619 |
redir = true; |
|
620 |
c = target.openConnection(); |
|
621 |
redirects++; |
|
622 |
} |
|
623 |
} |
|
624 |
} while (redir); |
|
625 |
return in; |
|
626 |
} |
|
627 |
||
628 |
||
629 |
// |
|
630 |
// Same as java.net.URL.hostsEqual |
|
631 |
// |
|
632 |
private static boolean hostsEqual(URL u1, URL u2) { |
|
633 |
final String h1 = u1.getHost(); |
|
634 |
final String h2 = u2.getHost(); |
|
635 |
||
636 |
if (h1 == null) { |
|
637 |
return h2 == null; |
|
638 |
} else if (h2 == null) { |
|
639 |
return false; |
|
640 |
} else if (h1.equalsIgnoreCase(h2)) { |
|
641 |
return true; |
|
642 |
} |
|
643 |
// Have to resolve addresses before comparing, otherwise |
|
644 |
// names like tachyon and tachyon.eng would compare different |
|
645 |
final boolean result[] = {false}; |
|
646 |
||
647 |
java.security.AccessController.doPrivileged( |
|
648 |
new java.security.PrivilegedAction() { |
|
649 |
public Object run() { |
|
650 |
try { |
|
651 |
InetAddress a1 = InetAddress.getByName(h1); |
|
652 |
InetAddress a2 = InetAddress.getByName(h2); |
|
653 |
result[0] = a1.equals(a2); |
|
654 |
} catch(UnknownHostException e) { |
|
655 |
} catch(SecurityException e) { |
|
656 |
} |
|
657 |
return null; |
|
658 |
} |
|
659 |
}); |
|
660 |
||
661 |
return result[0]; |
|
662 |
} |
|
663 |
||
664 |
// overridden in HTTPS subclass |
|
665 |
||
666 |
public void connect() throws IOException { |
|
667 |
plainConnect(); |
|
668 |
} |
|
669 |
||
670 |
private boolean checkReuseConnection () { |
|
671 |
if (connected) { |
|
672 |
return true; |
|
673 |
} |
|
674 |
if (reuseClient != null) { |
|
675 |
http = reuseClient; |
|
676 |
http.setReadTimeout(getReadTimeout()); |
|
677 |
http.reuse = false; |
|
678 |
reuseClient = null; |
|
679 |
connected = true; |
|
680 |
return true; |
|
681 |
} |
|
682 |
return false; |
|
683 |
} |
|
684 |
||
685 |
protected void plainConnect() throws IOException { |
|
686 |
if (connected) { |
|
687 |
return; |
|
688 |
} |
|
689 |
// try to see if request can be served from local cache |
|
690 |
if (cacheHandler != null && getUseCaches()) { |
|
691 |
try { |
|
692 |
URI uri = ParseUtil.toURI(url); |
|
693 |
if (uri != null) { |
|
694 |
cachedResponse = cacheHandler.get(uri, getRequestMethod(), requests.getHeaders(EXCLUDE_HEADERS)); |
|
695 |
if ("https".equalsIgnoreCase(uri.getScheme()) |
|
696 |
&& !(cachedResponse instanceof SecureCacheResponse)) { |
|
697 |
cachedResponse = null; |
|
698 |
} |
|
699 |
if (cachedResponse != null) { |
|
700 |
cachedHeaders = mapToMessageHeader(cachedResponse.getHeaders()); |
|
701 |
cachedInputStream = cachedResponse.getBody(); |
|
702 |
} |
|
703 |
} |
|
704 |
} catch (IOException ioex) { |
|
705 |
// ignore and commence normal connection |
|
706 |
} |
|
707 |
if (cachedHeaders != null && cachedInputStream != null) { |
|
708 |
connected = true; |
|
709 |
return; |
|
710 |
} else { |
|
711 |
cachedResponse = null; |
|
712 |
} |
|
713 |
} |
|
714 |
try { |
|
715 |
/* Try to open connections using the following scheme, |
|
716 |
* return on the first one that's successful: |
|
717 |
* 1) if (instProxy != null) |
|
718 |
* connect to instProxy; raise exception if failed |
|
719 |
* 2) else use system default ProxySelector |
|
720 |
* 3) is 2) fails, make direct connection |
|
721 |
*/ |
|
722 |
||
723 |
if (instProxy == null) { // no instance Proxy is set |
|
724 |
/** |
|
725 |
* Do we have to use a proxy? |
|
726 |
*/ |
|
727 |
ProxySelector sel = (ProxySelector) |
|
728 |
java.security.AccessController.doPrivileged( |
|
729 |
new java.security.PrivilegedAction() { |
|
730 |
public Object run() { |
|
731 |
return ProxySelector.getDefault(); |
|
732 |
} |
|
733 |
}); |
|
734 |
Proxy p = null; |
|
735 |
if (sel != null) { |
|
736 |
URI uri = sun.net.www.ParseUtil.toURI(url); |
|
737 |
Iterator<Proxy> it = sel.select(uri).iterator(); |
|
738 |
while (it.hasNext()) { |
|
739 |
p = it.next(); |
|
740 |
try { |
|
741 |
if (!failedOnce) { |
|
742 |
http = getNewHttpClient(url, p, connectTimeout); |
|
743 |
http.setReadTimeout(readTimeout); |
|
744 |
} else { |
|
745 |
// make sure to construct new connection if first |
|
746 |
// attempt failed |
|
747 |
http = getNewHttpClient(url, p, connectTimeout, false); |
|
748 |
http.setReadTimeout(readTimeout); |
|
749 |
} |
|
750 |
break; |
|
751 |
} catch (IOException ioex) { |
|
752 |
if (p != Proxy.NO_PROXY) { |
|
753 |
sel.connectFailed(uri, p.address(), ioex); |
|
754 |
if (!it.hasNext()) { |
|
755 |
// fallback to direct connection |
|
756 |
http = getNewHttpClient(url, null, connectTimeout, false); |
|
757 |
http.setReadTimeout(readTimeout); |
|
758 |
break; |
|
759 |
} |
|
760 |
} else { |
|
761 |
throw ioex; |
|
762 |
} |
|
763 |
continue; |
|
764 |
} |
|
765 |
} |
|
766 |
} else { |
|
767 |
// No proxy selector, create http client with no proxy |
|
768 |
if (!failedOnce) { |
|
769 |
http = getNewHttpClient(url, null, connectTimeout); |
|
770 |
http.setReadTimeout(readTimeout); |
|
771 |
} else { |
|
772 |
// make sure to construct new connection if first |
|
773 |
// attempt failed |
|
774 |
http = getNewHttpClient(url, null, connectTimeout, false); |
|
775 |
http.setReadTimeout(readTimeout); |
|
776 |
} |
|
777 |
} |
|
778 |
} else { |
|
779 |
if (!failedOnce) { |
|
780 |
http = getNewHttpClient(url, instProxy, connectTimeout); |
|
781 |
http.setReadTimeout(readTimeout); |
|
782 |
} else { |
|
783 |
// make sure to construct new connection if first |
|
784 |
// attempt failed |
|
785 |
http = getNewHttpClient(url, instProxy, connectTimeout, false); |
|
786 |
http.setReadTimeout(readTimeout); |
|
787 |
} |
|
788 |
} |
|
789 |
||
790 |
ps = (PrintStream)http.getOutputStream(); |
|
791 |
} catch (IOException e) { |
|
792 |
throw e; |
|
793 |
} |
|
794 |
// constructor to HTTP client calls openserver |
|
795 |
connected = true; |
|
796 |
} |
|
797 |
||
798 |
// subclass HttpsClient will overwrite & return an instance of HttpsClient |
|
799 |
protected HttpClient getNewHttpClient(URL url, Proxy p, int connectTimeout) |
|
800 |
throws IOException { |
|
801 |
return HttpClient.New(url, p, connectTimeout); |
|
802 |
} |
|
803 |
||
804 |
// subclass HttpsClient will overwrite & return an instance of HttpsClient |
|
805 |
protected HttpClient getNewHttpClient(URL url, Proxy p, |
|
806 |
int connectTimeout, boolean useCache) |
|
807 |
throws IOException { |
|
808 |
return HttpClient.New(url, p, connectTimeout, useCache); |
|
809 |
} |
|
810 |
||
811 |
/* |
|
812 |
* Allowable input/output sequences: |
|
813 |
* [interpreted as POST/PUT] |
|
814 |
* - get output, [write output,] get input, [read input] |
|
815 |
* - get output, [write output] |
|
816 |
* [interpreted as GET] |
|
817 |
* - get input, [read input] |
|
818 |
* Disallowed: |
|
819 |
* - get input, [read input,] get output, [write output] |
|
820 |
*/ |
|
821 |
||
74
068494063b1b
6641309: Wrong Cookie separator used in HttpURLConnection
jccollet
parents:
2
diff
changeset
|
822 |
@Override |
2 | 823 |
public synchronized OutputStream getOutputStream() throws IOException { |
824 |
||
825 |
try { |
|
826 |
if (!doOutput) { |
|
827 |
throw new ProtocolException("cannot write to a URLConnection" |
|
828 |
+ " if doOutput=false - call setDoOutput(true)"); |
|
829 |
} |
|
830 |
||
831 |
if (method.equals("GET")) { |
|
832 |
method = "POST"; // Backward compatibility |
|
833 |
} |
|
834 |
if (!"POST".equals(method) && !"PUT".equals(method) && |
|
835 |
"http".equals(url.getProtocol())) { |
|
836 |
throw new ProtocolException("HTTP method " + method + |
|
837 |
" doesn't support output"); |
|
838 |
} |
|
839 |
||
840 |
// if there's already an input stream open, throw an exception |
|
841 |
if (inputStream != null) { |
|
842 |
throw new ProtocolException("Cannot write output after reading input."); |
|
843 |
} |
|
844 |
||
845 |
if (!checkReuseConnection()) |
|
846 |
connect(); |
|
847 |
||
848 |
/* REMIND: This exists to fix the HttpsURLConnection subclass. |
|
849 |
* Hotjava needs to run on JDK1.1FCS. Do proper fix in subclass |
|
850 |
* for 1.2 and remove this. |
|
851 |
*/ |
|
852 |
||
853 |
if (streaming() && strOutputStream == null) { |
|
854 |
writeRequests(); |
|
855 |
} |
|
856 |
ps = (PrintStream)http.getOutputStream(); |
|
857 |
if (streaming()) { |
|
858 |
if (strOutputStream == null) { |
|
859 |
if (fixedContentLength != -1) { |
|
860 |
strOutputStream = new StreamingOutputStream (ps, fixedContentLength); |
|
861 |
} else if (chunkLength != -1) { |
|
862 |
strOutputStream = |
|
863 |
new StreamingOutputStream (new ChunkedOutputStream (ps, chunkLength), -1); |
|
864 |
} |
|
865 |
} |
|
866 |
return strOutputStream; |
|
867 |
} else { |
|
868 |
if (poster == null) { |
|
869 |
poster = new PosterOutputStream(); |
|
870 |
} |
|
871 |
return poster; |
|
872 |
} |
|
873 |
} catch (RuntimeException e) { |
|
874 |
disconnectInternal(); |
|
875 |
throw e; |
|
876 |
} catch (IOException e) { |
|
877 |
disconnectInternal(); |
|
878 |
throw e; |
|
879 |
} |
|
880 |
} |
|
881 |
||
882 |
private boolean streaming () { |
|
883 |
return (fixedContentLength != -1) || (chunkLength != -1); |
|
884 |
} |
|
885 |
||
886 |
/* |
|
887 |
* get applicable cookies based on the uri and request headers |
|
888 |
* add them to the existing request headers |
|
889 |
*/ |
|
890 |
private void setCookieHeader() throws IOException { |
|
891 |
if (cookieHandler != null) { |
|
892 |
// we only want to capture the user defined Cookies once, as |
|
893 |
// they cannot be changed by user code after we are connected, |
|
894 |
// only internally. |
|
895 |
if (setUserCookies) { |
|
896 |
int k = requests.getKey("Cookie"); |
|
897 |
if ( k != -1) |
|
898 |
userCookies = requests.getValue(k); |
|
899 |
setUserCookies = false; |
|
900 |
} |
|
901 |
||
902 |
// remove old Cookie header before setting new one. |
|
903 |
requests.remove("Cookie"); |
|
904 |
||
905 |
URI uri = ParseUtil.toURI(url); |
|
906 |
if (uri != null) { |
|
74
068494063b1b
6641309: Wrong Cookie separator used in HttpURLConnection
jccollet
parents:
2
diff
changeset
|
907 |
Map<String, List<String>> cookies = cookieHandler.get(uri, requests.getHeaders(EXCLUDE_HEADERS)); |
2 | 908 |
if (!cookies.isEmpty()) { |
74
068494063b1b
6641309: Wrong Cookie separator used in HttpURLConnection
jccollet
parents:
2
diff
changeset
|
909 |
for (Map.Entry<String, List<String>> entry : cookies.entrySet()) { |
068494063b1b
6641309: Wrong Cookie separator used in HttpURLConnection
jccollet
parents:
2
diff
changeset
|
910 |
String key = entry.getKey(); |
2 | 911 |
// ignore all entries that don't have "Cookie" |
912 |
// or "Cookie2" as keys |
|
913 |
if (!"Cookie".equalsIgnoreCase(key) && |
|
914 |
!"Cookie2".equalsIgnoreCase(key)) { |
|
915 |
continue; |
|
916 |
} |
|
74
068494063b1b
6641309: Wrong Cookie separator used in HttpURLConnection
jccollet
parents:
2
diff
changeset
|
917 |
List<String> l = entry.getValue(); |
2 | 918 |
if (l != null && !l.isEmpty()) { |
919 |
StringBuilder cookieValue = new StringBuilder(); |
|
74
068494063b1b
6641309: Wrong Cookie separator used in HttpURLConnection
jccollet
parents:
2
diff
changeset
|
920 |
for (String value : l) { |
068494063b1b
6641309: Wrong Cookie separator used in HttpURLConnection
jccollet
parents:
2
diff
changeset
|
921 |
cookieValue.append(value).append("; "); |
2 | 922 |
} |
74
068494063b1b
6641309: Wrong Cookie separator used in HttpURLConnection
jccollet
parents:
2
diff
changeset
|
923 |
// strip off the trailing '; ' |
2 | 924 |
try { |
74
068494063b1b
6641309: Wrong Cookie separator used in HttpURLConnection
jccollet
parents:
2
diff
changeset
|
925 |
requests.add(key, cookieValue.substring(0, cookieValue.length() - 2)); |
2 | 926 |
} catch (StringIndexOutOfBoundsException ignored) { |
927 |
// no-op |
|
928 |
} |
|
929 |
} |
|
930 |
} |
|
931 |
} |
|
932 |
} |
|
933 |
if (userCookies != null) { |
|
934 |
int k; |
|
935 |
if ((k = requests.getKey("Cookie")) != -1) |
|
936 |
requests.set("Cookie", requests.getValue(k) + ";" + userCookies); |
|
937 |
else |
|
938 |
requests.set("Cookie", userCookies); |
|
939 |
} |
|
940 |
||
941 |
} // end of getting cookies |
|
942 |
} |
|
943 |
||
74
068494063b1b
6641309: Wrong Cookie separator used in HttpURLConnection
jccollet
parents:
2
diff
changeset
|
944 |
@Override |
068494063b1b
6641309: Wrong Cookie separator used in HttpURLConnection
jccollet
parents:
2
diff
changeset
|
945 |
@SuppressWarnings("empty-statement") |
2 | 946 |
public synchronized InputStream getInputStream() throws IOException { |
947 |
||
948 |
if (!doInput) { |
|
949 |
throw new ProtocolException("Cannot read from URLConnection" |
|
950 |
+ " if doInput=false (call setDoInput(true))"); |
|
951 |
} |
|
952 |
||
953 |
if (rememberedException != null) { |
|
954 |
if (rememberedException instanceof RuntimeException) |
|
955 |
throw new RuntimeException(rememberedException); |
|
956 |
else { |
|
957 |
throw getChainedException((IOException)rememberedException); |
|
958 |
} |
|
959 |
} |
|
960 |
||
961 |
if (inputStream != null) { |
|
962 |
return inputStream; |
|
963 |
} |
|
964 |
||
965 |
if (streaming() ) { |
|
966 |
if (strOutputStream == null) { |
|
967 |
getOutputStream(); |
|
968 |
} |
|
969 |
/* make sure stream is closed */ |
|
970 |
strOutputStream.close (); |
|
971 |
if (!strOutputStream.writtenOK()) { |
|
972 |
throw new IOException ("Incomplete output stream"); |
|
973 |
} |
|
974 |
} |
|
975 |
||
976 |
int redirects = 0; |
|
977 |
int respCode = 0; |
|
978 |
long cl = -1; |
|
979 |
AuthenticationInfo serverAuthentication = null; |
|
980 |
AuthenticationInfo proxyAuthentication = null; |
|
981 |
AuthenticationHeader srvHdr = null; |
|
982 |
||
983 |
/** |
|
984 |
* Failed Negotiate |
|
985 |
* |
|
986 |
* In some cases, the Negotiate auth is supported for the |
|
987 |
* remote host but the negotiate process still fails (For |
|
988 |
* example, if the web page is located on a backend server |
|
989 |
* and delegation is needed but fails). The authentication |
|
990 |
* process will start again, and we need to detect this |
|
991 |
* kind of failure and do proper fallback (say, to NTLM). |
|
992 |
* |
|
993 |
* In order to achieve this, the inNegotiate flag is set |
|
994 |
* when the first negotiate challenge is met (and reset |
|
995 |
* if authentication is finished). If a fresh new negotiate |
|
996 |
* challenge (no parameter) is found while inNegotiate is |
|
997 |
* set, we know there's a failed auth attempt recently. |
|
998 |
* Here we'll ignore the header line so that fallback |
|
999 |
* can be practiced. |
|
1000 |
* |
|
1001 |
* inNegotiateProxy is for proxy authentication. |
|
1002 |
*/ |
|
1003 |
boolean inNegotiate = false; |
|
1004 |
boolean inNegotiateProxy = false; |
|
1005 |
||
1006 |
// If the user has set either of these headers then do not remove them |
|
1007 |
isUserServerAuth = requests.getKey("Authorization") != -1; |
|
1008 |
isUserProxyAuth = requests.getKey("Proxy-Authorization") != -1; |
|
1009 |
||
1010 |
try { |
|
1011 |
do { |
|
1012 |
if (!checkReuseConnection()) |
|
1013 |
connect(); |
|
1014 |
||
1015 |
if (cachedInputStream != null) { |
|
1016 |
return cachedInputStream; |
|
1017 |
} |
|
1018 |
||
1019 |
// Check if URL should be metered |
|
1020 |
boolean meteredInput = ProgressMonitor.getDefault().shouldMeterInput(url, method); |
|
1021 |
||
1022 |
if (meteredInput) { |
|
1023 |
pi = new ProgressSource(url, method); |
|
1024 |
pi.beginTracking(); |
|
1025 |
} |
|
1026 |
||
1027 |
/* REMIND: This exists to fix the HttpsURLConnection subclass. |
|
1028 |
* Hotjava needs to run on JDK1.1FCS. Do proper fix once a |
|
1029 |
* proper solution for SSL can be found. |
|
1030 |
*/ |
|
1031 |
ps = (PrintStream)http.getOutputStream(); |
|
1032 |
||
1033 |
if (!streaming()) { |
|
1034 |
writeRequests(); |
|
1035 |
} |
|
1036 |
http.parseHTTP(responses, pi, this); |
|
1037 |
if(logger.isLoggable(Level.FINEST)) { |
|
1038 |
logger.fine(responses.toString()); |
|
1039 |
} |
|
1040 |
inputStream = http.getInputStream(); |
|
1041 |
||
1042 |
respCode = getResponseCode(); |
|
1043 |
if (respCode == HTTP_PROXY_AUTH) { |
|
1044 |
if (streaming()) { |
|
1045 |
disconnectInternal(); |
|
1046 |
throw new HttpRetryException ( |
|
1047 |
RETRY_MSG1, HTTP_PROXY_AUTH); |
|
1048 |
} |
|
1049 |
||
1050 |
// Read comments labeled "Failed Negotiate" for details. |
|
1051 |
boolean dontUseNegotiate = false; |
|
1052 |
Iterator iter = responses.multiValueIterator("Proxy-Authenticate"); |
|
1053 |
while (iter.hasNext()) { |
|
1054 |
String value = ((String)iter.next()).trim(); |
|
1055 |
if (value.equalsIgnoreCase("Negotiate") || |
|
1056 |
value.equalsIgnoreCase("Kerberos")) { |
|
1057 |
if (!inNegotiateProxy) { |
|
1058 |
inNegotiateProxy = true; |
|
1059 |
} else { |
|
1060 |
dontUseNegotiate = true; |
|
1061 |
doingNTLMp2ndStage = false; |
|
1062 |
proxyAuthentication = null; |
|
1063 |
} |
|
1064 |
break; |
|
1065 |
} |
|
1066 |
} |
|
1067 |
||
1068 |
// changes: add a 3rd parameter to the constructor of |
|
1069 |
// AuthenticationHeader, so that NegotiateAuthentication. |
|
1070 |
// isSupported can be tested. |
|
1071 |
// The other 2 appearances of "new AuthenticationHeader" is |
|
1072 |
// altered in similar ways. |
|
1073 |
||
1074 |
AuthenticationHeader authhdr = new AuthenticationHeader ( |
|
1075 |
"Proxy-Authenticate", responses, |
|
1076 |
http.getProxyHostUsed(), dontUseNegotiate |
|
1077 |
); |
|
1078 |
||
1079 |
if (!doingNTLMp2ndStage) { |
|
1080 |
proxyAuthentication = |
|
1081 |
resetProxyAuthentication(proxyAuthentication, authhdr); |
|
1082 |
if (proxyAuthentication != null) { |
|
1083 |
redirects++; |
|
1084 |
disconnectInternal(); |
|
1085 |
continue; |
|
1086 |
} |
|
1087 |
} else { |
|
1088 |
/* in this case, only one header field will be present */ |
|
1089 |
String raw = responses.findValue ("Proxy-Authenticate"); |
|
1090 |
reset (); |
|
1091 |
if (!proxyAuthentication.setHeaders(this, |
|
1092 |
authhdr.headerParser(), raw)) { |
|
1093 |
disconnectInternal(); |
|
1094 |
throw new IOException ("Authentication failure"); |
|
1095 |
} |
|
1096 |
if (serverAuthentication != null && srvHdr != null && |
|
1097 |
!serverAuthentication.setHeaders(this, |
|
1098 |
srvHdr.headerParser(), raw)) { |
|
1099 |
disconnectInternal (); |
|
1100 |
throw new IOException ("Authentication failure"); |
|
1101 |
} |
|
1102 |
authObj = null; |
|
1103 |
doingNTLMp2ndStage = false; |
|
1104 |
continue; |
|
1105 |
} |
|
1106 |
} |
|
1107 |
||
1108 |
// cache proxy authentication info |
|
1109 |
if (proxyAuthentication != null) { |
|
1110 |
// cache auth info on success, domain header not relevant. |
|
1111 |
proxyAuthentication.addToCache(); |
|
1112 |
} |
|
1113 |
||
1114 |
if (respCode == HTTP_UNAUTHORIZED) { |
|
1115 |
if (streaming()) { |
|
1116 |
disconnectInternal(); |
|
1117 |
throw new HttpRetryException ( |
|
1118 |
RETRY_MSG2, HTTP_UNAUTHORIZED); |
|
1119 |
} |
|
1120 |
||
1121 |
// Read comments labeled "Failed Negotiate" for details. |
|
1122 |
boolean dontUseNegotiate = false; |
|
1123 |
Iterator iter = responses.multiValueIterator("WWW-Authenticate"); |
|
1124 |
while (iter.hasNext()) { |
|
1125 |
String value = ((String)iter.next()).trim(); |
|
1126 |
if (value.equalsIgnoreCase("Negotiate") || |
|
1127 |
value.equalsIgnoreCase("Kerberos")) { |
|
1128 |
if (!inNegotiate) { |
|
1129 |
inNegotiate = true; |
|
1130 |
} else { |
|
1131 |
dontUseNegotiate = true; |
|
1132 |
doingNTLM2ndStage = false; |
|
1133 |
serverAuthentication = null; |
|
1134 |
} |
|
1135 |
break; |
|
1136 |
} |
|
1137 |
} |
|
1138 |
||
1139 |
srvHdr = new AuthenticationHeader ( |
|
1140 |
"WWW-Authenticate", responses, |
|
1141 |
url.getHost().toLowerCase(), dontUseNegotiate |
|
1142 |
); |
|
1143 |
||
1144 |
String raw = srvHdr.raw(); |
|
1145 |
if (!doingNTLM2ndStage) { |
|
1146 |
if ((serverAuthentication != null)&& |
|
1147 |
!(serverAuthentication instanceof NTLMAuthentication)) { |
|
1148 |
if (serverAuthentication.isAuthorizationStale (raw)) { |
|
1149 |
/* we can retry with the current credentials */ |
|
1150 |
disconnectInternal(); |
|
1151 |
redirects++; |
|
1152 |
requests.set(serverAuthentication.getHeaderName(), |
|
1153 |
serverAuthentication.getHeaderValue(url, method)); |
|
1154 |
currentServerCredentials = serverAuthentication; |
|
1155 |
setCookieHeader(); |
|
1156 |
continue; |
|
1157 |
} else { |
|
1158 |
serverAuthentication.removeFromCache(); |
|
1159 |
} |
|
1160 |
} |
|
1161 |
serverAuthentication = getServerAuthentication(srvHdr); |
|
1162 |
currentServerCredentials = serverAuthentication; |
|
1163 |
||
1164 |
if (serverAuthentication != null) { |
|
1165 |
disconnectInternal(); |
|
1166 |
redirects++; // don't let things loop ad nauseum |
|
1167 |
setCookieHeader(); |
|
1168 |
continue; |
|
1169 |
} |
|
1170 |
} else { |
|
1171 |
reset (); |
|
1172 |
/* header not used for ntlm */ |
|
1173 |
if (!serverAuthentication.setHeaders(this, null, raw)) { |
|
1174 |
disconnectInternal(); |
|
1175 |
throw new IOException ("Authentication failure"); |
|
1176 |
} |
|
1177 |
doingNTLM2ndStage = false; |
|
1178 |
authObj = null; |
|
1179 |
setCookieHeader(); |
|
1180 |
continue; |
|
1181 |
} |
|
1182 |
} |
|
1183 |
// cache server authentication info |
|
1184 |
if (serverAuthentication != null) { |
|
1185 |
// cache auth info on success |
|
1186 |
if (!(serverAuthentication instanceof DigestAuthentication) || |
|
1187 |
(domain == null)) { |
|
1188 |
if (serverAuthentication instanceof BasicAuthentication) { |
|
1189 |
// check if the path is shorter than the existing entry |
|
1190 |
String npath = AuthenticationInfo.reducePath (url.getPath()); |
|
1191 |
String opath = serverAuthentication.path; |
|
1192 |
if (!opath.startsWith (npath) || npath.length() >= opath.length()) { |
|
1193 |
/* npath is longer, there must be a common root */ |
|
1194 |
npath = BasicAuthentication.getRootPath (opath, npath); |
|
1195 |
} |
|
1196 |
// remove the entry and create a new one |
|
1197 |
BasicAuthentication a = |
|
1198 |
(BasicAuthentication) serverAuthentication.clone(); |
|
1199 |
serverAuthentication.removeFromCache(); |
|
1200 |
a.path = npath; |
|
1201 |
serverAuthentication = a; |
|
1202 |
} |
|
1203 |
serverAuthentication.addToCache(); |
|
1204 |
} else { |
|
1205 |
// what we cache is based on the domain list in the request |
|
1206 |
DigestAuthentication srv = (DigestAuthentication) |
|
1207 |
serverAuthentication; |
|
1208 |
StringTokenizer tok = new StringTokenizer (domain," "); |
|
1209 |
String realm = srv.realm; |
|
1210 |
PasswordAuthentication pw = srv.pw; |
|
1211 |
digestparams = srv.params; |
|
1212 |
while (tok.hasMoreTokens()) { |
|
1213 |
String path = tok.nextToken(); |
|
1214 |
try { |
|
1215 |
/* path could be an abs_path or a complete URI */ |
|
1216 |
URL u = new URL (url, path); |
|
1217 |
DigestAuthentication d = new DigestAuthentication ( |
|
1218 |
false, u, realm, "Digest", pw, digestparams); |
|
1219 |
d.addToCache (); |
|
1220 |
} catch (Exception e) {} |
|
1221 |
} |
|
1222 |
} |
|
1223 |
} |
|
1224 |
||
1225 |
// some flags should be reset to its initialized form so that |
|
1226 |
// even after a redirect the necessary checks can still be |
|
1227 |
// preformed. |
|
1228 |
inNegotiate = false; |
|
1229 |
inNegotiateProxy = false; |
|
1230 |
||
1231 |
//serverAuthentication = null; |
|
1232 |
doingNTLMp2ndStage = false; |
|
1233 |
doingNTLM2ndStage = false; |
|
1234 |
if (!isUserServerAuth) |
|
1235 |
requests.remove("Authorization"); |
|
1236 |
if (!isUserProxyAuth) |
|
1237 |
requests.remove("Proxy-Authorization"); |
|
1238 |
||
1239 |
if (respCode == HTTP_OK) { |
|
1240 |
checkResponseCredentials (false); |
|
1241 |
} else { |
|
1242 |
needToCheck = false; |
|
1243 |
} |
|
1244 |
||
1245 |
// a flag need to clean |
|
1246 |
needToCheck = true; |
|
1247 |
||
1248 |
if (followRedirect()) { |
|
1249 |
/* if we should follow a redirect, then the followRedirects() |
|
1250 |
* method will disconnect() and re-connect us to the new |
|
1251 |
* location |
|
1252 |
*/ |
|
1253 |
redirects++; |
|
1254 |
||
1255 |
// redirecting HTTP response may have set cookie, so |
|
1256 |
// need to re-generate request header |
|
1257 |
setCookieHeader(); |
|
1258 |
||
1259 |
continue; |
|
1260 |
} |
|
1261 |
||
1262 |
try { |
|
1263 |
cl = Long.parseLong(responses.findValue("content-length")); |
|
1264 |
} catch (Exception exc) { }; |
|
1265 |
||
1266 |
if (method.equals("HEAD") || cl == 0 || |
|
1267 |
respCode == HTTP_NOT_MODIFIED || |
|
1268 |
respCode == HTTP_NO_CONTENT) { |
|
1269 |
||
1270 |
if (pi != null) { |
|
1271 |
pi.finishTracking(); |
|
1272 |
pi = null; |
|
1273 |
} |
|
1274 |
http.finished(); |
|
1275 |
http = null; |
|
1276 |
inputStream = new EmptyInputStream(); |
|
1277 |
connected = false; |
|
1278 |
} |
|
1279 |
||
1280 |
if (respCode == 200 || respCode == 203 || respCode == 206 || |
|
1281 |
respCode == 300 || respCode == 301 || respCode == 410) { |
|
1282 |
if (cacheHandler != null) { |
|
1283 |
// give cache a chance to save response in cache |
|
1284 |
URI uri = ParseUtil.toURI(url); |
|
1285 |
if (uri != null) { |
|
1286 |
URLConnection uconn = this; |
|
1287 |
if ("https".equalsIgnoreCase(uri.getScheme())) { |
|
1288 |
try { |
|
1289 |
// use reflection to get to the public |
|
1290 |
// HttpsURLConnection instance saved in |
|
1291 |
// DelegateHttpsURLConnection |
|
1292 |
uconn = (URLConnection)this.getClass().getField("httpsURLConnection").get(this); |
|
1293 |
} catch (IllegalAccessException iae) { |
|
1294 |
// ignored; use 'this' |
|
1295 |
} catch (NoSuchFieldException nsfe) { |
|
1296 |
// ignored; use 'this' |
|
1297 |
} |
|
1298 |
} |
|
1299 |
CacheRequest cacheRequest = |
|
1300 |
cacheHandler.put(uri, uconn); |
|
1301 |
if (cacheRequest != null && http != null) { |
|
1302 |
http.setCacheRequest(cacheRequest); |
|
1303 |
inputStream = new HttpInputStream(inputStream, cacheRequest); |
|
1304 |
} |
|
1305 |
} |
|
1306 |
} |
|
1307 |
} |
|
1308 |
||
1309 |
if (!(inputStream instanceof HttpInputStream)) { |
|
1310 |
inputStream = new HttpInputStream(inputStream); |
|
1311 |
} |
|
1312 |
||
1313 |
if (respCode >= 400) { |
|
1314 |
if (respCode == 404 || respCode == 410) { |
|
1315 |
throw new FileNotFoundException(url.toString()); |
|
1316 |
} else { |
|
1317 |
throw new java.io.IOException("Server returned HTTP" + |
|
1318 |
" response code: " + respCode + " for URL: " + |
|
1319 |
url.toString()); |
|
1320 |
} |
|
1321 |
} |
|
1322 |
poster = null; |
|
1323 |
strOutputStream = null; |
|
1324 |
return inputStream; |
|
1325 |
} while (redirects < maxRedirects); |
|
1326 |
||
1327 |
throw new ProtocolException("Server redirected too many " + |
|
1328 |
" times ("+ redirects + ")"); |
|
1329 |
} catch (RuntimeException e) { |
|
1330 |
disconnectInternal(); |
|
1331 |
rememberedException = e; |
|
1332 |
throw e; |
|
1333 |
} catch (IOException e) { |
|
1334 |
rememberedException = e; |
|
1335 |
||
1336 |
// buffer the error stream if bytes < 4k |
|
1337 |
// and it can be buffered within 1 second |
|
1338 |
String te = responses.findValue("Transfer-Encoding"); |
|
1339 |
if (http != null && http.isKeepingAlive() && enableESBuffer && |
|
1340 |
(cl > 0 || (te != null && te.equalsIgnoreCase("chunked")))) { |
|
1341 |
errorStream = ErrorStream.getErrorStream(inputStream, cl, http); |
|
1342 |
} |
|
1343 |
throw e; |
|
1344 |
} finally { |
|
1345 |
if (respCode == HTTP_PROXY_AUTH && proxyAuthentication != null) { |
|
1346 |
proxyAuthentication.endAuthRequest(); |
|
1347 |
} |
|
1348 |
else if (respCode == HTTP_UNAUTHORIZED && serverAuthentication != null) { |
|
1349 |
serverAuthentication.endAuthRequest(); |
|
1350 |
} |
|
1351 |
} |
|
1352 |
} |
|
1353 |
||
1354 |
/* |
|
1355 |
* Creates a chained exception that has the same type as |
|
1356 |
* original exception and with the same message. Right now, |
|
1357 |
* there is no convenient APIs for doing so. |
|
1358 |
*/ |
|
1359 |
private IOException getChainedException(IOException rememberedException) { |
|
1360 |
try { |
|
1361 |
final IOException originalException = rememberedException; |
|
1362 |
final Class[] cls = new Class[1]; |
|
1363 |
cls[0] = String.class; |
|
1364 |
final String[] args = new String[1]; |
|
1365 |
args[0] = originalException.getMessage(); |
|
1366 |
IOException chainedException = (IOException) |
|
1367 |
java.security.AccessController.doPrivileged |
|
1368 |
(new java.security.PrivilegedExceptionAction() { |
|
1369 |
public Object run() |
|
1370 |
throws Exception { |
|
1371 |
Constructor ctr = originalException.getClass().getConstructor(cls); |
|
1372 |
return (IOException)ctr.newInstance((Object[])args); |
|
1373 |
} |
|
1374 |
}); |
|
1375 |
chainedException.initCause(originalException); |
|
1376 |
return chainedException; |
|
1377 |
} catch (Exception ignored) { |
|
1378 |
return rememberedException; |
|
1379 |
} |
|
1380 |
} |
|
1381 |
||
74
068494063b1b
6641309: Wrong Cookie separator used in HttpURLConnection
jccollet
parents:
2
diff
changeset
|
1382 |
@Override |
2 | 1383 |
public InputStream getErrorStream() { |
1384 |
if (connected && responseCode >= 400) { |
|
1385 |
// Client Error 4xx and Server Error 5xx |
|
1386 |
if (errorStream != null) { |
|
1387 |
return errorStream; |
|
1388 |
} else if (inputStream != null) { |
|
1389 |
return inputStream; |
|
1390 |
} |
|
1391 |
} |
|
1392 |
return null; |
|
1393 |
} |
|
1394 |
||
1395 |
/** |
|
1396 |
* set or reset proxy authentication info in request headers |
|
1397 |
* after receiving a 407 error. In the case of NTLM however, |
|
1398 |
* receiving a 407 is normal and we just skip the stale check |
|
1399 |
* because ntlm does not support this feature. |
|
1400 |
*/ |
|
1401 |
private AuthenticationInfo |
|
1402 |
resetProxyAuthentication(AuthenticationInfo proxyAuthentication, AuthenticationHeader auth) { |
|
1403 |
if ((proxyAuthentication != null )&& ! (proxyAuthentication instanceof |
|
1404 |
NTLMAuthentication)) { |
|
1405 |
String raw = auth.raw(); |
|
1406 |
if (proxyAuthentication.isAuthorizationStale (raw)) { |
|
1407 |
/* we can retry with the current credentials */ |
|
1408 |
requests.set (proxyAuthentication.getHeaderName(), |
|
1409 |
proxyAuthentication.getHeaderValue( |
|
1410 |
url, method)); |
|
1411 |
currentProxyCredentials = proxyAuthentication; |
|
1412 |
return proxyAuthentication; |
|
1413 |
} else { |
|
1414 |
proxyAuthentication.removeFromCache(); |
|
1415 |
} |
|
1416 |
} |
|
1417 |
proxyAuthentication = getHttpProxyAuthentication(auth); |
|
1418 |
currentProxyCredentials = proxyAuthentication; |
|
1419 |
return proxyAuthentication; |
|
1420 |
} |
|
1421 |
||
1422 |
/** |
|
1423 |
* establish a tunnel through proxy server |
|
1424 |
*/ |
|
1425 |
public synchronized void doTunneling() throws IOException { |
|
1426 |
int retryTunnel = 0; |
|
1427 |
String statusLine = ""; |
|
1428 |
int respCode = 0; |
|
1429 |
AuthenticationInfo proxyAuthentication = null; |
|
1430 |
String proxyHost = null; |
|
1431 |
int proxyPort = -1; |
|
1432 |
||
1433 |
// save current requests so that they can be restored after tunnel is setup. |
|
1434 |
MessageHeader savedRequests = requests; |
|
1435 |
requests = new MessageHeader(); |
|
1436 |
||
1437 |
// Read comments labeled "Failed Negotiate" for details. |
|
1438 |
boolean inNegotiateProxy = false; |
|
1439 |
||
1440 |
try { |
|
1441 |
do { |
|
1442 |
if (!checkReuseConnection()) { |
|
1443 |
proxiedConnect(url, proxyHost, proxyPort, false); |
|
1444 |
} |
|
1445 |
// send the "CONNECT" request to establish a tunnel |
|
1446 |
// through proxy server |
|
1447 |
sendCONNECTRequest(); |
|
1448 |
responses.reset(); |
|
1449 |
||
1450 |
// There is no need to track progress in HTTP Tunneling, |
|
1451 |
// so ProgressSource is null. |
|
1452 |
http.parseHTTP(responses, null, this); |
|
1453 |
||
1454 |
statusLine = responses.getValue(0); |
|
1455 |
StringTokenizer st = new StringTokenizer(statusLine); |
|
1456 |
st.nextToken(); |
|
1457 |
respCode = Integer.parseInt(st.nextToken().trim()); |
|
1458 |
if (respCode == HTTP_PROXY_AUTH) { |
|
1459 |
// Read comments labeled "Failed Negotiate" for details. |
|
1460 |
boolean dontUseNegotiate = false; |
|
1461 |
Iterator iter = responses.multiValueIterator("Proxy-Authenticate"); |
|
1462 |
while (iter.hasNext()) { |
|
1463 |
String value = ((String)iter.next()).trim(); |
|
1464 |
if (value.equalsIgnoreCase("Negotiate") || |
|
1465 |
value.equalsIgnoreCase("Kerberos")) { |
|
1466 |
if (!inNegotiateProxy) { |
|
1467 |
inNegotiateProxy = true; |
|
1468 |
} else { |
|
1469 |
dontUseNegotiate = true; |
|
1470 |
doingNTLMp2ndStage = false; |
|
1471 |
proxyAuthentication = null; |
|
1472 |
} |
|
1473 |
break; |
|
1474 |
} |
|
1475 |
} |
|
1476 |
||
1477 |
AuthenticationHeader authhdr = new AuthenticationHeader ( |
|
1478 |
"Proxy-Authenticate", responses, |
|
1479 |
http.getProxyHostUsed(), dontUseNegotiate |
|
1480 |
); |
|
1481 |
if (!doingNTLMp2ndStage) { |
|
1482 |
proxyAuthentication = |
|
1483 |
resetProxyAuthentication(proxyAuthentication, authhdr); |
|
1484 |
if (proxyAuthentication != null) { |
|
1485 |
proxyHost = http.getProxyHostUsed(); |
|
1486 |
proxyPort = http.getProxyPortUsed(); |
|
1487 |
disconnectInternal(); |
|
1488 |
retryTunnel++; |
|
1489 |
continue; |
|
1490 |
} |
|
1491 |
} else { |
|
1492 |
String raw = responses.findValue ("Proxy-Authenticate"); |
|
1493 |
reset (); |
|
1494 |
if (!proxyAuthentication.setHeaders(this, |
|
1495 |
authhdr.headerParser(), raw)) { |
|
1496 |
proxyHost = http.getProxyHostUsed(); |
|
1497 |
proxyPort = http.getProxyPortUsed(); |
|
1498 |
disconnectInternal(); |
|
1499 |
throw new IOException ("Authentication failure"); |
|
1500 |
} |
|
1501 |
authObj = null; |
|
1502 |
doingNTLMp2ndStage = false; |
|
1503 |
continue; |
|
1504 |
} |
|
1505 |
} |
|
1506 |
// cache proxy authentication info |
|
1507 |
if (proxyAuthentication != null) { |
|
1508 |
// cache auth info on success, domain header not relevant. |
|
1509 |
proxyAuthentication.addToCache(); |
|
1510 |
} |
|
1511 |
||
1512 |
if (respCode == HTTP_OK) { |
|
1513 |
break; |
|
1514 |
} |
|
1515 |
// we don't know how to deal with other response code |
|
1516 |
// so disconnect and report error |
|
1517 |
disconnectInternal(); |
|
1518 |
break; |
|
1519 |
} while (retryTunnel < maxRedirects); |
|
1520 |
||
1521 |
if (retryTunnel >= maxRedirects || (respCode != HTTP_OK)) { |
|
1522 |
throw new IOException("Unable to tunnel through proxy."+ |
|
1523 |
" Proxy returns \"" + |
|
1524 |
statusLine + "\""); |
|
1525 |
} |
|
1526 |
} finally { |
|
1527 |
if (respCode == HTTP_PROXY_AUTH && proxyAuthentication != null) { |
|
1528 |
proxyAuthentication.endAuthRequest(); |
|
1529 |
} |
|
1530 |
} |
|
1531 |
||
1532 |
// restore original request headers |
|
1533 |
requests = savedRequests; |
|
1534 |
||
1535 |
// reset responses |
|
1536 |
responses.reset(); |
|
1537 |
} |
|
1538 |
||
1539 |
/** |
|
1540 |
* send a CONNECT request for establishing a tunnel to proxy server |
|
1541 |
*/ |
|
1542 |
private void sendCONNECTRequest() throws IOException { |
|
1543 |
int port = url.getPort(); |
|
1544 |
||
1545 |
// setRequests == true indicates the std. request headers |
|
1546 |
// have been set in (previous) requests. |
|
1547 |
// so the first one must be the http method (GET, etc.). |
|
1548 |
// we need to set it to CONNECT soon, remove this one first. |
|
1549 |
// otherwise, there may have 2 http methods in headers |
|
1550 |
if (setRequests) requests.set(0, null, null); |
|
1551 |
||
1552 |
requests.prepend("CONNECT " + url.getHost() + ":" |
|
1553 |
+ (port != -1 ? port : url.getDefaultPort()) |
|
1554 |
+ " " + httpVersion, null); |
|
1555 |
requests.setIfNotSet("User-Agent", userAgent); |
|
1556 |
||
1557 |
String host = url.getHost(); |
|
1558 |
if (port != -1 && port != url.getDefaultPort()) { |
|
1559 |
host += ":" + String.valueOf(port); |
|
1560 |
} |
|
1561 |
requests.setIfNotSet("Host", host); |
|
1562 |
||
1563 |
// Not really necessary for a tunnel, but can't hurt |
|
1564 |
requests.setIfNotSet("Accept", acceptString); |
|
1565 |
||
1566 |
setPreemptiveProxyAuthentication(requests); |
|
1567 |
http.writeRequests(requests, null); |
|
1568 |
// remove CONNECT header |
|
1569 |
requests.set(0, null, null); |
|
1570 |
} |
|
1571 |
||
1572 |
/** |
|
1573 |
* Sets pre-emptive proxy authentication in header |
|
1574 |
*/ |
|
1575 |
private void setPreemptiveProxyAuthentication(MessageHeader requests) { |
|
1576 |
AuthenticationInfo pauth |
|
1577 |
= AuthenticationInfo.getProxyAuth(http.getProxyHostUsed(), |
|
1578 |
http.getProxyPortUsed()); |
|
1579 |
if (pauth != null && pauth.supportsPreemptiveAuthorization()) { |
|
1580 |
// Sets "Proxy-authorization" |
|
1581 |
requests.set(pauth.getHeaderName(), |
|
1582 |
pauth.getHeaderValue(url,method)); |
|
1583 |
currentProxyCredentials = pauth; |
|
1584 |
} |
|
1585 |
} |
|
1586 |
||
1587 |
/** |
|
1588 |
* Gets the authentication for an HTTP proxy, and applies it to |
|
1589 |
* the connection. |
|
1590 |
*/ |
|
1591 |
private AuthenticationInfo getHttpProxyAuthentication (AuthenticationHeader authhdr) { |
|
1592 |
/* get authorization from authenticator */ |
|
1593 |
AuthenticationInfo ret = null; |
|
1594 |
String raw = authhdr.raw(); |
|
1595 |
String host = http.getProxyHostUsed(); |
|
1596 |
int port = http.getProxyPortUsed(); |
|
1597 |
if (host != null && authhdr.isPresent()) { |
|
1598 |
HeaderParser p = authhdr.headerParser(); |
|
1599 |
String realm = p.findValue("realm"); |
|
1600 |
String scheme = authhdr.scheme(); |
|
1601 |
char schemeID; |
|
1602 |
if ("basic".equalsIgnoreCase(scheme)) { |
|
1603 |
schemeID = BasicAuthentication.BASIC_AUTH; |
|
1604 |
} else if ("digest".equalsIgnoreCase(scheme)) { |
|
1605 |
schemeID = DigestAuthentication.DIGEST_AUTH; |
|
1606 |
} else if ("ntlm".equalsIgnoreCase(scheme)) { |
|
1607 |
schemeID = NTLMAuthentication.NTLM_AUTH; |
|
1608 |
doingNTLMp2ndStage = true; |
|
1609 |
} else if ("Kerberos".equalsIgnoreCase(scheme)) { |
|
1610 |
schemeID = NegotiateAuthentication.KERBEROS_AUTH; |
|
1611 |
doingNTLMp2ndStage = true; |
|
1612 |
} else if ("Negotiate".equalsIgnoreCase(scheme)) { |
|
1613 |
schemeID = NegotiateAuthentication.NEGOTIATE_AUTH; |
|
1614 |
doingNTLMp2ndStage = true; |
|
1615 |
} else { |
|
1616 |
schemeID = 0; |
|
1617 |
} |
|
1618 |
if (realm == null) |
|
1619 |
realm = ""; |
|
1620 |
ret = AuthenticationInfo.getProxyAuth(host, port, realm, schemeID); |
|
1621 |
if (ret == null) { |
|
1622 |
if (schemeID == BasicAuthentication.BASIC_AUTH) { |
|
1623 |
InetAddress addr = null; |
|
1624 |
try { |
|
1625 |
final String finalHost = host; |
|
1626 |
addr = (InetAddress) |
|
1627 |
java.security.AccessController.doPrivileged |
|
1628 |
(new java.security.PrivilegedExceptionAction() { |
|
1629 |
public Object run() |
|
1630 |
throws java.net.UnknownHostException { |
|
1631 |
return InetAddress.getByName(finalHost); |
|
1632 |
} |
|
1633 |
}); |
|
1634 |
} catch (java.security.PrivilegedActionException ignored) { |
|
1635 |
// User will have an unknown host. |
|
1636 |
} |
|
1637 |
PasswordAuthentication a = |
|
1638 |
privilegedRequestPasswordAuthentication( |
|
1639 |
host, addr, port, "http", |
|
1640 |
realm, scheme, url, RequestorType.PROXY); |
|
1641 |
if (a != null) { |
|
1642 |
ret = new BasicAuthentication(true, host, port, realm, a); |
|
1643 |
} |
|
1644 |
} else if (schemeID == DigestAuthentication.DIGEST_AUTH) { |
|
1645 |
PasswordAuthentication a = |
|
1646 |
privilegedRequestPasswordAuthentication( |
|
1647 |
host, null, port, url.getProtocol(), |
|
1648 |
realm, scheme, url, RequestorType.PROXY); |
|
1649 |
if (a != null) { |
|
1650 |
DigestAuthentication.Parameters params = |
|
1651 |
new DigestAuthentication.Parameters(); |
|
1652 |
ret = new DigestAuthentication(true, host, port, realm, |
|
1653 |
scheme, a, params); |
|
1654 |
} |
|
1655 |
} else if (schemeID == NTLMAuthentication.NTLM_AUTH) { |
|
1656 |
PasswordAuthentication a = null; |
|
1657 |
if (!tryTransparentNTLMProxy) { |
|
1658 |
a = privilegedRequestPasswordAuthentication( |
|
1659 |
host, null, port, url.getProtocol(), |
|
1660 |
"", scheme, url, RequestorType.PROXY); |
|
1661 |
} |
|
1662 |
/* If we are not trying transparent authentication then |
|
1663 |
* we need to have a PasswordAuthentication instance. For |
|
1664 |
* transparent authentication (Windows only) the username |
|
1665 |
* and password will be picked up from the current logged |
|
1666 |
* on users credentials. |
|
1667 |
*/ |
|
1668 |
if (tryTransparentNTLMProxy || |
|
1669 |
(!tryTransparentNTLMProxy && a != null)) { |
|
1670 |
ret = new NTLMAuthentication(true, host, port, a); |
|
1671 |
} |
|
1672 |
||
1673 |
tryTransparentNTLMProxy = false; |
|
1674 |
} else if (schemeID == NegotiateAuthentication.NEGOTIATE_AUTH) { |
|
1675 |
ret = new NegotiateAuthentication(true, host, port, null, "Negotiate"); |
|
1676 |
} else if (schemeID == NegotiateAuthentication.KERBEROS_AUTH) { |
|
1677 |
ret = new NegotiateAuthentication(true, host, port, null, "Kerberos"); |
|
1678 |
} |
|
1679 |
} |
|
1680 |
// For backwards compatibility, we also try defaultAuth |
|
1681 |
// REMIND: Get rid of this for JDK2.0. |
|
1682 |
||
1683 |
if (ret == null && defaultAuth != null |
|
1684 |
&& defaultAuth.schemeSupported(scheme)) { |
|
1685 |
try { |
|
1686 |
URL u = new URL("http", host, port, "/"); |
|
1687 |
String a = defaultAuth.authString(u, scheme, realm); |
|
1688 |
if (a != null) { |
|
1689 |
ret = new BasicAuthentication (true, host, port, realm, a); |
|
1690 |
// not in cache by default - cache on success |
|
1691 |
} |
|
1692 |
} catch (java.net.MalformedURLException ignored) { |
|
1693 |
} |
|
1694 |
} |
|
1695 |
if (ret != null) { |
|
1696 |
if (!ret.setHeaders(this, p, raw)) { |
|
1697 |
ret = null; |
|
1698 |
} |
|
1699 |
} |
|
1700 |
} |
|
1701 |
return ret; |
|
1702 |
} |
|
1703 |
||
1704 |
/** |
|
1705 |
* Gets the authentication for an HTTP server, and applies it to |
|
1706 |
* the connection. |
|
1707 |
* @param authHdr the AuthenticationHeader which tells what auth scheme is |
|
1708 |
* prefered. |
|
1709 |
*/ |
|
1710 |
private AuthenticationInfo getServerAuthentication (AuthenticationHeader authhdr) { |
|
1711 |
/* get authorization from authenticator */ |
|
1712 |
AuthenticationInfo ret = null; |
|
1713 |
String raw = authhdr.raw(); |
|
1714 |
/* When we get an NTLM auth from cache, don't set any special headers */ |
|
1715 |
if (authhdr.isPresent()) { |
|
1716 |
HeaderParser p = authhdr.headerParser(); |
|
1717 |
String realm = p.findValue("realm"); |
|
1718 |
String scheme = authhdr.scheme(); |
|
1719 |
char schemeID; |
|
1720 |
if ("basic".equalsIgnoreCase(scheme)) { |
|
1721 |
schemeID = BasicAuthentication.BASIC_AUTH; |
|
1722 |
} else if ("digest".equalsIgnoreCase(scheme)) { |
|
1723 |
schemeID = DigestAuthentication.DIGEST_AUTH; |
|
1724 |
} else if ("ntlm".equalsIgnoreCase(scheme)) { |
|
1725 |
schemeID = NTLMAuthentication.NTLM_AUTH; |
|
1726 |
doingNTLM2ndStage = true; |
|
1727 |
} else if ("Kerberos".equalsIgnoreCase(scheme)) { |
|
1728 |
schemeID = NegotiateAuthentication.KERBEROS_AUTH; |
|
1729 |
doingNTLM2ndStage = true; |
|
1730 |
} else if ("Negotiate".equalsIgnoreCase(scheme)) { |
|
1731 |
schemeID = NegotiateAuthentication.NEGOTIATE_AUTH; |
|
1732 |
doingNTLM2ndStage = true; |
|
1733 |
} else { |
|
1734 |
schemeID = 0; |
|
1735 |
} |
|
1736 |
domain = p.findValue ("domain"); |
|
1737 |
if (realm == null) |
|
1738 |
realm = ""; |
|
1739 |
ret = AuthenticationInfo.getServerAuth(url, realm, schemeID); |
|
1740 |
InetAddress addr = null; |
|
1741 |
if (ret == null) { |
|
1742 |
try { |
|
1743 |
addr = InetAddress.getByName(url.getHost()); |
|
1744 |
} catch (java.net.UnknownHostException ignored) { |
|
1745 |
// User will have addr = null |
|
1746 |
} |
|
1747 |
} |
|
1748 |
// replacing -1 with default port for a protocol |
|
1749 |
int port = url.getPort(); |
|
1750 |
if (port == -1) { |
|
1751 |
port = url.getDefaultPort(); |
|
1752 |
} |
|
1753 |
if (ret == null) { |
|
1754 |
if (schemeID == NegotiateAuthentication.KERBEROS_AUTH) { |
|
1755 |
URL url1; |
|
1756 |
try { |
|
1757 |
url1 = new URL (url, "/"); /* truncate the path */ |
|
1758 |
} catch (Exception e) { |
|
1759 |
url1 = url; |
|
1760 |
} |
|
1761 |
ret = new NegotiateAuthentication(false, url1, null, "Kerberos"); |
|
1762 |
} |
|
1763 |
if (schemeID == NegotiateAuthentication.NEGOTIATE_AUTH) { |
|
1764 |
URL url1; |
|
1765 |
try { |
|
1766 |
url1 = new URL (url, "/"); /* truncate the path */ |
|
1767 |
} catch (Exception e) { |
|
1768 |
url1 = url; |
|
1769 |
} |
|
1770 |
ret = new NegotiateAuthentication(false, url1, null, "Negotiate"); |
|
1771 |
} |
|
1772 |
if (schemeID == BasicAuthentication.BASIC_AUTH) { |
|
1773 |
PasswordAuthentication a = |
|
1774 |
privilegedRequestPasswordAuthentication( |
|
1775 |
url.getHost(), addr, port, url.getProtocol(), |
|
1776 |
realm, scheme, url, RequestorType.SERVER); |
|
1777 |
if (a != null) { |
|
1778 |
ret = new BasicAuthentication(false, url, realm, a); |
|
1779 |
} |
|
1780 |
} |
|
1781 |
||
1782 |
if (schemeID == DigestAuthentication.DIGEST_AUTH) { |
|
1783 |
PasswordAuthentication a = |
|
1784 |
privilegedRequestPasswordAuthentication( |
|
1785 |
url.getHost(), addr, port, url.getProtocol(), |
|
1786 |
realm, scheme, url, RequestorType.SERVER); |
|
1787 |
if (a != null) { |
|
1788 |
digestparams = new DigestAuthentication.Parameters(); |
|
1789 |
ret = new DigestAuthentication(false, url, realm, scheme, a, digestparams); |
|
1790 |
} |
|
1791 |
} |
|
1792 |
||
1793 |
if (schemeID == NTLMAuthentication.NTLM_AUTH) { |
|
1794 |
URL url1; |
|
1795 |
try { |
|
1796 |
url1 = new URL (url, "/"); /* truncate the path */ |
|
1797 |
} catch (Exception e) { |
|
1798 |
url1 = url; |
|
1799 |
} |
|
1800 |
PasswordAuthentication a = null; |
|
1801 |
if (!tryTransparentNTLMServer) { |
|
1802 |
a = privilegedRequestPasswordAuthentication( |
|
1803 |
url.getHost(), addr, port, url.getProtocol(), |
|
1804 |
"", scheme, url, RequestorType.SERVER); |
|
1805 |
} |
|
1806 |
||
1807 |
/* If we are not trying transparent authentication then |
|
1808 |
* we need to have a PasswordAuthentication instance. For |
|
1809 |
* transparent authentication (Windows only) the username |
|
1810 |
* and password will be picked up from the current logged |
|
1811 |
* on users credentials. |
|
1812 |
*/ |
|
1813 |
if (tryTransparentNTLMServer || |
|
1814 |
(!tryTransparentNTLMServer && a != null)) { |
|
1815 |
ret = new NTLMAuthentication(false, url1, a); |
|
1816 |
} |
|
1817 |
||
1818 |
tryTransparentNTLMServer = false; |
|
1819 |
} |
|
1820 |
} |
|
1821 |
||
1822 |
// For backwards compatibility, we also try defaultAuth |
|
1823 |
// REMIND: Get rid of this for JDK2.0. |
|
1824 |
||
1825 |
if (ret == null && defaultAuth != null |
|
1826 |
&& defaultAuth.schemeSupported(scheme)) { |
|
1827 |
String a = defaultAuth.authString(url, scheme, realm); |
|
1828 |
if (a != null) { |
|
1829 |
ret = new BasicAuthentication (false, url, realm, a); |
|
1830 |
// not in cache by default - cache on success |
|
1831 |
} |
|
1832 |
} |
|
1833 |
||
1834 |
if (ret != null ) { |
|
1835 |
if (!ret.setHeaders(this, p, raw)) { |
|
1836 |
ret = null; |
|
1837 |
} |
|
1838 |
} |
|
1839 |
} |
|
1840 |
return ret; |
|
1841 |
} |
|
1842 |
||
1843 |
/* inclose will be true if called from close(), in which case we |
|
1844 |
* force the call to check because this is the last chance to do so. |
|
1845 |
* If not in close(), then the authentication info could arrive in a trailer |
|
1846 |
* field, which we have not read yet. |
|
1847 |
*/ |
|
1848 |
private void checkResponseCredentials (boolean inClose) throws IOException { |
|
1849 |
try { |
|
1850 |
if (!needToCheck) |
|
1851 |
return; |
|
1852 |
if (validateProxy && currentProxyCredentials != null) { |
|
1853 |
String raw = responses.findValue ("Proxy-Authentication-Info"); |
|
1854 |
if (inClose || (raw != null)) { |
|
1855 |
currentProxyCredentials.checkResponse (raw, method, url); |
|
1856 |
currentProxyCredentials = null; |
|
1857 |
} |
|
1858 |
} |
|
1859 |
if (validateServer && currentServerCredentials != null) { |
|
1860 |
String raw = responses.findValue ("Authentication-Info"); |
|
1861 |
if (inClose || (raw != null)) { |
|
1862 |
currentServerCredentials.checkResponse (raw, method, url); |
|
1863 |
currentServerCredentials = null; |
|
1864 |
} |
|
1865 |
} |
|
1866 |
if ((currentServerCredentials==null) && (currentProxyCredentials == null)) { |
|
1867 |
needToCheck = false; |
|
1868 |
} |
|
1869 |
} catch (IOException e) { |
|
1870 |
disconnectInternal(); |
|
1871 |
connected = false; |
|
1872 |
throw e; |
|
1873 |
} |
|
1874 |
} |
|
1875 |
||
1876 |
/* Tells us whether to follow a redirect. If so, it |
|
1877 |
* closes the connection (break any keep-alive) and |
|
1878 |
* resets the url, re-connects, and resets the request |
|
1879 |
* property. |
|
1880 |
*/ |
|
1881 |
private boolean followRedirect() throws IOException { |
|
1882 |
if (!getInstanceFollowRedirects()) { |
|
1883 |
return false; |
|
1884 |
} |
|
1885 |
||
1886 |
int stat = getResponseCode(); |
|
1887 |
if (stat < 300 || stat > 307 || stat == 306 |
|
1888 |
|| stat == HTTP_NOT_MODIFIED) { |
|
1889 |
return false; |
|
1890 |
} |
|
1891 |
String loc = getHeaderField("Location"); |
|
1892 |
if (loc == null) { |
|
1893 |
/* this should be present - if not, we have no choice |
|
1894 |
* but to go forward w/ the response we got |
|
1895 |
*/ |
|
1896 |
return false; |
|
1897 |
} |
|
1898 |
URL locUrl; |
|
1899 |
try { |
|
1900 |
locUrl = new URL(loc); |
|
1901 |
if (!url.getProtocol().equalsIgnoreCase(locUrl.getProtocol())) { |
|
1902 |
return false; |
|
1903 |
} |
|
1904 |
||
1905 |
} catch (MalformedURLException mue) { |
|
1906 |
// treat loc as a relative URI to conform to popular browsers |
|
1907 |
locUrl = new URL(url, loc); |
|
1908 |
} |
|
1909 |
disconnectInternal(); |
|
1910 |
if (streaming()) { |
|
1911 |
throw new HttpRetryException (RETRY_MSG3, stat, loc); |
|
1912 |
} |
|
1913 |
||
1914 |
// clear out old response headers!!!! |
|
1915 |
responses = new MessageHeader(); |
|
1916 |
if (stat == HTTP_USE_PROXY) { |
|
1917 |
/* This means we must re-request the resource through the |
|
1918 |
* proxy denoted in the "Location:" field of the response. |
|
1919 |
* Judging by the spec, the string in the Location header |
|
1920 |
* _should_ denote a URL - let's hope for "http://my.proxy.org" |
|
1921 |
* Make a new HttpClient to the proxy, using HttpClient's |
|
1922 |
* Instance-specific proxy fields, but note we're still fetching |
|
1923 |
* the same URL. |
|
1924 |
*/ |
|
1925 |
String proxyHost = locUrl.getHost(); |
|
1926 |
int proxyPort = locUrl.getPort(); |
|
1927 |
||
1928 |
SecurityManager security = System.getSecurityManager(); |
|
1929 |
if (security != null) { |
|
1930 |
security.checkConnect(proxyHost, proxyPort); |
|
1931 |
} |
|
1932 |
||
1933 |
setProxiedClient (url, proxyHost, proxyPort); |
|
1934 |
requests.set(0, method + " " + http.getURLFile()+" " + |
|
1935 |
httpVersion, null); |
|
1936 |
connected = true; |
|
1937 |
} else { |
|
1938 |
// maintain previous headers, just change the name |
|
1939 |
// of the file we're getting |
|
1940 |
url = locUrl; |
|
1941 |
if (method.equals("POST") && !Boolean.getBoolean("http.strictPostRedirect") && (stat!=307)) { |
|
1942 |
/* The HTTP/1.1 spec says that a redirect from a POST |
|
1943 |
* *should not* be immediately turned into a GET, and |
|
1944 |
* that some HTTP/1.0 clients incorrectly did this. |
|
1945 |
* Correct behavior redirects a POST to another POST. |
|
1946 |
* Unfortunately, since most browsers have this incorrect |
|
1947 |
* behavior, the web works this way now. Typical usage |
|
1948 |
* seems to be: |
|
1949 |
* POST a login code or passwd to a web page. |
|
1950 |
* after validation, the server redirects to another |
|
1951 |
* (welcome) page |
|
1952 |
* The second request is (erroneously) expected to be GET |
|
1953 |
* |
|
1954 |
* We will do the incorrect thing (POST-->GET) by default. |
|
1955 |
* We will provide the capability to do the "right" thing |
|
1956 |
* (POST-->POST) by a system property, "http.strictPostRedirect=true" |
|
1957 |
*/ |
|
1958 |
||
1959 |
requests = new MessageHeader(); |
|
1960 |
setRequests = false; |
|
1961 |
setRequestMethod("GET"); |
|
1962 |
poster = null; |
|
1963 |
if (!checkReuseConnection()) |
|
1964 |
connect(); |
|
1965 |
} else { |
|
1966 |
if (!checkReuseConnection()) |
|
1967 |
connect(); |
|
1968 |
/* Even after a connect() call, http variable still can be |
|
1969 |
* null, if a ResponseCache has been installed and it returns |
|
1970 |
* a non-null CacheResponse instance. So check nullity before using it. |
|
1971 |
* |
|
1972 |
* And further, if http is null, there's no need to do anything |
|
1973 |
* about request headers because successive http session will use |
|
1974 |
* cachedInputStream/cachedHeaders anyway, which is returned by |
|
1975 |
* CacheResponse. |
|
1976 |
*/ |
|
1977 |
if (http != null) { |
|
1978 |
requests.set(0, method + " " + http.getURLFile()+" " + |
|
1979 |
httpVersion, null); |
|
1980 |
int port = url.getPort(); |
|
1981 |
String host = url.getHost(); |
|
1982 |
if (port != -1 && port != url.getDefaultPort()) { |
|
1983 |
host += ":" + String.valueOf(port); |
|
1984 |
} |
|
1985 |
requests.set("Host", host); |
|
1986 |
} |
|
1987 |
} |
|
1988 |
} |
|
1989 |
return true; |
|
1990 |
} |
|
1991 |
||
1992 |
/* dummy byte buffer for reading off socket prior to closing */ |
|
1993 |
byte[] cdata = new byte [128]; |
|
1994 |
||
1995 |
/** |
|
1996 |
* Reset (without disconnecting the TCP conn) in order to do another transaction with this instance |
|
1997 |
*/ |
|
1998 |
private void reset() throws IOException { |
|
1999 |
http.reuse = true; |
|
2000 |
/* must save before calling close */ |
|
2001 |
reuseClient = http; |
|
2002 |
InputStream is = http.getInputStream(); |
|
2003 |
if (!method.equals("HEAD")) { |
|
2004 |
try { |
|
2005 |
/* we want to read the rest of the response without using the |
|
2006 |
* hurry mechanism, because that would close the connection |
|
2007 |
* if everything is not available immediately |
|
2008 |
*/ |
|
2009 |
if ((is instanceof ChunkedInputStream) || |
|
2010 |
(is instanceof MeteredStream)) { |
|
2011 |
/* reading until eof will not block */ |
|
2012 |
while (is.read (cdata) > 0) {} |
|
2013 |
} else { |
|
2014 |
/* raw stream, which will block on read, so only read |
|
2015 |
* the expected number of bytes, probably 0 |
|
2016 |
*/ |
|
2017 |
int cl = 0, n=0; |
|
2018 |
try { |
|
2019 |
cl = Integer.parseInt (responses.findValue ("Content-Length")); |
|
2020 |
} catch (Exception e) {} |
|
2021 |
for (int i=0; i<cl; ) { |
|
2022 |
if ((n = is.read (cdata)) == -1) { |
|
2023 |
break; |
|
2024 |
} else { |
|
2025 |
i+= n; |
|
2026 |
} |
|
2027 |
} |
|
2028 |
} |
|
2029 |
} catch (IOException e) { |
|
2030 |
http.reuse = false; |
|
2031 |
reuseClient = null; |
|
2032 |
disconnectInternal(); |
|
2033 |
return; |
|
2034 |
} |
|
2035 |
try { |
|
2036 |
if (is instanceof MeteredStream) { |
|
2037 |
is.close(); |
|
2038 |
} |
|
2039 |
} catch (IOException e) { } |
|
2040 |
} |
|
2041 |
responseCode = -1; |
|
2042 |
responses = new MessageHeader(); |
|
2043 |
connected = false; |
|
2044 |
} |
|
2045 |
||
2046 |
/** |
|
2047 |
* Disconnect from the server (for internal use) |
|
2048 |
*/ |
|
2049 |
private void disconnectInternal() { |
|
2050 |
responseCode = -1; |
|
78
65353d0d0e31
6660405: HttpURLConnection returns the wrong InputStream
jccollet
parents:
74
diff
changeset
|
2051 |
inputStream = null; |
2 | 2052 |
if (pi != null) { |
2053 |
pi.finishTracking(); |
|
2054 |
pi = null; |
|
2055 |
} |
|
2056 |
if (http != null) { |
|
2057 |
http.closeServer(); |
|
2058 |
http = null; |
|
2059 |
connected = false; |
|
2060 |
} |
|
2061 |
} |
|
2062 |
||
2063 |
/** |
|
2064 |
* Disconnect from the server (public API) |
|
2065 |
*/ |
|
2066 |
public void disconnect() { |
|
2067 |
||
2068 |
responseCode = -1; |
|
2069 |
if (pi != null) { |
|
2070 |
pi.finishTracking(); |
|
2071 |
pi = null; |
|
2072 |
} |
|
2073 |
||
2074 |
if (http != null) { |
|
2075 |
/* |
|
2076 |
* If we have an input stream this means we received a response |
|
2077 |
* from the server. That stream may have been read to EOF and |
|
2078 |
* dependening on the stream type may already be closed or the |
|
2079 |
* the http client may be returned to the keep-alive cache. |
|
2080 |
* If the http client has been returned to the keep-alive cache |
|
2081 |
* it may be closed (idle timeout) or may be allocated to |
|
2082 |
* another request. |
|
2083 |
* |
|
2084 |
* In other to avoid timing issues we close the input stream |
|
2085 |
* which will either close the underlying connection or return |
|
2086 |
* the client to the cache. If there's a possibility that the |
|
2087 |
* client has been returned to the cache (ie: stream is a keep |
|
2088 |
* alive stream or a chunked input stream) then we remove an |
|
2089 |
* idle connection to the server. Note that this approach |
|
2090 |
* can be considered an approximation in that we may close a |
|
2091 |
* different idle connection to that used by the request. |
|
2092 |
* Additionally it's possible that we close two connections |
|
2093 |
* - the first becuase it wasn't an EOF (and couldn't be |
|
2094 |
* hurried) - the second, another idle connection to the |
|
2095 |
* same server. The is okay because "disconnect" is an |
|
2096 |
* indication that the application doesn't intend to access |
|
2097 |
* this http server for a while. |
|
2098 |
*/ |
|
2099 |
||
2100 |
if (inputStream != null) { |
|
2101 |
HttpClient hc = http; |
|
2102 |
||
2103 |
// un-synchronized |
|
2104 |
boolean ka = hc.isKeepingAlive(); |
|
2105 |
||
2106 |
try { |
|
2107 |
inputStream.close(); |
|
2108 |
} catch (IOException ioe) { } |
|
2109 |
||
2110 |
// if the connection is persistent it may have been closed |
|
2111 |
// or returned to the keep-alive cache. If it's been returned |
|
2112 |
// to the keep-alive cache then we would like to close it |
|
2113 |
// but it may have been allocated |
|
2114 |
||
2115 |
if (ka) { |
|
2116 |
hc.closeIdleConnection(); |
|
2117 |
} |
|
2118 |
||
2119 |
||
2120 |
} else { |
|
2121 |
// We are deliberatly being disconnected so HttpClient |
|
2122 |
// should not try to resend the request no matter what stage |
|
2123 |
// of the connection we are in. |
|
2124 |
http.setDoNotRetry(true); |
|
2125 |
||
2126 |
http.closeServer(); |
|
2127 |
} |
|
2128 |
||
2129 |
// poster = null; |
|
2130 |
http = null; |
|
2131 |
connected = false; |
|
2132 |
} |
|
2133 |
cachedInputStream = null; |
|
2134 |
if (cachedHeaders != null) { |
|
2135 |
cachedHeaders.reset(); |
|
2136 |
} |
|
2137 |
} |
|
2138 |
||
2139 |
public boolean usingProxy() { |
|
2140 |
if (http != null) { |
|
2141 |
return (http.getProxyHostUsed() != null); |
|
2142 |
} |
|
2143 |
return false; |
|
2144 |
} |
|
2145 |
||
2146 |
/** |
|
2147 |
* Gets a header field by name. Returns null if not known. |
|
2148 |
* @param name the name of the header field |
|
2149 |
*/ |
|
74
068494063b1b
6641309: Wrong Cookie separator used in HttpURLConnection
jccollet
parents:
2
diff
changeset
|
2150 |
@Override |
2 | 2151 |
public String getHeaderField(String name) { |
2152 |
try { |
|
2153 |
getInputStream(); |
|
2154 |
} catch (IOException e) {} |
|
2155 |
||
2156 |
if (cachedHeaders != null) { |
|
2157 |
return cachedHeaders.findValue(name); |
|
2158 |
} |
|
2159 |
||
2160 |
return responses.findValue(name); |
|
2161 |
} |
|
2162 |
||
2163 |
/** |
|
2164 |
* Returns an unmodifiable Map of the header fields. |
|
2165 |
* The Map keys are Strings that represent the |
|
2166 |
* response-header field names. Each Map value is an |
|
2167 |
* unmodifiable List of Strings that represents |
|
2168 |
* the corresponding field values. |
|
2169 |
* |
|
2170 |
* @return a Map of header fields |
|
2171 |
* @since 1.4 |
|
2172 |
*/ |
|
74
068494063b1b
6641309: Wrong Cookie separator used in HttpURLConnection
jccollet
parents:
2
diff
changeset
|
2173 |
@Override |
2 | 2174 |
public Map getHeaderFields() { |
2175 |
try { |
|
2176 |
getInputStream(); |
|
2177 |
} catch (IOException e) {} |
|
2178 |
||
2179 |
if (cachedHeaders != null) { |
|
2180 |
return cachedHeaders.getHeaders(); |
|
2181 |
} |
|
2182 |
||
2183 |
return responses.getHeaders(); |
|
2184 |
} |
|
2185 |
||
2186 |
/** |
|
2187 |
* Gets a header field by index. Returns null if not known. |
|
2188 |
* @param n the index of the header field |
|
2189 |
*/ |
|
74
068494063b1b
6641309: Wrong Cookie separator used in HttpURLConnection
jccollet
parents:
2
diff
changeset
|
2190 |
@Override |
2 | 2191 |
public String getHeaderField(int n) { |
2192 |
try { |
|
2193 |
getInputStream(); |
|
2194 |
} catch (IOException e) {} |
|
2195 |
||
2196 |
if (cachedHeaders != null) { |
|
2197 |
return cachedHeaders.getValue(n); |
|
2198 |
} |
|
2199 |
return responses.getValue(n); |
|
2200 |
} |
|
2201 |
||
2202 |
/** |
|
2203 |
* Gets a header field by index. Returns null if not known. |
|
2204 |
* @param n the index of the header field |
|
2205 |
*/ |
|
74
068494063b1b
6641309: Wrong Cookie separator used in HttpURLConnection
jccollet
parents:
2
diff
changeset
|
2206 |
@Override |
2 | 2207 |
public String getHeaderFieldKey(int n) { |
2208 |
try { |
|
2209 |
getInputStream(); |
|
2210 |
} catch (IOException e) {} |
|
2211 |
||
2212 |
if (cachedHeaders != null) { |
|
2213 |
return cachedHeaders.getKey(n); |
|
2214 |
} |
|
2215 |
||
2216 |
return responses.getKey(n); |
|
2217 |
} |
|
2218 |
||
2219 |
/** |
|
2220 |
* Sets request property. If a property with the key already |
|
2221 |
* exists, overwrite its value with the new value. |
|
2222 |
* @param value the value to be set |
|
2223 |
*/ |
|
74
068494063b1b
6641309: Wrong Cookie separator used in HttpURLConnection
jccollet
parents:
2
diff
changeset
|
2224 |
@Override |
2 | 2225 |
public void setRequestProperty(String key, String value) { |
2226 |
if (connected) |
|
2227 |
throw new IllegalStateException("Already connected"); |
|
2228 |
if (key == null) |
|
2229 |
throw new NullPointerException ("key is null"); |
|
2230 |
||
2231 |
checkMessageHeader(key, value); |
|
2232 |
requests.set(key, value); |
|
2233 |
} |
|
2234 |
||
2235 |
/** |
|
2236 |
* Adds a general request property specified by a |
|
2237 |
* key-value pair. This method will not overwrite |
|
2238 |
* existing values associated with the same key. |
|
2239 |
* |
|
2240 |
* @param key the keyword by which the request is known |
|
2241 |
* (e.g., "<code>accept</code>"). |
|
2242 |
* @param value the value associated with it. |
|
2243 |
* @see #getRequestProperties(java.lang.String) |
|
2244 |
* @since 1.4 |
|
2245 |
*/ |
|
74
068494063b1b
6641309: Wrong Cookie separator used in HttpURLConnection
jccollet
parents:
2
diff
changeset
|
2246 |
@Override |
2 | 2247 |
public void addRequestProperty(String key, String value) { |
2248 |
if (connected) |
|
2249 |
throw new IllegalStateException("Already connected"); |
|
2250 |
if (key == null) |
|
2251 |
throw new NullPointerException ("key is null"); |
|
2252 |
||
2253 |
checkMessageHeader(key, value); |
|
2254 |
requests.add(key, value); |
|
2255 |
} |
|
2256 |
||
2257 |
// |
|
2258 |
// Set a property for authentication. This can safely disregard |
|
2259 |
// the connected test. |
|
2260 |
// |
|
2261 |
void setAuthenticationProperty(String key, String value) { |
|
2262 |
checkMessageHeader(key, value); |
|
2263 |
requests.set(key, value); |
|
2264 |
} |
|
2265 |
||
74
068494063b1b
6641309: Wrong Cookie separator used in HttpURLConnection
jccollet
parents:
2
diff
changeset
|
2266 |
@Override |
2 | 2267 |
public String getRequestProperty (String key) { |
2268 |
// don't return headers containing security sensitive information |
|
2269 |
if (key != null) { |
|
2270 |
for (int i=0; i < EXCLUDE_HEADERS.length; i++) { |
|
2271 |
if (key.equalsIgnoreCase(EXCLUDE_HEADERS[i])) { |
|
2272 |
return null; |
|
2273 |
} |
|
2274 |
} |
|
2275 |
} |
|
2276 |
return requests.findValue(key); |
|
2277 |
} |
|
2278 |
||
2279 |
/** |
|
2280 |
* Returns an unmodifiable Map of general request |
|
2281 |
* properties for this connection. The Map keys |
|
2282 |
* are Strings that represent the request-header |
|
2283 |
* field names. Each Map value is a unmodifiable List |
|
2284 |
* of Strings that represents the corresponding |
|
2285 |
* field values. |
|
2286 |
* |
|
2287 |
* @return a Map of the general request properties for this connection. |
|
2288 |
* @throws IllegalStateException if already connected |
|
2289 |
* @since 1.4 |
|
2290 |
*/ |
|
74
068494063b1b
6641309: Wrong Cookie separator used in HttpURLConnection
jccollet
parents:
2
diff
changeset
|
2291 |
@Override |
2 | 2292 |
public Map getRequestProperties() { |
2293 |
if (connected) |
|
2294 |
throw new IllegalStateException("Already connected"); |
|
2295 |
||
2296 |
// exclude headers containing security-sensitive info |
|
2297 |
return requests.getHeaders(EXCLUDE_HEADERS); |
|
2298 |
} |
|
2299 |
||
74
068494063b1b
6641309: Wrong Cookie separator used in HttpURLConnection
jccollet
parents:
2
diff
changeset
|
2300 |
@Override |
2 | 2301 |
public void setConnectTimeout(int timeout) { |
2302 |
if (timeout < 0) |
|
2303 |
throw new IllegalArgumentException("timeouts can't be negative"); |
|
2304 |
connectTimeout = timeout; |
|
2305 |
} |
|
2306 |
||
2307 |
||
2308 |
/** |
|
2309 |
* Returns setting for connect timeout. |
|
2310 |
* <p> |
|
2311 |
* 0 return implies that the option is disabled |
|
2312 |
* (i.e., timeout of infinity). |
|
2313 |
* |
|
2314 |
* @return an <code>int</code> that indicates the connect timeout |
|
2315 |
* value in milliseconds |
|
2316 |
* @see java.net.URLConnection#setConnectTimeout(int) |
|
2317 |
* @see java.net.URLConnection#connect() |
|
2318 |
* @since 1.5 |
|
2319 |
*/ |
|
74
068494063b1b
6641309: Wrong Cookie separator used in HttpURLConnection
jccollet
parents:
2
diff
changeset
|
2320 |
@Override |
2 | 2321 |
public int getConnectTimeout() { |
2322 |
return (connectTimeout < 0 ? 0 : connectTimeout); |
|
2323 |
} |
|
2324 |
||
2325 |
/** |
|
2326 |
* Sets the read timeout to a specified timeout, in |
|
2327 |
* milliseconds. A non-zero value specifies the timeout when |
|
2328 |
* reading from Input stream when a connection is established to a |
|
2329 |
* resource. If the timeout expires before there is data available |
|
2330 |
* for read, a java.net.SocketTimeoutException is raised. A |
|
2331 |
* timeout of zero is interpreted as an infinite timeout. |
|
2332 |
* |
|
2333 |
* <p> Some non-standard implementation of this method ignores the |
|
2334 |
* specified timeout. To see the read timeout set, please call |
|
2335 |
* getReadTimeout(). |
|
2336 |
* |
|
2337 |
* @param timeout an <code>int</code> that specifies the timeout |
|
2338 |
* value to be used in milliseconds |
|
2339 |
* @throws IllegalArgumentException if the timeout parameter is negative |
|
2340 |
* |
|
2341 |
* @see java.net.URLConnectiongetReadTimeout() |
|
2342 |
* @see java.io.InputStream#read() |
|
2343 |
* @since 1.5 |
|
2344 |
*/ |
|
74
068494063b1b
6641309: Wrong Cookie separator used in HttpURLConnection
jccollet
parents:
2
diff
changeset
|
2345 |
@Override |
2 | 2346 |
public void setReadTimeout(int timeout) { |
2347 |
if (timeout < 0) |
|
2348 |
throw new IllegalArgumentException("timeouts can't be negative"); |
|
2349 |
readTimeout = timeout; |
|
2350 |
} |
|
2351 |
||
2352 |
/** |
|
2353 |
* Returns setting for read timeout. 0 return implies that the |
|
2354 |
* option is disabled (i.e., timeout of infinity). |
|
2355 |
* |
|
2356 |
* @return an <code>int</code> that indicates the read timeout |
|
2357 |
* value in milliseconds |
|
2358 |
* |
|
2359 |
* @see java.net.URLConnection#setReadTimeout(int) |
|
2360 |
* @see java.io.InputStream#read() |
|
2361 |
* @since 1.5 |
|
2362 |
*/ |
|
74
068494063b1b
6641309: Wrong Cookie separator used in HttpURLConnection
jccollet
parents:
2
diff
changeset
|
2363 |
@Override |
2 | 2364 |
public int getReadTimeout() { |
2365 |
return readTimeout < 0 ? 0 : readTimeout; |
|
2366 |
} |
|
2367 |
||
74
068494063b1b
6641309: Wrong Cookie separator used in HttpURLConnection
jccollet
parents:
2
diff
changeset
|
2368 |
@Override |
2 | 2369 |
protected void finalize() { |
2370 |
// this should do nothing. The stream finalizer will close |
|
2371 |
// the fd |
|
2372 |
} |
|
2373 |
||
2374 |
String getMethod() { |
|
2375 |
return method; |
|
2376 |
} |
|
2377 |
||
2378 |
private MessageHeader mapToMessageHeader(Map map) { |
|
2379 |
MessageHeader headers = new MessageHeader(); |
|
2380 |
if (map == null || map.isEmpty()) { |
|
2381 |
return headers; |
|
2382 |
} |
|
2383 |
Set entries = map.entrySet(); |
|
2384 |
Iterator itr1 = entries.iterator(); |
|
2385 |
while (itr1.hasNext()) { |
|
2386 |
Map.Entry entry = (Map.Entry)itr1.next(); |
|
2387 |
String key = (String)entry.getKey(); |
|
2388 |
List values = (List)entry.getValue(); |
|
2389 |
Iterator itr2 = values.iterator(); |
|
2390 |
while (itr2.hasNext()) { |
|
2391 |
String value = (String)itr2.next(); |
|
2392 |
if (key == null) { |
|
2393 |
headers.prepend(key, value); |
|
2394 |
} else { |
|
2395 |
headers.add(key, value); |
|
2396 |
} |
|
2397 |
} |
|
2398 |
} |
|
2399 |
return headers; |
|
2400 |
} |
|
2401 |
||
2402 |
/* The purpose of this wrapper is just to capture the close() call |
|
2403 |
* so we can check authentication information that may have |
|
2404 |
* arrived in a Trailer field |
|
2405 |
*/ |
|
2406 |
class HttpInputStream extends FilterInputStream { |
|
2407 |
private CacheRequest cacheRequest; |
|
2408 |
private OutputStream outputStream; |
|
2409 |
private boolean marked = false; |
|
2410 |
private int inCache = 0; |
|
2411 |
private int markCount = 0; |
|
2412 |
||
2413 |
public HttpInputStream (InputStream is) { |
|
2414 |
super (is); |
|
2415 |
this.cacheRequest = null; |
|
2416 |
this.outputStream = null; |
|
2417 |
} |
|
2418 |
||
2419 |
public HttpInputStream (InputStream is, CacheRequest cacheRequest) { |
|
2420 |
super (is); |
|
2421 |
this.cacheRequest = cacheRequest; |
|
2422 |
try { |
|
2423 |
this.outputStream = cacheRequest.getBody(); |
|
2424 |
} catch (IOException ioex) { |
|
2425 |
this.cacheRequest.abort(); |
|
2426 |
this.cacheRequest = null; |
|
2427 |
this.outputStream = null; |
|
2428 |
} |
|
2429 |
} |
|
2430 |
||
2431 |
/** |
|
2432 |
* Marks the current position in this input stream. A subsequent |
|
2433 |
* call to the <code>reset</code> method repositions this stream at |
|
2434 |
* the last marked position so that subsequent reads re-read the same |
|
2435 |
* bytes. |
|
2436 |
* <p> |
|
2437 |
* The <code>readlimit</code> argument tells this input stream to |
|
2438 |
* allow that many bytes to be read before the mark position gets |
|
2439 |
* invalidated. |
|
2440 |
* <p> |
|
2441 |
* This method simply performs <code>in.mark(readlimit)</code>. |
|
2442 |
* |
|
2443 |
* @param readlimit the maximum limit of bytes that can be read before |
|
2444 |
* the mark position becomes invalid. |
|
2445 |
* @see java.io.FilterInputStream#in |
|
2446 |
* @see java.io.FilterInputStream#reset() |
|
2447 |
*/ |
|
74
068494063b1b
6641309: Wrong Cookie separator used in HttpURLConnection
jccollet
parents:
2
diff
changeset
|
2448 |
@Override |
2 | 2449 |
public synchronized void mark(int readlimit) { |
2450 |
super.mark(readlimit); |
|
2451 |
if (cacheRequest != null) { |
|
2452 |
marked = true; |
|
2453 |
markCount = 0; |
|
2454 |
} |
|
2455 |
} |
|
2456 |
||
2457 |
/** |
|
2458 |
* Repositions this stream to the position at the time the |
|
2459 |
* <code>mark</code> method was last called on this input stream. |
|
2460 |
* <p> |
|
2461 |
* This method |
|
2462 |
* simply performs <code>in.reset()</code>. |
|
2463 |
* <p> |
|
2464 |
* Stream marks are intended to be used in |
|
2465 |
* situations where you need to read ahead a little to see what's in |
|
2466 |
* the stream. Often this is most easily done by invoking some |
|
2467 |
* general parser. If the stream is of the type handled by the |
|
2468 |
* parse, it just chugs along happily. If the stream is not of |
|
2469 |
* that type, the parser should toss an exception when it fails. |
|
2470 |
* If this happens within readlimit bytes, it allows the outer |
|
2471 |
* code to reset the stream and try another parser. |
|
2472 |
* |
|
2473 |
* @exception IOException if the stream has not been marked or if the |
|
2474 |
* mark has been invalidated. |
|
2475 |
* @see java.io.FilterInputStream#in |
|
2476 |
* @see java.io.FilterInputStream#mark(int) |
|
2477 |
*/ |
|
74
068494063b1b
6641309: Wrong Cookie separator used in HttpURLConnection
jccollet
parents:
2
diff
changeset
|
2478 |
@Override |
2 | 2479 |
public synchronized void reset() throws IOException { |
2480 |
super.reset(); |
|
2481 |
if (cacheRequest != null) { |
|
2482 |
marked = false; |
|
2483 |
inCache += markCount; |
|
2484 |
} |
|
2485 |
} |
|
2486 |
||
74
068494063b1b
6641309: Wrong Cookie separator used in HttpURLConnection
jccollet
parents:
2
diff
changeset
|
2487 |
@Override |
2 | 2488 |
public int read() throws IOException { |
2489 |
try { |
|
2490 |
byte[] b = new byte[1]; |
|
2491 |
int ret = read(b); |
|
2492 |
return (ret == -1? ret : (b[0] & 0x00FF)); |
|
2493 |
} catch (IOException ioex) { |
|
2494 |
if (cacheRequest != null) { |
|
2495 |
cacheRequest.abort(); |
|
2496 |
} |
|
2497 |
throw ioex; |
|
2498 |
} |
|
2499 |
} |
|
2500 |
||
74
068494063b1b
6641309: Wrong Cookie separator used in HttpURLConnection
jccollet
parents:
2
diff
changeset
|
2501 |
@Override |
2 | 2502 |
public int read(byte[] b) throws IOException { |
2503 |
return read(b, 0, b.length); |
|
2504 |
} |
|
2505 |
||
74
068494063b1b
6641309: Wrong Cookie separator used in HttpURLConnection
jccollet
parents:
2
diff
changeset
|
2506 |
@Override |
2 | 2507 |
public int read(byte[] b, int off, int len) throws IOException { |
2508 |
try { |
|
2509 |
int newLen = super.read(b, off, len); |
|
2510 |
int nWrite; |
|
2511 |
// write to cache |
|
2512 |
if (inCache > 0) { |
|
2513 |
if (inCache >= newLen) { |
|
2514 |
inCache -= newLen; |
|
2515 |
nWrite = 0; |
|
2516 |
} else { |
|
2517 |
nWrite = newLen - inCache; |
|
2518 |
inCache = 0; |
|
2519 |
} |
|
2520 |
} else { |
|
2521 |
nWrite = newLen; |
|
2522 |
} |
|
2523 |
if (nWrite > 0 && outputStream != null) |
|
2524 |
outputStream.write(b, off + (newLen-nWrite), nWrite); |
|
2525 |
if (marked) { |
|
2526 |
markCount += newLen; |
|
2527 |
} |
|
2528 |
return newLen; |
|
2529 |
} catch (IOException ioex) { |
|
2530 |
if (cacheRequest != null) { |
|
2531 |
cacheRequest.abort(); |
|
2532 |
} |
|
2533 |
throw ioex; |
|
2534 |
} |
|
2535 |
} |
|
2536 |
||
74
068494063b1b
6641309: Wrong Cookie separator used in HttpURLConnection
jccollet
parents:
2
diff
changeset
|
2537 |
@Override |
2 | 2538 |
public void close () throws IOException { |
2539 |
try { |
|
2540 |
if (outputStream != null) { |
|
2541 |
if (read() != -1) { |
|
2542 |
cacheRequest.abort(); |
|
2543 |
} else { |
|
2544 |
outputStream.close(); |
|
2545 |
} |
|
2546 |
} |
|
2547 |
super.close (); |
|
2548 |
} catch (IOException ioex) { |
|
2549 |
if (cacheRequest != null) { |
|
2550 |
cacheRequest.abort(); |
|
2551 |
} |
|
2552 |
throw ioex; |
|
2553 |
} finally { |
|
2554 |
HttpURLConnection.this.http = null; |
|
2555 |
checkResponseCredentials (true); |
|
2556 |
} |
|
2557 |
} |
|
2558 |
} |
|
2559 |
||
2560 |
class StreamingOutputStream extends FilterOutputStream { |
|
2561 |
||
2562 |
int expected; |
|
2563 |
int written; |
|
2564 |
boolean closed; |
|
2565 |
boolean error; |
|
2566 |
IOException errorExcp; |
|
2567 |
||
2568 |
/** |
|
2569 |
* expectedLength == -1 if the stream is chunked |
|
2570 |
* expectedLength > 0 if the stream is fixed content-length |
|
2571 |
* In the 2nd case, we make sure the expected number of |
|
2572 |
* of bytes are actually written |
|
2573 |
*/ |
|
2574 |
StreamingOutputStream (OutputStream os, int expectedLength) { |
|
2575 |
super (os); |
|
2576 |
expected = expectedLength; |
|
2577 |
written = 0; |
|
2578 |
closed = false; |
|
2579 |
error = false; |
|
2580 |
} |
|
2581 |
||
74
068494063b1b
6641309: Wrong Cookie separator used in HttpURLConnection
jccollet
parents:
2
diff
changeset
|
2582 |
@Override |
2 | 2583 |
public void write (int b) throws IOException { |
2584 |
checkError(); |
|
2585 |
written ++; |
|
2586 |
if (expected != -1 && written > expected) { |
|
2587 |
throw new IOException ("too many bytes written"); |
|
2588 |
} |
|
2589 |
out.write (b); |
|
2590 |
} |
|
2591 |
||
74
068494063b1b
6641309: Wrong Cookie separator used in HttpURLConnection
jccollet
parents:
2
diff
changeset
|
2592 |
@Override |
2 | 2593 |
public void write (byte[] b) throws IOException { |
2594 |
write (b, 0, b.length); |
|
2595 |
} |
|
2596 |
||
74
068494063b1b
6641309: Wrong Cookie separator used in HttpURLConnection
jccollet
parents:
2
diff
changeset
|
2597 |
@Override |
2 | 2598 |
public void write (byte[] b, int off, int len) throws IOException { |
2599 |
checkError(); |
|
2600 |
written += len; |
|
2601 |
if (expected != -1 && written > expected) { |
|
2602 |
out.close (); |
|
2603 |
throw new IOException ("too many bytes written"); |
|
2604 |
} |
|
2605 |
out.write (b, off, len); |
|
2606 |
} |
|
2607 |
||
2608 |
void checkError () throws IOException { |
|
2609 |
if (closed) { |
|
2610 |
throw new IOException ("Stream is closed"); |
|
2611 |
} |
|
2612 |
if (error) { |
|
2613 |
throw errorExcp; |
|
2614 |
} |
|
2615 |
if (((PrintStream)out).checkError()) { |
|
2616 |
throw new IOException("Error writing request body to server"); |
|
2617 |
} |
|
2618 |
} |
|
2619 |
||
2620 |
/* this is called to check that all the bytes |
|
2621 |
* that were supposed to be written were written |
|
2622 |
* and that the stream is now closed(). |
|
2623 |
*/ |
|
2624 |
boolean writtenOK () { |
|
2625 |
return closed && ! error; |
|
2626 |
} |
|
2627 |
||
74
068494063b1b
6641309: Wrong Cookie separator used in HttpURLConnection
jccollet
parents:
2
diff
changeset
|
2628 |
@Override |
2 | 2629 |
public void close () throws IOException { |
2630 |
if (closed) { |
|
2631 |
return; |
|
2632 |
} |
|
2633 |
closed = true; |
|
2634 |
if (expected != -1) { |
|
2635 |
/* not chunked */ |
|
2636 |
if (written != expected) { |
|
2637 |
error = true; |
|
2638 |
errorExcp = new IOException ("insufficient data written"); |
|
2639 |
out.close (); |
|
2640 |
throw errorExcp; |
|
2641 |
} |
|
2642 |
super.flush(); /* can't close the socket */ |
|
2643 |
} else { |
|
2644 |
/* chunked */ |
|
2645 |
super.close (); /* force final chunk to be written */ |
|
2646 |
/* trailing \r\n */ |
|
2647 |
OutputStream o = http.getOutputStream(); |
|
2648 |
o.write ('\r'); |
|
2649 |
o.write ('\n'); |
|
2650 |
o.flush(); |
|
2651 |
} |
|
2652 |
} |
|
2653 |
} |
|
2654 |
||
2655 |
||
2656 |
static class ErrorStream extends InputStream { |
|
2657 |
ByteBuffer buffer; |
|
2658 |
InputStream is; |
|
2659 |
||
2660 |
private ErrorStream(ByteBuffer buf) { |
|
2661 |
buffer = buf; |
|
2662 |
is = null; |
|
2663 |
} |
|
2664 |
||
2665 |
private ErrorStream(ByteBuffer buf, InputStream is) { |
|
2666 |
buffer = buf; |
|
2667 |
this.is = is; |
|
2668 |
} |
|
2669 |
||
2670 |
// when this method is called, it's either the case that cl > 0, or |
|
2671 |
// if chunk-encoded, cl = -1; in other words, cl can't be 0 |
|
2672 |
public static InputStream getErrorStream(InputStream is, long cl, HttpClient http) { |
|
2673 |
||
2674 |
// cl can't be 0; this following is here for extra precaution |
|
2675 |
if (cl == 0) { |
|
2676 |
return null; |
|
2677 |
} |
|
2678 |
||
2679 |
try { |
|
2680 |
// set SO_TIMEOUT to 1/5th of the total timeout |
|
2681 |
// remember the old timeout value so that we can restore it |
|
2682 |
int oldTimeout = http.setTimeout(timeout4ESBuffer/5); |
|
2683 |
||
2684 |
long expected = 0; |
|
2685 |
boolean isChunked = false; |
|
2686 |
// the chunked case |
|
2687 |
if (cl < 0) { |
|
2688 |
expected = bufSize4ES; |
|
2689 |
isChunked = true; |
|
2690 |
} else { |
|
2691 |
expected = cl; |
|
2692 |
} |
|
2693 |
if (expected <= bufSize4ES) { |
|
2694 |
int exp = (int) expected; |
|
2695 |
byte[] buffer = new byte[exp]; |
|
2696 |
int count = 0, time = 0, len = 0; |
|
2697 |
do { |
|
2698 |
try { |
|
2699 |
len = is.read(buffer, count, |
|
2700 |
buffer.length - count); |
|
2701 |
if (len < 0) { |
|
2702 |
if (isChunked) { |
|
2703 |
// chunked ended |
|
2704 |
// if chunked ended prematurely, |
|
2705 |
// an IOException would be thrown |
|
2706 |
break; |
|
2707 |
} |
|
2708 |
// the server sends less than cl bytes of data |
|
2709 |
throw new IOException("the server closes"+ |
|
2710 |
" before sending "+cl+ |
|
2711 |
" bytes of data"); |
|
2712 |
} |
|
2713 |
count += len; |
|
2714 |
} catch (SocketTimeoutException ex) { |
|
2715 |
time += timeout4ESBuffer/5; |
|
2716 |
} |
|
2717 |
} while (count < exp && time < timeout4ESBuffer); |
|
2718 |
||
2719 |
// reset SO_TIMEOUT to old value |
|
2720 |
http.setTimeout(oldTimeout); |
|
2721 |
||
2722 |
// if count < cl at this point, we will not try to reuse |
|
2723 |
// the connection |
|
2724 |
if (count == 0) { |
|
2725 |
// since we haven't read anything, |
|
2726 |
// we will return the underlying |
|
2727 |
// inputstream back to the application |
|
2728 |
return null; |
|
2729 |
} else if ((count == expected && !(isChunked)) || (isChunked && len <0)) { |
|
2730 |
// put the connection into keep-alive cache |
|
2731 |
// the inputstream will try to do the right thing |
|
2732 |
is.close(); |
|
2733 |
return new ErrorStream(ByteBuffer.wrap(buffer, 0, count)); |
|
2734 |
} else { |
|
2735 |
// we read part of the response body |
|
2736 |
return new ErrorStream( |
|
2737 |
ByteBuffer.wrap(buffer, 0, count), is); |
|
2738 |
} |
|
2739 |
} |
|
2740 |
return null; |
|
2741 |
} catch (IOException ioex) { |
|
2742 |
// ioex.printStackTrace(); |
|
2743 |
return null; |
|
2744 |
} |
|
2745 |
} |
|
2746 |
||
74
068494063b1b
6641309: Wrong Cookie separator used in HttpURLConnection
jccollet
parents:
2
diff
changeset
|
2747 |
@Override |
2 | 2748 |
public int available() throws IOException { |
2749 |
if (is == null) { |
|
2750 |
return buffer.remaining(); |
|
2751 |
} else { |
|
2752 |
return buffer.remaining()+is.available(); |
|
2753 |
} |
|
2754 |
} |
|
2755 |
||
2756 |
public int read() throws IOException { |
|
2757 |
byte[] b = new byte[1]; |
|
2758 |
int ret = read(b); |
|
2759 |
return (ret == -1? ret : (b[0] & 0x00FF)); |
|
2760 |
} |
|
2761 |
||
74
068494063b1b
6641309: Wrong Cookie separator used in HttpURLConnection
jccollet
parents:
2
diff
changeset
|
2762 |
@Override |
2 | 2763 |
public int read(byte[] b) throws IOException { |
2764 |
return read(b, 0, b.length); |
|
2765 |
} |
|
2766 |
||
74
068494063b1b
6641309: Wrong Cookie separator used in HttpURLConnection
jccollet
parents:
2
diff
changeset
|
2767 |
@Override |
2 | 2768 |
public int read(byte[] b, int off, int len) throws IOException { |
2769 |
int rem = buffer.remaining(); |
|
2770 |
if (rem > 0) { |
|
2771 |
int ret = rem < len? rem : len; |
|
2772 |
buffer.get(b, off, ret); |
|
2773 |
return ret; |
|
2774 |
} else { |
|
2775 |
if (is == null) { |
|
2776 |
return -1; |
|
2777 |
} else { |
|
2778 |
return is.read(b, off, len); |
|
2779 |
} |
|
2780 |
} |
|
2781 |
} |
|
2782 |
||
74
068494063b1b
6641309: Wrong Cookie separator used in HttpURLConnection
jccollet
parents:
2
diff
changeset
|
2783 |
@Override |
2 | 2784 |
public void close() throws IOException { |
2785 |
buffer = null; |
|
2786 |
if (is != null) { |
|
2787 |
is.close(); |
|
2788 |
} |
|
2789 |
} |
|
2790 |
} |
|
2791 |
} |
|
2792 |
||
2793 |
/** An input stream that just returns EOF. This is for |
|
2794 |
* HTTP URLConnections that are KeepAlive && use the |
|
2795 |
* HEAD method - i.e., stream not dead, but nothing to be read. |
|
2796 |
*/ |
|
2797 |
||
2798 |
class EmptyInputStream extends InputStream { |
|
2799 |
||
74
068494063b1b
6641309: Wrong Cookie separator used in HttpURLConnection
jccollet
parents:
2
diff
changeset
|
2800 |
@Override |
2 | 2801 |
public int available() { |
2802 |
return 0; |
|
2803 |
} |
|
2804 |
||
2805 |
public int read() { |
|
2806 |
return -1; |
|
2807 |
} |
|
2808 |
} |