Examples of Headers


Examples of org.jboss.com.sun.net.httpserver.Headers

                }
                String uriStr = requestLine.substring (start, space);
                URI uri = new URI (uriStr);
                start = space+1;
                String version = requestLine.substring (start);
                Headers headers = req.headers();
                String s = headers.getFirst ("Transfer-encoding");
                long clen = 0L;
                if (s !=null && s.equalsIgnoreCase ("chunked")) {
                    clen = -1L;
                } else {
                    s = headers.getFirst ("Content-Length");
                    if (s != null) {
                        clen = Long.parseLong(s);
                    }
                    if (clen == 0) {
                        requestCompleted (connection);
                    }
                }
                ctx = contexts.findContext (protocol, uri.getPath());
                if (ctx == null) {
                    reject (Code.HTTP_NOT_FOUND,
                            requestLine, "No context found for request");
                    return;
                }
                connection.setContext (ctx);
                if (ctx.getHandler() == null) {
                    reject (Code.HTTP_INTERNAL_ERROR,
                            requestLine, "No handler for context");
                    return;
                }
                tx = new ExchangeImpl (
                    method, uri, req, clen, connection
                );
                String chdr = headers.getFirst("Connection");
                Headers rheaders = tx.getResponseHeaders();

                if (chdr != null && chdr.equalsIgnoreCase ("close")) {
                    tx.close = true;
                }
                if (version.equalsIgnoreCase ("http/1.0")) {
                    tx.http10 = true;
                    if (chdr == null) {
                        tx.close = true;
                        rheaders.set ("Connection", "close");
                    } else if (chdr.equalsIgnoreCase ("keep-alive")) {
                        rheaders.set ("Connection", "keep-alive");
                        int idle=(int)ServerConfig.getIdleInterval()/1000;
                        int max=(int)ServerConfig.getMaxIdleConnections();
                        String val = "timeout="+idle+", max="+max;
                        rheaders.set ("Keep-Alive", val);
                    }
                }

                if (newconnection) {
                    connection.setParameters (
View Full Code Here

Examples of org.jboss.com.sun.net.httpserver.Headers

        /*
         *  Origin check, if it is set the Origin header should match the Host otherwise reject the request.
         *
         *  This check is for cross site scripted GET and POST requests.
         */
        final Headers headers = http.getRequestHeaders();
        final URI request = http.getRequestURI();
        if (headers.containsKey(ORIGIN)) {
            String origin = headers.getFirst(ORIGIN);
            String host = headers.getFirst(HOST);
            String protocol = http.getHttpContext().getServer() instanceof HttpServer ? HTTP : HTTPS;
            //This browser set header should not need IPv6 escaping
            String allowedOrigin = protocol + "://" + host;

            // This will reject multi-origin Origin headers due to the exact match.
            if (origin.equals(allowedOrigin) == false) {
                drain(http);
                http.sendResponseHeaders(FORBIDDEN, -1);

                return;
            }
        }

        /*
         *  Cross Site Request Forgery makes use of a specially constructed form to pass in what appears to be
         *  a valid operation request - except for upload requests any inbound requests where the Content-Type
         *  is not application/json or application/dmr-encoded will be rejected.
         */

        final boolean uploadRequest = UPLOAD_REQUEST.equals(request.getPath());
        if (POST.equals(requestMethod)) {
            if (uploadRequest) {
                // This type of request doesn't need the content type check.
                processUploadRequest(http);

                return;
            }

            String contentType = extractContentType(headers.getFirst(CONTENT_TYPE));
            if (!(APPLICATION_JSON.equals(contentType) || APPLICATION_DMR_ENCODED.equals(contentType))) {
                drain(http);
                // RFC 2616: 14.11 Content-Encoding
                // If the content-coding of an entity in a request message is not
                // acceptable to the origin server, the server SHOULD respond with a
View Full Code Here

Examples of org.jboss.com.sun.net.httpserver.Headers

        ModelNode dmr;
        ModelNode response;
        int status = OK;

        Headers requestHeaders = http.getRequestHeaders();
        boolean encode = APPLICATION_DMR_ENCODED.equals(requestHeaders.getFirst(ACCEPT))
                || APPLICATION_DMR_ENCODED.equals(requestHeaders.getFirst(CONTENT_TYPE));

        try {
            dmr = isGet ? convertGetRequest(request) : convertPostRequest(http.getRequestBody(), encode);
        } catch (Exception iae) {
            ROOT_LOGGER.debugf("Unable to construct ModelNode '%s'", iae.getMessage());
View Full Code Here

Examples of org.jboss.com.sun.net.httpserver.Headers

     * @param encode Flag indicating whether or not to Base64 encode the response payload.
     * @throws IOException if an error occurs while attempting to generate the HTTP response.
     */
    private void writeResponse(final HttpExchange http, boolean isGet, boolean pretty, ModelNode response, int status,
            boolean encode, String contentType) throws IOException {
        final Headers responseHeaders = http.getResponseHeaders();
        responseHeaders.add(CONTENT_TYPE, contentType);
        http.sendResponseHeaders(status, 0);

        final OutputStream out = http.getResponseBody();
        final PrintWriter print = new PrintWriter(out);

View Full Code Here

Examples of org.jboss.com.sun.net.httpserver.Headers

        while (!stream.isOuterStreamClosed()) {
            // purposefully send the trailing CRLF to headers so that a headerless body can be detected
            MimeHeaderParser.ParseResult result = MimeHeaderParser.parseHeaders(stream);
            if (result.eof()) continue; // Skip content-less part

            Headers partHeaders = result.headers();
            String disposition = partHeaders.getFirst(CONTENT_DISPOSITION);
            if (disposition != null) {
                matcher = DISPOSITION_FILE.matcher(disposition);
                if (matcher.matches()) {
                    SeekResult seek = new SeekResult();
                    seek.fileName = matcher.group(1);
View Full Code Here

Examples of org.jboss.com.sun.net.httpserver.Headers

        if (context.isAuthenticated()) {
            return new Authenticator.Success(context.getPrincipal());
        }

        // No previous authentication so time to continue the process.
        Headers requestHeaders = httpExchange.getRequestHeaders();
        if (requestHeaders.containsKey(AUTHORIZATION_HEADER) == false) {
            Headers responseHeaders = httpExchange.getResponseHeaders();

            responseHeaders.add(WWW_AUTHENTICATE_HEADER, CHALLENGE + " " + createChallenge(context, realm, false));

            return new Authenticator.Retry(UNAUTHORIZED);
        }

        String authorizationHeader = requestHeaders.getFirst(AUTHORIZATION_HEADER);
        if (authorizationHeader.startsWith(CHALLENGE + " ") == false) {
            throw MESSAGES.invalidAuthorizationHeader();
        }
        String challenge = authorizationHeader.substring(CHALLENGE.length() + 1);
        Map<String, String> challengeParameters = parseDigestChallenge(challenge);

        // Validate Challenge, expect one of 3 responses VALID, INVALID, STALE
        HttpPrincipal principal = validateUser(httpExchange, challengeParameters);

        // INVALID - Username / Password verification failed - Nonce is irrelevant.
        if (principal == null) {
            if (challengeParameters.containsKey(NONCE)) {
                context.useNonce(challengeParameters.get(NONCE));
            }

            Headers responseHeaders = httpExchange.getResponseHeaders();
            responseHeaders.add(WWW_AUTHENTICATE_HEADER, CHALLENGE + " " + createChallenge(context, realm, false));
            return new Authenticator.Retry(UNAUTHORIZED);
        }

        // VALID - Verified username and password, Nonce is correct.
        if (context.useNonce(challengeParameters.get(NONCE))) {
            context.principal = principal;

            return new Authenticator.Success(principal);
        }

        // STALE - Verification of username and password succeeded but Nonce now stale.
        Headers responseHeaders = httpExchange.getResponseHeaders();
        responseHeaders.add(WWW_AUTHENTICATE_HEADER, CHALLENGE + " " + createChallenge(context, realm, true));
        return new Authenticator.Retry(UNAUTHORIZED);
    }
View Full Code Here

Examples of org.jboss.com.sun.net.httpserver.Headers

    }


    public static DigestContext getOrCreateNegotiationContext(HttpExchange httpExchange, NonceFactory nonceFactory, boolean forceCreate) {
        Headers headers = httpExchange.getRequestHeaders();
        boolean proxied = headers.containsKey(VIA);

        if (proxied || forceCreate) {
            // If proxied we have to assume connections could be re-used so need a fresh DigestContext
            // each time and use of the central nonce store.
            return new DigestContext(nonceFactory, false);
View Full Code Here

Examples of org.jboss.com.sun.net.httpserver.Headers

        if (resource.equals("")) {
            /*
             * This is a request to the root of the context, redirect to the
             * default resource.
             */
            Headers responseHeaders = http.getResponseHeaders();
            responseHeaders.add(LOCATION, getDefaultUrl());
            http.sendResponseHeaders(MOVED_PERMENANTLY, 0);
            http.close();

            return;
        } else if (!resource.contains(".")) {
            respond404(http);
        }

        /*
         * This allows a sub-class of the ResourceHandler to store resources it may need in META-INF
         * without these resources being served up to remote clients unchecked.
         */
        if (resource.startsWith("META-INF")) {
            http.sendResponseHeaders(FORBIDDEN, 0);
            http.close();

            return;
        }

        // load resource
        ResourceHandle handle = getResourceHandle(resource);

        if(handle.getInputStream()!=null) {

            InputStream inputStream = handle.getInputStream();

            final Headers responseHeaders = http.getResponseHeaders();
            responseHeaders.add(CONTENT_TYPE, resolveContentType(path));

            // provide the ability to cache GWT artifacts
            if(!skipCache(resource)){

                if(System.currentTimeMillis()>lastExpiryDate) {
                    lastExpiryDate = calculateExpiryDate();
                    lastExpiryHeader = createDateFormat().format(new Date(lastExpiryDate));
                }

                responseHeaders.add(CACHE_CONTROL_HEADER, "private, max-age=2678400, must-revalidate");
                responseHeaders.add(EXPIRES_HEADER, lastExpiryHeader);
            }

            responseHeaders.add(LAST_MODIFIED_HEADER, lastModified);
            responseHeaders.add(CONTENT_LENGTH_HEADER, String.valueOf(handle.getSize()));

            http.sendResponseHeaders(OK, 0);

            // nio write
            OutputStream outputStream = http.getResponseBody();
View Full Code Here

Examples of org.jboss.com.sun.net.httpserver.Headers

        return contentType;
    }

    private void respond404(HttpExchange http) throws IOException {

        final Headers responseHeaders = http.getResponseHeaders();
        responseHeaders.add(CONTENT_TYPE, TEXT_HTML);
        http.sendResponseHeaders(NOT_FOUND, 0);
        OutputStream out = http.getResponseBody();
        out.flush();
        safeClose(out);
    }
View Full Code Here

Examples of org.jboss.com.sun.net.httpserver.Headers

        httpServer.removeContext("/logout");
    }

    @Override
    public void handle(HttpExchange exchange) throws IOException {
        final Headers requestHeaders = exchange.getRequestHeaders();
        final Headers responseHeaders = exchange.getResponseHeaders();

        // Redirect back if there is no realm to log out of
        if (realm == null) {
            responseHeaders.set(LOCATION, "/");
            exchange.sendResponseHeaders(307, -1);
        }

        String authorization = requestHeaders.getFirst("Authorization");
        String rawQuery = exchange.getRequestURI().getRawQuery();
        boolean query = rawQuery != null && rawQuery.contains("logout");

        String userAgent = requestHeaders.getFirst("User-Agent");
        boolean opera = userAgent != null && userAgent.contains("Opera");
        boolean win = !opera && userAgent != null && userAgent.contains("MSIE");

        String referrer = responseHeaders.getFirst("Referrer");

        // Calculate location URL
        String protocol = "http";
        String host = null;
        if (referrer != null) {
            try {
                URI uri = new URI(referrer);
                protocol = uri.getScheme();
                host = uri.getHost() + (uri.getPort() == -1 ? "" : ":" + String.valueOf(uri.getPort()));
            } catch (URISyntaxException e) {
            }
        }

        // Last resort
        if (host == null) {
            host = requestHeaders.getFirst("Host");
            if (host == null) {
                exchange.sendResponseHeaders(500, -1);
                return;
            }
        }
        /*
         * Main sequence of events:
         *
         * 1. Redirect to self using user:pass@host form of authority. This forces Safari to overwrite
         *    its cache. (Also forces FF and Chrome, but not absolutely necessary)
         *    Set the logout query param as a state signal for step 2
         * 2. Send 401 digest without a nonce stale marker, this will force  FF and Chrome and likely
         *    other browsers to assume an invalid (old) password. In the case of Opera, which doesn't
         *    invalidate under such a circumstance, send an invalid realm. This will overwrite its
         *    auth cache, since it indexes it by host and not realm.
         * 3. The credentials in 307 redirect wlll be transparently accepted and a final redirect to
         *    the console is performed. Opera ignores these, so the user must hit escape which will
         *    use javascript to perform the redirect
         *
         * In the case of Internet Explorer, all of this will be bypassed and will simply redirect
         * to the console. The console MUST use a special javascript call before redirecting to
         * logout.
         *
         */
        if (!win && (authorization == null || !authorization.contains("enter-login-here"))) {
            if (! query) {
                responseHeaders.set(LOCATION, protocol + "://enter-login-here:blah@" + host + "/logout?logout");
                exchange.sendResponseHeaders(307, -1);
                return;
            }

            String realm = opera ? "HIT THE ESCAPE KEY" : this.realm;
            DigestAuthenticator.DigestContext context = DigestAuthenticator.getOrCreateNegotiationContext(exchange, nonceFactory, false);
            responseHeaders.add(WWW_AUTHENTICATE_HEADER, "Digest " + DigestAuthenticator.createChallenge(context, realm, false));
            exchange.sendResponseHeaders(401, 0);
            PrintStream print = new PrintStream(exchange.getResponseBody());
            print.println("<html><script type='text/javascript'>window.location=\"" + protocol + "://" + host + "/\";</script></html>");
            print.flush();
            print.close();

            return;
        }

        // Success, now back to the login screen
        responseHeaders.set(LOCATION, protocol + "://" + host + "/");
        exchange.sendResponseHeaders(307, -1);
    }
View Full Code Here
TOP
Copyright © 2018 www.massapi.com. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.