Search in sources :

Example 6 with CacheRequest

use of java.net.CacheRequest in project jdk8u_jdk by JetBrains.

the class EmptyInputStream method getInputStream0.

@SuppressWarnings("empty-statement")
private synchronized InputStream getInputStream0() throws IOException {
    if (!doInput) {
        throw new ProtocolException("Cannot read from URLConnection" + " if doInput=false (call setDoInput(true))");
    }
    if (rememberedException != null) {
        if (rememberedException instanceof RuntimeException)
            throw new RuntimeException(rememberedException);
        else {
            throw getChainedException((IOException) rememberedException);
        }
    }
    if (inputStream != null) {
        return inputStream;
    }
    if (streaming()) {
        if (strOutputStream == null) {
            getOutputStream();
        }
        /* make sure stream is closed */
        strOutputStream.close();
        if (!strOutputStream.writtenOK()) {
            throw new IOException("Incomplete output stream");
        }
    }
    int redirects = 0;
    int respCode = 0;
    long cl = -1;
    AuthenticationInfo serverAuthentication = null;
    AuthenticationInfo proxyAuthentication = null;
    AuthenticationHeader srvHdr = null;
    /**
         * Failed Negotiate
         *
         * In some cases, the Negotiate auth is supported for the
         * remote host but the negotiate process still fails (For
         * example, if the web page is located on a backend server
         * and delegation is needed but fails). The authentication
         * process will start again, and we need to detect this
         * kind of failure and do proper fallback (say, to NTLM).
         *
         * In order to achieve this, the inNegotiate flag is set
         * when the first negotiate challenge is met (and reset
         * if authentication is finished). If a fresh new negotiate
         * challenge (no parameter) is found while inNegotiate is
         * set, we know there's a failed auth attempt recently.
         * Here we'll ignore the header line so that fallback
         * can be practiced.
         *
         * inNegotiateProxy is for proxy authentication.
         */
    boolean inNegotiate = false;
    boolean inNegotiateProxy = false;
    // If the user has set either of these headers then do not remove them
    isUserServerAuth = requests.getKey("Authorization") != -1;
    isUserProxyAuth = requests.getKey("Proxy-Authorization") != -1;
    try {
        do {
            if (!checkReuseConnection())
                connect();
            if (cachedInputStream != null) {
                return cachedInputStream;
            }
            // Check if URL should be metered
            boolean meteredInput = ProgressMonitor.getDefault().shouldMeterInput(url, method);
            if (meteredInput) {
                pi = new ProgressSource(url, method);
                pi.beginTracking();
            }
            /* REMIND: This exists to fix the HttpsURLConnection subclass.
                 * Hotjava needs to run on JDK1.1FCS.  Do proper fix once a
                 * proper solution for SSL can be found.
                 */
            ps = (PrintStream) http.getOutputStream();
            if (!streaming()) {
                writeRequests();
            }
            http.parseHTTP(responses, pi, this);
            if (logger.isLoggable(PlatformLogger.Level.FINE)) {
                logger.fine(responses.toString());
            }
            boolean b1 = responses.filterNTLMResponses("WWW-Authenticate");
            boolean b2 = responses.filterNTLMResponses("Proxy-Authenticate");
            if (b1 || b2) {
                if (logger.isLoggable(PlatformLogger.Level.FINE)) {
                    logger.fine(">>>> Headers are filtered");
                    logger.fine(responses.toString());
                }
            }
            inputStream = http.getInputStream();
            respCode = getResponseCode();
            if (respCode == -1) {
                disconnectInternal();
                throw new IOException("Invalid Http response");
            }
            if (respCode == HTTP_PROXY_AUTH) {
                if (streaming()) {
                    disconnectInternal();
                    throw new HttpRetryException(RETRY_MSG1, HTTP_PROXY_AUTH);
                }
                // Read comments labeled "Failed Negotiate" for details.
                boolean dontUseNegotiate = false;
                Iterator<String> iter = responses.multiValueIterator("Proxy-Authenticate");
                while (iter.hasNext()) {
                    String value = iter.next().trim();
                    if (value.equalsIgnoreCase("Negotiate") || value.equalsIgnoreCase("Kerberos")) {
                        if (!inNegotiateProxy) {
                            inNegotiateProxy = true;
                        } else {
                            dontUseNegotiate = true;
                            doingNTLMp2ndStage = false;
                            proxyAuthentication = null;
                        }
                        break;
                    }
                }
                // changes: add a 3rd parameter to the constructor of
                // AuthenticationHeader, so that NegotiateAuthentication.
                // isSupported can be tested.
                // The other 2 appearances of "new AuthenticationHeader" is
                // altered in similar ways.
                AuthenticationHeader authhdr = new AuthenticationHeader("Proxy-Authenticate", responses, new HttpCallerInfo(url, http.getProxyHostUsed(), http.getProxyPortUsed()), dontUseNegotiate, disabledProxyingSchemes);
                if (!doingNTLMp2ndStage) {
                    proxyAuthentication = resetProxyAuthentication(proxyAuthentication, authhdr);
                    if (proxyAuthentication != null) {
                        redirects++;
                        disconnectInternal();
                        continue;
                    }
                } else {
                    /* in this case, only one header field will be present */
                    String raw = responses.findValue("Proxy-Authenticate");
                    reset();
                    if (!proxyAuthentication.setHeaders(this, authhdr.headerParser(), raw)) {
                        disconnectInternal();
                        throw new IOException("Authentication failure");
                    }
                    if (serverAuthentication != null && srvHdr != null && !serverAuthentication.setHeaders(this, srvHdr.headerParser(), raw)) {
                        disconnectInternal();
                        throw new IOException("Authentication failure");
                    }
                    authObj = null;
                    doingNTLMp2ndStage = false;
                    continue;
                }
            } else {
                inNegotiateProxy = false;
                doingNTLMp2ndStage = false;
                if (!isUserProxyAuth)
                    requests.remove("Proxy-Authorization");
            }
            // cache proxy authentication info
            if (proxyAuthentication != null) {
                // cache auth info on success, domain header not relevant.
                proxyAuthentication.addToCache();
            }
            if (respCode == HTTP_UNAUTHORIZED) {
                if (streaming()) {
                    disconnectInternal();
                    throw new HttpRetryException(RETRY_MSG2, HTTP_UNAUTHORIZED);
                }
                // Read comments labeled "Failed Negotiate" for details.
                boolean dontUseNegotiate = false;
                Iterator<String> iter = responses.multiValueIterator("WWW-Authenticate");
                while (iter.hasNext()) {
                    String value = iter.next().trim();
                    if (value.equalsIgnoreCase("Negotiate") || value.equalsIgnoreCase("Kerberos")) {
                        if (!inNegotiate) {
                            inNegotiate = true;
                        } else {
                            dontUseNegotiate = true;
                            doingNTLM2ndStage = false;
                            serverAuthentication = null;
                        }
                        break;
                    }
                }
                srvHdr = new AuthenticationHeader("WWW-Authenticate", responses, new HttpCallerInfo(url), dontUseNegotiate);
                String raw = srvHdr.raw();
                if (!doingNTLM2ndStage) {
                    if ((serverAuthentication != null) && serverAuthentication.getAuthScheme() != NTLM) {
                        if (serverAuthentication.isAuthorizationStale(raw)) {
                            /* we can retry with the current credentials */
                            disconnectWeb();
                            redirects++;
                            requests.set(serverAuthentication.getHeaderName(), serverAuthentication.getHeaderValue(url, method));
                            currentServerCredentials = serverAuthentication;
                            setCookieHeader();
                            continue;
                        } else {
                            serverAuthentication.removeFromCache();
                        }
                    }
                    serverAuthentication = getServerAuthentication(srvHdr);
                    currentServerCredentials = serverAuthentication;
                    if (serverAuthentication != null) {
                        disconnectWeb();
                        // don't let things loop ad nauseum
                        redirects++;
                        setCookieHeader();
                        continue;
                    }
                } else {
                    reset();
                    /* header not used for ntlm */
                    if (!serverAuthentication.setHeaders(this, null, raw)) {
                        disconnectWeb();
                        throw new IOException("Authentication failure");
                    }
                    doingNTLM2ndStage = false;
                    authObj = null;
                    setCookieHeader();
                    continue;
                }
            }
            // cache server authentication info
            if (serverAuthentication != null) {
                // cache auth info on success
                if (!(serverAuthentication instanceof DigestAuthentication) || (domain == null)) {
                    if (serverAuthentication instanceof BasicAuthentication) {
                        // check if the path is shorter than the existing entry
                        String npath = AuthenticationInfo.reducePath(url.getPath());
                        String opath = serverAuthentication.path;
                        if (!opath.startsWith(npath) || npath.length() >= opath.length()) {
                            /* npath is longer, there must be a common root */
                            npath = BasicAuthentication.getRootPath(opath, npath);
                        }
                        // remove the entry and create a new one
                        BasicAuthentication a = (BasicAuthentication) serverAuthentication.clone();
                        serverAuthentication.removeFromCache();
                        a.path = npath;
                        serverAuthentication = a;
                    }
                    serverAuthentication.addToCache();
                } else {
                    // what we cache is based on the domain list in the request
                    DigestAuthentication srv = (DigestAuthentication) serverAuthentication;
                    StringTokenizer tok = new StringTokenizer(domain, " ");
                    String realm = srv.realm;
                    PasswordAuthentication pw = srv.pw;
                    digestparams = srv.params;
                    while (tok.hasMoreTokens()) {
                        String path = tok.nextToken();
                        try {
                            /* path could be an abs_path or a complete URI */
                            URL u = new URL(url, path);
                            DigestAuthentication d = new DigestAuthentication(false, u, realm, "Digest", pw, digestparams);
                            d.addToCache();
                        } catch (Exception e) {
                        }
                    }
                }
            }
            // some flags should be reset to its initialized form so that
            // even after a redirect the necessary checks can still be
            // preformed.
            inNegotiate = false;
            inNegotiateProxy = false;
            //serverAuthentication = null;
            doingNTLMp2ndStage = false;
            doingNTLM2ndStage = false;
            if (!isUserServerAuth)
                requests.remove("Authorization");
            if (!isUserProxyAuth)
                requests.remove("Proxy-Authorization");
            if (respCode == HTTP_OK) {
                checkResponseCredentials(false);
            } else {
                needToCheck = false;
            }
            // a flag need to clean
            needToCheck = true;
            if (followRedirect()) {
                /* if we should follow a redirect, then the followRedirects()
                     * method will disconnect() and re-connect us to the new
                     * location
                     */
                redirects++;
                // redirecting HTTP response may have set cookie, so
                // need to re-generate request header
                setCookieHeader();
                continue;
            }
            try {
                cl = Long.parseLong(responses.findValue("content-length"));
            } catch (Exception exc) {
            }
            ;
            if (method.equals("HEAD") || cl == 0 || respCode == HTTP_NOT_MODIFIED || respCode == HTTP_NO_CONTENT) {
                if (pi != null) {
                    pi.finishTracking();
                    pi = null;
                }
                http.finished();
                http = null;
                inputStream = new EmptyInputStream();
                connected = false;
            }
            if (respCode == 200 || respCode == 203 || respCode == 206 || respCode == 300 || respCode == 301 || respCode == 410) {
                if (cacheHandler != null && getUseCaches()) {
                    // give cache a chance to save response in cache
                    URI uri = ParseUtil.toURI(url);
                    if (uri != null) {
                        URLConnection uconn = this;
                        if ("https".equalsIgnoreCase(uri.getScheme())) {
                            try {
                                // use reflection to get to the public
                                // HttpsURLConnection instance saved in
                                // DelegateHttpsURLConnection
                                uconn = (URLConnection) this.getClass().getField("httpsURLConnection").get(this);
                            } catch (IllegalAccessException | NoSuchFieldException e) {
                            // ignored; use 'this'
                            }
                        }
                        CacheRequest cacheRequest = cacheHandler.put(uri, uconn);
                        if (cacheRequest != null && http != null) {
                            http.setCacheRequest(cacheRequest);
                            inputStream = new HttpInputStream(inputStream, cacheRequest);
                        }
                    }
                }
            }
            if (!(inputStream instanceof HttpInputStream)) {
                inputStream = new HttpInputStream(inputStream);
            }
            if (respCode >= 400) {
                if (respCode == 404 || respCode == 410) {
                    throw new FileNotFoundException(url.toString());
                } else {
                    throw new java.io.IOException("Server returned HTTP" + " response code: " + respCode + " for URL: " + url.toString());
                }
            }
            poster = null;
            strOutputStream = null;
            return inputStream;
        } while (redirects < maxRedirects);
        throw new ProtocolException("Server redirected too many " + " times (" + redirects + ")");
    } catch (RuntimeException e) {
        disconnectInternal();
        rememberedException = e;
        throw e;
    } catch (IOException e) {
        rememberedException = e;
        // buffer the error stream if bytes < 4k
        // and it can be buffered within 1 second
        String te = responses.findValue("Transfer-Encoding");
        if (http != null && http.isKeepingAlive() && enableESBuffer && (cl > 0 || (te != null && te.equalsIgnoreCase("chunked")))) {
            errorStream = ErrorStream.getErrorStream(inputStream, cl, http);
        }
        throw e;
    } finally {
        if (proxyAuthKey != null) {
            AuthenticationInfo.endAuthRequest(proxyAuthKey);
        }
        if (serverAuthKey != null) {
            AuthenticationInfo.endAuthRequest(serverAuthKey);
        }
    }
}
Also used : URI(java.net.URI) URL(java.net.URL) PasswordAuthentication(java.net.PasswordAuthentication) ProtocolException(java.net.ProtocolException) HttpRetryException(java.net.HttpRetryException) HttpRetryException(java.net.HttpRetryException) SocketTimeoutException(java.net.SocketTimeoutException) PrivilegedActionException(java.security.PrivilegedActionException) MalformedURLException(java.net.MalformedURLException) UnknownHostException(java.net.UnknownHostException) ProtocolException(java.net.ProtocolException) URLConnection(java.net.URLConnection) StringTokenizer(java.util.StringTokenizer) CacheRequest(java.net.CacheRequest)

