async-io.c++ 72.2 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) 2013-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 24 25 26 27
#if _WIN32
// Request Vista-level APIs.
#define WINVER 0x0600
#define _WIN32_WINNT 0x0600
#endif

28
#include "async-io.h"
29
#include "async-io-internal.h"
30
#include "debug.h"
31
#include "vector.h"
32
#include "io.h"
33
#include "one-of.h"
Harris Hancock's avatar
Harris Hancock committed
34
#include <deque>
35

36 37 38 39 40 41 42 43 44 45
#if _WIN32
#include <winsock2.h>
#include <ws2ipdef.h>
#include <ws2tcpip.h>
#include "windows-sanity.h"
#define inet_pton InetPtonA
#define inet_ntop InetNtopA
#else
#include <sys/socket.h>
#include <arpa/inet.h>
46
#include <netinet/in.h>
47 48 49
#include <sys/un.h>
#endif

50 51 52 53 54
namespace kj {

Promise<void> AsyncInputStream::read(void* buffer, size_t bytes) {
  return read(buffer, bytes, bytes).then([](size_t) {});
}
55

56 57
Promise<size_t> AsyncInputStream::read(void* buffer, size_t minBytes, size_t maxBytes) {
  return tryRead(buffer, minBytes, maxBytes).then([=](size_t result) {
58 59 60 61
    if (result >= minBytes) {
      return result;
    } else {
      kj::throwRecoverableException(KJ_EXCEPTION(DISCONNECTED, "stream disconnected prematurely"));
62 63 64 65 66 67 68
      // Pretend we read zeros from the input.
      memset(reinterpret_cast<byte*>(buffer) + result, 0, minBytes - result);
      return minBytes;
    }
  });
}

69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84
Maybe<uint64_t> AsyncInputStream::tryGetLength() { return nullptr; }

namespace {

class AsyncPump {
public:
  AsyncPump(AsyncInputStream& input, AsyncOutputStream& output, uint64_t limit)
      : input(input), output(output), limit(limit) {}

  Promise<uint64_t> pump() {
    // TODO(perf): This could be more efficient by reading half a buffer at a time and then
    //   starting the next read concurrent with writing the data from the previous read.

    uint64_t n = kj::min(limit - doneSoFar, sizeof(buffer));
    if (n == 0) return doneSoFar;

85
    return input.tryRead(buffer, 1, n)
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
        .then([this](size_t amount) -> Promise<uint64_t> {
      if (amount == 0) return doneSoFar;  // EOF
      doneSoFar += amount;
      return output.write(buffer, amount)
          .then([this]() {
        return pump();
      });
    });
  }

private:
  AsyncInputStream& input;
  AsyncOutputStream& output;
  uint64_t limit;
  uint64_t doneSoFar = 0;
  byte buffer[4096];
};

}  // namespace

Promise<uint64_t> AsyncInputStream::pumpTo(
    AsyncOutputStream& output, uint64_t amount) {
  // See if output wants to dispatch on us.
  KJ_IF_MAYBE(result, output.tryPumpFrom(*this, amount)) {
    return kj::mv(*result);
  }

  // OK, fall back to naive approach.
  auto pump = heap<AsyncPump>(*this, output, amount);
  auto promise = pump->pump();
  return promise.attach(kj::mv(pump));
}

119 120 121 122 123 124
namespace {

class AllReader {
public:
  AllReader(AsyncInputStream& input): input(input) {}

125 126 127
  Promise<Array<byte>> readAllBytes(uint64_t limit) {
    return loop(limit).then([this, limit](uint64_t headroom) {
      auto out = heapArray<byte>(limit - headroom);
128 129 130 131 132
      copyInto(out);
      return out;
    });
  }

133 134 135
  Promise<String> readAllText(uint64_t limit) {
    return loop(limit).then([this, limit](uint64_t headroom) {
      auto out = heapArray<char>(limit - headroom + 1);
136 137 138 139 140 141 142 143 144 145
      copyInto(out.slice(0, out.size() - 1).asBytes());
      out.back() = '\0';
      return String(kj::mv(out));
    });
  }

private:
  AsyncInputStream& input;
  Vector<Array<byte>> parts;

146 147 148 149
  Promise<uint64_t> loop(uint64_t limit) {
    KJ_REQUIRE(limit > 0, "Reached limit before EOF.");

    auto part = heapArray<byte>(kj::min(4096, limit));
150 151 152
    auto partPtr = part.asPtr();
    parts.add(kj::mv(part));
    return input.tryRead(partPtr.begin(), partPtr.size(), partPtr.size())
153 154
        .then([this,KJ_CPCAP(partPtr),limit](size_t amount) mutable -> Promise<uint64_t> {
      limit -= amount;
155
      if (amount < partPtr.size()) {
156
        return limit;
157
      } else {
158
        return loop(limit);
159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174
      }
    });
  }

  void copyInto(ArrayPtr<byte> out) {
    size_t pos = 0;
    for (auto& part: parts) {
      size_t n = kj::min(part.size(), out.size() - pos);
      memcpy(out.begin() + pos, part.begin(), n);
      pos += n;
    }
  }
};

}  // namespace

175
Promise<Array<byte>> AsyncInputStream::readAllBytes(uint64_t limit) {
176
  auto reader = kj::heap<AllReader>(*this);
177
  auto promise = reader->readAllBytes(limit);
178 179 180
  return promise.attach(kj::mv(reader));
}

181
Promise<String> AsyncInputStream::readAllText(uint64_t limit) {
182
  auto reader = kj::heap<AllReader>(*this);
183
  auto promise = reader->readAllText(limit);
184 185 186
  return promise.attach(kj::mv(reader));
}

187 188 189 190 191
Maybe<Promise<uint64_t>> AsyncOutputStream::tryPumpFrom(
    AsyncInputStream& input, uint64_t amount) {
  return nullptr;
}

192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381
namespace {

class AsyncPipe final: public AsyncIoStream, public Refcounted {
public:
  ~AsyncPipe() noexcept(false) {
    KJ_REQUIRE(state == nullptr || ownState.get() != nullptr,
        "destroying AsyncPipe with operation still in-progress; probably going to segfault") {
      // Don't std::terminate().
      break;
    }
  }

  Promise<size_t> tryRead(void* buffer, size_t minBytes, size_t maxBytes) override {
    if (minBytes == 0) {
      return size_t(0);
    } else KJ_IF_MAYBE(s, state) {
      return s->tryRead(buffer, minBytes, maxBytes);
    } else {
      return newAdaptedPromise<size_t, BlockedRead>(
          *this, arrayPtr(reinterpret_cast<byte*>(buffer), maxBytes), minBytes);
    }
  }

  Promise<uint64_t> pumpTo(AsyncOutputStream& output, uint64_t amount) override {
    if (amount == 0) {
      return uint64_t(0);
    } else KJ_IF_MAYBE(s, state) {
      return s->pumpTo(output, amount);
    } else {
      return newAdaptedPromise<uint64_t, BlockedPumpTo>(*this, output, amount);
    }
  }

  void abortRead() override {
    KJ_IF_MAYBE(s, state) {
      s->abortRead();
    } else {
      ownState = kj::heap<AbortedRead>();
      state = *ownState;
    }
  }

  Promise<void> write(const void* buffer, size_t size) override {
    if (size == 0) {
      return READY_NOW;
    } else KJ_IF_MAYBE(s, state) {
      return s->write(buffer, size);
    } else {
      return newAdaptedPromise<void, BlockedWrite>(
          *this, arrayPtr(reinterpret_cast<const byte*>(buffer), size), nullptr);
    }
  }

  Promise<void> write(ArrayPtr<const ArrayPtr<const byte>> pieces) override {
    while (pieces.size() > 0 && pieces[0].size() == 0) {
      pieces = pieces.slice(1, pieces.size());
    }

    if (pieces.size() == 0) {
      return kj::READY_NOW;
    } else KJ_IF_MAYBE(s, state) {
      return s->write(pieces);
    } else {
      return newAdaptedPromise<void, BlockedWrite>(
          *this, pieces[0], pieces.slice(1, pieces.size()));
    }
  }

  Maybe<Promise<uint64_t>> tryPumpFrom(
      AsyncInputStream& input, uint64_t amount) override {
    if (amount == 0) {
      return Promise<uint64_t>(uint64_t(0));
    } else KJ_IF_MAYBE(s, state) {
      return s->tryPumpFrom(input, amount);
    } else {
      return newAdaptedPromise<uint64_t, BlockedPumpFrom>(*this, input, amount);
    }
  }

  void shutdownWrite() override {
    KJ_IF_MAYBE(s, state) {
      s->shutdownWrite();
    } else {
      ownState = kj::heap<ShutdownedWrite>();
      state = *ownState;
    }
  }

private:
  Maybe<AsyncIoStream&> state;
  // Object-oriented state! If any method call is blocked waiting on activity from the other end,
  // then `state` is non-null and method calls should be forwarded to it. If no calls are
  // outstanding, `state` is null.

  kj::Own<AsyncIoStream> ownState;

  void endState(AsyncIoStream& obj) {
    KJ_IF_MAYBE(s, state) {
      if (s == &obj) {
        state = nullptr;
      }
    }
  }

  class BlockedWrite final: public AsyncIoStream {
    // AsyncPipe state when a write() is currently waiting for a corresponding read().

  public:
    BlockedWrite(PromiseFulfiller<void>& fulfiller, AsyncPipe& pipe,
                 ArrayPtr<const byte> writeBuffer,
                 ArrayPtr<const ArrayPtr<const byte>> morePieces)
        : fulfiller(fulfiller), pipe(pipe), writeBuffer(writeBuffer), morePieces(morePieces) {
      KJ_REQUIRE(pipe.state == nullptr);
      pipe.state = *this;
    }

    ~BlockedWrite() noexcept(false) {
      pipe.endState(*this);
    }

