http-test.c++ 102 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
// Copyright (c) 2017 Sandstorm Development Group, Inc. and contributors
// Licensed under the MIT License:
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

22 23
#define KJ_TESTING_KJ 1

24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121
#include "http.h"
#include <kj/debug.h>
#include <kj/test.h>
#include <map>

namespace kj {
namespace {

KJ_TEST("HttpMethod parse / stringify") {
#define TRY(name) \
  KJ_EXPECT(kj::str(HttpMethod::name) == #name); \
  KJ_IF_MAYBE(parsed, tryParseHttpMethod(#name)) { \
    KJ_EXPECT(*parsed == HttpMethod::name); \
  } else { \
    KJ_FAIL_EXPECT("couldn't parse \"" #name "\" as HttpMethod"); \
  }

  KJ_HTTP_FOR_EACH_METHOD(TRY)
#undef TRY

  KJ_EXPECT(tryParseHttpMethod("FOO") == nullptr);
  KJ_EXPECT(tryParseHttpMethod("") == nullptr);
  KJ_EXPECT(tryParseHttpMethod("G") == nullptr);
  KJ_EXPECT(tryParseHttpMethod("GE") == nullptr);
  KJ_EXPECT(tryParseHttpMethod("GET ") == nullptr);
  KJ_EXPECT(tryParseHttpMethod("get") == nullptr);
}

KJ_TEST("HttpHeaderTable") {
  HttpHeaderTable::Builder builder;

  auto host = builder.add("Host");
  auto host2 = builder.add("hOsT");
  auto fooBar = builder.add("Foo-Bar");
  auto bazQux = builder.add("baz-qux");
  auto bazQux2 = builder.add("Baz-Qux");

  auto table = builder.build();

  uint builtinHeaderCount = 0;
#define INCREMENT(id, name) ++builtinHeaderCount;
  KJ_HTTP_FOR_EACH_BUILTIN_HEADER(INCREMENT)
#undef INCREMENT

  KJ_EXPECT(table->idCount() == builtinHeaderCount + 2);

  KJ_EXPECT(host == HttpHeaderId::HOST);
  KJ_EXPECT(host != HttpHeaderId::DATE);
  KJ_EXPECT(host2 == host);

  KJ_EXPECT(host != fooBar);
  KJ_EXPECT(host != bazQux);
  KJ_EXPECT(fooBar != bazQux);
  KJ_EXPECT(bazQux == bazQux2);

  KJ_EXPECT(kj::str(host) == "Host");
  KJ_EXPECT(kj::str(host2) == "Host");
  KJ_EXPECT(kj::str(fooBar) == "Foo-Bar");
  KJ_EXPECT(kj::str(bazQux) == "baz-qux");
  KJ_EXPECT(kj::str(HttpHeaderId::HOST) == "Host");

  KJ_EXPECT(table->idToString(HttpHeaderId::DATE) == "Date");
  KJ_EXPECT(table->idToString(fooBar) == "Foo-Bar");

  KJ_EXPECT(KJ_ASSERT_NONNULL(table->stringToId("Date")) == HttpHeaderId::DATE);
  KJ_EXPECT(KJ_ASSERT_NONNULL(table->stringToId("dATE")) == HttpHeaderId::DATE);
  KJ_EXPECT(KJ_ASSERT_NONNULL(table->stringToId("Foo-Bar")) == fooBar);
  KJ_EXPECT(KJ_ASSERT_NONNULL(table->stringToId("foo-BAR")) == fooBar);
  KJ_EXPECT(table->stringToId("foobar") == nullptr);
  KJ_EXPECT(table->stringToId("barfoo") == nullptr);
}

KJ_TEST("HttpHeaders::parseRequest") {
  HttpHeaderTable::Builder builder;

  auto fooBar = builder.add("Foo-Bar");
  auto bazQux = builder.add("baz-qux");

  auto table = builder.build();

  HttpHeaders headers(*table);
  auto text = kj::heapString(
      "POST   /some/path \t   HTTP/1.1\r\n"
      "Foo-BaR: Baz\r\n"
      "Host: example.com\r\n"
      "Content-Length: 123\r\n"
      "DATE:     early\r\n"
      "other-Header: yep\r\n"
      "\r\n");
  auto result = KJ_ASSERT_NONNULL(headers.tryParseRequest(text.asArray()));

  KJ_EXPECT(result.method == HttpMethod::POST);
  KJ_EXPECT(result.url == "/some/path");
  KJ_EXPECT(KJ_ASSERT_NONNULL(headers.get(HttpHeaderId::HOST)) == "example.com");
  KJ_EXPECT(KJ_ASSERT_NONNULL(headers.get(HttpHeaderId::DATE)) == "early");
  KJ_EXPECT(KJ_ASSERT_NONNULL(headers.get(fooBar)) == "Baz");
  KJ_EXPECT(headers.get(bazQux) == nullptr);
  KJ_EXPECT(headers.get(HttpHeaderId::CONTENT_TYPE) == nullptr);
122 123
  KJ_EXPECT(KJ_ASSERT_NONNULL(headers.get(HttpHeaderId::CONTENT_LENGTH)) == "123");
  KJ_EXPECT(headers.get(HttpHeaderId::TRANSFER_ENCODING) == nullptr);
124 125 126 127 128

  std::map<kj::StringPtr, kj::StringPtr> unpackedHeaders;
  headers.forEach([&](kj::StringPtr name, kj::StringPtr value) {
    KJ_EXPECT(unpackedHeaders.insert(std::make_pair(name, value)).second);
  });
129 130
  KJ_EXPECT(unpackedHeaders.size() == 5);
  KJ_EXPECT(unpackedHeaders["Content-Length"] == "123");
131 132 133 134 135
  KJ_EXPECT(unpackedHeaders["Host"] == "example.com");
  KJ_EXPECT(unpackedHeaders["Date"] == "early");
  KJ_EXPECT(unpackedHeaders["Foo-Bar"] == "Baz");
  KJ_EXPECT(unpackedHeaders["other-Header"] == "yep");

136
  KJ_EXPECT(headers.serializeRequest(result.method, result.url) ==
137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171
      "POST /some/path HTTP/1.1\r\n"
      "Content-Length: 123\r\n"
      "Host: example.com\r\n"
      "Date: early\r\n"
      "Foo-Bar: Baz\r\n"
      "other-Header: yep\r\n"
      "\r\n");
}

KJ_TEST("HttpHeaders::parseResponse") {
  HttpHeaderTable::Builder builder;

  auto fooBar = builder.add("Foo-Bar");
  auto bazQux = builder.add("baz-qux");

  auto table = builder.build();

  HttpHeaders headers(*table);
  auto text = kj::heapString(
      "HTTP/1.1\t\t  418\t    I'm a teapot\r\n"
      "Foo-BaR: Baz\r\n"
      "Host: example.com\r\n"
      "Content-Length: 123\r\n"
      "DATE:     early\r\n"
      "other-Header: yep\r\n"
      "\r\n");
  auto result = KJ_ASSERT_NONNULL(headers.tryParseResponse(text.asArray()));

  KJ_EXPECT(result.statusCode == 418);
  KJ_EXPECT(result.statusText == "I'm a teapot");
  KJ_EXPECT(KJ_ASSERT_NONNULL(headers.get(HttpHeaderId::HOST)) == "example.com");
  KJ_EXPECT(KJ_ASSERT_NONNULL(headers.get(HttpHeaderId::DATE)) == "early");
  KJ_EXPECT(KJ_ASSERT_NONNULL(headers.get(fooBar)) == "Baz");
  KJ_EXPECT(headers.get(bazQux) == nullptr);
  KJ_EXPECT(headers.get(HttpHeaderId::CONTENT_TYPE) == nullptr);
172 173
  KJ_EXPECT(KJ_ASSERT_NONNULL(headers.get(HttpHeaderId::CONTENT_LENGTH)) == "123");
  KJ_EXPECT(headers.get(HttpHeaderId::TRANSFER_ENCODING) == nullptr);
174 175 176 177 178

  std::map<kj::StringPtr, kj::StringPtr> unpackedHeaders;
  headers.forEach([&](kj::StringPtr name, kj::StringPtr value) {
    KJ_EXPECT(unpackedHeaders.insert(std::make_pair(name, value)).second);
  });
179 180
  KJ_EXPECT(unpackedHeaders.size() == 5);
  KJ_EXPECT(unpackedHeaders["Content-Length"] == "123");
181 182 183 184 185 186
  KJ_EXPECT(unpackedHeaders["Host"] == "example.com");
  KJ_EXPECT(unpackedHeaders["Date"] == "early");
  KJ_EXPECT(unpackedHeaders["Foo-Bar"] == "Baz");
  KJ_EXPECT(unpackedHeaders["other-Header"] == "yep");

  KJ_EXPECT(headers.serializeResponse(
187
        result.statusCode, result.statusText) ==
188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237
      "HTTP/1.1 418 I'm a teapot\r\n"
      "Content-Length: 123\r\n"
      "Host: example.com\r\n"
      "Date: early\r\n"
      "Foo-Bar: Baz\r\n"
      "other-Header: yep\r\n"
      "\r\n");
}

KJ_TEST("HttpHeaders parse invalid") {
  auto table = HttpHeaderTable::Builder().build();
  HttpHeaders headers(*table);

  // NUL byte in request.
  KJ_EXPECT(headers.tryParseRequest(kj::heapString(
      "POST  \0 /some/path \t   HTTP/1.1\r\n"
      "Foo-BaR: Baz\r\n"
      "Host: example.com\r\n"
      "DATE:     early\r\n"
      "other-Header: yep\r\n"
      "\r\n")) == nullptr);

  // Control character in header name.
  KJ_EXPECT(headers.tryParseRequest(kj::heapString(
      "POST   /some/path \t   HTTP/1.1\r\n"
      "Foo-BaR: Baz\r\n"
      "Cont\001ent-Length: 123\r\n"
      "DATE:     early\r\n"
      "other-Header: yep\r\n"
      "\r\n")) == nullptr);

  // Separator character in header name.
  KJ_EXPECT(headers.tryParseRequest(kj::heapString(
      "POST   /some/path \t   HTTP/1.1\r\n"
      "Foo-BaR: Baz\r\n"
      "Host: example.com\r\n"
      "DATE/:     early\r\n"
      "other-Header: yep\r\n"
      "\r\n")) == nullptr);

  // Response status code not numeric.
  KJ_EXPECT(headers.tryParseResponse(kj::heapString(
      "HTTP/1.1\t\t  abc\t    I'm a teapot\r\n"
      "Foo-BaR: Baz\r\n"
      "Host: example.com\r\n"
      "DATE:     early\r\n"
      "other-Header: yep\r\n"
      "\r\n")) == nullptr);
}

238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260
KJ_TEST("HttpHeaders validation") {
  auto table = HttpHeaderTable::Builder().build();
  HttpHeaders headers(*table);

  headers.add("Valid-Name", "valid value");

  // The HTTP RFC prohibits control characters, but browsers only prohibit \0, \r, and \n. KJ goes
  // with the browsers for compatibility.
  headers.add("Valid-Name", "valid\x01value");

  // The HTTP RFC does not permit non-ASCII values.
  // KJ chooses to interpret them as UTF-8, to avoid the need for any expensive conversion.
  // Browsers apparently interpret them as LATIN-1. Applications can reinterpet these strings as
  // LATIN-1 easily enough if they really need to.
  headers.add("Valid-Name", u8"valid€value");

  KJ_EXPECT_THROW_MESSAGE("invalid header name", headers.add("Invalid Name", "value"));
  KJ_EXPECT_THROW_MESSAGE("invalid header name", headers.add("Invalid@Name", "value"));

  KJ_EXPECT_THROW_MESSAGE("invalid header value", headers.set(HttpHeaderId::HOST, "in\nvalid"));
  KJ_EXPECT_THROW_MESSAGE("invalid header value", headers.add("Valid-Name", "in\nvalid"));
}

261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339
// =======================================================================================

class ReadFragmenter final: public kj::AsyncIoStream {
public:
  ReadFragmenter(AsyncIoStream& inner, size_t limit): inner(inner), limit(limit) {}

  Promise<size_t> read(void* buffer, size_t minBytes, size_t maxBytes) override {
    return inner.read(buffer, minBytes, kj::max(minBytes, kj::min(limit, maxBytes)));
  }
  Promise<size_t> tryRead(void* buffer, size_t minBytes, size_t maxBytes) override {
    return inner.tryRead(buffer, minBytes, kj::max(minBytes, kj::min(limit, maxBytes)));
  }

  Maybe<uint64_t> tryGetLength() override { return inner.tryGetLength(); }

  Promise<uint64_t> pumpTo(AsyncOutputStream& output, uint64_t amount) override {
    return inner.pumpTo(output, amount);
  }

  Promise<void> write(const void* buffer, size_t size) override {
    return inner.write(buffer, size);
  }
  Promise<void> write(ArrayPtr<const ArrayPtr<const byte>> pieces) override {
    return inner.write(pieces);
  }

  Maybe<Promise<uint64_t>> tryPumpFrom(AsyncInputStream& input, uint64_t amount) override {
    return inner.tryPumpFrom(input, amount);
  }

  void shutdownWrite() override {
    return inner.shutdownWrite();
  }

  void abortRead() override { return inner.abortRead(); }

  void getsockopt(int level, int option, void* value, uint* length) override {
    return inner.getsockopt(level, option, value, length);
  }
  void setsockopt(int level, int option, const void* value, uint length) override {
    return inner.setsockopt(level, option, value, length);
  }

  void getsockname(struct sockaddr* addr, uint* length) override {
    return inner.getsockname(addr, length);
  }
  void getpeername(struct sockaddr* addr, uint* length) override {
    return inner.getsockname(addr, length);
  }

private:
  kj::AsyncIoStream& inner;
  size_t limit;
};

template <typename T>
class InitializeableArray: public Array<T> {
public:
  InitializeableArray(std::initializer_list<T> init)
      : Array<T>(kj::heapArray(init)) {}
};

enum Side { BOTH, CLIENT_ONLY, SERVER_ONLY };

struct HeaderTestCase {
  HttpHeaderId id;
  kj::StringPtr value;
};

struct HttpRequestTestCase {
  kj::StringPtr raw;

  HttpMethod method;
  kj::StringPtr path;
  InitializeableArray<HeaderTestCase> requestHeaders;
  kj::Maybe<uint64_t> requestBodySize;
  InitializeableArray<kj::StringPtr> requestBodyParts;

  Side side = BOTH;
340 341 342 343 344 345 346 347 348 349

  // TODO(cleanup): Delete this constructor if/when we move to C++14.
  HttpRequestTestCase(kj::StringPtr raw, HttpMethod method, kj::StringPtr path,
                      InitializeableArray<HeaderTestCase> requestHeaders,
                      kj::Maybe<uint64_t> requestBodySize,
                      InitializeableArray<kj::StringPtr> requestBodyParts,
                      Side side = BOTH)
      : raw(raw), method(method), path(path), requestHeaders(kj::mv(requestHeaders)),
        requestBodySize(requestBodySize), requestBodyParts(kj::mv(requestBodyParts)),
        side(side) {}
350 351 352 353 354 355 356 357 358 359 360 361 362 363
};

struct HttpResponseTestCase {
  kj::StringPtr raw;

  uint64_t statusCode;
  kj::StringPtr statusText;
  InitializeableArray<HeaderTestCase> responseHeaders;
  kj::Maybe<uint64_t> responseBodySize;
  InitializeableArray<kj::StringPtr> responseBodyParts;

  HttpMethod method = HttpMethod::GET;

  Side side = BOTH;
364 365 366 367 368 369 370 371 372 373 374

  // TODO(cleanup): Delete this constructor if/when we move to C++14.
  HttpResponseTestCase(kj::StringPtr raw, uint64_t statusCode, kj::StringPtr statusText,
                       InitializeableArray<HeaderTestCase> responseHeaders,
                       kj::Maybe<uint64_t> responseBodySize,
                       InitializeableArray<kj::StringPtr> responseBodyParts,
                       HttpMethod method = HttpMethod::GET,
                       Side side = BOTH)
      : raw(raw), statusCode(statusCode), statusText(statusText),
        responseHeaders(kj::mv(responseHeaders)), responseBodySize(responseBodySize),
        responseBodyParts(kj::mv(responseBodyParts)), method(method), side(side) {}
375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395
};

struct HttpTestCase {
  HttpRequestTestCase request;
  HttpResponseTestCase response;
};

kj::Promise<void> writeEach(kj::AsyncOutputStream& out, kj::ArrayPtr<const kj::StringPtr> parts) {
  if (parts.size() == 0) return kj::READY_NOW;

  return out.write(parts[0].begin(), parts[0].size())
      .then([&out,parts]() {
    return writeEach(out, parts.slice(1, parts.size()));
  });
}

kj::Promise<void> expectRead(kj::AsyncInputStream& in, kj::StringPtr expected) {
  if (expected.size() == 0) return kj::READY_NOW;

  auto buffer = kj::heapArray<char>(expected.size());

396
  auto promise = in.tryRead(buffer.begin(), 1, buffer.size());
397
  return promise.then(kj::mvCapture(buffer, [&in,expected](kj::Array<char> buffer, size_t amount) {
398 399 400 401
    if (amount == 0) {
      KJ_FAIL_ASSERT("expected data never sent", expected);
    }

402 403 404 405 406 407 408 409 410
    auto actual = buffer.slice(0, amount);
    if (memcmp(actual.begin(), expected.begin(), actual.size()) != 0) {
      KJ_FAIL_ASSERT("data from stream doesn't match expected", expected, actual);
    }

    return expectRead(in, expected.slice(amount));
  }));
}

411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430
kj::Promise<void> expectRead(kj::AsyncInputStream& in, kj::ArrayPtr<const byte> expected) {
  if (expected.size() == 0) return kj::READY_NOW;

  auto buffer = kj::heapArray<byte>(expected.size());

  auto promise = in.tryRead(buffer.begin(), 1, buffer.size());
  return promise.then(kj::mvCapture(buffer, [&in,expected](kj::Array<byte> buffer, size_t amount) {
    if (amount == 0) {
      KJ_FAIL_ASSERT("expected data never sent", expected);
    }

    auto actual = buffer.slice(0, amount);
    if (memcmp(actual.begin(), expected.begin(), actual.size()) != 0) {
      KJ_FAIL_ASSERT("data from stream doesn't match expected", expected, actual);
    }

    return expectRead(in, expected.slice(amount, expected.size()));
  }));
}

431
void testHttpClientRequest(kj::WaitScope& waitScope, const HttpRequestTestCase& testCase) {
432
  auto pipe = kj::newTwoWayPipe();
433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453

  auto serverTask = expectRead(*pipe.ends[1], testCase.raw).then([&]() {
    static const char SIMPLE_RESPONSE[] =
        "HTTP/1.1 200 OK\r\n"
        "Content-Length: 0\r\n"
        "\r\n";
    return pipe.ends[1]->write(SIMPLE_RESPONSE, strlen(SIMPLE_RESPONSE));
  }).then([&]() -> kj::Promise<void> {
    return kj::NEVER_DONE;
  });

  HttpHeaderTable table;
  auto client = newHttpClient(table, *pipe.ends[0]);

  HttpHeaders headers(table);
  for (auto& header: testCase.requestHeaders) {
    headers.set(header.id, header.value);
  }

  auto request = client->request(testCase.method, testCase.path, headers, testCase.requestBodySize);
  if (testCase.requestBodyParts.size() > 0) {
454
    writeEach(*request.body, testCase.requestBodyParts).wait(waitScope);
455 456 457 458 459 460 461 462
  }
  request.body = nullptr;
  auto clientTask = request.response
      .then([&](HttpClient::Response&& response) {
    auto promise = response.body->readAllText();
    return promise.attach(kj::mv(response.body));
  }).ignoreResult();

463
  serverTask.exclusiveJoin(kj::mv(clientTask)).wait(waitScope);
464 465 466 467

  // Verify no more data written by client.
  client = nullptr;
  pipe.ends[0]->shutdownWrite();
468
  KJ_EXPECT(pipe.ends[1]->readAllText().wait(waitScope) == "");
469 470
}

471
void testHttpClientResponse(kj::WaitScope& waitScope, const HttpResponseTestCase& testCase,
472
                            size_t readFragmentSize) {
473
  auto pipe = kj::newTwoWayPipe();
474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490
  ReadFragmenter fragmenter(*pipe.ends[0], readFragmentSize);

  auto expectedReqText = testCase.method == HttpMethod::GET || testCase.method == HttpMethod::HEAD
      ? kj::str(testCase.method, " / HTTP/1.1\r\n\r\n")
      : kj::str(testCase.method, " / HTTP/1.1\r\nContent-Length: 0\r\n");

  auto serverTask = expectRead(*pipe.ends[1], expectedReqText).then([&]() {
    return pipe.ends[1]->write(testCase.raw.begin(), testCase.raw.size());
  }).then([&]() -> kj::Promise<void> {
    pipe.ends[1]->shutdownWrite();
    return kj::NEVER_DONE;
  });

  HttpHeaderTable table;
  auto client = newHttpClient(table, fragmenter);

  HttpHeaders headers(table);
Kenton Varda's avatar
Kenton Varda committed
491
  auto request = client->request(testCase.method, "/", headers, uint64_t(0));
492 493 494 495 496 497 498 499 500 501 502 503 504 505 506
  request.body = nullptr;
  auto clientTask = request.response
      .then([&](HttpClient::Response&& response) {
    KJ_EXPECT(response.statusCode == testCase.statusCode);
    KJ_EXPECT(response.statusText == testCase.statusText);

    for (auto& header: testCase.responseHeaders) {
      KJ_EXPECT(KJ_ASSERT_NONNULL(response.headers->get(header.id)) == header.value);
    }
    auto promise = response.body->readAllText();
    return promise.attach(kj::mv(response.body));
  }).then([&](kj::String body) {
    KJ_EXPECT(body == kj::strArray(testCase.responseBodyParts, ""), body);
  });

507
  serverTask.exclusiveJoin(kj::mv(clientTask)).wait(waitScope);
508 509 510 511

  // Verify no more data written by client.
  client = nullptr;
  pipe.ends[0]->shutdownWrite();
512
  KJ_EXPECT(pipe.ends[1]->readAllText().wait(waitScope) == "");
513 514
}

515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541
void testHttpClient(kj::WaitScope& waitScope, HttpHeaderTable& table,
                    HttpClient& client, const HttpTestCase& testCase) {
  KJ_CONTEXT(testCase.request.raw, testCase.response.raw);

  HttpHeaders headers(table);
  for (auto& header: testCase.request.requestHeaders) {
    headers.set(header.id, header.value);
  }

  auto request = client.request(
      testCase.request.method, testCase.request.path, headers, testCase.request.requestBodySize);
  for (auto& part: testCase.request.requestBodyParts) {
    request.body->write(part.begin(), part.size()).wait(waitScope);
  }
  request.body = nullptr;

  auto response = request.response.wait(waitScope);

  KJ_EXPECT(response.statusCode == testCase.response.statusCode);
  auto body = response.body->readAllText().wait(waitScope);
  if (testCase.request.method == HttpMethod::HEAD) {
    KJ_EXPECT(body == "");
  } else {
    KJ_EXPECT(body == kj::strArray(testCase.response.responseBodyParts, ""), body);
  }
}

542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610
class TestHttpService final: public HttpService {
public:
  TestHttpService(const HttpRequestTestCase& expectedRequest,
                  const HttpResponseTestCase& response,
                  HttpHeaderTable& table)
      : singleExpectedRequest(&expectedRequest),
        singleResponse(&response),
        responseHeaders(table) {}
  TestHttpService(kj::ArrayPtr<const HttpTestCase> testCases,
                  HttpHeaderTable& table)
      : singleExpectedRequest(nullptr),
        singleResponse(nullptr),
        testCases(testCases),
        responseHeaders(table) {}

  uint getRequestCount() { return requestCount; }

  kj::Promise<void> request(
      HttpMethod method, kj::StringPtr url, const HttpHeaders& headers,
      kj::AsyncInputStream& requestBody, Response& responseSender) override {
    auto& expectedRequest = testCases == nullptr ? *singleExpectedRequest :
        testCases[requestCount % testCases.size()].request;
    auto& response = testCases == nullptr ? *singleResponse :
        testCases[requestCount % testCases.size()].response;

    ++requestCount;

    KJ_EXPECT(method == expectedRequest.method, method);
    KJ_EXPECT(url == expectedRequest.path, url);

    for (auto& header: expectedRequest.requestHeaders) {
      KJ_EXPECT(KJ_ASSERT_NONNULL(headers.get(header.id)) == header.value);
    }

    auto size = requestBody.tryGetLength();
    KJ_IF_MAYBE(expectedSize, expectedRequest.requestBodySize) {
      KJ_IF_MAYBE(s, size) {
        KJ_EXPECT(*s == *expectedSize, *s);
      } else {
        KJ_FAIL_EXPECT("tryGetLength() returned nullptr; expected known size");
      }
    } else {
      KJ_EXPECT(size == nullptr);
    }

    return requestBody.readAllText()
        .then([this,&expectedRequest,&response,&responseSender](kj::String text) {
      KJ_EXPECT(text == kj::strArray(expectedRequest.requestBodyParts, ""), text);

      responseHeaders.clear();
      for (auto& header: response.responseHeaders) {
        responseHeaders.set(header.id, header.value);
      }

      auto stream = responseSender.send(response.statusCode, response.statusText,
                                        responseHeaders, response.responseBodySize);
      auto promise = writeEach(*stream, response.responseBodyParts);
      return promise.attach(kj::mv(stream));
    });
  }

private:
  const HttpRequestTestCase* singleExpectedRequest;
  const HttpResponseTestCase* singleResponse;
  kj::ArrayPtr<const HttpTestCase> testCases;
  HttpHeaders responseHeaders;
  uint requestCount = 0;
};

611
void testHttpServerRequest(kj::WaitScope& waitScope, kj::Timer& timer,
612 613
                           const HttpRequestTestCase& requestCase,
                           const HttpResponseTestCase& responseCase) {
614
  auto pipe = kj::newTwoWayPipe();
615 616 617

  HttpHeaderTable table;
  TestHttpService service(requestCase, responseCase, table);
618
  HttpServer server(timer, table, service);
619 620 621

  auto listenTask = server.listenHttp(kj::mv(pipe.ends[0]));

622
  pipe.ends[1]->write(requestCase.raw.begin(), requestCase.raw.size()).wait(waitScope);
623 624
  pipe.ends[1]->shutdownWrite();

625
  expectRead(*pipe.ends[1], responseCase.raw).wait(waitScope);
626

627
  listenTask.wait(waitScope);
628 629 630 631

  KJ_EXPECT(service.getRequestCount() == 1);
}

632 633 634 635 636 637
kj::ArrayPtr<const HttpRequestTestCase> requestTestCases() {
  static const auto HUGE_STRING = kj::strArray(kj::repeat("abcdefgh", 4096), "");
  static const auto HUGE_REQUEST = kj::str(
      "GET / HTTP/1.1\r\n"
      "Host: ", HUGE_STRING, "\r\n"
      "\r\n");
638

639 640 641 642 643
  static const HttpRequestTestCase REQUEST_TEST_CASES[] {
    {
      "GET /foo/bar HTTP/1.1\r\n"
      "Host: example.com\r\n"
      "\r\n",
644

645 646 647
      HttpMethod::GET,
      "/foo/bar",
      {{HttpHeaderId::HOST, "example.com"}},
648
      uint64_t(0), {},
649
    },
650

651 652 653 654
    {
      "HEAD /foo/bar HTTP/1.1\r\n"
      "Host: example.com\r\n"
      "\r\n",
655

656 657 658
      HttpMethod::HEAD,
      "/foo/bar",
      {{HttpHeaderId::HOST, "example.com"}},
659
      uint64_t(0), {},
660
    },
661

662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677
    {
      "POST / HTTP/1.1\r\n"
      "Content-Length: 9\r\n"
      "Host: example.com\r\n"
      "Content-Type: text/plain\r\n"
      "\r\n"
      "foobarbaz",

      HttpMethod::POST,
      "/",
      {
        {HttpHeaderId::HOST, "example.com"},
        {HttpHeaderId::CONTENT_TYPE, "text/plain"},
      },
      9, { "foo", "bar", "baz" },
    },
678 679

    {
680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698
      "POST / HTTP/1.1\r\n"
      "Transfer-Encoding: chunked\r\n"
      "Host: example.com\r\n"
      "Content-Type: text/plain\r\n"
      "\r\n"
      "3\r\n"
      "foo\r\n"
      "6\r\n"
      "barbaz\r\n"
      "0\r\n"
      "\r\n",

      HttpMethod::POST,
      "/",
      {
        {HttpHeaderId::HOST, "example.com"},
        {HttpHeaderId::CONTENT_TYPE, "text/plain"},
      },
      nullptr, { "foo", "barbaz" },
699 700 701
    },

    {
702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718
      "POST / HTTP/1.1\r\n"
      "Transfer-Encoding: chunked\r\n"
      "Host: example.com\r\n"
      "Content-Type: text/plain\r\n"
      "\r\n"
      "1d\r\n"
      "0123456789abcdef0123456789abc\r\n"
      "0\r\n"
      "\r\n",

      HttpMethod::POST,
      "/",
      {
        {HttpHeaderId::HOST, "example.com"},
        {HttpHeaderId::CONTENT_TYPE, "text/plain"},
      },
      nullptr, { "0123456789abcdef0123456789abc" },
719 720 721
    },

    {
722 723 724 725 726
      HUGE_REQUEST,

      HttpMethod::GET,
      "/",
      {{HttpHeaderId::HOST, HUGE_STRING}},
727
      uint64_t(0), {}
728
    },
729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760

    {
      "GET /foo/bar HTTP/1.1\r\n"
      "Content-Length: 6\r\n"
      "Host: example.com\r\n"
      "\r\n"
      "foobar",

      HttpMethod::GET,
      "/foo/bar",
      {{HttpHeaderId::HOST, "example.com"}},
      uint64_t(6), { "foobar" },
    },

    {
      "GET /foo/bar HTTP/1.1\r\n"
      "Transfer-Encoding: chunked\r\n"
      "Host: example.com\r\n"
      "\r\n"
      "3\r\n"
      "foo\r\n"
      "3\r\n"
      "bar\r\n"
      "0\r\n"
      "\r\n",

      HttpMethod::GET,
      "/foo/bar",
      {{HttpHeaderId::HOST, "example.com"},
       {HttpHeaderId::TRANSFER_ENCODING, "chunked"}},
      nullptr, { "foo", "bar" },
    }
761
  };
762

763 764 765
  // TODO(cleanup): A bug in GCC 4.8, fixed in 4.9, prevents REQUEST_TEST_CASES from implicitly
  //   casting to our return type.
  return kj::arrayPtr(REQUEST_TEST_CASES, kj::size(REQUEST_TEST_CASES));
766
}
767

768 769 770 771 772 773 774 775
kj::ArrayPtr<const HttpResponseTestCase> responseTestCases() {
  static const HttpResponseTestCase RESPONSE_TEST_CASES[] {
    {
      "HTTP/1.1 200 OK\r\n"
      "Content-Type: text/plain\r\n"
      "Connection: close\r\n"
      "\r\n"
      "baz qux",
776

777 778 779
      200, "OK",
      {{HttpHeaderId::CONTENT_TYPE, "text/plain"}},
      nullptr, {"baz qux"},
780

781 782 783
      HttpMethod::GET,
      CLIENT_ONLY,   // Server never sends connection: close
    },
784

785 786 787 788 789
    {
      "HTTP/1.1 200 OK\r\n"
      "Content-Length: 123\r\n"
      "Content-Type: text/plain\r\n"
      "\r\n",
790

791 792 793
      200, "OK",
      {{HttpHeaderId::CONTENT_TYPE, "text/plain"}},
      123, {},
794

795 796
      HttpMethod::HEAD,
    },
797

798 799 800 801 802 803 804 805 806 807 808 809 810 811
    {
      "HTTP/1.1 200 OK\r\n"
      "Content-Length: foobar\r\n"
      "Content-Type: text/plain\r\n"
      "\r\n",

      200, "OK",
      {{HttpHeaderId::CONTENT_TYPE, "text/plain"},
       {HttpHeaderId::CONTENT_LENGTH, "foobar"}},
      123, {},

      HttpMethod::HEAD,
    },

812 813 814 815 816 817 818 819 820 821 822 823
    // Zero-length expected size response to HEAD request has no Content-Length header.
    {
      "HTTP/1.1 200 OK\r\n"
      "\r\n",

      200, "OK",
      {},
      uint64_t(0), {},

      HttpMethod::HEAD,
    },

824 825 826 827 828 829
    {
      "HTTP/1.1 200 OK\r\n"
      "Content-Length: 8\r\n"
      "Content-Type: text/plain\r\n"
      "\r\n"
      "quxcorge",
830

831 832 833 834
      200, "OK",
      {{HttpHeaderId::CONTENT_TYPE, "text/plain"}},
      8, { "qux", "corge" }
    },
835

836 837 838 839 840 841 842 843 844 845 846
    {
      "HTTP/1.1 200 OK\r\n"
      "Transfer-Encoding: chunked\r\n"
      "Content-Type: text/plain\r\n"
      "\r\n"
      "3\r\n"
      "qux\r\n"
      "5\r\n"
      "corge\r\n"
      "0\r\n"
      "\r\n",
847

848 849 850 851 852
      200, "OK",
      {{HttpHeaderId::CONTENT_TYPE, "text/plain"}},
      nullptr, { "qux", "corge" }
    },
  };
853

854 855 856
  // TODO(cleanup): A bug in GCC 4.8, fixed in 4.9, prevents RESPONSE_TEST_CASES from implicitly
  //   casting to our return type.
  return kj::arrayPtr(RESPONSE_TEST_CASES, kj::size(RESPONSE_TEST_CASES));
857
}
858 859

KJ_TEST("HttpClient requests") {
860 861
  kj::EventLoop eventLoop;
  kj::WaitScope waitScope(eventLoop);
862

863
  for (auto& testCase: requestTestCases()) {
864 865
    if (testCase.side == SERVER_ONLY) continue;
    KJ_CONTEXT(testCase.raw);
866
    testHttpClientRequest(waitScope, testCase);
867 868 869 870
  }
}

KJ_TEST("HttpClient responses") {
871 872
  kj::EventLoop eventLoop;
  kj::WaitScope waitScope(eventLoop);
873 874
  size_t FRAGMENT_SIZES[] = { 1, 2, 3, 4, 5, 6, 7, 8, 16, 31, kj::maxValue };

875
  for (auto& testCase: responseTestCases()) {
876 877 878
    if (testCase.side == SERVER_ONLY) continue;
    for (size_t fragmentSize: FRAGMENT_SIZES) {
      KJ_CONTEXT(testCase.raw, fragmentSize);
879
      testHttpClientResponse(waitScope, testCase, fragmentSize);
880 881 882 883
    }
  }
}

884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901
KJ_TEST("HttpClient canceled write") {
  kj::EventLoop eventLoop;
  kj::WaitScope waitScope(eventLoop);

  auto pipe = kj::newTwoWayPipe();

  auto serverPromise = pipe.ends[1]->readAllText();

  {
    HttpHeaderTable table;
    auto client = newHttpClient(table, *pipe.ends[0]);

    auto body = kj::heapArray<byte>(4096);
    memset(body.begin(), 0xcf, body.size());

    auto req = client->request(HttpMethod::POST, "/", HttpHeaders(table), uint64_t(4096));

    // Start a write and immediately cancel it.
902 903 904
    {
      auto ignore KJ_UNUSED = req.body->write(body.begin(), body.size());
    }
905 906 907 908 909 910 911 912 913 914 915 916 917 918 919

    KJ_EXPECT_THROW_MESSAGE("overwrote", req.body->write("foo", 3).wait(waitScope));
    req.body = nullptr;

    KJ_EXPECT(!serverPromise.poll(waitScope));

    KJ_EXPECT_THROW_MESSAGE("can't start new request until previous request body",
        client->request(HttpMethod::GET, "/", HttpHeaders(table)).response.wait(waitScope));
  }

  pipe.ends[0]->shutdownWrite();
  auto text = serverPromise.wait(waitScope);
  KJ_EXPECT(text == "POST / HTTP/1.1\r\nContent-Length: 4096\r\n\r\n", text);
}

920 921 922 923 924 925 926 927 928 929 930 931 932 933 934
KJ_TEST("HttpClient chunked body gather-write") {
  kj::EventLoop eventLoop;
  kj::WaitScope waitScope(eventLoop);

  auto pipe = kj::newTwoWayPipe();

  auto serverPromise = pipe.ends[1]->readAllText();

  {
    HttpHeaderTable table;
    auto client = newHttpClient(table, *pipe.ends[0]);

    auto req = client->request(HttpMethod::POST, "/", HttpHeaders(table));

    kj::ArrayPtr<const byte> bodyParts[] = {
935 936 937
      "foo"_kj.asBytes(), " "_kj.asBytes(),
      "bar"_kj.asBytes(), " "_kj.asBytes(),
      "baz"_kj.asBytes()
938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001
    };

    req.body->write(kj::arrayPtr(bodyParts, kj::size(bodyParts))).wait(waitScope);
    req.body = nullptr;

    // Wait for a response so the client has a chance to end the request body with a 0-chunk.
    kj::StringPtr responseText = "HTTP/1.1 204 No Content\r\n\r\n";
    pipe.ends[1]->write(responseText.begin(), responseText.size()).wait(waitScope);
    auto response = req.response.wait(waitScope);
  }

  pipe.ends[0]->shutdownWrite();

  auto text = serverPromise.wait(waitScope);
  KJ_EXPECT(text == "POST / HTTP/1.1\r\nTransfer-Encoding: chunked\r\n\r\n"
                    "b\r\nfoo bar baz\r\n0\r\n\r\n", text);
}

KJ_TEST("HttpClient chunked body pump from fixed length stream") {
  class FixedBodyStream final: public kj::AsyncInputStream {
    Promise<size_t> tryRead(void* buffer, size_t minBytes, size_t maxBytes) override {
      auto n = kj::min(body.size(), maxBytes);
      n = kj::max(n, minBytes);
      n = kj::min(n, body.size());
      memcpy(buffer, body.begin(), n);
      body = body.slice(n);
      return n;
    }

    Maybe<uint64_t> tryGetLength() override { return body.size(); }

    kj::StringPtr body = "foo bar baz";
  };

  kj::EventLoop eventLoop;
  kj::WaitScope waitScope(eventLoop);

  auto pipe = kj::newTwoWayPipe();

  auto serverPromise = pipe.ends[1]->readAllText();

  {
    HttpHeaderTable table;
    auto client = newHttpClient(table, *pipe.ends[0]);

    auto req = client->request(HttpMethod::POST, "/", HttpHeaders(table));

    FixedBodyStream bodyStream;
    bodyStream.pumpTo(*req.body).wait(waitScope);
    req.body = nullptr;

    // Wait for a response so the client has a chance to end the request body with a 0-chunk.
    kj::StringPtr responseText = "HTTP/1.1 204 No Content\r\n\r\n";
    pipe.ends[1]->write(responseText.begin(), responseText.size()).wait(waitScope);
    auto response = req.response.wait(waitScope);
  }

  pipe.ends[0]->shutdownWrite();

  auto text = serverPromise.wait(waitScope);
  KJ_EXPECT(text == "POST / HTTP/1.1\r\nTransfer-Encoding: chunked\r\n\r\n"
                    "b\r\nfoo bar baz\r\n0\r\n\r\n", text);
}

1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023
KJ_TEST("HttpServer requests") {
  HttpResponseTestCase RESPONSE = {
    "HTTP/1.1 200 OK\r\n"
    "Content-Length: 3\r\n"
    "\r\n"
    "foo",

    200, "OK",
    {},
    3, {"foo"}
  };

  HttpResponseTestCase HEAD_RESPONSE = {
    "HTTP/1.1 200 OK\r\n"
    "Content-Length: 3\r\n"
    "\r\n",

    200, "OK",
    {},
    3, {"foo"}
  };

1024 1025 1026
  kj::EventLoop eventLoop;
  kj::WaitScope waitScope(eventLoop);
  kj::TimerImpl timer(kj::origin<kj::TimePoint>());
1027

1028
  for (auto& testCase: requestTestCases()) {
1029 1030
    if (testCase.side == CLIENT_ONLY) continue;
    KJ_CONTEXT(testCase.raw);
1031
    testHttpServerRequest(waitScope, timer, testCase,
1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043
        testCase.method == HttpMethod::HEAD ? HEAD_RESPONSE : RESPONSE);
  }
}

KJ_TEST("HttpServer responses") {
  HttpRequestTestCase REQUEST = {
    "GET / HTTP/1.1\r\n"
    "\r\n",

    HttpMethod::GET,
    "/",
    {},
1044
    uint64_t(0), {},
1045 1046 1047 1048 1049 1050 1051 1052 1053
  };

  HttpRequestTestCase HEAD_REQUEST = {
    "HEAD / HTTP/1.1\r\n"
    "\r\n",

    HttpMethod::HEAD,
    "/",
    {},
1054
    uint64_t(0), {},
1055 1056
  };

1057 1058 1059
  kj::EventLoop eventLoop;
  kj::WaitScope waitScope(eventLoop);
  kj::TimerImpl timer(kj::origin<kj::TimePoint>());
1060

1061
  for (auto& testCase: responseTestCases()) {
1062 1063
    if (testCase.side == CLIENT_ONLY) continue;
    KJ_CONTEXT(testCase.raw);
1064
    testHttpServerRequest(waitScope, timer,
1065 1066 1067 1068 1069 1070
        testCase.method == HttpMethod::HEAD ? HEAD_REQUEST : REQUEST, testCase);
  }
}

// -----------------------------------------------------------------------------

1071 1072
kj::ArrayPtr<const HttpTestCase> pipelineTestCases() {
  static const HttpTestCase PIPELINE_TESTS[] = {
1073
    {
1074 1075 1076
      {
        "GET / HTTP/1.1\r\n"
        "\r\n",
1077

1078
        HttpMethod::GET, "/", {}, uint64_t(0), {},
1079 1080 1081 1082 1083 1084
      },
      {
        "HTTP/1.1 200 OK\r\n"
        "Content-Length: 7\r\n"
        "\r\n"
        "foo bar",
1085

1086 1087
        200, "OK", {}, 7, { "foo bar" }
      },
1088 1089 1090
    },

    {
1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106
      {
        "POST /foo HTTP/1.1\r\n"
        "Content-Length: 6\r\n"
        "\r\n"
        "grault",

        HttpMethod::POST, "/foo", {}, 6, { "grault" },
      },
      {
        "HTTP/1.1 404 Not Found\r\n"
        "Content-Length: 13\r\n"
        "\r\n"
        "baz qux corge",

        404, "Not Found", {}, 13, { "baz qux corge" }
      },
1107 1108
    },

1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149
    // Throw a zero-size request/response into the pipeline to check for a bug that existed with
    // them previously.
    {
      {
        "POST /foo HTTP/1.1\r\n"
        "Content-Length: 0\r\n"
        "\r\n",

        HttpMethod::POST, "/foo", {}, uint64_t(0), {},
      },
      {
        "HTTP/1.1 200 OK\r\n"
        "Content-Length: 0\r\n"
        "\r\n",

        200, "OK", {}, uint64_t(0), {}
      },
    },

    // Also a zero-size chunked request/response.
    {
      {
        "POST /foo HTTP/1.1\r\n"
        "Transfer-Encoding: chunked\r\n"
        "\r\n"
        "0\r\n"
        "\r\n",

        HttpMethod::POST, "/foo", {}, nullptr, {},
      },
      {
        "HTTP/1.1 200 OK\r\n"
        "Transfer-Encoding: chunked\r\n"
        "\r\n"
        "0\r\n"
        "\r\n",

        200, "OK", {}, nullptr, {}
      },
    },

1150
    {
1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176
      {
        "POST /bar HTTP/1.1\r\n"
        "Transfer-Encoding: chunked\r\n"
        "\r\n"
        "6\r\n"
        "garply\r\n"
        "5\r\n"
        "waldo\r\n"
        "0\r\n"
        "\r\n",

        HttpMethod::POST, "/bar", {}, nullptr, { "garply", "waldo" },
      },
      {
        "HTTP/1.1 200 OK\r\n"
        "Transfer-Encoding: chunked\r\n"
        "\r\n"
        "4\r\n"
        "fred\r\n"
        "5\r\n"
        "plugh\r\n"
        "0\r\n"
        "\r\n",

        200, "OK", {}, nullptr, { "fred", "plugh" }
      },
1177 1178 1179
    },

    {
1180 1181 1182
      {
        "HEAD / HTTP/1.1\r\n"
        "\r\n",
1183

1184
        HttpMethod::HEAD, "/", {}, uint64_t(0), {},
1185 1186 1187 1188 1189
      },
      {
        "HTTP/1.1 200 OK\r\n"
        "Content-Length: 7\r\n"
        "\r\n",
1190

1191 1192
        200, "OK", {}, 7, { "foo bar" }
      },
1193
    },
1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209

    // Zero-length expected size response to HEAD request has no Content-Length header.
    {
      {
        "HEAD / HTTP/1.1\r\n"
        "\r\n",

        HttpMethod::HEAD, "/", {}, uint64_t(0), {},
      },
      {
        "HTTP/1.1 200 OK\r\n"
        "\r\n",

        200, "OK", {}, uint64_t(0), {}, HttpMethod::HEAD,
      },
    },
1210 1211
  };

1212 1213 1214
  // TODO(cleanup): A bug in GCC 4.8, fixed in 4.9, prevents RESPONSE_TEST_CASES from implicitly
  //   casting to our return type.
  return kj::arrayPtr(PIPELINE_TESTS, kj::size(PIPELINE_TESTS));
1215
}
1216 1217

KJ_TEST("HttpClient pipeline") {
1218 1219
  auto PIPELINE_TESTS = pipelineTestCases();

1220 1221
  kj::EventLoop eventLoop;
  kj::WaitScope waitScope(eventLoop);
1222
  auto pipe = kj::newTwoWayPipe();
1223

1224 1225 1226 1227 1228 1229 1230 1231 1232
  kj::Promise<void> writeResponsesPromise = kj::READY_NOW;
  for (auto& testCase: PIPELINE_TESTS) {
    writeResponsesPromise = writeResponsesPromise
        .then([&]() {
      return expectRead(*pipe.ends[1], testCase.request.raw);
    }).then([&]() {
      return pipe.ends[1]->write(testCase.response.raw.begin(), testCase.response.raw.size());
    });
  }
1233 1234 1235 1236 1237

  HttpHeaderTable table;
  auto client = newHttpClient(table, *pipe.ends[0]);

  for (auto& testCase: PIPELINE_TESTS) {
1238
    testHttpClient(waitScope, table, *client, testCase);
1239 1240 1241 1242 1243
  }

  client = nullptr;
  pipe.ends[0]->shutdownWrite();

1244
  writeResponsesPromise.wait(waitScope);
1245 1246 1247
}

KJ_TEST("HttpClient parallel pipeline") {
1248 1249
  auto PIPELINE_TESTS = pipelineTestCases();

1250 1251
  kj::EventLoop eventLoop;
  kj::WaitScope waitScope(eventLoop);
1252
  auto pipe = kj::newTwoWayPipe();
1253

1254
  kj::Promise<void> readRequestsPromise = kj::READY_NOW;
1255 1256
  kj::Promise<void> writeResponsesPromise = kj::READY_NOW;
  for (auto& testCase: PIPELINE_TESTS) {
1257
    auto forked = readRequestsPromise
1258 1259
        .then([&]() {
      return expectRead(*pipe.ends[1], testCase.request.raw);
1260 1261 1262 1263 1264 1265 1266 1267
    }).fork();
    readRequestsPromise = forked.addBranch();

    // Don't write each response until the corresponding request is received.
    auto promises = kj::heapArrayBuilder<kj::Promise<void>>(2);
    promises.add(forked.addBranch());
    promises.add(kj::mv(writeResponsesPromise));
    writeResponsesPromise = kj::joinPromises(promises.finish()).then([&]() {
1268 1269 1270
      return pipe.ends[1]->write(testCase.response.raw.begin(), testCase.response.raw.size());
    });
  }
1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285

  HttpHeaderTable table;
  auto client = newHttpClient(table, *pipe.ends[0]);

  auto responsePromises = KJ_MAP(testCase, PIPELINE_TESTS) {
    KJ_CONTEXT(testCase.request.raw, testCase.response.raw);

    HttpHeaders headers(table);
    for (auto& header: testCase.request.requestHeaders) {
      headers.set(header.id, header.value);
    }

    auto request = client->request(
        testCase.request.method, testCase.request.path, headers, testCase.request.requestBodySize);
    for (auto& part: testCase.request.requestBodyParts) {
1286
      request.body->write(part.begin(), part.size()).wait(waitScope);
1287 1288 1289 1290 1291 1292 1293
    }

    return kj::mv(request.response);
  };

  for (auto i: kj::indices(PIPELINE_TESTS)) {
    auto& testCase = PIPELINE_TESTS[i];
1294
    auto response = responsePromises[i].wait(waitScope);
1295 1296

    KJ_EXPECT(response.statusCode == testCase.response.statusCode);
1297
    auto body = response.body->readAllText().wait(waitScope);
1298 1299 1300 1301 1302 1303 1304 1305 1306 1307
    if (testCase.request.method == HttpMethod::HEAD) {
      KJ_EXPECT(body == "");
    } else {
      KJ_EXPECT(body == kj::strArray(testCase.response.responseBodyParts, ""), body);
    }
  }

  client = nullptr;
  pipe.ends[0]->shutdownWrite();

1308
  writeResponsesPromise.wait(waitScope);
1309 1310 1311
}

KJ_TEST("HttpServer pipeline") {
1312 1313
  auto PIPELINE_TESTS = pipelineTestCases();

1314 1315 1316
  kj::EventLoop eventLoop;
  kj::WaitScope waitScope(eventLoop);
  kj::TimerImpl timer(kj::origin<kj::TimePoint>());
1317
  auto pipe = kj::newTwoWayPipe();
1318 1319 1320

  HttpHeaderTable table;
  TestHttpService service(PIPELINE_TESTS, table);
1321
  HttpServer server(timer, table, service);
1322 1323 1324 1325 1326 1327 1328

  auto listenTask = server.listenHttp(kj::mv(pipe.ends[0]));

  for (auto& testCase: PIPELINE_TESTS) {
    KJ_CONTEXT(testCase.request.raw, testCase.response.raw);

    pipe.ends[1]->write(testCase.request.raw.begin(), testCase.request.raw.size())
1329
        .wait(waitScope);
1330

1331
    expectRead(*pipe.ends[1], testCase.response.raw).wait(waitScope);
1332 1333 1334
  }

  pipe.ends[1]->shutdownWrite();
1335
  listenTask.wait(waitScope);
1336 1337 1338 1339 1340

  KJ_EXPECT(service.getRequestCount() == kj::size(PIPELINE_TESTS));
}

KJ_TEST("HttpServer parallel pipeline") {
1341 1342
  auto PIPELINE_TESTS = pipelineTestCases();

1343 1344 1345
  kj::EventLoop eventLoop;
  kj::WaitScope waitScope(eventLoop);
  kj::TimerImpl timer(kj::origin<kj::TimePoint>());
1346
  auto pipe = kj::newTwoWayPipe();
1347 1348 1349 1350 1351 1352 1353 1354

  auto allRequestText =
      kj::strArray(KJ_MAP(testCase, PIPELINE_TESTS) { return testCase.request.raw; }, "");
  auto allResponseText =
      kj::strArray(KJ_MAP(testCase, PIPELINE_TESTS) { return testCase.response.raw; }, "");

  HttpHeaderTable table;
  TestHttpService service(PIPELINE_TESTS, table);
1355
  HttpServer server(timer, table, service);
1356 1357 1358

  auto listenTask = server.listenHttp(kj::mv(pipe.ends[0]));

1359
  pipe.ends[1]->write(allRequestText.begin(), allRequestText.size()).wait(waitScope);
1360 1361
  pipe.ends[1]->shutdownWrite();

1362
  auto rawResponse = pipe.ends[1]->readAllText().wait(waitScope);
1363 1364
  KJ_EXPECT(rawResponse == allResponseText, rawResponse);

1365
  listenTask.wait(waitScope);
1366 1367 1368 1369 1370

  KJ_EXPECT(service.getRequestCount() == kj::size(PIPELINE_TESTS));
}

KJ_TEST("HttpClient <-> HttpServer") {
1371 1372
  auto PIPELINE_TESTS = pipelineTestCases();

1373 1374 1375
  kj::EventLoop eventLoop;
  kj::WaitScope waitScope(eventLoop);
  kj::TimerImpl timer(kj::origin<kj::TimePoint>());
1376
  auto pipe = kj::newTwoWayPipe();
1377 1378 1379

  HttpHeaderTable table;
  TestHttpService service(PIPELINE_TESTS, table);
1380
  HttpServer server(timer, table, service);
1381 1382 1383 1384 1385

  auto listenTask = server.listenHttp(kj::mv(pipe.ends[1]));
  auto client = newHttpClient(table, *pipe.ends[0]);

  for (auto& testCase: PIPELINE_TESTS) {
1386
    testHttpClient(waitScope, table, *client, testCase);
1387 1388 1389 1390
  }

  client = nullptr;
  pipe.ends[0]->shutdownWrite();
1391
  listenTask.wait(waitScope);
1392 1393 1394 1395 1396
  KJ_EXPECT(service.getRequestCount() == kj::size(PIPELINE_TESTS));
}

// -----------------------------------------------------------------------------

1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420
KJ_TEST("HttpInputStream requests") {
  kj::EventLoop eventLoop;
  kj::WaitScope waitScope(eventLoop);

  kj::HttpHeaderTable table;

  auto pipe = kj::newOneWayPipe();
  auto input = newHttpInputStream(*pipe.in, table);

  kj::Promise<void> writeQueue = kj::READY_NOW;

  for (auto& testCase: requestTestCases()) {
    writeQueue = writeQueue.then([&]() {
      return pipe.out->write(testCase.raw.begin(), testCase.raw.size());
    });
  }
  writeQueue = writeQueue.then([&]() {
    pipe.out = nullptr;
  });

  for (auto& testCase: requestTestCases()) {
    KJ_CONTEXT(testCase.raw);

    KJ_ASSERT(input->awaitNextMessage().wait(waitScope));
1421

1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531
    auto req = input->readRequest().wait(waitScope);
    KJ_EXPECT(req.method == testCase.method);
    KJ_EXPECT(req.url == testCase.path);
    for (auto& header: testCase.requestHeaders) {
      KJ_EXPECT(KJ_ASSERT_NONNULL(req.headers.get(header.id)) == header.value);
    }
    auto body = req.body->readAllText().wait(waitScope);
    KJ_EXPECT(body == kj::strArray(testCase.requestBodyParts, ""));
  }

  writeQueue.wait(waitScope);
  KJ_EXPECT(!input->awaitNextMessage().wait(waitScope));
}

KJ_TEST("HttpInputStream responses") {
  kj::EventLoop eventLoop;
  kj::WaitScope waitScope(eventLoop);

  kj::HttpHeaderTable table;

  auto pipe = kj::newOneWayPipe();
  auto input = newHttpInputStream(*pipe.in, table);

  kj::Promise<void> writeQueue = kj::READY_NOW;

  for (auto& testCase: responseTestCases()) {
    if (testCase.side == CLIENT_ONLY) continue;  // skip Connection: close case.
    writeQueue = writeQueue.then([&]() {
      return pipe.out->write(testCase.raw.begin(), testCase.raw.size());
    });
  }
  writeQueue = writeQueue.then([&]() {
    pipe.out = nullptr;
  });

  for (auto& testCase: responseTestCases()) {
    if (testCase.side == CLIENT_ONLY) continue;  // skip Connection: close case.
    KJ_CONTEXT(testCase.raw);

    KJ_ASSERT(input->awaitNextMessage().wait(waitScope));
    
    auto resp = input->readResponse(testCase.method).wait(waitScope);
    KJ_EXPECT(resp.statusCode == testCase.statusCode);
    KJ_EXPECT(resp.statusText == testCase.statusText);
    for (auto& header: testCase.responseHeaders) {
      KJ_EXPECT(KJ_ASSERT_NONNULL(resp.headers.get(header.id)) == header.value);
    }
    auto body = resp.body->readAllText().wait(waitScope);
    KJ_EXPECT(body == kj::strArray(testCase.responseBodyParts, ""));
  }

  writeQueue.wait(waitScope);
  KJ_EXPECT(!input->awaitNextMessage().wait(waitScope));
}

KJ_TEST("HttpInputStream bare messages") {
  kj::EventLoop eventLoop;
  kj::WaitScope waitScope(eventLoop);

  kj::HttpHeaderTable table;

  auto pipe = kj::newOneWayPipe();
  auto input = newHttpInputStream(*pipe.in, table);

  kj::StringPtr messages =
      "Content-Length: 6\r\n"
      "\r\n"
      "foobar"
      "Content-Length: 11\r\n"
      "Content-Type: some/type\r\n"
      "\r\n"
      "bazquxcorge"
      "Transfer-Encoding: chunked\r\n"
      "\r\n"
      "6\r\n"
      "grault\r\n"
      "b\r\n"
      "garplywaldo\r\n"
      "0\r\n"
      "\r\n"_kj;

  kj::Promise<void> writeTask = pipe.out->write(messages.begin(), messages.size())
      .then([&]() { pipe.out = nullptr; });

  {
    KJ_ASSERT(input->awaitNextMessage().wait(waitScope));
    auto message = input->readMessage().wait(waitScope);
    KJ_EXPECT(KJ_ASSERT_NONNULL(message.headers.get(HttpHeaderId::CONTENT_LENGTH)) == "6");
    KJ_EXPECT(message.body->readAllText().wait(waitScope) == "foobar");
  }
  {
    KJ_ASSERT(input->awaitNextMessage().wait(waitScope));
    auto message = input->readMessage().wait(waitScope);
    KJ_EXPECT(KJ_ASSERT_NONNULL(message.headers.get(HttpHeaderId::CONTENT_LENGTH)) == "11");
    KJ_EXPECT(KJ_ASSERT_NONNULL(message.headers.get(HttpHeaderId::CONTENT_TYPE)) == "some/type");
    KJ_EXPECT(message.body->readAllText().wait(waitScope) == "bazquxcorge");
  }
  {
    KJ_ASSERT(input->awaitNextMessage().wait(waitScope));
    auto message = input->readMessage().wait(waitScope);
    KJ_EXPECT(KJ_ASSERT_NONNULL(message.headers.get(HttpHeaderId::TRANSFER_ENCODING)) == "chunked");
    KJ_EXPECT(message.body->readAllText().wait(waitScope) == "graultgarplywaldo");
  }

  writeTask.wait(waitScope);
  KJ_EXPECT(!input->awaitNextMessage().wait(waitScope));
}

// -----------------------------------------------------------------------------

1532
KJ_TEST("WebSocket core protocol") {
1533 1534
  kj::EventLoop eventLoop;
  kj::WaitScope waitScope(eventLoop);
1535
  auto pipe = kj::newTwoWayPipe();
1536

1537 1538
  auto client = newWebSocket(kj::mv(pipe.ends[0]), nullptr);
  auto server = newWebSocket(kj::mv(pipe.ends[1]), nullptr);
1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549

  auto mediumString = kj::strArray(kj::repeat(kj::StringPtr("123456789"), 30), "");
  auto bigString = kj::strArray(kj::repeat(kj::StringPtr("123456789"), 10000), "");

  auto clientTask = client->send(kj::StringPtr("hello"))
      .then([&]() { return client->send(mediumString); })
      .then([&]() { return client->send(bigString); })
      .then([&]() { return client->send(kj::StringPtr("world").asBytes()); })
      .then([&]() { return client->close(1234, "bored"); });

  {
1550
    auto message = server->receive().wait(waitScope);
1551 1552 1553 1554 1555
    KJ_ASSERT(message.is<kj::String>());
    KJ_EXPECT(message.get<kj::String>() == "hello");
  }

  {
1556
    auto message = server->receive().wait(waitScope);
1557 1558 1559 1560 1561
    KJ_ASSERT(message.is<kj::String>());
    KJ_EXPECT(message.get<kj::String>() == mediumString);
  }

  {
1562
    auto message = server->receive().wait(waitScope);
1563 1564 1565 1566 1567
    KJ_ASSERT(message.is<kj::String>());
    KJ_EXPECT(message.get<kj::String>() == bigString);
  }

  {
1568
    auto message = server->receive().wait(waitScope);
1569 1570 1571 1572 1573
    KJ_ASSERT(message.is<kj::Array<byte>>());
    KJ_EXPECT(kj::str(message.get<kj::Array<byte>>().asChars()) == "world");
  }

  {
1574
    auto message = server->receive().wait(waitScope);
1575 1576 1577 1578 1579 1580 1581 1582
    KJ_ASSERT(message.is<WebSocket::Close>());
    KJ_EXPECT(message.get<WebSocket::Close>().code == 1234);
    KJ_EXPECT(message.get<WebSocket::Close>().reason == "bored");
  }

  auto serverTask = server->close(4321, "whatever");

  {
1583
    auto message = client->receive().wait(waitScope);
1584 1585 1586 1587 1588
    KJ_ASSERT(message.is<WebSocket::Close>());
    KJ_EXPECT(message.get<WebSocket::Close>().code == 4321);
    KJ_EXPECT(message.get<WebSocket::Close>().reason == "whatever");
  }

1589 1590
  clientTask.wait(waitScope);
  serverTask.wait(waitScope);
1591 1592 1593
}

KJ_TEST("WebSocket fragmented") {
1594 1595
  kj::EventLoop eventLoop;
  kj::WaitScope waitScope(eventLoop);
1596
  auto pipe = kj::newTwoWayPipe();
1597 1598

  auto client = kj::mv(pipe.ends[0]);
1599
  auto server = newWebSocket(kj::mv(pipe.ends[1]), nullptr);
1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611

  byte DATA[] = {
    0x01, 0x06, 'h', 'e', 'l', 'l', 'o', ' ',

    0x00, 0x03, 'w', 'o', 'r',

    0x80, 0x02, 'l', 'd',
  };

  auto clientTask = client->write(DATA, sizeof(DATA));

  {
1612
    auto message = server->receive().wait(waitScope);
1613 1614 1615 1616
    KJ_ASSERT(message.is<kj::String>());
    KJ_EXPECT(message.get<kj::String>() == "hello world");
  }

1617
  clientTask.wait(waitScope);
1618 1619
}

1620
class FakeEntropySource final: public EntropySource {
1621
public:
1622 1623 1624 1625 1626 1627
  void generate(kj::ArrayPtr<byte> buffer) override {
    static constexpr byte DUMMY[4] = { 12, 34, 56, 78 };

    for (auto i: kj::indices(buffer)) {
      buffer[i] = DUMMY[i % sizeof(DUMMY)];
    }
1628 1629 1630 1631
  }
};

KJ_TEST("WebSocket masked") {
1632 1633
  kj::EventLoop eventLoop;
  kj::WaitScope waitScope(eventLoop);
1634
  auto pipe = kj::newTwoWayPipe();
1635
  FakeEntropySource maskGenerator;
1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647

  auto client = kj::mv(pipe.ends[0]);
  auto server = newWebSocket(kj::mv(pipe.ends[1]), maskGenerator);

  byte DATA[] = {
    0x81, 0x86, 12, 34, 56, 78, 'h' ^ 12, 'e' ^ 34, 'l' ^ 56, 'l' ^ 78, 'o' ^ 12, ' ' ^ 34,
  };

  auto clientTask = client->write(DATA, sizeof(DATA));
  auto serverTask = server->send(kj::StringPtr("hello "));

  {
1648
    auto message = server->receive().wait(waitScope);
1649 1650 1651 1652
    KJ_ASSERT(message.is<kj::String>());
    KJ_EXPECT(message.get<kj::String>() == "hello ");
  }

1653
  expectRead(*client, DATA).wait(waitScope);
1654

1655 1656
  clientTask.wait(waitScope);
  serverTask.wait(waitScope);
1657 1658 1659
}

KJ_TEST("WebSocket unsolicited pong") {
1660 1661
  kj::EventLoop eventLoop;
  kj::WaitScope waitScope(eventLoop);
1662
  auto pipe = kj::newTwoWayPipe();
1663 1664

  auto client = kj::mv(pipe.ends[0]);
1665
  auto server = newWebSocket(kj::mv(pipe.ends[1]), nullptr);
1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677

  byte DATA[] = {
    0x01, 0x06, 'h', 'e', 'l', 'l', 'o', ' ',

    0x8A, 0x03, 'f', 'o', 'o',

    0x80, 0x05, 'w', 'o', 'r', 'l', 'd',
  };

  auto clientTask = client->write(DATA, sizeof(DATA));

  {
1678
    auto message = server->receive().wait(waitScope);
1679 1680 1681 1682
    KJ_ASSERT(message.is<kj::String>());
    KJ_EXPECT(message.get<kj::String>() == "hello world");
  }

1683
  clientTask.wait(waitScope);
1684 1685 1686
}

KJ_TEST("WebSocket ping") {
1687 1688
  kj::EventLoop eventLoop;
  kj::WaitScope waitScope(eventLoop);
1689
  auto pipe = kj::newTwoWayPipe();
1690 1691

  auto client = kj::mv(pipe.ends[0]);
1692
  auto server = newWebSocket(kj::mv(pipe.ends[1]), nullptr);
1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705

  // Be extra-annoying by having the ping arrive between fragments.
  byte DATA[] = {
    0x01, 0x06, 'h', 'e', 'l', 'l', 'o', ' ',

    0x89, 0x03, 'f', 'o', 'o',

    0x80, 0x05, 'w', 'o', 'r', 'l', 'd',
  };

  auto clientTask = client->write(DATA, sizeof(DATA));

  {
1706
    auto message = server->receive().wait(waitScope);
1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717
    KJ_ASSERT(message.is<kj::String>());
    KJ_EXPECT(message.get<kj::String>() == "hello world");
  }

  auto serverTask = server->send(kj::StringPtr("bar"));

  byte EXPECTED[] = {
    0x8A, 0x03, 'f', 'o', 'o',  // pong
    0x81, 0x03, 'b', 'a', 'r',  // message
  };

1718
  expectRead(*client, EXPECTED).wait(waitScope);
1719

1720 1721
  clientTask.wait(waitScope);
  serverTask.wait(waitScope);
1722 1723 1724
}

KJ_TEST("WebSocket ping mid-send") {
1725 1726
  kj::EventLoop eventLoop;
  kj::WaitScope waitScope(eventLoop);
1727
  auto pipe = kj::newTwoWayPipe();
1728 1729

  auto client = kj::mv(pipe.ends[0]);
1730
  auto server = newWebSocket(kj::mv(pipe.ends[1]), nullptr);
1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742

  auto bigString = kj::strArray(kj::repeat(kj::StringPtr("12345678"), 65536), "");
  auto serverTask = server->send(bigString).eagerlyEvaluate(nullptr);

  byte DATA[] = {
    0x89, 0x03, 'f', 'o', 'o',  // ping
    0x81, 0x03, 'b', 'a', 'r',  // some other message
  };

  auto clientTask = client->write(DATA, sizeof(DATA));

  {
1743
    auto message = server->receive().wait(waitScope);
1744 1745 1746 1747 1748
    KJ_ASSERT(message.is<kj::String>());
    KJ_EXPECT(message.get<kj::String>() == "bar");
  }

  byte EXPECTED1[] = { 0x81, 0x7f, 0, 0, 0, 0, 0, 8, 0, 0 };
1749 1750
  expectRead(*client, EXPECTED1).wait(waitScope);
  expectRead(*client, bigString).wait(waitScope);
1751 1752

  byte EXPECTED2[] = { 0x8A, 0x03, 'f', 'o', 'o' };
1753
  expectRead(*client, EXPECTED2).wait(waitScope);
1754

1755 1756
  clientTask.wait(waitScope);
  serverTask.wait(waitScope);
1757 1758
}

1759 1760 1761 1762
class InputOutputPair final: public kj::AsyncIoStream {
  // Creates an AsyncIoStream out of an AsyncInputStream and an AsyncOutputStream.

public:
1763 1764
  InputOutputPair(kj::Own<kj::AsyncInputStream> in, kj::Own<kj::AsyncOutputStream> out)
      : in(kj::mv(in)), out(kj::mv(out)) {}
1765 1766

  kj::Promise<size_t> read(void* buffer, size_t minBytes, size_t maxBytes) override {
1767
    return in->read(buffer, minBytes, maxBytes);
1768 1769
  }
  kj::Promise<size_t> tryRead(void* buffer, size_t minBytes, size_t maxBytes) override {
1770
    return in->tryRead(buffer, minBytes, maxBytes);
1771 1772 1773
  }

  Maybe<uint64_t> tryGetLength() override {
1774
    return in->tryGetLength();
1775 1776 1777
  }

  Promise<uint64_t> pumpTo(AsyncOutputStream& output, uint64_t amount = kj::maxValue) override {
1778
    return in->pumpTo(output, amount);
1779 1780 1781
  }

  kj::Promise<void> write(const void* buffer, size_t size) override {
1782
    return out->write(buffer, size);
1783 1784 1785
  }

  kj::Promise<void> write(kj::ArrayPtr<const kj::ArrayPtr<const byte>> pieces) override {
1786
    return out->write(pieces);
1787 1788 1789 1790
  }

  kj::Maybe<kj::Promise<uint64_t>> tryPumpFrom(
      kj::AsyncInputStream& input, uint64_t amount = kj::maxValue) override {
1791
    return out->tryPumpFrom(input, amount);
1792 1793 1794
  }

  void shutdownWrite() override {
1795
    out = nullptr;
1796 1797 1798
  }

private:
1799 1800
  kj::Own<kj::AsyncInputStream> in;
  kj::Own<kj::AsyncOutputStream> out;
1801 1802
};

1803
KJ_TEST("WebSocket double-ping mid-send") {
1804 1805
  kj::EventLoop eventLoop;
  kj::WaitScope waitScope(eventLoop);
1806

1807 1808 1809 1810 1811
  auto upPipe = newOneWayPipe();
  auto downPipe = newOneWayPipe();
  InputOutputPair client(kj::mv(downPipe.in), kj::mv(upPipe.out));
  auto server = newWebSocket(kj::heap<InputOutputPair>(kj::mv(upPipe.in), kj::mv(downPipe.out)),
                             nullptr);
1812 1813 1814 1815 1816 1817 1818 1819 1820 1821

  auto bigString = kj::strArray(kj::repeat(kj::StringPtr("12345678"), 65536), "");
  auto serverTask = server->send(bigString).eagerlyEvaluate(nullptr);

  byte DATA[] = {
    0x89, 0x03, 'f', 'o', 'o',  // ping
    0x89, 0x03, 'q', 'u', 'x',  // ping2
    0x81, 0x03, 'b', 'a', 'r',  // some other message
  };

1822
  auto clientTask = client.write(DATA, sizeof(DATA));
1823 1824

  {
1825
    auto message = server->receive().wait(waitScope);
1826 1827 1828 1829 1830
    KJ_ASSERT(message.is<kj::String>());
    KJ_EXPECT(message.get<kj::String>() == "bar");
  }

  byte EXPECTED1[] = { 0x81, 0x7f, 0, 0, 0, 0, 0, 8, 0, 0 };
1831 1832
  expectRead(client, EXPECTED1).wait(waitScope);
  expectRead(client, bigString).wait(waitScope);
1833 1834

  byte EXPECTED2[] = { 0x8A, 0x03, 'q', 'u', 'x' };
1835
  expectRead(client, EXPECTED2).wait(waitScope);
1836

1837 1838
  clientTask.wait(waitScope);
  serverTask.wait(waitScope);
1839 1840 1841
}

KJ_TEST("WebSocket ping received during pong send") {
1842 1843
  kj::EventLoop eventLoop;
  kj::WaitScope waitScope(eventLoop);
1844
  auto pipe = kj::newTwoWayPipe();
1845 1846

  auto client = kj::mv(pipe.ends[0]);
1847
  auto server = newWebSocket(kj::mv(pipe.ends[1]), nullptr);
1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861

  // Send a very large ping so that sending the pong takes a while. Then send a second ping
  // immediately after.
  byte PREFIX[] = { 0x89, 0x7f, 0, 0, 0, 0, 0, 8, 0, 0 };
  auto bigString = kj::strArray(kj::repeat(kj::StringPtr("12345678"), 65536), "");
  byte POSTFIX[] = {
    0x89, 0x03, 'f', 'o', 'o',
    0x81, 0x03, 'b', 'a', 'r',
  };

  kj::ArrayPtr<const byte> parts[] = {PREFIX, bigString.asBytes(), POSTFIX};
  auto clientTask = client->write(parts);

  {
1862
    auto message = server->receive().wait(waitScope);
1863 1864 1865 1866 1867
    KJ_ASSERT(message.is<kj::String>());
    KJ_EXPECT(message.get<kj::String>() == "bar");
  }

  byte EXPECTED1[] = { 0x8A, 0x7f, 0, 0, 0, 0, 0, 8, 0, 0 };
1868 1869
  expectRead(*client, EXPECTED1).wait(waitScope);
  expectRead(*client, bigString).wait(waitScope);
1870 1871

  byte EXPECTED2[] = { 0x8A, 0x03, 'f', 'o', 'o' };
1872
  expectRead(*client, EXPECTED2).wait(waitScope);
1873

1874
  clientTask.wait(waitScope);
1875 1876
}

1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895
KJ_TEST("WebSocket pump disconnect on send") {
  kj::EventLoop eventLoop;
  kj::WaitScope waitScope(eventLoop);
  auto pipe1 = kj::newTwoWayPipe();
  auto pipe2 = kj::newTwoWayPipe();

  auto client1 = newWebSocket(kj::mv(pipe1.ends[0]), nullptr);
  auto server1 = newWebSocket(kj::mv(pipe1.ends[1]), nullptr);
  auto client2 = newWebSocket(kj::mv(pipe2.ends[0]), nullptr);

  auto pumpTask = server1->pumpTo(*client2);
  auto sendTask = client1->send("hello"_kj);

  // Endpoint reads three bytes and then disconnects.
  char buffer[3];
  pipe2.ends[1]->read(buffer, 3).wait(waitScope);
  pipe2.ends[1] = nullptr;

  // Pump throws disconnected.
1896
  KJ_EXPECT_THROW_RECOVERABLE(DISCONNECTED, pumpTask.wait(waitScope));
1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926

  // client1 managed to send its whole message into the pump, though.
  sendTask.wait(waitScope);
}

KJ_TEST("WebSocket pump disconnect on receive") {
  kj::EventLoop eventLoop;
  kj::WaitScope waitScope(eventLoop);
  auto pipe1 = kj::newTwoWayPipe();
  auto pipe2 = kj::newTwoWayPipe();

  auto server1 = newWebSocket(kj::mv(pipe1.ends[1]), nullptr);
  auto client2 = newWebSocket(kj::mv(pipe2.ends[0]), nullptr);
  auto server2 = newWebSocket(kj::mv(pipe2.ends[1]), nullptr);

  auto pumpTask = server1->pumpTo(*client2);
  auto receiveTask = server2->receive();

  // Client sends three bytes of a valid message then disconnects.
  const char DATA[] = {0x01, 0x06, 'h'};
  pipe1.ends[0]->write(DATA, 3).wait(waitScope);
  pipe1.ends[0] = nullptr;

  // The pump completes successfully, forwarding the disconnect.
  pumpTask.wait(waitScope);

  // The eventual receiver gets a disconnect execption.
  KJ_EXPECT_THROW(DISCONNECTED, receiveTask.wait(waitScope));
}

1927 1928 1929 1930 1931 1932 1933 1934
class TestWebSocketService final: public HttpService, private kj::TaskSet::ErrorHandler {
public:
  TestWebSocketService(HttpHeaderTable& headerTable, HttpHeaderId hMyHeader)
      : headerTable(headerTable), hMyHeader(hMyHeader), tasks(*this) {}

  kj::Promise<void> request(
      HttpMethod method, kj::StringPtr url, const HttpHeaders& headers,
      kj::AsyncInputStream& requestBody, Response& response) override {
1935
    KJ_ASSERT(headers.isWebSocket());
1936 1937 1938 1939 1940 1941 1942 1943 1944

    HttpHeaders responseHeaders(headerTable);
    KJ_IF_MAYBE(h, headers.get(hMyHeader)) {
      responseHeaders.set(hMyHeader, kj::str("respond-", *h));
    }

    if (url == "/return-error") {
      response.send(404, "Not Found", responseHeaders, uint64_t(0));
      return kj::READY_NOW;
1945
    } else if (url == "/websocket") {
1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988
      auto ws = response.acceptWebSocket(responseHeaders);
      return doWebSocket(*ws, "start-inline").attach(kj::mv(ws));
    } else {
      KJ_FAIL_ASSERT("unexpected path", url);
    }
  }

private:
  HttpHeaderTable& headerTable;
  HttpHeaderId hMyHeader;
  kj::TaskSet tasks;

  void taskFailed(kj::Exception&& exception) override {
    KJ_LOG(ERROR, exception);
  }

  static kj::Promise<void> doWebSocket(WebSocket& ws, kj::StringPtr message) {
    auto copy = kj::str(message);
    return ws.send(copy).attach(kj::mv(copy))
        .then([&ws]() {
      return ws.receive();
    }).then([&ws](WebSocket::Message&& message) {
      KJ_SWITCH_ONEOF(message) {
        KJ_CASE_ONEOF(str, kj::String) {
          return doWebSocket(ws, kj::str("reply:", str));
        }
        KJ_CASE_ONEOF(data, kj::Array<byte>) {
          return doWebSocket(ws, kj::str("reply:", data));
        }
        KJ_CASE_ONEOF(close, WebSocket::Close) {
          auto reason = kj::str("close-reply:", close.reason);
          return ws.close(close.code + 1, reason).attach(kj::mv(reason));
        }
      }
      KJ_UNREACHABLE;
    });
  }
};

const char WEBSOCKET_REQUEST_HANDSHAKE[] =
    " HTTP/1.1\r\n"
    "Connection: Upgrade\r\n"
    "Upgrade: websocket\r\n"
1989
    "Sec-WebSocket-Key: DCI4TgwiOE4MIjhODCI4Tg==\r\n"
1990 1991 1992 1993 1994 1995 1996
    "Sec-WebSocket-Version: 13\r\n"
    "My-Header: foo\r\n"
    "\r\n";
const char WEBSOCKET_RESPONSE_HANDSHAKE[] =
    "HTTP/1.1 101 Switching Protocols\r\n"
    "Connection: Upgrade\r\n"
    "Upgrade: websocket\r\n"
1997
    "Sec-WebSocket-Accept: pShtIFKT0s8RYZvnWY/CrjQD8CM=\r\n"
1998 1999 2000 2001 2002 2003 2004
    "My-Header: respond-foo\r\n"
    "\r\n";
const char WEBSOCKET_RESPONSE_HANDSHAKE_ERROR[] =
    "HTTP/1.1 404 Not Found\r\n"
    "Content-Length: 0\r\n"
    "My-Header: respond-foo\r\n"
    "\r\n";
2005 2006 2007 2008 2009 2010 2011 2012 2013 2014
const byte WEBSOCKET_FIRST_MESSAGE_INLINE[] =
    { 0x81, 0x0c, 's','t','a','r','t','-','i','n','l','i','n','e' };
const byte WEBSOCKET_SEND_MESSAGE[] =
    { 0x81, 0x83, 12, 34, 56, 78, 'b'^12, 'a'^34, 'r'^56 };
const byte WEBSOCKET_REPLY_MESSAGE[] =
    { 0x81, 0x09, 'r','e','p','l','y',':','b','a','r' };
const byte WEBSOCKET_SEND_CLOSE[] =
    { 0x88, 0x85, 12, 34, 56, 78, 0x12^12, 0x34^34, 'q'^56, 'u'^78, 'x'^12 };
const byte WEBSOCKET_REPLY_CLOSE[] =
    { 0x88, 0x11, 0x12, 0x35, 'c','l','o','s','e','-','r','e','p','l','y',':','q','u','x' };
2015 2016

template <size_t s>
2017 2018 2019 2020
kj::ArrayPtr<const byte> asBytes(const char (&chars)[s]) {
  return kj::ArrayPtr<const char>(chars, s - 1).asBytes();
}

2021 2022 2023
void testWebSocketClient(kj::WaitScope& waitScope, HttpHeaderTable& headerTable,
                         kj::HttpHeaderId hMyHeader, HttpClient& client) {
  kj::HttpHeaders headers(headerTable);
2024
  headers.set(hMyHeader, "foo");
2025
  auto response = client.openWebSocket("/websocket", headers).wait(waitScope);
2026 2027 2028 2029 2030 2031 2032 2033

  KJ_EXPECT(response.statusCode == 101);
  KJ_EXPECT(response.statusText == "Switching Protocols", response.statusText);
  KJ_EXPECT(KJ_ASSERT_NONNULL(response.headers->get(hMyHeader)) == "respond-foo");
  KJ_ASSERT(response.webSocketOrBody.is<kj::Own<WebSocket>>());
  auto ws = kj::mv(response.webSocketOrBody.get<kj::Own<WebSocket>>());

  {
2034
    auto message = ws->receive().wait(waitScope);
2035 2036 2037 2038
    KJ_ASSERT(message.is<kj::String>());
    KJ_EXPECT(message.get<kj::String>() == "start-inline");
  }

2039
  ws->send(kj::StringPtr("bar")).wait(waitScope);
2040
  {
2041
    auto message = ws->receive().wait(waitScope);
2042 2043 2044 2045
    KJ_ASSERT(message.is<kj::String>());
    KJ_EXPECT(message.get<kj::String>() == "reply:bar");
  }

2046
  ws->close(0x1234, "qux").wait(waitScope);
2047
  {
2048
    auto message = ws->receive().wait(waitScope);
2049 2050 2051 2052
    KJ_ASSERT(message.is<WebSocket::Close>());
    KJ_EXPECT(message.get<WebSocket::Close>().code == 0x1235);
    KJ_EXPECT(message.get<WebSocket::Close>().reason == "close-reply:qux");
  }
2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075
}

KJ_TEST("HttpClient WebSocket handshake") {
  kj::EventLoop eventLoop;
  kj::WaitScope waitScope(eventLoop);
  auto pipe = kj::newTwoWayPipe();

  auto request = kj::str("GET /websocket", WEBSOCKET_REQUEST_HANDSHAKE);

  auto serverTask = expectRead(*pipe.ends[1], request)
      .then([&]() { return pipe.ends[1]->write({asBytes(WEBSOCKET_RESPONSE_HANDSHAKE)}); })
      .then([&]() { return pipe.ends[1]->write({WEBSOCKET_FIRST_MESSAGE_INLINE}); })
      .then([&]() { return expectRead(*pipe.ends[1], WEBSOCKET_SEND_MESSAGE); })
      .then([&]() { return pipe.ends[1]->write({WEBSOCKET_REPLY_MESSAGE}); })
      .then([&]() { return expectRead(*pipe.ends[1], WEBSOCKET_SEND_CLOSE); })
      .then([&]() { return pipe.ends[1]->write({WEBSOCKET_REPLY_CLOSE}); })
      .eagerlyEvaluate([](kj::Exception&& e) { KJ_LOG(ERROR, e); });

  HttpHeaderTable::Builder tableBuilder;
  HttpHeaderId hMyHeader = tableBuilder.add("My-Header");
  auto headerTable = tableBuilder.build();

  FakeEntropySource entropySource;
2076 2077
  HttpClientSettings clientSettings;
  clientSettings.entropySource = entropySource;
2078

2079
  auto client = newHttpClient(*headerTable, *pipe.ends[0], clientSettings);
2080 2081

  testWebSocketClient(waitScope, *headerTable, hMyHeader, *client);
2082

2083
  serverTask.wait(waitScope);
2084 2085 2086
}

KJ_TEST("HttpClient WebSocket error") {
2087 2088
  kj::EventLoop eventLoop;
  kj::WaitScope waitScope(eventLoop);
2089
  auto pipe = kj::newTwoWayPipe();
2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103

  auto request = kj::str("GET /websocket", WEBSOCKET_REQUEST_HANDSHAKE);

  auto serverTask = expectRead(*pipe.ends[1], request)
      .then([&]() { return pipe.ends[1]->write({asBytes(WEBSOCKET_RESPONSE_HANDSHAKE_ERROR)}); })
      .then([&]() { return expectRead(*pipe.ends[1], request); })
      .then([&]() { return pipe.ends[1]->write({asBytes(WEBSOCKET_RESPONSE_HANDSHAKE_ERROR)}); })
      .eagerlyEvaluate([](kj::Exception&& e) { KJ_LOG(ERROR, e); });

  HttpHeaderTable::Builder tableBuilder;
  HttpHeaderId hMyHeader = tableBuilder.add("My-Header");
  auto headerTable = tableBuilder.build();

  FakeEntropySource entropySource;
2104 2105
  HttpClientSettings clientSettings;
  clientSettings.entropySource = entropySource;
2106

2107
  auto client = newHttpClient(*headerTable, *pipe.ends[0], clientSettings);
2108 2109 2110 2111 2112

  kj::HttpHeaders headers(*headerTable);
  headers.set(hMyHeader, "foo");

  {
2113
    auto response = client->openWebSocket("/websocket", headers).wait(waitScope);
2114 2115 2116 2117 2118 2119 2120 2121

    KJ_EXPECT(response.statusCode == 404);
    KJ_EXPECT(response.statusText == "Not Found", response.statusText);
    KJ_EXPECT(KJ_ASSERT_NONNULL(response.headers->get(hMyHeader)) == "respond-foo");
    KJ_ASSERT(response.webSocketOrBody.is<kj::Own<AsyncInputStream>>());
  }

  {
2122
    auto response = client->openWebSocket("/websocket", headers).wait(waitScope);
2123 2124 2125 2126 2127 2128 2129

    KJ_EXPECT(response.statusCode == 404);
    KJ_EXPECT(response.statusText == "Not Found", response.statusText);
    KJ_EXPECT(KJ_ASSERT_NONNULL(response.headers->get(hMyHeader)) == "respond-foo");
    KJ_ASSERT(response.webSocketOrBody.is<kj::Own<AsyncInputStream>>());
  }

2130
  serverTask.wait(waitScope);
2131 2132 2133
}

KJ_TEST("HttpServer WebSocket handshake") {
2134 2135 2136
  kj::EventLoop eventLoop;
  kj::WaitScope waitScope(eventLoop);
  kj::TimerImpl timer(kj::origin<kj::TimePoint>());
2137
  auto pipe = kj::newTwoWayPipe();
2138 2139 2140 2141 2142

  HttpHeaderTable::Builder tableBuilder;
  HttpHeaderId hMyHeader = tableBuilder.add("My-Header");
  auto headerTable = tableBuilder.build();
  TestWebSocketService service(*headerTable, hMyHeader);
2143
  HttpServer server(timer, *headerTable, service);
2144 2145 2146

  auto listenTask = server.listenHttp(kj::mv(pipe.ends[0]));

2147
  auto request = kj::str("GET /websocket", WEBSOCKET_REQUEST_HANDSHAKE);
2148 2149
  pipe.ends[1]->write({request.asBytes()}).wait(waitScope);
  expectRead(*pipe.ends[1], WEBSOCKET_RESPONSE_HANDSHAKE).wait(waitScope);
2150

2151 2152 2153 2154 2155
  expectRead(*pipe.ends[1], WEBSOCKET_FIRST_MESSAGE_INLINE).wait(waitScope);
  pipe.ends[1]->write({WEBSOCKET_SEND_MESSAGE}).wait(waitScope);
  expectRead(*pipe.ends[1], WEBSOCKET_REPLY_MESSAGE).wait(waitScope);
  pipe.ends[1]->write({WEBSOCKET_SEND_CLOSE}).wait(waitScope);
  expectRead(*pipe.ends[1], WEBSOCKET_REPLY_CLOSE).wait(waitScope);
2156

2157
  listenTask.wait(waitScope);
2158 2159 2160
}

KJ_TEST("HttpServer WebSocket handshake error") {
2161 2162 2163
  kj::EventLoop eventLoop;
  kj::WaitScope waitScope(eventLoop);
  kj::TimerImpl timer(kj::origin<kj::TimePoint>());
2164
  auto pipe = kj::newTwoWayPipe();
2165 2166 2167 2168 2169

  HttpHeaderTable::Builder tableBuilder;
  HttpHeaderId hMyHeader = tableBuilder.add("My-Header");
  auto headerTable = tableBuilder.build();
  TestWebSocketService service(*headerTable, hMyHeader);
2170
  HttpServer server(timer, *headerTable, service);
2171 2172 2173 2174

  auto listenTask = server.listenHttp(kj::mv(pipe.ends[0]));

  auto request = kj::str("GET /return-error", WEBSOCKET_REQUEST_HANDSHAKE);
2175 2176
  pipe.ends[1]->write({request.asBytes()}).wait(waitScope);
  expectRead(*pipe.ends[1], WEBSOCKET_RESPONSE_HANDSHAKE_ERROR).wait(waitScope);
2177 2178

  // Can send more requests!
2179 2180
  pipe.ends[1]->write({request.asBytes()}).wait(waitScope);
  expectRead(*pipe.ends[1], WEBSOCKET_RESPONSE_HANDSHAKE_ERROR).wait(waitScope);
2181 2182 2183

  pipe.ends[1]->shutdownWrite();

2184
  listenTask.wait(waitScope);
2185 2186
}

2187 2188
// -----------------------------------------------------------------------------

2189
KJ_TEST("HttpServer request timeout") {
2190 2191
  auto PIPELINE_TESTS = pipelineTestCases();

2192 2193 2194
  kj::EventLoop eventLoop;
  kj::WaitScope waitScope(eventLoop);
  kj::TimerImpl timer(kj::origin<kj::TimePoint>());
2195
  auto pipe = kj::newTwoWayPipe();
2196 2197 2198 2199 2200

  HttpHeaderTable table;
  TestHttpService service(PIPELINE_TESTS, table);
  HttpServerSettings settings;
  settings.headerTimeout = 1 * kj::MILLISECONDS;
2201
  HttpServer server(timer, table, service, settings);
2202 2203

  // Shouldn't hang! Should time out.
2204 2205 2206 2207 2208 2209
  auto promise = server.listenHttp(kj::mv(pipe.ends[0]));
  KJ_EXPECT(!promise.poll(waitScope));
  timer.advanceTo(timer.now() + settings.headerTimeout / 2);
  KJ_EXPECT(!promise.poll(waitScope));
  timer.advanceTo(timer.now() + settings.headerTimeout);
  promise.wait(waitScope);
2210

2211
  // Closes the connection without sending anything.
2212
  KJ_EXPECT(pipe.ends[1]->readAllText().wait(waitScope) == "");
2213 2214 2215
}

KJ_TEST("HttpServer pipeline timeout") {
2216 2217
  auto PIPELINE_TESTS = pipelineTestCases();

2218 2219 2220
  kj::EventLoop eventLoop;
  kj::WaitScope waitScope(eventLoop);
  kj::TimerImpl timer(kj::origin<kj::TimePoint>());
2221
  auto pipe = kj::newTwoWayPipe();
2222 2223 2224 2225 2226

  HttpHeaderTable table;
  TestHttpService service(PIPELINE_TESTS, table);
  HttpServerSettings settings;
  settings.pipelineTimeout = 1 * kj::MILLISECONDS;
2227
  HttpServer server(timer, table, service, settings);
2228 2229 2230 2231 2232

  auto listenTask = server.listenHttp(kj::mv(pipe.ends[0]));

  // Do one request.
  pipe.ends[1]->write(PIPELINE_TESTS[0].request.raw.begin(), PIPELINE_TESTS[0].request.raw.size())
2233 2234
      .wait(waitScope);
  expectRead(*pipe.ends[1], PIPELINE_TESTS[0].response.raw).wait(waitScope);
2235 2236

  // Listen task should time out even though we didn't shutdown the socket.
2237 2238 2239 2240 2241
  KJ_EXPECT(!listenTask.poll(waitScope));
  timer.advanceTo(timer.now() + settings.pipelineTimeout / 2);
  KJ_EXPECT(!listenTask.poll(waitScope));
  timer.advanceTo(timer.now() + settings.pipelineTimeout);
  listenTask.wait(waitScope);
2242 2243

  // In this case, no data is sent back.
2244
  KJ_EXPECT(pipe.ends[1]->readAllText().wait(waitScope) == "");
2245 2246
}

2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269
class BrokenHttpService final: public HttpService {
  // HttpService that doesn't send a response.
public:
  BrokenHttpService() = default;
  explicit BrokenHttpService(kj::Exception&& exception): exception(kj::mv(exception)) {}

  kj::Promise<void> request(
      HttpMethod method, kj::StringPtr url, const HttpHeaders& headers,
      kj::AsyncInputStream& requestBody, Response& responseSender) override {
    return requestBody.readAllBytes().then([this](kj::Array<byte>&&) -> kj::Promise<void> {
      KJ_IF_MAYBE(e, exception) {
        return kj::cp(*e);
      } else {
        return kj::READY_NOW;
      }
    });
  }

private:
  kj::Maybe<kj::Exception> exception;
};

KJ_TEST("HttpServer no response") {
2270 2271
  auto PIPELINE_TESTS = pipelineTestCases();

2272 2273 2274
  kj::EventLoop eventLoop;
  kj::WaitScope waitScope(eventLoop);
  kj::TimerImpl timer(kj::origin<kj::TimePoint>());
2275
  auto pipe = kj::newTwoWayPipe();
2276 2277 2278

  HttpHeaderTable table;
  BrokenHttpService service;
2279
  HttpServer server(timer, table, service);
2280 2281 2282 2283 2284

  auto listenTask = server.listenHttp(kj::mv(pipe.ends[0]));

  // Do one request.
  pipe.ends[1]->write(PIPELINE_TESTS[0].request.raw.begin(), PIPELINE_TESTS[0].request.raw.size())
2285 2286
      .wait(waitScope);
  auto text = pipe.ends[1]->readAllText().wait(waitScope);
2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297

  KJ_EXPECT(text ==
      "HTTP/1.1 500 Internal Server Error\r\n"
      "Connection: close\r\n"
      "Content-Length: 51\r\n"
      "Content-Type: text/plain\r\n"
      "\r\n"
      "ERROR: The HttpService did not generate a response.", text);
}

KJ_TEST("HttpServer disconnected") {
2298 2299
  auto PIPELINE_TESTS = pipelineTestCases();

2300 2301 2302
  kj::EventLoop eventLoop;
  kj::WaitScope waitScope(eventLoop);
  kj::TimerImpl timer(kj::origin<kj::TimePoint>());
2303
  auto pipe = kj::newTwoWayPipe();
2304 2305 2306

  HttpHeaderTable table;
  BrokenHttpService service(KJ_EXCEPTION(DISCONNECTED, "disconnected"));
2307
  HttpServer server(timer, table, service);
2308 2309 2310 2311 2312

  auto listenTask = server.listenHttp(kj::mv(pipe.ends[0]));

  // Do one request.
  pipe.ends[1]->write(PIPELINE_TESTS[0].request.raw.begin(), PIPELINE_TESTS[0].request.raw.size())
2313 2314
      .wait(waitScope);
  auto text = pipe.ends[1]->readAllText().wait(waitScope);
2315 2316 2317 2318 2319

  KJ_EXPECT(text == "", text);
}

KJ_TEST("HttpServer overloaded") {
2320 2321
  auto PIPELINE_TESTS = pipelineTestCases();

2322 2323 2324
  kj::EventLoop eventLoop;
  kj::WaitScope waitScope(eventLoop);
  kj::TimerImpl timer(kj::origin<kj::TimePoint>());
2325
  auto pipe = kj::newTwoWayPipe();
2326 2327 2328

  HttpHeaderTable table;
  BrokenHttpService service(KJ_EXCEPTION(OVERLOADED, "overloaded"));
2329
  HttpServer server(timer, table, service);
2330 2331 2332 2333 2334

  auto listenTask = server.listenHttp(kj::mv(pipe.ends[0]));

  // Do one request.
  pipe.ends[1]->write(PIPELINE_TESTS[0].request.raw.begin(), PIPELINE_TESTS[0].request.raw.size())
2335 2336
      .wait(waitScope);
  auto text = pipe.ends[1]->readAllText().wait(waitScope);
2337 2338 2339 2340 2341

  KJ_EXPECT(text.startsWith("HTTP/1.1 503 Service Unavailable"), text);
}

KJ_TEST("HttpServer unimplemented") {
2342 2343
  auto PIPELINE_TESTS = pipelineTestCases();

2344 2345 2346
  kj::EventLoop eventLoop;
  kj::WaitScope waitScope(eventLoop);
  kj::TimerImpl timer(kj::origin<kj::TimePoint>());
2347
  auto pipe = kj::newTwoWayPipe();
2348 2349 2350

  HttpHeaderTable table;
  BrokenHttpService service(KJ_EXCEPTION(UNIMPLEMENTED, "unimplemented"));
2351
  HttpServer server(timer, table, service);
2352 2353 2354 2355 2356

  auto listenTask = server.listenHttp(kj::mv(pipe.ends[0]));

  // Do one request.
  pipe.ends[1]->write(PIPELINE_TESTS[0].request.raw.begin(), PIPELINE_TESTS[0].request.raw.size())
2357 2358
      .wait(waitScope);
  auto text = pipe.ends[1]->readAllText().wait(waitScope);
2359 2360 2361 2362 2363

  KJ_EXPECT(text.startsWith("HTTP/1.1 501 Not Implemented"), text);
}

KJ_TEST("HttpServer threw exception") {
2364 2365
  auto PIPELINE_TESTS = pipelineTestCases();

2366 2367 2368
  kj::EventLoop eventLoop;
  kj::WaitScope waitScope(eventLoop);
  kj::TimerImpl timer(kj::origin<kj::TimePoint>());
2369
  auto pipe = kj::newTwoWayPipe();
2370 2371 2372

  HttpHeaderTable table;
  BrokenHttpService service(KJ_EXCEPTION(FAILED, "failed"));
2373
  HttpServer server(timer, table, service);
2374 2375 2376 2377 2378

  auto listenTask = server.listenHttp(kj::mv(pipe.ends[0]));

  // Do one request.
  pipe.ends[1]->write(PIPELINE_TESTS[0].request.raw.begin(), PIPELINE_TESTS[0].request.raw.size())
2379 2380
      .wait(waitScope);
  auto text = pipe.ends[1]->readAllText().wait(waitScope);
2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407

  KJ_EXPECT(text.startsWith("HTTP/1.1 500 Internal Server Error"), text);
}

class PartialResponseService final: public HttpService {
  // HttpService that sends a partial response then throws.
public:
  kj::Promise<void> request(
      HttpMethod method, kj::StringPtr url, const HttpHeaders& headers,
      kj::AsyncInputStream& requestBody, Response& response) override {
    return requestBody.readAllBytes()
        .then([this,&response](kj::Array<byte>&&) -> kj::Promise<void> {
      HttpHeaders headers(table);
      auto body = response.send(200, "OK", headers, 32);
      auto promise = body->write("foo", 3);
      return promise.attach(kj::mv(body)).then([]() -> kj::Promise<void> {
        return KJ_EXCEPTION(FAILED, "failed");
      });
    });
  }

private:
  kj::Maybe<kj::Exception> exception;
  HttpHeaderTable table;
};

KJ_TEST("HttpServer threw exception after starting response") {
2408 2409
  auto PIPELINE_TESTS = pipelineTestCases();

2410 2411 2412
  kj::EventLoop eventLoop;
  kj::WaitScope waitScope(eventLoop);
  kj::TimerImpl timer(kj::origin<kj::TimePoint>());
2413
  auto pipe = kj::newTwoWayPipe();
2414 2415 2416

  HttpHeaderTable table;
  PartialResponseService service;
2417
  HttpServer server(timer, table, service);
2418 2419 2420 2421 2422 2423 2424

  auto listenTask = server.listenHttp(kj::mv(pipe.ends[0]));

  KJ_EXPECT_LOG(ERROR, "HttpService threw exception after generating a partial response");

  // Do one request.
  pipe.ends[1]->write(PIPELINE_TESTS[0].request.raw.begin(), PIPELINE_TESTS[0].request.raw.size())
2425 2426
      .wait(waitScope);
  auto text = pipe.ends[1]->readAllText().wait(waitScope);
2427 2428 2429 2430 2431 2432 2433 2434

  KJ_EXPECT(text ==
      "HTTP/1.1 200 OK\r\n"
      "Content-Length: 32\r\n"
      "\r\n"
      "foo", text);
}

2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480
class PartialResponseNoThrowService final: public HttpService {
  // HttpService that sends a partial response then returns without throwing.
public:
  kj::Promise<void> request(
      HttpMethod method, kj::StringPtr url, const HttpHeaders& headers,
      kj::AsyncInputStream& requestBody, Response& response) override {
    return requestBody.readAllBytes()
        .then([this,&response](kj::Array<byte>&&) -> kj::Promise<void> {
      HttpHeaders headers(table);
      auto body = response.send(200, "OK", headers, 32);
      auto promise = body->write("foo", 3);
      return promise.attach(kj::mv(body));
    });
  }

private:
  kj::Maybe<kj::Exception> exception;
  HttpHeaderTable table;
};

KJ_TEST("HttpServer failed to write complete response but didn't throw") {
  auto PIPELINE_TESTS = pipelineTestCases();

  kj::EventLoop eventLoop;
  kj::WaitScope waitScope(eventLoop);
  kj::TimerImpl timer(kj::origin<kj::TimePoint>());
  auto pipe = kj::newTwoWayPipe();

  HttpHeaderTable table;
  PartialResponseNoThrowService service;
  HttpServer server(timer, table, service);

  auto listenTask = server.listenHttp(kj::mv(pipe.ends[0]));

  // Do one request.
  pipe.ends[1]->write(PIPELINE_TESTS[0].request.raw.begin(), PIPELINE_TESTS[0].request.raw.size())
      .wait(waitScope);
  auto text = pipe.ends[1]->readAllText().wait(waitScope);

  KJ_EXPECT(text ==
      "HTTP/1.1 200 OK\r\n"
      "Content-Length: 32\r\n"
      "\r\n"
      "foo", text);
}

2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528
class SimpleInputStream final: public kj::AsyncInputStream {
  // An InputStream that returns bytes out of a static string.

public:
  SimpleInputStream(kj::StringPtr text)
      : unread(text.asBytes()) {}

  kj::Promise<size_t> tryRead(void* buffer, size_t minBytes, size_t maxBytes) override {
    size_t amount = kj::min(maxBytes, unread.size());
    memcpy(buffer, unread.begin(), amount);
    unread = unread.slice(amount, unread.size());
    return amount;
  }

private:
  kj::ArrayPtr<const byte> unread;
};

class PumpResponseService final: public HttpService {
  // HttpService that uses pumpTo() to write a response, without carefully specifying how much to
  // pump, but the stream happens to be the right size.
public:
  kj::Promise<void> request(
      HttpMethod method, kj::StringPtr url, const HttpHeaders& headers,
      kj::AsyncInputStream& requestBody, Response& response) override {
    return requestBody.readAllBytes()
        .then([this,&response](kj::Array<byte>&&) -> kj::Promise<void> {
      HttpHeaders headers(table);
      kj::StringPtr text = "Hello, World!";
      auto body = response.send(200, "OK", headers, text.size());

      auto stream = kj::heap<SimpleInputStream>(text);
      auto promise = stream->pumpTo(*body);
      return promise.attach(kj::mv(body), kj::mv(stream))
          .then([text](uint64_t amount) {
        KJ_EXPECT(amount == text.size());
      });
    });
  }

private:
  kj::Maybe<kj::Exception> exception;
  HttpHeaderTable table;
};

KJ_TEST("HttpFixedLengthEntityWriter correctly implements tryPumpFrom") {
  auto PIPELINE_TESTS = pipelineTestCases();

2529 2530 2531
  kj::EventLoop eventLoop;
  kj::WaitScope waitScope(eventLoop);
  kj::TimerImpl timer(kj::origin<kj::TimePoint>());
2532
  auto pipe = kj::newTwoWayPipe();
2533 2534 2535

  HttpHeaderTable table;
  PumpResponseService service;
2536
  HttpServer server(timer, table, service);
2537 2538 2539 2540 2541

  auto listenTask = server.listenHttp(kj::mv(pipe.ends[0]));

  // Do one request.
  pipe.ends[1]->write(PIPELINE_TESTS[0].request.raw.begin(), PIPELINE_TESTS[0].request.raw.size())
2542
      .wait(waitScope);
2543
  pipe.ends[1]->shutdownWrite();
2544
  auto text = pipe.ends[1]->readAllText().wait(waitScope);
2545 2546 2547 2548 2549 2550 2551 2552

  KJ_EXPECT(text ==
      "HTTP/1.1 200 OK\r\n"
      "Content-Length: 13\r\n"
      "\r\n"
      "Hello, World!", text);
}

2553 2554
// -----------------------------------------------------------------------------

2555 2556 2557
KJ_TEST("newHttpService from HttpClient") {
  auto PIPELINE_TESTS = pipelineTestCases();

2558 2559 2560
  kj::EventLoop eventLoop;
  kj::WaitScope waitScope(eventLoop);
  kj::TimerImpl timer(kj::origin<kj::TimePoint>());
2561 2562
  auto frontPipe = kj::newTwoWayPipe();
  auto backPipe = kj::newTwoWayPipe();
2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577

  kj::Promise<void> writeResponsesPromise = kj::READY_NOW;
  for (auto& testCase: PIPELINE_TESTS) {
    writeResponsesPromise = writeResponsesPromise
        .then([&]() {
      return expectRead(*backPipe.ends[1], testCase.request.raw);
    }).then([&]() {
      return backPipe.ends[1]->write(testCase.response.raw.begin(), testCase.response.raw.size());
    });
  }

  {
    HttpHeaderTable table;
    auto backClient = newHttpClient(table, *backPipe.ends[0]);
    auto frontService = newHttpService(*backClient);
2578
    HttpServer frontServer(timer, table, *frontService);
2579 2580 2581 2582 2583 2584
    auto listenTask = frontServer.listenHttp(kj::mv(frontPipe.ends[1]));

    for (auto& testCase: PIPELINE_TESTS) {
      KJ_CONTEXT(testCase.request.raw, testCase.response.raw);

      frontPipe.ends[0]->write(testCase.request.raw.begin(), testCase.request.raw.size())
2585
               .wait(waitScope);
2586

2587
      expectRead(*frontPipe.ends[0], testCase.response.raw).wait(waitScope);
2588 2589 2590
    }

    frontPipe.ends[0]->shutdownWrite();
2591
    listenTask.wait(waitScope);
2592 2593 2594
  }

  backPipe.ends[0]->shutdownWrite();
2595
  writeResponsesPromise.wait(waitScope);
2596 2597
}

2598
KJ_TEST("newHttpService from HttpClient WebSockets") {
2599 2600 2601
  kj::EventLoop eventLoop;
  kj::WaitScope waitScope(eventLoop);
  kj::TimerImpl timer(kj::origin<kj::TimePoint>());
2602 2603
  auto frontPipe = kj::newTwoWayPipe();
  auto backPipe = kj::newTwoWayPipe();
2604 2605 2606 2607 2608 2609 2610 2611 2612

  auto request = kj::str("GET /websocket", WEBSOCKET_REQUEST_HANDSHAKE);
  auto writeResponsesPromise = expectRead(*backPipe.ends[1], request)
      .then([&]() { return backPipe.ends[1]->write({asBytes(WEBSOCKET_RESPONSE_HANDSHAKE)}); })
      .then([&]() { return backPipe.ends[1]->write({WEBSOCKET_FIRST_MESSAGE_INLINE}); })
      .then([&]() { return expectRead(*backPipe.ends[1], WEBSOCKET_SEND_MESSAGE); })
      .then([&]() { return backPipe.ends[1]->write({WEBSOCKET_REPLY_MESSAGE}); })
      .then([&]() { return expectRead(*backPipe.ends[1], WEBSOCKET_SEND_CLOSE); })
      .then([&]() { return backPipe.ends[1]->write({WEBSOCKET_REPLY_CLOSE}); })
2613 2614 2615 2616 2617 2618 2619
      // expect EOF
      .then([&]() { return backPipe.ends[1]->readAllBytes(); })
      .then([&](kj::ArrayPtr<byte> content) {
        KJ_EXPECT(content.size() == 0);
        // Send EOF.
        backPipe.ends[1]->shutdownWrite();
      })
2620 2621 2622 2623 2624
      .eagerlyEvaluate([](kj::Exception&& e) { KJ_LOG(ERROR, e); });

  {
    HttpHeaderTable table;
    FakeEntropySource entropySource;
2625 2626 2627
    HttpClientSettings clientSettings;
    clientSettings.entropySource = entropySource;
    auto backClient = newHttpClient(table, *backPipe.ends[0], clientSettings);
2628
    auto frontService = newHttpService(*backClient);
2629
    HttpServer frontServer(timer, table, *frontService);
2630 2631
    auto listenTask = frontServer.listenHttp(kj::mv(frontPipe.ends[1]));

2632 2633
    frontPipe.ends[0]->write({request.asBytes()}).wait(waitScope);
    expectRead(*frontPipe.ends[0], WEBSOCKET_RESPONSE_HANDSHAKE).wait(waitScope);
2634

2635 2636 2637 2638 2639
    expectRead(*frontPipe.ends[0], WEBSOCKET_FIRST_MESSAGE_INLINE).wait(waitScope);
    frontPipe.ends[0]->write({WEBSOCKET_SEND_MESSAGE}).wait(waitScope);
    expectRead(*frontPipe.ends[0], WEBSOCKET_REPLY_MESSAGE).wait(waitScope);
    frontPipe.ends[0]->write({WEBSOCKET_SEND_CLOSE}).wait(waitScope);
    expectRead(*frontPipe.ends[0], WEBSOCKET_REPLY_CLOSE).wait(waitScope);
2640 2641

    frontPipe.ends[0]->shutdownWrite();
2642
    listenTask.wait(waitScope);
2643 2644
  }

2645
  writeResponsesPromise.wait(waitScope);
2646 2647 2648
}

KJ_TEST("newHttpService from HttpClient WebSockets disconnect") {
2649 2650 2651
  kj::EventLoop eventLoop;
  kj::WaitScope waitScope(eventLoop);
  kj::TimerImpl timer(kj::origin<kj::TimePoint>());
2652 2653
  auto frontPipe = kj::newTwoWayPipe();
  auto backPipe = kj::newTwoWayPipe();
2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665

  auto request = kj::str("GET /websocket", WEBSOCKET_REQUEST_HANDSHAKE);
  auto writeResponsesPromise = expectRead(*backPipe.ends[1], request)
      .then([&]() { return backPipe.ends[1]->write({asBytes(WEBSOCKET_RESPONSE_HANDSHAKE)}); })
      .then([&]() { return backPipe.ends[1]->write({WEBSOCKET_FIRST_MESSAGE_INLINE}); })
      .then([&]() { return expectRead(*backPipe.ends[1], WEBSOCKET_SEND_MESSAGE); })
      .then([&]() { backPipe.ends[1]->shutdownWrite(); })
      .eagerlyEvaluate([](kj::Exception&& e) { KJ_LOG(ERROR, e); });

  {
    HttpHeaderTable table;
    FakeEntropySource entropySource;
2666 2667 2668
    HttpClientSettings clientSettings;
    clientSettings.entropySource = entropySource;
    auto backClient = newHttpClient(table, *backPipe.ends[0], clientSettings);
2669
    auto frontService = newHttpService(*backClient);
2670
    HttpServer frontServer(timer, table, *frontService);
2671 2672
    auto listenTask = frontServer.listenHttp(kj::mv(frontPipe.ends[1]));

2673 2674
    frontPipe.ends[0]->write({request.asBytes()}).wait(waitScope);
    expectRead(*frontPipe.ends[0], WEBSOCKET_RESPONSE_HANDSHAKE).wait(waitScope);
2675

2676 2677
    expectRead(*frontPipe.ends[0], WEBSOCKET_FIRST_MESSAGE_INLINE).wait(waitScope);
    frontPipe.ends[0]->write({WEBSOCKET_SEND_MESSAGE}).wait(waitScope);
2678

2679
    KJ_EXPECT(frontPipe.ends[0]->readAllText().wait(waitScope) == "");
2680 2681

    frontPipe.ends[0]->shutdownWrite();
2682
    listenTask.wait(waitScope);
2683 2684
  }

2685
  writeResponsesPromise.wait(waitScope);
2686 2687
}

2688 2689
// -----------------------------------------------------------------------------

2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722
KJ_TEST("newHttpClient from HttpService") {
  auto PIPELINE_TESTS = pipelineTestCases();

  kj::EventLoop eventLoop;
  kj::WaitScope waitScope(eventLoop);
  kj::TimerImpl timer(kj::origin<kj::TimePoint>());

  HttpHeaderTable table;
  TestHttpService service(PIPELINE_TESTS, table);
  auto client = newHttpClient(service);

  for (auto& testCase: PIPELINE_TESTS) {
    testHttpClient(waitScope, table, *client, testCase);
  }
}

KJ_TEST("newHttpClient from HttpService WebSockets") {
  kj::EventLoop eventLoop;
  kj::WaitScope waitScope(eventLoop);
  kj::TimerImpl timer(kj::origin<kj::TimePoint>());
  auto pipe = kj::newTwoWayPipe();

  HttpHeaderTable::Builder tableBuilder;
  HttpHeaderId hMyHeader = tableBuilder.add("My-Header");
  auto headerTable = tableBuilder.build();
  TestWebSocketService service(*headerTable, hMyHeader);
  auto client = newHttpClient(service);

  testWebSocketClient(waitScope, *headerTable, hMyHeader, *client);
}

// -----------------------------------------------------------------------------

2723
class CountingIoStream final: public kj::AsyncIoStream {
2724 2725
  // An AsyncIoStream wrapper which decrements a counter when destroyed (allowing us to count how
  // many connections are open).
2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769

public:
  CountingIoStream(kj::Own<kj::AsyncIoStream> inner, uint& count)
      : inner(kj::mv(inner)), count(count) {}
  ~CountingIoStream() noexcept(false) {
    --count;
  }

  kj::Promise<size_t> read(void* buffer, size_t minBytes, size_t maxBytes) override {
    return inner->read(buffer, minBytes, maxBytes);
  }
  kj::Promise<size_t> tryRead(void* buffer, size_t minBytes, size_t maxBytes) override {
    return inner->tryRead(buffer, minBytes, maxBytes);
  }
  kj::Maybe<uint64_t> tryGetLength() override {
    return inner->tryGetLength();;
  }
  kj::Promise<uint64_t> pumpTo(kj::AsyncOutputStream& output, uint64_t amount) override {
    return inner->pumpTo(output, amount);
  }
  kj::Promise<void> write(const void* buffer, size_t size) override {
    return inner->write(buffer, size);
  }
  kj::Promise<void> write(kj::ArrayPtr<const kj::ArrayPtr<const byte>> pieces) override {
    return inner->write(pieces);
  }
  kj::Maybe<kj::Promise<uint64_t>> tryPumpFrom(
      kj::AsyncInputStream& input, uint64_t amount = kj::maxValue) override {
    return inner->tryPumpFrom(input, amount);
  }
  void shutdownWrite() override {
    return inner->shutdownWrite();
  }
  void abortRead() override {
    return inner->abortRead();
  }

public:
  kj::Own<AsyncIoStream> inner;
  uint& count;
};

class CountingNetworkAddress final: public kj::NetworkAddress {
public:
2770 2771
  CountingNetworkAddress(kj::NetworkAddress& inner, uint& count, uint& cumulative)
      : inner(inner), count(count), addrCount(ownAddrCount), cumulative(cumulative) {}
2772
  CountingNetworkAddress(kj::Own<kj::NetworkAddress> inner, uint& count, uint& addrCount)
2773 2774
      : inner(*inner), ownInner(kj::mv(inner)), count(count), addrCount(addrCount),
        cumulative(ownCumulative) {}
2775 2776 2777 2778 2779 2780
  ~CountingNetworkAddress() noexcept(false) {
    --addrCount;
  }

  kj::Promise<kj::Own<kj::AsyncIoStream>> connect() override {
    ++count;
2781
    ++cumulative;
2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797
    return inner.connect()
        .then([this](kj::Own<kj::AsyncIoStream> stream) -> kj::Own<kj::AsyncIoStream> {
      return kj::heap<CountingIoStream>(kj::mv(stream), count);
    });
  }

  kj::Own<kj::ConnectionReceiver> listen() override { KJ_UNIMPLEMENTED("test"); }
  kj::Own<kj::NetworkAddress> clone() override { KJ_UNIMPLEMENTED("test"); }
  kj::String toString() override { KJ_UNIMPLEMENTED("test"); }

private:
  kj::NetworkAddress& inner;
  kj::Own<kj::NetworkAddress> ownInner;
  uint& count;
  uint ownAddrCount = 1;
  uint& addrCount;
2798 2799
  uint ownCumulative = 0;
  uint& cumulative;
2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835
};

class ConnectionCountingNetwork final: public kj::Network {
public:
  ConnectionCountingNetwork(kj::Network& inner, uint& count, uint& addrCount)
      : inner(inner), count(count), addrCount(addrCount) {}

  Promise<Own<NetworkAddress>> parseAddress(StringPtr addr, uint portHint = 0) override {
    ++addrCount;
    return inner.parseAddress(addr, portHint)
        .then([this](Own<NetworkAddress>&& addr) -> Own<NetworkAddress> {
      return kj::heap<CountingNetworkAddress>(kj::mv(addr), count, addrCount);
    });
  }
  Own<NetworkAddress> getSockaddr(const void* sockaddr, uint len) override {
    KJ_UNIMPLEMENTED("test");
  }
  Own<Network> restrictPeers(
      kj::ArrayPtr<const kj::StringPtr> allow,
      kj::ArrayPtr<const kj::StringPtr> deny = nullptr) override {
    KJ_UNIMPLEMENTED("test");
  }

private:
  kj::Network& inner;
  uint& count;
  uint& addrCount;
};

class DummyService final: public HttpService {
public:
  DummyService(HttpHeaderTable& headerTable): headerTable(headerTable) {}

  kj::Promise<void> request(
      HttpMethod method, kj::StringPtr url, const HttpHeaders& headers,
      kj::AsyncInputStream& requestBody, Response& response) override {
2836
    if (!headers.isWebSocket()) {
2837 2838 2839
      if (url == "/throw") {
        return KJ_EXCEPTION(FAILED, "client requested failure");
      }
2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856

      auto body = kj::str(headers.get(HttpHeaderId::HOST).orDefault("null"), ":", url);
      auto stream = response.send(200, "OK", HttpHeaders(headerTable), body.size());
      auto promises = kj::heapArrayBuilder<kj::Promise<void>>(2);
      promises.add(stream->write(body.begin(), body.size()));
      promises.add(requestBody.readAllBytes().ignoreResult());
      return kj::joinPromises(promises.finish()).attach(kj::mv(stream), kj::mv(body));
    } else {
      auto ws = response.acceptWebSocket(HttpHeaders(headerTable));
      auto body = kj::str(headers.get(HttpHeaderId::HOST).orDefault("null"), ":", url);
      auto sendPromise = ws->send(body);

      auto promises = kj::heapArrayBuilder<kj::Promise<void>>(2);
      promises.add(sendPromise.attach(kj::mv(body)));
      promises.add(ws->receive().ignoreResult());
      return kj::joinPromises(promises.finish()).attach(kj::mv(ws));
    }
2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879
  }

private:
  HttpHeaderTable& headerTable;
};

KJ_TEST("HttpClient connection management") {
  auto io = kj::setupAsyncIo();

  kj::TimerImpl serverTimer(kj::origin<kj::TimePoint>());
  kj::TimerImpl clientTimer(kj::origin<kj::TimePoint>());
  HttpHeaderTable headerTable;

  auto listener = io.provider->getNetwork().parseAddress("localhost", 0)
      .wait(io.waitScope)->listen();
  DummyService service(headerTable);
  HttpServerSettings serverSettings;
  HttpServer server(serverTimer, headerTable, service, serverSettings);
  auto listenTask = server.listenHttp(*listener);

  auto addr = io.provider->getNetwork().parseAddress("localhost", listener->getPort())
      .wait(io.waitScope);
  uint count = 0;
2880 2881
  uint cumulative = 0;
  CountingNetworkAddress countingAddr(*addr, count, cumulative);
2882 2883 2884 2885 2886 2887 2888

  FakeEntropySource entropySource;
  HttpClientSettings clientSettings;
  clientSettings.entropySource = entropySource;
  auto client = newHttpClient(clientTimer, headerTable, countingAddr, clientSettings);

  KJ_EXPECT(count == 0);
2889
  KJ_EXPECT(cumulative == 0);
2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907

  uint i = 0;
  auto doRequest = [&]() {
    uint n = i++;
    return client->request(HttpMethod::GET, kj::str("/", n), HttpHeaders(headerTable)).response
        .then([](HttpClient::Response&& response) {
      auto promise = response.body->readAllText();
      return promise.attach(kj::mv(response.body));
    }).then([n](kj::String body) {
      KJ_EXPECT(body == kj::str("null:/", n));
    });
  };

  // We can do several requests in a row and only have one connection.
  doRequest().wait(io.waitScope);
  doRequest().wait(io.waitScope);
  doRequest().wait(io.waitScope);
  KJ_EXPECT(count == 1);
2908
  KJ_EXPECT(cumulative == 1);
2909 2910 2911 2912 2913 2914 2915

  // But if we do two in parallel, we'll end up with two connections.
  auto req1 = doRequest();
  auto req2 = doRequest();
  req1.wait(io.waitScope);
  req2.wait(io.waitScope);
  KJ_EXPECT(count == 2);
2916
  KJ_EXPECT(cumulative == 2);
2917

2918 2919 2920 2921 2922 2923 2924 2925
  // We can reuse after a POST, provided we write the whole POST body properly.
  {
    auto req = client->request(
        HttpMethod::POST, kj::str("/foo"), HttpHeaders(headerTable), size_t(6));
    req.body->write("foobar", 6).wait(io.waitScope);
    req.response.wait(io.waitScope).body->readAllBytes().wait(io.waitScope);
  }
  KJ_EXPECT(count == 2);
2926
  KJ_EXPECT(cumulative == 2);
2927 2928
  doRequest().wait(io.waitScope);
  KJ_EXPECT(count == 2);
2929
  KJ_EXPECT(cumulative == 2);
2930

2931 2932 2933 2934 2935 2936
  // Advance time for half the timeout, then exercise one of the connections.
  clientTimer.advanceTo(clientTimer.now() + clientSettings.idleTimout / 2);
  doRequest().wait(io.waitScope);
  doRequest().wait(io.waitScope);
  io.waitScope.poll();
  KJ_EXPECT(count == 2);
2937
  KJ_EXPECT(cumulative == 2);
2938 2939 2940 2941 2942

  // Advance time past when the other connection should time out. It should be dropped.
  clientTimer.advanceTo(clientTimer.now() + clientSettings.idleTimout * 3 / 4);
  io.waitScope.poll();
  KJ_EXPECT(count == 1);
2943
  KJ_EXPECT(cumulative == 2);
2944 2945 2946 2947 2948

  // Wait for the other to drop.
  clientTimer.advanceTo(clientTimer.now() + clientSettings.idleTimout / 2);
  io.waitScope.poll();
  KJ_EXPECT(count == 0);
2949
  KJ_EXPECT(cumulative == 2);
2950 2951 2952 2953

  // New request creates a new connection again.
  doRequest().wait(io.waitScope);
  KJ_EXPECT(count == 1);
2954
  KJ_EXPECT(cumulative == 3);
2955 2956 2957 2958 2959

  // WebSocket connections are not reused.
  client->openWebSocket(kj::str("/websocket"), HttpHeaders(headerTable))
      .wait(io.waitScope);
  KJ_EXPECT(count == 0);
2960
  KJ_EXPECT(cumulative == 3);
2961 2962 2963 2964

  // Errored connections are not reused.
  doRequest().wait(io.waitScope);
  KJ_EXPECT(count == 1);
2965
  KJ_EXPECT(cumulative == 4);
2966
  client->request(HttpMethod::GET, kj::str("/throw"), HttpHeaders(headerTable)).response
2967 2968
      .wait(io.waitScope).body->readAllBytes().wait(io.waitScope);
  KJ_EXPECT(count == 0);
2969
  KJ_EXPECT(cumulative == 4);
2970 2971 2972 2973

  // Connections where we failed to read the full response body are not reused.
  doRequest().wait(io.waitScope);
  KJ_EXPECT(count == 1);
2974
  KJ_EXPECT(cumulative == 5);
2975
  client->request(HttpMethod::GET, kj::str("/foo"), HttpHeaders(headerTable)).response
2976 2977
      .wait(io.waitScope);
  KJ_EXPECT(count == 0);
2978
  KJ_EXPECT(cumulative == 5);
2979

2980 2981 2982
  // Connections where we didn't even wait for the response headers are not reused.
  doRequest().wait(io.waitScope);
  KJ_EXPECT(count == 1);
2983
  KJ_EXPECT(cumulative == 6);
2984 2985
  client->request(HttpMethod::GET, kj::str("/foo"), HttpHeaders(headerTable));
  KJ_EXPECT(count == 0);
2986
  KJ_EXPECT(cumulative == 6);
2987

2988 2989 2990
  // Connections where we failed to write the full request body are not reused.
  doRequest().wait(io.waitScope);
  KJ_EXPECT(count == 1);
2991
  KJ_EXPECT(cumulative == 7);
2992 2993 2994
  client->request(HttpMethod::POST, kj::str("/foo"), HttpHeaders(headerTable), size_t(6)).response
      .wait(io.waitScope).body->readAllBytes().wait(io.waitScope);
  KJ_EXPECT(count == 0);
2995
  KJ_EXPECT(cumulative == 7);
2996

2997
#if __linux__
2998 2999 3000 3001 3002
  // TODO(someday): Figure out why this doesn't work on Windows and is flakey on Mac. My guess is
  //   that the closing of the TCP connection propagates synchronously on Linux so that by the time
  //   we poll() the EventPort it reports the client end of the connection has reached EOF, whereas
  //   on Mac and Windows this propagation probably involves some concurrent process which may or
  //   may not complete before we poll(). A solution in this case would be to use a dummy in-memory
3003 3004 3005 3006
  //   ConnectionReceiver that returns in-memory pipes (see UnbufferedPipe earlier in this file),
  //   so that we don't rely on any non-local behavior. Another solution would be to pause for
  //   a short time, maybe.

3007 3008 3009
  // If the server times out the connection, we figure it out on the client.
  doRequest().wait(io.waitScope);
  KJ_EXPECT(count == 1);
3010
  KJ_EXPECT(cumulative == 8);
3011 3012 3013
  serverTimer.advanceTo(serverTimer.now() + serverSettings.pipelineTimeout * 2);
  io.waitScope.poll();
  KJ_EXPECT(count == 0);
3014 3015 3016
  KJ_EXPECT(cumulative == 8);
#else
  ++cumulative;  // hack
Kenton Varda's avatar
Kenton Varda committed
3017
#endif
3018 3019 3020 3021

  // Can still make requests.
  doRequest().wait(io.waitScope);
  KJ_EXPECT(count == 1);
3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079
  KJ_EXPECT(cumulative == 9);
}

KJ_TEST("HttpClient disable connection reuse") {
  auto io = kj::setupAsyncIo();

  kj::TimerImpl serverTimer(kj::origin<kj::TimePoint>());
  kj::TimerImpl clientTimer(kj::origin<kj::TimePoint>());
  HttpHeaderTable headerTable;

  auto listener = io.provider->getNetwork().parseAddress("localhost", 0)
      .wait(io.waitScope)->listen();
  DummyService service(headerTable);
  HttpServerSettings serverSettings;
  HttpServer server(serverTimer, headerTable, service, serverSettings);
  auto listenTask = server.listenHttp(*listener);

  auto addr = io.provider->getNetwork().parseAddress("localhost", listener->getPort())
      .wait(io.waitScope);
  uint count = 0;
  uint cumulative = 0;
  CountingNetworkAddress countingAddr(*addr, count, cumulative);

  FakeEntropySource entropySource;
  HttpClientSettings clientSettings;
  clientSettings.entropySource = entropySource;
  clientSettings.idleTimout = 0 * kj::SECONDS;
  auto client = newHttpClient(clientTimer, headerTable, countingAddr, clientSettings);

  KJ_EXPECT(count == 0);
  KJ_EXPECT(cumulative == 0);

  uint i = 0;
  auto doRequest = [&]() {
    uint n = i++;
    return client->request(HttpMethod::GET, kj::str("/", n), HttpHeaders(headerTable)).response
        .then([](HttpClient::Response&& response) {
      auto promise = response.body->readAllText();
      return promise.attach(kj::mv(response.body));
    }).then([n](kj::String body) {
      KJ_EXPECT(body == kj::str("null:/", n));
    });
  };

  // We can do several requests in a row and only have one connection.
  doRequest().wait(io.waitScope);
  doRequest().wait(io.waitScope);
  doRequest().wait(io.waitScope);
  KJ_EXPECT(count == 0);
  KJ_EXPECT(cumulative == 3);

  // But if we do two in parallel, we'll end up with two connections.
  auto req1 = doRequest();
  auto req2 = doRequest();
  req1.wait(io.waitScope);
  req2.wait(io.waitScope);
  KJ_EXPECT(count == 0);
  KJ_EXPECT(cumulative == 5);
3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111
}

KJ_TEST("HttpClient multi host") {
  auto io = kj::setupAsyncIo();

  kj::TimerImpl serverTimer(kj::origin<kj::TimePoint>());
  kj::TimerImpl clientTimer(kj::origin<kj::TimePoint>());
  HttpHeaderTable headerTable;

  auto listener1 = io.provider->getNetwork().parseAddress("localhost", 0)
      .wait(io.waitScope)->listen();
  auto listener2 = io.provider->getNetwork().parseAddress("localhost", 0)
      .wait(io.waitScope)->listen();
  DummyService service(headerTable);
  HttpServer server(serverTimer, headerTable, service);
  auto listenTask1 = server.listenHttp(*listener1);
  auto listenTask2 = server.listenHttp(*listener2);

  uint count = 0, addrCount = 0;
  uint tlsCount = 0, tlsAddrCount = 0;
  ConnectionCountingNetwork countingNetwork(io.provider->getNetwork(), count, addrCount);
  ConnectionCountingNetwork countingTlsNetwork(io.provider->getNetwork(), tlsCount, tlsAddrCount);

  HttpClientSettings clientSettings;
  auto client = newHttpClient(clientTimer, headerTable,
      countingNetwork, countingTlsNetwork, clientSettings);

  KJ_EXPECT(count == 0);

  uint i = 0;
  auto doRequest = [&](bool tls, uint port) {
    uint n = i++;
3112 3113
    // We stick a double-slash in the URL to test that it doesn't get coalesced into one slash,
    // which was a bug in the past.
3114
    return client->request(HttpMethod::GET,
3115
        kj::str((tls ? "https://localhost:" : "http://localhost:"), port, "//", n),
3116 3117 3118 3119 3120
                HttpHeaders(headerTable)).response
        .then([](HttpClient::Response&& response) {
      auto promise = response.body->readAllText();
      return promise.attach(kj::mv(response.body));
    }).then([n, port](kj::String body) {
3121
      KJ_EXPECT(body == kj::str("localhost:", port, "://", n), body, port, n);
3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157
    });
  };

  uint port1 = listener1->getPort();
  uint port2 = listener2->getPort();

  // We can do several requests in a row to the same host and only have one connection.
  doRequest(false, port1).wait(io.waitScope);
  doRequest(false, port1).wait(io.waitScope);
  doRequest(false, port1).wait(io.waitScope);
  KJ_EXPECT(count == 1);
  KJ_EXPECT(tlsCount == 0);
  KJ_EXPECT(addrCount == 1);
  KJ_EXPECT(tlsAddrCount == 0);

  // Request a different host, and now we have two connections.
  doRequest(false, port2).wait(io.waitScope);
  KJ_EXPECT(count == 2);
  KJ_EXPECT(tlsCount == 0);
  KJ_EXPECT(addrCount == 2);
  KJ_EXPECT(tlsAddrCount == 0);

  // Try TLS.
  doRequest(true, port1).wait(io.waitScope);
  KJ_EXPECT(count == 2);
  KJ_EXPECT(tlsCount == 1);
  KJ_EXPECT(addrCount == 2);
  KJ_EXPECT(tlsAddrCount == 1);

  // Try first host again, no change in connection count.
  doRequest(false, port1).wait(io.waitScope);
  KJ_EXPECT(count == 2);
  KJ_EXPECT(tlsCount == 1);
  KJ_EXPECT(addrCount == 2);
  KJ_EXPECT(tlsAddrCount == 1);

3158
  // Multiple requests in parallel forces more connections to that host.
3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169
  auto promise1 = doRequest(false, port1);
  auto promise2 = doRequest(false, port1);
  promise1.wait(io.waitScope);
  promise2.wait(io.waitScope);
  KJ_EXPECT(count == 3);
  KJ_EXPECT(tlsCount == 1);
  KJ_EXPECT(addrCount == 2);
  KJ_EXPECT(tlsAddrCount == 1);

  // Let everything expire.
  clientTimer.advanceTo(clientTimer.now() + clientSettings.idleTimout * 2);
3170
  io.waitScope.poll();
3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185
  KJ_EXPECT(count == 0);
  KJ_EXPECT(tlsCount == 0);
  KJ_EXPECT(addrCount == 0);
  KJ_EXPECT(tlsAddrCount == 0);

  // We can still request those hosts again.
  doRequest(false, port1).wait(io.waitScope);
  KJ_EXPECT(count == 1);
  KJ_EXPECT(tlsCount == 0);
  KJ_EXPECT(addrCount == 1);
  KJ_EXPECT(tlsAddrCount == 0);
}

// -----------------------------------------------------------------------------

3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220
KJ_TEST("HttpClient to capnproto.org") {
  auto io = kj::setupAsyncIo();

  auto maybeConn = io.provider->getNetwork().parseAddress("capnproto.org", 80)
      .then([](kj::Own<kj::NetworkAddress> addr) {
    auto promise = addr->connect();
    return promise.attach(kj::mv(addr));
  }).then([](kj::Own<kj::AsyncIoStream>&& connection) -> kj::Maybe<kj::Own<kj::AsyncIoStream>> {
    return kj::mv(connection);
  }, [](kj::Exception&& e) -> kj::Maybe<kj::Own<kj::AsyncIoStream>> {
    KJ_LOG(WARNING, "skipping test because couldn't connect to capnproto.org");
    return nullptr;
  }).wait(io.waitScope);

  KJ_IF_MAYBE(conn, maybeConn) {
    // Successfully connected to capnproto.org. Try doing GET /. We expect to get a redirect to
    // HTTPS, because what kind of horrible web site would serve in plaintext, really?

    HttpHeaderTable table;
    auto client = newHttpClient(table, **conn);

    HttpHeaders headers(table);
    headers.set(HttpHeaderId::HOST, "capnproto.org");

    auto response = client->request(HttpMethod::GET, "/", headers).response.wait(io.waitScope);
    KJ_EXPECT(response.statusCode / 100 == 3);
    auto location = KJ_ASSERT_NONNULL(response.headers->get(HttpHeaderId::LOCATION));
    KJ_EXPECT(location == "https://capnproto.org/");

    auto body = response.body->readAllText().wait(io.waitScope);
  }
}

}  // namespace
}  // namespace kj