Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.hc.client5.http;

import java.util.List;

import org.apache.hc.core5.http.HttpHost;

/**
* Supplies the Application-Layer Protocol Negotiation (ALPN) protocol IDs
* to advertise in the HTTP {@code ALPN} header on a {@code CONNECT} request
* (RFC 7639).
*
* <p>If this method returns {@code null} or an empty list, the client will
* not add the {@code ALPN} header.</p>
*
* <p>Implementations should be fast and side-effect free; it may be invoked
* for each CONNECT attempt.</p>
*
* @since 5.6
*/
@FunctionalInterface
public interface ConnectAlpnProvider {

/**
* Returns the ALPN protocol IDs to advertise for a tunnel to {@code target}
* over the given {@code route}.
*
* @param target the origin server the tunnel will connect to (non-null)
* @param route the planned connection route, including proxy info (non-null)
* @return list of protocol IDs (e.g., {@code "h2"}, {@code "http/1.1"});
* {@code null} or empty to omit the header
*/
List<String> getAlpnForTunnel(HttpHost target, HttpRoute route);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,183 @@
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.hc.client5.http.impl;


import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import org.apache.hc.core5.annotation.Contract;
import org.apache.hc.core5.annotation.Internal;
import org.apache.hc.core5.annotation.ThreadingBehavior;
import org.apache.hc.core5.http.message.MessageSupport;
import org.apache.hc.core5.http.message.ParserCursor;
import org.apache.hc.core5.util.Args;

/**
* Codec for the HTTP {@code ALPN} header field (RFC 7639).
*
* @since 5.6
*/
@Contract(threading = ThreadingBehavior.IMMUTABLE)
@Internal
public final class AlpnHeaderSupport {

private static final char[] HEXADECIMAL = "0123456789ABCDEF".toCharArray();

private AlpnHeaderSupport() {
}

/**
* Formats a list of raw ALPN protocol IDs into a single {@code ALPN} header value.
*/
public static String formatValue(final List<String> protocolIds) {
Args.notEmpty(protocolIds, "protocolIds");
final StringBuilder sb = new StringBuilder();
boolean first = true;
for (final String id : protocolIds) {
if (!first) {
sb.append(", ");
}
sb.append(encodeId(id));
first = false;
}
return sb.toString();
}

/**
* Parses an {@code ALPN} header value into decoded protocol IDs.
*/
public static List<String> parseValue(final String value) {
if (value == null || value.isEmpty()) {
return Collections.emptyList();
}
final List<String> out = new ArrayList<>();
final ParserCursor cursor = new ParserCursor(0, value.length());
MessageSupport.parseTokens(value, cursor, token -> {
if (!token.isEmpty()) {
out.add(decodeId(token));
}
});
return out;
}

/**
* Encodes a single raw protocol ID to canonical token form.
*/
public static String encodeId(final String id) {
Args.notBlank(id, "id");
final byte[] bytes = id.getBytes(StandardCharsets.UTF_8);
final StringBuilder sb = new StringBuilder(bytes.length);
for (final byte b0 : bytes) {
final int b = b0 & 0xFF;
if (b == '%' || !isTchar(b)) {
appendPctEncoded(b, sb);
} else {
sb.append((char) b);
}
}
return sb.toString();
}

/**
* Decodes percent-encoded token to raw ID using UTF-8.
* Accepts lowercase hex; malformed/incomplete sequences are left literal.
*/
public static String decodeId(final String token) {
Args.notBlank(token, "token");
final byte[] buf = new byte[token.length()];
int bi = 0;
for (int i = 0; i < token.length(); ) {
final char c = token.charAt(i);
if (c == '%' && i + 2 < token.length()) {
final int hi = hexVal(token.charAt(i + 1));
final int lo = hexVal(token.charAt(i + 2));
if (hi >= 0 && lo >= 0) {
buf[bi++] = (byte) ((hi << 4) | lo);
i += 3;
continue;
}
}
buf[bi++] = (byte) c;
i++;
}
return new String(buf, 0, bi, StandardCharsets.UTF_8);
}

// RFC7230 tchar minus '%' (RFC7639 requires '%' be percent-encoded)
private static boolean isTchar(final int c) {
if (c >= '0' && c <= '9') {
return true;
}
if (c >= 'A' && c <= 'Z') {
return true;
}
if (c >= 'a' && c <= 'z') {
return true;
}
switch (c) {
case '!':
case '#':
case '$':
case '&':
case '\'':
case '*':
case '+':
case '-':
case '.':
case '^':
case '_':
case '`':
case '|':
case '~':
return true;
default:
return false;
}
}

private static void appendPctEncoded(final int b, final StringBuilder sb) {
sb.append('%');
sb.append(HEXADECIMAL[(b >>> 4) & 0x0F]);
sb.append(HEXADECIMAL[b & 0x0F]);
}

private static int hexVal(final char c) {
if (c >= '0' && c <= '9') {
return c - '0';
}
if (c >= 'A' && c <= 'F') {
return 10 + (c - 'A');
}
if (c >= 'a' && c <= 'f') {
return 10 + (c - 'a');
}
return -1;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@
import java.util.concurrent.atomic.AtomicReference;

import org.apache.hc.client5.http.AuthenticationStrategy;
import org.apache.hc.client5.http.ConnectAlpnProvider;
import org.apache.hc.client5.http.EndpointInfo;
import org.apache.hc.client5.http.HttpRoute;
import org.apache.hc.client5.http.RouteTracker;
Expand All @@ -47,6 +48,7 @@
import org.apache.hc.client5.http.auth.ChallengeType;
import org.apache.hc.client5.http.auth.MalformedChallengeException;
import org.apache.hc.client5.http.config.RequestConfig;
import org.apache.hc.client5.http.impl.AlpnHeaderSupport;
import org.apache.hc.client5.http.impl.auth.AuthCacheKeeper;
import org.apache.hc.client5.http.impl.auth.AuthenticationHandler;
import org.apache.hc.client5.http.impl.routing.BasicRouteDirector;
Expand All @@ -60,6 +62,7 @@
import org.apache.hc.core5.http.EntityDetails;
import org.apache.hc.core5.http.Header;
import org.apache.hc.core5.http.HttpException;
import org.apache.hc.core5.http.HttpHeaders;
import org.apache.hc.core5.http.HttpHost;
import org.apache.hc.core5.http.HttpRequest;
import org.apache.hc.core5.http.HttpResponse;
Expand Down Expand Up @@ -99,18 +102,31 @@ public final class AsyncConnectExec implements AsyncExecChainHandler {
private final AuthCacheKeeper authCacheKeeper;
private final HttpRouteDirector routeDirector;

private final ConnectAlpnProvider alpnProvider;


public AsyncConnectExec(
final HttpProcessor proxyHttpProcessor,
final AuthenticationStrategy proxyAuthStrategy,
final SchemePortResolver schemePortResolver,
final boolean authCachingDisabled) {
this(proxyHttpProcessor, proxyAuthStrategy, schemePortResolver, authCachingDisabled, null);
}

public AsyncConnectExec(
final HttpProcessor proxyHttpProcessor,
final AuthenticationStrategy proxyAuthStrategy,
final SchemePortResolver schemePortResolver,
final boolean authCachingDisabled,
final ConnectAlpnProvider alpnProvider) {
Args.notNull(proxyHttpProcessor, "Proxy HTTP processor");
Args.notNull(proxyAuthStrategy, "Proxy authentication strategy");
this.proxyHttpProcessor = proxyHttpProcessor;
this.proxyAuthStrategy = proxyAuthStrategy;
this.authenticator = new AuthenticationHandler();
this.authCacheKeeper = authCachingDisabled ? null : new AuthCacheKeeper(schemePortResolver);
this.routeDirector = BasicRouteDirector.INSTANCE;
this.alpnProvider = alpnProvider;
}

static class State {
Expand Down Expand Up @@ -275,7 +291,7 @@ public void cancelled() {
if (LOG.isDebugEnabled()) {
LOG.debug("{} create tunnel", exchangeId);
}
createTunnel(state, proxy, target, scope, new AsyncExecCallback() {
createTunnel(state, proxy, target, route, scope, new AsyncExecCallback() {

@Override
public AsyncDataConsumer handleResponse(final HttpResponse response, final EntityDetails entityDetails) throws HttpException, IOException {
Expand Down Expand Up @@ -380,6 +396,7 @@ private void createTunnel(
final State state,
final HttpHost proxy,
final HttpHost nextHop,
final HttpRoute route,
final AsyncExecChain.Scope scope,
final AsyncExecCallback asyncExecCallback) {

Expand Down Expand Up @@ -426,6 +443,14 @@ public void produceRequest(final RequestChannel requestChannel,
final HttpRequest connect = new BasicHttpRequest(Method.CONNECT, nextHop, nextHop.toHostString());
connect.setVersion(HttpVersion.HTTP_1_1);

// --- RFC 7639: inject ALPN header (if provided) ----------------
if (alpnProvider != null) {
final List<String> alpn = alpnProvider.getAlpnForTunnel(nextHop, route);
if (alpn != null && !alpn.isEmpty()) {
connect.addHeader(HttpHeaders.ALPN, AlpnHeaderSupport.formatValue(alpn));
}
}

proxyHttpProcessor.process(connect, null, clientContext);
authenticator.addAuthResponse(proxy, ChallengeType.PROXY, connect, proxyAuthExchange, clientContext);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,9 @@
import java.io.Closeable;
import java.net.ProxySelector;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
Expand All @@ -40,6 +42,7 @@
import java.util.function.UnaryOperator;

import org.apache.hc.client5.http.AuthenticationStrategy;
import org.apache.hc.client5.http.ConnectAlpnProvider;
import org.apache.hc.client5.http.ConnectionKeepAliveStrategy;
import org.apache.hc.client5.http.EarlyHintsListener;
import org.apache.hc.client5.http.HttpRequestRetryStrategy;
Expand Down Expand Up @@ -272,6 +275,8 @@ private ExecInterceptorEntry(
private boolean priorityHeaderDisabled;


private ConnectAlpnProvider connectAlpnProvider;

/**
* Maps {@code Content-Encoding} tokens to decoder factories in insertion order.
*/
Expand Down Expand Up @@ -909,6 +914,26 @@ public final HttpAsyncClientBuilder disableRequestPriority() {
return this;
}

/**
* Configures the {@code ALPN} header to be sent on {@code CONNECT}
* requests when establishing an HTTP tunnel through a proxy.
*
* <p>The supplied protocol IDs are advertised in the given order (preference order).
* If {@code ids} is {@code null} or empty, no {@code ALPN} header will be added.</p>
*
* <p>This is a convenience method equivalent to installing a {@link ConnectAlpnProvider}
* that always returns the same list.</p>
*
* @param ids ALPN protocol IDs to advertise (for example {@code "h2"} and {@code "http/1.1"})
* @return this builder
* @since 5.6
*/
public HttpAsyncClientBuilder setConnectAlpn(final String... ids) {
final List<String> list = ids != null && ids.length > 0 ? Arrays.asList(ids) : Collections.emptyList();
this.connectAlpnProvider = (t, r) -> list;
return this;
}

/**
* Registers a global {@link org.apache.hc.client5.http.EarlyHintsListener}
* that will be notified when the client receives {@code 103 Early Hints}
Expand Down Expand Up @@ -1068,7 +1093,8 @@ public CloseableHttpAsyncClient build() {
new DefaultHttpProcessor(new RequestTargetHost(), new RequestUserAgent(userAgentCopy)),
proxyAuthStrategyCopy,
schemePortResolver != null ? schemePortResolver : DefaultSchemePortResolver.INSTANCE,
authCachingDisabled),
authCachingDisabled,
connectAlpnProvider),
ChainElement.CONNECT.name());

if (earlyHintsListener != null) {
Expand Down
Loading