-
Notifications
You must be signed in to change notification settings - Fork 2k
/
HttpUtils.java
981 lines (904 loc) · 31.3 KB
/
HttpUtils.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
/*
* Copyright (c) 2011-2023 Contributors to the Eclipse Foundation
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0
* which is available at https://www.apache.org/licenses/LICENSE-2.0.
*
* SPDX-License-Identifier: EPL-2.0 OR Apache-2.0
*/
package io.vertx.core.http.impl;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.handler.codec.http.*;
import io.netty.handler.codec.http2.Http2Settings;
import io.netty.util.AsciiString;
import io.netty.util.CharsetUtil;
import io.vertx.core.Future;
import io.vertx.core.MultiMap;
import io.vertx.core.buffer.Buffer;
import io.vertx.core.file.AsyncFile;
import io.vertx.core.file.FileSystem;
import io.vertx.core.file.OpenOptions;
import io.vertx.core.http.HttpClosedException;
import io.vertx.core.http.HttpServerRequest;
import io.vertx.core.http.HttpServerResponse;
import io.vertx.core.http.StreamPriority;
import io.vertx.core.impl.ContextInternal;
import io.vertx.core.impl.VertxInternal;
import io.vertx.core.net.HostAndPort;
import io.vertx.core.spi.tracing.TagExtractor;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.Base64;
import java.util.List;
import java.util.Map;
import java.util.function.Consumer;
import static io.netty.handler.codec.http.HttpHeaderValues.APPLICATION_X_WWW_FORM_URLENCODED;
import static io.netty.handler.codec.http.HttpHeaderValues.MULTIPART_FORM_DATA;
import static io.netty.handler.codec.http.HttpResponseStatus.METHOD_NOT_ALLOWED;
import static io.netty.handler.codec.http.HttpVersion.HTTP_1_1;
import static io.vertx.core.http.Http2Settings.*;
/**
* Various http utils.
*
* @author <a href="mailto:nmaurer@redhat.com">Norman Maurer</a>
*/
public final class HttpUtils {
static final HttpClosedException CONNECTION_CLOSED_EXCEPTION = new HttpClosedException("Connection was closed");
static final HttpClosedException STREAM_CLOSED_EXCEPTION = new HttpClosedException("Stream was closed");
static final int SC_SWITCHING_PROTOCOLS = 101;
static final int SC_BAD_GATEWAY = 502;
static final TagExtractor<HttpServerRequest> SERVER_REQUEST_TAG_EXTRACTOR = new TagExtractor<HttpServerRequest>() {
@Override
public int len(HttpServerRequest req) {
return req.query() == null ? 4 : 5;
}
@Override
public String name(HttpServerRequest req, int index) {
switch (index) {
case 0:
return "http.url";
case 1:
return "http.method";
case 2:
return "http.scheme";
case 3:
return "http.path";
case 4:
return "http.query";
}
throw new IndexOutOfBoundsException("Invalid tag index " + index);
}
@Override
public String value(HttpServerRequest req, int index) {
switch (index) {
case 0:
return req.absoluteURI();
case 1:
return req.method().name();
case 2:
return req.scheme();
case 3:
return req.path();
case 4:
return req.query();
}
throw new IndexOutOfBoundsException("Invalid tag index " + index);
}
};
static final TagExtractor<HttpServerResponse> SERVER_RESPONSE_TAG_EXTRACTOR = new TagExtractor<HttpServerResponse>() {
@Override
public int len(HttpServerResponse resp) {
return 1;
}
@Override
public String name(HttpServerResponse resp, int index) {
if (index == 0) {
return "http.status_code";
}
throw new IndexOutOfBoundsException("Invalid tag index " + index);
}
@Override
public String value(HttpServerResponse resp, int index) {
if (index == 0) {
return "" + resp.getStatusCode();
}
throw new IndexOutOfBoundsException("Invalid tag index " + index);
}
};
static final TagExtractor<HttpRequestHead> CLIENT_HTTP_REQUEST_TAG_EXTRACTOR = new TagExtractor<HttpRequestHead>() {
@Override
public int len(HttpRequestHead req) {
return 2;
}
@Override
public String name(HttpRequestHead req, int index) {
switch (index) {
case 0:
return "http.url";
case 1:
return "http.method";
}
throw new IndexOutOfBoundsException("Invalid tag index " + index);
}
@Override
public String value(HttpRequestHead req, int index) {
switch (index) {
case 0:
return req.absoluteURI;
case 1:
return req.method.name();
}
throw new IndexOutOfBoundsException("Invalid tag index " + index);
}
};
static final TagExtractor<HttpResponseHead> CLIENT_RESPONSE_TAG_EXTRACTOR = new TagExtractor<HttpResponseHead>() {
@Override
public int len(HttpResponseHead resp) {
return 1;
}
@Override
public String name(HttpResponseHead resp, int index) {
if (index == 0) {
return "http.status_code";
}
throw new IndexOutOfBoundsException("Invalid tag index " + index);
}
@Override
public String value(HttpResponseHead resp, int index) {
if (index == 0) {
return "" + resp.statusCode;
}
throw new IndexOutOfBoundsException("Invalid tag index " + index);
}
};
static final StreamPriority DEFAULT_STREAM_PRIORITY = new StreamPriority() {
@Override
public StreamPriority setWeight(short weight) {
throw new UnsupportedOperationException("Unmodifiable stream priority");
}
@Override
public StreamPriority setDependency(int dependency) {
throw new UnsupportedOperationException("Unmodifiable stream priority");
}
@Override
public StreamPriority setExclusive(boolean exclusive) {
throw new UnsupportedOperationException("Unmodifiable stream priority");
}
};
private HttpUtils() {
}
private static int indexOfSlash(CharSequence str, int start) {
for (int i = start; i < str.length(); i++) {
if (str.charAt(i) == '/') {
return i;
}
}
return -1;
}
private static boolean matches(CharSequence path, int start, String what) {
return matches(path, start, what, false);
}
private static boolean matches(CharSequence path, int start, String what, boolean exact) {
if (exact) {
if (path.length() - start != what.length()) {
return false;
}
}
if (path.length() - start >= what.length()) {
for (int i = 0; i < what.length(); i++) {
if (path.charAt(start + i) != what.charAt(i)) {
return false;
}
}
return true;
}
return false;
}
/**
* Normalizes a path as per <a href="http://tools.ietf.org/html/rfc3986#section-5.2.4>rfc3986</a>.
*
* There are 2 extra transformations that are not part of the spec but kept for backwards compatibility:
*
* double slash // will be converted to single slash and the path will always start with slash.
*
* Null paths are not normalized as nothing can be said about them.
*
* @param pathname raw path
* @return normalized path
*/
public static String normalizePath(String pathname) {
if (pathname == null) {
return null;
}
// add trailing slash if not set
if (pathname.isEmpty()) {
return "/";
}
int indexOfFirstPercent = pathname.indexOf('%');
if (indexOfFirstPercent == -1) {
// no need to removeDots nor replace double slashes
if (pathname.indexOf('.') == -1 && pathname.indexOf("//") == -1) {
if (pathname.charAt(0) == '/') {
return pathname;
}
// See https://bugs.openjdk.org/browse/JDK-8085796
return "/" + pathname;
}
}
return normalizePathSlow(pathname, indexOfFirstPercent);
}
private static String normalizePathSlow(String pathname, int indexOfFirstPercent) {
final StringBuilder ibuf;
// Not standard!!!
if (pathname.charAt(0) != '/') {
ibuf = new StringBuilder(pathname.length() + 1);
ibuf.append('/');
if (indexOfFirstPercent != -1) {
indexOfFirstPercent++;
}
} else {
ibuf = new StringBuilder(pathname.length());
}
ibuf.append(pathname);
if (indexOfFirstPercent != -1) {
decodeUnreservedChars(ibuf, indexOfFirstPercent);
}
// remove dots as described in
// http://tools.ietf.org/html/rfc3986#section-5.2.4
return removeDots(ibuf);
}
private static void decodeUnreservedChars(StringBuilder path, int start) {
while (start < path.length()) {
// decode unreserved chars described in
// http://tools.ietf.org/html/rfc3986#section-2.4
if (path.charAt(start) == '%') {
decodeUnreserved(path, start);
}
start++;
}
}
private static void decodeUnreserved(StringBuilder path, int start) {
if (start + 3 <= path.length()) {
// these are latin chars so there is no danger of falling into some special unicode char that requires more
// than 1 byte
final String escapeSequence = path.substring(start + 1, start + 3);
int unescaped;
try {
unescaped = Integer.parseInt(escapeSequence, 16);
if (unescaped < 0) {
throw new IllegalArgumentException("Invalid escape sequence: %" + escapeSequence);
}
} catch (NumberFormatException e) {
throw new IllegalArgumentException("Invalid escape sequence: %" + escapeSequence);
}
// validate if the octet is within the allowed ranges
if (
// ALPHA
(unescaped >= 0x41 && unescaped <= 0x5A) ||
(unescaped >= 0x61 && unescaped <= 0x7A) ||
// DIGIT
(unescaped >= 0x30 && unescaped <= 0x39) ||
// HYPHEN
(unescaped == 0x2D) ||
// PERIOD
(unescaped == 0x2E) ||
// UNDERSCORE
(unescaped == 0x5F) ||
// TILDE
(unescaped == 0x7E)) {
path.setCharAt(start, (char) unescaped);
path.delete(start + 1, start + 3);
}
} else {
throw new IllegalArgumentException("Invalid position for escape character: " + start);
}
}
/**
* Removed dots as per <a href="http://tools.ietf.org/html/rfc3986#section-5.2.4>rfc3986</a>.
*
* There is 1 extra transformation that are not part of the spec but kept for backwards compatibility:
*
* double slash // will be converted to single slash.
*
* @param path raw path
* @return normalized path
*/
public static String removeDots(CharSequence path) {
if (path == null) {
return null;
}
final StringBuilder obuf = new StringBuilder(path.length());
int i = 0;
while (i < path.length()) {
// remove dots as described in
// http://tools.ietf.org/html/rfc3986#section-5.2.4
if (matches(path, i, "./")) {
i += 2;
} else if (matches(path, i, "../")) {
i += 3;
} else if (matches(path, i, "/./")) {
// preserve last slash
i += 2;
} else if (matches(path, i,"/.", true)) {
path = "/";
i = 0;
} else if (matches(path, i, "/../")) {
// preserve last slash
i += 3;
int pos = obuf.lastIndexOf("/");
if (pos != -1) {
obuf.delete(pos, obuf.length());
}
} else if (matches(path, i, "/..", true)) {
path = "/";
i = 0;
int pos = obuf.lastIndexOf("/");
if (pos != -1) {
obuf.delete(pos, obuf.length());
}
} else if (matches(path, i, ".", true) || matches(path, i, "..", true)) {
break;
} else {
if (path.charAt(i) == '/') {
i++;
// Not standard!!!
// but common // -> /
if (obuf.length() == 0 || obuf.charAt(obuf.length() - 1) != '/') {
obuf.append('/');
}
}
int pos = indexOfSlash(path, i);
if (pos != -1) {
obuf.append(path, i, pos);
i = pos;
} else {
obuf.append(path, i, path.length());
break;
}
}
}
return obuf.toString();
}
/**
* Resolve an URI reference as per <a href="http://tools.ietf.org/html/rfc3986#section-5.2.4>rfc3986</a>
*/
public static URI resolveURIReference(String base, String ref) throws URISyntaxException {
return resolveURIReference(URI.create(base), ref);
}
/**
* Resolve an URI reference as per <a href="http://tools.ietf.org/html/rfc3986#section-5.2.4>rfc3986</a>
*/
public static URI resolveURIReference(URI base, String ref) throws URISyntaxException {
URI _ref = URI.create(ref);
String scheme;
String authority;
String path;
String query;
if (_ref.getScheme() != null) {
scheme = _ref.getScheme();
authority = _ref.getAuthority();
path = removeDots(_ref.getRawPath());
query = _ref.getRawQuery();
} else {
if (_ref.getAuthority() != null) {
authority = _ref.getAuthority();
path = _ref.getRawPath();
query = _ref.getRawQuery();
} else {
if (_ref.getRawPath().length() == 0) {
path = base.getRawPath();
if (_ref.getRawQuery() != null) {
query = _ref.getRawQuery();
} else {
query = base.getRawQuery();
}
} else {
if (_ref.getRawPath().startsWith("/")) {
path = removeDots(_ref.getRawPath());
} else {
// Merge paths
String mergedPath;
String basePath = base.getRawPath();
if (base.getAuthority() != null && basePath.length() == 0) {
mergedPath = "/" + _ref.getRawPath();
} else {
int index = basePath.lastIndexOf('/');
if (index > -1) {
mergedPath = basePath.substring(0, index + 1) + _ref.getRawPath();
} else {
mergedPath = _ref.getRawPath();
}
}
path = removeDots(mergedPath);
}
query = _ref.getRawQuery();
}
authority = base.getAuthority();
}
scheme = base.getScheme();
}
return new URI(scheme, authority, path, query, _ref.getFragment());
}
/**
* Extract the path out of the uri.
*/
static String parsePath(String uri) {
if (uri.length() == 0) {
return "";
}
int i;
if (uri.charAt(0) == '/') {
i = 0;
} else {
i = uri.indexOf("://");
if (i == -1) {
i = 0;
} else {
i = uri.indexOf('/', i + 3);
if (i == -1) {
// contains no /
return "/";
}
}
}
int queryStart = uri.indexOf('?', i);
if (queryStart == -1) {
queryStart = uri.length();
if (i == 0) {
return uri;
}
}
return uri.substring(i, queryStart);
}
/**
* Extract the query out of a uri or returns the empty string if no query was found.
*/
static String parseQuery(String uri) {
int i = uri.indexOf('?');
if (i == -1) {
return null;
} else {
return uri.substring(i + 1);
}
}
static String absoluteURI(String serverOrigin, HttpServerRequest req) throws URISyntaxException {
String absoluteURI;
URI uri = new URI(req.uri());
String scheme = uri.getScheme();
if (scheme != null && (scheme.equals("http") || scheme.equals("https"))) {
absoluteURI = uri.toString();
} else {
boolean ssl = req.isSSL();
HostAndPort authority = req.authority();
if (authority != null) {
StringBuilder sb = new StringBuilder(req.scheme()).append("://").append(authority.host());
if (authority.port() > 0 && (ssl && authority.port() != 443) || (!ssl && authority.port() != 80)) {
sb.append(':').append(authority.port());
}
sb.append(uri);
absoluteURI = sb.toString();
} else {
// Fall back to the server origin
absoluteURI = serverOrigin + uri;
}
}
return absoluteURI;
}
static MultiMap params(String uri, Charset charset) {
QueryStringDecoder queryStringDecoder = new QueryStringDecoder(uri, charset);
Map<String, List<String>> prms = queryStringDecoder.parameters();
MultiMap params = MultiMap.caseInsensitiveMultiMap();
if (!prms.isEmpty()) {
for (Map.Entry<String, List<String>> entry: prms.entrySet()) {
params.add(entry.getKey(), entry.getValue());
}
}
return params;
}
public static void fromVertxInitialSettings(boolean server, io.vertx.core.http.Http2Settings vertxSettings, Http2Settings nettySettings) {
if (vertxSettings != null) {
if (!server && vertxSettings.isPushEnabled() != DEFAULT_ENABLE_PUSH) {
nettySettings.pushEnabled(vertxSettings.isPushEnabled());
}
if (vertxSettings.getHeaderTableSize() != DEFAULT_HEADER_TABLE_SIZE) {
nettySettings.put('\u0001', (Long)vertxSettings.getHeaderTableSize());
}
if (vertxSettings.getInitialWindowSize() != DEFAULT_INITIAL_WINDOW_SIZE) {
nettySettings.initialWindowSize(vertxSettings.getInitialWindowSize());
}
if (vertxSettings.getMaxConcurrentStreams() != DEFAULT_MAX_CONCURRENT_STREAMS) {
nettySettings.maxConcurrentStreams(vertxSettings.getMaxConcurrentStreams());
}
if (vertxSettings.getMaxFrameSize() != DEFAULT_MAX_FRAME_SIZE) {
nettySettings.maxFrameSize(vertxSettings.getMaxFrameSize());
}
if (vertxSettings.getMaxHeaderListSize() != DEFAULT_MAX_HEADER_LIST_SIZE) {
nettySettings.maxHeaderListSize(vertxSettings.getMaxHeaderListSize());
}
Map<Integer, Long> extraSettings = vertxSettings.getExtraSettings();
if (extraSettings != null) {
extraSettings.forEach((code, setting) -> {
nettySettings.put((char)(int)code, setting);
});
}
}
}
public static Http2Settings fromVertxSettings(io.vertx.core.http.Http2Settings settings) {
Http2Settings converted = new Http2Settings();
converted.pushEnabled(settings.isPushEnabled());
converted.maxFrameSize(settings.getMaxFrameSize());
converted.initialWindowSize(settings.getInitialWindowSize());
converted.headerTableSize(settings.getHeaderTableSize());
converted.maxConcurrentStreams(settings.getMaxConcurrentStreams());
converted.maxHeaderListSize(settings.getMaxHeaderListSize());
if (settings.getExtraSettings() != null) {
settings.getExtraSettings().forEach((key, value) -> {
converted.put((char)(int)key, value);
});
}
return converted;
}
public static io.vertx.core.http.Http2Settings toVertxSettings(Http2Settings settings) {
io.vertx.core.http.Http2Settings converted = new io.vertx.core.http.Http2Settings();
Boolean pushEnabled = settings.pushEnabled();
if (pushEnabled != null) {
converted.setPushEnabled(pushEnabled);
}
Long maxConcurrentStreams = settings.maxConcurrentStreams();
if (maxConcurrentStreams != null) {
converted.setMaxConcurrentStreams(maxConcurrentStreams);
}
Long maxHeaderListSize = settings.maxHeaderListSize();
if (maxHeaderListSize != null) {
converted.setMaxHeaderListSize(maxHeaderListSize);
}
Integer maxFrameSize = settings.maxFrameSize();
if (maxFrameSize != null) {
converted.setMaxFrameSize(maxFrameSize);
}
Integer initialWindowSize = settings.initialWindowSize();
if (initialWindowSize != null) {
converted.setInitialWindowSize(initialWindowSize);
}
Long headerTableSize = settings.headerTableSize();
if (headerTableSize != null) {
converted.setHeaderTableSize(headerTableSize);
}
settings.forEach((key, value) -> {
if (key > 6) {
converted.set(key, value);
}
});
return converted;
}
static Http2Settings decodeSettings(String base64Settings) {
try {
Http2Settings settings = new Http2Settings();
Buffer buffer = Buffer.buffer(Base64.getUrlDecoder().decode(base64Settings));
int pos = 0;
int len = buffer.length();
while (pos < len) {
int i = buffer.getUnsignedShort(pos);
pos += 2;
long j = buffer.getUnsignedInt(pos);
pos += 4;
settings.put((char)i, (Long)j);
}
return settings;
} catch (Exception ignore) {
}
return null;
}
public static String encodeSettings(io.vertx.core.http.Http2Settings settings) {
Buffer buffer = Buffer.buffer();
fromVertxSettings(settings).forEach((c, l) -> {
buffer.appendUnsignedShort(c);
buffer.appendUnsignedInt(l);
});
return Base64.getUrlEncoder().encodeToString(buffer.getBytes());
}
public static ByteBuf generateWSCloseFrameByteBuf(short statusCode, String reason) {
if (reason != null)
return Unpooled.copiedBuffer(
Unpooled.copyShort(statusCode), // First two bytes are reserved for status code
Unpooled.copiedBuffer(reason, StandardCharsets.UTF_8)
);
else
return Unpooled.copyShort(statusCode);
}
static void sendError(Channel ch, HttpResponseStatus status) {
sendError(ch, status, status.reasonPhrase());
}
static void sendError(Channel ch, HttpResponseStatus status, CharSequence err) {
FullHttpResponse resp = new DefaultFullHttpResponse(HTTP_1_1, status);
if (status.code() == METHOD_NOT_ALLOWED.code()) {
// SockJS requires this
resp.headers().set(io.vertx.core.http.HttpHeaders.ALLOW, io.vertx.core.http.HttpHeaders.GET);
}
if (err != null) {
resp.content().writeBytes(err.toString().getBytes(CharsetUtil.UTF_8));
HttpUtil.setContentLength(resp, err.length());
} else {
HttpUtil.setContentLength(resp, 0);
}
ch.writeAndFlush(resp);
}
static String getWebSocketLocation(HttpServerRequest req, boolean ssl) throws Exception {
String prefix;
if (ssl) {
prefix = "wss://";
} else {
prefix = "ws://";
}
URI uri = new URI(req.uri());
String path = uri.getRawPath();
String loc = prefix + req.headers().get(HttpHeaderNames.HOST) + path;
String query = uri.getRawQuery();
if (query != null) {
loc += "?" + query;
}
return loc;
}
/**
* @return convert the {@code sequence} to a lower case instance
*/
public static CharSequence toLowerCase(CharSequence sequence) {
StringBuilder buffer = null;
int len = sequence.length();
for (int index = 0; index < len; index++) {
char c = sequence.charAt(index);
if (c >= 'A' && c <= 'Z') {
if (buffer == null) {
buffer = new StringBuilder(sequence);
}
buffer.setCharAt(index, (char)(c + ('a' - 'A')));
}
}
if (buffer != null) {
return buffer.toString();
} else {
return sequence;
}
}
static HttpVersion toNettyHttpVersion(io.vertx.core.http.HttpVersion version) {
switch (version) {
case HTTP_1_0: {
return HttpVersion.HTTP_1_0;
}
case HTTP_1_1: {
return HttpVersion.HTTP_1_1;
}
default:
throw new IllegalArgumentException("Unsupported HTTP version: " + version);
}
}
static io.vertx.core.http.HttpMethod toVertxMethod(String method) {
return io.vertx.core.http.HttpMethod.valueOf(method);
}
private static final AsciiString TIMEOUT_EQ = AsciiString.of("timeout=");
public static int parseKeepAliveHeaderTimeout(CharSequence value) {
int len = value.length();
int pos = 0;
while (pos < len) {
int idx = AsciiString.indexOf(value, ',', pos);
int next;
if (idx == -1) {
idx = next = len;
} else {
next = idx + 1;
}
while (pos < idx && value.charAt(pos) == ' ') {
pos++;
}
int to = idx;
while (to > pos && value.charAt(to -1) == ' ') {
to--;
}
if (AsciiString.regionMatches(value, true, pos, TIMEOUT_EQ, 0, TIMEOUT_EQ.length())) {
pos += TIMEOUT_EQ.length();
if (pos < to) {
int ret = 0;
while (pos < to) {
int ch = value.charAt(pos++);
if (ch >= '0' && ch < '9') {
ret = ret * 10 + (ch - '0');
} else {
ret = -1;
break;
}
}
if (ret > -1) {
return ret;
}
}
}
pos = next;
}
return -1;
}
private static final Consumer<CharSequence> HEADER_VALUE_VALIDATOR = HttpUtils::validateHeaderValue;
public static void validateHeader(CharSequence name, CharSequence value) {
validateHeaderName(name);
if (value != null) {
validateHeaderValue(value);
}
}
public static void validateHeader(CharSequence name, Iterable<? extends CharSequence> values) {
validateHeaderName(name);
values.forEach(value -> {
if (value != null) {
HEADER_VALUE_VALIDATOR.accept(value);
}
});
}
public static void validateHeaderValue(CharSequence seq) {
int state = 0;
// Start looping through each of the character
for (int index = 0; index < seq.length(); index++) {
state = validateValueChar(seq, state, seq.charAt(index));
}
if (state != 0) {
throw new IllegalArgumentException("a header value must not end with '\\r' or '\\n':" + seq);
}
}
private static final int HIGHEST_INVALID_VALUE_CHAR_MASK = ~0x1F;
private static int validateValueChar(CharSequence seq, int state, char character) {
/*
* State:
* 0: Previous character was neither CR nor LF
* 1: The previous character was CR
* 2: The previous character was LF
*/
if ((character & HIGHEST_INVALID_VALUE_CHAR_MASK) == 0 || character == 0x7F) { // 0x7F is "DEL".
// The only characters allowed in the range 0x00-0x1F are : HTAB, LF and CR
switch (character) {
case 0x09: // Horizontal tab - HTAB
case 0x0a: // Line feed - LF
case 0x0d: // Carriage return - CR
break;
default:
throw new IllegalArgumentException("a header value contains a prohibited character '" + (int) character + "': " + seq);
}
}
// Check the CRLF (HT | SP) pattern
switch (state) {
case 0:
switch (character) {
case '\r':
return 1;
case '\n':
return 2;
}
break;
case 1:
switch (character) {
case '\n':
return 2;
default:
throw new IllegalArgumentException("only '\\n' is allowed after '\\r': " + seq);
}
case 2:
switch (character) {
case '\t':
case ' ':
return 0;
default:
throw new IllegalArgumentException("only ' ' and '\\t' are allowed after '\\n': " + seq);
}
}
return state;
}
private static final boolean[] VALID_H_NAME_ASCII_CHARS;
static {
VALID_H_NAME_ASCII_CHARS = new boolean[Byte.MAX_VALUE + 1];
Arrays.fill(VALID_H_NAME_ASCII_CHARS, true);
VALID_H_NAME_ASCII_CHARS[' '] = false;
VALID_H_NAME_ASCII_CHARS['"'] = false;
VALID_H_NAME_ASCII_CHARS['('] = false;
VALID_H_NAME_ASCII_CHARS[')'] = false;
VALID_H_NAME_ASCII_CHARS[','] = false;
VALID_H_NAME_ASCII_CHARS['/'] = false;
VALID_H_NAME_ASCII_CHARS[':'] = false;
VALID_H_NAME_ASCII_CHARS[';'] = false;
VALID_H_NAME_ASCII_CHARS['<'] = false;
VALID_H_NAME_ASCII_CHARS['>'] = false;
VALID_H_NAME_ASCII_CHARS['='] = false;
VALID_H_NAME_ASCII_CHARS['?'] = false;
VALID_H_NAME_ASCII_CHARS['@'] = false;
VALID_H_NAME_ASCII_CHARS['['] = false;
VALID_H_NAME_ASCII_CHARS[']'] = false;
VALID_H_NAME_ASCII_CHARS['\\'] = false;
VALID_H_NAME_ASCII_CHARS['{'] = false;
VALID_H_NAME_ASCII_CHARS['}'] = false;
VALID_H_NAME_ASCII_CHARS[0x7f] = false;
// control characters are not valid
for (int i = 0; i < 0x20; i++) {
VALID_H_NAME_ASCII_CHARS[i] = false;
}
}
public static void validateHeaderName(CharSequence value) {
if (value instanceof AsciiString) {
// no need to check for ASCII-ness anymore
validateHeaderName((AsciiString) value);
} else {
validateHeaderName0(value);
}
}
private static void validateHeaderName(AsciiString value) {
final int len = value.length();
final int off = value.arrayOffset();
final byte[] asciiChars = value.array();
for (int i = 0; i < len; i++) {
// Check to see if the character is not an ASCII character, or invalid
byte c = asciiChars[off + i];
if (c < 0) {
throw new IllegalArgumentException("a header name cannot contain non-ASCII character: " + value);
}
if (!VALID_H_NAME_ASCII_CHARS[c & 0x7F]) {
throw new IllegalArgumentException("a header name cannot contain some prohibited characters, such as : " + value);
}
}
}
private static void validateHeaderName0(CharSequence value) {
for (int i = 0; i < value.length(); i++) {
final char c = value.charAt(i);
// Check to see if the character is not an ASCII character, or invalid
if (c > 0x7f) {
throw new IllegalArgumentException("a header name cannot contain non-ASCII character: " + value);
}
if (!VALID_H_NAME_ASCII_CHARS[c & 0x7F]) {
throw new IllegalArgumentException("a header name cannot contain some prohibited characters, such as : " + value);
}
}
}
public static boolean isValidMultipartContentType(String contentType) {
return MULTIPART_FORM_DATA.regionMatches(true, 0, contentType, 0, MULTIPART_FORM_DATA.length())
|| APPLICATION_X_WWW_FORM_URLENCODED.regionMatches(true, 0, contentType, 0, APPLICATION_X_WWW_FORM_URLENCODED.length());
}
public static boolean isValidMultipartMethod(HttpMethod method) {
return method.equals(HttpMethod.POST) || method.equals(HttpMethod.PUT) || method.equals(HttpMethod.PATCH)
|| method.equals(HttpMethod.DELETE);
}
static Future<AsyncFile> resolveFile(ContextInternal context, String filename, long offset, long length) {
VertxInternal vertx = context.owner();
File file_ = vertx.resolveFile(filename);
if (!file_.exists()) {
return context.failedFuture(new FileNotFoundException());
}
//We open the fileName using a RandomAccessFile to make sure that this is an actual file that can be read.
//i.e is not a directory
try (RandomAccessFile raf = new RandomAccessFile(file_, "r")) {
FileSystem fs = vertx.fileSystem();
return fs.open(filename, new OpenOptions().setCreate(false).setWrite(false))
.andThen(ar -> {
if (ar.succeeded()) {
AsyncFile file = ar.result();
long contentLength = Math.min(length, file_.length() - offset);
file.setReadPos(offset);
file.setReadLength(contentLength);
}
});
} catch (IOException e) {
return context.failedFuture(e);
}
}
static boolean isConnectOrUpgrade(io.vertx.core.http.HttpMethod method, MultiMap headers) {
return method == io.vertx.core.http.HttpMethod.CONNECT || (method == io.vertx.core.http.HttpMethod.GET && headers.contains(io.vertx.core.http.HttpHeaders.CONNECTION, io.vertx.core.http.HttpHeaders.UPGRADE, true));
}
static boolean isKeepAlive(HttpRequest request) {
HttpVersion version = request.protocolVersion();
return (version == HttpVersion.HTTP_1_1 && !request.headers().contains(io.vertx.core.http.HttpHeaders.CONNECTION, io.vertx.core.http.HttpHeaders.CLOSE, true))
|| (version == HttpVersion.HTTP_1_0 && request.headers().contains(io.vertx.core.http.HttpHeaders.CONNECTION, io.vertx.core.http.HttpHeaders.KEEP_ALIVE, true));
}
}