    Promise<size_t> tryRead(void* readBufferPtr, size_t minBytes, size_t maxBytes) override {
      KJ_REQUIRE(canceler.isEmpty(), "already pumping");

      auto readBuffer = arrayPtr(reinterpret_cast<byte*>(readBufferPtr), maxBytes);

      size_t totalRead = 0;
      while (readBuffer.size() >= writeBuffer.size()) {
        // The whole current write buffer can be copied into the read buffer.

        {
          auto n = writeBuffer.size();
          memcpy(readBuffer.begin(), writeBuffer.begin(), n);
          totalRead += n;
          readBuffer = readBuffer.slice(n, readBuffer.size());
        }

        if (morePieces.size() == 0) {
          // All done writing.
          fulfiller.fulfill();
          pipe.endState(*this);

          if (totalRead >= minBytes) {
            // Also all done reading.
            return totalRead;
          } else {
            return pipe.tryRead(readBuffer.begin(), minBytes - totalRead, readBuffer.size())
                .then([totalRead](size_t amount) { return amount + totalRead; });
          }
        }

        writeBuffer = morePieces[0];
        morePieces = morePieces.slice(1, morePieces.size());
      }

      // At this point, the read buffer is smaller than the current write buffer, so we can fill
      // it completely.
      {
        auto n = readBuffer.size();
        memcpy(readBuffer.begin(), writeBuffer.begin(), n);
        writeBuffer = writeBuffer.slice(n, writeBuffer.size());
        totalRead += n;
      }

      return totalRead;
    }

    Promise<uint64_t> pumpTo(AsyncOutputStream& output, uint64_t amount) override {
      KJ_REQUIRE(canceler.isEmpty(), "already pumping");

      if (amount < writeBuffer.size()) {
        // Consume a portion of the write buffer.
        return canceler.wrap(output.write(writeBuffer.begin(), amount)
            .then([this,amount]() {
          writeBuffer = writeBuffer.slice(amount, writeBuffer.size());
          // We pumped the full amount, so we're done pumping.
          return amount;
        }));
      }

      // First piece doesn't cover the whole pump. Figure out how many more pieces to add.
      uint64_t actual = writeBuffer.size();
      size_t i = 0;
      while (i < morePieces.size() &&
             amount >= actual + morePieces[i].size()) {
        actual += morePieces[i++].size();
      }

      // Write the first piece.
      auto promise = output.write(writeBuffer.begin(), writeBuffer.size());

Harris Hancock's avatar
Harris Hancock committed
382
      // Write full pieces as a single gather-write.
383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427
      if (i > 0) {
        auto more = morePieces.slice(0, i);
        promise = promise.then([&output,more]() { return output.write(more); });
      }

      if (i == morePieces.size()) {
        // This will complete the write.
        return canceler.wrap(promise.then([this,&output,amount,actual]() -> Promise<uint64_t> {
          canceler.release();
          fulfiller.fulfill();
          pipe.endState(*this);

          if (actual == amount) {
            // Oh, we had exactly enough.
            return actual;
          } else {
            return pipe.pumpTo(output, amount - actual)
                .then([actual](uint64_t actual2) { return actual + actual2; });
          }
        }));
      } else {
        // Pump ends mid-piece. Write the last, partial piece.
        auto n = amount - actual;
        auto splitPiece = morePieces[i];
        KJ_ASSERT(n <= splitPiece.size());
        auto newWriteBuffer = splitPiece.slice(n, splitPiece.size());
        auto newMorePieces = morePieces.slice(i + 1, morePieces.size());
        auto prefix = splitPiece.slice(0, n);
        if (prefix.size() > 0) {
          promise = promise.then([&output,prefix]() {
            return output.write(prefix.begin(), prefix.size());
          });
        }

        return canceler.wrap(promise.then([this,newWriteBuffer,newMorePieces,amount]() {
          writeBuffer = newWriteBuffer;
          morePieces = newMorePieces;
          canceler.release();
          return amount;
        }));
      }
    }

    void abortRead() override {
      canceler.cancel("abortRead() was called");
428
      fulfiller.reject(KJ_EXCEPTION(DISCONNECTED, "read end of pipe was aborted"));
429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489
      pipe.endState(*this);
      pipe.abortRead();
    }

    Promise<void> write(const void* buffer, size_t size) override {
      KJ_FAIL_REQUIRE("can't write() again until previous write() completes");
    }
    Promise<void> write(ArrayPtr<const ArrayPtr<const byte>> pieces) override {
      KJ_FAIL_REQUIRE("can't write() again until previous write() completes");
    }
    Maybe<Promise<uint64_t>> tryPumpFrom(AsyncInputStream& input, uint64_t amount) override {
      KJ_FAIL_REQUIRE("can't tryPumpFrom() again until previous write() completes");
    }
    void shutdownWrite() override {
      KJ_FAIL_REQUIRE("can't shutdownWrite() until previous write() completes");
    }

  private:
    PromiseFulfiller<void>& fulfiller;
    AsyncPipe& pipe;
    ArrayPtr<const byte> writeBuffer;
    ArrayPtr<const ArrayPtr<const byte>> morePieces;
    Canceler canceler;
  };

  class BlockedPumpFrom final: public AsyncIoStream {
    // AsyncPipe state when a tryPumpFrom() is currently waiting for a corresponding read().

  public:
    BlockedPumpFrom(PromiseFulfiller<uint64_t>& fulfiller, AsyncPipe& pipe,
                    AsyncInputStream& input, uint64_t amount)
        : fulfiller(fulfiller), pipe(pipe), input(input), amount(amount) {
      KJ_REQUIRE(pipe.state == nullptr);
      pipe.state = *this;
    }

    ~BlockedPumpFrom() noexcept(false) {
      pipe.endState(*this);
    }

    Promise<size_t> tryRead(void* readBuffer, size_t minBytes, size_t maxBytes) override {
      KJ_REQUIRE(canceler.isEmpty(), "already pumping");

      auto pumpLeft = amount - pumpedSoFar;
      auto min = kj::min(pumpLeft, minBytes);
      auto max = kj::min(pumpLeft, maxBytes);
      return canceler.wrap(input.tryRead(readBuffer, min, max)
          .then([this,readBuffer,minBytes,maxBytes,min](size_t actual) -> kj::Promise<size_t> {
        canceler.release();
        pumpedSoFar += actual;
        KJ_ASSERT(pumpedSoFar <= amount);

        if (pumpedSoFar == amount || actual < min) {
          // Either we pumped all we wanted or we hit EOF.
          fulfiller.fulfill(kj::cp(pumpedSoFar));
          pipe.endState(*this);
        }

        if (actual >= minBytes) {
          return actual;
        } else {
490 491
          return pipe.tryRead(reinterpret_cast<byte*>(readBuffer) + actual,
                              minBytes - actual, maxBytes - actual)
492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527
              .then([actual](size_t actual2) { return actual + actual2; });
        }
      }));
    }

    Promise<uint64_t> pumpTo(AsyncOutputStream& output, uint64_t amount2) override {
      KJ_REQUIRE(canceler.isEmpty(), "already pumping");

      auto n = kj::min(amount2, amount - pumpedSoFar);
      return canceler.wrap(input.pumpTo(output, n)
          .then([this,&output,amount2,n](uint64_t actual) -> Promise<uint64_t> {
        canceler.release();
        pumpedSoFar += actual;
        KJ_ASSERT(pumpedSoFar <= amount);
        if (pumpedSoFar == amount) {
          fulfiller.fulfill(kj::cp(amount));
          pipe.endState(*this);
        }

        KJ_ASSERT(actual <= amount2);
        if (actual == amount2) {
          // Completed entire pumpTo amount.
          return amount2;
        } else if (actual < n) {
          // Received less than requested, presumably because EOF.
          return actual;
        } else {
          // We received all the bytes that were requested but it didn't complete the pump.
          KJ_ASSERT(pumpedSoFar == amount);
          return pipe.pumpTo(output, amount2 - actual);
        }
      }));
    }

    void abortRead() override {
      canceler.cancel("abortRead() was called");
528 529 530 531 532 533 534 535 536 537 538 539 540

      // The input might have reached EOF, but we haven't detected it yet because we haven't tried
      // to read that far. If we had not optimized tryPumpFrom() and instead used the default
      // pumpTo() implementation, then the input would not have called write() again once it
      // reached EOF, and therefore the abortRead() on the other end would *not* propagate an
      // exception! We need the same behavior here. To that end, we need to detect if we're at EOF
      // by reading one last byte.
      checkEofTask = kj::evalNow([&]() {
        static char junk;
        return input.tryRead(&junk, 1, 1).then([this](uint64_t n) {
          if (n == 0) {
            fulfiller.fulfill(kj::cp(pumpedSoFar));
          } else {
541
            fulfiller.reject(KJ_EXCEPTION(DISCONNECTED, "read end of pipe was aborted"));
542 543 544 545 546 547
          }
        }).eagerlyEvaluate([this](kj::Exception&& e) {
          fulfiller.reject(kj::mv(e));
        });
      });

548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571
      pipe.endState(*this);
      pipe.abortRead();
    }

    Promise<void> write(const void* buffer, size_t size) override {
      KJ_FAIL_REQUIRE("can't write() again until previous tryPumpFrom() completes");
    }
    Promise<void> write(ArrayPtr<const ArrayPtr<const byte>> pieces) override {
      KJ_FAIL_REQUIRE("can't write() again until previous tryPumpFrom() completes");
    }
    Maybe<Promise<uint64_t>> tryPumpFrom(AsyncInputStream& input, uint64_t amount) override {
      KJ_FAIL_REQUIRE("can't tryPumpFrom() again until previous tryPumpFrom() completes");
    }
    void shutdownWrite() override {
      KJ_FAIL_REQUIRE("can't shutdownWrite() until previous tryPumpFrom() completes");
    }

  private:
    PromiseFulfiller<uint64_t>& fulfiller;
    AsyncPipe& pipe;
    AsyncInputStream& input;
    uint64_t amount;
    uint64_t pumpedSoFar = 0;
    Canceler canceler;
572
    kj::Promise<void> checkEofTask = nullptr;
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
  };

  class BlockedRead final: public AsyncIoStream {
    // AsyncPipe state when a tryRead() is currently waiting for a corresponding write().

  public:
    BlockedRead(PromiseFulfiller<size_t>& fulfiller, AsyncPipe& pipe,
                ArrayPtr<byte> readBuffer, size_t minBytes)
        : fulfiller(fulfiller), pipe(pipe), readBuffer(readBuffer), minBytes(minBytes) {
      KJ_REQUIRE(pipe.state == nullptr);
      pipe.state = *this;
    }

    ~BlockedRead() noexcept(false) {
      pipe.endState(*this);
    }

