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    * http://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.ByteBufAllocator;
18  import io.netty.handler.codec.UnsupportedValueConverter;
19  import io.netty.handler.codec.http.DefaultFullHttpRequest;
20  import io.netty.handler.codec.http.DefaultFullHttpResponse;
21  import io.netty.handler.codec.http.DefaultHttpRequest;
22  import io.netty.handler.codec.http.DefaultHttpResponse;
23  import io.netty.handler.codec.http.FullHttpMessage;
24  import io.netty.handler.codec.http.FullHttpRequest;
25  import io.netty.handler.codec.http.FullHttpResponse;
26  import io.netty.handler.codec.http.HttpHeaderNames;
27  import io.netty.handler.codec.http.HttpHeaders;
28  import io.netty.handler.codec.http.HttpMessage;
29  import io.netty.handler.codec.http.HttpMethod;
30  import io.netty.handler.codec.http.HttpRequest;
31  import io.netty.handler.codec.http.HttpResponse;
32  import io.netty.handler.codec.http.HttpResponseStatus;
33  import io.netty.handler.codec.http.HttpUtil;
34  import io.netty.handler.codec.http.HttpVersion;
35  import io.netty.util.AsciiString;
36  import io.netty.util.internal.UnstableApi;
37  
38  import java.net.URI;
39  import java.util.Iterator;
40  import java.util.List;
41  import java.util.Map.Entry;
42  
43  import static io.netty.handler.codec.http.HttpHeaderNames.CONNECTION;
44  import static io.netty.handler.codec.http.HttpHeaderNames.COOKIE;
45  import static io.netty.handler.codec.http.HttpHeaderNames.TE;
46  import static io.netty.handler.codec.http.HttpHeaderValues.TRAILERS;
47  import static io.netty.handler.codec.http.HttpResponseStatus.parseLine;
48  import static io.netty.handler.codec.http.HttpScheme.HTTP;
49  import static io.netty.handler.codec.http.HttpScheme.HTTPS;
50  import static io.netty.handler.codec.http.HttpUtil.isAsteriskForm;
51  import static io.netty.handler.codec.http.HttpUtil.isOriginForm;
52  import static io.netty.handler.codec.http2.Http2Error.PROTOCOL_ERROR;
53  import static io.netty.handler.codec.http2.Http2Exception.connectionError;
54  import static io.netty.handler.codec.http2.Http2Exception.streamError;
55  import static io.netty.util.AsciiString.EMPTY_STRING;
56  import static io.netty.util.AsciiString.contentEqualsIgnoreCase;
57  import static io.netty.util.AsciiString.indexOf;
58  import static io.netty.util.AsciiString.trim;
59  import static io.netty.util.ByteProcessor.FIND_COMMA;
60  import static io.netty.util.ByteProcessor.FIND_SEMI_COLON;
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.length;
64  import static io.netty.util.internal.StringUtil.unescapeCsvFields;
65  
66  /**
67   * Provides utility methods and constants for the HTTP/2 to HTTP conversion
68   */
69  @UnstableApi
70  public final class HttpConversionUtil {
71      /**
72       * The set of headers that should not be directly copied when converting headers from HTTP to HTTP/2.
73       */
74      private static final CharSequenceMap<AsciiString> HTTP_TO_HTTP2_HEADER_BLACKLIST =
75              new CharSequenceMap<AsciiString>();
76      static {
77          HTTP_TO_HTTP2_HEADER_BLACKLIST.add(CONNECTION, EMPTY_STRING);
78          @SuppressWarnings("deprecation")
79          AsciiString keepAlive = HttpHeaderNames.KEEP_ALIVE;
80          HTTP_TO_HTTP2_HEADER_BLACKLIST.add(keepAlive, EMPTY_STRING);
81          @SuppressWarnings("deprecation")
82          AsciiString proxyConnection = HttpHeaderNames.PROXY_CONNECTION;
83          HTTP_TO_HTTP2_HEADER_BLACKLIST.add(proxyConnection, EMPTY_STRING);
84          HTTP_TO_HTTP2_HEADER_BLACKLIST.add(HttpHeaderNames.TRANSFER_ENCODING, EMPTY_STRING);
85          HTTP_TO_HTTP2_HEADER_BLACKLIST.add(HttpHeaderNames.HOST, EMPTY_STRING);
86          HTTP_TO_HTTP2_HEADER_BLACKLIST.add(HttpHeaderNames.UPGRADE, EMPTY_STRING);
87          HTTP_TO_HTTP2_HEADER_BLACKLIST.add(ExtensionHeaderNames.STREAM_ID.text(), EMPTY_STRING);
88          HTTP_TO_HTTP2_HEADER_BLACKLIST.add(ExtensionHeaderNames.SCHEME.text(), EMPTY_STRING);
89          HTTP_TO_HTTP2_HEADER_BLACKLIST.add(ExtensionHeaderNames.PATH.text(), EMPTY_STRING);
90      }
91  
92      /**
93       * This will be the method used for {@link HttpRequest} objects generated out of the HTTP message flow defined in <a
94       * href="http://tools.ietf.org/html/draft-ietf-httpbis-http2-16#section-8.1.">HTTP/2 Spec Message Flow</a>
95       */
96      public static final HttpMethod OUT_OF_MESSAGE_SEQUENCE_METHOD = HttpMethod.OPTIONS;
97  
98      /**
99       * This will be the path used for {@link HttpRequest} objects generated out of the HTTP message flow defined in <a
100      * href="http://tools.ietf.org/html/draft-ietf-httpbis-http2-16#section-8.1.">HTTP/2 Spec Message Flow</a>
101      */
102     public static final String OUT_OF_MESSAGE_SEQUENCE_PATH = "";
103 
104     /**
105      * This will be the status code used for {@link HttpResponse} objects generated out of the HTTP message flow defined
106      * in <a href="http://tools.ietf.org/html/draft-ietf-httpbis-http2-16#section-8.1.">HTTP/2 Spec Message Flow</a>
107      */
108     public static final HttpResponseStatus OUT_OF_MESSAGE_SEQUENCE_RETURN_CODE = HttpResponseStatus.OK;
109 
110     /**
111      * <a href="https://tools.ietf.org/html/rfc7540#section-8.1.2.3">rfc7540, 8.1.2.3</a> states the path must not
112      * be empty, and instead should be {@code /}.
113      */
114     private static final AsciiString EMPTY_REQUEST_PATH = AsciiString.cached("/");
115 
116     private HttpConversionUtil() {
117     }
118 
119     /**
120      * Provides the HTTP header extensions used to carry HTTP/2 information in HTTP objects
121      */
122     public enum ExtensionHeaderNames {
123         /**
124          * HTTP extension header which will identify the stream id from the HTTP/2 event(s) responsible for generating a
125          * {@code HttpObject}
126          * <p>
127          * {@code "x-http2-stream-id"}
128          */
129         STREAM_ID("x-http2-stream-id"),
130         /**
131          * HTTP extension header which will identify the scheme pseudo header from the HTTP/2 event(s) responsible for
132          * generating a {@code HttpObject}
133          * <p>
134          * {@code "x-http2-scheme"}
135          */
136         SCHEME("x-http2-scheme"),
137         /**
138          * HTTP extension header which will identify the path pseudo header from the HTTP/2 event(s) responsible for
139          * generating a {@code HttpObject}
140          * <p>
141          * {@code "x-http2-path"}
142          */
143         PATH("x-http2-path"),
144         /**
145          * HTTP extension header which will identify the stream id used to create this stream in a HTTP/2 push promise
146          * frame
147          * <p>
148          * {@code "x-http2-stream-promise-id"}
149          */
150         STREAM_PROMISE_ID("x-http2-stream-promise-id"),
151         /**
152          * HTTP extension header which will identify the stream id which this stream is dependent on. This stream will
153          * be a child node of the stream id associated with this header value.
154          * <p>
155          * {@code "x-http2-stream-dependency-id"}
156          */
157         STREAM_DEPENDENCY_ID("x-http2-stream-dependency-id"),
158         /**
159          * HTTP extension header which will identify the weight (if non-default and the priority is not on the default
160          * stream) of the associated HTTP/2 stream responsible responsible for generating a {@code HttpObject}
161          * <p>
162          * {@code "x-http2-stream-weight"}
163          */
164         STREAM_WEIGHT("x-http2-stream-weight");
165 
166         private final AsciiString text;
167 
168         ExtensionHeaderNames(String text) {
169             this.text = AsciiString.cached(text);
170         }
171 
172         public AsciiString text() {
173             return text;
174         }
175     }
176 
177     /**
178      * Apply HTTP/2 rules while translating status code to {@link HttpResponseStatus}
179      *
180      * @param status The status from an HTTP/2 frame
181      * @return The HTTP/1.x status
182      * @throws Http2Exception If there is a problem translating from HTTP/2 to HTTP/1.x
183      */
184     public static HttpResponseStatus parseStatus(CharSequence status) throws Http2Exception {
185         HttpResponseStatus result;
186         try {
187             result = parseLine(status);
188             if (result == HttpResponseStatus.SWITCHING_PROTOCOLS) {
189                 throw connectionError(PROTOCOL_ERROR, "Invalid HTTP/2 status code '%d'", result.code());
190             }
191         } catch (Http2Exception e) {
192             throw e;
193         } catch (Throwable t) {
194             throw connectionError(PROTOCOL_ERROR, t,
195                             "Unrecognized HTTP status code '%s' encountered in translation to HTTP/1.x", status);
196         }
197         return result;
198     }
199 
200     /**
201      * Create a new object to contain the response data
202      *
203      * @param streamId The stream associated with the response
204      * @param http2Headers The initial set of HTTP/2 headers to create the response with
205      * @param alloc The {@link ByteBufAllocator} to use to generate the content of the message
206      * @param validateHttpHeaders <ul>
207      *        <li>{@code true} to validate HTTP headers in the http-codec</li>
208      *        <li>{@code false} not to validate HTTP headers in the http-codec</li>
209      *        </ul>
210      * @return A new response object which represents headers/data
211      * @throws Http2Exception see {@link #addHttp2ToHttpHeaders(int, Http2Headers, FullHttpMessage, boolean)}
212      */
213     public static FullHttpResponse toFullHttpResponse(int streamId, Http2Headers http2Headers, ByteBufAllocator alloc,
214                                                       boolean validateHttpHeaders)
215                     throws Http2Exception {
216         HttpResponseStatus status = parseStatus(http2Headers.status());
217         // HTTP/2 does not define a way to carry the version or reason phrase that is included in an
218         // HTTP/1.1 status line.
219         FullHttpResponse msg = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, status, alloc.buffer(),
220                                                            validateHttpHeaders);
221         try {
222             addHttp2ToHttpHeaders(streamId, http2Headers, msg, false);
223         } catch (Http2Exception e) {
224             msg.release();
225             throw e;
226         } catch (Throwable t) {
227             msg.release();
228             throw streamError(streamId, PROTOCOL_ERROR, t, "HTTP/2 to HTTP/1.x headers conversion error");
229         }
230         return msg;
231     }
232 
233     /**
234      * Create a new object to contain the request data
235      *
236      * @param streamId The stream associated with the request
237      * @param http2Headers The initial set of HTTP/2 headers to create the request with
238      * @param alloc The {@link ByteBufAllocator} to use to generate the content of the message
239      * @param validateHttpHeaders <ul>
240      *        <li>{@code true} to validate HTTP headers in the http-codec</li>
241      *        <li>{@code false} not to validate HTTP headers in the http-codec</li>
242      *        </ul>
243      * @return A new request object which represents headers/data
244      * @throws Http2Exception see {@link #addHttp2ToHttpHeaders(int, Http2Headers, FullHttpMessage, boolean)}
245      */
246     public static FullHttpRequest toFullHttpRequest(int streamId, Http2Headers http2Headers, ByteBufAllocator alloc,
247                                                 boolean validateHttpHeaders)
248                     throws Http2Exception {
249         // HTTP/2 does not define a way to carry the version identifier that is included in the HTTP/1.1 request line.
250         final CharSequence method = checkNotNull(http2Headers.method(),
251                 "method header cannot be null in conversion to HTTP/1.x");
252         final CharSequence path = checkNotNull(http2Headers.path(),
253                 "path header cannot be null in conversion to HTTP/1.x");
254         FullHttpRequest msg = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.valueOf(method
255                         .toString()), path.toString(), alloc.buffer(), validateHttpHeaders);
256         try {
257             addHttp2ToHttpHeaders(streamId, http2Headers, msg, false);
258         } catch (Http2Exception e) {
259             msg.release();
260             throw e;
261         } catch (Throwable t) {
262             msg.release();
263             throw streamError(streamId, PROTOCOL_ERROR, t, "HTTP/2 to HTTP/1.x headers conversion error");
264         }
265         return msg;
266     }
267 
268     /**
269      * Create a new object to contain the request data.
270      *
271      * @param streamId The stream associated with the request
272      * @param http2Headers The initial set of HTTP/2 headers to create the request with
273      * @param validateHttpHeaders <ul>
274      *        <li>{@code true} to validate HTTP headers in the http-codec</li>
275      *        <li>{@code false} not to validate HTTP headers in the http-codec</li>
276      *        </ul>
277      * @return A new request object which represents headers for a chunked request
278      * @throws Http2Exception see {@link #addHttp2ToHttpHeaders(int, Http2Headers, FullHttpMessage, boolean)}
279      */
280     public static HttpRequest toHttpRequest(int streamId, Http2Headers http2Headers, boolean validateHttpHeaders)
281                     throws Http2Exception {
282         // HTTP/2 does not define a way to carry the version identifier that is included in the HTTP/1.1 request line.
283         final CharSequence method = checkNotNull(http2Headers.method(),
284                 "method header cannot be null in conversion to HTTP/1.x");
285         final CharSequence path = checkNotNull(http2Headers.path(),
286                 "path header cannot be null in conversion to HTTP/1.x");
287         HttpRequest msg = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.valueOf(method.toString()),
288                 path.toString(), validateHttpHeaders);
289         try {
290             addHttp2ToHttpHeaders(streamId, http2Headers, msg.headers(), msg.protocolVersion(), false, true);
291         } catch (Http2Exception e) {
292             throw e;
293         } catch (Throwable t) {
294             throw streamError(streamId, PROTOCOL_ERROR, t, "HTTP/2 to HTTP/1.x headers conversion error");
295         }
296         return msg;
297     }
298 
299     /**
300      * Create a new object to contain the response data.
301      *
302      * @param streamId The stream associated with the response
303      * @param http2Headers The initial set of HTTP/2 headers to create the response with
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 response object which represents headers for a chunked response
309      * @throws Http2Exception see {@link #addHttp2ToHttpHeaders(int, Http2Headers,
310      *         HttpHeaders, HttpVersion, boolean, boolean)}
311      */
312     public static HttpResponse toHttpResponse(final int streamId,
313                                               final Http2Headers http2Headers,
314                                               final boolean validateHttpHeaders) throws Http2Exception {
315         final HttpResponseStatus status = parseStatus(http2Headers.status());
316         // HTTP/2 does not define a way to carry the version or reason phrase that is included in an
317         // HTTP/1.1 status line.
318         final HttpResponse msg = new DefaultHttpResponse(HttpVersion.HTTP_1_1, status, validateHttpHeaders);
319         try {
320             addHttp2ToHttpHeaders(streamId, http2Headers, msg.headers(), msg.protocolVersion(), false, true);
321         } catch (final Http2Exception e) {
322             throw e;
323         } catch (final Throwable t) {
324             throw streamError(streamId, PROTOCOL_ERROR, t, "HTTP/2 to HTTP/1.x headers conversion error");
325         }
326         return msg;
327     }
328 
329     /**
330      * Translate and add HTTP/2 headers to HTTP/1.x headers.
331      *
332      * @param streamId The stream associated with {@code sourceHeaders}.
333      * @param sourceHeaders The HTTP/2 headers to convert.
334      * @param destinationMessage The object which will contain the resulting HTTP/1.x headers.
335      * @param addToTrailer {@code true} to add to trailing headers. {@code false} to add to initial headers.
336      * @throws Http2Exception If not all HTTP/2 headers can be translated to HTTP/1.x.
337      * @see #addHttp2ToHttpHeaders(int, Http2Headers, HttpHeaders, HttpVersion, boolean, boolean)
338      */
339     public static void addHttp2ToHttpHeaders(int streamId, Http2Headers sourceHeaders,
340                     FullHttpMessage destinationMessage, boolean addToTrailer) throws Http2Exception {
341         addHttp2ToHttpHeaders(streamId, sourceHeaders,
342                 addToTrailer ? destinationMessage.trailingHeaders() : destinationMessage.headers(),
343                 destinationMessage.protocolVersion(), addToTrailer, destinationMessage instanceof HttpRequest);
344     }
345 
346     /**
347      * Translate and add HTTP/2 headers to HTTP/1.x headers.
348      *
349      * @param streamId The stream associated with {@code sourceHeaders}.
350      * @param inputHeaders The HTTP/2 headers to convert.
351      * @param outputHeaders The object which will contain the resulting HTTP/1.x headers..
352      * @param httpVersion What HTTP/1.x version {@code outputHeaders} should be treated as when doing the conversion.
353      * @param isTrailer {@code true} if {@code outputHeaders} should be treated as trailing headers.
354      * {@code false} otherwise.
355      * @param isRequest {@code true} if the {@code outputHeaders} will be used in a request message.
356      * {@code false} for response message.
357      * @throws Http2Exception If not all HTTP/2 headers can be translated to HTTP/1.x.
358      */
359     public static void addHttp2ToHttpHeaders(int streamId, Http2Headers inputHeaders, HttpHeaders outputHeaders,
360             HttpVersion httpVersion, boolean isTrailer, boolean isRequest) throws Http2Exception {
361         Http2ToHttpHeaderTranslator translator = new Http2ToHttpHeaderTranslator(streamId, outputHeaders, isRequest);
362         try {
363             for (Entry<CharSequence, CharSequence> entry : inputHeaders) {
364                 translator.translate(entry);
365             }
366         } catch (Http2Exception ex) {
367             throw ex;
368         } catch (Throwable t) {
369             throw streamError(streamId, PROTOCOL_ERROR, t, "HTTP/2 to HTTP/1.x headers conversion error");
370         }
371 
372         outputHeaders.remove(HttpHeaderNames.TRANSFER_ENCODING);
373         outputHeaders.remove(HttpHeaderNames.TRAILER);
374         if (!isTrailer) {
375             outputHeaders.setInt(ExtensionHeaderNames.STREAM_ID.text(), streamId);
376             HttpUtil.setKeepAlive(outputHeaders, httpVersion, true);
377         }
378     }
379 
380     /**
381      * Converts the given HTTP/1.x headers into HTTP/2 headers.
382      * The following headers are only used if they can not be found in from the {@code HOST} header or the
383      * {@code Request-Line} as defined by <a href="https://tools.ietf.org/html/rfc7230">rfc7230</a>
384      * <ul>
385      * <li>{@link ExtensionHeaderNames#SCHEME}</li>
386      * </ul>
387      * {@link ExtensionHeaderNames#PATH} is ignored and instead extracted from the {@code Request-Line}.
388      */
389     public static Http2Headers toHttp2Headers(HttpMessage in, boolean validateHeaders) {
390         HttpHeaders inHeaders = in.headers();
391         final Http2Headers out = new DefaultHttp2Headers(validateHeaders, inHeaders.size());
392         if (in instanceof HttpRequest) {
393             HttpRequest request = (HttpRequest) in;
394             URI requestTargetUri = URI.create(request.uri());
395             out.path(toHttp2Path(requestTargetUri));
396             out.method(request.method().asciiName());
397             setHttp2Scheme(inHeaders, requestTargetUri, out);
398 
399             if (!isOriginForm(requestTargetUri) && !isAsteriskForm(requestTargetUri)) {
400                 // Attempt to take from HOST header before taking from the request-line
401                 String host = inHeaders.getAsString(HttpHeaderNames.HOST);
402                 setHttp2Authority((host == null || host.isEmpty()) ? requestTargetUri.getAuthority() : host, out);
403             }
404         } else if (in instanceof HttpResponse) {
405             HttpResponse response = (HttpResponse) in;
406             out.status(response.status().codeAsText());
407         }
408 
409         // Add the HTTP headers which have not been consumed above
410         toHttp2Headers(inHeaders, out);
411         return out;
412     }
413 
414     public static Http2Headers toHttp2Headers(HttpHeaders inHeaders, boolean validateHeaders) {
415         if (inHeaders.isEmpty()) {
416             return EmptyHttp2Headers.INSTANCE;
417         }
418 
419         final Http2Headers out = new DefaultHttp2Headers(validateHeaders, inHeaders.size());
420         toHttp2Headers(inHeaders, out);
421         return out;
422     }
423 
424     private static CharSequenceMap<AsciiString> toLowercaseMap(Iterator<? extends CharSequence> valuesIter,
425                                                                int arraySizeHint) {
426         UnsupportedValueConverter<AsciiString> valueConverter = UnsupportedValueConverter.<AsciiString>instance();
427         CharSequenceMap<AsciiString> result = new CharSequenceMap<AsciiString>(true, valueConverter, arraySizeHint);
428 
429         while (valuesIter.hasNext()) {
430             AsciiString lowerCased = AsciiString.of(valuesIter.next()).toLowerCase();
431             try {
432                 int index = lowerCased.forEachByte(FIND_COMMA);
433                 if (index != -1) {
434                     int start = 0;
435                     do {
436                         result.add(lowerCased.subSequence(start, index, false).trim(), EMPTY_STRING);
437                         start = index + 1;
438                     } while (start < lowerCased.length() &&
439                              (index = lowerCased.forEachByte(start, lowerCased.length() - start, FIND_COMMA)) != -1);
440                     result.add(lowerCased.subSequence(start, lowerCased.length(), false).trim(), EMPTY_STRING);
441                 } else {
442                     result.add(lowerCased.trim(), EMPTY_STRING);
443                 }
444             } catch (Exception e) {
445                 // This is not expect to happen because FIND_COMMA never throws but must be caught
446                 // because of the ByteProcessor interface.
447                 throw new IllegalStateException(e);
448             }
449         }
450         return result;
451     }
452 
453     /**
454      * Filter the {@link HttpHeaderNames#TE} header according to the
455      * <a href="https://tools.ietf.org/html/rfc7540#section-8.1.2.2">special rules in the HTTP/2 RFC</a>.
456      * @param entry An entry whose name is {@link HttpHeaderNames#TE}.
457      * @param out the resulting HTTP/2 headers.
458      */
459     private static void toHttp2HeadersFilterTE(Entry<CharSequence, CharSequence> entry,
460                                                Http2Headers out) {
461         if (indexOf(entry.getValue(), ',', 0) == -1) {
462             if (contentEqualsIgnoreCase(trim(entry.getValue()), TRAILERS)) {
463                 out.add(TE, TRAILERS);
464             }
465         } else {
466             List<CharSequence> teValues = unescapeCsvFields(entry.getValue());
467             for (CharSequence teValue : teValues) {
468                 if (contentEqualsIgnoreCase(trim(teValue), TRAILERS)) {
469                     out.add(TE, TRAILERS);
470                     break;
471                 }
472             }
473         }
474     }
475 
476     public static void toHttp2Headers(HttpHeaders inHeaders, Http2Headers out) {
477         Iterator<Entry<CharSequence, CharSequence>> iter = inHeaders.iteratorCharSequence();
478         // Choose 8 as a default size because it is unlikely we will see more than 4 Connection headers values, but
479         // still allowing for "enough" space in the map to reduce the chance of hash code collision.
480         CharSequenceMap<AsciiString> connectionBlacklist =
481             toLowercaseMap(inHeaders.valueCharSequenceIterator(CONNECTION), 8);
482         while (iter.hasNext()) {
483             Entry<CharSequence, CharSequence> entry = iter.next();
484             final AsciiString aName = AsciiString.of(entry.getKey()).toLowerCase();
485             if (!HTTP_TO_HTTP2_HEADER_BLACKLIST.contains(aName) && !connectionBlacklist.contains(aName)) {
486                 // https://tools.ietf.org/html/rfc7540#section-8.1.2.2 makes a special exception for TE
487                 if (aName.contentEqualsIgnoreCase(TE)) {
488                     toHttp2HeadersFilterTE(entry, out);
489                 } else if (aName.contentEqualsIgnoreCase(COOKIE)) {
490                     AsciiString value = AsciiString.of(entry.getValue());
491                     // split up cookies to allow for better compression
492                     // https://tools.ietf.org/html/rfc7540#section-8.1.2.5
493                     try {
494                         int index = value.forEachByte(FIND_SEMI_COLON);
495                         if (index != -1) {
496                             int start = 0;
497                             do {
498                                 out.add(COOKIE, value.subSequence(start, index, false));
499                                 // skip 2 characters "; " (see https://tools.ietf.org/html/rfc6265#section-4.2.1)
500                                 start = index + 2;
501                             } while (start < value.length() &&
502                                     (index = value.forEachByte(start, value.length() - start, FIND_SEMI_COLON)) != -1);
503                             if (start >= value.length()) {
504                                 throw new IllegalArgumentException("cookie value is of unexpected format: " + value);
505                             }
506                             out.add(COOKIE, value.subSequence(start, value.length(), false));
507                         } else {
508                             out.add(COOKIE, value);
509                         }
510                     } catch (Exception e) {
511                         // This is not expect to happen because FIND_SEMI_COLON never throws but must be caught
512                         // because of the ByteProcessor interface.
513                         throw new IllegalStateException(e);
514                     }
515                 } else {
516                     out.add(aName, entry.getValue());
517                 }
518             }
519         }
520     }
521 
522     /**
523      * Generate a HTTP/2 {code :path} from a URI in accordance with
524      * <a href="https://tools.ietf.org/html/rfc7230#section-5.3">rfc7230, 5.3</a>.
525      */
526     private static AsciiString toHttp2Path(URI uri) {
527         StringBuilder pathBuilder = new StringBuilder(length(uri.getRawPath()) +
528                 length(uri.getRawQuery()) + length(uri.getRawFragment()) + 2);
529         if (!isNullOrEmpty(uri.getRawPath())) {
530             pathBuilder.append(uri.getRawPath());
531         }
532         if (!isNullOrEmpty(uri.getRawQuery())) {
533             pathBuilder.append('?');
534             pathBuilder.append(uri.getRawQuery());
535         }
536         if (!isNullOrEmpty(uri.getRawFragment())) {
537             pathBuilder.append('#');
538             pathBuilder.append(uri.getRawFragment());
539         }
540         String path = pathBuilder.toString();
541         return path.isEmpty() ? EMPTY_REQUEST_PATH : new AsciiString(path);
542     }
543 
544     // package-private for testing only
545     static void setHttp2Authority(String authority, Http2Headers out) {
546         // The authority MUST NOT include the deprecated "userinfo" subcomponent
547         if (authority != null) {
548             if (authority.isEmpty()) {
549                 out.authority(EMPTY_STRING);
550             } else {
551                 int start = authority.indexOf('@') + 1;
552                 int length = authority.length() - start;
553                 if (length == 0) {
554                     throw new IllegalArgumentException("authority: " + authority);
555                 }
556                 out.authority(new AsciiString(authority, start, length));
557             }
558         }
559     }
560 
561     private static void setHttp2Scheme(HttpHeaders in, URI uri, Http2Headers out) {
562         String value = uri.getScheme();
563         if (value != null) {
564             out.scheme(new AsciiString(value));
565             return;
566         }
567 
568         // Consume the Scheme extension header if present
569         CharSequence cValue = in.get(ExtensionHeaderNames.SCHEME.text());
570         if (cValue != null) {
571             out.scheme(AsciiString.of(cValue));
572             return;
573         }
574 
575         if (uri.getPort() == HTTPS.port()) {
576             out.scheme(HTTPS.name());
577         } else if (uri.getPort() == HTTP.port()) {
578             out.scheme(HTTP.name());
579         } else {
580             throw new IllegalArgumentException(":scheme must be specified. " +
581                     "see https://tools.ietf.org/html/rfc7540#section-8.1.2.3");
582         }
583     }
584 
585     /**
586      * Utility which translates HTTP/2 headers to HTTP/1 headers.
587      */
588     private static final class Http2ToHttpHeaderTranslator {
589         /**
590          * Translations from HTTP/2 header name to the HTTP/1.x equivalent.
591          */
592         private static final CharSequenceMap<AsciiString>
593             REQUEST_HEADER_TRANSLATIONS = new CharSequenceMap<AsciiString>();
594         private static final CharSequenceMap<AsciiString>
595             RESPONSE_HEADER_TRANSLATIONS = new CharSequenceMap<AsciiString>();
596         static {
597             RESPONSE_HEADER_TRANSLATIONS.add(Http2Headers.PseudoHeaderName.AUTHORITY.value(),
598                             HttpHeaderNames.HOST);
599             RESPONSE_HEADER_TRANSLATIONS.add(Http2Headers.PseudoHeaderName.SCHEME.value(),
600                             ExtensionHeaderNames.SCHEME.text());
601             REQUEST_HEADER_TRANSLATIONS.add(RESPONSE_HEADER_TRANSLATIONS);
602             RESPONSE_HEADER_TRANSLATIONS.add(Http2Headers.PseudoHeaderName.PATH.value(),
603                             ExtensionHeaderNames.PATH.text());
604         }
605 
606         private final int streamId;
607         private final HttpHeaders output;
608         private final CharSequenceMap<AsciiString> translations;
609 
610         /**
611          * Create a new instance
612          *
613          * @param output The HTTP/1.x headers object to store the results of the translation
614          * @param request if {@code true}, translates headers using the request translation map. Otherwise uses the
615          *        response translation map.
616          */
617         Http2ToHttpHeaderTranslator(int streamId, HttpHeaders output, boolean request) {
618             this.streamId = streamId;
619             this.output = output;
620             translations = request ? REQUEST_HEADER_TRANSLATIONS : RESPONSE_HEADER_TRANSLATIONS;
621         }
622 
623         public void translate(Entry<CharSequence, CharSequence> entry) throws Http2Exception {
624             final CharSequence name = entry.getKey();
625             final CharSequence value = entry.getValue();
626             AsciiString translatedName = translations.get(name);
627             if (translatedName != null) {
628                 output.add(translatedName, AsciiString.of(value));
629             } else if (!Http2Headers.PseudoHeaderName.isPseudoHeader(name)) {
630                 // https://tools.ietf.org/html/rfc7540#section-8.1.2.3
631                 // All headers that start with ':' are only valid in HTTP/2 context
632                 if (name.length() == 0 || name.charAt(0) == ':') {
633                     throw streamError(streamId, PROTOCOL_ERROR,
634                             "Invalid HTTP/2 header '%s' encountered in translation to HTTP/1.x", name);
635                 }
636                 if (COOKIE.equals(name)) {
637                     // combine the cookie values into 1 header entry.
638                     // https://tools.ietf.org/html/rfc7540#section-8.1.2.5
639                     String existingCookie = output.get(COOKIE);
640                     output.set(COOKIE,
641                                (existingCookie != null) ? (existingCookie + "; " + value) : value);
642                 } else {
643                     output.add(name, value);
644                 }
645             }
646         }
647     }
648 }