Debian Codegraph @

src/kj/compat/http.c++

raw
1 // Copyright (c) 2017 Sandstorm Development Group, Inc. and contributors
2 // Licensed under the MIT License:
3 //
4 // Permission is hereby granted, free of charge, to any person obtaining a copy
5 // of this software and associated documentation files (the "Software"), to deal
6 // in the Software without restriction, including without limitation the rights
7 // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
8 // copies of the Software, and to permit persons to whom the Software is
9 // furnished to do so, subject to the following conditions:
10 //
11 // The above copyright notice and this permission notice shall be included in
12 // all copies or substantial portions of the Software.
13 //
14 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15 // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16 // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17 // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18 // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19 // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
20 // THE SOFTWARE.
21
22 #include "http.h"
23 #include "kj/exception.h"
24 #include "url.h"
25 #include <kj/debug.h>
26 #include <kj/parse/char.h>
27 #include <kj/string.h>
28 #include <unordered_map>
29 #include <stdlib.h>
30 #include <kj/encoding.h>
31 #include <deque>
32 #include <queue>
33 #include <map>
34 #if KJ_HAS_ZLIB
35 #include <zlib.h>
36 #endif // KJ_HAS_ZLIB
37
38 namespace kj {
39
40 // =======================================================================================
41 // SHA-1 implementation from https://github.com/clibs/sha1
42 //
43 // The WebSocket standard depends on SHA-1. ARRRGGGHHHHH.
44 //
45 // Any old checksum would have served the purpose, or hell, even just returning the header
46 // verbatim. But NO, they decided to throw a whole complicated hash algorithm in there, AND
47 // THEY CHOSE A BROKEN ONE THAT WE OTHERWISE WOULDN'T NEED ANYMORE.
48 //
49 // TODO(cleanup): Move this to a shared hashing library. Maybe. Or maybe don't, because no one
50 // should be using SHA-1 anymore.
51 //
52 // THIS USAGE IS NOT SECURITY SENSITIVE. IF YOU REPORT A SECURITY ISSUE BECAUSE YOU SAW SHA1 IN THE
53 // SOURCE CODE I WILL MAKE FUN OF YOU.
54
55 /*
56 SHA-1 in C
57 By Steve Reid <[email protected]>
58 100% Public Domain
59 Test Vectors (from FIPS PUB 180-1)
60 "abc"
61 A9993E36 4706816A BA3E2571 7850C26C 9CD0D89D
62 "abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq"
63 84983E44 1C3BD26E BAAE4AA1 F95129E5 E54670F1
64 A million repetitions of "a"
65 34AA973C D4C4DAA4 F61EEB2B DBAD2731 6534016F
66 */
67
68 /* #define LITTLE_ENDIAN * This should be #define'd already, if true. */
69 /* #define SHA1HANDSOFF * Copies data before messing with it. */
70
71 #define SHA1HANDSOFF
72
73 typedef struct
74 {
75 uint32_t state[5];
76 uint32_t count[2];
77 unsigned char buffer[64];
78 } SHA1_CTX;
79
80 #define rol(value, bits) (((value) << (bits)) | ((value) >> (32 - (bits))))
81
82 /* blk0() and blk() perform the initial expand. */
83 /* I got the idea of expanding during the round function from SSLeay */
84 #if BYTE_ORDER == LITTLE_ENDIAN
85 #define blk0(i) (block->l[i] = (rol(block->l[i],24)&0xFF00FF00) \
86 |(rol(block->l[i],8)&0x00FF00FF))
87 #elif BYTE_ORDER == BIG_ENDIAN
88 #define blk0(i) block->l[i]
89 #else
90 #error "Endianness not defined!"
91 #endif
92 #define blk(i) (block->l[i&15] = rol(block->l[(i+13)&15]^block->l[(i+8)&15] \
93 ^block->l[(i+2)&15]^block->l[i&15],1))
94
95 /* (R0+R1), R2, R3, R4 are the different operations used in SHA1 */
96 #define R0(v,w,x,y,z,i) z+=((w&(x^y))^y)+blk0(i)+0x5A827999+rol(v,5);w=rol(w,30);
97 #define R1(v,w,x,y,z,i) z+=((w&(x^y))^y)+blk(i)+0x5A827999+rol(v,5);w=rol(w,30);
98 #define R2(v,w,x,y,z,i) z+=(w^x^y)+blk(i)+0x6ED9EBA1+rol(v,5);w=rol(w,30);
99 #define R3(v,w,x,y,z,i) z+=(((w|x)&y)|(w&x))+blk(i)+0x8F1BBCDC+rol(v,5);w=rol(w,30);
100 #define R4(v,w,x,y,z,i) z+=(w^x^y)+blk(i)+0xCA62C1D6+rol(v,5);w=rol(w,30);
101
102
103 /* Hash a single 512-bit block. This is the core of the algorithm. */
104
105 void SHA1Transform(
106 uint32_t state[5],
107 const unsigned char buffer[64]
108 )
109 {
110 uint32_t a, b, c, d, e;
111
112 typedef union
113 {
114 unsigned char c[64];
115 uint32_t l[16];
116 } CHAR64LONG16;
117
118 #ifdef SHA1HANDSOFF
119 CHAR64LONG16 block[1]; /* use array to appear as a pointer */
120
121 memcpy(block, buffer, 64);
122 #else
123 /* The following had better never be used because it causes the
124 * pointer-to-const buffer to be cast into a pointer to non-const.
125 * And the result is written through. I threw a "const" in, hoping
126 * this will cause a diagnostic.
127 */
128 CHAR64LONG16 *block = (const CHAR64LONG16 *) buffer;
129 #endif
130 /* Copy context->state[] to working vars */
131 a = state[0];
132 b = state[1];
133 c = state[2];
134 d = state[3];
135 e = state[4];
136 /* 4 rounds of 20 operations each. Loop unrolled. */
137 R0(a, b, c, d, e, 0);
138 R0(e, a, b, c, d, 1);
139 R0(d, e, a, b, c, 2);
140 R0(c, d, e, a, b, 3);
141 R0(b, c, d, e, a, 4);
142 R0(a, b, c, d, e, 5);
143 R0(e, a, b, c, d, 6);
144 R0(d, e, a, b, c, 7);
145 R0(c, d, e, a, b, 8);
146 R0(b, c, d, e, a, 9);
147 R0(a, b, c, d, e, 10);
148 R0(e, a, b, c, d, 11);
149 R0(d, e, a, b, c, 12);
150 R0(c, d, e, a, b, 13);
151 R0(b, c, d, e, a, 14);
152 R0(a, b, c, d, e, 15);
153 R1(e, a, b, c, d, 16);
154 R1(d, e, a, b, c, 17);
155 R1(c, d, e, a, b, 18);
156 R1(b, c, d, e, a, 19);
157 R2(a, b, c, d, e, 20);
158 R2(e, a, b, c, d, 21);
159 R2(d, e, a, b, c, 22);
160 R2(c, d, e, a, b, 23);
161 R2(b, c, d, e, a, 24);
162 R2(a, b, c, d, e, 25);
163 R2(e, a, b, c, d, 26);
164 R2(d, e, a, b, c, 27);
165 R2(c, d, e, a, b, 28);
166 R2(b, c, d, e, a, 29);
167 R2(a, b, c, d, e, 30);
168 R2(e, a, b, c, d, 31);
169 R2(d, e, a, b, c, 32);
170 R2(c, d, e, a, b, 33);
171 R2(b, c, d, e, a, 34);
172 R2(a, b, c, d, e, 35);
173 R2(e, a, b, c, d, 36);
174 R2(d, e, a, b, c, 37);
175 R2(c, d, e, a, b, 38);
176 R2(b, c, d, e, a, 39);
177 R3(a, b, c, d, e, 40);
178 R3(e, a, b, c, d, 41);
179 R3(d, e, a, b, c, 42);
180 R3(c, d, e, a, b, 43);
181 R3(b, c, d, e, a, 44);
182 R3(a, b, c, d, e, 45);
183 R3(e, a, b, c, d, 46);
184 R3(d, e, a, b, c, 47);
185 R3(c, d, e, a, b, 48);
186 R3(b, c, d, e, a, 49);
187 R3(a, b, c, d, e, 50);
188 R3(e, a, b, c, d, 51);
189 R3(d, e, a, b, c, 52);
190 R3(c, d, e, a, b, 53);
191 R3(b, c, d, e, a, 54);
192 R3(a, b, c, d, e, 55);
193 R3(e, a, b, c, d, 56);
194 R3(d, e, a, b, c, 57);
195 R3(c, d, e, a, b, 58);
196 R3(b, c, d, e, a, 59);
197 R4(a, b, c, d, e, 60);
198 R4(e, a, b, c, d, 61);
199 R4(d, e, a, b, c, 62);
200 R4(c, d, e, a, b, 63);
201 R4(b, c, d, e, a, 64);
202 R4(a, b, c, d, e, 65);
203 R4(e, a, b, c, d, 66);
204 R4(d, e, a, b, c, 67);
205 R4(c, d, e, a, b, 68);
206 R4(b, c, d, e, a, 69);
207 R4(a, b, c, d, e, 70);
208 R4(e, a, b, c, d, 71);
209 R4(d, e, a, b, c, 72);
210 R4(c, d, e, a, b, 73);
211 R4(b, c, d, e, a, 74);
212 R4(a, b, c, d, e, 75);
213 R4(e, a, b, c, d, 76);
214 R4(d, e, a, b, c, 77);
215 R4(c, d, e, a, b, 78);
216 R4(b, c, d, e, a, 79);
217 /* Add the working vars back into context.state[] */
218 state[0] += a;
219 state[1] += b;
220 state[2] += c;
221 state[3] += d;
222 state[4] += e;
223 /* Wipe variables */
224 a = b = c = d = e = 0;
225 #ifdef SHA1HANDSOFF
226 memset(block, '\0', sizeof(block));
227 #endif
228 }
229
230
231 /* SHA1Init - Initialize new context */
232
233 void SHA1Init(
234 SHA1_CTX * context
235 )
236 {
237 /* SHA1 initialization constants */
238 context->state[0] = 0x67452301;
239 context->state[1] = 0xEFCDAB89;
240 context->state[2] = 0x98BADCFE;
241 context->state[3] = 0x10325476;
242 context->state[4] = 0xC3D2E1F0;
243 context->count[0] = context->count[1] = 0;
244 }
245
246
247 /* Run your data through this. */
248
249 void SHA1Update(
250 SHA1_CTX * context,
251 const unsigned char *data,
252 uint32_t len
253 )
254 {
255 uint32_t i;
256
257 uint32_t j;
258
259 j = context->count[0];
260 if ((context->count[0] += len << 3) < j)
261 context->count[1]++;
262 context->count[1] += (len >> 29);
263 j = (j >> 3) & 63;
264 if ((j + len) > 63)
265 {
266 memcpy(&context->buffer[j], data, (i = 64 - j));
267 SHA1Transform(context->state, context->buffer);
268 for (; i + 63 < len; i += 64)
269 {
270 SHA1Transform(context->state, &data[i]);
271 }
272 j = 0;
273 }
274 else
275 i = 0;
276 memcpy(&context->buffer[j], &data[i], len - i);
277 }
278
279
280 /* Add padding and return the message digest. */
281
282 void SHA1Final(
283 unsigned char digest[20],
284 SHA1_CTX * context
285 )
286 {
287 unsigned i;
288
289 unsigned char finalcount[8];
290
291 unsigned char c;
292
293 #if 0 /* untested "improvement" by DHR */
294 /* Convert context->count to a sequence of bytes
295 * in finalcount. Second element first, but
296 * big-endian order within element.
297 * But we do it all backwards.
298 */
299 unsigned char *fcp = &finalcount[8];
300 for (i = 0; i < 2; i++)
301 {
302 uint32_t t = context->count[i];
303 int j;
304 for (j = 0; j < 4; t >>= 8, j++)
305 *--fcp = (unsigned char) t}
306 #else
307 for (i = 0; i < 8; i++)
308 {
309 finalcount[i] = (unsigned char) ((context->count[(i >= 4 ? 0 : 1)] >> ((3 - (i & 3)) * 8)) & 255); /* Endian independent */
310 }
311 #endif
312 c = 0200;
313 SHA1Update(context, &c, 1);
314 while ((context->count[0] & 504) != 448)
315 {
316 c = 0000;
317 SHA1Update(context, &c, 1);
318 }
319 SHA1Update(context, finalcount, 8); /* Should cause a SHA1Transform() */
320 for (i = 0; i < 20; i++)
321 {
322 digest[i] = (unsigned char)
323 ((context->state[i >> 2] >> ((3 - (i & 3)) * 8)) & 255);
324 }
325 /* Wipe variables */
326 memset(context, '\0', sizeof(*context));
327 memset(&finalcount, '\0', sizeof(finalcount));
328 }
329
330 // End SHA-1 implementation.
331 // =======================================================================================
332
333 static const char* METHOD_NAMES[] = {
334 #define METHOD_NAME(id) #id,
335 KJ_HTTP_FOR_EACH_METHOD(METHOD_NAME)
336 #undef METHOD_NAME
337 };
338
339 kj::StringPtr KJ_STRINGIFY(HttpMethod method) {
340 return METHOD_NAMES[static_cast<uint>(method)];
341 }
342
343 kj::StringPtr KJ_STRINGIFY(HttpConnectMethod method) {
344 return "CONNECT"_kj;
345 }
346
347 static kj::Maybe<kj::OneOf<HttpMethod, HttpConnectMethod>> consumeHttpMethod(char*& ptr) {
348 char* p = ptr;
349
350 #define EXPECT_REST(prefix, suffix) \
351 if (strncmp(p, #suffix, sizeof(#suffix)-1) == 0) { \
352 ptr = p + (sizeof(#suffix)-1); \
353 return kj::Maybe<kj::OneOf<HttpMethod, HttpConnectMethod>>(HttpMethod::prefix##suffix); \
354 } else { \
355 return nullptr; \
356 }
357
358 switch (*p++) {
359 case 'A': EXPECT_REST(A,CL)
360 case 'C':
361 switch (*p++) {
362 case 'H': EXPECT_REST(CH,ECKOUT)
363 case 'O':
364 switch (*p++) {
365 case 'P': EXPECT_REST(COP,Y)
366 case 'N':
367 if (strncmp(p, "NECT", 4) == 0) {
368 ptr = p + 4;
369 return kj::Maybe<kj::OneOf<HttpMethod, HttpConnectMethod>>(HttpConnectMethod());
370 } else {
371 return nullptr;
372 }
373 default: return nullptr;
374 }
375 default: return nullptr;
376 }
377 case 'D': EXPECT_REST(D,ELETE)
378 case 'G': EXPECT_REST(G,ET)
379 case 'H': EXPECT_REST(H,EAD)
380 case 'L': EXPECT_REST(L,OCK)
381 case 'M':
382 switch (*p++) {
383 case 'E': EXPECT_REST(ME,RGE)
384 case 'K':
385 switch (*p++) {
386 case 'A': EXPECT_REST(MKA,CTIVITY)
387 case 'C': EXPECT_REST(MKC,OL)
388 default: return nullptr;
389 }
390 case 'O': EXPECT_REST(MO,VE)
391 case 'S': EXPECT_REST(MS,EARCH)
392 default: return nullptr;
393 }
394 case 'N': EXPECT_REST(N,OTIFY)
395 case 'O': EXPECT_REST(O,PTIONS)
396 case 'P':
397 switch (*p++) {
398 case 'A': EXPECT_REST(PA,TCH)
399 case 'O': EXPECT_REST(PO,ST)
400 case 'R':
401 if (*p++ != 'O' || *p++ != 'P') return nullptr;
402 switch (*p++) {
403 case 'F': EXPECT_REST(PROPF,IND)
404 case 'P': EXPECT_REST(PROPP,ATCH)
405 default: return nullptr;
406 }
407 case 'U':
408 switch (*p++) {
409 case 'R': EXPECT_REST(PUR,GE)
410 case 'T': EXPECT_REST(PUT,)
411 default: return nullptr;
412 }
413 default: return nullptr;
414 }
415 case 'R': EXPECT_REST(R,EPORT)
416 case 'S':
417 switch (*p++) {
418 case 'E': EXPECT_REST(SE,ARCH)
419 case 'U': EXPECT_REST(SU,BSCRIBE)
420 default: return nullptr;
421 }
422 case 'T': EXPECT_REST(T,RACE)
423 case 'U':
424 if (*p++ != 'N') return nullptr;
425 switch (*p++) {
426 case 'L': EXPECT_REST(UNL,OCK)
427 case 'S': EXPECT_REST(UNS,UBSCRIBE)
428 default: return nullptr;
429 }
430 default: return nullptr;
431 }
432 #undef EXPECT_REST
433 }
434
435 kj::Maybe<HttpMethod> tryParseHttpMethod(kj::StringPtr name) {
436 KJ_IF_MAYBE(method, tryParseHttpMethodAllowingConnect(name)) {
437 KJ_SWITCH_ONEOF(*method) {
438 KJ_CASE_ONEOF(m, HttpMethod) { return m; }
439 KJ_CASE_ONEOF(m, HttpConnectMethod) { return nullptr; }
440 }
441 KJ_UNREACHABLE;
442 } else {
443 return nullptr;
444 }
445 }
446
447 kj::Maybe<kj::OneOf<HttpMethod, HttpConnectMethod>> tryParseHttpMethodAllowingConnect(
448 kj::StringPtr name) {
449 // const_cast OK because we don't actually access it. consumeHttpMethod() is also called by some
450 // code later than explicitly needs to use a non-const pointer.
451 char* ptr = const_cast<char*>(name.begin());
452 auto result = consumeHttpMethod(ptr);
453 if (*ptr == '\0') {
454 return result;
455 } else {
456 return nullptr;
457 }
458 }
459
460 // =======================================================================================
461
462 namespace {
463
464 constexpr char WEBSOCKET_GUID[] = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
465 // From RFC6455.
466
467 static kj::String generateWebSocketAccept(kj::StringPtr key) {
468 // WebSocket demands we do a SHA-1 here. ARRGHH WHY SHA-1 WHYYYYYY?
469 SHA1_CTX ctx;
470 byte digest[20];
471 SHA1Init(&ctx);
472 SHA1Update(&ctx, key.asBytes().begin(), key.size());
473 SHA1Update(&ctx, reinterpret_cast<const byte*>(WEBSOCKET_GUID), strlen(WEBSOCKET_GUID));
474 SHA1Final(digest, &ctx);
475 return kj::encodeBase64(digest);
476 }
477
478 constexpr auto HTTP_SEPARATOR_CHARS = kj::parse::anyOfChars("()<>@,;:\\\"/[]?={} \t");
479 // RFC2616 section 2.2: https://www.w3.org/Protocols/rfc2616/rfc2616-sec2.html#sec2.2
480
481 constexpr auto HTTP_TOKEN_CHARS =
482 kj::parse::controlChar.orChar('\x7f')
483 .orGroup(kj::parse::whitespaceChar)
484 .orGroup(HTTP_SEPARATOR_CHARS)
485 .invert();
486 // RFC2616 section 2.2: https://www.w3.org/Protocols/rfc2616/rfc2616-sec2.html#sec2.2
487
488 constexpr auto HTTP_HEADER_NAME_CHARS = HTTP_TOKEN_CHARS;
489 // RFC2616 section 4.2: https://www.w3.org/Protocols/rfc2616/rfc2616-sec4.html#sec4.2
490
491 static void requireValidHeaderName(kj::StringPtr name) {
492 for (char c: name) {
493 KJ_REQUIRE(HTTP_HEADER_NAME_CHARS.contains(c), "invalid header name", name);
494 }
495 }
496
497 static void requireValidHeaderValue(kj::StringPtr value) {
498 KJ_REQUIRE(HttpHeaders::isValidHeaderValue(value), "invalid header value",
499 kj::encodeCEscape(value));
500 }
501
502 static const char* BUILTIN_HEADER_NAMES[] = {
503 // Indexed by header ID, which includes connection headers, so we include those names too.
504 #define HEADER_NAME(id, name) name,
505 KJ_HTTP_FOR_EACH_BUILTIN_HEADER(HEADER_NAME)
506 #undef HEADER_NAME
507 };
508
509 } // namespace
510
511 #define HEADER_ID(id, name) constexpr uint HttpHeaders::BuiltinIndices::id;
512 KJ_HTTP_FOR_EACH_BUILTIN_HEADER(HEADER_ID)
513 #undef HEADER_ID
514
515 #define DEFINE_HEADER(id, name) \
516 const HttpHeaderId HttpHeaderId::id(nullptr, HttpHeaders::BuiltinIndices::id);
517 KJ_HTTP_FOR_EACH_BUILTIN_HEADER(DEFINE_HEADER)
518 #undef DEFINE_HEADER
519
520 kj::StringPtr HttpHeaderId::toString() const {
521 if (table == nullptr) {
522 KJ_ASSERT(id < kj::size(BUILTIN_HEADER_NAMES));
523 return BUILTIN_HEADER_NAMES[id];
524 } else {
525 return table->idToString(*this);
526 }
527 }
528
529 namespace {
530
531 struct HeaderNameHash {
532 size_t operator()(kj::StringPtr s) const {
533 size_t result = 5381;
534 for (byte b: s.asBytes()) {
535 // Masking bit 0x20 makes our hash case-insensitive while conveniently avoiding any
536 // collisions that would matter for header names.
537 result = ((result << 5) + result) ^ (b & ~0x20);
538 }
539 return result;
540 }
541
542 bool operator()(kj::StringPtr a, kj::StringPtr b) const {
543 // TODO(perf): I wonder if we can beat strcasecmp() by masking bit 0x20 from each byte. We'd
544 // need to prohibit one of the technically-legal characters '^' or '~' from header names
545 // since they'd otherwise be ambiguous, but otherwise there is no ambiguity.
546 #if _MSC_VER
547 return _stricmp(a.cStr(), b.cStr()) == 0;
548 #else
549 return strcasecmp(a.cStr(), b.cStr()) == 0;
550 #endif
551 }
552 };
553
554 } // namespace
555
556 struct HttpHeaderTable::IdsByNameMap {
557 // TODO(perf): If we were cool we could maybe use a perfect hash here, since our hashtable is
558 // static once built.
559
560 std::unordered_map<kj::StringPtr, uint, HeaderNameHash, HeaderNameHash> map;
561 };
562
563 HttpHeaderTable::Builder::Builder()
564 : table(kj::heap<HttpHeaderTable>()) {
565 table->buildStatus = BuildStatus::BUILDING;
566 }
567
568 HttpHeaderId HttpHeaderTable::Builder::add(kj::StringPtr name) {
569 requireValidHeaderName(name);
570
571 auto insertResult = table->idsByName->map.insert(std::make_pair(name, table->namesById.size()));
572 if (insertResult.second) {
573 table->namesById.add(name);
574 }
575 return HttpHeaderId(table, insertResult.first->second);
576 }
577
578 HttpHeaderTable::HttpHeaderTable()
579 : idsByName(kj::heap<IdsByNameMap>()) {
580 #define ADD_HEADER(id, name) \
581 namesById.add(name); \
582 idsByName->map.insert(std::make_pair(name, HttpHeaders::BuiltinIndices::id));
583 KJ_HTTP_FOR_EACH_BUILTIN_HEADER(ADD_HEADER);
584 #undef ADD_HEADER
585 }
586 HttpHeaderTable::~HttpHeaderTable() noexcept(false) {}
587
588 kj::Maybe<HttpHeaderId> HttpHeaderTable::stringToId(kj::StringPtr name) const {
589 auto iter = idsByName->map.find(name);
590 if (iter == idsByName->map.end()) {
591 return nullptr;
592 } else {
593 return HttpHeaderId(this, iter->second);
594 }
595 }
596
597 // =======================================================================================
598
599 bool HttpHeaders::isValidHeaderValue(kj::StringPtr value) {
600 for (char c: value) {
601 // While the HTTP spec suggests that only printable ASCII characters are allowed in header
602 // values, reality has a different opinion. See: https://github.com/httpwg/http11bis/issues/19
603 // We follow the browsers' lead.
604 if (c == '\0' || c == '\r' || c == '\n') {
605 return false;
606 }
607 }
608
609 return true;
610 }
611
612 HttpHeaders::HttpHeaders(const HttpHeaderTable& table)
613 : table(&table),
614 indexedHeaders(kj::heapArray<kj::StringPtr>(table.idCount())) {
615 KJ_ASSERT(
616 table.isReady(), "HttpHeaders object was constructed from "
617 "HttpHeaderTable that wasn't fully built yet at the time of construction");
618 }
619
620 void HttpHeaders::clear() {
621 for (auto& header: indexedHeaders) {
622 header = nullptr;
623 }
624
625 unindexedHeaders.clear();
626 }
627
628 size_t HttpHeaders::size() const {
629 size_t result = unindexedHeaders.size();
630 for (auto i: kj::indices(indexedHeaders)) {
631 if (indexedHeaders[i] != nullptr) {
632 ++result;
633 }
634 }
635 return result;
636 }
637
638 HttpHeaders HttpHeaders::clone() const {
639 HttpHeaders result(*table);
640
641 for (auto i: kj::indices(indexedHeaders)) {
642 if (indexedHeaders[i] != nullptr) {
643 result.indexedHeaders[i] = result.cloneToOwn(indexedHeaders[i]);
644 }
645 }
646
647 result.unindexedHeaders.resize(unindexedHeaders.size());
648 for (auto i: kj::indices(unindexedHeaders)) {
649 result.unindexedHeaders[i].name = result.cloneToOwn(unindexedHeaders[i].name);
650 result.unindexedHeaders[i].value = result.cloneToOwn(unindexedHeaders[i].value);
651 }
652
653 return result;
654 }
655
656 HttpHeaders HttpHeaders::cloneShallow() const {
657 HttpHeaders result(*table);
658
659 for (auto i: kj::indices(indexedHeaders)) {
660 if (indexedHeaders[i] != nullptr) {
661 result.indexedHeaders[i] = indexedHeaders[i];
662 }
663 }
664
665 result.unindexedHeaders.resize(unindexedHeaders.size());
666 for (auto i: kj::indices(unindexedHeaders)) {
667 result.unindexedHeaders[i] = unindexedHeaders[i];
668 }
669
670 return result;
671 }
672
673 kj::StringPtr HttpHeaders::cloneToOwn(kj::StringPtr str) {
674 auto copy = kj::heapString(str);
675 kj::StringPtr result = copy;
676 ownedStrings.add(copy.releaseArray());
677 return result;
678 }
679
680
681 namespace {
682
683 template <char... chars>
684 constexpr bool fastCaseCmp(const char* actual);
685
686 } // namespace
687
688 bool HttpHeaders::isWebSocket() const {
689 return fastCaseCmp<'w', 'e', 'b', 's', 'o', 'c', 'k', 'e', 't'>(
690 get(HttpHeaderId::UPGRADE).orDefault(nullptr).cStr());
691 }
692
693 void HttpHeaders::set(HttpHeaderId id, kj::StringPtr value) {
694 id.requireFrom(*table);
695 requireValidHeaderValue(value);
696
697 indexedHeaders[id.id] = value;
698 }
699
700 void HttpHeaders::set(HttpHeaderId id, kj::String&& value) {
701 set(id, kj::StringPtr(value));
702 takeOwnership(kj::mv(value));
703 }
704
705 void HttpHeaders::add(kj::StringPtr name, kj::StringPtr value) {
706 requireValidHeaderName(name);
707 requireValidHeaderValue(value);
708
709 addNoCheck(name, value);
710 }
711
712 void HttpHeaders::add(kj::StringPtr name, kj::String&& value) {
713 add(name, kj::StringPtr(value));
714 takeOwnership(kj::mv(value));
715 }
716
717 void HttpHeaders::add(kj::String&& name, kj::String&& value) {
718 add(kj::StringPtr(name), kj::StringPtr(value));
719 takeOwnership(kj::mv(name));
720 takeOwnership(kj::mv(value));
721 }
722
723 void HttpHeaders::addNoCheck(kj::StringPtr name, kj::StringPtr value) {
724 KJ_IF_MAYBE(id, table->stringToId(name)) {
725 if (indexedHeaders[id->id] == nullptr) {
726 indexedHeaders[id->id] = value;
727 } else {
728 // Duplicate HTTP headers are equivalent to the values being separated by a comma.
729
730 #if _MSC_VER
731 if (_stricmp(name.cStr(), "set-cookie") == 0) {
732 #else
733 if (strcasecmp(name.cStr(), "set-cookie") == 0) {
734 #endif
735 // Uh-oh, Set-Cookie will be corrupted if we try to concatenate it. We'll make it an
736 // unindexed header, which is weird, but the alternative is guaranteed corruption, so...
737 // TODO(cleanup): Maybe HttpHeaders should just special-case set-cookie in general?
738 unindexedHeaders.add(Header {name, value});
739 } else {
740 auto concat = kj::str(indexedHeaders[id->id], ", ", value);
741 indexedHeaders[id->id] = concat;
742 ownedStrings.add(concat.releaseArray());
743 }
744 }
745 } else {
746 unindexedHeaders.add(Header {name, value});
747 }
748 }
749
750 void HttpHeaders::takeOwnership(kj::String&& string) {
751 ownedStrings.add(string.releaseArray());
752 }
753 void HttpHeaders::takeOwnership(kj::Array<char>&& chars) {
754 ownedStrings.add(kj::mv(chars));
755 }
756 void HttpHeaders::takeOwnership(HttpHeaders&& otherHeaders) {
757 for (auto& str: otherHeaders.ownedStrings) {
758 ownedStrings.add(kj::mv(str));
759 }
760 otherHeaders.ownedStrings.clear();
761 }
762
763 // -----------------------------------------------------------------------------
764
765 static inline char* skipSpace(char* p) {
766 for (;;) {
767 switch (*p) {
768 case '\t':
769 case ' ':
770 ++p;
771 break;
772 default:
773 return p;
774 }
775 }
776 }
777
778 static kj::Maybe<kj::StringPtr> consumeWord(char*& ptr) {
779 char* start = skipSpace(ptr);
780 char* p = start;
781
782 for (;;) {
783 switch (*p) {
784 case '\0':
785 ptr = p;
786 return kj::StringPtr(start, p);
787
788 case '\t':
789 case ' ': {
790 char* end = p++;
791 ptr = p;
792 *end = '\0';
793 return kj::StringPtr(start, end);
794 }
795
796 case '\n':
797 case '\r':
798 // Not expecting EOL!
799 return nullptr;
800
801 default:
802 ++p;
803 break;
804 }
805 }
806 }
807
808 static kj::Maybe<uint> consumeNumber(char*& ptr) {
809 char* start = skipSpace(ptr);
810 char* p = start;
811
812 uint result = 0;
813
814 for (;;) {
815 char c = *p;
816 if ('0' <= c && c <= '9') {
817 result = result * 10 + (c - '0');
818 ++p;
819 } else {
820 if (p == start) return nullptr;
821 ptr = p;
822 return result;
823 }
824 }
825 }
826
827 static kj::StringPtr consumeLine(char*& ptr) {
828 char* start = skipSpace(ptr);
829 char* p = start;
830
831 for (;;) {
832 switch (*p) {
833 case '\0':
834 ptr = p;
835 return kj::StringPtr(start, p);
836
837 case '\r': {
838 char* end = p++;
839 if (*p == '\n') ++p;
840
841 if (*p == ' ' || *p == '\t') {
842 // Whoa, continuation line. These are deprecated, but historically a line starting with
843 // a space was treated as a continuation of the previous line. The behavior should be
844 // the same as if the \r\n were replaced with spaces, so let's do that here to prevent
845 // confusion later.
846 *end = ' ';
847 p[-1] = ' ';
848 break;
849 }
850
851 ptr = p;
852 *end = '\0';
853 return kj::StringPtr(start, end);
854 }
855
856 case '\n': {
857 char* end = p++;
858
859 if (*p == ' ' || *p == '\t') {
860 // Whoa, continuation line. These are deprecated, but historically a line starting with
861 // a space was treated as a continuation of the previous line. The behavior should be
862 // the same as if the \n were replaced with spaces, so let's do that here to prevent
863 // confusion later.
864 *end = ' ';
865 break;
866 }
867
868 ptr = p;
869 *end = '\0';
870 return kj::StringPtr(start, end);
871 }
872
873 default:
874 ++p;
875 break;
876 }
877 }
878 }
879
880 static kj::Maybe<kj::StringPtr> consumeHeaderName(char*& ptr) {
881 // Do NOT skip spaces before the header name. Leading spaces indicate a continuation line; they
882 // should have been handled in consumeLine().
883 char* p = ptr;
884
885 char* start = p;
886 while (HTTP_HEADER_NAME_CHARS.contains(*p)) ++p;
887 char* end = p;
888
889 p = skipSpace(p);
890
891 if (end == start || *p != ':') return nullptr;
892 ++p;
893
894 p = skipSpace(p);
895
896 *end = '\0';
897 ptr = p;
898 return kj::StringPtr(start, end);
899 }
900
901 static char* trimHeaderEnding(kj::ArrayPtr<char> content) {
902 // Trim off the trailing \r\n from a header blob.
903
904 if (content.size() < 2) return nullptr;
905
906 // Remove trailing \r\n\r\n and replace with \0 sentinel char.
907 char* end = content.end();
908
909 if (end[-1] != '\n') return nullptr;
910 --end;
911 if (end[-1] == '\r') --end;
912 *end = '\0';
913
914 return end;
915 }
916
917 HttpHeaders::RequestOrProtocolError HttpHeaders::tryParseRequest(kj::ArrayPtr<char> content) {
918 KJ_SWITCH_ONEOF(tryParseRequestOrConnect(content)) {
919 KJ_CASE_ONEOF(request, Request) {
920 return kj::mv(request);
921 }
922 KJ_CASE_ONEOF(error, ProtocolError) {
923 return kj::mv(error);
924 }
925 KJ_CASE_ONEOF(connect, ConnectRequest) {
926 return ProtocolError { 501, "Not Implemented",
927 "Unrecognized request method.", content };
928 }
929 }
930 KJ_UNREACHABLE;
931 }
932
933 HttpHeaders::RequestConnectOrProtocolError HttpHeaders::tryParseRequestOrConnect(
934 kj::ArrayPtr<char> content) {
935 char* end = trimHeaderEnding(content);
936 if (end == nullptr) {
937 return ProtocolError { 400, "Bad Request",
938 "Request headers have no terminal newline.", content };
939 }
940
941 char* ptr = content.begin();
942
943 HttpHeaders::RequestConnectOrProtocolError result;
944
945 KJ_IF_MAYBE(method, consumeHttpMethod(ptr)) {
946 if (*ptr != ' ' && *ptr != '\t') {
947 return ProtocolError { 501, "Not Implemented",
948 "Unrecognized request method.", content };
949 }
950 ++ptr;
951
952 kj::Maybe<StringPtr> path;
953 KJ_IF_MAYBE(p, consumeWord(ptr)) {
954 path = *p;
955 } else {
956 return ProtocolError { 400, "Bad Request",
957 "Invalid request line.", content };
958 }
959
960 KJ_SWITCH_ONEOF(*method) {
961 KJ_CASE_ONEOF(m, HttpMethod) {
962 result = HttpHeaders::Request { m, KJ_ASSERT_NONNULL(path) };
963 }
964 KJ_CASE_ONEOF(m, HttpConnectMethod) {
965 result = HttpHeaders::ConnectRequest { KJ_ASSERT_NONNULL(path) };
966 }
967 }
968 } else {
969 return ProtocolError { 501, "Not Implemented",
970 "Unrecognized request method.", content };
971 }
972
973 // Ignore rest of line. Don't care about "HTTP/1.1" or whatever.
974 consumeLine(ptr);
975
976 if (!parseHeaders(ptr, end)) {
977 return ProtocolError { 400, "Bad Request",
978 "The headers sent by your client are not valid.", content };
979 }
980
981 return result;
982 }
983
984 HttpHeaders::ResponseOrProtocolError HttpHeaders::tryParseResponse(kj::ArrayPtr<char> content) {
985 char* end = trimHeaderEnding(content);
986 if (end == nullptr) {
987 return ProtocolError { 502, "Bad Gateway",
988 "Response headers have no terminal newline.", content };
989 }
990
991 char* ptr = content.begin();
992
993 HttpHeaders::Response response;
994
995 KJ_IF_MAYBE(version, consumeWord(ptr)) {
996 if (!version->startsWith("HTTP/")) {
997 return ProtocolError { 502, "Bad Gateway",
998 "Invalid response status line (invalid protocol).", content };
999 }
1000 } else {
1001 return ProtocolError { 502, "Bad Gateway",
1002 "Invalid response status line (no spaces).", content };
1003 }
1004
1005 KJ_IF_MAYBE(code, consumeNumber(ptr)) {
1006 response.statusCode = *code;
1007 } else {
1008 return ProtocolError { 502, "Bad Gateway",
1009 "Invalid response status line (invalid status code).", content };
1010 }
1011
1012 response.statusText = consumeLine(ptr);
1013
1014 if (!parseHeaders(ptr, end)) {
1015 return ProtocolError { 502, "Bad Gateway",
1016 "The headers sent by the server are not valid.", content };
1017 }
1018
1019 return response;
1020 }
1021
1022 bool HttpHeaders::tryParse(kj::ArrayPtr<char> content) {
1023 char* end = trimHeaderEnding(content);
1024 if (end == nullptr) return false;
1025
1026 char* ptr = content.begin();
1027 return parseHeaders(ptr, end);
1028 }
1029
1030 bool HttpHeaders::parseHeaders(char* ptr, char* end) {
1031 while (*ptr != '\0') {
1032 KJ_IF_MAYBE(name, consumeHeaderName(ptr)) {
1033 kj::StringPtr line = consumeLine(ptr);
1034 addNoCheck(*name, line);
1035 } else {
1036 return false;
1037 }
1038 }
1039
1040 return ptr == end;
1041 }
1042
1043 // -----------------------------------------------------------------------------
1044
1045 kj::String HttpHeaders::serializeRequest(
1046 HttpMethod method, kj::StringPtr url,
1047 kj::ArrayPtr<const kj::StringPtr> connectionHeaders) const {
1048 return serialize(kj::toCharSequence(method), url, kj::StringPtr("HTTP/1.1"), connectionHeaders);
1049 }
1050
1051 kj::String HttpHeaders::serializeConnectRequest(
1052 kj::StringPtr authority,
1053 kj::ArrayPtr<const kj::StringPtr> connectionHeaders) const {
1054 return serialize("CONNECT"_kj, authority, kj::StringPtr("HTTP/1.1"), connectionHeaders);
1055 }
1056
1057 kj::String HttpHeaders::serializeResponse(
1058 uint statusCode, kj::StringPtr statusText,
1059 kj::ArrayPtr<const kj::StringPtr> connectionHeaders) const {
1060 auto statusCodeStr = kj::toCharSequence(statusCode);
1061
1062 return serialize(kj::StringPtr("HTTP/1.1"), statusCodeStr, statusText, connectionHeaders);
1063 }
1064
1065 kj::String HttpHeaders::serialize(kj::ArrayPtr<const char> word1,
1066 kj::ArrayPtr<const char> word2,
1067 kj::ArrayPtr<const char> word3,
1068 kj::ArrayPtr<const kj::StringPtr> connectionHeaders) const {
1069 const kj::StringPtr space = " ";
1070 const kj::StringPtr newline = "\r\n";
1071 const kj::StringPtr colon = ": ";
1072
1073 size_t size = 2; // final \r\n
1074 if (word1 != nullptr) {
1075 size += word1.size() + word2.size() + word3.size() + 4;
1076 }
1077 KJ_ASSERT(connectionHeaders.size() <= indexedHeaders.size());
1078 for (auto i: kj::indices(indexedHeaders)) {
1079 kj::StringPtr value = i < connectionHeaders.size() ? connectionHeaders[i] : indexedHeaders[i];
1080 if (value != nullptr) {
1081 size += table->idToString(HttpHeaderId(table, i)).size() + value.size() + 4;
1082 }
1083 }
1084 for (auto& header: unindexedHeaders) {
1085 size += header.name.size() + header.value.size() + 4;
1086 }
1087
1088 String result = heapString(size);
1089 char* ptr = result.begin();
1090
1091 if (word1 != nullptr) {
1092 ptr = kj::_::fill(ptr, word1, space, word2, space, word3, newline);
1093 }
1094 for (auto i: kj::indices(indexedHeaders)) {
1095 kj::StringPtr value = i < connectionHeaders.size() ? connectionHeaders[i] : indexedHeaders[i];
1096 if (value != nullptr) {
1097 ptr = kj::_::fill(ptr, table->idToString(HttpHeaderId(table, i)), colon, value, newline);
1098 }
1099 }
1100 for (auto& header: unindexedHeaders) {
1101 ptr = kj::_::fill(ptr, header.name, colon, header.value, newline);
1102 }
1103 ptr = kj::_::fill(ptr, newline);
1104
1105 KJ_ASSERT(ptr == result.end());
1106 return result;
1107 }
1108
1109 kj::String HttpHeaders::toString() const {
1110 return serialize(nullptr, nullptr, nullptr, nullptr);
1111 }
1112
1113 // =======================================================================================
1114
1115 namespace {
1116
1117 template <typename Subclass>
1118 class WrappableStreamMixin {
1119 // Both HttpInputStreamImpl and HttpOutputStream are commonly wrapped by a class that implements
1120 // a particular type of body stream, such as a chunked body or a fixed-length body. That wrapper
1121 // stream is passed back to the application to represent the specific request/response body, but
1122 // the inner stream is associated with the connection and can be reused several times.
1123 //
1124 // It's easy for applications to screw up and hold on to a body stream beyond the lifetime of the
1125 // underlying connection stream. This used to lead to UAF. This mixin class implements behavior
1126 // that detached the wrapper if it outlives the wrapped stream, so that we log errors and
1127
1128 public:
1129 WrappableStreamMixin() = default;
1130 WrappableStreamMixin(WrappableStreamMixin&& other) {
1131 // This constructor is only needed by HttpServer::Connection::makeHttpInput() which constructs
1132 // a new stream and returns it. Technically the constructor will always be elided anyway.
1133 KJ_REQUIRE(other.currentWrapper == nullptr, "can't move a wrappable object that has wrappers!");
1134 }
1135 KJ_DISALLOW_COPY(WrappableStreamMixin);
1136
1137 ~WrappableStreamMixin() noexcept(false) {
1138 KJ_IF_MAYBE(w, currentWrapper) {
1139 KJ_LOG(ERROR, "HTTP connection destroyed while HTTP body streams still exist",
1140 kj::getStackTrace());
1141 *w = nullptr;
1142 }
1143 }
1144
1145 void setCurrentWrapper(kj::Maybe<Subclass&>& weakRef) {
1146 // Tracks the current `HttpEntityBodyReader` instance which is wrapping this stream. There can
1147 // be only one wrapper at a time, and the wrapper must be destroyed before the underlying HTTP
1148 // connection is torn down. The purpose of tracking the wrapper here is to detect when these
1149 // rules are violated by apps, and log an error instead of going UB.
1150 //
1151 // `weakRef` is the wrapper's pointer to this object. If the underlying stream is destroyed
1152 // before the wrapper, then `weakRef` will be nulled out.
1153
1154 // The API should prevent an app from obtaining multiple wrappers with the same backing stream.
1155 KJ_ASSERT(currentWrapper == nullptr,
1156 "bug in KJ HTTP: only one HTTP stream wrapper can exist at a time");
1157
1158 currentWrapper = weakRef;
1159 weakRef = static_cast<Subclass&>(*this);
1160 }
1161
1162 void unsetCurrentWrapper(kj::Maybe<Subclass&>& weakRef) {
1163 auto& current = KJ_ASSERT_NONNULL(currentWrapper);
1164 KJ_ASSERT(&current == &weakRef,
1165 "bug in KJ HTTP: unsetCurrentWrapper() passed the wrong wrapper");
1166 weakRef = nullptr;
1167 currentWrapper = nullptr;
1168 }
1169
1170 private:
1171 kj::Maybe<kj::Maybe<Subclass&>&> currentWrapper;
1172 };
1173
1174 // =======================================================================================
1175
1176 static constexpr size_t MIN_BUFFER = 4096;
1177 static constexpr size_t MAX_BUFFER = 128 * 1024;
1178 static constexpr size_t MAX_CHUNK_HEADER_SIZE = 32;
1179
1180 class HttpInputStreamImpl final: public HttpInputStream,
1181 public WrappableStreamMixin<HttpInputStreamImpl> {
1182 private:
1183 static kj::OneOf<HttpHeaders::Request, HttpHeaders::ConnectRequest> getResumingRequest(
1184 kj::OneOf<HttpMethod, HttpConnectMethod> method,
1185 kj::StringPtr url) {
1186 KJ_SWITCH_ONEOF(method) {
1187 KJ_CASE_ONEOF(m, HttpMethod) {
1188 return HttpHeaders::Request { m, url };
1189 }
1190 KJ_CASE_ONEOF(m, HttpConnectMethod) {
1191 return HttpHeaders::ConnectRequest { url };
1192 }
1193 }
1194 KJ_UNREACHABLE;
1195 }
1196 public:
1197 explicit HttpInputStreamImpl(AsyncInputStream& inner, const HttpHeaderTable& table)
1198 : inner(inner), headerBuffer(kj::heapArray<char>(MIN_BUFFER)), headers(table) {
1199 }
1200
1201 explicit HttpInputStreamImpl(AsyncInputStream& inner,
1202 kj::Array<char> headerBufferParam,
1203 kj::ArrayPtr<char> leftoverParam,
1204 kj::OneOf<HttpMethod, HttpConnectMethod> method,
1205 kj::StringPtr url,
1206 HttpHeaders headers)
1207 : inner(inner),
1208 headerBuffer(kj::mv(headerBufferParam)),
1209 // Initialize `messageHeaderEnd` to a safe value, we'll adjust it below.
1210 messageHeaderEnd(leftoverParam.begin() - headerBuffer.begin()),
1211 leftover(leftoverParam),
1212 headers(kj::mv(headers)),
1213 resumingRequest(getResumingRequest(method, url)) {
1214 // Constructor used for resuming a SuspendedRequest.
1215
1216 // We expect headerBuffer to look like this:
1217 // <method> <url> <headers> [CR] LF <leftover>
1218 // We initialized `messageHeaderEnd` to the beginning of `leftover`, but we want to point it at
1219 // the CR (or LF if there's no CR).
1220 KJ_REQUIRE(messageHeaderEnd >= 2 && leftover.end() <= headerBuffer.end(),
1221 "invalid SuspendedRequest - leftover buffer not where it should be");
1222 KJ_REQUIRE(leftover.begin()[-1] == '\n', "invalid SuspendedRequest - missing LF");
1223 messageHeaderEnd -= 1 + (leftover.begin()[-2] == '\r');
1224
1225 // We're in the middle of a message, so set up our state as such. Note that the only way to
1226 // resume a SuspendedRequest is via an HttpServer, but HttpServers never call
1227 // `awaitNextMessage()` before fully reading request bodies, meaning we expect that
1228 // `messageReadQueue` will never be used.
1229 ++pendingMessageCount;
1230 auto paf = kj::newPromiseAndFulfiller<void>();
1231 onMessageDone = kj::mv(paf.fulfiller);
1232 messageReadQueue = kj::mv(paf.promise);
1233 }
1234
1235 bool canReuse() {
1236 return !broken && pendingMessageCount == 0;
1237 }
1238
1239 bool canSuspend() {
1240 // We are at a suspendable point if we've parsed the headers, but haven't consumed anything
1241 // beyond that.
1242 //
1243 // TODO(cleanup): This is a silly check; we need a more defined way to track the state of the
1244 // stream.
1245 bool messageHeaderEndLooksRight =
1246 (leftover.begin() - (headerBuffer.begin() + messageHeaderEnd) == 2 &&
1247 leftover.begin()[-1] == '\n' && leftover.begin()[-2] == '\r')
1248 || (leftover.begin() - (headerBuffer.begin() + messageHeaderEnd) == 1 &&
1249 leftover.begin()[-1] == '\n');
1250
1251 return !broken && headerBuffer.size() > 0 && messageHeaderEndLooksRight;
1252 }
1253
1254 // ---------------------------------------------------------------------------
1255 // public interface
1256
1257 kj::Promise<Request> readRequest() override {
1258 return readRequestHeaders()
1259 .then([this](HttpHeaders::RequestConnectOrProtocolError&& requestOrProtocolError)
1260 -> HttpInputStream::Request {
1261 auto request = KJ_REQUIRE_NONNULL(
1262 requestOrProtocolError.tryGet<HttpHeaders::Request>(), "bad request");
1263 auto body = getEntityBody(HttpInputStreamImpl::REQUEST, request.method, 0, headers);
1264
1265 return { request.method, request.url, headers, kj::mv(body) };
1266 });
1267 }
1268
1269 kj::Promise<kj::OneOf<Request, Connect>> readRequestAllowingConnect() override {
1270 return readRequestHeaders()
1271 .then([this](HttpHeaders::RequestConnectOrProtocolError&& requestOrProtocolError)
1272 -> kj::OneOf<HttpInputStream::Request, HttpInputStream::Connect> {
1273 KJ_SWITCH_ONEOF(requestOrProtocolError) {
1274 KJ_CASE_ONEOF(request, HttpHeaders::Request) {
1275 auto body = getEntityBody(HttpInputStreamImpl::REQUEST, request.method, 0, headers);
1276 return HttpInputStream::Request { request.method, request.url, headers, kj::mv(body) };
1277 }
1278 KJ_CASE_ONEOF(request, HttpHeaders::ConnectRequest) {
1279 auto body = getEntityBody(HttpInputStreamImpl::REQUEST, HttpConnectMethod(), 0, headers);
1280 return HttpInputStream::Connect { request.authority, headers, kj::mv(body) };
1281 }
1282 KJ_CASE_ONEOF(error, HttpHeaders::ProtocolError) {
1283 KJ_FAIL_REQUIRE("bad request");
1284 }
1285 }
1286 KJ_UNREACHABLE;
1287 });
1288 }
1289
1290 kj::Promise<Response> readResponse(HttpMethod requestMethod) override {
1291 return readResponseHeaders()
1292 .then([this,requestMethod](HttpHeaders::ResponseOrProtocolError&& responseOrProtocolError)
1293 -> HttpInputStream::Response {
1294 auto response = KJ_REQUIRE_NONNULL(
1295 responseOrProtocolError.tryGet<HttpHeaders::Response>(), "bad response");
1296 auto body = getEntityBody(HttpInputStreamImpl::RESPONSE, requestMethod,
1297 response.statusCode, headers);
1298
1299 return { response.statusCode, response.statusText, headers, kj::mv(body) };
1300 });
1301 }
1302
1303 kj::Promise<Message> readMessage() override {
1304 return readMessageHeaders()
1305 .then([this](kj::ArrayPtr<char> text) -> HttpInputStream::Message {
1306 headers.clear();
1307 KJ_REQUIRE(headers.tryParse(text), "bad message");
1308 auto body = getEntityBody(HttpInputStreamImpl::RESPONSE, HttpMethod::GET, 0, headers);
1309
1310 return { headers, kj::mv(body) };
1311 });
1312 }
1313
1314 // ---------------------------------------------------------------------------
1315 // Stream locking: While an entity-body is being read, the body stream "locks" the underlying
1316 // HTTP stream. Once the entity-body is complete, we can read the next pipelined message.
1317
1318 void finishRead() {
1319 // Called when entire request has been read.
1320
1321 KJ_REQUIRE_NONNULL(onMessageDone)->fulfill();
1322 onMessageDone = nullptr;
1323 --pendingMessageCount;
1324 }
1325
1326 void abortRead() {
1327 // Called when a body input stream was destroyed without reading to the end.
1328
1329 KJ_REQUIRE_NONNULL(onMessageDone)->reject(KJ_EXCEPTION(FAILED,
1330 "application did not finish reading previous HTTP response body",
1331 "can't read next pipelined request/response"));
1332 onMessageDone = nullptr;
1333 broken = true;
1334 }
1335
1336 // ---------------------------------------------------------------------------
1337
1338 kj::Promise<bool> awaitNextMessage() override {
1339 // Waits until more data is available, but doesn't consume it. Returns false on EOF.
1340 //
1341 // Used on the server after a request is handled, to check for pipelined requests.
1342 //
1343 // Used on the client to detect when idle connections are closed from the server end. (In this
1344 // case, the promise always returns false or is canceled.)
1345
1346 if (resumingRequest != nullptr) {
1347 // We're resuming a request, so report that we have a message.
1348 return true;
1349 }
1350
1351 if (onMessageDone != nullptr) {
1352 // We're still working on reading the previous body.
1353 auto fork = messageReadQueue.fork();
1354 messageReadQueue = fork.addBranch();
1355 return fork.addBranch().then([this]() {
1356 return awaitNextMessage();
1357 });
1358 }
1359
1360 snarfBufferedLineBreak();
1361
1362 if (!lineBreakBeforeNextHeader && leftover != nullptr) {
1363 return true;
1364 }
1365
1366 return inner.tryRead(headerBuffer.begin(), 1, headerBuffer.size())
1367 .then([this](size_t amount) -> kj::Promise<bool> {
1368 if (amount > 0) {
1369 leftover = headerBuffer.slice(0, amount);
1370 return awaitNextMessage();
1371 } else {
1372 return false;
1373 }
1374 });
1375 }
1376
1377 bool isCleanDrain() {
1378 // Returns whether we can cleanly drain the stream at this point.
1379 if (onMessageDone != nullptr) return false;
1380 snarfBufferedLineBreak();
1381 return !lineBreakBeforeNextHeader && leftover == nullptr;
1382 }
1383
1384 kj::Promise<kj::ArrayPtr<char>> readMessageHeaders() {
1385 ++pendingMessageCount;
1386 auto paf = kj::newPromiseAndFulfiller<void>();
1387
1388 auto promise = messageReadQueue
1389 .then([this,fulfiller=kj::mv(paf.fulfiller)]() mutable {
1390 onMessageDone = kj::mv(fulfiller);
1391 return readHeader(HeaderType::MESSAGE, 0, 0);
1392 });
1393
1394 messageReadQueue = kj::mv(paf.promise);
1395
1396 return promise;
1397 }
1398
1399 kj::Promise<uint64_t> readChunkHeader() {
1400 KJ_REQUIRE(onMessageDone != nullptr);
1401
1402 // We use the portion of the header after the end of message headers.
1403 return readHeader(HeaderType::CHUNK, messageHeaderEnd, messageHeaderEnd)
1404 .then([](kj::ArrayPtr<char> text) -> uint64_t {
1405 KJ_REQUIRE(text.size() > 0) { break; }
1406
1407 uint64_t value = 0;
1408 for (char c: text) {
1409 uint64_t digit;
1410 if ('0' <= c && c <= '9') {
1411 digit = c - '0';
1412 } else if ('a' <= c && c <= 'f') {
1413 digit = c - 'a' + 10;
1414 } else if ('A' <= c && c <= 'F') {
1415 digit = c - 'A' + 10;
1416 } else {
1417 KJ_FAIL_REQUIRE("invalid HTTP chunk size", text, text.asBytes()) { break; }
1418 return value;
1419 }
1420 KJ_REQUIRE(value <= (uint64_t(kj::maxValue) >> 4),
1421 "HTTP chunk size overflow", text, text.asBytes()) { break; }
1422 value = value * 16 + digit;
1423 }
1424
1425 return value;
1426 });
1427 }
1428
1429 inline kj::Promise<HttpHeaders::RequestConnectOrProtocolError> readRequestHeaders() {
1430 KJ_IF_MAYBE(resuming, resumingRequest) {
1431 KJ_DEFER(resumingRequest = nullptr);
1432 return HttpHeaders::RequestConnectOrProtocolError(*resuming);
1433 }
1434
1435 return readMessageHeaders().then([this](kj::ArrayPtr<char> text) {
1436 headers.clear();
1437 return headers.tryParseRequestOrConnect(text);
1438 });
1439 }
1440
1441 inline kj::Promise<HttpHeaders::ResponseOrProtocolError> readResponseHeaders() {
1442 // Note: readResponseHeaders() could be called multiple times concurrently when pipelining
1443 // requests. readMessageHeaders() will serialize these, but it's important not to mess with
1444 // state (like calling headers.clear()) before said serialization has taken place.
1445 return readMessageHeaders().then([this](kj::ArrayPtr<char> text) {
1446 headers.clear();
1447 return headers.tryParseResponse(text);
1448 });
1449 }
1450
1451 inline const HttpHeaders& getHeaders() const { return headers; }
1452
1453 Promise<size_t> tryRead(void* buffer, size_t minBytes, size_t maxBytes) {
1454 // Read message body data.
1455
1456 KJ_REQUIRE(onMessageDone != nullptr);
1457
1458 if (leftover == nullptr) {
1459 // No leftovers. Forward directly to inner stream.
1460 return inner.tryRead(buffer, minBytes, maxBytes);
1461 } else if (leftover.size() >= maxBytes) {
1462 // Didn't even read the entire leftover buffer.
1463 memcpy(buffer, leftover.begin(), maxBytes);
1464 leftover = leftover.slice(maxBytes, leftover.size());
1465 return maxBytes;
1466 } else {
1467 // Read the entire leftover buffer, plus some.
1468 memcpy(buffer, leftover.begin(), leftover.size());
1469 size_t copied = leftover.size();
1470 leftover = nullptr;
1471 if (copied >= minBytes) {
1472 // Got enough to stop here.
1473 return copied;
1474 } else {
1475 // Read the rest from the underlying stream.
1476 return inner.tryRead(reinterpret_cast<byte*>(buffer) + copied,
1477 minBytes - copied, maxBytes - copied)
1478 .then([copied](size_t n) { return n + copied; });
1479 }
1480 }
1481 }
1482
1483 enum RequestOrResponse {
1484 REQUEST,
1485 RESPONSE
1486 };
1487
1488 kj::Own<kj::AsyncInputStream> getEntityBody(
1489 RequestOrResponse type,
1490 kj::OneOf<HttpMethod, HttpConnectMethod> method,
1491 uint statusCode,
1492 const kj::HttpHeaders& headers);
1493
1494 struct ReleasedBuffer {
1495 kj::Array<byte> buffer;
1496 kj::ArrayPtr<byte> leftover;
1497 };
1498
1499 ReleasedBuffer releaseBuffer() {
1500 return { headerBuffer.releaseAsBytes(), leftover.asBytes() };
1501 }
1502
1503 private:
1504 AsyncInputStream& inner;
1505 kj::Array<char> headerBuffer;
1506
1507 size_t messageHeaderEnd = 0;
1508 // Position in headerBuffer where the message headers end -- further buffer space can
1509 // be used for chunk headers.
1510
1511 kj::ArrayPtr<char> leftover;
1512 // Data in headerBuffer that comes immediately after the header content, if any.
1513
1514 HttpHeaders headers;
1515 // Parsed headers, after a call to parseAwaited*().
1516
1517 kj::Maybe<kj::OneOf<HttpHeaders::Request, HttpHeaders::ConnectRequest>> resumingRequest;
1518 // Non-null if we're resuming a SuspendedRequest.
1519
1520 bool lineBreakBeforeNextHeader = false;
1521 // If true, the next await should expect to start with a spurious '\n' or '\r\n'. This happens
1522 // as a side-effect of HTTP chunked encoding, where such a newline is added to the end of each
1523 // chunk, for no good reason.
1524
1525 bool broken = false;
1526 // Becomes true if the caller failed to read the whole entity-body before closing the stream.
1527
1528 uint pendingMessageCount = 0;
1529 // Number of reads we have queued up.
1530
1531 kj::Promise<void> messageReadQueue = kj::READY_NOW;
1532
1533 kj::Maybe<kj::Own<kj::PromiseFulfiller<void>>> onMessageDone;
1534 // Fulfill once the current message has been completely read. Unblocks reading of the next
1535 // message headers.
1536
1537 enum class HeaderType {
1538 MESSAGE,
1539 CHUNK
1540 };
1541
1542 kj::Promise<kj::ArrayPtr<char>> readHeader(
1543 HeaderType type, size_t bufferStart, size_t bufferEnd) {
1544 // Reads the HTTP message header or a chunk header (as in transfer-encoding chunked) and
1545 // returns the buffer slice containing it.
1546 //
1547 // The main source of complication here is that we want to end up with one continuous buffer
1548 // containing the result, and that the input is delimited by newlines rather than by an upfront
1549 // length.
1550
1551 kj::Promise<size_t> readPromise = nullptr;
1552
1553 // Figure out where we're reading from.
1554 if (leftover != nullptr) {
1555 // Some data is still left over from the previous message, so start with that.
1556
1557 // This can only happen if this is the initial call to readHeader() (not recursive).
1558 KJ_ASSERT(bufferStart == bufferEnd);
1559
1560 // OK, set bufferStart and bufferEnd to both point to the start of the leftover, and then
1561 // fake a read promise as if we read the bytes from the leftover.
1562 bufferStart = leftover.begin() - headerBuffer.begin();
1563 bufferEnd = bufferStart;
1564 readPromise = leftover.size();
1565 leftover = nullptr;
1566 } else {
1567 // Need to read more data from the underlying stream.
1568
1569 if (bufferEnd == headerBuffer.size()) {
1570 // Out of buffer space.
1571
1572 // Maybe we can move bufferStart backwards to make more space at the end?
1573 size_t minStart = type == HeaderType::MESSAGE ? 0 : messageHeaderEnd;
1574
1575 if (bufferStart > minStart) {
1576 // Move to make space.
1577 memmove(headerBuffer.begin() + minStart, headerBuffer.begin() + bufferStart,
1578 bufferEnd - bufferStart);
1579 bufferEnd = bufferEnd - bufferStart + minStart;
1580 bufferStart = minStart;
1581 } else {
1582 // Really out of buffer space. Grow the buffer.
1583 if (type != HeaderType::MESSAGE) {
1584 // Can't grow because we'd invalidate the HTTP headers.
1585 return KJ_EXCEPTION(FAILED, "invalid HTTP chunk size");
1586 }
1587 KJ_REQUIRE(headerBuffer.size() < MAX_BUFFER, "request headers too large");
1588 auto newBuffer = kj::heapArray<char>(headerBuffer.size() * 2);
1589 memcpy(newBuffer.begin(), headerBuffer.begin(), headerBuffer.size());
1590 headerBuffer = kj::mv(newBuffer);
1591 }
1592 }
1593
1594 // How many bytes will we read?
1595 size_t maxBytes = headerBuffer.size() - bufferEnd;
1596
1597 if (type == HeaderType::CHUNK) {
1598 // Roughly limit the amount of data we read to MAX_CHUNK_HEADER_SIZE.
1599 // TODO(perf): This is mainly to avoid copying a lot of body data into our buffer just to
1600 // copy it again when it is read. But maybe the copy would be cheaper than overhead of
1601 // extra event loop turns?
1602 KJ_REQUIRE(bufferEnd - bufferStart <= MAX_CHUNK_HEADER_SIZE, "invalid HTTP chunk size");
1603 maxBytes = kj::min(maxBytes, MAX_CHUNK_HEADER_SIZE);
1604 }
1605
1606 readPromise = inner.read(headerBuffer.begin() + bufferEnd, 1, maxBytes);
1607 }
1608
1609 return readPromise.then([this,type,bufferStart,bufferEnd](size_t amount) mutable
1610 -> kj::Promise<kj::ArrayPtr<char>> {
1611 if (lineBreakBeforeNextHeader) {
1612 // Hackily deal with expected leading line break.
1613 if (bufferEnd == bufferStart && headerBuffer[bufferEnd] == '\r') {
1614 ++bufferEnd;
1615 --amount;
1616 }
1617
1618 if (amount > 0 && headerBuffer[bufferEnd] == '\n') {
1619 lineBreakBeforeNextHeader = false;
1620 ++bufferEnd;
1621 --amount;
1622
1623 // Cut the leading line break out of the buffer entirely.
1624 bufferStart = bufferEnd;
1625 }
1626
1627 if (amount == 0) {
1628 return readHeader(type, bufferStart, bufferEnd);
1629 }
1630 }
1631
1632 size_t pos = bufferEnd;
1633 size_t newEnd = pos + amount;
1634
1635 for (;;) {
1636 // Search for next newline.
1637 char* nl = reinterpret_cast<char*>(
1638 memchr(headerBuffer.begin() + pos, '\n', newEnd - pos));
1639 if (nl == nullptr) {
1640 // No newline found. Wait for more data.
1641 return readHeader(type, bufferStart, newEnd);
1642 }
1643
1644 // Is this newline which we found the last of the header? For a chunk header, always. For
1645 // a message header, we search for two newlines in a row. We accept either "\r\n" or just
1646 // "\n" as a newline sequence (though the standard requires "\r\n").
1647 if (type == HeaderType::CHUNK ||
1648 (nl - headerBuffer.begin() >= 4 &&
1649 ((nl[-1] == '\r' && nl[-2] == '\n') || (nl[-1] == '\n')))) {
1650 // OK, we've got all the data!
1651
1652 size_t endIndex = nl + 1 - headerBuffer.begin();
1653 size_t leftoverStart = endIndex;
1654
1655 // Strip off the last newline from end.
1656 endIndex -= 1 + (nl[-1] == '\r');
1657
1658 if (type == HeaderType::MESSAGE) {
1659 if (headerBuffer.size() - newEnd < MAX_CHUNK_HEADER_SIZE) {
1660 // Ugh, there's not enough space for the secondary await buffer. Grow once more.
1661 auto newBuffer = kj::heapArray<char>(headerBuffer.size() * 2);
1662 memcpy(newBuffer.begin(), headerBuffer.begin(), headerBuffer.size());
1663 headerBuffer = kj::mv(newBuffer);
1664 }
1665 messageHeaderEnd = endIndex;
1666 } else {
1667 // For some reason, HTTP specifies that there will be a line break after each chunk.
1668 lineBreakBeforeNextHeader = true;
1669 }
1670
1671 auto result = headerBuffer.slice(bufferStart, endIndex);
1672 leftover = headerBuffer.slice(leftoverStart, newEnd);
1673 return result;
1674 } else {
1675 pos = nl - headerBuffer.begin() + 1;
1676 }
1677 }
1678 });
1679 }
1680
1681 void snarfBufferedLineBreak() {
1682 // Slightly-crappy code to snarf the expected line break. This will actually eat the leading
1683 // regex /\r*\n?/.
1684 while (lineBreakBeforeNextHeader && leftover.size() > 0) {
1685 if (leftover[0] == '\r') {
1686 leftover = leftover.slice(1, leftover.size());
1687 } else if (leftover[0] == '\n') {
1688 leftover = leftover.slice(1, leftover.size());
1689 lineBreakBeforeNextHeader = false;
1690 } else {
1691 // Err, missing line break, whatever.
1692 lineBreakBeforeNextHeader = false;
1693 }
1694 }
1695 }
1696 };
1697
1698 // -----------------------------------------------------------------------------
1699
1700 class HttpEntityBodyReader: public kj::AsyncInputStream {
1701 public:
1702 HttpEntityBodyReader(HttpInputStreamImpl& inner) {
1703 inner.setCurrentWrapper(weakInner);
1704 }
1705 ~HttpEntityBodyReader() noexcept(false) {
1706 if (!finished) {
1707 KJ_IF_MAYBE(inner, weakInner) {
1708 inner->unsetCurrentWrapper(weakInner);
1709 inner->abortRead();
1710 } else {
1711 // Since we're in a destructor, log an error instead of throwing.
1712 KJ_LOG(ERROR, "HTTP body input stream outlived underlying connection", kj::getStackTrace());
1713 }
1714 }
1715 }
1716
1717 protected:
1718 HttpInputStreamImpl& getInner() {
1719 KJ_IF_MAYBE(i, weakInner) {
1720 return *i;
1721 } else if (finished) {
1722 // This is a bug in the implementations in this file, not the app.
1723 KJ_FAIL_ASSERT("bug in KJ HTTP: tried to access inner stream after it had been released");
1724 } else {
1725 KJ_FAIL_REQUIRE("HTTP body input stream outlived underlying connection");
1726 }
1727 }
1728
1729 void doneReading() {
1730 auto& inner = getInner();
1731 inner.unsetCurrentWrapper(weakInner);
1732 finished = true;
1733 inner.finishRead();
1734 }
1735
1736 inline bool alreadyDone() { return weakInner == nullptr; }
1737
1738 private:
1739 kj::Maybe<HttpInputStreamImpl&> weakInner;
1740 bool finished = false;
1741 };
1742
1743 class HttpNullEntityReader final: public HttpEntityBodyReader {
1744 // Stream for an entity-body which is not present. Always returns EOF on read, but tryGetLength()
1745 // may indicate non-zero in the special case of a response to a HEAD request.
1746
1747 public:
1748 HttpNullEntityReader(HttpInputStreamImpl& inner, kj::Maybe<uint64_t> length)
1749 : HttpEntityBodyReader(inner), length(length) {
1750 // `length` is what to return from tryGetLength(). For a response to a HEAD request, this may
1751 // be non-zero.
1752 doneReading();
1753 }
1754
1755 Promise<size_t> tryRead(void* buffer, size_t minBytes, size_t maxBytes) override {
1756 return constPromise<size_t, 0>();
1757 }
1758
1759 Maybe<uint64_t> tryGetLength() override {
1760 return length;
1761 }
1762
1763 private:
1764 kj::Maybe<uint64_t> length;
1765 };
1766
1767 class HttpConnectionCloseEntityReader final: public HttpEntityBodyReader {
1768 // Stream which reads until EOF.
1769
1770 public:
1771 HttpConnectionCloseEntityReader(HttpInputStreamImpl& inner)
1772 : HttpEntityBodyReader(inner) {}
1773
1774 Promise<size_t> tryRead(void* buffer, size_t minBytes, size_t maxBytes) override {
1775 if (alreadyDone()) return constPromise<size_t, 0>();
1776
1777 return getInner().tryRead(buffer, minBytes, maxBytes)
1778 .then([=](size_t amount) {
1779 if (amount < minBytes) {
1780 doneReading();
1781 }
1782 return amount;
1783 });
1784 }
1785 };
1786
1787 class HttpFixedLengthEntityReader final: public HttpEntityBodyReader {
1788 // Stream which reads only up to a fixed length from the underlying stream, then emulates EOF.
1789
1790 public:
1791 HttpFixedLengthEntityReader(HttpInputStreamImpl& inner, size_t length)
1792 : HttpEntityBodyReader(inner), length(length) {
1793 if (length == 0) doneReading();
1794 }
1795
1796 Maybe<uint64_t> tryGetLength() override {
1797 return length;
1798 }
1799
1800 Promise<size_t> tryRead(void* buffer, size_t minBytes, size_t maxBytes) override {
1801 KJ_REQUIRE(clean, "can't read more data after a previous read didn't complete");
1802 clean = false;
1803 return tryReadInternal(buffer, minBytes, maxBytes, 0);
1804 }
1805
1806 private:
1807 size_t length;
1808 bool clean = true;
1809
1810 Promise<size_t> tryReadInternal(void* buffer, size_t minBytes, size_t maxBytes,
1811 size_t alreadyRead) {
1812 if (length == 0) {
1813 clean = true;
1814 return constPromise<size_t, 0>();
1815 }
1816
1817 // We have to set minBytes to 1 here so that if we read any data at all, we update our
1818 // counter immediately, so that we still know where we are in case of cancellation.
1819 return getInner().tryRead(buffer, 1, kj::min(maxBytes, length))
1820 .then([=](size_t amount) -> kj::Promise<size_t> {
1821 length -= amount;
1822 if (length > 0) {
1823 // We haven't reached the end of the entity body yet.
1824 if (amount == 0) {
1825 kj::throwRecoverableException(KJ_EXCEPTION(DISCONNECTED,
1826 "premature EOF in HTTP entity body; did not reach Content-Length"));
1827 } else if (amount < minBytes) {
1828 // We requested a minimum 1 byte above, but our own caller actually set a larger minimum
1829 // which has not yet been reached. Keep trying until we reach it.
1830 return tryReadInternal(reinterpret_cast<byte*>(buffer) + amount,
1831 minBytes - amount, maxBytes - amount, alreadyRead + amount);
1832 }
1833 } else if (length == 0) {
1834 doneReading();
1835 }
1836 clean = true;
1837 return amount + alreadyRead;
1838 });
1839 }
1840 };
1841
1842 class HttpChunkedEntityReader final: public HttpEntityBodyReader {
1843 // Stream which reads a Transfer-Encoding: Chunked stream.
1844
1845 public:
1846 HttpChunkedEntityReader(HttpInputStreamImpl& inner)
1847 : HttpEntityBodyReader(inner) {}
1848
1849 Promise<size_t> tryRead(void* buffer, size_t minBytes, size_t maxBytes) override {
1850 KJ_REQUIRE(clean, "can't read more data after a previous read didn't complete");
1851 clean = false;
1852 return tryReadInternal(buffer, minBytes, maxBytes, 0);
1853 }
1854
1855 private:
1856 size_t chunkSize = 0;
1857 bool clean = true;
1858
1859 Promise<size_t> tryReadInternal(void* buffer, size_t minBytes, size_t maxBytes,
1860 size_t alreadyRead) {
1861 if (alreadyDone()) {
1862 clean = true;
1863 return alreadyRead;
1864 } else if (chunkSize == 0) {
1865 // Read next chunk header.
1866 return getInner().readChunkHeader().then([=](uint64_t nextChunkSize) {
1867 if (nextChunkSize == 0) {
1868 doneReading();
1869 }
1870
1871 chunkSize = nextChunkSize;
1872 return tryReadInternal(buffer, minBytes, maxBytes, alreadyRead);
1873 });
1874 } else {
1875 // Read current chunk.
1876 // We have to set minBytes to 1 here so that if we read any data at all, we update our
1877 // counter immediately, so that we still know where we are in case of cancellation.
1878 return getInner().tryRead(buffer, 1, kj::min(maxBytes, chunkSize))
1879 .then([=](size_t amount) -> kj::Promise<size_t> {
1880 chunkSize -= amount;
1881 if (amount == 0) {
1882 kj::throwRecoverableException(KJ_EXCEPTION(DISCONNECTED, "premature EOF in HTTP chunk"));
1883 } else if (amount < minBytes) {
1884 // We requested a minimum 1 byte above, but our own caller actually set a larger minimum
1885 // which has not yet been reached. Keep trying until we reach it.
1886 return tryReadInternal(reinterpret_cast<byte*>(buffer) + amount,
1887 minBytes - amount, maxBytes - amount, alreadyRead + amount);
1888 }
1889 clean = true;
1890 return alreadyRead + amount;
1891 });
1892 }
1893 }
1894 };
1895
1896 template <char...>
1897 struct FastCaseCmp;
1898
1899 template <char first, char... rest>
1900 struct FastCaseCmp<first, rest...> {
1901 static constexpr bool apply(const char* actual) {
1902 return
1903 ('a' <= first && first <= 'z') || ('A' <= first && first <= 'Z')
1904 ? (*actual | 0x20) == (first | 0x20) && FastCaseCmp<rest...>::apply(actual + 1)
1905 : *actual == first && FastCaseCmp<rest...>::apply(actual + 1);
1906 }
1907 };
1908
1909 template <>
1910 struct FastCaseCmp<> {
1911 static constexpr bool apply(const char* actual) {
1912 return *actual == '\0';
1913 }
1914 };
1915
1916 template <char... chars>
1917 constexpr bool fastCaseCmp(const char* actual) {
1918 return FastCaseCmp<chars...>::apply(actual);
1919 }
1920
1921 // Tests
1922 static_assert(fastCaseCmp<'f','O','o','B','1'>("FooB1"), "");
1923 static_assert(!fastCaseCmp<'f','O','o','B','2'>("FooB1"), "");
1924 static_assert(!fastCaseCmp<'n','O','o','B','1'>("FooB1"), "");
1925 static_assert(!fastCaseCmp<'f','O','o','B'>("FooB1"), "");
1926 static_assert(!fastCaseCmp<'f','O','o','B','1','a'>("FooB1"), "");
1927
1928 kj::Own<kj::AsyncInputStream> HttpInputStreamImpl::getEntityBody(
1929 RequestOrResponse type,
1930 kj::OneOf<HttpMethod, HttpConnectMethod> method,
1931 uint statusCode,
1932 const kj::HttpHeaders& headers) {
1933 KJ_REQUIRE(headerBuffer.size() > 0, "Cannot get entity body after header buffer release.");
1934
1935 auto isHeadRequest = method.tryGet<HttpMethod>().map([](auto& m) {
1936 return m == HttpMethod::HEAD;
1937 }).orDefault(false);
1938
1939 auto isConnectRequest = method.is<HttpConnectMethod>();
1940
1941 // Rules to determine how HTTP entity-body is delimited:
1942 // https://tools.ietf.org/html/rfc7230#section-3.3.3
1943 // #1
1944 if (type == RESPONSE) {
1945 if (isHeadRequest) {
1946 // Body elided.
1947 kj::Maybe<uint64_t> length;
1948 KJ_IF_MAYBE(cl, headers.get(HttpHeaderId::CONTENT_LENGTH)) {
1949 // Validate that the Content-Length is a non-negative integer. Note that strtoull() accepts
1950 // leading '-' signs and silently converts negative values to large unsigned values, so we
1951 // must explicitly check for a leading digit.
1952 char* end;
1953 uint64_t parsedValue = strtoull(cl->cStr(), &end, 10);
1954 if ((*cl)[0] >= '0' && (*cl)[0] <= '9' && end > cl->begin() && *end == '\0') {
1955 length = parsedValue;
1956 }
1957 // If invalid, we just leave `length` as nullptr, since the body is elided anyway.
1958 } else if (headers.get(HttpHeaderId::TRANSFER_ENCODING) == nullptr) {
1959 // HACK: Neither Content-Length nor Transfer-Encoding header in response to HEAD
1960 // request. Propagate this fact with a 0 expected body length.
1961 length = uint64_t(0);
1962 }
1963 return kj::heap<HttpNullEntityReader>(*this, length);
1964 } else if (isConnectRequest && statusCode >= 200 && statusCode < 300) {
1965 KJ_FAIL_ASSERT("a CONNECT response with a 2xx status does not have an entity body to get");
1966 } else if (statusCode == 204 || statusCode == 304) {
1967 // No body.
1968 return kj::heap<HttpNullEntityReader>(*this, uint64_t(0));
1969 }
1970 }
1971
1972 // For CONNECT requests messages, we let the rest of the logic play out.
1973 // We already check before here to ensure that Transfer-Encoding and
1974 // Content-Length headers are not present in which case the code below
1975 // does the right thing.
1976
1977 // #3
1978 KJ_IF_MAYBE(te, headers.get(HttpHeaderId::TRANSFER_ENCODING)) {
1979 // TODO(someday): Support pluggable transfer encodings? Or at least gzip?
1980 // TODO(someday): Support stacked transfer encodings, e.g. "gzip, chunked".
1981
1982 // NOTE: #3¶3 is ambiguous about what should happen if Transfer-Encoding and Content-Length are
1983 // both present. It says that Transfer-Encoding takes precedence, but also that the request
1984 // "ought to be handled as an error", and that proxies "MUST" drop the Content-Length before
1985 // forwarding. We ignore the vague "ought to" part and implement the other two. (The
1986 // dropping of Content-Length will happen naturally if/when the message is sent back out to
1987 // the network.)
1988 if (fastCaseCmp<'c','h','u','n','k','e','d'>(te->cStr())) {
1989 // #3¶1
1990 return kj::heap<HttpChunkedEntityReader>(*this);
1991 } else if (fastCaseCmp<'i','d','e','n','t','i','t','y'>(te->cStr())) {
1992 // #3¶2
1993 KJ_REQUIRE(type != REQUEST, "request body cannot have Transfer-Encoding other than chunked");
1994 return kj::heap<HttpConnectionCloseEntityReader>(*this);
1995 }
1996
1997 KJ_FAIL_REQUIRE("unknown transfer encoding", *te) { break; };
1998 }
1999
2000 // #4 and #5
2001 KJ_IF_MAYBE(cl, headers.get(HttpHeaderId::CONTENT_LENGTH)) {
2002 // NOTE: By spec, multiple Content-Length values are allowed as long as they are the same, e.g.
2003 // "Content-Length: 5, 5, 5". Hopefully no one actually does that...
2004 char* end;
2005 uint64_t length = strtoull(cl->cStr(), &end, 10);
2006 // Note that strtoull() accepts leading '-' signs and silently converts negative values to
2007 // large unsigned values, so we must explicitly check for a leading digit.
2008 if ((*cl)[0] >= '0' && (*cl)[0] <= '9' && end > cl->begin() && *end == '\0') {
2009 // #5
2010 return kj::heap<HttpFixedLengthEntityReader>(*this, length);
2011 } else {
2012 // #4 (bad content-length)
2013 KJ_FAIL_REQUIRE("invalid Content-Length header value", *cl) { break; }
2014 // To pass the -fno-exceptions test (but KJ-HTTP is really not safe to use in that mode).
2015 return kj::heap<HttpNullEntityReader>(*this, uint64_t(0));
2016 }
2017 }
2018
2019 // #6
2020 if (type == REQUEST) {
2021 // Lack of a Content-Length or Transfer-Encoding means no body for requests.
2022 return kj::heap<HttpNullEntityReader>(*this, uint64_t(0));
2023 }
2024
2025 // RFC 2616 permitted "multipart/byteranges" responses to be self-delimiting, but this was
2026 // mercifully removed in RFC 7230, and new exceptions of this type are disallowed:
2027 // https://www.w3.org/Protocols/rfc2616/rfc2616-sec4.html#sec4.4
2028 // https://tools.ietf.org/html/rfc7230#page-81
2029 // To be extra-safe, we'll reject a multipart/byteranges response that lacks transfer-encoding
2030 // and content-length.
2031 KJ_IF_MAYBE(type, headers.get(HttpHeaderId::CONTENT_TYPE)) {
2032 if (type->startsWith("multipart/byteranges")) {
2033 KJ_FAIL_REQUIRE(
2034 "refusing to handle multipart/byteranges response without transfer-encoding nor "
2035 "content-length due to ambiguity between RFC 2616 vs RFC 7230.");
2036 }
2037 }
2038
2039 // #7
2040 return kj::heap<HttpConnectionCloseEntityReader>(*this);
2041 }
2042
2043 } // namespace
2044
2045 kj::Own<HttpInputStream> newHttpInputStream(
2046 kj::AsyncInputStream& input, const HttpHeaderTable& table) {
2047 return kj::heap<HttpInputStreamImpl>(input, table);
2048 }
2049
2050 // =======================================================================================
2051
2052 namespace {
2053
2054 class HttpOutputStream: public WrappableStreamMixin<HttpOutputStream> {
2055 public:
2056 HttpOutputStream(AsyncOutputStream& inner): inner(inner) {}
2057
2058 bool isInBody() {
2059 return inBody;
2060 }
2061
2062 bool canReuse() {
2063 return !inBody && !broken && !writeInProgress;
2064 }
2065
2066 bool canWriteBodyData() {
2067 return !writeInProgress && inBody;
2068 }
2069
2070 bool isBroken() {
2071 return broken;
2072 }
2073
2074 void writeHeaders(String content) {
2075 // Writes some header content and begins a new entity body.
2076
2077 KJ_REQUIRE(!writeInProgress, "concurrent write()s not allowed") { return; }
2078 KJ_REQUIRE(!inBody, "previous HTTP message body incomplete; can't write more messages");
2079 inBody = true;
2080
2081 queueWrite(kj::mv(content));
2082 }
2083
2084 void writeBodyData(kj::String content) {
2085 KJ_REQUIRE(!writeInProgress, "concurrent write()s not allowed") { return; }
2086 KJ_REQUIRE(inBody) { return; }
2087
2088 queueWrite(kj::mv(content));
2089 }
2090
2091 kj::Promise<void> writeBodyData(const void* buffer, size_t size) {
2092 KJ_REQUIRE(!writeInProgress, "concurrent write()s not allowed") { return kj::READY_NOW; }
2093 KJ_REQUIRE(inBody) { return kj::READY_NOW; }
2094
2095 writeInProgress = true;
2096 auto fork = writeQueue.fork();
2097 writeQueue = fork.addBranch();
2098
2099 return fork.addBranch().then([this,buffer,size]() {
2100 return inner.write(buffer, size);
2101 }).then([this]() {
2102 writeInProgress = false;
2103 });
2104 }
2105
2106 kj::Promise<void> writeBodyData(kj::ArrayPtr<const kj::ArrayPtr<const byte>> pieces) {
2107 KJ_REQUIRE(!writeInProgress, "concurrent write()s not allowed") { return kj::READY_NOW; }
2108 KJ_REQUIRE(inBody) { return kj::READY_NOW; }
2109
2110 writeInProgress = true;
2111 auto fork = writeQueue.fork();
2112 writeQueue = fork.addBranch();
2113
2114 return fork.addBranch().then([this,pieces]() {
2115 return inner.write(pieces);
2116 }).then([this]() {
2117 writeInProgress = false;
2118 });
2119 }
2120
2121 Promise<uint64_t> pumpBodyFrom(AsyncInputStream& input, uint64_t amount) {
2122 KJ_REQUIRE(!writeInProgress, "concurrent write()s not allowed") { return uint64_t(0); }
2123 KJ_REQUIRE(inBody) { return uint64_t(0); }
2124
2125 writeInProgress = true;
2126 auto fork = writeQueue.fork();
2127 writeQueue = fork.addBranch();
2128
2129 return fork.addBranch().then([this,&input,amount]() {
2130 return input.pumpTo(inner, amount);
2131 }).then([this](uint64_t actual) {
2132 writeInProgress = false;
2133 return actual;
2134 });
2135 }
2136
2137 void finishBody() {
2138 // Called when entire body was written.
2139
2140 KJ_REQUIRE(inBody) { return; }
2141 inBody = false;
2142
2143 if (writeInProgress) {
2144 // It looks like the last write never completed -- possibly because it was canceled or threw
2145 // an exception. We must treat this equivalent to abortBody().
2146 broken = true;
2147
2148 // Cancel any writes that are still queued.
2149 writeQueue = KJ_EXCEPTION(FAILED,
2150 "previous HTTP message body incomplete; can't write more messages");
2151 }
2152 }
2153
2154 void abortBody() {
2155 // Called if the application failed to write all expected body bytes.
2156 KJ_REQUIRE(inBody) { return; }
2157 inBody = false;
2158 broken = true;
2159
2160 // Cancel any writes that are still queued.
2161 writeQueue = KJ_EXCEPTION(FAILED,
2162 "previous HTTP message body incomplete; can't write more messages");
2163 }
2164
2165 kj::Promise<void> flush() {
2166 auto fork = writeQueue.fork();
2167 writeQueue = fork.addBranch();
2168 return fork.addBranch();
2169 }
2170
2171 Promise<void> whenWriteDisconnected() {
2172 return inner.whenWriteDisconnected();
2173 }
2174
2175 bool isWriteInProgress() { return writeInProgress; }
2176
2177 private:
2178 AsyncOutputStream& inner;
2179 kj::Promise<void> writeQueue = kj::READY_NOW;
2180 bool inBody = false;
2181 bool broken = false;
2182
2183 bool writeInProgress = false;
2184 // True if a write method has been called and has not completed successfully. In the case that
2185 // a write throws an exception or is canceled, this remains true forever. In these cases, the
2186 // underlying stream is in an inconsistent state and cannot be reused.
2187
2188 void queueWrite(kj::String content) {
2189 // We only use queueWrite() in cases where we can take ownership of the write buffer, and where
2190 // it is convenient if we can return `void` rather than a promise. In particular, this is used
2191 // to write headers and chunk boundaries. Writes of application data do not go into
2192 // `writeQueue` because this would prevent cancellation. Instead, they wait until `writeQueue`
2193 // is empty, then they make the write directly, using `writeInProgress` to detect and block
2194 // concurrent writes.
2195
2196 writeQueue = writeQueue.then([this,content=kj::mv(content)]() mutable {
2197 auto promise = inner.write(content.begin(), content.size());
2198 return promise.attach(kj::mv(content));
2199 });
2200 }
2201 };
2202
2203 class HttpEntityBodyWriter: public kj::AsyncOutputStream {
2204 public:
2205 HttpEntityBodyWriter(HttpOutputStream& inner) {
2206 inner.setCurrentWrapper(weakInner);
2207 }
2208 ~HttpEntityBodyWriter() noexcept(false) {
2209 if (!finished) {
2210 KJ_IF_MAYBE(inner, weakInner) {
2211 inner->unsetCurrentWrapper(weakInner);
2212 inner->abortBody();
2213 } else {
2214 // Since we're in a destructor, log an error instead of throwing.
2215 KJ_LOG(ERROR, "HTTP body output stream outlived underlying connection",
2216 kj::getStackTrace());
2217 }
2218 }
2219 }
2220
2221 protected:
2222 HttpOutputStream& getInner() {
2223 KJ_IF_MAYBE(i, weakInner) {
2224 return *i;
2225 } else if (finished) {
2226 // This is a bug in the implementations in this file, not the app.
2227 KJ_FAIL_ASSERT("bug in KJ HTTP: tried to access inner stream after it had been released");
2228 } else {
2229 KJ_FAIL_REQUIRE("HTTP body output stream outlived underlying connection");
2230 }
2231 }
2232
2233 void doneWriting() {
2234 auto& inner = getInner();
2235 inner.unsetCurrentWrapper(weakInner);
2236 finished = true;
2237 inner.finishBody();
2238 }
2239
2240 inline bool alreadyDone() { return weakInner == nullptr; }
2241
2242 private:
2243 kj::Maybe<HttpOutputStream&> weakInner;
2244 bool finished = false;
2245 };
2246
2247 class HttpNullEntityWriter final: public kj::AsyncOutputStream {
2248 // Does not inherit HttpEntityBodyWriter because it doesn't actually write anything.
2249 public:
2250 Promise<void> write(const void* buffer, size_t size) override {
2251 return KJ_EXCEPTION(FAILED, "HTTP message has no entity-body; can't write()");
2252 }
2253 Promise<void> write(ArrayPtr<const ArrayPtr<const byte>> pieces) override {
2254 return KJ_EXCEPTION(FAILED, "HTTP message has no entity-body; can't write()");
2255 }
2256 Promise<void> whenWriteDisconnected() override {
2257 return kj::NEVER_DONE;
2258 }
2259 };
2260
2261 class HttpDiscardingEntityWriter final: public kj::AsyncOutputStream {
2262 // Does not inherit HttpEntityBodyWriter because it doesn't actually write anything.
2263 public:
2264 Promise<void> write(const void* buffer, size_t size) override {
2265 return kj::READY_NOW;
2266 }
2267 Promise<void> write(ArrayPtr<const ArrayPtr<const byte>> pieces) override {
2268 return kj::READY_NOW;
2269 }
2270 Promise<void> whenWriteDisconnected() override {
2271 return kj::NEVER_DONE;
2272 }
2273 };
2274
2275 class HttpFixedLengthEntityWriter final: public HttpEntityBodyWriter {
2276 public:
2277 HttpFixedLengthEntityWriter(HttpOutputStream& inner, uint64_t length)
2278 : HttpEntityBodyWriter(inner), length(length) {
2279 if (length == 0) doneWriting();
2280 }
2281
2282 Promise<void> write(const void* buffer, size_t size) override {
2283 if (size == 0) return kj::READY_NOW;
2284 KJ_REQUIRE(size <= length, "overwrote Content-Length");
2285 length -= size;
2286
2287 return maybeFinishAfter(getInner().writeBodyData(buffer, size));
2288 }
2289 Promise<void> write(ArrayPtr<const ArrayPtr<const byte>> pieces) override {
2290 uint64_t size = 0;
2291 for (auto& piece: pieces) size += piece.size();
2292
2293 if (size == 0) return kj::READY_NOW;
2294 KJ_REQUIRE(size <= length, "overwrote Content-Length");
2295 length -= size;
2296
2297 return maybeFinishAfter(getInner().writeBodyData(pieces));
2298 }
2299
2300 Maybe<Promise<uint64_t>> tryPumpFrom(AsyncInputStream& input, uint64_t amount) override {
2301 if (amount == 0) return constPromise<uint64_t, 0>();
2302
2303 bool overshot = amount > length;
2304 if (overshot) {
2305 // Hmm, the requested amount was too large, but it's common to specify kj::max as the amount
2306 // to pump, in which case we pump to EOF. Let's try to verify whether EOF is where we
2307 // expect it to be.
2308 KJ_IF_MAYBE(available, input.tryGetLength()) {
2309 // Great, the stream knows how large it is. If it's indeed larger than the space available
2310 // then let's abort.
2311 KJ_REQUIRE(*available <= length, "overwrote Content-Length");
2312 } else {
2313 // OK, we have no idea how large the input is, so we'll have to check later.
2314 }
2315 }
2316
2317 amount = kj::min(amount, length);
2318 length -= amount;
2319
2320 auto promise = amount == 0
2321 ? kj::Promise<uint64_t>(amount)
2322 : getInner().pumpBodyFrom(input, amount).then([this,amount](uint64_t actual) {
2323 // Adjust for bytes not written.
2324 length += amount - actual;
2325 if (length == 0) doneWriting();
2326 return actual;
2327 });
2328
2329 if (overshot) {
2330 promise = promise.then([amount,&input](uint64_t actual) -> kj::Promise<uint64_t> {
2331 if (actual == amount) {
2332 // We read exactly the amount expected. In order to detect an overshoot, we have to
2333 // try reading one more byte. Ugh.
2334 static byte junk;
2335 return input.tryRead(&junk, 1, 1).then([actual](size_t extra) {
2336 KJ_REQUIRE(extra == 0, "overwrote Content-Length");
2337 return actual;
2338 });
2339 } else {
2340 // We actually read less data than requested so we couldn't have overshot. In fact, we
2341 // undershot.
2342 return actual;
2343 }
2344 });
2345 }
2346
2347 return kj::mv(promise);
2348 }
2349
2350 Promise<void> whenWriteDisconnected() override {
2351 return getInner().whenWriteDisconnected();
2352 }
2353
2354 private:
2355 uint64_t length;
2356
2357 kj::Promise<void> maybeFinishAfter(kj::Promise<void> promise) {
2358 if (length == 0) {
2359 return promise.then([this]() { doneWriting(); });
2360 } else {
2361 return kj::mv(promise);
2362 }
2363 }
2364 };
2365
2366 class HttpChunkedEntityWriter final: public HttpEntityBodyWriter {
2367 public:
2368 HttpChunkedEntityWriter(HttpOutputStream& inner)
2369 : HttpEntityBodyWriter(inner) {}
2370 ~HttpChunkedEntityWriter() noexcept(false) {
2371 if (!alreadyDone()) {
2372 auto& inner = getInner();
2373 if (inner.canWriteBodyData()) {
2374 inner.writeBodyData(kj::str("0\r\n\r\n"));
2375 doneWriting();
2376 }
2377 }
2378 }
2379
2380 Promise<void> write(const void* buffer, size_t size) override {
2381 if (size == 0) return kj::READY_NOW; // can't encode zero-size chunk since it indicates EOF.
2382
2383 auto header = kj::str(kj::hex(size), "\r\n");
2384 auto parts = kj::heapArray<ArrayPtr<const byte>>(3);
2385 parts[0] = header.asBytes();
2386 parts[1] = kj::arrayPtr(reinterpret_cast<const byte*>(buffer), size);
2387 parts[2] = kj::StringPtr("\r\n").asBytes();
2388
2389 auto promise = getInner().writeBodyData(parts.asPtr());
2390 return promise.attach(kj::mv(header), kj::mv(parts));
2391 }
2392
2393 Promise<void> write(ArrayPtr<const ArrayPtr<const byte>> pieces) override {
2394 uint64_t size = 0;
2395 for (auto& piece: pieces) size += piece.size();
2396
2397 if (size == 0) return kj::READY_NOW; // can't encode zero-size chunk since it indicates EOF.
2398
2399 auto header = kj::str(kj::hex(size), "\r\n");
2400 auto partsBuilder = kj::heapArrayBuilder<ArrayPtr<const byte>>(pieces.size() + 2);
2401 partsBuilder.add(header.asBytes());
2402 for (auto& piece: pieces) {
2403 partsBuilder.add(piece);
2404 }
2405 partsBuilder.add(kj::StringPtr("\r\n").asBytes());
2406
2407 auto parts = partsBuilder.finish();
2408 auto promise = getInner().writeBodyData(parts.asPtr());
2409 return promise.attach(kj::mv(header), kj::mv(parts));
2410 }
2411
2412 Maybe<Promise<uint64_t>> tryPumpFrom(AsyncInputStream& input, uint64_t amount) override {
2413 KJ_IF_MAYBE(l, input.tryGetLength()) {
2414 // Hey, we know exactly how large the input is, so we can write just one chunk.
2415
2416 uint64_t length = kj::min(amount, *l);
2417 auto& inner = getInner();
2418 inner.writeBodyData(kj::str(kj::hex(length), "\r\n"));
2419 return inner.pumpBodyFrom(input, length)
2420 .then([this,length](uint64_t actual) {
2421 auto& inner = getInner();
2422 if (actual < length) {
2423 inner.abortBody();
2424 KJ_FAIL_REQUIRE(
2425 "value returned by input.tryGetLength() was greater than actual bytes transferred") {
2426 break;
2427 }
2428 }
2429
2430 inner.writeBodyData(kj::str("\r\n"));
2431 return actual;
2432 });
2433 } else {
2434 // Need to use naive read/write loop.
2435 return nullptr;
2436 }
2437 }
2438
2439 Promise<void> whenWriteDisconnected() override {
2440 return getInner().whenWriteDisconnected();
2441 }
2442 };
2443
2444 // =======================================================================================
2445
2446 class WebSocketImpl final: public WebSocket, private WebSocketErrorHandler {
2447 public:
2448 WebSocketImpl(kj::Own<kj::AsyncIoStream> stream,
2449 kj::Maybe<EntropySource&> maskKeyGenerator,
2450 kj::Maybe<CompressionParameters> compressionConfigParam = nullptr,
2451 kj::Maybe<WebSocketErrorHandler&> errorHandler = nullptr,
2452 kj::Array<byte> buffer = kj::heapArray<byte>(4096),
2453 kj::ArrayPtr<byte> leftover = nullptr,
2454 kj::Maybe<kj::Promise<void>> waitBeforeSend = nullptr)
2455 : stream(kj::mv(stream)), maskKeyGenerator(maskKeyGenerator),
2456 compressionConfig(kj::mv(compressionConfigParam)),
2457 errorHandler(errorHandler.orDefault(*this)),
2458 sendingPong(kj::mv(waitBeforeSend)),
2459 recvBuffer(kj::mv(buffer)), recvData(leftover) {
2460 #if KJ_HAS_ZLIB
2461 KJ_IF_MAYBE(config, compressionConfig) {
2462 compressionContext.emplace(ZlibContext::Mode::COMPRESS, *config);
2463 decompressionContext.emplace(ZlibContext::Mode::DECOMPRESS, *config);
2464 }
2465 #else
2466 KJ_REQUIRE(compressionConfig == nullptr,
2467 "WebSocket compression is only supported if KJ is compiled with Zlib.");
2468 #endif // KJ_HAS_ZLIB
2469 }
2470
2471 kj::Promise<void> send(kj::ArrayPtr<const byte> message) override {
2472 return sendImpl(OPCODE_BINARY, message);
2473 }
2474
2475 kj::Promise<void> send(kj::ArrayPtr<const char> message) override {
2476 return sendImpl(OPCODE_TEXT, message.asBytes());
2477 }
2478
2479 kj::Promise<void> close(uint16_t code, kj::StringPtr reason) override {
2480 kj::Array<byte> payload;
2481 if (code == 1005) {
2482 KJ_REQUIRE(reason.size() == 0, "WebSocket close code 1005 cannot have a reason");
2483
2484 // code 1005 -- leave payload empty
2485 } else {
2486 payload = heapArray<byte>(reason.size() + 2);
2487 payload[0] = code >> 8;
2488 payload[1] = code;
2489 memcpy(payload.begin() + 2, reason.begin(), reason.size());
2490 }
2491
2492 auto promise = sendImpl(OPCODE_CLOSE, payload);
2493 return promise.attach(kj::mv(payload));
2494 }
2495
2496 kj::Promise<void> disconnect() override {
2497 KJ_REQUIRE(!currentlySending, "another message send is already in progress");
2498
2499 KJ_IF_MAYBE(p, sendingPong) {
2500 // We recently sent a pong, make sure it's finished before proceeding.
2501 currentlySending = true;
2502 auto promise = p->then([this]() {
2503 currentlySending = false;
2504 return disconnect();
2505 });
2506 sendingPong = nullptr;
2507 return promise;
2508 }
2509
2510 disconnected = true;
2511
2512 stream->shutdownWrite();
2513 return kj::READY_NOW;
2514 }
2515
2516 void abort() override {
2517 queuedPong = nullptr;
2518 sendingPong = nullptr;
2519 disconnected = true;
2520 stream->abortRead();
2521 stream->shutdownWrite();
2522 }
2523
2524 kj::Promise<void> whenAborted() override {
2525 return stream->whenWriteDisconnected();
2526 }
2527
2528 kj::Promise<Message> receive(size_t maxSize) override {
2529 size_t headerSize = Header::headerSize(recvData.begin(), recvData.size());
2530
2531 if (headerSize > recvData.size()) {
2532 if (recvData.begin() != recvBuffer.begin()) {
2533 // Move existing data to front of buffer.
2534 if (recvData.size() > 0) {
2535 memmove(recvBuffer.begin(), recvData.begin(), recvData.size());
2536 }
2537 recvData = recvBuffer.slice(0, recvData.size());
2538 }
2539
2540 return stream->tryRead(recvData.end(), 1, recvBuffer.end() - recvData.end())
2541 .then([this,maxSize](size_t actual) -> kj::Promise<Message> {
2542 receivedBytes += actual;
2543 if (actual == 0) {
2544 if (recvData.size() > 0) {
2545 return KJ_EXCEPTION(DISCONNECTED, "WebSocket EOF in frame header");
2546 } else {
2547 // It's incorrect for the WebSocket to disconnect without sending `Close`.
2548 return KJ_EXCEPTION(DISCONNECTED,
2549 "WebSocket disconnected between frames without sending `Close`.");
2550 }
2551 }
2552
2553 recvData = recvBuffer.slice(0, recvData.size() + actual);
2554 return receive(maxSize);
2555 });
2556 }
2557
2558 auto& recvHeader = *reinterpret_cast<Header*>(recvData.begin());
2559 if (recvHeader.hasRsv2or3()) {
2560 return errorHandler.handleWebSocketProtocolError({
2561 1002, "Received frame had RSV bits 2 or 3 set",
2562 });
2563 }
2564
2565 recvData = recvData.slice(headerSize, recvData.size());
2566
2567 size_t payloadLen = recvHeader.getPayloadLen();
2568 if (payloadLen > maxSize) {
2569 return errorHandler.handleWebSocketProtocolError({
2570 1009, kj::str("Message is too large: ", payloadLen, " > ", maxSize)
2571 });
2572 }
2573
2574 auto opcode = recvHeader.getOpcode();
2575 bool isData = opcode < OPCODE_FIRST_CONTROL;
2576 if (opcode == OPCODE_CONTINUATION) {
2577 if (fragments.empty()) {
2578 return errorHandler.handleWebSocketProtocolError({
2579 1002, "Unexpected continuation frame"
2580 });
2581 }
2582
2583 opcode = fragmentOpcode;
2584 } else if (isData) {
2585 if (!fragments.empty()) {
2586 return errorHandler.handleWebSocketProtocolError({
2587 1002, "Missing continuation frame"
2588 });
2589 }
2590 }
2591
2592 bool isFin = recvHeader.isFin();
2593 bool isCompressed = false;
2594
2595 kj::Array<byte> message; // space to allocate
2596 byte* payloadTarget; // location into which to read payload (size is payloadLen)
2597 kj::Maybe<size_t> originalMaxSize; // maxSize from first `receive()` call
2598 if (isFin) {
2599 size_t amountToAllocate;
2600 if (recvHeader.isCompressed() || fragmentCompressed) {
2601 // Add 4 since we append 0x00 0x00 0xFF 0xFF to the tail of the payload.
2602 // See: https://datatracker.ietf.org/doc/html/rfc7692#section-7.2.2
2603 amountToAllocate = payloadLen + 4;
2604 isCompressed = true;
2605 } else {
2606 // Add space for NUL terminator when allocating text message.
2607 amountToAllocate = payloadLen + (opcode == OPCODE_TEXT && isFin);
2608 }
2609
2610 if (isData && !fragments.empty()) {
2611 // Final frame of a fragmented message. Gather the fragments.
2612 size_t offset = 0;
2613 for (auto& fragment: fragments) offset += fragment.size();
2614 message = kj::heapArray<byte>(offset + amountToAllocate);
2615 originalMaxSize = offset + maxSize; // gives us back the original maximum message size.
2616
2617 offset = 0;
2618 for (auto& fragment: fragments) {
2619 memcpy(message.begin() + offset, fragment.begin(), fragment.size());
2620 offset += fragment.size();
2621 }
2622 payloadTarget = message.begin() + offset;
2623
2624 fragments.clear();
2625 fragmentOpcode = 0;
2626 fragmentCompressed = false;
2627 } else {
2628 // Single-frame message.
2629 message = kj::heapArray<byte>(amountToAllocate);
2630 originalMaxSize = maxSize; // gives us back the original maximum message size.
2631 payloadTarget = message.begin();
2632 }
2633 } else {
2634 // Fragmented message, and this isn't the final fragment.
2635 if (!isData) {
2636 return errorHandler.handleWebSocketProtocolError({
2637 1002, "Received fragmented control frame"
2638 });
2639 }
2640
2641 message = kj::heapArray<byte>(payloadLen);
2642 payloadTarget = message.begin();
2643 if (fragments.empty()) {
2644 // This is the first fragment, so set the opcode.
2645 fragmentOpcode = opcode;
2646 fragmentCompressed = recvHeader.isCompressed();
2647 }
2648 }
2649
2650 Mask mask = recvHeader.getMask();
2651
2652 auto handleMessage =
2653 [this,opcode,payloadTarget,payloadLen,mask,isFin,maxSize,originalMaxSize,
2654 isCompressed,message=kj::mv(message)]() mutable
2655 -> kj::Promise<Message> {
2656 if (!mask.isZero()) {
2657 mask.apply(kj::arrayPtr(payloadTarget, payloadLen));
2658 }
2659
2660 if (!isFin) {
2661 // Add fragment to the list and loop.
2662 auto newMax = maxSize - message.size();
2663 fragments.add(kj::mv(message));
2664 return receive(newMax);
2665 }
2666
2667 // Provide a reasonable error if a compressed frame is received without compression enabled.
2668 if (isCompressed && compressionConfig == nullptr) {
2669 return errorHandler.handleWebSocketProtocolError({
2670 1002, kj::str(
2671 "Received a WebSocket frame whose compression bit was set, but the compression "
2672 "extension was not negotiated for this connection.")
2673 });
2674 }
2675
2676 switch (opcode) {
2677 case OPCODE_CONTINUATION:
2678 // Shouldn't get here; handled above.
2679 KJ_UNREACHABLE;
2680 case OPCODE_TEXT:
2681 #if KJ_HAS_ZLIB
2682 if (isCompressed) {
2683 auto& config = KJ_ASSERT_NONNULL(compressionConfig);
2684 auto& decompressor = KJ_ASSERT_NONNULL(decompressionContext);
2685 KJ_ASSERT(message.size() >= 4);
2686 auto tail = message.slice(message.size() - 4, message.size());
2687 // Note that we added an additional 4 bytes to `message`s capacity to account for these
2688 // extra bytes. See `amountToAllocate` in the if(recvHeader.isCompressed()) block above.
2689 const byte tailBytes[] = {0x00, 0x00, 0xFF, 0xFF};
2690 memcpy(tail.begin(), tailBytes, sizeof(tailBytes));
2691 // We have to append 0x00 0x00 0xFF 0xFF to the message before inflating.
2692 // See: https://datatracker.ietf.org/doc/html/rfc7692#section-7.2.2
2693 if (config.inboundNoContextTakeover) {
2694 // We must reset context on each message.
2695 decompressor.reset();
2696 }
2697 bool addNullTerminator = true;
2698 // We want to add the null terminator when receiving a TEXT message.
2699 auto decompressed = decompressor.processMessage(message, originalMaxSize,
2700 addNullTerminator);
2701 return Message(kj::String(decompressed.releaseAsChars()));
2702 }
2703 #endif // KJ_HAS_ZLIB
2704 message.back() = '\0';
2705 return Message(kj::String(message.releaseAsChars()));
2706 case OPCODE_BINARY:
2707 #if KJ_HAS_ZLIB
2708 if (isCompressed) {
2709 auto& config = KJ_ASSERT_NONNULL(compressionConfig);
2710 auto& decompressor = KJ_ASSERT_NONNULL(decompressionContext);
2711 KJ_ASSERT(message.size() >= 4);
2712 auto tail = message.slice(message.size() - 4, message.size());
2713 // Note that we added an additional 4 bytes to `message`s capacity to account for these
2714 // extra bytes. See `amountToAllocate` in the if(recvHeader.isCompressed()) block above.
2715 const byte tailBytes[] = {0x00, 0x00, 0xFF, 0xFF};
2716 memcpy(tail.begin(), tailBytes, sizeof(tailBytes));
2717 // We have to append 0x00 0x00 0xFF 0xFF to the message before inflating.
2718 // See: https://datatracker.ietf.org/doc/html/rfc7692#section-7.2.2
2719 if (config.inboundNoContextTakeover) {
2720 // We must reset context on each message.
2721 decompressor.reset();
2722 }
2723 auto decompressed = decompressor.processMessage(message, originalMaxSize);
2724 return Message(decompressed.releaseAsBytes());
2725 }
2726 #endif // KJ_HAS_ZLIB
2727 return Message(message.releaseAsBytes());
2728 case OPCODE_CLOSE:
2729 if (message.size() < 2) {
2730 return Message(Close { 1005, nullptr });
2731 } else {
2732 uint16_t status = (static_cast<uint16_t>(message[0]) << 8)
2733 | (static_cast<uint16_t>(message[1]) );
2734 return Message(Close {
2735 status, kj::heapString(message.slice(2, message.size()).asChars())
2736 });
2737 }
2738 case OPCODE_PING:
2739 // Send back a pong.
2740 queuePong(kj::mv(message));
2741 return receive(maxSize);
2742 case OPCODE_PONG:
2743 // Unsolicited pong. Ignore.
2744 return receive(maxSize);
2745 default:
2746 return errorHandler.handleWebSocketProtocolError({
2747 1002, kj::str("Unknown opcode ", opcode)
2748 });
2749 }
2750 };
2751
2752 if (payloadLen <= recvData.size()) {
2753 // All data already received.
2754 memcpy(payloadTarget, recvData.begin(), payloadLen);
2755 recvData = recvData.slice(payloadLen, recvData.size());
2756 return handleMessage();
2757 } else {
2758 // Need to read more data.
2759 memcpy(payloadTarget, recvData.begin(), recvData.size());
2760 size_t remaining = payloadLen - recvData.size();
2761 auto promise = stream->tryRead(payloadTarget + recvData.size(), remaining, remaining)
2762 .then([this, remaining](size_t amount) {
2763 receivedBytes += amount;
2764 if (amount < remaining) {
2765 kj::throwRecoverableException(KJ_EXCEPTION(DISCONNECTED, "WebSocket EOF in message"));
2766 }
2767 });
2768 recvData = nullptr;
2769 return promise.then(kj::mv(handleMessage));
2770 }
2771 }
2772
2773 kj::Maybe<kj::Promise<void>> tryPumpFrom(WebSocket& other) override {
2774 KJ_IF_MAYBE(optOther, kj::dynamicDowncastIfAvailable<WebSocketImpl>(other)) {
2775 // Both WebSockets are raw WebSockets, so we can pump the streams directly rather than read
2776 // whole messages.
2777
2778 if ((maskKeyGenerator == nullptr) == (optOther->maskKeyGenerator == nullptr)) {
2779 // Oops, it appears that we either believe we are the client side of both sockets, or we
2780 // are the server side of both sockets. Since clients must "mask" their outgoing frames but
2781 // servers must *not* do so, we can't direct-pump. Sad.
2782 return nullptr;
2783 }
2784
2785 KJ_IF_MAYBE(config, compressionConfig) {
2786 KJ_IF_MAYBE(otherConfig, optOther->compressionConfig) {
2787 if (config->outboundMaxWindowBits != otherConfig->inboundMaxWindowBits ||
2788 config->inboundMaxWindowBits != otherConfig->outboundMaxWindowBits ||
2789 config->inboundNoContextTakeover!= otherConfig->outboundNoContextTakeover ||
2790 config->outboundNoContextTakeover!= otherConfig->inboundNoContextTakeover) {
2791 // Compression configurations differ.
2792 return nullptr;
2793 }
2794 } else {
2795 // Only one websocket uses compression.
2796 return nullptr;
2797 }
2798 } else {
2799 if (optOther->compressionConfig != nullptr) {
2800 // Only one websocket uses compression.
2801 return nullptr;
2802 }
2803 }
2804 // Both websockets use compatible compression configurations so we can pump directly.
2805
2806 // Check same error conditions as with sendImpl().
2807 KJ_REQUIRE(!disconnected, "WebSocket can't send after disconnect()");
2808 KJ_REQUIRE(!currentlySending, "another message send is already in progress");
2809 currentlySending = true;
2810
2811 // If the application chooses to pump messages out, but receives incoming messages normally
2812 // with `receive()`, then we will receive pings and attempt to send pongs. But we can't
2813 // safely insert a pong in the middle of a pumped stream. We kind of don't have a choice
2814 // except to drop them on the floor, which is what will happen if we set `hasSentClose` true.
2815 // Hopefully most apps that set up a pump do so in both directions at once, and so pings will
2816 // flow through and pongs will flow back.
2817 hasSentClose = true;
2818
2819 return optOther->optimizedPumpTo(*this);
2820 }
2821
2822 return nullptr;
2823 }
2824
2825 uint64_t sentByteCount() override { return sentBytes; }
2826
2827 uint64_t receivedByteCount() override { return receivedBytes; }
2828
2829 kj::Maybe<kj::String> getPreferredExtensions(ExtensionsContext ctx) override {
2830 if (maskKeyGenerator == nullptr) {
2831 // `this` is the server side of a websocket.
2832 if (ctx == ExtensionsContext::REQUEST) {
2833 // The other WebSocket is (going to be) the client side of a WebSocket, i.e. this is a
2834 // proxying pass-through scenario. Optimization is possible. Confusingly, we have to use
2835 // generateExtensionResponse() (even though we're generating headers to be passed in a
2836 // request) because this is the function that correctly maps our config's inbound/outbound
2837 // to client/server.
2838 KJ_IF_MAYBE(c, compressionConfig) {
2839 return _::generateExtensionResponse(*c);
2840 } else {
2841 return kj::String(nullptr); // recommend no compression
2842 }
2843 } else {
2844 // We're apparently arranging to pump from the server side of one WebSocket to the server
2845 // side of another; i.e., we are a server, we have two clients, and we're trying to pump
2846 // between them. We cannot optimize this case, because the masking requirements are
2847 // different for client->server vs. server->client messages. Since we have to parse out
2848 // the messages anyway there's no point in trying to match extensions, so return null.
2849 return nullptr;
2850 }
2851 } else {
2852 // `this` is the client side of a websocket.
2853 if (ctx == ExtensionsContext::RESPONSE) {
2854 // The other WebSocket is (going to be) the server side of a WebSocket, i.e. this is a
2855 // proxying pass-through scenario. Optimization is possible. Confusingly, we have to use
2856 // generateExtensionRequest() (even though we're generating headers to be passed in a
2857 // response) because this is the function that correctly maps our config's inbound/outbound
2858 // to server/client.
2859 KJ_IF_MAYBE(c, compressionConfig) {
2860 CompressionParameters arr[1]{*c};
2861 return _::generateExtensionRequest(arr);
2862 } else {
2863 return kj::String(nullptr); // recommend no compression
2864 }
2865 } else {
2866 // We're apparently arranging to pump from the client side of one WebSocket to the client
2867 // side of another; i.e., we are a client, we are connected to two servers, and we're
2868 // trying to pump between them. We cannot optimize this case, because the masking
2869 // requirements are different for client->server vs. server->client messages. Since we have
2870 // to parse out the messages anyway there's no point in trying to match extensions, so
2871 // return null.
2872 return nullptr;
2873 }
2874 }
2875 }
2876
2877 private:
2878 class Mask {
2879 public:
2880 Mask(): maskBytes { 0, 0, 0, 0 } {}
2881 Mask(const byte* ptr) { memcpy(maskBytes, ptr, 4); }
2882
2883 Mask(kj::Maybe<EntropySource&> generator) {
2884 KJ_IF_MAYBE(g, generator) {
2885 g->generate(maskBytes);
2886 } else {
2887 memset(maskBytes, 0, 4);
2888 }
2889 }
2890
2891 void apply(kj::ArrayPtr<byte> bytes) const {
2892 apply(bytes.begin(), bytes.size());
2893 }
2894
2895 void copyTo(byte* output) const {
2896 memcpy(output, maskBytes, 4);
2897 }
2898
2899 bool isZero() const {
2900 return (maskBytes[0] | maskBytes[1] | maskBytes[2] | maskBytes[3]) == 0;
2901 }
2902
2903 private:
2904 byte maskBytes[4];
2905
2906 void apply(byte* __restrict__ bytes, size_t size) const {
2907 for (size_t i = 0; i < size; i++) {
2908 bytes[i] ^= maskBytes[i % 4];
2909 }
2910 }
2911 };
2912
2913 class Header {
2914 public:
2915 kj::ArrayPtr<const byte> compose(bool fin, bool compressed, byte opcode, uint64_t payloadLen,
2916 Mask mask) {
2917 bytes[0] = (fin ? FIN_MASK : 0) | (compressed ? RSV1_MASK : 0) | opcode;
2918 // Note that we can only set the compressed bit on DATA frames.
2919 bool hasMask = !mask.isZero();
2920
2921 size_t fill;
2922
2923 if (payloadLen < 126) {
2924 bytes[1] = (hasMask ? USE_MASK_MASK : 0) | payloadLen;
2925 if (hasMask) {
2926 mask.copyTo(bytes + 2);
2927 fill = 6;
2928 } else {
2929 fill = 2;
2930 }
2931 } else if (payloadLen < 65536) {
2932 bytes[1] = (hasMask ? USE_MASK_MASK : 0) | 126;
2933 bytes[2] = static_cast<byte>(payloadLen >> 8);
2934 bytes[3] = static_cast<byte>(payloadLen );
2935 if (hasMask) {
2936 mask.copyTo(bytes + 4);
2937 fill = 8;
2938 } else {
2939 fill = 4;
2940 }
2941 } else {
2942 bytes[1] = (hasMask ? USE_MASK_MASK : 0) | 127;
2943 bytes[2] = static_cast<byte>(payloadLen >> 56);
2944 bytes[3] = static_cast<byte>(payloadLen >> 48);
2945 bytes[4] = static_cast<byte>(payloadLen >> 40);
2946 bytes[5] = static_cast<byte>(payloadLen >> 42);
2947 bytes[6] = static_cast<byte>(payloadLen >> 24);
2948 bytes[7] = static_cast<byte>(payloadLen >> 16);
2949 bytes[8] = static_cast<byte>(payloadLen >> 8);
2950 bytes[9] = static_cast<byte>(payloadLen );
2951 if (hasMask) {
2952 mask.copyTo(bytes + 10);
2953 fill = 14;
2954 } else {
2955 fill = 10;
2956 }
2957 }
2958
2959 return arrayPtr(bytes, fill);
2960 }
2961
2962 bool isFin() const {
2963 return bytes[0] & FIN_MASK;
2964 }
2965
2966 bool isCompressed() const {
2967 return bytes[0] & RSV1_MASK;
2968 }
2969
2970 bool hasRsv2or3() const {
2971 return bytes[0] & RSV2_3_MASK;
2972 }
2973
2974 byte getOpcode() const {
2975 return bytes[0] & OPCODE_MASK;
2976 }
2977
2978 uint64_t getPayloadLen() const {
2979 byte payloadLen = bytes[1] & PAYLOAD_LEN_MASK;
2980 if (payloadLen == 127) {
2981 return (static_cast<uint64_t>(bytes[2]) << 56)
2982 | (static_cast<uint64_t>(bytes[3]) << 48)
2983 | (static_cast<uint64_t>(bytes[4]) << 40)
2984 | (static_cast<uint64_t>(bytes[5]) << 32)
2985 | (static_cast<uint64_t>(bytes[6]) << 24)
2986 | (static_cast<uint64_t>(bytes[7]) << 16)
2987 | (static_cast<uint64_t>(bytes[8]) << 8)
2988 | (static_cast<uint64_t>(bytes[9]) );
2989 } else if (payloadLen == 126) {
2990 return (static_cast<uint64_t>(bytes[2]) << 8)
2991 | (static_cast<uint64_t>(bytes[3]) );
2992 } else {
2993 return payloadLen;
2994 }
2995 }
2996
2997 Mask getMask() const {
2998 if (bytes[1] & USE_MASK_MASK) {
2999 byte payloadLen = bytes[1] & PAYLOAD_LEN_MASK;
3000 if (payloadLen == 127) {
3001 return Mask(bytes + 10);
3002 } else if (payloadLen == 126) {
3003 return Mask(bytes + 4);
3004 } else {
3005 return Mask(bytes + 2);
3006 }
3007 } else {
3008 return Mask();
3009 }
3010 }
3011
3012 static size_t headerSize(byte const* bytes, size_t sizeSoFar) {
3013 if (sizeSoFar < 2) return 2;
3014
3015 size_t required = 2;
3016
3017 if (bytes[1] & USE_MASK_MASK) {
3018 required += 4;
3019 }
3020
3021 byte payloadLen = bytes[1] & PAYLOAD_LEN_MASK;
3022 if (payloadLen == 127) {
3023 required += 8;
3024 } else if (payloadLen == 126) {
3025 required += 2;
3026 }
3027
3028 return required;
3029 }
3030
3031 private:
3032 byte bytes[14];
3033
3034 static constexpr byte FIN_MASK = 0x80;
3035 static constexpr byte RSV2_3_MASK = 0x30;
3036 static constexpr byte RSV1_MASK = 0x40;
3037 static constexpr byte OPCODE_MASK = 0x0f;
3038
3039 static constexpr byte USE_MASK_MASK = 0x80;
3040 static constexpr byte PAYLOAD_LEN_MASK = 0x7f;
3041 };
3042
3043 #if KJ_HAS_ZLIB
3044 class ZlibContext {
3045 // `ZlibContext` is the WebSocket's interface to Zlib's compression/decompression functions.
3046 // Depending on the `mode`, `ZlibContext` will act as a compressor or a decompressor.
3047 public:
3048 enum class Mode {
3049 COMPRESS,
3050 DECOMPRESS,
3051 };
3052
3053 struct Result {
3054 int processResult = 0;
3055 kj::Array<const byte> buffer;
3056 size_t size = 0; // Number of bytes used; size <= buffer.size().
3057 };
3058
3059 ZlibContext(Mode mode, const CompressionParameters& config) : mode(mode) {
3060 switch (mode) {
3061 case Mode::COMPRESS: {
3062 int windowBits = -config.outboundMaxWindowBits.orDefault(15);
3063 // We use negative values because we want to use raw deflate.
3064 if(windowBits == -8) {
3065 // Zlib cannot accept `windowBits` of 8 for the deflater. However, due to an
3066 // implementation quirk, `windowBits` of 8 and 9 would both use 250 bytes.
3067 // Therefore, a decompressor using `windowBits` of 8 could safely inflate a message
3068 // that a zlib client compressed using `windowBits` = 9.
3069 // https://bugs.chromium.org/p/chromium/issues/detail?id=691074
3070 windowBits = -9;
3071 }
3072 int result = deflateInit2(
3073 &ctx,
3074 Z_DEFAULT_COMPRESSION,
3075 Z_DEFLATED,
3076 windowBits,
3077 8, // memLevel = 8 is the default
3078 Z_DEFAULT_STRATEGY);
3079 KJ_REQUIRE(result == Z_OK, "Failed to initialize compression context (deflate).");
3080 break;
3081 }
3082 case Mode::DECOMPRESS: {
3083 int windowBits = -config.inboundMaxWindowBits.orDefault(15);
3084 // We use negative values because we want to use raw inflate.
3085 int result = inflateInit2(&ctx, windowBits);
3086 KJ_REQUIRE(result == Z_OK, "Failed to initialize decompression context (inflate).");
3087 break;
3088 }
3089 }
3090 }
3091
3092 ~ZlibContext() noexcept(false) {
3093 switch (mode) {
3094 case Mode::COMPRESS:
3095 deflateEnd(&ctx);
3096 break;
3097 case Mode::DECOMPRESS:
3098 inflateEnd(&ctx);
3099 break;
3100 }
3101 }
3102
3103 KJ_DISALLOW_COPY_AND_MOVE(ZlibContext);
3104
3105 kj::Array<kj::byte> processMessage(kj::ArrayPtr<const byte> message,
3106 kj::Maybe<size_t> maxSize = nullptr,
3107 bool addNullTerminator = false) {
3108 // If `this` is the compressor, calling `processMessage()` will compress the `message`.
3109 // Likewise, if `this` is the decompressor, `processMessage()` will decompress the `message`.
3110 //
3111 // `maxSize` is only passed in when decompressing, since we want to ensure the decompressed
3112 // message is smaller than the `maxSize` passed to `receive()`.
3113 //
3114 // If (de)compression is successful, the result is returned as a Vector, otherwise,
3115 // an Exception is thrown.
3116
3117 ctx.next_in = const_cast<byte*>(reinterpret_cast<const byte*>(message.begin()));
3118 ctx.avail_in = message.size();
3119
3120 kj::Vector<Result> parts(processLoop(maxSize));
3121
3122 size_t amountToAllocate = 0;
3123 for (const auto& part : parts) {
3124 amountToAllocate += part.size;
3125 }
3126
3127 if (addNullTerminator) {
3128 // Add space for the null-terminator.
3129 amountToAllocate += 1;
3130 }
3131
3132 kj::Array<kj::byte> processedMessage = kj::heapArray<kj::byte>(amountToAllocate);
3133 size_t currentIndex = 0; // Current index into processedMessage.
3134 for (const auto& part : parts) {
3135 memcpy(&processedMessage[currentIndex], part.buffer.begin(), part.size);
3136 // We need to use `part.size` to determine the number of useful bytes, since data after
3137 // `part.size` is unused (and probably junk).
3138 currentIndex += part.size;
3139 }
3140
3141 if (addNullTerminator) {
3142 processedMessage[currentIndex++] = '\0';
3143 }
3144
3145 KJ_ASSERT(currentIndex == processedMessage.size());
3146
3147 return kj::mv(processedMessage);
3148 }
3149
3150 void reset() {
3151 // Resets the (de)compression context. This should only be called when the (de)compressor uses
3152 // client/server_no_context_takeover.
3153 switch (mode) {
3154 case Mode::COMPRESS: {
3155 KJ_ASSERT(deflateReset(&ctx) == Z_OK, "deflateReset() failed.");
3156 break;
3157 }
3158 case Mode::DECOMPRESS: {
3159 KJ_ASSERT(inflateReset(&ctx) == Z_OK, "inflateReset failed.");
3160 break;
3161 }
3162 }
3163
3164 }
3165
3166 private:
3167 Result pumpOnce() {
3168 // Prepares Zlib's internal state for a call to deflate/inflate, then calls the relevant
3169 // function to process the input buffer. It is assumed that the caller has already set up
3170 // Zlib's input buffer.
3171 //
3172 // Since calls to deflate/inflate will process data until the input is empty, or until the
3173 // output is full, multiple calls to `pumpOnce()` may be required to process the entire
3174 // message. We're done processing once either `result` is `Z_STREAM_END`, or we get
3175 // `Z_BUF_ERROR` and did not write any more output.
3176 size_t bufSize = 4096;
3177 Array<kj::byte> buffer = kj::heapArray<kj::byte>(bufSize);
3178 ctx.next_out = buffer.begin();
3179 ctx.avail_out = bufSize;
3180
3181 int result = Z_OK;
3182
3183 switch (mode) {
3184 case Mode::COMPRESS:
3185 result = deflate(&ctx, Z_SYNC_FLUSH);
3186 KJ_REQUIRE(result == Z_OK || result == Z_BUF_ERROR || result == Z_STREAM_END,
3187 "Compression failed", result);
3188 break;
3189 case Mode::DECOMPRESS:
3190 result = inflate(&ctx, Z_SYNC_FLUSH);
3191 KJ_REQUIRE(result == Z_OK || result == Z_BUF_ERROR || result == Z_STREAM_END,
3192 "Decompression failed", result, " with reason", ctx.msg);
3193 break;
3194 }
3195
3196 return Result {
3197 result,
3198 kj::mv(buffer),
3199 bufSize - ctx.avail_out,
3200 };
3201 }
3202
3203 kj::Vector<Result> processLoop(kj::Maybe<size_t> maxSize) {
3204 // Since Zlib buffers the writes, we want to continue processing until there's nothing left.
3205 kj::Vector<Result> output;
3206 size_t totalBytesProcessed = 0;
3207 for (;;) {
3208 Result result = pumpOnce();
3209
3210 auto status = result.processResult;
3211 auto bytesProcessed = result.size;
3212 if (bytesProcessed > 0) {
3213 output.add(kj::mv(result));
3214 totalBytesProcessed += bytesProcessed;
3215 KJ_IF_MAYBE(m, maxSize) {
3216 // This is only non-null for `receive` calls, so we must be decompressing. We don't want
3217 // the decompressed message to OOM us, so let's make sure it's not too big.
3218 KJ_REQUIRE(totalBytesProcessed < *m,
3219 "Decompressed WebSocket message is too large");
3220 }
3221 }
3222
3223 if ((ctx.avail_in == 0 && ctx.avail_out != 0) || status == Z_STREAM_END) {
3224 // If we're out of input to consume, and we have space in the output buffer, then we must
3225 // have flushed the remaining message, so we're done pumping. Alternatively, if we found a
3226 // BFINAL deflate block, then we know the stream is completely finished.
3227 if (status == Z_STREAM_END) {
3228 reset();
3229 }
3230 return kj::mv(output);
3231 }
3232 }
3233 }
3234
3235 Mode mode;
3236 z_stream ctx = {};
3237 };
3238 #endif // KJ_HAS_ZLIB
3239
3240 static constexpr byte OPCODE_CONTINUATION = 0;
3241 static constexpr byte OPCODE_TEXT = 1;
3242 static constexpr byte OPCODE_BINARY = 2;
3243 static constexpr byte OPCODE_CLOSE = 8;
3244 static constexpr byte OPCODE_PING = 9;
3245 static constexpr byte OPCODE_PONG = 10;
3246
3247 static constexpr byte OPCODE_FIRST_CONTROL = 8;
3248
3249 // ---------------------------------------------------------------------------
3250
3251 kj::Own<kj::AsyncIoStream> stream;
3252 kj::Maybe<EntropySource&> maskKeyGenerator;
3253 kj::Maybe<CompressionParameters> compressionConfig;
3254 WebSocketErrorHandler& errorHandler;
3255 #if KJ_HAS_ZLIB
3256 kj::Maybe<ZlibContext> compressionContext;
3257 kj::Maybe<ZlibContext> decompressionContext;
3258 #endif // KJ_HAS_ZLIB
3259
3260 bool hasSentClose = false;
3261 bool disconnected = false;
3262 bool currentlySending = false;
3263 Header sendHeader;
3264 kj::ArrayPtr<const byte> sendParts[2];
3265
3266 kj::Maybe<kj::Array<byte>> queuedPong;
3267 // If a Ping is received while currentlySending is true, then queuedPong is set to the body of
3268 // a pong message that should be sent once the current send is complete.
3269
3270 kj::Maybe<kj::Promise<void>> sendingPong;
3271 // If a Pong is being sent asynchronously in response to a Ping, this is a promise for the
3272 // completion of that send.
3273 //
3274 // Additionally, this member is used if we need to block our first send on WebSocket startup,
3275 // e.g. because we need to wait for HTTP handshake writes to flush before we can start sending
3276 // WebSocket data. `sendingPong` was overloaded for this use case because the logic is the same.
3277 // Perhaps it should be renamed to `blockSend` or `writeQueue`.
3278
3279 uint fragmentOpcode = 0;
3280 bool fragmentCompressed = false;
3281 // For fragmented messages, was the first frame compressed?
3282 // Note that subsequent frames of a compressed message will not set the RSV1 bit.
3283 kj::Vector<kj::Array<byte>> fragments;
3284 // If `fragments` is non-empty, we've already received some fragments of a message.
3285 // `fragmentOpcode` is the original opcode.
3286
3287 kj::Array<byte> recvBuffer;
3288 kj::ArrayPtr<byte> recvData;
3289
3290 uint64_t sentBytes = 0;
3291 uint64_t receivedBytes = 0;
3292
3293 kj::Promise<void> sendImpl(byte opcode, kj::ArrayPtr<const byte> message) {
3294 KJ_REQUIRE(!disconnected, "WebSocket can't send after disconnect()");
3295 KJ_REQUIRE(!currentlySending, "another message send is already in progress");
3296
3297 currentlySending = true;
3298
3299 KJ_IF_MAYBE(p, sendingPong) {
3300 // We recently sent a pong, make sure it's finished before proceeding.
3301 auto promise = p->then([this, opcode, message]() {
3302 currentlySending = false;
3303 return sendImpl(opcode, message);
3304 });
3305 sendingPong = nullptr;
3306 return promise;
3307 }
3308
3309 // We don't stop the application from sending further messages after close() -- this is the
3310 // application's error to make. But, we do want to make sure we don't send any PONGs after a
3311 // close, since that would be our error. So we stack whether we closed for that reason.
3312 hasSentClose = hasSentClose || opcode == OPCODE_CLOSE;
3313
3314 Mask mask(maskKeyGenerator);
3315
3316 bool useCompression = false;
3317 kj::Maybe<kj::Array<byte>> compressedMessage;
3318 if (opcode == OPCODE_BINARY || opcode == OPCODE_TEXT) {
3319 // We can only compress data frames.
3320 #if KJ_HAS_ZLIB
3321 KJ_IF_MAYBE(config, compressionConfig) {
3322 useCompression = true;
3323 // Compress `message` according to `compressionConfig`s outbound parameters.
3324 auto& compressor = KJ_ASSERT_NONNULL(compressionContext);
3325 if (config->outboundNoContextTakeover) {
3326 // We must reset context on each message.
3327 compressor.reset();
3328 }
3329 auto& innerMessage = compressedMessage.emplace(compressor.processMessage(message));
3330 if (message.size() > 0) {
3331 KJ_ASSERT(innerMessage.asPtr().endsWith({0x00, 0x00, 0xFF, 0xFF}));
3332 message = innerMessage.slice(0, innerMessage.size() - 4);
3333 // Strip 0x00 0x00 0xFF 0xFF off the tail.
3334 // See: https://datatracker.ietf.org/doc/html/rfc7692#section-7.2.1
3335 } else {
3336 // RFC 7692 (7.2.3.6) specifies that an empty uncompressed DEFLATE block (0x00) should be
3337 // built if the compression library doesn't generate data when the input is empty.
3338 message = compressedMessage.emplace(kj::heapArray<byte>({0x00}));
3339 }
3340 }
3341 #endif // KJ_HAS_ZLIB
3342 }
3343
3344 kj::Array<byte> ownMessage;
3345 if (!mask.isZero()) {
3346 // Sadness, we have to make a copy to apply the mask.
3347 ownMessage = kj::heapArray(message);
3348 mask.apply(ownMessage);
3349 message = ownMessage;
3350 }
3351
3352 sendParts[0] = sendHeader.compose(true, useCompression, opcode, message.size(), mask);
3353 sendParts[1] = message;
3354 KJ_ASSERT(!sendHeader.hasRsv2or3(), "RSV bits 2 and 3 must be 0, as we do not currently "
3355 "support an extension that would set these bits");
3356
3357 auto promise = stream->write(sendParts).attach(kj::mv(compressedMessage));
3358 if (!mask.isZero()) {
3359 promise = promise.attach(kj::mv(ownMessage));
3360 }
3361 return promise.then([this, size = sendParts[0].size() + sendParts[1].size()]() {
3362 currentlySending = false;
3363
3364 // Send queued pong if needed.
3365 KJ_IF_MAYBE(q, queuedPong) {
3366 kj::Array<byte> payload = kj::mv(*q);
3367 queuedPong = nullptr;
3368 queuePong(kj::mv(payload));
3369 }
3370 sentBytes += size;
3371 });
3372 }
3373
3374 void queuePong(kj::Array<byte> payload) {
3375 if (currentlySending) {
3376 // There is a message-send in progress, so we cannot write to the stream now.
3377 //
3378 // Note: According to spec, if the server receives a second ping before responding to the
3379 // previous one, it can opt to respond only to the last ping. So we don't have to check if
3380 // queuedPong is already non-null.
3381 queuedPong = kj::mv(payload);
3382 } else KJ_IF_MAYBE(promise, sendingPong) {
3383 // We're still sending a previous pong. Wait for it to finish before sending ours.
3384 sendingPong = promise->then([this,payload=kj::mv(payload)]() mutable {
3385 return sendPong(kj::mv(payload));
3386 });
3387 } else {
3388 // We're not sending any pong currently.
3389 sendingPong = sendPong(kj::mv(payload));
3390 }
3391 }
3392
3393 kj::Promise<void> sendPong(kj::Array<byte> payload) {
3394 if (hasSentClose || disconnected) {
3395 return kj::READY_NOW;
3396 }
3397
3398 sendParts[0] = sendHeader.compose(true, false, OPCODE_PONG,
3399 payload.size(), Mask(maskKeyGenerator));
3400 sendParts[1] = payload;
3401 return stream->write(sendParts).attach(kj::mv(payload));
3402 }
3403
3404 kj::Promise<void> optimizedPumpTo(WebSocketImpl& other) {
3405 KJ_IF_MAYBE(p, other.sendingPong) {
3406 // We recently sent a pong, make sure it's finished before proceeding.
3407 auto promise = p->then([this, &other]() {
3408 return optimizedPumpTo(other);
3409 });
3410 other.sendingPong = nullptr;
3411 return promise;
3412 }
3413
3414 if (recvData.size() > 0) {
3415 // We have some data buffered. Write it first.
3416 return other.stream->write(recvData.begin(), recvData.size())
3417 .then([this, &other, size = recvData.size()]() {
3418 recvData = nullptr;
3419 other.sentBytes += size;
3420 return optimizedPumpTo(other);
3421 });
3422 }
3423
3424 auto cancelPromise = other.stream->whenWriteDisconnected()
3425 .then([this]() -> kj::Promise<void> {
3426 this->abort();
3427 return KJ_EXCEPTION(DISCONNECTED,
3428 "destination of WebSocket pump disconnected prematurely");
3429 });
3430
3431 // There's no buffered incoming data, so start pumping stream now.
3432 return stream->pumpTo(*other.stream).then([this, &other](size_t s) -> kj::Promise<void> {
3433 // WebSocket pumps are expected to include end-of-stream.
3434 other.disconnected = true;
3435 other.stream->shutdownWrite();
3436 receivedBytes += s;
3437 other.sentBytes += s;
3438 return kj::READY_NOW;
3439 }, [&other](kj::Exception&& e) -> kj::Promise<void> {
3440 // We don't know if it was a read or a write that threw. If it was a read that threw, we need
3441 // to send a disconnect on the destination. If it was the destination that threw, it
3442 // shouldn't hurt to disconnect() it again, but we'll catch and squelch any exceptions.
3443 other.disconnected = true;
3444 kj::runCatchingExceptions([&other]() { other.stream->shutdownWrite(); });
3445 return kj::mv(e);
3446 }).exclusiveJoin(kj::mv(cancelPromise));
3447 }
3448 };
3449
3450 kj::Own<WebSocket> upgradeToWebSocket(
3451 kj::Own<kj::AsyncIoStream> stream, HttpInputStreamImpl& httpInput, HttpOutputStream& httpOutput,
3452 kj::Maybe<EntropySource&> maskKeyGenerator,
3453 kj::Maybe<CompressionParameters> compressionConfig = nullptr,
3454 kj::Maybe<WebSocketErrorHandler&> errorHandler = nullptr) {
3455 // Create a WebSocket upgraded from an HTTP stream.
3456 auto releasedBuffer = httpInput.releaseBuffer();
3457 return kj::heap<WebSocketImpl>(kj::mv(stream), maskKeyGenerator,
3458 kj::mv(compressionConfig), errorHandler,
3459 kj::mv(releasedBuffer.buffer),
3460 releasedBuffer.leftover, httpOutput.flush());
3461 }
3462
3463 } // namespace
3464
3465 kj::Own<WebSocket> newWebSocket(kj::Own<kj::AsyncIoStream> stream,
3466 kj::Maybe<EntropySource&> maskKeyGenerator,
3467 kj::Maybe<CompressionParameters> compressionConfig,
3468 kj::Maybe<WebSocketErrorHandler&> errorHandler) {
3469 return kj::heap<WebSocketImpl>(kj::mv(stream), maskKeyGenerator, kj::mv(compressionConfig), errorHandler);
3470 }
3471
3472 static kj::Promise<void> pumpWebSocketLoop(WebSocket& from, WebSocket& to) {
3473 return from.receive().then([&from,&to](WebSocket::Message&& message) {
3474 KJ_SWITCH_ONEOF(message) {
3475 KJ_CASE_ONEOF(text, kj::String) {
3476 return to.send(text)
3477 .attach(kj::mv(text))
3478 .then([&from,&to]() { return pumpWebSocketLoop(from, to); });
3479 }
3480 KJ_CASE_ONEOF(data, kj::Array<byte>) {
3481 return to.send(data)
3482 .attach(kj::mv(data))
3483 .then([&from,&to]() { return pumpWebSocketLoop(from, to); });
3484 }
3485 KJ_CASE_ONEOF(close, WebSocket::Close) {
3486 // Once a close has passed through, the pump is complete.
3487 return to.close(close.code, close.reason)
3488 .attach(kj::mv(close));
3489 }
3490 }
3491 KJ_UNREACHABLE;
3492 }, [&to](kj::Exception&& e) {
3493 if (e.getType() == kj::Exception::Type::DISCONNECTED) {
3494 return to.disconnect();
3495 } else {
3496 return to.close(1002, e.getDescription());
3497 }
3498 });
3499 }
3500
3501 kj::Promise<void> WebSocket::pumpTo(WebSocket& other) {
3502 KJ_IF_MAYBE(p, other.tryPumpFrom(*this)) {
3503 // Yay, optimized pump!
3504 return kj::mv(*p);
3505 } else {
3506 // Fall back to default implementation.
3507 return kj::evalNow([&]() {
3508 auto cancelPromise = other.whenAborted().then([this]() -> kj::Promise<void> {
3509 this->abort();
3510 return KJ_EXCEPTION(DISCONNECTED,
3511 "destination of WebSocket pump disconnected prematurely");
3512 });
3513 return pumpWebSocketLoop(*this, other).exclusiveJoin(kj::mv(cancelPromise));
3514 });
3515 }
3516 }
3517
3518 kj::Maybe<kj::Promise<void>> WebSocket::tryPumpFrom(WebSocket& other) {
3519 return nullptr;
3520 }
3521
3522 namespace {
3523
3524 class WebSocketPipeImpl final: public WebSocket, public kj::Refcounted {
3525 // Represents one direction of a WebSocket pipe.
3526 //
3527 // This class behaves as a "loopback" WebSocket: a message sent using send() is received using
3528 // receive(), on the same object. This is *not* how WebSocket implementations usually behave.
3529 // But, this object is actually used to implement only one direction of a bidirectional pipe. At
3530 // another layer above this, the pipe is actually composed of two WebSocketPipeEnd instances,
3531 // which layer on top of two WebSocketPipeImpl instances representing the two directions. So,
3532 // send() calls on a WebSocketPipeImpl instance always come from one of the two WebSocketPipeEnds
3533 // while receive() calls come from the other end.
3534
3535 public:
3536 ~WebSocketPipeImpl() noexcept(false) {
3537 KJ_REQUIRE(state == nullptr || ownState.get() != nullptr,
3538 "destroying WebSocketPipe with operation still in-progress; probably going to segfault") {
3539 // Don't std::terminate().
3540 break;
3541 }
3542 }
3543
3544 void abort() override {
3545 KJ_IF_MAYBE(s, state) {
3546 s->abort();
3547 } else {
3548 ownState = heap<Aborted>();
3549 state = *ownState;
3550
3551 aborted = true;
3552 KJ_IF_MAYBE(f, abortedFulfiller) {
3553 f->get()->fulfill();
3554 abortedFulfiller = nullptr;
3555 }
3556 }
3557 }
3558
3559 kj::Promise<void> send(kj::ArrayPtr<const byte> message) override {
3560 KJ_IF_MAYBE(s, state) {
3561 return s->send(message).then([&, size = message.size()]() { transferredBytes += size; });
3562 } else {
3563 return newAdaptedPromise<void, BlockedSend>(*this, MessagePtr(message))
3564 .then([&, size = message.size()]() { transferredBytes += size; });
3565 }
3566 }
3567 kj::Promise<void> send(kj::ArrayPtr<const char> message) override {
3568 KJ_IF_MAYBE(s, state) {
3569 return s->send(message).then([&, size = message.size()]() { transferredBytes += size; });
3570 } else {
3571 return newAdaptedPromise<void, BlockedSend>(*this, MessagePtr(message))
3572 .then([&, size = message.size()]() { transferredBytes += size; });
3573 }
3574 }
3575 kj::Promise<void> close(uint16_t code, kj::StringPtr reason) override {
3576 KJ_IF_MAYBE(s, state) {
3577 return s->close(code, reason)
3578 .then([&, size = reason.size()]() { transferredBytes += (2 +size); });
3579 } else {
3580 return newAdaptedPromise<void, BlockedSend>(*this, MessagePtr(ClosePtr { code, reason }))
3581 .then([&, size = reason.size()]() { transferredBytes += (2 +size); });
3582 }
3583 }
3584 kj::Promise<void> disconnect() override {
3585 KJ_IF_MAYBE(s, state) {
3586 return s->disconnect();
3587 } else {
3588 ownState = heap<Disconnected>();
3589 state = *ownState;
3590 return kj::READY_NOW;
3591 }
3592 }
3593 kj::Promise<void> whenAborted() override {
3594 if (aborted) {
3595 return kj::READY_NOW;
3596 } else KJ_IF_MAYBE(p, abortedPromise) {
3597 return p->addBranch();
3598 } else {
3599 auto paf = newPromiseAndFulfiller<void>();
3600 abortedFulfiller = kj::mv(paf.fulfiller);
3601 auto fork = paf.promise.fork();
3602 auto result = fork.addBranch();
3603 abortedPromise = kj::mv(fork);
3604 return result;
3605 }
3606 }
3607 kj::Maybe<kj::Promise<void>> tryPumpFrom(WebSocket& other) override {
3608 KJ_IF_MAYBE(s, state) {
3609 return s->tryPumpFrom(other);
3610 } else {
3611 return newAdaptedPromise<void, BlockedPumpFrom>(*this, other);
3612 }
3613 }
3614
3615 kj::Promise<Message> receive(size_t maxSize) override {
3616 KJ_IF_MAYBE(s, state) {
3617 return s->receive(maxSize);
3618 } else {
3619 return newAdaptedPromise<Message, BlockedReceive>(*this, maxSize);
3620 }
3621 }
3622 kj::Promise<void> pumpTo(WebSocket& other) override {
3623 auto onAbort = other.whenAborted()
3624 .then([]() -> kj::Promise<void> {
3625 return KJ_EXCEPTION(DISCONNECTED, "WebSocket was aborted");
3626 });
3627
3628 KJ_IF_MAYBE(s, state) {
3629 auto before = other.receivedByteCount();
3630 return s->pumpTo(other).attach(kj::defer([this, &other, before]() {
3631 transferredBytes += other.receivedByteCount() - before;
3632 })).exclusiveJoin(kj::mv(onAbort));
3633 } else {
3634 return newAdaptedPromise<void, BlockedPumpTo>(*this, other).exclusiveJoin(kj::mv(onAbort));
3635 }
3636 }
3637
3638 uint64_t sentByteCount() override {
3639 return transferredBytes;
3640 }
3641 uint64_t receivedByteCount() override {
3642 return transferredBytes;
3643 }
3644
3645 private:
3646 kj::Maybe<WebSocket&> state;
3647 // Object-oriented state! If any method call is blocked waiting on activity from the other end,
3648 // then `state` is non-null and method calls should be forwarded to it. If no calls are
3649 // outstanding, `state` is null.
3650
3651 kj::Own<WebSocket> ownState;
3652
3653 uint64_t transferredBytes = 0;
3654
3655 bool aborted = false;
3656 Maybe<Own<PromiseFulfiller<void>>> abortedFulfiller = nullptr;
3657 Maybe<ForkedPromise<void>> abortedPromise = nullptr;
3658
3659 void endState(WebSocket& obj) {
3660 KJ_IF_MAYBE(s, state) {
3661 if (s == &obj) {
3662 state = nullptr;
3663 }
3664 }
3665 }
3666
3667 struct ClosePtr {
3668 uint16_t code;
3669 kj::StringPtr reason;
3670 };
3671 typedef kj::OneOf<kj::ArrayPtr<const char>, kj::ArrayPtr<const byte>, ClosePtr> MessagePtr;
3672
3673 class BlockedSend final: public WebSocket {
3674 public:
3675 BlockedSend(kj::PromiseFulfiller<void>& fulfiller, WebSocketPipeImpl& pipe, MessagePtr message)
3676 : fulfiller(fulfiller), pipe(pipe), message(kj::mv(message)) {
3677 KJ_REQUIRE(pipe.state == nullptr);
3678 pipe.state = *this;
3679 }
3680 ~BlockedSend() noexcept(false) {
3681 pipe.endState(*this);
3682 }
3683
3684 void abort() override {
3685 canceler.cancel("other end of WebSocketPipe was destroyed");
3686 fulfiller.reject(KJ_EXCEPTION(DISCONNECTED, "other end of WebSocketPipe was destroyed"));
3687 pipe.endState(*this);
3688 pipe.abort();
3689 }
3690 kj::Promise<void> whenAborted() override {
3691 KJ_FAIL_ASSERT("can't get here -- implemented by WebSocketPipeImpl");
3692 }
3693
3694 kj::Promise<void> send(kj::ArrayPtr<const byte> message) override {
3695 KJ_FAIL_ASSERT("another message send is already in progress");
3696 }
3697 kj::Promise<void> send(kj::ArrayPtr<const char> message) override {
3698 KJ_FAIL_ASSERT("another message send is already in progress");
3699 }
3700 kj::Promise<void> close(uint16_t code, kj::StringPtr reason) override {
3701 KJ_FAIL_ASSERT("another message send is already in progress");
3702 }
3703 kj::Promise<void> disconnect() override {
3704 KJ_FAIL_ASSERT("another message send is already in progress");
3705 }
3706 kj::Maybe<kj::Promise<void>> tryPumpFrom(WebSocket& other) override {
3707 KJ_FAIL_ASSERT("another message send is already in progress");
3708 }
3709
3710 kj::Promise<Message> receive(size_t maxSize) override {
3711 KJ_REQUIRE(canceler.isEmpty(), "already pumping");
3712 fulfiller.fulfill();
3713 pipe.endState(*this);
3714 KJ_SWITCH_ONEOF(message) {
3715 KJ_CASE_ONEOF(arr, kj::ArrayPtr<const char>) {
3716 return Message(kj::str(arr));
3717 }
3718 KJ_CASE_ONEOF(arr, kj::ArrayPtr<const byte>) {
3719 auto copy = kj::heapArray<byte>(arr.size());
3720 memcpy(copy.begin(), arr.begin(), arr.size());
3721 return Message(kj::mv(copy));
3722 }
3723 KJ_CASE_ONEOF(close, ClosePtr) {
3724 return Message(Close { close.code, kj::str(close.reason) });
3725 }
3726 }
3727 KJ_UNREACHABLE;
3728 }
3729 kj::Promise<void> pumpTo(WebSocket& other) override {
3730 KJ_REQUIRE(canceler.isEmpty(), "already pumping");
3731 kj::Promise<void> promise = nullptr;
3732 KJ_SWITCH_ONEOF(message) {
3733 KJ_CASE_ONEOF(arr, kj::ArrayPtr<const char>) {
3734 promise = other.send(arr);
3735 }
3736 KJ_CASE_ONEOF(arr, kj::ArrayPtr<const byte>) {
3737 promise = other.send(arr);
3738 }
3739 KJ_CASE_ONEOF(close, ClosePtr) {
3740 promise = other.close(close.code, close.reason);
3741 }
3742 }
3743 return canceler.wrap(promise.then([this,&other]() {
3744 canceler.release();
3745 fulfiller.fulfill();
3746 pipe.endState(*this);
3747 return pipe.pumpTo(other);
3748 }, [this](kj::Exception&& e) -> kj::Promise<void> {
3749 canceler.release();
3750 fulfiller.reject(kj::cp(e));
3751 pipe.endState(*this);
3752 return kj::mv(e);
3753 }));
3754 }
3755
3756 uint64_t sentByteCount() override {
3757 KJ_FAIL_ASSERT("Bytes are not counted for the individual states of WebSocketPipeImpl.");
3758 }
3759 uint64_t receivedByteCount() override {
3760 KJ_FAIL_ASSERT("Bytes are not counted for the individual states of WebSocketPipeImpl.");
3761 }
3762
3763 private:
3764 kj::PromiseFulfiller<void>& fulfiller;
3765 WebSocketPipeImpl& pipe;
3766 MessagePtr message;
3767 Canceler canceler;
3768 };
3769
3770 class BlockedPumpFrom final: public WebSocket {
3771 public:
3772 BlockedPumpFrom(kj::PromiseFulfiller<void>& fulfiller, WebSocketPipeImpl& pipe,
3773 WebSocket& input)
3774 : fulfiller(fulfiller), pipe(pipe), input(input) {
3775 KJ_REQUIRE(pipe.state == nullptr);
3776 pipe.state = *this;
3777 }
3778 ~BlockedPumpFrom() noexcept(false) {
3779 pipe.endState(*this);
3780 }
3781
3782 void abort() override {
3783 canceler.cancel("other end of WebSocketPipe was destroyed");
3784 fulfiller.reject(KJ_EXCEPTION(DISCONNECTED, "other end of WebSocketPipe was destroyed"));
3785 pipe.endState(*this);
3786 pipe.abort();
3787 }
3788 kj::Promise<void> whenAborted() override {
3789 KJ_FAIL_ASSERT("can't get here -- implemented by WebSocketPipeImpl");
3790 }
3791
3792 kj::Promise<void> send(kj::ArrayPtr<const byte> message) override {
3793 KJ_FAIL_ASSERT("another message send is already in progress");
3794 }
3795 kj::Promise<void> send(kj::ArrayPtr<const char> message) override {
3796 KJ_FAIL_ASSERT("another message send is already in progress");
3797 }
3798 kj::Promise<void> close(uint16_t code, kj::StringPtr reason) override {
3799 KJ_FAIL_ASSERT("another message send is already in progress");
3800 }
3801 kj::Promise<void> disconnect() override {
3802 KJ_FAIL_ASSERT("another message send is already in progress");
3803 }
3804 kj::Maybe<kj::Promise<void>> tryPumpFrom(WebSocket& other) override {
3805 KJ_FAIL_ASSERT("another message send is already in progress");
3806 }
3807
3808 kj::Promise<Message> receive(size_t maxSize) override {
3809 KJ_REQUIRE(canceler.isEmpty(), "another message receive is already in progress");
3810 return canceler.wrap(input.receive(maxSize)
3811 .then([this](Message message) {
3812 if (message.is<Close>()) {
3813 canceler.release();
3814 fulfiller.fulfill();
3815 pipe.endState(*this);
3816 }
3817 return kj::mv(message);
3818 }, [this](kj::Exception&& e) -> Message {
3819 canceler.release();
3820 fulfiller.reject(kj::cp(e));
3821 pipe.endState(*this);
3822 kj::throwRecoverableException(kj::mv(e));
3823 return Message(kj::String());
3824 }));
3825 }
3826 kj::Promise<void> pumpTo(WebSocket& other) override {
3827 KJ_REQUIRE(canceler.isEmpty(), "another message receive is already in progress");
3828 return canceler.wrap(input.pumpTo(other)
3829 .then([this]() {
3830 canceler.release();
3831 fulfiller.fulfill();
3832 pipe.endState(*this);
3833 }, [this](kj::Exception&& e) {
3834 canceler.release();
3835 fulfiller.reject(kj::cp(e));
3836 pipe.endState(*this);
3837 kj::throwRecoverableException(kj::mv(e));
3838 }));
3839 }
3840
3841 uint64_t sentByteCount() override {
3842 KJ_FAIL_ASSERT("Bytes are not counted for the individual states of WebSocketPipeImpl.");
3843 }
3844 uint64_t receivedByteCount() override {
3845 KJ_FAIL_ASSERT("Bytes are not counted for the individual states of WebSocketPipeImpl.");
3846 }
3847
3848 private:
3849 kj::PromiseFulfiller<void>& fulfiller;
3850 WebSocketPipeImpl& pipe;
3851 WebSocket& input;
3852 Canceler canceler;
3853 };
3854
3855 class BlockedReceive final: public WebSocket {
3856 public:
3857 BlockedReceive(kj::PromiseFulfiller<Message>& fulfiller, WebSocketPipeImpl& pipe,
3858 size_t maxSize)
3859 : fulfiller(fulfiller), pipe(pipe), maxSize(maxSize) {
3860 KJ_REQUIRE(pipe.state == nullptr);
3861 pipe.state = *this;
3862 }
3863 ~BlockedReceive() noexcept(false) {
3864 pipe.endState(*this);
3865 }
3866
3867 void abort() override {
3868 canceler.cancel("other end of WebSocketPipe was destroyed");
3869 fulfiller.reject(KJ_EXCEPTION(DISCONNECTED, "other end of WebSocketPipe was destroyed"));
3870 pipe.endState(*this);
3871 pipe.abort();
3872 }
3873 kj::Promise<void> whenAborted() override {
3874 KJ_FAIL_ASSERT("can't get here -- implemented by WebSocketPipeImpl");
3875 }
3876
3877 kj::Promise<void> send(kj::ArrayPtr<const byte> message) override {
3878 KJ_REQUIRE(canceler.isEmpty(), "already pumping");
3879 auto copy = kj::heapArray<byte>(message.size());
3880 memcpy(copy.begin(), message.begin(), message.size());
3881 fulfiller.fulfill(Message(kj::mv(copy)));
3882 pipe.endState(*this);
3883 return kj::READY_NOW;
3884 }
3885 kj::Promise<void> send(kj::ArrayPtr<const char> message) override {
3886 KJ_REQUIRE(canceler.isEmpty(), "already pumping");
3887 fulfiller.fulfill(Message(kj::str(message)));
3888 pipe.endState(*this);
3889 return kj::READY_NOW;
3890 }
3891 kj::Promise<void> close(uint16_t code, kj::StringPtr reason) override {
3892 KJ_REQUIRE(canceler.isEmpty(), "already pumping");
3893 fulfiller.fulfill(Message(Close { code, kj::str(reason) }));
3894 pipe.endState(*this);
3895 return kj::READY_NOW;
3896 }
3897 kj::Promise<void> disconnect() override {
3898 KJ_REQUIRE(canceler.isEmpty(), "already pumping");
3899 fulfiller.reject(KJ_EXCEPTION(DISCONNECTED, "WebSocket disconnected"));
3900 pipe.endState(*this);
3901 return pipe.disconnect();
3902 }
3903 kj::Maybe<kj::Promise<void>> tryPumpFrom(WebSocket& other) override {
3904 KJ_REQUIRE(canceler.isEmpty(), "already pumping");
3905 return canceler.wrap(other.receive(maxSize).then([this,&other](Message message) {
3906 canceler.release();
3907 fulfiller.fulfill(kj::mv(message));
3908 pipe.endState(*this);
3909 return other.pumpTo(pipe);
3910 }, [this](kj::Exception&& e) -> kj::Promise<void> {
3911 canceler.release();
3912 fulfiller.reject(kj::cp(e));
3913 pipe.endState(*this);
3914 return kj::mv(e);
3915 }));
3916 }
3917
3918 kj::Promise<Message> receive(size_t maxSize) override {
3919 KJ_FAIL_ASSERT("another message receive is already in progress");
3920 }
3921 kj::Promise<void> pumpTo(WebSocket& other) override {
3922 KJ_FAIL_ASSERT("another message receive is already in progress");
3923 }
3924
3925 uint64_t sentByteCount() override {
3926 KJ_FAIL_ASSERT("Bytes are not counted for the individual states of WebSocketPipeImpl.");
3927 }
3928 uint64_t receivedByteCount() override {
3929 KJ_FAIL_ASSERT("Bytes are not counted for the individual states of WebSocketPipeImpl.");
3930 }
3931
3932 private:
3933 kj::PromiseFulfiller<Message>& fulfiller;
3934 WebSocketPipeImpl& pipe;
3935 size_t maxSize;
3936 Canceler canceler;
3937 };
3938
3939 class BlockedPumpTo final: public WebSocket {
3940 public:
3941 BlockedPumpTo(kj::PromiseFulfiller<void>& fulfiller, WebSocketPipeImpl& pipe, WebSocket& output)
3942 : fulfiller(fulfiller), pipe(pipe), output(output) {
3943 KJ_REQUIRE(pipe.state == nullptr);
3944 pipe.state = *this;
3945 }
3946 ~BlockedPumpTo() noexcept(false) {
3947 pipe.endState(*this);
3948 }
3949
3950 void abort() override {
3951 canceler.cancel("other end of WebSocketPipe was destroyed");
3952
3953 // abort() is called when the pipe end is dropped. This should be treated as disconnecting,
3954 // so pumpTo() should complete normally.
3955 fulfiller.fulfill();
3956
3957 pipe.endState(*this);
3958 pipe.abort();
3959 }
3960 kj::Promise<void> whenAborted() override {
3961 KJ_FAIL_ASSERT("can't get here -- implemented by WebSocketPipeImpl");
3962 }
3963
3964 kj::Promise<void> send(kj::ArrayPtr<const byte> message) override {
3965 KJ_REQUIRE(canceler.isEmpty(), "another message send is already in progress");
3966 return canceler.wrap(output.send(message));
3967 }
3968 kj::Promise<void> send(kj::ArrayPtr<const char> message) override {
3969 KJ_REQUIRE(canceler.isEmpty(), "another message send is already in progress");
3970 return canceler.wrap(output.send(message));
3971 }
3972 kj::Promise<void> close(uint16_t code, kj::StringPtr reason) override {
3973 KJ_REQUIRE(canceler.isEmpty(), "another message send is already in progress");
3974 return canceler.wrap(output.close(code, reason).then([this]() {
3975 // A pump is expected to end upon seeing a Close message.
3976 canceler.release();
3977 pipe.endState(*this);
3978 fulfiller.fulfill();
3979 }, [this](kj::Exception&& e) {
3980 canceler.release();
3981 pipe.endState(*this);
3982 fulfiller.reject(kj::cp(e));
3983 kj::throwRecoverableException(kj::mv(e));
3984 }));
3985 }
3986 kj::Promise<void> disconnect() override {
3987 KJ_REQUIRE(canceler.isEmpty(), "another message send is already in progress");
3988 return canceler.wrap(output.disconnect().then([this]() {
3989 canceler.release();
3990 pipe.endState(*this);
3991 fulfiller.fulfill();
3992 return pipe.disconnect();
3993 }, [this](kj::Exception&& e) {
3994 canceler.release();
3995 pipe.endState(*this);
3996 fulfiller.reject(kj::cp(e));
3997 kj::throwRecoverableException(kj::mv(e));
3998 }));
3999 }
4000 kj::Maybe<kj::Promise<void>> tryPumpFrom(WebSocket& other) override {
4001 KJ_REQUIRE(canceler.isEmpty(), "another message send is already in progress");
4002 return canceler.wrap(other.pumpTo(output).then([this]() {
4003 canceler.release();
4004 pipe.endState(*this);
4005 fulfiller.fulfill();
4006 }, [this](kj::Exception&& e) {
4007 canceler.release();
4008 pipe.endState(*this);
4009 fulfiller.reject(kj::cp(e));
4010 kj::throwRecoverableException(kj::mv(e));
4011 }));
4012 }
4013
4014 kj::Promise<Message> receive(size_t maxSize) override {
4015 KJ_FAIL_ASSERT("another message receive is already in progress");
4016 }
4017 kj::Promise<void> pumpTo(WebSocket& other) override {
4018 KJ_FAIL_ASSERT("another message receive is already in progress");
4019 }
4020
4021 uint64_t sentByteCount() override {
4022 KJ_FAIL_ASSERT("Bytes are not counted for the individual states of WebSocketPipeImpl.");
4023 }
4024 uint64_t receivedByteCount() override {
4025 KJ_FAIL_ASSERT("Bytes are not counted for the individual states of WebSocketPipeImpl.");
4026 }
4027
4028 private:
4029 kj::PromiseFulfiller<void>& fulfiller;
4030 WebSocketPipeImpl& pipe;
4031 WebSocket& output;
4032 Canceler canceler;
4033 };
4034
4035 class Disconnected final: public WebSocket {
4036 public:
4037 void abort() override {
4038 // can ignore
4039 }
4040 kj::Promise<void> whenAborted() override {
4041 KJ_FAIL_ASSERT("can't get here -- implemented by WebSocketPipeImpl");
4042 }
4043
4044 kj::Promise<void> send(kj::ArrayPtr<const byte> message) override {
4045 KJ_FAIL_REQUIRE("can't send() after disconnect()");
4046 }
4047 kj::Promise<void> send(kj::ArrayPtr<const char> message) override {
4048 KJ_FAIL_REQUIRE("can't send() after disconnect()");
4049 }
4050 kj::Promise<void> close(uint16_t code, kj::StringPtr reason) override {
4051 KJ_FAIL_REQUIRE("can't close() after disconnect()");
4052 }
4053 kj::Promise<void> disconnect() override {
4054 return kj::READY_NOW;
4055 }
4056 kj::Maybe<kj::Promise<void>> tryPumpFrom(WebSocket& other) override {
4057 KJ_FAIL_REQUIRE("can't tryPumpFrom() after disconnect()");
4058 }
4059
4060 kj::Promise<Message> receive(size_t maxSize) override {
4061 return KJ_EXCEPTION(DISCONNECTED, "WebSocket disconnected");
4062 }
4063 kj::Promise<void> pumpTo(WebSocket& other) override {
4064 return kj::READY_NOW;
4065 }
4066
4067 uint64_t sentByteCount() override {
4068 KJ_FAIL_ASSERT("Bytes are not counted for the individual states of WebSocketPipeImpl.");
4069 }
4070 uint64_t receivedByteCount() override {
4071 KJ_FAIL_ASSERT("Bytes are not counted for the individual states of WebSocketPipeImpl.");
4072 }
4073
4074 };
4075
4076 class Aborted final: public WebSocket {
4077 public:
4078 void abort() override {
4079 // can ignore
4080 }
4081 kj::Promise<void> whenAborted() override {
4082 KJ_FAIL_ASSERT("can't get here -- implemented by WebSocketPipeImpl");
4083 }
4084
4085 kj::Promise<void> send(kj::ArrayPtr<const byte> message) override {
4086 return KJ_EXCEPTION(DISCONNECTED, "other end of WebSocketPipe was destroyed");
4087 }
4088 kj::Promise<void> send(kj::ArrayPtr<const char> message) override {
4089 return KJ_EXCEPTION(DISCONNECTED, "other end of WebSocketPipe was destroyed");
4090 }
4091 kj::Promise<void> close(uint16_t code, kj::StringPtr reason) override {
4092 return KJ_EXCEPTION(DISCONNECTED, "other end of WebSocketPipe was destroyed");
4093 }
4094 kj::Promise<void> disconnect() override {
4095 return KJ_EXCEPTION(DISCONNECTED, "other end of WebSocketPipe was destroyed");
4096 }
4097 kj::Maybe<kj::Promise<void>> tryPumpFrom(WebSocket& other) override {
4098 return kj::Promise<void>(KJ_EXCEPTION(DISCONNECTED,
4099 "other end of WebSocketPipe was destroyed"));
4100 }
4101
4102 kj::Promise<Message> receive(size_t maxSize) override {
4103 return KJ_EXCEPTION(DISCONNECTED, "other end of WebSocketPipe was destroyed");
4104 }
4105 kj::Promise<void> pumpTo(WebSocket& other) override {
4106 return KJ_EXCEPTION(DISCONNECTED, "other end of WebSocketPipe was destroyed");
4107 }
4108
4109 uint64_t sentByteCount() override {
4110 KJ_FAIL_ASSERT("Bytes are not counted for the individual states of WebSocketPipeImpl.");
4111 }
4112 uint64_t receivedByteCount() override {
4113 KJ_FAIL_ASSERT("Bytes are not counted for the individual states of WebSocketPipeImpl.");
4114 }
4115 };
4116 };
4117
4118 class WebSocketPipeEnd final: public WebSocket {
4119 public:
4120 WebSocketPipeEnd(kj::Own<WebSocketPipeImpl> in, kj::Own<WebSocketPipeImpl> out)
4121 : in(kj::mv(in)), out(kj::mv(out)) {}
4122 ~WebSocketPipeEnd() noexcept(false) {
4123 in->abort();
4124 out->abort();
4125 }
4126
4127 kj::Promise<void> send(kj::ArrayPtr<const byte> message) override {
4128 return out->send(message);
4129 }
4130 kj::Promise<void> send(kj::ArrayPtr<const char> message) override {
4131 return out->send(message);
4132 }
4133 kj::Promise<void> close(uint16_t code, kj::StringPtr reason) override {
4134 return out->close(code, reason);
4135 }
4136 kj::Promise<void> disconnect() override {
4137 return out->disconnect();
4138 }
4139 void abort() override {
4140 in->abort();
4141 out->abort();
4142 }
4143 kj::Promise<void> whenAborted() override {
4144 return out->whenAborted();
4145 }
4146 kj::Maybe<kj::Promise<void>> tryPumpFrom(WebSocket& other) override {
4147 return out->tryPumpFrom(other);
4148 }
4149
4150 kj::Promise<Message> receive(size_t maxSize) override {
4151 return in->receive(maxSize);
4152 }
4153 kj::Promise<void> pumpTo(WebSocket& other) override {
4154 return in->pumpTo(other);
4155 }
4156
4157 uint64_t sentByteCount() override { return out->sentByteCount(); }
4158 uint64_t receivedByteCount() override { return in->sentByteCount(); }
4159
4160 private:
4161 kj::Own<WebSocketPipeImpl> in;
4162 kj::Own<WebSocketPipeImpl> out;
4163 };
4164
4165 } // namespace
4166
4167 WebSocketPipe newWebSocketPipe() {
4168 auto pipe1 = kj::refcounted<WebSocketPipeImpl>();
4169 auto pipe2 = kj::refcounted<WebSocketPipeImpl>();
4170
4171 auto end1 = kj::heap<WebSocketPipeEnd>(kj::addRef(*pipe1), kj::addRef(*pipe2));
4172 auto end2 = kj::heap<WebSocketPipeEnd>(kj::mv(pipe2), kj::mv(pipe1));
4173
4174 return { { kj::mv(end1), kj::mv(end2) } };
4175 }
4176
4177 // =======================================================================================
4178 class AsyncIoStreamWithInitialBuffer final: public kj::AsyncIoStream {
4179 // An AsyncIoStream implementation that accepts an initial buffer of data
4180 // to be read out first, and is optionally capable of deferring writes
4181 // until a given waitBeforeSend promise is fulfilled.
4182 //
4183 // Instances are created with a leftoverBackingBuffer (a kj::Array<byte>)
4184 // and a leftover kj::ArrayPtr<byte> that provides a view into the backing
4185 // buffer representing the queued data that is pending to be read. Calling
4186 // tryRead will consume the data from the leftover first. Once leftover has
4187 // been fully consumed, reads will defer to the underlying stream.
4188 public:
4189 AsyncIoStreamWithInitialBuffer(kj::Own<kj::AsyncIoStream> stream,
4190 kj::Array<byte> leftoverBackingBuffer,
4191 kj::ArrayPtr<byte> leftover)
4192 : stream(kj::mv(stream)),
4193 leftoverBackingBuffer(kj::mv(leftoverBackingBuffer)),
4194 leftover(leftover) {}
4195
4196 void shutdownWrite() override {
4197 stream->shutdownWrite();
4198 }
4199
4200 // AsyncInputStream
4201 Promise<size_t> tryRead(void* buffer, size_t minBytes, size_t maxBytes) override {
4202 KJ_REQUIRE(maxBytes >= minBytes);
4203 auto destination = static_cast<byte*>(buffer);
4204
4205 // If there are at least minBytes available in the leftover buffer...
4206 if (leftover.size() >= minBytes) {
4207 // We are going to immediately read up to maxBytes from the leftover buffer...
4208 auto bytesToCopy = kj::min(maxBytes, leftover.size());
4209 memcpy(destination, leftover.begin(), bytesToCopy);
4210 leftover = leftover.slice(bytesToCopy, leftover.size());
4211
4212 // If we've consumed all of the data in the leftover buffer, go ahead and free it.
4213 if (leftover.size() == 0) {
4214 leftoverBackingBuffer = nullptr;
4215 }
4216
4217 return bytesToCopy;
4218 } else {
4219 // We know here that leftover.size() is less than minBytes, but it might not
4220 // be zero. Copy everything from leftover into the destination buffer then read
4221 // the rest from the underlying stream.
4222 auto bytesToCopy = leftover.size();
4223 KJ_DASSERT(bytesToCopy < minBytes);
4224
4225 if (bytesToCopy > 0) {
4226 memcpy(destination, leftover.begin(), bytesToCopy);
4227 leftoverBackingBuffer = nullptr;
4228 minBytes -= bytesToCopy;
4229 maxBytes -= bytesToCopy;
4230 KJ_DASSERT(minBytes >= 1);
4231 KJ_DASSERT(maxBytes >= minBytes);
4232 }
4233
4234 return stream->tryRead(destination + bytesToCopy, minBytes, maxBytes)
4235 .then([bytesToCopy](size_t amount) { return amount + bytesToCopy; });
4236 }
4237 }
4238
4239 Maybe<uint64_t> tryGetLength() override {
4240 // For a CONNECT pipe, we have no idea how much data there is going to be.
4241 return nullptr;
4242 }
4243
4244 kj::Promise<uint64_t> pumpTo(AsyncOutputStream& output,
4245 uint64_t amount = kj::maxValue) override {
4246 return pumpLoop(output, amount, 0);
4247 }
4248
4249 kj::Maybe<kj::Promise<uint64_t>> tryPumpFrom(AsyncInputStream& input,
4250 uint64_t amount = kj::maxValue) override {
4251 return input.pumpTo(*stream, amount);
4252 }
4253
4254 // AsyncOutputStream
4255 Promise<void> write(const void* buffer, size_t size) override {
4256 return stream->write(buffer, size);
4257 }
4258
4259 Promise<void> write(ArrayPtr<const ArrayPtr<const byte>> pieces) override {
4260 return stream->write(pieces);
4261 }
4262
4263 Promise<void> whenWriteDisconnected() override {
4264 return stream->whenWriteDisconnected();
4265 }
4266
4267 private:
4268
4269 kj::Promise<uint64_t> pumpLoop(
4270 kj::AsyncOutputStream& output,
4271 uint64_t remaining,
4272 uint64_t total) {
4273 // If there is any data remaining in the leftover queue, we'll write it out first to output.
4274 if (leftover.size() > 0) {
4275 auto bytesToWrite = kj::min(leftover.size(), remaining);
4276 return output.write(leftover.begin(), bytesToWrite).then(
4277 [this, &output, remaining, total, bytesToWrite]() mutable -> kj::Promise<uint64_t> {
4278 leftover = leftover.slice(bytesToWrite, leftover.size());
4279 // If the leftover buffer has been fully consumed, go ahead and free it now.
4280 if (leftover.size() == 0) {
4281 leftoverBackingBuffer = nullptr;
4282 }
4283 remaining -= bytesToWrite;
4284 total += bytesToWrite;
4285
4286 if (remaining == 0) {
4287 return total;
4288 }
4289 return pumpLoop(output, remaining, total);
4290 });
4291 } else {
4292 // Otherwise, we are just going to defer to stream's pumpTo, making sure to
4293 // account for the total amount we've already written from the leftover queue.
4294 return stream->pumpTo(output, remaining).then([total](auto read) {
4295 return total + read;
4296 });
4297 }
4298 };
4299
4300 kj::Own<kj::AsyncIoStream> stream;
4301 kj::Array<byte> leftoverBackingBuffer;
4302 kj::ArrayPtr<byte> leftover;
4303 };
4304
4305 class AsyncIoStreamWithGuards final: public kj::AsyncIoStream,
4306 private kj::TaskSet::ErrorHandler {
4307 // This AsyncIoStream adds separate kj::Promise guards to both the input and output,
4308 // delaying reads and writes until each relevant guard is resolved.
4309 //
4310 // When the read guard promise resolves, it may provide a released buffer that will
4311 // be read out first.
4312 // The primary use case for this impl is to support pipelined CONNECT calls which
4313 // optimistically allow outbound writes to happen while establishing the CONNECT
4314 // tunnel has not yet been completed. If the guard promise rejects, the stream
4315 // is permanently errored and existing pending calls (reads and writes) are canceled.
4316 public:
4317 AsyncIoStreamWithGuards(
4318 kj::Own<kj::AsyncIoStream> inner,
4319 kj::Promise<kj::Maybe<HttpInputStreamImpl::ReleasedBuffer>> readGuard,
4320 kj::Promise<void> writeGuard)
4321 : inner(kj::mv(inner)),
4322 readGuard(handleReadGuard(kj::mv(readGuard))),
4323 writeGuard(handleWriteGuard(kj::mv(writeGuard))),
4324 tasks(*this) {}
4325
4326 // AsyncInputStream
4327 Promise<size_t> tryRead(void* buffer, size_t minBytes, size_t maxBytes) override {
4328 if (readGuardReleased) {
4329 return inner->tryRead(buffer, minBytes, maxBytes);
4330 }
4331 return readGuard.addBranch().then([this, buffer, minBytes, maxBytes] {
4332 return inner->tryRead(buffer, minBytes, maxBytes);
4333 });
4334 }
4335
4336 Maybe<uint64_t> tryGetLength() override {
4337 return nullptr;
4338 }
4339
4340 kj::Promise<uint64_t> pumpTo(AsyncOutputStream& output, uint64_t amount = kj::maxValue) override {
4341 if (readGuardReleased) {
4342 return inner->pumpTo(output, amount);
4343 }
4344 return readGuard.addBranch().then([this, &output, amount] {
4345 return inner->pumpTo(output, amount);
4346 });
4347 }
4348
4349 // AsyncOutputStream
4350
4351 void shutdownWrite() override {
4352 if (writeGuardReleased) {
4353 inner->shutdownWrite();
4354 } else {
4355 tasks.add(writeGuard.addBranch().then([this]() { inner->shutdownWrite(); }));
4356 }
4357 }
4358
4359 kj::Maybe<kj::Promise<uint64_t>> tryPumpFrom(AsyncInputStream& input,
4360 uint64_t amount = kj::maxValue) override {
4361 if (writeGuardReleased) {
4362 return input.pumpTo(*inner, amount);
4363 } else {
4364 return writeGuard.addBranch().then([this,&input,amount]() {
4365 return input.pumpTo(*inner, amount);
4366 });
4367 }
4368 }
4369
4370 Promise<void> write(const void* buffer, size_t size) override {
4371 if (writeGuardReleased) {
4372 return inner->write(buffer, size);
4373 } else {
4374 return writeGuard.addBranch().then([this,buffer,size]() {
4375 return inner->write(buffer, size);
4376 });
4377 }
4378 }
4379
4380 Promise<void> write(ArrayPtr<const ArrayPtr<const byte>> pieces) override {
4381 if (writeGuardReleased) {
4382 return inner->write(pieces);
4383 } else {
4384 return writeGuard.addBranch().then([this, pieces]() {
4385 return inner->write(pieces);
4386 });
4387 }
4388 }
4389
4390 Promise<void> whenWriteDisconnected() override {
4391 if (writeGuardReleased) {
4392 return inner->whenWriteDisconnected();
4393 } else {
4394 return writeGuard.addBranch().then([this]() {
4395 return inner->whenWriteDisconnected();
4396 }, [](kj::Exception&& e) mutable -> kj::Promise<void> {
4397 if (e.getType() == kj::Exception::Type::DISCONNECTED) {
4398 return kj::READY_NOW;
4399 } else {
4400 return kj::mv(e);
4401 }
4402 });
4403 }
4404 }
4405
4406 private:
4407 kj::Own<kj::AsyncIoStream> inner;
4408 kj::ForkedPromise<void> readGuard;
4409 kj::ForkedPromise<void> writeGuard;
4410 bool readGuardReleased = false;
4411 bool writeGuardReleased = false;
4412 kj::TaskSet tasks;
4413 // Set of tasks used to call `shutdownWrite` after write guard is released.
4414
4415 void taskFailed(kj::Exception&& exception) override {
4416 // This `taskFailed` callback is only used when `shutdownWrite` is being called. Because we
4417 // don't care about DISCONNECTED exceptions when `shutdownWrite` is called we ignore this
4418 // class of exceptions here.
4419 if (exception.getType() != kj::Exception::Type::DISCONNECTED) {
4420 KJ_LOG(ERROR, exception);
4421 }
4422 }
4423
4424 kj::ForkedPromise<void> handleWriteGuard(kj::Promise<void> guard) {
4425 return guard.then([this]() {
4426 writeGuardReleased = true;
4427 }).fork();
4428 }
4429
4430 kj::ForkedPromise<void> handleReadGuard(
4431 kj::Promise<kj::Maybe<HttpInputStreamImpl::ReleasedBuffer>> guard) {
4432 return guard.then([this](kj::Maybe<HttpInputStreamImpl::ReleasedBuffer> buffer) mutable {
4433 readGuardReleased = true;
4434 KJ_IF_MAYBE(b, buffer) {
4435 if (b->leftover.size() > 0) {
4436 // We only need to replace the inner stream if a non-empty buffer is provided.
4437 inner = heap<AsyncIoStreamWithInitialBuffer>(
4438 kj::mv(inner),
4439 kj::mv(b->buffer), b->leftover);
4440 }
4441 }
4442 }).fork();
4443 }
4444 };
4445
4446 // =======================================================================================
4447
4448 namespace _ { // private implementation details
4449
4450 kj::ArrayPtr<const char> splitNext(kj::ArrayPtr<const char>& cursor, char delimiter) {
4451 // Consumes and returns the next item in a delimited list.
4452 //
4453 // If a delimiter is found:
4454 // - `cursor` is updated to point to the rest of the string after the delimiter.
4455 // - The text before the delimiter is returned.
4456 // If no delimiter is found:
4457 // - `cursor` is updated to an empty string.
4458 // - The text that had been in `cursor` is returned.
4459 //
4460 // (It's up to the caller to stop the loop once `cursor` is empty.)
4461 KJ_IF_MAYBE(index, cursor.findFirst(delimiter)) {
4462 auto part = cursor.slice(0, *index);
4463 cursor = cursor.slice(*index + 1, cursor.size());
4464 return part;
4465 }
4466 kj::ArrayPtr<const char> result(kj::mv(cursor));
4467 cursor = nullptr;
4468
4469 return result;
4470 }
4471
4472 void stripLeadingAndTrailingSpace(ArrayPtr<const char>& str) {
4473 // Remove any leading/trailing spaces from `str`, modifying it in-place.
4474 while (str.size() > 0 && (str[0] == ' ' || str[0] == '\t')) {
4475 str = str.slice(1, str.size());
4476 }
4477 while (str.size() > 0 && (str.back() == ' ' || str.back() == '\t')) {
4478 str = str.slice(0, str.size() - 1);
4479 }
4480 }
4481
4482 kj::Vector<kj::ArrayPtr<const char>> splitParts(kj::ArrayPtr<const char> input, char delim) {
4483 // Given a string `input` and a delimiter `delim`, split the string into a vector of substrings,
4484 // separated by the delimiter. Note that leading/trailing whitespace is stripped from each element.
4485 kj::Vector<kj::ArrayPtr<const char>> parts;
4486
4487 while (input.size() != 0) {
4488 auto part = splitNext(input, delim);
4489 stripLeadingAndTrailingSpace(part);
4490 parts.add(kj::mv(part));
4491 }
4492
4493 return parts;
4494 }
4495
4496 kj::Array<KeyMaybeVal> toKeysAndVals(const kj::ArrayPtr<kj::ArrayPtr<const char>>& params) {
4497 // Given a collection of parameters (a single offer), parse the parameters into <key, MaybeValue>
4498 // pairs. If the parameter contains an `=`, we set the `key` to everything before, and the `value`
4499 // to everything after. Otherwise, we set the `key` to be the entire parameter.
4500 // Either way, both the key and value (if it exists) are stripped of leading & trailing whitespace.
4501 auto result = kj::heapArray<KeyMaybeVal>(params.size());
4502 size_t count = 0;
4503 for (const auto& param : params) {
4504 kj::ArrayPtr<const char> key;
4505 kj::Maybe<kj::ArrayPtr<const char>> value;
4506
4507 KJ_IF_MAYBE(index, param.findFirst('=')) {
4508 // Found '=' so we have a value.
4509 key = param.slice(0, *index);
4510 stripLeadingAndTrailingSpace(key);
4511 value = param.slice(*index + 1, param.size());
4512 KJ_IF_MAYBE(v, value) {
4513 stripLeadingAndTrailingSpace(*v);
4514 }
4515 } else {
4516 key = kj::mv(param);
4517 }
4518
4519 result[count].key = kj::mv(key);
4520 result[count].val = kj::mv(value);
4521 ++count;
4522 }
4523 return kj::mv(result);
4524 }
4525
4526 struct ParamType {
4527 enum { CLIENT, SERVER } side;
4528 enum { NO_CONTEXT_TAKEOVER, MAX_WINDOW_BITS } property;
4529 };
4530
4531 inline kj::Maybe<ParamType> parseKeyName(kj::ArrayPtr<const char>& key) {
4532 // Returns a `ParamType` struct if the `key` is valid and nullptr if invalid.
4533
4534 if (key == "client_no_context_takeover"_kj) {
4535 return ParamType { ParamType::CLIENT, ParamType::NO_CONTEXT_TAKEOVER };
4536 } else if (key == "server_no_context_takeover"_kj) {
4537 return ParamType { ParamType::SERVER, ParamType::NO_CONTEXT_TAKEOVER };
4538 } else if (key == "client_max_window_bits"_kj) {
4539 return ParamType { ParamType::CLIENT, ParamType::MAX_WINDOW_BITS };
4540 } else if (key == "server_max_window_bits"_kj) {
4541 return ParamType { ParamType::SERVER, ParamType::MAX_WINDOW_BITS };
4542 }
4543 return nullptr;
4544 }
4545
4546 kj::Maybe<UnverifiedConfig> populateUnverifiedConfig(kj::Array<KeyMaybeVal>& params) {
4547 // Given a collection of <key, MaybeValue> pairs, attempt to populate an `UnverifiedConfig` struct.
4548 // If the struct cannot be populated, we return null.
4549 //
4550 // This function populates the struct with what it finds, it does not perform bounds checking or
4551 // concern itself with valid `Value`s (so long as the `Value` is non-empty).
4552 //
4553 // The following issues would prevent a struct from being populated:
4554 // Key issues:
4555 // - `Key` is invalid (see `parseKeyName()`).
4556 // - `Key` is repeated.
4557 // Value issues:
4558 // - Got a `Value` when none was expected (only the `max_window_bits` parameters expect values).
4559 // - Got an empty `Value` (0 characters, or all whitespace characters).
4560
4561 if (params.size() > 4) {
4562 // We expect 4 `Key`s at most, having more implies repeats/invalid keys are present.
4563 return nullptr;
4564 }
4565
4566 UnverifiedConfig config;
4567
4568 for (auto& param : params) {
4569 KJ_IF_MAYBE(paramType, parseKeyName(param.key)) {
4570 // `Key` is valid, but we still want to check for repeats.
4571 const auto& side = paramType->side;
4572 const auto& property = paramType->property;
4573
4574 if (property == ParamType::NO_CONTEXT_TAKEOVER) {
4575 auto& takeOverSetting = (side == ParamType::CLIENT) ?
4576 config.clientNoContextTakeover : config.serverNoContextTakeover;
4577
4578 if (takeOverSetting == true) {
4579 // This `Key` is a repeat; invalid config.
4580 return nullptr;
4581 }
4582
4583 if (param.val != nullptr) {
4584 // The `x_no_context_takeover` parameter shouldn't have a value; invalid config.
4585 return nullptr;
4586 }
4587
4588 takeOverSetting = true;
4589 } else if (property == ParamType::MAX_WINDOW_BITS) {
4590 auto& maxBitsSetting =
4591 (side == ParamType::CLIENT) ? config.clientMaxWindowBits : config.serverMaxWindowBits;
4592
4593 if (maxBitsSetting != nullptr) {
4594 // This `Key` is a repeat; invalid config.
4595 return nullptr;
4596 }
4597
4598 KJ_IF_MAYBE(value, param.val) {
4599 if (value->size() == 0) {
4600 // This is equivalent to `x_max_window_bits=`, since we got an "=" we expected a token
4601 // to follow.
4602 return nullptr;
4603 }
4604 maxBitsSetting = param.val;
4605 } else {
4606 // We know we got this `max_window_bits` parameter in a Request/Response, and we also know
4607 // that it didn't include an "=" (otherwise the value wouldn't be null).
4608 // It's important to retain the information that the parameter was received *without* a
4609 // corresponding value, as this may determine whether the offer is valid or not.
4610 //
4611 // To retain this information, we'll set `maxBitsSetting` to be an empty ArrayPtr so this
4612 // can be dealt with properly later.
4613 maxBitsSetting = ArrayPtr<const char>();
4614 }
4615 }
4616 } else {
4617 // Invalid parameter.
4618 return nullptr;
4619 }
4620 }
4621 return kj::mv(config);
4622 }
4623
4624 kj::Maybe<CompressionParameters> validateCompressionConfig(UnverifiedConfig&& config,
4625 bool isAgreement) {
4626 // Verifies that the `config` is valid depending on whether we're validating a Request (offer) or
4627 // a Response (agreement). This essentially consumes the `UnverifiedConfig` and converts it into a
4628 // `CompressionParameters` struct.
4629 CompressionParameters result;
4630
4631 KJ_IF_MAYBE(serverBits, config.serverMaxWindowBits) {
4632 if (serverBits->size() == 0) {
4633 // This means `server_max_window_bits` was passed without a value. Since a value is required,
4634 // this config is invalid.
4635 return nullptr;
4636 } else {
4637 KJ_IF_MAYBE(bits, kj::str(*serverBits).tryParseAs<size_t>()) {
4638 if (*bits < 8 || 15 < *bits) {
4639 // Out of range -- invalid.
4640 return nullptr;
4641 }
4642 if (isAgreement) {
4643 result.inboundMaxWindowBits = *bits;
4644 } else {
4645 result.outboundMaxWindowBits = *bits;
4646 }
4647 } else {
4648 // Invalid ABNF, expected 1*DIGIT.
4649 return nullptr;
4650 }
4651 }
4652 }
4653
4654 KJ_IF_MAYBE(clientBits, config.clientMaxWindowBits) {
4655 if (clientBits->size() == 0) {
4656 if (!isAgreement) {
4657 // `client_max_window_bits` does not need to have a value in an offer, let's set it to 15
4658 // to get the best level of compression.
4659 result.inboundMaxWindowBits = 15;
4660 } else {
4661 // `client_max_window_bits` must have a value in a Response.
4662 return nullptr;
4663 }
4664 } else {
4665 KJ_IF_MAYBE(bits, kj::str(*clientBits).tryParseAs<size_t>()) {
4666 if (*bits < 8 || 15 < *bits) {
4667 // Out of range -- invalid.
4668 return nullptr;
4669 }
4670 if (isAgreement) {
4671 result.outboundMaxWindowBits = *bits;
4672 } else {
4673 result.inboundMaxWindowBits = *bits;
4674 }
4675 } else {
4676 // Invalid ABNF, expected 1*DIGIT.
4677 return nullptr;
4678 }
4679 }
4680 }
4681
4682 if (isAgreement) {
4683 result.outboundNoContextTakeover = config.clientNoContextTakeover;
4684 result.inboundNoContextTakeover = config.serverNoContextTakeover;
4685 } else {
4686 result.inboundNoContextTakeover = config.clientNoContextTakeover;
4687 result.outboundNoContextTakeover = config.serverNoContextTakeover;
4688 }
4689 return kj::mv(result);
4690 }
4691
4692 inline kj::Maybe<CompressionParameters> tryExtractParameters(
4693 kj::Vector<kj::ArrayPtr<const char>>& configuration,
4694 bool isAgreement) {
4695 // If the `configuration` is structured correctly and has no invalid parameters/values, we will
4696 // return a populated `CompressionParameters` struct.
4697 if (configuration.size() == 1) {
4698 // Plain `permessage-deflate`.
4699 return CompressionParameters{};
4700 }
4701 auto params = configuration.slice(1, configuration.size());
4702 auto keyMaybeValuePairs = toKeysAndVals(params);
4703 // Parse parameter strings into parameter[=value] pairs.
4704 auto maybeUnverified = populateUnverifiedConfig(keyMaybeValuePairs);
4705 KJ_IF_MAYBE(unverified, maybeUnverified) {
4706 // Parsing succeeded, i.e. the parameter (`key`) names are valid and we don't have
4707 // values for `x_no_context_takeover` parameters (the configuration is structured correctly).
4708 // All that's left is to check the `x_max_window_bits` values (if any are present).
4709 KJ_IF_MAYBE(validConfig, validateCompressionConfig(kj::mv(*unverified), isAgreement)) {
4710 return kj::mv(*validConfig);
4711 }
4712 }
4713 return nullptr;
4714 }
4715
4716 kj::Vector<CompressionParameters> findValidExtensionOffers(StringPtr offers) {
4717 // A function to be called by the client that wants to offer extensions through
4718 // `Sec-WebSocket-Extensions`. This function takes the value of the header (a string) and
4719 // populates a Vector of all the valid offers.
4720 kj::Vector<CompressionParameters> result;
4721
4722 auto extensions = splitParts(offers, ',');
4723
4724 for (const auto& offer : extensions) {
4725 auto splitOffer = splitParts(offer, ';');
4726 if (splitOffer.front() != "permessage-deflate"_kj) {
4727 continue;
4728 }
4729 KJ_IF_MAYBE(validated, tryExtractParameters(splitOffer, false)) {
4730 // We need to swap the inbound/outbound properties since `tryExtractParameters` thinks we're
4731 // parsing as the server (`isAgreement` is false).
4732 auto tempCtx = validated->inboundNoContextTakeover;
4733 validated->inboundNoContextTakeover = validated->outboundNoContextTakeover;
4734 validated->outboundNoContextTakeover = tempCtx;
4735 auto tempWindow = validated->inboundMaxWindowBits;
4736 validated->inboundMaxWindowBits = validated->outboundMaxWindowBits;
4737 validated->outboundMaxWindowBits = tempWindow;
4738 result.add(kj::mv(*validated));
4739 }
4740 }
4741
4742 return kj::mv(result);
4743 }
4744
4745 kj::String generateExtensionRequest(const ArrayPtr<CompressionParameters>& extensions) {
4746 // Build the `Sec-WebSocket-Extensions` request from the validated parameters.
4747 constexpr auto EXT = "permessage-deflate"_kj;
4748 auto offers = kj::heapArray<String>(extensions.size());
4749 size_t i = 0;
4750 for (const auto& offer : extensions) {
4751 offers[i] = kj::str(EXT);
4752 if (offer.outboundNoContextTakeover) {
4753 offers[i] = kj::str(offers[i], "; client_no_context_takeover");
4754 }
4755 if (offer.inboundNoContextTakeover) {
4756 offers[i] = kj::str(offers[i], "; server_no_context_takeover");
4757 }
4758 if (offer.outboundMaxWindowBits != nullptr) {
4759 auto w = KJ_ASSERT_NONNULL(offer.outboundMaxWindowBits);
4760 offers[i] = kj::str(offers[i], "; client_max_window_bits=", w);
4761 }
4762 if (offer.inboundMaxWindowBits != nullptr) {
4763 auto w = KJ_ASSERT_NONNULL(offer.inboundMaxWindowBits);
4764 offers[i] = kj::str(offers[i], "; server_max_window_bits=", w);
4765 }
4766 ++i;
4767 }
4768 return kj::strArray(offers, ", ");
4769 }
4770
4771 kj::Maybe<CompressionParameters> tryParseExtensionOffers(StringPtr offers) {
4772 // Given a string of offers, accept the first valid offer by returning a `CompressionParameters`
4773 // struct. If there are no valid offers, return `nullptr`.
4774 auto splitOffers = splitParts(offers, ',');
4775
4776 for (const auto& offer : splitOffers) {
4777 auto splitOffer = splitParts(offer, ';');
4778
4779 if (splitOffer.front() != "permessage-deflate"_kj) {
4780 // Extension token was invalid.
4781 continue;
4782 }
4783 KJ_IF_MAYBE(config, tryExtractParameters(splitOffer, false)) {
4784 return kj::mv(*config);
4785 }
4786 }
4787 return nullptr;
4788 }
4789
4790 kj::Maybe<CompressionParameters> tryParseAllExtensionOffers(StringPtr offers,
4791 CompressionParameters manualConfig) {
4792 // Similar to `tryParseExtensionOffers()`, however, this function is called when parsing in
4793 // `MANUAL_COMPRESSION` mode. In some cases, the server's configuration might not support the
4794 // `server_no_context_takeover` or `server_max_window_bits` parameters. Essentially, this function
4795 // will look at all the client's offers, and accept the first one that it can support.
4796 //
4797 // We differentiate these functions because in `AUTOMATIC_COMPRESSION` mode, KJ can support these
4798 // server restricting compression parameters.
4799 auto splitOffers = splitParts(offers, ',');
4800
4801 for (const auto& offer : splitOffers) {
4802 auto splitOffer = splitParts(offer, ';');
4803
4804 if (splitOffer.front() != "permessage-deflate"_kj) {
4805 // Extension token was invalid.
4806 continue;
4807 }
4808 KJ_IF_MAYBE(config, tryExtractParameters(splitOffer, false)) {
4809 KJ_IF_MAYBE(finalConfig, compareClientAndServerConfigs(*config, manualConfig)) {
4810 // Found a compatible configuration between the server's config and client's offer.
4811 return kj::mv(*finalConfig);
4812 }
4813 }
4814 }
4815 return nullptr;
4816 }
4817
4818 kj::Maybe<CompressionParameters> compareClientAndServerConfigs(CompressionParameters requestConfig,
4819 CompressionParameters manualConfig) {
4820 // We start from the `manualConfig` and go through a series of filters to get a compression
4821 // configuration that both the client and the server can agree upon. If no agreement can be made,
4822 // we return null.
4823
4824 CompressionParameters acceptedParameters = manualConfig;
4825
4826 // We only need to modify `client_no_context_takeover` and `server_no_context_takeover` when
4827 // `manualConfig` doesn't include them.
4828 if (manualConfig.inboundNoContextTakeover == false) {
4829 acceptedParameters.inboundNoContextTakeover = false;
4830 }
4831
4832 if (manualConfig.outboundNoContextTakeover == false) {
4833 acceptedParameters.outboundNoContextTakeover = false;
4834 if (requestConfig.outboundNoContextTakeover == true) {
4835 // The client has told the server to not use context takeover. This is not a "hint",
4836 // rather it is a restriction on the server's configuration. If the server does not support
4837 // the configuration, it must reject the offer.
4838 return nullptr;
4839 }
4840 }
4841
4842 // client_max_window_bits
4843 if (requestConfig.inboundMaxWindowBits != nullptr &&
4844 manualConfig.inboundMaxWindowBits != nullptr) {
4845 // We want `min(requestConfig, manualConfig)` in this case.
4846 auto reqBits = KJ_ASSERT_NONNULL(requestConfig.inboundMaxWindowBits);
4847 auto manualBits = KJ_ASSERT_NONNULL(manualConfig.inboundMaxWindowBits);
4848 if (reqBits < manualBits) {
4849 acceptedParameters.inboundMaxWindowBits = reqBits;
4850 }
4851 } else {
4852 // We will not reply with `client_max_window_bits`.
4853 acceptedParameters.inboundMaxWindowBits = nullptr;
4854 }
4855
4856 // server_max_window_bits
4857 if (manualConfig.outboundMaxWindowBits != nullptr) {
4858 auto manualBits = KJ_ASSERT_NONNULL(manualConfig.outboundMaxWindowBits);
4859 if (requestConfig.outboundMaxWindowBits != nullptr) {
4860 // We want `min(requestConfig, manualConfig)` in this case.
4861 auto reqBits = KJ_ASSERT_NONNULL(requestConfig.outboundMaxWindowBits);
4862 if (reqBits < manualBits) {
4863 acceptedParameters.outboundMaxWindowBits = reqBits;
4864 }
4865 }
4866 } else {
4867 acceptedParameters.outboundMaxWindowBits = nullptr;
4868 if (requestConfig.outboundMaxWindowBits != nullptr) {
4869 // The client has told the server to use `server_max_window_bits`. This is not a "hint",
4870 // rather it is a restriction on the server's configuration. If the server does not support
4871 // the configuration, it must reject the offer.
4872 return nullptr;
4873 }
4874 }
4875 return acceptedParameters;
4876 }
4877
4878 kj::String generateExtensionResponse(const CompressionParameters& parameters) {
4879 // Build the `Sec-WebSocket-Extensions` response from the agreed parameters.
4880 kj::String response = kj::str("permessage-deflate");
4881 if (parameters.inboundNoContextTakeover) {
4882 response = kj::str(response, "; client_no_context_takeover");
4883 }
4884 if (parameters.outboundNoContextTakeover) {
4885 response = kj::str(response, "; server_no_context_takeover");
4886 }
4887 if (parameters.inboundMaxWindowBits != nullptr) {
4888 auto w = KJ_REQUIRE_NONNULL(parameters.inboundMaxWindowBits);
4889 response = kj::str(response, "; client_max_window_bits=", w);
4890 }
4891 if (parameters.outboundMaxWindowBits != nullptr) {
4892 auto w = KJ_REQUIRE_NONNULL(parameters.outboundMaxWindowBits);
4893 response = kj::str(response, "; server_max_window_bits=", w);
4894 }
4895 return kj::mv(response);
4896 }
4897
4898 kj::OneOf<CompressionParameters, kj::Exception> tryParseExtensionAgreement(
4899 const Maybe<CompressionParameters>& clientOffer,
4900 StringPtr agreedParameters) {
4901 // Like `tryParseExtensionOffers`, but called by the client when parsing the server's Response.
4902 // If the client must decline the agreement, we want to provide some details about what went wrong
4903 // (since the client has to fail the connection).
4904 constexpr auto FAILURE = "Server failed WebSocket handshake: "_kj;
4905 auto e = KJ_EXCEPTION(FAILED);
4906
4907 if (clientOffer == nullptr) {
4908 // We've received extensions when we did not send any in the first place.
4909 e.setDescription(
4910 kj::str(FAILURE, "added Sec-WebSocket-Extensions when client did not offer any."));
4911 return kj::mv(e);
4912 }
4913
4914 auto offers = splitParts(agreedParameters, ',');
4915 if (offers.size() != 1) {
4916 constexpr auto EXPECT = "expected exactly one extension (permessage-deflate) but received "
4917 "more than one."_kj;
4918 e.setDescription(kj::str(FAILURE, EXPECT));
4919 return kj::mv(e);
4920 }
4921 auto splitOffer = splitParts(offers.front(), ';');
4922
4923 if (splitOffer.front() != "permessage-deflate"_kj) {
4924 e.setDescription(kj::str(FAILURE, "response included a Sec-WebSocket-Extensions value that was "
4925 "not permessage-deflate."));
4926 return kj::mv(e);
4927 }
4928
4929 // Verify the parameters of our single extension, and compare it with the clients original offer.
4930 KJ_IF_MAYBE(config, tryExtractParameters(splitOffer, true)) {
4931 const auto& client = KJ_ASSERT_NONNULL(clientOffer);
4932 // The server might have ignored the client's hints regarding its compressor's configuration.
4933 // That's fine, but as the client, we still want to use those outbound compression parameters.
4934 if (config->outboundMaxWindowBits == nullptr) {
4935 config->outboundMaxWindowBits = client.outboundMaxWindowBits;
4936 } else KJ_IF_MAYBE(value, client.outboundMaxWindowBits) {
4937 if (*value < KJ_ASSERT_NONNULL(config->outboundMaxWindowBits)) {
4938 // If the client asked for a value smaller than what the server responded with, use the
4939 // value that the client originally specified.
4940 config->outboundMaxWindowBits = *value;
4941 }
4942 }
4943 if (config->outboundNoContextTakeover == false) {
4944 config->outboundNoContextTakeover = client.outboundNoContextTakeover;
4945 }
4946 return kj::mv(*config);
4947 }
4948
4949 // There was a problem parsing the server's `Sec-WebSocket-Extensions` response.
4950 e.setDescription(kj::str(FAILURE, "the Sec-WebSocket-Extensions header in the Response included "
4951 "an invalid value."));
4952 return kj::mv(e);
4953 }
4954 } // namespace _ (private)
4955 namespace {
4956 class NullInputStream final: public kj::AsyncInputStream {
4957 public:
4958 NullInputStream(kj::Maybe<size_t> expectedLength = size_t(0))
4959 : expectedLength(expectedLength) {}
4960
4961 kj::Promise<size_t> tryRead(void* buffer, size_t minBytes, size_t maxBytes) override {
4962 return constPromise<size_t, 0>();
4963 }
4964
4965 kj::Maybe<uint64_t> tryGetLength() override {
4966 return expectedLength;
4967 }
4968
4969 kj::Promise<uint64_t> pumpTo(AsyncOutputStream& output, uint64_t amount) override {
4970 return constPromise<uint64_t, 0>();
4971 }
4972
4973 private:
4974 kj::Maybe<size_t> expectedLength;
4975 };
4976
4977 class NullOutputStream final: public kj::AsyncOutputStream {
4978 public:
4979 Promise<void> write(const void* buffer, size_t size) override {
4980 return kj::READY_NOW;
4981 }
4982 Promise<void> write(ArrayPtr<const ArrayPtr<const byte>> pieces) override {
4983 return kj::READY_NOW;
4984 }
4985 Promise<void> whenWriteDisconnected() override {
4986 return kj::NEVER_DONE;
4987 }
4988
4989 // We can't really optimize tryPumpFrom() unless AsyncInputStream grows a skip() method.
4990 };
4991
4992 class NullIoStream final: public kj::AsyncIoStream {
4993 public:
4994 void shutdownWrite() override {}
4995
4996 Promise<void> write(const void* buffer, size_t size) override {
4997 return kj::READY_NOW;
4998 }
4999 Promise<void> write(ArrayPtr<const ArrayPtr<const byte>> pieces) override {
5000 return kj::READY_NOW;
5001 }
5002 Promise<void> whenWriteDisconnected() override {
5003 return kj::NEVER_DONE;
5004 }
5005
5006 kj::Promise<size_t> tryRead(void* buffer, size_t minBytes, size_t maxBytes) override {
5007 return constPromise<size_t, 0>();
5008 }
5009
5010 kj::Maybe<uint64_t> tryGetLength() override {
5011 return kj::Maybe<uint64_t>((uint64_t)0);
5012 }
5013
5014 kj::Promise<uint64_t> pumpTo(AsyncOutputStream& output, uint64_t amount) override {
5015 return constPromise<uint64_t, 0>();
5016 }
5017 };
5018
5019 class HttpClientImpl final: public HttpClient,
5020 private HttpClientErrorHandler {
5021 public:
5022 HttpClientImpl(const HttpHeaderTable& responseHeaderTable, kj::Own<kj::AsyncIoStream> rawStream,
5023 HttpClientSettings settings)
5024 : httpInput(*rawStream, responseHeaderTable),
5025 httpOutput(*rawStream),
5026 ownStream(kj::mv(rawStream)),
5027 settings(kj::mv(settings)) {}
5028
5029 bool canReuse() {
5030 // Returns true if we can immediately reuse this HttpClient for another message (so all
5031 // previous messages have been fully read).
5032
5033 return !upgraded && !closed && httpInput.canReuse() && httpOutput.canReuse();
5034 }
5035
5036 Request request(HttpMethod method, kj::StringPtr url, const HttpHeaders& headers,
5037 kj::Maybe<uint64_t> expectedBodySize = nullptr) override {
5038 KJ_REQUIRE(!upgraded,
5039 "can't make further requests on this HttpClient because it has been or is in the process "
5040 "of being upgraded");
5041 KJ_REQUIRE(!closed,
5042 "this HttpClient's connection has been closed by the server or due to an error");
5043 KJ_REQUIRE(httpOutput.canReuse(),
5044 "can't start new request until previous request body has been fully written");
5045 closeWatcherTask = nullptr;
5046
5047 kj::StringPtr connectionHeaders[HttpHeaders::CONNECTION_HEADERS_COUNT];
5048 kj::String lengthStr;
5049
5050 bool isGet = method == HttpMethod::GET || method == HttpMethod::HEAD;
5051 bool hasBody;
5052
5053 KJ_IF_MAYBE(s, expectedBodySize) {
5054 if (isGet && *s == 0) {
5055 // GET with empty body; don't send any Content-Length.
5056 hasBody = false;
5057 } else {
5058 lengthStr = kj::str(*s);
5059 connectionHeaders[HttpHeaders::BuiltinIndices::CONTENT_LENGTH] = lengthStr;
5060 hasBody = true;
5061 }
5062 } else {
5063 if (isGet && headers.get(HttpHeaderId::TRANSFER_ENCODING) == nullptr) {
5064 // GET with empty body; don't send any Transfer-Encoding.
5065 hasBody = false;
5066 } else {
5067 // HACK: Normally GET requests shouldn't have bodies. But, if the caller set a
5068 // Transfer-Encoding header on a GET, we use this as a special signal that it might
5069 // actually want to send a body. This allows pass-through of a GET request with a chunked
5070 // body to "just work". We strongly discourage writing any new code that sends
5071 // full-bodied GETs.
5072 connectionHeaders[HttpHeaders::BuiltinIndices::TRANSFER_ENCODING] = "chunked";
5073 hasBody = true;
5074 }
5075 }
5076
5077 httpOutput.writeHeaders(headers.serializeRequest(method, url, connectionHeaders));
5078
5079 kj::Own<kj::AsyncOutputStream> bodyStream;
5080 if (!hasBody) {
5081 // No entity-body.
5082 httpOutput.finishBody();
5083 bodyStream = heap<HttpNullEntityWriter>();
5084 } else KJ_IF_MAYBE(s, expectedBodySize) {
5085 bodyStream = heap<HttpFixedLengthEntityWriter>(httpOutput, *s);
5086 } else {
5087 bodyStream = heap<HttpChunkedEntityWriter>(httpOutput);
5088 }
5089
5090 auto id = ++counter;
5091
5092 auto responsePromise = httpInput.readResponseHeaders().then(
5093 [this,method,id](HttpHeaders::ResponseOrProtocolError&& responseOrProtocolError)
5094 -> HttpClient::Response {
5095 KJ_SWITCH_ONEOF(responseOrProtocolError) {
5096 KJ_CASE_ONEOF(response, HttpHeaders::Response) {
5097 auto& responseHeaders = httpInput.getHeaders();
5098 HttpClient::Response result {
5099 response.statusCode,
5100 response.statusText,
5101 &responseHeaders,
5102 httpInput.getEntityBody(
5103 HttpInputStreamImpl::RESPONSE, method, response.statusCode, responseHeaders)
5104 };
5105
5106 if (fastCaseCmp<'c', 'l', 'o', 's', 'e'>(
5107 responseHeaders.get(HttpHeaderId::CONNECTION).orDefault(nullptr).cStr())) {
5108 closed = true;
5109 } else if (counter == id) {
5110 watchForClose();
5111 } else {
5112 // Another request was already queued after this one, so we don't want to watch for
5113 // stream closure because we're fully expecting another response.
5114 }
5115 return result;
5116 }
5117 KJ_CASE_ONEOF(protocolError, HttpHeaders::ProtocolError) {
5118 closed = true;
5119 return settings.errorHandler.orDefault(*this).handleProtocolError(
5120 kj::mv(protocolError));
5121 }
5122 }
5123
5124 KJ_UNREACHABLE;
5125 });
5126
5127 return { kj::mv(bodyStream), kj::mv(responsePromise) };
5128 }
5129
5130 kj::Promise<WebSocketResponse> openWebSocket(
5131 kj::StringPtr url, const HttpHeaders& headers) override {
5132 KJ_REQUIRE(!upgraded,
5133 "can't make further requests on this HttpClient because it has been or is in the process "
5134 "of being upgraded");
5135 KJ_REQUIRE(!closed,
5136 "this HttpClient's connection has been closed by the server or due to an error");
5137 closeWatcherTask = nullptr;
5138
5139 // Mark upgraded for now, even though the upgrade could fail, because we can't allow pipelined
5140 // requests in the meantime.
5141 upgraded = true;
5142
5143 byte keyBytes[16];
5144 KJ_ASSERT_NONNULL(settings.entropySource,
5145 "can't use openWebSocket() because no EntropySource was provided when creating the "
5146 "HttpClient").generate(keyBytes);
5147 auto keyBase64 = kj::encodeBase64(keyBytes);
5148
5149 kj::StringPtr connectionHeaders[HttpHeaders::WEBSOCKET_CONNECTION_HEADERS_COUNT];
5150 connectionHeaders[HttpHeaders::BuiltinIndices::CONNECTION] = "Upgrade";
5151 connectionHeaders[HttpHeaders::BuiltinIndices::UPGRADE] = "websocket";
5152 connectionHeaders[HttpHeaders::BuiltinIndices::SEC_WEBSOCKET_VERSION] = "13";
5153 connectionHeaders[HttpHeaders::BuiltinIndices::SEC_WEBSOCKET_KEY] = keyBase64;
5154
5155 kj::Maybe<kj::String> offeredExtensions;
5156 kj::Maybe<CompressionParameters> clientOffer;
5157 kj::Vector<CompressionParameters> extensions;
5158 auto compressionMode = settings.webSocketCompressionMode;
5159
5160 if (compressionMode == HttpClientSettings::MANUAL_COMPRESSION) {
5161 KJ_IF_MAYBE(value, headers.get(HttpHeaderId::SEC_WEBSOCKET_EXTENSIONS)) {
5162 // Strip all `Sec-WebSocket-Extensions` except for `permessage-deflate`.
5163 extensions = _::findValidExtensionOffers(*value);
5164 }
5165 } else if (compressionMode == HttpClientSettings::AUTOMATIC_COMPRESSION) {
5166 // If AUTOMATIC_COMPRESSION is enabled, we send `Sec-WebSocket-Extensions: permessage-deflate`
5167 // to the server and ignore the `headers` provided by the caller.
5168 extensions.add(CompressionParameters());
5169 }
5170
5171 if (extensions.size() > 0) {
5172 clientOffer = extensions.front();
5173 // We hold on to a copy of the client's most preferred offer so even if the server
5174 // ignores `client_no_context_takeover` or `client_max_window_bits`, we can still refer to
5175 // the original offer made by the client (thereby allowing the client to use these parameters).
5176 //
5177 // It's safe to ignore the remaining offers because:
5178 // 1. Offers are ordered by preference.
5179 // 2. `client_x` parameters are hints to the server and do not result in rejections, so the
5180 // client is likely to put them in every offer anyways.
5181 connectionHeaders[HttpHeaders::BuiltinIndices::SEC_WEBSOCKET_EXTENSIONS] =
5182 offeredExtensions.emplace(_::generateExtensionRequest(extensions.asPtr()));
5183 }
5184
5185 httpOutput.writeHeaders(headers.serializeRequest(HttpMethod::GET, url, connectionHeaders));
5186
5187 // No entity-body.
5188 httpOutput.finishBody();
5189
5190 auto id = ++counter;
5191
5192 return httpInput.readResponseHeaders()
5193 .then([this,id,keyBase64 = kj::mv(keyBase64),clientOffer = kj::mv(clientOffer)](
5194 HttpHeaders::ResponseOrProtocolError&& responseOrProtocolError)
5195 -> HttpClient::WebSocketResponse {
5196 KJ_SWITCH_ONEOF(responseOrProtocolError) {
5197 KJ_CASE_ONEOF(response, HttpHeaders::Response) {
5198 auto& responseHeaders = httpInput.getHeaders();
5199 if (response.statusCode == 101) {
5200 if (!fastCaseCmp<'w', 'e', 'b', 's', 'o', 'c', 'k', 'e', 't'>(
5201 responseHeaders.get(HttpHeaderId::UPGRADE).orDefault(nullptr).cStr())) {
5202 kj::String ownMessage;
5203 kj::StringPtr message;
5204 KJ_IF_MAYBE(actual, responseHeaders.get(HttpHeaderId::UPGRADE)) {
5205 ownMessage = kj::str(
5206 "Server failed WebSocket handshake: incorrect Upgrade header: "
5207 "expected 'websocket', got '", *actual, "'.");
5208 message = ownMessage;
5209 } else {
5210 message = "Server failed WebSocket handshake: missing Upgrade header.";
5211 }
5212 return settings.errorHandler.orDefault(*this).handleWebSocketProtocolError({
5213 502, "Bad Gateway", message, nullptr
5214 });
5215 }
5216
5217 auto expectedAccept = generateWebSocketAccept(keyBase64);
5218 if (responseHeaders.get(HttpHeaderId::SEC_WEBSOCKET_ACCEPT).orDefault(nullptr)
5219 != expectedAccept) {
5220 kj::String ownMessage;
5221 kj::StringPtr message;
5222 KJ_IF_MAYBE(actual, responseHeaders.get(HttpHeaderId::SEC_WEBSOCKET_ACCEPT)) {
5223 ownMessage = kj::str(
5224 "Server failed WebSocket handshake: incorrect Sec-WebSocket-Accept header: "
5225 "expected '", expectedAccept, "', got '", *actual, "'.");
5226 message = ownMessage;
5227 } else {
5228 message = "Server failed WebSocket handshake: missing Upgrade header.";
5229 }
5230 return settings.errorHandler.orDefault(*this).handleWebSocketProtocolError({
5231 502, "Bad Gateway", message, nullptr
5232 });
5233 }
5234
5235 kj::Maybe<CompressionParameters> compressionParameters;
5236 if (settings.webSocketCompressionMode != HttpClientSettings::NO_COMPRESSION) {
5237 KJ_IF_MAYBE(agreedParameters, responseHeaders.get(
5238 HttpHeaderId::SEC_WEBSOCKET_EXTENSIONS)) {
5239
5240 auto parseResult = _::tryParseExtensionAgreement(clientOffer,
5241 *agreedParameters);
5242 if (parseResult.is<kj::Exception>()) {
5243 return settings.errorHandler.orDefault(*this).handleWebSocketProtocolError({
5244 502, "Bad Gateway", parseResult.get<kj::Exception>().getDescription(), nullptr});
5245 }
5246 compressionParameters.emplace(kj::mv(parseResult.get<CompressionParameters>()));
5247 }
5248 }
5249
5250 return {
5251 response.statusCode,
5252 response.statusText,
5253 &httpInput.getHeaders(),
5254 upgradeToWebSocket(kj::mv(ownStream), httpInput, httpOutput, settings.entropySource,
5255 kj::mv(compressionParameters)),
5256 };
5257 } else {
5258 upgraded = false;
5259 HttpClient::WebSocketResponse result {
5260 response.statusCode,
5261 response.statusText,
5262 &responseHeaders,
5263 httpInput.getEntityBody(HttpInputStreamImpl::RESPONSE, HttpMethod::GET,
5264 response.statusCode, responseHeaders)
5265 };
5266 if (fastCaseCmp<'c', 'l', 'o', 's', 'e'>(
5267 responseHeaders.get(HttpHeaderId::CONNECTION).orDefault(nullptr).cStr())) {
5268 closed = true;
5269 } else if (counter == id) {
5270 watchForClose();
5271 } else {
5272 // Another request was already queued after this one, so we don't want to watch for
5273 // stream closure because we're fully expecting another response.
5274 }
5275 return result;
5276 }
5277 }
5278 KJ_CASE_ONEOF(protocolError, HttpHeaders::ProtocolError) {
5279 return settings.errorHandler.orDefault(*this).handleWebSocketProtocolError(
5280 kj::mv(protocolError));
5281 }
5282 }
5283
5284 KJ_UNREACHABLE;
5285 });
5286 }
5287
5288 ConnectRequest connect(
5289 kj::StringPtr host, const HttpHeaders& headers, HttpConnectSettings settings) override {
5290 KJ_REQUIRE(!upgraded,
5291 "can't make further requests on this HttpClient because it has been or is in the process "
5292 "of being upgraded");
5293 KJ_REQUIRE(!closed,
5294 "this HttpClient's connection has been closed by the server or due to an error");
5295 KJ_REQUIRE(httpOutput.canReuse(),
5296 "can't start new request until previous request body has been fully written");
5297
5298 if (settings.useTls) {
5299 KJ_UNIMPLEMENTED("This HttpClient does not support TLS.");
5300 }
5301
5302 closeWatcherTask = nullptr;
5303
5304 // Mark upgraded for now even though the tunnel could fail, because we can't allow pipelined
5305 // requests in the meantime.
5306 upgraded = true;
5307
5308 kj::StringPtr connectionHeaders[HttpHeaders::CONNECTION_HEADERS_COUNT];
5309
5310 httpOutput.writeHeaders(headers.serializeConnectRequest(host, connectionHeaders));
5311
5312 auto id = ++counter;
5313
5314 auto split = httpInput.readResponseHeaders().then(
5315 [this, id](HttpHeaders::ResponseOrProtocolError&& responseOrProtocolError) mutable
5316 -> kj::Tuple<kj::Promise<ConnectRequest::Status>,
5317 kj::Promise<kj::Maybe<HttpInputStreamImpl::ReleasedBuffer>>> {
5318 KJ_SWITCH_ONEOF(responseOrProtocolError) {
5319 KJ_CASE_ONEOF(response, HttpHeaders::Response) {
5320 auto& responseHeaders = httpInput.getHeaders();
5321 if (response.statusCode < 200 || response.statusCode >= 300) {
5322 // Any statusCode that is not in the 2xx range in interpreted
5323 // as an HTTP response. Any status code in the 2xx range is
5324 // interpreted as a successful CONNECT response.
5325 closed = true;
5326 return kj::tuple(ConnectRequest::Status(
5327 response.statusCode,
5328 kj::str(response.statusText),
5329 kj::heap(responseHeaders.clone()),
5330 httpInput.getEntityBody(
5331 HttpInputStreamImpl::RESPONSE,
5332 HttpConnectMethod(),
5333 response.statusCode,
5334 responseHeaders)),
5335 KJ_EXCEPTION(DISCONNECTED, "the connect request was rejected"));
5336 }
5337 KJ_ASSERT(counter == id);
5338 return kj::tuple(ConnectRequest::Status(
5339 response.statusCode,
5340 kj::str(response.statusText),
5341 kj::heap(responseHeaders.clone())
5342 ), kj::Maybe<HttpInputStreamImpl::ReleasedBuffer>(httpInput.releaseBuffer()));
5343 }
5344 KJ_CASE_ONEOF(protocolError, HttpHeaders::ProtocolError) {
5345 closed = true;
5346 auto response = handleProtocolError(protocolError);
5347 return kj::tuple(ConnectRequest::Status(
5348 response.statusCode,
5349 kj::str(response.statusText),
5350 kj::heap(response.headers->clone()),
5351 kj::mv(response.body)
5352 ), KJ_EXCEPTION(DISCONNECTED, "the connect request errored"));
5353 }
5354 }
5355 KJ_UNREACHABLE;
5356 }).split();
5357
5358 return ConnectRequest {
5359 kj::mv(kj::get<0>(split)), // Promise for the result
5360 heap<AsyncIoStreamWithGuards>(
5361 kj::mv(ownStream),
5362 kj::mv(kj::get<1>(split)) /* read guard (Promise for the ReleasedBuffer) */,
5363 httpOutput.flush() /* write guard (void Promise) */)
5364 };
5365 }
5366
5367 private:
5368 HttpInputStreamImpl httpInput;
5369 HttpOutputStream httpOutput;
5370 kj::Own<AsyncIoStream> ownStream;
5371 HttpClientSettings settings;
5372 kj::Maybe<kj::Promise<void>> closeWatcherTask;
5373 bool upgraded = false;
5374 bool closed = false;
5375
5376 uint counter = 0;
5377 // Counts requests for the sole purpose of detecting if more requests have been made after some
5378 // point in history.
5379
5380 void watchForClose() {
5381 closeWatcherTask = httpInput.awaitNextMessage()
5382 .then([this](bool hasData) -> kj::Promise<void> {
5383 if (hasData) {
5384 // Uhh... The server sent some data before we asked for anything. Perhaps due to properties
5385 // of this application, the server somehow already knows what the next request will be, and
5386 // it is trying to optimize. Or maybe this is some sort of test and the server is just
5387 // replaying a script. In any case, we will humor it -- leave the data in the buffer and
5388 // let it become the response to the next request.
5389 return kj::READY_NOW;
5390 } else {
5391 // EOF -- server disconnected.
5392 closed = true;
5393 if (httpOutput.isInBody()) {
5394 // Huh, the application is still sending a request. We should let it finish. We do not
5395 // need to proactively free the socket in this case because we know that we're not
5396 // sitting in a reusable connection pool, because we know the application is still
5397 // actively using the connection.
5398 return kj::READY_NOW;
5399 } else {
5400 return httpOutput.flush().then([this]() {
5401 // We might be sitting in NetworkAddressHttpClient's `availableClients` pool. We don't
5402 // have a way to notify it to remove this client from the pool; instead, when it tries
5403 // to pull this client from the pool later, it will notice the client is dead and will
5404 // discard it then. But, we would like to avoid holding on to a socket forever. So,
5405 // destroy the socket now.
5406 // TODO(cleanup): Maybe we should arrange to proactively remove ourselves? Seems
5407 // like the code will be awkward.
5408 ownStream = nullptr;
5409 });
5410 }
5411 }
5412 }).eagerlyEvaluate(nullptr);
5413 }
5414 };
5415
5416 } // namespace
5417
5418 kj::Promise<HttpClient::WebSocketResponse> HttpClient::openWebSocket(
5419 kj::StringPtr url, const HttpHeaders& headers) {
5420 return request(HttpMethod::GET, url, headers, nullptr)
5421 .response.then([](HttpClient::Response&& response) -> WebSocketResponse {
5422 kj::OneOf<kj::Own<kj::AsyncInputStream>, kj::Own<WebSocket>> body;
5423 body.init<kj::Own<kj::AsyncInputStream>>(kj::mv(response.body));
5424
5425 return {
5426 response.statusCode,
5427 response.statusText,
5428 response.headers,
5429 kj::mv(body)
5430 };
5431 });
5432 }
5433
5434 HttpClient::ConnectRequest HttpClient::connect(
5435 kj::StringPtr host, const HttpHeaders& headers, HttpConnectSettings settings) {
5436 KJ_UNIMPLEMENTED("CONNECT is not implemented by this HttpClient");
5437 }
5438
5439 kj::Own<HttpClient> newHttpClient(
5440 const HttpHeaderTable& responseHeaderTable, kj::AsyncIoStream& stream,
5441 HttpClientSettings settings) {
5442 return kj::heap<HttpClientImpl>(responseHeaderTable,
5443 kj::Own<kj::AsyncIoStream>(&stream, kj::NullDisposer::instance),
5444 kj::mv(settings));
5445 }
5446
5447 HttpClient::Response HttpClientErrorHandler::handleProtocolError(
5448 HttpHeaders::ProtocolError protocolError) {
5449 KJ_FAIL_REQUIRE(protocolError.description) { break; }
5450 return HttpClient::Response();
5451 }
5452
5453 HttpClient::WebSocketResponse HttpClientErrorHandler::handleWebSocketProtocolError(
5454 HttpHeaders::ProtocolError protocolError) {
5455 auto response = handleProtocolError(protocolError);
5456 return HttpClient::WebSocketResponse {
5457 response.statusCode, response.statusText, response.headers, kj::mv(response.body)
5458 };
5459 }
5460
5461 kj::Exception WebSocketErrorHandler::handleWebSocketProtocolError(
5462 WebSocket::ProtocolError protocolError) {
5463 return KJ_EXCEPTION(FAILED, "WebSocket protocol error", protocolError.statusCode, protocolError.description);
5464 }
5465
5466 class PausableReadAsyncIoStream::PausableRead {
5467 public:
5468 PausableRead(
5469 kj::PromiseFulfiller<size_t>& fulfiller, PausableReadAsyncIoStream& parent,
5470 void* buffer, size_t minBytes, size_t maxBytes)
5471 : fulfiller(fulfiller), parent(parent),
5472 operationBuffer(buffer), operationMinBytes(minBytes), operationMaxBytes(maxBytes),
5473 innerRead(parent.tryReadImpl(operationBuffer, operationMinBytes, operationMaxBytes).then(
5474 [&fulfiller](size_t size) mutable -> kj::Promise<void> {
5475 fulfiller.fulfill(kj::mv(size));
5476 return kj::READY_NOW;
5477 }, [&fulfiller](kj::Exception&& err) {
5478 fulfiller.reject(kj::mv(err));
5479 })) {
5480 KJ_ASSERT(parent.maybePausableRead == nullptr);
5481 parent.maybePausableRead = *this;
5482 }
5483
5484 ~PausableRead() noexcept(false) {
5485 parent.maybePausableRead = nullptr;
5486 }
5487
5488 void pause() {
5489 innerRead = nullptr;
5490 }
5491
5492 void unpause() {
5493 innerRead = parent.tryReadImpl(operationBuffer, operationMinBytes, operationMaxBytes).then(
5494 [this](size_t size) -> kj::Promise<void> {
5495 fulfiller.fulfill(kj::mv(size));
5496 return kj::READY_NOW;
5497 }, [this](kj::Exception&& err) {
5498 fulfiller.reject(kj::mv(err));
5499 });
5500 }
5501
5502 void reject(kj::Exception&& exc) {
5503 fulfiller.reject(kj::mv(exc));
5504 }
5505 private:
5506 kj::PromiseFulfiller<size_t>& fulfiller;
5507 PausableReadAsyncIoStream& parent;
5508
5509 void* operationBuffer;
5510 size_t operationMinBytes;
5511 size_t operationMaxBytes;
5512 // The parameters of the current tryRead call. Used to unpause a paused read.
5513
5514 kj::Promise<void> innerRead;
5515 // The current pending read.
5516 };
5517
5518 _::Deferred<kj::Function<void()>> PausableReadAsyncIoStream::trackRead() {
5519 KJ_REQUIRE(!currentlyReading, "only one read is allowed at any one time");
5520 currentlyReading = true;
5521 return kj::defer<kj::Function<void()>>([this]() { currentlyReading = false; });
5522 }
5523
5524 _::Deferred<kj::Function<void()>> PausableReadAsyncIoStream::trackWrite() {
5525 KJ_REQUIRE(!currentlyWriting, "only one write is allowed at any one time");
5526 currentlyWriting = true;
5527 return kj::defer<kj::Function<void()>>([this]() { currentlyWriting = false; });
5528 }
5529
5530 kj::Promise<size_t> PausableReadAsyncIoStream::tryRead(
5531 void* buffer, size_t minBytes, size_t maxBytes) {
5532 return kj::newAdaptedPromise<size_t, PausableRead>(*this, buffer, minBytes, maxBytes);
5533 }
5534
5535 kj::Promise<size_t> PausableReadAsyncIoStream::tryReadImpl(
5536 void* buffer, size_t minBytes, size_t maxBytes) {
5537 // Hack: evalNow used here because `newAdaptedPromise` has a bug. We may need to change
5538 // `PromiseDisposer::alloc` to not be `noexcept` but in order to do so we'll need to benchmark
5539 // its performance.
5540 return kj::evalNow([&]() -> kj::Promise<size_t> {
5541 return inner->tryRead(buffer, minBytes, maxBytes).attach(trackRead());
5542 });
5543 }
5544
5545 kj::Maybe<uint64_t> PausableReadAsyncIoStream::tryGetLength() {
5546 return inner->tryGetLength();
5547 }
5548
5549 kj::Promise<uint64_t> PausableReadAsyncIoStream::pumpTo(
5550 kj::AsyncOutputStream& output, uint64_t amount) {
5551 return kj::unoptimizedPumpTo(*this, output, amount);
5552 }
5553
5554 kj::Promise<void> PausableReadAsyncIoStream::write(const void* buffer, size_t size) {
5555 return inner->write(buffer, size).attach(trackWrite());
5556 }
5557
5558 kj::Promise<void> PausableReadAsyncIoStream::write(
5559 kj::ArrayPtr<const kj::ArrayPtr<const byte>> pieces) {
5560 return inner->write(pieces).attach(trackWrite());
5561 }
5562
5563 kj::Maybe<kj::Promise<uint64_t>> PausableReadAsyncIoStream::tryPumpFrom(
5564 kj::AsyncInputStream& input, uint64_t amount) {
5565 auto result = inner->tryPumpFrom(input, amount);
5566 KJ_IF_MAYBE(r, result) {
5567 return r->attach(trackWrite());
5568 } else {
5569 return nullptr;
5570 }
5571 }
5572
5573 kj::Promise<void> PausableReadAsyncIoStream::whenWriteDisconnected() {
5574 return inner->whenWriteDisconnected();
5575 }
5576
5577 void PausableReadAsyncIoStream::shutdownWrite() {
5578 inner->shutdownWrite();
5579 }
5580
5581 void PausableReadAsyncIoStream::abortRead() {
5582 inner->abortRead();
5583 }
5584
5585 kj::Maybe<int> PausableReadAsyncIoStream::getFd() const {
5586 return inner->getFd();
5587 }
5588
5589 void PausableReadAsyncIoStream::pause() {
5590 KJ_IF_MAYBE(pausable, maybePausableRead) {
5591 pausable->pause();
5592 }
5593 }
5594
5595 void PausableReadAsyncIoStream::unpause() {
5596 KJ_IF_MAYBE(pausable, maybePausableRead) {
5597 pausable->unpause();
5598 }
5599 }
5600
5601 bool PausableReadAsyncIoStream::getCurrentlyReading() {
5602 return currentlyReading;
5603 }
5604
5605 bool PausableReadAsyncIoStream::getCurrentlyWriting() {
5606 return currentlyWriting;
5607 }
5608
5609 kj::Own<kj::AsyncIoStream> PausableReadAsyncIoStream::takeStream() {
5610 return kj::mv(inner);
5611 }
5612
5613 void PausableReadAsyncIoStream::replaceStream(kj::Own<kj::AsyncIoStream> stream) {
5614 inner = kj::mv(stream);
5615 }
5616
5617 void PausableReadAsyncIoStream::reject(kj::Exception&& exc) {
5618 KJ_IF_MAYBE(pausable, maybePausableRead) {
5619 pausable->reject(kj::mv(exc));
5620 }
5621 }
5622
5623 // =======================================================================================
5624
5625 namespace {
5626
5627 class NetworkAddressHttpClient final: public HttpClient {
5628 public:
5629 NetworkAddressHttpClient(kj::Timer& timer, const HttpHeaderTable& responseHeaderTable,
5630 kj::Own<kj::NetworkAddress> address, HttpClientSettings settings)
5631 : timer(timer),
5632 responseHeaderTable(responseHeaderTable),
5633 address(kj::mv(address)),
5634 settings(kj::mv(settings)) {}
5635
5636 bool isDrained() {
5637 // Returns true if there are no open connections.
5638 return activeConnectionCount == 0 && availableClients.empty();
5639 }
5640
5641 kj::Promise<void> onDrained() {
5642 // Returns a promise which resolves the next time isDrained() transitions from false to true.
5643 auto paf = kj::newPromiseAndFulfiller<void>();
5644 drainedFulfiller = kj::mv(paf.fulfiller);
5645 return kj::mv(paf.promise);
5646 }
5647
5648 Request request(HttpMethod method, kj::StringPtr url, const HttpHeaders& headers,
5649 kj::Maybe<uint64_t> expectedBodySize = nullptr) override {
5650 auto refcounted = getClient();
5651 auto result = refcounted->client->request(method, url, headers, expectedBodySize);
5652 result.body = result.body.attach(kj::addRef(*refcounted));
5653 result.response = result.response.then(
5654 [refcounted=kj::mv(refcounted)](Response&& response) mutable {
5655 response.body = response.body.attach(kj::mv(refcounted));
5656 return kj::mv(response);
5657 });
5658 return result;
5659 }
5660
5661 kj::Promise<WebSocketResponse> openWebSocket(
5662 kj::StringPtr url, const HttpHeaders& headers) override {
5663 auto refcounted = getClient();
5664 auto result = refcounted->client->openWebSocket(url, headers);
5665 return result.then(
5666 [refcounted=kj::mv(refcounted)](WebSocketResponse&& response) mutable {
5667 KJ_SWITCH_ONEOF(response.webSocketOrBody) {
5668 KJ_CASE_ONEOF(body, kj::Own<kj::AsyncInputStream>) {
5669 response.webSocketOrBody = body.attach(kj::mv(refcounted));
5670 }
5671 KJ_CASE_ONEOF(ws, kj::Own<WebSocket>) {
5672 // The only reason we need to attach the client to the WebSocket is because otherwise
5673 // the response headers will be deleted prematurely. Otherwise, the WebSocket has taken
5674 // ownership of the connection.
5675 //
5676 // TODO(perf): Maybe we could transfer ownership of the response headers specifically?
5677 response.webSocketOrBody = ws.attach(kj::mv(refcounted));
5678 }
5679 }
5680 return kj::mv(response);
5681 });
5682 }
5683
5684 ConnectRequest connect(
5685 kj::StringPtr host, const HttpHeaders& headers, HttpConnectSettings settings) override {
5686 auto refcounted = getClient();
5687 auto request = refcounted->client->connect(host, headers, settings);
5688 return ConnectRequest {
5689 request.status.attach(kj::addRef(*refcounted)),
5690 request.connection.attach(kj::mv(refcounted))
5691 };
5692 }
5693
5694 private:
5695 kj::Timer& timer;
5696 const HttpHeaderTable& responseHeaderTable;
5697 kj::Own<kj::NetworkAddress> address;
5698 HttpClientSettings settings;
5699
5700 kj::Maybe<kj::Own<kj::PromiseFulfiller<void>>> drainedFulfiller;
5701 uint activeConnectionCount = 0;
5702
5703 bool timeoutsScheduled = false;
5704 kj::Promise<void> timeoutTask = nullptr;
5705
5706 struct AvailableClient {
5707 kj::Own<HttpClientImpl> client;
5708 kj::TimePoint expires;
5709 };
5710
5711 std::deque<AvailableClient> availableClients;
5712
5713 struct RefcountedClient final: public kj::Refcounted {
5714 RefcountedClient(NetworkAddressHttpClient& parent, kj::Own<HttpClientImpl> client)
5715 : parent(parent), client(kj::mv(client)) {
5716 ++parent.activeConnectionCount;
5717 }
5718 ~RefcountedClient() noexcept(false) {
5719 --parent.activeConnectionCount;
5720 KJ_IF_MAYBE(exception, kj::runCatchingExceptions([&]() {
5721 parent.returnClientToAvailable(kj::mv(client));
5722 })) {
5723 KJ_LOG(ERROR, *exception);
5724 }
5725 }
5726
5727 NetworkAddressHttpClient& parent;
5728 kj::Own<HttpClientImpl> client;
5729 };
5730
5731 kj::Own<RefcountedClient> getClient() {
5732 for (;;) {
5733 if (availableClients.empty()) {
5734 auto stream = newPromisedStream(address->connect());
5735 return kj::refcounted<RefcountedClient>(*this,
5736 kj::heap<HttpClientImpl>(responseHeaderTable, kj::mv(stream), settings));
5737 } else {
5738 auto client = kj::mv(availableClients.back().client);
5739 availableClients.pop_back();
5740 if (client->canReuse()) {
5741 return kj::refcounted<RefcountedClient>(*this, kj::mv(client));
5742 }
5743 // Whoops, this client's connection was closed by the server at some point. Discard.
5744 }
5745 }
5746 }
5747
5748 void returnClientToAvailable(kj::Own<HttpClientImpl> client) {
5749 // Only return the connection to the pool if it is reusable and if our settings indicate we
5750 // should reuse connections.
5751 if (client->canReuse() && settings.idleTimeout > 0 * kj::SECONDS) {
5752 availableClients.push_back(AvailableClient {
5753 kj::mv(client), timer.now() + settings.idleTimeout
5754 });
5755 }
5756
5757 // Call this either way because it also signals onDrained().
5758 if (!timeoutsScheduled) {
5759 timeoutsScheduled = true;
5760 timeoutTask = applyTimeouts();
5761 }
5762 }
5763
5764 kj::Promise<void> applyTimeouts() {
5765 if (availableClients.empty()) {
5766 timeoutsScheduled = false;
5767 if (activeConnectionCount == 0) {
5768 KJ_IF_MAYBE(f, drainedFulfiller) {
5769 f->get()->fulfill();
5770 drainedFulfiller = nullptr;
5771 }
5772 }
5773 return kj::READY_NOW;
5774 } else {
5775 auto time = availableClients.front().expires;
5776 return timer.atTime(time).then([this,time]() {
5777 while (!availableClients.empty() && availableClients.front().expires <= time) {
5778 availableClients.pop_front();
5779 }
5780 return applyTimeouts();
5781 });
5782 }
5783 }
5784 };
5785
5786 class TransitionaryAsyncIoStream final: public kj::AsyncIoStream {
5787 // This specialised AsyncIoStream is used by NetworkHttpClient to support startTls.
5788 public:
5789 TransitionaryAsyncIoStream(kj::Own<kj::AsyncIoStream> unencryptedStream)
5790 : inner(kj::heap<kj::PausableReadAsyncIoStream>(kj::mv(unencryptedStream))) {}
5791
5792 kj::Promise<size_t> tryRead(void* buffer, size_t minBytes, size_t maxBytes) override {
5793 return inner->tryRead(buffer, minBytes, maxBytes);
5794 }
5795
5796 kj::Maybe<uint64_t> tryGetLength() override {
5797 return inner->tryGetLength();
5798 }
5799
5800 kj::Promise<uint64_t> pumpTo(kj::AsyncOutputStream& output, uint64_t amount) override {
5801 return inner->pumpTo(output, amount);
5802 }
5803
5804 kj::Promise<void> write(const void* buffer, size_t size) override {
5805 return inner->write(buffer, size);
5806 }
5807
5808 kj::Promise<void> write(kj::ArrayPtr<const kj::ArrayPtr<const byte>> pieces) override {
5809 return inner->write(pieces);
5810 }
5811
5812 kj::Maybe<kj::Promise<uint64_t>> tryPumpFrom(
5813 kj::AsyncInputStream& input, uint64_t amount = kj::maxValue) override {
5814 return inner->tryPumpFrom(input, amount);
5815 }
5816
5817 kj::Promise<void> whenWriteDisconnected() override {
5818 return inner->whenWriteDisconnected();
5819 }
5820
5821 void shutdownWrite() override {
5822 inner->shutdownWrite();
5823 }
5824
5825 void abortRead() override {
5826 inner->abortRead();
5827 }
5828
5829 kj::Maybe<int> getFd() const override {
5830 return inner->getFd();
5831 }
5832
5833 void startTls(
5834 kj::SecureNetworkWrapper* wrapper, kj::StringPtr expectedServerHostname) {
5835 // Pause any potential pending reads.
5836 inner->pause();
5837
5838 KJ_ON_SCOPE_FAILURE({
5839 inner->reject(KJ_EXCEPTION(FAILED, "StartTls failed."));
5840 });
5841
5842 KJ_ASSERT(!inner->getCurrentlyReading() && !inner->getCurrentlyWriting(),
5843 "Cannot call startTls while reads/writes are outstanding");
5844 kj::Promise<kj::Own<kj::AsyncIoStream>> secureStream =
5845 wrapper->wrapClient(inner->takeStream(), expectedServerHostname);
5846 inner->replaceStream(kj::newPromisedStream(kj::mv(secureStream)));
5847 // Resume any previous pending reads.
5848 inner->unpause();
5849 }
5850
5851 private:
5852 kj::Own<kj::PausableReadAsyncIoStream> inner;
5853 };
5854
5855 class PromiseNetworkAddressHttpClient final: public HttpClient {
5856 // An HttpClient which waits for a promise to resolve then forwards all calls to the promised
5857 // client.
5858
5859 public:
5860 PromiseNetworkAddressHttpClient(kj::Promise<kj::Own<NetworkAddressHttpClient>> promise)
5861 : promise(promise.then([this](kj::Own<NetworkAddressHttpClient>&& client) {
5862 this->client = kj::mv(client);
5863 }).fork()) {}
5864
5865 bool isDrained() {
5866 KJ_IF_MAYBE(c, client) {
5867 return c->get()->isDrained();
5868 } else {
5869 return failed;
5870 }
5871 }
5872
5873 kj::Promise<void> onDrained() {
5874 KJ_IF_MAYBE(c, client) {
5875 return c->get()->onDrained();
5876 } else {
5877 return promise.addBranch().then([this]() {
5878 return KJ_ASSERT_NONNULL(client)->onDrained();
5879 }, [this](kj::Exception&& e) {
5880 // Connecting failed. Treat as immediately drained.
5881 failed = true;
5882 return kj::READY_NOW;
5883 });
5884 }
5885 }
5886
5887 Request request(HttpMethod method, kj::StringPtr url, const HttpHeaders& headers,
5888 kj::Maybe<uint64_t> expectedBodySize = nullptr) override {
5889 KJ_IF_MAYBE(c, client) {
5890 return c->get()->request(method, url, headers, expectedBodySize);
5891 } else {
5892 // This gets complicated since request() returns a pair of a stream and a promise.
5893 auto urlCopy = kj::str(url);
5894 auto headersCopy = headers.clone();
5895 auto combined = promise.addBranch().then(
5896 [this,method,expectedBodySize,url=kj::mv(urlCopy), headers=kj::mv(headersCopy)]()
5897 -> kj::Tuple<kj::Own<kj::AsyncOutputStream>, kj::Promise<Response>> {
5898 auto req = KJ_ASSERT_NONNULL(client)->request(method, url, headers, expectedBodySize);
5899 return kj::tuple(kj::mv(req.body), kj::mv(req.response));
5900 });
5901
5902 auto split = combined.split();
5903 return {
5904 newPromisedStream(kj::mv(kj::get<0>(split))),
5905 kj::mv(kj::get<1>(split))
5906 };
5907 }
5908 }
5909
5910 kj::Promise<WebSocketResponse> openWebSocket(
5911 kj::StringPtr url, const HttpHeaders& headers) override {
5912 KJ_IF_MAYBE(c, client) {
5913 return c->get()->openWebSocket(url, headers);
5914 } else {
5915 auto urlCopy = kj::str(url);
5916 auto headersCopy = headers.clone();
5917 return promise.addBranch().then(
5918 [this,url=kj::mv(urlCopy),headers=kj::mv(headersCopy)]() {
5919 return KJ_ASSERT_NONNULL(client)->openWebSocket(url, headers);
5920 });
5921 }
5922 }
5923
5924 ConnectRequest connect(
5925 kj::StringPtr host, const HttpHeaders& headers, HttpConnectSettings settings) override {
5926 KJ_IF_MAYBE(c, client) {
5927 return c->get()->connect(host, headers, settings);
5928 } else {
5929 auto split = promise.addBranch().then(
5930 [this, host=kj::str(host), headers=headers.clone(), settings]() mutable
5931 -> kj::Tuple<kj::Promise<ConnectRequest::Status>,
5932 kj::Promise<kj::Own<kj::AsyncIoStream>>> {
5933 auto request = KJ_ASSERT_NONNULL(client)->connect(host, headers, kj::mv(settings));
5934 return kj::tuple(kj::mv(request.status), kj::mv(request.connection));
5935 }).split();
5936
5937 return ConnectRequest {
5938 kj::mv(kj::get<0>(split)),
5939 kj::newPromisedStream(kj::mv(kj::get<1>(split)))
5940 };
5941 }
5942 }
5943
5944 private:
5945 kj::ForkedPromise<void> promise;
5946 kj::Maybe<kj::Own<NetworkAddressHttpClient>> client;
5947 bool failed = false;
5948 };
5949
5950 class NetworkHttpClient final: public HttpClient, private kj::TaskSet::ErrorHandler {
5951 public:
5952 NetworkHttpClient(kj::Timer& timer, const HttpHeaderTable& responseHeaderTable,
5953 kj::Network& network, kj::Maybe<kj::Network&> tlsNetwork,
5954 HttpClientSettings settings)
5955 : timer(timer),
5956 responseHeaderTable(responseHeaderTable),
5957 network(network),
5958 tlsNetwork(tlsNetwork),
5959 settings(kj::mv(settings)),
5960 tasks(*this) {}
5961
5962 Request request(HttpMethod method, kj::StringPtr url, const HttpHeaders& headers,
5963 kj::Maybe<uint64_t> expectedBodySize = nullptr) override {
5964 // We need to parse the proxy-style URL to convert it to host-style.
5965 // Use URL parsing options that avoid unnecessary rewrites.
5966 Url::Options urlOptions;
5967 urlOptions.allowEmpty = true;
5968 urlOptions.percentDecode = false;
5969
5970 auto parsed = Url::parse(url, Url::HTTP_PROXY_REQUEST, urlOptions);
5971 auto path = parsed.toString(Url::HTTP_REQUEST);
5972 auto headersCopy = headers.clone();
5973 headersCopy.set(HttpHeaderId::HOST, parsed.host);
5974 return getClient(parsed).request(method, path, headersCopy, expectedBodySize);
5975 }
5976
5977 kj::Promise<WebSocketResponse> openWebSocket(
5978 kj::StringPtr url, const HttpHeaders& headers) override {
5979 // We need to parse the proxy-style URL to convert it to host-style.
5980 // Use URL parsing options that avoid unnecessary rewrites.
5981 Url::Options urlOptions;
5982 urlOptions.allowEmpty = true;
5983 urlOptions.percentDecode = false;
5984
5985 auto parsed = Url::parse(url, Url::HTTP_PROXY_REQUEST, urlOptions);
5986 auto path = parsed.toString(Url::HTTP_REQUEST);
5987 auto headersCopy = headers.clone();
5988 headersCopy.set(HttpHeaderId::HOST, parsed.host);
5989 return getClient(parsed).openWebSocket(path, headersCopy);
5990 }
5991
5992 ConnectRequest connect(
5993 kj::StringPtr host, const HttpHeaders& headers,
5994 HttpConnectSettings connectSettings) override {
5995 // We want to connect directly instead of going through a proxy here.
5996 // https://github.com/capnproto/capnproto/pull/1454#discussion_r900414879
5997 kj::Maybe<kj::Promise<kj::Own<kj::NetworkAddress>>> addr;
5998 if (connectSettings.useTls) {
5999 kj::Network& tlsNet = KJ_REQUIRE_NONNULL(tlsNetwork, "this HttpClient doesn't support TLS");
6000 addr = tlsNet.parseAddress(host);
6001 } else {
6002 addr = network.parseAddress(host);
6003 }
6004
6005 auto split = KJ_ASSERT_NONNULL(addr).then([this](auto address) {
6006 return address->connect().then([this](auto connection)
6007 -> kj::Tuple<kj::Promise<ConnectRequest::Status>,
6008 kj::Promise<kj::Own<kj::AsyncIoStream>>> {
6009 return kj::tuple(
6010 ConnectRequest::Status(
6011 200,
6012 kj::str("OK"),
6013 kj::heap<kj::HttpHeaders>(responseHeaderTable) // Empty headers
6014 ),
6015 kj::mv(connection));
6016 }).attach(kj::mv(address));
6017 }).split();
6018
6019 auto connection = kj::newPromisedStream(kj::mv(kj::get<1>(split)));
6020
6021 if (!connectSettings.useTls) {
6022 KJ_IF_MAYBE(wrapper, settings.tlsContext) {
6023 KJ_IF_MAYBE(tlsStarter, connectSettings.tlsStarter) {
6024 auto transitConnectionRef = kj::refcountedWrapper(
6025 kj::heap<TransitionaryAsyncIoStream>(kj::mv(connection)));
6026 Function<kj::Promise<void>(kj::StringPtr)> cb =
6027 [wrapper, ref1 = transitConnectionRef->addWrappedRef()](
6028 kj::StringPtr expectedServerHostname) mutable {
6029 ref1->startTls(wrapper, expectedServerHostname);
6030 return kj::READY_NOW;
6031 };
6032 connection = transitConnectionRef->addWrappedRef();
6033 *tlsStarter = kj::mv(cb);
6034 }
6035 }
6036 }
6037
6038 return ConnectRequest {
6039 kj::mv(kj::get<0>(split)),
6040 kj::mv(connection)
6041 };
6042 }
6043
6044 private:
6045 kj::Timer& timer;
6046 const HttpHeaderTable& responseHeaderTable;
6047 kj::Network& network;
6048 kj::Maybe<kj::Network&> tlsNetwork;
6049 HttpClientSettings settings;
6050
6051 struct Host {
6052 kj::String name; // including port, if non-default
6053 kj::Own<PromiseNetworkAddressHttpClient> client;
6054 };
6055
6056 std::map<kj::StringPtr, Host> httpHosts;
6057 std::map<kj::StringPtr, Host> httpsHosts;
6058
6059 struct RequestInfo {
6060 HttpMethod method;
6061 kj::String hostname;
6062 kj::String path;
6063 HttpHeaders headers;
6064 kj::Maybe<uint64_t> expectedBodySize;
6065 };
6066
6067 kj::TaskSet tasks;
6068
6069 HttpClient& getClient(kj::Url& parsed) {
6070 bool isHttps = parsed.scheme == "https";
6071 bool isHttp = parsed.scheme == "http";
6072 KJ_REQUIRE(isHttp || isHttps);
6073
6074 auto& hosts = isHttps ? httpsHosts : httpHosts;
6075
6076 // Look for a cached client for this host.
6077 // TODO(perf): It would be nice to recognize when different hosts have the same address and
6078 // reuse the same connection pool, but:
6079 // - We'd need a reliable way to compare NetworkAddresses, e.g. .equals() and .hashCode().
6080 // It's very Java... ick.
6081 // - Correctly handling TLS would be tricky: we'd need to verify that the new hostname is
6082 // on the certificate. When SNI is in use we might have to request an additional
6083 // certificate (is that possible?).
6084 auto iter = hosts.find(parsed.host);
6085
6086 if (iter == hosts.end()) {
6087 // Need to open a new connection.
6088 kj::Network* networkToUse = &network;
6089 if (isHttps) {
6090 networkToUse = &KJ_REQUIRE_NONNULL(tlsNetwork, "this HttpClient doesn't support HTTPS");
6091 }
6092
6093 auto promise = networkToUse->parseAddress(parsed.host, isHttps ? 443 : 80)
6094 .then([this](kj::Own<kj::NetworkAddress> addr) {
6095 return kj::heap<NetworkAddressHttpClient>(
6096 timer, responseHeaderTable, kj::mv(addr), settings);
6097 });
6098
6099 Host host {
6100 kj::mv(parsed.host),
6101 kj::heap<PromiseNetworkAddressHttpClient>(kj::mv(promise))
6102 };
6103 kj::StringPtr nameRef = host.name;
6104
6105 auto insertResult = hosts.insert(std::make_pair(nameRef, kj::mv(host)));
6106 KJ_ASSERT(insertResult.second);
6107 iter = insertResult.first;
6108
6109 tasks.add(handleCleanup(hosts, iter));
6110 }
6111
6112 return *iter->second.client;
6113 }
6114
6115 kj::Promise<void> handleCleanup(std::map<kj::StringPtr, Host>& hosts,
6116 std::map<kj::StringPtr, Host>::iterator iter) {
6117 return iter->second.client->onDrained()
6118 .then([this,&hosts,iter]() -> kj::Promise<void> {
6119 // Double-check that it's really drained to avoid race conditions.
6120 if (iter->second.client->isDrained()) {
6121 hosts.erase(iter);
6122 return kj::READY_NOW;
6123 } else {
6124 return handleCleanup(hosts, iter);
6125 }
6126 });
6127 }
6128
6129 void taskFailed(kj::Exception&& exception) override {
6130 KJ_LOG(ERROR, exception);
6131 }
6132 };
6133
6134 } // namespace
6135
6136 kj::Own<HttpClient> newHttpClient(kj::Timer& timer, const HttpHeaderTable& responseHeaderTable,
6137 kj::NetworkAddress& addr, HttpClientSettings settings) {
6138 return kj::heap<NetworkAddressHttpClient>(timer, responseHeaderTable,
6139 kj::Own<kj::NetworkAddress>(&addr, kj::NullDisposer::instance), kj::mv(settings));
6140 }
6141
6142 kj::Own<HttpClient> newHttpClient(kj::Timer& timer, const HttpHeaderTable& responseHeaderTable,
6143 kj::Network& network, kj::Maybe<kj::Network&> tlsNetwork,
6144 HttpClientSettings settings) {
6145 return kj::heap<NetworkHttpClient>(
6146 timer, responseHeaderTable, network, tlsNetwork, kj::mv(settings));
6147 }
6148
6149 // =======================================================================================
6150
6151 namespace {
6152
6153 class ConcurrencyLimitingHttpClient final: public HttpClient {
6154 public:
6155 KJ_DISALLOW_COPY_AND_MOVE(ConcurrencyLimitingHttpClient);
6156 ConcurrencyLimitingHttpClient(
6157 kj::HttpClient& inner, uint maxConcurrentRequests,
6158 kj::Function<void(uint runningCount, uint pendingCount)> countChangedCallback)
6159 : inner(inner),
6160 maxConcurrentRequests(maxConcurrentRequests),
6161 countChangedCallback(kj::mv(countChangedCallback)) {}
6162
6163 ~ConcurrencyLimitingHttpClient() noexcept(false) {
6164 if (concurrentRequests > 0) {
6165 static bool logOnce KJ_UNUSED = ([&] {
6166 KJ_LOG(ERROR, "ConcurrencyLimitingHttpClient getting destroyed when concurrent requests "
6167 "are still active", concurrentRequests);
6168 return true;
6169 })();
6170 }
6171 }
6172
6173 Request request(HttpMethod method, kj::StringPtr url, const HttpHeaders& headers,
6174 kj::Maybe<uint64_t> expectedBodySize = nullptr) override {
6175 if (concurrentRequests < maxConcurrentRequests) {
6176 auto counter = ConnectionCounter(*this);
6177 auto request = inner.request(method, url, headers, expectedBodySize);
6178 fireCountChanged();
6179 auto promise = attachCounter(kj::mv(request.response), kj::mv(counter));
6180 return { kj::mv(request.body), kj::mv(promise) };
6181 }
6182
6183 auto paf = kj::newPromiseAndFulfiller<ConnectionCounter>();
6184 auto urlCopy = kj::str(url);
6185 auto headersCopy = headers.clone();
6186
6187 auto combined = paf.promise
6188 .then([this,
6189 method,
6190 urlCopy = kj::mv(urlCopy),
6191 headersCopy = kj::mv(headersCopy),
6192 expectedBodySize](ConnectionCounter&& counter) mutable {
6193 auto req = inner.request(method, urlCopy, headersCopy, expectedBodySize);
6194 return kj::tuple(kj::mv(req.body), attachCounter(kj::mv(req.response), kj::mv(counter)));
6195 });
6196 auto split = combined.split();
6197 pendingRequests.push(kj::mv(paf.fulfiller));
6198 fireCountChanged();
6199 return { newPromisedStream(kj::mv(kj::get<0>(split))), kj::mv(kj::get<1>(split)) };
6200 }
6201
6202 kj::Promise<WebSocketResponse> openWebSocket(
6203 kj::StringPtr url, const kj::HttpHeaders& headers) override {
6204 if (concurrentRequests < maxConcurrentRequests) {
6205 auto counter = ConnectionCounter(*this);
6206 auto response = inner.openWebSocket(url, headers);
6207 fireCountChanged();
6208 return attachCounter(kj::mv(response), kj::mv(counter));
6209 }
6210
6211 auto paf = kj::newPromiseAndFulfiller<ConnectionCounter>();
6212 auto urlCopy = kj::str(url);
6213 auto headersCopy = headers.clone();
6214
6215 auto promise = paf.promise
6216 .then([this,
6217 urlCopy = kj::mv(urlCopy),
6218 headersCopy = kj::mv(headersCopy)](ConnectionCounter&& counter) mutable {
6219 return attachCounter(inner.openWebSocket(urlCopy, headersCopy), kj::mv(counter));
6220 });
6221
6222 pendingRequests.push(kj::mv(paf.fulfiller));
6223 fireCountChanged();
6224 return kj::mv(promise);
6225 }
6226
6227 ConnectRequest connect(
6228 kj::StringPtr host, const kj::HttpHeaders& headers, HttpConnectSettings settings) override {
6229 if (concurrentRequests < maxConcurrentRequests) {
6230 auto counter = ConnectionCounter(*this);
6231 auto response = inner.connect(host, headers, settings);
6232 fireCountChanged();
6233 return attachCounter(kj::mv(response), kj::mv(counter));
6234 }
6235
6236 auto paf = kj::newPromiseAndFulfiller<ConnectionCounter>();
6237
6238 auto split = paf.promise
6239 .then([this, host=kj::str(host), headers=headers.clone(), settings]
6240 (ConnectionCounter&& counter) mutable
6241 -> kj::Tuple<kj::Promise<ConnectRequest::Status>,
6242 kj::Promise<kj::Own<kj::AsyncIoStream>>> {
6243 auto request = attachCounter(inner.connect(host, headers, settings), kj::mv(counter));
6244 return kj::tuple(kj::mv(request.status), kj::mv(request.connection));
6245 }).split();
6246
6247 pendingRequests.push(kj::mv(paf.fulfiller));
6248 fireCountChanged();
6249
6250 return ConnectRequest {
6251 kj::mv(kj::get<0>(split)),
6252 kj::newPromisedStream(kj::mv(kj::get<1>(split)))
6253 };
6254 }
6255
6256 private:
6257 struct ConnectionCounter;
6258
6259 kj::HttpClient& inner;
6260 uint maxConcurrentRequests;
6261 uint concurrentRequests = 0;
6262 kj::Function<void(uint runningCount, uint pendingCount)> countChangedCallback;
6263
6264 std::queue<kj::Own<kj::PromiseFulfiller<ConnectionCounter>>> pendingRequests;
6265 // TODO(someday): want maximum cap on queue size?
6266
6267 struct ConnectionCounter final {
6268 ConnectionCounter(ConcurrencyLimitingHttpClient& client) : parent(&client) {
6269 ++parent->concurrentRequests;
6270 }
6271 KJ_DISALLOW_COPY(ConnectionCounter);
6272 ~ConnectionCounter() noexcept(false) {
6273 if (parent != nullptr) {
6274 --parent->concurrentRequests;
6275 parent->serviceQueue();
6276 parent->fireCountChanged();
6277 }
6278 }
6279 ConnectionCounter(ConnectionCounter&& other) : parent(other.parent) {
6280 other.parent = nullptr;
6281 }
6282 ConnectionCounter& operator=(ConnectionCounter&& other) {
6283 if (this != &other) {
6284 this->parent = other.parent;
6285 other.parent = nullptr;
6286 }
6287 return *this;
6288 }
6289
6290 ConcurrencyLimitingHttpClient* parent;
6291 };
6292
6293 void serviceQueue() {
6294 while (concurrentRequests < maxConcurrentRequests && !pendingRequests.empty()) {
6295 auto fulfiller = kj::mv(pendingRequests.front());
6296 pendingRequests.pop();
6297 // ConnectionCounter's destructor calls this function, so we can avoid unnecessary recursion
6298 // if we only create a ConnectionCounter when we find a waiting fulfiller.
6299 if (fulfiller->isWaiting()) {
6300 fulfiller->fulfill(ConnectionCounter(*this));
6301 }
6302 }
6303 }
6304
6305 void fireCountChanged() {
6306 countChangedCallback(concurrentRequests, pendingRequests.size());
6307 }
6308
6309 using WebSocketOrBody = kj::OneOf<kj::Own<kj::AsyncInputStream>, kj::Own<WebSocket>>;
6310 static WebSocketOrBody attachCounter(WebSocketOrBody&& webSocketOrBody,
6311 ConnectionCounter&& counter) {
6312 KJ_SWITCH_ONEOF(webSocketOrBody) {
6313 KJ_CASE_ONEOF(ws, kj::Own<WebSocket>) {
6314 return ws.attach(kj::mv(counter));
6315 }
6316 KJ_CASE_ONEOF(body, kj::Own<kj::AsyncInputStream>) {
6317 return body.attach(kj::mv(counter));
6318 }
6319 }
6320 KJ_UNREACHABLE;
6321 }
6322
6323 static kj::Promise<WebSocketResponse> attachCounter(kj::Promise<WebSocketResponse>&& promise,
6324 ConnectionCounter&& counter) {
6325 return promise.then([counter = kj::mv(counter)](WebSocketResponse&& response) mutable {
6326 return WebSocketResponse {
6327 response.statusCode,
6328 response.statusText,
6329 response.headers,
6330 attachCounter(kj::mv(response.webSocketOrBody), kj::mv(counter))
6331 };
6332 });
6333 }
6334
6335 static kj::Promise<Response> attachCounter(kj::Promise<Response>&& promise,
6336 ConnectionCounter&& counter) {
6337 return promise.then([counter = kj::mv(counter)](Response&& response) mutable {
6338 return Response {
6339 response.statusCode,
6340 response.statusText,
6341 response.headers,
6342 response.body.attach(kj::mv(counter))
6343 };
6344 });
6345 }
6346
6347 static ConnectRequest attachCounter(
6348 ConnectRequest&& request,
6349 ConnectionCounter&& counter) {
6350 // Notice here that we are only attaching the counter to the connection stream. In the case
6351 // where the connect tunnel request is rejected and the status promise resolves with an
6352 // errorBody, there is a possibility that the consuming code might drop the connection stream
6353 // and the counter while the error body stream is still be consumed. Technically speaking that
6354 // means we could potentially exceed our concurrency limit temporarily but we consider that
6355 // acceptable here since the error body is an exception path (plus not requiring that we
6356 // attach to the errorBody keeps ConnectionCounter from having to be a refcounted heap
6357 // allocation).
6358 request.connection = request.connection.attach(kj::mv(counter));
6359 return kj::mv(request);
6360 }
6361 };
6362
6363 }
6364
6365 kj::Own<HttpClient> newConcurrencyLimitingHttpClient(
6366 HttpClient& inner, uint maxConcurrentRequests,
6367 kj::Function<void(uint runningCount, uint pendingCount)> countChangedCallback) {
6368 return kj::heap<ConcurrencyLimitingHttpClient>(inner, maxConcurrentRequests,
6369 kj::mv(countChangedCallback));
6370 }
6371
6372 // =======================================================================================
6373
6374 namespace {
6375
6376 class HttpClientAdapter final: public HttpClient {
6377 public:
6378 HttpClientAdapter(HttpService& service): service(service) {}
6379
6380 Request request(HttpMethod method, kj::StringPtr url, const HttpHeaders& headers,
6381 kj::Maybe<uint64_t> expectedBodySize = nullptr) override {
6382 // We have to clone the URL and headers because HttpService implementation are allowed to
6383 // assume that they remain valid until the service handler completes whereas HttpClient callers
6384 // are allowed to destroy them immediately after the call.
6385 auto urlCopy = kj::str(url);
6386 auto headersCopy = kj::heap(headers.clone());
6387
6388 auto pipe = newOneWayPipe(expectedBodySize);
6389
6390 // TODO(cleanup): The ownership relationships here are a mess. Can we do something better
6391 // involving a PromiseAdapter, maybe?
6392 auto paf = kj::newPromiseAndFulfiller<Response>();
6393 auto responder = kj::refcounted<ResponseImpl>(method, kj::mv(paf.fulfiller));
6394
6395 auto requestPaf = kj::newPromiseAndFulfiller<kj::Promise<void>>();
6396 responder->setPromise(kj::mv(requestPaf.promise));
6397
6398 auto promise = service.request(method, urlCopy, *headersCopy, *pipe.in, *responder)
6399 .attach(kj::mv(pipe.in), kj::mv(urlCopy), kj::mv(headersCopy));
6400 requestPaf.fulfiller->fulfill(kj::mv(promise));
6401
6402 return {
6403 kj::mv(pipe.out),
6404 paf.promise.attach(kj::mv(responder))
6405 };
6406 }
6407
6408 kj::Promise<WebSocketResponse> openWebSocket(
6409 kj::StringPtr url, const HttpHeaders& headers) override {
6410 // We have to clone the URL and headers because HttpService implementation are allowed to
6411 // assume that they remain valid until the service handler completes whereas HttpClient callers
6412 // are allowed to destroy them immediately after the call. Also we need to add
6413 // `Upgrade: websocket` so that headers.isWebSocket() returns true on the service side.
6414 auto urlCopy = kj::str(url);
6415 auto headersCopy = kj::heap(headers.clone());
6416 headersCopy->set(HttpHeaderId::UPGRADE, "websocket");
6417 KJ_DASSERT(headersCopy->isWebSocket());
6418
6419 auto paf = kj::newPromiseAndFulfiller<WebSocketResponse>();
6420 auto responder = kj::refcounted<WebSocketResponseImpl>(kj::mv(paf.fulfiller));
6421
6422 auto requestPaf = kj::newPromiseAndFulfiller<kj::Promise<void>>();
6423 responder->setPromise(kj::mv(requestPaf.promise));
6424
6425 auto in = kj::heap<NullInputStream>();
6426 auto promise = service.request(HttpMethod::GET, urlCopy, *headersCopy, *in, *responder)
6427 .attach(kj::mv(in), kj::mv(urlCopy), kj::mv(headersCopy));
6428 requestPaf.fulfiller->fulfill(kj::mv(promise));
6429
6430 return paf.promise.attach(kj::mv(responder));
6431 }
6432
6433 ConnectRequest connect(
6434 kj::StringPtr host, const HttpHeaders& headers, HttpConnectSettings settings) override {
6435 // We have to clone the host and the headers because HttpServer implementation are allowed to
6436 // assusme that they remain valid until the service handler completes whereas HttpClient callers
6437 // are allowed to destroy them immediately after the call.
6438 auto hostCopy = kj::str(host);
6439 auto headersCopy = kj::heap(headers.clone());
6440
6441 // 1. Create a new TwoWayPipe, one will be returned with the ConnectRequest,
6442 // the other will be held by the ConnectResponseImpl.
6443 auto pipe = kj::newTwoWayPipe();
6444
6445 // 2. Create a promise/fulfiller pair for the status. The promise will be
6446 // returned with the ConnectResponse, the fulfiller will be held by the
6447 // ConnectResponseImpl.
6448 auto paf = kj::newPromiseAndFulfiller<ConnectRequest::Status>();
6449
6450 // 3. Create the ConnectResponseImpl
6451 auto response = kj::refcounted<ConnectResponseImpl>(kj::mv(paf.fulfiller),
6452 kj::mv(pipe.ends[0]));
6453
6454 // 5. Call service.connect, passing in the tunnel.
6455 // The call to tunnel->getConnectStream() returns a guarded stream that will buffer
6456 // writes until the status is indicated by calling accept/reject.
6457 auto connectStream = response->getConnectStream();
6458 auto promise = service.connect(hostCopy, *headersCopy, *connectStream, *response, settings)
6459 .eagerlyEvaluate([response=kj::mv(response),
6460 host=kj::mv(hostCopy),
6461 headers=kj::mv(headersCopy),
6462 connectStream=kj::mv(connectStream)](kj::Exception&& ex) mutable {
6463 // A few things need to happen here.
6464 // 1. We'll log the exception.
6465 // 2. We'll break the pipe.
6466 // 3. We'll reject the status promise if it is still pending.
6467 //
6468 // We'll do all of this within the ConnectResponseImpl, however, since it
6469 // maintains the state necessary here.
6470 response->handleException(kj::mv(ex), kj::mv(connectStream));
6471 });
6472
6473 // TODO(bug): There's a challenge with attaching the service.connect promise to the
6474 // connection stream below in that the client will likely drop the connection as soon
6475 // as it reads EOF, but the promise representing the service connect() call may still
6476 // be running and want to do some cleanup after it has sent EOF. That cleanup will be
6477 // canceled. For regular HTTP calls, DelayedEofInputStream was created to address this
6478 // exact issue but with connect() being bidirectional it's rather more difficult. We
6479 // want a delay similar to what DelayedEofInputStream adds but only when both directions
6480 // have been closed. That currently is not possible until we have an alternative to
6481 // shutdownWrite() that returns a Promise (e.g. Promise<void> end()). For now, we can
6482 // live with the current limitation.
6483 return ConnectRequest {
6484 kj::mv(paf.promise),
6485 pipe.ends[1].attach(kj::mv(promise)),
6486 };
6487 }
6488
6489 private:
6490 HttpService& service;
6491
6492 class DelayedEofInputStream final: public kj::AsyncInputStream {
6493 // An AsyncInputStream wrapper that, when it reaches EOF, delays the final read until some
6494 // promise completes.
6495
6496 public:
6497 DelayedEofInputStream(kj::Own<kj::AsyncInputStream> inner, kj::Promise<void> completionTask)
6498 : inner(kj::mv(inner)), completionTask(kj::mv(completionTask)) {}
6499
6500 kj::Promise<size_t> tryRead(void* buffer, size_t minBytes, size_t maxBytes) override {
6501 return wrap(minBytes, inner->tryRead(buffer, minBytes, maxBytes));
6502 }
6503
6504 kj::Maybe<uint64_t> tryGetLength() override {
6505 return inner->tryGetLength();
6506 }
6507
6508 kj::Promise<uint64_t> pumpTo(kj::AsyncOutputStream& output, uint64_t amount) override {
6509 return wrap(amount, inner->pumpTo(output, amount));
6510 }
6511
6512 private:
6513 kj::Own<kj::AsyncInputStream> inner;
6514 kj::Maybe<kj::Promise<void>> completionTask;
6515
6516 template <typename T>
6517 kj::Promise<T> wrap(T requested, kj::Promise<T> innerPromise) {
6518 return innerPromise.then([this,requested](T actual) -> kj::Promise<T> {
6519 if (actual < requested) {
6520 // Must have reached EOF.
6521 KJ_IF_MAYBE(t, completionTask) {
6522 // Delay until completion.
6523 auto result = t->then([actual]() { return actual; });
6524 completionTask = nullptr;
6525 return result;
6526 } else {
6527 // Must have called tryRead() again after we already signaled EOF. Fine.
6528 return actual;
6529 }
6530 } else {
6531 return actual;
6532 }
6533 }, [this](kj::Exception&& e) -> kj::Promise<T> {
6534 // The stream threw an exception, but this exception is almost certainly just complaining
6535 // that the other end of the stream was dropped. In all likelihood, the HttpService
6536 // request() call itself will throw a much more interesting error -- we'd rather propagate
6537 // that one, if so.
6538 KJ_IF_MAYBE(t, completionTask) {
6539 auto result = t->then([e = kj::mv(e)]() mutable -> kj::Promise<T> {
6540 // Looks like the service didn't throw. I guess we should propagate the stream error
6541 // after all.
6542 return kj::mv(e);
6543 });
6544 completionTask = nullptr;
6545 return result;
6546 } else {
6547 // Must have called tryRead() again after we already signaled EOF or threw. Fine.
6548 return kj::mv(e);
6549 }
6550 });
6551 }
6552 };
6553
6554 class ResponseImpl final: public HttpService::Response, public kj::Refcounted {
6555 public:
6556 ResponseImpl(kj::HttpMethod method,
6557 kj::Own<kj::PromiseFulfiller<HttpClient::Response>> fulfiller)
6558 : method(method), fulfiller(kj::mv(fulfiller)) {}
6559
6560 void setPromise(kj::Promise<void> promise) {
6561 task = promise.eagerlyEvaluate([this](kj::Exception&& exception) {
6562 if (fulfiller->isWaiting()) {
6563 fulfiller->reject(kj::mv(exception));
6564 } else {
6565 // We need to cause the response stream's read() to throw this, so we should propagate it.
6566 kj::throwRecoverableException(kj::mv(exception));
6567 }
6568 });
6569 }
6570
6571 kj::Own<kj::AsyncOutputStream> send(
6572 uint statusCode, kj::StringPtr statusText, const HttpHeaders& headers,
6573 kj::Maybe<uint64_t> expectedBodySize = nullptr) override {
6574 // The caller of HttpClient is allowed to assume that the statusText and headers remain
6575 // valid until the body stream is dropped, but the HttpService implementation is allowed to
6576 // send values that are only valid until send() returns, so we have to copy.
6577 auto statusTextCopy = kj::str(statusText);
6578 auto headersCopy = kj::heap(headers.clone());
6579
6580 if (method == kj::HttpMethod::HEAD || expectedBodySize.orDefault(1) == 0) {
6581 // We're not expecting any body. We need to delay reporting completion to the client until
6582 // the server side has actually returned from the service method, otherwise we may
6583 // prematurely cancel it.
6584
6585 task = task.then([this,statusCode,statusTextCopy=kj::mv(statusTextCopy),
6586 headersCopy=kj::mv(headersCopy),expectedBodySize]() mutable {
6587 fulfiller->fulfill({
6588 statusCode, statusTextCopy, headersCopy.get(),
6589 kj::heap<NullInputStream>(expectedBodySize)
6590 .attach(kj::mv(statusTextCopy), kj::mv(headersCopy))
6591 });
6592 }).eagerlyEvaluate([](kj::Exception&& e) { KJ_LOG(ERROR, e); });
6593 return kj::heap<NullOutputStream>();
6594 } else {
6595 auto pipe = newOneWayPipe(expectedBodySize);
6596
6597 // Wrap the stream in a wrapper that delays the last read (the one that signals EOF) until
6598 // the service's request promise has finished.
6599 auto wrapper = kj::heap<DelayedEofInputStream>(
6600 kj::mv(pipe.in), task.attach(kj::addRef(*this)));
6601
6602 fulfiller->fulfill({
6603 statusCode, statusTextCopy, headersCopy.get(),
6604 wrapper.attach(kj::mv(statusTextCopy), kj::mv(headersCopy))
6605 });
6606 return kj::mv(pipe.out);
6607 }
6608 }
6609
6610 kj::Own<WebSocket> acceptWebSocket(const HttpHeaders& headers) override {
6611 KJ_FAIL_REQUIRE("a WebSocket was not requested");
6612 }
6613
6614 private:
6615 kj::HttpMethod method;
6616 kj::Own<kj::PromiseFulfiller<HttpClient::Response>> fulfiller;
6617 kj::Promise<void> task = nullptr;
6618 };
6619
6620 class DelayedCloseWebSocket final: public WebSocket {
6621 // A WebSocket wrapper that, when it reaches Close (in both directions), delays the final close
6622 // operation until some promise completes.
6623
6624 public:
6625 DelayedCloseWebSocket(kj::Own<kj::WebSocket> inner, kj::Promise<void> completionTask)
6626 : inner(kj::mv(inner)), completionTask(kj::mv(completionTask)) {}
6627
6628 kj::Promise<void> send(kj::ArrayPtr<const byte> message) override {
6629 return inner->send(message);
6630 }
6631 kj::Promise<void> send(kj::ArrayPtr<const char> message) override {
6632 return inner->send(message);
6633 }
6634 kj::Promise<void> close(uint16_t code, kj::StringPtr reason) override {
6635 return inner->close(code, reason)
6636 .then([this]() {
6637 return afterSendClosed();
6638 });
6639 }
6640 kj::Promise<void> disconnect() override {
6641 return inner->disconnect();
6642 }
6643 void abort() override {
6644 // Don't need to worry about completion task in this case -- cancelling it is reasonable.
6645 inner->abort();
6646 }
6647 kj::Promise<void> whenAborted() override {
6648 return inner->whenAborted();
6649 }
6650 kj::Promise<Message> receive(size_t maxSize) override {
6651 return inner->receive(maxSize).then([this](Message&& message) -> kj::Promise<Message> {
6652 if (message.is<WebSocket::Close>()) {
6653 return afterReceiveClosed()
6654 .then([message = kj::mv(message)]() mutable { return kj::mv(message); });
6655 }
6656 return kj::mv(message);
6657 });
6658 }
6659 kj::Promise<void> pumpTo(WebSocket& other) override {
6660 return inner->pumpTo(other).then([this]() {
6661 return afterReceiveClosed();
6662 });
6663 }
6664 kj::Maybe<kj::Promise<void>> tryPumpFrom(WebSocket& other) override {
6665 return other.pumpTo(*inner).then([this]() {
6666 return afterSendClosed();
6667 });
6668 }
6669
6670 uint64_t sentByteCount() override { return inner->sentByteCount(); }
6671 uint64_t receivedByteCount() override { return inner->receivedByteCount(); }
6672
6673 private:
6674 kj::Own<kj::WebSocket> inner;
6675 kj::Maybe<kj::Promise<void>> completionTask;
6676
6677 bool sentClose = false;
6678 bool receivedClose = false;
6679
6680 kj::Promise<void> afterSendClosed() {
6681 sentClose = true;
6682 if (receivedClose) {
6683 KJ_IF_MAYBE(t, completionTask) {
6684 auto result = kj::mv(*t);
6685 completionTask = nullptr;
6686 return result;
6687 }
6688 }
6689 return kj::READY_NOW;
6690 }
6691
6692 kj::Promise<void> afterReceiveClosed() {
6693 receivedClose = true;
6694 if (sentClose) {
6695 KJ_IF_MAYBE(t, completionTask) {
6696 auto result = kj::mv(*t);
6697 completionTask = nullptr;
6698 return result;
6699 }
6700 }
6701 return kj::READY_NOW;
6702 }
6703 };
6704
6705 class WebSocketResponseImpl final: public HttpService::Response, public kj::Refcounted {
6706 public:
6707 WebSocketResponseImpl(kj::Own<kj::PromiseFulfiller<HttpClient::WebSocketResponse>> fulfiller)
6708 : fulfiller(kj::mv(fulfiller)) {}
6709
6710 void setPromise(kj::Promise<void> promise) {
6711 task = promise.eagerlyEvaluate([this](kj::Exception&& exception) {
6712 if (fulfiller->isWaiting()) {
6713 fulfiller->reject(kj::mv(exception));
6714 } else {
6715 // We need to cause the client-side WebSocket to throw on close, so propagate the
6716 // exception.
6717 kj::throwRecoverableException(kj::mv(exception));
6718 }
6719 });
6720 }
6721
6722 kj::Own<kj::AsyncOutputStream> send(
6723 uint statusCode, kj::StringPtr statusText, const HttpHeaders& headers,
6724 kj::Maybe<uint64_t> expectedBodySize = nullptr) override {
6725 // The caller of HttpClient is allowed to assume that the statusText and headers remain
6726 // valid until the body stream is dropped, but the HttpService implementation is allowed to
6727 // send values that are only valid until send() returns, so we have to copy.
6728 auto statusTextCopy = kj::str(statusText);
6729 auto headersCopy = kj::heap(headers.clone());
6730
6731 if (expectedBodySize.orDefault(1) == 0) {
6732 // We're not expecting any body. We need to delay reporting completion to the client until
6733 // the server side has actually returned from the service method, otherwise we may
6734 // prematurely cancel it.
6735
6736 task = task.then([this,statusCode,statusTextCopy=kj::mv(statusTextCopy),
6737 headersCopy=kj::mv(headersCopy),expectedBodySize]() mutable {
6738 fulfiller->fulfill({
6739 statusCode, statusTextCopy, headersCopy.get(),
6740 kj::Own<AsyncInputStream>(kj::heap<NullInputStream>(expectedBodySize)
6741 .attach(kj::mv(statusTextCopy), kj::mv(headersCopy)))
6742 });
6743 }).eagerlyEvaluate([](kj::Exception&& e) { KJ_LOG(ERROR, e); });
6744 return kj::heap<NullOutputStream>();
6745 } else {
6746 auto pipe = newOneWayPipe(expectedBodySize);
6747
6748 // Wrap the stream in a wrapper that delays the last read (the one that signals EOF) until
6749 // the service's request promise has finished.
6750 kj::Own<AsyncInputStream> wrapper =
6751 kj::heap<DelayedEofInputStream>(kj::mv(pipe.in), task.attach(kj::addRef(*this)));
6752
6753 fulfiller->fulfill({
6754 statusCode, statusTextCopy, headersCopy.get(),
6755 wrapper.attach(kj::mv(statusTextCopy), kj::mv(headersCopy))
6756 });
6757 return kj::mv(pipe.out);
6758 }
6759 }
6760
6761 kj::Own<WebSocket> acceptWebSocket(const HttpHeaders& headers) override {
6762 // The caller of HttpClient is allowed to assume that the headers remain valid until the body
6763 // stream is dropped, but the HttpService implementation is allowed to send headers that are
6764 // only valid until acceptWebSocket() returns, so we have to copy.
6765 auto headersCopy = kj::heap(headers.clone());
6766
6767 auto pipe = newWebSocketPipe();
6768
6769 // Wrap the client-side WebSocket in a wrapper that delays clean close of the WebSocket until
6770 // the service's request promise has finished.
6771 kj::Own<WebSocket> wrapper =
6772 kj::heap<DelayedCloseWebSocket>(kj::mv(pipe.ends[0]), task.attach(kj::addRef(*this)));
6773 fulfiller->fulfill({
6774 101, "Switching Protocols", headersCopy.get(),
6775 wrapper.attach(kj::mv(headersCopy))
6776 });
6777 return kj::mv(pipe.ends[1]);
6778 }
6779
6780 private:
6781 kj::Own<kj::PromiseFulfiller<HttpClient::WebSocketResponse>> fulfiller;
6782 kj::Promise<void> task = nullptr;
6783 };
6784
6785 class ConnectResponseImpl final: public HttpService::ConnectResponse, public kj::Refcounted {
6786 public:
6787 ConnectResponseImpl(
6788 kj::Own<kj::PromiseFulfiller<HttpClient::ConnectRequest::Status>> fulfiller,
6789 kj::Own<kj::AsyncIoStream> stream)
6790 : fulfiller(kj::mv(fulfiller)),
6791 streamAndFulfiller(initStreamsAndFulfiller(kj::mv(stream))) {}
6792
6793 ~ConnectResponseImpl() noexcept(false) {
6794 if (fulfiller->isWaiting() || streamAndFulfiller.fulfiller->isWaiting()) {
6795 auto ex = KJ_EXCEPTION(FAILED,
6796 "service's connect() implementation never called accept() nor reject()");
6797 if (fulfiller->isWaiting()) {
6798 fulfiller->reject(kj::cp(ex));
6799 }
6800 if (streamAndFulfiller.fulfiller->isWaiting()) {
6801 streamAndFulfiller.fulfiller->reject(kj::mv(ex));
6802 }
6803 }
6804 }
6805
6806 void accept(uint statusCode, kj::StringPtr statusText, const HttpHeaders& headers) override {
6807 KJ_REQUIRE(statusCode >= 200 && statusCode < 300, "the statusCode must be 2xx for accept");
6808 respond(statusCode, statusText, headers);
6809 }
6810
6811 kj::Own<kj::AsyncOutputStream> reject(
6812 uint statusCode,
6813 kj::StringPtr statusText,
6814 const HttpHeaders& headers,
6815 kj::Maybe<uint64_t> expectedBodySize = nullptr) override {
6816 KJ_REQUIRE(statusCode < 200 || statusCode >= 300,
6817 "the statusCode must not be 2xx for reject.");
6818 auto pipe = kj::newOneWayPipe();
6819 respond(statusCode, statusText, headers, kj::mv(pipe.in));
6820 return kj::mv(pipe.out);
6821 }
6822
6823 private:
6824 struct StreamsAndFulfiller {
6825 // guarded is the wrapped/guarded stream that wraps a reference to
6826 // the underlying stream but blocks reads until the connection is accepted
6827 // or rejected.
6828 // This will be handed off when getConnectStream() is called.
6829 // The fulfiller is used to resolve the guard for the second stream. This will
6830 // be fulfilled or rejected when accept/reject is called.
6831 kj::Own<kj::AsyncIoStream> guarded;
6832 kj::Own<kj::PromiseFulfiller<void>> fulfiller;
6833 };
6834
6835 kj::Own<kj::PromiseFulfiller<HttpClient::ConnectRequest::Status>> fulfiller;
6836 StreamsAndFulfiller streamAndFulfiller;
6837 bool connectStreamDetached = false;
6838
6839 StreamsAndFulfiller initStreamsAndFulfiller(kj::Own<kj::AsyncIoStream> stream) {
6840 auto paf = kj::newPromiseAndFulfiller<void>();
6841 auto guarded = kj::heap<AsyncIoStreamWithGuards>(
6842 kj::mv(stream),
6843 kj::Maybe<HttpInputStreamImpl::ReleasedBuffer>(nullptr),
6844 kj::mv(paf.promise));
6845 return StreamsAndFulfiller {
6846 kj::mv(guarded),
6847 kj::mv(paf.fulfiller)
6848 };
6849 }
6850
6851 void handleException(kj::Exception&& ex, kj::Own<kj::AsyncIoStream> connectStream) {
6852 // Log the exception...
6853 KJ_LOG(ERROR, "Error in HttpClientAdapter connect()", kj::cp(ex));
6854 // Reject the status promise if it is still pending...
6855 if (fulfiller->isWaiting()) {
6856 fulfiller->reject(kj::cp(ex));
6857 }
6858 if (streamAndFulfiller.fulfiller->isWaiting()) {
6859 // If the guard hasn't yet ben released, we can fail the pending reads by
6860 // rejecting the fulfiller here.
6861 streamAndFulfiller.fulfiller->reject(kj::mv(ex));
6862 } else {
6863 // The guard has already been released at this point.
6864 // TODO(connect): How to properly propagate the actual exception to the
6865 // connect stream? Here we "simply" shut it down.
6866 connectStream->abortRead();
6867 connectStream->shutdownWrite();
6868 }
6869 }
6870
6871 kj::Own<kj::AsyncIoStream> getConnectStream() {
6872 KJ_ASSERT(!connectStreamDetached, "the connect stream was already detached");
6873 connectStreamDetached = true;
6874 return streamAndFulfiller.guarded.attach(kj::addRef(*this));
6875 }
6876
6877 void respond(uint statusCode,
6878 kj::StringPtr statusText,
6879 const HttpHeaders& headers,
6880 kj::Maybe<kj::Own<kj::AsyncInputStream>> errorBody = nullptr) {
6881 if (errorBody == nullptr) {
6882 streamAndFulfiller.fulfiller->fulfill();
6883 } else {
6884 streamAndFulfiller.fulfiller->reject(
6885 KJ_EXCEPTION(DISCONNECTED, "the connect request was rejected"));
6886 }
6887 fulfiller->fulfill(HttpClient::ConnectRequest::Status(
6888 statusCode,
6889 kj::str(statusText),
6890 kj::heap(headers.clone()),
6891 kj::mv(errorBody)));
6892 }
6893
6894 friend class HttpClientAdapter;
6895 };
6896
6897 };
6898
6899 } // namespace
6900
6901 kj::Own<HttpClient> newHttpClient(HttpService& service) {
6902 return kj::heap<HttpClientAdapter>(service);
6903 }
6904
6905 // =======================================================================================
6906
6907 namespace {
6908
6909 class HttpServiceAdapter final: public HttpService {
6910 public:
6911 HttpServiceAdapter(HttpClient& client): client(client) {}
6912
6913 kj::Promise<void> request(
6914 HttpMethod method, kj::StringPtr url, const HttpHeaders& headers,
6915 kj::AsyncInputStream& requestBody, Response& response) override {
6916 if (!headers.isWebSocket()) {
6917 auto innerReq = client.request(method, url, headers, requestBody.tryGetLength());
6918
6919 auto promises = kj::heapArrayBuilder<kj::Promise<void>>(2);
6920 promises.add(requestBody.pumpTo(*innerReq.body).ignoreResult()
6921 .attach(kj::mv(innerReq.body)).eagerlyEvaluate(nullptr));
6922
6923 promises.add(innerReq.response
6924 .then([&response](HttpClient::Response&& innerResponse) {
6925 auto out = response.send(
6926 innerResponse.statusCode, innerResponse.statusText, *innerResponse.headers,
6927 innerResponse.body->tryGetLength());
6928 auto promise = innerResponse.body->pumpTo(*out);
6929 return promise.ignoreResult().attach(kj::mv(out), kj::mv(innerResponse.body));
6930 }));
6931
6932 return kj::joinPromisesFailFast(promises.finish());
6933 } else {
6934 return client.openWebSocket(url, headers)
6935 .then([&response](HttpClient::WebSocketResponse&& innerResponse) -> kj::Promise<void> {
6936 KJ_SWITCH_ONEOF(innerResponse.webSocketOrBody) {
6937 KJ_CASE_ONEOF(ws, kj::Own<WebSocket>) {
6938 auto ws2 = response.acceptWebSocket(*innerResponse.headers);
6939 auto promises = kj::heapArrayBuilder<kj::Promise<void>>(2);
6940 promises.add(ws->pumpTo(*ws2));
6941 promises.add(ws2->pumpTo(*ws));
6942 return kj::joinPromisesFailFast(promises.finish()).attach(kj::mv(ws), kj::mv(ws2));
6943 }
6944 KJ_CASE_ONEOF(body, kj::Own<kj::AsyncInputStream>) {
6945 auto out = response.send(
6946 innerResponse.statusCode, innerResponse.statusText, *innerResponse.headers,
6947 body->tryGetLength());
6948 auto promise = body->pumpTo(*out);
6949 return promise.ignoreResult().attach(kj::mv(out), kj::mv(body));
6950 }
6951 }
6952 KJ_UNREACHABLE;
6953 });
6954 }
6955 }
6956
6957 kj::Promise<void> connect(kj::StringPtr host,
6958 const HttpHeaders& headers,
6959 kj::AsyncIoStream& connection,
6960 ConnectResponse& response,
6961 HttpConnectSettings settings) override {
6962 KJ_REQUIRE(!headers.isWebSocket(), "WebSocket upgrade headers are not permitted in a connect.");
6963
6964 auto request = client.connect(host, headers, settings);
6965
6966 // This operates optimistically. In order to support pipelining, we connect the
6967 // input and outputs streams immediately, even if we're not yet certain that the
6968 // tunnel can actually be established.
6969 auto promises = kj::heapArrayBuilder<kj::Promise<void>>(2);
6970
6971 // For the inbound pipe (from the clients stream to the passed in stream)
6972 // We want to guard reads pending the acceptance of the tunnel. If the
6973 // tunnel is not accepted, the guard will be rejected, causing pending
6974 // reads to fail.
6975 auto paf = kj::newPromiseAndFulfiller<kj::Maybe<HttpInputStreamImpl::ReleasedBuffer>>();
6976 auto io = kj::heap<AsyncIoStreamWithGuards>(
6977 kj::mv(request.connection),
6978 kj::mv(paf.promise) /* read guard */,
6979 kj::READY_NOW /* write guard */);
6980
6981 // Writing from connection to io is unguarded and allowed immediately.
6982 promises.add(connection.pumpTo(*io).then([&io=*io](uint64_t size) {
6983 io.shutdownWrite();
6984 }));
6985
6986 promises.add(io->pumpTo(connection).then([&connection](uint64_t size) {
6987 connection.shutdownWrite();
6988 }));
6989
6990 auto pumpPromise = kj::joinPromisesFailFast(promises.finish());
6991
6992 return request.status.then(
6993 [&response,&connection,fulfiller=kj::mv(paf.fulfiller),
6994 pumpPromise=kj::mv(pumpPromise)]
6995 (HttpClient::ConnectRequest::Status status) mutable -> kj::Promise<void> {
6996 if (status.statusCode >= 200 && status.statusCode < 300) {
6997 // Release the read guard!
6998 fulfiller->fulfill(kj::Maybe<HttpInputStreamImpl::ReleasedBuffer>(nullptr));
6999 response.accept(status.statusCode, status.statusText, *status.headers);
7000 return kj::mv(pumpPromise);
7001 } else {
7002 // If the connect request is rejected, we want to shutdown the tunnel
7003 // and pipeline the status.errorBody to the AsyncOutputStream returned by
7004 // reject if it exists.
7005 pumpPromise = nullptr;
7006 connection.shutdownWrite();
7007 fulfiller->reject(KJ_EXCEPTION(DISCONNECTED, "the connect request was rejected"));
7008 KJ_IF_MAYBE(errorBody, status.errorBody) {
7009 auto out = response.reject(status.statusCode, status.statusText, *status.headers,
7010 errorBody->get()->tryGetLength());
7011 return (*errorBody)->pumpTo(*out).then([](uint64_t) -> kj::Promise<void> {
7012 return kj::READY_NOW;
7013 }).attach(kj::mv(out), kj::mv(*errorBody));
7014 } else {
7015 response.reject(status.statusCode, status.statusText, *status.headers, (uint64_t)0);
7016 return kj::READY_NOW;
7017 }
7018 }
7019 }).attach(kj::mv(io));
7020 }
7021
7022 private:
7023 HttpClient& client;
7024 };
7025
7026 } // namespace
7027
7028 kj::Own<HttpService> newHttpService(HttpClient& client) {
7029 return kj::heap<HttpServiceAdapter>(client);
7030 }
7031
7032 // =======================================================================================
7033
7034 kj::Promise<void> HttpService::Response::sendError(
7035 uint statusCode, kj::StringPtr statusText, const HttpHeaders& headers) {
7036 auto stream = send(statusCode, statusText, headers, statusText.size());
7037 auto promise = stream->write(statusText.begin(), statusText.size());
7038 return promise.attach(kj::mv(stream));
7039 }
7040
7041 kj::Promise<void> HttpService::Response::sendError(
7042 uint statusCode, kj::StringPtr statusText, const HttpHeaderTable& headerTable) {
7043 return sendError(statusCode, statusText, HttpHeaders(headerTable));
7044 }
7045
7046 kj::Promise<void> HttpService::connect(
7047 kj::StringPtr host,
7048 const HttpHeaders& headers,
7049 kj::AsyncIoStream& connection,
7050 ConnectResponse& response,
7051 kj::HttpConnectSettings settings) {
7052 KJ_UNIMPLEMENTED("CONNECT is not implemented by this HttpService");
7053 }
7054
7055 class HttpServer::Connection final: private HttpService::Response,
7056 private HttpService::ConnectResponse,
7057 private HttpServerErrorHandler {
7058 public:
7059 Connection(HttpServer& server, kj::AsyncIoStream& stream,
7060 SuspendableHttpServiceFactory factory, kj::Maybe<SuspendedRequest> suspendedRequest,
7061 bool wantCleanDrain)
7062 : server(server),
7063 stream(stream),
7064 factory(kj::mv(factory)),
7065 httpInput(makeHttpInput(stream, server.requestHeaderTable, kj::mv(suspendedRequest))),
7066 httpOutput(stream),
7067 wantCleanDrain(wantCleanDrain) {
7068 ++server.connectionCount;
7069 }
7070 ~Connection() noexcept(false) {
7071 if (--server.connectionCount == 0) {
7072 KJ_IF_MAYBE(f, server.zeroConnectionsFulfiller) {
7073 f->get()->fulfill();
7074 }
7075 }
7076 }
7077
7078 public:
7079 kj::Promise<bool> startLoop(bool firstRequest) {
7080 return loop(firstRequest).catch_([this](kj::Exception&& e) -> kj::Promise<bool> {
7081 // Exception; report 5xx.
7082
7083 KJ_IF_MAYBE(p, webSocketError) {
7084 // sendWebSocketError() was called. Finish sending and close the connection. Don't log
7085 // the exception because it's probably a side-effect of this.
7086 auto promise = kj::mv(*p);
7087 webSocketError = nullptr;
7088 return kj::mv(promise);
7089 }
7090
7091 KJ_IF_MAYBE(p, tunnelRejected) {
7092 // reject() was called to reject a CONNECT request. Finish sending and close the connection.
7093 // Don't log the exception because it's probably a side-effect of this.
7094 auto promise = kj::mv(*p);
7095 tunnelRejected = nullptr;
7096 return kj::mv(promise);
7097 }
7098
7099 return sendError(kj::mv(e));
7100 });
7101 }
7102
7103 SuspendedRequest suspend(SuspendableRequest& suspendable) {
7104 KJ_REQUIRE(httpInput.canSuspend(),
7105 "suspend() may only be called before the request body is consumed");
7106 KJ_DEFER(suspended = true);
7107 auto released = httpInput.releaseBuffer();
7108 return {
7109 kj::mv(released.buffer),
7110 released.leftover,
7111 suspendable.method,
7112 suspendable.url,
7113 suspendable.headers.cloneShallow(),
7114 };
7115 }
7116
7117 private:
7118 HttpServer& server;
7119 kj::AsyncIoStream& stream;
7120
7121 SuspendableHttpServiceFactory factory;
7122 // Creates a new kj::Own<HttpService> for each request we handle on this connection.
7123
7124 HttpInputStreamImpl httpInput;
7125 HttpOutputStream httpOutput;
7126 kj::Maybe<kj::OneOf<HttpMethod, HttpConnectMethod>> currentMethod;
7127 bool timedOut = false;
7128 bool closed = false;
7129 bool upgraded = false;
7130 bool webSocketOrConnectClosed = false;
7131 bool closeAfterSend = false; // True if send() should set Connection: close.
7132 bool wantCleanDrain = false;
7133 bool suspended = false;
7134 kj::Maybe<kj::Promise<bool>> webSocketError;
7135 kj::Maybe<kj::Promise<bool>> tunnelRejected;
7136 kj::Maybe<kj::Own<kj::PromiseFulfiller<void>>> tunnelWriteGuard;
7137
7138 static HttpInputStreamImpl makeHttpInput(
7139 kj::AsyncIoStream& stream,
7140 const kj::HttpHeaderTable& table,
7141 kj::Maybe<SuspendedRequest> suspendedRequest) {
7142 // Constructor helper function to create our HttpInputStreamImpl.
7143
7144 KJ_IF_MAYBE(sr, suspendedRequest) {
7145 return HttpInputStreamImpl(stream,
7146 sr->buffer.releaseAsChars(),
7147 sr->leftover.asChars(),
7148 sr->method,
7149 sr->url,
7150 kj::mv(sr->headers));
7151 }
7152 return HttpInputStreamImpl(stream, table);
7153 }
7154
7155 kj::Promise<bool> loop(bool firstRequest) {
7156 if (!firstRequest && server.draining && httpInput.isCleanDrain()) {
7157 // Don't call awaitNextMessage() in this case because that will initiate a read() which will
7158 // immediately be canceled, losing data.
7159 return true;
7160 }
7161
7162 auto firstByte = httpInput.awaitNextMessage();
7163
7164 if (!firstRequest) {
7165 // For requests after the first, require that the first byte arrive before the pipeline
7166 // timeout, otherwise treat it like the connection was simply closed.
7167 auto timeoutPromise = server.timer.afterDelay(server.settings.pipelineTimeout);
7168
7169 if (httpInput.isCleanDrain()) {
7170 // If we haven't buffered any data, then we can safely drain here, so allow the wait to
7171 // be canceled by the onDrain promise.
7172 auto cleanDrainPromise = server.onDrain.addBranch()
7173 .then([this]() -> kj::Promise<void> {
7174 // This is a little tricky... drain() has been called, BUT we could have read some data
7175 // into the buffer in the meantime, and we don't want to lose that. If any data has
7176 // arrived, then we have no choice but to read the rest of the request and respond to
7177 // it.
7178 if (!httpInput.isCleanDrain()) {
7179 return kj::NEVER_DONE;
7180 }
7181
7182 // OK... As far as we know, no data has arrived in the buffer. However, unfortunately,
7183 // we don't *really* know that, because read() is asynchronous. It may have already
7184 // delivered some bytes, but we just haven't received the notification yet, because it's
7185 // still queued on the event loop. As a horrible hack, we use evalLast(), so that any
7186 // such pending notifications get a chance to be delivered.
7187 // TODO(someday): Does this actually work on Windows, where the notification could also
7188 // be queued on the IOCP?
7189 return kj::evalLast([this]() -> kj::Promise<void> {
7190 if (httpInput.isCleanDrain()) {
7191 return kj::READY_NOW;
7192 } else {
7193 return kj::NEVER_DONE;
7194 }
7195 });
7196 });
7197 timeoutPromise = timeoutPromise.exclusiveJoin(kj::mv(cleanDrainPromise));
7198 }
7199
7200 firstByte = firstByte.exclusiveJoin(timeoutPromise.then([this]() -> bool {
7201 timedOut = true;
7202 return false;
7203 }));
7204 }
7205
7206 auto receivedHeaders = firstByte
7207 .then([this,firstRequest](bool hasData)
7208 -> kj::Promise<HttpHeaders::RequestConnectOrProtocolError> {
7209 if (hasData) {
7210 auto readHeaders = httpInput.readRequestHeaders();
7211 if (!firstRequest) {
7212 // On requests other than the first, the header timeout starts ticking when we receive
7213 // the first byte of a pipeline response.
7214 readHeaders = readHeaders.exclusiveJoin(
7215 server.timer.afterDelay(server.settings.headerTimeout)
7216 .then([this]() -> HttpHeaders::RequestConnectOrProtocolError {
7217 timedOut = true;
7218 return HttpHeaders::ProtocolError {
7219 408, "Request Timeout",
7220 "Timed out waiting for next request headers.", nullptr
7221 };
7222 }));
7223 }
7224 return kj::mv(readHeaders);
7225 } else {
7226 // Client closed connection or pipeline timed out with no bytes received. This is not an
7227 // error, so don't report one.
7228 this->closed = true;
7229 return HttpHeaders::RequestConnectOrProtocolError(HttpHeaders::ProtocolError {
7230 408, "Request Timeout",
7231 "Client closed connection or connection timeout "
7232 "while waiting for request headers.", nullptr
7233 });
7234 }
7235 });
7236
7237 if (firstRequest) {
7238 // On the first request, the header timeout starts ticking immediately upon request opening.
7239 // NOTE: Since we assume that the client wouldn't have formed a connection if they did not
7240 // intend to send a request, we immediately treat this connection as having an active
7241 // request, i.e. we do NOT cancel it if drain() is called.
7242 auto timeoutPromise = server.timer.afterDelay(server.settings.headerTimeout)
7243 .then([this]() -> HttpHeaders::RequestConnectOrProtocolError {
7244 timedOut = true;
7245 return HttpHeaders::ProtocolError {
7246 408, "Request Timeout",
7247 "Timed out waiting for initial request headers.", nullptr
7248 };
7249 });
7250 receivedHeaders = receivedHeaders.exclusiveJoin(kj::mv(timeoutPromise));
7251 }
7252
7253 return receivedHeaders
7254 .then([this](HttpHeaders::RequestConnectOrProtocolError&& requestOrProtocolError)
7255 -> kj::Promise<bool> {
7256 if (timedOut) {
7257 // Client took too long to send anything, so we're going to close the connection. In
7258 // theory, we should send back an HTTP 408 error -- it is designed exactly for this
7259 // purpose. Alas, in practice, Google Chrome does not have any special handling for 408
7260 // errors -- it will assume the error is a response to the next request it tries to send,
7261 // and will happily serve the error to the user. OTOH, if we simply close the connection,
7262 // Chrome does the "right thing", apparently. (Though I'm not sure what happens if a
7263 // request is in-flight when we close... if it's a GET, the browser should retry. But if
7264 // it's a POST, retrying may be dangerous. This is why 408 exists -- it unambiguously
7265 // tells the client that it should retry.)
7266 //
7267 // Also note that if we ever decide to send 408 again, we might want to send some other
7268 // error in the case that the server is draining, which also sets timedOut = true; see
7269 // above.
7270
7271 return httpOutput.flush().then([this]() {
7272 return server.draining && httpInput.isCleanDrain();
7273 });
7274 }
7275
7276 if (closed) {
7277 // Client closed connection. Close our end too.
7278 return httpOutput.flush().then([]() { return false; });
7279 }
7280
7281 KJ_SWITCH_ONEOF(requestOrProtocolError) {
7282 KJ_CASE_ONEOF(request, HttpHeaders::ConnectRequest) {
7283 auto& headers = httpInput.getHeaders();
7284
7285 currentMethod = HttpConnectMethod();
7286
7287 // The HTTP specification says that CONNECT requests have no meaningful payload
7288 // but stops short of saying that CONNECT *cannot* have a payload. Implementations
7289 // can choose to either accept payloads or reject them. We choose to reject it.
7290 // Specifically, if there are Content-Length or Transfer-Encoding headers in the
7291 // request headers, we'll automatically reject the CONNECT request.
7292 //
7293 // The key implication here is that any data that immediately follows the headers
7294 // block of the CONNECT request is considered to be part of the tunnel if it is
7295 // established.
7296
7297 KJ_IF_MAYBE(cl, headers.get(HttpHeaderId::CONTENT_LENGTH)) {
7298 return sendError(HttpHeaders::ProtocolError {
7299 400,
7300 "Bad Request"_kj,
7301 "Bad Request"_kj,
7302 nullptr,
7303 });
7304 }
7305 KJ_IF_MAYBE(te, headers.get(HttpHeaderId::TRANSFER_ENCODING)) {
7306 return sendError(HttpHeaders::ProtocolError {
7307 400,
7308 "Bad Request"_kj,
7309 "Bad Request"_kj,
7310 nullptr,
7311 });
7312 }
7313
7314 SuspendableRequest suspendable(*this, HttpConnectMethod(), request.authority, headers);
7315 auto maybeService = factory(suspendable);
7316
7317 if (suspended) {
7318 return false;
7319 }
7320
7321 auto service = KJ_ASSERT_NONNULL(kj::mv(maybeService),
7322 "SuspendableHttpServiceFactory did not suspend, but returned nullptr.");
7323 auto connectStream = getConnectStream();
7324 auto promise = service->connect(
7325 request.authority, headers, *connectStream, *this, {})
7326 .attach(kj::mv(service), kj::mv(connectStream));
7327 return promise.then([this]() mutable -> kj::Promise<bool> {
7328 KJ_IF_MAYBE(p, tunnelRejected) {
7329 // reject() was called to reject a CONNECT attempt.
7330 // Finish sending and close the connection.
7331 auto promise = kj::mv(*p);
7332 tunnelRejected = nullptr;
7333 return kj::mv(promise);
7334 }
7335
7336 if (httpOutput.isBroken()) {
7337 return false;
7338 }
7339
7340 return httpOutput.flush().then([]() mutable -> kj::Promise<bool> {
7341 // There is really no reasonable path to reusing a CONNECT connection.
7342 return false;
7343 });
7344 });
7345 }
7346 KJ_CASE_ONEOF(request, HttpHeaders::Request) {
7347 auto& headers = httpInput.getHeaders();
7348
7349 currentMethod = request.method;
7350
7351 SuspendableRequest suspendable(*this, request.method, request.url, headers);
7352 auto maybeService = factory(suspendable);
7353
7354 if (suspended) {
7355 return false;
7356 }
7357
7358 auto service = KJ_ASSERT_NONNULL(kj::mv(maybeService),
7359 "SuspendableHttpServiceFactory did not suspend, but returned nullptr.");
7360
7361 // TODO(perf): If the client disconnects, should we cancel the response? Probably, to
7362 // prevent permanent deadlock. It's slightly weird in that arguably the client should
7363 // be able to shutdown the upstream but still wait on the downstream, but I believe many
7364 // other HTTP servers do similar things.
7365
7366 auto body = httpInput.getEntityBody(
7367 HttpInputStreamImpl::REQUEST, request.method, 0, headers);
7368
7369 auto promise = service->request(
7370 request.method, request.url, headers, *body, *this).attach(kj::mv(service));
7371 return promise.then([this, body = kj::mv(body)]() mutable -> kj::Promise<bool> {
7372 // Response done. Await next request.
7373
7374 KJ_IF_MAYBE(p, webSocketError) {
7375 // sendWebSocketError() was called. Finish sending and close the connection.
7376 auto promise = kj::mv(*p);
7377 webSocketError = nullptr;
7378 return kj::mv(promise);
7379 }
7380
7381 if (upgraded) {
7382 // We've upgraded to WebSocket, and by now we should have closed the WebSocket.
7383 if (!webSocketOrConnectClosed) {
7384 // This is gonna segfault later so abort now instead.
7385 KJ_LOG(FATAL, "Accepted WebSocket object must be destroyed before HttpService "
7386 "request handler completes.");
7387 abort();
7388 }
7389
7390 // Once we start a WebSocket there's no going back to HTTP.
7391 return false;
7392 }
7393
7394 if (currentMethod != nullptr) {
7395 return sendError();
7396 }
7397
7398 if (httpOutput.isBroken()) {
7399 // We started a response but didn't finish it. But HttpService returns success?
7400 // Perhaps it decided that it doesn't want to finish this response. We'll have to
7401 // disconnect here. If the response body is not complete (e.g. Content-Length not
7402 // reached), the client should notice. We don't want to log an error because this
7403 // condition might be intentional on the service's part.
7404 return false;
7405 }
7406
7407 return httpOutput.flush().then(
7408 [this, body = kj::mv(body)]() mutable -> kj::Promise<bool> {
7409 if (httpInput.canReuse()) {
7410 // Things look clean. Go ahead and accept the next request.
7411
7412 if (closeAfterSend) {
7413 // We sent Connection: close, so drop the connection now.
7414 return false;
7415 } else {
7416 // Note that we don't have to handle server.draining here because we'll take care
7417 // of it the next time around the loop.
7418 return loop(false);
7419 }
7420 } else {
7421 // Apparently, the application did not read the request body. Maybe this is a bug,
7422 // or maybe not: maybe the client tried to upload too much data and the application
7423 // legitimately wants to cancel the upload without reading all it it.
7424 //
7425 // We have a problem, though: We did send a response, and we didn't send
7426 // `Connection: close`, so the client may expect that it can send another request.
7427 // Perhaps the client has even finished sending the previous request's body, in
7428 // which case the moment it finishes receiving the response, it could be completely
7429 // within its rights to start a new request. If we close the socket now, we might
7430 // interrupt that new request.
7431 //
7432 // Or maybe we did send `Connection: close`, as indicated by `closeAfterSend` being
7433 // true. Even in that case, we should still try to read and ignore the request,
7434 // otherwise when we close the connection the client may get a "connection reset"
7435 // error before they get a chance to actually read the response body that we sent
7436 // them.
7437 //
7438 // There's no way we can get out of this perfectly cleanly. HTTP just isn't good
7439 // enough at connection management. The best we can do is give the client some grace
7440 // period and then abort the connection.
7441
7442 auto dummy = kj::heap<HttpDiscardingEntityWriter>();
7443 auto lengthGrace = kj::evalNow([&]() {
7444 return body->pumpTo(*dummy, server.settings.canceledUploadGraceBytes);
7445 }).catch_([](kj::Exception&& e) -> uint64_t {
7446 // Reading from the input failed in some way. This may actually be the whole
7447 // reason we got here in the first place so don't propagate this error, just
7448 // give up on discarding the input.
7449 return 0; // This zero is ignored but `canReuse()` will return false below.
7450 }).then([this](uint64_t amount) {
7451 if (httpInput.canReuse()) {
7452 // Success, we can continue.
7453 return true;
7454 } else {
7455 // Still more data. Give up.
7456 return false;
7457 }
7458 });
7459 lengthGrace = lengthGrace.attach(kj::mv(dummy), kj::mv(body));
7460
7461 auto timeGrace = server.timer.afterDelay(server.settings.canceledUploadGracePeriod)
7462 .then([]() { return false; });
7463
7464 return lengthGrace.exclusiveJoin(kj::mv(timeGrace))
7465 .then([this](bool clean) -> kj::Promise<bool> {
7466 if (clean && !closeAfterSend) {
7467 // We recovered. Continue loop.
7468 return loop(false);
7469 } else {
7470 // Client still not done, or we sent Connection: close and so want to drop the
7471 // connection anyway. Return broken.
7472 return false;
7473 }
7474 });
7475 }
7476 });
7477 });
7478 }
7479 KJ_CASE_ONEOF(protocolError, HttpHeaders::ProtocolError) {
7480 // Bad request.
7481
7482 // sendError() uses Response::send(), which requires that we have a currentMethod, but we
7483 // never read one. GET seems like the correct choice here.
7484 currentMethod = HttpMethod::GET;
7485 return sendError(kj::mv(protocolError));
7486 }
7487 }
7488
7489 KJ_UNREACHABLE;
7490 });
7491 }
7492
7493 kj::Own<kj::AsyncOutputStream> send(
7494 uint statusCode, kj::StringPtr statusText, const HttpHeaders& headers,
7495 kj::Maybe<uint64_t> expectedBodySize) override {
7496 auto method = KJ_REQUIRE_NONNULL(currentMethod, "already called send()");
7497 currentMethod = nullptr;
7498
7499 kj::StringPtr connectionHeaders[HttpHeaders::CONNECTION_HEADERS_COUNT];
7500 kj::String lengthStr;
7501
7502 if (!closeAfterSend) {
7503 // Check if application wants us to close connections.
7504 //
7505 // If the application used listenHttpClientDrain() to listen, then it expects that after a
7506 // clean drain, the connection is still open and can receive more requests. Otherwise, after
7507 // receiving drain(), we will close the connection, so we should send a `Connection: close`
7508 // header.
7509 if (server.draining && !wantCleanDrain) {
7510 closeAfterSend = true;
7511 } else KJ_IF_MAYBE(c, server.settings.callbacks) {
7512 // The application has registered its own callback to decide whether to send
7513 // `Connection: close`.
7514 if (c->shouldClose()) {
7515 closeAfterSend = true;
7516 }
7517 }
7518 }
7519
7520 if (closeAfterSend) {
7521 connectionHeaders[HttpHeaders::BuiltinIndices::CONNECTION] = "close";
7522 }
7523
7524 bool isHeadRequest = method.tryGet<HttpMethod>().map([](auto& m) {
7525 return m == HttpMethod::HEAD;
7526 }).orDefault(false);
7527
7528 if (statusCode == 204 || statusCode == 304) {
7529 // No entity-body.
7530 } else if (statusCode == 205) {
7531 // Status code 205 also has no body, but unlike 204 and 304, it must explicitly encode an
7532 // empty body, e.g. using content-length: 0. I'm guessing this is one of those things,
7533 // where some early clients expected an explicit body while others assumed an empty body,
7534 // and so the standard had to choose the common denominator.
7535 //
7536 // Spec: https://tools.ietf.org/html/rfc7231#section-6.3.6
7537 connectionHeaders[HttpHeaders::BuiltinIndices::CONTENT_LENGTH] = "0";
7538 } else KJ_IF_MAYBE(s, expectedBodySize) {
7539 // HACK: We interpret a zero-length expected body length on responses to HEAD requests to
7540 // mean "don't set a Content-Length header at all." This provides a way to omit a body
7541 // header on HEAD responses with non-null-body status codes. This is a hack that *only*
7542 // makes sense for HEAD responses.
7543 if (!isHeadRequest || *s > 0) {
7544 lengthStr = kj::str(*s);
7545 connectionHeaders[HttpHeaders::BuiltinIndices::CONTENT_LENGTH] = lengthStr;
7546 }
7547 } else {
7548 connectionHeaders[HttpHeaders::BuiltinIndices::TRANSFER_ENCODING] = "chunked";
7549 }
7550
7551 // For HEAD requests, if the application specified a Content-Length or Transfer-Encoding
7552 // header, use that instead of whatever we decided above.
7553 kj::ArrayPtr<kj::StringPtr> connectionHeadersArray = connectionHeaders;
7554 if (isHeadRequest) {
7555 if (headers.get(HttpHeaderId::CONTENT_LENGTH) != nullptr ||
7556 headers.get(HttpHeaderId::TRANSFER_ENCODING) != nullptr) {
7557 connectionHeadersArray = connectionHeadersArray
7558 .slice(0, HttpHeaders::HEAD_RESPONSE_CONNECTION_HEADERS_COUNT);
7559 }
7560 }
7561
7562 httpOutput.writeHeaders(headers.serializeResponse(
7563 statusCode, statusText, connectionHeadersArray));
7564
7565 kj::Own<kj::AsyncOutputStream> bodyStream;
7566 if (isHeadRequest) {
7567 // Ignore entity-body.
7568 httpOutput.finishBody();
7569 return heap<HttpDiscardingEntityWriter>();
7570 } else if (statusCode == 204 || statusCode == 205 || statusCode == 304) {
7571 // No entity-body.
7572 httpOutput.finishBody();
7573 return heap<HttpNullEntityWriter>();
7574 } else KJ_IF_MAYBE(s, expectedBodySize) {
7575 return heap<HttpFixedLengthEntityWriter>(httpOutput, *s);
7576 } else {
7577 return heap<HttpChunkedEntityWriter>(httpOutput);
7578 }
7579 }
7580
7581 kj::Own<WebSocket> acceptWebSocket(const HttpHeaders& headers) override {
7582 auto& requestHeaders = httpInput.getHeaders();
7583 KJ_REQUIRE(requestHeaders.isWebSocket(),
7584 "can't call acceptWebSocket() if the request headers didn't have Upgrade: WebSocket");
7585
7586 auto method = KJ_REQUIRE_NONNULL(currentMethod, "already called send()");
7587 KJ_REQUIRE(method.tryGet<HttpMethod>().map([](auto& m) {
7588 return m == HttpMethod::GET;
7589 }).orDefault(false), "WebSocket must be initiated with a GET request.");
7590
7591 if (requestHeaders.get(HttpHeaderId::SEC_WEBSOCKET_VERSION).orDefault(nullptr) != "13") {
7592 return sendWebSocketError("The requested WebSocket version is not supported.");
7593 }
7594
7595 kj::String key;
7596 KJ_IF_MAYBE(k, requestHeaders.get(HttpHeaderId::SEC_WEBSOCKET_KEY)) {
7597 key = kj::str(*k);
7598 } else {
7599 return sendWebSocketError("Missing Sec-WebSocket-Key");
7600 }
7601
7602 kj::Maybe<CompressionParameters> acceptedParameters;
7603 kj::String agreedParameters;
7604 auto compressionMode = server.settings.webSocketCompressionMode;
7605 if (compressionMode == HttpServerSettings::AUTOMATIC_COMPRESSION) {
7606 // If AUTOMATIC_COMPRESSION is enabled, we ignore the `headers` passed by the application and
7607 // strictly refer to the `requestHeaders` from the client.
7608 KJ_IF_MAYBE(value, requestHeaders.get(HttpHeaderId::SEC_WEBSOCKET_EXTENSIONS)) {
7609 // Perform compression parameter negotiation.
7610 KJ_IF_MAYBE(config, _::tryParseExtensionOffers(*value)) {
7611 acceptedParameters = kj::mv(*config);
7612 }
7613 }
7614 } else if (compressionMode == HttpServerSettings::MANUAL_COMPRESSION) {
7615 // If MANUAL_COMPRESSION is enabled, we use the `headers` passed in by the application, and
7616 // try to find a configuration that respects both the server's preferred configuration,
7617 // as well as the client's requested configuration.
7618 KJ_IF_MAYBE(value, headers.get(HttpHeaderId::SEC_WEBSOCKET_EXTENSIONS)) {
7619 // First, we get the manual configuration using `headers`.
7620 KJ_IF_MAYBE(manualConfig, _::tryParseExtensionOffers(*value)) {
7621 KJ_IF_MAYBE(requestOffers, requestHeaders.get(HttpHeaderId::SEC_WEBSOCKET_EXTENSIONS)) {
7622 // Next, we to find a configuration that both the client and server can accept.
7623 acceptedParameters = _::tryParseAllExtensionOffers(*requestOffers, *manualConfig);
7624 }
7625 }
7626 }
7627 }
7628
7629 auto websocketAccept = generateWebSocketAccept(key);
7630
7631 kj::StringPtr connectionHeaders[HttpHeaders::WEBSOCKET_CONNECTION_HEADERS_COUNT];
7632 connectionHeaders[HttpHeaders::BuiltinIndices::SEC_WEBSOCKET_ACCEPT] = websocketAccept;
7633 connectionHeaders[HttpHeaders::BuiltinIndices::UPGRADE] = "websocket";
7634 connectionHeaders[HttpHeaders::BuiltinIndices::CONNECTION] = "Upgrade";
7635 KJ_IF_MAYBE(parameters, acceptedParameters) {
7636 agreedParameters = _::generateExtensionResponse(*parameters);
7637 connectionHeaders[HttpHeaders::BuiltinIndices::SEC_WEBSOCKET_EXTENSIONS] = agreedParameters;
7638 }
7639
7640 // Since we're about to write headers, we should nullify `currentMethod`. This tells
7641 // `sendError(kj::Exception)` (called from `HttpServer::Connection::startLoop()`) not to expose
7642 // the `HttpService::Response&` reference to the HttpServer's error `handleApplicationError()`
7643 // callback. This prevents the error handler from inadvertently trying to send another error on
7644 // the connection.
7645 currentMethod = nullptr;
7646
7647 httpOutput.writeHeaders(headers.serializeResponse(
7648 101, "Switching Protocols", connectionHeaders));
7649
7650 upgraded = true;
7651 // We need to give the WebSocket an Own<AsyncIoStream>, but we only have a reference. This is
7652 // safe because the application is expected to drop the WebSocket object before returning
7653 // from the request handler. For some extra safety, we check that webSocketOrConnectClosed has
7654 // been set true when the handler returns.
7655 auto deferNoteClosed = kj::defer([this]() { webSocketOrConnectClosed = true; });
7656 kj::Own<kj::AsyncIoStream> ownStream(&stream, kj::NullDisposer::instance);
7657 return upgradeToWebSocket(ownStream.attach(kj::mv(deferNoteClosed)),
7658 httpInput, httpOutput, nullptr, kj::mv(acceptedParameters),
7659 server.settings.webSocketErrorHandler);
7660 }
7661
7662 kj::Promise<bool> sendError(HttpHeaders::ProtocolError protocolError) {
7663 closeAfterSend = true;
7664
7665 // Client protocol errors always happen on request headers parsing, before we call into the
7666 // HttpService, meaning no response has been sent and we can provide a Response object.
7667 auto promise = server.settings.errorHandler.orDefault(*this).handleClientProtocolError(
7668 kj::mv(protocolError), *this);
7669 return finishSendingError(kj::mv(promise));
7670 }
7671
7672 kj::Promise<bool> sendError(kj::Exception&& exception) {
7673 closeAfterSend = true;
7674
7675 // We only provide the Response object if we know we haven't already sent a response.
7676 auto promise = server.settings.errorHandler.orDefault(*this).handleApplicationError(
7677 kj::mv(exception), currentMethod.map([this](auto&&) -> Response& { return *this; }));
7678 return finishSendingError(kj::mv(promise));
7679 }
7680
7681 kj::Promise<bool> sendError() {
7682 closeAfterSend = true;
7683
7684 // We can provide a Response object, since none has already been sent.
7685 auto promise = server.settings.errorHandler.orDefault(*this).handleNoResponse(*this);
7686 return finishSendingError(kj::mv(promise));
7687 }
7688
7689 kj::Promise<bool> finishSendingError(kj::Promise<void> promise) {
7690 return promise.then([this]() -> kj::Promise<void> {
7691 if (httpOutput.isBroken()) {
7692 // Skip flush for broken streams, since it will throw an exception that may be worse than
7693 // the one we just handled.
7694 return kj::READY_NOW;
7695 } else {
7696 return httpOutput.flush();
7697 }
7698 }).then([]() { return false; }); // loop ends after flush
7699 }
7700
7701 kj::Own<WebSocket> sendWebSocketError(StringPtr errorMessage) {
7702 kj::Exception exception = KJ_EXCEPTION(FAILED,
7703 "received bad WebSocket handshake", errorMessage);
7704 webSocketError = sendError(
7705 HttpHeaders::ProtocolError { 400, "Bad Request", errorMessage, nullptr });
7706 kj::throwRecoverableException(kj::mv(exception));
7707
7708 // Fallback path when exceptions are disabled.
7709 class BrokenWebSocket final: public WebSocket {
7710 public:
7711 BrokenWebSocket(kj::Exception exception): exception(kj::mv(exception)) {}
7712
7713 kj::Promise<void> send(kj::ArrayPtr<const byte> message) override {
7714 return kj::cp(exception);
7715 }
7716 kj::Promise<void> send(kj::ArrayPtr<const char> message) override {
7717 return kj::cp(exception);
7718 }
7719 kj::Promise<void> close(uint16_t code, kj::StringPtr reason) override {
7720 return kj::cp(exception);
7721 }
7722 kj::Promise<void> disconnect() override {
7723 return kj::cp(exception);
7724 }
7725 void abort() override {
7726 kj::throwRecoverableException(kj::cp(exception));
7727 }
7728 kj::Promise<void> whenAborted() override {
7729 return kj::cp(exception);
7730 }
7731 kj::Promise<Message> receive(size_t maxSize) override {
7732 return kj::cp(exception);
7733 }
7734
7735 uint64_t sentByteCount() override { KJ_FAIL_ASSERT("received bad WebSocket handshake"); }
7736 uint64_t receivedByteCount() override { KJ_FAIL_ASSERT("received bad WebSocket handshake"); }
7737
7738 private:
7739 kj::Exception exception;
7740 };
7741
7742 return kj::heap<BrokenWebSocket>(KJ_EXCEPTION(FAILED,
7743 "received bad WebSocket handshake", errorMessage));
7744 }
7745
7746 kj::Own<kj::AsyncIoStream> getConnectStream() {
7747 // Returns an AsyncIoStream over the internal stream but that waits for a Promise to be
7748 // resolved to allow writes after either accept or reject are called. Reads are allowed
7749 // immediately.
7750 KJ_REQUIRE(tunnelWriteGuard == nullptr, "the tunnel stream was already retrieved");
7751 auto paf = kj::newPromiseAndFulfiller<void>();
7752 tunnelWriteGuard = kj::mv(paf.fulfiller);
7753
7754 kj::Own<kj::AsyncIoStream> ownStream(&stream, kj::NullDisposer::instance);
7755 auto releasedBuffer = httpInput.releaseBuffer();
7756 auto deferNoteClosed = kj::defer([this]() { webSocketOrConnectClosed = true; });
7757 return kj::heap<AsyncIoStreamWithGuards>(
7758 kj::heap<AsyncIoStreamWithInitialBuffer>(
7759 kj::mv(ownStream),
7760 kj::mv(releasedBuffer.buffer),
7761 releasedBuffer.leftover).attach(kj::mv(deferNoteClosed)),
7762 kj::Maybe<HttpInputStreamImpl::ReleasedBuffer>(nullptr),
7763 kj::mv(paf.promise));
7764 }
7765
7766 void accept(uint statusCode, kj::StringPtr statusText, const HttpHeaders& headers) override {
7767 auto method = KJ_REQUIRE_NONNULL(currentMethod, "already called send()");
7768 currentMethod = nullptr;
7769 KJ_ASSERT(method.is<HttpConnectMethod>(), "only use accept() with CONNECT requests");
7770 KJ_REQUIRE(statusCode >= 200 && statusCode < 300, "the statusCode must be 2xx for accept");
7771 tunnelRejected = nullptr;
7772
7773 auto& fulfiller = KJ_ASSERT_NONNULL(tunnelWriteGuard, "the tunnel stream was not initialized");
7774 httpOutput.writeHeaders(headers.serializeResponse(statusCode, statusText));
7775 auto promise = httpOutput.flush().then([&fulfiller]() {
7776 fulfiller->fulfill();
7777 }).eagerlyEvaluate(nullptr);
7778 fulfiller = fulfiller.attach(kj::mv(promise));
7779 }
7780
7781 kj::Own<kj::AsyncOutputStream> reject(
7782 uint statusCode,
7783 kj::StringPtr statusText,
7784 const HttpHeaders& headers,
7785 kj::Maybe<uint64_t> expectedBodySize) override {
7786 auto method = KJ_REQUIRE_NONNULL(currentMethod, "already called send()");
7787 KJ_REQUIRE(method.is<HttpConnectMethod>(), "Only use reject() with CONNECT requests.");
7788 KJ_REQUIRE(statusCode < 200 || statusCode >= 300, "the statusCode must not be 2xx for reject.");
7789 tunnelRejected = Maybe<kj::Promise<bool>>(true);
7790
7791 auto& fulfiller = KJ_ASSERT_NONNULL(tunnelWriteGuard, "the tunnel stream was not initialized");
7792 fulfiller->reject(KJ_EXCEPTION(DISCONNECTED, "the tunnel request was rejected"));
7793 closeAfterSend = true;
7794 return send(statusCode, statusText, headers, expectedBodySize);
7795 }
7796 };
7797
7798 HttpServer::HttpServer(kj::Timer& timer, const HttpHeaderTable& requestHeaderTable,
7799 HttpService& service, Settings settings)
7800 : HttpServer(timer, requestHeaderTable, &service, settings,
7801 kj::newPromiseAndFulfiller<void>()) {}
7802
7803 HttpServer::HttpServer(kj::Timer& timer, const HttpHeaderTable& requestHeaderTable,
7804 HttpServiceFactory serviceFactory, Settings settings)
7805 : HttpServer(timer, requestHeaderTable, kj::mv(serviceFactory), settings,
7806 kj::newPromiseAndFulfiller<void>()) {}
7807
7808 HttpServer::HttpServer(kj::Timer& timer, const HttpHeaderTable& requestHeaderTable,
7809 kj::OneOf<HttpService*, HttpServiceFactory> service,
7810 Settings settings, kj::PromiseFulfillerPair<void> paf)
7811 : timer(timer), requestHeaderTable(requestHeaderTable), service(kj::mv(service)),
7812 settings(settings), onDrain(paf.promise.fork()), drainFulfiller(kj::mv(paf.fulfiller)),
7813 tasks(*this) {}
7814
7815 kj::Promise<void> HttpServer::drain() {
7816 KJ_REQUIRE(!draining, "you can only call drain() once");
7817
7818 draining = true;
7819 drainFulfiller->fulfill();
7820
7821 if (connectionCount == 0) {
7822 return kj::READY_NOW;
7823 } else {
7824 auto paf = kj::newPromiseAndFulfiller<void>();
7825 zeroConnectionsFulfiller = kj::mv(paf.fulfiller);
7826 return kj::mv(paf.promise);
7827 }
7828 }
7829
7830 kj::Promise<void> HttpServer::listenHttp(kj::ConnectionReceiver& port) {
7831 return listenLoop(port).exclusiveJoin(onDrain.addBranch());
7832 }
7833
7834 kj::Promise<void> HttpServer::listenLoop(kj::ConnectionReceiver& port) {
7835 return port.accept()
7836 .then([this,&port](kj::Own<kj::AsyncIoStream>&& connection) -> kj::Promise<void> {
7837 tasks.add(kj::evalNow([&]() { return listenHttp(kj::mv(connection)); }));
7838 return listenLoop(port);
7839 });
7840 }
7841
7842 kj::Promise<void> HttpServer::listenHttp(kj::Own<kj::AsyncIoStream> connection) {
7843 auto promise = listenHttpImpl(*connection, false /* wantCleanDrain */).ignoreResult();
7844
7845 // eagerlyEvaluate() to maintain historical guarantee that this method eagerly closes the
7846 // connection when done.
7847 return promise.attach(kj::mv(connection)).eagerlyEvaluate(nullptr);
7848 }
7849
7850 kj::Promise<bool> HttpServer::listenHttpCleanDrain(kj::AsyncIoStream& connection) {
7851 return listenHttpImpl(connection, true /* wantCleanDrain */);
7852 }
7853
7854 kj::Promise<bool> HttpServer::listenHttpImpl(kj::AsyncIoStream& connection, bool wantCleanDrain) {
7855 kj::Own<HttpService> srv;
7856
7857 KJ_SWITCH_ONEOF(service) {
7858 KJ_CASE_ONEOF(ptr, HttpService*) {
7859 // Fake Own okay because we can assume the HttpService outlives this HttpServer, and we can
7860 // assume `this` HttpServer outlives the returned `listenHttpCleanDrain()` promise, which will
7861 // own the fake Own.
7862 srv = kj::Own<HttpService>(ptr, kj::NullDisposer::instance);
7863 }
7864 KJ_CASE_ONEOF(func, HttpServiceFactory) {
7865 srv = func(connection);
7866 }
7867 }
7868
7869 KJ_ASSERT(srv.get() != nullptr);
7870
7871 return listenHttpImpl(connection, [srv = kj::mv(srv)](SuspendableRequest&) mutable {
7872 // This factory function will be owned by the Connection object, meaning the Connection object
7873 // will own the HttpService. We also know that the Connection object outlives all
7874 // service.request() promises (service.request() is called from a Connection member function).
7875 // The Owns we return from this function are attached to the service.request() promises,
7876 // meaning this factory function will outlive all Owns we return. So, it's safe to return a fake
7877 // Own.
7878 return kj::Own<HttpService>(srv.get(), kj::NullDisposer::instance);
7879 }, nullptr /* suspendedRequest */, wantCleanDrain);
7880 }
7881
7882 kj::Promise<bool> HttpServer::listenHttpCleanDrain(kj::AsyncIoStream& connection,
7883 SuspendableHttpServiceFactory factory,
7884 kj::Maybe<SuspendedRequest> suspendedRequest) {
7885 // Don't close on drain, because a "clean drain" means we return the connection to the
7886 // application still-open between requests so that it can continue serving future HTTP requests
7887 // on it.
7888 return listenHttpImpl(connection, kj::mv(factory), kj::mv(suspendedRequest),
7889 true /* wantCleanDrain */);
7890 }
7891
7892 kj::Promise<bool> HttpServer::listenHttpImpl(kj::AsyncIoStream& connection,
7893 SuspendableHttpServiceFactory factory,
7894 kj::Maybe<SuspendedRequest> suspendedRequest,
7895 bool wantCleanDrain) {
7896 auto obj = heap<Connection>(*this, connection, kj::mv(factory), kj::mv(suspendedRequest),
7897 wantCleanDrain);
7898
7899 // Start reading requests and responding to them, but immediately cancel processing if the client
7900 // disconnects.
7901 auto promise = obj->startLoop(true)
7902 .exclusiveJoin(connection.whenWriteDisconnected().then([]() {return false;}));
7903
7904 // Eagerly evaluate so that we drop the connection when the promise resolves, even if the caller
7905 // doesn't eagerly evaluate.
7906 return promise.attach(kj::mv(obj)).eagerlyEvaluate(nullptr);
7907 }
7908
7909 namespace {
7910 void defaultHandleListenLoopException(kj::Exception&& exception) {
7911 KJ_LOG(ERROR, "unhandled exception in HTTP server", exception);
7912 }
7913 } // namespace
7914
7915 void HttpServer::taskFailed(kj::Exception&& exception) {
7916 KJ_IF_MAYBE(handler, settings.errorHandler) {
7917 handler->handleListenLoopException(kj::mv(exception));
7918 } else {
7919 defaultHandleListenLoopException(kj::mv(exception));
7920 }
7921 }
7922
7923 HttpServer::SuspendedRequest::SuspendedRequest(
7924 kj::Array<byte> bufferParam, kj::ArrayPtr<byte> leftoverParam,
7925 kj::OneOf<HttpMethod, HttpConnectMethod> method,
7926 kj::StringPtr url, HttpHeaders headers)
7927 : buffer(kj::mv(bufferParam)),
7928 leftover(leftoverParam),
7929 method(method),
7930 url(url),
7931 headers(kj::mv(headers)) {
7932 if (leftover.size() > 0) {
7933 // We have a `leftover`; make sure it is a slice of `buffer`.
7934 KJ_ASSERT(leftover.begin() >= buffer.begin() && leftover.begin() <= buffer.end());
7935 KJ_ASSERT(leftover.end() >= buffer.begin() && leftover.end() <= buffer.end());
7936 } else {
7937 // We have no `leftover`, but we still expect it to point into `buffer` somewhere. This is
7938 // important so that `messageHeaderEnd` is initialized correctly in HttpInputStreamImpl's
7939 // constructor.
7940 KJ_ASSERT(leftover.begin() >= buffer.begin() && leftover.begin() <= buffer.end());
7941 }
7942 }
7943
7944 HttpServer::SuspendedRequest HttpServer::SuspendableRequest::suspend() {
7945 return connection.suspend(*this);
7946 }
7947
7948 kj::Promise<void> HttpServerErrorHandler::handleClientProtocolError(
7949 HttpHeaders::ProtocolError protocolError, kj::HttpService::Response& response) {
7950 // Default error handler implementation.
7951
7952 HttpHeaderTable headerTable {};
7953 HttpHeaders headers(headerTable);
7954 headers.set(HttpHeaderId::CONTENT_TYPE, "text/plain");
7955
7956 auto errorMessage = kj::str("ERROR: ", protocolError.description);
7957 auto body = response.send(protocolError.statusCode, protocolError.statusMessage,
7958 headers, errorMessage.size());
7959
7960 return body->write(errorMessage.begin(), errorMessage.size())
7961 .attach(kj::mv(errorMessage), kj::mv(body));
7962 }
7963
7964 kj::Promise<void> HttpServerErrorHandler::handleApplicationError(
7965 kj::Exception exception, kj::Maybe<kj::HttpService::Response&> response) {
7966 // Default error handler implementation.
7967
7968 if (exception.getType() == kj::Exception::Type::DISCONNECTED) {
7969 // How do we tell an HTTP client that there was a transient network error, and it should
7970 // try again immediately? There's no HTTP status code for this (503 is meant for "try
7971 // again later, not now"). Here's an idea: Don't send any response; just close the
7972 // connection, so that it looks like the connection between the HTTP client and server
7973 // was dropped. A good client should treat this exactly the way we want.
7974 //
7975 // We also bail here to avoid logging the disconnection, which isn't very interesting.
7976 return kj::READY_NOW;
7977 }
7978
7979 KJ_IF_MAYBE(r, response) {
7980 KJ_LOG(INFO, "threw exception while serving HTTP response", exception);
7981
7982 HttpHeaderTable headerTable {};
7983 HttpHeaders headers(headerTable);
7984 headers.set(HttpHeaderId::CONTENT_TYPE, "text/plain");
7985
7986 kj::String errorMessage;
7987 kj::Own<AsyncOutputStream> body;
7988
7989 if (exception.getType() == kj::Exception::Type::OVERLOADED) {
7990 errorMessage = kj::str(
7991 "ERROR: The server is temporarily unable to handle your request. Details:\n\n", exception);
7992 body = r->send(503, "Service Unavailable", headers, errorMessage.size());
7993 } else if (exception.getType() == kj::Exception::Type::UNIMPLEMENTED) {
7994 errorMessage = kj::str(
7995 "ERROR: The server does not implement this operation. Details:\n\n", exception);
7996 body = r->send(501, "Not Implemented", headers, errorMessage.size());
7997 } else {
7998 errorMessage = kj::str(
7999 "ERROR: The server threw an exception. Details:\n\n", exception);
8000 body = r->send(500, "Internal Server Error", headers, errorMessage.size());
8001 }
8002
8003 return body->write(errorMessage.begin(), errorMessage.size())
8004 .attach(kj::mv(errorMessage), kj::mv(body));
8005 }
8006
8007 KJ_LOG(ERROR, "HttpService threw exception after generating a partial response",
8008 "too late to report error to client", exception);
8009 return kj::READY_NOW;
8010 }
8011
8012 void HttpServerErrorHandler::handleListenLoopException(kj::Exception&& exception) {
8013 defaultHandleListenLoopException(kj::mv(exception));
8014 }
8015
8016 kj::Promise<void> HttpServerErrorHandler::handleNoResponse(kj::HttpService::Response& response) {
8017 HttpHeaderTable headerTable {};
8018 HttpHeaders headers(headerTable);
8019 headers.set(HttpHeaderId::CONTENT_TYPE, "text/plain");
8020
8021 constexpr auto errorMessage = "ERROR: The HttpService did not generate a response."_kj;
8022 auto body = response.send(500, "Internal Server Error", headers, errorMessage.size());
8023
8024 return body->write(errorMessage.begin(), errorMessage.size()).attach(kj::mv(body));
8025 }
8026
8027 } // namespace kj