    Promise<size_t> tryRead(void* readBuffer, size_t minBytes, size_t maxBytes) override {
      KJ_FAIL_REQUIRE("can't read() again until previous read() completes");
    }
    Promise<uint64_t> pumpTo(AsyncOutputStream& output, uint64_t amount) override {
      KJ_FAIL_REQUIRE("can't read() again until previous read() completes");
    }

    void abortRead() override {
      canceler.cancel("abortRead() was called");
599
      fulfiller.reject(KJ_EXCEPTION(DISCONNECTED, "read end of pipe was aborted"));
600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714
      pipe.endState(*this);
      pipe.abortRead();
    }

    Promise<void> write(const void* writeBuffer, size_t size) override {
      KJ_REQUIRE(canceler.isEmpty(), "already pumping");

      if (size < readBuffer.size()) {
        // Consume a portion of the read buffer.
        memcpy(readBuffer.begin(), writeBuffer, size);
        readSoFar += size;
        readBuffer = readBuffer.slice(size, readBuffer.size());
        if (readSoFar >= minBytes) {
          // We've read enough to close out this read.
          fulfiller.fulfill(kj::cp(readSoFar));
          pipe.endState(*this);
        }
        return READY_NOW;
      } else {
        // Consume entire read buffer.
        auto n = readBuffer.size();
        fulfiller.fulfill(readSoFar + n);
        pipe.endState(*this);
        memcpy(readBuffer.begin(), writeBuffer, n);
        if (n == size) {
          // That's it.
          return READY_NOW;
        } else {
          return pipe.write(reinterpret_cast<const byte*>(writeBuffer) + n, size - n);
        }
      }
    }

    Promise<void> write(ArrayPtr<const ArrayPtr<const byte>> pieces) override {
      KJ_REQUIRE(canceler.isEmpty(), "already pumping");

      while (pieces.size() > 0) {
        if (pieces[0].size() < readBuffer.size()) {
          // Consume a portion of the read buffer.
          auto n = pieces[0].size();
          memcpy(readBuffer.begin(), pieces[0].begin(), n);
          readSoFar += n;
          readBuffer = readBuffer.slice(n, readBuffer.size());
          pieces = pieces.slice(1, pieces.size());
          // loop
        } else {
          // Consume entire read buffer.
          auto n = readBuffer.size();
          fulfiller.fulfill(readSoFar + n);
          pipe.endState(*this);
          memcpy(readBuffer.begin(), pieces[0].begin(), n);

          auto restOfPiece = pieces[0].slice(n, pieces[0].size());
          pieces = pieces.slice(1, pieces.size());
          if (restOfPiece.size() == 0) {
            // We exactly finished the current piece, so just issue a write for the remaining
            // pieces.
            if (pieces.size() == 0) {
              // Nothing left.
              return READY_NOW;
            } else {
              // Write remaining pieces.
              return pipe.write(pieces);
            }
          } else {
            // Unfortunately we have to execute a separate write() for the remaining part of this
            // piece, because we can't modify the pieces array.
            auto promise = pipe.write(restOfPiece.begin(), restOfPiece.size());
            if (pieces.size() > 0) {
              // No more pieces so that's it.
              return kj::mv(promise);
            } else {
              // Also need to write the remaining pieces.
              auto& pipeRef = pipe;
              return promise.then([pieces,&pipeRef]() {
                return pipeRef.write(pieces);
              });
            }
          }
        }
      }

      // Consumed all written pieces.
      if (readSoFar >= minBytes) {
        // We've read enough to close out this read.
        fulfiller.fulfill(kj::cp(readSoFar));
        pipe.endState(*this);
      }

      return READY_NOW;
    }

    Maybe<Promise<uint64_t>> tryPumpFrom(AsyncInputStream& input, uint64_t amount) override {
      KJ_REQUIRE(canceler.isEmpty(), "already pumping");

      KJ_ASSERT(minBytes > readSoFar);
      auto minToRead = kj::min(amount, minBytes - readSoFar);
      auto maxToRead = kj::min(amount, readBuffer.size());

      return canceler.wrap(input.tryRead(readBuffer.begin(), minToRead, maxToRead)
          .then([this,&input,amount,minToRead](size_t actual) -> Promise<uint64_t> {
        readBuffer = readBuffer.slice(actual, readBuffer.size());
        readSoFar += actual;

        if (readSoFar >= minBytes || actual < minToRead) {
          // We've read enough to close out this read (readSoFar >= minBytes)
          // OR we reached EOF and couldn't complete the read (actual < minToRead)
          // Either way, we want to close out this read.
          canceler.release();
          fulfiller.fulfill(kj::cp(readSoFar));
          pipe.endState(*this);

          if (actual < amount) {
            // We din't complete pumping. Restart from the pipe.
            return input.pumpTo(pipe, amount - actual)
715
                .then([actual](uint64_t actual2) -> uint64_t { return actual + actual2; });
716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748
          }
        }

        // If we read less than `actual`, but more than `minToRead`, it can only have been
        // because we reached `minBytes`, so the conditional above would have executed. So, here
        // we know that actual == amount.
        KJ_ASSERT(actual == amount);

        // We pumped the full amount, so we're done pumping.
        return amount;
      }));
    }

    void shutdownWrite() override {
      canceler.cancel("shutdownWrite() was called");
      fulfiller.fulfill(kj::cp(readSoFar));
      pipe.endState(*this);
      pipe.shutdownWrite();
    }

  private:
    PromiseFulfiller<size_t>& fulfiller;
    AsyncPipe& pipe;
    ArrayPtr<byte> readBuffer;
    size_t minBytes;
    size_t readSoFar = 0;
    Canceler canceler;
  };

  class BlockedPumpTo final: public AsyncIoStream {
    // AsyncPipe state when a pumpTo() is currently waiting for a corresponding write().

  public:
749
    BlockedPumpTo(PromiseFulfiller<uint64_t>& fulfiller, AsyncPipe& pipe,
750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768
                  AsyncOutputStream& output, uint64_t amount)
        : fulfiller(fulfiller), pipe(pipe), output(output), amount(amount) {
      KJ_REQUIRE(pipe.state == nullptr);
      pipe.state = *this;
    }

    ~BlockedPumpTo() noexcept(false) {
      pipe.endState(*this);
    }

    Promise<size_t> tryRead(void* readBuffer, size_t minBytes, size_t maxBytes) override {
      KJ_FAIL_REQUIRE("can't read() again until previous pumpTo() completes");
    }
    Promise<uint64_t> pumpTo(AsyncOutputStream& output, uint64_t amount) override {
      KJ_FAIL_REQUIRE("can't read() again until previous pumpTo() completes");
    }

    void abortRead() override {
      canceler.cancel("abortRead() was called");
769
      fulfiller.reject(KJ_EXCEPTION(DISCONNECTED, "read end of pipe was aborted"));
770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835
      pipe.endState(*this);
      pipe.abortRead();
    }

    Promise<void> write(const void* writeBuffer, size_t size) override {
      KJ_REQUIRE(canceler.isEmpty(), "already pumping");

      auto actual = kj::min(amount - pumpedSoFar, size);
      return canceler.wrap(output.write(writeBuffer, actual)
          .then([this,size,actual,writeBuffer]() -> kj::Promise<void> {
        canceler.release();
        pumpedSoFar += actual;

        KJ_ASSERT(pumpedSoFar <= amount);
        KJ_ASSERT(actual <= size);

        if (pumpedSoFar == amount) {
          // Done with pump.
          fulfiller.fulfill(kj::cp(pumpedSoFar));
          pipe.endState(*this);
        }

        if (actual == size) {
          return kj::READY_NOW;
        } else {
          KJ_ASSERT(pumpedSoFar == amount);
          return pipe.write(reinterpret_cast<const byte*>(writeBuffer) + actual, size - actual);
        }
      }));
    }

    Promise<void> write(ArrayPtr<const ArrayPtr<const byte>> pieces) override {
      KJ_REQUIRE(canceler.isEmpty(), "already pumping");

      size_t size = 0;
      size_t needed = amount - pumpedSoFar;
      for (auto i: kj::indices(pieces)) {
        if (pieces[i].size() > needed) {
          // The pump ends in the middle of this write.

          auto promise = output.write(pieces.slice(0, i));

          if (needed > 0) {
            // The pump includes part of this piece, but not all. Unfortunately we need to split
            // writes.
            auto partial = pieces[i].slice(0, needed);
            promise = promise.then([this,partial]() {
              return output.write(partial.begin(), partial.size());
            });
            auto partial2 = pieces[i].slice(needed, pieces[i].size());
            promise = canceler.wrap(promise.then([this,partial2]() {
              canceler.release();
              fulfiller.fulfill(kj::cp(amount));
              pipe.endState(*this);
              return pipe.write(partial2.begin(), partial2.size());
            }));
            ++i;
          } else {
            // The pump ends exactly at the end of a piece, how nice.
            promise = canceler.wrap(promise.then([this]() {
              canceler.release();
              fulfiller.fulfill(kj::cp(amount));
              pipe.endState(*this);
            }));
          }

836
          auto remainder = pieces.slice(i, pieces.size());
837 838 839 840 841 842 843 844 845 846 847 848 849 850 851
          if (remainder.size() > 0) {
            auto& pipeRef = pipe;
            promise = promise.then([&pipeRef,remainder]() {
              return pipeRef.write(remainder);
            });
          }

          return promise;
        } else {
          size += pieces[i].size();
          needed -= pieces[i].size();
        }
      }

      // Turns out we can forward this whole write.
852
      KJ_ASSERT(size <= amount - pumpedSoFar);
853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904
      return canceler.wrap(output.write(pieces).then([this,size]() {
        pumpedSoFar += size;
        KJ_ASSERT(pumpedSoFar <= amount);
        if (pumpedSoFar == amount) {
          // Done pumping.
          canceler.release();
          fulfiller.fulfill(kj::cp(amount));
          pipe.endState(*this);
        }
      }));
    }