Example 7 with CacheRequest

use of java.net.CacheRequest in project j2objc by google.

the class URLConnectionTest method backdoorUrlToUri.

/**
     * Exercises HttpURLConnection to convert URL to a URI. Unlike URL#toURI,
     * HttpURLConnection recovers from URLs with unescaped but unsupported URI
     * characters like '{' and '|' by escaping these characters.
     */
private URI backdoorUrlToUri(URL url) throws Exception {
    final AtomicReference<URI> uriReference = new AtomicReference<URI>();
    ResponseCache.setDefault(new ResponseCache() {

        @Override
        public CacheRequest put(URI uri, URLConnection connection) throws IOException {
            return null;
        }

        @Override
        public CacheResponse get(URI uri, String requestMethod, Map<String, List<String>> requestHeaders) throws IOException {
            uriReference.set(uri);
            throw new UnsupportedOperationException();
        }
    });
    try {
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.getResponseCode();
    } catch (Exception expected) {
    }
    return uriReference.get();
}
Also used : AtomicReference(java.util.concurrent.atomic.AtomicReference) IOException(java.io.IOException) URI(java.net.URI) HttpURLConnection(java.net.HttpURLConnection) URLConnection(java.net.URLConnection) URISyntaxException(java.net.URISyntaxException) SocketTimeoutException(java.net.SocketTimeoutException) HttpRetryException(java.net.HttpRetryException) IOException(java.io.IOException) UnknownHostException(java.net.UnknownHostException) ProtocolException(java.net.ProtocolException) CacheResponse(java.net.CacheResponse) HttpURLConnection(java.net.HttpURLConnection) CacheRequest(java.net.CacheRequest) ArrayList(java.util.ArrayList) List(java.util.List) ResponseCache(java.net.ResponseCache)

