Search in sources :

Example 1 with ProtocolException

use of org.httpkit.ProtocolException in project http-kit by http-kit.

the class HttpDecoder method parseProxyLine.

private boolean parseProxyLine(String line) throws ProtocolException {
    // PROXY TCP4 255.255.255.255 255.255.255.255 65535 65535\r\n
    if (!line.startsWith("PROXY ")) {
        return false;
    }
    final Matcher m = PROXY_PATTERN.matcher(line);
    if (!m.matches()) {
        throw new ProtocolException("Unsupported or malformed proxy header: " + line);
    }
    try {
        final InetAddress clientAddr = InetAddress.getByName(m.group(1));
        final InetAddress proxyAddr = InetAddress.getByName(m.group(2));
        final int clientPort = Integer.parseInt(m.group(3), 10);
        final int proxyPort = Integer.parseInt(m.group(4), 10);
        if (((clientPort | proxyPort) & ~0xffff) != 0) {
            throw new ProtocolException("Invalid port number: " + line);
        }
        xForwardedFor = clientAddr.getHostAddress();
        if (proxyPort == 80) {
            xForwardedProto = "http";
        } else if (proxyPort == 443) {
            xForwardedProto = "https";
        }
        xForwardedPort = proxyPort;
        return true;
    } catch (NumberFormatException ex) {
        throw new ProtocolException("Malformed port in: " + line);
    } catch (UnknownHostException ex) {
        throw new ProtocolException("Malformed address in: " + line);
    }
}
Also used : ProtocolException(org.httpkit.ProtocolException) UnknownHostException(java.net.UnknownHostException) Matcher(java.util.regex.Matcher) InetAddress(java.net.InetAddress)

Example 2 with ProtocolException

use of org.httpkit.ProtocolException in project http-kit by http-kit.

the class HttpClient method exec.

public void exec(String url, RequestConfig cfg, SSLEngine engine, IRespListener cb) {
    URI uri, proxyUri = null;
    try {
        uri = new URI(url);
        if (cfg.proxy_url != null) {
            proxyUri = new URI(cfg.proxy_url);
        }
    } catch (URISyntaxException e) {
        cb.onThrowable(e);
        return;
    }
    if (uri.getHost() == null) {
        cb.onThrowable(new IllegalArgumentException("host is null: " + url));
        return;
    }
    String scheme = uri.getScheme();
    if (!"http".equals(scheme) && !"https".equals(scheme)) {
        String message = (scheme == null) ? "No protocol specified" : scheme + " is not supported";
        cb.onThrowable(new ProtocolException(message));
        return;
    }
    InetSocketAddress addr;
    try {
        if (proxyUri == null) {
            addr = addressFinder.findAddress(uri);
        } else {
            addr = addressFinder.findAddress(proxyUri);
        }
    } catch (UnknownHostException e) {
        cb.onThrowable(e);
        return;
    }
    // copy to modify, normalize header
    HeaderMap headers = HeaderMap.camelCase(cfg.headers);
    if (// if caller set it explicitly, let he do it
    !headers.containsKey("Host"))
        headers.put("Host", HttpUtils.getHost(uri));
    // headers.put("Accept", "*/*");
    if (// allow override
    !headers.containsKey("User-Agent"))
        // default
        headers.put("User-Agent", RequestConfig.DEFAULT_USER_AGENT);
    if (!headers.containsKey("Accept-Encoding") && cfg.autoCompression)
        // compression is good
        headers.put("Accept-Encoding", "gzip, deflate");
    ByteBuffer[] request;
    try {
        if (proxyUri == null) {
            request = encode(cfg.method, headers, cfg.body, HttpUtils.getPath(uri));
        } else {
            String proxyScheme = proxyUri.getScheme();
            headers.put("Proxy-Connection", "Keep-Alive");
            if (("http".equals(proxyScheme) && !"https".equals(scheme)) || cfg.tunnel == false) {
                request = encode(cfg.method, headers, cfg.body, uri.toString());
            } else if ("https".equals(proxyScheme) || "https".equals(scheme)) {
                headers.put("Host", HttpUtils.getProxyHost(uri));
                headers.put("Protocol", "https");
                HttpMethod https_method = cfg.tunnel == true ? HttpMethod.valueOf("CONNECT") : cfg.method;
                request = encode(https_method, headers, cfg.body, HttpUtils.getProxyHost(uri));
            } else {
                String message = (proxyScheme == null) ? "No proxy protocol specified" : proxyScheme + " for proxy is not supported";
                cb.onThrowable(new ProtocolException(message));
                return;
            }
        }
    } catch (IOException e) {
        cb.onThrowable(e);
        return;
    }
    if ((proxyUri == null && "https".equals(scheme)) || (proxyUri != null && "https".equals(proxyUri.getScheme()))) {
        if (engine == null) {
            engine = getDefaultContext().createSSLEngine();
            engine.setUseClientMode(true);
        }
        if (!engine.getUseClientMode())
            engine.setUseClientMode(true);
        // configure SSLEngine with URI
        sslEngineUriConfigurer.configure(engine, uri);
        pending.offer(new HttpsRequest(addr, request, cb, requests, cfg, engine));
    } else {
        pending.offer(new Request(addr, request, cb, requests, cfg));
    }
    // pending.offer(new Request(addr, request, cb, requests, cfg));
    selector.wakeup();
}
Also used : ProtocolException(org.httpkit.ProtocolException) IOException(java.io.IOException) ByteBuffer(java.nio.ByteBuffer)