    Maybe<Promise<uint64_t>> tryPumpFrom(AsyncInputStream& input, uint64_t amount2) override {
      KJ_REQUIRE(canceler.isEmpty(), "already pumping");

      auto n = kj::min(amount2, amount - pumpedSoFar);
      return output.tryPumpFrom(input, n)
          .map([&](Promise<uint64_t> subPump) {
        return canceler.wrap(subPump
            .then([this,&input,amount2,n](uint64_t actual) -> Promise<uint64_t> {
          canceler.release();
          pumpedSoFar += actual;
          KJ_ASSERT(pumpedSoFar <= amount);
          if (pumpedSoFar == amount) {
            fulfiller.fulfill(kj::cp(amount));
            pipe.endState(*this);
          }

          KJ_ASSERT(actual <= amount2);
          if (actual == amount2) {
            // Completed entire tryPumpFrom amount.
            return amount2;
          } else if (actual < n) {
            // Received less than requested, presumably because EOF.
            return actual;
          } else {
            // We received all the bytes that were requested but it didn't complete the pump.
            KJ_ASSERT(pumpedSoFar == amount);
            return input.pumpTo(pipe, amount2 - actual);
          }
        }));
      });
    }

    void shutdownWrite() override {
      canceler.cancel("shutdownWrite() was called");
      fulfiller.fulfill(kj::cp(pumpedSoFar));
      pipe.endState(*this);
      pipe.shutdownWrite();
    }

  private:
905
    PromiseFulfiller<uint64_t>& fulfiller;
906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974
    AsyncPipe& pipe;
    AsyncOutputStream& output;
    uint64_t amount;
    size_t pumpedSoFar = 0;
    Canceler canceler;
  };

  class AbortedRead final: public AsyncIoStream {
    // AsyncPipe state when abortRead() has been called.

  public:
    Promise<size_t> tryRead(void* readBufferPtr, size_t minBytes, size_t maxBytes) override {
      KJ_FAIL_REQUIRE("abortRead() has been called");
    }
    Promise<uint64_t> pumpTo(AsyncOutputStream& output, uint64_t amount) override {
      KJ_FAIL_REQUIRE("abortRead() has been called");
    }
    void abortRead() override {
      // ignore repeated abort
    }

    Promise<void> write(const void* buffer, size_t size) override {
      KJ_FAIL_REQUIRE("abortRead() has been called");
    }
    Promise<void> write(ArrayPtr<const ArrayPtr<const byte>> pieces) override {
      KJ_FAIL_REQUIRE("abortRead() has been called");
    }
    Maybe<Promise<uint64_t>> tryPumpFrom(AsyncInputStream& input, uint64_t amount) override {
      KJ_FAIL_REQUIRE("abortRead() has been called");
    }
    void shutdownWrite() override {
      // ignore -- currently shutdownWrite() actually means that the PipeWriteEnd was dropped,
      // which is not an error even if reads have been aborted.
    }
  };

  class ShutdownedWrite final: public AsyncIoStream {
    // AsyncPipe state when shutdownWrite() has been called.

  public:
    Promise<size_t> tryRead(void* readBufferPtr, size_t minBytes, size_t maxBytes) override {
      return size_t(0);
    }
    Promise<uint64_t> pumpTo(AsyncOutputStream& output, uint64_t amount) override {
      return uint64_t(0);
    }
    void abortRead() override {
      // ignore
    }

    Promise<void> write(const void* buffer, size_t size) override {
      KJ_FAIL_REQUIRE("shutdownWrite() has been called");
    }
    Promise<void> write(ArrayPtr<const ArrayPtr<const byte>> pieces) override {
      KJ_FAIL_REQUIRE("shutdownWrite() has been called");
    }
    Maybe<Promise<uint64_t>> tryPumpFrom(AsyncInputStream& input, uint64_t amount) override {
      KJ_FAIL_REQUIRE("shutdownWrite() has been called");
    }
    void shutdownWrite() override {
      // ignore -- currently shutdownWrite() actually means that the PipeWriteEnd was dropped,
      // so it will only be called once anyhow.
    }
  };
};

class PipeReadEnd final: public AsyncInputStream {
public:
  PipeReadEnd(kj::Own<AsyncPipe> pipe): pipe(kj::mv(pipe)) {}
975
  ~PipeReadEnd() noexcept(false) {
976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996
    unwind.catchExceptionsIfUnwinding([&]() {
      pipe->abortRead();
    });
  }

  Promise<size_t> tryRead(void* buffer, size_t minBytes, size_t maxBytes) override {
    return pipe->tryRead(buffer, minBytes, maxBytes);
  }

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

private:
  Own<AsyncPipe> pipe;
  UnwindDetector unwind;
};

class PipeWriteEnd final: public AsyncOutputStream {
public:
  PipeWriteEnd(kj::Own<AsyncPipe> pipe): pipe(kj::mv(pipe)) {}
997
  ~PipeWriteEnd() noexcept(false) {
998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024
    unwind.catchExceptionsIfUnwinding([&]() {
      pipe->shutdownWrite();
    });
  }

  Promise<void> write(const void* buffer, size_t size) override {
    return pipe->write(buffer, size);
  }

  Promise<void> write(ArrayPtr<const ArrayPtr<const byte>> pieces) override {
    return pipe->write(pieces);
  }

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

private:
  Own<AsyncPipe> pipe;
  UnwindDetector unwind;
};

class TwoWayPipeEnd final: public AsyncIoStream {
public:
  TwoWayPipeEnd(kj::Own<AsyncPipe> in, kj::Own<AsyncPipe> out)
      : in(kj::mv(in)), out(kj::mv(out)) {}
1025
  ~TwoWayPipeEnd() noexcept(false) {
1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085
    unwind.catchExceptionsIfUnwinding([&]() {
      out->shutdownWrite();
      in->abortRead();
    });
  }

  Promise<size_t> tryRead(void* buffer, size_t minBytes, size_t maxBytes) override {
    return in->tryRead(buffer, minBytes, maxBytes);
  }
  Promise<uint64_t> pumpTo(AsyncOutputStream& output, uint64_t amount) override {
    return in->pumpTo(output, amount);
  }
  void abortRead() override {
    in->abortRead();
  }

  Promise<void> write(const void* buffer, size_t size) override {
    return out->write(buffer, size);
  }
  Promise<void> write(ArrayPtr<const ArrayPtr<const byte>> pieces) override {
    return out->write(pieces);
  }
  Maybe<Promise<uint64_t>> tryPumpFrom(
      AsyncInputStream& input, uint64_t amount) override {
    return out->tryPumpFrom(input, amount);
  }
  void shutdownWrite() override {
    out->shutdownWrite();
  }

private:
  kj::Own<AsyncPipe> in;
  kj::Own<AsyncPipe> out;
  UnwindDetector unwind;
};

class LimitedInputStream final: public AsyncInputStream {
public:
  LimitedInputStream(kj::Own<AsyncInputStream> inner, uint64_t limit)
      : inner(kj::mv(inner)), limit(limit) {
    if (limit == 0) {
      inner = nullptr;
    }
  }

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

  Promise<size_t> tryRead(void* buffer, size_t minBytes, size_t maxBytes) override {
    if (limit == 0) return size_t(0);
    return inner->tryRead(buffer, kj::min(minBytes, limit), kj::min(maxBytes, limit))
        .then([this,minBytes](size_t actual) {
      decreaseLimit(actual, minBytes);
      return actual;
    });
  }

  Promise<uint64_t> pumpTo(AsyncOutputStream& output, uint64_t amount) override {
    if (limit == 0) return uint64_t(0);
1086 1087 1088 1089
    auto requested = kj::min(amount, limit);
    return inner->pumpTo(output, requested)
        .then([this,requested](uint64_t actual) {
      decreaseLimit(actual, requested);
1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128
      return actual;
    });
  }

private:
  Own<AsyncInputStream> inner;
  uint64_t limit;

  void decreaseLimit(uint64_t amount, uint64_t requested) {
    KJ_ASSERT(limit >= amount);
    limit -= amount;
    if (limit == 0) {
      inner = nullptr;
    } else if (amount < requested) {
      KJ_FAIL_REQUIRE("pipe ended prematurely");
    }
  }
};

}  // namespace

OneWayPipe newOneWayPipe(kj::Maybe<uint64_t> expectedLength) {
  auto impl = kj::refcounted<AsyncPipe>();
  Own<AsyncInputStream> readEnd = kj::heap<PipeReadEnd>(kj::addRef(*impl));
  KJ_IF_MAYBE(l, expectedLength) {
    readEnd = kj::heap<LimitedInputStream>(kj::mv(readEnd), *l);
  }
  Own<AsyncOutputStream> writeEnd = kj::heap<PipeWriteEnd>(kj::mv(impl));
  return { kj::mv(readEnd), kj::mv(writeEnd) };
}

TwoWayPipe newTwoWayPipe() {
  auto pipe1 = kj::refcounted<AsyncPipe>();
  auto pipe2 = kj::refcounted<AsyncPipe>();
  auto end1 = kj::heap<TwoWayPipeEnd>(kj::addRef(*pipe1), kj::addRef(*pipe2));
  auto end2 = kj::heap<TwoWayPipeEnd>(kj::mv(pipe2), kj::mv(pipe1));
  return { { kj::mv(end1), kj::mv(end2) } };
}

Harris Hancock's avatar
Harris Hancock committed
1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 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 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 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 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751
namespace {

class AsyncTee final: public Refcounted {
public:
  using BranchId = uint;

  explicit AsyncTee(Own<AsyncInputStream> inner, uint64_t bufferSizeLimit)
      : inner(mv(inner)), bufferSizeLimit(bufferSizeLimit), length(this->inner->tryGetLength()) {}
  ~AsyncTee() noexcept(false) {
    bool hasBranches = false;
    for (auto& branch: branches) {
      hasBranches = hasBranches || branch != nullptr;
    }
    KJ_ASSERT(!hasBranches, "destroying AsyncTee with branch still alive") {
      // Don't std::terminate().
      break;
    }
  }

  void addBranch(BranchId branch) {
    KJ_REQUIRE(branches[branch] == nullptr, "branch already exists");
    branches[branch] = Branch();
  }

  void removeBranch(BranchId branch) {
    auto& state = KJ_REQUIRE_NONNULL(branches[branch], "branch was already destroyed");
    KJ_REQUIRE(state.sink == nullptr,
        "destroying tee branch with operation still in-progress; probably going to segfault") {
      // Don't std::terminate().
      break;
    }

    branches[branch] = nullptr;
  }

