| 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 |
#define KJ_TESTING_KJ 1 |
| 23 |
|
| 24 |
#include "http.h" |
| 25 |
#include <kj/debug.h> |
| 26 |
#include <kj/test.h> |
| 27 |
#include <kj/encoding.h> |
| 28 |
#include <kj/vector.h> |
| 29 |
#include <map> |
| 30 |
|
| 31 |
#if KJ_HTTP_TEST_USE_OS_PIPE |
| 32 |
// Run the test using OS-level socketpairs. (See http-socketpair-test.c++.) |
| 33 |
#define KJ_HTTP_TEST_SETUP_IO \ |
| 34 |
auto io = kj::setupAsyncIo(); \ |
| 35 |
auto& waitScope KJ_UNUSED = io.waitScope |
| 36 |
#define KJ_HTTP_TEST_SETUP_LOOPBACK_LISTENER_AND_ADDR \ |
| 37 |
auto listener = io.provider->getNetwork().parseAddress("localhost", 0) \ |
| 38 |
.wait(waitScope)->listen(); \ |
| 39 |
auto addr = io.provider->getNetwork().parseAddress("localhost", listener->getPort()) \ |
| 40 |
.wait(waitScope) |
| 41 |
#define KJ_HTTP_TEST_CREATE_2PIPE \ |
| 42 |
io.provider->newTwoWayPipe() |
| 43 |
#else |
| 44 |
// Run the test using in-process two-way pipes. |
| 45 |
#define KJ_HTTP_TEST_SETUP_IO \ |
| 46 |
kj::EventLoop eventLoop; \ |
| 47 |
kj::WaitScope waitScope(eventLoop) |
| 48 |
#define KJ_HTTP_TEST_SETUP_LOOPBACK_LISTENER_AND_ADDR \ |
| 49 |
auto capPipe = newCapabilityPipe(); \ |
| 50 |
auto listener = kj::heap<kj::CapabilityStreamConnectionReceiver>(*capPipe.ends[0]); \ |
| 51 |
auto addr = kj::heap<kj::CapabilityStreamNetworkAddress>(nullptr, *capPipe.ends[1]) |
| 52 |
#define KJ_HTTP_TEST_CREATE_2PIPE \ |
| 53 |
kj::newTwoWayPipe() |
| 54 |
#endif |
| 55 |
|
| 56 |
namespace kj { |
| 57 |
namespace { |
| 58 |
|
| 59 |
KJ_TEST("HttpMethod parse / stringify") { |
| 60 |
#define TRY(name) \ |
| 61 |
KJ_EXPECT(kj::str(HttpMethod::name) == #name); \ |
| 62 |
KJ_IF_MAYBE(parsed, tryParseHttpMethodAllowingConnect(#name)) { \ |
| 63 |
KJ_SWITCH_ONEOF(*parsed) { \ |
| 64 |
KJ_CASE_ONEOF(method, HttpMethod) { \ |
| 65 |
KJ_EXPECT(method == HttpMethod::name); \ |
| 66 |
} \ |
| 67 |
KJ_CASE_ONEOF(method, HttpConnectMethod) { \ |
| 68 |
KJ_FAIL_EXPECT("http method parsed as CONNECT", #name); \ |
| 69 |
} \ |
| 70 |
} \ |
| 71 |
} else { \ |
| 72 |
KJ_FAIL_EXPECT("couldn't parse \"" #name "\" as HttpMethod"); \ |
| 73 |
} |
| 74 |
|
| 75 |
KJ_HTTP_FOR_EACH_METHOD(TRY) |
| 76 |
#undef TRY |
| 77 |
|
| 78 |
KJ_EXPECT(tryParseHttpMethod("FOO") == nullptr); |
| 79 |
KJ_EXPECT(tryParseHttpMethod("") == nullptr); |
| 80 |
KJ_EXPECT(tryParseHttpMethod("G") == nullptr); |
| 81 |
KJ_EXPECT(tryParseHttpMethod("GE") == nullptr); |
| 82 |
KJ_EXPECT(tryParseHttpMethod("GET ") == nullptr); |
| 83 |
KJ_EXPECT(tryParseHttpMethod("get") == nullptr); |
| 84 |
|
| 85 |
KJ_EXPECT(KJ_ASSERT_NONNULL(tryParseHttpMethodAllowingConnect("CONNECT")) |
| 86 |
.is<HttpConnectMethod>()); |
| 87 |
KJ_EXPECT(tryParseHttpMethod("connect") == nullptr); |
| 88 |
} |
| 89 |
|
| 90 |
KJ_TEST("HttpHeaderTable") { |
| 91 |
HttpHeaderTable::Builder builder; |
| 92 |
|
| 93 |
auto host = builder.add("Host"); |
| 94 |
auto host2 = builder.add("hOsT"); |
| 95 |
auto fooBar = builder.add("Foo-Bar"); |
| 96 |
auto bazQux = builder.add("baz-qux"); |
| 97 |
auto bazQux2 = builder.add("Baz-Qux"); |
| 98 |
|
| 99 |
auto table = builder.build(); |
| 100 |
|
| 101 |
uint builtinHeaderCount = 0; |
| 102 |
#define INCREMENT(id, name) ++builtinHeaderCount; |
| 103 |
KJ_HTTP_FOR_EACH_BUILTIN_HEADER(INCREMENT) |
| 104 |
#undef INCREMENT |
| 105 |
|
| 106 |
KJ_EXPECT(table->idCount() == builtinHeaderCount + 2); |
| 107 |
|
| 108 |
KJ_EXPECT(host == HttpHeaderId::HOST); |
| 109 |
KJ_EXPECT(host != HttpHeaderId::DATE); |
| 110 |
KJ_EXPECT(host2 == host); |
| 111 |
|
| 112 |
KJ_EXPECT(host != fooBar); |
| 113 |
KJ_EXPECT(host != bazQux); |
| 114 |
KJ_EXPECT(fooBar != bazQux); |
| 115 |
KJ_EXPECT(bazQux == bazQux2); |
| 116 |
|
| 117 |
KJ_EXPECT(kj::str(host) == "Host"); |
| 118 |
KJ_EXPECT(kj::str(host2) == "Host"); |
| 119 |
KJ_EXPECT(kj::str(fooBar) == "Foo-Bar"); |
| 120 |
KJ_EXPECT(kj::str(bazQux) == "baz-qux"); |
| 121 |
KJ_EXPECT(kj::str(HttpHeaderId::HOST) == "Host"); |
| 122 |
|
| 123 |
KJ_EXPECT(table->idToString(HttpHeaderId::DATE) == "Date"); |
| 124 |
KJ_EXPECT(table->idToString(fooBar) == "Foo-Bar"); |
| 125 |
|
| 126 |
KJ_EXPECT(KJ_ASSERT_NONNULL(table->stringToId("Date")) == HttpHeaderId::DATE); |
| 127 |
KJ_EXPECT(KJ_ASSERT_NONNULL(table->stringToId("dATE")) == HttpHeaderId::DATE); |
| 128 |
KJ_EXPECT(KJ_ASSERT_NONNULL(table->stringToId("Foo-Bar")) == fooBar); |
| 129 |
KJ_EXPECT(KJ_ASSERT_NONNULL(table->stringToId("foo-BAR")) == fooBar); |
| 130 |
KJ_EXPECT(table->stringToId("foobar") == nullptr); |
| 131 |
KJ_EXPECT(table->stringToId("barfoo") == nullptr); |
| 132 |
} |
| 133 |
|
| 134 |
KJ_TEST("HttpHeaders::parseRequest") { |
| 135 |
HttpHeaderTable::Builder builder; |
| 136 |
|
| 137 |
auto fooBar = builder.add("Foo-Bar"); |
| 138 |
auto bazQux = builder.add("baz-qux"); |
| 139 |
|
| 140 |
auto table = builder.build(); |
| 141 |
|
| 142 |
HttpHeaders headers(*table); |
| 143 |
auto text = kj::heapString( |
| 144 |
"POST /some/path \t HTTP/1.1\r\n" |
| 145 |
"Foo-BaR: Baz\r\n" |
| 146 |
"Host: example.com\r\n" |
| 147 |
"Content-Length: 123\r\n" |
| 148 |
"DATE: early\r\n" |
| 149 |
"other-Header: yep\r\n" |
| 150 |
"with.dots: sure\r\n" |
| 151 |
"\r\n"); |
| 152 |
auto result = headers.tryParseRequest(text.asArray()).get<HttpHeaders::Request>(); |
| 153 |
|
| 154 |
KJ_EXPECT(result.method == HttpMethod::POST); |
| 155 |
KJ_EXPECT(result.url == "/some/path"); |
| 156 |
KJ_EXPECT(KJ_ASSERT_NONNULL(headers.get(HttpHeaderId::HOST)) == "example.com"); |
| 157 |
KJ_EXPECT(KJ_ASSERT_NONNULL(headers.get(HttpHeaderId::DATE)) == "early"); |
| 158 |
KJ_EXPECT(KJ_ASSERT_NONNULL(headers.get(fooBar)) == "Baz"); |
| 159 |
KJ_EXPECT(headers.get(bazQux) == nullptr); |
| 160 |
KJ_EXPECT(headers.get(HttpHeaderId::CONTENT_TYPE) == nullptr); |
| 161 |
KJ_EXPECT(KJ_ASSERT_NONNULL(headers.get(HttpHeaderId::CONTENT_LENGTH)) == "123"); |
| 162 |
KJ_EXPECT(headers.get(HttpHeaderId::TRANSFER_ENCODING) == nullptr); |
| 163 |
|
| 164 |
std::map<kj::StringPtr, kj::StringPtr> unpackedHeaders; |
| 165 |
headers.forEach([&](kj::StringPtr name, kj::StringPtr value) { |
| 166 |
KJ_EXPECT(unpackedHeaders.insert(std::make_pair(name, value)).second); |
| 167 |
}); |
| 168 |
KJ_EXPECT(unpackedHeaders.size() == 6); |
| 169 |
KJ_EXPECT(unpackedHeaders["Content-Length"] == "123"); |
| 170 |
KJ_EXPECT(unpackedHeaders["Host"] == "example.com"); |
| 171 |
KJ_EXPECT(unpackedHeaders["Date"] == "early"); |
| 172 |
KJ_EXPECT(unpackedHeaders["Foo-Bar"] == "Baz"); |
| 173 |
KJ_EXPECT(unpackedHeaders["other-Header"] == "yep"); |
| 174 |
KJ_EXPECT(unpackedHeaders["with.dots"] == "sure"); |
| 175 |
|
| 176 |
KJ_EXPECT(headers.serializeRequest(result.method, result.url) == |
| 177 |
"POST /some/path HTTP/1.1\r\n" |
| 178 |
"Content-Length: 123\r\n" |
| 179 |
"Host: example.com\r\n" |
| 180 |
"Date: early\r\n" |
| 181 |
"Foo-Bar: Baz\r\n" |
| 182 |
"other-Header: yep\r\n" |
| 183 |
"with.dots: sure\r\n" |
| 184 |
"\r\n"); |
| 185 |
} |
| 186 |
|
| 187 |
KJ_TEST("HttpHeaders::parseResponse") { |
| 188 |
HttpHeaderTable::Builder builder; |
| 189 |
|
| 190 |
auto fooBar = builder.add("Foo-Bar"); |
| 191 |
auto bazQux = builder.add("baz-qux"); |
| 192 |
|
| 193 |
auto table = builder.build(); |
| 194 |
|
| 195 |
HttpHeaders headers(*table); |
| 196 |
auto text = kj::heapString( |
| 197 |
"HTTP/1.1\t\t 418\t I'm a teapot\r\n" |
| 198 |
"Foo-BaR: Baz\r\n" |
| 199 |
"Host: example.com\r\n" |
| 200 |
"Content-Length: 123\r\n" |
| 201 |
"DATE: early\r\n" |
| 202 |
"other-Header: yep\r\n" |
| 203 |
"\r\n"); |
| 204 |
auto result = headers.tryParseResponse(text.asArray()).get<HttpHeaders::Response>(); |
| 205 |
|
| 206 |
KJ_EXPECT(result.statusCode == 418); |
| 207 |
KJ_EXPECT(result.statusText == "I'm a teapot"); |
| 208 |
KJ_EXPECT(KJ_ASSERT_NONNULL(headers.get(HttpHeaderId::HOST)) == "example.com"); |
| 209 |
KJ_EXPECT(KJ_ASSERT_NONNULL(headers.get(HttpHeaderId::DATE)) == "early"); |
| 210 |
KJ_EXPECT(KJ_ASSERT_NONNULL(headers.get(fooBar)) == "Baz"); |
| 211 |
KJ_EXPECT(headers.get(bazQux) == nullptr); |
| 212 |
KJ_EXPECT(headers.get(HttpHeaderId::CONTENT_TYPE) == nullptr); |
| 213 |
KJ_EXPECT(KJ_ASSERT_NONNULL(headers.get(HttpHeaderId::CONTENT_LENGTH)) == "123"); |
| 214 |
KJ_EXPECT(headers.get(HttpHeaderId::TRANSFER_ENCODING) == nullptr); |
| 215 |
|
| 216 |
std::map<kj::StringPtr, kj::StringPtr> unpackedHeaders; |
| 217 |
headers.forEach([&](kj::StringPtr name, kj::StringPtr value) { |
| 218 |
KJ_EXPECT(unpackedHeaders.insert(std::make_pair(name, value)).second); |
| 219 |
}); |
| 220 |
KJ_EXPECT(unpackedHeaders.size() == 5); |
| 221 |
KJ_EXPECT(unpackedHeaders["Content-Length"] == "123"); |
| 222 |
KJ_EXPECT(unpackedHeaders["Host"] == "example.com"); |
| 223 |
KJ_EXPECT(unpackedHeaders["Date"] == "early"); |
| 224 |
KJ_EXPECT(unpackedHeaders["Foo-Bar"] == "Baz"); |
| 225 |
KJ_EXPECT(unpackedHeaders["other-Header"] == "yep"); |
| 226 |
|
| 227 |
KJ_EXPECT(headers.serializeResponse( |
| 228 |
result.statusCode, result.statusText) == |
| 229 |
"HTTP/1.1 418 I'm a teapot\r\n" |
| 230 |
"Content-Length: 123\r\n" |
| 231 |
"Host: example.com\r\n" |
| 232 |
"Date: early\r\n" |
| 233 |
"Foo-Bar: Baz\r\n" |
| 234 |
"other-Header: yep\r\n" |
| 235 |
"\r\n"); |
| 236 |
} |
| 237 |
|
| 238 |
KJ_TEST("HttpHeaders parse invalid") { |
| 239 |
auto table = HttpHeaderTable::Builder().build(); |
| 240 |
HttpHeaders headers(*table); |
| 241 |
|
| 242 |
// NUL byte in request. |
| 243 |
{ |
| 244 |
auto input = kj::heapString( |
| 245 |
"POST \0 /some/path \t HTTP/1.1\r\n" |
| 246 |
"Foo-BaR: Baz\r\n" |
| 247 |
"Host: example.com\r\n" |
| 248 |
"DATE: early\r\n" |
| 249 |
"other-Header: yep\r\n" |
| 250 |
"\r\n"); |
| 251 |
|
| 252 |
auto protocolError = headers.tryParseRequest(input).get<HttpHeaders::ProtocolError>(); |
| 253 |
|
| 254 |
KJ_EXPECT(protocolError.description == "Request headers have no terminal newline.", |
| 255 |
protocolError.description); |
| 256 |
KJ_EXPECT(protocolError.rawContent.asChars() == input); |
| 257 |
} |
| 258 |
|
| 259 |
// Control character in header name. |
| 260 |
{ |
| 261 |
auto input = kj::heapString( |
| 262 |
"POST /some/path \t HTTP/1.1\r\n" |
| 263 |
"Foo-BaR: Baz\r\n" |
| 264 |
"Cont\001ent-Length: 123\r\n" |
| 265 |
"DATE: early\r\n" |
| 266 |
"other-Header: yep\r\n" |
| 267 |
"\r\n"); |
| 268 |
|
| 269 |
auto protocolError = headers.tryParseRequest(input).get<HttpHeaders::ProtocolError>(); |
| 270 |
|
| 271 |
KJ_EXPECT(protocolError.description == "The headers sent by your client are not valid.", |
| 272 |
protocolError.description); |
| 273 |
KJ_EXPECT(protocolError.rawContent.asChars() == input); |
| 274 |
} |
| 275 |
|
| 276 |
// Separator character in header name. |
| 277 |
{ |
| 278 |
auto input = kj::heapString( |
| 279 |
"POST /some/path \t HTTP/1.1\r\n" |
| 280 |
"Foo-BaR: Baz\r\n" |
| 281 |
"Host: example.com\r\n" |
| 282 |
"DATE/: early\r\n" |
| 283 |
"other-Header: yep\r\n" |
| 284 |
"\r\n"); |
| 285 |
|
| 286 |
auto protocolError = headers.tryParseRequest(input).get<HttpHeaders::ProtocolError>(); |
| 287 |
|
| 288 |
KJ_EXPECT(protocolError.description == "The headers sent by your client are not valid.", |
| 289 |
protocolError.description); |
| 290 |
KJ_EXPECT(protocolError.rawContent.asChars() == input); |
| 291 |
} |
| 292 |
|
| 293 |
// Response status code not numeric. |
| 294 |
{ |
| 295 |
auto input = kj::heapString( |
| 296 |
"HTTP/1.1\t\t abc\t I'm a teapot\r\n" |
| 297 |
"Foo-BaR: Baz\r\n" |
| 298 |
"Host: example.com\r\n" |
| 299 |
"DATE: early\r\n" |
| 300 |
"other-Header: yep\r\n" |
| 301 |
"\r\n"); |
| 302 |
|
| 303 |
auto protocolError = headers.tryParseRequest(input).get<HttpHeaders::ProtocolError>(); |
| 304 |
|
| 305 |
KJ_EXPECT(protocolError.description == "Unrecognized request method.", |
| 306 |
protocolError.description); |
| 307 |
KJ_EXPECT(protocolError.rawContent.asChars() == input); |
| 308 |
} |
| 309 |
} |
| 310 |
|
| 311 |
KJ_TEST("HttpHeaders require valid HttpHeaderTable") { |
| 312 |
const auto ERROR_MESSAGE = |
| 313 |
"HttpHeaders object was constructed from HttpHeaderTable " |
| 314 |
"that wasn't fully built yet at the time of construction"_kj; |
| 315 |
|
| 316 |
{ |
| 317 |
// A tabula rasa is valid. |
| 318 |
HttpHeaderTable table; |
| 319 |
KJ_REQUIRE(table.isReady()); |
| 320 |
|
| 321 |
HttpHeaders headers(table); |
| 322 |
} |
| 323 |
|
| 324 |
{ |
| 325 |
// A future table is not valid. |
| 326 |
HttpHeaderTable::Builder builder; |
| 327 |
|
| 328 |
auto& futureTable = builder.getFutureTable(); |
| 329 |
KJ_REQUIRE(!futureTable.isReady()); |
| 330 |
|
| 331 |
auto makeHeadersThenBuild = [&]() { |
| 332 |
HttpHeaders headers(futureTable); |
| 333 |
auto table = builder.build(); |
| 334 |
}; |
| 335 |
KJ_EXPECT_THROW_MESSAGE(ERROR_MESSAGE, makeHeadersThenBuild()); |
| 336 |
} |
| 337 |
|
| 338 |
{ |
| 339 |
// A well built table is valid. |
| 340 |
HttpHeaderTable::Builder builder; |
| 341 |
|
| 342 |
auto& futureTable = builder.getFutureTable(); |
| 343 |
KJ_REQUIRE(!futureTable.isReady()); |
| 344 |
|
| 345 |
auto ownedTable = builder.build(); |
| 346 |
KJ_REQUIRE(futureTable.isReady()); |
| 347 |
KJ_REQUIRE(ownedTable->isReady()); |
| 348 |
|
| 349 |
HttpHeaders headers(futureTable); |
| 350 |
} |
| 351 |
} |
| 352 |
|
| 353 |
KJ_TEST("HttpHeaders validation") { |
| 354 |
auto table = HttpHeaderTable::Builder().build(); |
| 355 |
HttpHeaders headers(*table); |
| 356 |
|
| 357 |
headers.add("Valid-Name", "valid value"); |
| 358 |
|
| 359 |
// The HTTP RFC prohibits control characters, but browsers only prohibit \0, \r, and \n. KJ goes |
| 360 |
// with the browsers for compatibility. |
| 361 |
headers.add("Valid-Name", "valid\x01value"); |
| 362 |
|
| 363 |
// The HTTP RFC does not permit non-ASCII values. |
| 364 |
// KJ chooses to interpret them as UTF-8, to avoid the need for any expensive conversion. |
| 365 |
// Browsers apparently interpret them as LATIN-1. Applications can reinterpet these strings as |
| 366 |
// LATIN-1 easily enough if they really need to. |
| 367 |
headers.add("Valid-Name", u8"valid€value"); |
| 368 |
|
| 369 |
KJ_EXPECT_THROW_MESSAGE("invalid header name", headers.add("Invalid Name", "value")); |
| 370 |
KJ_EXPECT_THROW_MESSAGE("invalid header name", headers.add("Invalid@Name", "value")); |
| 371 |
|
| 372 |
KJ_EXPECT_THROW_MESSAGE("invalid header value", headers.set(HttpHeaderId::HOST, "in\nvalid")); |
| 373 |
KJ_EXPECT_THROW_MESSAGE("invalid header value", headers.add("Valid-Name", "in\nvalid")); |
| 374 |
} |
| 375 |
|
| 376 |
KJ_TEST("HttpHeaders Set-Cookie handling") { |
| 377 |
HttpHeaderTable::Builder builder; |
| 378 |
auto hCookie = builder.add("Cookie"); |
| 379 |
auto hSetCookie = builder.add("Set-Cookie"); |
| 380 |
auto table = builder.build(); |
| 381 |
|
| 382 |
HttpHeaders headers(*table); |
| 383 |
headers.set(hCookie, "Foo"); |
| 384 |
headers.add("Cookie", "Bar"); |
| 385 |
headers.add("Cookie", "Baz"); |
| 386 |
headers.set(hSetCookie, "Foo"); |
| 387 |
headers.add("Set-Cookie", "Bar"); |
| 388 |
headers.add("Set-Cookie", "Baz"); |
| 389 |
|
| 390 |
auto text = headers.toString(); |
| 391 |
KJ_EXPECT(text == |
| 392 |
"Cookie: Foo, Bar, Baz\r\n" |
| 393 |
"Set-Cookie: Foo\r\n" |
| 394 |
"Set-Cookie: Bar\r\n" |
| 395 |
"Set-Cookie: Baz\r\n" |
| 396 |
"\r\n", text); |
| 397 |
} |
| 398 |
|
| 399 |
// ======================================================================================= |
| 400 |
|
| 401 |
class ReadFragmenter final: public kj::AsyncIoStream { |
| 402 |
public: |
| 403 |
ReadFragmenter(AsyncIoStream& inner, size_t limit): inner(inner), limit(limit) {} |
| 404 |
|
| 405 |
Promise<size_t> read(void* buffer, size_t minBytes, size_t maxBytes) override { |
| 406 |
return inner.read(buffer, minBytes, kj::max(minBytes, kj::min(limit, maxBytes))); |
| 407 |
} |
| 408 |
Promise<size_t> tryRead(void* buffer, size_t minBytes, size_t maxBytes) override { |
| 409 |
return inner.tryRead(buffer, minBytes, kj::max(minBytes, kj::min(limit, maxBytes))); |
| 410 |
} |
| 411 |
|
| 412 |
Maybe<uint64_t> tryGetLength() override { return inner.tryGetLength(); } |
| 413 |
|
| 414 |
Promise<uint64_t> pumpTo(AsyncOutputStream& output, uint64_t amount) override { |
| 415 |
return inner.pumpTo(output, amount); |
| 416 |
} |
| 417 |
|
| 418 |
Promise<void> write(const void* buffer, size_t size) override { |
| 419 |
return inner.write(buffer, size); |
| 420 |
} |
| 421 |
Promise<void> write(ArrayPtr<const ArrayPtr<const byte>> pieces) override { |
| 422 |
return inner.write(pieces); |
| 423 |
} |
| 424 |
|
| 425 |
Maybe<Promise<uint64_t>> tryPumpFrom(AsyncInputStream& input, uint64_t amount) override { |
| 426 |
return inner.tryPumpFrom(input, amount); |
| 427 |
} |
| 428 |
|
| 429 |
Promise<void> whenWriteDisconnected() override { |
| 430 |
return inner.whenWriteDisconnected(); |
| 431 |
} |
| 432 |
|
| 433 |
void shutdownWrite() override { |
| 434 |
return inner.shutdownWrite(); |
| 435 |
} |
| 436 |
|
| 437 |
void abortRead() override { return inner.abortRead(); } |
| 438 |
|
| 439 |
void getsockopt(int level, int option, void* value, uint* length) override { |
| 440 |
return inner.getsockopt(level, option, value, length); |
| 441 |
} |
| 442 |
void setsockopt(int level, int option, const void* value, uint length) override { |
| 443 |
return inner.setsockopt(level, option, value, length); |
| 444 |
} |
| 445 |
|
| 446 |
void getsockname(struct sockaddr* addr, uint* length) override { |
| 447 |
return inner.getsockname(addr, length); |
| 448 |
} |
| 449 |
void getpeername(struct sockaddr* addr, uint* length) override { |
| 450 |
return inner.getsockname(addr, length); |
| 451 |
} |
| 452 |
|
| 453 |
private: |
| 454 |
kj::AsyncIoStream& inner; |
| 455 |
size_t limit; |
| 456 |
}; |
| 457 |
|
| 458 |
template <typename T> |
| 459 |
class InitializeableArray: public Array<T> { |
| 460 |
public: |
| 461 |
InitializeableArray(std::initializer_list<T> init) |
| 462 |
: Array<T>(kj::heapArray(init)) {} |
| 463 |
}; |
| 464 |
|
| 465 |
enum Side { BOTH, CLIENT_ONLY, SERVER_ONLY }; |
| 466 |
|
| 467 |
struct HeaderTestCase { |
| 468 |
HttpHeaderId id; |
| 469 |
kj::StringPtr value; |
| 470 |
}; |
| 471 |
|
| 472 |
struct HttpRequestTestCase { |
| 473 |
kj::StringPtr raw; |
| 474 |
|
| 475 |
HttpMethod method; |
| 476 |
kj::StringPtr path; |
| 477 |
InitializeableArray<HeaderTestCase> requestHeaders; |
| 478 |
kj::Maybe<uint64_t> requestBodySize; |
| 479 |
InitializeableArray<kj::StringPtr> requestBodyParts; |
| 480 |
|
| 481 |
Side side = BOTH; |
| 482 |
|
| 483 |
// TODO(cleanup): Delete this constructor if/when we move to C++14. |
| 484 |
HttpRequestTestCase(kj::StringPtr raw, HttpMethod method, kj::StringPtr path, |
| 485 |
InitializeableArray<HeaderTestCase> requestHeaders, |
| 486 |
kj::Maybe<uint64_t> requestBodySize, |
| 487 |
InitializeableArray<kj::StringPtr> requestBodyParts, |
| 488 |
Side side = BOTH) |
| 489 |
: raw(raw), method(method), path(path), requestHeaders(kj::mv(requestHeaders)), |
| 490 |
requestBodySize(requestBodySize), requestBodyParts(kj::mv(requestBodyParts)), |
| 491 |
side(side) {} |
| 492 |
}; |
| 493 |
|
| 494 |
struct HttpResponseTestCase { |
| 495 |
kj::StringPtr raw; |
| 496 |
|
| 497 |
uint64_t statusCode; |
| 498 |
kj::StringPtr statusText; |
| 499 |
InitializeableArray<HeaderTestCase> responseHeaders; |
| 500 |
kj::Maybe<uint64_t> responseBodySize; |
| 501 |
InitializeableArray<kj::StringPtr> responseBodyParts; |
| 502 |
|
| 503 |
HttpMethod method = HttpMethod::GET; |
| 504 |
|
| 505 |
Side side = BOTH; |
| 506 |
|
| 507 |
// TODO(cleanup): Delete this constructor if/when we move to C++14. |
| 508 |
HttpResponseTestCase(kj::StringPtr raw, uint64_t statusCode, kj::StringPtr statusText, |
| 509 |
InitializeableArray<HeaderTestCase> responseHeaders, |
| 510 |
kj::Maybe<uint64_t> responseBodySize, |
| 511 |
InitializeableArray<kj::StringPtr> responseBodyParts, |
| 512 |
HttpMethod method = HttpMethod::GET, |
| 513 |
Side side = BOTH) |
| 514 |
: raw(raw), statusCode(statusCode), statusText(statusText), |
| 515 |
responseHeaders(kj::mv(responseHeaders)), responseBodySize(responseBodySize), |
| 516 |
responseBodyParts(kj::mv(responseBodyParts)), method(method), side(side) {} |
| 517 |
}; |
| 518 |
|
| 519 |
struct HttpTestCase { |
| 520 |
HttpRequestTestCase request; |
| 521 |
HttpResponseTestCase response; |
| 522 |
}; |
| 523 |
|
| 524 |
kj::Promise<void> writeEach(kj::AsyncOutputStream& out, kj::ArrayPtr<const kj::StringPtr> parts) { |
| 525 |
if (parts.size() == 0) return kj::READY_NOW; |
| 526 |
|
| 527 |
return out.write(parts[0].begin(), parts[0].size()) |
| 528 |
.then([&out,parts]() { |
| 529 |
return writeEach(out, parts.slice(1, parts.size())); |
| 530 |
}); |
| 531 |
} |
| 532 |
|
| 533 |
kj::Promise<void> expectRead(kj::AsyncInputStream& in, kj::StringPtr expected) { |
| 534 |
if (expected.size() == 0) return kj::READY_NOW; |
| 535 |
|
| 536 |
auto buffer = kj::heapArray<char>(expected.size()); |
| 537 |
|
| 538 |
auto promise = in.tryRead(buffer.begin(), 1, buffer.size()); |
| 539 |
return promise.then([&in,expected,buffer=kj::mv(buffer)](size_t amount) { |
| 540 |
if (amount == 0) { |
| 541 |
KJ_FAIL_ASSERT("expected data never sent", expected); |
| 542 |
} |
| 543 |
|
| 544 |
auto actual = buffer.slice(0, amount); |
| 545 |
if (memcmp(actual.begin(), expected.begin(), actual.size()) != 0) { |
| 546 |
KJ_FAIL_ASSERT("data from stream doesn't match expected", expected, actual); |
| 547 |
} |
| 548 |
|
| 549 |
return expectRead(in, expected.slice(amount)); |
| 550 |
}); |
| 551 |
} |
| 552 |
|
| 553 |
kj::Promise<void> expectRead(kj::AsyncInputStream& in, kj::ArrayPtr<const byte> expected) { |
| 554 |
if (expected.size() == 0) return kj::READY_NOW; |
| 555 |
|
| 556 |
auto buffer = kj::heapArray<byte>(expected.size()); |
| 557 |
|
| 558 |
auto promise = in.tryRead(buffer.begin(), 1, buffer.size()); |
| 559 |
return promise.then([&in,expected,buffer=kj::mv(buffer)](size_t amount) { |
| 560 |
if (amount == 0) { |
| 561 |
KJ_FAIL_ASSERT("expected data never sent", expected); |
| 562 |
} |
| 563 |
|
| 564 |
auto actual = buffer.slice(0, amount); |
| 565 |
if (memcmp(actual.begin(), expected.begin(), actual.size()) != 0) { |
| 566 |
KJ_FAIL_ASSERT("data from stream doesn't match expected", expected, actual); |
| 567 |
} |
| 568 |
|
| 569 |
return expectRead(in, expected.slice(amount, expected.size())); |
| 570 |
}); |
| 571 |
} |
| 572 |
|
| 573 |
kj::Promise<void> expectEnd(kj::AsyncInputStream& in) { |
| 574 |
static char buffer; |
| 575 |
|
| 576 |
auto promise = in.tryRead(&buffer, 1, 1); |
| 577 |
return promise.then([](size_t amount) { |
| 578 |
KJ_ASSERT(amount == 0, "expected EOF"); |
| 579 |
}); |
| 580 |
} |
| 581 |
|
| 582 |
void testHttpClientRequest(kj::WaitScope& waitScope, const HttpRequestTestCase& testCase, |
| 583 |
kj::TwoWayPipe pipe) { |
| 584 |
|
| 585 |
auto serverTask = expectRead(*pipe.ends[1], testCase.raw).then([&]() { |
| 586 |
static const char SIMPLE_RESPONSE[] = |
| 587 |
"HTTP/1.1 200 OK\r\n" |
| 588 |
"Content-Length: 0\r\n" |
| 589 |
"\r\n"; |
| 590 |
return pipe.ends[1]->write(SIMPLE_RESPONSE, strlen(SIMPLE_RESPONSE)); |
| 591 |
}).then([&]() -> kj::Promise<void> { |
| 592 |
return kj::NEVER_DONE; |
| 593 |
}); |
| 594 |
|
| 595 |
HttpHeaderTable table; |
| 596 |
auto client = newHttpClient(table, *pipe.ends[0]); |
| 597 |
|
| 598 |
HttpHeaders headers(table); |
| 599 |
for (auto& header: testCase.requestHeaders) { |
| 600 |
headers.set(header.id, header.value); |
| 601 |
} |
| 602 |
|
| 603 |
auto request = client->request(testCase.method, testCase.path, headers, testCase.requestBodySize); |
| 604 |
if (testCase.requestBodyParts.size() > 0) { |
| 605 |
writeEach(*request.body, testCase.requestBodyParts).wait(waitScope); |
| 606 |
} |
| 607 |
request.body = nullptr; |
| 608 |
auto clientTask = request.response |
| 609 |
.then([&](HttpClient::Response&& response) { |
| 610 |
auto promise = response.body->readAllText(); |
| 611 |
return promise.attach(kj::mv(response.body)); |
| 612 |
}).ignoreResult(); |
| 613 |
|
| 614 |
serverTask.exclusiveJoin(kj::mv(clientTask)).wait(waitScope); |
| 615 |
|
| 616 |
// Verify no more data written by client. |
| 617 |
client = nullptr; |
| 618 |
pipe.ends[0]->shutdownWrite(); |
| 619 |
KJ_EXPECT(pipe.ends[1]->readAllText().wait(waitScope) == ""); |
| 620 |
} |
| 621 |
|
| 622 |
void testHttpClientResponse(kj::WaitScope& waitScope, const HttpResponseTestCase& testCase, |
| 623 |
size_t readFragmentSize, kj::TwoWayPipe pipe) { |
| 624 |
ReadFragmenter fragmenter(*pipe.ends[0], readFragmentSize); |
| 625 |
|
| 626 |
auto expectedReqText = testCase.method == HttpMethod::GET || testCase.method == HttpMethod::HEAD |
| 627 |
? kj::str(testCase.method, " / HTTP/1.1\r\n\r\n") |
| 628 |
: kj::str(testCase.method, " / HTTP/1.1\r\nContent-Length: 0\r\n"); |
| 629 |
|
| 630 |
auto serverTask = expectRead(*pipe.ends[1], expectedReqText).then([&]() { |
| 631 |
return pipe.ends[1]->write(testCase.raw.begin(), testCase.raw.size()); |
| 632 |
}).then([&]() -> kj::Promise<void> { |
| 633 |
pipe.ends[1]->shutdownWrite(); |
| 634 |
return kj::NEVER_DONE; |
| 635 |
}); |
| 636 |
|
| 637 |
HttpHeaderTable table; |
| 638 |
auto client = newHttpClient(table, fragmenter); |
| 639 |
|
| 640 |
HttpHeaders headers(table); |
| 641 |
auto request = client->request(testCase.method, "/", headers, uint64_t(0)); |
| 642 |
request.body = nullptr; |
| 643 |
auto clientTask = request.response |
| 644 |
.then([&](HttpClient::Response&& response) { |
| 645 |
KJ_EXPECT(response.statusCode == testCase.statusCode); |
| 646 |
KJ_EXPECT(response.statusText == testCase.statusText); |
| 647 |
|
| 648 |
for (auto& header: testCase.responseHeaders) { |
| 649 |
KJ_EXPECT(KJ_ASSERT_NONNULL(response.headers->get(header.id)) == header.value); |
| 650 |
} |
| 651 |
auto promise = response.body->readAllText(); |
| 652 |
return promise.attach(kj::mv(response.body)); |
| 653 |
}).then([&](kj::String body) { |
| 654 |
KJ_EXPECT(body == kj::strArray(testCase.responseBodyParts, ""), body); |
| 655 |
}); |
| 656 |
|
| 657 |
serverTask.exclusiveJoin(kj::mv(clientTask)).wait(waitScope); |
| 658 |
|
| 659 |
// Verify no more data written by client. |
| 660 |
client = nullptr; |
| 661 |
pipe.ends[0]->shutdownWrite(); |
| 662 |
KJ_EXPECT(pipe.ends[1]->readAllText().wait(waitScope) == ""); |
| 663 |
} |
| 664 |
|
| 665 |
void testHttpClient(kj::WaitScope& waitScope, HttpHeaderTable& table, |
| 666 |
HttpClient& client, const HttpTestCase& testCase) { |
| 667 |
KJ_CONTEXT(testCase.request.raw, testCase.response.raw); |
| 668 |
|
| 669 |
HttpHeaders headers(table); |
| 670 |
for (auto& header: testCase.request.requestHeaders) { |
| 671 |
headers.set(header.id, header.value); |
| 672 |
} |
| 673 |
|
| 674 |
auto request = client.request( |
| 675 |
testCase.request.method, testCase.request.path, headers, testCase.request.requestBodySize); |
| 676 |
for (auto& part: testCase.request.requestBodyParts) { |
| 677 |
request.body->write(part.begin(), part.size()).wait(waitScope); |
| 678 |
} |
| 679 |
request.body = nullptr; |
| 680 |
|
| 681 |
auto response = request.response.wait(waitScope); |
| 682 |
|
| 683 |
KJ_EXPECT(response.statusCode == testCase.response.statusCode); |
| 684 |
auto body = response.body->readAllText().wait(waitScope); |
| 685 |
if (testCase.request.method == HttpMethod::HEAD) { |
| 686 |
KJ_EXPECT(body == ""); |
| 687 |
} else { |
| 688 |
KJ_EXPECT(body == kj::strArray(testCase.response.responseBodyParts, ""), body); |
| 689 |
} |
| 690 |
} |
| 691 |
|
| 692 |
class TestHttpService final: public HttpService { |
| 693 |
public: |
| 694 |
TestHttpService(const HttpRequestTestCase& expectedRequest, |
| 695 |
const HttpResponseTestCase& response, |
| 696 |
HttpHeaderTable& table) |
| 697 |
: singleExpectedRequest(&expectedRequest), |
| 698 |
singleResponse(&response), |
| 699 |
responseHeaders(table) {} |
| 700 |
TestHttpService(kj::ArrayPtr<const HttpTestCase> testCases, |
| 701 |
HttpHeaderTable& table) |
| 702 |
: singleExpectedRequest(nullptr), |
| 703 |
singleResponse(nullptr), |
| 704 |
testCases(testCases), |
| 705 |
responseHeaders(table) {} |
| 706 |
|
| 707 |
uint getRequestCount() { return requestCount; } |
| 708 |
|
| 709 |
kj::Promise<void> request( |
| 710 |
HttpMethod method, kj::StringPtr url, const HttpHeaders& headers, |
| 711 |
kj::AsyncInputStream& requestBody, Response& responseSender) override { |
| 712 |
auto& expectedRequest = testCases == nullptr ? *singleExpectedRequest : |
| 713 |
testCases[requestCount % testCases.size()].request; |
| 714 |
auto& response = testCases == nullptr ? *singleResponse : |
| 715 |
testCases[requestCount % testCases.size()].response; |
| 716 |
|
| 717 |
++requestCount; |
| 718 |
|
| 719 |
KJ_EXPECT(method == expectedRequest.method, method); |
| 720 |
KJ_EXPECT(url == expectedRequest.path, url); |
| 721 |
|
| 722 |
for (auto& header: expectedRequest.requestHeaders) { |
| 723 |
KJ_EXPECT(KJ_ASSERT_NONNULL(headers.get(header.id)) == header.value); |
| 724 |
} |
| 725 |
|
| 726 |
auto size = requestBody.tryGetLength(); |
| 727 |
KJ_IF_MAYBE(expectedSize, expectedRequest.requestBodySize) { |
| 728 |
KJ_IF_MAYBE(s, size) { |
| 729 |
KJ_EXPECT(*s == *expectedSize, *s); |
| 730 |
} else { |
| 731 |
KJ_FAIL_EXPECT("tryGetLength() returned nullptr; expected known size"); |
| 732 |
} |
| 733 |
} else { |
| 734 |
KJ_EXPECT(size == nullptr); |
| 735 |
} |
| 736 |
|
| 737 |
return requestBody.readAllText() |
| 738 |
.then([this,&expectedRequest,&response,&responseSender](kj::String text) { |
| 739 |
KJ_EXPECT(text == kj::strArray(expectedRequest.requestBodyParts, ""), text); |
| 740 |
|
| 741 |
responseHeaders.clear(); |
| 742 |
for (auto& header: response.responseHeaders) { |
| 743 |
responseHeaders.set(header.id, header.value); |
| 744 |
} |
| 745 |
|
| 746 |
auto stream = responseSender.send(response.statusCode, response.statusText, |
| 747 |
responseHeaders, response.responseBodySize); |
| 748 |
auto promise = writeEach(*stream, response.responseBodyParts); |
| 749 |
return promise.attach(kj::mv(stream)); |
| 750 |
}); |
| 751 |
} |
| 752 |
|
| 753 |
private: |
| 754 |
const HttpRequestTestCase* singleExpectedRequest; |
| 755 |
const HttpResponseTestCase* singleResponse; |
| 756 |
kj::ArrayPtr<const HttpTestCase> testCases; |
| 757 |
HttpHeaders responseHeaders; |
| 758 |
uint requestCount = 0; |
| 759 |
}; |
| 760 |
|
| 761 |
void testHttpServerRequest(kj::WaitScope& waitScope, kj::Timer& timer, |
| 762 |
const HttpRequestTestCase& requestCase, |
| 763 |
const HttpResponseTestCase& responseCase, |
| 764 |
kj::TwoWayPipe pipe) { |
| 765 |
HttpHeaderTable table; |
| 766 |
TestHttpService service(requestCase, responseCase, table); |
| 767 |
HttpServer server(timer, table, service); |
| 768 |
|
| 769 |
auto listenTask = server.listenHttp(kj::mv(pipe.ends[0])); |
| 770 |
|
| 771 |
pipe.ends[1]->write(requestCase.raw.begin(), requestCase.raw.size()).wait(waitScope); |
| 772 |
pipe.ends[1]->shutdownWrite(); |
| 773 |
|
| 774 |
expectRead(*pipe.ends[1], responseCase.raw).wait(waitScope); |
| 775 |
|
| 776 |
listenTask.wait(waitScope); |
| 777 |
|
| 778 |
KJ_EXPECT(service.getRequestCount() == 1); |
| 779 |
} |
| 780 |
|
| 781 |
kj::ArrayPtr<const HttpRequestTestCase> requestTestCases() { |
| 782 |
static const auto HUGE_STRING = kj::strArray(kj::repeat("abcdefgh", 4096), ""); |
| 783 |
static const auto HUGE_REQUEST = kj::str( |
| 784 |
"GET / HTTP/1.1\r\n" |
| 785 |
"Host: ", HUGE_STRING, "\r\n" |
| 786 |
"\r\n"); |
| 787 |
|
| 788 |
static const HttpRequestTestCase REQUEST_TEST_CASES[] { |
| 789 |
{ |
| 790 |
"GET /foo/bar HTTP/1.1\r\n" |
| 791 |
"Host: example.com\r\n" |
| 792 |
"\r\n", |
| 793 |
|
| 794 |
HttpMethod::GET, |
| 795 |
"/foo/bar", |
| 796 |
{{HttpHeaderId::HOST, "example.com"}}, |
| 797 |
uint64_t(0), {}, |
| 798 |
}, |
| 799 |
|
| 800 |
{ |
| 801 |
"HEAD /foo/bar HTTP/1.1\r\n" |
| 802 |
"Host: example.com\r\n" |
| 803 |
"\r\n", |
| 804 |
|
| 805 |
HttpMethod::HEAD, |
| 806 |
"/foo/bar", |
| 807 |
{{HttpHeaderId::HOST, "example.com"}}, |
| 808 |
uint64_t(0), {}, |
| 809 |
}, |
| 810 |
|
| 811 |
{ |
| 812 |
"POST / HTTP/1.1\r\n" |
| 813 |
"Content-Length: 9\r\n" |
| 814 |
"Host: example.com\r\n" |
| 815 |
"Content-Type: text/plain\r\n" |
| 816 |
"\r\n" |
| 817 |
"foobarbaz", |
| 818 |
|
| 819 |
HttpMethod::POST, |
| 820 |
"/", |
| 821 |
{ |
| 822 |
{HttpHeaderId::HOST, "example.com"}, |
| 823 |
{HttpHeaderId::CONTENT_TYPE, "text/plain"}, |
| 824 |
}, |
| 825 |
9, { "foo", "bar", "baz" }, |
| 826 |
}, |
| 827 |
|
| 828 |
{ |
| 829 |
"POST / HTTP/1.1\r\n" |
| 830 |
"Transfer-Encoding: chunked\r\n" |
| 831 |
"Host: example.com\r\n" |
| 832 |
"Content-Type: text/plain\r\n" |
| 833 |
"\r\n" |
| 834 |
"3\r\n" |
| 835 |
"foo\r\n" |
| 836 |
"6\r\n" |
| 837 |
"barbaz\r\n" |
| 838 |
"0\r\n" |
| 839 |
"\r\n", |
| 840 |
|
| 841 |
HttpMethod::POST, |
| 842 |
"/", |
| 843 |
{ |
| 844 |
{HttpHeaderId::HOST, "example.com"}, |
| 845 |
{HttpHeaderId::CONTENT_TYPE, "text/plain"}, |
| 846 |
}, |
| 847 |
nullptr, { "foo", "barbaz" }, |
| 848 |
}, |
| 849 |
|
| 850 |
{ |
| 851 |
"POST / HTTP/1.1\r\n" |
| 852 |
"Transfer-Encoding: chunked\r\n" |
| 853 |
"Host: example.com\r\n" |
| 854 |
"Content-Type: text/plain\r\n" |
| 855 |
"\r\n" |
| 856 |
"1d\r\n" |
| 857 |
"0123456789abcdef0123456789abc\r\n" |
| 858 |
"0\r\n" |
| 859 |
"\r\n", |
| 860 |
|
| 861 |
HttpMethod::POST, |
| 862 |
"/", |
| 863 |
{ |
| 864 |
{HttpHeaderId::HOST, "example.com"}, |
| 865 |
{HttpHeaderId::CONTENT_TYPE, "text/plain"}, |
| 866 |
}, |
| 867 |
nullptr, { "0123456789abcdef0123456789abc" }, |
| 868 |
}, |
| 869 |
|
| 870 |
{ |
| 871 |
HUGE_REQUEST, |
| 872 |
|
| 873 |
HttpMethod::GET, |
| 874 |
"/", |
| 875 |
{{HttpHeaderId::HOST, HUGE_STRING}}, |
| 876 |
uint64_t(0), {} |
| 877 |
}, |
| 878 |
|
| 879 |
{ |
| 880 |
"GET /foo/bar HTTP/1.1\r\n" |
| 881 |
"Content-Length: 6\r\n" |
| 882 |
"Host: example.com\r\n" |
| 883 |
"\r\n" |
| 884 |
"foobar", |
| 885 |
|
| 886 |
HttpMethod::GET, |
| 887 |
"/foo/bar", |
| 888 |
{{HttpHeaderId::HOST, "example.com"}}, |
| 889 |
uint64_t(6), { "foobar" }, |
| 890 |
}, |
| 891 |
|
| 892 |
{ |
| 893 |
"GET /foo/bar HTTP/1.1\r\n" |
| 894 |
"Transfer-Encoding: chunked\r\n" |
| 895 |
"Host: example.com\r\n" |
| 896 |
"\r\n" |
| 897 |
"3\r\n" |
| 898 |
"foo\r\n" |
| 899 |
"3\r\n" |
| 900 |
"bar\r\n" |
| 901 |
"0\r\n" |
| 902 |
"\r\n", |
| 903 |
|
| 904 |
HttpMethod::GET, |
| 905 |
"/foo/bar", |
| 906 |
{{HttpHeaderId::HOST, "example.com"}, |
| 907 |
{HttpHeaderId::TRANSFER_ENCODING, "chunked"}}, |
| 908 |
nullptr, { "foo", "bar" }, |
| 909 |
} |
| 910 |
}; |
| 911 |
|
| 912 |
// TODO(cleanup): A bug in GCC 4.8, fixed in 4.9, prevents REQUEST_TEST_CASES from implicitly |
| 913 |
// casting to our return type. |
| 914 |
return kj::arrayPtr(REQUEST_TEST_CASES, kj::size(REQUEST_TEST_CASES)); |
| 915 |
} |
| 916 |
|
| 917 |
kj::ArrayPtr<const HttpResponseTestCase> responseTestCases() { |
| 918 |
static const HttpResponseTestCase RESPONSE_TEST_CASES[] { |
| 919 |
{ |
| 920 |
"HTTP/1.1 200 OK\r\n" |
| 921 |
"Content-Type: text/plain\r\n" |
| 922 |
"Connection: close\r\n" |
| 923 |
"\r\n" |
| 924 |
"baz qux", |
| 925 |
|
| 926 |
200, "OK", |
| 927 |
{{HttpHeaderId::CONTENT_TYPE, "text/plain"}}, |
| 928 |
nullptr, {"baz qux"}, |
| 929 |
|
| 930 |
HttpMethod::GET, |
| 931 |
CLIENT_ONLY, // Server never sends connection: close |
| 932 |
}, |
| 933 |
|
| 934 |
{ |
| 935 |
"HTTP/1.1 200 OK\r\n" |
| 936 |
"Content-Type: text/plain\r\n" |
| 937 |
"Transfer-Encoding: identity\r\n" |
| 938 |
"Content-Length: foobar\r\n" // intentionally wrong |
| 939 |
"\r\n" |
| 940 |
"baz qux", |
| 941 |
|
| 942 |
200, "OK", |
| 943 |
{{HttpHeaderId::CONTENT_TYPE, "text/plain"}}, |
| 944 |
nullptr, {"baz qux"}, |
| 945 |
|
| 946 |
HttpMethod::GET, |
| 947 |
CLIENT_ONLY, // Server never sends transfer-encoding: identity |
| 948 |
}, |
| 949 |
|
| 950 |
{ |
| 951 |
"HTTP/1.1 200 OK\r\n" |
| 952 |
"Content-Type: text/plain\r\n" |
| 953 |
"\r\n" |
| 954 |
"baz qux", |
| 955 |
|
| 956 |
200, "OK", |
| 957 |
{{HttpHeaderId::CONTENT_TYPE, "text/plain"}}, |
| 958 |
nullptr, {"baz qux"}, |
| 959 |
|
| 960 |
HttpMethod::GET, |
| 961 |
CLIENT_ONLY, // Server never sends non-delimited message |
| 962 |
}, |
| 963 |
|
| 964 |
{ |
| 965 |
"HTTP/1.1 200 OK\r\n" |
| 966 |
"Content-Length: 123\r\n" |
| 967 |
"Content-Type: text/plain\r\n" |
| 968 |
"\r\n", |
| 969 |
|
| 970 |
200, "OK", |
| 971 |
{{HttpHeaderId::CONTENT_TYPE, "text/plain"}}, |
| 972 |
123, {}, |
| 973 |
|
| 974 |
HttpMethod::HEAD, |
| 975 |
}, |
| 976 |
|
| 977 |
{ |
| 978 |
"HTTP/1.1 200 OK\r\n" |
| 979 |
"Content-Length: foobar\r\n" |
| 980 |
"Content-Type: text/plain\r\n" |
| 981 |
"\r\n", |
| 982 |
|
| 983 |
200, "OK", |
| 984 |
{{HttpHeaderId::CONTENT_TYPE, "text/plain"}, |
| 985 |
{HttpHeaderId::CONTENT_LENGTH, "foobar"}}, |
| 986 |
123, {}, |
| 987 |
|
| 988 |
HttpMethod::HEAD, |
| 989 |
}, |
| 990 |
|
| 991 |
// Zero-length expected size response to HEAD request has no Content-Length header. |
| 992 |
{ |
| 993 |
"HTTP/1.1 200 OK\r\n" |
| 994 |
"\r\n", |
| 995 |
|
| 996 |
200, "OK", |
| 997 |
{}, |
| 998 |
uint64_t(0), {}, |
| 999 |
|
| 1000 |
HttpMethod::HEAD, |
| 1001 |
}, |
| 1002 |
|
| 1003 |
{ |
| 1004 |
"HTTP/1.1 204 No Content\r\n" |
| 1005 |
"\r\n", |
| 1006 |
|
| 1007 |
204, "No Content", |
| 1008 |
{}, |
| 1009 |
uint64_t(0), {}, |
| 1010 |
}, |
| 1011 |
|
| 1012 |
{ |
| 1013 |
"HTTP/1.1 205 Reset Content\r\n" |
| 1014 |
"Content-Length: 0\r\n" |
| 1015 |
"\r\n", |
| 1016 |
|
| 1017 |
205, "Reset Content", |
| 1018 |
{}, |
| 1019 |
uint64_t(0), {}, |
| 1020 |
}, |
| 1021 |
|
| 1022 |
{ |
| 1023 |
"HTTP/1.1 304 Not Modified\r\n" |
| 1024 |
"\r\n", |
| 1025 |
|
| 1026 |
304, "Not Modified", |
| 1027 |
{}, |
| 1028 |
uint64_t(0), {}, |
| 1029 |
}, |
| 1030 |
|
| 1031 |
{ |
| 1032 |
"HTTP/1.1 200 OK\r\n" |
| 1033 |
"Content-Length: 8\r\n" |
| 1034 |
"Content-Type: text/plain\r\n" |
| 1035 |
"\r\n" |
| 1036 |
"quxcorge", |
| 1037 |
|
| 1038 |
200, "OK", |
| 1039 |
{{HttpHeaderId::CONTENT_TYPE, "text/plain"}}, |
| 1040 |
8, { "qux", "corge" } |
| 1041 |
}, |
| 1042 |
|
| 1043 |
{ |
| 1044 |
"HTTP/1.1 200 OK\r\n" |
| 1045 |
"Transfer-Encoding: chunked\r\n" |
| 1046 |
"Content-Type: text/plain\r\n" |
| 1047 |
"\r\n" |
| 1048 |
"3\r\n" |
| 1049 |
"qux\r\n" |
| 1050 |
"5\r\n" |
| 1051 |
"corge\r\n" |
| 1052 |
"0\r\n" |
| 1053 |
"\r\n", |
| 1054 |
|
| 1055 |
200, "OK", |
| 1056 |
{{HttpHeaderId::CONTENT_TYPE, "text/plain"}}, |
| 1057 |
nullptr, { "qux", "corge" } |
| 1058 |
}, |
| 1059 |
}; |
| 1060 |
|
| 1061 |
// TODO(cleanup): A bug in GCC 4.8, fixed in 4.9, prevents RESPONSE_TEST_CASES from implicitly |
| 1062 |
// casting to our return type. |
| 1063 |
return kj::arrayPtr(RESPONSE_TEST_CASES, kj::size(RESPONSE_TEST_CASES)); |
| 1064 |
} |
| 1065 |
|
| 1066 |
KJ_TEST("HttpClient requests") { |
| 1067 |
KJ_HTTP_TEST_SETUP_IO; |
| 1068 |
|
| 1069 |
for (auto& testCase: requestTestCases()) { |
| 1070 |
if (testCase.side == SERVER_ONLY) continue; |
| 1071 |
KJ_CONTEXT(testCase.raw); |
| 1072 |
testHttpClientRequest(waitScope, testCase, KJ_HTTP_TEST_CREATE_2PIPE); |
| 1073 |
} |
| 1074 |
} |
| 1075 |
|
| 1076 |
KJ_TEST("HttpClient responses") { |
| 1077 |
KJ_HTTP_TEST_SETUP_IO; |
| 1078 |
size_t FRAGMENT_SIZES[] = { 1, 2, 3, 4, 5, 6, 7, 8, 16, 31, kj::maxValue }; |
| 1079 |
|
| 1080 |
for (auto& testCase: responseTestCases()) { |
| 1081 |
if (testCase.side == SERVER_ONLY) continue; |
| 1082 |
for (size_t fragmentSize: FRAGMENT_SIZES) { |
| 1083 |
KJ_CONTEXT(testCase.raw, fragmentSize); |
| 1084 |
testHttpClientResponse(waitScope, testCase, fragmentSize, KJ_HTTP_TEST_CREATE_2PIPE); |
| 1085 |
} |
| 1086 |
} |
| 1087 |
} |
| 1088 |
|
| 1089 |
KJ_TEST("HttpClient canceled write") { |
| 1090 |
KJ_HTTP_TEST_SETUP_IO; |
| 1091 |
|
| 1092 |
auto pipe = KJ_HTTP_TEST_CREATE_2PIPE; |
| 1093 |
|
| 1094 |
auto serverPromise = pipe.ends[1]->readAllText(); |
| 1095 |
|
| 1096 |
{ |
| 1097 |
HttpHeaderTable table; |
| 1098 |
auto client = newHttpClient(table, *pipe.ends[0]); |
| 1099 |
|
| 1100 |
auto body = kj::heapArray<byte>(4096); |
| 1101 |
memset(body.begin(), 0xcf, body.size()); |
| 1102 |
|
| 1103 |
auto req = client->request(HttpMethod::POST, "/", HttpHeaders(table), uint64_t(4096)); |
| 1104 |
|
| 1105 |
// Note: This poll() forces the server to receive what was written so far. Otherwise, |
| 1106 |
// cancelling the write below may in fact cancel the previous write as well. |
| 1107 |
KJ_EXPECT(!serverPromise.poll(waitScope)); |
| 1108 |
|
| 1109 |
// Start a write and immediately cancel it. |
| 1110 |
{ |
| 1111 |
auto ignore KJ_UNUSED = req.body->write(body.begin(), body.size()); |
| 1112 |
} |
| 1113 |
|
| 1114 |
KJ_EXPECT_THROW_MESSAGE("overwrote", req.body->write("foo", 3).wait(waitScope)); |
| 1115 |
req.body = nullptr; |
| 1116 |
|
| 1117 |
KJ_EXPECT(!serverPromise.poll(waitScope)); |
| 1118 |
|
| 1119 |
KJ_EXPECT_THROW_MESSAGE("can't start new request until previous request body", |
| 1120 |
client->request(HttpMethod::GET, "/", HttpHeaders(table)).response.wait(waitScope)); |
| 1121 |
} |
| 1122 |
|
| 1123 |
pipe.ends[0]->shutdownWrite(); |
| 1124 |
auto text = serverPromise.wait(waitScope); |
| 1125 |
KJ_EXPECT(text == "POST / HTTP/1.1\r\nContent-Length: 4096\r\n\r\n", text); |
| 1126 |
} |
| 1127 |
|
| 1128 |
KJ_TEST("HttpClient chunked body gather-write") { |
| 1129 |
KJ_HTTP_TEST_SETUP_IO; |
| 1130 |
|
| 1131 |
auto pipe = KJ_HTTP_TEST_CREATE_2PIPE; |
| 1132 |
|
| 1133 |
auto serverPromise = pipe.ends[1]->readAllText(); |
| 1134 |
|
| 1135 |
{ |
| 1136 |
HttpHeaderTable table; |
| 1137 |
auto client = newHttpClient(table, *pipe.ends[0]); |
| 1138 |
|
| 1139 |
auto req = client->request(HttpMethod::POST, "/", HttpHeaders(table)); |
| 1140 |
|
| 1141 |
kj::ArrayPtr<const byte> bodyParts[] = { |
| 1142 |
"foo"_kj.asBytes(), " "_kj.asBytes(), |
| 1143 |
"bar"_kj.asBytes(), " "_kj.asBytes(), |
| 1144 |
"baz"_kj.asBytes() |
| 1145 |
}; |
| 1146 |
|
| 1147 |
req.body->write(kj::arrayPtr(bodyParts, kj::size(bodyParts))).wait(waitScope); |
| 1148 |
req.body = nullptr; |
| 1149 |
|
| 1150 |
// Wait for a response so the client has a chance to end the request body with a 0-chunk. |
| 1151 |
kj::StringPtr responseText = "HTTP/1.1 204 No Content\r\n\r\n"; |
| 1152 |
pipe.ends[1]->write(responseText.begin(), responseText.size()).wait(waitScope); |
| 1153 |
auto response = req.response.wait(waitScope); |
| 1154 |
} |
| 1155 |
|
| 1156 |
pipe.ends[0]->shutdownWrite(); |
| 1157 |
|
| 1158 |
auto text = serverPromise.wait(waitScope); |
| 1159 |
KJ_EXPECT(text == "POST / HTTP/1.1\r\nTransfer-Encoding: chunked\r\n\r\n" |
| 1160 |
"b\r\nfoo bar baz\r\n0\r\n\r\n", text); |
| 1161 |
} |
| 1162 |
|
| 1163 |
KJ_TEST("HttpClient chunked body pump from fixed length stream") { |
| 1164 |
class FixedBodyStream final: public kj::AsyncInputStream { |
| 1165 |
Promise<size_t> tryRead(void* buffer, size_t minBytes, size_t maxBytes) override { |
| 1166 |
auto n = kj::min(body.size(), maxBytes); |
| 1167 |
n = kj::max(n, minBytes); |
| 1168 |
n = kj::min(n, body.size()); |
| 1169 |
memcpy(buffer, body.begin(), n); |
| 1170 |
body = body.slice(n); |
| 1171 |
return n; |
| 1172 |
} |
| 1173 |
|
| 1174 |
Maybe<uint64_t> tryGetLength() override { return body.size(); } |
| 1175 |
|
| 1176 |
kj::StringPtr body = "foo bar baz"; |
| 1177 |
}; |
| 1178 |
|
| 1179 |
KJ_HTTP_TEST_SETUP_IO; |
| 1180 |
|
| 1181 |
auto pipe = KJ_HTTP_TEST_CREATE_2PIPE; |
| 1182 |
|
| 1183 |
auto serverPromise = pipe.ends[1]->readAllText(); |
| 1184 |
|
| 1185 |
{ |
| 1186 |
HttpHeaderTable table; |
| 1187 |
auto client = newHttpClient(table, *pipe.ends[0]); |
| 1188 |
|
| 1189 |
auto req = client->request(HttpMethod::POST, "/", HttpHeaders(table)); |
| 1190 |
|
| 1191 |
FixedBodyStream bodyStream; |
| 1192 |
bodyStream.pumpTo(*req.body).wait(waitScope); |
| 1193 |
req.body = nullptr; |
| 1194 |
|
| 1195 |
// Wait for a response so the client has a chance to end the request body with a 0-chunk. |
| 1196 |
kj::StringPtr responseText = "HTTP/1.1 204 No Content\r\n\r\n"; |
| 1197 |
pipe.ends[1]->write(responseText.begin(), responseText.size()).wait(waitScope); |
| 1198 |
auto response = req.response.wait(waitScope); |
| 1199 |
} |
| 1200 |
|
| 1201 |
pipe.ends[0]->shutdownWrite(); |
| 1202 |
|
| 1203 |
auto text = serverPromise.wait(waitScope); |
| 1204 |
KJ_EXPECT(text == "POST / HTTP/1.1\r\nTransfer-Encoding: chunked\r\n\r\n" |
| 1205 |
"b\r\nfoo bar baz\r\n0\r\n\r\n", text); |
| 1206 |
} |
| 1207 |
|
| 1208 |
KJ_TEST("HttpServer requests") { |
| 1209 |
HttpResponseTestCase RESPONSE = { |
| 1210 |
"HTTP/1.1 200 OK\r\n" |
| 1211 |
"Content-Length: 3\r\n" |
| 1212 |
"\r\n" |
| 1213 |
"foo", |
| 1214 |
|
| 1215 |
200, "OK", |
| 1216 |
{}, |
| 1217 |
3, {"foo"} |
| 1218 |
}; |
| 1219 |
|
| 1220 |
HttpResponseTestCase HEAD_RESPONSE = { |
| 1221 |
"HTTP/1.1 200 OK\r\n" |
| 1222 |
"Content-Length: 3\r\n" |
| 1223 |
"\r\n", |
| 1224 |
|
| 1225 |
200, "OK", |
| 1226 |
{}, |
| 1227 |
3, {"foo"} |
| 1228 |
}; |
| 1229 |
|
| 1230 |
KJ_HTTP_TEST_SETUP_IO; |
| 1231 |
kj::TimerImpl timer(kj::origin<kj::TimePoint>()); |
| 1232 |
|
| 1233 |
for (auto& testCase: requestTestCases()) { |
| 1234 |
if (testCase.side == CLIENT_ONLY) continue; |
| 1235 |
KJ_CONTEXT(testCase.raw); |
| 1236 |
testHttpServerRequest(waitScope, timer, testCase, |
| 1237 |
testCase.method == HttpMethod::HEAD ? HEAD_RESPONSE : RESPONSE, |
| 1238 |
KJ_HTTP_TEST_CREATE_2PIPE); |
| 1239 |
} |
| 1240 |
} |
| 1241 |
|
| 1242 |
KJ_TEST("HttpServer responses") { |
| 1243 |
HttpRequestTestCase REQUEST = { |
| 1244 |
"GET / HTTP/1.1\r\n" |
| 1245 |
"\r\n", |
| 1246 |
|
| 1247 |
HttpMethod::GET, |
| 1248 |
"/", |
| 1249 |
{}, |
| 1250 |
uint64_t(0), {}, |
| 1251 |
}; |
| 1252 |
|
| 1253 |
HttpRequestTestCase HEAD_REQUEST = { |
| 1254 |
"HEAD / HTTP/1.1\r\n" |
| 1255 |
"\r\n", |
| 1256 |
|
| 1257 |
HttpMethod::HEAD, |
| 1258 |
"/", |
| 1259 |
{}, |
| 1260 |
uint64_t(0), {}, |
| 1261 |
}; |
| 1262 |
|
| 1263 |
KJ_HTTP_TEST_SETUP_IO; |
| 1264 |
kj::TimerImpl timer(kj::origin<kj::TimePoint>()); |
| 1265 |
|
| 1266 |
for (auto& testCase: responseTestCases()) { |
| 1267 |
if (testCase.side == CLIENT_ONLY) continue; |
| 1268 |
KJ_CONTEXT(testCase.raw); |
| 1269 |
testHttpServerRequest(waitScope, timer, |
| 1270 |
testCase.method == HttpMethod::HEAD ? HEAD_REQUEST : REQUEST, testCase, |
| 1271 |
KJ_HTTP_TEST_CREATE_2PIPE); |
| 1272 |
} |
| 1273 |
} |
| 1274 |
|
| 1275 |
// ----------------------------------------------------------------------------- |
| 1276 |
|
| 1277 |
kj::ArrayPtr<const HttpTestCase> pipelineTestCases() { |
| 1278 |
static const HttpTestCase PIPELINE_TESTS[] = { |
| 1279 |
{ |
| 1280 |
{ |
| 1281 |
"GET / HTTP/1.1\r\n" |
| 1282 |
"\r\n", |
| 1283 |
|
| 1284 |
HttpMethod::GET, "/", {}, uint64_t(0), {}, |
| 1285 |
}, |
| 1286 |
{ |
| 1287 |
"HTTP/1.1 200 OK\r\n" |
| 1288 |
"Content-Length: 7\r\n" |
| 1289 |
"\r\n" |
| 1290 |
"foo bar", |
| 1291 |
|
| 1292 |
200, "OK", {}, 7, { "foo bar" } |
| 1293 |
}, |
| 1294 |
}, |
| 1295 |
|
| 1296 |
{ |
| 1297 |
{ |
| 1298 |
"POST /foo HTTP/1.1\r\n" |
| 1299 |
"Content-Length: 6\r\n" |
| 1300 |
"\r\n" |
| 1301 |
"grault", |
| 1302 |
|
| 1303 |
HttpMethod::POST, "/foo", {}, 6, { "grault" }, |
| 1304 |
}, |
| 1305 |
{ |
| 1306 |
"HTTP/1.1 404 Not Found\r\n" |
| 1307 |
"Content-Length: 13\r\n" |
| 1308 |
"\r\n" |
| 1309 |
"baz qux corge", |
| 1310 |
|
| 1311 |
404, "Not Found", {}, 13, { "baz qux corge" } |
| 1312 |
}, |
| 1313 |
}, |
| 1314 |
|
| 1315 |
// Throw a zero-size request/response into the pipeline to check for a bug that existed with |
| 1316 |
// them previously. |
| 1317 |
{ |
| 1318 |
{ |
| 1319 |
"POST /foo HTTP/1.1\r\n" |
| 1320 |
"Content-Length: 0\r\n" |
| 1321 |
"\r\n", |
| 1322 |
|
| 1323 |
HttpMethod::POST, "/foo", {}, uint64_t(0), {}, |
| 1324 |
}, |
| 1325 |
{ |
| 1326 |
"HTTP/1.1 200 OK\r\n" |
| 1327 |
"Content-Length: 0\r\n" |
| 1328 |
"\r\n", |
| 1329 |
|
| 1330 |
200, "OK", {}, uint64_t(0), {} |
| 1331 |
}, |
| 1332 |
}, |
| 1333 |
|
| 1334 |
// Also a zero-size chunked request/response. |
| 1335 |
{ |
| 1336 |
{ |
| 1337 |
"POST /foo HTTP/1.1\r\n" |
| 1338 |
"Transfer-Encoding: chunked\r\n" |
| 1339 |
"\r\n" |
| 1340 |
"0\r\n" |
| 1341 |
"\r\n", |
| 1342 |
|
| 1343 |
HttpMethod::POST, "/foo", {}, nullptr, {}, |
| 1344 |
}, |
| 1345 |
{ |
| 1346 |
"HTTP/1.1 200 OK\r\n" |
| 1347 |
"Transfer-Encoding: chunked\r\n" |
| 1348 |
"\r\n" |
| 1349 |
"0\r\n" |
| 1350 |
"\r\n", |
| 1351 |
|
| 1352 |
200, "OK", {}, nullptr, {} |
| 1353 |
}, |
| 1354 |
}, |
| 1355 |
|
| 1356 |
{ |
| 1357 |
{ |
| 1358 |
"POST /bar HTTP/1.1\r\n" |
| 1359 |
"Transfer-Encoding: chunked\r\n" |
| 1360 |
"\r\n" |
| 1361 |
"6\r\n" |
| 1362 |
"garply\r\n" |
| 1363 |
"5\r\n" |
| 1364 |
"waldo\r\n" |
| 1365 |
"0\r\n" |
| 1366 |
"\r\n", |
| 1367 |
|
| 1368 |
HttpMethod::POST, "/bar", {}, nullptr, { "garply", "waldo" }, |
| 1369 |
}, |
| 1370 |
{ |
| 1371 |
"HTTP/1.1 200 OK\r\n" |
| 1372 |
"Transfer-Encoding: chunked\r\n" |
| 1373 |
"\r\n" |
| 1374 |
"4\r\n" |
| 1375 |
"fred\r\n" |
| 1376 |
"5\r\n" |
| 1377 |
"plugh\r\n" |
| 1378 |
"0\r\n" |
| 1379 |
"\r\n", |
| 1380 |
|
| 1381 |
200, "OK", {}, nullptr, { "fred", "plugh" } |
| 1382 |
}, |
| 1383 |
}, |
| 1384 |
|
| 1385 |
{ |
| 1386 |
{ |
| 1387 |
"HEAD / HTTP/1.1\r\n" |
| 1388 |
"\r\n", |
| 1389 |
|
| 1390 |
HttpMethod::HEAD, "/", {}, uint64_t(0), {}, |
| 1391 |
}, |
| 1392 |
{ |
| 1393 |
"HTTP/1.1 200 OK\r\n" |
| 1394 |
"Content-Length: 7\r\n" |
| 1395 |
"\r\n", |
| 1396 |
|
| 1397 |
200, "OK", {}, 7, { "foo bar" } |
| 1398 |
}, |
| 1399 |
}, |
| 1400 |
|
| 1401 |
// Zero-length expected size response to HEAD request has no Content-Length header. |
| 1402 |
{ |
| 1403 |
{ |
| 1404 |
"HEAD / HTTP/1.1\r\n" |
| 1405 |
"\r\n", |
| 1406 |
|
| 1407 |
HttpMethod::HEAD, "/", {}, uint64_t(0), {}, |
| 1408 |
}, |
| 1409 |
{ |
| 1410 |
"HTTP/1.1 200 OK\r\n" |
| 1411 |
"\r\n", |
| 1412 |
|
| 1413 |
200, "OK", {}, uint64_t(0), {}, HttpMethod::HEAD, |
| 1414 |
}, |
| 1415 |
}, |
| 1416 |
}; |
| 1417 |
|
| 1418 |
// TODO(cleanup): A bug in GCC 4.8, fixed in 4.9, prevents RESPONSE_TEST_CASES from implicitly |
| 1419 |
// casting to our return type. |
| 1420 |
return kj::arrayPtr(PIPELINE_TESTS, kj::size(PIPELINE_TESTS)); |
| 1421 |
} |
| 1422 |
|
| 1423 |
KJ_TEST("HttpClient pipeline") { |
| 1424 |
auto PIPELINE_TESTS = pipelineTestCases(); |
| 1425 |
|
| 1426 |
KJ_HTTP_TEST_SETUP_IO; |
| 1427 |
auto pipe = KJ_HTTP_TEST_CREATE_2PIPE; |
| 1428 |
|
| 1429 |
kj::Promise<void> writeResponsesPromise = kj::READY_NOW; |
| 1430 |
for (auto& testCase: PIPELINE_TESTS) { |
| 1431 |
writeResponsesPromise = writeResponsesPromise |
| 1432 |
.then([&]() { |
| 1433 |
return expectRead(*pipe.ends[1], testCase.request.raw); |
| 1434 |
}).then([&]() { |
| 1435 |
return pipe.ends[1]->write(testCase.response.raw.begin(), testCase.response.raw.size()); |
| 1436 |
}); |
| 1437 |
} |
| 1438 |
|
| 1439 |
HttpHeaderTable table; |
| 1440 |
auto client = newHttpClient(table, *pipe.ends[0]); |
| 1441 |
|
| 1442 |
for (auto& testCase: PIPELINE_TESTS) { |
| 1443 |
testHttpClient(waitScope, table, *client, testCase); |
| 1444 |
} |
| 1445 |
|
| 1446 |
client = nullptr; |
| 1447 |
pipe.ends[0]->shutdownWrite(); |
| 1448 |
|
| 1449 |
writeResponsesPromise.wait(waitScope); |
| 1450 |
} |
| 1451 |
|
| 1452 |
KJ_TEST("HttpClient parallel pipeline") { |
| 1453 |
auto PIPELINE_TESTS = pipelineTestCases(); |
| 1454 |
|
| 1455 |
KJ_HTTP_TEST_SETUP_IO; |
| 1456 |
auto pipe = KJ_HTTP_TEST_CREATE_2PIPE; |
| 1457 |
|
| 1458 |
kj::Promise<void> readRequestsPromise = kj::READY_NOW; |
| 1459 |
kj::Promise<void> writeResponsesPromise = kj::READY_NOW; |
| 1460 |
for (auto& testCase: PIPELINE_TESTS) { |
| 1461 |
auto forked = readRequestsPromise |
| 1462 |
.then([&]() { |
| 1463 |
return expectRead(*pipe.ends[1], testCase.request.raw); |
| 1464 |
}).fork(); |
| 1465 |
readRequestsPromise = forked.addBranch(); |
| 1466 |
|
| 1467 |
// Don't write each response until the corresponding request is received. |
| 1468 |
auto promises = kj::heapArrayBuilder<kj::Promise<void>>(2); |
| 1469 |
promises.add(forked.addBranch()); |
| 1470 |
promises.add(kj::mv(writeResponsesPromise)); |
| 1471 |
writeResponsesPromise = kj::joinPromises(promises.finish()).then([&]() { |
| 1472 |
return pipe.ends[1]->write(testCase.response.raw.begin(), testCase.response.raw.size()); |
| 1473 |
}); |
| 1474 |
} |
| 1475 |
|
| 1476 |
HttpHeaderTable table; |
| 1477 |
auto client = newHttpClient(table, *pipe.ends[0]); |
| 1478 |
|
| 1479 |
auto responsePromises = KJ_MAP(testCase, PIPELINE_TESTS) { |
| 1480 |
KJ_CONTEXT(testCase.request.raw, testCase.response.raw); |
| 1481 |
|
| 1482 |
HttpHeaders headers(table); |
| 1483 |
for (auto& header: testCase.request.requestHeaders) { |
| 1484 |
headers.set(header.id, header.value); |
| 1485 |
} |
| 1486 |
|
| 1487 |
auto request = client->request( |
| 1488 |
testCase.request.method, testCase.request.path, headers, testCase.request.requestBodySize); |
| 1489 |
for (auto& part: testCase.request.requestBodyParts) { |
| 1490 |
request.body->write(part.begin(), part.size()).wait(waitScope); |
| 1491 |
} |
| 1492 |
|
| 1493 |
return kj::mv(request.response); |
| 1494 |
}; |
| 1495 |
|
| 1496 |
for (auto i: kj::indices(PIPELINE_TESTS)) { |
| 1497 |
auto& testCase = PIPELINE_TESTS[i]; |
| 1498 |
auto response = responsePromises[i].wait(waitScope); |
| 1499 |
|
| 1500 |
KJ_EXPECT(response.statusCode == testCase.response.statusCode); |
| 1501 |
auto body = response.body->readAllText().wait(waitScope); |
| 1502 |
if (testCase.request.method == HttpMethod::HEAD) { |
| 1503 |
KJ_EXPECT(body == ""); |
| 1504 |
} else { |
| 1505 |
KJ_EXPECT(body == kj::strArray(testCase.response.responseBodyParts, ""), body); |
| 1506 |
} |
| 1507 |
} |
| 1508 |
|
| 1509 |
client = nullptr; |
| 1510 |
pipe.ends[0]->shutdownWrite(); |
| 1511 |
|
| 1512 |
writeResponsesPromise.wait(waitScope); |
| 1513 |
} |
| 1514 |
|
| 1515 |
KJ_TEST("HttpServer pipeline") { |
| 1516 |
auto PIPELINE_TESTS = pipelineTestCases(); |
| 1517 |
|
| 1518 |
KJ_HTTP_TEST_SETUP_IO; |
| 1519 |
kj::TimerImpl timer(kj::origin<kj::TimePoint>()); |
| 1520 |
auto pipe = KJ_HTTP_TEST_CREATE_2PIPE; |
| 1521 |
|
| 1522 |
HttpHeaderTable table; |
| 1523 |
TestHttpService service(PIPELINE_TESTS, table); |
| 1524 |
HttpServer server(timer, table, service); |
| 1525 |
|
| 1526 |
auto listenTask = server.listenHttp(kj::mv(pipe.ends[0])); |
| 1527 |
|
| 1528 |
for (auto& testCase: PIPELINE_TESTS) { |
| 1529 |
KJ_CONTEXT(testCase.request.raw, testCase.response.raw); |
| 1530 |
|
| 1531 |
pipe.ends[1]->write(testCase.request.raw.begin(), testCase.request.raw.size()) |
| 1532 |
.wait(waitScope); |
| 1533 |
|
| 1534 |
expectRead(*pipe.ends[1], testCase.response.raw).wait(waitScope); |
| 1535 |
} |
| 1536 |
|
| 1537 |
pipe.ends[1]->shutdownWrite(); |
| 1538 |
listenTask.wait(waitScope); |
| 1539 |
|
| 1540 |
KJ_EXPECT(service.getRequestCount() == kj::size(PIPELINE_TESTS)); |
| 1541 |
} |
| 1542 |
|
| 1543 |
KJ_TEST("HttpServer parallel pipeline") { |
| 1544 |
auto PIPELINE_TESTS = pipelineTestCases(); |
| 1545 |
|
| 1546 |
KJ_HTTP_TEST_SETUP_IO; |
| 1547 |
kj::TimerImpl timer(kj::origin<kj::TimePoint>()); |
| 1548 |
auto pipe = KJ_HTTP_TEST_CREATE_2PIPE; |
| 1549 |
|
| 1550 |
auto allRequestText = |
| 1551 |
kj::strArray(KJ_MAP(testCase, PIPELINE_TESTS) { return testCase.request.raw; }, ""); |
| 1552 |
auto allResponseText = |
| 1553 |
kj::strArray(KJ_MAP(testCase, PIPELINE_TESTS) { return testCase.response.raw; }, ""); |
| 1554 |
|
| 1555 |
HttpHeaderTable table; |
| 1556 |
TestHttpService service(PIPELINE_TESTS, table); |
| 1557 |
HttpServer server(timer, table, service); |
| 1558 |
|
| 1559 |
auto listenTask = server.listenHttp(kj::mv(pipe.ends[0])); |
| 1560 |
|
| 1561 |
pipe.ends[1]->write(allRequestText.begin(), allRequestText.size()).wait(waitScope); |
| 1562 |
pipe.ends[1]->shutdownWrite(); |
| 1563 |
|
| 1564 |
auto rawResponse = pipe.ends[1]->readAllText().wait(waitScope); |
| 1565 |
KJ_EXPECT(rawResponse == allResponseText, rawResponse); |
| 1566 |
|
| 1567 |
listenTask.wait(waitScope); |
| 1568 |
|
| 1569 |
KJ_EXPECT(service.getRequestCount() == kj::size(PIPELINE_TESTS)); |
| 1570 |
} |
| 1571 |
|
| 1572 |
KJ_TEST("HttpClient <-> HttpServer") { |
| 1573 |
auto PIPELINE_TESTS = pipelineTestCases(); |
| 1574 |
|
| 1575 |
KJ_HTTP_TEST_SETUP_IO; |
| 1576 |
kj::TimerImpl timer(kj::origin<kj::TimePoint>()); |
| 1577 |
auto pipe = KJ_HTTP_TEST_CREATE_2PIPE; |
| 1578 |
|
| 1579 |
HttpHeaderTable table; |
| 1580 |
TestHttpService service(PIPELINE_TESTS, table); |
| 1581 |
HttpServer server(timer, table, service); |
| 1582 |
|
| 1583 |
auto listenTask = server.listenHttp(kj::mv(pipe.ends[1])); |
| 1584 |
auto client = newHttpClient(table, *pipe.ends[0]); |
| 1585 |
|
| 1586 |
for (auto& testCase: PIPELINE_TESTS) { |
| 1587 |
testHttpClient(waitScope, table, *client, testCase); |
| 1588 |
} |
| 1589 |
|
| 1590 |
client = nullptr; |
| 1591 |
pipe.ends[0]->shutdownWrite(); |
| 1592 |
listenTask.wait(waitScope); |
| 1593 |
KJ_EXPECT(service.getRequestCount() == kj::size(PIPELINE_TESTS)); |
| 1594 |
} |
| 1595 |
|
| 1596 |
// ----------------------------------------------------------------------------- |
| 1597 |
|
| 1598 |
KJ_TEST("HttpInputStream requests") { |
| 1599 |
KJ_HTTP_TEST_SETUP_IO; |
| 1600 |
|
| 1601 |
kj::HttpHeaderTable table; |
| 1602 |
|
| 1603 |
auto pipe = kj::newOneWayPipe(); |
| 1604 |
auto input = newHttpInputStream(*pipe.in, table); |
| 1605 |
|
| 1606 |
kj::Promise<void> writeQueue = kj::READY_NOW; |
| 1607 |
|
| 1608 |
for (auto& testCase: requestTestCases()) { |
| 1609 |
writeQueue = writeQueue.then([&]() { |
| 1610 |
return pipe.out->write(testCase.raw.begin(), testCase.raw.size()); |
| 1611 |
}); |
| 1612 |
} |
| 1613 |
writeQueue = writeQueue.then([&]() { |
| 1614 |
pipe.out = nullptr; |
| 1615 |
}); |
| 1616 |
|
| 1617 |
for (auto& testCase: requestTestCases()) { |
| 1618 |
KJ_CONTEXT(testCase.raw); |
| 1619 |
|
| 1620 |
KJ_ASSERT(input->awaitNextMessage().wait(waitScope)); |
| 1621 |
|
| 1622 |
auto req = input->readRequest().wait(waitScope); |
| 1623 |
KJ_EXPECT(req.method == testCase.method); |
| 1624 |
KJ_EXPECT(req.url == testCase.path); |
| 1625 |
for (auto& header: testCase.requestHeaders) { |
| 1626 |
KJ_EXPECT(KJ_ASSERT_NONNULL(req.headers.get(header.id)) == header.value); |
| 1627 |
} |
| 1628 |
auto body = req.body->readAllText().wait(waitScope); |
| 1629 |
KJ_EXPECT(body == kj::strArray(testCase.requestBodyParts, "")); |
| 1630 |
} |
| 1631 |
|
| 1632 |
writeQueue.wait(waitScope); |
| 1633 |
KJ_EXPECT(!input->awaitNextMessage().wait(waitScope)); |
| 1634 |
} |
| 1635 |
|
| 1636 |
KJ_TEST("HttpInputStream responses") { |
| 1637 |
KJ_HTTP_TEST_SETUP_IO; |
| 1638 |
|
| 1639 |
kj::HttpHeaderTable table; |
| 1640 |
|
| 1641 |
auto pipe = kj::newOneWayPipe(); |
| 1642 |
auto input = newHttpInputStream(*pipe.in, table); |
| 1643 |
|
| 1644 |
kj::Promise<void> writeQueue = kj::READY_NOW; |
| 1645 |
|
| 1646 |
for (auto& testCase: responseTestCases()) { |
| 1647 |
if (testCase.side == CLIENT_ONLY) continue; // skip Connection: close case. |
| 1648 |
writeQueue = writeQueue.then([&]() { |
| 1649 |
return pipe.out->write(testCase.raw.begin(), testCase.raw.size()); |
| 1650 |
}); |
| 1651 |
} |
| 1652 |
writeQueue = writeQueue.then([&]() { |
| 1653 |
pipe.out = nullptr; |
| 1654 |
}); |
| 1655 |
|
| 1656 |
for (auto& testCase: responseTestCases()) { |
| 1657 |
if (testCase.side == CLIENT_ONLY) continue; // skip Connection: close case. |
| 1658 |
KJ_CONTEXT(testCase.raw); |
| 1659 |
|
| 1660 |
KJ_ASSERT(input->awaitNextMessage().wait(waitScope)); |
| 1661 |
|
| 1662 |
auto resp = input->readResponse(testCase.method).wait(waitScope); |
| 1663 |
KJ_EXPECT(resp.statusCode == testCase.statusCode); |
| 1664 |
KJ_EXPECT(resp.statusText == testCase.statusText); |
| 1665 |
for (auto& header: testCase.responseHeaders) { |
| 1666 |
KJ_EXPECT(KJ_ASSERT_NONNULL(resp.headers.get(header.id)) == header.value); |
| 1667 |
} |
| 1668 |
auto body = resp.body->readAllText().wait(waitScope); |
| 1669 |
KJ_EXPECT(body == kj::strArray(testCase.responseBodyParts, "")); |
| 1670 |
} |
| 1671 |
|
| 1672 |
writeQueue.wait(waitScope); |
| 1673 |
KJ_EXPECT(!input->awaitNextMessage().wait(waitScope)); |
| 1674 |
} |
| 1675 |
|
| 1676 |
KJ_TEST("HttpInputStream bare messages") { |
| 1677 |
KJ_HTTP_TEST_SETUP_IO; |
| 1678 |
|
| 1679 |
kj::HttpHeaderTable table; |
| 1680 |
|
| 1681 |
auto pipe = kj::newOneWayPipe(); |
| 1682 |
auto input = newHttpInputStream(*pipe.in, table); |
| 1683 |
|
| 1684 |
kj::StringPtr messages = |
| 1685 |
"Content-Length: 6\r\n" |
| 1686 |
"\r\n" |
| 1687 |
"foobar" |
| 1688 |
"Content-Length: 11\r\n" |
| 1689 |
"Content-Type: some/type\r\n" |
| 1690 |
"\r\n" |
| 1691 |
"bazquxcorge" |
| 1692 |
"Transfer-Encoding: chunked\r\n" |
| 1693 |
"\r\n" |
| 1694 |
"6\r\n" |
| 1695 |
"grault\r\n" |
| 1696 |
"b\r\n" |
| 1697 |
"garplywaldo\r\n" |
| 1698 |
"0\r\n" |
| 1699 |
"\r\n"_kj; |
| 1700 |
|
| 1701 |
kj::Promise<void> writeTask = pipe.out->write(messages.begin(), messages.size()) |
| 1702 |
.then([&]() { pipe.out = nullptr; }); |
| 1703 |
|
| 1704 |
{ |
| 1705 |
KJ_ASSERT(input->awaitNextMessage().wait(waitScope)); |
| 1706 |
auto message = input->readMessage().wait(waitScope); |
| 1707 |
KJ_EXPECT(KJ_ASSERT_NONNULL(message.headers.get(HttpHeaderId::CONTENT_LENGTH)) == "6"); |
| 1708 |
KJ_EXPECT(message.body->readAllText().wait(waitScope) == "foobar"); |
| 1709 |
} |
| 1710 |
{ |
| 1711 |
KJ_ASSERT(input->awaitNextMessage().wait(waitScope)); |
| 1712 |
auto message = input->readMessage().wait(waitScope); |
| 1713 |
KJ_EXPECT(KJ_ASSERT_NONNULL(message.headers.get(HttpHeaderId::CONTENT_LENGTH)) == "11"); |
| 1714 |
KJ_EXPECT(KJ_ASSERT_NONNULL(message.headers.get(HttpHeaderId::CONTENT_TYPE)) == "some/type"); |
| 1715 |
KJ_EXPECT(message.body->readAllText().wait(waitScope) == "bazquxcorge"); |
| 1716 |
} |
| 1717 |
{ |
| 1718 |
KJ_ASSERT(input->awaitNextMessage().wait(waitScope)); |
| 1719 |
auto message = input->readMessage().wait(waitScope); |
| 1720 |
KJ_EXPECT(KJ_ASSERT_NONNULL(message.headers.get(HttpHeaderId::TRANSFER_ENCODING)) == "chunked"); |
| 1721 |
KJ_EXPECT(message.body->readAllText().wait(waitScope) == "graultgarplywaldo"); |
| 1722 |
} |
| 1723 |
|
| 1724 |
writeTask.wait(waitScope); |
| 1725 |
KJ_EXPECT(!input->awaitNextMessage().wait(waitScope)); |
| 1726 |
} |
| 1727 |
|
| 1728 |
// ----------------------------------------------------------------------------- |
| 1729 |
|
| 1730 |
KJ_TEST("WebSocket core protocol") { |
| 1731 |
KJ_HTTP_TEST_SETUP_IO; |
| 1732 |
auto pipe = KJ_HTTP_TEST_CREATE_2PIPE; |
| 1733 |
|
| 1734 |
auto client = newWebSocket(kj::mv(pipe.ends[0]), nullptr); |
| 1735 |
auto server = newWebSocket(kj::mv(pipe.ends[1]), nullptr); |
| 1736 |
|
| 1737 |
auto mediumString = kj::strArray(kj::repeat(kj::StringPtr("123456789"), 30), ""); |
| 1738 |
auto bigString = kj::strArray(kj::repeat(kj::StringPtr("123456789"), 10000), ""); |
| 1739 |
|
| 1740 |
auto clientTask = client->send(kj::StringPtr("hello")) |
| 1741 |
.then([&]() { return client->send(mediumString); }) |
| 1742 |
.then([&]() { return client->send(bigString); }) |
| 1743 |
.then([&]() { return client->send(kj::StringPtr("world").asBytes()); }) |
| 1744 |
.then([&]() { return client->close(1234, "bored"); }) |
| 1745 |
.then([&]() { KJ_EXPECT(client->sentByteCount() == 90307)}); |
| 1746 |
|
| 1747 |
{ |
| 1748 |
auto message = server->receive().wait(waitScope); |
| 1749 |
KJ_ASSERT(message.is<kj::String>()); |
| 1750 |
KJ_EXPECT(message.get<kj::String>() == "hello"); |
| 1751 |
} |
| 1752 |
|
| 1753 |
{ |
| 1754 |
auto message = server->receive().wait(waitScope); |
| 1755 |
KJ_ASSERT(message.is<kj::String>()); |
| 1756 |
KJ_EXPECT(message.get<kj::String>() == mediumString); |
| 1757 |
} |
| 1758 |
|
| 1759 |
{ |
| 1760 |
auto message = server->receive().wait(waitScope); |
| 1761 |
KJ_ASSERT(message.is<kj::String>()); |
| 1762 |
KJ_EXPECT(message.get<kj::String>() == bigString); |
| 1763 |
} |
| 1764 |
|
| 1765 |
{ |
| 1766 |
auto message = server->receive().wait(waitScope); |
| 1767 |
KJ_ASSERT(message.is<kj::Array<byte>>()); |
| 1768 |
KJ_EXPECT(kj::str(message.get<kj::Array<byte>>().asChars()) == "world"); |
| 1769 |
} |
| 1770 |
|
| 1771 |
{ |
| 1772 |
auto message = server->receive().wait(waitScope); |
| 1773 |
KJ_ASSERT(message.is<WebSocket::Close>()); |
| 1774 |
KJ_EXPECT(message.get<WebSocket::Close>().code == 1234); |
| 1775 |
KJ_EXPECT(message.get<WebSocket::Close>().reason == "bored"); |
| 1776 |
KJ_EXPECT(server->receivedByteCount() == 90307); |
| 1777 |
} |
| 1778 |
|
| 1779 |
auto serverTask = server->close(4321, "whatever"); |
| 1780 |
|
| 1781 |
{ |
| 1782 |
auto message = client->receive().wait(waitScope); |
| 1783 |
KJ_ASSERT(message.is<WebSocket::Close>()); |
| 1784 |
KJ_EXPECT(message.get<WebSocket::Close>().code == 4321); |
| 1785 |
KJ_EXPECT(message.get<WebSocket::Close>().reason == "whatever"); |
| 1786 |
KJ_EXPECT(client->receivedByteCount() == 12); |
| 1787 |
} |
| 1788 |
|
| 1789 |
clientTask.wait(waitScope); |
| 1790 |
serverTask.wait(waitScope); |
| 1791 |
} |
| 1792 |
|
| 1793 |
KJ_TEST("WebSocket fragmented") { |
| 1794 |
KJ_HTTP_TEST_SETUP_IO; |
| 1795 |
auto pipe = KJ_HTTP_TEST_CREATE_2PIPE; |
| 1796 |
|
| 1797 |
auto client = kj::mv(pipe.ends[0]); |
| 1798 |
auto server = newWebSocket(kj::mv(pipe.ends[1]), nullptr); |
| 1799 |
|
| 1800 |
byte DATA[] = { |
| 1801 |
0x01, 0x06, 'h', 'e', 'l', 'l', 'o', ' ', |
| 1802 |
|
| 1803 |
0x00, 0x03, 'w', 'o', 'r', |
| 1804 |
|
| 1805 |
0x80, 0x02, 'l', 'd', |
| 1806 |
}; |
| 1807 |
|
| 1808 |
auto clientTask = client->write(DATA, sizeof(DATA)); |
| 1809 |
|
| 1810 |
{ |
| 1811 |
auto message = server->receive().wait(waitScope); |
| 1812 |
KJ_ASSERT(message.is<kj::String>()); |
| 1813 |
KJ_EXPECT(message.get<kj::String>() == "hello world"); |
| 1814 |
} |
| 1815 |
|
| 1816 |
clientTask.wait(waitScope); |
| 1817 |
} |
| 1818 |
|
| 1819 |
#if KJ_HAS_ZLIB |
| 1820 |
KJ_TEST("WebSocket compressed fragment") { |
| 1821 |
KJ_HTTP_TEST_SETUP_IO; |
| 1822 |
auto pipe = KJ_HTTP_TEST_CREATE_2PIPE; |
| 1823 |
|
| 1824 |
auto client = kj::mv(pipe.ends[0]); |
| 1825 |
auto server = newWebSocket(kj::mv(pipe.ends[1]), nullptr, CompressionParameters{ |
| 1826 |
.outboundNoContextTakeover = false, |
| 1827 |
.inboundNoContextTakeover = false, |
| 1828 |
.outboundMaxWindowBits=15, |
| 1829 |
.inboundMaxWindowBits=15, |
| 1830 |
}); |
| 1831 |
|
| 1832 |
// The message is "Hello", sent in two fragments, see the fragmented example at the bottom of: |
| 1833 |
// https://datatracker.ietf.org/doc/html/rfc7692#section-7.2.3.1 |
| 1834 |
byte COMPRESSED_DATA[] = { |
| 1835 |
0x41, 0x03, 0xf2, 0x48, 0xcd, |
| 1836 |
|
| 1837 |
0x80, 0x04, 0xc9, 0xc9, 0x07, 0x00 |
| 1838 |
}; |
| 1839 |
|
| 1840 |
auto clientTask = client->write(COMPRESSED_DATA, sizeof(COMPRESSED_DATA)); |
| 1841 |
|
| 1842 |
{ |
| 1843 |
auto message = server->receive().wait(waitScope); |
| 1844 |
KJ_ASSERT(message.is<kj::String>()); |
| 1845 |
KJ_EXPECT(message.get<kj::String>() == "Hello"); |
| 1846 |
} |
| 1847 |
|
| 1848 |
clientTask.wait(waitScope); |
| 1849 |
} |
| 1850 |
#endif // KJ_HAS_ZLIB |
| 1851 |
|
| 1852 |
class FakeEntropySource final: public EntropySource { |
| 1853 |
public: |
| 1854 |
void generate(kj::ArrayPtr<byte> buffer) override { |
| 1855 |
static constexpr byte DUMMY[4] = { 12, 34, 56, 78 }; |
| 1856 |
|
| 1857 |
for (auto i: kj::indices(buffer)) { |
| 1858 |
buffer[i] = DUMMY[i % sizeof(DUMMY)]; |
| 1859 |
} |
| 1860 |
} |
| 1861 |
}; |
| 1862 |
|
| 1863 |
KJ_TEST("WebSocket masked") { |
| 1864 |
KJ_HTTP_TEST_SETUP_IO; |
| 1865 |
auto pipe = KJ_HTTP_TEST_CREATE_2PIPE; |
| 1866 |
FakeEntropySource maskGenerator; |
| 1867 |
|
| 1868 |
auto client = kj::mv(pipe.ends[0]); |
| 1869 |
auto server = newWebSocket(kj::mv(pipe.ends[1]), maskGenerator); |
| 1870 |
|
| 1871 |
byte DATA[] = { |
| 1872 |
0x81, 0x86, 12, 34, 56, 78, 'h' ^ 12, 'e' ^ 34, 'l' ^ 56, 'l' ^ 78, 'o' ^ 12, ' ' ^ 34, |
| 1873 |
}; |
| 1874 |
|
| 1875 |
auto clientTask = client->write(DATA, sizeof(DATA)); |
| 1876 |
auto serverTask = server->send(kj::StringPtr("hello ")); |
| 1877 |
|
| 1878 |
{ |
| 1879 |
auto message = server->receive().wait(waitScope); |
| 1880 |
KJ_ASSERT(message.is<kj::String>()); |
| 1881 |
KJ_EXPECT(message.get<kj::String>() == "hello "); |
| 1882 |
} |
| 1883 |
|
| 1884 |
expectRead(*client, DATA).wait(waitScope); |
| 1885 |
|
| 1886 |
clientTask.wait(waitScope); |
| 1887 |
serverTask.wait(waitScope); |
| 1888 |
} |
| 1889 |
|
| 1890 |
class WebSocketErrorCatcher : public WebSocketErrorHandler { |
| 1891 |
public: |
| 1892 |
kj::Vector<kj::WebSocket::ProtocolError> errors; |
| 1893 |
|
| 1894 |
kj::Exception handleWebSocketProtocolError(kj::WebSocket::ProtocolError protocolError) { |
| 1895 |
errors.add(kj::mv(protocolError)); |
| 1896 |
return KJ_EXCEPTION(FAILED, protocolError.description); |
| 1897 |
} |
| 1898 |
}; |
| 1899 |
|
| 1900 |
KJ_TEST("WebSocket unexpected RSV bits") { |
| 1901 |
KJ_HTTP_TEST_SETUP_IO; |
| 1902 |
auto pipe = KJ_HTTP_TEST_CREATE_2PIPE; |
| 1903 |
|
| 1904 |
WebSocketErrorCatcher errorCatcher; |
| 1905 |
auto client = kj::mv(pipe.ends[0]); |
| 1906 |
auto server = newWebSocket(kj::mv(pipe.ends[1]), nullptr, nullptr, errorCatcher); |
| 1907 |
|
| 1908 |
byte DATA[] = { |
| 1909 |
0x01, 0x06, 'h', 'e', 'l', 'l', 'o', ' ', |
| 1910 |
|
| 1911 |
0xF0, 0x05, 'w', 'o', 'r', 'l', 'd' // all RSV bits set, plus FIN |
| 1912 |
}; |
| 1913 |
|
| 1914 |
auto clientTask = client->write(DATA, sizeof(DATA)); |
| 1915 |
|
| 1916 |
{ |
| 1917 |
bool gotException = false; |
| 1918 |
auto serverTask = server->receive().then([](auto&& m) {}, [&gotException](kj::Exception&& ex) { gotException = true; }); |
| 1919 |
serverTask.wait(waitScope); |
| 1920 |
KJ_ASSERT(gotException); |
| 1921 |
KJ_ASSERT(errorCatcher.errors.size() == 1); |
| 1922 |
KJ_ASSERT(errorCatcher.errors[0].statusCode == 1002); |
| 1923 |
} |
| 1924 |
|
| 1925 |
clientTask.wait(waitScope); |
| 1926 |
} |
| 1927 |
|
| 1928 |
KJ_TEST("WebSocket unexpected continuation frame") { |
| 1929 |
KJ_HTTP_TEST_SETUP_IO; |
| 1930 |
auto pipe = KJ_HTTP_TEST_CREATE_2PIPE; |
| 1931 |
|
| 1932 |
WebSocketErrorCatcher errorCatcher; |
| 1933 |
auto client = kj::mv(pipe.ends[0]); |
| 1934 |
auto server = newWebSocket(kj::mv(pipe.ends[1]), nullptr, nullptr, errorCatcher); |
| 1935 |
|
| 1936 |
byte DATA[] = { |
| 1937 |
0x80, 0x06, 'h', 'e', 'l', 'l', 'o', ' ', // Continuation frame with no start frame, plus FIN |
| 1938 |
}; |
| 1939 |
|
| 1940 |
auto clientTask = client->write(DATA, sizeof(DATA)); |
| 1941 |
|
| 1942 |
{ |
| 1943 |
bool gotException = false; |
| 1944 |
auto serverTask = server->receive().then([](auto&& m) {}, [&gotException](kj::Exception&& ex) { gotException = true; }); |
| 1945 |
serverTask.wait(waitScope); |
| 1946 |
KJ_ASSERT(gotException); |
| 1947 |
KJ_ASSERT(errorCatcher.errors.size() == 1); |
| 1948 |
KJ_ASSERT(errorCatcher.errors[0].statusCode == 1002); |
| 1949 |
} |
| 1950 |
|
| 1951 |
clientTask.wait(waitScope); |
| 1952 |
} |
| 1953 |
|
| 1954 |
KJ_TEST("WebSocket missing continuation frame") { |
| 1955 |
KJ_HTTP_TEST_SETUP_IO; |
| 1956 |
auto pipe = KJ_HTTP_TEST_CREATE_2PIPE; |
| 1957 |
|
| 1958 |
WebSocketErrorCatcher errorCatcher; |
| 1959 |
auto client = kj::mv(pipe.ends[0]); |
| 1960 |
auto server = newWebSocket(kj::mv(pipe.ends[1]), nullptr, nullptr, errorCatcher); |
| 1961 |
|
| 1962 |
byte DATA[] = { |
| 1963 |
0x01, 0x06, 'h', 'e', 'l', 'l', 'o', ' ', // Start frame |
| 1964 |
0x01, 0x06, 'w', 'o', 'r', 'l', 'd', '!', // Another start frame |
| 1965 |
}; |
| 1966 |
|
| 1967 |
auto clientTask = client->write(DATA, sizeof(DATA)); |
| 1968 |
|
| 1969 |
{ |
| 1970 |
bool gotException = false; |
| 1971 |
auto serverTask = server->receive().then([](auto&& m) {}, [&gotException](kj::Exception&& ex) { gotException = true; }); |
| 1972 |
serverTask.wait(waitScope); |
| 1973 |
KJ_ASSERT(gotException); |
| 1974 |
KJ_ASSERT(errorCatcher.errors.size() == 1); |
| 1975 |
} |
| 1976 |
|
| 1977 |
clientTask.wait(waitScope); |
| 1978 |
} |
| 1979 |
|
| 1980 |
KJ_TEST("WebSocket fragmented control frame") { |
| 1981 |
KJ_HTTP_TEST_SETUP_IO; |
| 1982 |
auto pipe = KJ_HTTP_TEST_CREATE_2PIPE; |
| 1983 |
|
| 1984 |
WebSocketErrorCatcher errorCatcher; |
| 1985 |
auto client = kj::mv(pipe.ends[0]); |
| 1986 |
auto server = newWebSocket(kj::mv(pipe.ends[1]), nullptr, nullptr, errorCatcher); |
| 1987 |
|
| 1988 |
byte DATA[] = { |
| 1989 |
0x09, 0x04, 'd', 'a', 't', 'a' // Fragmented ping frame |
| 1990 |
}; |
| 1991 |
|
| 1992 |
auto clientTask = client->write(DATA, sizeof(DATA)); |
| 1993 |
|
| 1994 |
{ |
| 1995 |
bool gotException = false; |
| 1996 |
auto serverTask = server->receive().then([](auto&& m) {}, [&gotException](kj::Exception&& ex) { gotException = true; }); |
| 1997 |
serverTask.wait(waitScope); |
| 1998 |
KJ_ASSERT(gotException); |
| 1999 |
KJ_ASSERT(errorCatcher.errors.size() == 1); |
| 2000 |
KJ_ASSERT(errorCatcher.errors[0].statusCode == 1002); |
| 2001 |
} |
| 2002 |
|
| 2003 |
clientTask.wait(waitScope); |
| 2004 |
} |
| 2005 |
|
| 2006 |
KJ_TEST("WebSocket unknown opcode") { |
| 2007 |
KJ_HTTP_TEST_SETUP_IO; |
| 2008 |
auto pipe = KJ_HTTP_TEST_CREATE_2PIPE; |
| 2009 |
|
| 2010 |
WebSocketErrorCatcher errorCatcher; |
| 2011 |
auto client = kj::mv(pipe.ends[0]); |
| 2012 |
auto server = newWebSocket(kj::mv(pipe.ends[1]), nullptr, nullptr, errorCatcher); |
| 2013 |
|
| 2014 |
byte DATA[] = { |
| 2015 |
0x85, 0x04, 'd', 'a', 't', 'a' // 5 is a reserved opcode |
| 2016 |
}; |
| 2017 |
|
| 2018 |
auto clientTask = client->write(DATA, sizeof(DATA)); |
| 2019 |
|
| 2020 |
{ |
| 2021 |
bool gotException = false; |
| 2022 |
auto serverTask = server->receive().then([](auto&& m) {}, [&gotException](kj::Exception&& ex) { gotException = true; }); |
| 2023 |
serverTask.wait(waitScope); |
| 2024 |
KJ_ASSERT(gotException); |
| 2025 |
KJ_ASSERT(errorCatcher.errors.size() == 1); |
| 2026 |
KJ_ASSERT(errorCatcher.errors[0].statusCode == 1002); |
| 2027 |
} |
| 2028 |
|
| 2029 |
clientTask.wait(waitScope); |
| 2030 |
} |
| 2031 |
|
| 2032 |
KJ_TEST("WebSocket unsolicited pong") { |
| 2033 |
KJ_HTTP_TEST_SETUP_IO; |
| 2034 |
auto pipe = KJ_HTTP_TEST_CREATE_2PIPE; |
| 2035 |
|
| 2036 |
auto client = kj::mv(pipe.ends[0]); |
| 2037 |
auto server = newWebSocket(kj::mv(pipe.ends[1]), nullptr); |
| 2038 |
|
| 2039 |
byte DATA[] = { |
| 2040 |
0x01, 0x06, 'h', 'e', 'l', 'l', 'o', ' ', |
| 2041 |
|
| 2042 |
0x8A, 0x03, 'f', 'o', 'o', |
| 2043 |
|
| 2044 |
0x80, 0x05, 'w', 'o', 'r', 'l', 'd', |
| 2045 |
}; |
| 2046 |
|
| 2047 |
auto clientTask = client->write(DATA, sizeof(DATA)); |
| 2048 |
|
| 2049 |
{ |
| 2050 |
auto message = server->receive().wait(waitScope); |
| 2051 |
KJ_ASSERT(message.is<kj::String>()); |
| 2052 |
KJ_EXPECT(message.get<kj::String>() == "hello world"); |
| 2053 |
} |
| 2054 |
|
| 2055 |
clientTask.wait(waitScope); |
| 2056 |
} |
| 2057 |
|
| 2058 |
KJ_TEST("WebSocket ping") { |
| 2059 |
KJ_HTTP_TEST_SETUP_IO; |
| 2060 |
auto pipe = KJ_HTTP_TEST_CREATE_2PIPE; |
| 2061 |
|
| 2062 |
auto client = kj::mv(pipe.ends[0]); |
| 2063 |
auto server = newWebSocket(kj::mv(pipe.ends[1]), nullptr); |
| 2064 |
|
| 2065 |
// Be extra-annoying by having the ping arrive between fragments. |
| 2066 |
byte DATA[] = { |
| 2067 |
0x01, 0x06, 'h', 'e', 'l', 'l', 'o', ' ', |
| 2068 |
|
| 2069 |
0x89, 0x03, 'f', 'o', 'o', |
| 2070 |
|
| 2071 |
0x80, 0x05, 'w', 'o', 'r', 'l', 'd', |
| 2072 |
}; |
| 2073 |
|
| 2074 |
auto clientTask = client->write(DATA, sizeof(DATA)); |
| 2075 |
|
| 2076 |
{ |
| 2077 |
auto message = server->receive().wait(waitScope); |
| 2078 |
KJ_ASSERT(message.is<kj::String>()); |
| 2079 |
KJ_EXPECT(message.get<kj::String>() == "hello world"); |
| 2080 |
} |
| 2081 |
|
| 2082 |
auto serverTask = server->send(kj::StringPtr("bar")); |
| 2083 |
|
| 2084 |
byte EXPECTED[] = { |
| 2085 |
0x8A, 0x03, 'f', 'o', 'o', // pong |
| 2086 |
0x81, 0x03, 'b', 'a', 'r', // message |
| 2087 |
}; |
| 2088 |
|
| 2089 |
expectRead(*client, EXPECTED).wait(waitScope); |
| 2090 |
|
| 2091 |
clientTask.wait(waitScope); |
| 2092 |
serverTask.wait(waitScope); |
| 2093 |
} |
| 2094 |
|
| 2095 |
KJ_TEST("WebSocket ping mid-send") { |
| 2096 |
KJ_HTTP_TEST_SETUP_IO; |
| 2097 |
auto pipe = KJ_HTTP_TEST_CREATE_2PIPE; |
| 2098 |
|
| 2099 |
auto client = kj::mv(pipe.ends[0]); |
| 2100 |
auto server = newWebSocket(kj::mv(pipe.ends[1]), nullptr); |
| 2101 |
|
| 2102 |
auto bigString = kj::strArray(kj::repeat(kj::StringPtr("12345678"), 65536), ""); |
| 2103 |
auto serverTask = server->send(bigString).eagerlyEvaluate(nullptr); |
| 2104 |
|
| 2105 |
byte DATA[] = { |
| 2106 |
0x89, 0x03, 'f', 'o', 'o', // ping |
| 2107 |
0x81, 0x03, 'b', 'a', 'r', // some other message |
| 2108 |
}; |
| 2109 |
|
| 2110 |
auto clientTask = client->write(DATA, sizeof(DATA)); |
| 2111 |
|
| 2112 |
{ |
| 2113 |
auto message = server->receive().wait(waitScope); |
| 2114 |
KJ_ASSERT(message.is<kj::String>()); |
| 2115 |
KJ_EXPECT(message.get<kj::String>() == "bar"); |
| 2116 |
} |
| 2117 |
|
| 2118 |
byte EXPECTED1[] = { 0x81, 0x7f, 0, 0, 0, 0, 0, 8, 0, 0 }; |
| 2119 |
expectRead(*client, EXPECTED1).wait(waitScope); |
| 2120 |
expectRead(*client, bigString).wait(waitScope); |
| 2121 |
|
| 2122 |
byte EXPECTED2[] = { 0x8A, 0x03, 'f', 'o', 'o' }; |
| 2123 |
expectRead(*client, EXPECTED2).wait(waitScope); |
| 2124 |
|
| 2125 |
clientTask.wait(waitScope); |
| 2126 |
serverTask.wait(waitScope); |
| 2127 |
} |
| 2128 |
|
| 2129 |
class InputOutputPair final: public kj::AsyncIoStream { |
| 2130 |
// Creates an AsyncIoStream out of an AsyncInputStream and an AsyncOutputStream. |
| 2131 |
|
| 2132 |
public: |
| 2133 |
InputOutputPair(kj::Own<kj::AsyncInputStream> in, kj::Own<kj::AsyncOutputStream> out) |
| 2134 |
: in(kj::mv(in)), out(kj::mv(out)) {} |
| 2135 |
|
| 2136 |
kj::Promise<size_t> read(void* buffer, size_t minBytes, size_t maxBytes) override { |
| 2137 |
return in->read(buffer, minBytes, maxBytes); |
| 2138 |
} |
| 2139 |
kj::Promise<size_t> tryRead(void* buffer, size_t minBytes, size_t maxBytes) override { |
| 2140 |
return in->tryRead(buffer, minBytes, maxBytes); |
| 2141 |
} |
| 2142 |
|
| 2143 |
Maybe<uint64_t> tryGetLength() override { |
| 2144 |
return in->tryGetLength(); |
| 2145 |
} |
| 2146 |
|
| 2147 |
Promise<uint64_t> pumpTo(AsyncOutputStream& output, uint64_t amount = kj::maxValue) override { |
| 2148 |
return in->pumpTo(output, amount); |
| 2149 |
} |
| 2150 |
|
| 2151 |
kj::Promise<void> write(const void* buffer, size_t size) override { |
| 2152 |
return out->write(buffer, size); |
| 2153 |
} |
| 2154 |
|
| 2155 |
kj::Promise<void> write(kj::ArrayPtr<const kj::ArrayPtr<const byte>> pieces) override { |
| 2156 |
return out->write(pieces); |
| 2157 |
} |
| 2158 |
|
| 2159 |
kj::Maybe<kj::Promise<uint64_t>> tryPumpFrom( |
| 2160 |
kj::AsyncInputStream& input, uint64_t amount = kj::maxValue) override { |
| 2161 |
return out->tryPumpFrom(input, amount); |
| 2162 |
} |
| 2163 |
|
| 2164 |
Promise<void> whenWriteDisconnected() override { |
| 2165 |
return out->whenWriteDisconnected(); |
| 2166 |
} |
| 2167 |
|
| 2168 |
void shutdownWrite() override { |
| 2169 |
out = nullptr; |
| 2170 |
} |
| 2171 |
|
| 2172 |
private: |
| 2173 |
kj::Own<kj::AsyncInputStream> in; |
| 2174 |
kj::Own<kj::AsyncOutputStream> out; |
| 2175 |
}; |
| 2176 |
|
| 2177 |
KJ_TEST("WebSocket double-ping mid-send") { |
| 2178 |
KJ_HTTP_TEST_SETUP_IO; |
| 2179 |
|
| 2180 |
auto upPipe = newOneWayPipe(); |
| 2181 |
auto downPipe = newOneWayPipe(); |
| 2182 |
InputOutputPair client(kj::mv(downPipe.in), kj::mv(upPipe.out)); |
| 2183 |
auto server = newWebSocket(kj::heap<InputOutputPair>(kj::mv(upPipe.in), kj::mv(downPipe.out)), |
| 2184 |
nullptr); |
| 2185 |
|
| 2186 |
auto bigString = kj::strArray(kj::repeat(kj::StringPtr("12345678"), 65536), ""); |
| 2187 |
auto serverTask = server->send(bigString).eagerlyEvaluate(nullptr); |
| 2188 |
|
| 2189 |
byte DATA[] = { |
| 2190 |
0x89, 0x03, 'f', 'o', 'o', // ping |
| 2191 |
0x89, 0x03, 'q', 'u', 'x', // ping2 |
| 2192 |
0x81, 0x03, 'b', 'a', 'r', // some other message |
| 2193 |
}; |
| 2194 |
|
| 2195 |
auto clientTask = client.write(DATA, sizeof(DATA)); |
| 2196 |
|
| 2197 |
{ |
| 2198 |
auto message = server->receive().wait(waitScope); |
| 2199 |
KJ_ASSERT(message.is<kj::String>()); |
| 2200 |
KJ_EXPECT(message.get<kj::String>() == "bar"); |
| 2201 |
} |
| 2202 |
|
| 2203 |
byte EXPECTED1[] = { 0x81, 0x7f, 0, 0, 0, 0, 0, 8, 0, 0 }; |
| 2204 |
expectRead(client, EXPECTED1).wait(waitScope); |
| 2205 |
expectRead(client, bigString).wait(waitScope); |
| 2206 |
|
| 2207 |
byte EXPECTED2[] = { 0x8A, 0x03, 'q', 'u', 'x' }; |
| 2208 |
expectRead(client, EXPECTED2).wait(waitScope); |
| 2209 |
|
| 2210 |
clientTask.wait(waitScope); |
| 2211 |
serverTask.wait(waitScope); |
| 2212 |
} |
| 2213 |
|
| 2214 |
KJ_TEST("WebSocket ping received during pong send") { |
| 2215 |
KJ_HTTP_TEST_SETUP_IO; |
| 2216 |
auto pipe = KJ_HTTP_TEST_CREATE_2PIPE; |
| 2217 |
|
| 2218 |
auto client = kj::mv(pipe.ends[0]); |
| 2219 |
auto server = newWebSocket(kj::mv(pipe.ends[1]), nullptr); |
| 2220 |
|
| 2221 |
// Send a very large ping so that sending the pong takes a while. Then send a second ping |
| 2222 |
// immediately after. |
| 2223 |
byte PREFIX[] = { 0x89, 0x7f, 0, 0, 0, 0, 0, 8, 0, 0 }; |
| 2224 |
auto bigString = kj::strArray(kj::repeat(kj::StringPtr("12345678"), 65536), ""); |
| 2225 |
byte POSTFIX[] = { |
| 2226 |
0x89, 0x03, 'f', 'o', 'o', |
| 2227 |
0x81, 0x03, 'b', 'a', 'r', |
| 2228 |
}; |
| 2229 |
|
| 2230 |
kj::ArrayPtr<const byte> parts[] = {PREFIX, bigString.asBytes(), POSTFIX}; |
| 2231 |
auto clientTask = client->write(parts); |
| 2232 |
|
| 2233 |
{ |
| 2234 |
auto message = server->receive().wait(waitScope); |
| 2235 |
KJ_ASSERT(message.is<kj::String>()); |
| 2236 |
KJ_EXPECT(message.get<kj::String>() == "bar"); |
| 2237 |
} |
| 2238 |
|
| 2239 |
byte EXPECTED1[] = { 0x8A, 0x7f, 0, 0, 0, 0, 0, 8, 0, 0 }; |
| 2240 |
expectRead(*client, EXPECTED1).wait(waitScope); |
| 2241 |
expectRead(*client, bigString).wait(waitScope); |
| 2242 |
|
| 2243 |
byte EXPECTED2[] = { 0x8A, 0x03, 'f', 'o', 'o' }; |
| 2244 |
expectRead(*client, EXPECTED2).wait(waitScope); |
| 2245 |
|
| 2246 |
clientTask.wait(waitScope); |
| 2247 |
} |
| 2248 |
|
| 2249 |
KJ_TEST("WebSocket pump byte counting") { |
| 2250 |
KJ_HTTP_TEST_SETUP_IO; |
| 2251 |
auto pipe1 = KJ_HTTP_TEST_CREATE_2PIPE; |
| 2252 |
auto pipe2 = KJ_HTTP_TEST_CREATE_2PIPE; |
| 2253 |
|
| 2254 |
FakeEntropySource maskGenerator; |
| 2255 |
auto server1 = newWebSocket(kj::mv(pipe1.ends[1]), nullptr); |
| 2256 |
auto client2 = newWebSocket(kj::mv(pipe2.ends[0]), maskGenerator); |
| 2257 |
auto server2 = newWebSocket(kj::mv(pipe2.ends[1]), nullptr); |
| 2258 |
|
| 2259 |
auto pumpTask = server1->pumpTo(*client2); |
| 2260 |
auto receiveTask = server2->receive(); |
| 2261 |
|
| 2262 |
// Client sends three bytes of a valid message then disconnects. |
| 2263 |
const char DATA[] = {0x01, 0x06, 'h'}; |
| 2264 |
pipe1.ends[0]->write(DATA, 3).wait(waitScope); |
| 2265 |
pipe1.ends[0] = nullptr; |
| 2266 |
|
| 2267 |
// The pump completes successfully, forwarding the disconnect. |
| 2268 |
pumpTask.wait(waitScope); |
| 2269 |
|
| 2270 |
// The eventual receiver gets a disconnect exception. |
| 2271 |
// (Note: We don't use KJ_EXPECT_THROW here because under -fno-exceptions it forks and we lose |
| 2272 |
// state.) |
| 2273 |
receiveTask.then([](auto) { |
| 2274 |
KJ_FAIL_EXPECT("expected exception"); |
| 2275 |
}, [](kj::Exception&& e) { |
| 2276 |
KJ_EXPECT(e.getType() == kj::Exception::Type::DISCONNECTED); |
| 2277 |
}).wait(waitScope); |
| 2278 |
|
| 2279 |
KJ_EXPECT(server1->receivedByteCount() == 3); |
| 2280 |
#if KJ_NO_RTTI |
| 2281 |
// Optimized socket pump will be disabled, so only whole messages are counted by client2/server2. |
| 2282 |
KJ_EXPECT(client2->sentByteCount() == 0); |
| 2283 |
KJ_EXPECT(server2->receivedByteCount() == 0); |
| 2284 |
#else |
| 2285 |
KJ_EXPECT(client2->sentByteCount() == 3); |
| 2286 |
KJ_EXPECT(server2->receivedByteCount() == 3); |
| 2287 |
#endif |
| 2288 |
} |
| 2289 |
|
| 2290 |
KJ_TEST("WebSocket pump disconnect on send") { |
| 2291 |
KJ_HTTP_TEST_SETUP_IO; |
| 2292 |
auto pipe1 = KJ_HTTP_TEST_CREATE_2PIPE; |
| 2293 |
auto pipe2 = KJ_HTTP_TEST_CREATE_2PIPE; |
| 2294 |
|
| 2295 |
FakeEntropySource maskGenerator; |
| 2296 |
auto client1 = newWebSocket(kj::mv(pipe1.ends[0]), maskGenerator); |
| 2297 |
auto server1 = newWebSocket(kj::mv(pipe1.ends[1]), nullptr); |
| 2298 |
auto client2 = newWebSocket(kj::mv(pipe2.ends[0]), maskGenerator); |
| 2299 |
|
| 2300 |
auto pumpTask = server1->pumpTo(*client2); |
| 2301 |
auto sendTask = client1->send("hello"_kj); |
| 2302 |
|
| 2303 |
// Endpoint reads three bytes and then disconnects. |
| 2304 |
char buffer[3]; |
| 2305 |
pipe2.ends[1]->read(buffer, 3).wait(waitScope); |
| 2306 |
pipe2.ends[1] = nullptr; |
| 2307 |
|
| 2308 |
// Pump throws disconnected. |
| 2309 |
KJ_EXPECT_THROW_RECOVERABLE(DISCONNECTED, pumpTask.wait(waitScope)); |
| 2310 |
|
| 2311 |
// client1 may or may not have been able to send its whole message depending on buffering. |
| 2312 |
sendTask.then([]() {}, [](kj::Exception&& e) { |
| 2313 |
KJ_EXPECT(e.getType() == kj::Exception::Type::DISCONNECTED); |
| 2314 |
}).wait(waitScope); |
| 2315 |
} |
| 2316 |
|
| 2317 |
KJ_TEST("WebSocket pump disconnect on receive") { |
| 2318 |
KJ_HTTP_TEST_SETUP_IO; |
| 2319 |
auto pipe1 = KJ_HTTP_TEST_CREATE_2PIPE; |
| 2320 |
auto pipe2 = KJ_HTTP_TEST_CREATE_2PIPE; |
| 2321 |
|
| 2322 |
FakeEntropySource maskGenerator; |
| 2323 |
auto server1 = newWebSocket(kj::mv(pipe1.ends[1]), nullptr); |
| 2324 |
auto client2 = newWebSocket(kj::mv(pipe2.ends[0]), maskGenerator); |
| 2325 |
auto server2 = newWebSocket(kj::mv(pipe2.ends[1]), nullptr); |
| 2326 |
|
| 2327 |
auto pumpTask = server1->pumpTo(*client2); |
| 2328 |
auto receiveTask = server2->receive(); |
| 2329 |
|
| 2330 |
// Client sends three bytes of a valid message then disconnects. |
| 2331 |
const char DATA[] = {0x01, 0x06, 'h'}; |
| 2332 |
pipe1.ends[0]->write(DATA, 3).wait(waitScope); |
| 2333 |
pipe1.ends[0] = nullptr; |
| 2334 |
|
| 2335 |
// The pump completes successfully, forwarding the disconnect. |
| 2336 |
pumpTask.wait(waitScope); |
| 2337 |
|
| 2338 |
// The eventual receiver gets a disconnect exception. |
| 2339 |
KJ_EXPECT_THROW(DISCONNECTED, receiveTask.wait(waitScope)); |
| 2340 |
} |
| 2341 |
|
| 2342 |
KJ_TEST("WebSocket abort propagates through pipe") { |
| 2343 |
// Pumping one end of a WebSocket pipe into another WebSocket which later becomes aborted will |
| 2344 |
// cancel the pump promise with a DISCONNECTED exception. |
| 2345 |
|
| 2346 |
KJ_HTTP_TEST_SETUP_IO; |
| 2347 |
auto pipe1 = KJ_HTTP_TEST_CREATE_2PIPE; |
| 2348 |
|
| 2349 |
auto server = newWebSocket(kj::mv(pipe1.ends[1]), nullptr); |
| 2350 |
auto client = newWebSocket(kj::mv(pipe1.ends[0]), nullptr); |
| 2351 |
|
| 2352 |
auto wsPipe = newWebSocketPipe(); |
| 2353 |
|
| 2354 |
auto downstreamPump = wsPipe.ends[0]->pumpTo(*server); |
| 2355 |
KJ_EXPECT(!downstreamPump.poll(waitScope)); |
| 2356 |
|
| 2357 |
client->abort(); |
| 2358 |
|
| 2359 |
KJ_EXPECT(downstreamPump.poll(waitScope)); |
| 2360 |
KJ_EXPECT_THROW_RECOVERABLE(DISCONNECTED, downstreamPump.wait(waitScope)); |
| 2361 |
} |
| 2362 |
|
| 2363 |
KJ_TEST("WebSocket maximum message size") { |
| 2364 |
KJ_HTTP_TEST_SETUP_IO; |
| 2365 |
auto pipe =KJ_HTTP_TEST_CREATE_2PIPE; |
| 2366 |
|
| 2367 |
WebSocketErrorCatcher errorCatcher; |
| 2368 |
FakeEntropySource maskGenerator; |
| 2369 |
auto client = newWebSocket(kj::mv(pipe.ends[0]), maskGenerator); |
| 2370 |
auto server = newWebSocket(kj::mv(pipe.ends[1]), nullptr, nullptr, errorCatcher); |
| 2371 |
|
| 2372 |
size_t maxSize = 100; |
| 2373 |
auto biggestAllowedString = kj::strArray(kj::repeat(kj::StringPtr("A"), maxSize), ""); |
| 2374 |
auto tooBigString = kj::strArray(kj::repeat(kj::StringPtr("B"), maxSize + 1), ""); |
| 2375 |
|
| 2376 |
auto clientTask = client->send(biggestAllowedString) |
| 2377 |
.then([&]() { return client->send(tooBigString); }) |
| 2378 |
.then([&]() { return client->close(1234, "done"); }); |
| 2379 |
|
| 2380 |
{ |
| 2381 |
auto message = server->receive(maxSize).wait(waitScope); |
| 2382 |
KJ_ASSERT(message.is<kj::String>()); |
| 2383 |
KJ_EXPECT(message.get<kj::String>().size() == maxSize); |
| 2384 |
} |
| 2385 |
|
| 2386 |
{ |
| 2387 |
KJ_EXPECT_THROW_RECOVERABLE_MESSAGE("too large", |
| 2388 |
server->receive(maxSize).ignoreResult().wait(waitScope)); |
| 2389 |
KJ_ASSERT(errorCatcher.errors.size() == 1); |
| 2390 |
KJ_ASSERT(errorCatcher.errors[0].statusCode == 1009); |
| 2391 |
} |
| 2392 |
} |
| 2393 |
|
| 2394 |
class TestWebSocketService final: public HttpService, private kj::TaskSet::ErrorHandler { |
| 2395 |
public: |
| 2396 |
TestWebSocketService(HttpHeaderTable& headerTable, HttpHeaderId hMyHeader) |
| 2397 |
: headerTable(headerTable), hMyHeader(hMyHeader), tasks(*this) {} |
| 2398 |
|
| 2399 |
kj::Promise<void> request( |
| 2400 |
HttpMethod method, kj::StringPtr url, const HttpHeaders& headers, |
| 2401 |
kj::AsyncInputStream& requestBody, Response& response) override { |
| 2402 |
KJ_ASSERT(headers.isWebSocket()); |
| 2403 |
|
| 2404 |
HttpHeaders responseHeaders(headerTable); |
| 2405 |
KJ_IF_MAYBE(h, headers.get(hMyHeader)) { |
| 2406 |
responseHeaders.set(hMyHeader, kj::str("respond-", *h)); |
| 2407 |
} |
| 2408 |
|
| 2409 |
if (url == "/return-error") { |
| 2410 |
response.send(404, "Not Found", responseHeaders, uint64_t(0)); |
| 2411 |
return kj::READY_NOW; |
| 2412 |
} else if (url == "/websocket") { |
| 2413 |
auto ws = response.acceptWebSocket(responseHeaders); |
| 2414 |
return doWebSocket(*ws, "start-inline").attach(kj::mv(ws)); |
| 2415 |
} else { |
| 2416 |
KJ_FAIL_ASSERT("unexpected path", url); |
| 2417 |
} |
| 2418 |
} |
| 2419 |
|
| 2420 |
private: |
| 2421 |
HttpHeaderTable& headerTable; |
| 2422 |
HttpHeaderId hMyHeader; |
| 2423 |
kj::TaskSet tasks; |
| 2424 |
|
| 2425 |
void taskFailed(kj::Exception&& exception) override { |
| 2426 |
KJ_LOG(ERROR, exception); |
| 2427 |
} |
| 2428 |
|
| 2429 |
static kj::Promise<void> doWebSocket(WebSocket& ws, kj::StringPtr message) { |
| 2430 |
auto copy = kj::str(message); |
| 2431 |
return ws.send(copy).attach(kj::mv(copy)) |
| 2432 |
.then([&ws]() { |
| 2433 |
return ws.receive(); |
| 2434 |
}).then([&ws](WebSocket::Message&& message) { |
| 2435 |
KJ_SWITCH_ONEOF(message) { |
| 2436 |
KJ_CASE_ONEOF(str, kj::String) { |
| 2437 |
return doWebSocket(ws, kj::str("reply:", str)); |
| 2438 |
} |
| 2439 |
KJ_CASE_ONEOF(data, kj::Array<byte>) { |
| 2440 |
return doWebSocket(ws, kj::str("reply:", data)); |
| 2441 |
} |
| 2442 |
KJ_CASE_ONEOF(close, WebSocket::Close) { |
| 2443 |
auto reason = kj::str("close-reply:", close.reason); |
| 2444 |
return ws.close(close.code + 1, reason).attach(kj::mv(reason)); |
| 2445 |
} |
| 2446 |
} |
| 2447 |
KJ_UNREACHABLE; |
| 2448 |
}); |
| 2449 |
} |
| 2450 |
}; |
| 2451 |
|
| 2452 |
const char WEBSOCKET_REQUEST_HANDSHAKE[] = |
| 2453 |
" HTTP/1.1\r\n" |
| 2454 |
"Connection: Upgrade\r\n" |
| 2455 |
"Upgrade: websocket\r\n" |
| 2456 |
"Sec-WebSocket-Key: DCI4TgwiOE4MIjhODCI4Tg==\r\n" |
| 2457 |
"Sec-WebSocket-Version: 13\r\n" |
| 2458 |
"My-Header: foo\r\n" |
| 2459 |
"\r\n"; |
| 2460 |
const char WEBSOCKET_RESPONSE_HANDSHAKE[] = |
| 2461 |
"HTTP/1.1 101 Switching Protocols\r\n" |
| 2462 |
"Connection: Upgrade\r\n" |
| 2463 |
"Upgrade: websocket\r\n" |
| 2464 |
"Sec-WebSocket-Accept: pShtIFKT0s8RYZvnWY/CrjQD8CM=\r\n" |
| 2465 |
"My-Header: respond-foo\r\n" |
| 2466 |
"\r\n"; |
| 2467 |
#if KJ_HAS_ZLIB |
| 2468 |
const char WEBSOCKET_COMPRESSION_HANDSHAKE[] = |
| 2469 |
" HTTP/1.1\r\n" |
| 2470 |
"Connection: Upgrade\r\n" |
| 2471 |
"Upgrade: websocket\r\n" |
| 2472 |
"Sec-WebSocket-Key: DCI4TgwiOE4MIjhODCI4Tg==\r\n" |
| 2473 |
"Sec-WebSocket-Version: 13\r\n" |
| 2474 |
"Sec-WebSocket-Extensions: permessage-deflate; server_no_context_takeover\r\n" |
| 2475 |
"\r\n"; |
| 2476 |
const char WEBSOCKET_COMPRESSION_RESPONSE_HANDSHAKE[] = |
| 2477 |
"HTTP/1.1 101 Switching Protocols\r\n" |
| 2478 |
"Connection: Upgrade\r\n" |
| 2479 |
"Upgrade: websocket\r\n" |
| 2480 |
"Sec-WebSocket-Accept: pShtIFKT0s8RYZvnWY/CrjQD8CM=\r\n" |
| 2481 |
"Sec-WebSocket-Extensions: permessage-deflate; server_no_context_takeover\r\n" |
| 2482 |
"\r\n"; |
| 2483 |
const char WEBSOCKET_COMPRESSION_CLIENT_DISCARDS_CTX_HANDSHAKE[] = |
| 2484 |
" HTTP/1.1\r\n" |
| 2485 |
"Connection: Upgrade\r\n" |
| 2486 |
"Upgrade: websocket\r\n" |
| 2487 |
"Sec-WebSocket-Key: DCI4TgwiOE4MIjhODCI4Tg==\r\n" |
| 2488 |
"Sec-WebSocket-Version: 13\r\n" |
| 2489 |
"Sec-WebSocket-Extensions: permessage-deflate; client_no_context_takeover; " |
| 2490 |
"server_no_context_takeover\r\n" |
| 2491 |
"\r\n"; |
| 2492 |
const char WEBSOCKET_COMPRESSION_CLIENT_DISCARDS_CTX_RESPONSE_HANDSHAKE[] = |
| 2493 |
"HTTP/1.1 101 Switching Protocols\r\n" |
| 2494 |
"Connection: Upgrade\r\n" |
| 2495 |
"Upgrade: websocket\r\n" |
| 2496 |
"Sec-WebSocket-Accept: pShtIFKT0s8RYZvnWY/CrjQD8CM=\r\n" |
| 2497 |
"Sec-WebSocket-Extensions: permessage-deflate; client_no_context_takeover; " |
| 2498 |
"server_no_context_takeover\r\n" |
| 2499 |
"\r\n"; |
| 2500 |
#endif // KJ_HAS_ZLIB |
| 2501 |
const char WEBSOCKET_RESPONSE_HANDSHAKE_ERROR[] = |
| 2502 |
"HTTP/1.1 404 Not Found\r\n" |
| 2503 |
"Content-Length: 0\r\n" |
| 2504 |
"My-Header: respond-foo\r\n" |
| 2505 |
"\r\n"; |
| 2506 |
const byte WEBSOCKET_FIRST_MESSAGE_INLINE[] = |
| 2507 |
{ 0x81, 0x0c, 's','t','a','r','t','-','i','n','l','i','n','e' }; |
| 2508 |
const byte WEBSOCKET_SEND_MESSAGE[] = |
| 2509 |
{ 0x81, 0x83, 12, 34, 56, 78, 'b'^12, 'a'^34, 'r'^56 }; |
| 2510 |
const byte WEBSOCKET_REPLY_MESSAGE[] = |
| 2511 |
{ 0x81, 0x09, 'r','e','p','l','y',':','b','a','r' }; |
| 2512 |
const byte WEBSOCKET_SEND_CLOSE[] = |
| 2513 |
{ 0x88, 0x85, 12, 34, 56, 78, 0x12^12, 0x34^34, 'q'^56, 'u'^78, 'x'^12 }; |
| 2514 |
const byte WEBSOCKET_REPLY_CLOSE[] = |
| 2515 |
{ 0x88, 0x11, 0x12, 0x35, 'c','l','o','s','e','-','r','e','p','l','y',':','q','u','x' }; |
| 2516 |
|
| 2517 |
#if KJ_HAS_ZLIB |
| 2518 |
const byte WEBSOCKET_FIRST_COMPRESSED_MESSAGE[] = |
| 2519 |
{ 0xc1, 0x07, 0xf2, 0x48, 0xcd, 0xc9, 0xc9, 0x07, 0x00 }; |
| 2520 |
// See this example: https://datatracker.ietf.org/doc/html/rfc7692#section-7.2.3.2 |
| 2521 |
const byte WEBSOCKET_SEND_COMPRESSED_MESSAGE[] = |
| 2522 |
{ 0xc1, 0x87, 12, 34, 56, 78, 0xf2^12, 0x48^34, 0xcd^56, 0xc9^78, 0xc9^12, 0x07^34, 0x00^56 }; |
| 2523 |
const byte WEBSOCKET_SEND_COMPRESSED_MESSAGE_REUSE_CTX[] = |
| 2524 |
{ 0xc1, 0x85, 12, 34, 56, 78, 0xf2^12, 0x00^34, 0x11^56, 0x00^78, 0x00^12}; |
| 2525 |
// See same compression example, but where `client_no_context_takeover` is used (saves 2 bytes). |
| 2526 |
const byte WEBSOCKET_DEFLATE_NO_COMPRESSION_MESSAGE[] = |
| 2527 |
{ 0xc1, 0x0b, 0x00, 0x05, 0x00, 0xfa, 0xff, 0x48, 0x65, 0x6c, 0x6c, 0x6f, 0x00 }; |
| 2528 |
// See this example: https://datatracker.ietf.org/doc/html/rfc7692#section-7.2.3.3 |
| 2529 |
// This uses a DEFLATE block with no compression. |
| 2530 |
const byte WEBSOCKET_BFINAL_SET_MESSAGE[] = |
| 2531 |
{ 0xc1, 0x08, 0xf3, 0x48, 0xcd, 0xc9, 0xc9, 0x07, 0x00, 0x00 }; |
| 2532 |
// See this example: https://datatracker.ietf.org/doc/html/rfc7692#section-7.2.3.4 |
| 2533 |
// This uses a DEFLATE block with BFINAL set to 1. |
| 2534 |
const byte WEBSOCKET_TWO_DEFLATE_BLOCKS_MESSAGE[] = |
| 2535 |
{ 0xc1, 0x0d, 0xf2, 0x48, 0x05, 0x00, 0x00, 0x00, 0xff, 0xff, 0xca, 0xc9, 0xc9, 0x07, 0x00 }; |
| 2536 |
// See this example: https://datatracker.ietf.org/doc/html/rfc7692#section-7.2.3.5 |
| 2537 |
// This uses two DEFLATE blocks in a single message. |
| 2538 |
const byte WEBSOCKET_EMPTY_COMPRESSED_MESSAGE[] = |
| 2539 |
{ 0xc1, 0x01, 0x00 }; |
| 2540 |
const byte WEBSOCKET_EMPTY_SEND_COMPRESSED_MESSAGE[] = |
| 2541 |
{ 0xc1, 0x81, 12, 34, 56, 78, 0x00^12 }; |
| 2542 |
#endif // KJ_HAS_ZLIB |
| 2543 |
|
| 2544 |
template <size_t s> |
| 2545 |
kj::ArrayPtr<const byte> asBytes(const char (&chars)[s]) { |
| 2546 |
return kj::ArrayPtr<const char>(chars, s - 1).asBytes(); |
| 2547 |
} |
| 2548 |
|
| 2549 |
void testWebSocketClient(kj::WaitScope& waitScope, HttpHeaderTable& headerTable, |
| 2550 |
kj::HttpHeaderId hMyHeader, HttpClient& client) { |
| 2551 |
kj::HttpHeaders headers(headerTable); |
| 2552 |
headers.set(hMyHeader, "foo"); |
| 2553 |
auto response = client.openWebSocket("/websocket", headers).wait(waitScope); |
| 2554 |
|
| 2555 |
KJ_EXPECT(response.statusCode == 101); |
| 2556 |
KJ_EXPECT(response.statusText == "Switching Protocols", response.statusText); |
| 2557 |
KJ_EXPECT(KJ_ASSERT_NONNULL(response.headers->get(hMyHeader)) == "respond-foo"); |
| 2558 |
KJ_ASSERT(response.webSocketOrBody.is<kj::Own<WebSocket>>()); |
| 2559 |
auto ws = kj::mv(response.webSocketOrBody.get<kj::Own<WebSocket>>()); |
| 2560 |
|
| 2561 |
{ |
| 2562 |
auto message = ws->receive().wait(waitScope); |
| 2563 |
KJ_ASSERT(message.is<kj::String>()); |
| 2564 |
KJ_EXPECT(message.get<kj::String>() == "start-inline"); |
| 2565 |
} |
| 2566 |
|
| 2567 |
ws->send(kj::StringPtr("bar")).wait(waitScope); |
| 2568 |
{ |
| 2569 |
auto message = ws->receive().wait(waitScope); |
| 2570 |
KJ_ASSERT(message.is<kj::String>()); |
| 2571 |
KJ_EXPECT(message.get<kj::String>() == "reply:bar"); |
| 2572 |
} |
| 2573 |
|
| 2574 |
ws->close(0x1234, "qux").wait(waitScope); |
| 2575 |
{ |
| 2576 |
auto message = ws->receive().wait(waitScope); |
| 2577 |
KJ_ASSERT(message.is<WebSocket::Close>()); |
| 2578 |
KJ_EXPECT(message.get<WebSocket::Close>().code == 0x1235); |
| 2579 |
KJ_EXPECT(message.get<WebSocket::Close>().reason == "close-reply:qux"); |
| 2580 |
} |
| 2581 |
} |
| 2582 |
|
| 2583 |
#if KJ_HAS_ZLIB |
| 2584 |
void testWebSocketTwoMessageCompression(kj::WaitScope& waitScope, HttpHeaderTable& headerTable, |
| 2585 |
kj::HttpHeaderId extHeader, kj::StringPtr extensions, |
| 2586 |
HttpClient& client) { |
| 2587 |
// In this test, the server will always use `server_no_context_takeover` (since we can just reuse |
| 2588 |
// the message). However, we will modify the client's compressor in different ways to see how the |
| 2589 |
// compressed message changes. |
| 2590 |
|
| 2591 |
kj::HttpHeaders headers(headerTable); |
| 2592 |
headers.set(extHeader, extensions); |
| 2593 |
auto response = client.openWebSocket("/websocket", headers).wait(waitScope); |
| 2594 |
|
| 2595 |
KJ_EXPECT(response.statusCode == 101); |
| 2596 |
KJ_EXPECT(response.statusText == "Switching Protocols", response.statusText); |
| 2597 |
KJ_EXPECT(KJ_ASSERT_NONNULL(response.headers->get(extHeader)).startsWith("permessage-deflate")); |
| 2598 |
KJ_ASSERT(response.webSocketOrBody.is<kj::Own<WebSocket>>()); |
| 2599 |
auto ws = kj::mv(response.webSocketOrBody.get<kj::Own<WebSocket>>()); |
| 2600 |
|
| 2601 |
{ |
| 2602 |
auto message = ws->receive().wait(waitScope); |
| 2603 |
KJ_ASSERT(message.is<kj::String>()); |
| 2604 |
KJ_EXPECT(message.get<kj::String>() == "Hello"); |
| 2605 |
} |
| 2606 |
ws->send(kj::StringPtr("Hello")).wait(waitScope); |
| 2607 |
|
| 2608 |
{ |
| 2609 |
auto message = ws->receive().wait(waitScope); |
| 2610 |
KJ_ASSERT(message.is<kj::String>()); |
| 2611 |
KJ_EXPECT(message.get<kj::String>() == "Hello"); |
| 2612 |
} |
| 2613 |
ws->send(kj::StringPtr("Hello")).wait(waitScope); |
| 2614 |
|
| 2615 |
ws->close(0x1234, "qux").wait(waitScope); |
| 2616 |
{ |
| 2617 |
auto message = ws->receive().wait(waitScope); |
| 2618 |
KJ_ASSERT(message.is<WebSocket::Close>()); |
| 2619 |
KJ_EXPECT(message.get<WebSocket::Close>().code == 0x1235); |
| 2620 |
KJ_EXPECT(message.get<WebSocket::Close>().reason == "close-reply:qux"); |
| 2621 |
} |
| 2622 |
} |
| 2623 |
#endif // KJ_HAS_ZLIB |
| 2624 |
|
| 2625 |
#if KJ_HAS_ZLIB |
| 2626 |
void testWebSocketEmptyMessageCompression(kj::WaitScope& waitScope, HttpHeaderTable& headerTable, |
| 2627 |
kj::HttpHeaderId extHeader, kj::StringPtr extensions, |
| 2628 |
HttpClient& client) { |
| 2629 |
// Confirm that we can send empty messages when compression is enabled. |
| 2630 |
|
| 2631 |
kj::HttpHeaders headers(headerTable); |
| 2632 |
headers.set(extHeader, extensions); |
| 2633 |
auto response = client.openWebSocket("/websocket", headers).wait(waitScope); |
| 2634 |
|
| 2635 |
KJ_EXPECT(response.statusCode == 101); |
| 2636 |
KJ_EXPECT(response.statusText == "Switching Protocols", response.statusText); |
| 2637 |
KJ_EXPECT(KJ_ASSERT_NONNULL(response.headers->get(extHeader)).startsWith("permessage-deflate")); |
| 2638 |
KJ_ASSERT(response.webSocketOrBody.is<kj::Own<WebSocket>>()); |
| 2639 |
auto ws = kj::mv(response.webSocketOrBody.get<kj::Own<WebSocket>>()); |
| 2640 |
|
| 2641 |
{ |
| 2642 |
auto message = ws->receive().wait(waitScope); |
| 2643 |
KJ_ASSERT(message.is<kj::String>()); |
| 2644 |
KJ_EXPECT(message.get<kj::String>() == "Hello"); |
| 2645 |
} |
| 2646 |
ws->send(kj::StringPtr("Hello")).wait(waitScope); |
| 2647 |
|
| 2648 |
{ |
| 2649 |
auto message = ws->receive().wait(waitScope); |
| 2650 |
KJ_ASSERT(message.is<kj::String>()); |
| 2651 |
KJ_EXPECT(message.get<kj::String>() == ""); |
| 2652 |
} |
| 2653 |
ws->send(kj::StringPtr("")).wait(waitScope); |
| 2654 |
|
| 2655 |
{ |
| 2656 |
auto message = ws->receive().wait(waitScope); |
| 2657 |
KJ_ASSERT(message.is<kj::String>()); |
| 2658 |
KJ_EXPECT(message.get<kj::String>() == "Hello"); |
| 2659 |
} |
| 2660 |
ws->send(kj::StringPtr("Hello")).wait(waitScope); |
| 2661 |
|
| 2662 |
ws->close(0x1234, "qux").wait(waitScope); |
| 2663 |
{ |
| 2664 |
auto message = ws->receive().wait(waitScope); |
| 2665 |
KJ_ASSERT(message.is<WebSocket::Close>()); |
| 2666 |
KJ_EXPECT(message.get<WebSocket::Close>().code == 0x1235); |
| 2667 |
KJ_EXPECT(message.get<WebSocket::Close>().reason == "close-reply:qux"); |
| 2668 |
} |
| 2669 |
} |
| 2670 |
#endif // KJ_HAS_ZLIB |
| 2671 |
|
| 2672 |
#if KJ_HAS_ZLIB |
| 2673 |
void testWebSocketOptimizePumpProxy(kj::WaitScope& waitScope, HttpHeaderTable& headerTable, |
| 2674 |
kj::HttpHeaderId extHeader, kj::StringPtr extensions, |
| 2675 |
HttpClient& client) { |
| 2676 |
// Suppose we are proxying a websocket conversation between a client and a server. |
| 2677 |
// This looks something like: CLIENT <--> (proxyServer <==PUMP==> proxyClient) <--> SERVER |
| 2678 |
// |
| 2679 |
// We want to enable optimizedPumping from the proxy's server (which communicates with the client), |
| 2680 |
// to the proxy's client (which communicates with the origin server). |
| 2681 |
// |
| 2682 |
// For this to work, proxyServer's inbound settings must map to proxyClient's outbound settings |
| 2683 |
// (and vice versa). In this case, `ws` is `proxyClient`, so we want to take `ws`'s compression |
| 2684 |
// configuration and pass it to `proxyServer` in a way that would allow for optimizedPumping. |
| 2685 |
|
| 2686 |
kj::HttpHeaders headers(headerTable); |
| 2687 |
headers.set(extHeader, extensions); |
| 2688 |
auto response = client.openWebSocket("/websocket", headers).wait(waitScope); |
| 2689 |
|
| 2690 |
KJ_EXPECT(response.statusCode == 101); |
| 2691 |
KJ_EXPECT(response.statusText == "Switching Protocols", response.statusText); |
| 2692 |
KJ_EXPECT(KJ_ASSERT_NONNULL(response.headers->get(extHeader)).startsWith("permessage-deflate")); |
| 2693 |
KJ_ASSERT(response.webSocketOrBody.is<kj::Own<WebSocket>>()); |
| 2694 |
auto ws = kj::mv(response.webSocketOrBody.get<kj::Own<WebSocket>>()); |
| 2695 |
|
| 2696 |
auto maybeExt = ws->getPreferredExtensions(kj::WebSocket::ExtensionsContext::REQUEST); |
| 2697 |
// Should be nullptr since we are asking `ws` (a client) to give us extensions that we can give to |
| 2698 |
// another client. Since clients cannot `optimizedPumpTo` each other, we must get null. |
| 2699 |
KJ_ASSERT(maybeExt == nullptr); |
| 2700 |
|
| 2701 |
maybeExt = ws->getPreferredExtensions(kj::WebSocket::ExtensionsContext::RESPONSE); |
| 2702 |
kj::StringPtr extStr = KJ_ASSERT_NONNULL(maybeExt); |
| 2703 |
KJ_ASSERT(extStr == "permessage-deflate; server_no_context_takeover"); |
| 2704 |
// We got back the string the client sent! |
| 2705 |
// We could then pass this string as a header to `acceptWebSocket` and ensure the `proxyServer`s |
| 2706 |
// inbound settings match the `proxyClient`s outbound settings. |
| 2707 |
|
| 2708 |
ws->close(0x1234, "qux").wait(waitScope); |
| 2709 |
{ |
| 2710 |
auto message = ws->receive().wait(waitScope); |
| 2711 |
KJ_ASSERT(message.is<WebSocket::Close>()); |
| 2712 |
KJ_EXPECT(message.get<WebSocket::Close>().code == 0x1235); |
| 2713 |
KJ_EXPECT(message.get<WebSocket::Close>().reason == "close-reply:qux"); |
| 2714 |
} |
| 2715 |
} |
| 2716 |
#endif // KJ_HAS_ZLIB |
| 2717 |
#if KJ_HAS_ZLIB |
| 2718 |
void testWebSocketFourMessageCompression(kj::WaitScope& waitScope, HttpHeaderTable& headerTable, |
| 2719 |
kj::HttpHeaderId extHeader, kj::StringPtr extensions, |
| 2720 |
HttpClient& client) { |
| 2721 |
// In this test, the server will always use `server_no_context_takeover` (since we can just reuse |
| 2722 |
// the message). We will receive three messages. |
| 2723 |
|
| 2724 |
kj::HttpHeaders headers(headerTable); |
| 2725 |
headers.set(extHeader, extensions); |
| 2726 |
auto response = client.openWebSocket("/websocket", headers).wait(waitScope); |
| 2727 |
|
| 2728 |
KJ_EXPECT(response.statusCode == 101); |
| 2729 |
KJ_EXPECT(response.statusText == "Switching Protocols", response.statusText); |
| 2730 |
KJ_EXPECT(KJ_ASSERT_NONNULL(response.headers->get(extHeader)).startsWith("permessage-deflate")); |
| 2731 |
KJ_ASSERT(response.webSocketOrBody.is<kj::Own<WebSocket>>()); |
| 2732 |
auto ws = kj::mv(response.webSocketOrBody.get<kj::Own<WebSocket>>()); |
| 2733 |
|
| 2734 |
for (size_t i = 0; i < 4; i++) { |
| 2735 |
{ |
| 2736 |
auto message = ws->receive().wait(waitScope); |
| 2737 |
KJ_ASSERT(message.is<kj::String>()); |
| 2738 |
KJ_EXPECT(message.get<kj::String>() == "Hello"); |
| 2739 |
} |
| 2740 |
} |
| 2741 |
|
| 2742 |
ws->close(0x1234, "qux").wait(waitScope); |
| 2743 |
{ |
| 2744 |
auto message = ws->receive().wait(waitScope); |
| 2745 |
KJ_ASSERT(message.is<WebSocket::Close>()); |
| 2746 |
KJ_EXPECT(message.get<WebSocket::Close>().code == 0x1235); |
| 2747 |
KJ_EXPECT(message.get<WebSocket::Close>().reason == "close-reply:qux"); |
| 2748 |
} |
| 2749 |
} |
| 2750 |
#endif // KJ_HAS_ZLIB |
| 2751 |
|
| 2752 |
inline kj::Promise<void> writeA(kj::AsyncOutputStream& out, kj::ArrayPtr<const byte> data) { |
| 2753 |
return out.write(data.begin(), data.size()); |
| 2754 |
} |
| 2755 |
|
| 2756 |
KJ_TEST("HttpClient WebSocket handshake") { |
| 2757 |
KJ_HTTP_TEST_SETUP_IO; |
| 2758 |
auto pipe = KJ_HTTP_TEST_CREATE_2PIPE; |
| 2759 |
|
| 2760 |
auto request = kj::str("GET /websocket", WEBSOCKET_REQUEST_HANDSHAKE); |
| 2761 |
|
| 2762 |
auto serverTask = expectRead(*pipe.ends[1], request) |
| 2763 |
.then([&]() { return writeA(*pipe.ends[1], asBytes(WEBSOCKET_RESPONSE_HANDSHAKE)); }) |
| 2764 |
.then([&]() { return writeA(*pipe.ends[1], WEBSOCKET_FIRST_MESSAGE_INLINE); }) |
| 2765 |
.then([&]() { return expectRead(*pipe.ends[1], WEBSOCKET_SEND_MESSAGE); }) |
| 2766 |
.then([&]() { return writeA(*pipe.ends[1], WEBSOCKET_REPLY_MESSAGE); }) |
| 2767 |
.then([&]() { return expectRead(*pipe.ends[1], WEBSOCKET_SEND_CLOSE); }) |
| 2768 |
.then([&]() { return writeA(*pipe.ends[1], WEBSOCKET_REPLY_CLOSE); }) |
| 2769 |
.eagerlyEvaluate([](kj::Exception&& e) { KJ_LOG(ERROR, e); }); |
| 2770 |
|
| 2771 |
HttpHeaderTable::Builder tableBuilder; |
| 2772 |
HttpHeaderId hMyHeader = tableBuilder.add("My-Header"); |
| 2773 |
auto headerTable = tableBuilder.build(); |
| 2774 |
|
| 2775 |
FakeEntropySource entropySource; |
| 2776 |
HttpClientSettings clientSettings; |
| 2777 |
clientSettings.entropySource = entropySource; |
| 2778 |
|
| 2779 |
auto client = newHttpClient(*headerTable, *pipe.ends[0], clientSettings); |
| 2780 |
|
| 2781 |
testWebSocketClient(waitScope, *headerTable, hMyHeader, *client); |
| 2782 |
|
| 2783 |
serverTask.wait(waitScope); |
| 2784 |
} |
| 2785 |
|
| 2786 |
KJ_TEST("WebSocket Compression String Parsing (splitNext)") { |
| 2787 |
// Test `splitNext()`. |
| 2788 |
// We want to assert that: |
| 2789 |
// If a delimiter is found: |
| 2790 |
// - `input` is updated to point to the rest of the string after the delimiter. |
| 2791 |
// - The text before the delimiter is returned. |
| 2792 |
// If no delimiter is found: |
| 2793 |
// - `input` is updated to an empty string. |
| 2794 |
// - The text that had been in `input` is returned. |
| 2795 |
|
| 2796 |
const auto s = "permessage-deflate; client_max_window_bits=10;server_no_context_takeover"_kj; |
| 2797 |
|
| 2798 |
const auto expectedPartOne = "permessage-deflate"_kj; |
| 2799 |
const auto expectedRemainingOne = "client_max_window_bits=10;server_no_context_takeover"_kj; |
| 2800 |
|
| 2801 |
auto cursor = s.asArray(); |
| 2802 |
auto actual = _::splitNext(cursor, ';'); |
| 2803 |
KJ_ASSERT(actual == expectedPartOne); |
| 2804 |
|
| 2805 |
_::stripLeadingAndTrailingSpace(cursor); |
| 2806 |
KJ_ASSERT(cursor == expectedRemainingOne.asArray()); |
| 2807 |
|
| 2808 |
const auto expectedPartTwo = "client_max_window_bits=10"_kj; |
| 2809 |
const auto expectedRemainingTwo = "server_no_context_takeover"_kj; |
| 2810 |
|
| 2811 |
actual = _::splitNext(cursor, ';'); |
| 2812 |
KJ_ASSERT(actual == expectedPartTwo); |
| 2813 |
KJ_ASSERT(cursor == expectedRemainingTwo); |
| 2814 |
|
| 2815 |
const auto expectedPartThree = "server_no_context_takeover"_kj; |
| 2816 |
const auto expectedRemainingThree = ""_kj; |
| 2817 |
actual = _::splitNext(cursor, ';'); |
| 2818 |
KJ_ASSERT(actual == expectedPartThree); |
| 2819 |
KJ_ASSERT(cursor == expectedRemainingThree); |
| 2820 |
} |
| 2821 |
|
| 2822 |
KJ_TEST("WebSocket Compression String Parsing (splitParts)") { |
| 2823 |
// Test `splitParts()`. |
| 2824 |
// We want to assert that we: |
| 2825 |
// 1. Correctly split by the delimiter. |
| 2826 |
// 2. Strip whitespace before/after the extracted part. |
| 2827 |
const auto permitted = "permessage-deflate"_kj; |
| 2828 |
|
| 2829 |
const auto s = "permessage-deflate; client_max_window_bits=10;server_no_context_takeover, " |
| 2830 |
" permessage-deflate; ; ," // strips leading whitespace |
| 2831 |
"permessage-deflate"_kj; |
| 2832 |
|
| 2833 |
// These are the expected values. |
| 2834 |
const auto extOne = "permessage-deflate; client_max_window_bits=10;server_no_context_takeover"_kj; |
| 2835 |
const auto extTwo = "permessage-deflate; ;"_kj; |
| 2836 |
const auto extThree = "permessage-deflate"_kj; |
| 2837 |
|
| 2838 |
auto actualExtensions = kj::_::splitParts(s, ','); |
| 2839 |
KJ_ASSERT(actualExtensions.size() == 3); |
| 2840 |
KJ_ASSERT(actualExtensions[0] == extOne); |
| 2841 |
KJ_ASSERT(actualExtensions[1] == extTwo); |
| 2842 |
KJ_ASSERT(actualExtensions[2] == extThree); |
| 2843 |
// Splitting by ',' was fine, now let's try splitting the parameters (split by ';'). |
| 2844 |
|
| 2845 |
const auto paramOne = "client_max_window_bits=10"_kj; |
| 2846 |
const auto paramTwo = "server_no_context_takeover"_kj; |
| 2847 |
|
| 2848 |
auto actualParamsFirstExt = kj::_::splitParts(actualExtensions[0], ';'); |
| 2849 |
KJ_ASSERT(actualParamsFirstExt.size() == 3); |
| 2850 |
KJ_ASSERT(actualParamsFirstExt[0] == permitted); |
| 2851 |
KJ_ASSERT(actualParamsFirstExt[1] == paramOne); |
| 2852 |
KJ_ASSERT(actualParamsFirstExt[2] == paramTwo); |
| 2853 |
|
| 2854 |
auto actualParamsSecondExt = kj::_::splitParts(actualExtensions[1], ';'); |
| 2855 |
KJ_ASSERT(actualParamsSecondExt.size() == 2); |
| 2856 |
KJ_ASSERT(actualParamsSecondExt[0] == permitted); |
| 2857 |
KJ_ASSERT(actualParamsSecondExt[1] == ""_kj); // Note that the whitespace was stripped. |
| 2858 |
|
| 2859 |
auto actualParamsThirdExt = kj::_::splitParts(actualExtensions[2], ';'); |
| 2860 |
// No parameters supplied in the third offer. We expect to only see the extension name. |
| 2861 |
KJ_ASSERT(actualParamsThirdExt.size() == 1); |
| 2862 |
KJ_ASSERT(actualParamsThirdExt[0] == permitted); |
| 2863 |
} |
| 2864 |
|
| 2865 |
KJ_TEST("WebSocket Compression String Parsing (toKeysAndVals)") { |
| 2866 |
// If an "=" is found, everything before the "=" goes into the `Key` and everything after goes |
| 2867 |
// into the `Value`. Otherwise, everything goes into the `Key` and the `Value` remains null. |
| 2868 |
const auto cleanParameters = "client_no_context_takeover; client_max_window_bits; " |
| 2869 |
"server_max_window_bits=10"_kj; |
| 2870 |
auto parts = _::splitParts(cleanParameters, ';'); |
| 2871 |
auto keysMaybeValues = _::toKeysAndVals(parts.asPtr()); |
| 2872 |
KJ_ASSERT(keysMaybeValues.size() == 3); |
| 2873 |
|
| 2874 |
auto firstKey = "client_no_context_takeover"_kj; |
| 2875 |
KJ_ASSERT(keysMaybeValues[0].key == firstKey.asArray()); |
| 2876 |
KJ_ASSERT(keysMaybeValues[0].val == nullptr); |
| 2877 |
|
| 2878 |
auto secondKey = "client_max_window_bits"_kj; |
| 2879 |
KJ_ASSERT(keysMaybeValues[1].key == secondKey.asArray()); |
| 2880 |
KJ_ASSERT(keysMaybeValues[1].val == nullptr); |
| 2881 |
|
| 2882 |
auto thirdKey = "server_max_window_bits"_kj; |
| 2883 |
auto thirdVal = "10"_kj; |
| 2884 |
KJ_ASSERT(keysMaybeValues[2].key == thirdKey.asArray()); |
| 2885 |
KJ_ASSERT(keysMaybeValues[2].val == thirdVal.asArray()); |
| 2886 |
|
| 2887 |
const auto weirdParameters = "= 14 ; client_max_window_bits= ; server_max_window_bits =hello"_kj; |
| 2888 |
// This is weird because: |
| 2889 |
// 1. Parameter 1 has no key. |
| 2890 |
// 2. Parameter 2 has an "=" but no subsequent value. |
| 2891 |
// 3. Parameter 3 has an "=" with an invalid value. |
| 2892 |
// That said, we don't mind if the parameters are weird when calling this function. The point |
| 2893 |
// is to create KeyMaybeVal pairs and process them later. |
| 2894 |
|
| 2895 |
parts = _::splitParts(weirdParameters, ';'); |
| 2896 |
keysMaybeValues = _::toKeysAndVals(parts.asPtr()); |
| 2897 |
KJ_ASSERT(keysMaybeValues.size() == 3); |
| 2898 |
|
| 2899 |
firstKey = ""_kj; |
| 2900 |
auto firstVal = "14"_kj; |
| 2901 |
KJ_ASSERT(keysMaybeValues[0].key == firstKey.asArray()); |
| 2902 |
KJ_ASSERT(keysMaybeValues[0].val == firstVal.asArray()); |
| 2903 |
|
| 2904 |
secondKey = "client_max_window_bits"_kj; |
| 2905 |
auto secondVal = ""_kj; |
| 2906 |
KJ_ASSERT(keysMaybeValues[1].key == secondKey.asArray()); |
| 2907 |
KJ_ASSERT(keysMaybeValues[1].val == secondVal.asArray()); |
| 2908 |
|
| 2909 |
thirdKey = "server_max_window_bits"_kj; |
| 2910 |
thirdVal = "hello"_kj; |
| 2911 |
KJ_ASSERT(keysMaybeValues[2].key == thirdKey.asArray()); |
| 2912 |
KJ_ASSERT(keysMaybeValues[2].val == thirdVal.asArray()); |
| 2913 |
} |
| 2914 |
|
| 2915 |
KJ_TEST("WebSocket Compression String Parsing (populateUnverifiedConfig)") { |
| 2916 |
// First we'll cover cases where the `UnverifiedConfig` is successfully constructed, |
| 2917 |
// which indicates the offer was structured in a parseable way. Next, we'll cover cases where the |
| 2918 |
// offer is structured incorrectly. |
| 2919 |
const auto cleanParameters = "client_no_context_takeover; client_max_window_bits; " |
| 2920 |
"server_max_window_bits=10"_kj; |
| 2921 |
auto parts = _::splitParts(cleanParameters, ';'); |
| 2922 |
auto keysMaybeValues = _::toKeysAndVals(parts.asPtr()); |
| 2923 |
|
| 2924 |
auto unverified = _::populateUnverifiedConfig(keysMaybeValues); |
| 2925 |
auto config = KJ_ASSERT_NONNULL(unverified); |
| 2926 |
KJ_ASSERT(config.clientNoContextTakeover == true); |
| 2927 |
KJ_ASSERT(config.serverNoContextTakeover == false); |
| 2928 |
|
| 2929 |
auto clientBits = KJ_ASSERT_NONNULL(config.clientMaxWindowBits); |
| 2930 |
KJ_ASSERT(clientBits == ""_kj); |
| 2931 |
auto serverBits = KJ_ASSERT_NONNULL(config.serverMaxWindowBits); |
| 2932 |
KJ_ASSERT(serverBits == "10"_kj); |
| 2933 |
// Valid config can be populated succesfully. |
| 2934 |
|
| 2935 |
const auto weirdButValidParameters = "client_no_context_takeover; client_max_window_bits; " |
| 2936 |
"server_max_window_bits=this_should_be_a_number"_kj; |
| 2937 |
parts = _::splitParts(weirdButValidParameters, ';'); |
| 2938 |
keysMaybeValues = _::toKeysAndVals(parts.asPtr()); |
| 2939 |
|
| 2940 |
unverified = _::populateUnverifiedConfig(keysMaybeValues); |
| 2941 |
config = KJ_ASSERT_NONNULL(unverified); |
| 2942 |
KJ_ASSERT(config.clientNoContextTakeover == true); |
| 2943 |
KJ_ASSERT(config.serverNoContextTakeover == false); |
| 2944 |
|
| 2945 |
clientBits = KJ_ASSERT_NONNULL(config.clientMaxWindowBits); |
| 2946 |
KJ_ASSERT(clientBits == ""_kj); |
| 2947 |
serverBits = KJ_ASSERT_NONNULL(config.serverMaxWindowBits); |
| 2948 |
KJ_ASSERT(serverBits == "this_should_be_a_number"_kj); |
| 2949 |
// Note that while the value associated with `server_max_window_bits` is not a number, |
| 2950 |
// `populateUnverifiedConfig` succeeds because the parameter[=value] is generally structured |
| 2951 |
// correctly. |
| 2952 |
|
| 2953 |
// --- HANDLE INCORRECTLY STRUCTURED OFFERS --- |
| 2954 |
auto invalidKey = "somethingKey; client_max_window_bits;"_kj; |
| 2955 |
parts = _::splitParts(invalidKey, ';'); |
| 2956 |
keysMaybeValues = _::toKeysAndVals(parts.asPtr()); |
| 2957 |
KJ_ASSERT(_::populateUnverifiedConfig(keysMaybeValues) == nullptr); |
| 2958 |
// Fail to populate due to invalid key name |
| 2959 |
|
| 2960 |
auto invalidKeyTwo = "client_max_window_bitsJUNK; server_no_context_takeover"_kj; |
| 2961 |
parts = _::splitParts(invalidKeyTwo, ';'); |
| 2962 |
keysMaybeValues = _::toKeysAndVals(parts.asPtr()); |
| 2963 |
KJ_ASSERT(_::populateUnverifiedConfig(keysMaybeValues) == nullptr); |
| 2964 |
// Fail to populate due to invalid key name (invalid characters after valid parameter name). |
| 2965 |
|
| 2966 |
auto repeatedKey = "client_no_context_takeover; client_no_context_takeover"_kj; |
| 2967 |
parts = _::splitParts(repeatedKey, ';'); |
| 2968 |
keysMaybeValues = _::toKeysAndVals(parts.asPtr()); |
| 2969 |
KJ_ASSERT(_::populateUnverifiedConfig(keysMaybeValues) == nullptr); |
| 2970 |
// Fail to populate due to repeated key name. |
| 2971 |
|
| 2972 |
auto unexpectedValue = "client_no_context_takeover="_kj; |
| 2973 |
parts = _::splitParts(unexpectedValue, ';'); |
| 2974 |
keysMaybeValues = _::toKeysAndVals(parts.asPtr()); |
| 2975 |
KJ_ASSERT(_::populateUnverifiedConfig(keysMaybeValues) == nullptr); |
| 2976 |
// Fail to populate due to value in `x_no_context_takeover` parameter (unexpected value). |
| 2977 |
|
| 2978 |
auto unexpectedValueTwo = "client_no_context_takeover= "_kj; |
| 2979 |
parts = _::splitParts(unexpectedValueTwo, ';'); |
| 2980 |
keysMaybeValues = _::toKeysAndVals(parts.asPtr()); |
| 2981 |
KJ_ASSERT(_::populateUnverifiedConfig(keysMaybeValues) == nullptr); |
| 2982 |
// Fail to populate due to value in `x_no_context_takeover` parameter. |
| 2983 |
|
| 2984 |
auto emptyValue = "client_max_window_bits="_kj; |
| 2985 |
parts = _::splitParts(emptyValue, ';'); |
| 2986 |
keysMaybeValues = _::toKeysAndVals(parts.asPtr()); |
| 2987 |
KJ_ASSERT(_::populateUnverifiedConfig(keysMaybeValues) == nullptr); |
| 2988 |
// Fail to populate due to empty value in `x_max_window_bits` parameter. |
| 2989 |
// "Empty" in this case means an "=" was provided, but no subsequent value was provided. |
| 2990 |
|
| 2991 |
auto emptyValueTwo = "client_max_window_bits= "_kj; |
| 2992 |
parts = _::splitParts(emptyValueTwo, ';'); |
| 2993 |
keysMaybeValues = _::toKeysAndVals(parts.asPtr()); |
| 2994 |
KJ_ASSERT(_::populateUnverifiedConfig(keysMaybeValues) == nullptr); |
| 2995 |
// Fail to populate due to empty value in `x_max_window_bits` parameter. |
| 2996 |
// "Empty" in this case means an "=" was provided, but no subsequent value was provided. |
| 2997 |
} |
| 2998 |
|
| 2999 |
KJ_TEST("WebSocket Compression String Parsing (validateCompressionConfig)") { |
| 3000 |
// We've tested `toKeysAndVals()` and `populateUnverifiedConfig()`, so we only need to test |
| 3001 |
// correctly structured offers/agreements here. |
| 3002 |
const auto cleanParameters = "client_no_context_takeover; client_max_window_bits; " |
| 3003 |
"server_max_window_bits=10"_kj; |
| 3004 |
auto parts = _::splitParts(cleanParameters, ';'); |
| 3005 |
auto keysMaybeValues = _::toKeysAndVals(parts.asPtr()); |
| 3006 |
auto maybeUnverified = _::populateUnverifiedConfig(keysMaybeValues); |
| 3007 |
auto unverified = KJ_ASSERT_NONNULL(maybeUnverified); |
| 3008 |
auto maybeValid = _::validateCompressionConfig(kj::mv(unverified), false); // Validate as Server. |
| 3009 |
auto valid = KJ_ASSERT_NONNULL(maybeValid); |
| 3010 |
KJ_ASSERT(valid.inboundNoContextTakeover == true); |
| 3011 |
KJ_ASSERT(valid.outboundNoContextTakeover == false); |
| 3012 |
auto inboundBits = KJ_ASSERT_NONNULL(valid.inboundMaxWindowBits); |
| 3013 |
KJ_ASSERT(inboundBits == 15); // `client_max_window_bits` can be empty in an offer. |
| 3014 |
auto outboundBits = KJ_ASSERT_NONNULL(valid.outboundMaxWindowBits); |
| 3015 |
KJ_ASSERT(outboundBits == 10); |
| 3016 |
// Valid config successfully constructed. |
| 3017 |
|
| 3018 |
const auto correctStructureButInvalid = "client_no_context_takeover; client_max_window_bits; " |
| 3019 |
"server_max_window_bits=this_should_be_a_number"_kj; |
| 3020 |
parts = _::splitParts(correctStructureButInvalid, ';'); |
| 3021 |
keysMaybeValues = _::toKeysAndVals(parts.asPtr()); |
| 3022 |
|
| 3023 |
maybeUnverified = _::populateUnverifiedConfig(keysMaybeValues); |
| 3024 |
unverified = KJ_ASSERT_NONNULL(maybeUnverified); |
| 3025 |
maybeValid = _::validateCompressionConfig(kj::mv(unverified), false); // Validate as Server. |
| 3026 |
KJ_ASSERT(maybeValid == nullptr); |
| 3027 |
// The config "looks" correct, but the `server_max_window_bits` parameter has an invalid value. |
| 3028 |
|
| 3029 |
const auto invalidRange = "client_max_window_bits; server_max_window_bits=18;"_kj; |
| 3030 |
// `server_max_window_bits` is out of range, decline. |
| 3031 |
parts = _::splitParts(invalidRange, ';'); |
| 3032 |
keysMaybeValues = _::toKeysAndVals(parts.asPtr()); |
| 3033 |
maybeUnverified = _::populateUnverifiedConfig(keysMaybeValues); |
| 3034 |
maybeValid = _::validateCompressionConfig(kj::mv(KJ_REQUIRE_NONNULL(maybeUnverified)), false); |
| 3035 |
KJ_ASSERT(maybeValid == nullptr); |
| 3036 |
|
| 3037 |
const auto invalidRangeTwo = "client_max_window_bits=4"_kj; |
| 3038 |
// `server_max_window_bits` is out of range, decline. |
| 3039 |
parts = _::splitParts(invalidRangeTwo, ';'); |
| 3040 |
keysMaybeValues = _::toKeysAndVals(parts.asPtr()); |
| 3041 |
maybeUnverified = _::populateUnverifiedConfig(keysMaybeValues); |
| 3042 |
maybeValid = _::validateCompressionConfig(kj::mv(KJ_REQUIRE_NONNULL(maybeUnverified)), false); |
| 3043 |
KJ_ASSERT(maybeValid == nullptr); |
| 3044 |
|
| 3045 |
const auto invalidRequest = "server_max_window_bits"_kj; |
| 3046 |
// `sever_max_window_bits` must have a value in a request AND a response. |
| 3047 |
parts = _::splitParts(invalidRequest, ';'); |
| 3048 |
keysMaybeValues = _::toKeysAndVals(parts.asPtr()); |
| 3049 |
maybeUnverified = _::populateUnverifiedConfig(keysMaybeValues); |
| 3050 |
maybeValid = _::validateCompressionConfig(kj::mv(KJ_REQUIRE_NONNULL(maybeUnverified)), false); |
| 3051 |
KJ_ASSERT(maybeValid == nullptr); |
| 3052 |
|
| 3053 |
const auto invalidResponse = "client_max_window_bits"_kj; |
| 3054 |
// `client_max_window_bits` must have a value in a response. |
| 3055 |
parts = _::splitParts(invalidResponse, ';'); |
| 3056 |
keysMaybeValues = _::toKeysAndVals(parts.asPtr()); |
| 3057 |
maybeUnverified = _::populateUnverifiedConfig(keysMaybeValues); |
| 3058 |
maybeValid = _::validateCompressionConfig(kj::mv(KJ_REQUIRE_NONNULL(maybeUnverified)), true); |
| 3059 |
KJ_ASSERT(maybeValid == nullptr); |
| 3060 |
} |
| 3061 |
|
| 3062 |
KJ_TEST("WebSocket Compression String Parsing (findValidExtensionOffers)") { |
| 3063 |
// Test that we can extract only the valid extensions from a string of offers. |
| 3064 |
constexpr auto extensions = "permessage-deflate; " // Valid offer. |
| 3065 |
"client_no_context_takeover; " |
| 3066 |
"client_max_window_bits; " |
| 3067 |
"server_max_window_bits=10, " |
| 3068 |
"permessage-deflate; " // Another valid offer. |
| 3069 |
"client_no_context_takeover; " |
| 3070 |
"client_max_window_bits, " |
| 3071 |
"permessage-invalid; " // Invalid ext name. |
| 3072 |
"client_no_context_takeover, " |
| 3073 |
"permessage-deflate; " // Invalid parmeter. |
| 3074 |
"invalid_parameter; " |
| 3075 |
"client_max_window_bits; " |
| 3076 |
"server_max_window_bits=10, " |
| 3077 |
"permessage-deflate; " // Invalid parmeter value. |
| 3078 |
"server_max_window_bits=should_be_a_number, " |
| 3079 |
"permessage-deflate; " // Unexpected parmeter value. |
| 3080 |
"client_max_window_bits=true, " |
| 3081 |
"permessage-deflate; " // Missing expected parmeter value. |
| 3082 |
"server_max_window_bits, " |
| 3083 |
"permessage-deflate; " // Invalid parameter value (too high). |
| 3084 |
"client_max_window_bits=99, " |
| 3085 |
"permessage-deflate; " // Invalid parameter value (too low). |
| 3086 |
"client_max_window_bits=4, " |
| 3087 |
"permessage-deflate; " // Invalid parameter (repeated). |
| 3088 |
"client_max_window_bits; " |
| 3089 |
"client_max_window_bits, " |
| 3090 |
"permessage-deflate"_kj; // Valid offer (no parameters). |
| 3091 |
|
| 3092 |
auto validOffers = _::findValidExtensionOffers(extensions); |
| 3093 |
KJ_ASSERT(validOffers.size() == 3); |
| 3094 |
KJ_ASSERT(validOffers[0].outboundNoContextTakeover == true); |
| 3095 |
KJ_ASSERT(validOffers[0].inboundNoContextTakeover == false); |
| 3096 |
KJ_ASSERT(validOffers[0].outboundMaxWindowBits == 15); |
| 3097 |
KJ_ASSERT(validOffers[0].inboundMaxWindowBits == 10); |
| 3098 |
|
| 3099 |
KJ_ASSERT(validOffers[1].outboundNoContextTakeover == true); |
| 3100 |
KJ_ASSERT(validOffers[1].inboundNoContextTakeover == false); |
| 3101 |
KJ_ASSERT(validOffers[1].outboundMaxWindowBits == 15); |
| 3102 |
KJ_ASSERT(validOffers[1].inboundMaxWindowBits == nullptr); |
| 3103 |
|
| 3104 |
KJ_ASSERT(validOffers[2].outboundNoContextTakeover == false); |
| 3105 |
KJ_ASSERT(validOffers[2].inboundNoContextTakeover == false); |
| 3106 |
KJ_ASSERT(validOffers[2].outboundMaxWindowBits == nullptr); |
| 3107 |
KJ_ASSERT(validOffers[2].inboundMaxWindowBits == nullptr); |
| 3108 |
} |
| 3109 |
|
| 3110 |
KJ_TEST("WebSocket Compression String Parsing (generateExtensionRequest)") { |
| 3111 |
// Test that we can extract only the valid extensions from a string of offers. |
| 3112 |
constexpr auto extensions = "permessage-deflate; " |
| 3113 |
"client_no_context_takeover; " |
| 3114 |
"server_max_window_bits=10; " |
| 3115 |
"client_max_window_bits, " |
| 3116 |
"permessage-deflate; " |
| 3117 |
"client_no_context_takeover; " |
| 3118 |
"client_max_window_bits, " |
| 3119 |
"permessage-deflate"_kj; |
| 3120 |
constexpr auto EXPECTED = "permessage-deflate; " |
| 3121 |
"client_no_context_takeover; " |
| 3122 |
"client_max_window_bits=15; " |
| 3123 |
"server_max_window_bits=10, " |
| 3124 |
"permessage-deflate; " |
| 3125 |
"client_no_context_takeover; " |
| 3126 |
"client_max_window_bits=15, " |
| 3127 |
"permessage-deflate"_kj; |
| 3128 |
auto validOffers = _::findValidExtensionOffers(extensions); |
| 3129 |
auto extensionRequest = _::generateExtensionRequest(validOffers); |
| 3130 |
KJ_ASSERT(extensionRequest == EXPECTED); |
| 3131 |
} |
| 3132 |
|
| 3133 |
KJ_TEST("WebSocket Compression String Parsing (tryParseExtensionOffers)") { |
| 3134 |
// Test that we can accept a valid offer from string of offers. |
| 3135 |
constexpr auto extensions = "permessage-invalid; " // Invalid ext name. |
| 3136 |
"client_no_context_takeover, " |
| 3137 |
"permessage-deflate; " // Invalid parmeter. |
| 3138 |
"invalid_parameter; " |
| 3139 |
"client_max_window_bits; " |
| 3140 |
"server_max_window_bits=10, " |
| 3141 |
"permessage-deflate; " // Invalid parmeter value. |
| 3142 |
"server_max_window_bits=should_be_a_number, " |
| 3143 |
"permessage-deflate; " // Unexpected parmeter value. |
| 3144 |
"client_max_window_bits=true, " |
| 3145 |
"permessage-deflate; " // Missing expected parmeter value. |
| 3146 |
"server_max_window_bits, " |
| 3147 |
"permessage-deflate; " // Invalid parameter value (too high). |
| 3148 |
"client_max_window_bits=99, " |
| 3149 |
"permessage-deflate; " // Invalid parameter value (too low). |
| 3150 |
"client_max_window_bits=4, " |
| 3151 |
"permessage-deflate; " // Invalid parameter (repeated). |
| 3152 |
"client_max_window_bits; " |
| 3153 |
"client_max_window_bits, " |
| 3154 |
"permessage-deflate; " // Valid offer. |
| 3155 |
"client_no_context_takeover; " |
| 3156 |
"client_max_window_bits; " |
| 3157 |
"server_max_window_bits=10, " |
| 3158 |
"permessage-deflate; " // Another valid offer. |
| 3159 |
"client_no_context_takeover; " |
| 3160 |
"client_max_window_bits, " |
| 3161 |
"permessage-deflate"_kj; // Valid offer (no parameters). |
| 3162 |
|
| 3163 |
auto maybeAccepted = _::tryParseExtensionOffers(extensions); |
| 3164 |
auto accepted = KJ_ASSERT_NONNULL(maybeAccepted); |
| 3165 |
KJ_ASSERT(accepted.outboundNoContextTakeover == false); |
| 3166 |
KJ_ASSERT(accepted.inboundNoContextTakeover == true); |
| 3167 |
KJ_ASSERT(accepted.outboundMaxWindowBits == 10); |
| 3168 |
KJ_ASSERT(accepted.inboundMaxWindowBits == 15); |
| 3169 |
|
| 3170 |
// Try the second valid offer from the big list above. |
| 3171 |
auto offerTwo = "permessage-deflate; client_no_context_takeover; client_max_window_bits"_kj; |
| 3172 |
maybeAccepted = _::tryParseExtensionOffers(offerTwo); |
| 3173 |
accepted = KJ_ASSERT_NONNULL(maybeAccepted); |
| 3174 |
KJ_ASSERT(accepted.outboundNoContextTakeover == false); |
| 3175 |
KJ_ASSERT(accepted.inboundNoContextTakeover == true); |
| 3176 |
KJ_ASSERT(accepted.outboundMaxWindowBits == nullptr); |
| 3177 |
KJ_ASSERT(accepted.inboundMaxWindowBits == 15); |
| 3178 |
|
| 3179 |
auto offerThree = "permessage-deflate"_kj; // The third valid offer. |
| 3180 |
maybeAccepted = _::tryParseExtensionOffers(offerThree); |
| 3181 |
accepted = KJ_ASSERT_NONNULL(maybeAccepted); |
| 3182 |
KJ_ASSERT(accepted.outboundNoContextTakeover == false); |
| 3183 |
KJ_ASSERT(accepted.inboundNoContextTakeover == false); |
| 3184 |
KJ_ASSERT(accepted.outboundMaxWindowBits == nullptr); |
| 3185 |
KJ_ASSERT(accepted.inboundMaxWindowBits == nullptr); |
| 3186 |
|
| 3187 |
auto invalid = "invalid"_kj; // Any of the invalid offers we saw above would return NULL. |
| 3188 |
maybeAccepted = _::tryParseExtensionOffers(invalid); |
| 3189 |
KJ_ASSERT(maybeAccepted == nullptr); |
| 3190 |
} |
| 3191 |
|
| 3192 |
KJ_TEST("WebSocket Compression String Parsing (tryParseAllExtensionOffers)") { |
| 3193 |
// We want to test the following: |
| 3194 |
// 1. We reject all if we don't find an offer we can accept. |
| 3195 |
// 2. We accept one after iterating over offers that we have to reject. |
| 3196 |
// 3. We accept an offer with a `server_max_window_bits` parameter if the manual config allows |
| 3197 |
// it, and choose the smaller "number of bits" (from clients request). |
| 3198 |
// 4. We accept an offer with a `server_no_context_takeover` parameter if the manual config |
| 3199 |
// allows it, and choose the smaller "number of bits" (from manual config) from |
| 3200 |
// `server_max_window_bits`. |
| 3201 |
constexpr auto serverOnly = "permessage-deflate; " |
| 3202 |
"client_no_context_takeover; " |
| 3203 |
"server_max_window_bits = 14; " |
| 3204 |
"server_no_context_takeover, " |
| 3205 |
"permessage-deflate; " |
| 3206 |
"client_no_context_takeover; " |
| 3207 |
"server_no_context_takeover, " |
| 3208 |
"permessage-deflate; " |
| 3209 |
"client_no_context_takeover; " |
| 3210 |
"server_max_window_bits = 14"_kj; |
| 3211 |
|
| 3212 |
constexpr auto acceptLast = "permessage-deflate; " |
| 3213 |
"client_no_context_takeover; " |
| 3214 |
"server_max_window_bits = 14; " |
| 3215 |
"server_no_context_takeover, " |
| 3216 |
"permessage-deflate; " |
| 3217 |
"client_no_context_takeover; " |
| 3218 |
"server_no_context_takeover, " |
| 3219 |
"permessage-deflate; " |
| 3220 |
"client_no_context_takeover; " |
| 3221 |
"server_max_window_bits = 14, " |
| 3222 |
"permessage-deflate; " // accept this |
| 3223 |
"client_no_context_takeover"_kj; |
| 3224 |
|
| 3225 |
const auto defaultConfig = CompressionParameters(); |
| 3226 |
// Our default config is equivalent to `permessage-deflate` with no parameters. |
| 3227 |
|
| 3228 |
auto maybeAccepted = _::tryParseAllExtensionOffers(serverOnly, defaultConfig); |
| 3229 |
KJ_ASSERT(maybeAccepted == nullptr); |
| 3230 |
// Asserts that we rejected all the offers with `server_x` parameters. |
| 3231 |
|
| 3232 |
maybeAccepted = _::tryParseAllExtensionOffers(acceptLast, defaultConfig); |
| 3233 |
auto accepted = KJ_ASSERT_NONNULL(maybeAccepted); |
| 3234 |
KJ_ASSERT(accepted.outboundNoContextTakeover == false); |
| 3235 |
KJ_ASSERT(accepted.inboundNoContextTakeover == false); |
| 3236 |
KJ_ASSERT(accepted.outboundMaxWindowBits == nullptr); |
| 3237 |
KJ_ASSERT(accepted.inboundMaxWindowBits == nullptr); |
| 3238 |
// Asserts that we accepted the only offer that did not have a `server_x` parameter. |
| 3239 |
|
| 3240 |
const auto allowServerBits = CompressionParameters { |
| 3241 |
false, |
| 3242 |
false, |
| 3243 |
15, // server_max_window_bits = 15 |
| 3244 |
nullptr |
| 3245 |
}; |
| 3246 |
maybeAccepted = _::tryParseAllExtensionOffers(serverOnly, allowServerBits); |
| 3247 |
accepted = KJ_ASSERT_NONNULL(maybeAccepted); |
| 3248 |
KJ_ASSERT(accepted.outboundNoContextTakeover == false); |
| 3249 |
KJ_ASSERT(accepted.inboundNoContextTakeover == false); |
| 3250 |
KJ_ASSERT(accepted.outboundMaxWindowBits == 14); // Note that we chose the lower of (14, 15). |
| 3251 |
KJ_ASSERT(accepted.inboundMaxWindowBits == nullptr); |
| 3252 |
// Asserts that we accepted an offer that allowed for `server_max_window_bits` AND we chose the |
| 3253 |
// lower number of bits (in this case, the clients offer of 14). |
| 3254 |
|
| 3255 |
const auto allowServerTakeoverAndBits = CompressionParameters { |
| 3256 |
true, // server_no_context_takeover = true |
| 3257 |
false, |
| 3258 |
13, // server_max_window_bits = 13 |
| 3259 |
nullptr |
| 3260 |
}; |
| 3261 |
|
| 3262 |
maybeAccepted = _::tryParseAllExtensionOffers(serverOnly, allowServerTakeoverAndBits); |
| 3263 |
accepted = KJ_ASSERT_NONNULL(maybeAccepted); |
| 3264 |
KJ_ASSERT(accepted.outboundNoContextTakeover == true); |
| 3265 |
KJ_ASSERT(accepted.inboundNoContextTakeover == false); |
| 3266 |
KJ_ASSERT(accepted.outboundMaxWindowBits == 13); // Note that we chose the lower of (14, 15). |
| 3267 |
KJ_ASSERT(accepted.inboundMaxWindowBits == nullptr); |
| 3268 |
// Asserts that we accepted an offer that allowed for `server_no_context_takeover` AND we chose |
| 3269 |
// the lower number of bits (in this case, the manual config's choice of 13). |
| 3270 |
} |
| 3271 |
|
| 3272 |
KJ_TEST("WebSocket Compression String Parsing (generateExtensionResponse)") { |
| 3273 |
// Test that we can extract only the valid extensions from a string of offers. |
| 3274 |
constexpr auto extensions = "permessage-deflate; " |
| 3275 |
"client_no_context_takeover; " |
| 3276 |
"server_max_window_bits=10; " |
| 3277 |
"client_max_window_bits, " |
| 3278 |
"permessage-deflate; " |
| 3279 |
"client_no_context_takeover; " |
| 3280 |
"client_max_window_bits, " |
| 3281 |
"permessage-deflate"_kj; |
| 3282 |
constexpr auto EXPECTED = "permessage-deflate; " |
| 3283 |
"client_no_context_takeover; " |
| 3284 |
"client_max_window_bits=15; " |
| 3285 |
"server_max_window_bits=10"_kj; |
| 3286 |
auto accepted = _::tryParseExtensionOffers(extensions); |
| 3287 |
auto extensionResponse = _::generateExtensionResponse(KJ_ASSERT_NONNULL(accepted)); |
| 3288 |
KJ_ASSERT(extensionResponse == EXPECTED); |
| 3289 |
} |
| 3290 |
|
| 3291 |
KJ_TEST("WebSocket Compression String Parsing (tryParseExtensionAgreement)") { |
| 3292 |
constexpr auto didNotOffer = "Server failed WebSocket handshake: " |
| 3293 |
"added Sec-WebSocket-Extensions when client did not offer any."_kj; |
| 3294 |
constexpr auto tooMany = "Server failed WebSocket handshake: " |
| 3295 |
"expected exactly one extension (permessage-deflate) but received more than one."_kj; |
| 3296 |
constexpr auto badExt = "Server failed WebSocket handshake: " |
| 3297 |
"response included a Sec-WebSocket-Extensions value that was not permessage-deflate."_kj; |
| 3298 |
constexpr auto badVal = "Server failed WebSocket handshake: " |
| 3299 |
"the Sec-WebSocket-Extensions header in the Response included an invalid value."_kj; |
| 3300 |
|
| 3301 |
constexpr auto tooManyExtensions = "permessage-deflate; client_no_context_takeover; " |
| 3302 |
"client_max_window_bits; server_max_window_bits=10, " |
| 3303 |
"permessage-deflate; client_no_context_takeover; client_max_window_bits;"_kj; |
| 3304 |
|
| 3305 |
auto maybeAccepted = _::tryParseExtensionAgreement(nullptr, tooManyExtensions); |
| 3306 |
KJ_ASSERT( |
| 3307 |
KJ_ASSERT_NONNULL(maybeAccepted.tryGet<kj::Exception>()).getDescription() == didNotOffer); |
| 3308 |
|
| 3309 |
Maybe<CompressionParameters> defaultConfig = CompressionParameters{}; |
| 3310 |
maybeAccepted = _::tryParseExtensionAgreement(defaultConfig, tooManyExtensions); |
| 3311 |
KJ_ASSERT(KJ_ASSERT_NONNULL(maybeAccepted.tryGet<kj::Exception>()).getDescription() == tooMany); |
| 3312 |
|
| 3313 |
constexpr auto invalidExt = "permessage-invalid; " |
| 3314 |
"client_no_context_takeover; " |
| 3315 |
"client_max_window_bits; " |
| 3316 |
"server_max_window_bits=10;"; |
| 3317 |
maybeAccepted = _::tryParseExtensionAgreement(defaultConfig, invalidExt); |
| 3318 |
KJ_ASSERT(KJ_ASSERT_NONNULL(maybeAccepted.tryGet<kj::Exception>()).getDescription() == badExt); |
| 3319 |
|
| 3320 |
constexpr auto invalidVal = "permessage-deflate; " |
| 3321 |
"client_no_context_takeover; " |
| 3322 |
"client_max_window_bits; " |
| 3323 |
"server_max_window_bits=100;"; |
| 3324 |
maybeAccepted = _::tryParseExtensionAgreement(defaultConfig, invalidVal); |
| 3325 |
KJ_ASSERT(KJ_ASSERT_NONNULL(maybeAccepted.tryGet<kj::Exception>()).getDescription() == badVal); |
| 3326 |
|
| 3327 |
constexpr auto missingVal = "permessage-deflate; " |
| 3328 |
"client_no_context_takeover; " |
| 3329 |
"client_max_window_bits; " // This must have a value in a Response! |
| 3330 |
"server_max_window_bits=10;"; |
| 3331 |
maybeAccepted = _::tryParseExtensionAgreement(defaultConfig, missingVal); |
| 3332 |
KJ_ASSERT(KJ_ASSERT_NONNULL(maybeAccepted.tryGet<kj::Exception>()).getDescription() == badVal); |
| 3333 |
|
| 3334 |
constexpr auto valid = "permessage-deflate; client_no_context_takeover; " |
| 3335 |
"client_max_window_bits=15; server_max_window_bits=10"_kj; |
| 3336 |
maybeAccepted = _::tryParseExtensionAgreement(defaultConfig, valid); |
| 3337 |
auto config = KJ_ASSERT_NONNULL(maybeAccepted.tryGet<CompressionParameters>()); |
| 3338 |
KJ_ASSERT(config.outboundNoContextTakeover == true); |
| 3339 |
KJ_ASSERT(config.inboundNoContextTakeover == false); |
| 3340 |
KJ_ASSERT(config.outboundMaxWindowBits == 15); |
| 3341 |
KJ_ASSERT(config.inboundMaxWindowBits == 10); |
| 3342 |
|
| 3343 |
auto client = CompressionParameters{ true, false, 15, 10 }; |
| 3344 |
// If the server ignores our `client_no_context_takeover` parameter, we (the client) still use it. |
| 3345 |
constexpr auto serverIgnores = "permessage-deflate; client_max_window_bits=15; " |
| 3346 |
"server_max_window_bits=10"_kj; |
| 3347 |
maybeAccepted = _::tryParseExtensionAgreement(client, serverIgnores); |
| 3348 |
config = KJ_ASSERT_NONNULL(maybeAccepted.tryGet<CompressionParameters>()); |
| 3349 |
KJ_ASSERT(config.outboundNoContextTakeover == true); // Note that this is missing in the response. |
| 3350 |
KJ_ASSERT(config.inboundNoContextTakeover == false); |
| 3351 |
KJ_ASSERT(config.outboundMaxWindowBits == 15); |
| 3352 |
KJ_ASSERT(config.inboundMaxWindowBits == 10); |
| 3353 |
} |
| 3354 |
|
| 3355 |
#if KJ_HAS_ZLIB |
| 3356 |
KJ_TEST("HttpClient WebSocket Empty Message Compression") { |
| 3357 |
// We'll try to send and receive "Hello", then "", followed by "Hello" again. |
| 3358 |
KJ_HTTP_TEST_SETUP_IO; |
| 3359 |
auto pipe = KJ_HTTP_TEST_CREATE_2PIPE; |
| 3360 |
|
| 3361 |
auto request = kj::str("GET /websocket", WEBSOCKET_COMPRESSION_HANDSHAKE); |
| 3362 |
|
| 3363 |
auto serverTask = expectRead(*pipe.ends[1], request) |
| 3364 |
.then([&]() { return writeA(*pipe.ends[1], asBytes(WEBSOCKET_COMPRESSION_RESPONSE_HANDSHAKE)); }) |
| 3365 |
.then([&]() { return writeA(*pipe.ends[1], WEBSOCKET_FIRST_COMPRESSED_MESSAGE); }) |
| 3366 |
.then([&]() { return expectRead(*pipe.ends[1], WEBSOCKET_SEND_COMPRESSED_MESSAGE); }) |
| 3367 |
.then([&]() { return writeA(*pipe.ends[1], WEBSOCKET_EMPTY_COMPRESSED_MESSAGE); }) |
| 3368 |
.then([&]() { return expectRead(*pipe.ends[1], WEBSOCKET_EMPTY_SEND_COMPRESSED_MESSAGE); }) |
| 3369 |
.then([&]() { return writeA(*pipe.ends[1], WEBSOCKET_FIRST_COMPRESSED_MESSAGE); }) |
| 3370 |
.then([&]() { return expectRead(*pipe.ends[1], WEBSOCKET_SEND_COMPRESSED_MESSAGE_REUSE_CTX); }) |
| 3371 |
.then([&]() { return expectRead(*pipe.ends[1], WEBSOCKET_SEND_CLOSE); }) |
| 3372 |
.then([&]() { return writeA(*pipe.ends[1], WEBSOCKET_REPLY_CLOSE); }) |
| 3373 |
.eagerlyEvaluate([](kj::Exception&& e) { KJ_LOG(ERROR, e); }); |
| 3374 |
|
| 3375 |
HttpHeaderTable::Builder tableBuilder; |
| 3376 |
HttpHeaderId extHeader = tableBuilder.add("Sec-WebSocket-Extensions"); |
| 3377 |
auto headerTable = tableBuilder.build(); |
| 3378 |
|
| 3379 |
FakeEntropySource entropySource; |
| 3380 |
HttpClientSettings clientSettings; |
| 3381 |
clientSettings.entropySource = entropySource; |
| 3382 |
clientSettings.webSocketCompressionMode = HttpClientSettings::MANUAL_COMPRESSION; |
| 3383 |
|
| 3384 |
auto client = newHttpClient(*headerTable, *pipe.ends[0], clientSettings); |
| 3385 |
|
| 3386 |
constexpr auto extensions = "permessage-deflate; server_no_context_takeover"_kj; |
| 3387 |
testWebSocketEmptyMessageCompression(waitScope, *headerTable, extHeader, extensions, *client); |
| 3388 |
|
| 3389 |
serverTask.wait(waitScope); |
| 3390 |
} |
| 3391 |
#endif // KJ_HAS_ZLIB |
| 3392 |
|
| 3393 |
#if KJ_HAS_ZLIB |
| 3394 |
KJ_TEST("HttpClient WebSocket Default Compression") { |
| 3395 |
// We'll try to send and receive "Hello" twice. The second time we receive "Hello", the compressed |
| 3396 |
// message will be smaller as a result of the client reusing the lookback window. |
| 3397 |
KJ_HTTP_TEST_SETUP_IO; |
| 3398 |
auto pipe = KJ_HTTP_TEST_CREATE_2PIPE; |
| 3399 |
|
| 3400 |
auto request = kj::str("GET /websocket", WEBSOCKET_COMPRESSION_HANDSHAKE); |
| 3401 |
|
| 3402 |
auto serverTask = expectRead(*pipe.ends[1], request) |
| 3403 |
.then([&]() { return writeA(*pipe.ends[1], asBytes(WEBSOCKET_COMPRESSION_RESPONSE_HANDSHAKE)); }) |
| 3404 |
.then([&]() { return writeA(*pipe.ends[1], WEBSOCKET_FIRST_COMPRESSED_MESSAGE); }) |
| 3405 |
.then([&]() { return expectRead(*pipe.ends[1], WEBSOCKET_SEND_COMPRESSED_MESSAGE); }) |
| 3406 |
.then([&]() { return writeA(*pipe.ends[1], WEBSOCKET_FIRST_COMPRESSED_MESSAGE); }) |
| 3407 |
.then([&]() { return expectRead(*pipe.ends[1], WEBSOCKET_SEND_COMPRESSED_MESSAGE_REUSE_CTX); }) |
| 3408 |
.then([&]() { return expectRead(*pipe.ends[1], WEBSOCKET_SEND_CLOSE); }) |
| 3409 |
.then([&]() { return writeA(*pipe.ends[1], WEBSOCKET_REPLY_CLOSE); }) |
| 3410 |
.eagerlyEvaluate([](kj::Exception&& e) { KJ_LOG(ERROR, e); }); |
| 3411 |
|
| 3412 |
HttpHeaderTable::Builder tableBuilder; |
| 3413 |
HttpHeaderId extHeader = tableBuilder.add("Sec-WebSocket-Extensions"); |
| 3414 |
auto headerTable = tableBuilder.build(); |
| 3415 |
|
| 3416 |
FakeEntropySource entropySource; |
| 3417 |
HttpClientSettings clientSettings; |
| 3418 |
clientSettings.entropySource = entropySource; |
| 3419 |
clientSettings.webSocketCompressionMode = HttpClientSettings::MANUAL_COMPRESSION; |
| 3420 |
|
| 3421 |
auto client = newHttpClient(*headerTable, *pipe.ends[0], clientSettings); |
| 3422 |
|
| 3423 |
constexpr auto extensions = "permessage-deflate; server_no_context_takeover"_kj; |
| 3424 |
testWebSocketTwoMessageCompression(waitScope, *headerTable, extHeader, extensions, *client); |
| 3425 |
|
| 3426 |
serverTask.wait(waitScope); |
| 3427 |
} |
| 3428 |
#endif // KJ_HAS_ZLIB |
| 3429 |
|
| 3430 |
#if KJ_HAS_ZLIB |
| 3431 |
KJ_TEST("HttpClient WebSocket Extract Extensions") { |
| 3432 |
KJ_HTTP_TEST_SETUP_IO; |
| 3433 |
auto pipe = KJ_HTTP_TEST_CREATE_2PIPE; |
| 3434 |
|
| 3435 |
auto request = kj::str("GET /websocket", WEBSOCKET_COMPRESSION_HANDSHAKE); |
| 3436 |
|
| 3437 |
auto serverTask = expectRead(*pipe.ends[1], request) |
| 3438 |
.then([&]() { return writeA(*pipe.ends[1], asBytes(WEBSOCKET_COMPRESSION_RESPONSE_HANDSHAKE)); }) |
| 3439 |
.then([&]() { return expectRead(*pipe.ends[1], WEBSOCKET_SEND_CLOSE); }) |
| 3440 |
.then([&]() { return writeA(*pipe.ends[1], WEBSOCKET_REPLY_CLOSE); }) |
| 3441 |
.eagerlyEvaluate([](kj::Exception&& e) { KJ_LOG(ERROR, e); }); |
| 3442 |
|
| 3443 |
HttpHeaderTable::Builder tableBuilder; |
| 3444 |
HttpHeaderId extHeader = tableBuilder.add("Sec-WebSocket-Extensions"); |
| 3445 |
auto headerTable = tableBuilder.build(); |
| 3446 |
|
| 3447 |
FakeEntropySource entropySource; |
| 3448 |
HttpClientSettings clientSettings; |
| 3449 |
clientSettings.entropySource = entropySource; |
| 3450 |
clientSettings.webSocketCompressionMode = HttpClientSettings::MANUAL_COMPRESSION; |
| 3451 |
|
| 3452 |
auto client = newHttpClient(*headerTable, *pipe.ends[0], clientSettings); |
| 3453 |
|
| 3454 |
constexpr auto extensions = "permessage-deflate; server_no_context_takeover"_kj; |
| 3455 |
testWebSocketOptimizePumpProxy(waitScope, *headerTable, extHeader, extensions, *client); |
| 3456 |
|
| 3457 |
serverTask.wait(waitScope); |
| 3458 |
} |
| 3459 |
#endif // KJ_HAS_ZLIB |
| 3460 |
|
| 3461 |
#if KJ_HAS_ZLIB |
| 3462 |
KJ_TEST("HttpClient WebSocket Compression (Client Discards Compression Context)") { |
| 3463 |
// We'll try to send and receive "Hello" twice. The second time we receive "Hello", the compressed |
| 3464 |
// message will be the same size as the first time, since the client discards the lookback window. |
| 3465 |
KJ_HTTP_TEST_SETUP_IO; |
| 3466 |
auto pipe = KJ_HTTP_TEST_CREATE_2PIPE; |
| 3467 |
|
| 3468 |
auto request = kj::str("GET /websocket", WEBSOCKET_COMPRESSION_CLIENT_DISCARDS_CTX_HANDSHAKE); |
| 3469 |
|
| 3470 |
auto serverTask = expectRead(*pipe.ends[1], request) |
| 3471 |
.then([&]() { return writeA(*pipe.ends[1], |
| 3472 |
asBytes(WEBSOCKET_COMPRESSION_CLIENT_DISCARDS_CTX_RESPONSE_HANDSHAKE)); }) |
| 3473 |
.then([&]() { return writeA(*pipe.ends[1], WEBSOCKET_FIRST_COMPRESSED_MESSAGE); }) |
| 3474 |
.then([&]() { return expectRead(*pipe.ends[1], WEBSOCKET_SEND_COMPRESSED_MESSAGE); }) |
| 3475 |
.then([&]() { return writeA(*pipe.ends[1], WEBSOCKET_FIRST_COMPRESSED_MESSAGE); }) |
| 3476 |
.then([&]() { return expectRead(*pipe.ends[1], WEBSOCKET_SEND_COMPRESSED_MESSAGE); }) |
| 3477 |
.then([&]() { return expectRead(*pipe.ends[1], WEBSOCKET_SEND_CLOSE); }) |
| 3478 |
.then([&]() { return writeA(*pipe.ends[1], WEBSOCKET_REPLY_CLOSE); }) |
| 3479 |
.eagerlyEvaluate([](kj::Exception&& e) { KJ_LOG(ERROR, e); }); |
| 3480 |
|
| 3481 |
HttpHeaderTable::Builder tableBuilder; |
| 3482 |
HttpHeaderId extHeader = tableBuilder.add("Sec-WebSocket-Extensions"); |
| 3483 |
auto headerTable = tableBuilder.build(); |
| 3484 |
|
| 3485 |
FakeEntropySource entropySource; |
| 3486 |
HttpClientSettings clientSettings; |
| 3487 |
clientSettings.entropySource = entropySource; |
| 3488 |
clientSettings.webSocketCompressionMode = HttpClientSettings::MANUAL_COMPRESSION; |
| 3489 |
|
| 3490 |
auto client = newHttpClient(*headerTable, *pipe.ends[0], clientSettings); |
| 3491 |
|
| 3492 |
constexpr auto extensions = |
| 3493 |
"permessage-deflate; client_no_context_takeover; server_no_context_takeover"_kj; |
| 3494 |
testWebSocketTwoMessageCompression(waitScope, *headerTable, extHeader, extensions, *client); |
| 3495 |
|
| 3496 |
serverTask.wait(waitScope); |
| 3497 |
} |
| 3498 |
#endif // KJ_HAS_ZLIB |
| 3499 |
|
| 3500 |
#if KJ_HAS_ZLIB |
| 3501 |
KJ_TEST("HttpClient WebSocket Compression (Different DEFLATE blocks)") { |
| 3502 |
// In this test, we'll try to use the following DEFLATE blocks: |
| 3503 |
// - Two DEFLATE blocks in 1 message. |
| 3504 |
// - A block with no compression. |
| 3505 |
// - A block with BFINAL set to 1. |
| 3506 |
// Then, we'll try to send a normal compressed message following the BFINAL message to ensure we |
| 3507 |
// can still process messages after receiving BFINAL. |
| 3508 |
KJ_HTTP_TEST_SETUP_IO; |
| 3509 |
auto pipe = KJ_HTTP_TEST_CREATE_2PIPE; |
| 3510 |
|
| 3511 |
auto request = kj::str("GET /websocket", WEBSOCKET_COMPRESSION_CLIENT_DISCARDS_CTX_HANDSHAKE); |
| 3512 |
|
| 3513 |
auto serverTask = expectRead(*pipe.ends[1], request) |
| 3514 |
.then([&]() { return writeA(*pipe.ends[1], |
| 3515 |
asBytes(WEBSOCKET_COMPRESSION_CLIENT_DISCARDS_CTX_RESPONSE_HANDSHAKE)); }) |
| 3516 |
.then([&]() { return writeA(*pipe.ends[1], WEBSOCKET_TWO_DEFLATE_BLOCKS_MESSAGE); }) |
| 3517 |
.then([&]() { return writeA(*pipe.ends[1], WEBSOCKET_DEFLATE_NO_COMPRESSION_MESSAGE); }) |
| 3518 |
.then([&]() { return writeA(*pipe.ends[1], WEBSOCKET_BFINAL_SET_MESSAGE); }) |
| 3519 |
.then([&]() { return writeA(*pipe.ends[1], WEBSOCKET_SEND_COMPRESSED_MESSAGE); }) |
| 3520 |
.then([&]() { return expectRead(*pipe.ends[1], WEBSOCKET_SEND_CLOSE); }) |
| 3521 |
.then([&]() { return writeA(*pipe.ends[1], WEBSOCKET_REPLY_CLOSE); }) |
| 3522 |
.eagerlyEvaluate([](kj::Exception&& e) { KJ_LOG(ERROR, e); }); |
| 3523 |
|
| 3524 |
HttpHeaderTable::Builder tableBuilder; |
| 3525 |
HttpHeaderId extHeader = tableBuilder.add("Sec-WebSocket-Extensions"); |
| 3526 |
auto headerTable = tableBuilder.build(); |
| 3527 |
|
| 3528 |
FakeEntropySource entropySource; |
| 3529 |
HttpClientSettings clientSettings; |
| 3530 |
clientSettings.entropySource = entropySource; |
| 3531 |
clientSettings.webSocketCompressionMode = HttpClientSettings::MANUAL_COMPRESSION; |
| 3532 |
|
| 3533 |
auto client = newHttpClient(*headerTable, *pipe.ends[0], clientSettings); |
| 3534 |
|
| 3535 |
constexpr auto extensions = |
| 3536 |
"permessage-deflate; client_no_context_takeover; server_no_context_takeover"_kj; |
| 3537 |
testWebSocketFourMessageCompression(waitScope, *headerTable, extHeader, extensions, *client); |
| 3538 |
|
| 3539 |
serverTask.wait(waitScope); |
| 3540 |
} |
| 3541 |
#endif // KJ_HAS_ZLIB |
| 3542 |
|
| 3543 |
KJ_TEST("HttpClient WebSocket error") { |
| 3544 |
KJ_HTTP_TEST_SETUP_IO; |
| 3545 |
auto pipe = KJ_HTTP_TEST_CREATE_2PIPE; |
| 3546 |
|
| 3547 |
auto request = kj::str("GET /websocket", WEBSOCKET_REQUEST_HANDSHAKE); |
| 3548 |
|
| 3549 |
auto serverTask = expectRead(*pipe.ends[1], request) |
| 3550 |
.then([&]() { return writeA(*pipe.ends[1], asBytes(WEBSOCKET_RESPONSE_HANDSHAKE_ERROR)); }) |
| 3551 |
.then([&]() { return expectRead(*pipe.ends[1], request); }) |
| 3552 |
.then([&]() { return writeA(*pipe.ends[1], asBytes(WEBSOCKET_RESPONSE_HANDSHAKE_ERROR)); }) |
| 3553 |
.eagerlyEvaluate([](kj::Exception&& e) { KJ_LOG(ERROR, e); }); |
| 3554 |
|
| 3555 |
HttpHeaderTable::Builder tableBuilder; |
| 3556 |
HttpHeaderId hMyHeader = tableBuilder.add("My-Header"); |
| 3557 |
auto headerTable = tableBuilder.build(); |
| 3558 |
|
| 3559 |
FakeEntropySource entropySource; |
| 3560 |
HttpClientSettings clientSettings; |
| 3561 |
clientSettings.entropySource = entropySource; |
| 3562 |
|
| 3563 |
auto client = newHttpClient(*headerTable, *pipe.ends[0], clientSettings); |
| 3564 |
|
| 3565 |
kj::HttpHeaders headers(*headerTable); |
| 3566 |
headers.set(hMyHeader, "foo"); |
| 3567 |
|
| 3568 |
{ |
| 3569 |
auto response = client->openWebSocket("/websocket", headers).wait(waitScope); |
| 3570 |
|
| 3571 |
KJ_EXPECT(response.statusCode == 404); |
| 3572 |
KJ_EXPECT(response.statusText == "Not Found", response.statusText); |
| 3573 |
KJ_EXPECT(KJ_ASSERT_NONNULL(response.headers->get(hMyHeader)) == "respond-foo"); |
| 3574 |
KJ_ASSERT(response.webSocketOrBody.is<kj::Own<AsyncInputStream>>()); |
| 3575 |
} |
| 3576 |
|
| 3577 |
{ |
| 3578 |
auto response = client->openWebSocket("/websocket", headers).wait(waitScope); |
| 3579 |
|
| 3580 |
KJ_EXPECT(response.statusCode == 404); |
| 3581 |
KJ_EXPECT(response.statusText == "Not Found", response.statusText); |
| 3582 |
KJ_EXPECT(KJ_ASSERT_NONNULL(response.headers->get(hMyHeader)) == "respond-foo"); |
| 3583 |
KJ_ASSERT(response.webSocketOrBody.is<kj::Own<AsyncInputStream>>()); |
| 3584 |
} |
| 3585 |
|
| 3586 |
serverTask.wait(waitScope); |
| 3587 |
} |
| 3588 |
|
| 3589 |
KJ_TEST("HttpServer WebSocket handshake") { |
| 3590 |
KJ_HTTP_TEST_SETUP_IO; |
| 3591 |
kj::TimerImpl timer(kj::origin<kj::TimePoint>()); |
| 3592 |
auto pipe = KJ_HTTP_TEST_CREATE_2PIPE; |
| 3593 |
|
| 3594 |
HttpHeaderTable::Builder tableBuilder; |
| 3595 |
HttpHeaderId hMyHeader = tableBuilder.add("My-Header"); |
| 3596 |
auto headerTable = tableBuilder.build(); |
| 3597 |
TestWebSocketService service(*headerTable, hMyHeader); |
| 3598 |
HttpServer server(timer, *headerTable, service); |
| 3599 |
|
| 3600 |
auto listenTask = server.listenHttp(kj::mv(pipe.ends[0])); |
| 3601 |
|
| 3602 |
auto request = kj::str("GET /websocket", WEBSOCKET_REQUEST_HANDSHAKE); |
| 3603 |
writeA(*pipe.ends[1], request.asBytes()).wait(waitScope); |
| 3604 |
expectRead(*pipe.ends[1], WEBSOCKET_RESPONSE_HANDSHAKE).wait(waitScope); |
| 3605 |
|
| 3606 |
expectRead(*pipe.ends[1], WEBSOCKET_FIRST_MESSAGE_INLINE).wait(waitScope); |
| 3607 |
writeA(*pipe.ends[1], WEBSOCKET_SEND_MESSAGE).wait(waitScope); |
| 3608 |
expectRead(*pipe.ends[1], WEBSOCKET_REPLY_MESSAGE).wait(waitScope); |
| 3609 |
writeA(*pipe.ends[1], WEBSOCKET_SEND_CLOSE).wait(waitScope); |
| 3610 |
expectRead(*pipe.ends[1], WEBSOCKET_REPLY_CLOSE).wait(waitScope); |
| 3611 |
|
| 3612 |
listenTask.wait(waitScope); |
| 3613 |
} |
| 3614 |
|
| 3615 |
KJ_TEST("HttpServer WebSocket handshake error") { |
| 3616 |
KJ_HTTP_TEST_SETUP_IO; |
| 3617 |
kj::TimerImpl timer(kj::origin<kj::TimePoint>()); |
| 3618 |
auto pipe = KJ_HTTP_TEST_CREATE_2PIPE; |
| 3619 |
|
| 3620 |
HttpHeaderTable::Builder tableBuilder; |
| 3621 |
HttpHeaderId hMyHeader = tableBuilder.add("My-Header"); |
| 3622 |
auto headerTable = tableBuilder.build(); |
| 3623 |
TestWebSocketService service(*headerTable, hMyHeader); |
| 3624 |
HttpServer server(timer, *headerTable, service); |
| 3625 |
|
| 3626 |
auto listenTask = server.listenHttp(kj::mv(pipe.ends[0])); |
| 3627 |
|
| 3628 |
auto request = kj::str("GET /return-error", WEBSOCKET_REQUEST_HANDSHAKE); |
| 3629 |
writeA(*pipe.ends[1], request.asBytes()).wait(waitScope); |
| 3630 |
expectRead(*pipe.ends[1], WEBSOCKET_RESPONSE_HANDSHAKE_ERROR).wait(waitScope); |
| 3631 |
|
| 3632 |
// Can send more requests! |
| 3633 |
writeA(*pipe.ends[1], request.asBytes()).wait(waitScope); |
| 3634 |
expectRead(*pipe.ends[1], WEBSOCKET_RESPONSE_HANDSHAKE_ERROR).wait(waitScope); |
| 3635 |
|
| 3636 |
pipe.ends[1]->shutdownWrite(); |
| 3637 |
|
| 3638 |
listenTask.wait(waitScope); |
| 3639 |
} |
| 3640 |
|
| 3641 |
void testBadWebSocketHandshake( |
| 3642 |
WaitScope& waitScope, Timer& timer, StringPtr request, StringPtr response, TwoWayPipe pipe) { |
| 3643 |
// Write an invalid WebSocket GET request, and expect a particular error response. |
| 3644 |
|
| 3645 |
HttpHeaderTable::Builder tableBuilder; |
| 3646 |
HttpHeaderId hMyHeader = tableBuilder.add("My-Header"); |
| 3647 |
auto headerTable = tableBuilder.build(); |
| 3648 |
TestWebSocketService service(*headerTable, hMyHeader); |
| 3649 |
|
| 3650 |
class ErrorHandler final: public HttpServerErrorHandler { |
| 3651 |
Promise<void> handleApplicationError( |
| 3652 |
Exception exception, Maybe<HttpService::Response&> response) override { |
| 3653 |
// When I first wrote this, I expected this function to be called, because |
| 3654 |
// `TestWebSocketService::request()` definitely throws. However, the exception it throws comes |
| 3655 |
// from `HttpService::Response::acceptWebSocket()`, which stores the fact which it threw a |
| 3656 |
// WebSocket error. This prevents the HttpServer's listen loop from propagating the exception |
| 3657 |
// to our HttpServerErrorHandler (i.e., this function), because it assumes the exception is |
| 3658 |
// related to the WebSocket error response. See `HttpServer::Connection::startLoop()` for |
| 3659 |
// details. |
| 3660 |
bool responseWasSent = response == nullptr; |
| 3661 |
KJ_FAIL_EXPECT("Unexpected application error", responseWasSent, exception); |
| 3662 |
return READY_NOW; |
| 3663 |
} |
| 3664 |
}; |
| 3665 |
|
| 3666 |
ErrorHandler errorHandler; |
| 3667 |
|
| 3668 |
HttpServerSettings serverSettings; |
| 3669 |
serverSettings.errorHandler = errorHandler; |
| 3670 |
|
| 3671 |
HttpServer server(timer, *headerTable, service, serverSettings); |
| 3672 |
|
| 3673 |
auto listenTask = server.listenHttp(kj::mv(pipe.ends[0])); |
| 3674 |
|
| 3675 |
pipe.ends[1]->write(request.begin(), request.size()).wait(waitScope); |
| 3676 |
pipe.ends[1]->shutdownWrite(); |
| 3677 |
|
| 3678 |
expectRead(*pipe.ends[1], response).wait(waitScope); |
| 3679 |
|
| 3680 |
listenTask.wait(waitScope); |
| 3681 |
} |
| 3682 |
|
| 3683 |
KJ_TEST("HttpServer WebSocket handshake with unsupported Sec-WebSocket-Version") { |
| 3684 |
static constexpr auto REQUEST = |
| 3685 |
"GET /websocket HTTP/1.1\r\n" |
| 3686 |
"Connection: Upgrade\r\n" |
| 3687 |
"Upgrade: websocket\r\n" |
| 3688 |
"Sec-WebSocket-Key: DCI4TgwiOE4MIjhODCI4Tg==\r\n" |
| 3689 |
"Sec-WebSocket-Version: 1\r\n" |
| 3690 |
"My-Header: foo\r\n" |
| 3691 |
"\r\n"_kj; |
| 3692 |
|
| 3693 |
static constexpr auto RESPONSE = |
| 3694 |
"HTTP/1.1 400 Bad Request\r\n" |
| 3695 |
"Connection: close\r\n" |
| 3696 |
"Content-Length: 56\r\n" |
| 3697 |
"Content-Type: text/plain\r\n" |
| 3698 |
"\r\n" |
| 3699 |
"ERROR: The requested WebSocket version is not supported."_kj; |
| 3700 |
|
| 3701 |
KJ_HTTP_TEST_SETUP_IO; |
| 3702 |
kj::TimerImpl timer(kj::origin<kj::TimePoint>()); |
| 3703 |
|
| 3704 |
testBadWebSocketHandshake(waitScope, timer, REQUEST, RESPONSE, KJ_HTTP_TEST_CREATE_2PIPE); |
| 3705 |
} |
| 3706 |
|
| 3707 |
KJ_TEST("HttpServer WebSocket handshake with missing Sec-WebSocket-Key") { |
| 3708 |
static constexpr auto REQUEST = |
| 3709 |
"GET /websocket HTTP/1.1\r\n" |
| 3710 |
"Connection: Upgrade\r\n" |
| 3711 |
"Upgrade: websocket\r\n" |
| 3712 |
"Sec-WebSocket-Version: 13\r\n" |
| 3713 |
"My-Header: foo\r\n" |
| 3714 |
"\r\n"_kj; |
| 3715 |
|
| 3716 |
static constexpr auto RESPONSE = |
| 3717 |
"HTTP/1.1 400 Bad Request\r\n" |
| 3718 |
"Connection: close\r\n" |
| 3719 |
"Content-Length: 32\r\n" |
| 3720 |
"Content-Type: text/plain\r\n" |
| 3721 |
"\r\n" |
| 3722 |
"ERROR: Missing Sec-WebSocket-Key"_kj; |
| 3723 |
|
| 3724 |
KJ_HTTP_TEST_SETUP_IO; |
| 3725 |
kj::TimerImpl timer(kj::origin<kj::TimePoint>()); |
| 3726 |
|
| 3727 |
testBadWebSocketHandshake(waitScope, timer, REQUEST, RESPONSE, KJ_HTTP_TEST_CREATE_2PIPE); |
| 3728 |
} |
| 3729 |
|
| 3730 |
KJ_TEST("HttpServer WebSocket with application error after accept") { |
| 3731 |
KJ_HTTP_TEST_SETUP_IO; |
| 3732 |
kj::TimerImpl timer(kj::origin<kj::TimePoint>()); |
| 3733 |
|
| 3734 |
class WebSocketApplicationErrorService: public HttpService, public HttpServerErrorHandler { |
| 3735 |
// Accepts a WebSocket, receives a message, and throws an exception (application error). |
| 3736 |
|
| 3737 |
public: |
| 3738 |
Promise<void> request( |
| 3739 |
HttpMethod method, kj::StringPtr, const HttpHeaders&, |
| 3740 |
AsyncInputStream&, Response& response) override { |
| 3741 |
KJ_ASSERT(method == HttpMethod::GET); |
| 3742 |
HttpHeaderTable headerTable; |
| 3743 |
HttpHeaders responseHeaders(headerTable); |
| 3744 |
auto webSocket = response.acceptWebSocket(responseHeaders); |
| 3745 |
return webSocket->receive().then([](WebSocket::Message) { |
| 3746 |
throwRecoverableException(KJ_EXCEPTION(FAILED, "test exception")); |
| 3747 |
}).attach(kj::mv(webSocket)); |
| 3748 |
} |
| 3749 |
|
| 3750 |
Promise<void> handleApplicationError(Exception exception, Maybe<Response&> response) override { |
| 3751 |
// We accepted the WebSocket, so the response was already sent. At one time, we _did_ expose a |
| 3752 |
// useless Response reference here, so this is a regression test. |
| 3753 |
bool responseWasSent = response == nullptr; |
| 3754 |
KJ_EXPECT(responseWasSent); |
| 3755 |
KJ_EXPECT(exception.getDescription() == "test exception"_kj); |
| 3756 |
return READY_NOW; |
| 3757 |
} |
| 3758 |
}; |
| 3759 |
|
| 3760 |
// Set up the HTTP service. |
| 3761 |
|
| 3762 |
WebSocketApplicationErrorService service; |
| 3763 |
|
| 3764 |
HttpServerSettings serverSettings; |
| 3765 |
serverSettings.errorHandler = service; |
| 3766 |
|
| 3767 |
HttpHeaderTable headerTable; |
| 3768 |
HttpServer server(timer, headerTable, service, serverSettings); |
| 3769 |
|
| 3770 |
auto pipe = KJ_HTTP_TEST_CREATE_2PIPE; |
| 3771 |
|
| 3772 |
auto listenTask = server.listenHttp(kj::mv(pipe.ends[0])); |
| 3773 |
|
| 3774 |
// Make a client and open a WebSocket to the service. |
| 3775 |
|
| 3776 |
FakeEntropySource entropySource; |
| 3777 |
HttpClientSettings clientSettings; |
| 3778 |
clientSettings.entropySource = entropySource; |
| 3779 |
auto client = newHttpClient( |
| 3780 |
headerTable, *pipe.ends[1], clientSettings); |
| 3781 |
|
| 3782 |
HttpHeaders headers(headerTable); |
| 3783 |
auto webSocketResponse = client->openWebSocket("/websocket"_kj, headers) |
| 3784 |
.wait(waitScope); |
| 3785 |
|
| 3786 |
KJ_ASSERT(webSocketResponse.statusCode == 101); |
| 3787 |
auto webSocket = kj::mv(KJ_ASSERT_NONNULL(webSocketResponse.webSocketOrBody.tryGet<Own<WebSocket>>())); |
| 3788 |
|
| 3789 |
webSocket->send("ignored"_kj).wait(waitScope); |
| 3790 |
|
| 3791 |
listenTask.wait(waitScope); |
| 3792 |
} |
| 3793 |
|
| 3794 |
// ----------------------------------------------------------------------------- |
| 3795 |
|
| 3796 |
KJ_TEST("HttpServer request timeout") { |
| 3797 |
auto PIPELINE_TESTS = pipelineTestCases(); |
| 3798 |
|
| 3799 |
KJ_HTTP_TEST_SETUP_IO; |
| 3800 |
kj::TimerImpl timer(kj::origin<kj::TimePoint>()); |
| 3801 |
auto pipe = KJ_HTTP_TEST_CREATE_2PIPE; |
| 3802 |
|
| 3803 |
HttpHeaderTable table; |
| 3804 |
TestHttpService service(PIPELINE_TESTS, table); |
| 3805 |
HttpServerSettings settings; |
| 3806 |
settings.headerTimeout = 1 * kj::MILLISECONDS; |
| 3807 |
HttpServer server(timer, table, service, settings); |
| 3808 |
|
| 3809 |
// Shouldn't hang! Should time out. |
| 3810 |
auto promise = server.listenHttp(kj::mv(pipe.ends[0])); |
| 3811 |
KJ_EXPECT(!promise.poll(waitScope)); |
| 3812 |
timer.advanceTo(timer.now() + settings.headerTimeout / 2); |
| 3813 |
KJ_EXPECT(!promise.poll(waitScope)); |
| 3814 |
timer.advanceTo(timer.now() + settings.headerTimeout); |
| 3815 |
promise.wait(waitScope); |
| 3816 |
|
| 3817 |
// Closes the connection without sending anything. |
| 3818 |
KJ_EXPECT(pipe.ends[1]->readAllText().wait(waitScope) == ""); |
| 3819 |
} |
| 3820 |
|
| 3821 |
KJ_TEST("HttpServer pipeline timeout") { |
| 3822 |
auto PIPELINE_TESTS = pipelineTestCases(); |
| 3823 |
|
| 3824 |
KJ_HTTP_TEST_SETUP_IO; |
| 3825 |
kj::TimerImpl timer(kj::origin<kj::TimePoint>()); |
| 3826 |
auto pipe = KJ_HTTP_TEST_CREATE_2PIPE; |
| 3827 |
|
| 3828 |
HttpHeaderTable table; |
| 3829 |
TestHttpService service(PIPELINE_TESTS, table); |
| 3830 |
HttpServerSettings settings; |
| 3831 |
settings.pipelineTimeout = 1 * kj::MILLISECONDS; |
| 3832 |
HttpServer server(timer, table, service, settings); |
| 3833 |
|
| 3834 |
auto listenTask = server.listenHttp(kj::mv(pipe.ends[0])); |
| 3835 |
|
| 3836 |
// Do one request. |
| 3837 |
pipe.ends[1]->write(PIPELINE_TESTS[0].request.raw.begin(), PIPELINE_TESTS[0].request.raw.size()) |
| 3838 |
.wait(waitScope); |
| 3839 |
expectRead(*pipe.ends[1], PIPELINE_TESTS[0].response.raw).wait(waitScope); |
| 3840 |
|
| 3841 |
// Listen task should time out even though we didn't shutdown the socket. |
| 3842 |
KJ_EXPECT(!listenTask.poll(waitScope)); |
| 3843 |
timer.advanceTo(timer.now() + settings.pipelineTimeout / 2); |
| 3844 |
KJ_EXPECT(!listenTask.poll(waitScope)); |
| 3845 |
timer.advanceTo(timer.now() + settings.pipelineTimeout); |
| 3846 |
listenTask.wait(waitScope); |
| 3847 |
|
| 3848 |
// In this case, no data is sent back. |
| 3849 |
KJ_EXPECT(pipe.ends[1]->readAllText().wait(waitScope) == ""); |
| 3850 |
} |
| 3851 |
|
| 3852 |
class BrokenHttpService final: public HttpService { |
| 3853 |
// HttpService that doesn't send a response. |
| 3854 |
public: |
| 3855 |
BrokenHttpService() = default; |
| 3856 |
explicit BrokenHttpService(kj::Exception&& exception): exception(kj::mv(exception)) {} |
| 3857 |
|
| 3858 |
kj::Promise<void> request( |
| 3859 |
HttpMethod method, kj::StringPtr url, const HttpHeaders& headers, |
| 3860 |
kj::AsyncInputStream& requestBody, Response& responseSender) override { |
| 3861 |
return requestBody.readAllBytes().then([this](kj::Array<byte>&&) -> kj::Promise<void> { |
| 3862 |
KJ_IF_MAYBE(e, exception) { |
| 3863 |
return kj::cp(*e); |
| 3864 |
} else { |
| 3865 |
return kj::READY_NOW; |
| 3866 |
} |
| 3867 |
}); |
| 3868 |
} |
| 3869 |
|
| 3870 |
private: |
| 3871 |
kj::Maybe<kj::Exception> exception; |
| 3872 |
}; |
| 3873 |
|
| 3874 |
KJ_TEST("HttpServer no response") { |
| 3875 |
auto PIPELINE_TESTS = pipelineTestCases(); |
| 3876 |
|
| 3877 |
KJ_HTTP_TEST_SETUP_IO; |
| 3878 |
kj::TimerImpl timer(kj::origin<kj::TimePoint>()); |
| 3879 |
auto pipe = KJ_HTTP_TEST_CREATE_2PIPE; |
| 3880 |
|
| 3881 |
HttpHeaderTable table; |
| 3882 |
BrokenHttpService service; |
| 3883 |
HttpServer server(timer, table, service); |
| 3884 |
|
| 3885 |
auto listenTask = server.listenHttp(kj::mv(pipe.ends[0])); |
| 3886 |
|
| 3887 |
// Do one request. |
| 3888 |
pipe.ends[1]->write(PIPELINE_TESTS[0].request.raw.begin(), PIPELINE_TESTS[0].request.raw.size()) |
| 3889 |
.wait(waitScope); |
| 3890 |
auto text = pipe.ends[1]->readAllText().wait(waitScope); |
| 3891 |
|
| 3892 |
KJ_EXPECT(text == |
| 3893 |
"HTTP/1.1 500 Internal Server Error\r\n" |
| 3894 |
"Connection: close\r\n" |
| 3895 |
"Content-Length: 51\r\n" |
| 3896 |
"Content-Type: text/plain\r\n" |
| 3897 |
"\r\n" |
| 3898 |
"ERROR: The HttpService did not generate a response.", text); |
| 3899 |
} |
| 3900 |
|
| 3901 |
KJ_TEST("HttpServer disconnected") { |
| 3902 |
auto PIPELINE_TESTS = pipelineTestCases(); |
| 3903 |
|
| 3904 |
KJ_HTTP_TEST_SETUP_IO; |
| 3905 |
kj::TimerImpl timer(kj::origin<kj::TimePoint>()); |
| 3906 |
auto pipe = KJ_HTTP_TEST_CREATE_2PIPE; |
| 3907 |
|
| 3908 |
HttpHeaderTable table; |
| 3909 |
BrokenHttpService service(KJ_EXCEPTION(DISCONNECTED, "disconnected")); |
| 3910 |
HttpServer server(timer, table, service); |
| 3911 |
|
| 3912 |
auto listenTask = server.listenHttp(kj::mv(pipe.ends[0])); |
| 3913 |
|
| 3914 |
// Do one request. |
| 3915 |
pipe.ends[1]->write(PIPELINE_TESTS[0].request.raw.begin(), PIPELINE_TESTS[0].request.raw.size()) |
| 3916 |
.wait(waitScope); |
| 3917 |
auto text = pipe.ends[1]->readAllText().wait(waitScope); |
| 3918 |
|
| 3919 |
KJ_EXPECT(text == "", text); |
| 3920 |
} |
| 3921 |
|
| 3922 |
KJ_TEST("HttpServer overloaded") { |
| 3923 |
auto PIPELINE_TESTS = pipelineTestCases(); |
| 3924 |
|
| 3925 |
KJ_HTTP_TEST_SETUP_IO; |
| 3926 |
kj::TimerImpl timer(kj::origin<kj::TimePoint>()); |
| 3927 |
auto pipe = KJ_HTTP_TEST_CREATE_2PIPE; |
| 3928 |
|
| 3929 |
HttpHeaderTable table; |
| 3930 |
BrokenHttpService service(KJ_EXCEPTION(OVERLOADED, "overloaded")); |
| 3931 |
HttpServer server(timer, table, service); |
| 3932 |
|
| 3933 |
auto listenTask = server.listenHttp(kj::mv(pipe.ends[0])); |
| 3934 |
|
| 3935 |
// Do one request. |
| 3936 |
pipe.ends[1]->write(PIPELINE_TESTS[0].request.raw.begin(), PIPELINE_TESTS[0].request.raw.size()) |
| 3937 |
.wait(waitScope); |
| 3938 |
auto text = pipe.ends[1]->readAllText().wait(waitScope); |
| 3939 |
|
| 3940 |
KJ_EXPECT(text.startsWith("HTTP/1.1 503 Service Unavailable"), text); |
| 3941 |
} |
| 3942 |
|
| 3943 |
KJ_TEST("HttpServer unimplemented") { |
| 3944 |
auto PIPELINE_TESTS = pipelineTestCases(); |
| 3945 |
|
| 3946 |
KJ_HTTP_TEST_SETUP_IO; |
| 3947 |
kj::TimerImpl timer(kj::origin<kj::TimePoint>()); |
| 3948 |
auto pipe = KJ_HTTP_TEST_CREATE_2PIPE; |
| 3949 |
|
| 3950 |
HttpHeaderTable table; |
| 3951 |
BrokenHttpService service(KJ_EXCEPTION(UNIMPLEMENTED, "unimplemented")); |
| 3952 |
HttpServer server(timer, table, service); |
| 3953 |
|
| 3954 |
auto listenTask = server.listenHttp(kj::mv(pipe.ends[0])); |
| 3955 |
|
| 3956 |
// Do one request. |
| 3957 |
pipe.ends[1]->write(PIPELINE_TESTS[0].request.raw.begin(), PIPELINE_TESTS[0].request.raw.size()) |
| 3958 |
.wait(waitScope); |
| 3959 |
auto text = pipe.ends[1]->readAllText().wait(waitScope); |
| 3960 |
|
| 3961 |
KJ_EXPECT(text.startsWith("HTTP/1.1 501 Not Implemented"), text); |
| 3962 |
} |
| 3963 |
|
| 3964 |
KJ_TEST("HttpServer threw exception") { |
| 3965 |
auto PIPELINE_TESTS = pipelineTestCases(); |
| 3966 |
|
| 3967 |
KJ_HTTP_TEST_SETUP_IO; |
| 3968 |
kj::TimerImpl timer(kj::origin<kj::TimePoint>()); |
| 3969 |
auto pipe = KJ_HTTP_TEST_CREATE_2PIPE; |
| 3970 |
|
| 3971 |
HttpHeaderTable table; |
| 3972 |
BrokenHttpService service(KJ_EXCEPTION(FAILED, "failed")); |
| 3973 |
HttpServer server(timer, table, service); |
| 3974 |
|
| 3975 |
auto listenTask = server.listenHttp(kj::mv(pipe.ends[0])); |
| 3976 |
|
| 3977 |
// Do one request. |
| 3978 |
pipe.ends[1]->write(PIPELINE_TESTS[0].request.raw.begin(), PIPELINE_TESTS[0].request.raw.size()) |
| 3979 |
.wait(waitScope); |
| 3980 |
auto text = pipe.ends[1]->readAllText().wait(waitScope); |
| 3981 |
|
| 3982 |
KJ_EXPECT(text.startsWith("HTTP/1.1 500 Internal Server Error"), text); |
| 3983 |
} |
| 3984 |
|
| 3985 |
KJ_TEST("HttpServer bad request") { |
| 3986 |
KJ_HTTP_TEST_SETUP_IO; |
| 3987 |
kj::TimerImpl timer(kj::origin<kj::TimePoint>()); |
| 3988 |
auto pipe = KJ_HTTP_TEST_CREATE_2PIPE; |
| 3989 |
|
| 3990 |
HttpHeaderTable table; |
| 3991 |
BrokenHttpService service; |
| 3992 |
HttpServer server(timer, table, service); |
| 3993 |
|
| 3994 |
auto listenTask = server.listenHttp(kj::mv(pipe.ends[0])); |
| 3995 |
|
| 3996 |
static constexpr auto request = "GET / HTTP/1.1\r\nbad request\r\n\r\n"_kj; |
| 3997 |
auto writePromise = pipe.ends[1]->write(request.begin(), request.size()); |
| 3998 |
auto response = pipe.ends[1]->readAllText().wait(waitScope); |
| 3999 |
KJ_EXPECT(writePromise.poll(waitScope)); |
| 4000 |
writePromise.wait(waitScope); |
| 4001 |
|
| 4002 |
static constexpr auto expectedResponse = |
| 4003 |
"HTTP/1.1 400 Bad Request\r\n" |
| 4004 |
"Connection: close\r\n" |
| 4005 |
"Content-Length: 53\r\n" |
| 4006 |
"Content-Type: text/plain\r\n" |
| 4007 |
"\r\n" |
| 4008 |
"ERROR: The headers sent by your client are not valid."_kj; |
| 4009 |
|
| 4010 |
KJ_EXPECT(expectedResponse == response, expectedResponse, response); |
| 4011 |
} |
| 4012 |
|
| 4013 |
KJ_TEST("HttpServer invalid method") { |
| 4014 |
KJ_HTTP_TEST_SETUP_IO; |
| 4015 |
kj::TimerImpl timer(kj::origin<kj::TimePoint>()); |
| 4016 |
auto pipe = KJ_HTTP_TEST_CREATE_2PIPE; |
| 4017 |
|
| 4018 |
HttpHeaderTable table; |
| 4019 |
BrokenHttpService service; |
| 4020 |
HttpServer server(timer, table, service); |
| 4021 |
|
| 4022 |
auto listenTask = server.listenHttp(kj::mv(pipe.ends[0])); |
| 4023 |
|
| 4024 |
static constexpr auto request = "bad request\r\n\r\n"_kj; |
| 4025 |
auto writePromise = pipe.ends[1]->write(request.begin(), request.size()); |
| 4026 |
auto response = pipe.ends[1]->readAllText().wait(waitScope); |
| 4027 |
KJ_EXPECT(writePromise.poll(waitScope)); |
| 4028 |
writePromise.wait(waitScope); |
| 4029 |
|
| 4030 |
static constexpr auto expectedResponse = |
| 4031 |
"HTTP/1.1 501 Not Implemented\r\n" |
| 4032 |
"Connection: close\r\n" |
| 4033 |
"Content-Length: 35\r\n" |
| 4034 |
"Content-Type: text/plain\r\n" |
| 4035 |
"\r\n" |
| 4036 |
"ERROR: Unrecognized request method."_kj; |
| 4037 |
|
| 4038 |
KJ_EXPECT(expectedResponse == response, expectedResponse, response); |
| 4039 |
} |
| 4040 |
|
| 4041 |
KJ_TEST("HttpServer rejects negative Content-Length") { |
| 4042 |
KJ_HTTP_TEST_SETUP_IO; |
| 4043 |
kj::TimerImpl timer(kj::origin<kj::TimePoint>()); |
| 4044 |
auto pipe = KJ_HTTP_TEST_CREATE_2PIPE; |
| 4045 |
|
| 4046 |
HttpHeaderTable table; |
| 4047 |
BrokenHttpService service; |
| 4048 |
HttpServer server(timer, table, service); |
| 4049 |
|
| 4050 |
auto listenTask = server.listenHttp(kj::mv(pipe.ends[0])); |
| 4051 |
|
| 4052 |
auto msg = |
| 4053 |
"POST / HTTP/1.1\r\n" |
| 4054 |
"Content-Length: -1\r\n" |
| 4055 |
"\r\n" |
| 4056 |
"foo"_kj.asBytes(); |
| 4057 |
|
| 4058 |
auto writePromise = pipe.ends[1]->write(msg.begin(), msg.size()); |
| 4059 |
auto response = pipe.ends[1]->readAllText().wait(waitScope); |
| 4060 |
|
| 4061 |
// The server should reject the negative Content-Length. The KJ_FAIL_REQUIRE in getEntityBody() |
| 4062 |
// gets caught by the server loop and turned into a 500 error. |
| 4063 |
KJ_EXPECT(response.startsWith("HTTP/1.1 500 Internal Server Error"), response); |
| 4064 |
|
| 4065 |
KJ_EXPECT(writePromise.poll(waitScope)); |
| 4066 |
writePromise.catch_([](kj::Exception&&) {}).wait(waitScope); |
| 4067 |
} |
| 4068 |
|
| 4069 |
KJ_TEST("HttpServer rejects chunked body with overflowing chunk size") { |
| 4070 |
KJ_HTTP_TEST_SETUP_IO; |
| 4071 |
kj::TimerImpl timer(kj::origin<kj::TimePoint>()); |
| 4072 |
auto pipe = KJ_HTTP_TEST_CREATE_2PIPE; |
| 4073 |
|
| 4074 |
HttpHeaderTable table; |
| 4075 |
BrokenHttpService service; |
| 4076 |
HttpServer server(timer, table, service); |
| 4077 |
|
| 4078 |
auto listenTask = server.listenHttp(kj::mv(pipe.ends[0])); |
| 4079 |
|
| 4080 |
// 17 hex digits: 0x10000000000000000 = 2^64, which overflows uint64_t. |
| 4081 |
auto msg = |
| 4082 |
"POST / HTTP/1.1\r\n" |
| 4083 |
"Transfer-Encoding: chunked\r\n" |
| 4084 |
"\r\n" |
| 4085 |
"10000000000000000\r\n" |
| 4086 |
"x\r\n" |
| 4087 |
"0\r\n" |
| 4088 |
"\r\n"_kj.asBytes(); |
| 4089 |
|
| 4090 |
auto writePromise = pipe.ends[1]->write(msg.begin(), msg.size()); |
| 4091 |
auto response = pipe.ends[1]->readAllText().wait(waitScope); |
| 4092 |
|
| 4093 |
// The chunk size overflow causes a KJ_REQUIRE failure during body reading, which the server |
| 4094 |
// catches and turns into a 500 error. |
| 4095 |
KJ_EXPECT(response.startsWith("HTTP/1.1 500 Internal Server Error"), response); |
| 4096 |
|
| 4097 |
KJ_EXPECT(writePromise.poll(waitScope)); |
| 4098 |
writePromise.catch_([](kj::Exception&&) {}).wait(waitScope); |
| 4099 |
} |
| 4100 |
|
| 4101 |
// Ensure that HttpServerSettings can continue to be constexpr. |
| 4102 |
KJ_UNUSED static constexpr HttpServerSettings STATIC_CONSTEXPR_SETTINGS {}; |
| 4103 |
|
| 4104 |
class TestErrorHandler: public HttpServerErrorHandler { |
| 4105 |
public: |
| 4106 |
kj::Promise<void> handleClientProtocolError( |
| 4107 |
HttpHeaders::ProtocolError protocolError, kj::HttpService::Response& response) override { |
| 4108 |
// In a real error handler, you should redact `protocolError.rawContent`. |
| 4109 |
auto message = kj::str("Saw protocol error: ", protocolError.description, "; rawContent = ", |
| 4110 |
encodeCEscape(protocolError.rawContent)); |
| 4111 |
return sendError(400, "Bad Request", kj::mv(message), response); |
| 4112 |
} |
| 4113 |
|
| 4114 |
kj::Promise<void> handleApplicationError( |
| 4115 |
kj::Exception exception, kj::Maybe<kj::HttpService::Response&> response) override { |
| 4116 |
return sendError(500, "Internal Server Error", |
| 4117 |
kj::str("Saw application error: ", exception.getDescription()), response); |
| 4118 |
} |
| 4119 |
|
| 4120 |
kj::Promise<void> handleNoResponse(kj::HttpService::Response& response) override { |
| 4121 |
return sendError(500, "Internal Server Error", kj::str("Saw no response."), response); |
| 4122 |
} |
| 4123 |
|
| 4124 |
static TestErrorHandler instance; |
| 4125 |
|
| 4126 |
private: |
| 4127 |
kj::Promise<void> sendError(uint statusCode, kj::StringPtr statusText, String message, |
| 4128 |
Maybe<HttpService::Response&> response) { |
| 4129 |
KJ_IF_MAYBE(r, response) { |
| 4130 |
HttpHeaderTable headerTable; |
| 4131 |
HttpHeaders headers(headerTable); |
| 4132 |
auto body = r->send(statusCode, statusText, headers, message.size()); |
| 4133 |
return body->write(message.begin(), message.size()).attach(kj::mv(body), kj::mv(message)); |
| 4134 |
} else { |
| 4135 |
KJ_LOG(ERROR, "Saw an error but too late to report to client."); |
| 4136 |
return kj::READY_NOW; |
| 4137 |
} |
| 4138 |
} |
| 4139 |
}; |
| 4140 |
|
| 4141 |
TestErrorHandler TestErrorHandler::instance {}; |
| 4142 |
|
| 4143 |
KJ_TEST("HttpServer no response, custom error handler") { |
| 4144 |
auto PIPELINE_TESTS = pipelineTestCases(); |
| 4145 |
|
| 4146 |
KJ_HTTP_TEST_SETUP_IO; |
| 4147 |
kj::TimerImpl timer(kj::origin<kj::TimePoint>()); |
| 4148 |
auto pipe = KJ_HTTP_TEST_CREATE_2PIPE; |
| 4149 |
|
| 4150 |
HttpServerSettings settings {}; |
| 4151 |
settings.errorHandler = TestErrorHandler::instance; |
| 4152 |
|
| 4153 |
HttpHeaderTable table; |
| 4154 |
BrokenHttpService service; |
| 4155 |
HttpServer server(timer, table, service, settings); |
| 4156 |
|
| 4157 |
auto listenTask = server.listenHttp(kj::mv(pipe.ends[0])); |
| 4158 |
|
| 4159 |
// Do one request. |
| 4160 |
pipe.ends[1]->write(PIPELINE_TESTS[0].request.raw.begin(), PIPELINE_TESTS[0].request.raw.size()) |
| 4161 |
.wait(waitScope); |
| 4162 |
auto text = pipe.ends[1]->readAllText().wait(waitScope); |
| 4163 |
|
| 4164 |
KJ_EXPECT(text == |
| 4165 |
"HTTP/1.1 500 Internal Server Error\r\n" |
| 4166 |
"Connection: close\r\n" |
| 4167 |
"Content-Length: 16\r\n" |
| 4168 |
"\r\n" |
| 4169 |
"Saw no response.", text); |
| 4170 |
} |
| 4171 |
|
| 4172 |
KJ_TEST("HttpServer threw exception, custom error handler") { |
| 4173 |
auto PIPELINE_TESTS = pipelineTestCases(); |
| 4174 |
|
| 4175 |
KJ_HTTP_TEST_SETUP_IO; |
| 4176 |
kj::TimerImpl timer(kj::origin<kj::TimePoint>()); |
| 4177 |
auto pipe = KJ_HTTP_TEST_CREATE_2PIPE; |
| 4178 |
|
| 4179 |
HttpServerSettings settings {}; |
| 4180 |
settings.errorHandler = TestErrorHandler::instance; |
| 4181 |
|
| 4182 |
HttpHeaderTable table; |
| 4183 |
BrokenHttpService service(KJ_EXCEPTION(FAILED, "failed")); |
| 4184 |
HttpServer server(timer, table, service, settings); |
| 4185 |
|
| 4186 |
auto listenTask = server.listenHttp(kj::mv(pipe.ends[0])); |
| 4187 |
|
| 4188 |
// Do one request. |
| 4189 |
pipe.ends[1]->write(PIPELINE_TESTS[0].request.raw.begin(), PIPELINE_TESTS[0].request.raw.size()) |
| 4190 |
.wait(waitScope); |
| 4191 |
auto text = pipe.ends[1]->readAllText().wait(waitScope); |
| 4192 |
|
| 4193 |
KJ_EXPECT(text == |
| 4194 |
"HTTP/1.1 500 Internal Server Error\r\n" |
| 4195 |
"Connection: close\r\n" |
| 4196 |
"Content-Length: 29\r\n" |
| 4197 |
"\r\n" |
| 4198 |
"Saw application error: failed", text); |
| 4199 |
} |
| 4200 |
|
| 4201 |
KJ_TEST("HttpServer bad request, custom error handler") { |
| 4202 |
KJ_HTTP_TEST_SETUP_IO; |
| 4203 |
kj::TimerImpl timer(kj::origin<kj::TimePoint>()); |
| 4204 |
auto pipe = KJ_HTTP_TEST_CREATE_2PIPE; |
| 4205 |
|
| 4206 |
HttpServerSettings settings {}; |
| 4207 |
settings.errorHandler = TestErrorHandler::instance; |
| 4208 |
|
| 4209 |
HttpHeaderTable table; |
| 4210 |
BrokenHttpService service; |
| 4211 |
HttpServer server(timer, table, service, settings); |
| 4212 |
|
| 4213 |
auto listenTask = server.listenHttp(kj::mv(pipe.ends[0])); |
| 4214 |
|
| 4215 |
static constexpr auto request = "bad request\r\n\r\n"_kj; |
| 4216 |
auto writePromise = pipe.ends[1]->write(request.begin(), request.size()); |
| 4217 |
auto response = pipe.ends[1]->readAllText().wait(waitScope); |
| 4218 |
KJ_EXPECT(writePromise.poll(waitScope)); |
| 4219 |
writePromise.wait(waitScope); |
| 4220 |
|
| 4221 |
static constexpr auto expectedResponse = |
| 4222 |
"HTTP/1.1 400 Bad Request\r\n" |
| 4223 |
"Connection: close\r\n" |
| 4224 |
"Content-Length: 80\r\n" |
| 4225 |
"\r\n" |
| 4226 |
"Saw protocol error: Unrecognized request method.; " |
| 4227 |
"rawContent = bad request\\000\\n"_kj; |
| 4228 |
|
| 4229 |
KJ_EXPECT(expectedResponse == response, expectedResponse, response); |
| 4230 |
} |
| 4231 |
|
| 4232 |
class PartialResponseService final: public HttpService { |
| 4233 |
// HttpService that sends a partial response then throws. |
| 4234 |
public: |
| 4235 |
kj::Promise<void> request( |
| 4236 |
HttpMethod method, kj::StringPtr url, const HttpHeaders& headers, |
| 4237 |
kj::AsyncInputStream& requestBody, Response& response) override { |
| 4238 |
return requestBody.readAllBytes() |
| 4239 |
.then([this,&response](kj::Array<byte>&&) -> kj::Promise<void> { |
| 4240 |
HttpHeaders headers(table); |
| 4241 |
auto body = response.send(200, "OK", headers, 32); |
| 4242 |
auto promise = body->write("foo", 3); |
| 4243 |
return promise.attach(kj::mv(body)).then([]() -> kj::Promise<void> { |
| 4244 |
return KJ_EXCEPTION(FAILED, "failed"); |
| 4245 |
}); |
| 4246 |
}); |
| 4247 |
} |
| 4248 |
|
| 4249 |
private: |
| 4250 |
kj::Maybe<kj::Exception> exception; |
| 4251 |
HttpHeaderTable table; |
| 4252 |
}; |
| 4253 |
|
| 4254 |
KJ_TEST("HttpServer threw exception after starting response") { |
| 4255 |
auto PIPELINE_TESTS = pipelineTestCases(); |
| 4256 |
|
| 4257 |
KJ_HTTP_TEST_SETUP_IO; |
| 4258 |
kj::TimerImpl timer(kj::origin<kj::TimePoint>()); |
| 4259 |
auto pipe = KJ_HTTP_TEST_CREATE_2PIPE; |
| 4260 |
|
| 4261 |
HttpHeaderTable table; |
| 4262 |
PartialResponseService service; |
| 4263 |
HttpServer server(timer, table, service); |
| 4264 |
|
| 4265 |
auto listenTask = server.listenHttp(kj::mv(pipe.ends[0])); |
| 4266 |
|
| 4267 |
KJ_EXPECT_LOG(ERROR, "HttpService threw exception after generating a partial response"); |
| 4268 |
|
| 4269 |
// Do one request. |
| 4270 |
pipe.ends[1]->write(PIPELINE_TESTS[0].request.raw.begin(), PIPELINE_TESTS[0].request.raw.size()) |
| 4271 |
.wait(waitScope); |
| 4272 |
auto text = pipe.ends[1]->readAllText().wait(waitScope); |
| 4273 |
|
| 4274 |
KJ_EXPECT(text == |
| 4275 |
"HTTP/1.1 200 OK\r\n" |
| 4276 |
"Content-Length: 32\r\n" |
| 4277 |
"\r\n" |
| 4278 |
"foo", text); |
| 4279 |
} |
| 4280 |
|
| 4281 |
class PartialResponseNoThrowService final: public HttpService { |
| 4282 |
// HttpService that sends a partial response then returns without throwing. |
| 4283 |
public: |
| 4284 |
kj::Promise<void> request( |
| 4285 |
HttpMethod method, kj::StringPtr url, const HttpHeaders& headers, |
| 4286 |
kj::AsyncInputStream& requestBody, Response& response) override { |
| 4287 |
return requestBody.readAllBytes() |
| 4288 |
.then([this,&response](kj::Array<byte>&&) -> kj::Promise<void> { |
| 4289 |
HttpHeaders headers(table); |
| 4290 |
auto body = response.send(200, "OK", headers, 32); |
| 4291 |
auto promise = body->write("foo", 3); |
| 4292 |
return promise.attach(kj::mv(body)); |
| 4293 |
}); |
| 4294 |
} |
| 4295 |
|
| 4296 |
private: |
| 4297 |
kj::Maybe<kj::Exception> exception; |
| 4298 |
HttpHeaderTable table; |
| 4299 |
}; |
| 4300 |
|
| 4301 |
KJ_TEST("HttpServer failed to write complete response but didn't throw") { |
| 4302 |
auto PIPELINE_TESTS = pipelineTestCases(); |
| 4303 |
|
| 4304 |
KJ_HTTP_TEST_SETUP_IO; |
| 4305 |
kj::TimerImpl timer(kj::origin<kj::TimePoint>()); |
| 4306 |
auto pipe = KJ_HTTP_TEST_CREATE_2PIPE; |
| 4307 |
|
| 4308 |
HttpHeaderTable table; |
| 4309 |
PartialResponseNoThrowService service; |
| 4310 |
HttpServer server(timer, table, service); |
| 4311 |
|
| 4312 |
auto listenTask = server.listenHttp(kj::mv(pipe.ends[0])); |
| 4313 |
|
| 4314 |
// Do one request. |
| 4315 |
pipe.ends[1]->write(PIPELINE_TESTS[0].request.raw.begin(), PIPELINE_TESTS[0].request.raw.size()) |
| 4316 |
.wait(waitScope); |
| 4317 |
auto text = pipe.ends[1]->readAllText().wait(waitScope); |
| 4318 |
|
| 4319 |
KJ_EXPECT(text == |
| 4320 |
"HTTP/1.1 200 OK\r\n" |
| 4321 |
"Content-Length: 32\r\n" |
| 4322 |
"\r\n" |
| 4323 |
"foo", text); |
| 4324 |
} |
| 4325 |
|
| 4326 |
class SimpleInputStream final: public kj::AsyncInputStream { |
| 4327 |
// An InputStream that returns bytes out of a static string. |
| 4328 |
|
| 4329 |
public: |
| 4330 |
SimpleInputStream(kj::StringPtr text) |
| 4331 |
: unread(text.asBytes()) {} |
| 4332 |
|
| 4333 |
kj::Promise<size_t> tryRead(void* buffer, size_t minBytes, size_t maxBytes) override { |
| 4334 |
size_t amount = kj::min(maxBytes, unread.size()); |
| 4335 |
memcpy(buffer, unread.begin(), amount); |
| 4336 |
unread = unread.slice(amount, unread.size()); |
| 4337 |
return amount; |
| 4338 |
} |
| 4339 |
|
| 4340 |
private: |
| 4341 |
kj::ArrayPtr<const byte> unread; |
| 4342 |
}; |
| 4343 |
|
| 4344 |
class PumpResponseService final: public HttpService { |
| 4345 |
// HttpService that uses pumpTo() to write a response, without carefully specifying how much to |
| 4346 |
// pump, but the stream happens to be the right size. |
| 4347 |
public: |
| 4348 |
kj::Promise<void> request( |
| 4349 |
HttpMethod method, kj::StringPtr url, const HttpHeaders& headers, |
| 4350 |
kj::AsyncInputStream& requestBody, Response& response) override { |
| 4351 |
return requestBody.readAllBytes() |
| 4352 |
.then([this,&response](kj::Array<byte>&&) -> kj::Promise<void> { |
| 4353 |
HttpHeaders headers(table); |
| 4354 |
kj::StringPtr text = "Hello, World!"; |
| 4355 |
auto body = response.send(200, "OK", headers, text.size()); |
| 4356 |
|
| 4357 |
auto stream = kj::heap<SimpleInputStream>(text); |
| 4358 |
auto promise = stream->pumpTo(*body); |
| 4359 |
return promise.attach(kj::mv(body), kj::mv(stream)) |
| 4360 |
.then([text](uint64_t amount) { |
| 4361 |
KJ_EXPECT(amount == text.size()); |
| 4362 |
}); |
| 4363 |
}); |
| 4364 |
} |
| 4365 |
|
| 4366 |
private: |
| 4367 |
kj::Maybe<kj::Exception> exception; |
| 4368 |
HttpHeaderTable table; |
| 4369 |
}; |
| 4370 |
|
| 4371 |
KJ_TEST("HttpFixedLengthEntityWriter correctly implements tryPumpFrom") { |
| 4372 |
auto PIPELINE_TESTS = pipelineTestCases(); |
| 4373 |
|
| 4374 |
KJ_HTTP_TEST_SETUP_IO; |
| 4375 |
kj::TimerImpl timer(kj::origin<kj::TimePoint>()); |
| 4376 |
auto pipe = KJ_HTTP_TEST_CREATE_2PIPE; |
| 4377 |
|
| 4378 |
HttpHeaderTable table; |
| 4379 |
PumpResponseService service; |
| 4380 |
HttpServer server(timer, table, service); |
| 4381 |
|
| 4382 |
auto listenTask = server.listenHttp(kj::mv(pipe.ends[0])); |
| 4383 |
|
| 4384 |
// Do one request. |
| 4385 |
pipe.ends[1]->write(PIPELINE_TESTS[0].request.raw.begin(), PIPELINE_TESTS[0].request.raw.size()) |
| 4386 |
.wait(waitScope); |
| 4387 |
pipe.ends[1]->shutdownWrite(); |
| 4388 |
auto text = pipe.ends[1]->readAllText().wait(waitScope); |
| 4389 |
|
| 4390 |
KJ_EXPECT(text == |
| 4391 |
"HTTP/1.1 200 OK\r\n" |
| 4392 |
"Content-Length: 13\r\n" |
| 4393 |
"\r\n" |
| 4394 |
"Hello, World!", text); |
| 4395 |
} |
| 4396 |
|
| 4397 |
class HangingHttpService final: public HttpService { |
| 4398 |
// HttpService that hangs forever. |
| 4399 |
public: |
| 4400 |
kj::Promise<void> request( |
| 4401 |
HttpMethod method, kj::StringPtr url, const HttpHeaders& headers, |
| 4402 |
kj::AsyncInputStream& requestBody, Response& responseSender) override { |
| 4403 |
kj::Promise<void> result = kj::NEVER_DONE; |
| 4404 |
++inFlight; |
| 4405 |
return result.attach(kj::defer([this]() { |
| 4406 |
if (--inFlight == 0) { |
| 4407 |
KJ_IF_MAYBE(f, onCancelFulfiller) { |
| 4408 |
f->get()->fulfill(); |
| 4409 |
} |
| 4410 |
} |
| 4411 |
})); |
| 4412 |
} |
| 4413 |
|
| 4414 |
kj::Promise<void> onCancel() { |
| 4415 |
auto paf = kj::newPromiseAndFulfiller<void>(); |
| 4416 |
onCancelFulfiller = kj::mv(paf.fulfiller); |
| 4417 |
return kj::mv(paf.promise); |
| 4418 |
} |
| 4419 |
|
| 4420 |
uint inFlight = 0; |
| 4421 |
|
| 4422 |
private: |
| 4423 |
kj::Maybe<kj::Exception> exception; |
| 4424 |
kj::Maybe<kj::Own<kj::PromiseFulfiller<void>>> onCancelFulfiller; |
| 4425 |
}; |
| 4426 |
|
| 4427 |
KJ_TEST("HttpServer cancels request when client disconnects") { |
| 4428 |
KJ_HTTP_TEST_SETUP_IO; |
| 4429 |
kj::TimerImpl timer(kj::origin<kj::TimePoint>()); |
| 4430 |
auto pipe = KJ_HTTP_TEST_CREATE_2PIPE; |
| 4431 |
|
| 4432 |
HttpHeaderTable table; |
| 4433 |
HangingHttpService service; |
| 4434 |
HttpServer server(timer, table, service); |
| 4435 |
|
| 4436 |
auto listenTask = server.listenHttp(kj::mv(pipe.ends[0])); |
| 4437 |
|
| 4438 |
KJ_EXPECT(service.inFlight == 0); |
| 4439 |
|
| 4440 |
static constexpr auto request = "GET / HTTP/1.1\r\n\r\n"_kj; |
| 4441 |
pipe.ends[1]->write(request.begin(), request.size()).wait(waitScope); |
| 4442 |
|
| 4443 |
auto cancelPromise = service.onCancel(); |
| 4444 |
KJ_EXPECT(!cancelPromise.poll(waitScope)); |
| 4445 |
KJ_EXPECT(service.inFlight == 1); |
| 4446 |
|
| 4447 |
// Disconnect client and verify server cancels. |
| 4448 |
pipe.ends[1] = nullptr; |
| 4449 |
KJ_ASSERT(cancelPromise.poll(waitScope)); |
| 4450 |
KJ_EXPECT(service.inFlight == 0); |
| 4451 |
cancelPromise.wait(waitScope); |
| 4452 |
} |
| 4453 |
|
| 4454 |
class SuspendAfter: private HttpService { |
| 4455 |
// A SuspendableHttpServiceFactory which responds to the first `n` requests with 200 OK, then |
| 4456 |
// suspends all subsequent requests until its counter is reset. |
| 4457 |
|
| 4458 |
public: |
| 4459 |
void suspendAfter(uint countdownParam) { countdown = countdownParam; } |
| 4460 |
|
| 4461 |
kj::Maybe<kj::Own<HttpService>> operator()(HttpServer::SuspendableRequest& sr) { |
| 4462 |
if (countdown == 0) { |
| 4463 |
suspendedRequest = sr.suspend(); |
| 4464 |
return nullptr; |
| 4465 |
} |
| 4466 |
--countdown; |
| 4467 |
return kj::Own<HttpService>(static_cast<HttpService*>(this), kj::NullDisposer::instance); |
| 4468 |
} |
| 4469 |
|
| 4470 |
kj::Maybe<HttpServer::SuspendedRequest> getSuspended() { |
| 4471 |
KJ_DEFER(suspendedRequest = nullptr); |
| 4472 |
return kj::mv(suspendedRequest); |
| 4473 |
} |
| 4474 |
|
| 4475 |
private: |
| 4476 |
kj::Promise<void> request( |
| 4477 |
HttpMethod method, kj::StringPtr url, const HttpHeaders& headers, |
| 4478 |
kj::AsyncInputStream& requestBody, Response& response) override { |
| 4479 |
HttpHeaders responseHeaders(table); |
| 4480 |
response.send(200, "OK", responseHeaders); |
| 4481 |
return requestBody.readAllBytes().ignoreResult(); |
| 4482 |
} |
| 4483 |
|
| 4484 |
HttpHeaderTable table; |
| 4485 |
|
| 4486 |
uint countdown = kj::maxValue; |
| 4487 |
kj::Maybe<HttpServer::SuspendedRequest> suspendedRequest; |
| 4488 |
}; |
| 4489 |
|
| 4490 |
KJ_TEST("HttpServer can suspend a request") { |
| 4491 |
// This test sends a single request to an HttpServer three times. First it writes the request to |
| 4492 |
// its pipe and arranges for the HttpServer to suspend the request. Then it resumes the suspended |
| 4493 |
// request and arranges for this resumption to be suspended as well. Then it resumes once more and |
| 4494 |
// arranges for the request to be completed. |
| 4495 |
|
| 4496 |
KJ_HTTP_TEST_SETUP_IO; |
| 4497 |
kj::TimerImpl timer(kj::origin<kj::TimePoint>()); |
| 4498 |
auto pipe = KJ_HTTP_TEST_CREATE_2PIPE; |
| 4499 |
|
| 4500 |
HttpHeaderTable table; |
| 4501 |
// This HttpService will not actually be used, because we're passing a factory in to |
| 4502 |
// listenHttpCleanDrain(). |
| 4503 |
HangingHttpService service; |
| 4504 |
HttpServer server(timer, table, service); |
| 4505 |
|
| 4506 |
kj::Maybe<HttpServer::SuspendedRequest> suspendedRequest; |
| 4507 |
|
| 4508 |
SuspendAfter factory; |
| 4509 |
|
| 4510 |
{ |
| 4511 |
// Observe the HttpServer suspend. |
| 4512 |
|
| 4513 |
factory.suspendAfter(0); |
| 4514 |
auto listenPromise = server.listenHttpCleanDrain(*pipe.ends[0], factory); |
| 4515 |
|
| 4516 |
static constexpr kj::StringPtr REQUEST = |
| 4517 |
"POST / HTTP/1.1\r\n" |
| 4518 |
"Transfer-Encoding: chunked\r\n" |
| 4519 |
"\r\n" |
| 4520 |
"6\r\n" |
| 4521 |
"foobar\r\n" |
| 4522 |
"0\r\n" |
| 4523 |
"\r\n"_kj; |
| 4524 |
pipe.ends[1]->write(REQUEST.begin(), REQUEST.size()).wait(waitScope); |
| 4525 |
|
| 4526 |
// The listen promise is fulfilled with false. |
| 4527 |
KJ_EXPECT(listenPromise.poll(waitScope)); |
| 4528 |
KJ_EXPECT(!listenPromise.wait(waitScope)); |
| 4529 |
|
| 4530 |
// And we have a SuspendedRequest. |
| 4531 |
suspendedRequest = factory.getSuspended(); |
| 4532 |
KJ_EXPECT(suspendedRequest != nullptr); |
| 4533 |
} |
| 4534 |
|
| 4535 |
{ |
| 4536 |
// Observe the HttpServer suspend again without reading from the connection. |
| 4537 |
|
| 4538 |
factory.suspendAfter(0); |
| 4539 |
auto listenPromise = server.listenHttpCleanDrain( |
| 4540 |
*pipe.ends[0], factory, kj::mv(suspendedRequest)); |
| 4541 |
|
| 4542 |
// The listen promise is again fulfilled with false. |
| 4543 |
KJ_EXPECT(listenPromise.poll(waitScope)); |
| 4544 |
KJ_EXPECT(!listenPromise.wait(waitScope)); |
| 4545 |
|
| 4546 |
// We again have a suspendedRequest. |
| 4547 |
suspendedRequest = factory.getSuspended(); |
| 4548 |
KJ_EXPECT(suspendedRequest != nullptr); |
| 4549 |
} |
| 4550 |
|
| 4551 |
{ |
| 4552 |
// The SuspendedRequest is completed. |
| 4553 |
|
| 4554 |
factory.suspendAfter(1); |
| 4555 |
auto listenPromise = server.listenHttpCleanDrain( |
| 4556 |
*pipe.ends[0], factory, kj::mv(suspendedRequest)); |
| 4557 |
|
| 4558 |
auto drainPromise = kj::evalLast([&]() { |
| 4559 |
return server.drain(); |
| 4560 |
}); |
| 4561 |
|
| 4562 |
// We need to read the response for the HttpServer to drain. |
| 4563 |
auto readPromise = pipe.ends[1]->readAllText(); |
| 4564 |
|
| 4565 |
// This time, the server drained cleanly. |
| 4566 |
KJ_EXPECT(listenPromise.poll(waitScope)); |
| 4567 |
KJ_EXPECT(listenPromise.wait(waitScope)); |
| 4568 |
|
| 4569 |
drainPromise.wait(waitScope); |
| 4570 |
|
| 4571 |
// Close the server side of the pipe so our read promise completes. |
| 4572 |
pipe.ends[0] = nullptr; |
| 4573 |
|
| 4574 |
auto response = readPromise.wait(waitScope); |
| 4575 |
static constexpr kj::StringPtr RESPONSE = |
| 4576 |
"HTTP/1.1 200 OK\r\n" |
| 4577 |
"Transfer-Encoding: chunked\r\n" |
| 4578 |
"\r\n" |
| 4579 |
"0\r\n" |
| 4580 |
"\r\n"_kj; |
| 4581 |
KJ_EXPECT(RESPONSE == response); |
| 4582 |
} |
| 4583 |
} |
| 4584 |
|
| 4585 |
KJ_TEST("HttpServer can suspend and resume pipelined requests") { |
| 4586 |
// This test sends multiple requests with both Content-Length and Transfer-Encoding: chunked |
| 4587 |
// bodies, and verifies that suspending both kinds does not corrupt the stream. |
| 4588 |
|
| 4589 |
KJ_HTTP_TEST_SETUP_IO; |
| 4590 |
kj::TimerImpl timer(kj::origin<kj::TimePoint>()); |
| 4591 |
auto pipe = KJ_HTTP_TEST_CREATE_2PIPE; |
| 4592 |
|
| 4593 |
HttpHeaderTable table; |
| 4594 |
// This HttpService will not actually be used, because we're passing a factory in to |
| 4595 |
// listenHttpCleanDrain(). |
| 4596 |
HangingHttpService service; |
| 4597 |
HttpServer server(timer, table, service); |
| 4598 |
|
| 4599 |
// We'll suspend the second request. |
| 4600 |
kj::Maybe<HttpServer::SuspendedRequest> suspendedRequest; |
| 4601 |
SuspendAfter factory; |
| 4602 |
|
| 4603 |
static constexpr kj::StringPtr LENGTHFUL_REQUEST = |
| 4604 |
"POST / HTTP/1.1\r\n" |
| 4605 |
"Content-Length: 6\r\n" |
| 4606 |
"\r\n" |
| 4607 |
"foobar"_kj; |
| 4608 |
static constexpr kj::StringPtr CHUNKED_REQUEST = |
| 4609 |
"POST / HTTP/1.1\r\n" |
| 4610 |
"Transfer-Encoding: chunked\r\n" |
| 4611 |
"\r\n" |
| 4612 |
"6\r\n" |
| 4613 |
"foobar\r\n" |
| 4614 |
"0\r\n" |
| 4615 |
"\r\n"_kj; |
| 4616 |
|
| 4617 |
// Set up several requests; we'll suspend and transfer the second and third one. |
| 4618 |
auto writePromise = pipe.ends[1]->write(LENGTHFUL_REQUEST.begin(), LENGTHFUL_REQUEST.size()) |
| 4619 |
.then([&]() { |
| 4620 |
return pipe.ends[1]->write(CHUNKED_REQUEST.begin(), CHUNKED_REQUEST.size()); |
| 4621 |
}).then([&]() { |
| 4622 |
return pipe.ends[1]->write(LENGTHFUL_REQUEST.begin(), LENGTHFUL_REQUEST.size()); |
| 4623 |
}).then([&]() { |
| 4624 |
return pipe.ends[1]->write(CHUNKED_REQUEST.begin(), CHUNKED_REQUEST.size()); |
| 4625 |
}); |
| 4626 |
|
| 4627 |
auto readPromise = pipe.ends[1]->readAllText(); |
| 4628 |
|
| 4629 |
{ |
| 4630 |
// Observe the HttpServer suspend the second request. |
| 4631 |
|
| 4632 |
factory.suspendAfter(1); |
| 4633 |
auto listenPromise = server.listenHttpCleanDrain(*pipe.ends[0], factory); |
| 4634 |
|
| 4635 |
KJ_EXPECT(listenPromise.poll(waitScope)); |
| 4636 |
KJ_EXPECT(!listenPromise.wait(waitScope)); |
| 4637 |
suspendedRequest = factory.getSuspended(); |
| 4638 |
KJ_EXPECT(suspendedRequest != nullptr); |
| 4639 |
} |
| 4640 |
|
| 4641 |
{ |
| 4642 |
// Let's resume one request and suspend the next pipelined request. |
| 4643 |
|
| 4644 |
factory.suspendAfter(1); |
| 4645 |
auto listenPromise = server.listenHttpCleanDrain( |
| 4646 |
*pipe.ends[0], factory, kj::mv(suspendedRequest)); |
| 4647 |
|
| 4648 |
KJ_EXPECT(listenPromise.poll(waitScope)); |
| 4649 |
KJ_EXPECT(!listenPromise.wait(waitScope)); |
| 4650 |
suspendedRequest = factory.getSuspended(); |
| 4651 |
KJ_EXPECT(suspendedRequest != nullptr); |
| 4652 |
} |
| 4653 |
|
| 4654 |
{ |
| 4655 |
// Resume again and run to completion. |
| 4656 |
|
| 4657 |
factory.suspendAfter(kj::maxValue); |
| 4658 |
auto listenPromise = server.listenHttpCleanDrain( |
| 4659 |
*pipe.ends[0], factory, kj::mv(suspendedRequest)); |
| 4660 |
|
| 4661 |
auto drainPromise = kj::evalLast([&]() { |
| 4662 |
return server.drain(); |
| 4663 |
}); |
| 4664 |
|
| 4665 |
// This time, the server drained cleanly. |
| 4666 |
KJ_EXPECT(listenPromise.poll(waitScope)); |
| 4667 |
KJ_EXPECT(listenPromise.wait(waitScope)); |
| 4668 |
// No suspended request this time. |
| 4669 |
suspendedRequest = factory.getSuspended(); |
| 4670 |
KJ_EXPECT(suspendedRequest == nullptr); |
| 4671 |
|
| 4672 |
drainPromise.wait(waitScope); |
| 4673 |
} |
| 4674 |
|
| 4675 |
writePromise.wait(waitScope); |
| 4676 |
|
| 4677 |
// Close the server side of the pipe so our read promise completes. |
| 4678 |
pipe.ends[0] = nullptr; |
| 4679 |
|
| 4680 |
auto responses = readPromise.wait(waitScope); |
| 4681 |
static constexpr kj::StringPtr RESPONSE = |
| 4682 |
"HTTP/1.1 200 OK\r\n" |
| 4683 |
"Transfer-Encoding: chunked\r\n" |
| 4684 |
"\r\n" |
| 4685 |
"0\r\n" |
| 4686 |
"\r\n"_kj; |
| 4687 |
KJ_EXPECT(kj::str(kj::delimited(kj::repeat(RESPONSE, 4), "")) == responses); |
| 4688 |
} |
| 4689 |
|
| 4690 |
KJ_TEST("HttpServer can suspend a request with no leftover") { |
| 4691 |
// This test verifies that if the request loop's read perfectly ends at the end of message |
| 4692 |
// headers, leaving no leftover section, we can still successfully suspend and resume. |
| 4693 |
|
| 4694 |
KJ_HTTP_TEST_SETUP_IO; |
| 4695 |
kj::TimerImpl timer(kj::origin<kj::TimePoint>()); |
| 4696 |
auto pipe = KJ_HTTP_TEST_CREATE_2PIPE; |
| 4697 |
|
| 4698 |
HttpHeaderTable table; |
| 4699 |
// This HttpService will not actually be used, because we're passing a factory in to |
| 4700 |
// listenHttpCleanDrain(). |
| 4701 |
HangingHttpService service; |
| 4702 |
HttpServer server(timer, table, service); |
| 4703 |
|
| 4704 |
kj::Maybe<HttpServer::SuspendedRequest> suspendedRequest; |
| 4705 |
|
| 4706 |
SuspendAfter factory; |
| 4707 |
|
| 4708 |
{ |
| 4709 |
factory.suspendAfter(0); |
| 4710 |
auto listenPromise = server.listenHttpCleanDrain(*pipe.ends[0], factory); |
| 4711 |
|
| 4712 |
static constexpr kj::StringPtr REQUEST_HEADERS = |
| 4713 |
"POST / HTTP/1.1\r\n" |
| 4714 |
"Transfer-Encoding: chunked\r\n" |
| 4715 |
"\r\n"_kj; |
| 4716 |
pipe.ends[1]->write(REQUEST_HEADERS.begin(), REQUEST_HEADERS.size()).wait(waitScope); |
| 4717 |
|
| 4718 |
// The listen promise is fulfilled with false. |
| 4719 |
KJ_EXPECT(listenPromise.poll(waitScope)); |
| 4720 |
KJ_EXPECT(!listenPromise.wait(waitScope)); |
| 4721 |
|
| 4722 |
// And we have a SuspendedRequest. We know that it has no leftover, because we only wrote |
| 4723 |
// headers, no body yet. |
| 4724 |
suspendedRequest = factory.getSuspended(); |
| 4725 |
KJ_EXPECT(suspendedRequest != nullptr); |
| 4726 |
} |
| 4727 |
|
| 4728 |
{ |
| 4729 |
factory.suspendAfter(1); |
| 4730 |
auto listenPromise = server.listenHttpCleanDrain( |
| 4731 |
*pipe.ends[0], factory, kj::mv(suspendedRequest)); |
| 4732 |
|
| 4733 |
auto drainPromise = kj::evalLast([&]() { |
| 4734 |
return server.drain(); |
| 4735 |
}); |
| 4736 |
|
| 4737 |
// We need to read the response for the HttpServer to drain. |
| 4738 |
auto readPromise = pipe.ends[1]->readAllText(); |
| 4739 |
|
| 4740 |
static constexpr kj::StringPtr REQUEST_BODY = |
| 4741 |
"6\r\n" |
| 4742 |
"foobar\r\n" |
| 4743 |
"0\r\n" |
| 4744 |
"\r\n"_kj; |
| 4745 |
pipe.ends[1]->write(REQUEST_BODY.begin(), REQUEST_BODY.size()).wait(waitScope); |
| 4746 |
|
| 4747 |
// Clean drain. |
| 4748 |
KJ_EXPECT(listenPromise.poll(waitScope)); |
| 4749 |
KJ_EXPECT(listenPromise.wait(waitScope)); |
| 4750 |
|
| 4751 |
drainPromise.wait(waitScope); |
| 4752 |
|
| 4753 |
// No SuspendedRequest. |
| 4754 |
suspendedRequest = factory.getSuspended(); |
| 4755 |
KJ_EXPECT(suspendedRequest == nullptr); |
| 4756 |
|
| 4757 |
// Close the server side of the pipe so our read promise completes. |
| 4758 |
pipe.ends[0] = nullptr; |
| 4759 |
|
| 4760 |
auto response = readPromise.wait(waitScope); |
| 4761 |
static constexpr kj::StringPtr RESPONSE = |
| 4762 |
"HTTP/1.1 200 OK\r\n" |
| 4763 |
"Transfer-Encoding: chunked\r\n" |
| 4764 |
"\r\n" |
| 4765 |
"0\r\n" |
| 4766 |
"\r\n"_kj; |
| 4767 |
KJ_EXPECT(RESPONSE == response); |
| 4768 |
} |
| 4769 |
} |
| 4770 |
|
| 4771 |
KJ_TEST("HttpServer::listenHttpCleanDrain() factory-created services outlive requests") { |
| 4772 |
// Test that the lifetimes of factory-created Own<HttpService> objects are handled correctly. |
| 4773 |
|
| 4774 |
KJ_HTTP_TEST_SETUP_IO; |
| 4775 |
kj::TimerImpl timer(kj::origin<kj::TimePoint>()); |
| 4776 |
auto pipe = KJ_HTTP_TEST_CREATE_2PIPE; |
| 4777 |
|
| 4778 |
HttpHeaderTable table; |
| 4779 |
// This HttpService will not actually be used, because we're passing a factory in to |
| 4780 |
// listenHttpCleanDrain(). |
| 4781 |
HangingHttpService service; |
| 4782 |
HttpServer server(timer, table, service); |
| 4783 |
|
| 4784 |
uint serviceCount = 0; |
| 4785 |
|
| 4786 |
// A factory which returns a service whose request() function responds asynchronously. |
| 4787 |
auto factory = [&](HttpServer::SuspendableRequest&) -> kj::Own<HttpService> { |
| 4788 |
class ServiceImpl final: public HttpService { |
| 4789 |
public: |
| 4790 |
explicit ServiceImpl(uint& serviceCount): serviceCount(++serviceCount) {} |
| 4791 |
~ServiceImpl() noexcept(false) { --serviceCount; } |
| 4792 |
KJ_DISALLOW_COPY_AND_MOVE(ServiceImpl); |
| 4793 |
|
| 4794 |
kj::Promise<void> request( |
| 4795 |
HttpMethod method, kj::StringPtr url, const HttpHeaders& headers, |
| 4796 |
kj::AsyncInputStream& requestBody, Response& response) override { |
| 4797 |
return evalLater([&serviceCount = serviceCount, &table = table, &requestBody, &response]() { |
| 4798 |
// This KJ_EXPECT here is the entire point of this test. |
| 4799 |
KJ_EXPECT(serviceCount == 1) |
| 4800 |
HttpHeaders responseHeaders(table); |
| 4801 |
response.send(200, "OK", responseHeaders); |
| 4802 |
return requestBody.readAllBytes().ignoreResult(); |
| 4803 |
}); |
| 4804 |
} |
| 4805 |
|
| 4806 |
private: |
| 4807 |
HttpHeaderTable table; |
| 4808 |
|
| 4809 |
uint& serviceCount; |
| 4810 |
}; |
| 4811 |
|
| 4812 |
return kj::heap<ServiceImpl>(serviceCount); |
| 4813 |
}; |
| 4814 |
|
| 4815 |
auto listenPromise = server.listenHttpCleanDrain(*pipe.ends[0], factory); |
| 4816 |
|
| 4817 |
static constexpr kj::StringPtr REQUEST = |
| 4818 |
"POST / HTTP/1.1\r\n" |
| 4819 |
"Content-Length: 6\r\n" |
| 4820 |
"\r\n" |
| 4821 |
"foobar"_kj; |
| 4822 |
pipe.ends[1]->write(REQUEST.begin(), REQUEST.size()).wait(waitScope); |
| 4823 |
|
| 4824 |
// We need to read the response for the HttpServer to drain. |
| 4825 |
auto readPromise = pipe.ends[1]->readAllText(); |
| 4826 |
|
| 4827 |
// http-socketpair-test quirk: we must drive the request loop past the point of receiving request |
| 4828 |
// headers so that our call to server.drain() doesn't prematurely cancel the request. |
| 4829 |
KJ_EXPECT(!listenPromise.poll(waitScope)); |
| 4830 |
|
| 4831 |
auto drainPromise = kj::evalLast([&]() { |
| 4832 |
return server.drain(); |
| 4833 |
}); |
| 4834 |
|
| 4835 |
// Clean drain. |
| 4836 |
KJ_EXPECT(listenPromise.poll(waitScope)); |
| 4837 |
KJ_EXPECT(listenPromise.wait(waitScope)); |
| 4838 |
|
| 4839 |
drainPromise.wait(waitScope); |
| 4840 |
|
| 4841 |
// Close the server side of the pipe so our read promise completes. |
| 4842 |
pipe.ends[0] = nullptr; |
| 4843 |
auto response = readPromise.wait(waitScope); |
| 4844 |
|
| 4845 |
static constexpr kj::StringPtr RESPONSE = |
| 4846 |
"HTTP/1.1 200 OK\r\n" |
| 4847 |
"Transfer-Encoding: chunked\r\n" |
| 4848 |
"\r\n" |
| 4849 |
"0\r\n" |
| 4850 |
"\r\n"_kj; |
| 4851 |
KJ_EXPECT(RESPONSE == response); |
| 4852 |
} |
| 4853 |
|
| 4854 |
// ----------------------------------------------------------------------------- |
| 4855 |
|
| 4856 |
KJ_TEST("newHttpService from HttpClient") { |
| 4857 |
auto PIPELINE_TESTS = pipelineTestCases(); |
| 4858 |
|
| 4859 |
KJ_HTTP_TEST_SETUP_IO; |
| 4860 |
kj::TimerImpl timer(kj::origin<kj::TimePoint>()); |
| 4861 |
auto frontPipe = KJ_HTTP_TEST_CREATE_2PIPE; |
| 4862 |
auto backPipe = KJ_HTTP_TEST_CREATE_2PIPE; |
| 4863 |
|
| 4864 |
kj::Promise<void> writeResponsesPromise = kj::READY_NOW; |
| 4865 |
for (auto& testCase: PIPELINE_TESTS) { |
| 4866 |
writeResponsesPromise = writeResponsesPromise |
| 4867 |
.then([&]() { |
| 4868 |
return expectRead(*backPipe.ends[1], testCase.request.raw); |
| 4869 |
}).then([&]() { |
| 4870 |
return backPipe.ends[1]->write(testCase.response.raw.begin(), testCase.response.raw.size()); |
| 4871 |
}); |
| 4872 |
} |
| 4873 |
|
| 4874 |
{ |
| 4875 |
HttpHeaderTable table; |
| 4876 |
auto backClient = newHttpClient(table, *backPipe.ends[0]); |
| 4877 |
auto frontService = newHttpService(*backClient); |
| 4878 |
HttpServer frontServer(timer, table, *frontService); |
| 4879 |
auto listenTask = frontServer.listenHttp(kj::mv(frontPipe.ends[1])); |
| 4880 |
|
| 4881 |
for (auto& testCase: PIPELINE_TESTS) { |
| 4882 |
KJ_CONTEXT(testCase.request.raw, testCase.response.raw); |
| 4883 |
|
| 4884 |
frontPipe.ends[0]->write(testCase.request.raw.begin(), testCase.request.raw.size()) |
| 4885 |
.wait(waitScope); |
| 4886 |
|
| 4887 |
expectRead(*frontPipe.ends[0], testCase.response.raw).wait(waitScope); |
| 4888 |
} |
| 4889 |
|
| 4890 |
frontPipe.ends[0]->shutdownWrite(); |
| 4891 |
listenTask.wait(waitScope); |
| 4892 |
} |
| 4893 |
|
| 4894 |
backPipe.ends[0]->shutdownWrite(); |
| 4895 |
writeResponsesPromise.wait(waitScope); |
| 4896 |
} |
| 4897 |
|
| 4898 |
KJ_TEST("newHttpService from HttpClient WebSockets") { |
| 4899 |
KJ_HTTP_TEST_SETUP_IO; |
| 4900 |
kj::TimerImpl timer(kj::origin<kj::TimePoint>()); |
| 4901 |
auto frontPipe = KJ_HTTP_TEST_CREATE_2PIPE; |
| 4902 |
auto backPipe = KJ_HTTP_TEST_CREATE_2PIPE; |
| 4903 |
|
| 4904 |
auto request = kj::str("GET /websocket", WEBSOCKET_REQUEST_HANDSHAKE); |
| 4905 |
auto writeResponsesPromise = expectRead(*backPipe.ends[1], request) |
| 4906 |
.then([&]() { return writeA(*backPipe.ends[1], asBytes(WEBSOCKET_RESPONSE_HANDSHAKE)); }) |
| 4907 |
.then([&]() { return writeA(*backPipe.ends[1], WEBSOCKET_FIRST_MESSAGE_INLINE); }) |
| 4908 |
.then([&]() { return expectRead(*backPipe.ends[1], WEBSOCKET_SEND_MESSAGE); }) |
| 4909 |
.then([&]() { return writeA(*backPipe.ends[1], WEBSOCKET_REPLY_MESSAGE); }) |
| 4910 |
.then([&]() { return expectRead(*backPipe.ends[1], WEBSOCKET_SEND_CLOSE); }) |
| 4911 |
.then([&]() { return writeA(*backPipe.ends[1], WEBSOCKET_REPLY_CLOSE); }) |
| 4912 |
.then([&]() { return expectEnd(*backPipe.ends[1]); }) |
| 4913 |
.then([&]() { backPipe.ends[1]->shutdownWrite(); }) |
| 4914 |
.eagerlyEvaluate([](kj::Exception&& e) { KJ_LOG(ERROR, e); }); |
| 4915 |
|
| 4916 |
{ |
| 4917 |
HttpHeaderTable table; |
| 4918 |
FakeEntropySource entropySource; |
| 4919 |
HttpClientSettings clientSettings; |
| 4920 |
clientSettings.entropySource = entropySource; |
| 4921 |
auto backClientStream = kj::mv(backPipe.ends[0]); |
| 4922 |
auto backClient = newHttpClient(table, *backClientStream, clientSettings); |
| 4923 |
auto frontService = newHttpService(*backClient); |
| 4924 |
HttpServer frontServer(timer, table, *frontService); |
| 4925 |
auto listenTask = frontServer.listenHttp(kj::mv(frontPipe.ends[1])); |
| 4926 |
|
| 4927 |
writeA(*frontPipe.ends[0], request.asBytes()).wait(waitScope); |
| 4928 |
expectRead(*frontPipe.ends[0], WEBSOCKET_RESPONSE_HANDSHAKE).wait(waitScope); |
| 4929 |
|
| 4930 |
expectRead(*frontPipe.ends[0], WEBSOCKET_FIRST_MESSAGE_INLINE).wait(waitScope); |
| 4931 |
writeA(*frontPipe.ends[0], WEBSOCKET_SEND_MESSAGE).wait(waitScope); |
| 4932 |
expectRead(*frontPipe.ends[0], WEBSOCKET_REPLY_MESSAGE).wait(waitScope); |
| 4933 |
writeA(*frontPipe.ends[0], WEBSOCKET_SEND_CLOSE).wait(waitScope); |
| 4934 |
expectRead(*frontPipe.ends[0], WEBSOCKET_REPLY_CLOSE).wait(waitScope); |
| 4935 |
|
| 4936 |
frontPipe.ends[0]->shutdownWrite(); |
| 4937 |
listenTask.wait(waitScope); |
| 4938 |
} |
| 4939 |
|
| 4940 |
writeResponsesPromise.wait(waitScope); |
| 4941 |
} |
| 4942 |
|
| 4943 |
KJ_TEST("newHttpService from HttpClient WebSockets disconnect") { |
| 4944 |
KJ_HTTP_TEST_SETUP_IO; |
| 4945 |
kj::TimerImpl timer(kj::origin<kj::TimePoint>()); |
| 4946 |
auto frontPipe = KJ_HTTP_TEST_CREATE_2PIPE; |
| 4947 |
auto backPipe = KJ_HTTP_TEST_CREATE_2PIPE; |
| 4948 |
|
| 4949 |
auto request = kj::str("GET /websocket", WEBSOCKET_REQUEST_HANDSHAKE); |
| 4950 |
auto writeResponsesPromise = expectRead(*backPipe.ends[1], request) |
| 4951 |
.then([&]() { return writeA(*backPipe.ends[1], asBytes(WEBSOCKET_RESPONSE_HANDSHAKE)); }) |
| 4952 |
.then([&]() { return writeA(*backPipe.ends[1], WEBSOCKET_FIRST_MESSAGE_INLINE); }) |
| 4953 |
.then([&]() { return expectRead(*backPipe.ends[1], WEBSOCKET_SEND_MESSAGE); }) |
| 4954 |
.then([&]() { backPipe.ends[1]->shutdownWrite(); }) |
| 4955 |
.eagerlyEvaluate([](kj::Exception&& e) { KJ_LOG(ERROR, e); }); |
| 4956 |
|
| 4957 |
{ |
| 4958 |
HttpHeaderTable table; |
| 4959 |
FakeEntropySource entropySource; |
| 4960 |
HttpClientSettings clientSettings; |
| 4961 |
clientSettings.entropySource = entropySource; |
| 4962 |
auto backClient = newHttpClient(table, *backPipe.ends[0], clientSettings); |
| 4963 |
auto frontService = newHttpService(*backClient); |
| 4964 |
HttpServer frontServer(timer, table, *frontService); |
| 4965 |
auto listenTask = frontServer.listenHttp(kj::mv(frontPipe.ends[1])); |
| 4966 |
|
| 4967 |
writeA(*frontPipe.ends[0], request.asBytes()).wait(waitScope); |
| 4968 |
expectRead(*frontPipe.ends[0], WEBSOCKET_RESPONSE_HANDSHAKE).wait(waitScope); |
| 4969 |
|
| 4970 |
expectRead(*frontPipe.ends[0], WEBSOCKET_FIRST_MESSAGE_INLINE).wait(waitScope); |
| 4971 |
writeA(*frontPipe.ends[0], WEBSOCKET_SEND_MESSAGE).wait(waitScope); |
| 4972 |
|
| 4973 |
KJ_EXPECT(frontPipe.ends[0]->readAllText().wait(waitScope) == ""); |
| 4974 |
|
| 4975 |
frontPipe.ends[0]->shutdownWrite(); |
| 4976 |
listenTask.wait(waitScope); |
| 4977 |
} |
| 4978 |
|
| 4979 |
writeResponsesPromise.wait(waitScope); |
| 4980 |
} |
| 4981 |
|
| 4982 |
// ----------------------------------------------------------------------------- |
| 4983 |
|
| 4984 |
KJ_TEST("newHttpClient from HttpService") { |
| 4985 |
auto PIPELINE_TESTS = pipelineTestCases(); |
| 4986 |
|
| 4987 |
KJ_HTTP_TEST_SETUP_IO; |
| 4988 |
kj::TimerImpl timer(kj::origin<kj::TimePoint>()); |
| 4989 |
|
| 4990 |
HttpHeaderTable table; |
| 4991 |
TestHttpService service(PIPELINE_TESTS, table); |
| 4992 |
auto client = newHttpClient(service); |
| 4993 |
|
| 4994 |
for (auto& testCase: PIPELINE_TESTS) { |
| 4995 |
testHttpClient(waitScope, table, *client, testCase); |
| 4996 |
} |
| 4997 |
} |
| 4998 |
|
| 4999 |
KJ_TEST("newHttpClient from HttpService WebSockets") { |
| 5000 |
KJ_HTTP_TEST_SETUP_IO; |
| 5001 |
kj::TimerImpl timer(kj::origin<kj::TimePoint>()); |
| 5002 |
auto pipe = KJ_HTTP_TEST_CREATE_2PIPE; |
| 5003 |
|
| 5004 |
HttpHeaderTable::Builder tableBuilder; |
| 5005 |
HttpHeaderId hMyHeader = tableBuilder.add("My-Header"); |
| 5006 |
auto headerTable = tableBuilder.build(); |
| 5007 |
TestWebSocketService service(*headerTable, hMyHeader); |
| 5008 |
auto client = newHttpClient(service); |
| 5009 |
|
| 5010 |
testWebSocketClient(waitScope, *headerTable, hMyHeader, *client); |
| 5011 |
} |
| 5012 |
|
| 5013 |
KJ_TEST("adapted client/server propagates request exceptions like non-adapted client") { |
| 5014 |
KJ_HTTP_TEST_SETUP_IO; |
| 5015 |
|
| 5016 |
HttpHeaderTable table; |
| 5017 |
HttpHeaders headers(table); |
| 5018 |
|
| 5019 |
class FailingHttpClient final: public HttpClient { |
| 5020 |
public: |
| 5021 |
Request request( |
| 5022 |
HttpMethod method, kj::StringPtr url, const HttpHeaders& headers, |
| 5023 |
kj::Maybe<uint64_t> expectedBodySize = nullptr) override { |
| 5024 |
KJ_FAIL_ASSERT("request_fail"); |
| 5025 |
} |
| 5026 |
|
| 5027 |
kj::Promise<WebSocketResponse> openWebSocket( |
| 5028 |
kj::StringPtr url, const HttpHeaders& headers) override { |
| 5029 |
KJ_FAIL_ASSERT("websocket_fail"); |
| 5030 |
} |
| 5031 |
}; |
| 5032 |
|
| 5033 |
auto rawClient = kj::heap<FailingHttpClient>(); |
| 5034 |
|
| 5035 |
auto innerClient = kj::heap<FailingHttpClient>(); |
| 5036 |
auto adaptedService = kj::newHttpService(*innerClient).attach(kj::mv(innerClient)); |
| 5037 |
auto adaptedClient = kj::newHttpClient(*adaptedService).attach(kj::mv(adaptedService)); |
| 5038 |
|
| 5039 |
KJ_EXPECT_THROW_MESSAGE("request_fail", rawClient->request(HttpMethod::POST, "/"_kj, headers)); |
| 5040 |
KJ_EXPECT_THROW_MESSAGE("request_fail", adaptedClient->request(HttpMethod::POST, "/"_kj, headers)); |
| 5041 |
|
| 5042 |
KJ_EXPECT_THROW_MESSAGE("websocket_fail", rawClient->openWebSocket("/"_kj, headers)); |
| 5043 |
KJ_EXPECT_THROW_MESSAGE("websocket_fail", adaptedClient->openWebSocket("/"_kj, headers)); |
| 5044 |
} |
| 5045 |
|
| 5046 |
class DelayedCompletionHttpService final: public HttpService { |
| 5047 |
public: |
| 5048 |
DelayedCompletionHttpService(HttpHeaderTable& table, kj::Maybe<uint64_t> expectedLength) |
| 5049 |
: table(table), expectedLength(expectedLength) {} |
| 5050 |
|
| 5051 |
kj::Promise<void> request( |
| 5052 |
HttpMethod method, kj::StringPtr url, const HttpHeaders& headers, |
| 5053 |
kj::AsyncInputStream& requestBody, Response& response) override { |
| 5054 |
auto stream = response.send(200, "OK", HttpHeaders(table), expectedLength); |
| 5055 |
auto promise = stream->write("foo", 3); |
| 5056 |
return promise.attach(kj::mv(stream)).then([this]() { |
| 5057 |
return kj::mv(paf.promise); |
| 5058 |
}); |
| 5059 |
} |
| 5060 |
|
| 5061 |
kj::PromiseFulfiller<void>& getFulfiller() { return *paf.fulfiller; } |
| 5062 |
|
| 5063 |
private: |
| 5064 |
HttpHeaderTable& table; |
| 5065 |
kj::Maybe<uint64_t> expectedLength; |
| 5066 |
kj::PromiseFulfillerPair<void> paf = kj::newPromiseAndFulfiller<void>(); |
| 5067 |
}; |
| 5068 |
|
| 5069 |
void doDelayedCompletionTest(bool exception, kj::Maybe<uint64_t> expectedLength) noexcept { |
| 5070 |
KJ_HTTP_TEST_SETUP_IO; |
| 5071 |
|
| 5072 |
HttpHeaderTable table; |
| 5073 |
|
| 5074 |
DelayedCompletionHttpService service(table, expectedLength); |
| 5075 |
auto client = newHttpClient(service); |
| 5076 |
|
| 5077 |
auto resp = client->request(HttpMethod::GET, "/", HttpHeaders(table), uint64_t(0)) |
| 5078 |
.response.wait(waitScope); |
| 5079 |
KJ_EXPECT(resp.statusCode == 200); |
| 5080 |
|
| 5081 |
// Read "foo" from the response body: works |
| 5082 |
char buffer[16]; |
| 5083 |
KJ_ASSERT(resp.body->tryRead(buffer, 1, sizeof(buffer)).wait(waitScope) == 3); |
| 5084 |
buffer[3] = '\0'; |
| 5085 |
KJ_EXPECT(buffer == "foo"_kj); |
| 5086 |
|
| 5087 |
// But reading any more hangs. |
| 5088 |
auto promise = resp.body->tryRead(buffer, 1, sizeof(buffer)); |
| 5089 |
|
| 5090 |
KJ_EXPECT(!promise.poll(waitScope)); |
| 5091 |
|
| 5092 |
// Until we cause the service to return. |
| 5093 |
if (exception) { |
| 5094 |
service.getFulfiller().reject(KJ_EXCEPTION(FAILED, "service-side failure")); |
| 5095 |
} else { |
| 5096 |
service.getFulfiller().fulfill(); |
| 5097 |
} |
| 5098 |
|
| 5099 |
KJ_ASSERT(promise.poll(waitScope)); |
| 5100 |
|
| 5101 |
if (exception) { |
| 5102 |
KJ_EXPECT_THROW_MESSAGE("service-side failure", promise.wait(waitScope)); |
| 5103 |
} else { |
| 5104 |
promise.wait(waitScope); |
| 5105 |
} |
| 5106 |
}; |
| 5107 |
|
| 5108 |
KJ_TEST("adapted client waits for service to complete before returning EOF on response stream") { |
| 5109 |
doDelayedCompletionTest(false, uint64_t(3)); |
| 5110 |
} |
| 5111 |
|
| 5112 |
KJ_TEST("adapted client waits for service to complete before returning EOF on chunked response") { |
| 5113 |
doDelayedCompletionTest(false, nullptr); |
| 5114 |
} |
| 5115 |
|
| 5116 |
KJ_TEST("adapted client propagates throw from service after complete response body sent") { |
| 5117 |
doDelayedCompletionTest(true, uint64_t(3)); |
| 5118 |
} |
| 5119 |
|
| 5120 |
KJ_TEST("adapted client propagates throw from service after incomplete response body sent") { |
| 5121 |
doDelayedCompletionTest(true, uint64_t(6)); |
| 5122 |
} |
| 5123 |
|
| 5124 |
KJ_TEST("adapted client propagates throw from service after chunked response body sent") { |
| 5125 |
doDelayedCompletionTest(true, nullptr); |
| 5126 |
} |
| 5127 |
|
| 5128 |
class DelayedCompletionWebSocketHttpService final: public HttpService { |
| 5129 |
public: |
| 5130 |
DelayedCompletionWebSocketHttpService(HttpHeaderTable& table, bool closeUpstreamFirst) |
| 5131 |
: table(table), closeUpstreamFirst(closeUpstreamFirst) {} |
| 5132 |
|
| 5133 |
kj::Promise<void> request( |
| 5134 |
HttpMethod method, kj::StringPtr url, const HttpHeaders& headers, |
| 5135 |
kj::AsyncInputStream& requestBody, Response& response) override { |
| 5136 |
KJ_ASSERT(headers.isWebSocket()); |
| 5137 |
|
| 5138 |
auto ws = response.acceptWebSocket(HttpHeaders(table)); |
| 5139 |
kj::Promise<void> promise = kj::READY_NOW; |
| 5140 |
if (closeUpstreamFirst) { |
| 5141 |
// Wait for a close message from the client before starting. |
| 5142 |
promise = promise.then([&ws = *ws]() { return ws.receive(); }).ignoreResult(); |
| 5143 |
} |
| 5144 |
promise = promise |
| 5145 |
.then([&ws = *ws]() { return ws.send("foo"_kj); }) |
| 5146 |
.then([&ws = *ws]() { return ws.close(1234, "closed"_kj); }); |
| 5147 |
if (!closeUpstreamFirst) { |
| 5148 |
// Wait for a close message from the client at the end. |
| 5149 |
promise = promise.then([&ws = *ws]() { return ws.receive(); }).ignoreResult(); |
| 5150 |
} |
| 5151 |
return promise.attach(kj::mv(ws)).then([this]() { |
| 5152 |
return kj::mv(paf.promise); |
| 5153 |
}); |
| 5154 |
} |
| 5155 |
|
| 5156 |
kj::PromiseFulfiller<void>& getFulfiller() { return *paf.fulfiller; } |
| 5157 |
|
| 5158 |
private: |
| 5159 |
HttpHeaderTable& table; |
| 5160 |
bool closeUpstreamFirst; |
| 5161 |
kj::PromiseFulfillerPair<void> paf = kj::newPromiseAndFulfiller<void>(); |
| 5162 |
}; |
| 5163 |
|
| 5164 |
void doDelayedCompletionWebSocketTest(bool exception, bool closeUpstreamFirst) noexcept { |
| 5165 |
KJ_HTTP_TEST_SETUP_IO; |
| 5166 |
|
| 5167 |
HttpHeaderTable table; |
| 5168 |
|
| 5169 |
DelayedCompletionWebSocketHttpService service(table, closeUpstreamFirst); |
| 5170 |
auto client = newHttpClient(service); |
| 5171 |
|
| 5172 |
auto resp = client->openWebSocket("/", HttpHeaders(table)).wait(waitScope); |
| 5173 |
auto ws = kj::mv(KJ_ASSERT_NONNULL(resp.webSocketOrBody.tryGet<kj::Own<WebSocket>>())); |
| 5174 |
|
| 5175 |
if (closeUpstreamFirst) { |
| 5176 |
// Send "close" immediately. |
| 5177 |
ws->close(1234, "whatever"_kj).wait(waitScope); |
| 5178 |
} |
| 5179 |
|
| 5180 |
// Read "foo" from the WebSocket: works |
| 5181 |
{ |
| 5182 |
auto msg = ws->receive().wait(waitScope); |
| 5183 |
KJ_ASSERT(msg.is<kj::String>()); |
| 5184 |
KJ_ASSERT(msg.get<kj::String>() == "foo"); |
| 5185 |
} |
| 5186 |
|
| 5187 |
kj::Promise<void> promise = nullptr; |
| 5188 |
if (closeUpstreamFirst) { |
| 5189 |
// Receiving the close hangs. |
| 5190 |
promise = ws->receive() |
| 5191 |
.then([](WebSocket::Message&& msg) { KJ_EXPECT(msg.is<WebSocket::Close>()); }); |
| 5192 |
} else { |
| 5193 |
auto msg = ws->receive().wait(waitScope); |
| 5194 |
KJ_ASSERT(msg.is<WebSocket::Close>()); |
| 5195 |
|
| 5196 |
// Sending a close hangs. |
| 5197 |
promise = ws->close(1234, "whatever"_kj); |
| 5198 |
} |
| 5199 |
KJ_EXPECT(!promise.poll(waitScope)); |
| 5200 |
|
| 5201 |
// Until we cause the service to return. |
| 5202 |
if (exception) { |
| 5203 |
service.getFulfiller().reject(KJ_EXCEPTION(FAILED, "service-side failure")); |
| 5204 |
} else { |
| 5205 |
service.getFulfiller().fulfill(); |
| 5206 |
} |
| 5207 |
|
| 5208 |
KJ_ASSERT(promise.poll(waitScope)); |
| 5209 |
|
| 5210 |
if (exception) { |
| 5211 |
KJ_EXPECT_THROW_RECOVERABLE_MESSAGE("service-side failure", promise.wait(waitScope)); |
| 5212 |
} else { |
| 5213 |
promise.wait(waitScope); |
| 5214 |
} |
| 5215 |
}; |
| 5216 |
|
| 5217 |
KJ_TEST("adapted client waits for service to complete before completing upstream close on WebSocket") { |
| 5218 |
doDelayedCompletionWebSocketTest(false, false); |
| 5219 |
} |
| 5220 |
|
| 5221 |
KJ_TEST("adapted client waits for service to complete before returning downstream close on WebSocket") { |
| 5222 |
doDelayedCompletionWebSocketTest(false, true); |
| 5223 |
} |
| 5224 |
|
| 5225 |
KJ_TEST("adapted client propagates throw from service after WebSocket upstream close sent") { |
| 5226 |
doDelayedCompletionWebSocketTest(true, false); |
| 5227 |
} |
| 5228 |
|
| 5229 |
KJ_TEST("adapted client propagates throw from service after WebSocket downstream close sent") { |
| 5230 |
doDelayedCompletionWebSocketTest(true, true); |
| 5231 |
} |
| 5232 |
|
| 5233 |
// ----------------------------------------------------------------------------- |
| 5234 |
|
| 5235 |
class CountingIoStream final: public kj::AsyncIoStream { |
| 5236 |
// An AsyncIoStream wrapper which decrements a counter when destroyed (allowing us to count how |
| 5237 |
// many connections are open). |
| 5238 |
|
| 5239 |
public: |
| 5240 |
CountingIoStream(kj::Own<kj::AsyncIoStream> inner, uint& count) |
| 5241 |
: inner(kj::mv(inner)), count(count) {} |
| 5242 |
~CountingIoStream() noexcept(false) { |
| 5243 |
--count; |
| 5244 |
} |
| 5245 |
|
| 5246 |
kj::Promise<size_t> read(void* buffer, size_t minBytes, size_t maxBytes) override { |
| 5247 |
return inner->read(buffer, minBytes, maxBytes); |
| 5248 |
} |
| 5249 |
kj::Promise<size_t> tryRead(void* buffer, size_t minBytes, size_t maxBytes) override { |
| 5250 |
return inner->tryRead(buffer, minBytes, maxBytes); |
| 5251 |
} |
| 5252 |
kj::Maybe<uint64_t> tryGetLength() override { |
| 5253 |
return inner->tryGetLength();; |
| 5254 |
} |
| 5255 |
kj::Promise<uint64_t> pumpTo(kj::AsyncOutputStream& output, uint64_t amount) override { |
| 5256 |
return inner->pumpTo(output, amount); |
| 5257 |
} |
| 5258 |
kj::Promise<void> write(const void* buffer, size_t size) override { |
| 5259 |
return inner->write(buffer, size); |
| 5260 |
} |
| 5261 |
kj::Promise<void> write(kj::ArrayPtr<const kj::ArrayPtr<const byte>> pieces) override { |
| 5262 |
return inner->write(pieces); |
| 5263 |
} |
| 5264 |
kj::Maybe<kj::Promise<uint64_t>> tryPumpFrom( |
| 5265 |
kj::AsyncInputStream& input, uint64_t amount = kj::maxValue) override { |
| 5266 |
return inner->tryPumpFrom(input, amount); |
| 5267 |
} |
| 5268 |
Promise<void> whenWriteDisconnected() override { |
| 5269 |
return inner->whenWriteDisconnected(); |
| 5270 |
} |
| 5271 |
void shutdownWrite() override { |
| 5272 |
return inner->shutdownWrite(); |
| 5273 |
} |
| 5274 |
void abortRead() override { |
| 5275 |
return inner->abortRead(); |
| 5276 |
} |
| 5277 |
|
| 5278 |
public: |
| 5279 |
kj::Own<AsyncIoStream> inner; |
| 5280 |
uint& count; |
| 5281 |
}; |
| 5282 |
|
| 5283 |
class CountingNetworkAddress final: public kj::NetworkAddress { |
| 5284 |
public: |
| 5285 |
CountingNetworkAddress(kj::NetworkAddress& inner, uint& count, uint& cumulative) |
| 5286 |
: inner(inner), count(count), addrCount(ownAddrCount), cumulative(cumulative) {} |
| 5287 |
CountingNetworkAddress(kj::Own<kj::NetworkAddress> inner, uint& count, uint& addrCount) |
| 5288 |
: inner(*inner), ownInner(kj::mv(inner)), count(count), addrCount(addrCount), |
| 5289 |
cumulative(ownCumulative) {} |
| 5290 |
~CountingNetworkAddress() noexcept(false) { |
| 5291 |
--addrCount; |
| 5292 |
} |
| 5293 |
|
| 5294 |
kj::Promise<kj::Own<kj::AsyncIoStream>> connect() override { |
| 5295 |
++count; |
| 5296 |
++cumulative; |
| 5297 |
return inner.connect() |
| 5298 |
.then([this](kj::Own<kj::AsyncIoStream> stream) -> kj::Own<kj::AsyncIoStream> { |
| 5299 |
return kj::heap<CountingIoStream>(kj::mv(stream), count); |
| 5300 |
}); |
| 5301 |
} |
| 5302 |
|
| 5303 |
kj::Own<kj::ConnectionReceiver> listen() override { KJ_UNIMPLEMENTED("test"); } |
| 5304 |
kj::Own<kj::NetworkAddress> clone() override { KJ_UNIMPLEMENTED("test"); } |
| 5305 |
kj::String toString() override { KJ_UNIMPLEMENTED("test"); } |
| 5306 |
|
| 5307 |
private: |
| 5308 |
kj::NetworkAddress& inner; |
| 5309 |
kj::Own<kj::NetworkAddress> ownInner; |
| 5310 |
uint& count; |
| 5311 |
uint ownAddrCount = 1; |
| 5312 |
uint& addrCount; |
| 5313 |
uint ownCumulative = 0; |
| 5314 |
uint& cumulative; |
| 5315 |
}; |
| 5316 |
|
| 5317 |
class ConnectionCountingNetwork final: public kj::Network { |
| 5318 |
public: |
| 5319 |
ConnectionCountingNetwork(kj::Network& inner, uint& count, uint& addrCount) |
| 5320 |
: inner(inner), count(count), addrCount(addrCount) {} |
| 5321 |
|
| 5322 |
Promise<Own<NetworkAddress>> parseAddress(StringPtr addr, uint portHint = 0) override { |
| 5323 |
++addrCount; |
| 5324 |
return inner.parseAddress(addr, portHint) |
| 5325 |
.then([this](Own<NetworkAddress>&& addr) -> Own<NetworkAddress> { |
| 5326 |
return kj::heap<CountingNetworkAddress>(kj::mv(addr), count, addrCount); |
| 5327 |
}); |
| 5328 |
} |
| 5329 |
Own<NetworkAddress> getSockaddr(const void* sockaddr, uint len) override { |
| 5330 |
KJ_UNIMPLEMENTED("test"); |
| 5331 |
} |
| 5332 |
Own<Network> restrictPeers( |
| 5333 |
kj::ArrayPtr<const kj::StringPtr> allow, |
| 5334 |
kj::ArrayPtr<const kj::StringPtr> deny = nullptr) override { |
| 5335 |
KJ_UNIMPLEMENTED("test"); |
| 5336 |
} |
| 5337 |
|
| 5338 |
private: |
| 5339 |
kj::Network& inner; |
| 5340 |
uint& count; |
| 5341 |
uint& addrCount; |
| 5342 |
}; |
| 5343 |
|
| 5344 |
class DummyService final: public HttpService { |
| 5345 |
public: |
| 5346 |
DummyService(HttpHeaderTable& headerTable): headerTable(headerTable) {} |
| 5347 |
|
| 5348 |
kj::Promise<void> request( |
| 5349 |
HttpMethod method, kj::StringPtr url, const HttpHeaders& headers, |
| 5350 |
kj::AsyncInputStream& requestBody, Response& response) override { |
| 5351 |
if (!headers.isWebSocket()) { |
| 5352 |
if (url == "/throw") { |
| 5353 |
return KJ_EXCEPTION(FAILED, "client requested failure"); |
| 5354 |
} |
| 5355 |
|
| 5356 |
auto body = kj::str(headers.get(HttpHeaderId::HOST).orDefault("null"), ":", url); |
| 5357 |
auto stream = response.send(200, "OK", HttpHeaders(headerTable), body.size()); |
| 5358 |
auto promises = kj::heapArrayBuilder<kj::Promise<void>>(2); |
| 5359 |
promises.add(stream->write(body.begin(), body.size())); |
| 5360 |
promises.add(requestBody.readAllBytes().ignoreResult()); |
| 5361 |
return kj::joinPromises(promises.finish()).attach(kj::mv(stream), kj::mv(body)); |
| 5362 |
} else { |
| 5363 |
auto ws = response.acceptWebSocket(HttpHeaders(headerTable)); |
| 5364 |
auto body = kj::str(headers.get(HttpHeaderId::HOST).orDefault("null"), ":", url); |
| 5365 |
auto sendPromise = ws->send(body); |
| 5366 |
|
| 5367 |
auto promises = kj::heapArrayBuilder<kj::Promise<void>>(2); |
| 5368 |
promises.add(sendPromise.attach(kj::mv(body))); |
| 5369 |
promises.add(ws->receive().ignoreResult()); |
| 5370 |
return kj::joinPromises(promises.finish()).attach(kj::mv(ws)); |
| 5371 |
} |
| 5372 |
} |
| 5373 |
|
| 5374 |
private: |
| 5375 |
HttpHeaderTable& headerTable; |
| 5376 |
}; |
| 5377 |
|
| 5378 |
KJ_TEST("HttpClient connection management") { |
| 5379 |
KJ_HTTP_TEST_SETUP_IO; |
| 5380 |
KJ_HTTP_TEST_SETUP_LOOPBACK_LISTENER_AND_ADDR; |
| 5381 |
|
| 5382 |
kj::TimerImpl serverTimer(kj::origin<kj::TimePoint>()); |
| 5383 |
kj::TimerImpl clientTimer(kj::origin<kj::TimePoint>()); |
| 5384 |
HttpHeaderTable headerTable; |
| 5385 |
|
| 5386 |
DummyService service(headerTable); |
| 5387 |
HttpServerSettings serverSettings; |
| 5388 |
HttpServer server(serverTimer, headerTable, service, serverSettings); |
| 5389 |
auto listenTask = server.listenHttp(*listener); |
| 5390 |
|
| 5391 |
uint count = 0; |
| 5392 |
uint cumulative = 0; |
| 5393 |
CountingNetworkAddress countingAddr(*addr, count, cumulative); |
| 5394 |
|
| 5395 |
FakeEntropySource entropySource; |
| 5396 |
HttpClientSettings clientSettings; |
| 5397 |
clientSettings.entropySource = entropySource; |
| 5398 |
auto client = newHttpClient(clientTimer, headerTable, countingAddr, clientSettings); |
| 5399 |
|
| 5400 |
KJ_EXPECT(count == 0); |
| 5401 |
KJ_EXPECT(cumulative == 0); |
| 5402 |
|
| 5403 |
uint i = 0; |
| 5404 |
auto doRequest = [&]() { |
| 5405 |
uint n = i++; |
| 5406 |
return client->request(HttpMethod::GET, kj::str("/", n), HttpHeaders(headerTable)).response |
| 5407 |
.then([](HttpClient::Response&& response) { |
| 5408 |
auto promise = response.body->readAllText(); |
| 5409 |
return promise.attach(kj::mv(response.body)); |
| 5410 |
}).then([n](kj::String body) { |
| 5411 |
KJ_EXPECT(body == kj::str("null:/", n)); |
| 5412 |
}); |
| 5413 |
}; |
| 5414 |
|
| 5415 |
// We can do several requests in a row and only have one connection. |
| 5416 |
doRequest().wait(waitScope); |
| 5417 |
doRequest().wait(waitScope); |
| 5418 |
doRequest().wait(waitScope); |
| 5419 |
KJ_EXPECT(count == 1); |
| 5420 |
KJ_EXPECT(cumulative == 1); |
| 5421 |
|
| 5422 |
// But if we do two in parallel, we'll end up with two connections. |
| 5423 |
auto req1 = doRequest(); |
| 5424 |
auto req2 = doRequest(); |
| 5425 |
req1.wait(waitScope); |
| 5426 |
req2.wait(waitScope); |
| 5427 |
KJ_EXPECT(count == 2); |
| 5428 |
KJ_EXPECT(cumulative == 2); |
| 5429 |
|
| 5430 |
// We can reuse after a POST, provided we write the whole POST body properly. |
| 5431 |
{ |
| 5432 |
auto req = client->request( |
| 5433 |
HttpMethod::POST, kj::str("/foo"), HttpHeaders(headerTable), size_t(6)); |
| 5434 |
req.body->write("foobar", 6).wait(waitScope); |
| 5435 |
req.response.wait(waitScope).body->readAllBytes().wait(waitScope); |
| 5436 |
} |
| 5437 |
KJ_EXPECT(count == 2); |
| 5438 |
KJ_EXPECT(cumulative == 2); |
| 5439 |
doRequest().wait(waitScope); |
| 5440 |
KJ_EXPECT(count == 2); |
| 5441 |
KJ_EXPECT(cumulative == 2); |
| 5442 |
|
| 5443 |
// Advance time for half the timeout, then exercise one of the connections. |
| 5444 |
clientTimer.advanceTo(clientTimer.now() + clientSettings.idleTimeout / 2); |
| 5445 |
doRequest().wait(waitScope); |
| 5446 |
doRequest().wait(waitScope); |
| 5447 |
waitScope.poll(); |
| 5448 |
KJ_EXPECT(count == 2); |
| 5449 |
KJ_EXPECT(cumulative == 2); |
| 5450 |
|
| 5451 |
// Advance time past when the other connection should time out. It should be dropped. |
| 5452 |
clientTimer.advanceTo(clientTimer.now() + clientSettings.idleTimeout * 3 / 4); |
| 5453 |
waitScope.poll(); |
| 5454 |
KJ_EXPECT(count == 1); |
| 5455 |
KJ_EXPECT(cumulative == 2); |
| 5456 |
|
| 5457 |
// Wait for the other to drop. |
| 5458 |
clientTimer.advanceTo(clientTimer.now() + clientSettings.idleTimeout / 2); |
| 5459 |
waitScope.poll(); |
| 5460 |
KJ_EXPECT(count == 0); |
| 5461 |
KJ_EXPECT(cumulative == 2); |
| 5462 |
|
| 5463 |
// New request creates a new connection again. |
| 5464 |
doRequest().wait(waitScope); |
| 5465 |
KJ_EXPECT(count == 1); |
| 5466 |
KJ_EXPECT(cumulative == 3); |
| 5467 |
|
| 5468 |
// WebSocket connections are not reused. |
| 5469 |
client->openWebSocket(kj::str("/websocket"), HttpHeaders(headerTable)) |
| 5470 |
.wait(waitScope); |
| 5471 |
KJ_EXPECT(count == 0); |
| 5472 |
KJ_EXPECT(cumulative == 3); |
| 5473 |
|
| 5474 |
// Errored connections are not reused. |
| 5475 |
doRequest().wait(waitScope); |
| 5476 |
KJ_EXPECT(count == 1); |
| 5477 |
KJ_EXPECT(cumulative == 4); |
| 5478 |
client->request(HttpMethod::GET, kj::str("/throw"), HttpHeaders(headerTable)).response |
| 5479 |
.wait(waitScope).body->readAllBytes().wait(waitScope); |
| 5480 |
KJ_EXPECT(count == 0); |
| 5481 |
KJ_EXPECT(cumulative == 4); |
| 5482 |
|
| 5483 |
// Connections where we failed to read the full response body are not reused. |
| 5484 |
doRequest().wait(waitScope); |
| 5485 |
KJ_EXPECT(count == 1); |
| 5486 |
KJ_EXPECT(cumulative == 5); |
| 5487 |
client->request(HttpMethod::GET, kj::str("/foo"), HttpHeaders(headerTable)).response |
| 5488 |
.wait(waitScope); |
| 5489 |
KJ_EXPECT(count == 0); |
| 5490 |
KJ_EXPECT(cumulative == 5); |
| 5491 |
|
| 5492 |
// Connections where we didn't even wait for the response headers are not reused. |
| 5493 |
doRequest().wait(waitScope); |
| 5494 |
KJ_EXPECT(count == 1); |
| 5495 |
KJ_EXPECT(cumulative == 6); |
| 5496 |
client->request(HttpMethod::GET, kj::str("/foo"), HttpHeaders(headerTable)); |
| 5497 |
KJ_EXPECT(count == 0); |
| 5498 |
KJ_EXPECT(cumulative == 6); |
| 5499 |
|
| 5500 |
// Connections where we failed to write the full request body are not reused. |
| 5501 |
doRequest().wait(waitScope); |
| 5502 |
KJ_EXPECT(count == 1); |
| 5503 |
KJ_EXPECT(cumulative == 7); |
| 5504 |
client->request(HttpMethod::POST, kj::str("/foo"), HttpHeaders(headerTable), size_t(6)).response |
| 5505 |
.wait(waitScope).body->readAllBytes().wait(waitScope); |
| 5506 |
KJ_EXPECT(count == 0); |
| 5507 |
KJ_EXPECT(cumulative == 7); |
| 5508 |
|
| 5509 |
// If the server times out the connection, we figure it out on the client. |
| 5510 |
doRequest().wait(waitScope); |
| 5511 |
|
| 5512 |
// TODO(someday): Figure out why the following poll is necessary for the test to pass on Windows |
| 5513 |
// and Mac. Without it, it seems that the request's connection never starts, so the |
| 5514 |
// subsequent advanceTo() does not actually time out the connection. |
| 5515 |
waitScope.poll(); |
| 5516 |
|
| 5517 |
KJ_EXPECT(count == 1); |
| 5518 |
KJ_EXPECT(cumulative == 8); |
| 5519 |
serverTimer.advanceTo(serverTimer.now() + serverSettings.pipelineTimeout * 2); |
| 5520 |
waitScope.poll(); |
| 5521 |
KJ_EXPECT(count == 0); |
| 5522 |
KJ_EXPECT(cumulative == 8); |
| 5523 |
|
| 5524 |
// Can still make requests. |
| 5525 |
doRequest().wait(waitScope); |
| 5526 |
KJ_EXPECT(count == 1); |
| 5527 |
KJ_EXPECT(cumulative == 9); |
| 5528 |
} |
| 5529 |
|
| 5530 |
KJ_TEST("HttpClient disable connection reuse") { |
| 5531 |
KJ_HTTP_TEST_SETUP_IO; |
| 5532 |
KJ_HTTP_TEST_SETUP_LOOPBACK_LISTENER_AND_ADDR; |
| 5533 |
|
| 5534 |
kj::TimerImpl serverTimer(kj::origin<kj::TimePoint>()); |
| 5535 |
kj::TimerImpl clientTimer(kj::origin<kj::TimePoint>()); |
| 5536 |
HttpHeaderTable headerTable; |
| 5537 |
|
| 5538 |
DummyService service(headerTable); |
| 5539 |
HttpServerSettings serverSettings; |
| 5540 |
HttpServer server(serverTimer, headerTable, service, serverSettings); |
| 5541 |
auto listenTask = server.listenHttp(*listener); |
| 5542 |
|
| 5543 |
uint count = 0; |
| 5544 |
uint cumulative = 0; |
| 5545 |
CountingNetworkAddress countingAddr(*addr, count, cumulative); |
| 5546 |
|
| 5547 |
FakeEntropySource entropySource; |
| 5548 |
HttpClientSettings clientSettings; |
| 5549 |
clientSettings.entropySource = entropySource; |
| 5550 |
clientSettings.idleTimeout = 0 * kj::SECONDS; |
| 5551 |
auto client = newHttpClient(clientTimer, headerTable, countingAddr, clientSettings); |
| 5552 |
|
| 5553 |
KJ_EXPECT(count == 0); |
| 5554 |
KJ_EXPECT(cumulative == 0); |
| 5555 |
|
| 5556 |
uint i = 0; |
| 5557 |
auto doRequest = [&]() { |
| 5558 |
uint n = i++; |
| 5559 |
return client->request(HttpMethod::GET, kj::str("/", n), HttpHeaders(headerTable)).response |
| 5560 |
.then([](HttpClient::Response&& response) { |
| 5561 |
auto promise = response.body->readAllText(); |
| 5562 |
return promise.attach(kj::mv(response.body)); |
| 5563 |
}).then([n](kj::String body) { |
| 5564 |
KJ_EXPECT(body == kj::str("null:/", n)); |
| 5565 |
}); |
| 5566 |
}; |
| 5567 |
|
| 5568 |
// Each serial request gets its own connection. |
| 5569 |
doRequest().wait(waitScope); |
| 5570 |
doRequest().wait(waitScope); |
| 5571 |
doRequest().wait(waitScope); |
| 5572 |
KJ_EXPECT(count == 0); |
| 5573 |
KJ_EXPECT(cumulative == 3); |
| 5574 |
|
| 5575 |
// Each parallel request gets its own connection. |
| 5576 |
auto req1 = doRequest(); |
| 5577 |
auto req2 = doRequest(); |
| 5578 |
req1.wait(waitScope); |
| 5579 |
req2.wait(waitScope); |
| 5580 |
KJ_EXPECT(count == 0); |
| 5581 |
KJ_EXPECT(cumulative == 5); |
| 5582 |
} |
| 5583 |
|
| 5584 |
KJ_TEST("HttpClient concurrency limiting") { |
| 5585 |
#if KJ_HTTP_TEST_USE_OS_PIPE && !__linux__ |
| 5586 |
// On Windows and Mac, OS event delivery is not always immediate, and that seems to make this |
| 5587 |
// test flakey. On Linux, events are always immediately delivered. For now, we compile the test |
| 5588 |
// but we don't run it outside of Linux. We do run the in-memory-pipes version on all OSs since |
| 5589 |
// that mode shouldn't depend on kernel behavior at all. |
| 5590 |
return; |
| 5591 |
#endif |
| 5592 |
|
| 5593 |
KJ_HTTP_TEST_SETUP_IO; |
| 5594 |
KJ_HTTP_TEST_SETUP_LOOPBACK_LISTENER_AND_ADDR; |
| 5595 |
|
| 5596 |
kj::TimerImpl serverTimer(kj::origin<kj::TimePoint>()); |
| 5597 |
kj::TimerImpl clientTimer(kj::origin<kj::TimePoint>()); |
| 5598 |
HttpHeaderTable headerTable; |
| 5599 |
|
| 5600 |
DummyService service(headerTable); |
| 5601 |
HttpServerSettings serverSettings; |
| 5602 |
HttpServer server(serverTimer, headerTable, service, serverSettings); |
| 5603 |
auto listenTask = server.listenHttp(*listener); |
| 5604 |
|
| 5605 |
uint count = 0; |
| 5606 |
uint cumulative = 0; |
| 5607 |
CountingNetworkAddress countingAddr(*addr, count, cumulative); |
| 5608 |
|
| 5609 |
FakeEntropySource entropySource; |
| 5610 |
HttpClientSettings clientSettings; |
| 5611 |
clientSettings.entropySource = entropySource; |
| 5612 |
clientSettings.idleTimeout = 0 * kj::SECONDS; |
| 5613 |
auto innerClient = newHttpClient(clientTimer, headerTable, countingAddr, clientSettings); |
| 5614 |
|
| 5615 |
struct CallbackEvent { |
| 5616 |
uint runningCount; |
| 5617 |
uint pendingCount; |
| 5618 |
|
| 5619 |
bool operator==(const CallbackEvent& other) const { |
| 5620 |
return runningCount == other.runningCount && pendingCount == other.pendingCount; |
| 5621 |
} |
| 5622 |
bool operator!=(const CallbackEvent& other) const { return !(*this == other); } |
| 5623 |
// TODO(someday): Can use default spaceship operator in C++20: |
| 5624 |
//auto operator<=>(const CallbackEvent&) const = default; |
| 5625 |
}; |
| 5626 |
|
| 5627 |
kj::Vector<CallbackEvent> callbackEvents; |
| 5628 |
auto callback = [&](uint runningCount, uint pendingCount) { |
| 5629 |
callbackEvents.add(CallbackEvent{runningCount, pendingCount}); |
| 5630 |
}; |
| 5631 |
auto client = newConcurrencyLimitingHttpClient(*innerClient, 1, kj::mv(callback)); |
| 5632 |
|
| 5633 |
KJ_EXPECT(count == 0); |
| 5634 |
KJ_EXPECT(cumulative == 0); |
| 5635 |
|
| 5636 |
uint i = 0; |
| 5637 |
auto doRequest = [&]() { |
| 5638 |
uint n = i++; |
| 5639 |
return client->request(HttpMethod::GET, kj::str("/", n), HttpHeaders(headerTable)).response |
| 5640 |
.then([](HttpClient::Response&& response) { |
| 5641 |
auto promise = response.body->readAllText(); |
| 5642 |
return promise.attach(kj::mv(response.body)); |
| 5643 |
}).then([n](kj::String body) { |
| 5644 |
KJ_EXPECT(body == kj::str("null:/", n)); |
| 5645 |
}); |
| 5646 |
}; |
| 5647 |
|
| 5648 |
// Second connection blocked by first. |
| 5649 |
auto req1 = doRequest(); |
| 5650 |
|
| 5651 |
KJ_EXPECT(callbackEvents == kj::ArrayPtr<const CallbackEvent>({ {1, 0} })); |
| 5652 |
callbackEvents.clear(); |
| 5653 |
|
| 5654 |
auto req2 = doRequest(); |
| 5655 |
|
| 5656 |
// TODO(someday): Figure out why this poll() is necessary on Windows and macOS. |
| 5657 |
waitScope.poll(); |
| 5658 |
|
| 5659 |
KJ_EXPECT(req1.poll(waitScope)); |
| 5660 |
KJ_EXPECT(!req2.poll(waitScope)); |
| 5661 |
KJ_EXPECT(count == 1); |
| 5662 |
KJ_EXPECT(cumulative == 1); |
| 5663 |
KJ_EXPECT(callbackEvents == kj::ArrayPtr<const CallbackEvent>({ {1, 1} })); |
| 5664 |
callbackEvents.clear(); |
| 5665 |
|
| 5666 |
// Releasing first connection allows second to start. |
| 5667 |
req1.wait(waitScope); |
| 5668 |
KJ_EXPECT(req2.poll(waitScope)); |
| 5669 |
KJ_EXPECT(count == 1); |
| 5670 |
KJ_EXPECT(cumulative == 2); |
| 5671 |
KJ_EXPECT(callbackEvents == kj::ArrayPtr<const CallbackEvent>({ {1, 0} })); |
| 5672 |
callbackEvents.clear(); |
| 5673 |
|
| 5674 |
req2.wait(waitScope); |
| 5675 |
KJ_EXPECT(count == 0); |
| 5676 |
KJ_EXPECT(cumulative == 2); |
| 5677 |
KJ_EXPECT(callbackEvents == kj::ArrayPtr<const CallbackEvent>({ {0, 0} })); |
| 5678 |
callbackEvents.clear(); |
| 5679 |
|
| 5680 |
// Using body stream after releasing blocked response promise throws no exception |
| 5681 |
auto req3 = doRequest(); |
| 5682 |
{ |
| 5683 |
kj::Own<kj::AsyncOutputStream> req4Body; |
| 5684 |
{ |
| 5685 |
auto req4 = client->request(HttpMethod::GET, kj::str("/", ++i), HttpHeaders(headerTable)); |
| 5686 |
waitScope.poll(); |
| 5687 |
req4Body = kj::mv(req4.body); |
| 5688 |
} |
| 5689 |
auto writePromise = req4Body->write("a", 1); |
| 5690 |
KJ_EXPECT(!writePromise.poll(waitScope)); |
| 5691 |
} |
| 5692 |
req3.wait(waitScope); |
| 5693 |
KJ_EXPECT(count == 0); |
| 5694 |
KJ_EXPECT(cumulative == 3); |
| 5695 |
|
| 5696 |
// Similar connection limiting for web sockets |
| 5697 |
// TODO(someday): Figure out why the sequencing of websockets events does |
| 5698 |
// not work correctly on Windows (and maybe macOS?). The solution is not as |
| 5699 |
// simple as inserting poll()s as above, since doing so puts the websocket in |
| 5700 |
// a state that trips a "previous HTTP message body incomplete" assertion, |
| 5701 |
// while trying to write 500 network response. |
| 5702 |
callbackEvents.clear(); |
| 5703 |
auto ws1 = kj::heap(client->openWebSocket(kj::str("/websocket"), HttpHeaders(headerTable))); |
| 5704 |
KJ_EXPECT(callbackEvents == kj::ArrayPtr<const CallbackEvent>({ {1, 0} })); |
| 5705 |
callbackEvents.clear(); |
| 5706 |
auto ws2 = kj::heap(client->openWebSocket(kj::str("/websocket"), HttpHeaders(headerTable))); |
| 5707 |
KJ_EXPECT(ws1->poll(waitScope)); |
| 5708 |
KJ_EXPECT(!ws2->poll(waitScope)); |
| 5709 |
KJ_EXPECT(count == 1); |
| 5710 |
KJ_EXPECT(cumulative == 4); |
| 5711 |
KJ_EXPECT(callbackEvents == kj::ArrayPtr<const CallbackEvent>({ {1, 1} })); |
| 5712 |
callbackEvents.clear(); |
| 5713 |
|
| 5714 |
{ |
| 5715 |
auto response1 = ws1->wait(waitScope); |
| 5716 |
KJ_EXPECT(!ws2->poll(waitScope)); |
| 5717 |
KJ_EXPECT(callbackEvents == kj::ArrayPtr<const CallbackEvent>({})); |
| 5718 |
} |
| 5719 |
KJ_EXPECT(ws2->poll(waitScope)); |
| 5720 |
KJ_EXPECT(count == 1); |
| 5721 |
KJ_EXPECT(cumulative == 5); |
| 5722 |
KJ_EXPECT(callbackEvents == kj::ArrayPtr<const CallbackEvent>({ {1, 0} })); |
| 5723 |
callbackEvents.clear(); |
| 5724 |
{ |
| 5725 |
auto response2 = ws2->wait(waitScope); |
| 5726 |
KJ_EXPECT(callbackEvents == kj::ArrayPtr<const CallbackEvent>({})); |
| 5727 |
} |
| 5728 |
KJ_EXPECT(count == 0); |
| 5729 |
KJ_EXPECT(cumulative == 5); |
| 5730 |
KJ_EXPECT(callbackEvents == kj::ArrayPtr<const CallbackEvent>({ {0, 0} })); |
| 5731 |
} |
| 5732 |
|
| 5733 |
#if KJ_HTTP_TEST_USE_OS_PIPE |
| 5734 |
// This test relies on access to the network. |
| 5735 |
KJ_TEST("NetworkHttpClient connect impl") { |
| 5736 |
KJ_HTTP_TEST_SETUP_IO; |
| 5737 |
auto listener1 = io.provider->getNetwork().parseAddress("localhost", 0) |
| 5738 |
.wait(io.waitScope)->listen(); |
| 5739 |
|
| 5740 |
auto ignored KJ_UNUSED = listener1->accept().then([](Own<kj::AsyncIoStream> stream) { |
| 5741 |
auto buffer = kj::str("test"); |
| 5742 |
return stream->write(buffer.cStr(), buffer.size()).attach(kj::mv(stream), kj::mv(buffer)); |
| 5743 |
}).eagerlyEvaluate(nullptr); |
| 5744 |
|
| 5745 |
HttpClientSettings clientSettings; |
| 5746 |
kj::TimerImpl clientTimer(kj::origin<kj::TimePoint>()); |
| 5747 |
HttpHeaderTable headerTable; |
| 5748 |
auto client = newHttpClient(clientTimer, headerTable, |
| 5749 |
io.provider->getNetwork(), nullptr, clientSettings); |
| 5750 |
auto request = client->connect( |
| 5751 |
kj::str("localhost:", listener1->getPort()), HttpHeaders(headerTable), {}); |
| 5752 |
|
| 5753 |
auto buf = kj::heapArray<char>(4); |
| 5754 |
return request.connection->tryRead(buf.begin(), 1, buf.size()) |
| 5755 |
.then([buf = kj::mv(buf)](size_t count) { |
| 5756 |
KJ_ASSERT(count == 4); |
| 5757 |
KJ_ASSERT(kj::str(buf.asChars()) == "test"); |
| 5758 |
}).attach(kj::mv(request.connection)).wait(io.waitScope); |
| 5759 |
} |
| 5760 |
#endif |
| 5761 |
|
| 5762 |
#if KJ_HTTP_TEST_USE_OS_PIPE |
| 5763 |
// TODO(someday): Implement mock kj::Network for userspace version of this test? |
| 5764 |
KJ_TEST("HttpClient multi host") { |
| 5765 |
auto io = kj::setupAsyncIo(); |
| 5766 |
|
| 5767 |
kj::TimerImpl serverTimer(kj::origin<kj::TimePoint>()); |
| 5768 |
kj::TimerImpl clientTimer(kj::origin<kj::TimePoint>()); |
| 5769 |
HttpHeaderTable headerTable; |
| 5770 |
|
| 5771 |
auto listener1 = io.provider->getNetwork().parseAddress("localhost", 0) |
| 5772 |
.wait(io.waitScope)->listen(); |
| 5773 |
auto listener2 = io.provider->getNetwork().parseAddress("localhost", 0) |
| 5774 |
.wait(io.waitScope)->listen(); |
| 5775 |
DummyService service(headerTable); |
| 5776 |
HttpServer server(serverTimer, headerTable, service); |
| 5777 |
auto listenTask1 = server.listenHttp(*listener1); |
| 5778 |
auto listenTask2 = server.listenHttp(*listener2); |
| 5779 |
|
| 5780 |
uint count = 0, addrCount = 0; |
| 5781 |
uint tlsCount = 0, tlsAddrCount = 0; |
| 5782 |
ConnectionCountingNetwork countingNetwork(io.provider->getNetwork(), count, addrCount); |
| 5783 |
ConnectionCountingNetwork countingTlsNetwork(io.provider->getNetwork(), tlsCount, tlsAddrCount); |
| 5784 |
|
| 5785 |
HttpClientSettings clientSettings; |
| 5786 |
auto client = newHttpClient(clientTimer, headerTable, |
| 5787 |
countingNetwork, countingTlsNetwork, clientSettings); |
| 5788 |
|
| 5789 |
KJ_EXPECT(count == 0); |
| 5790 |
|
| 5791 |
uint i = 0; |
| 5792 |
auto doRequest = [&](bool tls, uint port) { |
| 5793 |
uint n = i++; |
| 5794 |
// We stick a double-slash in the URL to test that it doesn't get coalesced into one slash, |
| 5795 |
// which was a bug in the past. |
| 5796 |
return client->request(HttpMethod::GET, |
| 5797 |
kj::str((tls ? "https://localhost:" : "http://localhost:"), port, "//", n), |
| 5798 |
HttpHeaders(headerTable)).response |
| 5799 |
.then([](HttpClient::Response&& response) { |
| 5800 |
auto promise = response.body->readAllText(); |
| 5801 |
return promise.attach(kj::mv(response.body)); |
| 5802 |
}).then([n, port](kj::String body) { |
| 5803 |
KJ_EXPECT(body == kj::str("localhost:", port, "://", n), body, port, n); |
| 5804 |
}); |
| 5805 |
}; |
| 5806 |
|
| 5807 |
uint port1 = listener1->getPort(); |
| 5808 |
uint port2 = listener2->getPort(); |
| 5809 |
|
| 5810 |
// We can do several requests in a row to the same host and only have one connection. |
| 5811 |
doRequest(false, port1).wait(io.waitScope); |
| 5812 |
doRequest(false, port1).wait(io.waitScope); |
| 5813 |
doRequest(false, port1).wait(io.waitScope); |
| 5814 |
KJ_EXPECT(count == 1); |
| 5815 |
KJ_EXPECT(tlsCount == 0); |
| 5816 |
KJ_EXPECT(addrCount == 1); |
| 5817 |
KJ_EXPECT(tlsAddrCount == 0); |
| 5818 |
|
| 5819 |
// Request a different host, and now we have two connections. |
| 5820 |
doRequest(false, port2).wait(io.waitScope); |
| 5821 |
KJ_EXPECT(count == 2); |
| 5822 |
KJ_EXPECT(tlsCount == 0); |
| 5823 |
KJ_EXPECT(addrCount == 2); |
| 5824 |
KJ_EXPECT(tlsAddrCount == 0); |
| 5825 |
|
| 5826 |
// Try TLS. |
| 5827 |
doRequest(true, port1).wait(io.waitScope); |
| 5828 |
KJ_EXPECT(count == 2); |
| 5829 |
KJ_EXPECT(tlsCount == 1); |
| 5830 |
KJ_EXPECT(addrCount == 2); |
| 5831 |
KJ_EXPECT(tlsAddrCount == 1); |
| 5832 |
|
| 5833 |
// Try first host again, no change in connection count. |
| 5834 |
doRequest(false, port1).wait(io.waitScope); |
| 5835 |
KJ_EXPECT(count == 2); |
| 5836 |
KJ_EXPECT(tlsCount == 1); |
| 5837 |
KJ_EXPECT(addrCount == 2); |
| 5838 |
KJ_EXPECT(tlsAddrCount == 1); |
| 5839 |
|
| 5840 |
// Multiple requests in parallel forces more connections to that host. |
| 5841 |
auto promise1 = doRequest(false, port1); |
| 5842 |
auto promise2 = doRequest(false, port1); |
| 5843 |
promise1.wait(io.waitScope); |
| 5844 |
promise2.wait(io.waitScope); |
| 5845 |
KJ_EXPECT(count == 3); |
| 5846 |
KJ_EXPECT(tlsCount == 1); |
| 5847 |
KJ_EXPECT(addrCount == 2); |
| 5848 |
KJ_EXPECT(tlsAddrCount == 1); |
| 5849 |
|
| 5850 |
// Let everything expire. |
| 5851 |
clientTimer.advanceTo(clientTimer.now() + clientSettings.idleTimeout * 2); |
| 5852 |
io.waitScope.poll(); |
| 5853 |
KJ_EXPECT(count == 0); |
| 5854 |
KJ_EXPECT(tlsCount == 0); |
| 5855 |
KJ_EXPECT(addrCount == 0); |
| 5856 |
KJ_EXPECT(tlsAddrCount == 0); |
| 5857 |
|
| 5858 |
// We can still request those hosts again. |
| 5859 |
doRequest(false, port1).wait(io.waitScope); |
| 5860 |
KJ_EXPECT(count == 1); |
| 5861 |
KJ_EXPECT(tlsCount == 0); |
| 5862 |
KJ_EXPECT(addrCount == 1); |
| 5863 |
KJ_EXPECT(tlsAddrCount == 0); |
| 5864 |
} |
| 5865 |
#endif |
| 5866 |
|
| 5867 |
// ----------------------------------------------------------------------------- |
| 5868 |
|
| 5869 |
#if KJ_HTTP_TEST_USE_OS_PIPE |
| 5870 |
// This test only makes sense using the real network. |
| 5871 |
KJ_TEST("HttpClient to capnproto.org") { |
| 5872 |
auto io = kj::setupAsyncIo(); |
| 5873 |
|
| 5874 |
auto maybeConn = io.provider->getNetwork().parseAddress("capnproto.org", 80) |
| 5875 |
.then([](kj::Own<kj::NetworkAddress> addr) { |
| 5876 |
auto promise = addr->connect(); |
| 5877 |
return promise.attach(kj::mv(addr)); |
| 5878 |
}).then([](kj::Own<kj::AsyncIoStream>&& connection) -> kj::Maybe<kj::Own<kj::AsyncIoStream>> { |
| 5879 |
return kj::mv(connection); |
| 5880 |
}, [](kj::Exception&& e) -> kj::Maybe<kj::Own<kj::AsyncIoStream>> { |
| 5881 |
KJ_LOG(WARNING, "skipping test because couldn't connect to capnproto.org"); |
| 5882 |
return nullptr; |
| 5883 |
}).wait(io.waitScope); |
| 5884 |
|
| 5885 |
KJ_IF_MAYBE(conn, maybeConn) { |
| 5886 |
// Successfully connected to capnproto.org. Try doing GET /. We expect to get a redirect to |
| 5887 |
// HTTPS, because what kind of horrible web site would serve in plaintext, really? |
| 5888 |
|
| 5889 |
HttpHeaderTable table; |
| 5890 |
auto client = newHttpClient(table, **conn); |
| 5891 |
|
| 5892 |
HttpHeaders headers(table); |
| 5893 |
headers.set(HttpHeaderId::HOST, "capnproto.org"); |
| 5894 |
|
| 5895 |
auto response = client->request(HttpMethod::GET, "/", headers).response.wait(io.waitScope); |
| 5896 |
KJ_EXPECT(response.statusCode / 100 == 3); |
| 5897 |
auto location = KJ_ASSERT_NONNULL(response.headers->get(HttpHeaderId::LOCATION)); |
| 5898 |
KJ_EXPECT(location == "https://capnproto.org/"); |
| 5899 |
|
| 5900 |
auto body = response.body->readAllText().wait(io.waitScope); |
| 5901 |
} |
| 5902 |
} |
| 5903 |
#endif |
| 5904 |
|
| 5905 |
// ======================================================================================= |
| 5906 |
// Misc bugfix tests |
| 5907 |
|
| 5908 |
class ReadCancelHttpService final: public HttpService { |
| 5909 |
// HttpService that tries to read all request data but cancels after 1ms and sends a response. |
| 5910 |
public: |
| 5911 |
ReadCancelHttpService(kj::Timer& timer, HttpHeaderTable& headerTable) |
| 5912 |
: timer(timer), headerTable(headerTable) {} |
| 5913 |
|
| 5914 |
kj::Promise<void> request( |
| 5915 |
HttpMethod method, kj::StringPtr url, const HttpHeaders& headers, |
| 5916 |
kj::AsyncInputStream& requestBody, Response& responseSender) override { |
| 5917 |
if (method == HttpMethod::POST) { |
| 5918 |
// Try to read all content, but cancel after 1ms. |
| 5919 |
|
| 5920 |
// Actually, we can't literally cancel mid-read, because this leaves the stream in an |
| 5921 |
// unknown state which requires closing the connection. Instead, we know that the sender |
| 5922 |
// will send 5 bytes, so we read that, then pause. |
| 5923 |
static char junk[5]; |
| 5924 |
return requestBody.read(junk, 5) |
| 5925 |
.then([]() -> kj::Promise<void> { return kj::NEVER_DONE; }) |
| 5926 |
.exclusiveJoin(timer.afterDelay(1 * kj::MILLISECONDS)) |
| 5927 |
.then([this, &responseSender]() { |
| 5928 |
responseSender.send(408, "Request Timeout", kj::HttpHeaders(headerTable), uint64_t(0)); |
| 5929 |
}); |
| 5930 |
} else { |
| 5931 |
responseSender.send(200, "OK", kj::HttpHeaders(headerTable), uint64_t(0)); |
| 5932 |
return kj::READY_NOW; |
| 5933 |
} |
| 5934 |
} |
| 5935 |
|
| 5936 |
private: |
| 5937 |
kj::Timer& timer; |
| 5938 |
HttpHeaderTable& headerTable; |
| 5939 |
}; |
| 5940 |
|
| 5941 |
KJ_TEST("canceling a length stream mid-read correctly discards rest of request") { |
| 5942 |
KJ_HTTP_TEST_SETUP_IO; |
| 5943 |
kj::TimerImpl timer(kj::origin<kj::TimePoint>()); |
| 5944 |
auto pipe = KJ_HTTP_TEST_CREATE_2PIPE; |
| 5945 |
|
| 5946 |
HttpHeaderTable table; |
| 5947 |
ReadCancelHttpService service(timer, table); |
| 5948 |
HttpServer server(timer, table, service); |
| 5949 |
|
| 5950 |
auto listenTask = server.listenHttp(kj::mv(pipe.ends[0])); |
| 5951 |
|
| 5952 |
{ |
| 5953 |
static constexpr kj::StringPtr REQUEST = |
| 5954 |
"POST / HTTP/1.1\r\n" |
| 5955 |
"Content-Length: 6\r\n" |
| 5956 |
"\r\n" |
| 5957 |
"fooba"_kj; // incomplete |
| 5958 |
pipe.ends[1]->write(REQUEST.begin(), REQUEST.size()).wait(waitScope); |
| 5959 |
|
| 5960 |
auto promise = expectRead(*pipe.ends[1], |
| 5961 |
"HTTP/1.1 408 Request Timeout\r\n" |
| 5962 |
"Content-Length: 0\r\n" |
| 5963 |
"\r\n"_kj); |
| 5964 |
|
| 5965 |
KJ_EXPECT(!promise.poll(waitScope)); |
| 5966 |
|
| 5967 |
// Trigger timeout, then response should be sent. |
| 5968 |
timer.advanceTo(timer.now() + 1 * kj::MILLISECONDS); |
| 5969 |
KJ_ASSERT(promise.poll(waitScope)); |
| 5970 |
promise.wait(waitScope); |
| 5971 |
} |
| 5972 |
|
| 5973 |
// We left our request stream hanging. The server will try to read and discard the request body. |
| 5974 |
// Let's give it the rest of the data, followed by a second request. |
| 5975 |
{ |
| 5976 |
static constexpr kj::StringPtr REQUEST = |
| 5977 |
"r" |
| 5978 |
"GET / HTTP/1.1\r\n" |
| 5979 |
"\r\n"_kj; |
| 5980 |
pipe.ends[1]->write(REQUEST.begin(), REQUEST.size()).wait(waitScope); |
| 5981 |
|
| 5982 |
auto promise = expectRead(*pipe.ends[1], |
| 5983 |
"HTTP/1.1 200 OK\r\n" |
| 5984 |
"Content-Length: 0\r\n" |
| 5985 |
"\r\n"_kj); |
| 5986 |
KJ_ASSERT(promise.poll(waitScope)); |
| 5987 |
promise.wait(waitScope); |
| 5988 |
} |
| 5989 |
} |
| 5990 |
|
| 5991 |
KJ_TEST("canceling a chunked stream mid-read correctly discards rest of request") { |
| 5992 |
KJ_HTTP_TEST_SETUP_IO; |
| 5993 |
kj::TimerImpl timer(kj::origin<kj::TimePoint>()); |
| 5994 |
auto pipe = KJ_HTTP_TEST_CREATE_2PIPE; |
| 5995 |
|
| 5996 |
HttpHeaderTable table; |
| 5997 |
ReadCancelHttpService service(timer, table); |
| 5998 |
HttpServer server(timer, table, service); |
| 5999 |
|
| 6000 |
auto listenTask = server.listenHttp(kj::mv(pipe.ends[0])); |
| 6001 |
|
| 6002 |
{ |
| 6003 |
static constexpr kj::StringPtr REQUEST = |
| 6004 |
"POST / HTTP/1.1\r\n" |
| 6005 |
"Transfer-Encoding: chunked\r\n" |
| 6006 |
"\r\n" |
| 6007 |
"6\r\n" |
| 6008 |
"fooba"_kj; // incomplete chunk |
| 6009 |
pipe.ends[1]->write(REQUEST.begin(), REQUEST.size()).wait(waitScope); |
| 6010 |
|
| 6011 |
auto promise = expectRead(*pipe.ends[1], |
| 6012 |
"HTTP/1.1 408 Request Timeout\r\n" |
| 6013 |
"Content-Length: 0\r\n" |
| 6014 |
"\r\n"_kj); |
| 6015 |
|
| 6016 |
KJ_EXPECT(!promise.poll(waitScope)); |
| 6017 |
|
| 6018 |
// Trigger timeout, then response should be sent. |
| 6019 |
timer.advanceTo(timer.now() + 1 * kj::MILLISECONDS); |
| 6020 |
KJ_ASSERT(promise.poll(waitScope)); |
| 6021 |
promise.wait(waitScope); |
| 6022 |
} |
| 6023 |
|
| 6024 |
// We left our request stream hanging. The server will try to read and discard the request body. |
| 6025 |
// Let's give it the rest of the data, followed by a second request. |
| 6026 |
{ |
| 6027 |
static constexpr kj::StringPtr REQUEST = |
| 6028 |
"r\r\n" |
| 6029 |
"4a\r\n" |
| 6030 |
"this is some text that is the body of a chunk and not a valid chunk header\r\n" |
| 6031 |
"0\r\n" |
| 6032 |
"\r\n" |
| 6033 |
"GET / HTTP/1.1\r\n" |
| 6034 |
"\r\n"_kj; |
| 6035 |
pipe.ends[1]->write(REQUEST.begin(), REQUEST.size()).wait(waitScope); |
| 6036 |
|
| 6037 |
auto promise = expectRead(*pipe.ends[1], |
| 6038 |
"HTTP/1.1 200 OK\r\n" |
| 6039 |
"Content-Length: 0\r\n" |
| 6040 |
"\r\n"_kj); |
| 6041 |
KJ_ASSERT(promise.poll(waitScope)); |
| 6042 |
promise.wait(waitScope); |
| 6043 |
} |
| 6044 |
} |
| 6045 |
|
| 6046 |
KJ_TEST("drain() doesn't lose bytes when called at the wrong moment") { |
| 6047 |
KJ_HTTP_TEST_SETUP_IO; |
| 6048 |
kj::TimerImpl timer(kj::origin<kj::TimePoint>()); |
| 6049 |
auto pipe = KJ_HTTP_TEST_CREATE_2PIPE; |
| 6050 |
|
| 6051 |
HttpHeaderTable table; |
| 6052 |
DummyService service(table); |
| 6053 |
HttpServer server(timer, table, service); |
| 6054 |
|
| 6055 |
auto listenTask = server.listenHttpCleanDrain(*pipe.ends[0]); |
| 6056 |
|
| 6057 |
// Do a regular request. |
| 6058 |
static constexpr kj::StringPtr REQUEST = |
| 6059 |
"GET / HTTP/1.1\r\n" |
| 6060 |
"Host: example.com\r\n" |
| 6061 |
"\r\n"_kj; |
| 6062 |
pipe.ends[1]->write(REQUEST.begin(), REQUEST.size()).wait(waitScope); |
| 6063 |
expectRead(*pipe.ends[1], |
| 6064 |
"HTTP/1.1 200 OK\r\n" |
| 6065 |
"Content-Length: 13\r\n" |
| 6066 |
"\r\n" |
| 6067 |
"example.com:/"_kj).wait(waitScope); |
| 6068 |
|
| 6069 |
// Make sure the server is blocked on the next read from the socket. |
| 6070 |
kj::Promise<void>(kj::NEVER_DONE).poll(waitScope); |
| 6071 |
|
| 6072 |
// Now simultaneously deliver a new request AND drain the socket. |
| 6073 |
auto drainPromise = server.drain(); |
| 6074 |
static constexpr kj::StringPtr REQUEST2 = |
| 6075 |
"GET /foo HTTP/1.1\r\n" |
| 6076 |
"Host: example.com\r\n" |
| 6077 |
"\r\n"_kj; |
| 6078 |
pipe.ends[1]->write(REQUEST2.begin(), REQUEST2.size()).wait(waitScope); |
| 6079 |
|
| 6080 |
#if KJ_HTTP_TEST_USE_OS_PIPE |
| 6081 |
// In the case of an OS pipe, the drain will complete before any data is read from the socket. |
| 6082 |
drainPromise.wait(waitScope); |
| 6083 |
|
| 6084 |
// The HTTP server should indicate the connection was released but still valid. |
| 6085 |
KJ_ASSERT(listenTask.wait(waitScope)); |
| 6086 |
|
| 6087 |
// The request will not have been read off the socket. We can read it now. |
| 6088 |
pipe.ends[1]->shutdownWrite(); |
| 6089 |
KJ_EXPECT(pipe.ends[0]->readAllText().wait(waitScope) == REQUEST2); |
| 6090 |
|
| 6091 |
#else |
| 6092 |
// In the case of an in-memory pipe, the write() will have delivered bytes directly to the |
| 6093 |
// destination buffer synchronously, which means that the server must handle the request |
| 6094 |
// before draining. |
| 6095 |
KJ_EXPECT(!drainPromise.poll(waitScope)); |
| 6096 |
|
| 6097 |
// The HTTP request should get a response. |
| 6098 |
expectRead(*pipe.ends[1], |
| 6099 |
"HTTP/1.1 200 OK\r\n" |
| 6100 |
"Content-Length: 16\r\n" |
| 6101 |
"\r\n" |
| 6102 |
"example.com:/foo"_kj).wait(waitScope); |
| 6103 |
|
| 6104 |
// Now the drain completes. |
| 6105 |
drainPromise.wait(waitScope); |
| 6106 |
|
| 6107 |
// The HTTP server should indicate the connection was released but still valid. |
| 6108 |
KJ_ASSERT(listenTask.wait(waitScope)); |
| 6109 |
#endif |
| 6110 |
} |
| 6111 |
|
| 6112 |
KJ_TEST("drain() does not cancel the first request on a new connection") { |
| 6113 |
KJ_HTTP_TEST_SETUP_IO; |
| 6114 |
kj::TimerImpl timer(kj::origin<kj::TimePoint>()); |
| 6115 |
auto pipe = KJ_HTTP_TEST_CREATE_2PIPE; |
| 6116 |
|
| 6117 |
HttpHeaderTable table; |
| 6118 |
DummyService service(table); |
| 6119 |
HttpServer server(timer, table, service); |
| 6120 |
|
| 6121 |
auto listenTask = server.listenHttpCleanDrain(*pipe.ends[0]); |
| 6122 |
|
| 6123 |
// Request a drain(). It won't complete, because the newly-connected socket is considered to have |
| 6124 |
// an in-flight request. |
| 6125 |
auto drainPromise = server.drain(); |
| 6126 |
KJ_EXPECT(!drainPromise.poll(waitScope)); |
| 6127 |
|
| 6128 |
// Deliver the request. |
| 6129 |
static constexpr kj::StringPtr REQUEST2 = |
| 6130 |
"GET /foo HTTP/1.1\r\n" |
| 6131 |
"Host: example.com\r\n" |
| 6132 |
"\r\n"_kj; |
| 6133 |
pipe.ends[1]->write(REQUEST2.begin(), REQUEST2.size()).wait(waitScope); |
| 6134 |
|
| 6135 |
// It should get a response. |
| 6136 |
expectRead(*pipe.ends[1], |
| 6137 |
"HTTP/1.1 200 OK\r\n" |
| 6138 |
"Content-Length: 16\r\n" |
| 6139 |
"\r\n" |
| 6140 |
"example.com:/foo"_kj).wait(waitScope); |
| 6141 |
|
| 6142 |
// Now the drain completes. |
| 6143 |
drainPromise.wait(waitScope); |
| 6144 |
|
| 6145 |
// The HTTP server should indicate the connection was released but still valid. |
| 6146 |
KJ_ASSERT(listenTask.wait(waitScope)); |
| 6147 |
} |
| 6148 |
|
| 6149 |
KJ_TEST("drain() when NOT using listenHttpCleanDrain() sends Connection: close header") { |
| 6150 |
KJ_HTTP_TEST_SETUP_IO; |
| 6151 |
kj::TimerImpl timer(kj::origin<kj::TimePoint>()); |
| 6152 |
auto pipe = KJ_HTTP_TEST_CREATE_2PIPE; |
| 6153 |
|
| 6154 |
HttpHeaderTable table; |
| 6155 |
DummyService service(table); |
| 6156 |
HttpServer server(timer, table, service); |
| 6157 |
|
| 6158 |
auto listenTask = server.listenHttp(kj::mv(pipe.ends[0])); |
| 6159 |
|
| 6160 |
// Request a drain(). It won't complete, because the newly-connected socket is considered to have |
| 6161 |
// an in-flight request. |
| 6162 |
auto drainPromise = server.drain(); |
| 6163 |
KJ_EXPECT(!drainPromise.poll(waitScope)); |
| 6164 |
|
| 6165 |
// Deliver the request. |
| 6166 |
static constexpr kj::StringPtr REQUEST2 = |
| 6167 |
"GET /foo HTTP/1.1\r\n" |
| 6168 |
"Host: example.com\r\n" |
| 6169 |
"\r\n"_kj; |
| 6170 |
pipe.ends[1]->write(REQUEST2.begin(), REQUEST2.size()).wait(waitScope); |
| 6171 |
|
| 6172 |
// It should get a response. |
| 6173 |
expectRead(*pipe.ends[1], |
| 6174 |
"HTTP/1.1 200 OK\r\n" |
| 6175 |
"Connection: close\r\n" |
| 6176 |
"Content-Length: 16\r\n" |
| 6177 |
"\r\n" |
| 6178 |
"example.com:/foo"_kj).wait(waitScope); |
| 6179 |
|
| 6180 |
// And then EOF. |
| 6181 |
auto rest = pipe.ends[1]->readAllText(); |
| 6182 |
KJ_ASSERT(rest.poll(waitScope)); |
| 6183 |
KJ_EXPECT(rest.wait(waitScope) == nullptr); |
| 6184 |
|
| 6185 |
// The drain task and listen task are done. |
| 6186 |
drainPromise.wait(waitScope); |
| 6187 |
listenTask.wait(waitScope); |
| 6188 |
} |
| 6189 |
|
| 6190 |
class BrokenConnectionListener final: public kj::ConnectionReceiver { |
| 6191 |
public: |
| 6192 |
void fulfillOne(kj::Own<kj::AsyncIoStream> stream) { |
| 6193 |
fulfiller->fulfill(kj::mv(stream)); |
| 6194 |
} |
| 6195 |
|
| 6196 |
kj::Promise<kj::Own<kj::AsyncIoStream>> accept() override { |
| 6197 |
auto paf = kj::newPromiseAndFulfiller<kj::Own<kj::AsyncIoStream>>(); |
| 6198 |
fulfiller = kj::mv(paf.fulfiller); |
| 6199 |
return kj::mv(paf.promise); |
| 6200 |
} |
| 6201 |
|
| 6202 |
uint getPort() override { |
| 6203 |
KJ_UNIMPLEMENTED("not used"); |
| 6204 |
} |
| 6205 |
|
| 6206 |
private: |
| 6207 |
kj::Own<kj::PromiseFulfiller<kj::Own<kj::AsyncIoStream>>> fulfiller; |
| 6208 |
}; |
| 6209 |
|
| 6210 |
class BrokenConnection final: public kj::AsyncIoStream { |
| 6211 |
public: |
| 6212 |
Promise<size_t> tryRead(void* buffer, size_t minBytes, size_t maxBytes) override { |
| 6213 |
return KJ_EXCEPTION(FAILED, "broken"); |
| 6214 |
} |
| 6215 |
Promise<void> write(const void* buffer, size_t size) override { |
| 6216 |
return KJ_EXCEPTION(FAILED, "broken"); |
| 6217 |
} |
| 6218 |
Promise<void> write(ArrayPtr<const ArrayPtr<const byte>> pieces) override { |
| 6219 |
return KJ_EXCEPTION(FAILED, "broken"); |
| 6220 |
} |
| 6221 |
Promise<void> whenWriteDisconnected() override { |
| 6222 |
return kj::NEVER_DONE; |
| 6223 |
} |
| 6224 |
|
| 6225 |
void shutdownWrite() override {} |
| 6226 |
}; |
| 6227 |
|
| 6228 |
KJ_TEST("HttpServer.listenHttp() doesn't prematurely terminate if an accepted connection is broken") { |
| 6229 |
KJ_HTTP_TEST_SETUP_IO; |
| 6230 |
kj::TimerImpl timer(kj::origin<kj::TimePoint>()); |
| 6231 |
|
| 6232 |
HttpHeaderTable table; |
| 6233 |
DummyService service(table); |
| 6234 |
HttpServer server(timer, table, service); |
| 6235 |
|
| 6236 |
BrokenConnectionListener listener; |
| 6237 |
auto promise = server.listenHttp(listener).eagerlyEvaluate(nullptr); |
| 6238 |
|
| 6239 |
// Loop is waiting for a connection. |
| 6240 |
KJ_ASSERT(!promise.poll(waitScope)); |
| 6241 |
|
| 6242 |
KJ_EXPECT_LOG(ERROR, "failed: broken"); |
| 6243 |
listener.fulfillOne(kj::heap<BrokenConnection>()); |
| 6244 |
|
| 6245 |
// The loop should not have stopped, even though the connection was broken. |
| 6246 |
KJ_ASSERT(!promise.poll(waitScope)); |
| 6247 |
} |
| 6248 |
|
| 6249 |
KJ_TEST("HttpServer handles disconnected exception for clients disconnecting after headers") { |
| 6250 |
// This test case reproduces a race condition where a client could disconnect after the server |
| 6251 |
// sent response headers but before it sent the response body, resulting in a broken pipe |
| 6252 |
// "disconnected" exception when writing the body. The default handler for application errors |
| 6253 |
// tells the server to ignore "disconnected" exceptions and close the connection, but code |
| 6254 |
// after the handler exercised the broken connection, causing the server loop to instead fail |
| 6255 |
// with a "failed" exception. |
| 6256 |
|
| 6257 |
KJ_HTTP_TEST_SETUP_IO; |
| 6258 |
kj::TimerImpl timer(kj::origin<kj::TimePoint>()); |
| 6259 |
auto pipe = KJ_HTTP_TEST_CREATE_2PIPE; |
| 6260 |
|
| 6261 |
class SendErrorHttpService final: public HttpService { |
| 6262 |
// HttpService that serves an error page via sendError(). |
| 6263 |
public: |
| 6264 |
SendErrorHttpService(HttpHeaderTable& headerTable): headerTable(headerTable) {} |
| 6265 |
kj::Promise<void> request( |
| 6266 |
HttpMethod method, kj::StringPtr url, const HttpHeaders& headers, |
| 6267 |
kj::AsyncInputStream& requestBody, Response& responseSender) override { |
| 6268 |
return responseSender.sendError(404, "Not Found", headerTable); |
| 6269 |
} |
| 6270 |
|
| 6271 |
private: |
| 6272 |
HttpHeaderTable& headerTable; |
| 6273 |
}; |
| 6274 |
|
| 6275 |
class DisconnectingAsyncIoStream final: public kj::AsyncIoStream { |
| 6276 |
public: |
| 6277 |
DisconnectingAsyncIoStream(AsyncIoStream& inner): inner(inner) {} |
| 6278 |
|
| 6279 |
Promise<size_t> read(void* buffer, size_t minBytes, size_t maxBytes) override { |
| 6280 |
return inner.read(buffer, minBytes, maxBytes); |
| 6281 |
} |
| 6282 |
Promise<size_t> tryRead(void* buffer, size_t minBytes, size_t maxBytes) override { |
| 6283 |
return inner.tryRead(buffer, minBytes, maxBytes); |
| 6284 |
} |
| 6285 |
|
| 6286 |
Maybe<uint64_t> tryGetLength() override { return inner.tryGetLength(); } |
| 6287 |
|
| 6288 |
Promise<uint64_t> pumpTo(AsyncOutputStream& output, uint64_t amount) override { |
| 6289 |
return inner.pumpTo(output, amount); |
| 6290 |
} |
| 6291 |
|
| 6292 |
Promise<void> write(const void* buffer, size_t size) override { |
| 6293 |
int writeId = writeCount++; |
| 6294 |
if (writeId == 0) { |
| 6295 |
// Allow first write (headers) to succeed. |
| 6296 |
auto promise = inner.write(buffer, size); |
| 6297 |
inner.shutdownWrite(); |
| 6298 |
return promise; |
| 6299 |
} else if (writeId == 1) { |
| 6300 |
// Fail subsequent write (body) with a disconnected exception. |
| 6301 |
return KJ_EXCEPTION(DISCONNECTED, "a_disconnected_exception"); |
| 6302 |
} else { |
| 6303 |
KJ_FAIL_ASSERT("Unexpected write"); |
| 6304 |
} |
| 6305 |
} |
| 6306 |
Promise<void> write(ArrayPtr<const ArrayPtr<const byte>> pieces) override { |
| 6307 |
return inner.write(pieces); |
| 6308 |
} |
| 6309 |
|
| 6310 |
Maybe<Promise<uint64_t>> tryPumpFrom(AsyncInputStream& input, uint64_t amount) override { |
| 6311 |
return inner.tryPumpFrom(input, amount); |
| 6312 |
} |
| 6313 |
|
| 6314 |
Promise<void> whenWriteDisconnected() override { |
| 6315 |
return inner.whenWriteDisconnected(); |
| 6316 |
} |
| 6317 |
|
| 6318 |
void shutdownWrite() override { |
| 6319 |
return inner.shutdownWrite(); |
| 6320 |
} |
| 6321 |
|
| 6322 |
void abortRead() override { |
| 6323 |
return inner.abortRead(); |
| 6324 |
} |
| 6325 |
|
| 6326 |
void getsockopt(int level, int option, void* value, uint* length) override { |
| 6327 |
return inner.getsockopt(level, option, value, length); |
| 6328 |
} |
| 6329 |
void setsockopt(int level, int option, const void* value, uint length) override { |
| 6330 |
return inner.setsockopt(level, option, value, length); |
| 6331 |
} |
| 6332 |
|
| 6333 |
void getsockname(struct sockaddr* addr, uint* length) override { |
| 6334 |
return inner.getsockname(addr, length); |
| 6335 |
} |
| 6336 |
void getpeername(struct sockaddr* addr, uint* length) override { |
| 6337 |
return inner.getsockname(addr, length); |
| 6338 |
} |
| 6339 |
|
| 6340 |
int writeCount = 0; |
| 6341 |
|
| 6342 |
private: |
| 6343 |
kj::AsyncIoStream& inner; |
| 6344 |
}; |
| 6345 |
|
| 6346 |
class TestErrorHandler: public HttpServerErrorHandler { |
| 6347 |
public: |
| 6348 |
kj::Promise<void> handleApplicationError( |
| 6349 |
kj::Exception exception, kj::Maybe<kj::HttpService::Response&> response) override { |
| 6350 |
applicationErrorCount++; |
| 6351 |
if (exception.getType() == kj::Exception::Type::DISCONNECTED) { |
| 6352 |
// Tell HttpServer to ignore disconnected exceptions (the default behavior). |
| 6353 |
return kj::READY_NOW; |
| 6354 |
} |
| 6355 |
KJ_FAIL_ASSERT("Unexpected application error type", exception.getType()); |
| 6356 |
} |
| 6357 |
|
| 6358 |
int applicationErrorCount = 0; |
| 6359 |
}; |
| 6360 |
|
| 6361 |
TestErrorHandler testErrorHandler; |
| 6362 |
HttpServerSettings settings {}; |
| 6363 |
settings.errorHandler = testErrorHandler; |
| 6364 |
|
| 6365 |
HttpHeaderTable table; |
| 6366 |
SendErrorHttpService service(table); |
| 6367 |
HttpServer server(timer, table, service, settings); |
| 6368 |
|
| 6369 |
auto stream = kj::heap<DisconnectingAsyncIoStream>(*pipe.ends[0]); |
| 6370 |
auto listenPromise = server.listenHttpCleanDrain(*stream); |
| 6371 |
|
| 6372 |
static constexpr auto request = "GET / HTTP/1.1\r\n\r\n"_kj; |
| 6373 |
pipe.ends[1]->write(request.begin(), request.size()).wait(waitScope); |
| 6374 |
pipe.ends[1]->shutdownWrite(); |
| 6375 |
|
| 6376 |
// Client races to read headers but not body, then disconnects. (Note that the following code |
| 6377 |
// doesn't reliably reproduce the race condition by itself -- DisconnectingAsyncIoStream is |
| 6378 |
// needed to ensure the disconnected exception throws on the correct write promise.) |
| 6379 |
expectRead(*pipe.ends[1], |
| 6380 |
"HTTP/1.1 404 Not Found\r\n" |
| 6381 |
"Content-Length: 9\r\n" |
| 6382 |
"\r\n"_kj).wait(waitScope); |
| 6383 |
pipe.ends[1] = nullptr; |
| 6384 |
|
| 6385 |
// The race condition failure would manifest as a "previous HTTP message body incomplete" |
| 6386 |
// "FAILED" exception here: |
| 6387 |
bool canReuse = listenPromise.wait(waitScope); |
| 6388 |
|
| 6389 |
KJ_ASSERT(!canReuse); |
| 6390 |
KJ_ASSERT(stream->writeCount == 2); |
| 6391 |
KJ_ASSERT(testErrorHandler.applicationErrorCount == 1); |
| 6392 |
} |
| 6393 |
|
| 6394 |
// ======================================================================================= |
| 6395 |
// CONNECT tests |
| 6396 |
|
| 6397 |
class ConnectEchoService final: public HttpService { |
| 6398 |
// A simple CONNECT echo. It will always accept, and whatever data it |
| 6399 |
// receives will be echoed back. |
| 6400 |
public: |
| 6401 |
ConnectEchoService(HttpHeaderTable& headerTable, uint statusCodeToSend = 200) |
| 6402 |
: headerTable(headerTable), |
| 6403 |
statusCodeToSend(statusCodeToSend) { |
| 6404 |
KJ_ASSERT(statusCodeToSend >= 200 && statusCodeToSend < 300); |
| 6405 |
} |
| 6406 |
|
| 6407 |
uint connectCount = 0; |
| 6408 |
|
| 6409 |
kj::Promise<void> request( |
| 6410 |
HttpMethod method, kj::StringPtr url, const HttpHeaders& headers, |
| 6411 |
kj::AsyncInputStream& requestBody, Response& response) override { |
| 6412 |
KJ_UNIMPLEMENTED("Regular HTTP requests are not implemented here."); |
| 6413 |
} |
| 6414 |
|
| 6415 |
kj::Promise<void> connect(kj::StringPtr host, |
| 6416 |
const HttpHeaders& headers, |
| 6417 |
kj::AsyncIoStream& connection, |
| 6418 |
ConnectResponse& response, |
| 6419 |
kj::HttpConnectSettings settings) override { |
| 6420 |
connectCount++; |
| 6421 |
response.accept(statusCodeToSend, "OK", HttpHeaders(headerTable)); |
| 6422 |
return connection.pumpTo(connection).ignoreResult(); |
| 6423 |
} |
| 6424 |
|
| 6425 |
private: |
| 6426 |
HttpHeaderTable& headerTable; |
| 6427 |
uint statusCodeToSend; |
| 6428 |
}; |
| 6429 |
|
| 6430 |
class ConnectRejectService final: public HttpService { |
| 6431 |
// A simple CONNECT implementation that always rejects. |
| 6432 |
public: |
| 6433 |
ConnectRejectService(HttpHeaderTable& headerTable, uint statusCodeToSend = 400) |
| 6434 |
: headerTable(headerTable), |
| 6435 |
statusCodeToSend(statusCodeToSend) { |
| 6436 |
KJ_ASSERT(statusCodeToSend >= 300); |
| 6437 |
} |
| 6438 |
|
| 6439 |
uint connectCount = 0; |
| 6440 |
|
| 6441 |
kj::Promise<void> request( |
| 6442 |
HttpMethod method, kj::StringPtr url, const HttpHeaders& headers, |
| 6443 |
kj::AsyncInputStream& requestBody, Response& response) override { |
| 6444 |
KJ_UNIMPLEMENTED("Regular HTTP requests are not implemented here."); |
| 6445 |
} |
| 6446 |
|
| 6447 |
kj::Promise<void> connect(kj::StringPtr host, |
| 6448 |
const HttpHeaders& headers, |
| 6449 |
kj::AsyncIoStream& connection, |
| 6450 |
ConnectResponse& response, |
| 6451 |
kj::HttpConnectSettings settings) override { |
| 6452 |
connectCount++; |
| 6453 |
auto out = response.reject(statusCodeToSend, "Failed"_kj, HttpHeaders(headerTable), 4); |
| 6454 |
return out->write("boom", 4).attach(kj::mv(out)); |
| 6455 |
} |
| 6456 |
|
| 6457 |
private: |
| 6458 |
HttpHeaderTable& headerTable; |
| 6459 |
uint statusCodeToSend; |
| 6460 |
}; |
| 6461 |
|
| 6462 |
class ConnectCancelReadService final: public HttpService { |
| 6463 |
// A simple CONNECT server that will accept a connection then immediately |
| 6464 |
// cancel reading from it to test handling of abrupt termination. |
| 6465 |
public: |
| 6466 |
ConnectCancelReadService(HttpHeaderTable& headerTable) |
| 6467 |
: headerTable(headerTable) {} |
| 6468 |
|
| 6469 |
kj::Promise<void> request( |
| 6470 |
HttpMethod method, kj::StringPtr url, const HttpHeaders& headers, |
| 6471 |
kj::AsyncInputStream& requestBody, Response& response) override { |
| 6472 |
KJ_UNIMPLEMENTED("Regular HTTP requests are not implemented here."); |
| 6473 |
} |
| 6474 |
|
| 6475 |
kj::Promise<void> connect(kj::StringPtr host, |
| 6476 |
const HttpHeaders& headers, |
| 6477 |
kj::AsyncIoStream& connection, |
| 6478 |
ConnectResponse& response, |
| 6479 |
kj::HttpConnectSettings settings) override { |
| 6480 |
response.accept(200, "OK", HttpHeaders(headerTable)); |
| 6481 |
// Return an immediately resolved promise and drop the connection |
| 6482 |
return kj::READY_NOW; |
| 6483 |
} |
| 6484 |
|
| 6485 |
private: |
| 6486 |
HttpHeaderTable& headerTable; |
| 6487 |
}; |
| 6488 |
|
| 6489 |
class ConnectCancelWriteService final: public HttpService { |
| 6490 |
// A simple CONNECT server that will accept a connection then immediately |
| 6491 |
// cancel writing to it to test handling of abrupt termination. |
| 6492 |
public: |
| 6493 |
ConnectCancelWriteService(HttpHeaderTable& headerTable) |
| 6494 |
: headerTable(headerTable) {} |
| 6495 |
|
| 6496 |
kj::Promise<void> request( |
| 6497 |
HttpMethod method, kj::StringPtr url, const HttpHeaders& headers, |
| 6498 |
kj::AsyncInputStream& requestBody, Response& response) override { |
| 6499 |
KJ_UNIMPLEMENTED("Regular HTTP requests are not implemented here."); |
| 6500 |
} |
| 6501 |
|
| 6502 |
kj::Promise<void> connect(kj::StringPtr host, |
| 6503 |
const HttpHeaders& headers, |
| 6504 |
kj::AsyncIoStream& connection, |
| 6505 |
ConnectResponse& response, |
| 6506 |
kj::HttpConnectSettings settings) override { |
| 6507 |
response.accept(200, "OK", HttpHeaders(headerTable)); |
| 6508 |
|
| 6509 |
auto msg = "hello"_kj; |
| 6510 |
auto promise KJ_UNUSED = connection.write(msg.begin(), 5); |
| 6511 |
|
| 6512 |
// Return an immediately resolved promise and drop the io |
| 6513 |
return kj::READY_NOW; |
| 6514 |
} |
| 6515 |
|
| 6516 |
private: |
| 6517 |
HttpHeaderTable& headerTable; |
| 6518 |
}; |
| 6519 |
|
| 6520 |
class ConnectHttpService final: public HttpService { |
| 6521 |
// A CONNECT service that tunnels HTTP requests just to verify that, yes, the CONNECT |
| 6522 |
// impl can actually tunnel actual protocols. |
| 6523 |
public: |
| 6524 |
ConnectHttpService(HttpHeaderTable& table) |
| 6525 |
: timer(kj::origin<kj::TimePoint>()), |
| 6526 |
tunneledService(table), |
| 6527 |
server(timer, table, tunneledService) {} |
| 6528 |
private: |
| 6529 |
|
| 6530 |
kj::Promise<void> request( |
| 6531 |
HttpMethod method, kj::StringPtr url, const HttpHeaders& headers, |
| 6532 |
kj::AsyncInputStream& requestBody, Response& response) override { |
| 6533 |
KJ_UNIMPLEMENTED("Regular HTTP requests are not implemented here."); |
| 6534 |
} |
| 6535 |
|
| 6536 |
kj::Promise<void> connect(kj::StringPtr host, |
| 6537 |
const HttpHeaders& headers, |
| 6538 |
kj::AsyncIoStream& connection, |
| 6539 |
ConnectResponse& response, |
| 6540 |
kj::HttpConnectSettings settings) override { |
| 6541 |
response.accept(200, "OK", HttpHeaders(tunneledService.table)); |
| 6542 |
return server.listenHttp(kj::Own<kj::AsyncIoStream>(&connection, kj::NullDisposer::instance)); |
| 6543 |
} |
| 6544 |
|
| 6545 |
class SimpleHttpService final: public HttpService { |
| 6546 |
public: |
| 6547 |
SimpleHttpService(HttpHeaderTable& table) : table(table) {} |
| 6548 |
kj::Promise<void> request( |
| 6549 |
HttpMethod method, kj::StringPtr url, const HttpHeaders& headers, |
| 6550 |
kj::AsyncInputStream& requestBody, Response& response) override { |
| 6551 |
auto out = response.send(200, "OK"_kj, HttpHeaders(table)); |
| 6552 |
auto msg = "hello there"_kj; |
| 6553 |
return out->write(msg.begin(), 11).attach(kj::mv(out)); |
| 6554 |
} |
| 6555 |
|
| 6556 |
HttpHeaderTable& table; |
| 6557 |
}; |
| 6558 |
|
| 6559 |
kj::TimerImpl timer; |
| 6560 |
SimpleHttpService tunneledService; |
| 6561 |
HttpServer server; |
| 6562 |
}; |
| 6563 |
|
| 6564 |
class ConnectCloseService final: public HttpService { |
| 6565 |
// A simple CONNECT server that will accept a connection then immediately |
| 6566 |
// shutdown the write side of the AsyncIoStream to simulate socket disconnection. |
| 6567 |
public: |
| 6568 |
ConnectCloseService(HttpHeaderTable& headerTable) |
| 6569 |
: headerTable(headerTable) {} |
| 6570 |
|
| 6571 |
kj::Promise<void> request( |
| 6572 |
HttpMethod method, kj::StringPtr url, const HttpHeaders& headers, |
| 6573 |
kj::AsyncInputStream& requestBody, Response& response) override { |
| 6574 |
KJ_UNIMPLEMENTED("Regular HTTP requests are not implemented here."); |
| 6575 |
} |
| 6576 |
|
| 6577 |
kj::Promise<void> connect(kj::StringPtr host, |
| 6578 |
const HttpHeaders& headers, |
| 6579 |
kj::AsyncIoStream& connection, |
| 6580 |
ConnectResponse& response, |
| 6581 |
kj::HttpConnectSettings settings) override { |
| 6582 |
response.accept(200, "OK", HttpHeaders(headerTable)); |
| 6583 |
connection.shutdownWrite(); |
| 6584 |
return kj::READY_NOW; |
| 6585 |
} |
| 6586 |
|
| 6587 |
private: |
| 6588 |
HttpHeaderTable& headerTable; |
| 6589 |
}; |
| 6590 |
|
| 6591 |
KJ_TEST("Simple CONNECT Server works") { |
| 6592 |
KJ_HTTP_TEST_SETUP_IO; |
| 6593 |
|
| 6594 |
auto pipe = KJ_HTTP_TEST_CREATE_2PIPE; |
| 6595 |
|
| 6596 |
kj::TimerImpl timer(kj::origin<kj::TimePoint>()); |
| 6597 |
|
| 6598 |
HttpHeaderTable table; |
| 6599 |
ConnectEchoService service(table); |
| 6600 |
HttpServer server(timer, table, service); |
| 6601 |
|
| 6602 |
auto listenTask = server.listenHttp(kj::mv(pipe.ends[0])); |
| 6603 |
|
| 6604 |
auto msg = "CONNECT https://example.org HTTP/1.1\r\n" |
| 6605 |
"\r\n" |
| 6606 |
"hello"_kj; |
| 6607 |
|
| 6608 |
pipe.ends[1]->write(msg.begin(), msg.size()).wait(waitScope); |
| 6609 |
pipe.ends[1]->shutdownWrite(); |
| 6610 |
|
| 6611 |
expectRead(*pipe.ends[1], |
| 6612 |
"HTTP/1.1 200 OK\r\n" |
| 6613 |
"\r\n" |
| 6614 |
"hello"_kj).wait(waitScope); |
| 6615 |
|
| 6616 |
expectEnd(*pipe.ends[1]); |
| 6617 |
|
| 6618 |
listenTask.wait(waitScope); |
| 6619 |
|
| 6620 |
KJ_ASSERT(service.connectCount == 1); |
| 6621 |
} |
| 6622 |
|
| 6623 |
KJ_TEST("Simple CONNECT Client/Server works") { |
| 6624 |
KJ_HTTP_TEST_SETUP_IO; |
| 6625 |
|
| 6626 |
auto pipe = KJ_HTTP_TEST_CREATE_2PIPE; |
| 6627 |
|
| 6628 |
kj::TimerImpl timer(kj::origin<kj::TimePoint>()); |
| 6629 |
|
| 6630 |
HttpHeaderTable table; |
| 6631 |
ConnectEchoService service(table); |
| 6632 |
HttpServer server(timer, table, service); |
| 6633 |
|
| 6634 |
auto listenTask = server.listenHttp(kj::mv(pipe.ends[0])); |
| 6635 |
|
| 6636 |
auto client = newHttpClient(table, *pipe.ends[1]); |
| 6637 |
|
| 6638 |
HttpHeaderTable clientHeaders; |
| 6639 |
// Initiates a CONNECT with the echo server. Once established, sends a bit of data |
| 6640 |
// and waits for it to be echoed back. |
| 6641 |
auto request = client->connect( |
| 6642 |
"https://example.org"_kj, HttpHeaders(clientHeaders), {}); |
| 6643 |
|
| 6644 |
request.status.then([io=kj::mv(request.connection)](auto status) mutable { |
| 6645 |
KJ_ASSERT(status.statusCode == 200); |
| 6646 |
KJ_ASSERT(status.statusText == "OK"_kj); |
| 6647 |
|
| 6648 |
auto promises = kj::heapArrayBuilder<kj::Promise<void>>(2); |
| 6649 |
promises.add(io->write("hello", 5)); |
| 6650 |
promises.add(expectRead(*io, "hello"_kj)); |
| 6651 |
return kj::joinPromises(promises.finish()) |
| 6652 |
.then([io=kj::mv(io)]() mutable { |
| 6653 |
io->shutdownWrite(); |
| 6654 |
return expectEnd(*io).attach(kj::mv(io)); |
| 6655 |
}); |
| 6656 |
}).wait(waitScope); |
| 6657 |
|
| 6658 |
listenTask.wait(waitScope); |
| 6659 |
|
| 6660 |
KJ_ASSERT(service.connectCount == 1); |
| 6661 |
} |
| 6662 |
|
| 6663 |
KJ_TEST("CONNECT Server (201 status)") { |
| 6664 |
KJ_HTTP_TEST_SETUP_IO; |
| 6665 |
|
| 6666 |
// Test that CONNECT works with 2xx status codes that typically do |
| 6667 |
// not carry a response payload. |
| 6668 |
|
| 6669 |
auto pipe = KJ_HTTP_TEST_CREATE_2PIPE; |
| 6670 |
|
| 6671 |
kj::TimerImpl timer(kj::origin<kj::TimePoint>()); |
| 6672 |
|
| 6673 |
HttpHeaderTable table; |
| 6674 |
ConnectEchoService service(table, 201); |
| 6675 |
HttpServer server(timer, table, service); |
| 6676 |
|
| 6677 |
auto listenTask = server.listenHttp(kj::mv(pipe.ends[0])); |
| 6678 |
|
| 6679 |
auto msg = "CONNECT https://example.org HTTP/1.1\r\n" |
| 6680 |
"\r\n" |
| 6681 |
"hello"_kj; |
| 6682 |
|
| 6683 |
pipe.ends[1]->write(msg.begin(), msg.size()).wait(waitScope); |
| 6684 |
pipe.ends[1]->shutdownWrite(); |
| 6685 |
|
| 6686 |
expectRead(*pipe.ends[1], |
| 6687 |
"HTTP/1.1 201 OK\r\n" |
| 6688 |
"\r\n" |
| 6689 |
"hello"_kj).wait(waitScope); |
| 6690 |
|
| 6691 |
expectEnd(*pipe.ends[1]); |
| 6692 |
|
| 6693 |
listenTask.wait(waitScope); |
| 6694 |
|
| 6695 |
KJ_ASSERT(service.connectCount == 1); |
| 6696 |
} |
| 6697 |
|
| 6698 |
KJ_TEST("CONNECT Client (204 status)") { |
| 6699 |
KJ_HTTP_TEST_SETUP_IO; |
| 6700 |
|
| 6701 |
auto pipe = KJ_HTTP_TEST_CREATE_2PIPE; |
| 6702 |
|
| 6703 |
// Test that CONNECT works with 2xx status codes that typically do |
| 6704 |
// not carry a response payload. |
| 6705 |
|
| 6706 |
kj::TimerImpl timer(kj::origin<kj::TimePoint>()); |
| 6707 |
|
| 6708 |
HttpHeaderTable table; |
| 6709 |
ConnectEchoService service(table, 204); |
| 6710 |
HttpServer server(timer, table, service); |
| 6711 |
|
| 6712 |
auto listenTask = server.listenHttp(kj::mv(pipe.ends[0])); |
| 6713 |
|
| 6714 |
auto client = newHttpClient(table, *pipe.ends[1]); |
| 6715 |
|
| 6716 |
HttpHeaderTable clientHeaders; |
| 6717 |
// Initiates a CONNECT with the echo server. Once established, sends a bit of data |
| 6718 |
// and waits for it to be echoed back. |
| 6719 |
auto request = client->connect( |
| 6720 |
"https://example.org"_kj, HttpHeaders(clientHeaders), {}); |
| 6721 |
|
| 6722 |
request.status.then([io=kj::mv(request.connection)](auto status) mutable { |
| 6723 |
KJ_ASSERT(status.statusCode == 204); |
| 6724 |
KJ_ASSERT(status.statusText == "OK"_kj); |
| 6725 |
|
| 6726 |
auto promises = kj::heapArrayBuilder<kj::Promise<void>>(2); |
| 6727 |
promises.add(io->write("hello", 5)); |
| 6728 |
promises.add(expectRead(*io, "hello"_kj)); |
| 6729 |
|
| 6730 |
return kj::joinPromises(promises.finish()) |
| 6731 |
.then([io=kj::mv(io)]() mutable { |
| 6732 |
io->shutdownWrite(); |
| 6733 |
return expectEnd(*io).attach(kj::mv(io)); |
| 6734 |
}); |
| 6735 |
}).wait(waitScope); |
| 6736 |
|
| 6737 |
listenTask.wait(waitScope); |
| 6738 |
|
| 6739 |
KJ_ASSERT(service.connectCount == 1); |
| 6740 |
} |
| 6741 |
|
| 6742 |
KJ_TEST("CONNECT Server rejected") { |
| 6743 |
KJ_HTTP_TEST_SETUP_IO; |
| 6744 |
|
| 6745 |
auto pipe = KJ_HTTP_TEST_CREATE_2PIPE; |
| 6746 |
|
| 6747 |
kj::TimerImpl timer(kj::origin<kj::TimePoint>()); |
| 6748 |
|
| 6749 |
HttpHeaderTable table; |
| 6750 |
ConnectRejectService service(table); |
| 6751 |
HttpServer server(timer, table, service); |
| 6752 |
|
| 6753 |
auto listenTask = server.listenHttp(kj::mv(pipe.ends[0])); |
| 6754 |
|
| 6755 |
auto msg = "CONNECT https://example.org HTTP/1.1\r\n" |
| 6756 |
"\r\n" |
| 6757 |
"hello"_kj; |
| 6758 |
|
| 6759 |
pipe.ends[1]->write(msg.begin(), msg.size()).wait(waitScope); |
| 6760 |
pipe.ends[1]->shutdownWrite(); |
| 6761 |
|
| 6762 |
expectRead(*pipe.ends[1], |
| 6763 |
"HTTP/1.1 400 Failed\r\n" |
| 6764 |
"Connection: close\r\n" |
| 6765 |
"Content-Length: 4\r\n" |
| 6766 |
"\r\n" |
| 6767 |
"boom"_kj).wait(waitScope); |
| 6768 |
|
| 6769 |
expectEnd(*pipe.ends[1]); |
| 6770 |
|
| 6771 |
listenTask.wait(waitScope); |
| 6772 |
|
| 6773 |
KJ_ASSERT(service.connectCount == 1); |
| 6774 |
} |
| 6775 |
|
| 6776 |
#ifndef KJ_HTTP_TEST_USE_OS_PIPE |
| 6777 |
KJ_TEST("CONNECT Client rejected") { |
| 6778 |
KJ_HTTP_TEST_SETUP_IO; |
| 6779 |
|
| 6780 |
auto pipe = KJ_HTTP_TEST_CREATE_2PIPE; |
| 6781 |
|
| 6782 |
kj::TimerImpl timer(kj::origin<kj::TimePoint>()); |
| 6783 |
|
| 6784 |
HttpHeaderTable table; |
| 6785 |
ConnectRejectService service(table); |
| 6786 |
HttpServer server(timer, table, service); |
| 6787 |
|
| 6788 |
auto listenTask = server.listenHttp(kj::mv(pipe.ends[0])); |
| 6789 |
|
| 6790 |
auto client = newHttpClient(table, *pipe.ends[1]); |
| 6791 |
|
| 6792 |
HttpHeaderTable clientHeaders; |
| 6793 |
auto request = client->connect( |
| 6794 |
"https://example.org"_kj, HttpHeaders(clientHeaders), {}); |
| 6795 |
|
| 6796 |
request.status.then([](auto status) mutable { |
| 6797 |
KJ_ASSERT(status.statusCode == 400); |
| 6798 |
KJ_ASSERT(status.statusText == "Failed"_kj); |
| 6799 |
|
| 6800 |
auto& errorBody = KJ_ASSERT_NONNULL(status.errorBody); |
| 6801 |
|
| 6802 |
return expectRead(*errorBody, "boom"_kj).then([&errorBody=*errorBody]() { |
| 6803 |
return expectEnd(errorBody); |
| 6804 |
}).attach(kj::mv(errorBody)); |
| 6805 |
}).wait(waitScope); |
| 6806 |
|
| 6807 |
listenTask.wait(waitScope); |
| 6808 |
|
| 6809 |
KJ_ASSERT(service.connectCount == 1); |
| 6810 |
} |
| 6811 |
#endif |
| 6812 |
|
| 6813 |
KJ_TEST("CONNECT Server cancels read") { |
| 6814 |
KJ_HTTP_TEST_SETUP_IO; |
| 6815 |
|
| 6816 |
auto pipe = KJ_HTTP_TEST_CREATE_2PIPE; |
| 6817 |
|
| 6818 |
kj::TimerImpl timer(kj::origin<kj::TimePoint>()); |
| 6819 |
|
| 6820 |
HttpHeaderTable table; |
| 6821 |
ConnectCancelReadService service(table); |
| 6822 |
HttpServer server(timer, table, service); |
| 6823 |
|
| 6824 |
auto listenTask = server.listenHttp(kj::mv(pipe.ends[0])); |
| 6825 |
|
| 6826 |
auto msg = "CONNECT https://example.org HTTP/1.1\r\n" |
| 6827 |
"\r\n" |
| 6828 |
"hello"_kj; |
| 6829 |
|
| 6830 |
pipe.ends[1]->write(msg.begin(), msg.size()).wait(waitScope); |
| 6831 |
pipe.ends[1]->shutdownWrite(); |
| 6832 |
|
| 6833 |
expectRead(*pipe.ends[1], |
| 6834 |
"HTTP/1.1 200 OK\r\n" |
| 6835 |
"\r\n"_kj).wait(waitScope); |
| 6836 |
|
| 6837 |
expectEnd(*pipe.ends[1]); |
| 6838 |
|
| 6839 |
listenTask.wait(waitScope); |
| 6840 |
} |
| 6841 |
|
| 6842 |
#ifndef KJ_HTTP_TEST_USE_OS_PIPE |
| 6843 |
KJ_TEST("CONNECT Server cancels read w/client") { |
| 6844 |
KJ_HTTP_TEST_SETUP_IO; |
| 6845 |
|
| 6846 |
auto pipe = KJ_HTTP_TEST_CREATE_2PIPE; |
| 6847 |
|
| 6848 |
kj::TimerImpl timer(kj::origin<kj::TimePoint>()); |
| 6849 |
|
| 6850 |
HttpHeaderTable table; |
| 6851 |
ConnectCancelReadService service(table); |
| 6852 |
HttpServer server(timer, table, service); |
| 6853 |
|
| 6854 |
auto listenTask = server.listenHttp(kj::mv(pipe.ends[0])); |
| 6855 |
|
| 6856 |
auto client = newHttpClient(table, *pipe.ends[1]); |
| 6857 |
bool failed = false; |
| 6858 |
|
| 6859 |
HttpHeaderTable clientHeaders; |
| 6860 |
auto request = client->connect( |
| 6861 |
"https://example.org"_kj, HttpHeaders(clientHeaders), {}); |
| 6862 |
|
| 6863 |
request.status.then([&failed, io=kj::mv(request.connection)](auto status) mutable { |
| 6864 |
KJ_ASSERT(status.statusCode == 200); |
| 6865 |
KJ_ASSERT(status.statusText == "OK"_kj); |
| 6866 |
|
| 6867 |
return io->write("hello", 5).catch_([&](kj::Exception&& ex) { |
| 6868 |
KJ_ASSERT(ex.getType() == kj::Exception::Type::DISCONNECTED); |
| 6869 |
failed = true; |
| 6870 |
}).attach(kj::mv(io)); |
| 6871 |
}).wait(waitScope); |
| 6872 |
|
| 6873 |
KJ_ASSERT(failed, "the write promise should have failed"); |
| 6874 |
|
| 6875 |
listenTask.wait(waitScope); |
| 6876 |
} |
| 6877 |
#endif |
| 6878 |
|
| 6879 |
KJ_TEST("CONNECT Server cancels write") { |
| 6880 |
KJ_HTTP_TEST_SETUP_IO; |
| 6881 |
|
| 6882 |
auto pipe = KJ_HTTP_TEST_CREATE_2PIPE; |
| 6883 |
|
| 6884 |
kj::TimerImpl timer(kj::origin<kj::TimePoint>()); |
| 6885 |
|
| 6886 |
HttpHeaderTable table; |
| 6887 |
ConnectCancelWriteService service(table); |
| 6888 |
HttpServer server(timer, table, service); |
| 6889 |
|
| 6890 |
auto listenTask = server.listenHttp(kj::mv(pipe.ends[0])); |
| 6891 |
|
| 6892 |
auto msg = "CONNECT https://example.org HTTP/1.1\r\n" |
| 6893 |
"\r\n" |
| 6894 |
"hello"_kj; |
| 6895 |
|
| 6896 |
pipe.ends[1]->write(msg.begin(), msg.size()).wait(waitScope); |
| 6897 |
pipe.ends[1]->shutdownWrite(); |
| 6898 |
|
| 6899 |
expectRead(*pipe.ends[1], |
| 6900 |
"HTTP/1.1 200 OK\r\n" |
| 6901 |
"\r\n"_kj).wait(waitScope); |
| 6902 |
|
| 6903 |
expectEnd(*pipe.ends[1]); |
| 6904 |
|
| 6905 |
listenTask.wait(waitScope); |
| 6906 |
} |
| 6907 |
|
| 6908 |
#ifndef KJ_HTTP_TEST_USE_OS_PIPE |
| 6909 |
KJ_TEST("CONNECT Server cancels write w/client") { |
| 6910 |
KJ_HTTP_TEST_SETUP_IO; |
| 6911 |
|
| 6912 |
auto pipe = KJ_HTTP_TEST_CREATE_2PIPE; |
| 6913 |
|
| 6914 |
kj::TimerImpl timer(kj::origin<kj::TimePoint>()); |
| 6915 |
|
| 6916 |
HttpHeaderTable table; |
| 6917 |
ConnectCancelWriteService service(table); |
| 6918 |
HttpServer server(timer, table, service); |
| 6919 |
|
| 6920 |
auto listenTask = server.listenHttp(kj::mv(pipe.ends[0])); |
| 6921 |
|
| 6922 |
auto client = newHttpClient(table, *pipe.ends[1]); |
| 6923 |
|
| 6924 |
HttpHeaderTable clientHeaders; |
| 6925 |
bool failed = false; |
| 6926 |
auto request = client->connect( |
| 6927 |
"https://example.org"_kj, HttpHeaders(clientHeaders), {}); |
| 6928 |
|
| 6929 |
request.status.then([&failed, io=kj::mv(request.connection)](auto status) mutable { |
| 6930 |
KJ_ASSERT(status.statusCode == 200); |
| 6931 |
KJ_ASSERT(status.statusText == "OK"_kj); |
| 6932 |
|
| 6933 |
return io->write("hello", 5).catch_([&failed](kj::Exception&& ex) mutable { |
| 6934 |
KJ_ASSERT(ex.getType() == kj::Exception::Type::DISCONNECTED); |
| 6935 |
failed = true; |
| 6936 |
}).attach(kj::mv(io)); |
| 6937 |
}).wait(waitScope); |
| 6938 |
|
| 6939 |
KJ_ASSERT(failed, "the write promise should have failed"); |
| 6940 |
|
| 6941 |
listenTask.wait(waitScope); |
| 6942 |
} |
| 6943 |
#endif |
| 6944 |
|
| 6945 |
KJ_TEST("CONNECT rejects Transfer-Encoding") { |
| 6946 |
KJ_HTTP_TEST_SETUP_IO; |
| 6947 |
|
| 6948 |
auto pipe = KJ_HTTP_TEST_CREATE_2PIPE; |
| 6949 |
|
| 6950 |
kj::TimerImpl timer(kj::origin<kj::TimePoint>()); |
| 6951 |
|
| 6952 |
HttpHeaderTable table; |
| 6953 |
ConnectEchoService service(table); |
| 6954 |
HttpServer server(timer, table, service); |
| 6955 |
|
| 6956 |
auto listenTask = server.listenHttp(kj::mv(pipe.ends[0])); |
| 6957 |
|
| 6958 |
auto msg = "CONNECT https://example.org HTTP/1.1\r\n" |
| 6959 |
"Transfer-Encoding: chunked\r\n" |
| 6960 |
"\r\n" |
| 6961 |
"5\r\n" |
| 6962 |
"hello" |
| 6963 |
"0\r\n"_kj; |
| 6964 |
|
| 6965 |
pipe.ends[1]->write(msg.begin(), msg.size()).wait(waitScope); |
| 6966 |
pipe.ends[1]->shutdownWrite(); |
| 6967 |
|
| 6968 |
expectRead(*pipe.ends[1], |
| 6969 |
"HTTP/1.1 400 Bad Request\r\n" |
| 6970 |
"Connection: close\r\n" |
| 6971 |
"Content-Length: 18\r\n" |
| 6972 |
"Content-Type: text/plain\r\n" |
| 6973 |
"\r\n" |
| 6974 |
"ERROR: Bad Request"_kj).wait(waitScope); |
| 6975 |
|
| 6976 |
expectEnd(*pipe.ends[1]); |
| 6977 |
|
| 6978 |
listenTask.wait(waitScope); |
| 6979 |
} |
| 6980 |
|
| 6981 |
KJ_TEST("CONNECT rejects Content-Length") { |
| 6982 |
KJ_HTTP_TEST_SETUP_IO; |
| 6983 |
|
| 6984 |
auto pipe = KJ_HTTP_TEST_CREATE_2PIPE; |
| 6985 |
|
| 6986 |
kj::TimerImpl timer(kj::origin<kj::TimePoint>()); |
| 6987 |
|
| 6988 |
HttpHeaderTable table; |
| 6989 |
ConnectEchoService service(table); |
| 6990 |
HttpServer server(timer, table, service); |
| 6991 |
|
| 6992 |
auto listenTask = server.listenHttp(kj::mv(pipe.ends[0])); |
| 6993 |
|
| 6994 |
auto msg = "CONNECT https://example.org HTTP/1.1\r\n" |
| 6995 |
"Content-Length: 5\r\n" |
| 6996 |
"\r\n" |
| 6997 |
"hello"_kj; |
| 6998 |
|
| 6999 |
pipe.ends[1]->write(msg.begin(), msg.size()).wait(waitScope); |
| 7000 |
pipe.ends[1]->shutdownWrite(); |
| 7001 |
|
| 7002 |
expectRead(*pipe.ends[1], |
| 7003 |
"HTTP/1.1 400 Bad Request\r\n" |
| 7004 |
"Connection: close\r\n" |
| 7005 |
"Content-Length: 18\r\n" |
| 7006 |
"Content-Type: text/plain\r\n" |
| 7007 |
"\r\n" |
| 7008 |
"ERROR: Bad Request"_kj).wait(waitScope); |
| 7009 |
|
| 7010 |
expectEnd(*pipe.ends[1]); |
| 7011 |
|
| 7012 |
listenTask.wait(waitScope); |
| 7013 |
} |
| 7014 |
|
| 7015 |
KJ_TEST("CONNECT HTTP-tunneled-over-CONNECT") { |
| 7016 |
KJ_HTTP_TEST_SETUP_IO; |
| 7017 |
|
| 7018 |
auto pipe = KJ_HTTP_TEST_CREATE_2PIPE; |
| 7019 |
|
| 7020 |
kj::TimerImpl timer(kj::origin<kj::TimePoint>()); |
| 7021 |
HttpHeaderTable table; |
| 7022 |
ConnectHttpService service(table); |
| 7023 |
HttpServer server(timer, table, service); |
| 7024 |
|
| 7025 |
auto listenTask KJ_UNUSED = server.listenHttp(kj::mv(pipe.ends[0])); |
| 7026 |
|
| 7027 |
auto client = newHttpClient(table, *pipe.ends[1]); |
| 7028 |
|
| 7029 |
HttpHeaderTable connectHeaderTable; |
| 7030 |
HttpHeaderTable tunneledHeaderTable; |
| 7031 |
HttpClientSettings settings; |
| 7032 |
|
| 7033 |
auto request = client->connect( |
| 7034 |
"https://example.org"_kj, HttpHeaders(connectHeaderTable), {}); |
| 7035 |
|
| 7036 |
auto text = request.status.then([ |
| 7037 |
&tunneledHeaderTable, |
| 7038 |
&settings, |
| 7039 |
io=kj::mv(request.connection)](auto status) mutable { |
| 7040 |
KJ_ASSERT(status.statusCode == 200); |
| 7041 |
KJ_ASSERT(status.statusText == "OK"_kj); |
| 7042 |
auto client = newHttpClient(tunneledHeaderTable, *io, settings) |
| 7043 |
.attach(kj::mv(io)); |
| 7044 |
|
| 7045 |
return client->request(HttpMethod::GET, "http://example.org"_kj, |
| 7046 |
HttpHeaders(tunneledHeaderTable)) |
| 7047 |
.response.then([](HttpClient::Response&& response) { |
| 7048 |
return response.body->readAllText().attach(kj::mv(response)); |
| 7049 |
}).attach(kj::mv(client)); |
| 7050 |
}).wait(waitScope); |
| 7051 |
|
| 7052 |
KJ_ASSERT(text == "hello there"); |
| 7053 |
} |
| 7054 |
|
| 7055 |
KJ_TEST("CONNECT HTTP-tunneled-over-pipelined-CONNECT") { |
| 7056 |
KJ_HTTP_TEST_SETUP_IO; |
| 7057 |
|
| 7058 |
auto pipe = KJ_HTTP_TEST_CREATE_2PIPE; |
| 7059 |
|
| 7060 |
kj::TimerImpl timer(kj::origin<kj::TimePoint>()); |
| 7061 |
HttpHeaderTable table; |
| 7062 |
ConnectHttpService service(table); |
| 7063 |
HttpServer server(timer, table, service); |
| 7064 |
|
| 7065 |
auto listenTask KJ_UNUSED = server.listenHttp(kj::mv(pipe.ends[0])); |
| 7066 |
|
| 7067 |
auto client = newHttpClient(table, *pipe.ends[1]); |
| 7068 |
|
| 7069 |
HttpHeaderTable connectHeaderTable; |
| 7070 |
HttpHeaderTable tunneledHeaderTable; |
| 7071 |
HttpClientSettings settings; |
| 7072 |
|
| 7073 |
auto request = client->connect( |
| 7074 |
"https://exmaple.org"_kj, HttpHeaders(connectHeaderTable), {}); |
| 7075 |
auto conn = kj::mv(request.connection); |
| 7076 |
auto proxyClient = newHttpClient(tunneledHeaderTable, *conn, settings).attach(kj::mv(conn)); |
| 7077 |
|
| 7078 |
auto get = proxyClient->request(HttpMethod::GET, |
| 7079 |
"http://example.org"_kj, |
| 7080 |
HttpHeaders(tunneledHeaderTable)); |
| 7081 |
auto text = get.response.then([](HttpClient::Response&& response) mutable { |
| 7082 |
return response.body->readAllText().attach(kj::mv(response)); |
| 7083 |
}).attach(kj::mv(proxyClient)).wait(waitScope); |
| 7084 |
|
| 7085 |
KJ_ASSERT(text == "hello there"); |
| 7086 |
} |
| 7087 |
|
| 7088 |
KJ_TEST("CONNECT pipelined via an adapter") { |
| 7089 |
KJ_HTTP_TEST_SETUP_IO; |
| 7090 |
|
| 7091 |
auto pipe = KJ_HTTP_TEST_CREATE_2PIPE; |
| 7092 |
|
| 7093 |
kj::TimerImpl timer(kj::origin<kj::TimePoint>()); |
| 7094 |
HttpHeaderTable table; |
| 7095 |
ConnectHttpService service(table); |
| 7096 |
HttpServer server(timer, table, service); |
| 7097 |
|
| 7098 |
auto listenTask KJ_UNUSED = server.listenHttp(kj::mv(pipe.ends[0])); |
| 7099 |
|
| 7100 |
bool acceptCalled = false; |
| 7101 |
|
| 7102 |
auto client = newHttpClient(table, *pipe.ends[1]); |
| 7103 |
auto adaptedService = kj::newHttpService(*client).attach(kj::mv(client)); |
| 7104 |
|
| 7105 |
// adaptedService is an HttpService that wraps an HttpClient that sends |
| 7106 |
// a request to server. |
| 7107 |
|
| 7108 |
auto clientPipe = newTwoWayPipe(); |
| 7109 |
|
| 7110 |
struct ResponseImpl final: public HttpService::ConnectResponse { |
| 7111 |
bool& acceptCalled; |
| 7112 |
ResponseImpl(bool& acceptCalled) : acceptCalled(acceptCalled) {} |
| 7113 |
void accept(uint statusCode, kj::StringPtr statusText, const HttpHeaders& headers) override { |
| 7114 |
acceptCalled = true; |
| 7115 |
} |
| 7116 |
|
| 7117 |
kj::Own<kj::AsyncOutputStream> reject( |
| 7118 |
uint statusCode, |
| 7119 |
kj::StringPtr statusText, |
| 7120 |
const HttpHeaders& headers, |
| 7121 |
kj::Maybe<uint64_t> expectedBodySize) override { |
| 7122 |
KJ_UNREACHABLE; |
| 7123 |
} |
| 7124 |
}; |
| 7125 |
|
| 7126 |
ResponseImpl response(acceptCalled); |
| 7127 |
|
| 7128 |
HttpHeaderTable connectHeaderTable; |
| 7129 |
HttpHeaderTable tunneledHeaderTable; |
| 7130 |
HttpClientSettings settings; |
| 7131 |
|
| 7132 |
auto promise = adaptedService->connect("https://example.org"_kj, |
| 7133 |
HttpHeaders(connectHeaderTable), |
| 7134 |
*clientPipe.ends[0], |
| 7135 |
response, |
| 7136 |
{}).attach(kj::mv(clientPipe.ends[0])); |
| 7137 |
|
| 7138 |
auto proxyClient = newHttpClient(tunneledHeaderTable, *clientPipe.ends[1], settings) |
| 7139 |
.attach(kj::mv(clientPipe.ends[1])); |
| 7140 |
|
| 7141 |
auto text = proxyClient->request(HttpMethod::GET, |
| 7142 |
"http://example.org"_kj, |
| 7143 |
HttpHeaders(tunneledHeaderTable)) |
| 7144 |
.response.then([](HttpClient::Response&& response) mutable { |
| 7145 |
return response.body->readAllText().attach(kj::mv(response)); |
| 7146 |
}).wait(waitScope); |
| 7147 |
|
| 7148 |
KJ_ASSERT(acceptCalled); |
| 7149 |
KJ_ASSERT(text == "hello there"); |
| 7150 |
} |
| 7151 |
|
| 7152 |
KJ_TEST("CONNECT pipelined via an adapter (reject)") { |
| 7153 |
KJ_HTTP_TEST_SETUP_IO; |
| 7154 |
|
| 7155 |
auto pipe = KJ_HTTP_TEST_CREATE_2PIPE; |
| 7156 |
|
| 7157 |
kj::TimerImpl timer(kj::origin<kj::TimePoint>()); |
| 7158 |
HttpHeaderTable table; |
| 7159 |
ConnectRejectService service(table); |
| 7160 |
HttpServer server(timer, table, service); |
| 7161 |
|
| 7162 |
auto listenTask KJ_UNUSED = server.listenHttp(kj::mv(pipe.ends[0])); |
| 7163 |
|
| 7164 |
bool rejectCalled = false; |
| 7165 |
bool failedAsExpected = false; |
| 7166 |
|
| 7167 |
auto client = newHttpClient(table, *pipe.ends[1]); |
| 7168 |
auto adaptedService = kj::newHttpService(*client).attach(kj::mv(client)); |
| 7169 |
|
| 7170 |
// adaptedService is an HttpService that wraps an HttpClient that sends |
| 7171 |
// a request to server. |
| 7172 |
|
| 7173 |
auto clientPipe = newTwoWayPipe(); |
| 7174 |
|
| 7175 |
struct ResponseImpl final: public HttpService::ConnectResponse { |
| 7176 |
bool& rejectCalled; |
| 7177 |
kj::OneWayPipe pipe; |
| 7178 |
ResponseImpl(bool& rejectCalled) |
| 7179 |
: rejectCalled(rejectCalled), |
| 7180 |
pipe(kj::newOneWayPipe()) {} |
| 7181 |
void accept(uint statusCode, kj::StringPtr statusText, const HttpHeaders& headers) override { |
| 7182 |
KJ_UNREACHABLE; |
| 7183 |
} |
| 7184 |
|
| 7185 |
kj::Own<kj::AsyncOutputStream> reject( |
| 7186 |
uint statusCode, |
| 7187 |
kj::StringPtr statusText, |
| 7188 |
const HttpHeaders& headers, |
| 7189 |
kj::Maybe<uint64_t> expectedBodySize) override { |
| 7190 |
rejectCalled = true; |
| 7191 |
return kj::mv(pipe.out); |
| 7192 |
} |
| 7193 |
|
| 7194 |
kj::Own<kj::AsyncInputStream> getRejectStream() { |
| 7195 |
return kj::mv(pipe.in); |
| 7196 |
} |
| 7197 |
}; |
| 7198 |
|
| 7199 |
ResponseImpl response(rejectCalled); |
| 7200 |
|
| 7201 |
HttpHeaderTable connectHeaderTable; |
| 7202 |
HttpHeaderTable tunneledHeaderTable; |
| 7203 |
HttpClientSettings settings; |
| 7204 |
|
| 7205 |
auto promise = adaptedService->connect("https://example.org"_kj, |
| 7206 |
HttpHeaders(connectHeaderTable), |
| 7207 |
*clientPipe.ends[0], |
| 7208 |
response, |
| 7209 |
{}).attach(kj::mv(clientPipe.ends[0])); |
| 7210 |
|
| 7211 |
auto proxyClient = newHttpClient(tunneledHeaderTable, *clientPipe.ends[1], settings) |
| 7212 |
.attach(kj::mv(clientPipe.ends[1])); |
| 7213 |
|
| 7214 |
auto text = proxyClient->request(HttpMethod::GET, |
| 7215 |
"http://example.org"_kj, |
| 7216 |
HttpHeaders(tunneledHeaderTable)) |
| 7217 |
.response.then([](HttpClient::Response&& response) mutable { |
| 7218 |
return response.body->readAllText().attach(kj::mv(response)); |
| 7219 |
}, [&](kj::Exception&& ex) -> kj::Promise<kj::String> { |
| 7220 |
// We fully expect the stream to fail here. |
| 7221 |
if (ex.getDescription() == "stream disconnected prematurely") { |
| 7222 |
failedAsExpected = true; |
| 7223 |
} |
| 7224 |
return kj::str("ok"); |
| 7225 |
}).wait(waitScope); |
| 7226 |
|
| 7227 |
auto rejectStream = response.getRejectStream(); |
| 7228 |
|
| 7229 |
#ifndef KJ_HTTP_TEST_USE_OS_PIPE |
| 7230 |
expectRead(*rejectStream, "boom"_kj).wait(waitScope); |
| 7231 |
#endif |
| 7232 |
|
| 7233 |
KJ_ASSERT(rejectCalled); |
| 7234 |
KJ_ASSERT(failedAsExpected); |
| 7235 |
KJ_ASSERT(text == "ok"); |
| 7236 |
} |
| 7237 |
|
| 7238 |
} // namespace |
| 7239 |
} // namespace kj |