Example 3 with ProtocolException

use of org.httpkit.ProtocolException in project http-kit by http-kit.

the class HttpDecoder method createRequest.

private void createRequest(String sb) throws ProtocolException {
    int aStart;
    int aEnd;
    int bStart;
    int bEnd;
    int cStart;
    int cEnd;
    aStart = findNonWhitespace(sb, 0);
    aEnd = findWhitespace(sb, aStart);
    bStart = findNonWhitespace(sb, aEnd);
    bEnd = findWhitespace(sb, bStart);
    cStart = findNonWhitespace(sb, bEnd);
    cEnd = findEndOfString(sb, cStart);
    if (cStart < cEnd) {
        try {
            HttpMethod method = HttpMethod.valueOf(sb.substring(aStart, aEnd).toUpperCase());
            HttpVersion version = HTTP_1_1;
            if ("HTTP/1.0".equals(sb.substring(cStart, cEnd))) {
                version = HTTP_1_0;
            }
            request = new HttpRequest(method, sb.substring(bStart, bEnd), version);
        } catch (Exception e) {
            throw new ProtocolException("method not understand");
        }
    } else {
        throw new ProtocolException("not http?");
    }
}
Also used : ProtocolException(org.httpkit.ProtocolException) HttpVersion(org.httpkit.HttpVersion) HttpMethod(org.httpkit.HttpMethod) LineTooLargeException(org.httpkit.LineTooLargeException) ProtocolException(org.httpkit.ProtocolException) UnknownHostException(java.net.UnknownHostException) RequestTooLargeException(org.httpkit.RequestTooLargeException)

Example 4 with ProtocolException

use of org.httpkit.ProtocolException in project http-kit by http-kit.

the class HttpDecoder method decode.