  Promise<size_t> tryRead(BranchId branch, void* buffer, size_t minBytes, size_t maxBytes)  {
    auto& state = KJ_ASSERT_NONNULL(branches[branch]);
    KJ_ASSERT(state.sink == nullptr);

    // If there is excess data in the buffer for us, slurp that up.
    auto readBuffer = arrayPtr(reinterpret_cast<byte*>(buffer), maxBytes);
    auto readSoFar = state.buffer.consume(readBuffer, minBytes);

    if (minBytes == 0) {
      return readSoFar;
    }

    if (state.buffer.empty()) {
      KJ_IF_MAYBE(reason, stoppage) {
        // Prefer a short read to an exception. The exception prevents the pull loop from adding any
        // data to the buffer, so `readSoFar` will be zero the next time someone calls `tryRead()`,
        // and the caller will see the exception.
        if (reason->is<Eof>() || readSoFar > 0) {
          return readSoFar;
        }
        return cp(reason->get<Exception>());
      }
    }

    auto promise = newAdaptedPromise<size_t, ReadSink>(state.sink, readBuffer, minBytes, readSoFar);
    ensurePulling();
    return mv(promise);
  }

  Maybe<uint64_t> tryGetLength(BranchId branch)  {
    auto& state = KJ_ASSERT_NONNULL(branches[branch]);

    return length.map([&state](uint64_t amount) {
      return amount + state.buffer.size();
    });
  }

  Promise<uint64_t> pumpTo(BranchId branch, AsyncOutputStream& output, uint64_t amount)  {
    auto& state = KJ_ASSERT_NONNULL(branches[branch]);
    KJ_ASSERT(state.sink == nullptr);

    if (amount == 0) {
      return amount;
    }

    if (state.buffer.empty()) {
      KJ_IF_MAYBE(reason, stoppage) {
        if (reason->is<Eof>()) {
          return uint64_t(0);
        }
        return cp(reason->get<Exception>());
      }
    }

    auto promise = newAdaptedPromise<uint64_t, PumpSink>(state.sink, output, amount);
    ensurePulling();
    return mv(promise);
  }

private:
  struct Eof {};
  using Stoppage = OneOf<Eof, Exception>;

  class Buffer {
  public:
    uint64_t consume(ArrayPtr<byte>& readBuffer, size_t& minBytes);
    // Consume as many bytes as possible, copying them into `readBuffer`. Return the number of bytes
    // consumed.
    //
    // `readBuffer` and `minBytes` are both assigned appropriate new values, such that after any
    // call to `consume()`, `readBuffer` will point to the remaining slice of unwritten space, and
    // `minBytes` will have been decremented (clamped to zero) by the amount of bytes read. That is,
    // the read can be considered fulfilled if `minBytes` is zero after a call to `consume()`.

    Array<const ArrayPtr<const byte>> asArray(uint64_t minBytes, uint64_t& amount);
    // Consume the first `minBytes` of the buffer (or the entire buffer) and return it in an Array
    // of ArrayPtr<const byte>s, suitable for passing to AsyncOutputStream.write(). The outer Array
    // owns the underlying data.

    void produce(Array<byte> bytes);
    // Enqueue a byte array to the end of the buffer list.

    bool empty() const;
    uint64_t size() const;

  private:
    std::deque<Array<byte>> bufferList;
  };

  class Sink {
  public:
    struct Need {
      // We use uint64_t here because:
      // - pumpTo() accepts it as the `amount` parameter.
      // - all practical values of tryRead()'s `maxBytes` parameter (a size_t) should also fit into
      //   a uint64_t, unless we're on a machine with multiple exabytes of memory ...

      uint64_t minBytes = 0;

      uint64_t maxBytes = kj::maxValue;
    };

    virtual Promise<void> fill(Buffer& inBuffer, const Maybe<Stoppage>& stoppage) = 0;
    // Attempt to fill the sink with bytes andreturn a promise which must resolve before any inner
    // read may be attempted. If a sink requires backpressure to be respected, this is how it should
    // be communicated.
    //
    // If the sink is full, it must detach from the tee before the returned promise is resolved.
    //
    // The returned promise must not result in an exception.

    virtual Need need() = 0;

    virtual void reject(Exception&& exception) = 0;
    // Inform this sink of a catastrophic exception and detach it. Regular read exceptions should be
    // propagated through `fill()`'s stoppage parameter instead.
  };

  template <typename T>
  class SinkBase: public Sink {
    // Registers itself with the tee as a sink on construction, detaches from the tee on
    // fulfillment, rejection, or destruction.
    //
    // A bit of a Frankenstein, avert your eyes. For one thing, it's more of a mixin than a base...

  public:
    explicit SinkBase(PromiseFulfiller<T>& fulfiller, Maybe<Sink&>& sinkLink)
        : fulfiller(fulfiller), sinkLink(sinkLink) {
      KJ_ASSERT(sinkLink == nullptr, "sink initiated with sink already in flight");
      sinkLink = *this;
    }
    KJ_DISALLOW_COPY(SinkBase);
    ~SinkBase() noexcept(false) { detach(); }

    void reject(Exception&& exception) override {
      // The tee is allowed to reject this sink if it needs to, e.g. to propagate a non-inner read
      // exception from the pull loop. Only the derived class is allowed to fulfill() directly,
      // though -- the tee must keep calling fill().

      fulfiller.reject(mv(exception));
      detach();
    }

  protected:
    template <typename U>
    void fulfill(U value) {
      fulfiller.fulfill(fwd<U>(value));
      detach();
    }

  private:
    void detach() {
      KJ_IF_MAYBE(sink, sinkLink) {
        if (sink == this) {
          sinkLink = nullptr;
        }
      }
    }

    PromiseFulfiller<T>& fulfiller;
    Maybe<Sink&>& sinkLink;
  };

  struct Branch {
    Buffer buffer;
    Maybe<Sink&> sink;
  };

  class ReadSink final: public SinkBase<size_t> {
  public:
    explicit ReadSink(PromiseFulfiller<size_t>& fulfiller, Maybe<Sink&>& registration,
                      ArrayPtr<byte> buffer, size_t minBytes, size_t readSoFar)
        : SinkBase(fulfiller, registration), buffer(buffer),
          minBytes(minBytes), readSoFar(readSoFar) {}

    Promise<void> fill(Buffer& inBuffer, const Maybe<Stoppage>& stoppage) override {
      auto amount = inBuffer.consume(buffer, minBytes);
      readSoFar += amount;

      if (minBytes == 0) {
        // We satisfied the read request.
        fulfill(readSoFar);
        return READY_NOW;
      }

      if (amount == 0 && inBuffer.empty()) {
        // We made no progress on the read request and the buffer is tapped out.
        KJ_IF_MAYBE(reason, stoppage) {
          if (reason->is<Eof>() || readSoFar > 0) {
            // Prefer short read to exception.
            fulfill(readSoFar);
          } else {
            reject(cp(reason->get<Exception>()));
          }
          return READY_NOW;
        }
      }

      return READY_NOW;
    }

    Need need() override { return Need { minBytes, buffer.size() }; }

  private:
    ArrayPtr<byte> buffer;
    size_t minBytes;
    // Arguments to the outer tryRead() call, sliced/decremented after every buffer consumption.

    size_t readSoFar;
    // End result of the outer tryRead().
  };

  class PumpSink final: public SinkBase<uint64_t> {
  public:
    explicit PumpSink(PromiseFulfiller<uint64_t>& fulfiller, Maybe<Sink&>& registration,
                      AsyncOutputStream& output, uint64_t limit)
        : SinkBase(fulfiller, registration), output(output), limit(limit) {}

    ~PumpSink() noexcept(false) {
      canceler.cancel("This pump has been canceled.");
    }

    Promise<void> fill(Buffer& inBuffer, const Maybe<Stoppage>& stoppage) override {
      KJ_ASSERT(limit > 0);

      uint64_t amount = 0;

      // TODO(someday): This consumes data from the buffer, but we cannot know if the stream to
      //   which we're pumping will accept it until after the write() promise completes. If the
      //   write() promise rejects, we lose this data. We should consume the data from the buffer
      //   only after successful writes.
      auto writeBuffer = inBuffer.asArray(limit, amount);
      KJ_ASSERT(limit >= amount);
      if (amount > 0) {
        Promise<void> promise = nullptr;

        try {
          promise = canceler.wrap(output.write(writeBuffer).attach(mv(writeBuffer)));
        } catch (const Exception& exception) {
          reject(cp(exception));
          return READY_NOW;
        }

        promise = promise.then([this, amount]() {
          limit -= amount;
          pumpedSoFar += amount;
          if (limit == 0) {
            fulfill(pumpedSoFar);
          }
        }).eagerlyEvaluate([this](Exception&& exception) {
          reject(mv(exception));
        });

        return mv(promise);
      } else KJ_IF_MAYBE(reason, stoppage) {
        if (reason->is<Eof>()) {
          // Unlike in the read case, it makes more sense to immediately propagate exceptions to the
          // pump promise rather than show it a "short pump".
          fulfill(pumpedSoFar);
        } else {
          reject(cp(reason->get<Exception>()));
        }
      }

      return READY_NOW;
    }

    Need need() override { return Need { 1, limit }; }

  private:
    AsyncOutputStream& output;
    uint64_t limit;
    // Arguments to the outer pumpTo() call, decremented after every buffer consumption.
    //
    // Equal to zero once fulfiller has been fulfilled/rejected.

    uint64_t pumpedSoFar = 0;
    // End result of the outer pumpTo().

    Canceler canceler;
    // When the pump is canceled, we also need to cancel any write operations in flight.
  };

  // =====================================================================================

  Maybe<Sink::Need> analyzeSinks() {
    // Return nullptr if there are no sinks at all. Otherwise, return the largest `minBytes` and the
    // smallest `maxBytes` requested by any sink. The pull loop will use these values to calculate
    // the optimal buffer size for the next inner read, so that a minimum amount of data is buffered
    // at any given time.

    uint64_t minBytes = 0;
    uint64_t maxBytes = kj::maxValue;

    uint nBranches = 0;
    uint nSinks = 0;

    for (auto& state: branches) {
      KJ_IF_MAYBE(s, state) {
        ++nBranches;
        KJ_IF_MAYBE(sink, s->sink) {
          ++nSinks;
          auto need = sink->need();
          minBytes = kj::max(minBytes, need.minBytes);
          maxBytes = kj::min(maxBytes, need.maxBytes);
        }
      }
    }

    if (nSinks > 0) {
      KJ_ASSERT(minBytes > 0);
      KJ_ASSERT(maxBytes > 0, "sink was filled but did not detach");

      // Sinks may report non-overlapping needs.
      maxBytes = kj::max(minBytes, maxBytes);

      return Sink::Need { minBytes, maxBytes };
    }

    // No active sinks.
    return nullptr;
  }

