View Javadoc
1   /*
2    * Copyright 2014 The Netty Project
3    *
4    * The Netty Project licenses this file to you under the Apache License, version 2.0 (the
5    * "License"); you may not use this file except in compliance with the License. You may obtain a
6    * copy of the License at:
7    *
8    * https://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software distributed under the License
11   * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
12   * or implied. See the License for the specific language governing permissions and limitations under
13   * the License.
14   */
15  package io.netty.handler.codec.http2;
16  
17  import io.netty.buffer.ByteBuf;
18  import io.netty.buffer.ByteBufAllocator;
19  import io.netty.handler.codec.UnsupportedValueConverter;
20  import io.netty.handler.codec.http.DefaultFullHttpRequest;
21  import io.netty.handler.codec.http.DefaultFullHttpResponse;
22  import io.netty.handler.codec.http.DefaultHttpRequest;
23  import io.netty.handler.codec.http.DefaultHttpResponse;
24  import io.netty.handler.codec.http.FullHttpMessage;
25  import io.netty.handler.codec.http.FullHttpRequest;
26  import io.netty.handler.codec.http.FullHttpResponse;
27  import io.netty.handler.codec.http.HttpHeaderNames;
28  import io.netty.handler.codec.http.HttpHeaders;
29  import io.netty.handler.codec.http.HttpMessage;
30  import io.netty.handler.codec.http.HttpMethod;
31  import io.netty.handler.codec.http.HttpRequest;
32  import io.netty.handler.codec.http.HttpResponse;
33  import io.netty.handler.codec.http.HttpResponseStatus;
34  import io.netty.handler.codec.http.HttpUtil;
35  import io.netty.handler.codec.http.HttpVersion;
36  import io.netty.util.AsciiString;
37  import io.netty.util.internal.InternalThreadLocalMap;
38  import io.netty.util.internal.StringUtil;
39  
40  import java.net.URI;
41  import java.util.Iterator;
42  import java.util.List;
43  import java.util.Map.Entry;
44  
45  import static io.netty.handler.codec.http.HttpHeaderNames.CONNECTION;
46  import static io.netty.handler.codec.http.HttpHeaderNames.COOKIE;
47  import static io.netty.handler.codec.http.HttpHeaderNames.TE;
48  import static io.netty.handler.codec.http.HttpHeaderValues.TRAILERS;
49  import static io.netty.handler.codec.http.HttpResponseStatus.parseLine;
50  import static io.netty.handler.codec.http.HttpScheme.HTTP;
51  import static io.netty.handler.codec.http.HttpScheme.HTTPS;
52  import static io.netty.handler.codec.http.HttpUtil.isAsteriskForm;
53  import static io.netty.handler.codec.http.HttpUtil.isOriginForm;
54  import static io.netty.handler.codec.http2.Http2Error.PROTOCOL_ERROR;
55  import static io.netty.handler.codec.http2.Http2Exception.connectionError;
56  import static io.netty.handler.codec.http2.Http2Exception.streamError;
57  import static io.netty.util.AsciiString.EMPTY_STRING;
58  import static io.netty.util.AsciiString.contentEqualsIgnoreCase;
59  import static io.netty.util.AsciiString.indexOf;
60  import static io.netty.util.AsciiString.trim;
61  import static io.netty.util.internal.ObjectUtil.checkNotNull;
62  import static io.netty.util.internal.StringUtil.isNullOrEmpty;
63  import static io.netty.util.internal.StringUtil.unescapeCsvFields;
64  
65  /**
66   * Provides utility methods and constants for the HTTP/2 to HTTP conversion
67   */
68  public final class HttpConversionUtil {
69      // Parsing logic adapted from Vert.x HttpUtils.parsePath/parseQuery:
70      // https://github.com/eclipse-vertx/vert.x/blob/98a8ef6c8b408009ff86eb8277fd0bbb2b866857/
71      // vertx-core/src/main/java/io/vertx/core/http/impl/HttpUtils.java#L279-L319
72      /**
73       * The set of headers that should not be directly copied when converting headers from HTTP to HTTP/2.
74       */
75      private static final CharSequenceMap<AsciiString> HTTP_TO_HTTP2_HEADER_BLACKLIST =
76              new CharSequenceMap<AsciiString>();
77      static {
78          HTTP_TO_HTTP2_HEADER_BLACKLIST.add(CONNECTION, EMPTY_STRING);
79          @SuppressWarnings("deprecation")
80          AsciiString keepAlive = HttpHeaderNames.KEEP_ALIVE;
81          HTTP_TO_HTTP2_HEADER_BLACKLIST.add(keepAlive, EMPTY_STRING);
82          @SuppressWarnings("deprecation")
83          AsciiString proxyConnection = HttpHeaderNames.PROXY_CONNECTION;
84          HTTP_TO_HTTP2_HEADER_BLACKLIST.add(proxyConnection, EMPTY_STRING);
85          HTTP_TO_HTTP2_HEADER_BLACKLIST.add(HttpHeaderNames.TRANSFER_ENCODING, EMPTY_STRING);
86          HTTP_TO_HTTP2_HEADER_BLACKLIST.add(HttpHeaderNames.HOST, EMPTY_STRING);
87          HTTP_TO_HTTP2_HEADER_BLACKLIST.add(HttpHeaderNames.UPGRADE, EMPTY_STRING);
88          HTTP_TO_HTTP2_HEADER_BLACKLIST.add(ExtensionHeaderNames.STREAM_ID.text(), EMPTY_STRING);
89          HTTP_TO_HTTP2_HEADER_BLACKLIST.add(ExtensionHeaderNames.SCHEME.text(), EMPTY_STRING);
90          HTTP_TO_HTTP2_HEADER_BLACKLIST.add(ExtensionHeaderNames.PATH.text(), EMPTY_STRING);
91          HTTP_TO_HTTP2_HEADER_BLACKLIST.add(ExtensionHeaderNames.PROTOCOL.text(), EMPTY_STRING);
92      }
93  
94      private static final CharSequenceMap<AsciiString> HTTP2_TO_HTTP_HEADER_BLACKLIST =
95              new CharSequenceMap<>(false);
96      static {
97          for (ExtensionHeaderNames name : ExtensionHeaderNames.values()) {
98              HTTP2_TO_HTTP_HEADER_BLACKLIST.add(name.text(), EMPTY_STRING);
99          }
100     }
101 
102     /**
103      * This will be the method used for {@link HttpRequest} objects generated out of the HTTP message flow defined in <a
104      * href="https://tools.ietf.org/html/rfc7540#section-8.1">[RFC 7540], Section 8.1</a>
105      */
106     public static final HttpMethod OUT_OF_MESSAGE_SEQUENCE_METHOD = HttpMethod.OPTIONS;
107 
108     /**
109      * This will be the path used for {@link HttpRequest} objects generated out of the HTTP message flow defined in <a
110      * href="https://tools.ietf.org/html/rfc7540#section-8.1">[RFC 7540], Section 8.1</a>
111      */
112     public static final String OUT_OF_MESSAGE_SEQUENCE_PATH = "";
113 
114     /**
115      * This will be the status code used for {@link HttpResponse} objects generated out of the HTTP message flow defined
116      * in <a href="https://tools.ietf.org/html/rfc7540#section-8.1">[RFC 7540], Section 8.1</a>
117      */
118     public static final HttpResponseStatus OUT_OF_MESSAGE_SEQUENCE_RETURN_CODE = HttpResponseStatus.OK;
119 
120     /**
121      * <a href="https://tools.ietf.org/html/rfc7540#section-8.1.2.3">[RFC 7540], 8.1.2.3</a> states the path must not
122      * be empty, and instead should be {@code /}.
123      */
124     private static final AsciiString EMPTY_REQUEST_PATH = AsciiString.cached("/");
125 
126     private HttpConversionUtil() {
127     }
128 
129     /**
130      * Provides the HTTP header extensions used to carry HTTP/2 information in HTTP objects
131      */
132     public enum ExtensionHeaderNames {
133         /**
134          * HTTP extension header which will identify the stream id from the HTTP/2 event(s) responsible for
135          * generating an {@code HttpObject}
136          * <p>
137          * {@code "x-http2-stream-id"}
138          */
139         STREAM_ID("x-http2-stream-id"),
140         /**
141          * HTTP extension header which will identify the scheme pseudo header from the HTTP/2 event(s) responsible for
142          * generating an {@code HttpObject}
143          * <p>
144          * {@code "x-http2-scheme"}
145          */
146         SCHEME("x-http2-scheme"),
147         /**
148          * HTTP extension header which will identify the path pseudo header from the HTTP/2 event(s) responsible for
149          * generating an {@code HttpObject}
150          * <p>
151          * {@code "x-http2-path"}
152          */
153         PATH("x-http2-path"),
154         /**
155          * HTTP extension header which will identify the stream id used to create this stream in an HTTP/2 push promise
156          * frame
157          * <p>
158          * {@code "x-http2-stream-promise-id"}
159          */
160         STREAM_PROMISE_ID("x-http2-stream-promise-id"),
161         /**
162          * HTTP extension header which will identify the stream id which this stream is dependent on. This stream will
163          * be a child node of the stream id associated with this header value.
164          * <p>
165          * {@code "x-http2-stream-dependency-id"}
166          */
167         STREAM_DEPENDENCY_ID("x-http2-stream-dependency-id"),
168         /**
169          * HTTP extension header which will identify the weight (if non-default and the priority is not on the default
170          * stream) of the associated HTTP/2 stream responsible responsible for generating an {@code HttpObject}
171          * <p>
172          * {@code "x-http2-stream-weight"}
173          */
174         STREAM_WEIGHT("x-http2-stream-weight"),
175         /**
176          * HTTP extension header which will identify the protocol pseudo header from an Extended CONNECT
177          * (<a href="https://tools.ietf.org/html/rfc8441">RFC 8441</a>) HTTP/2 event responsible for generating an
178          * {@code HttpObject}
179          * <p>
180          * {@code "x-http2-protocol"}
181          */
182         PROTOCOL("x-http2-protocol");
183 
184         private final AsciiString text;
185 
186         ExtensionHeaderNames(String text) {
187             this.text = AsciiString.cached(text);
188         }
189 
190         public AsciiString text() {
191             return text;
192         }
193     }
194 
195     /**
196      * Apply HTTP/2 rules while translating status code to {@link HttpResponseStatus}
197      *
198      * @param status The status from an HTTP/2 frame
199      * @return The HTTP/1.x status
200      * @throws Http2Exception If there is a problem translating from HTTP/2 to HTTP/1.x
201      */
202     public static HttpResponseStatus parseStatus(CharSequence status) throws Http2Exception {
203         HttpResponseStatus result;
204         try {
205             result = parseLine(status);
206             if (result == HttpResponseStatus.SWITCHING_PROTOCOLS) {
207                 throw connectionError(PROTOCOL_ERROR, "Invalid HTTP/2 status code '%d'", result.code());
208             }
209         } catch (Http2Exception e) {
210             throw e;
211         } catch (Throwable t) {
212             throw connectionError(PROTOCOL_ERROR, t,
213                             "Unrecognized HTTP status code '%s' encountered in translation to HTTP/1.x", status);
214         }
215         return result;
216     }
217 
218     /**
219      * Create a new object to contain the response data
220      *
221      * @param streamId The stream associated with the response
222      * @param http2Headers The initial set of HTTP/2 headers to create the response with
223      * @param alloc The {@link ByteBufAllocator} to use to generate the content of the message
224      * @param validateHttpHeaders <ul>
225      *        <li>{@code true} to validate HTTP headers in the http-codec</li>
226      *        <li>{@code false} not to validate HTTP headers in the http-codec</li>
227      *        </ul>
228      * @return A new response object which represents headers/data
229      * @throws Http2Exception see {@link #addHttp2ToHttpHeaders(int, Http2Headers, FullHttpMessage, boolean)}
230      */
231     public static FullHttpResponse toFullHttpResponse(int streamId, Http2Headers http2Headers, ByteBufAllocator alloc,
232                                                       boolean validateHttpHeaders) throws Http2Exception {
233         return toFullHttpResponse(streamId, http2Headers, alloc.buffer(), validateHttpHeaders);
234     }
235 
236     /**
237      * Create a new object to contain the response data
238      *
239      * @param streamId The stream associated with the response
240      * @param http2Headers The initial set of HTTP/2 headers to create the response with
241      * @param content {@link ByteBuf} content to put in {@link FullHttpResponse}
242      * @param validateHttpHeaders <ul>
243      *        <li>{@code true} to validate HTTP headers in the http-codec</li>
244      *        <li>{@code false} not to validate HTTP headers in the http-codec</li>
245      *        </ul>
246      * @return A new response object which represents headers/data
247      * @throws Http2Exception see {@link #addHttp2ToHttpHeaders(int, Http2Headers, FullHttpMessage, boolean)}
248      */
249     public static FullHttpResponse toFullHttpResponse(int streamId, Http2Headers http2Headers, ByteBuf content,
250                                                       boolean validateHttpHeaders)
251                     throws Http2Exception {
252         HttpResponseStatus status = parseStatus(http2Headers.status());
253         // HTTP/2 does not define a way to carry the version or reason phrase that is included in an
254         // HTTP/1.1 status line.
255         FullHttpResponse msg = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, status, content,
256                                                            validateHttpHeaders);
257         try {
258             addHttp2ToHttpHeaders(streamId, http2Headers, msg, false);
259         } catch (Http2Exception e) {
260             msg.release();
261             throw e;
262         } catch (Throwable t) {
263             msg.release();
264             throw streamError(streamId, PROTOCOL_ERROR, t, "HTTP/2 to HTTP/1.x headers conversion error");
265         }
266         return msg;
267     }
268 
269     /**
270      * Create a new object to contain the request data
271      *
272      * @param streamId The stream associated with the request
273      * @param http2Headers The initial set of HTTP/2 headers to create the request with
274      * @param alloc The {@link ByteBufAllocator} to use to generate the content of the message
275      * @param validateHttpHeaders <ul>
276      *        <li>{@code true} to validate HTTP headers in the http-codec</li>
277      *        <li>{@code false} not to validate HTTP headers in the http-codec</li>
278      *        </ul>
279      * @return A new request object which represents headers/data
280      * @throws Http2Exception see {@link #addHttp2ToHttpHeaders(int, Http2Headers, FullHttpMessage, boolean)}
281      */
282     public static FullHttpRequest toFullHttpRequest(int streamId, Http2Headers http2Headers, ByteBufAllocator alloc,
283                                                     boolean validateHttpHeaders) throws Http2Exception {
284         return toFullHttpRequest(streamId, http2Headers, alloc.buffer(), validateHttpHeaders);
285     }
286 
287     private static String extractPath(CharSequence method, Http2Headers headers) {
288         if (HttpMethod.CONNECT.asciiName().contentEqualsIgnoreCase(method)) {
289             // See https://tools.ietf.org/html/rfc7231#section-4.3.6
290             return checkNotNull(headers.authority(),
291                     "authority header cannot be null in the conversion to HTTP/1.x").toString();
292         } else {
293             return checkNotNull(headers.path(),
294                     "path header cannot be null in conversion to HTTP/1.x").toString();
295         }
296     }
297 
298     /**
299      * Create a new object to contain the request data
300      *
301      * @param streamId The stream associated with the request
302      * @param http2Headers The initial set of HTTP/2 headers to create the request with
303      * @param content {@link ByteBuf} content to put in {@link FullHttpRequest}
304      * @param validateHttpHeaders <ul>
305      *        <li>{@code true} to validate HTTP headers in the http-codec</li>
306      *        <li>{@code false} not to validate HTTP headers in the http-codec</li>
307      *        </ul>
308      * @return A new request object which represents headers/data
309      * @throws Http2Exception see {@link #addHttp2ToHttpHeaders(int, Http2Headers, FullHttpMessage, boolean)}
310      */
311     public static FullHttpRequest toFullHttpRequest(int streamId, Http2Headers http2Headers, ByteBuf content,
312                                                 boolean validateHttpHeaders) throws Http2Exception {
313         // HTTP/2 does not define a way to carry the version identifier that is included in the HTTP/1.1 request line.
314         final CharSequence method = checkNotNull(http2Headers.method(),
315                 "method header cannot be null in conversion to HTTP/1.x");
316         final CharSequence path = extractPath(method, http2Headers);
317         FullHttpRequest msg = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.valueOf(method
318                         .toString()), path.toString(), content, validateHttpHeaders);
319         try {
320             addHttp2ToHttpHeaders(streamId, http2Headers, msg, false);
321         } catch (Http2Exception e) {
322             msg.release();
323             throw e;
324         } catch (Throwable t) {
325             msg.release();
326             throw streamError(streamId, PROTOCOL_ERROR, t, "HTTP/2 to HTTP/1.x headers conversion error");
327         }
328         return msg;
329     }
330 
331     /**
332      * Create a new object to contain the request data.
333      *
334      * @param streamId The stream associated with the request
335      * @param http2Headers The initial set of HTTP/2 headers to create the request with
336      * @param validateHttpHeaders <ul>
337      *        <li>{@code true} to validate HTTP headers in the http-codec</li>
338      *        <li>{@code false} not to validate HTTP headers in the http-codec</li>
339      *        </ul>
340      * @return A new request object which represents headers for a chunked request
341      * @throws Http2Exception see {@link #addHttp2ToHttpHeaders(int, Http2Headers, FullHttpMessage, boolean)}
342      */
343     public static HttpRequest toHttpRequest(int streamId, Http2Headers http2Headers, boolean validateHttpHeaders)
344                     throws Http2Exception {
345         // HTTP/2 does not define a way to carry the version identifier that is included in the HTTP/1.1 request line.
346         final CharSequence method = checkNotNull(http2Headers.method(),
347                 "method header cannot be null in conversion to HTTP/1.x");
348         final CharSequence path = extractPath(method, http2Headers);
349         HttpRequest msg = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.valueOf(method.toString()),
350                 path.toString(), validateHttpHeaders);
351         try {
352             addHttp2ToHttpHeaders(streamId, http2Headers, msg.headers(), msg.protocolVersion(), false, true);
353         } catch (Http2Exception e) {
354             throw e;
355         } catch (Throwable t) {
356             throw streamError(streamId, PROTOCOL_ERROR, t, "HTTP/2 to HTTP/1.x headers conversion error");
357         }
358         return msg;
359     }
360 
361     /**
362      * Create a new object to contain the response data.
363      *
364      * @param streamId The stream associated with the response
365      * @param http2Headers The initial set of HTTP/2 headers to create the response with
366      * @param validateHttpHeaders <ul>
367      *        <li>{@code true} to validate HTTP headers in the http-codec</li>
368      *        <li>{@code false} not to validate HTTP headers in the http-codec</li>
369      *        </ul>
370      * @return A new response object which represents headers for a chunked response
371      * @throws Http2Exception see {@link #addHttp2ToHttpHeaders(int, Http2Headers,
372      *         HttpHeaders, HttpVersion, boolean, boolean)}
373      */
374     public static HttpResponse toHttpResponse(final int streamId,
375                                               final Http2Headers http2Headers,
376                                               final boolean validateHttpHeaders) throws Http2Exception {
377         final HttpResponseStatus status = parseStatus(http2Headers.status());
378         // HTTP/2 does not define a way to carry the version or reason phrase that is included in an
379         // HTTP/1.1 status line.
380         final HttpResponse msg = new DefaultHttpResponse(HttpVersion.HTTP_1_1, status, validateHttpHeaders);
381         try {
382             addHttp2ToHttpHeaders(streamId, http2Headers, msg.headers(), msg.protocolVersion(), false, false);
383         } catch (final Http2Exception e) {
384             throw e;
385         } catch (final Throwable t) {
386             throw streamError(streamId, PROTOCOL_ERROR, t, "HTTP/2 to HTTP/1.x headers conversion error");
387         }
388         return msg;
389     }
390 
391     /**
392      * Translate and add HTTP/2 headers to HTTP/1.x headers.
393      *
394      * @param streamId The stream associated with {@code sourceHeaders}.
395      * @param inputHeaders The HTTP/2 headers to convert.
396      * @param destinationMessage The object which will contain the resulting HTTP/1.x headers.
397      * @param addToTrailer {@code true} to add to trailing headers. {@code false} to add to initial headers.
398      * @throws Http2Exception If not all HTTP/2 headers can be translated to HTTP/1.x.
399      * @see #addHttp2ToHttpHeaders(int, Http2Headers, HttpHeaders, HttpVersion, boolean, boolean)
400      */
401     public static void addHttp2ToHttpHeaders(int streamId, Http2Headers inputHeaders,
402                     FullHttpMessage destinationMessage, boolean addToTrailer) throws Http2Exception {
403         addHttp2ToHttpHeaders(streamId, inputHeaders,
404                 addToTrailer ? destinationMessage.trailingHeaders() : destinationMessage.headers(),
405                 destinationMessage.protocolVersion(), addToTrailer, destinationMessage instanceof HttpRequest);
406     }
407 
408     /**
409      * Translate and add HTTP/2 headers to HTTP/1.x headers.
410      *
411      * @param streamId The stream associated with {@code sourceHeaders}.
412      * @param inputHeaders The HTTP/2 headers to convert.
413      * @param outputHeaders The object which will contain the resulting HTTP/1.x headers..
414      * @param httpVersion What HTTP/1.x version {@code outputHeaders} should be treated as when doing the conversion.
415      * @param isTrailer {@code true} if {@code outputHeaders} should be treated as trailing headers.
416      * {@code false} otherwise.
417      * @param isRequest {@code true} if the {@code outputHeaders} will be used in a request message.
418      * {@code false} for response message.
419      * @throws Http2Exception If not all HTTP/2 headers can be translated to HTTP/1.x.
420      */
421     public static void addHttp2ToHttpHeaders(int streamId, Http2Headers inputHeaders, HttpHeaders outputHeaders,
422             HttpVersion httpVersion, boolean isTrailer, boolean isRequest) throws Http2Exception {
423         // Extended CONNECT (RFC 8441) changes the semantics of a CONNECT request: the server must not treat
424         // ':authority' as an ordinary tunnel target the way it would for a regular CONNECT request. Preserve the
425         // ':protocol' and ':path' pseudo-headers as extension headers so that code operating on the converted
426         // HTTP/1.x object can still distinguish an Extended CONNECT request from a regular CONNECT request.
427         boolean isConnect = isRequest && HttpMethod.CONNECT.asciiName().contentEqualsIgnoreCase(inputHeaders.method());
428         Http2ToHttpHeaderTranslator translator =
429                 new Http2ToHttpHeaderTranslator(streamId, outputHeaders, isRequest, isConnect);
430         try {
431             translator.translateHeaders(inputHeaders);
432         } catch (Http2Exception ex) {
433             throw ex;
434         } catch (Throwable t) {
435             throw streamError(streamId, PROTOCOL_ERROR, t, "HTTP/2 to HTTP/1.x headers conversion error");
436         }
437 
438         outputHeaders.remove(HttpHeaderNames.TRANSFER_ENCODING);
439         outputHeaders.remove(HttpHeaderNames.TRAILER);
440         if (!isTrailer) {
441             outputHeaders.setInt(ExtensionHeaderNames.STREAM_ID.text(), streamId);
442             HttpUtil.setKeepAlive(outputHeaders, httpVersion, true);
443         }
444     }
445 
446     /**
447      * Converts the given HTTP/1.x headers into HTTP/2 headers.
448      * The following headers are only used if they can not be found in from the {@code HOST} header or the
449      * {@code Request-Line} as defined by <a href="https://tools.ietf.org/html/rfc7230">rfc7230</a>
450      * <ul>
451      * <li>{@link ExtensionHeaderNames#SCHEME}</li>
452      * </ul>
453      * {@link ExtensionHeaderNames#PATH} is ignored and instead extracted from the {@code Request-Line}.
454      */
455     public static Http2Headers toHttp2Headers(HttpMessage in, boolean validateHeaders) {
456         HttpHeaders inHeaders = in.headers();
457         final Http2Headers out = new DefaultHttp2Headers(validateHeaders, inHeaders.size());
458         if (in instanceof HttpRequest) {
459             HttpRequest request = (HttpRequest) in;
460             if (request.method().equals(HttpMethod.CONNECT)) {
461                 // https://datatracker.ietf.org/doc/html/rfc9112#section-3.2.3 defines the HTTP/1 CONNECT
462                 // request-target as authority-form (host:port), which is the only valid request-target for
463                 // CONNECT. Use it directly for :authority, ignoring any (potentially conflicting) Host header,
464                 // and per https://datatracker.ietf.org/doc/html/rfc9113#section-8.5 omit :scheme and :path.
465 
466                 String authorityForm = request.uri();
467                 if (authorityForm != null) {
468                     // CONNECT uses a special form of request target, unique to this method, consisting of only the
469                     // host and port number of the tunnel destination, separated by a colon per
470                     // https://www.rfc-editor.org/info/rfc9110/#name-connect
471                     if (authorityForm.isEmpty() || authorityForm.indexOf('@') >= 0 || authorityForm.indexOf('/') >= 0) {
472                         throw new IllegalArgumentException("Invalid CONNECT request target: " + authorityForm);
473                     }
474                     out.authority(new AsciiString(authorityForm));
475                 }
476             } else {
477                 String host = inHeaders.getAsString(HttpHeaderNames.HOST);
478                 if (isOriginForm(request.uri()) || isAsteriskForm(request.uri())) {
479                     out.path(new AsciiString(request.uri()));
480                     setHttp2Scheme(inHeaders, out);
481                 } else {
482                     String requestTarget = request.uri();
483                     out.path(toHttp2Path(requestTarget));
484                     if (hasSchemeAndAuthority(requestTarget)) {
485                         URI requestTargetUri = URI.create(http2PathlessRequestTarget(requestTarget));
486                         // The absolute-form request-target authority is authoritative and takes precedence over
487                         // a (potentially conflicting) HOST header, per RFC 9112 section 3.2 and RFC 9113 section 8.3.1.
488                         String requestTargetAuthority = requestTargetUri.getAuthority();
489                         host = isNullOrEmpty(requestTargetAuthority) ? host : requestTargetAuthority;
490                         setHttp2Scheme(inHeaders, requestTargetUri, out);
491                     } else {
492                         int schemeEnd = schemeEnd(requestTarget);
493                         if (schemeEnd != -1) {
494                             setHttp2Scheme(inHeaders, requestTarget.substring(0, schemeEnd), -1, out);
495                         } else {
496                             setHttp2Scheme(inHeaders, out);
497                         }
498                     }
499                 }
500                 setHttp2Authority(host, out);
501             }
502             out.method(request.method().asciiName());
503         } else if (in instanceof HttpResponse) {
504             HttpResponse response = (HttpResponse) in;
505             out.status(response.status().codeAsText());
506         }
507 
508         // Add the HTTP headers which have not been consumed above
509         toHttp2Headers(inHeaders, out);
510         return out;
511     }
512 
513     public static Http2Headers toHttp2Headers(HttpHeaders inHeaders, boolean validateHeaders) {
514         if (inHeaders.isEmpty()) {
515             return EmptyHttp2Headers.INSTANCE;
516         }
517 
518         final Http2Headers out = new DefaultHttp2Headers(validateHeaders, inHeaders.size());
519         toHttp2Headers(inHeaders, out);
520         return out;
521     }
522 
523     private static CharSequenceMap<AsciiString> toLowercaseMap(Iterator<? extends CharSequence> valuesIter,
524                                                                int arraySizeHint) {
525         UnsupportedValueConverter<AsciiString> valueConverter = UnsupportedValueConverter.<AsciiString>instance();
526         CharSequenceMap<AsciiString> result = new CharSequenceMap<AsciiString>(true, valueConverter, arraySizeHint);
527 
528         while (valuesIter.hasNext()) {
529             AsciiString lowerCased = AsciiString.of(valuesIter.next()).toLowerCase();
530             int index = lowerCased.indexOf(',', 0);
531             if (index != -1) {
532                 int start = 0;
533                 do {
534                     result.add(lowerCased.subSequence(start, index, false).trim(), EMPTY_STRING);
535                     start = index + 1;
536                 } while (start < lowerCased.length() &&
537                          (index = lowerCased.indexOf(',', start)) != -1);
538                 result.add(lowerCased.subSequence(start, lowerCased.length(), false).trim(), EMPTY_STRING);
539             } else {
540                 result.add(lowerCased.trim(), EMPTY_STRING);
541             }
542         }
543         return result;
544     }
545 
546     /**
547      * Filter the {@link HttpHeaderNames#TE} header according to the
548      * <a href="https://tools.ietf.org/html/rfc7540#section-8.1.2.2">special rules in the HTTP/2 RFC</a>.
549      * @param entry An entry whose name is {@link HttpHeaderNames#TE}.
550      * @param out the resulting HTTP/2 headers.
551      */
552     private static void toHttp2HeadersFilterTE(Entry<CharSequence, CharSequence> entry,
553                                                Http2Headers out) {
554         if (indexOf(entry.getValue(), ',', 0) == -1) {
555             if (contentEqualsIgnoreCase(trim(entry.getValue()), TRAILERS)) {
556                 out.add(TE, TRAILERS);
557             }
558         } else {
559             List<CharSequence> teValues = unescapeCsvFields(entry.getValue());
560             for (CharSequence teValue : teValues) {
561                 if (contentEqualsIgnoreCase(trim(teValue), TRAILERS)) {
562                     out.add(TE, TRAILERS);
563                     break;
564                 }
565             }
566         }
567     }
568 
569     public static void toHttp2Headers(HttpHeaders inHeaders, Http2Headers out) {
570         Iterator<Entry<CharSequence, CharSequence>> iter = inHeaders.iteratorCharSequence();
571         // Choose 8 as a default size because it is unlikely we will see more than 4 Connection headers values, but
572         // still allowing for "enough" space in the map to reduce the chance of hash code collision.
573         CharSequenceMap<AsciiString> connectionBlacklist =
574             toLowercaseMap(inHeaders.valueCharSequenceIterator(CONNECTION), 8);
575         while (iter.hasNext()) {
576             Entry<CharSequence, CharSequence> entry = iter.next();
577             final AsciiString aName = AsciiString.of(entry.getKey()).toLowerCase();
578             if (!HTTP_TO_HTTP2_HEADER_BLACKLIST.contains(aName) && !connectionBlacklist.contains(aName)) {
579                 // https://tools.ietf.org/html/rfc7540#section-8.1.2.2 makes a special exception for TE
580                 if (aName.contentEqualsIgnoreCase(TE)) {
581                     toHttp2HeadersFilterTE(entry, out);
582                 } else if (aName.contentEqualsIgnoreCase(COOKIE)) {
583                     CharSequence valueCs = entry.getValue();
584                     // validate
585                     boolean invalid = false;
586                     for (int i = 0; i < valueCs.length(); i++) {
587                         char c = valueCs.charAt(i);
588                         if (c == ';') {
589                             if (i + 1 >= valueCs.length() || valueCs.charAt(i + 1) != ' ') {
590                                 // semicolon not followed by space. invalid, don't split
591                                 invalid = true;
592                                 break;
593                             }
594                             i++; // skip space
595                         } else if (c > 255) {
596                             // not ascii, don't split
597                             invalid = true;
598                             break;
599                         }
600                     }
601 
602                     if (invalid) {
603                         out.add(COOKIE, valueCs);
604                     } else {
605                         splitValidCookieHeader(out, valueCs);
606                     }
607                 } else {
608                     out.add(aName, entry.getValue());
609                 }
610             }
611         }
612     }
613 
614     private static void splitValidCookieHeader(Http2Headers out, CharSequence valueCs) {
615         AsciiString value = AsciiString.of(valueCs);
616         // split up cookies to allow for better compression
617         // https://tools.ietf.org/html/rfc7540#section-8.1.2.5
618         int index = value.indexOf(';', 0);
619         if (index != -1) {
620             int start = 0;
621             do {
622                 out.add(COOKIE, value.subSequence(start, index, false));
623                 assert index + 1 < value.length();
624                 assert value.charAt(index + 1) == ' ';
625                 // skip 2 characters "; " (see https://tools.ietf.org/html/rfc6265#section-4.2.1)
626                 start = index + 2;
627             } while (start < value.length() &&
628                     (index = value.indexOf(';', start)) != -1);
629             assert start < value.length();
630             out.add(COOKIE, value.subSequence(start, value.length(), false));
631         } else {
632             out.add(COOKIE, value);
633         }
634     }
635 
636     /**
637      * Generate an HTTP/2 {code :path} from a request-target in accordance with
638      * <a href="https://tools.ietf.org/html/rfc7230#section-5.3">rfc7230, 5.3</a>.
639      */
640     private static AsciiString toHttp2Path(String uri) {
641         String path = dropEmptyFragment(parsePath(uri));
642         String query = parseQuery(uri);
643         if (isNullOrEmpty(query)) {
644             return path.isEmpty() ? EMPTY_REQUEST_PATH : new AsciiString(path);
645         }
646         StringBuilder pathBuilder = new StringBuilder(path.length() + query.length() + 1);
647         pathBuilder.append(path);
648         appendQuery(pathBuilder, query);
649         return new AsciiString(pathBuilder.toString());
650     }
651 
652     /**
653      * Extract the path out of the request-target. Based on Vert.x' HttpUtils.parsePath logic.
654      */
655     private static String parsePath(String uri) {
656         if (uri.isEmpty()) {
657             return StringUtil.EMPTY_STRING;
658         }
659         int i;
660         if (uri.charAt(0) == '/') {
661             i = 0;
662         } else {
663             i = uri.indexOf("://");
664             // Netty change: validate the scheme before treating :// as authority syntax.
665             if (!isValidScheme(uri, i)) {
666                 i = 0;
667             } else {
668                 int authorityStart = i + 3;
669                 // Netty change: only accept '/' before query/fragment as path start.
670                 int queryOrFragmentStart = queryOrFragmentStart(uri, authorityStart);
671                 i = uri.indexOf('/', authorityStart);
672                 if (i == -1 || (queryOrFragmentStart != -1 && queryOrFragmentStart < i)) {
673                     // contains no /
674                     return "/";
675                 }
676             }
677         }
678 
679         int queryStart = uri.indexOf('?', i);
680         if (queryStart == -1) {
681             queryStart = uri.length();
682             if (i == 0) {
683                 return uri;
684             }
685         }
686         return uri.substring(i, queryStart);
687     }
688 
689     /**
690      * Extract the query out of a request-target or returns {@code null} if no query was found.
691      */
692     private static String parseQuery(String uri) {
693         int i = uri.indexOf('?');
694         if (i == -1) {
695             return null;
696         } else {
697             return uri.substring(i + 1);
698         }
699     }
700 
701     private static String dropEmptyFragment(String path) {
702         // Netty change: old URI-based conversion dropped an empty fragment delimiter.
703         return path.endsWith("#") ? path.substring(0, path.length() - 1) : path;
704     }
705 
706     private static void appendQuery(StringBuilder pathBuilder, String query) {
707         int fragmentStart = query.indexOf('#');
708         if (fragmentStart == 0) {
709             // Netty change: old URI-based conversion skipped an empty query before a fragment.
710             pathBuilder.append(query);
711         } else if (fragmentStart == query.length() - 1) {
712             // Netty change: old URI-based conversion dropped an empty fragment delimiter after a query.
713             pathBuilder.append('?').append(query, 0, fragmentStart);
714         } else {
715             pathBuilder.append('?').append(query);
716         }
717     }
718 
719     static int queryOrFragmentStart(String uri, int searchStart) {
720         int queryStart = uri.indexOf('?', searchStart);
721         int fragmentStart = uri.indexOf('#', searchStart);
722         return queryStart == -1 ? fragmentStart :
723                 fragmentStart == -1 ? queryStart : Math.min(queryStart, fragmentStart);
724     }
725 
726     // Netty addition: detect authority for HTTP/2 :scheme/:authority extraction.
727     static boolean hasSchemeAndAuthority(String requestTarget) {
728         int schemeEnd = requestTarget.indexOf("://");
729         return isValidScheme(requestTarget, schemeEnd);
730     }
731 
732     private static int schemeEnd(String requestTarget) {
733         int schemeEnd = requestTarget.indexOf(':');
734         return isValidScheme(requestTarget, schemeEnd) ? schemeEnd : -1;
735     }
736 
737     // Netty addition: prepare only scheme://authority for URI validation.
738     private static String http2PathlessRequestTarget(String requestTarget) {
739         int schemeEnd = requestTarget.indexOf("://");
740         int authorityStart = schemeEnd + 3;
741         // Netty addition: strip before path/query/fragment; Vert.x parsePath does not validate authority.
742         int pathStart = requestTarget.indexOf('/', authorityStart);
743         int delimiter = queryOrFragmentStart(requestTarget, authorityStart);
744         if (pathStart != -1 && (delimiter == -1 || pathStart < delimiter)) {
745             delimiter = pathStart;
746         }
747         if (delimiter == -1) {
748             return requestTarget;
749         }
750         return delimiter == authorityStart ? requestTarget.substring(0, delimiter + 1) :
751                 requestTarget.substring(0, delimiter);
752     }
753 
754     // Netty addition: validate the text before :// as a scheme.
755     static boolean isValidScheme(String uri, int schemeEnd) {
756         if (schemeEnd <= 0) {
757             return false;
758         }
759         char first = uri.charAt(0);
760         if (!isAlpha(first)) {
761             return false;
762         }
763         for (int i = 1; i < schemeEnd; ++i) {
764             char c = uri.charAt(i);
765             if (!isAlpha(c) && (c < '0' || c > '9') && c != '+' && c != '-' && c != '.') {
766                 return false;
767             }
768         }
769         return true;
770     }
771 
772     private static boolean isAlpha(char c) {
773         return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z');
774     }
775 
776     // package-private for testing only
777     static void setHttp2Authority(String authority, Http2Headers out) {
778         // The authority MUST NOT include the deprecated "userinfo" subcomponent
779         if (authority != null) {
780             if (authority.isEmpty()) {
781                 out.authority(EMPTY_STRING);
782             } else {
783                 int start = authority.indexOf('@') + 1;
784                 int length = authority.length() - start;
785                 if (length == 0) {
786                     throw new IllegalArgumentException("authority: " + authority);
787                 }
788                 out.authority(new AsciiString(authority, start, length));
789             }
790         }
791     }
792 
793     private static void setHttp2Scheme(HttpHeaders in, Http2Headers out) {
794         setHttp2Scheme(in, URI.create(""), out);
795     }
796 
797     private static void setHttp2Scheme(HttpHeaders in, URI uri, Http2Headers out) {
798         setHttp2Scheme(in, uri.getScheme(), uri.getPort(), out);
799     }
800 
801     private static void setHttp2Scheme(HttpHeaders in, String scheme, int port, Http2Headers out) {
802         if (!isNullOrEmpty(scheme)) {
803             out.scheme(new AsciiString(scheme));
804             return;
805         }
806 
807         // Consume the Scheme extension header if present
808         CharSequence cValue = in.get(ExtensionHeaderNames.SCHEME.text());
809         if (cValue != null) {
810             out.scheme(AsciiString.of(cValue));
811             return;
812         }
813 
814         if (port == HTTPS.port()) {
815             out.scheme(HTTPS.name());
816         } else if (port == HTTP.port()) {
817             out.scheme(HTTP.name());
818         } else {
819             throw new IllegalArgumentException(":scheme must be specified. " +
820                     "see https://tools.ietf.org/html/rfc7540#section-8.1.2.3");
821         }
822     }
823 
824     /**
825      * Utility which translates HTTP/2 headers to HTTP/1 headers.
826      */
827     private static final class Http2ToHttpHeaderTranslator {
828         /**
829          * Translations from HTTP/2 header name to the HTTP/1.x equivalent.
830          */
831         private static final CharSequenceMap<AsciiString>
832             REQUEST_HEADER_TRANSLATIONS = new CharSequenceMap<AsciiString>();
833         private static final CharSequenceMap<AsciiString>
834             RESPONSE_HEADER_TRANSLATIONS = new CharSequenceMap<AsciiString>();
835         /**
836          * Translations used for Extended CONNECT (RFC 8441) requests. In addition to the regular request
837          * translations, the ':path' and ':protocol' pseudo-headers are preserved as extension headers so that
838          * an Extended CONNECT request cannot be mistaken for a regular CONNECT request once converted to an
839          * HTTP/1.x object.
840          */
841         private static final CharSequenceMap<AsciiString>
842             CONNECT_REQUEST_HEADER_TRANSLATIONS = new CharSequenceMap<AsciiString>();
843         static {
844             RESPONSE_HEADER_TRANSLATIONS.add(Http2Headers.PseudoHeaderName.AUTHORITY.value(),
845                             HttpHeaderNames.HOST);
846             RESPONSE_HEADER_TRANSLATIONS.add(Http2Headers.PseudoHeaderName.SCHEME.value(),
847                             ExtensionHeaderNames.SCHEME.text());
848             REQUEST_HEADER_TRANSLATIONS.add(RESPONSE_HEADER_TRANSLATIONS);
849             RESPONSE_HEADER_TRANSLATIONS.add(Http2Headers.PseudoHeaderName.PATH.value(),
850                             ExtensionHeaderNames.PATH.text());
851             CONNECT_REQUEST_HEADER_TRANSLATIONS.add(REQUEST_HEADER_TRANSLATIONS);
852             CONNECT_REQUEST_HEADER_TRANSLATIONS.add(Http2Headers.PseudoHeaderName.PATH.value(),
853                             ExtensionHeaderNames.PATH.text());
854             CONNECT_REQUEST_HEADER_TRANSLATIONS.add(Http2Headers.PseudoHeaderName.PROTOCOL.value(),
855                             ExtensionHeaderNames.PROTOCOL.text());
856         }
857 
858         private final int streamId;
859         private final HttpHeaders output;
860         private final CharSequenceMap<AsciiString> translations;
861 
862         /**
863          * Create a new instance
864          *
865          * @param output The HTTP/1.x headers object to store the results of the translation
866          * @param request if {@code true}, translates headers using the request translation map. Otherwise uses the
867          *        response translation map.
868          * @param connect if {@code true}, translates headers using the CONNECT request translation map, which
869          *        additionally preserves the ':path' and ':protocol' pseudo-headers of an Extended CONNECT
870          *        (RFC 8441) request as extension headers. Ignored unless {@code request} is {@code true}.
871          */
872         Http2ToHttpHeaderTranslator(int streamId, HttpHeaders output, boolean request, boolean connect) {
873             this.streamId = streamId;
874             this.output = output;
875             if (request) {
876                 translations = connect ? CONNECT_REQUEST_HEADER_TRANSLATIONS : REQUEST_HEADER_TRANSLATIONS;
877             } else {
878                 translations = RESPONSE_HEADER_TRANSLATIONS;
879             }
880         }
881 
882         void translateHeaders(Iterable<Entry<CharSequence, CharSequence>> inputHeaders) throws Http2Exception {
883             // lazily created as needed
884             StringBuilder cookies = null;
885             boolean hostHeaderFound = false;
886 
887             for (Entry<CharSequence, CharSequence> entry : inputHeaders) {
888                 final CharSequence name = entry.getKey();
889                 final CharSequence value = entry.getValue();
890                 AsciiString translatedName = translations.get(name);
891                 if (translatedName != null) {
892                     if (translatedName.contentEqualsIgnoreCase(HttpHeaderNames.HOST)) {
893                         hostHeaderFound = true;
894                     }
895                     output.add(translatedName, AsciiString.of(value));
896                 } else if (!Http2Headers.PseudoHeaderName.isPseudoHeader(name)) {
897                     // https://tools.ietf.org/html/rfc7540#section-8.1.2.3
898                     // All headers that start with ':' are only valid in HTTP/2 context
899                     if (name.length() == 0 || name.charAt(0) == ':') {
900                         throw streamError(streamId, PROTOCOL_ERROR,
901                                 "Invalid HTTP/2 header '%s' encountered in translation to HTTP/1.x", name);
902                     }
903                     if (HTTP2_TO_HTTP_HEADER_BLACKLIST.contains(name)) {
904                         continue;
905                     }
906                     if (COOKIE.equals(name)) {
907                         // combine the cookie values into 1 header entry.
908                         // https://tools.ietf.org/html/rfc7540#section-8.1.2.5
909                         if (cookies == null) {
910                             cookies = InternalThreadLocalMap.get().stringBuilder();
911                         } else if (cookies.length() > 0) {
912                             cookies.append("; ");
913                         }
914                         cookies.append(value);
915                     } else if (contentEqualsIgnoreCase(HttpHeaderNames.HOST, name)) {
916                         // https://www.rfc-editor.org/rfc/rfc9113#section-8.3.1 requires that intermediaries
917                         // translating to HTTP/1.x treat a literal 'host' header that conflicts with ':authority'
918                         // as malformed, and RFC 9110 section 7.2 requires 'Host' be sent as a single field-value.
919                         // Reject the request rather than emitting an HTTP/1.x message with duplicate Host headers.
920                         if (hostHeaderFound) {
921                             if (!contentEqualsIgnoreCase(output.get(HttpHeaderNames.HOST), value)) {
922                                 throw streamError(streamId, PROTOCOL_ERROR,
923                                         "Conflicting ':authority' and 'host' headers found");
924                             }
925                         } else {
926                             hostHeaderFound = true;
927                             output.add(name, value);
928                         }
929                     } else {
930                         output.add(name, value);
931                     }
932                 }
933             }
934             if (cookies != null) {
935                 output.add(COOKIE, cookies.toString());
936             }
937         }
938     }
939 }