View Javadoc
1   /*
2    * Copyright 2012 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.http;
17  
18  import static io.netty.util.internal.ObjectUtil.checkPositiveOrZero;
19  
20  import io.netty.buffer.ByteBuf;
21  import io.netty.util.CharsetUtil;
22  import io.netty.util.internal.ObjectUtil;
23  
24  import java.util.regex.Pattern;
25  import java.util.Locale;
26  
27  
28  /**
29   * The version of HTTP or its derived protocols, such as
30   * <a href="https://en.wikipedia.org/wiki/Real_Time_Streaming_Protocol">RTSP</a> and
31   * <a href="https://en.wikipedia.org/wiki/Internet_Content_Adaptation_Protocol">ICAP</a>.
32   */
33  public class HttpVersion implements Comparable<HttpVersion> {
34  
35      private static final Pattern VERSION_PATTERN =
36          Pattern.compile("(\\S+)/(\\d+)\\.(\\d+)");
37      static final String HTTP_1_0_STRING = "HTTP/1.0";
38      static final String HTTP_1_1_STRING = "HTTP/1.1";
39      private static final int MAX_INT_DIV_10 = Integer.MAX_VALUE / 10;
40      private static final int MAX_INT_MOD_10 = Integer.MAX_VALUE % 10;
41  
42      /**
43       * HTTP/1.0
44       */
45      public static final HttpVersion HTTP_1_0 = new HttpVersion("HTTP", 1, 0, false, true);
46  
47      /**
48       * HTTP/1.1
49       */
50      public static final HttpVersion HTTP_1_1 = new HttpVersion("HTTP", 1, 1, true, true);
51  
52      /**
53       * Returns an existing or new {@link HttpVersion} instance which matches to
54       * the specified protocol version string.  If the specified {@code text} is
55       * equal to {@code "HTTP/1.0"}, {@link #HTTP_1_0} will be returned.  If the
56       * specified {@code text} is equal to {@code "HTTP/1.1"}, {@link #HTTP_1_1}
57       * will be returned.  Otherwise, a new {@link HttpVersion} instance will be
58       * returned.
59       */
60      public static HttpVersion valueOf(String text) {
61          return valueOf(text, false);
62      }
63  
64      static HttpVersion valueOf(String text, boolean strict) {
65          ObjectUtil.checkNotNull(text, "text");
66  
67          // super fast-path
68          if (text == HTTP_1_1_STRING) {
69              return HTTP_1_1;
70          }
71          if (text == HTTP_1_0_STRING) {
72              return HTTP_1_0;
73          }
74  
75          if (text.isEmpty()) {
76              throw new IllegalArgumentException("text is empty (possibly HTTP/0.9)");
77          }
78  
79          // Try to match without convert to uppercase first as this is what 99% of all clients
80          // will send anyway. Also there is a change to the RFC to make it clear that it is
81          // expected to be case-sensitive
82          //
83          // See:
84          // * https://trac.tools.ietf.org/wg/httpbis/trac/ticket/1
85          // * https://trac.tools.ietf.org/wg/httpbis/trac/wiki
86          //
87          HttpVersion version = version0(text);
88          if (version == null) {
89              version = new HttpVersion(text, strict, true);
90          }
91          return version;
92      }
93  
94      private static HttpVersion version0(String text) {
95          if (HTTP_1_1_STRING.equals(text)) {
96              return HTTP_1_1;
97          }
98          if (HTTP_1_0_STRING.equals(text)) {
99              return HTTP_1_0;
100         }
101         return null;
102     }
103 
104     private final String protocolName;
105     private final int majorVersion;
106     private final int minorVersion;
107     private final String text;
108     private final boolean keepAliveDefault;
109     private final byte[] bytes;
110 
111     /**
112      * Creates a new HTTP version with the specified version string.  You will
113      * not need to create a new instance unless you are implementing a protocol
114      * derived from HTTP, such as
115      * <a href="https://en.wikipedia.org/wiki/Real_Time_Streaming_Protocol">RTSP</a> and
116      * <a href="https://en.wikipedia.org/wiki/Internet_Content_Adaptation_Protocol">ICAP</a>.
117      *
118      * @param keepAliveDefault
119      *        {@code true} if and only if the connection is kept alive unless
120      *        the {@code "Connection"} header is set to {@code "close"} explicitly.
121      */
122     public HttpVersion(String text, boolean keepAliveDefault) {
123         this(text, false, keepAliveDefault);
124     }
125 
126     HttpVersion(String text, boolean strict, boolean keepAliveDefault) {
127         // toUpperCase() without an explicit Locale uses the JVM default. In Turkish locale
128         // (tr_TR) 'i' uppercases to 'İ' (U+0130), which would corrupt protocol strings such
129         // as "icap/1.0" or any custom HTTP-derived scheme that contains a lowercase 'i'.
130         // Control characters or whitespace at the token boundary must fail the checks below.
131         ObjectUtil.checkNotNull(text, "text");
132         if (text.isEmpty()) {
133             throw new IllegalArgumentException("text must not be empty");
134         }
135         text = text.toUpperCase(Locale.US);
136 
137         if (strict) {
138             // Only single digit major / minor version is allowed.
139             // See
140             //  - https://datatracker.ietf.org/doc/html/rfc7230#section-2.6
141             //  - https://datatracker.ietf.org/doc/html/rfc9110#name-protocol-version
142             if (text.length() != 8 || !text.startsWith("HTTP/") || text.charAt(6) != '.') {
143                 throw new IllegalArgumentException("invalid version format: " + text);
144             }
145             protocolName = "HTTP";
146             majorVersion = toDecimal(text.charAt(5));
147             minorVersion = toDecimal(text.charAt(7));
148         } else {
149             int slashIndex = text.indexOf('/');
150             int dotIndex = text.indexOf('.', slashIndex + 1);
151 
152             if (slashIndex <= 0 || dotIndex <= slashIndex + 1
153                     || dotIndex >= text.length() - 1 || hasControlOrWhitespace(text, slashIndex)) {
154                 throw new IllegalArgumentException("invalid version format: " + text);
155             }
156 
157             protocolName = text.substring(0, slashIndex);
158             majorVersion = parseInt(text, slashIndex + 1, dotIndex);
159             minorVersion = parseInt(text, dotIndex + 1, text.length());
160         }
161 
162         this.text = protocolName + '/' + majorVersion + '.' + minorVersion;
163         this.keepAliveDefault = keepAliveDefault;
164         bytes = null;
165     }
166 
167     private static boolean hasControlOrWhitespace(String s, int end) {
168         for (int i = 0; i < end; i++) {
169             char c = s.charAt(i);
170             if (Character.isISOControl(c) || Character.isWhitespace(c)) {
171                 return true;
172             }
173         }
174         return false;
175     }
176 
177     private static int parseInt(String text, int start, int end) {
178         int result = 0;
179         for (int i = start; i < end; i++) {
180             int digit = toDecimal(text.charAt(i));
181             if (result > MAX_INT_DIV_10 || result == MAX_INT_DIV_10 && digit > MAX_INT_MOD_10) {
182                 throw new IllegalArgumentException("Invalid version number, too large: " + text);
183             }
184             result = result * 10 + digit;
185         }
186         return result;
187     }
188 
189     private static int toDecimal(final int value) {
190         if (value < '0' || value > '9') {
191             throw new IllegalArgumentException("Invalid version number, only 0-9 (0x30-0x39) allowed," +
192                     " but received a '" + (char) value + "' (0x" + Integer.toHexString(value) + ")");
193         }
194         return value - '0';
195     }
196 
197     /**
198      * Creates a new HTTP version with the specified protocol name and version
199      * numbers.  You will not need to create a new instance unless you are
200      * implementing a protocol derived from HTTP, such as
201      * <a href="https://en.wikipedia.org/wiki/Real_Time_Streaming_Protocol">RTSP</a> and
202      * <a href="https://en.wikipedia.org/wiki/Internet_Content_Adaptation_Protocol">ICAP</a>
203      *
204      * @param keepAliveDefault
205      *        {@code true} if and only if the connection is kept alive unless
206      *        the {@code "Connection"} header is set to {@code "close"} explicitly.
207      */
208     public HttpVersion(
209             String protocolName, int majorVersion, int minorVersion,
210             boolean keepAliveDefault) {
211         this(protocolName, majorVersion, minorVersion, keepAliveDefault, false);
212     }
213 
214     private HttpVersion(
215             String protocolName, int majorVersion, int minorVersion,
216             boolean keepAliveDefault, boolean bytes) {
217         // See the comment in the (text, strict, keepAliveDefault) constructor for why this needs
218         // an explicit Locale.US: avoids the Turkish-locale 'i' -> 'İ' corruption.
219         ObjectUtil.checkNotNull(protocolName, "protocolName");
220         if (protocolName.isEmpty()) {
221             throw new IllegalArgumentException("protocolName must not be empty");
222         }
223         protocolName = protocolName.toUpperCase(Locale.US);
224 
225         if (hasControlOrWhitespace(protocolName, protocolName.length())) {
226             throw new IllegalArgumentException("invalid character in protocolName");
227         }
228 
229         checkPositiveOrZero(majorVersion, "majorVersion");
230         checkPositiveOrZero(minorVersion, "minorVersion");
231 
232         this.protocolName = protocolName;
233         this.majorVersion = majorVersion;
234         this.minorVersion = minorVersion;
235         text = protocolName + '/' + majorVersion + '.' + minorVersion;
236         this.keepAliveDefault = keepAliveDefault;
237 
238         if (bytes) {
239             this.bytes = text.getBytes(CharsetUtil.US_ASCII);
240         } else {
241             this.bytes = null;
242         }
243     }
244 
245     /**
246      * Returns the name of the protocol such as {@code "HTTP"} in {@code "HTTP/1.0"}.
247      */
248     public String protocolName() {
249         return protocolName;
250     }
251 
252     /**
253      * Returns the name of the protocol such as {@code 1} in {@code "HTTP/1.0"}.
254      */
255     public int majorVersion() {
256         return majorVersion;
257     }
258 
259     /**
260      * Returns the name of the protocol such as {@code 0} in {@code "HTTP/1.0"}.
261      */
262     public int minorVersion() {
263         return minorVersion;
264     }
265 
266     /**
267      * Returns the full protocol version text such as {@code "HTTP/1.0"}.
268      */
269     public String text() {
270         return text;
271     }
272 
273     /**
274      * Returns {@code true} if and only if the connection is kept alive unless
275      * the {@code "Connection"} header is set to {@code "close"} explicitly.
276      */
277     public boolean isKeepAliveDefault() {
278         return keepAliveDefault;
279     }
280 
281     /**
282      * Returns the full protocol version text such as {@code "HTTP/1.0"}.
283      */
284     @Override
285     public String toString() {
286         return text();
287     }
288 
289     @Override
290     public int hashCode() {
291         return (protocolName().hashCode() * 31 + majorVersion()) * 31 +
292                minorVersion();
293     }
294 
295     @Override
296     public boolean equals(Object o) {
297         if (!(o instanceof HttpVersion)) {
298             return false;
299         }
300 
301         HttpVersion that = (HttpVersion) o;
302         return minorVersion() == that.minorVersion() &&
303                majorVersion() == that.majorVersion() &&
304                protocolName().equals(that.protocolName());
305     }
306 
307     @Override
308     public int compareTo(HttpVersion o) {
309         int v = protocolName().compareTo(o.protocolName());
310         if (v != 0) {
311             return v;
312         }
313 
314         v = majorVersion() - o.majorVersion();
315         if (v != 0) {
316             return v;
317         }
318 
319         return minorVersion() - o.minorVersion();
320     }
321 
322     void encode(ByteBuf buf) {
323         if (bytes == null) {
324             buf.writeCharSequence(text, CharsetUtil.US_ASCII);
325         } else {
326             buf.writeBytes(bytes);
327         }
328     }
329 }