  void ensurePulling() {
    if (!pulling) {
      pulling = true;
      UnwindDetector unwind;
      KJ_DEFER(if (unwind.isUnwinding()) pulling = false);
      pullPromise = pull();
    }
  }

  Promise<void> pull() {
    // Use evalLater() so that two pump sinks added on the same turn of the event loop will not
    // cause buffering.
    return evalLater([this] {
      // Attempt to fill any sinks that exist.

      Vector<Promise<void>> promises;

      for (auto& state: branches) {
        KJ_IF_MAYBE(s, state) {
          KJ_IF_MAYBE(sink, s->sink) {
            promises.add(sink->fill(s->buffer, stoppage));
          }
        }
      }

      // Respect the greatest of the sinks' backpressures.
      return joinPromises(promises.releaseAsArray());
    }).then([this]() -> Promise<void> {
      // Check to see whether we need to perform an inner read.

      auto need = analyzeSinks();

      if (need == nullptr) {
        // No more sinks, stop pulling.
        pulling = false;
        return READY_NOW;
      }

      if (stoppage != nullptr) {
        // We're eof or errored, don't read, but loop so we can fill the sink(s).
        return pull();
      }

      auto& n = KJ_ASSERT_NONNULL(need);

      KJ_ASSERT(n.minBytes > 0);

      // We must perform an inner read.

      // We'd prefer not to explode our buffer, if that's cool. We cap `maxBytes` to the buffer size
      // limit or our builtin MAX_BLOCK_SIZE, whichever is smaller. But, we make sure `maxBytes` is
      // still >= `minBytes`.
      n.maxBytes = kj::min(n.maxBytes, MAX_BLOCK_SIZE);
      n.maxBytes = kj::min(n.maxBytes, bufferSizeLimit);
      n.maxBytes = kj::max(n.minBytes, n.maxBytes);
      for (auto& state: branches) {
        KJ_IF_MAYBE(s, state) {
          // TODO(perf): buffer.size() is O(n) where n = # of individual heap-allocated byte arrays.
          if (s->buffer.size() + n.maxBytes > bufferSizeLimit) {
            stoppage = Stoppage(KJ_EXCEPTION(FAILED, "tee buffer size limit exceeded"));
            return pull();
          }
        }
      }
      auto heapBuffer = heapArray<byte>(n.maxBytes);

      // gcc 4.9 quirk: If I don't hoist this into a separate variable and instead call
      //
      //   inner->tryRead(heapBuffer.begin(), n.minBytes, heapBuffer.size())
      //
      // `heapBuffer` seems to get moved into the lambda capture before the arguments to `tryRead()`
      // are evaluated, meaning `inner` sees a nullptr destination. Bizarrely, `inner` sees the
      // correct value for `heapBuffer.size()`... I dunno, man.
      auto destination = heapBuffer.begin();

      try {
        return inner->tryRead(destination, n.minBytes, n.maxBytes)
            .then([this, heapBuffer = mv(heapBuffer), minBytes = n.minBytes](size_t amount) mutable
                -> Promise<void> {
          length = length.map([amount](uint64_t n) {
            KJ_ASSERT(n >= amount);
            return n - amount;
          });

          if (amount < heapBuffer.size()) {
            heapBuffer = heapBuffer.slice(0, amount).attach(mv(heapBuffer));
          }

          KJ_ASSERT(stoppage == nullptr);
          Maybe<ArrayPtr<byte>> bufferPtr = nullptr;
          for (auto& state: branches) {
            KJ_IF_MAYBE(s, state) {
              // Prefer to move the buffer into the receiving branch's deque, rather than memcpy.
              //
              // TODO(perf): For the 2-branch case, this is fine, since the majority of the time
              //   only one buffer will be in use. If we generalize to the n-branch case, this would
              //   become memcpy-heavy.
              KJ_IF_MAYBE(ptr, bufferPtr) {
                s->buffer.produce(heapArray(*ptr));
              } else {
                bufferPtr = ArrayPtr<byte>(heapBuffer);
                s->buffer.produce(mv(heapBuffer));
              }
            }
          }

          if (amount < minBytes) {
            // Short read, EOF.
            stoppage = Stoppage(Eof());
          }

          return pull();
        }, [this](Exception&& exception) {
          // Exception from the inner tryRead(). Propagate.
          stoppage = Stoppage(mv(exception));
          return pull();
        });
      } catch (const Exception& exception) {
        // Exception from the inner tryRead(). Propagate.
        stoppage = Stoppage(cp(exception));
        return pull();
      }
    }).eagerlyEvaluate([this](Exception&& exception) {
      // Exception from our loop, not from inner tryRead(). Something is broken; tell everybody!
      pulling = false;
      for (auto& state: branches) {
        KJ_IF_MAYBE(s, state) {
          KJ_IF_MAYBE(sink, s->sink) {
            sink->reject(KJ_EXCEPTION(FAILED, "Exception in tee loop", exception));
          }
        }
      }
    });
  }

  constexpr static size_t MAX_BLOCK_SIZE = 1 << 14;  // 16k

  Own<AsyncInputStream> inner;
  const uint64_t bufferSizeLimit = kj::maxValue;
  Maybe<uint64_t> length;
  Maybe<Branch> branches[2];
  Maybe<Stoppage> stoppage;
  Promise<void> pullPromise = READY_NOW;
  bool pulling = false;
};

constexpr size_t AsyncTee::MAX_BLOCK_SIZE;

uint64_t AsyncTee::Buffer::consume(ArrayPtr<byte>& readBuffer, size_t& minBytes) {
  uint64_t totalAmount = 0;

  while (readBuffer.size() > 0 && !bufferList.empty()) {
    auto& bytes = bufferList.front();
    auto amount = kj::min(bytes.size(), readBuffer.size());
    memcpy(readBuffer.begin(), bytes.begin(), amount);
    totalAmount += amount;

    readBuffer = readBuffer.slice(amount, readBuffer.size());
    minBytes -= kj::min(amount, minBytes);

    if (amount == bytes.size()) {
      bufferList.pop_front();
    } else {
      bytes = heapArray(bytes.slice(amount, bytes.size()));
      return totalAmount;
    }
  }

  return totalAmount;
}

void AsyncTee::Buffer::produce(Array<byte> bytes) {
  bufferList.push_back(mv(bytes));
}

Array<const ArrayPtr<const byte>> AsyncTee::Buffer::asArray(
    uint64_t maxBytes, uint64_t& amount) {
  amount = 0;

  Vector<ArrayPtr<const byte>> buffers;
  Vector<Array<byte>> ownBuffers;

  while (maxBytes > 0 && !bufferList.empty()) {
    auto& bytes = bufferList.front();

    if (bytes.size() <= maxBytes) {
      amount += bytes.size();
      maxBytes -= bytes.size();

      buffers.add(bytes);
      ownBuffers.add(mv(bytes));

      bufferList.pop_front();
    } else {
      auto ownBytes = heapArray(bytes.slice(0, maxBytes));
      buffers.add(ownBytes);
      ownBuffers.add(mv(ownBytes));

      bytes = heapArray(bytes.slice(maxBytes, bytes.size()));

      amount += maxBytes;
      maxBytes = 0;
    }
  }


  if (buffers.size() > 0) {
    return buffers.releaseAsArray().attach(mv(ownBuffers));
  }

  return {};
}

bool AsyncTee::Buffer::empty() const {
  return bufferList.empty();
}

uint64_t AsyncTee::Buffer::size() const {
  uint64_t result = 0;

  for (auto& bytes: bufferList) {
    result += bytes.size();
  }

  return result;
}

class TeeBranch final: public AsyncInputStream {
public:
  TeeBranch(Own<AsyncTee> tee, uint8_t branch): tee(mv(tee)), branch(branch) {
    this->tee->addBranch(branch);
  }
  ~TeeBranch() noexcept(false) {
    unwind.catchExceptionsIfUnwinding([&]() {
      tee->removeBranch(branch);
    });
  }

  Promise<size_t> tryRead(void* buffer, size_t minBytes, size_t maxBytes) override {
    return tee->tryRead(branch, buffer, minBytes, maxBytes);
  }

  Promise<uint64_t> pumpTo(AsyncOutputStream& output, uint64_t amount) override {
    return tee->pumpTo(branch, output, amount);
  }