public HttpRequest decode(ByteBuffer buffer) throws LineTooLargeException, ProtocolException, RequestTooLargeException {
    String line;
    while (buffer.hasRemaining()) {
        switch(state) {
            case ALL_READ:
                return request;
            case CONNECTION_OPEN:
                line = lineReader.readLine(buffer);
                if (line != null) {
                    // or throws ProtocolException, if the PROXY line is malformed or unsupported.
                    if (parseProxyLine(line)) {
                        // valid proxy header
                        state = State.READ_INITIAL;
                    } else if (proxyProtocolOption == ProxyProtocolOption.OPTIONAL) {
                        // did not parse as a proxy header, try to create a request from it
                        // as the READ_INITIAL state would.
                        createRequest(line);
                        state = State.READ_HEADER;
                    } else {
                        throw new ProtocolException("Expected PROXY header, got: " + line);
                    }
                }
                break;
            case READ_INITIAL:
                line = lineReader.readLine(buffer);
                if (line != null) {
                    createRequest(line);
                    state = State.READ_HEADER;
                }
                break;
            case READ_HEADER:
                readHeaders(buffer);
                break;
            case READ_CHUNK_SIZE:
                line = lineReader.readLine(buffer);
                if (line != null) {
                    readRemaining = getChunkSize(line);
                    if (readRemaining == 0) {
                        state = State.READ_CHUNK_FOOTER;
                    } else {
                        throwIfBodyIsTooLarge();
                        if (content == null) {
                            content = new byte[readRemaining];
                        } else if (content.length < readCount + readRemaining) {
                            // *1.3 to protect slow client
                            int newLength = (int) ((readRemaining + readCount) * 1.3);
                            content = Arrays.copyOf(content, newLength);
                        }
                        state = State.READ_CHUNKED_CONTENT;
                    }
                }
                break;
            case READ_FIXED_LENGTH_CONTENT:
                readFixedLength(buffer);
                if (readRemaining == 0) {
                    finish();
                }
                break;
            case READ_CHUNKED_CONTENT:
                readFixedLength(buffer);
                if (readRemaining == 0) {
                    state = State.READ_CHUNK_DELIMITER;
                }
                break;
            case READ_CHUNK_FOOTER:
                readEmptyLine(buffer);
                finish();
                break;
            case READ_CHUNK_DELIMITER:
                readEmptyLine(buffer);
                state = State.READ_CHUNK_SIZE;
                break;
        }
    }
    return state == State.ALL_READ ? request : null;
}
Also used : ProtocolException(org.httpkit.ProtocolException)

Example 5 with ProtocolException

use of org.httpkit.ProtocolException in project http-kit by http-kit.

the class HttpDecoder method readHeaders.

private void readHeaders(ByteBuffer buffer) throws LineTooLargeException, RequestTooLargeException, ProtocolException {
    if (proxyProtocolOption == ProxyProtocolOption.OPTIONAL || proxyProtocolOption == ProxyProtocolOption.ENABLED) {
        headers.put("x-forwarded-for", xForwardedFor);
        headers.put("x-forwarded-proto", xForwardedProto);
        headers.put("x-forwarded-port", xForwardedPort);
    }
    String line = lineReader.readLine(buffer);
    while (line != null && !line.isEmpty()) {
        HttpUtils.splitAndAddHeader(line, headers);
        line = lineReader.readLine(buffer);
    }
    if (line == null) {
        return;
    }
    request.setHeaders(headers);
    String te = HttpUtils.getStringValue(headers, TRANSFER_ENCODING);
    if (CHUNKED.equals(te)) {
        state = State.READ_CHUNK_SIZE;
    } else {
        String cl = HttpUtils.getStringValue(headers, CONTENT_LENGTH);
        if (cl != null) {
            try {
                readRemaining = Integer.parseInt(cl);
                if (readRemaining > 0) {
                    throwIfBodyIsTooLarge();
                    content = new byte[readRemaining];
                    state = State.READ_FIXED_LENGTH_CONTENT;
                } else {
                    state = State.ALL_READ;
                }
            } catch (NumberFormatException e) {
                throw new ProtocolException(e.getMessage());
            }
        } else {
            state = State.ALL_READ;
        }
    }
}
Also used : ProtocolException(org.httpkit.ProtocolException)

Aggregations

ProtocolException (org.httpkit.ProtocolException)7 UnknownHostException (java.net.UnknownHostException)2 LineTooLargeException (org.httpkit.LineTooLargeException)2 RequestTooLargeException (org.httpkit.RequestTooLargeException)2 IOException (java.io.IOException)1 InetAddress (java.net.InetAddress)1 ByteBuffer (java.nio.ByteBuffer)1 Matcher (java.util.regex.Matcher)1 HeaderMap (org.httpkit.HeaderMap)1 HttpMethod (org.httpkit.HttpMethod)1 HttpVersion (org.httpkit.HttpVersion)1 BinaryFrame (org.httpkit.server.Frame.BinaryFrame)1 CloseFrame (org.httpkit.server.Frame.CloseFrame)1 PingFrame (org.httpkit.server.Frame.PingFrame)1 PongFrame (org.httpkit.server.Frame.PongFrame)1 TextFrame (org.httpkit.server.Frame.TextFrame)1