View Javadoc
1   /*
2    * Copyright 2020 The Netty Project
3    *
4    * The Netty Project licenses this file to you under the Apache License,
5    * version 2.0 (the "License"); you may not use this file except in compliance
6    * with the License. You may obtain a 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
11   * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12   * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13   * License for the specific language governing permissions and limitations
14   * under the License.
15   */
16  package io.netty.handler.codec.http3;
17  
18  import io.netty.handler.codec.http.HttpHeaderNames;
19  import io.netty.handler.codec.http.HttpHeaderValidationUtil;
20  import io.netty.handler.codec.http.HttpMethod;
21  import io.netty.util.AsciiString;
22  
23  import java.util.List;
24  import java.util.function.BiConsumer;
25  
26  import static io.netty.handler.codec.http3.Http3Headers.PseudoHeaderName.AUTHORITY;
27  import static io.netty.handler.codec.http3.Http3Headers.PseudoHeaderName.METHOD;
28  import static io.netty.handler.codec.http3.Http3Headers.PseudoHeaderName.PATH;
29  import static io.netty.handler.codec.http3.Http3Headers.PseudoHeaderName.PROTOCOL;
30  import static io.netty.handler.codec.http3.Http3Headers.PseudoHeaderName.SCHEME;
31  import static io.netty.handler.codec.http3.Http3Headers.PseudoHeaderName.STATUS;
32  import static io.netty.handler.codec.http3.Http3Headers.PseudoHeaderName.getPseudoHeader;
33  import static io.netty.handler.codec.http3.Http3Headers.PseudoHeaderName.hasPseudoHeaderFormat;
34  
35  /**
36   * {@link BiConsumer} that does add header names and values to
37   * {@link Http3Headers} while also validate these.
38   */
39  final class Http3HeadersSink implements BiConsumer<CharSequence, CharSequence> {
40      private final Http3Headers headers;
41      private final long maxHeaderListSize;
42      private final boolean validate;
43      private final boolean trailer;
44      private long headersLength;
45      private boolean exceededMaxLength;
46      private Http3HeadersValidationException validationException;
47      private HeaderType previousType;
48      private boolean request;
49      private int receivedPseudoHeaders;
50  
51      Http3HeadersSink(Http3Headers headers, long maxHeaderListSize, boolean validate, boolean trailer) {
52          this.headers = headers;
53          this.maxHeaderListSize = maxHeaderListSize;
54          this.validate = validate;
55          this.trailer = trailer;
56      }
57  
58      /**
59       * This method must be called after the sink is used.
60       */
61      void finish() throws Http3HeadersValidationException, Http3Exception {
62          if (exceededMaxLength) {
63              throw new Http3Exception(Http3ErrorCode.H3_EXCESSIVE_LOAD,
64                      String.format("Header size exceeded max allowed size (%d)", maxHeaderListSize));
65          }
66          if (validationException != null) {
67              throw validationException;
68          }
69          if (validate) {
70              if (trailer) {
71                  if (receivedPseudoHeaders != 0) {
72                      // Trailers must not have pseudo headers.
73                      throw new Http3HeadersValidationException("Pseudo-header(s) included in trailers.");
74                  }
75                  return;
76              }
77  
78              // Validate that all mandatory pseudo-headers are included.
79              if (request) {
80                  validateAuthorityAndHost();
81                  CharSequence method = headers.method();
82                  // fast-path
83                  if (HttpMethod.CONNECT.asciiName().contentEqualsIgnoreCase(method)) {
84                      // Check if this is an Extended CONNECT request (RFC 9220)
85                      // Extended CONNECT includes the :protocol pseudo-header
86                      if ((receivedPseudoHeaders & PROTOCOL.getFlag()) != 0) {
87                          // Extended CONNECT (RFC 9220) requires:
88                          // - :method
89                          // - :scheme
90                          // - :authority
91                          // - :path
92                          // - :protocol
93                          final int requiredPseudoHeaders = METHOD.getFlag() | SCHEME.getFlag() |
94                                                           AUTHORITY.getFlag() | PATH.getFlag() | PROTOCOL.getFlag();
95                          if (receivedPseudoHeaders != requiredPseudoHeaders) {
96                              throw new Http3HeadersValidationException(
97                                      "Not all mandatory pseudo-headers included for Extended CONNECT.");
98                          }
99                      } else {
100                         // Regular CONNECT (RFC 9114) requires:
101                         // - :method
102                         // - :authority
103                         final int requiredPseudoHeaders = METHOD.getFlag() | AUTHORITY.getFlag();
104                         if (receivedPseudoHeaders != requiredPseudoHeaders) {
105                             throw new Http3HeadersValidationException("Not all mandatory pseudo-headers included.");
106                         }
107                     }
108                 } else if (HttpMethod.OPTIONS.asciiName().contentEqualsIgnoreCase(method)) {
109                     // See:
110                     //
111                     // https://www.rfc-editor.org/rfc/rfc9114.html#section-4.3.1
112                     // https://www.rfc-editor.org/rfc/rfc9110#section-7.1
113                     // - :method
114                     // - :scheme
115                     // - :authority
116                     // - :path
117                     final int requiredPseudoHeaders = METHOD.getFlag() | SCHEME.getFlag() | PATH.getFlag();
118                     if ((receivedPseudoHeaders & requiredPseudoHeaders) != requiredPseudoHeaders ||
119                             (!authorityOrHostHeaderReceived() && !"*".contentEquals(headers.path()))) {
120                         throw new Http3HeadersValidationException("Not all mandatory pseudo-headers included.");
121                     }
122                 } else {
123                     // For other requests we must include:
124                     // - :method
125                     // - :scheme
126                     // - :authority
127                     // - :path
128                     final int requiredPseudoHeaders = METHOD.getFlag() | SCHEME.getFlag() | PATH.getFlag();
129                     if ((receivedPseudoHeaders & requiredPseudoHeaders) != requiredPseudoHeaders ||
130                         !authorityOrHostHeaderReceived()) {
131                         throw new Http3HeadersValidationException("Not all mandatory pseudo-headers included.");
132                     }
133                 }
134             } else {
135                 // For responses we must include:
136                 // - :status
137                 if (receivedPseudoHeaders != STATUS.getFlag()) {
138                     throw new Http3HeadersValidationException("Not all mandatory pseudo-headers included.");
139                 }
140             }
141         }
142     }
143 
144     /**
145      * https://www.rfc-editor.org/rfc/rfc9114#section-4.3.1
146      * the request MUST contain either an :authority pseudo-header field or a Host header field.
147      * If both fields are present, they MUST contain the same value.
148      * https://datatracker.ietf.org/doc/html/rfc9110#section-5.3
149      * a sender MUST NOT generate multiple field lines with the same name ...
150      * unless that field's definition allows ... a comma-separated list
151      */
152     private void validateAuthorityAndHost() {
153         if (!headers.contains(HttpHeaderNames.HOST)) {
154             return;
155         }
156         CharSequence authority = headers.authority();
157         List<CharSequence> hosts = headers.getAll(HttpHeaderNames.HOST);
158         CharSequence expected = authority != null ? authority : hosts.get(0);
159         for (int i = 0; i < hosts.size(); i++) {
160             if (!AsciiString.contentEqualsIgnoreCase(expected, hosts.get(i))) {
161                 throw new Http3HeadersValidationException(authority != null ?
162                         "Conflicting ':authority' pseudo-header and 'host' header field." :
163                         "Conflicting 'host' header fields.");
164             }
165         }
166     }
167 
168     /**
169      * Find host header field in case the :authority pseudo header is not specified.
170      * See:
171      * https://www.rfc-editor.org/rfc/rfc9110#section-7.2
172      */
173     private boolean authorityOrHostHeaderReceived() {
174         return (receivedPseudoHeaders & AUTHORITY.getFlag()) == AUTHORITY.getFlag() ||
175                 headers.contains(HttpHeaderNames.HOST);
176     }
177 
178     @Override
179     public void accept(CharSequence name, CharSequence value) {
180         headersLength += QpackHeaderField.sizeOf(name, value);
181         exceededMaxLength |= headersLength > maxHeaderListSize;
182 
183         if (exceededMaxLength || validationException != null) {
184             // We don't store the header since we've already failed validation requirements.
185             return;
186         }
187 
188         if (validate) {
189             try {
190                  validate(headers, name, value);
191             } catch (Http3HeadersValidationException ex) {
192                 validationException = ex;
193                 return;
194             }
195         }
196 
197         headers.add(name, value);
198     }
199 
200     private void validate(Http3Headers headers, CharSequence name, CharSequence value) {
201         if (hasPseudoHeaderFormat(name)) {
202             if (previousType == HeaderType.REGULAR_HEADER) {
203                 throw new Http3HeadersValidationException(
204                         String.format("Pseudo-header field '%s' found after regular header.", name));
205             }
206 
207             final Http3Headers.PseudoHeaderName pseudoHeader = getPseudoHeader(name);
208             if (pseudoHeader == null) {
209                 throw new Http3HeadersValidationException(
210                         String.format("Invalid HTTP/3 pseudo-header '%s' encountered.", name));
211             }
212             if ((receivedPseudoHeaders & pseudoHeader.getFlag()) != 0) {
213                 // There can't be any duplicates for pseudy header names.
214                 throw new Http3HeadersValidationException(
215                         String.format("Pseudo-header field '%s' exists already.", name));
216             }
217             receivedPseudoHeaders |= pseudoHeader.getFlag();
218 
219             final HeaderType currentHeaderType = pseudoHeader.isRequestOnly() ?
220                     HeaderType.REQUEST_PSEUDO_HEADER : HeaderType.RESPONSE_PSEUDO_HEADER;
221             request = pseudoHeader.isRequestOnly();
222             previousType = currentHeaderType;
223         } else {
224             // https://www.rfc-editor.org/rfc/rfc9114.html#section-4.2
225             if (HttpHeaderValidationUtil.validateToken(name) != -1) {
226                 throw new Http3HeadersValidationException(String.format("Invalid header name '%s'.", name));
227             }
228             if (HttpHeaderValidationUtil.isConnectionHeader(name, true)) {
229                 throw new Http3HeadersValidationException(
230                         String.format("Illegal connection-specific header '%s' encountered.", name));
231             }
232             if (HttpHeaderValidationUtil.isTeNotTrailers(name, value)) {
233                 throw new Http3HeadersValidationException(
234                         "Illegal value specified for the 'TE' header (only 'trailers' is allowed).");
235             }
236             previousType = HeaderType.REGULAR_HEADER;
237         }
238 
239         // https://www.rfc-editor.org/rfc/rfc9114.html#section-10.3
240         int index = HttpHeaderValidationUtil.validateValidHeaderValue(value);
241         if (index != -1) {
242             throw new Http3HeadersValidationException(String.format(
243                     "Value of header '%s' contains prohibited character 0x%02X at index %d.",
244                     name, (int) value.charAt(index), index));
245         }
246     }
247 
248     private enum HeaderType {
249         REGULAR_HEADER,
250         REQUEST_PSEUDO_HEADER,
251         RESPONSE_PSEUDO_HEADER
252     }
253 }