  Maybe<uint64_t> tryGetLength() override {
    return tee->tryGetLength(branch);
  }

private:
  Own<AsyncTee> tee;
  const uint8_t branch;
  UnwindDetector unwind;
};

}  // namespace

Tee newTee(Own<AsyncInputStream> input, uint64_t limit) {
  auto impl = refcounted<AsyncTee>(mv(input), limit);
  Own<AsyncInputStream> branch1 = heap<TeeBranch>(addRef(*impl), 0);
  Own<AsyncInputStream> branch2 = heap<TeeBranch>(mv(impl), 1);
  return { { mv(branch1), mv(branch2) } };
}

1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779
Promise<Own<AsyncCapabilityStream>> AsyncCapabilityStream::receiveStream() {
  return tryReceiveStream()
      .then([](Maybe<Own<AsyncCapabilityStream>>&& result)
            -> Promise<Own<AsyncCapabilityStream>> {
    KJ_IF_MAYBE(r, result) {
      return kj::mv(*r);
    } else {
      return KJ_EXCEPTION(FAILED, "EOF when expecting to receive capability");
    }
  });
}

Promise<AutoCloseFd> AsyncCapabilityStream::receiveFd() {
  return tryReceiveFd().then([](Maybe<AutoCloseFd>&& result) -> Promise<AutoCloseFd> {
    KJ_IF_MAYBE(r, result) {
      return kj::mv(*r);
    } else {
      return KJ_EXCEPTION(FAILED, "EOF when expecting to receive capability");
    }
  });
}
Promise<Maybe<AutoCloseFd>> AsyncCapabilityStream::tryReceiveFd() {
  return KJ_EXCEPTION(UNIMPLEMENTED, "this stream cannot receive file descriptors");
}
Promise<void> AsyncCapabilityStream::sendFd(int fd) {
  return KJ_EXCEPTION(UNIMPLEMENTED, "this stream cannot send file descriptors");
}

1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806
void AsyncIoStream::getsockopt(int level, int option, void* value, uint* length) {
  KJ_UNIMPLEMENTED("Not a socket.");
}
void AsyncIoStream::setsockopt(int level, int option, const void* value, uint length) {
  KJ_UNIMPLEMENTED("Not a socket.");
}
void AsyncIoStream::getsockname(struct sockaddr* addr, uint* length) {
  KJ_UNIMPLEMENTED("Not a socket.");
}
void AsyncIoStream::getpeername(struct sockaddr* addr, uint* length) {
  KJ_UNIMPLEMENTED("Not a socket.");
}
void ConnectionReceiver::getsockopt(int level, int option, void* value, uint* length) {
  KJ_UNIMPLEMENTED("Not a socket.");
}
void ConnectionReceiver::setsockopt(int level, int option, const void* value, uint length) {
  KJ_UNIMPLEMENTED("Not a socket.");
}
void DatagramPort::getsockopt(int level, int option, void* value, uint* length) {
  KJ_UNIMPLEMENTED("Not a socket.");
}
void DatagramPort::setsockopt(int level, int option, const void* value, uint length) {
  KJ_UNIMPLEMENTED("Not a socket.");
}
Own<DatagramPort> NetworkAddress::bindDatagramPort() {
  KJ_UNIMPLEMENTED("Datagram sockets not implemented.");
}
1807 1808
Own<DatagramPort> LowLevelAsyncIoProvider::wrapDatagramSocketFd(
    Fd fd, LowLevelAsyncIoProvider::NetworkFilter& filter, uint flags) {
1809 1810
  KJ_UNIMPLEMENTED("Datagram sockets not implemented.");
}
1811 1812 1813 1814 1815
#if !_WIN32
Own<AsyncCapabilityStream> LowLevelAsyncIoProvider::wrapUnixSocketFd(Fd fd, uint flags) {
  KJ_UNIMPLEMENTED("Unix socket with FD passing not implemented.");
}
#endif
1816 1817 1818
CapabilityPipe AsyncIoProvider::newCapabilityPipe() {
  KJ_UNIMPLEMENTED("Capability pipes not implemented.");
}
1819

1820
Own<AsyncInputStream> LowLevelAsyncIoProvider::wrapInputFd(OwnFd&& fd, uint flags) {
1821 1822
  return wrapInputFd(reinterpret_cast<Fd>(fd.release()), flags | TAKE_OWNERSHIP);
}
1823
Own<AsyncOutputStream> LowLevelAsyncIoProvider::wrapOutputFd(OwnFd&& fd, uint flags) {
1824 1825
  return wrapOutputFd(reinterpret_cast<Fd>(fd.release()), flags | TAKE_OWNERSHIP);
}
1826
Own<AsyncIoStream> LowLevelAsyncIoProvider::wrapSocketFd(OwnFd&& fd, uint flags) {
1827 1828 1829
  return wrapSocketFd(reinterpret_cast<Fd>(fd.release()), flags | TAKE_OWNERSHIP);
}
#if !_WIN32
1830
Own<AsyncCapabilityStream> LowLevelAsyncIoProvider::wrapUnixSocketFd(OwnFd&& fd, uint flags) {
1831 1832 1833 1834
  return wrapUnixSocketFd(reinterpret_cast<Fd>(fd.release()), flags | TAKE_OWNERSHIP);
}
#endif
Promise<Own<AsyncIoStream>> LowLevelAsyncIoProvider::wrapConnectingSocketFd(
1835
    OwnFd&& fd, const struct sockaddr* addr, uint addrlen, uint flags) {
1836 1837 1838 1839
  return wrapConnectingSocketFd(reinterpret_cast<Fd>(fd.release()), addr, addrlen,
                                flags | TAKE_OWNERSHIP);
}
Own<ConnectionReceiver> LowLevelAsyncIoProvider::wrapListenSocketFd(
1840
    OwnFd&& fd, NetworkFilter& filter, uint flags) {
1841 1842
  return wrapListenSocketFd(reinterpret_cast<Fd>(fd.release()), filter, flags | TAKE_OWNERSHIP);
}
1843
Own<ConnectionReceiver> LowLevelAsyncIoProvider::wrapListenSocketFd(OwnFd&& fd, uint flags) {
1844 1845 1846
  return wrapListenSocketFd(reinterpret_cast<Fd>(fd.release()), flags | TAKE_OWNERSHIP);
}
Own<DatagramPort> LowLevelAsyncIoProvider::wrapDatagramSocketFd(
1847
    OwnFd&& fd, NetworkFilter& filter, uint flags) {
1848 1849
  return wrapDatagramSocketFd(reinterpret_cast<Fd>(fd.release()), filter, flags | TAKE_OWNERSHIP);
}
1850
Own<DatagramPort> LowLevelAsyncIoProvider::wrapDatagramSocketFd(OwnFd&& fd, uint flags) {
1851 1852 1853
  return wrapDatagramSocketFd(reinterpret_cast<Fd>(fd.release()), flags | TAKE_OWNERSHIP);
}

1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867
namespace {

class DummyNetworkFilter: public kj::LowLevelAsyncIoProvider::NetworkFilter {
public:
  bool shouldAllow(const struct sockaddr* addr, uint addrlen) override { return true; }
};

}  // namespace

LowLevelAsyncIoProvider::NetworkFilter& LowLevelAsyncIoProvider::NetworkFilter::getAllAllowed() {
  static DummyNetworkFilter result;
  return result;
}

1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900
// =======================================================================================
// Convenience adapters.

Promise<Own<AsyncIoStream>> CapabilityStreamConnectionReceiver::accept() {
  return inner.receiveStream()
      .then([](Own<AsyncCapabilityStream>&& stream) -> Own<AsyncIoStream> {
    return kj::mv(stream);
  });
}

uint CapabilityStreamConnectionReceiver::getPort() {
  return 0;
}

Promise<Own<AsyncIoStream>> CapabilityStreamNetworkAddress::connect() {
  auto pipe = provider.newCapabilityPipe();
  auto result = kj::mv(pipe.ends[0]);
  return inner.sendStream(kj::mv(pipe.ends[1]))
      .then(kj::mvCapture(result, [](Own<AsyncIoStream>&& result) {
    return kj::mv(result);
  }));
}
Own<ConnectionReceiver> CapabilityStreamNetworkAddress::listen() {
  return kj::heap<CapabilityStreamConnectionReceiver>(inner);
}

Own<NetworkAddress> CapabilityStreamNetworkAddress::clone() {
  KJ_UNIMPLEMENTED("can't clone CapabilityStreamNetworkAddress");
}
String CapabilityStreamNetworkAddress::toString() {
  return kj::str("<CapabilityStreamNetworkAddress>");
}

1901 1902 1903 1904
// =======================================================================================

namespace _ {  // private

1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924
#if !_WIN32

kj::ArrayPtr<const char> safeUnixPath(const struct sockaddr_un* addr, uint addrlen) {
  KJ_REQUIRE(addr->sun_family == AF_UNIX, "not a unix address");
  KJ_REQUIRE(addrlen >= offsetof(sockaddr_un, sun_path), "invalid unix address");

  size_t maxPathlen = addrlen - offsetof(sockaddr_un, sun_path);

  size_t pathlen;
  if (maxPathlen > 0 && addr->sun_path[0] == '\0') {
    // Linux "abstract" unix address
    pathlen = strnlen(addr->sun_path + 1, maxPathlen - 1) + 1;
  } else {
    pathlen = strnlen(addr->sun_path, maxPathlen);
  }
  return kj::arrayPtr(addr->sun_path, pathlen);
}

#endif  // !_WIN32

1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955
CidrRange::CidrRange(StringPtr pattern) {
  size_t slashPos = KJ_REQUIRE_NONNULL(pattern.findFirst('/'), "invalid CIDR", pattern);

  bitCount = pattern.slice(slashPos + 1).parseAs<uint>();

  KJ_STACK_ARRAY(char, addr, slashPos + 1, 128, 128);
  memcpy(addr.begin(), pattern.begin(), slashPos);
  addr[slashPos] = '\0';

  if (pattern.findFirst(':') == nullptr) {
    family = AF_INET;
    KJ_REQUIRE(bitCount <= 32, "invalid CIDR", pattern);
  } else {
    family = AF_INET6;
    KJ_REQUIRE(bitCount <= 128, "invalid CIDR", pattern);
  }

  KJ_ASSERT(inet_pton(family, addr.begin(), bits) > 0, "invalid CIDR", pattern);
  zeroIrrelevantBits();
}

CidrRange::CidrRange(int family, ArrayPtr<const byte> bits, uint bitCount)
    : family(family), bitCount(bitCount) {
  if (family == AF_INET) {
    KJ_REQUIRE(bitCount <= 32);
  } else {
    KJ_REQUIRE(bitCount <= 128);
  }
  KJ_REQUIRE(bits.size() * 8 >= bitCount);
  size_t byteCount = (bitCount + 7) / 8;
  memcpy(this->bits, bits.begin(), byteCount);
1956
  memset(this->bits + byteCount, 0, sizeof(this->bits) - byteCount);
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 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066

  zeroIrrelevantBits();
}

CidrRange CidrRange::inet4(ArrayPtr<const byte> bits, uint bitCount) {
  return CidrRange(AF_INET, bits, bitCount);
}
CidrRange CidrRange::inet6(
    ArrayPtr<const uint16_t> prefix, ArrayPtr<const uint16_t> suffix,
    uint bitCount) {
  KJ_REQUIRE(prefix.size() + suffix.size() <= 8);

  byte bits[16] = { 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0, };

  for (size_t i: kj::indices(prefix)) {
    bits[i * 2] = prefix[i] >> 8;
    bits[i * 2 + 1] = prefix[i] & 0xff;
  }

  byte* suffixBits = bits + (16 - suffix.size() * 2);
  for (size_t i: kj::indices(suffix)) {
    suffixBits[i * 2] = suffix[i] >> 8;
    suffixBits[i * 2 + 1] = suffix[i] & 0xff;
  }

  return CidrRange(AF_INET6, bits, bitCount);
}

bool CidrRange::matches(const struct sockaddr* addr) const {
  const byte* otherBits;

  switch (family) {
    case AF_INET:
      if (addr->sa_family == AF_INET6) {
        otherBits = reinterpret_cast<const struct sockaddr_in6*>(addr)->sin6_addr.s6_addr;
        static constexpr byte V6MAPPED[12] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xff, 0xff };
        if (memcmp(otherBits, V6MAPPED, sizeof(V6MAPPED)) == 0) {
          // We're an ipv4 range and the address is ipv6, but it's a "v6 mapped" address, meaning
          // it's equivalent to an ipv4 address. Try to match against the ipv4 part.
          otherBits = otherBits + sizeof(V6MAPPED);
        } else {
          return false;
        }
      } else if (addr->sa_family == AF_INET) {
        otherBits = reinterpret_cast<const byte*>(
            &reinterpret_cast<const struct sockaddr_in*>(addr)->sin_addr.s_addr);
      } else {
        return false;
      }

      break;

    case AF_INET6:
      if (addr->sa_family != AF_INET6) return false;

      otherBits = reinterpret_cast<const struct sockaddr_in6*>(addr)->sin6_addr.s6_addr;
      break;

    default:
      KJ_UNREACHABLE;
  }