Example 8 with CacheRequest

use of java.net.CacheRequest in project okhttp by square.

the class HttpResponseCacheTest method getInstalledWithWrongTypeInstalled.

@Test
public void getInstalledWithWrongTypeInstalled() {
    ResponseCache.setDefault(new ResponseCache() {

        @Override
        public CacheResponse get(URI uri, String requestMethod, Map<String, List<String>> requestHeaders) {
            return null;
        }

        @Override
        public CacheRequest put(URI uri, URLConnection connection) {
            return null;
        }
    });
    assertNull(HttpResponseCache.getInstalled());
}
Also used : CacheResponse(java.net.CacheResponse) CacheRequest(java.net.CacheRequest) List(java.util.List) ResponseCache(java.net.ResponseCache) URI(java.net.URI) URLConnection(java.net.URLConnection) Test(org.junit.Test)

Example 9 with CacheRequest

use of java.net.CacheRequest in project robovm by robovm.

the class URLConnectionTest method testResponseCacheReturnsNullOutputStream.

/**
     * Don't explode if the cache returns a null body. http://b/3373699
     */
public void testResponseCacheReturnsNullOutputStream() throws Exception {
    final AtomicBoolean aborted = new AtomicBoolean();
    ResponseCache.setDefault(new ResponseCache() {

        @Override
        public CacheResponse get(URI uri, String requestMethod, Map<String, List<String>> requestHeaders) throws IOException {
            return null;
        }

        @Override
        public CacheRequest put(URI uri, URLConnection connection) throws IOException {
            return new CacheRequest() {

                @Override
                public void abort() {
                    aborted.set(true);
                }

                @Override
                public OutputStream getBody() throws IOException {
                    return null;
                }
            };
        }
    });
    server.enqueue(new MockResponse().setBody("abcdef"));
    server.play();
    HttpURLConnection connection = (HttpURLConnection) server.getUrl("/").openConnection();
    InputStream in = connection.getInputStream();
    assertEquals("abc", readAscii(in, 3));
    in.close();
    // The best behavior is ambiguous, but RI 6 doesn't abort here
    assertFalse(aborted.get());
}
Also used : MockResponse(com.google.mockwebserver.MockResponse) GZIPInputStream(java.util.zip.GZIPInputStream) InputStream(java.io.InputStream) GZIPOutputStream(java.util.zip.GZIPOutputStream) ByteArrayOutputStream(java.io.ByteArrayOutputStream) OutputStream(java.io.OutputStream) IOException(java.io.IOException) URI(java.net.URI) HttpURLConnection(java.net.HttpURLConnection) URLConnection(java.net.URLConnection) HttpsURLConnection(javax.net.ssl.HttpsURLConnection) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) CacheResponse(java.net.CacheResponse) HttpURLConnection(java.net.HttpURLConnection) CacheRequest(java.net.CacheRequest) List(java.util.List) ArrayList(java.util.ArrayList) HttpResponseCache(com.android.okhttp.HttpResponseCache) ResponseCache(java.net.ResponseCache)

Aggregations

CacheRequest (java.net.CacheRequest)9 URI (java.net.URI)9 URLConnection (java.net.URLConnection)8 CacheResponse (java.net.CacheResponse)6 ResponseCache (java.net.ResponseCache)6 List (java.util.List)6 HttpURLConnection (java.net.HttpURLConnection)5 IOException (java.io.IOException)4 ArrayList (java.util.ArrayList)4 OutputStream (java.io.OutputStream)3 HttpRetryException (java.net.HttpRetryException)3 ProtocolException (java.net.ProtocolException)3 SocketTimeoutException (java.net.SocketTimeoutException)3 UnknownHostException (java.net.UnknownHostException)3 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)3 HttpsURLConnection (javax.net.ssl.HttpsURLConnection)3 HttpResponseCache (com.android.okhttp.HttpResponseCache)2 MockResponse (com.google.mockwebserver.MockResponse)2 ByteArrayOutputStream (java.io.ByteArrayOutputStream)2 InputStream (java.io.InputStream)2