  if (memcmp(bits, otherBits, bitCount / 8) != 0) return false;

  return bitCount == 128 ||
      bits[bitCount / 8] == (otherBits[bitCount / 8] & (0xff00 >> (bitCount % 8)));
}

bool CidrRange::matchesFamily(int family) const {
  switch (family) {
    case AF_INET:
      return this->family == AF_INET;
    case AF_INET6:
      // Even if we're a v4 CIDR, we can match v6 addresses in the v4-mapped range.
      return true;
    default:
      return false;
  }
}

String CidrRange::toString() const {
  char result[128];
  KJ_ASSERT(inet_ntop(family, (void*)bits, result, sizeof(result)) == result);
  return kj::str(result, '/', bitCount);
}

void CidrRange::zeroIrrelevantBits() {
  // Mask out insignificant bits of partial byte.
  if (bitCount < 128) {
    bits[bitCount / 8] &= 0xff00 >> (bitCount % 8);

    // Zero the remaining bytes.
    size_t n = bitCount / 8 + 1;
    memset(bits + n, 0, sizeof(bits) - n);
  }
}

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

ArrayPtr<const CidrRange> localCidrs() {
  static const CidrRange result[] = {
    // localhost
    "127.0.0.0/8"_kj,
    "::1/128"_kj,

    // Trying to *connect* to 0.0.0.0 on many systems is equivalent to connecting to localhost.
    // (wat)
    "0.0.0.0/32"_kj,
    "::/128"_kj,
  };
2067 2068 2069 2070

  // TODO(cleanup): A bug in GCC 4.8, fixed in 4.9, prevents result from implicitly
  //   casting to our return type.
  return kj::arrayPtr(result, kj::size(result));
2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083
}

ArrayPtr<const CidrRange> privateCidrs() {
  static const CidrRange result[] = {
    "10.0.0.0/8"_kj,            // RFC1918 reserved for internal network
    "100.64.0.0/10"_kj,         // RFC6598 "shared address space" for carrier-grade NAT
    "169.254.0.0/16"_kj,        // RFC3927 "link local" (auto-configured LAN in absence of DHCP)
    "172.16.0.0/12"_kj,         // RFC1918 reserved for internal network
    "192.168.0.0/16"_kj,        // RFC1918 reserved for internal network

    "fc00::/7"_kj,              // RFC4193 unique private network
    "fe80::/10"_kj,             // RFC4291 "link local" (auto-configured LAN in absence of DHCP)
  };
2084 2085 2086 2087

  // TODO(cleanup): A bug in GCC 4.8, fixed in 4.9, prevents result from implicitly
  //   casting to our return type.
  return kj::arrayPtr(result, kj::size(result));
2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099
}

ArrayPtr<const CidrRange> reservedCidrs() {
  static const CidrRange result[] = {
    "192.0.0.0/24"_kj,          // RFC6890 reserved for special protocols
    "224.0.0.0/4"_kj,           // RFC1112 multicast
    "240.0.0.0/4"_kj,           // RFC1112 multicast / reserved for future use
    "255.255.255.255/32"_kj,    // RFC0919 broadcast address

    "2001::/23"_kj,             // RFC2928 reserved for special protocols
    "ff00::/8"_kj,              // RFC4291 multicast
  };
2100 2101 2102 2103

  // TODO(cleanup): A bug in GCC 4.8, fixed in 4.9, prevents result from implicitly
  //   casting to our return type.
  return kj::arrayPtr(result, kj::size(result));
2104 2105 2106 2107 2108 2109 2110 2111 2112
}

ArrayPtr<const CidrRange> exampleAddresses() {
  static const CidrRange result[] = {
    "192.0.2.0/24"_kj,          // RFC5737 "example address" block 1 -- like example.com for IPs
    "198.51.100.0/24"_kj,       // RFC5737 "example address" block 2 -- like example.com for IPs
    "203.0.113.0/24"_kj,        // RFC5737 "example address" block 3 -- like example.com for IPs
    "2001:db8::/32"_kj,         // RFC3849 "example address" block -- like example.com for IPs
  };
2113 2114 2115 2116

  // TODO(cleanup): A bug in GCC 4.8, fixed in 4.9, prevents result from implicitly
  //   casting to our return type.
  return kj::arrayPtr(result, kj::size(result));
2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156
}

NetworkFilter::NetworkFilter()
    : allowUnix(true), allowAbstractUnix(true) {
  allowCidrs.add(CidrRange::inet4({0,0,0,0}, 0));
  allowCidrs.add(CidrRange::inet6({}, {}, 0));
  denyCidrs.addAll(reservedCidrs());
}

NetworkFilter::NetworkFilter(ArrayPtr<const StringPtr> allow, ArrayPtr<const StringPtr> deny,
                             NetworkFilter& next)
    : allowUnix(false), allowAbstractUnix(false), next(next) {
  for (auto rule: allow) {
    if (rule == "local") {
      allowCidrs.addAll(localCidrs());
    } else if (rule == "network") {
      allowCidrs.add(CidrRange::inet4({0,0,0,0}, 0));
      allowCidrs.add(CidrRange::inet6({}, {}, 0));
      denyCidrs.addAll(localCidrs());
    } else if (rule == "private") {
      allowCidrs.addAll(privateCidrs());
      allowCidrs.addAll(localCidrs());
    } else if (rule == "public") {
      allowCidrs.add(CidrRange::inet4({0,0,0,0}, 0));
      allowCidrs.add(CidrRange::inet6({}, {}, 0));
      denyCidrs.addAll(privateCidrs());
      denyCidrs.addAll(localCidrs());
    } else if (rule == "unix") {
      allowUnix = true;
    } else if (rule == "unix-abstract") {
      allowAbstractUnix = true;
    } else {
      allowCidrs.add(CidrRange(rule));
    }
  }

  for (auto rule: deny) {
    if (rule == "local") {
      denyCidrs.addAll(localCidrs());
    } else if (rule == "network") {
2157
      KJ_FAIL_REQUIRE("don't deny 'network', allow 'local' instead");
2158 2159 2160 2161
    } else if (rule == "private") {
      denyCidrs.addAll(privateCidrs());
    } else if (rule == "public") {
      // Tricky: What if we allow 'network' and deny 'public'?
2162
      KJ_FAIL_REQUIRE("don't deny 'public', allow 'private' instead");
2163 2164 2165 2166 2167 2168 2169 2170 2171 2172
    } else if (rule == "unix") {
      allowUnix = false;
    } else if (rule == "unix-abstract") {
      allowAbstractUnix = false;
    } else {
      denyCidrs.add(CidrRange(rule));
    }
  }
}

2173
bool NetworkFilter::shouldAllow(const struct sockaddr* addr, uint addrlen) {
2174
  KJ_REQUIRE(addrlen >= sizeof(addr->sa_family));
2175

2176 2177
#if !_WIN32
  if (addr->sa_family == AF_UNIX) {
2178 2179
    auto path = safeUnixPath(reinterpret_cast<const struct sockaddr_un*>(addr), addrlen);
    if (path.size() > 0 && path[0] == '\0') {
2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202
      return allowAbstractUnix;
    } else {
      return allowUnix;
    }
  }
#endif

  bool allowed = false;
  uint allowSpecificity = 0;
  for (auto& cidr: allowCidrs) {
    if (cidr.matches(addr)) {
      allowSpecificity = kj::max(allowSpecificity, cidr.getSpecificity());
      allowed = true;
    }
  }
  if (!allowed) return false;
  for (auto& cidr: denyCidrs) {
    if (cidr.matches(addr)) {
      if (cidr.getSpecificity() >= allowSpecificity) return false;
    }
  }

  KJ_IF_MAYBE(n, next) {
2203
    return n->shouldAllow(addr, addrlen);
2204 2205 2206 2207 2208
  } else {
    return true;
  }
}

2209
bool NetworkFilter::shouldAllowParse(const struct sockaddr* addr, uint addrlen) {
2210 2211 2212
  bool matched = false;
#if !_WIN32
  if (addr->sa_family == AF_UNIX) {
2213 2214
    auto path = safeUnixPath(reinterpret_cast<const struct sockaddr_un*>(addr), addrlen);
    if (path.size() > 0 && path[0] == '\0') {
2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231
      if (allowAbstractUnix) matched = true;
    } else {
      if (allowUnix) matched = true;
    }
  } else {
#endif
    for (auto& cidr: allowCidrs) {
      if (cidr.matchesFamily(addr->sa_family)) {
        matched = true;
      }
    }
#if !_WIN32
  }
#endif

  if (matched) {
    KJ_IF_MAYBE(n, next) {
2232
      return n->shouldAllowParse(addr, addrlen);
2233 2234 2235 2236 2237 2238 2239 2240 2241 2242
    } else {
      return true;
    }
  } else {
    // No allow rule matches this address family, so don't even allow parsing it.
    return false;
  }
}

}  // namespace _ (private)
2243
}  // namespace kj