| 1 | // Copyright (c) 2013-2017 Sandstorm Development Group, Inc. and contributors |
| 2 | // Licensed under the MIT License: |
| 3 | // |
| 4 | // Permission is hereby granted, free of charge, to any person obtaining a copy |
| 5 | // of this software and associated documentation files (the "Software"), to deal |
| 6 | // in the Software without restriction, including without limitation the rights |
| 7 | // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell |
| 8 | // copies of the Software, and to permit persons to whom the Software is |
| 9 | // furnished to do so, subject to the following conditions: |
| 10 | // |
| 11 | // The above copyright notice and this permission notice shall be included in |
| 12 | // all copies or substantial portions of the Software. |
| 13 | // |
| 14 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR |
| 15 | // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, |
| 16 | // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE |
| 17 | // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER |
| 18 | // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, |
| 19 | // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN |
| 20 | // THE SOFTWARE. |
| 21 | |
| 22 | #if _WIN32 |
| 23 | // Request Vista-level APIs. |
| 24 | #include <kj/win32-api-version.h> |
| 25 | #endif |
| 26 | |
| 27 | #include "async-io.h" |
| 28 | #include "async-io-internal.h" |
| 29 | #include "debug.h" |
| 30 | #include "vector.h" |
| 31 | #include "io.h" |
| 32 | #include "one-of.h" |
| 33 | #include <deque> |
| 34 | #include <kj/filesystem.h> |
| 35 | |
| 36 | #if _WIN32 |
| 37 | #include <winsock2.h> |
| 38 | #include <ws2ipdef.h> |
| 39 | #include <ws2tcpip.h> |
| 40 | #include <kj/windows-sanity.h> |
| 41 | #define inet_pton InetPtonA |
| 42 | #define inet_ntop InetNtopA |
| 43 | #include <io.h> |
| 44 | #define dup _dup |
| 45 | #else |
| 46 | #include <sys/socket.h> |
| 47 | #include <arpa/inet.h> |
| 48 | #include <netinet/in.h> |
| 49 | #include <sys/un.h> |
| 50 | #include <unistd.h> |
| 51 | #endif |
| 52 | |
| 53 | namespace kj { |
| 54 | |
| 55 | Promise<void> AsyncInputStream::read(void* buffer, size_t bytes) { |
| 56 | return read(buffer, bytes, bytes).then([](size_t) {}); |
| 57 | } |
| 58 | |
| 59 | Promise<size_t> AsyncInputStream::read(void* buffer, size_t minBytes, size_t maxBytes) { |
| 60 | return tryRead(buffer, minBytes, maxBytes).then([=](size_t result) { |
| 61 | if (result >= minBytes) { |
| 62 | return result; |
| 63 | } else { |
| 64 | kj::throwRecoverableException(KJ_EXCEPTION(DISCONNECTED, "stream disconnected prematurely")); |
| 65 | // Pretend we read zeros from the input. |
| 66 | memset(reinterpret_cast<byte*>(buffer) + result, 0, minBytes - result); |
| 67 | return minBytes; |
| 68 | } |
| 69 | }); |
| 70 | } |
| 71 | |
| 72 | Maybe<uint64_t> AsyncInputStream::tryGetLength() { return nullptr; } |
| 73 | |
| 74 | void AsyncInputStream::registerAncillaryMessageHandler( |
| 75 | Function<void(ArrayPtr<AncillaryMessage>)> fn) { |
| 76 | KJ_UNIMPLEMENTED("registerAncillaryMsgHandler is not implemented by this AsyncInputStream"); |
| 77 | } |
| 78 | |
| 79 | Maybe<Own<AsyncInputStream>> AsyncInputStream::tryTee(uint64_t) { |
| 80 | return nullptr; |
| 81 | } |
| 82 | |
| 83 | namespace { |
| 84 | |
| 85 | class AsyncPump { |
| 86 | public: |
| 87 | AsyncPump(AsyncInputStream& input, AsyncOutputStream& output, uint64_t limit, uint64_t doneSoFar) |
| 88 | : input(input), output(output), limit(limit), doneSoFar(doneSoFar) {} |
| 89 | |
| 90 | Promise<uint64_t> pump() { |
| 91 | // TODO(perf): This could be more efficient by reading half a buffer at a time and then |
| 92 | // starting the next read concurrent with writing the data from the previous read. |
| 93 | |
| 94 | uint64_t n = kj::min(limit - doneSoFar, sizeof(buffer)); |
| 95 | if (n == 0) return doneSoFar; |
| 96 | |
| 97 | return input.tryRead(buffer, 1, n) |
| 98 | .then([this](size_t amount) -> Promise<uint64_t> { |
| 99 | if (amount == 0) return doneSoFar; // EOF |
| 100 | doneSoFar += amount; |
| 101 | return output.write(buffer, amount) |
| 102 | .then([this]() { |
| 103 | return pump(); |
| 104 | }); |
| 105 | }); |
| 106 | } |
| 107 | |
| 108 | private: |
| 109 | AsyncInputStream& input; |
| 110 | AsyncOutputStream& output; |
| 111 | uint64_t limit; |
| 112 | uint64_t doneSoFar; |
| 113 | byte buffer[4096]; |
| 114 | }; |
| 115 | |
| 116 | } // namespace |
| 117 | |
| 118 | Promise<uint64_t> unoptimizedPumpTo( |
| 119 | AsyncInputStream& input, AsyncOutputStream& output, uint64_t amount, |
| 120 | uint64_t completedSoFar) { |
| 121 | auto pump = heap<AsyncPump>(input, output, amount, completedSoFar); |
| 122 | auto promise = pump->pump(); |
| 123 | return promise.attach(kj::mv(pump)); |
| 124 | } |
| 125 | |
| 126 | Promise<uint64_t> AsyncInputStream::pumpTo( |
| 127 | AsyncOutputStream& output, uint64_t amount) { |
| 128 | // See if output wants to dispatch on us. |
| 129 | KJ_IF_MAYBE(result, output.tryPumpFrom(*this, amount)) { |
| 130 | return kj::mv(*result); |
| 131 | } |
| 132 | |
| 133 | // OK, fall back to naive approach. |
| 134 | return unoptimizedPumpTo(*this, output, amount); |
| 135 | } |
| 136 | |
| 137 | namespace { |
| 138 | |
| 139 | class AllReader { |
| 140 | public: |
| 141 | AllReader(AsyncInputStream& input): input(input) {} |
| 142 | |
| 143 | Promise<Array<byte>> readAllBytes(uint64_t limit) { |
| 144 | return loop(limit).then([this, limit](uint64_t headroom) { |
| 145 | auto out = heapArray<byte>(limit - headroom); |
| 146 | copyInto(out); |
| 147 | return out; |
| 148 | }); |
| 149 | } |
| 150 | |
| 151 | Promise<String> readAllText(uint64_t limit) { |
| 152 | return loop(limit).then([this, limit](uint64_t headroom) { |
| 153 | auto out = heapArray<char>(limit - headroom + 1); |
| 154 | copyInto(out.slice(0, out.size() - 1).asBytes()); |
| 155 | out.back() = '\0'; |
| 156 | return String(kj::mv(out)); |
| 157 | }); |
| 158 | } |
| 159 | |
| 160 | private: |
| 161 | AsyncInputStream& input; |
| 162 | Vector<Array<byte>> parts; |
| 163 | |
| 164 | Promise<uint64_t> loop(uint64_t limit) { |
| 165 | KJ_REQUIRE(limit > 0, "Reached limit before EOF."); |
| 166 | |
| 167 | auto part = heapArray<byte>(kj::min(4096, limit)); |
| 168 | auto partPtr = part.asPtr(); |
| 169 | parts.add(kj::mv(part)); |
| 170 | return input.tryRead(partPtr.begin(), partPtr.size(), partPtr.size()) |
| 171 | .then([this,KJ_CPCAP(partPtr),limit](size_t amount) mutable -> Promise<uint64_t> { |
| 172 | limit -= amount; |
| 173 | if (amount < partPtr.size()) { |
| 174 | return limit; |
| 175 | } else { |
| 176 | return loop(limit); |
| 177 | } |
| 178 | }); |
| 179 | } |
| 180 | |
| 181 | void copyInto(ArrayPtr<byte> out) { |
| 182 | size_t pos = 0; |
| 183 | for (auto& part: parts) { |
| 184 | size_t n = kj::min(part.size(), out.size() - pos); |
| 185 | memcpy(out.begin() + pos, part.begin(), n); |
| 186 | pos += n; |
| 187 | } |
| 188 | } |
| 189 | }; |
| 190 | |
| 191 | } // namespace |
| 192 | |
| 193 | Promise<Array<byte>> AsyncInputStream::readAllBytes(uint64_t limit) { |
| 194 | auto reader = kj::heap<AllReader>(*this); |
| 195 | auto promise = reader->readAllBytes(limit); |
| 196 | return promise.attach(kj::mv(reader)); |
| 197 | } |
| 198 | |
| 199 | Promise<String> AsyncInputStream::readAllText(uint64_t limit) { |
| 200 | auto reader = kj::heap<AllReader>(*this); |
| 201 | auto promise = reader->readAllText(limit); |
| 202 | return promise.attach(kj::mv(reader)); |
| 203 | } |
| 204 | |
| 205 | Maybe<Promise<uint64_t>> AsyncOutputStream::tryPumpFrom( |
| 206 | AsyncInputStream& input, uint64_t amount) { |
| 207 | return nullptr; |
| 208 | } |
| 209 | |
| 210 | namespace { |
| 211 | |
| 212 | class AsyncPipe final: public AsyncCapabilityStream, public Refcounted { |
| 213 | public: |
| 214 | ~AsyncPipe() noexcept(false) { |
| 215 | KJ_REQUIRE(state == nullptr || ownState.get() != nullptr, |
| 216 | "destroying AsyncPipe with operation still in-progress; probably going to segfault") { |
| 217 | // Don't std::terminate(). |
| 218 | break; |
| 219 | } |
| 220 | } |
| 221 | |
| 222 | Promise<size_t> tryRead(void* buffer, size_t minBytes, size_t maxBytes) override { |
| 223 | if (minBytes == 0) { |
| 224 | return constPromise<size_t, 0>(); |
| 225 | } else KJ_IF_MAYBE(s, state) { |
| 226 | return s->tryRead(buffer, minBytes, maxBytes); |
| 227 | } else { |
| 228 | return newAdaptedPromise<ReadResult, BlockedRead>( |
| 229 | *this, arrayPtr(reinterpret_cast<byte*>(buffer), maxBytes), minBytes) |
| 230 | .then([](ReadResult r) { return r.byteCount; }); |
| 231 | } |
| 232 | } |
| 233 | |
| 234 | Promise<ReadResult> tryReadWithFds(void* buffer, size_t minBytes, size_t maxBytes, |
| 235 | AutoCloseFd* fdBuffer, size_t maxFds) override { |
| 236 | if (minBytes == 0) { |
| 237 | return ReadResult { 0, 0 }; |
| 238 | } else KJ_IF_MAYBE(s, state) { |
| 239 | return s->tryReadWithFds(buffer, minBytes, maxBytes, fdBuffer, maxFds); |
| 240 | } else { |
| 241 | return newAdaptedPromise<ReadResult, BlockedRead>( |
| 242 | *this, arrayPtr(reinterpret_cast<byte*>(buffer), maxBytes), minBytes, |
| 243 | kj::arrayPtr(fdBuffer, maxFds)); |
| 244 | } |
| 245 | } |
| 246 | |
| 247 | Promise<ReadResult> tryReadWithStreams( |
| 248 | void* buffer, size_t minBytes, size_t maxBytes, |
| 249 | Own<AsyncCapabilityStream>* streamBuffer, size_t maxStreams) override { |
| 250 | if (minBytes == 0) { |
| 251 | return ReadResult { 0, 0 }; |
| 252 | } else KJ_IF_MAYBE(s, state) { |
| 253 | return s->tryReadWithStreams(buffer, minBytes, maxBytes, streamBuffer, maxStreams); |
| 254 | } else { |
| 255 | return newAdaptedPromise<ReadResult, BlockedRead>( |
| 256 | *this, arrayPtr(reinterpret_cast<byte*>(buffer), maxBytes), minBytes, |
| 257 | kj::arrayPtr(streamBuffer, maxStreams)); |
| 258 | } |
| 259 | } |
| 260 | |
| 261 | Promise<uint64_t> pumpTo(AsyncOutputStream& output, uint64_t amount) override { |
| 262 | if (amount == 0) { |
| 263 | return constPromise<uint64_t, 0>(); |
| 264 | } else KJ_IF_MAYBE(s, state) { |
| 265 | return s->pumpTo(output, amount); |
| 266 | } else { |
| 267 | return newAdaptedPromise<uint64_t, BlockedPumpTo>(*this, output, amount); |
| 268 | } |
| 269 | } |
| 270 | |
| 271 | void abortRead() override { |
| 272 | KJ_IF_MAYBE(s, state) { |
| 273 | s->abortRead(); |
| 274 | } else { |
| 275 | ownState = kj::heap<AbortedRead>(); |
| 276 | state = *ownState; |
| 277 | |
| 278 | readAborted = true; |
| 279 | KJ_IF_MAYBE(f, readAbortFulfiller) { |
| 280 | f->get()->fulfill(); |
| 281 | readAbortFulfiller = nullptr; |
| 282 | } |
| 283 | } |
| 284 | } |
| 285 | |
| 286 | Promise<void> write(const void* buffer, size_t size) override { |
| 287 | if (size == 0) { |
| 288 | return READY_NOW; |
| 289 | } else KJ_IF_MAYBE(s, state) { |
| 290 | return s->write(buffer, size); |
| 291 | } else { |
| 292 | return newAdaptedPromise<void, BlockedWrite>( |
| 293 | *this, arrayPtr(reinterpret_cast<const byte*>(buffer), size), nullptr); |
| 294 | } |
| 295 | } |
| 296 | |
| 297 | Promise<void> write(ArrayPtr<const ArrayPtr<const byte>> pieces) override { |
| 298 | while (pieces.size() > 0 && pieces[0].size() == 0) { |
| 299 | pieces = pieces.slice(1, pieces.size()); |
| 300 | } |
| 301 | |
| 302 | if (pieces.size() == 0) { |
| 303 | return kj::READY_NOW; |
| 304 | } else KJ_IF_MAYBE(s, state) { |
| 305 | return s->write(pieces); |
| 306 | } else { |
| 307 | return newAdaptedPromise<void, BlockedWrite>( |
| 308 | *this, pieces[0], pieces.slice(1, pieces.size())); |
| 309 | } |
| 310 | } |
| 311 | |
| 312 | Promise<void> writeWithFds(ArrayPtr<const byte> data, |
| 313 | ArrayPtr<const ArrayPtr<const byte>> moreData, |
| 314 | ArrayPtr<const int> fds) override { |
| 315 | while (data.size() == 0 && moreData.size() > 0) { |
| 316 | data = moreData.front(); |
| 317 | moreData = moreData.slice(1, moreData.size()); |
| 318 | } |
| 319 | |
| 320 | if (data.size() == 0) { |
| 321 | KJ_REQUIRE(fds.size() == 0, "can't attach FDs to empty message"); |
| 322 | return READY_NOW; |
| 323 | } else KJ_IF_MAYBE(s, state) { |
| 324 | return s->writeWithFds(data, moreData, fds); |
| 325 | } else { |
| 326 | return newAdaptedPromise<void, BlockedWrite>(*this, data, moreData, fds); |
| 327 | } |
| 328 | } |
| 329 | |
| 330 | Promise<void> writeWithStreams(ArrayPtr<const byte> data, |
| 331 | ArrayPtr<const ArrayPtr<const byte>> moreData, |
| 332 | Array<Own<AsyncCapabilityStream>> streams) override { |
| 333 | while (data.size() == 0 && moreData.size() > 0) { |
| 334 | data = moreData.front(); |
| 335 | moreData = moreData.slice(1, moreData.size()); |
| 336 | } |
| 337 | |
| 338 | if (data.size() == 0) { |
| 339 | KJ_REQUIRE(streams.size() == 0, "can't attach capabilities to empty message"); |
| 340 | return READY_NOW; |
| 341 | } else KJ_IF_MAYBE(s, state) { |
| 342 | return s->writeWithStreams(data, moreData, kj::mv(streams)); |
| 343 | } else { |
| 344 | return newAdaptedPromise<void, BlockedWrite>(*this, data, moreData, kj::mv(streams)); |
| 345 | } |
| 346 | } |
| 347 | |
| 348 | Maybe<Promise<uint64_t>> tryPumpFrom( |
| 349 | AsyncInputStream& input, uint64_t amount) override { |
| 350 | if (amount == 0) { |
| 351 | return constPromise<uint64_t, 0>(); |
| 352 | } else KJ_IF_MAYBE(s, state) { |
| 353 | return s->tryPumpFrom(input, amount); |
| 354 | } else { |
| 355 | return newAdaptedPromise<uint64_t, BlockedPumpFrom>(*this, input, amount); |
| 356 | } |
| 357 | } |
| 358 | |
| 359 | Promise<void> whenWriteDisconnected() override { |
| 360 | if (readAborted) { |
| 361 | return kj::READY_NOW; |
| 362 | } else KJ_IF_MAYBE(p, readAbortPromise) { |
| 363 | return p->addBranch(); |
| 364 | } else { |
| 365 | auto paf = newPromiseAndFulfiller<void>(); |
| 366 | readAbortFulfiller = kj::mv(paf.fulfiller); |
| 367 | auto fork = paf.promise.fork(); |
| 368 | auto result = fork.addBranch(); |
| 369 | readAbortPromise = kj::mv(fork); |
| 370 | return result; |
| 371 | } |
| 372 | } |
| 373 | |
| 374 | void shutdownWrite() override { |
| 375 | KJ_IF_MAYBE(s, state) { |
| 376 | s->shutdownWrite(); |
| 377 | } else { |
| 378 | ownState = kj::heap<ShutdownedWrite>(); |
| 379 | state = *ownState; |
| 380 | } |
| 381 | } |
| 382 | |
| 383 | private: |
| 384 | Maybe<AsyncCapabilityStream&> state; |
| 385 | // Object-oriented state! If any method call is blocked waiting on activity from the other end, |
| 386 | // then `state` is non-null and method calls should be forwarded to it. If no calls are |
| 387 | // outstanding, `state` is null. |
| 388 | |
| 389 | kj::Own<AsyncCapabilityStream> ownState; |
| 390 | |
| 391 | bool readAborted = false; |
| 392 | Maybe<Own<PromiseFulfiller<void>>> readAbortFulfiller = nullptr; |
| 393 | Maybe<ForkedPromise<void>> readAbortPromise = nullptr; |
| 394 | |
| 395 | void endState(AsyncIoStream& obj) { |
| 396 | KJ_IF_MAYBE(s, state) { |
| 397 | if (s == &obj) { |
| 398 | state = nullptr; |
| 399 | } |
| 400 | } |
| 401 | } |
| 402 | |
| 403 | template <typename F> |
| 404 | static auto teeExceptionVoid(F& fulfiller) { |
| 405 | // Returns a functor that can be passed as the second parameter to .then() to propagate the |
| 406 | // exception to a given fulfiller. The functor's return type is void. |
| 407 | return [&fulfiller](kj::Exception&& e) { |
| 408 | fulfiller.reject(kj::cp(e)); |
| 409 | kj::throwRecoverableException(kj::mv(e)); |
| 410 | }; |
| 411 | } |
| 412 | template <typename F> |
| 413 | static auto teeExceptionSize(F& fulfiller) { |
| 414 | // Returns a functor that can be passed as the second parameter to .then() to propagate the |
| 415 | // exception to a given fulfiller. The functor's return type is size_t. |
| 416 | return [&fulfiller](kj::Exception&& e) -> size_t { |
| 417 | fulfiller.reject(kj::cp(e)); |
| 418 | kj::throwRecoverableException(kj::mv(e)); |
| 419 | return 0; |
| 420 | }; |
| 421 | } |
| 422 | template <typename T, typename F> |
| 423 | static auto teeExceptionPromise(F& fulfiller) { |
| 424 | // Returns a functor that can be passed as the second parameter to .then() to propagate the |
| 425 | // exception to a given fulfiller. The functor's return type is Promise<T>. |
| 426 | return [&fulfiller](kj::Exception&& e) -> kj::Promise<T> { |
| 427 | fulfiller.reject(kj::cp(e)); |
| 428 | return kj::mv(e); |
| 429 | }; |
| 430 | } |
| 431 | |
| 432 | class BlockedWrite final: public AsyncCapabilityStream { |
| 433 | // AsyncPipe state when a write() is currently waiting for a corresponding read(). |
| 434 | |
| 435 | public: |
| 436 | BlockedWrite(PromiseFulfiller<void>& fulfiller, AsyncPipe& pipe, |
| 437 | ArrayPtr<const byte> writeBuffer, |
| 438 | ArrayPtr<const ArrayPtr<const byte>> morePieces, |
| 439 | kj::OneOf<ArrayPtr<const int>, Array<Own<AsyncCapabilityStream>>> capBuffer = {}) |
| 440 | : fulfiller(fulfiller), pipe(pipe), writeBuffer(writeBuffer), morePieces(morePieces), |
| 441 | capBuffer(kj::mv(capBuffer)) { |
| 442 | KJ_REQUIRE(pipe.state == nullptr); |
| 443 | pipe.state = *this; |
| 444 | } |
| 445 | |
| 446 | ~BlockedWrite() noexcept(false) { |
| 447 | pipe.endState(*this); |
| 448 | } |
| 449 | |
| 450 | Promise<size_t> tryRead(void* buffer, size_t minBytes, size_t maxBytes) override { |
| 451 | KJ_SWITCH_ONEOF(tryReadImpl(buffer, minBytes, maxBytes)) { |
| 452 | KJ_CASE_ONEOF(done, Done) { |
| 453 | return done.result; |
| 454 | } |
| 455 | KJ_CASE_ONEOF(retry, Retry) { |
| 456 | return pipe.tryRead(retry.buffer, retry.minBytes, retry.maxBytes) |
| 457 | .then([n = retry.alreadyRead](size_t amount) { return amount + n; }); |
| 458 | } |
| 459 | } |
| 460 | KJ_UNREACHABLE; |
| 461 | } |
| 462 | |
| 463 | Promise<ReadResult> tryReadWithFds(void* buffer, size_t minBytes, size_t maxBytes, |
| 464 | AutoCloseFd* fdBuffer, size_t maxFds) override { |
| 465 | size_t capCount = 0; |
| 466 | { // TODO(cleanup): Remove redundant braces when we update to C++17. |
| 467 | KJ_SWITCH_ONEOF(capBuffer) { |
| 468 | KJ_CASE_ONEOF(fds, ArrayPtr<const int>) { |
| 469 | capCount = kj::max(fds.size(), maxFds); |
| 470 | // Unfortunately, we have to dup() each FD, because the writer doesn't release ownership |
| 471 | // by default. |
| 472 | // TODO(perf): Should we add an ownership-releasing version of writeWithFds()? |
| 473 | for (auto i: kj::zeroTo(capCount)) { |
| 474 | int duped; |
| 475 | KJ_SYSCALL(duped = dup(fds[i])); |
| 476 | fdBuffer[i] = kj::AutoCloseFd(fds[i]); |
| 477 | } |
| 478 | fdBuffer += capCount; |
| 479 | maxFds -= capCount; |
| 480 | } |
| 481 | KJ_CASE_ONEOF(streams, Array<Own<AsyncCapabilityStream>>) { |
| 482 | if (streams.size() > 0 && maxFds > 0) { |
| 483 | // TODO(someday): We could let people pass a LowLevelAsyncIoProvider to |
| 484 | // newTwoWayPipe() if we wanted to auto-wrap FDs, but does anyone care? |
| 485 | KJ_FAIL_REQUIRE( |
| 486 | "async pipe message was written with streams attached, but corresponding read " |
| 487 | "asked for FDs, and we don't know how to convert here"); |
| 488 | } |
| 489 | } |
| 490 | } |
| 491 | } |
| 492 | |
| 493 | // Drop any unclaimed caps. This mirrors the behavior of unix sockets, where if we didn't |
| 494 | // provide enough buffer space for all the written FDs, the remaining ones are lost. |
| 495 | capBuffer = {}; |
| 496 | |
| 497 | KJ_SWITCH_ONEOF(tryReadImpl(buffer, minBytes, maxBytes)) { |
| 498 | KJ_CASE_ONEOF(done, Done) { |
| 499 | return ReadResult { done.result, capCount }; |
| 500 | } |
| 501 | KJ_CASE_ONEOF(retry, Retry) { |
| 502 | return pipe.tryReadWithFds( |
| 503 | retry.buffer, retry.minBytes, retry.maxBytes, fdBuffer, maxFds) |
| 504 | .then([byteCount = retry.alreadyRead, capCount](ReadResult result) { |
| 505 | result.byteCount += byteCount; |
| 506 | result.capCount += capCount; |
| 507 | return result; |
| 508 | }); |
| 509 | } |
| 510 | } |
| 511 | KJ_UNREACHABLE; |
| 512 | } |
| 513 | |
| 514 | Promise<ReadResult> tryReadWithStreams( |
| 515 | void* buffer, size_t minBytes, size_t maxBytes, |
| 516 | Own<AsyncCapabilityStream>* streamBuffer, size_t maxStreams) override { |
| 517 | size_t capCount = 0; |
| 518 | { // TODO(cleanup): Remove redundant braces when we update to C++17. |
| 519 | KJ_SWITCH_ONEOF(capBuffer) { |
| 520 | KJ_CASE_ONEOF(fds, ArrayPtr<const int>) { |
| 521 | if (fds.size() > 0 && maxStreams > 0) { |
| 522 | // TODO(someday): Use AsyncIoStream's `Maybe<int> getFd()` method? |
| 523 | KJ_FAIL_REQUIRE( |
| 524 | "async pipe message was written with FDs attached, but corresponding read " |
| 525 | "asked for streams, and we don't know how to convert here"); |
| 526 | } |
| 527 | } |
| 528 | KJ_CASE_ONEOF(streams, Array<Own<AsyncCapabilityStream>>) { |
| 529 | capCount = kj::max(streams.size(), maxStreams); |
| 530 | for (auto i: kj::zeroTo(capCount)) { |
| 531 | streamBuffer[i] = kj::mv(streams[i]); |
| 532 | } |
| 533 | streamBuffer += capCount; |
| 534 | maxStreams -= capCount; |
| 535 | } |
| 536 | } |
| 537 | } |
| 538 | |
| 539 | // Drop any unclaimed caps. This mirrors the behavior of unix sockets, where if we didn't |
| 540 | // provide enough buffer space for all the written FDs, the remaining ones are lost. |
| 541 | capBuffer = {}; |
| 542 | |
| 543 | KJ_SWITCH_ONEOF(tryReadImpl(buffer, minBytes, maxBytes)) { |
| 544 | KJ_CASE_ONEOF(done, Done) { |
| 545 | return ReadResult { done.result, capCount }; |
| 546 | } |
| 547 | KJ_CASE_ONEOF(retry, Retry) { |
| 548 | return pipe.tryReadWithStreams( |
| 549 | retry.buffer, retry.minBytes, retry.maxBytes, streamBuffer, maxStreams) |
| 550 | .then([byteCount = retry.alreadyRead, capCount](ReadResult result) { |
| 551 | result.byteCount += byteCount; |
| 552 | result.capCount += capCount; |
| 553 | return result; |
| 554 | }); |
| 555 | } |
| 556 | } |
| 557 | KJ_UNREACHABLE; |
| 558 | } |
| 559 | |
| 560 | Promise<uint64_t> pumpTo(AsyncOutputStream& output, uint64_t amount) override { |
| 561 | // Note: Pumps drop all capabilities. |
| 562 | KJ_REQUIRE(canceler.isEmpty(), "already pumping"); |
| 563 | |
| 564 | if (amount < writeBuffer.size()) { |
| 565 | // Consume a portion of the write buffer. |
| 566 | return canceler.wrap(output.write(writeBuffer.begin(), amount) |
| 567 | .then([this,amount]() { |
| 568 | writeBuffer = writeBuffer.slice(amount, writeBuffer.size()); |
| 569 | // We pumped the full amount, so we're done pumping. |
| 570 | return amount; |
| 571 | }, teeExceptionSize(fulfiller))); |
| 572 | } |
| 573 | |
| 574 | // First piece doesn't cover the whole pump. Figure out how many more pieces to add. |
| 575 | uint64_t actual = writeBuffer.size(); |
| 576 | size_t i = 0; |
| 577 | while (i < morePieces.size() && |
| 578 | amount >= actual + morePieces[i].size()) { |
| 579 | actual += morePieces[i++].size(); |
| 580 | } |
| 581 | |
| 582 | // Write the first piece. |
| 583 | auto promise = output.write(writeBuffer.begin(), writeBuffer.size()); |
| 584 | |
| 585 | // Write full pieces as a single gather-write. |
| 586 | if (i > 0) { |
| 587 | auto more = morePieces.slice(0, i); |
| 588 | promise = promise.then([&output,more]() { return output.write(more); }); |
| 589 | } |
| 590 | |
| 591 | if (i == morePieces.size()) { |
| 592 | // This will complete the write. |
| 593 | return canceler.wrap(promise.then([this,&output,amount,actual]() -> Promise<uint64_t> { |
| 594 | canceler.release(); |
| 595 | fulfiller.fulfill(); |
| 596 | pipe.endState(*this); |
| 597 | |
| 598 | if (actual == amount) { |
| 599 | // Oh, we had exactly enough. |
| 600 | return actual; |
| 601 | } else { |
| 602 | return pipe.pumpTo(output, amount - actual) |
| 603 | .then([actual](uint64_t actual2) { return actual + actual2; }); |
| 604 | } |
| 605 | }, teeExceptionPromise<uint64_t>(fulfiller))); |
| 606 | } else { |
| 607 | // Pump ends mid-piece. Write the last, partial piece. |
| 608 | auto n = amount - actual; |
| 609 | auto splitPiece = morePieces[i]; |
| 610 | KJ_ASSERT(n <= splitPiece.size()); |
| 611 | auto newWriteBuffer = splitPiece.slice(n, splitPiece.size()); |
| 612 | auto newMorePieces = morePieces.slice(i + 1, morePieces.size()); |
| 613 | auto prefix = splitPiece.slice(0, n); |
| 614 | if (prefix.size() > 0) { |
| 615 | promise = promise.then([&output,prefix]() { |
| 616 | return output.write(prefix.begin(), prefix.size()); |
| 617 | }); |
| 618 | } |
| 619 | |
| 620 | return canceler.wrap(promise.then([this,newWriteBuffer,newMorePieces,amount]() { |
| 621 | writeBuffer = newWriteBuffer; |
| 622 | morePieces = newMorePieces; |
| 623 | canceler.release(); |
| 624 | return amount; |
| 625 | }, teeExceptionSize(fulfiller))); |
| 626 | } |
| 627 | } |
| 628 | |
| 629 | void abortRead() override { |
| 630 | canceler.cancel("abortRead() was called"); |
| 631 | fulfiller.reject(KJ_EXCEPTION(DISCONNECTED, "read end of pipe was aborted")); |
| 632 | pipe.endState(*this); |
| 633 | pipe.abortRead(); |
| 634 | } |
| 635 | |
| 636 | Promise<void> write(const void* buffer, size_t size) override { |
| 637 | KJ_FAIL_REQUIRE("can't write() again until previous write() completes"); |
| 638 | } |
| 639 | Promise<void> write(ArrayPtr<const ArrayPtr<const byte>> pieces) override { |
| 640 | KJ_FAIL_REQUIRE("can't write() again until previous write() completes"); |
| 641 | } |
| 642 | Promise<void> writeWithFds(ArrayPtr<const byte> data, |
| 643 | ArrayPtr<const ArrayPtr<const byte>> moreData, |
| 644 | ArrayPtr<const int> fds) override { |
| 645 | KJ_FAIL_REQUIRE("can't write() again until previous write() completes"); |
| 646 | } |
| 647 | Promise<void> writeWithStreams(ArrayPtr<const byte> data, |
| 648 | ArrayPtr<const ArrayPtr<const byte>> moreData, |
| 649 | Array<Own<AsyncCapabilityStream>> streams) override { |
| 650 | KJ_FAIL_REQUIRE("can't write() again until previous write() completes"); |
| 651 | } |
| 652 | Maybe<Promise<uint64_t>> tryPumpFrom(AsyncInputStream& input, uint64_t amount) override { |
| 653 | KJ_FAIL_REQUIRE("can't tryPumpFrom() again until previous write() completes"); |
| 654 | } |
| 655 | void shutdownWrite() override { |
| 656 | KJ_FAIL_REQUIRE("can't shutdownWrite() until previous write() completes"); |
| 657 | } |
| 658 | |
| 659 | Promise<void> whenWriteDisconnected() override { |
| 660 | KJ_FAIL_ASSERT("can't get here -- implemented by AsyncPipe"); |
| 661 | } |
| 662 | |
| 663 | private: |
| 664 | PromiseFulfiller<void>& fulfiller; |
| 665 | AsyncPipe& pipe; |
| 666 | ArrayPtr<const byte> writeBuffer; |
| 667 | ArrayPtr<const ArrayPtr<const byte>> morePieces; |
| 668 | kj::OneOf<ArrayPtr<const int>, Array<Own<AsyncCapabilityStream>>> capBuffer; |
| 669 | Canceler canceler; |
| 670 | |
| 671 | struct Done { size_t result; }; |
| 672 | struct Retry { void* buffer; size_t minBytes; size_t maxBytes; size_t alreadyRead; }; |
| 673 | |
| 674 | OneOf<Done, Retry> tryReadImpl(void* readBufferPtr, size_t minBytes, size_t maxBytes) { |
| 675 | KJ_REQUIRE(canceler.isEmpty(), "already pumping"); |
| 676 | |
| 677 | auto readBuffer = arrayPtr(reinterpret_cast<byte*>(readBufferPtr), maxBytes); |
| 678 | |
| 679 | size_t totalRead = 0; |
| 680 | while (readBuffer.size() >= writeBuffer.size()) { |
| 681 | // The whole current write buffer can be copied into the read buffer. |
| 682 | |
| 683 | { |
| 684 | auto n = writeBuffer.size(); |
| 685 | memcpy(readBuffer.begin(), writeBuffer.begin(), n); |
| 686 | totalRead += n; |
| 687 | readBuffer = readBuffer.slice(n, readBuffer.size()); |
| 688 | } |
| 689 | |
| 690 | if (morePieces.size() == 0) { |
| 691 | // All done writing. |
| 692 | fulfiller.fulfill(); |
| 693 | pipe.endState(*this); |
| 694 | |
| 695 | if (totalRead >= minBytes) { |
| 696 | // Also all done reading. |
| 697 | return Done { totalRead }; |
| 698 | } else { |
| 699 | return Retry { readBuffer.begin(), minBytes - totalRead, readBuffer.size(), totalRead }; |
| 700 | } |
| 701 | } |
| 702 | |
| 703 | writeBuffer = morePieces[0]; |
| 704 | morePieces = morePieces.slice(1, morePieces.size()); |
| 705 | } |
| 706 | |
| 707 | // At this point, the read buffer is smaller than the current write buffer, so we can fill |
| 708 | // it completely. |
| 709 | { |
| 710 | auto n = readBuffer.size(); |
| 711 | memcpy(readBuffer.begin(), writeBuffer.begin(), n); |
| 712 | writeBuffer = writeBuffer.slice(n, writeBuffer.size()); |
| 713 | totalRead += n; |
| 714 | } |
| 715 | |
| 716 | return Done { totalRead }; |
| 717 | } |
| 718 | }; |
| 719 | |
| 720 | class BlockedPumpFrom final: public AsyncCapabilityStream { |
| 721 | // AsyncPipe state when a tryPumpFrom() is currently waiting for a corresponding read(). |
| 722 | |
| 723 | public: |
| 724 | BlockedPumpFrom(PromiseFulfiller<uint64_t>& fulfiller, AsyncPipe& pipe, |
| 725 | AsyncInputStream& input, uint64_t amount) |
| 726 | : fulfiller(fulfiller), pipe(pipe), input(input), amount(amount) { |
| 727 | KJ_REQUIRE(pipe.state == nullptr); |
| 728 | pipe.state = *this; |
| 729 | } |
| 730 | |
| 731 | ~BlockedPumpFrom() noexcept(false) { |
| 732 | pipe.endState(*this); |
| 733 | } |
| 734 | |
| 735 | Promise<size_t> tryRead(void* readBuffer, size_t minBytes, size_t maxBytes) override { |
| 736 | KJ_REQUIRE(canceler.isEmpty(), "already pumping"); |
| 737 | |
| 738 | auto pumpLeft = amount - pumpedSoFar; |
| 739 | auto min = kj::min(pumpLeft, minBytes); |
| 740 | auto max = kj::min(pumpLeft, maxBytes); |
| 741 | return canceler.wrap(input.tryRead(readBuffer, min, max) |
| 742 | .then([this,readBuffer,minBytes,maxBytes,min](size_t actual) -> kj::Promise<size_t> { |
| 743 | canceler.release(); |
| 744 | pumpedSoFar += actual; |
| 745 | KJ_ASSERT(pumpedSoFar <= amount); |
| 746 | |
| 747 | if (pumpedSoFar == amount || actual < min) { |
| 748 | // Either we pumped all we wanted or we hit EOF. |
| 749 | fulfiller.fulfill(kj::cp(pumpedSoFar)); |
| 750 | pipe.endState(*this); |
| 751 | } |
| 752 | |
| 753 | if (actual >= minBytes) { |
| 754 | return actual; |
| 755 | } else { |
| 756 | return pipe.tryRead(reinterpret_cast<byte*>(readBuffer) + actual, |
| 757 | minBytes - actual, maxBytes - actual) |
| 758 | .then([actual](size_t actual2) { return actual + actual2; }); |
| 759 | } |
| 760 | }, teeExceptionPromise<size_t>(fulfiller))); |
| 761 | } |
| 762 | |
| 763 | Promise<ReadResult> tryReadWithFds(void* readBuffer, size_t minBytes, size_t maxBytes, |
| 764 | AutoCloseFd* fdBuffer, size_t maxFds) override { |
| 765 | // Pumps drop all capabilities, so fall back to regular read. (We don't even know if the |
| 766 | // destination is an AsyncCapabilityStream...) |
| 767 | return tryRead(readBuffer, minBytes, maxBytes) |
| 768 | .then([](size_t n) { return ReadResult { n, 0 }; }); |
| 769 | } |
| 770 | |
| 771 | Promise<ReadResult> tryReadWithStreams( |
| 772 | void* readBuffer, size_t minBytes, size_t maxBytes, |
| 773 | Own<AsyncCapabilityStream>* streamBuffer, size_t maxStreams) override { |
| 774 | // Pumps drop all capabilities, so fall back to regular read. (We don't even know if the |
| 775 | // destination is an AsyncCapabilityStream...) |
| 776 | return tryRead(readBuffer, minBytes, maxBytes) |
| 777 | .then([](size_t n) { return ReadResult { n, 0 }; }); |
| 778 | } |
| 779 | |
| 780 | Promise<uint64_t> pumpTo(AsyncOutputStream& output, uint64_t amount2) override { |
| 781 | KJ_REQUIRE(canceler.isEmpty(), "already pumping"); |
| 782 | |
| 783 | auto n = kj::min(amount2, amount - pumpedSoFar); |
| 784 | return canceler.wrap(input.pumpTo(output, n) |
| 785 | .then([this,&output,amount2,n](uint64_t actual) -> Promise<uint64_t> { |
| 786 | canceler.release(); |
| 787 | pumpedSoFar += actual; |
| 788 | KJ_ASSERT(pumpedSoFar <= amount); |
| 789 | if (pumpedSoFar == amount || actual < n) { |
| 790 | // Either we pumped all we wanted or we hit EOF. |
| 791 | fulfiller.fulfill(kj::cp(pumpedSoFar)); |
| 792 | pipe.endState(*this); |
| 793 | return pipe.pumpTo(output, amount2 - actual) |
| 794 | .then([actual](uint64_t actual2) { return actual + actual2; }); |
| 795 | } |
| 796 | |
| 797 | // Completed entire pumpTo amount. |
| 798 | KJ_ASSERT(actual == amount2); |
| 799 | return amount2; |
| 800 | }, teeExceptionSize(fulfiller))); |
| 801 | } |
| 802 | |
| 803 | void abortRead() override { |
| 804 | canceler.cancel("abortRead() was called"); |
| 805 | |
| 806 | // The input might have reached EOF, but we haven't detected it yet because we haven't tried |
| 807 | // to read that far. If we had not optimized tryPumpFrom() and instead used the default |
| 808 | // pumpTo() implementation, then the input would not have called write() again once it |
| 809 | // reached EOF, and therefore the abortRead() on the other end would *not* propagate an |
| 810 | // exception! We need the same behavior here. To that end, we need to detect if we're at EOF |
| 811 | // by reading one last byte. |
| 812 | checkEofTask = kj::evalNow([&]() { |
| 813 | static char junk; |
| 814 | return input.tryRead(&junk, 1, 1).then([this](uint64_t n) { |
| 815 | if (n == 0) { |
| 816 | fulfiller.fulfill(kj::cp(pumpedSoFar)); |
| 817 | } else { |
| 818 | fulfiller.reject(KJ_EXCEPTION(DISCONNECTED, "read end of pipe was aborted")); |
| 819 | } |
| 820 | }).eagerlyEvaluate([this](kj::Exception&& e) { |
| 821 | fulfiller.reject(kj::mv(e)); |
| 822 | }); |
| 823 | }); |
| 824 | |
| 825 | pipe.endState(*this); |
| 826 | pipe.abortRead(); |
| 827 | } |
| 828 | |
| 829 | Promise<void> write(const void* buffer, size_t size) override { |
| 830 | KJ_FAIL_REQUIRE("can't write() again until previous tryPumpFrom() completes"); |
| 831 | } |
| 832 | Promise<void> write(ArrayPtr<const ArrayPtr<const byte>> pieces) override { |
| 833 | KJ_FAIL_REQUIRE("can't write() again until previous tryPumpFrom() completes"); |
| 834 | } |
| 835 | Promise<void> writeWithFds(ArrayPtr<const byte> data, |
| 836 | ArrayPtr<const ArrayPtr<const byte>> moreData, |
| 837 | ArrayPtr<const int> fds) override { |
| 838 | KJ_FAIL_REQUIRE("can't write() again until previous tryPumpFrom() completes"); |
| 839 | } |
| 840 | Promise<void> writeWithStreams(ArrayPtr<const byte> data, |
| 841 | ArrayPtr<const ArrayPtr<const byte>> moreData, |
| 842 | Array<Own<AsyncCapabilityStream>> streams) override { |
| 843 | KJ_FAIL_REQUIRE("can't write() again until previous tryPumpFrom() completes"); |
| 844 | } |
| 845 | Maybe<Promise<uint64_t>> tryPumpFrom(AsyncInputStream& input, uint64_t amount) override { |
| 846 | KJ_FAIL_REQUIRE("can't tryPumpFrom() again until previous tryPumpFrom() completes"); |
| 847 | } |
| 848 | void shutdownWrite() override { |
| 849 | KJ_FAIL_REQUIRE("can't shutdownWrite() until previous tryPumpFrom() completes"); |
| 850 | } |
| 851 | |
| 852 | Promise<void> whenWriteDisconnected() override { |
| 853 | KJ_FAIL_ASSERT("can't get here -- implemented by AsyncPipe"); |
| 854 | } |
| 855 | |
| 856 | private: |
| 857 | PromiseFulfiller<uint64_t>& fulfiller; |
| 858 | AsyncPipe& pipe; |
| 859 | AsyncInputStream& input; |
| 860 | uint64_t amount; |
| 861 | uint64_t pumpedSoFar = 0; |
| 862 | Canceler canceler; |
| 863 | kj::Promise<void> checkEofTask = nullptr; |
| 864 | }; |
| 865 | |
| 866 | class BlockedRead final: public AsyncCapabilityStream { |
| 867 | // AsyncPipe state when a tryRead() is currently waiting for a corresponding write(). |
| 868 | |
| 869 | public: |
| 870 | BlockedRead( |
| 871 | PromiseFulfiller<ReadResult>& fulfiller, AsyncPipe& pipe, |
| 872 | ArrayPtr<byte> readBuffer, size_t minBytes, |
| 873 | kj::OneOf<ArrayPtr<AutoCloseFd>, ArrayPtr<Own<AsyncCapabilityStream>>> capBuffer = {}) |
| 874 | : fulfiller(fulfiller), pipe(pipe), readBuffer(readBuffer), minBytes(minBytes), |
| 875 | capBuffer(capBuffer) { |
| 876 | KJ_REQUIRE(pipe.state == nullptr); |
| 877 | pipe.state = *this; |
| 878 | } |
| 879 | |
| 880 | ~BlockedRead() noexcept(false) { |
| 881 | pipe.endState(*this); |
| 882 | } |
| 883 | |
| 884 | Promise<size_t> tryRead(void* readBuffer, size_t minBytes, size_t maxBytes) override { |
| 885 | KJ_FAIL_REQUIRE("can't read() again until previous read() completes"); |
| 886 | } |
| 887 | Promise<ReadResult> tryReadWithFds(void* readBuffer, size_t minBytes, size_t maxBytes, |
| 888 | AutoCloseFd* fdBuffer, size_t maxFds) override { |
| 889 | KJ_FAIL_REQUIRE("can't read() again until previous read() completes"); |
| 890 | } |
| 891 | Promise<ReadResult> tryReadWithStreams( |
| 892 | void* readBuffer, size_t minBytes, size_t maxBytes, |
| 893 | Own<AsyncCapabilityStream>* streamBuffer, size_t maxStreams) override { |
| 894 | KJ_FAIL_REQUIRE("can't read() again until previous read() completes"); |
| 895 | } |
| 896 | Promise<uint64_t> pumpTo(AsyncOutputStream& output, uint64_t amount) override { |
| 897 | KJ_FAIL_REQUIRE("can't read() again until previous read() completes"); |
| 898 | } |
| 899 | |
| 900 | void abortRead() override { |
| 901 | canceler.cancel("abortRead() was called"); |
| 902 | fulfiller.reject(KJ_EXCEPTION(DISCONNECTED, "read end of pipe was aborted")); |
| 903 | pipe.endState(*this); |
| 904 | pipe.abortRead(); |
| 905 | } |
| 906 | |
| 907 | Promise<void> write(const void* writeBuffer, size_t size) override { |
| 908 | KJ_REQUIRE(canceler.isEmpty(), "already pumping"); |
| 909 | |
| 910 | auto data = arrayPtr(reinterpret_cast<const byte*>(writeBuffer), size); |
| 911 | KJ_SWITCH_ONEOF(writeImpl(data, nullptr)) { |
| 912 | KJ_CASE_ONEOF(done, Done) { |
| 913 | return READY_NOW; |
| 914 | } |
| 915 | KJ_CASE_ONEOF(retry, Retry) { |
| 916 | KJ_ASSERT(retry.moreData == nullptr); |
| 917 | return pipe.write(retry.data.begin(), retry.data.size()); |
| 918 | } |
| 919 | } |
| 920 | KJ_UNREACHABLE; |
| 921 | } |
| 922 | |
| 923 | Promise<void> write(ArrayPtr<const ArrayPtr<const byte>> pieces) override { |
| 924 | KJ_REQUIRE(canceler.isEmpty(), "already pumping"); |
| 925 | |
| 926 | KJ_SWITCH_ONEOF(writeImpl(pieces[0], pieces.slice(1, pieces.size()))) { |
| 927 | KJ_CASE_ONEOF(done, Done) { |
| 928 | return READY_NOW; |
| 929 | } |
| 930 | KJ_CASE_ONEOF(retry, Retry) { |
| 931 | if (retry.data.size() == 0) { |
| 932 | // We exactly finished the current piece, so just issue a write for the remaining |
| 933 | // pieces. |
| 934 | if (retry.moreData.size() == 0) { |
| 935 | // Nothing left. |
| 936 | return READY_NOW; |
| 937 | } else { |
| 938 | // Write remaining pieces. |
| 939 | return pipe.write(retry.moreData); |
| 940 | } |
| 941 | } else { |
| 942 | // Unfortunately we have to execute a separate write() for the remaining part of this |
| 943 | // piece, because we can't modify the pieces array. |
| 944 | auto promise = pipe.write(retry.data.begin(), retry.data.size()); |
| 945 | if (retry.moreData.size() == 0) { |
| 946 | // No more pieces so that's it. |
| 947 | return kj::mv(promise); |
| 948 | } else { |
| 949 | // Also need to write the remaining pieces. |
| 950 | auto& pipeRef = pipe; |
| 951 | return promise.then([pieces=retry.moreData,&pipeRef]() { |
| 952 | return pipeRef.write(pieces); |
| 953 | }); |
| 954 | } |
| 955 | } |
| 956 | } |
| 957 | } |
| 958 | KJ_UNREACHABLE; |
| 959 | } |
| 960 | |
| 961 | Promise<void> writeWithFds(ArrayPtr<const byte> data, |
| 962 | ArrayPtr<const ArrayPtr<const byte>> moreData, |
| 963 | ArrayPtr<const int> fds) override { |
| 964 | #if __GNUC__ && !__clang__ && __GNUC__ >= 7 |
| 965 | // GCC 7 decides the open-brace below is "misleadingly indented" as if it were guarded by the `for` |
| 966 | // that appears in the implementation of KJ_REQUIRE(). Shut up shut up shut up. |
| 967 | #pragma GCC diagnostic ignored "-Wmisleading-indentation" |
| 968 | #endif |
| 969 | KJ_REQUIRE(canceler.isEmpty(), "already pumping"); |
| 970 | |
| 971 | { // TODO(cleanup): Remove redundant braces when we update to C++17. |
| 972 | KJ_SWITCH_ONEOF(capBuffer) { |
| 973 | KJ_CASE_ONEOF(fdBuffer, ArrayPtr<AutoCloseFd>) { |
| 974 | size_t count = kj::max(fdBuffer.size(), fds.size()); |
| 975 | // Unfortunately, we have to dup() each FD, because the writer doesn't release ownership |
| 976 | // by default. |
| 977 | // TODO(perf): Should we add an ownership-releasing version of writeWithFds()? |
| 978 | for (auto i: kj::zeroTo(count)) { |
| 979 | int duped; |
| 980 | KJ_SYSCALL(duped = dup(fds[i])); |
| 981 | fdBuffer[i] = kj::AutoCloseFd(duped); |
| 982 | } |
| 983 | capBuffer = fdBuffer.slice(count, fdBuffer.size()); |
| 984 | readSoFar.capCount += count; |
| 985 | } |
| 986 | KJ_CASE_ONEOF(streamBuffer, ArrayPtr<Own<AsyncCapabilityStream>>) { |
| 987 | if (streamBuffer.size() > 0 && fds.size() > 0) { |
| 988 | // TODO(someday): Use AsyncIoStream's `Maybe<int> getFd()` method? |
| 989 | KJ_FAIL_REQUIRE( |
| 990 | "async pipe message was written with FDs attached, but corresponding read " |
| 991 | "asked for streams, and we don't know how to convert here"); |
| 992 | } |
| 993 | } |
| 994 | } |
| 995 | } |
| 996 | |
| 997 | KJ_SWITCH_ONEOF(writeImpl(data, moreData)) { |
| 998 | KJ_CASE_ONEOF(done, Done) { |
| 999 | return READY_NOW; |
| 1000 | } |
| 1001 | KJ_CASE_ONEOF(retry, Retry) { |
| 1002 | // Any leftover fds in `fds` are dropped on the floor, per contract. |
| 1003 | // TODO(cleanup): We use another writeWithFds() call here only because it accepts `data` |
| 1004 | // and `moreData` directly. After the stream API refactor, we should be able to avoid |
| 1005 | // this. |
| 1006 | return pipe.writeWithFds(retry.data, retry.moreData, nullptr); |
| 1007 | } |
| 1008 | } |
| 1009 | KJ_UNREACHABLE; |
| 1010 | } |
| 1011 | |
| 1012 | Promise<void> writeWithStreams(ArrayPtr<const byte> data, |
| 1013 | ArrayPtr<const ArrayPtr<const byte>> moreData, |
| 1014 | Array<Own<AsyncCapabilityStream>> streams) override { |
| 1015 | KJ_REQUIRE(canceler.isEmpty(), "already pumping"); |
| 1016 | |
| 1017 | { // TODO(cleanup): Remove redundant braces when we update to C++17. |
| 1018 | KJ_SWITCH_ONEOF(capBuffer) { |
| 1019 | KJ_CASE_ONEOF(fdBuffer, ArrayPtr<AutoCloseFd>) { |
| 1020 | if (fdBuffer.size() > 0 && streams.size() > 0) { |
| 1021 | // TODO(someday): We could let people pass a LowLevelAsyncIoProvider to newTwoWayPipe() |
| 1022 | // if we wanted to auto-wrap FDs, but does anyone care? |
| 1023 | KJ_FAIL_REQUIRE( |
| 1024 | "async pipe message was written with streams attached, but corresponding read " |
| 1025 | "asked for FDs, and we don't know how to convert here"); |
| 1026 | } |
| 1027 | } |
| 1028 | KJ_CASE_ONEOF(streamBuffer, ArrayPtr<Own<AsyncCapabilityStream>>) { |
| 1029 | size_t count = kj::max(streamBuffer.size(), streams.size()); |
| 1030 | for (auto i: kj::zeroTo(count)) { |
| 1031 | streamBuffer[i] = kj::mv(streams[i]); |
| 1032 | } |
| 1033 | capBuffer = streamBuffer.slice(count, streamBuffer.size()); |
| 1034 | readSoFar.capCount += count; |
| 1035 | } |
| 1036 | } |
| 1037 | } |
| 1038 | |
| 1039 | KJ_SWITCH_ONEOF(writeImpl(data, moreData)) { |
| 1040 | KJ_CASE_ONEOF(done, Done) { |
| 1041 | return READY_NOW; |
| 1042 | } |
| 1043 | KJ_CASE_ONEOF(retry, Retry) { |
| 1044 | // Any leftover fds in `fds` are dropped on the floor, per contract. |
| 1045 | // TODO(cleanup): We use another writeWithStreams() call here only because it accepts |
| 1046 | // `data` and `moreData` directly. After the stream API refactor, we should be able to |
| 1047 | // avoid this. |
| 1048 | return pipe.writeWithStreams(retry.data, retry.moreData, nullptr); |
| 1049 | } |
| 1050 | } |
| 1051 | KJ_UNREACHABLE; |
| 1052 | } |
| 1053 | |
| 1054 | Maybe<Promise<uint64_t>> tryPumpFrom(AsyncInputStream& input, uint64_t amount) override { |
| 1055 | // Note: Pumps drop all capabilities. |
| 1056 | KJ_REQUIRE(canceler.isEmpty(), "already pumping"); |
| 1057 | |
| 1058 | KJ_ASSERT(minBytes > readSoFar.byteCount); |
| 1059 | auto minToRead = kj::min(amount, minBytes - readSoFar.byteCount); |
| 1060 | auto maxToRead = kj::min(amount, readBuffer.size()); |
| 1061 | |
| 1062 | return canceler.wrap(input.tryRead(readBuffer.begin(), minToRead, maxToRead) |
| 1063 | .then([this,&input,amount](size_t actual) -> Promise<uint64_t> { |
| 1064 | readBuffer = readBuffer.slice(actual, readBuffer.size()); |
| 1065 | readSoFar.byteCount += actual; |
| 1066 | |
| 1067 | if (readSoFar.byteCount >= minBytes) { |
| 1068 | // We've read enough to close out this read (readSoFar >= minBytes). |
| 1069 | canceler.release(); |
| 1070 | fulfiller.fulfill(kj::cp(readSoFar)); |
| 1071 | pipe.endState(*this); |
| 1072 | |
| 1073 | if (actual < amount) { |
| 1074 | // We didn't read as much data as the pump requested, but we did fulfill the read, so |
| 1075 | // we don't know whether we reached EOF on the input. We need to continue the pump, |
| 1076 | // replacing the BlockedRead state. |
| 1077 | return input.pumpTo(pipe, amount - actual) |
| 1078 | .then([actual](uint64_t actual2) -> uint64_t { return actual + actual2; }); |
| 1079 | } else { |
| 1080 | // We pumped as much data as was requested, so we can return that now. |
| 1081 | return actual; |
| 1082 | } |
| 1083 | } else { |
| 1084 | // The pump completed without fulfilling the read. This either means that the pump |
| 1085 | // reached EOF or the `amount` requested was not enough to satisfy the read in the first |
| 1086 | // place. Pumps do not propagate EOF, so either way we want to leave the BlockedRead in |
| 1087 | // place waiting for more data. |
| 1088 | return actual; |
| 1089 | } |
| 1090 | }, teeExceptionPromise<uint64_t>(fulfiller))); |
| 1091 | } |
| 1092 | |
| 1093 | void shutdownWrite() override { |
| 1094 | canceler.cancel("shutdownWrite() was called"); |
| 1095 | fulfiller.fulfill(kj::cp(readSoFar)); |
| 1096 | pipe.endState(*this); |
| 1097 | pipe.shutdownWrite(); |
| 1098 | } |
| 1099 | |
| 1100 | Promise<void> whenWriteDisconnected() override { |
| 1101 | KJ_FAIL_ASSERT("can't get here -- implemented by AsyncPipe"); |
| 1102 | } |
| 1103 | |
| 1104 | private: |
| 1105 | PromiseFulfiller<ReadResult>& fulfiller; |
| 1106 | AsyncPipe& pipe; |
| 1107 | ArrayPtr<byte> readBuffer; |
| 1108 | size_t minBytes; |
| 1109 | kj::OneOf<ArrayPtr<AutoCloseFd>, ArrayPtr<Own<AsyncCapabilityStream>>> capBuffer; |
| 1110 | ReadResult readSoFar = {0, 0}; |
| 1111 | Canceler canceler; |
| 1112 | |
| 1113 | struct Done {}; |
| 1114 | struct Retry { ArrayPtr<const byte> data; ArrayPtr<const ArrayPtr<const byte>> moreData; }; |
| 1115 | |
| 1116 | OneOf<Done, Retry> writeImpl(ArrayPtr<const byte> data, |
| 1117 | ArrayPtr<const ArrayPtr<const byte>> moreData) { |
| 1118 | for (;;) { |
| 1119 | if (data.size() < readBuffer.size()) { |
| 1120 | // First write segment consumes a portion of the read buffer but not all of it. |
| 1121 | auto n = data.size(); |
| 1122 | memcpy(readBuffer.begin(), data.begin(), n); |
| 1123 | readSoFar.byteCount += n; |
| 1124 | readBuffer = readBuffer.slice(n, readBuffer.size()); |
| 1125 | if (moreData.size() == 0) { |
| 1126 | // Consumed all written pieces. |
| 1127 | if (readSoFar.byteCount >= minBytes) { |
| 1128 | // We've read enough to close out this read. |
| 1129 | fulfiller.fulfill(kj::cp(readSoFar)); |
| 1130 | pipe.endState(*this); |
| 1131 | } |
| 1132 | return Done(); |
| 1133 | } |
| 1134 | data = moreData[0]; |
| 1135 | moreData = moreData.slice(1, moreData.size()); |
| 1136 | // loop |
| 1137 | } else { |
| 1138 | // First write segment consumes entire read buffer. |
| 1139 | auto n = readBuffer.size(); |
| 1140 | readSoFar.byteCount += n; |
| 1141 | fulfiller.fulfill(kj::cp(readSoFar)); |
| 1142 | pipe.endState(*this); |
| 1143 | memcpy(readBuffer.begin(), data.begin(), n); |
| 1144 | |
| 1145 | data = data.slice(n, data.size()); |
| 1146 | if (data.size() == 0 && moreData.size() == 0) { |
| 1147 | return Done(); |
| 1148 | } else { |
| 1149 | // Note: Even if `data` is empty, we don't replace it with moreData[0], because the |
| 1150 | // retry might need to use write(ArrayPtr<ArrayPtr<byte>>) which doesn't allow |
| 1151 | // passing a separate first segment. |
| 1152 | return Retry { data, moreData }; |
| 1153 | } |
| 1154 | } |
| 1155 | } |
| 1156 | } |
| 1157 | }; |
| 1158 | |
| 1159 | class BlockedPumpTo final: public AsyncCapabilityStream { |
| 1160 | // AsyncPipe state when a pumpTo() is currently waiting for a corresponding write(). |
| 1161 | |
| 1162 | public: |
| 1163 | BlockedPumpTo(PromiseFulfiller<uint64_t>& fulfiller, AsyncPipe& pipe, |
| 1164 | AsyncOutputStream& output, uint64_t amount) |
| 1165 | : fulfiller(fulfiller), pipe(pipe), output(output), amount(amount) { |
| 1166 | KJ_REQUIRE(pipe.state == nullptr); |
| 1167 | pipe.state = *this; |
| 1168 | } |
| 1169 | |
| 1170 | ~BlockedPumpTo() noexcept(false) { |
| 1171 | pipe.endState(*this); |
| 1172 | } |
| 1173 | |
| 1174 | Promise<size_t> tryRead(void* readBuffer, size_t minBytes, size_t maxBytes) override { |
| 1175 | KJ_FAIL_REQUIRE("can't read() again until previous pumpTo() completes"); |
| 1176 | } |
| 1177 | Promise<ReadResult> tryReadWithFds(void* readBuffer, size_t minBytes, size_t maxBytes, |
| 1178 | AutoCloseFd* fdBuffer, size_t maxFds) override { |
| 1179 | KJ_FAIL_REQUIRE("can't read() again until previous pumpTo() completes"); |
| 1180 | } |
| 1181 | Promise<ReadResult> tryReadWithStreams( |
| 1182 | void* readBuffer, size_t minBytes, size_t maxBytes, |
| 1183 | Own<AsyncCapabilityStream>* streamBuffer, size_t maxStreams) override { |
| 1184 | KJ_FAIL_REQUIRE("can't read() again until previous pumpTo() completes"); |
| 1185 | } |
| 1186 | Promise<uint64_t> pumpTo(AsyncOutputStream& output, uint64_t amount) override { |
| 1187 | KJ_FAIL_REQUIRE("can't read() again until previous pumpTo() completes"); |
| 1188 | } |
| 1189 | |
| 1190 | void abortRead() override { |
| 1191 | canceler.cancel("abortRead() was called"); |
| 1192 | fulfiller.reject(KJ_EXCEPTION(DISCONNECTED, "read end of pipe was aborted")); |
| 1193 | pipe.endState(*this); |
| 1194 | pipe.abortRead(); |
| 1195 | } |
| 1196 | |
| 1197 | Promise<void> write(const void* writeBuffer, size_t size) override { |
| 1198 | KJ_REQUIRE(canceler.isEmpty(), "already pumping"); |
| 1199 | |
| 1200 | auto actual = kj::min(amount - pumpedSoFar, size); |
| 1201 | return canceler.wrap(output.write(writeBuffer, actual) |
| 1202 | .then([this,size,actual,writeBuffer]() -> kj::Promise<void> { |
| 1203 | canceler.release(); |
| 1204 | pumpedSoFar += actual; |
| 1205 | |
| 1206 | KJ_ASSERT(pumpedSoFar <= amount); |
| 1207 | KJ_ASSERT(actual <= size); |
| 1208 | |
| 1209 | if (pumpedSoFar == amount) { |
| 1210 | // Done with pump. |
| 1211 | fulfiller.fulfill(kj::cp(pumpedSoFar)); |
| 1212 | pipe.endState(*this); |
| 1213 | } |
| 1214 | |
| 1215 | if (actual == size) { |
| 1216 | return kj::READY_NOW; |
| 1217 | } else { |
| 1218 | KJ_ASSERT(pumpedSoFar == amount); |
| 1219 | return pipe.write(reinterpret_cast<const byte*>(writeBuffer) + actual, size - actual); |
| 1220 | } |
| 1221 | }, teeExceptionPromise<void>(fulfiller))); |
| 1222 | } |
| 1223 | |
| 1224 | Promise<void> write(ArrayPtr<const ArrayPtr<const byte>> pieces) override { |
| 1225 | KJ_REQUIRE(canceler.isEmpty(), "already pumping"); |
| 1226 | |
| 1227 | size_t size = 0; |
| 1228 | size_t needed = amount - pumpedSoFar; |
| 1229 | for (auto i: kj::indices(pieces)) { |
| 1230 | if (pieces[i].size() > needed) { |
| 1231 | // The pump ends in the middle of this write. |
| 1232 | |
| 1233 | auto promise = output.write(pieces.slice(0, i)); |
| 1234 | |
| 1235 | if (needed > 0) { |
| 1236 | // The pump includes part of this piece, but not all. Unfortunately we need to split |
| 1237 | // writes. |
| 1238 | auto partial = pieces[i].slice(0, needed); |
| 1239 | promise = promise.then([this,partial]() { |
| 1240 | return output.write(partial.begin(), partial.size()); |
| 1241 | }); |
| 1242 | auto partial2 = pieces[i].slice(needed, pieces[i].size()); |
| 1243 | promise = canceler.wrap(promise.then([this,partial2]() { |
| 1244 | canceler.release(); |
| 1245 | fulfiller.fulfill(kj::cp(amount)); |
| 1246 | pipe.endState(*this); |
| 1247 | return pipe.write(partial2.begin(), partial2.size()); |
| 1248 | }, teeExceptionPromise<void>(fulfiller))); |
| 1249 | ++i; |
| 1250 | } else { |
| 1251 | // The pump ends exactly at the end of a piece, how nice. |
| 1252 | promise = canceler.wrap(promise.then([this]() { |
| 1253 | canceler.release(); |
| 1254 | fulfiller.fulfill(kj::cp(amount)); |
| 1255 | pipe.endState(*this); |
| 1256 | }, teeExceptionVoid(fulfiller))); |
| 1257 | } |
| 1258 | |
| 1259 | auto remainder = pieces.slice(i, pieces.size()); |
| 1260 | if (remainder.size() > 0) { |
| 1261 | auto& pipeRef = pipe; |
| 1262 | promise = promise.then([&pipeRef,remainder]() { |
| 1263 | return pipeRef.write(remainder); |
| 1264 | }); |
| 1265 | } |
| 1266 | |
| 1267 | return promise; |
| 1268 | } else { |
| 1269 | size += pieces[i].size(); |
| 1270 | needed -= pieces[i].size(); |
| 1271 | } |
| 1272 | } |
| 1273 | |
| 1274 | // Turns out we can forward this whole write. |
| 1275 | KJ_ASSERT(size <= amount - pumpedSoFar); |
| 1276 | return canceler.wrap(output.write(pieces).then([this,size]() { |
| 1277 | pumpedSoFar += size; |
| 1278 | KJ_ASSERT(pumpedSoFar <= amount); |
| 1279 | if (pumpedSoFar == amount) { |
| 1280 | // Done pumping. |
| 1281 | canceler.release(); |
| 1282 | fulfiller.fulfill(kj::cp(amount)); |
| 1283 | pipe.endState(*this); |
| 1284 | } |
| 1285 | }, teeExceptionVoid(fulfiller))); |
| 1286 | } |
| 1287 | |
| 1288 | Promise<void> writeWithFds(ArrayPtr<const byte> data, |
| 1289 | ArrayPtr<const ArrayPtr<const byte>> moreData, |
| 1290 | ArrayPtr<const int> fds) override { |
| 1291 | // Pumps drop all capabilities, so fall back to regular write(). |
| 1292 | |
| 1293 | // TODO(cleaunp): After stream API refactor, regular write() methods will take |
| 1294 | // (data, moreData) and we can clean this up. |
| 1295 | if (moreData.size() == 0) { |
| 1296 | return write(data.begin(), data.size()); |
| 1297 | } else { |
| 1298 | auto pieces = kj::heapArrayBuilder<const ArrayPtr<const byte>>(moreData.size() + 1); |
| 1299 | pieces.add(data); |
| 1300 | pieces.addAll(moreData); |
| 1301 | return write(pieces.finish()); |
| 1302 | } |
| 1303 | } |
| 1304 | |
| 1305 | Promise<void> writeWithStreams(ArrayPtr<const byte> data, |
| 1306 | ArrayPtr<const ArrayPtr<const byte>> moreData, |
| 1307 | Array<Own<AsyncCapabilityStream>> streams) override { |
| 1308 | // Pumps drop all capabilities, so fall back to regular write(). |
| 1309 | |
| 1310 | // TODO(cleaunp): After stream API refactor, regular write() methods will take |
| 1311 | // (data, moreData) and we can clean this up. |
| 1312 | if (moreData.size() == 0) { |
| 1313 | return write(data.begin(), data.size()); |
| 1314 | } else { |
| 1315 | auto pieces = kj::heapArrayBuilder<const ArrayPtr<const byte>>(moreData.size() + 1); |
| 1316 | pieces.add(data); |
| 1317 | pieces.addAll(moreData); |
| 1318 | return write(pieces.finish()); |
| 1319 | } |
| 1320 | } |
| 1321 | |
| 1322 | Maybe<Promise<uint64_t>> tryPumpFrom(AsyncInputStream& input, uint64_t amount2) override { |
| 1323 | KJ_REQUIRE(canceler.isEmpty(), "already pumping"); |
| 1324 | |
| 1325 | auto n = kj::min(amount2, amount - pumpedSoFar); |
| 1326 | return output.tryPumpFrom(input, n) |
| 1327 | .map([&](Promise<uint64_t> subPump) { |
| 1328 | return canceler.wrap(subPump |
| 1329 | .then([this,&input,amount2,n](uint64_t actual) -> Promise<uint64_t> { |
| 1330 | canceler.release(); |
| 1331 | pumpedSoFar += actual; |
| 1332 | KJ_ASSERT(pumpedSoFar <= amount); |
| 1333 | if (pumpedSoFar == amount) { |
| 1334 | fulfiller.fulfill(kj::cp(amount)); |
| 1335 | pipe.endState(*this); |
| 1336 | } |
| 1337 | |
| 1338 | KJ_ASSERT(actual <= amount2); |
| 1339 | if (actual == amount2) { |
| 1340 | // Completed entire tryPumpFrom amount. |
| 1341 | return amount2; |
| 1342 | } else if (actual < n) { |
| 1343 | // Received less than requested, presumably because EOF. |
| 1344 | return actual; |
| 1345 | } else { |
| 1346 | // We received all the bytes that were requested but it didn't complete the pump. |
| 1347 | KJ_ASSERT(pumpedSoFar == amount); |
| 1348 | return input.pumpTo(pipe, amount2 - actual); |
| 1349 | } |
| 1350 | }, teeExceptionPromise<uint64_t>(fulfiller))); |
| 1351 | }); |
| 1352 | } |
| 1353 | |
| 1354 | void shutdownWrite() override { |
| 1355 | canceler.cancel("shutdownWrite() was called"); |
| 1356 | fulfiller.fulfill(kj::cp(pumpedSoFar)); |
| 1357 | pipe.endState(*this); |
| 1358 | pipe.shutdownWrite(); |
| 1359 | } |
| 1360 | |
| 1361 | Promise<void> whenWriteDisconnected() override { |
| 1362 | KJ_FAIL_ASSERT("can't get here -- implemented by AsyncPipe"); |
| 1363 | } |
| 1364 | |
| 1365 | private: |
| 1366 | PromiseFulfiller<uint64_t>& fulfiller; |
| 1367 | AsyncPipe& pipe; |
| 1368 | AsyncOutputStream& output; |
| 1369 | uint64_t amount; |
| 1370 | size_t pumpedSoFar = 0; |
| 1371 | Canceler canceler; |
| 1372 | }; |
| 1373 | |
| 1374 | class AbortedRead final: public AsyncCapabilityStream { |
| 1375 | // AsyncPipe state when abortRead() has been called. |
| 1376 | |
| 1377 | public: |
| 1378 | Promise<size_t> tryRead(void* readBufferPtr, size_t minBytes, size_t maxBytes) override { |
| 1379 | return KJ_EXCEPTION(DISCONNECTED, "abortRead() has been called"); |
| 1380 | } |
| 1381 | Promise<ReadResult> tryReadWithFds(void* readBuffer, size_t minBytes, size_t maxBytes, |
| 1382 | AutoCloseFd* fdBuffer, size_t maxFds) override { |
| 1383 | return KJ_EXCEPTION(DISCONNECTED, "abortRead() has been called"); |
| 1384 | } |
| 1385 | Promise<ReadResult> tryReadWithStreams( |
| 1386 | void* readBuffer, size_t minBytes, size_t maxBytes, |
| 1387 | Own<AsyncCapabilityStream>* streamBuffer, size_t maxStreams) override { |
| 1388 | return KJ_EXCEPTION(DISCONNECTED, "abortRead() has been called"); |
| 1389 | } |
| 1390 | Promise<uint64_t> pumpTo(AsyncOutputStream& output, uint64_t amount) override { |
| 1391 | return KJ_EXCEPTION(DISCONNECTED, "abortRead() has been called"); |
| 1392 | } |
| 1393 | void abortRead() override { |
| 1394 | // ignore repeated abort |
| 1395 | } |
| 1396 | |
| 1397 | Promise<void> write(const void* buffer, size_t size) override { |
| 1398 | return KJ_EXCEPTION(DISCONNECTED, "abortRead() has been called"); |
| 1399 | } |
| 1400 | Promise<void> write(ArrayPtr<const ArrayPtr<const byte>> pieces) override { |
| 1401 | return KJ_EXCEPTION(DISCONNECTED, "abortRead() has been called"); |
| 1402 | } |
| 1403 | Promise<void> writeWithFds(ArrayPtr<const byte> data, |
| 1404 | ArrayPtr<const ArrayPtr<const byte>> moreData, |
| 1405 | ArrayPtr<const int> fds) override { |
| 1406 | return KJ_EXCEPTION(DISCONNECTED, "abortRead() has been called"); |
| 1407 | } |
| 1408 | Promise<void> writeWithStreams(ArrayPtr<const byte> data, |
| 1409 | ArrayPtr<const ArrayPtr<const byte>> moreData, |
| 1410 | Array<Own<AsyncCapabilityStream>> streams) override { |
| 1411 | return KJ_EXCEPTION(DISCONNECTED, "abortRead() has been called"); |
| 1412 | } |
| 1413 | Maybe<Promise<uint64_t>> tryPumpFrom(AsyncInputStream& input, uint64_t amount) override { |
| 1414 | // There might not actually be any data in `input`, in which case a pump wouldn't actually |
| 1415 | // write anything and wouldn't fail. |
| 1416 | |
| 1417 | if (input.tryGetLength().orDefault(1) == 0) { |
| 1418 | // Yeah a pump would pump nothing. |
| 1419 | return constPromise<uint64_t, 0>(); |
| 1420 | } else { |
| 1421 | // While we *could* just return nullptr here, it would probably then fall back to a normal |
| 1422 | // buffered pump, which would allocate a big old buffer just to find there's nothing to |
| 1423 | // read. Let's try reading 1 byte to avoid that allocation. |
| 1424 | static char c; |
| 1425 | return input.tryRead(&c, 1, 1).then([](size_t n) { |
| 1426 | if (n == 0) { |
| 1427 | // Yay, we're at EOF as hoped. |
| 1428 | return uint64_t(0); |
| 1429 | } else { |
| 1430 | // There was data in the input. The pump would have thrown. |
| 1431 | kj::throwRecoverableException( |
| 1432 | KJ_EXCEPTION(DISCONNECTED, "abortRead() has been called")); |
| 1433 | return uint64_t(0); |
| 1434 | } |
| 1435 | }); |
| 1436 | } |
| 1437 | } |
| 1438 | void shutdownWrite() override { |
| 1439 | // ignore -- currently shutdownWrite() actually means that the PipeWriteEnd was dropped, |
| 1440 | // which is not an error even if reads have been aborted. |
| 1441 | } |
| 1442 | Promise<void> whenWriteDisconnected() override { |
| 1443 | KJ_FAIL_ASSERT("can't get here -- implemented by AsyncPipe"); |
| 1444 | } |
| 1445 | }; |
| 1446 | |
| 1447 | class ShutdownedWrite final: public AsyncCapabilityStream { |
| 1448 | // AsyncPipe state when shutdownWrite() has been called. |
| 1449 | |
| 1450 | public: |
| 1451 | Promise<size_t> tryRead(void* readBufferPtr, size_t minBytes, size_t maxBytes) override { |
| 1452 | return constPromise<size_t, 0>(); |
| 1453 | } |
| 1454 | Promise<ReadResult> tryReadWithFds(void* readBuffer, size_t minBytes, size_t maxBytes, |
| 1455 | AutoCloseFd* fdBuffer, size_t maxFds) override { |
| 1456 | return ReadResult { 0, 0 }; |
| 1457 | } |
| 1458 | Promise<ReadResult> tryReadWithStreams( |
| 1459 | void* readBuffer, size_t minBytes, size_t maxBytes, |
| 1460 | Own<AsyncCapabilityStream>* streamBuffer, size_t maxStreams) override { |
| 1461 | return ReadResult { 0, 0 }; |
| 1462 | } |
| 1463 | Promise<uint64_t> pumpTo(AsyncOutputStream& output, uint64_t amount) override { |
| 1464 | return constPromise<uint64_t, 0>(); |
| 1465 | } |
| 1466 | void abortRead() override { |
| 1467 | // ignore |
| 1468 | } |
| 1469 | |
| 1470 | Promise<void> write(const void* buffer, size_t size) override { |
| 1471 | KJ_FAIL_REQUIRE("shutdownWrite() has been called"); |
| 1472 | } |
| 1473 | Promise<void> write(ArrayPtr<const ArrayPtr<const byte>> pieces) override { |
| 1474 | KJ_FAIL_REQUIRE("shutdownWrite() has been called"); |
| 1475 | } |
| 1476 | Promise<void> writeWithFds(ArrayPtr<const byte> data, |
| 1477 | ArrayPtr<const ArrayPtr<const byte>> moreData, |
| 1478 | ArrayPtr<const int> fds) override { |
| 1479 | KJ_FAIL_REQUIRE("shutdownWrite() has been called"); |
| 1480 | } |
| 1481 | Promise<void> writeWithStreams(ArrayPtr<const byte> data, |
| 1482 | ArrayPtr<const ArrayPtr<const byte>> moreData, |
| 1483 | Array<Own<AsyncCapabilityStream>> streams) override { |
| 1484 | KJ_FAIL_REQUIRE("shutdownWrite() has been called"); |
| 1485 | } |
| 1486 | Maybe<Promise<uint64_t>> tryPumpFrom(AsyncInputStream& input, uint64_t amount) override { |
| 1487 | KJ_FAIL_REQUIRE("shutdownWrite() has been called"); |
| 1488 | } |
| 1489 | void shutdownWrite() override { |
| 1490 | // ignore -- currently shutdownWrite() actually means that the PipeWriteEnd was dropped, |
| 1491 | // so it will only be called once anyhow. |
| 1492 | } |
| 1493 | Promise<void> whenWriteDisconnected() override { |
| 1494 | KJ_FAIL_ASSERT("can't get here -- implemented by AsyncPipe"); |
| 1495 | } |
| 1496 | }; |
| 1497 | }; |
| 1498 | |
| 1499 | class PipeReadEnd final: public AsyncInputStream { |
| 1500 | public: |
| 1501 | PipeReadEnd(kj::Own<AsyncPipe> pipe): pipe(kj::mv(pipe)) {} |
| 1502 | ~PipeReadEnd() noexcept(false) { |
| 1503 | unwind.catchExceptionsIfUnwinding([&]() { |
| 1504 | pipe->abortRead(); |
| 1505 | }); |
| 1506 | } |
| 1507 | |
| 1508 | Promise<size_t> tryRead(void* buffer, size_t minBytes, size_t maxBytes) override { |
| 1509 | return pipe->tryRead(buffer, minBytes, maxBytes); |
| 1510 | } |
| 1511 | |
| 1512 | Promise<uint64_t> pumpTo(AsyncOutputStream& output, uint64_t amount) override { |
| 1513 | return pipe->pumpTo(output, amount); |
| 1514 | } |
| 1515 | |
| 1516 | private: |
| 1517 | Own<AsyncPipe> pipe; |
| 1518 | UnwindDetector unwind; |
| 1519 | }; |
| 1520 | |
| 1521 | class PipeWriteEnd final: public AsyncOutputStream { |
| 1522 | public: |
| 1523 | PipeWriteEnd(kj::Own<AsyncPipe> pipe): pipe(kj::mv(pipe)) {} |
| 1524 | ~PipeWriteEnd() noexcept(false) { |
| 1525 | unwind.catchExceptionsIfUnwinding([&]() { |
| 1526 | pipe->shutdownWrite(); |
| 1527 | }); |
| 1528 | } |
| 1529 | |
| 1530 | Promise<void> write(const void* buffer, size_t size) override { |
| 1531 | return pipe->write(buffer, size); |
| 1532 | } |
| 1533 | |
| 1534 | Promise<void> write(ArrayPtr<const ArrayPtr<const byte>> pieces) override { |
| 1535 | return pipe->write(pieces); |
| 1536 | } |
| 1537 | |
| 1538 | Maybe<Promise<uint64_t>> tryPumpFrom( |
| 1539 | AsyncInputStream& input, uint64_t amount) override { |
| 1540 | return pipe->tryPumpFrom(input, amount); |
| 1541 | } |
| 1542 | |
| 1543 | Promise<void> whenWriteDisconnected() override { |
| 1544 | return pipe->whenWriteDisconnected(); |
| 1545 | } |
| 1546 | |
| 1547 | private: |
| 1548 | Own<AsyncPipe> pipe; |
| 1549 | UnwindDetector unwind; |
| 1550 | }; |
| 1551 | |
| 1552 | class TwoWayPipeEnd final: public AsyncCapabilityStream { |
| 1553 | public: |
| 1554 | TwoWayPipeEnd(kj::Own<AsyncPipe> in, kj::Own<AsyncPipe> out) |
| 1555 | : in(kj::mv(in)), out(kj::mv(out)) {} |
| 1556 | ~TwoWayPipeEnd() noexcept(false) { |
| 1557 | unwind.catchExceptionsIfUnwinding([&]() { |
| 1558 | out->shutdownWrite(); |
| 1559 | in->abortRead(); |
| 1560 | }); |
| 1561 | } |
| 1562 | |
| 1563 | Promise<size_t> tryRead(void* buffer, size_t minBytes, size_t maxBytes) override { |
| 1564 | return in->tryRead(buffer, minBytes, maxBytes); |
| 1565 | } |
| 1566 | Promise<ReadResult> tryReadWithFds(void* buffer, size_t minBytes, size_t maxBytes, |
| 1567 | AutoCloseFd* fdBuffer, size_t maxFds) override { |
| 1568 | return in->tryReadWithFds(buffer, minBytes, maxBytes, fdBuffer, maxFds); |
| 1569 | } |
| 1570 | Promise<ReadResult> tryReadWithStreams( |
| 1571 | void* buffer, size_t minBytes, size_t maxBytes, |
| 1572 | Own<AsyncCapabilityStream>* streamBuffer, size_t maxStreams) override { |
| 1573 | return in->tryReadWithStreams(buffer, minBytes, maxBytes, streamBuffer, maxStreams); |
| 1574 | } |
| 1575 | Promise<uint64_t> pumpTo(AsyncOutputStream& output, uint64_t amount) override { |
| 1576 | return in->pumpTo(output, amount); |
| 1577 | } |
| 1578 | void abortRead() override { |
| 1579 | in->abortRead(); |
| 1580 | } |
| 1581 | |
| 1582 | Promise<void> write(const void* buffer, size_t size) override { |
| 1583 | return out->write(buffer, size); |
| 1584 | } |
| 1585 | Promise<void> write(ArrayPtr<const ArrayPtr<const byte>> pieces) override { |
| 1586 | return out->write(pieces); |
| 1587 | } |
| 1588 | Promise<void> writeWithFds(ArrayPtr<const byte> data, |
| 1589 | ArrayPtr<const ArrayPtr<const byte>> moreData, |
| 1590 | ArrayPtr<const int> fds) override { |
| 1591 | return out->writeWithFds(data, moreData, fds); |
| 1592 | } |
| 1593 | Promise<void> writeWithStreams(ArrayPtr<const byte> data, |
| 1594 | ArrayPtr<const ArrayPtr<const byte>> moreData, |
| 1595 | Array<Own<AsyncCapabilityStream>> streams) override { |
| 1596 | return out->writeWithStreams(data, moreData, kj::mv(streams)); |
| 1597 | } |
| 1598 | Maybe<Promise<uint64_t>> tryPumpFrom( |
| 1599 | AsyncInputStream& input, uint64_t amount) override { |
| 1600 | return out->tryPumpFrom(input, amount); |
| 1601 | } |
| 1602 | Promise<void> whenWriteDisconnected() override { |
| 1603 | return out->whenWriteDisconnected(); |
| 1604 | } |
| 1605 | void shutdownWrite() override { |
| 1606 | out->shutdownWrite(); |
| 1607 | } |
| 1608 | |
| 1609 | private: |
| 1610 | kj::Own<AsyncPipe> in; |
| 1611 | kj::Own<AsyncPipe> out; |
| 1612 | UnwindDetector unwind; |
| 1613 | }; |
| 1614 | |
| 1615 | class LimitedInputStream final: public AsyncInputStream { |
| 1616 | public: |
| 1617 | LimitedInputStream(kj::Own<AsyncInputStream> inner, uint64_t limit) |
| 1618 | : inner(kj::mv(inner)), limit(limit) { |
| 1619 | if (limit == 0) { |
| 1620 | this->inner = nullptr; |
| 1621 | } |
| 1622 | } |
| 1623 | |
| 1624 | Maybe<uint64_t> tryGetLength() override { |
| 1625 | return limit; |
| 1626 | } |
| 1627 | |
| 1628 | Promise<size_t> tryRead(void* buffer, size_t minBytes, size_t maxBytes) override { |
| 1629 | if (limit == 0) return constPromise<size_t, 0>(); |
| 1630 | return inner->tryRead(buffer, kj::min(minBytes, limit), kj::min(maxBytes, limit)) |
| 1631 | .then([this,minBytes](size_t actual) { |
| 1632 | decreaseLimit(actual, minBytes); |
| 1633 | return actual; |
| 1634 | }); |
| 1635 | } |
| 1636 | |
| 1637 | Promise<uint64_t> pumpTo(AsyncOutputStream& output, uint64_t amount) override { |
| 1638 | if (limit == 0) return constPromise<uint64_t, 0>(); |
| 1639 | auto requested = kj::min(amount, limit); |
| 1640 | return inner->pumpTo(output, requested) |
| 1641 | .then([this,requested](uint64_t actual) { |
| 1642 | decreaseLimit(actual, requested); |
| 1643 | return actual; |
| 1644 | }); |
| 1645 | } |
| 1646 | |
| 1647 | private: |
| 1648 | Own<AsyncInputStream> inner; |
| 1649 | uint64_t limit; |
| 1650 | |
| 1651 | void decreaseLimit(uint64_t amount, uint64_t requested) { |
| 1652 | KJ_ASSERT(limit >= amount); |
| 1653 | limit -= amount; |
| 1654 | if (limit == 0) { |
| 1655 | inner = nullptr; |
| 1656 | } else if (amount < requested) { |
| 1657 | kj::throwRecoverableException(KJ_EXCEPTION(DISCONNECTED, |
| 1658 | "fixed-length pipe ended prematurely")); |
| 1659 | } |
| 1660 | } |
| 1661 | }; |
| 1662 | |
| 1663 | } // namespace |
| 1664 | |
| 1665 | OneWayPipe newOneWayPipe(kj::Maybe<uint64_t> expectedLength) { |
| 1666 | auto impl = kj::refcounted<AsyncPipe>(); |
| 1667 | Own<AsyncInputStream> readEnd = kj::heap<PipeReadEnd>(kj::addRef(*impl)); |
| 1668 | KJ_IF_MAYBE(l, expectedLength) { |
| 1669 | readEnd = kj::heap<LimitedInputStream>(kj::mv(readEnd), *l); |
| 1670 | } |
| 1671 | Own<AsyncOutputStream> writeEnd = kj::heap<PipeWriteEnd>(kj::mv(impl)); |
| 1672 | return { kj::mv(readEnd), kj::mv(writeEnd) }; |
| 1673 | } |
| 1674 | |
| 1675 | TwoWayPipe newTwoWayPipe() { |
| 1676 | auto pipe1 = kj::refcounted<AsyncPipe>(); |
| 1677 | auto pipe2 = kj::refcounted<AsyncPipe>(); |
| 1678 | auto end1 = kj::heap<TwoWayPipeEnd>(kj::addRef(*pipe1), kj::addRef(*pipe2)); |
| 1679 | auto end2 = kj::heap<TwoWayPipeEnd>(kj::mv(pipe2), kj::mv(pipe1)); |
| 1680 | return { { kj::mv(end1), kj::mv(end2) } }; |
| 1681 | } |
| 1682 | |
| 1683 | CapabilityPipe newCapabilityPipe() { |
| 1684 | auto pipe1 = kj::refcounted<AsyncPipe>(); |
| 1685 | auto pipe2 = kj::refcounted<AsyncPipe>(); |
| 1686 | auto end1 = kj::heap<TwoWayPipeEnd>(kj::addRef(*pipe1), kj::addRef(*pipe2)); |
| 1687 | auto end2 = kj::heap<TwoWayPipeEnd>(kj::mv(pipe2), kj::mv(pipe1)); |
| 1688 | return { { kj::mv(end1), kj::mv(end2) } }; |
| 1689 | } |
| 1690 | |
| 1691 | namespace { |
| 1692 | |
| 1693 | class AsyncTee final: public Refcounted { |
| 1694 | class Buffer { |
| 1695 | public: |
| 1696 | Buffer() = default; |
| 1697 | |
| 1698 | uint64_t consume(ArrayPtr<byte>& readBuffer, size_t& minBytes); |
| 1699 | // Consume as many bytes as possible, copying them into `readBuffer`. Return the number of bytes |
| 1700 | // consumed. |
| 1701 | // |
| 1702 | // `readBuffer` and `minBytes` are both assigned appropriate new values, such that after any |
| 1703 | // call to `consume()`, `readBuffer` will point to the remaining slice of unwritten space, and |
| 1704 | // `minBytes` will have been decremented (clamped to zero) by the amount of bytes read. That is, |
| 1705 | // the read can be considered fulfilled if `minBytes` is zero after a call to `consume()`. |
| 1706 | |
| 1707 | Array<const ArrayPtr<const byte>> asArray(uint64_t minBytes, uint64_t& amount); |
| 1708 | // Consume the first `minBytes` of the buffer (or the entire buffer) and return it in an Array |
| 1709 | // of ArrayPtr<const byte>s, suitable for passing to AsyncOutputStream.write(). The outer Array |
| 1710 | // owns the underlying data. |
| 1711 | |
| 1712 | void produce(Array<byte> bytes); |
| 1713 | // Enqueue a byte array to the end of the buffer list. |
| 1714 | |
| 1715 | bool empty() const; |
| 1716 | uint64_t size() const; |
| 1717 | |
| 1718 | Buffer clone() const { |
| 1719 | size_t size = 0; |
| 1720 | for (const auto& buf: bufferList) { |
| 1721 | size += buf.size(); |
| 1722 | } |
| 1723 | auto builder = heapArrayBuilder<byte>(size); |
| 1724 | for (const auto& buf: bufferList) { |
| 1725 | builder.addAll(buf); |
| 1726 | } |
| 1727 | std::deque<Array<byte>> deque; |
| 1728 | deque.emplace_back(builder.finish()); |
| 1729 | return Buffer{mv(deque)}; |
| 1730 | } |
| 1731 | |
| 1732 | private: |
| 1733 | Buffer(std::deque<Array<byte>>&& buffer) : bufferList(mv(buffer)) {} |
| 1734 | |
| 1735 | std::deque<Array<byte>> bufferList; |
| 1736 | }; |
| 1737 | |
| 1738 | class Sink; |
| 1739 | |
| 1740 | public: |
| 1741 | class Branch final: public AsyncInputStream { |
| 1742 | public: |
| 1743 | Branch(Own<AsyncTee> teeArg): tee(mv(teeArg)) { |
| 1744 | tee->branches.add(*this); |
| 1745 | } |
| 1746 | |
| 1747 | Branch(Own<AsyncTee> teeArg, Branch& cloneFrom) |
| 1748 | : tee(mv(teeArg)), buffer(cloneFrom.buffer.clone()) { |
| 1749 | tee->branches.add(*this); |
| 1750 | } |
| 1751 | |
| 1752 | ~Branch() noexcept(false) { |
| 1753 | KJ_ASSERT(link.isLinked()) { |
| 1754 | // Don't std::terminate(). |
| 1755 | return; |
| 1756 | } |
| 1757 | tee->branches.remove(*this); |
| 1758 | |
| 1759 | KJ_REQUIRE(sink == nullptr, |
| 1760 | "destroying tee branch with operation still in-progress; probably going to segfault") { |
| 1761 | // Don't std::terminate(). |
| 1762 | break; |
| 1763 | } |
| 1764 | } |
| 1765 | |
| 1766 | Promise<size_t> tryRead(void* buffer, size_t minBytes, size_t maxBytes) override { |
| 1767 | return tee->tryRead(*this, buffer, minBytes, maxBytes); |
| 1768 | } |
| 1769 | |
| 1770 | Promise<uint64_t> pumpTo(AsyncOutputStream& output, uint64_t amount) override { |
| 1771 | return tee->pumpTo(*this, output, amount); |
| 1772 | } |
| 1773 | |
| 1774 | Maybe<uint64_t> tryGetLength() override { |
| 1775 | return tee->tryGetLength(*this); |
| 1776 | } |
| 1777 | |
| 1778 | Maybe<Own<AsyncInputStream>> tryTee(uint64_t limit) override { |
| 1779 | if (tee->getBufferSizeLimit() != limit) { |
| 1780 | // Cannot optimize this path as the limit has changed, so we need a new AsyncTee to manage |
| 1781 | // the limit. |
| 1782 | return nullptr; |
| 1783 | } |
| 1784 | |
| 1785 | return kj::heap<Branch>(addRef(*tee), *this); |
| 1786 | } |
| 1787 | |
| 1788 | private: |
| 1789 | Own<AsyncTee> tee; |
| 1790 | ListLink<Branch> link; |
| 1791 | |
| 1792 | Buffer buffer; |
| 1793 | Maybe<Sink&> sink; |
| 1794 | |
| 1795 | friend class AsyncTee; |
| 1796 | }; |
| 1797 | |
| 1798 | explicit AsyncTee(Own<AsyncInputStream> inner, uint64_t bufferSizeLimit) |
| 1799 | : inner(mv(inner)), bufferSizeLimit(bufferSizeLimit), length(this->inner->tryGetLength()) {} |
| 1800 | ~AsyncTee() noexcept(false) { |
| 1801 | KJ_ASSERT(branches.size() == 0, "destroying AsyncTee with branch still alive") { |
| 1802 | // Don't std::terminate(). |
| 1803 | break; |
| 1804 | } |
| 1805 | } |
| 1806 | |
| 1807 | Promise<size_t> tryRead(Branch& branch, void* buffer, size_t minBytes, size_t maxBytes) { |
| 1808 | KJ_ASSERT(branch.sink == nullptr); |
| 1809 | |
| 1810 | // If there is excess data in the buffer for us, slurp that up. |
| 1811 | auto readBuffer = arrayPtr(reinterpret_cast<byte*>(buffer), maxBytes); |
| 1812 | auto readSoFar = branch.buffer.consume(readBuffer, minBytes); |
| 1813 | |
| 1814 | if (minBytes == 0) { |
| 1815 | return readSoFar; |
| 1816 | } |
| 1817 | |
| 1818 | if (branch.buffer.empty()) { |
| 1819 | KJ_IF_MAYBE(reason, stoppage) { |
| 1820 | // Prefer a short read to an exception. The exception prevents the pull loop from adding any |
| 1821 | // data to the buffer, so `readSoFar` will be zero the next time someone calls `tryRead()`, |
| 1822 | // and the caller will see the exception. |
| 1823 | if (reason->is<Eof>() || readSoFar > 0) { |
| 1824 | return readSoFar; |
| 1825 | } |
| 1826 | return cp(reason->get<Exception>()); |
| 1827 | } |
| 1828 | } |
| 1829 | |
| 1830 | auto promise = newAdaptedPromise<size_t, ReadSink>( |
| 1831 | branch.sink, readBuffer, minBytes, readSoFar); |
| 1832 | ensurePulling(); |
| 1833 | return mv(promise); |
| 1834 | } |
| 1835 | |
| 1836 | Maybe<uint64_t> tryGetLength(Branch& branch) { |
| 1837 | return length.map([&branch](uint64_t amount) { |
| 1838 | return amount + branch.buffer.size(); |
| 1839 | }); |
| 1840 | } |
| 1841 | |
| 1842 | uint64_t getBufferSizeLimit() const { |
| 1843 | return bufferSizeLimit; |
| 1844 | } |
| 1845 | |
| 1846 | Promise<uint64_t> pumpTo(Branch& branch, AsyncOutputStream& output, uint64_t amount) { |
| 1847 | KJ_ASSERT(branch.sink == nullptr); |
| 1848 | |
| 1849 | if (amount == 0) { |
| 1850 | return amount; |
| 1851 | } |
| 1852 | |
| 1853 | if (branch.buffer.empty()) { |
| 1854 | KJ_IF_MAYBE(reason, stoppage) { |
| 1855 | if (reason->is<Eof>()) { |
| 1856 | return constPromise<uint64_t, 0>(); |
| 1857 | } |
| 1858 | return cp(reason->get<Exception>()); |
| 1859 | } |
| 1860 | } |
| 1861 | |
| 1862 | auto promise = newAdaptedPromise<uint64_t, PumpSink>(branch.sink, output, amount); |
| 1863 | ensurePulling(); |
| 1864 | return mv(promise); |
| 1865 | } |
| 1866 | |
| 1867 | private: |
| 1868 | struct Eof {}; |
| 1869 | using Stoppage = OneOf<Eof, Exception>; |
| 1870 | |
| 1871 | class Sink { |
| 1872 | public: |
| 1873 | struct Need { |
| 1874 | // We use uint64_t here because: |
| 1875 | // - pumpTo() accepts it as the `amount` parameter. |
| 1876 | // - all practical values of tryRead()'s `maxBytes` parameter (a size_t) should also fit into |
| 1877 | // a uint64_t, unless we're on a machine with multiple exabytes of memory ... |
| 1878 | |
| 1879 | uint64_t minBytes = 0; |
| 1880 | |
| 1881 | uint64_t maxBytes = kj::maxValue; |
| 1882 | }; |
| 1883 | |
| 1884 | virtual Promise<void> fill(Buffer& inBuffer, const Maybe<Stoppage>& stoppage) = 0; |
| 1885 | // Attempt to fill the sink with bytes andreturn a promise which must resolve before any inner |
| 1886 | // read may be attempted. If a sink requires backpressure to be respected, this is how it should |
| 1887 | // be communicated. |
| 1888 | // |
| 1889 | // If the sink is full, it must detach from the tee before the returned promise is resolved. |
| 1890 | // |
| 1891 | // The returned promise must not result in an exception. |
| 1892 | |
| 1893 | virtual Need need() = 0; |
| 1894 | |
| 1895 | virtual void reject(Exception&& exception) = 0; |
| 1896 | // Inform this sink of a catastrophic exception and detach it. Regular read exceptions should be |
| 1897 | // propagated through `fill()`'s stoppage parameter instead. |
| 1898 | }; |
| 1899 | |
| 1900 | template <typename T> |
| 1901 | class SinkBase: public Sink { |
| 1902 | // Registers itself with the tee as a sink on construction, detaches from the tee on |
| 1903 | // fulfillment, rejection, or destruction. |
| 1904 | // |
| 1905 | // A bit of a Frankenstein, avert your eyes. For one thing, it's more of a mixin than a base... |
| 1906 | |
| 1907 | public: |
| 1908 | explicit SinkBase(PromiseFulfiller<T>& fulfiller, Maybe<Sink&>& sinkLink) |
| 1909 | : fulfiller(fulfiller), sinkLink(sinkLink) { |
| 1910 | KJ_ASSERT(sinkLink == nullptr, "sink initiated with sink already in flight"); |
| 1911 | sinkLink = *this; |
| 1912 | } |
| 1913 | KJ_DISALLOW_COPY_AND_MOVE(SinkBase); |
| 1914 | ~SinkBase() noexcept(false) { detach(); } |
| 1915 | |
| 1916 | void reject(Exception&& exception) override { |
| 1917 | // The tee is allowed to reject this sink if it needs to, e.g. to propagate a non-inner read |
| 1918 | // exception from the pull loop. Only the derived class is allowed to fulfill() directly, |
| 1919 | // though -- the tee must keep calling fill(). |
| 1920 | |
| 1921 | fulfiller.reject(mv(exception)); |
| 1922 | detach(); |
| 1923 | } |
| 1924 | |
| 1925 | protected: |
| 1926 | template <typename U> |
| 1927 | void fulfill(U value) { |
| 1928 | fulfiller.fulfill(fwd<U>(value)); |
| 1929 | detach(); |
| 1930 | } |
| 1931 | |
| 1932 | private: |
| 1933 | void detach() { |
| 1934 | KJ_IF_MAYBE(sink, sinkLink) { |
| 1935 | if (sink == this) { |
| 1936 | sinkLink = nullptr; |
| 1937 | } |
| 1938 | } |
| 1939 | } |
| 1940 | |
| 1941 | PromiseFulfiller<T>& fulfiller; |
| 1942 | Maybe<Sink&>& sinkLink; |
| 1943 | }; |
| 1944 | |
| 1945 | class ReadSink final: public SinkBase<size_t> { |
| 1946 | public: |
| 1947 | explicit ReadSink(PromiseFulfiller<size_t>& fulfiller, Maybe<Sink&>& registration, |
| 1948 | ArrayPtr<byte> buffer, size_t minBytes, size_t readSoFar) |
| 1949 | : SinkBase(fulfiller, registration), buffer(buffer), |
| 1950 | minBytes(minBytes), readSoFar(readSoFar) {} |
| 1951 | |
| 1952 | Promise<void> fill(Buffer& inBuffer, const Maybe<Stoppage>& stoppage) override { |
| 1953 | auto amount = inBuffer.consume(buffer, minBytes); |
| 1954 | readSoFar += amount; |
| 1955 | |
| 1956 | if (minBytes == 0) { |
| 1957 | // We satisfied the read request. |
| 1958 | fulfill(readSoFar); |
| 1959 | return READY_NOW; |
| 1960 | } |
| 1961 | |
| 1962 | if (amount == 0 && inBuffer.empty()) { |
| 1963 | // We made no progress on the read request and the buffer is tapped out. |
| 1964 | KJ_IF_MAYBE(reason, stoppage) { |
| 1965 | if (reason->is<Eof>() || readSoFar > 0) { |
| 1966 | // Prefer short read to exception. |
| 1967 | fulfill(readSoFar); |
| 1968 | } else { |
| 1969 | reject(cp(reason->get<Exception>())); |
| 1970 | } |
| 1971 | return READY_NOW; |
| 1972 | } |
| 1973 | } |
| 1974 | |
| 1975 | return READY_NOW; |
| 1976 | } |
| 1977 | |
| 1978 | Need need() override { return Need { minBytes, buffer.size() }; } |
| 1979 | |
| 1980 | private: |
| 1981 | ArrayPtr<byte> buffer; |
| 1982 | size_t minBytes; |
| 1983 | // Arguments to the outer tryRead() call, sliced/decremented after every buffer consumption. |
| 1984 | |
| 1985 | size_t readSoFar; |
| 1986 | // End result of the outer tryRead(). |
| 1987 | }; |
| 1988 | |
| 1989 | class PumpSink final: public SinkBase<uint64_t> { |
| 1990 | public: |
| 1991 | explicit PumpSink(PromiseFulfiller<uint64_t>& fulfiller, Maybe<Sink&>& registration, |
| 1992 | AsyncOutputStream& output, uint64_t limit) |
| 1993 | : SinkBase(fulfiller, registration), output(output), limit(limit) {} |
| 1994 | |
| 1995 | ~PumpSink() noexcept(false) { |
| 1996 | canceler.cancel("This pump has been canceled."); |
| 1997 | } |
| 1998 | |
| 1999 | Promise<void> fill(Buffer& inBuffer, const Maybe<Stoppage>& stoppage) override { |
| 2000 | KJ_ASSERT(limit > 0); |
| 2001 | |
| 2002 | uint64_t amount = 0; |
| 2003 | |
| 2004 | // TODO(someday): This consumes data from the buffer, but we cannot know if the stream to |
| 2005 | // which we're pumping will accept it until after the write() promise completes. If the |
| 2006 | // write() promise rejects, we lose this data. We should consume the data from the buffer |
| 2007 | // only after successful writes. |
| 2008 | auto writeBuffer = inBuffer.asArray(limit, amount); |
| 2009 | KJ_ASSERT(limit >= amount); |
| 2010 | if (amount > 0) { |
| 2011 | Promise<void> promise = kj::evalNow([&]() { |
| 2012 | return output.write(writeBuffer).attach(mv(writeBuffer)); |
| 2013 | }).then([this, amount]() { |
| 2014 | limit -= amount; |
| 2015 | pumpedSoFar += amount; |
| 2016 | if (limit == 0) { |
| 2017 | fulfill(pumpedSoFar); |
| 2018 | } |
| 2019 | }).eagerlyEvaluate([this](Exception&& exception) { |
| 2020 | reject(mv(exception)); |
| 2021 | }); |
| 2022 | |
| 2023 | return canceler.wrap(mv(promise)).catch_([](kj::Exception&&) {}); |
| 2024 | } else KJ_IF_MAYBE(reason, stoppage) { |
| 2025 | if (reason->is<Eof>()) { |
| 2026 | // Unlike in the read case, it makes more sense to immediately propagate exceptions to the |
| 2027 | // pump promise rather than show it a "short pump". |
| 2028 | fulfill(pumpedSoFar); |
| 2029 | } else { |
| 2030 | reject(cp(reason->get<Exception>())); |
| 2031 | } |
| 2032 | } |
| 2033 | |
| 2034 | return READY_NOW; |
| 2035 | } |
| 2036 | |
| 2037 | Need need() override { return Need { 1, limit }; } |
| 2038 | |
| 2039 | private: |
| 2040 | AsyncOutputStream& output; |
| 2041 | uint64_t limit; |
| 2042 | // Arguments to the outer pumpTo() call, decremented after every buffer consumption. |
| 2043 | // |
| 2044 | // Equal to zero once fulfiller has been fulfilled/rejected. |
| 2045 | |
| 2046 | uint64_t pumpedSoFar = 0; |
| 2047 | // End result of the outer pumpTo(). |
| 2048 | |
| 2049 | Canceler canceler; |
| 2050 | // When the pump is canceled, we also need to cancel any write operations in flight. |
| 2051 | }; |
| 2052 | |
| 2053 | // ===================================================================================== |
| 2054 | |
| 2055 | Maybe<Sink::Need> analyzeSinks() { |
| 2056 | // Return nullptr if there are no sinks at all. Otherwise, return the largest `minBytes` and the |
| 2057 | // smallest `maxBytes` requested by any sink. The pull loop will use these values to calculate |
| 2058 | // the optimal buffer size for the next inner read, so that a minimum amount of data is buffered |
| 2059 | // at any given time. |
| 2060 | |
| 2061 | uint64_t minBytes = 0; |
| 2062 | uint64_t maxBytes = kj::maxValue; |
| 2063 | |
| 2064 | uint nSinks = 0; |
| 2065 | |
| 2066 | for (auto& branch: branches) { |
| 2067 | KJ_IF_MAYBE(sink, branch.sink) { |
| 2068 | ++nSinks; |
| 2069 | auto need = sink->need(); |
| 2070 | minBytes = kj::max(minBytes, need.minBytes); |
| 2071 | maxBytes = kj::min(maxBytes, need.maxBytes); |
| 2072 | } |
| 2073 | } |
| 2074 | |
| 2075 | if (nSinks > 0) { |
| 2076 | KJ_ASSERT(minBytes > 0); |
| 2077 | KJ_ASSERT(maxBytes > 0, "sink was filled but did not detach"); |
| 2078 | |
| 2079 | // Sinks may report non-overlapping needs. |
| 2080 | maxBytes = kj::max(minBytes, maxBytes); |
| 2081 | |
| 2082 | return Sink::Need { minBytes, maxBytes }; |
| 2083 | } |
| 2084 | |
| 2085 | // No active sinks. |
| 2086 | return nullptr; |
| 2087 | } |
| 2088 | |
| 2089 | void ensurePulling() { |
| 2090 | if (!pulling) { |
| 2091 | pulling = true; |
| 2092 | UnwindDetector unwind; |
| 2093 | KJ_DEFER(if (unwind.isUnwinding()) pulling = false); |
| 2094 | pullPromise = pull(); |
| 2095 | } |
| 2096 | } |
| 2097 | |
| 2098 | Promise<void> pull() { |
| 2099 | return pullLoop().eagerlyEvaluate([this](Exception&& exception) { |
| 2100 | // Exception from our loop, not from inner tryRead(). Something is broken; tell everybody! |
| 2101 | pulling = false; |
| 2102 | for (auto& branch: branches) { |
| 2103 | KJ_IF_MAYBE(sink, branch.sink) { |
| 2104 | sink->reject(KJ_EXCEPTION(FAILED, "Exception in tee loop", exception)); |
| 2105 | } |
| 2106 | } |
| 2107 | }); |
| 2108 | } |
| 2109 | |
| 2110 | constexpr static size_t MAX_BLOCK_SIZE = 1 << 14; // 16k |
| 2111 | |
| 2112 | Own<AsyncInputStream> inner; |
| 2113 | const uint64_t bufferSizeLimit = kj::maxValue; |
| 2114 | Maybe<uint64_t> length; |
| 2115 | List<Branch, &Branch::link> branches; |
| 2116 | Maybe<Stoppage> stoppage; |
| 2117 | Promise<void> pullPromise = READY_NOW; |
| 2118 | bool pulling = false; |
| 2119 | |
| 2120 | private: |
| 2121 | Promise<void> pullLoop() { |
| 2122 | // Use evalLater() so that two pump sinks added on the same turn of the event loop will not |
| 2123 | // cause buffering. |
| 2124 | return evalLater([this] { |
| 2125 | // Attempt to fill any sinks that exist. |
| 2126 | |
| 2127 | Vector<Promise<void>> promises; |
| 2128 | |
| 2129 | for (auto& branch: branches) { |
| 2130 | KJ_IF_MAYBE(sink, branch.sink) { |
| 2131 | promises.add(sink->fill(branch.buffer, stoppage)); |
| 2132 | } |
| 2133 | } |
| 2134 | |
| 2135 | // Respect the greatest of the sinks' backpressures. |
| 2136 | return joinPromises(promises.releaseAsArray()); |
| 2137 | }).then([this]() -> Promise<void> { |
| 2138 | // Check to see whether we need to perform an inner read. |
| 2139 | |
| 2140 | auto need = analyzeSinks(); |
| 2141 | |
| 2142 | if (need == nullptr) { |
| 2143 | // No more sinks, stop pulling. |
| 2144 | pulling = false; |
| 2145 | return READY_NOW; |
| 2146 | } |
| 2147 | |
| 2148 | if (stoppage != nullptr) { |
| 2149 | // We're eof or errored, don't read, but loop so we can fill the sink(s). |
| 2150 | return pullLoop(); |
| 2151 | } |
| 2152 | |
| 2153 | auto& n = KJ_ASSERT_NONNULL(need); |
| 2154 | |
| 2155 | KJ_ASSERT(n.minBytes > 0); |
| 2156 | |
| 2157 | // We must perform an inner read. |
| 2158 | |
| 2159 | // We'd prefer not to explode our buffer, if that's cool. We cap `maxBytes` to the buffer size |
| 2160 | // limit or our builtin MAX_BLOCK_SIZE, whichever is smaller. But, we make sure `maxBytes` is |
| 2161 | // still >= `minBytes`. |
| 2162 | n.maxBytes = kj::min(n.maxBytes, MAX_BLOCK_SIZE); |
| 2163 | n.maxBytes = kj::min(n.maxBytes, bufferSizeLimit); |
| 2164 | n.maxBytes = kj::max(n.minBytes, n.maxBytes); |
| 2165 | for (auto& branch: branches) { |
| 2166 | // TODO(perf): buffer.size() is O(n) where n = # of individual heap-allocated byte arrays. |
| 2167 | if (branch.buffer.size() + n.maxBytes > bufferSizeLimit) { |
| 2168 | stoppage = Stoppage(KJ_EXCEPTION(FAILED, "tee buffer size limit exceeded")); |
| 2169 | return pullLoop(); |
| 2170 | } |
| 2171 | } |
| 2172 | auto heapBuffer = heapArray<byte>(n.maxBytes); |
| 2173 | |
| 2174 | // gcc 4.9 quirk: If I don't hoist this into a separate variable and instead call |
| 2175 | // |
| 2176 | // inner->tryRead(heapBuffer.begin(), n.minBytes, heapBuffer.size()) |
| 2177 | // |
| 2178 | // `heapBuffer` seems to get moved into the lambda capture before the arguments to `tryRead()` |
| 2179 | // are evaluated, meaning `inner` sees a nullptr destination. Bizarrely, `inner` sees the |
| 2180 | // correct value for `heapBuffer.size()`... I dunno, man. |
| 2181 | auto destination = heapBuffer.begin(); |
| 2182 | |
| 2183 | return kj::evalNow([&]() { return inner->tryRead(destination, n.minBytes, n.maxBytes); }) |
| 2184 | .then([this, heapBuffer = mv(heapBuffer), minBytes = n.minBytes](size_t amount) mutable |
| 2185 | -> Promise<void> { |
| 2186 | length = length.map([amount](uint64_t n) { |
| 2187 | KJ_ASSERT(n >= amount); |
| 2188 | return n - amount; |
| 2189 | }); |
| 2190 | |
| 2191 | if (amount < heapBuffer.size()) { |
| 2192 | heapBuffer = heapBuffer.slice(0, amount).attach(mv(heapBuffer)); |
| 2193 | } |
| 2194 | |
| 2195 | KJ_ASSERT(stoppage == nullptr); |
| 2196 | Maybe<ArrayPtr<byte>> bufferPtr = nullptr; |
| 2197 | for (auto& branch: branches) { |
| 2198 | // Prefer to move the buffer into the receiving branch's deque, rather than memcpy. |
| 2199 | // |
| 2200 | // TODO(perf): For the 2-branch case, this is fine, since the majority of the time |
| 2201 | // only one buffer will be in use. If we generalize to the n-branch case, this would |
| 2202 | // become memcpy-heavy. |
| 2203 | KJ_IF_MAYBE(ptr, bufferPtr) { |
| 2204 | branch.buffer.produce(heapArray(*ptr)); |
| 2205 | } else { |
| 2206 | bufferPtr = ArrayPtr<byte>(heapBuffer); |
| 2207 | branch.buffer.produce(mv(heapBuffer)); |
| 2208 | } |
| 2209 | } |
| 2210 | |
| 2211 | if (amount < minBytes) { |
| 2212 | // Short read, EOF. |
| 2213 | stoppage = Stoppage(Eof()); |
| 2214 | } |
| 2215 | |
| 2216 | return pullLoop(); |
| 2217 | }, [this](Exception&& exception) { |
| 2218 | // Exception from the inner tryRead(). Propagate. |
| 2219 | stoppage = Stoppage(mv(exception)); |
| 2220 | return pullLoop(); |
| 2221 | }); |
| 2222 | }); |
| 2223 | } |
| 2224 | }; |
| 2225 | |
| 2226 | constexpr size_t AsyncTee::MAX_BLOCK_SIZE; |
| 2227 | |
| 2228 | uint64_t AsyncTee::Buffer::consume(ArrayPtr<byte>& readBuffer, size_t& minBytes) { |
| 2229 | uint64_t totalAmount = 0; |
| 2230 | |
| 2231 | while (readBuffer.size() > 0 && !bufferList.empty()) { |
| 2232 | auto& bytes = bufferList.front(); |
| 2233 | auto amount = kj::min(bytes.size(), readBuffer.size()); |
| 2234 | memcpy(readBuffer.begin(), bytes.begin(), amount); |
| 2235 | totalAmount += amount; |
| 2236 | |
| 2237 | readBuffer = readBuffer.slice(amount, readBuffer.size()); |
| 2238 | minBytes -= kj::min(amount, minBytes); |
| 2239 | |
| 2240 | if (amount == bytes.size()) { |
| 2241 | bufferList.pop_front(); |
| 2242 | } else { |
| 2243 | bytes = heapArray(bytes.slice(amount, bytes.size())); |
| 2244 | return totalAmount; |
| 2245 | } |
| 2246 | } |
| 2247 | |
| 2248 | return totalAmount; |
| 2249 | } |
| 2250 | |
| 2251 | void AsyncTee::Buffer::produce(Array<byte> bytes) { |
| 2252 | bufferList.push_back(mv(bytes)); |
| 2253 | } |
| 2254 | |
| 2255 | Array<const ArrayPtr<const byte>> AsyncTee::Buffer::asArray( |
| 2256 | uint64_t maxBytes, uint64_t& amount) { |
| 2257 | amount = 0; |
| 2258 | |
| 2259 | Vector<ArrayPtr<const byte>> buffers; |
| 2260 | Vector<Array<byte>> ownBuffers; |
| 2261 | |
| 2262 | while (maxBytes > 0 && !bufferList.empty()) { |
| 2263 | auto& bytes = bufferList.front(); |
| 2264 | |
| 2265 | if (bytes.size() <= maxBytes) { |
| 2266 | amount += bytes.size(); |
| 2267 | maxBytes -= bytes.size(); |
| 2268 | |
| 2269 | buffers.add(bytes); |
| 2270 | ownBuffers.add(mv(bytes)); |
| 2271 | |
| 2272 | bufferList.pop_front(); |
| 2273 | } else { |
| 2274 | auto ownBytes = heapArray(bytes.slice(0, maxBytes)); |
| 2275 | buffers.add(ownBytes); |
| 2276 | ownBuffers.add(mv(ownBytes)); |
| 2277 | |
| 2278 | bytes = heapArray(bytes.slice(maxBytes, bytes.size())); |
| 2279 | |
| 2280 | amount += maxBytes; |
| 2281 | maxBytes = 0; |
| 2282 | } |
| 2283 | } |
| 2284 | |
| 2285 | |
| 2286 | if (buffers.size() > 0) { |
| 2287 | return buffers.releaseAsArray().attach(mv(ownBuffers)); |
| 2288 | } |
| 2289 | |
| 2290 | return {}; |
| 2291 | } |
| 2292 | |
| 2293 | bool AsyncTee::Buffer::empty() const { |
| 2294 | return bufferList.empty(); |
| 2295 | } |
| 2296 | |
| 2297 | uint64_t AsyncTee::Buffer::size() const { |
| 2298 | uint64_t result = 0; |
| 2299 | |
| 2300 | for (auto& bytes: bufferList) { |
| 2301 | result += bytes.size(); |
| 2302 | } |
| 2303 | |
| 2304 | return result; |
| 2305 | } |
| 2306 | |
| 2307 | } // namespace |
| 2308 | |
| 2309 | Tee newTee(Own<AsyncInputStream> input, uint64_t limit) { |
| 2310 | KJ_IF_MAYBE(t, input->tryTee(limit)) { |
| 2311 | return { { mv(input), mv(*t) }}; |
| 2312 | } |
| 2313 | |
| 2314 | auto impl = refcounted<AsyncTee>(mv(input), limit); |
| 2315 | Own<AsyncInputStream> branch1 = heap<AsyncTee::Branch>(addRef(*impl)); |
| 2316 | Own<AsyncInputStream> branch2 = heap<AsyncTee::Branch>(mv(impl)); |
| 2317 | return { { mv(branch1), mv(branch2) } }; |
| 2318 | } |
| 2319 | |
| 2320 | namespace { |
| 2321 | |
| 2322 | class PromisedAsyncIoStream final: public kj::AsyncIoStream, private kj::TaskSet::ErrorHandler { |
| 2323 | // An AsyncIoStream which waits for a promise to resolve then forwards all calls to the promised |
| 2324 | // stream. |
| 2325 | |
| 2326 | public: |
| 2327 | PromisedAsyncIoStream(kj::Promise<kj::Own<AsyncIoStream>> promise) |
| 2328 | : promise(promise.then([this](kj::Own<AsyncIoStream> result) { |
| 2329 | stream = kj::mv(result); |
| 2330 | }).fork()), |
| 2331 | tasks(*this) {} |
| 2332 | |
| 2333 | kj::Promise<size_t> read(void* buffer, size_t minBytes, size_t maxBytes) override { |
| 2334 | KJ_IF_MAYBE(s, stream) { |
| 2335 | return s->get()->read(buffer, minBytes, maxBytes); |
| 2336 | } else { |
| 2337 | return promise.addBranch().then([this,buffer,minBytes,maxBytes]() { |
| 2338 | return KJ_ASSERT_NONNULL(stream)->read(buffer, minBytes, maxBytes); |
| 2339 | }); |
| 2340 | } |
| 2341 | } |
| 2342 | kj::Promise<size_t> tryRead(void* buffer, size_t minBytes, size_t maxBytes) override { |
| 2343 | KJ_IF_MAYBE(s, stream) { |
| 2344 | return s->get()->tryRead(buffer, minBytes, maxBytes); |
| 2345 | } else { |
| 2346 | return promise.addBranch().then([this,buffer,minBytes,maxBytes]() { |
| 2347 | return KJ_ASSERT_NONNULL(stream)->tryRead(buffer, minBytes, maxBytes); |
| 2348 | }); |
| 2349 | } |
| 2350 | } |
| 2351 | |
| 2352 | kj::Maybe<uint64_t> tryGetLength() override { |
| 2353 | KJ_IF_MAYBE(s, stream) { |
| 2354 | return s->get()->tryGetLength(); |
| 2355 | } else { |
| 2356 | return nullptr; |
| 2357 | } |
| 2358 | } |
| 2359 | |
| 2360 | kj::Promise<uint64_t> pumpTo(kj::AsyncOutputStream& output, uint64_t amount) override { |
| 2361 | KJ_IF_MAYBE(s, stream) { |
| 2362 | return s->get()->pumpTo(output, amount); |
| 2363 | } else { |
| 2364 | return promise.addBranch().then([this,&output,amount]() { |
| 2365 | return KJ_ASSERT_NONNULL(stream)->pumpTo(output, amount); |
| 2366 | }); |
| 2367 | } |
| 2368 | } |
| 2369 | |
| 2370 | kj::Promise<void> write(const void* buffer, size_t size) override { |
| 2371 | KJ_IF_MAYBE(s, stream) { |
| 2372 | return s->get()->write(buffer, size); |
| 2373 | } else { |
| 2374 | return promise.addBranch().then([this,buffer,size]() { |
| 2375 | return KJ_ASSERT_NONNULL(stream)->write(buffer, size); |
| 2376 | }); |
| 2377 | } |
| 2378 | } |
| 2379 | kj::Promise<void> write(kj::ArrayPtr<const kj::ArrayPtr<const byte>> pieces) override { |
| 2380 | KJ_IF_MAYBE(s, stream) { |
| 2381 | return s->get()->write(pieces); |
| 2382 | } else { |
| 2383 | return promise.addBranch().then([this,pieces]() { |
| 2384 | return KJ_ASSERT_NONNULL(stream)->write(pieces); |
| 2385 | }); |
| 2386 | } |
| 2387 | } |
| 2388 | |
| 2389 | kj::Maybe<kj::Promise<uint64_t>> tryPumpFrom( |
| 2390 | kj::AsyncInputStream& input, uint64_t amount = kj::maxValue) override { |
| 2391 | KJ_IF_MAYBE(s, stream) { |
| 2392 | // Call input.pumpTo() on the resolved stream instead, so that if it does some dynamic_casts |
| 2393 | // or whatnot to detect stream types it can retry those on the inner stream. |
| 2394 | return input.pumpTo(**s, amount); |
| 2395 | } else { |
| 2396 | return promise.addBranch().then([this,&input,amount]() { |
| 2397 | // Here we actually have no choice but to call input.pumpTo() because if we called |
| 2398 | // tryPumpFrom(input, amount) and it returned nullptr, what would we do? It's too late for |
| 2399 | // us to return nullptr. But the thing about dynamic_cast also applies. |
| 2400 | return input.pumpTo(*KJ_ASSERT_NONNULL(stream), amount); |
| 2401 | }); |
| 2402 | } |
| 2403 | } |
| 2404 | |
| 2405 | Promise<void> whenWriteDisconnected() override { |
| 2406 | KJ_IF_MAYBE(s, stream) { |
| 2407 | return s->get()->whenWriteDisconnected(); |
| 2408 | } else { |
| 2409 | return promise.addBranch().then([this]() { |
| 2410 | return KJ_ASSERT_NONNULL(stream)->whenWriteDisconnected(); |
| 2411 | }, [](kj::Exception&& e) -> kj::Promise<void> { |
| 2412 | if (e.getType() == kj::Exception::Type::DISCONNECTED) { |
| 2413 | return kj::READY_NOW; |
| 2414 | } else { |
| 2415 | return kj::mv(e); |
| 2416 | } |
| 2417 | }); |
| 2418 | } |
| 2419 | } |
| 2420 | |
| 2421 | void shutdownWrite() override { |
| 2422 | KJ_IF_MAYBE(s, stream) { |
| 2423 | return s->get()->shutdownWrite(); |
| 2424 | } else { |
| 2425 | tasks.add(promise.addBranch().then([this]() { |
| 2426 | return KJ_ASSERT_NONNULL(stream)->shutdownWrite(); |
| 2427 | })); |
| 2428 | } |
| 2429 | } |
| 2430 | |
| 2431 | void abortRead() override { |
| 2432 | KJ_IF_MAYBE(s, stream) { |
| 2433 | return s->get()->abortRead(); |
| 2434 | } else { |
| 2435 | tasks.add(promise.addBranch().then([this]() { |
| 2436 | return KJ_ASSERT_NONNULL(stream)->abortRead(); |
| 2437 | })); |
| 2438 | } |
| 2439 | } |
| 2440 | |
| 2441 | kj::Maybe<int> getFd() const override { |
| 2442 | KJ_IF_MAYBE(s, stream) { |
| 2443 | return s->get()->getFd(); |
| 2444 | } else { |
| 2445 | return nullptr; |
| 2446 | } |
| 2447 | } |
| 2448 | |
| 2449 | private: |
| 2450 | kj::ForkedPromise<void> promise; |
| 2451 | kj::Maybe<kj::Own<AsyncIoStream>> stream; |
| 2452 | kj::TaskSet tasks; |
| 2453 | |
| 2454 | void taskFailed(kj::Exception&& exception) override { |
| 2455 | KJ_LOG(ERROR, exception); |
| 2456 | } |
| 2457 | }; |
| 2458 | |
| 2459 | class PromisedAsyncOutputStream final: public kj::AsyncOutputStream { |
| 2460 | // An AsyncOutputStream which waits for a promise to resolve then forwards all calls to the |
| 2461 | // promised stream. |
| 2462 | // |
| 2463 | // TODO(cleanup): Can this share implementation with PromiseIoStream? Seems hard. |
| 2464 | |
| 2465 | public: |
| 2466 | PromisedAsyncOutputStream(kj::Promise<kj::Own<AsyncOutputStream>> promise) |
| 2467 | : promise(promise.then([this](kj::Own<AsyncOutputStream> result) { |
| 2468 | stream = kj::mv(result); |
| 2469 | }).fork()) {} |
| 2470 | |
| 2471 | kj::Promise<void> write(const void* buffer, size_t size) override { |
| 2472 | KJ_IF_MAYBE(s, stream) { |
| 2473 | return s->get()->write(buffer, size); |
| 2474 | } else { |
| 2475 | return promise.addBranch().then([this,buffer,size]() { |
| 2476 | return KJ_ASSERT_NONNULL(stream)->write(buffer, size); |
| 2477 | }); |
| 2478 | } |
| 2479 | } |
| 2480 | kj::Promise<void> write(kj::ArrayPtr<const kj::ArrayPtr<const byte>> pieces) override { |
| 2481 | KJ_IF_MAYBE(s, stream) { |
| 2482 | return s->get()->write(pieces); |
| 2483 | } else { |
| 2484 | return promise.addBranch().then([this,pieces]() { |
| 2485 | return KJ_ASSERT_NONNULL(stream)->write(pieces); |
| 2486 | }); |
| 2487 | } |
| 2488 | } |
| 2489 | |
| 2490 | kj::Maybe<kj::Promise<uint64_t>> tryPumpFrom( |
| 2491 | kj::AsyncInputStream& input, uint64_t amount = kj::maxValue) override { |
| 2492 | KJ_IF_MAYBE(s, stream) { |
| 2493 | return s->get()->tryPumpFrom(input, amount); |
| 2494 | } else { |
| 2495 | return promise.addBranch().then([this,&input,amount]() { |
| 2496 | // Call input.pumpTo() on the resolved stream instead. |
| 2497 | return input.pumpTo(*KJ_ASSERT_NONNULL(stream), amount); |
| 2498 | }); |
| 2499 | } |
| 2500 | } |
| 2501 | |
| 2502 | Promise<void> whenWriteDisconnected() override { |
| 2503 | KJ_IF_MAYBE(s, stream) { |
| 2504 | return s->get()->whenWriteDisconnected(); |
| 2505 | } else { |
| 2506 | return promise.addBranch().then([this]() { |
| 2507 | return KJ_ASSERT_NONNULL(stream)->whenWriteDisconnected(); |
| 2508 | }, [](kj::Exception&& e) -> kj::Promise<void> { |
| 2509 | if (e.getType() == kj::Exception::Type::DISCONNECTED) { |
| 2510 | return kj::READY_NOW; |
| 2511 | } else { |
| 2512 | return kj::mv(e); |
| 2513 | } |
| 2514 | }); |
| 2515 | } |
| 2516 | } |
| 2517 | |
| 2518 | private: |
| 2519 | kj::ForkedPromise<void> promise; |
| 2520 | kj::Maybe<kj::Own<AsyncOutputStream>> stream; |
| 2521 | }; |
| 2522 | |
| 2523 | } // namespace |
| 2524 | |
| 2525 | Own<AsyncOutputStream> newPromisedStream(Promise<Own<AsyncOutputStream>> promise) { |
| 2526 | return heap<PromisedAsyncOutputStream>(kj::mv(promise)); |
| 2527 | } |
| 2528 | Own<AsyncIoStream> newPromisedStream(Promise<Own<AsyncIoStream>> promise) { |
| 2529 | return heap<PromisedAsyncIoStream>(kj::mv(promise)); |
| 2530 | } |
| 2531 | |
| 2532 | Promise<void> AsyncCapabilityStream::writeWithFds( |
| 2533 | ArrayPtr<const byte> data, ArrayPtr<const ArrayPtr<const byte>> moreData, |
| 2534 | ArrayPtr<const AutoCloseFd> fds) { |
| 2535 | // HACK: AutoCloseFd actually contains an `int` under the hood. We can reinterpret_cast to avoid |
| 2536 | // unnecessary memory allocation. |
| 2537 | static_assert(sizeof(AutoCloseFd) == sizeof(int), "this optimization won't work"); |
| 2538 | auto intArray = arrayPtr(reinterpret_cast<const int*>(fds.begin()), fds.size()); |
| 2539 | |
| 2540 | // Be extra-paranoid about aliasing rules by injecting a compiler barrier here. Probably |
| 2541 | // not necessary but also probably doesn't hurt. |
| 2542 | #if _MSC_VER |
| 2543 | _ReadWriteBarrier(); |
| 2544 | #else |
| 2545 | __asm__ __volatile__("": : :"memory"); |
| 2546 | #endif |
| 2547 | |
| 2548 | return writeWithFds(data, moreData, intArray); |
| 2549 | } |
| 2550 | |
| 2551 | Promise<Own<AsyncCapabilityStream>> AsyncCapabilityStream::receiveStream() { |
| 2552 | return tryReceiveStream() |
| 2553 | .then([](Maybe<Own<AsyncCapabilityStream>>&& result) |
| 2554 | -> Promise<Own<AsyncCapabilityStream>> { |
| 2555 | KJ_IF_MAYBE(r, result) { |
| 2556 | return kj::mv(*r); |
| 2557 | } else { |
| 2558 | return KJ_EXCEPTION(FAILED, "EOF when expecting to receive capability"); |
| 2559 | } |
| 2560 | }); |
| 2561 | } |
| 2562 | |
| 2563 | kj::Promise<Maybe<Own<AsyncCapabilityStream>>> AsyncCapabilityStream::tryReceiveStream() { |
| 2564 | struct ResultHolder { |
| 2565 | byte b; |
| 2566 | Own<AsyncCapabilityStream> stream; |
| 2567 | }; |
| 2568 | auto result = kj::heap<ResultHolder>(); |
| 2569 | auto promise = tryReadWithStreams(&result->b, 1, 1, &result->stream, 1); |
| 2570 | return promise.then([result = kj::mv(result)](ReadResult actual) mutable |
| 2571 | -> Maybe<Own<AsyncCapabilityStream>> { |
| 2572 | if (actual.byteCount == 0) { |
| 2573 | return nullptr; |
| 2574 | } |
| 2575 | |
| 2576 | KJ_REQUIRE(actual.capCount == 1, |
| 2577 | "expected to receive a capability (e.g. file descriptor via SCM_RIGHTS), but didn't") { |
| 2578 | return nullptr; |
| 2579 | } |
| 2580 | |
| 2581 | return kj::mv(result->stream); |
| 2582 | }); |
| 2583 | } |
| 2584 | |
| 2585 | Promise<void> AsyncCapabilityStream::sendStream(Own<AsyncCapabilityStream> stream) { |
| 2586 | static constexpr byte b = 0; |
| 2587 | auto streams = kj::heapArray<Own<AsyncCapabilityStream>>(1); |
| 2588 | streams[0] = kj::mv(stream); |
| 2589 | return writeWithStreams(arrayPtr(&b, 1), nullptr, kj::mv(streams)); |
| 2590 | } |
| 2591 | |
| 2592 | Promise<AutoCloseFd> AsyncCapabilityStream::receiveFd() { |
| 2593 | return tryReceiveFd().then([](Maybe<AutoCloseFd>&& result) -> Promise<AutoCloseFd> { |
| 2594 | KJ_IF_MAYBE(r, result) { |
| 2595 | return kj::mv(*r); |
| 2596 | } else { |
| 2597 | return KJ_EXCEPTION(FAILED, "EOF when expecting to receive capability"); |
| 2598 | } |
| 2599 | }); |
| 2600 | } |
| 2601 | |
| 2602 | kj::Promise<kj::Maybe<AutoCloseFd>> AsyncCapabilityStream::tryReceiveFd() { |
| 2603 | struct ResultHolder { |
| 2604 | byte b; |
| 2605 | AutoCloseFd fd; |
| 2606 | }; |
| 2607 | auto result = kj::heap<ResultHolder>(); |
| 2608 | auto promise = tryReadWithFds(&result->b, 1, 1, &result->fd, 1); |
| 2609 | return promise.then([result = kj::mv(result)](ReadResult actual) mutable |
| 2610 | -> Maybe<AutoCloseFd> { |
| 2611 | if (actual.byteCount == 0) { |
| 2612 | return nullptr; |
| 2613 | } |
| 2614 | |
| 2615 | KJ_REQUIRE(actual.capCount == 1, |
| 2616 | "expected to receive a file descriptor (e.g. via SCM_RIGHTS), but didn't") { |
| 2617 | return nullptr; |
| 2618 | } |
| 2619 | |
| 2620 | return kj::mv(result->fd); |
| 2621 | }); |
| 2622 | } |
| 2623 | |
| 2624 | Promise<void> AsyncCapabilityStream::sendFd(int fd) { |
| 2625 | static constexpr byte b = 0; |
| 2626 | auto fds = kj::heapArray<int>(1); |
| 2627 | fds[0] = fd; |
| 2628 | auto promise = writeWithFds(arrayPtr(&b, 1), nullptr, fds); |
| 2629 | return promise.attach(kj::mv(fds)); |
| 2630 | } |
| 2631 | |
| 2632 | void AsyncIoStream::getsockopt(int level, int option, void* value, uint* length) { |
| 2633 | KJ_UNIMPLEMENTED("Not a socket.") { *length = 0; break; } |
| 2634 | } |
| 2635 | void AsyncIoStream::setsockopt(int level, int option, const void* value, uint length) { |
| 2636 | KJ_UNIMPLEMENTED("Not a socket.") { break; } |
| 2637 | } |
| 2638 | void AsyncIoStream::getsockname(struct sockaddr* addr, uint* length) { |
| 2639 | KJ_UNIMPLEMENTED("Not a socket.") { *length = 0; break; } |
| 2640 | } |
| 2641 | void AsyncIoStream::getpeername(struct sockaddr* addr, uint* length) { |
| 2642 | KJ_UNIMPLEMENTED("Not a socket.") { *length = 0; break; } |
| 2643 | } |
| 2644 | void ConnectionReceiver::getsockopt(int level, int option, void* value, uint* length) { |
| 2645 | KJ_UNIMPLEMENTED("Not a socket.") { *length = 0; break; } |
| 2646 | } |
| 2647 | void ConnectionReceiver::setsockopt(int level, int option, const void* value, uint length) { |
| 2648 | KJ_UNIMPLEMENTED("Not a socket.") { break; } |
| 2649 | } |
| 2650 | void ConnectionReceiver::getsockname(struct sockaddr* addr, uint* length) { |
| 2651 | KJ_UNIMPLEMENTED("Not a socket.") { *length = 0; break; } |
| 2652 | } |
| 2653 | void DatagramPort::getsockopt(int level, int option, void* value, uint* length) { |
| 2654 | KJ_UNIMPLEMENTED("Not a socket.") { *length = 0; break; } |
| 2655 | } |
| 2656 | void DatagramPort::setsockopt(int level, int option, const void* value, uint length) { |
| 2657 | KJ_UNIMPLEMENTED("Not a socket.") { break; } |
| 2658 | } |
| 2659 | Own<DatagramPort> NetworkAddress::bindDatagramPort() { |
| 2660 | KJ_UNIMPLEMENTED("Datagram sockets not implemented."); |
| 2661 | } |
| 2662 | Own<DatagramPort> LowLevelAsyncIoProvider::wrapDatagramSocketFd( |
| 2663 | Fd fd, LowLevelAsyncIoProvider::NetworkFilter& filter, uint flags) { |
| 2664 | KJ_UNIMPLEMENTED("Datagram sockets not implemented."); |
| 2665 | } |
| 2666 | #if !_WIN32 |
| 2667 | Own<AsyncCapabilityStream> LowLevelAsyncIoProvider::wrapUnixSocketFd(Fd fd, uint flags) { |
| 2668 | KJ_UNIMPLEMENTED("Unix socket with FD passing not implemented."); |
| 2669 | } |
| 2670 | #endif |
| 2671 | CapabilityPipe AsyncIoProvider::newCapabilityPipe() { |
| 2672 | KJ_UNIMPLEMENTED("Capability pipes not implemented."); |
| 2673 | } |
| 2674 | |
| 2675 | Own<AsyncInputStream> LowLevelAsyncIoProvider::wrapInputFd(OwnFd&& fd, uint flags) { |
| 2676 | return wrapInputFd(reinterpret_cast<Fd>(fd.release()), flags | TAKE_OWNERSHIP); |
| 2677 | } |
| 2678 | Own<AsyncOutputStream> LowLevelAsyncIoProvider::wrapOutputFd(OwnFd&& fd, uint flags) { |
| 2679 | return wrapOutputFd(reinterpret_cast<Fd>(fd.release()), flags | TAKE_OWNERSHIP); |
| 2680 | } |
| 2681 | Own<AsyncIoStream> LowLevelAsyncIoProvider::wrapSocketFd(OwnFd&& fd, uint flags) { |
| 2682 | return wrapSocketFd(reinterpret_cast<Fd>(fd.release()), flags | TAKE_OWNERSHIP); |
| 2683 | } |
| 2684 | #if !_WIN32 |
| 2685 | Own<AsyncCapabilityStream> LowLevelAsyncIoProvider::wrapUnixSocketFd(OwnFd&& fd, uint flags) { |
| 2686 | return wrapUnixSocketFd(reinterpret_cast<Fd>(fd.release()), flags | TAKE_OWNERSHIP); |
| 2687 | } |
| 2688 | #endif |
| 2689 | Promise<Own<AsyncIoStream>> LowLevelAsyncIoProvider::wrapConnectingSocketFd( |
| 2690 | OwnFd&& fd, const struct sockaddr* addr, uint addrlen, uint flags) { |
| 2691 | return wrapConnectingSocketFd(reinterpret_cast<Fd>(fd.release()), addr, addrlen, |
| 2692 | flags | TAKE_OWNERSHIP); |
| 2693 | } |
| 2694 | Own<ConnectionReceiver> LowLevelAsyncIoProvider::wrapListenSocketFd( |
| 2695 | OwnFd&& fd, NetworkFilter& filter, uint flags) { |
| 2696 | return wrapListenSocketFd(reinterpret_cast<Fd>(fd.release()), filter, flags | TAKE_OWNERSHIP); |
| 2697 | } |
| 2698 | Own<ConnectionReceiver> LowLevelAsyncIoProvider::wrapListenSocketFd(OwnFd&& fd, uint flags) { |
| 2699 | return wrapListenSocketFd(reinterpret_cast<Fd>(fd.release()), flags | TAKE_OWNERSHIP); |
| 2700 | } |
| 2701 | Own<DatagramPort> LowLevelAsyncIoProvider::wrapDatagramSocketFd( |
| 2702 | OwnFd&& fd, NetworkFilter& filter, uint flags) { |
| 2703 | return wrapDatagramSocketFd(reinterpret_cast<Fd>(fd.release()), filter, flags | TAKE_OWNERSHIP); |
| 2704 | } |
| 2705 | Own<DatagramPort> LowLevelAsyncIoProvider::wrapDatagramSocketFd(OwnFd&& fd, uint flags) { |
| 2706 | return wrapDatagramSocketFd(reinterpret_cast<Fd>(fd.release()), flags | TAKE_OWNERSHIP); |
| 2707 | } |
| 2708 | |
| 2709 | namespace { |
| 2710 | |
| 2711 | class DummyNetworkFilter: public kj::LowLevelAsyncIoProvider::NetworkFilter { |
| 2712 | public: |
| 2713 | bool shouldAllow(const struct sockaddr* addr, uint addrlen) override { return true; } |
| 2714 | }; |
| 2715 | |
| 2716 | } // namespace |
| 2717 | |
| 2718 | LowLevelAsyncIoProvider::NetworkFilter& LowLevelAsyncIoProvider::NetworkFilter::getAllAllowed() { |
| 2719 | static DummyNetworkFilter result; |
| 2720 | return result; |
| 2721 | } |
| 2722 | |
| 2723 | // ======================================================================================= |
| 2724 | // Convenience adapters. |
| 2725 | |
| 2726 | Promise<Own<AsyncIoStream>> CapabilityStreamConnectionReceiver::accept() { |
| 2727 | return inner.receiveStream() |
| 2728 | .then([](Own<AsyncCapabilityStream>&& stream) -> Own<AsyncIoStream> { |
| 2729 | return kj::mv(stream); |
| 2730 | }); |
| 2731 | } |
| 2732 | |
| 2733 | Promise<AuthenticatedStream> CapabilityStreamConnectionReceiver::acceptAuthenticated() { |
| 2734 | return accept().then([](Own<AsyncIoStream>&& stream) { |
| 2735 | return AuthenticatedStream { kj::mv(stream), UnknownPeerIdentity::newInstance() }; |
| 2736 | }); |
| 2737 | } |
| 2738 | |
| 2739 | uint CapabilityStreamConnectionReceiver::getPort() { |
| 2740 | return 0; |
| 2741 | } |
| 2742 | |
| 2743 | Promise<Own<AsyncIoStream>> CapabilityStreamNetworkAddress::connect() { |
| 2744 | CapabilityPipe pipe; |
| 2745 | KJ_IF_MAYBE(p, provider) { |
| 2746 | pipe = p->newCapabilityPipe(); |
| 2747 | } else { |
| 2748 | pipe = kj::newCapabilityPipe(); |
| 2749 | } |
| 2750 | auto result = kj::mv(pipe.ends[0]); |
| 2751 | return inner.sendStream(kj::mv(pipe.ends[1])) |
| 2752 | .then([result=kj::mv(result)]() mutable { |
| 2753 | return Own<AsyncIoStream>(kj::mv(result)); |
| 2754 | }); |
| 2755 | } |
| 2756 | Promise<AuthenticatedStream> CapabilityStreamNetworkAddress::connectAuthenticated() { |
| 2757 | return connect().then([](Own<AsyncIoStream>&& stream) { |
| 2758 | return AuthenticatedStream { kj::mv(stream), UnknownPeerIdentity::newInstance() }; |
| 2759 | }); |
| 2760 | } |
| 2761 | Own<ConnectionReceiver> CapabilityStreamNetworkAddress::listen() { |
| 2762 | return kj::heap<CapabilityStreamConnectionReceiver>(inner); |
| 2763 | } |
| 2764 | |
| 2765 | Own<NetworkAddress> CapabilityStreamNetworkAddress::clone() { |
| 2766 | KJ_UNIMPLEMENTED("can't clone CapabilityStreamNetworkAddress"); |
| 2767 | } |
| 2768 | String CapabilityStreamNetworkAddress::toString() { |
| 2769 | return kj::str("<CapabilityStreamNetworkAddress>"); |
| 2770 | } |
| 2771 | |
| 2772 | Promise<size_t> FileInputStream::tryRead(void* buffer, size_t minBytes, size_t maxBytes) { |
| 2773 | // Note that our contract with `minBytes` is that we should only return fewer than `minBytes` on |
| 2774 | // EOF. A file read will only produce fewer than the requested number of bytes if EOF was reached. |
| 2775 | // `minBytes` cannot be greater than `maxBytes`. So, this read satisfies the `minBytes` |
| 2776 | // requirement. |
| 2777 | size_t result = file.read(offset, arrayPtr(reinterpret_cast<byte*>(buffer), maxBytes)); |
| 2778 | offset += result; |
| 2779 | return result; |
| 2780 | } |
| 2781 | |
| 2782 | Maybe<uint64_t> FileInputStream::tryGetLength() { |
| 2783 | uint64_t size = file.stat().size; |
| 2784 | return offset < size ? size - offset : 0; |
| 2785 | } |
| 2786 | |
| 2787 | Promise<void> FileOutputStream::write(const void* buffer, size_t size) { |
| 2788 | file.write(offset, arrayPtr(reinterpret_cast<const byte*>(buffer), size)); |
| 2789 | offset += size; |
| 2790 | return kj::READY_NOW; |
| 2791 | } |
| 2792 | |
| 2793 | Promise<void> FileOutputStream::write(ArrayPtr<const ArrayPtr<const byte>> pieces) { |
| 2794 | // TODO(perf): Extend kj::File with an array-of-arrays write? |
| 2795 | for (auto piece: pieces) { |
| 2796 | file.write(offset, piece); |
| 2797 | offset += piece.size(); |
| 2798 | } |
| 2799 | return kj::READY_NOW; |
| 2800 | } |
| 2801 | |
| 2802 | Promise<void> FileOutputStream::whenWriteDisconnected() { |
| 2803 | return kj::NEVER_DONE; |
| 2804 | } |
| 2805 | |
| 2806 | // ======================================================================================= |
| 2807 | |
| 2808 | namespace { |
| 2809 | |
| 2810 | class AggregateConnectionReceiver final: public ConnectionReceiver { |
| 2811 | public: |
| 2812 | AggregateConnectionReceiver(Array<Own<ConnectionReceiver>> receiversParam) |
| 2813 | : receivers(kj::mv(receiversParam)), |
| 2814 | acceptTasks(kj::heapArray<Maybe<Promise<void>>>(receivers.size())) {} |
| 2815 | |
| 2816 | Promise<Own<AsyncIoStream>> accept() override { |
| 2817 | return acceptAuthenticated().then([](AuthenticatedStream&& authenticated) { |
| 2818 | return kj::mv(authenticated.stream); |
| 2819 | }); |
| 2820 | } |
| 2821 | |
| 2822 | Promise<AuthenticatedStream> acceptAuthenticated() override { |
| 2823 | // Whenever our accept() is called, we want it to resolve to the first connection accepted by |
| 2824 | // any of our child receivers. Naively, it may seem like we should call accept() on them all |
| 2825 | // and exclusiveJoin() the results. Unfortunately, this might not work in a certain race |
| 2826 | // condition: if two or more of our children receive connections simultaneously, both child |
| 2827 | // accept() calls may return, but we'll only end up taking one and dropping the other. |
| 2828 | // |
| 2829 | // To avoid this problem, we must instead initiate `accept()` calls on all children, and even |
| 2830 | // after one of them returns a result, we must allow the others to keep running. If we end up |
| 2831 | // accepting any sockets from children when there is no outstanding accept() on the aggregate, |
| 2832 | // we must put that socket into a backlog. We only restart accept() calls on children if the |
| 2833 | // backlog is empty, and hence the maximum length of the backlog is the number of children |
| 2834 | // minus 1. |
| 2835 | |
| 2836 | if (backlog.empty()) { |
| 2837 | auto result = kj::newAdaptedPromise<AuthenticatedStream, Waiter>(*this); |
| 2838 | ensureAllAccepting(); |
| 2839 | return result; |
| 2840 | } else { |
| 2841 | auto result = kj::mv(backlog.front()); |
| 2842 | backlog.pop_front(); |
| 2843 | return result; |
| 2844 | } |
| 2845 | } |
| 2846 | |
| 2847 | uint getPort() override { |
| 2848 | return receivers[0]->getPort(); |
| 2849 | } |
| 2850 | void getsockopt(int level, int option, void* value, uint* length) override { |
| 2851 | return receivers[0]->getsockopt(level, option, value, length); |
| 2852 | } |
| 2853 | void setsockopt(int level, int option, const void* value, uint length) override { |
| 2854 | // Apply to all. |
| 2855 | for (auto& r: receivers) { |
| 2856 | r->setsockopt(level, option, value, length); |
| 2857 | } |
| 2858 | } |
| 2859 | void getsockname(struct sockaddr* addr, uint* length) override { |
| 2860 | return receivers[0]->getsockname(addr, length); |
| 2861 | } |
| 2862 | |
| 2863 | private: |
| 2864 | Array<Own<ConnectionReceiver>> receivers; |
| 2865 | Array<Maybe<Promise<void>>> acceptTasks; |
| 2866 | |
| 2867 | struct Waiter { |
| 2868 | Waiter(PromiseFulfiller<AuthenticatedStream>& fulfiller, |
| 2869 | AggregateConnectionReceiver& parent) |
| 2870 | : fulfiller(fulfiller), parent(parent) { |
| 2871 | parent.waiters.add(*this); |
| 2872 | } |
| 2873 | ~Waiter() noexcept(false) { |
| 2874 | if (link.isLinked()) { |
| 2875 | parent.waiters.remove(*this); |
| 2876 | } |
| 2877 | } |
| 2878 | |
| 2879 | PromiseFulfiller<AuthenticatedStream>& fulfiller; |
| 2880 | AggregateConnectionReceiver& parent; |
| 2881 | ListLink<Waiter> link; |
| 2882 | }; |
| 2883 | |
| 2884 | List<Waiter, &Waiter::link> waiters; |
| 2885 | std::deque<Promise<AuthenticatedStream>> backlog; |
| 2886 | // At least one of `waiters` or `backlog` is always empty. |
| 2887 | |
| 2888 | void ensureAllAccepting() { |
| 2889 | for (auto i: kj::indices(receivers)) { |
| 2890 | if (acceptTasks[i] == nullptr) { |
| 2891 | acceptTasks[i] = acceptLoop(i); |
| 2892 | } |
| 2893 | } |
| 2894 | } |
| 2895 | |
| 2896 | Promise<void> acceptLoop(size_t index) { |
| 2897 | return kj::evalNow([&]() { return receivers[index]->acceptAuthenticated(); }) |
| 2898 | .then([this](AuthenticatedStream&& as) { |
| 2899 | if (waiters.empty()) { |
| 2900 | backlog.push_back(kj::mv(as)); |
| 2901 | } else { |
| 2902 | auto& waiter = waiters.front(); |
| 2903 | waiter.fulfiller.fulfill(kj::mv(as)); |
| 2904 | waiters.remove(waiter); |
| 2905 | } |
| 2906 | }, [this](Exception&& e) { |
| 2907 | if (waiters.empty()) { |
| 2908 | backlog.push_back(kj::mv(e)); |
| 2909 | } else { |
| 2910 | auto& waiter = waiters.front(); |
| 2911 | waiter.fulfiller.reject(kj::mv(e)); |
| 2912 | waiters.remove(waiter); |
| 2913 | } |
| 2914 | }).then([this, index]() -> Promise<void> { |
| 2915 | if (waiters.empty()) { |
| 2916 | // Don't keep accepting if there's no one waiting. |
| 2917 | // HACK: We can't cancel ourselves, so detach the task so we can null out the slot. |
| 2918 | // We know that the promise we're detaching here is exactly the promise that's currently |
| 2919 | // executing and has no further `.then()`s on it, so no further callbacks will run in |
| 2920 | // detached state... we're just using `detach()` as a tricky way to have the event loop |
| 2921 | // dispose of this promise later after we've returned. |
| 2922 | // TODO(cleanup): This pattern has come up several times, we need a better way to handle |
| 2923 | // it. |
| 2924 | KJ_ASSERT_NONNULL(acceptTasks[index]).detach([](auto&&) {}); |
| 2925 | acceptTasks[index] = nullptr; |
| 2926 | return READY_NOW; |
| 2927 | } else { |
| 2928 | return acceptLoop(index); |
| 2929 | } |
| 2930 | }); |
| 2931 | } |
| 2932 | }; |
| 2933 | |
| 2934 | } // namespace |
| 2935 | |
| 2936 | Own<ConnectionReceiver> newAggregateConnectionReceiver(Array<Own<ConnectionReceiver>> receivers) { |
| 2937 | return kj::heap<AggregateConnectionReceiver>(kj::mv(receivers)); |
| 2938 | } |
| 2939 | |
| 2940 | // ----------------------------------------------------------------------------- |
| 2941 | |
| 2942 | namespace _ { // private |
| 2943 | |
| 2944 | #if !_WIN32 |
| 2945 | |
| 2946 | kj::ArrayPtr<const char> safeUnixPath(const struct sockaddr_un* addr, uint addrlen) { |
| 2947 | KJ_REQUIRE(addr->sun_family == AF_UNIX, "not a unix address"); |
| 2948 | KJ_REQUIRE(addrlen >= offsetof(sockaddr_un, sun_path), "invalid unix address"); |
| 2949 | |
| 2950 | size_t maxPathlen = addrlen - offsetof(sockaddr_un, sun_path); |
| 2951 | |
| 2952 | size_t pathlen; |
| 2953 | if (maxPathlen > 0 && addr->sun_path[0] == '\0') { |
| 2954 | // Linux "abstract" unix address |
| 2955 | pathlen = strnlen(addr->sun_path + 1, maxPathlen - 1) + 1; |
| 2956 | } else { |
| 2957 | pathlen = strnlen(addr->sun_path, maxPathlen); |
| 2958 | } |
| 2959 | return kj::arrayPtr(addr->sun_path, pathlen); |
| 2960 | } |
| 2961 | |
| 2962 | #endif // !_WIN32 |
| 2963 | |
| 2964 | ArrayPtr<const CidrRange> localCidrs() { |
| 2965 | static const CidrRange result[] = { |
| 2966 | // localhost |
| 2967 | "127.0.0.0/8"_kj, |
| 2968 | "::1/128"_kj, |
| 2969 | |
| 2970 | // Trying to *connect* to 0.0.0.0 on many systems is equivalent to connecting to localhost. |
| 2971 | // (wat) |
| 2972 | "0.0.0.0/32"_kj, |
| 2973 | "::/128"_kj, |
| 2974 | }; |
| 2975 | |
| 2976 | // TODO(cleanup): A bug in GCC 4.8, fixed in 4.9, prevents result from implicitly |
| 2977 | // casting to our return type. |
| 2978 | return kj::arrayPtr(result, kj::size(result)); |
| 2979 | } |
| 2980 | |
| 2981 | ArrayPtr<const CidrRange> privateCidrs() { |
| 2982 | static const CidrRange result[] = { |
| 2983 | "10.0.0.0/8"_kj, // RFC1918 reserved for internal network |
| 2984 | "100.64.0.0/10"_kj, // RFC6598 "shared address space" for carrier-grade NAT |
| 2985 | "169.254.0.0/16"_kj, // RFC3927 "link local" (auto-configured LAN in absence of DHCP) |
| 2986 | "172.16.0.0/12"_kj, // RFC1918 reserved for internal network |
| 2987 | "192.168.0.0/16"_kj, // RFC1918 reserved for internal network |
| 2988 | |
| 2989 | "fc00::/7"_kj, // RFC4193 unique private network |
| 2990 | "fe80::/10"_kj, // RFC4291 "link local" (auto-configured LAN in absence of DHCP) |
| 2991 | }; |
| 2992 | |
| 2993 | // TODO(cleanup): A bug in GCC 4.8, fixed in 4.9, prevents result from implicitly |
| 2994 | // casting to our return type. |
| 2995 | return kj::arrayPtr(result, kj::size(result)); |
| 2996 | } |
| 2997 | |
| 2998 | ArrayPtr<const CidrRange> reservedCidrs() { |
| 2999 | static const CidrRange result[] = { |
| 3000 | "192.0.0.0/24"_kj, // RFC6890 reserved for special protocols |
| 3001 | "224.0.0.0/4"_kj, // RFC1112 multicast |
| 3002 | "240.0.0.0/4"_kj, // RFC1112 multicast / reserved for future use |
| 3003 | "255.255.255.255/32"_kj, // RFC0919 broadcast address |
| 3004 | |
| 3005 | "2001::/23"_kj, // RFC2928 reserved for special protocols |
| 3006 | "ff00::/8"_kj, // RFC4291 multicast |
| 3007 | }; |
| 3008 | |
| 3009 | // TODO(cleanup): A bug in GCC 4.8, fixed in 4.9, prevents result from implicitly |
| 3010 | // casting to our return type. |
| 3011 | return kj::arrayPtr(result, kj::size(result)); |
| 3012 | } |
| 3013 | |
| 3014 | ArrayPtr<const CidrRange> exampleAddresses() { |
| 3015 | static const CidrRange result[] = { |
| 3016 | "192.0.2.0/24"_kj, // RFC5737 "example address" block 1 -- like example.com for IPs |
| 3017 | "198.51.100.0/24"_kj, // RFC5737 "example address" block 2 -- like example.com for IPs |
| 3018 | "203.0.113.0/24"_kj, // RFC5737 "example address" block 3 -- like example.com for IPs |
| 3019 | "2001:db8::/32"_kj, // RFC3849 "example address" block -- like example.com for IPs |
| 3020 | }; |
| 3021 | |
| 3022 | // TODO(cleanup): A bug in GCC 4.8, fixed in 4.9, prevents result from implicitly |
| 3023 | // casting to our return type. |
| 3024 | return kj::arrayPtr(result, kj::size(result)); |
| 3025 | } |
| 3026 | |
| 3027 | bool matchesAny(ArrayPtr<const CidrRange> cidrs, const struct sockaddr* addr) { |
| 3028 | for (auto& cidr: cidrs) { |
| 3029 | if (cidr.matches(addr)) return true; |
| 3030 | } |
| 3031 | return false; |
| 3032 | } |
| 3033 | |
| 3034 | NetworkFilter::NetworkFilter() |
| 3035 | : allowUnix(true), allowAbstractUnix(true) { |
| 3036 | allowCidrs.add(CidrRange::inet4({0,0,0,0}, 0)); |
| 3037 | allowCidrs.add(CidrRange::inet6({}, {}, 0)); |
| 3038 | denyCidrs.addAll(reservedCidrs()); |
| 3039 | } |
| 3040 | |
| 3041 | NetworkFilter::NetworkFilter(ArrayPtr<const StringPtr> allow, ArrayPtr<const StringPtr> deny, |
| 3042 | NetworkFilter& next) |
| 3043 | : allowUnix(false), allowAbstractUnix(false), next(next) { |
| 3044 | for (auto rule: allow) { |
| 3045 | if (rule == "local") { |
| 3046 | allowCidrs.addAll(localCidrs()); |
| 3047 | } else if (rule == "network") { |
| 3048 | // Can't be represented as a simple union of CIDRs, so we handle in shouldAllow(). |
| 3049 | allowNetwork = true; |
| 3050 | } else if (rule == "private") { |
| 3051 | allowCidrs.addAll(privateCidrs()); |
| 3052 | allowCidrs.addAll(localCidrs()); |
| 3053 | } else if (rule == "public") { |
| 3054 | // Can't be represented as a simple union of CIDRs, so we handle in shouldAllow(). |
| 3055 | allowPublic = true; |
| 3056 | } else if (rule == "unix") { |
| 3057 | allowUnix = true; |
| 3058 | } else if (rule == "unix-abstract") { |
| 3059 | allowAbstractUnix = true; |
| 3060 | } else { |
| 3061 | allowCidrs.add(CidrRange(rule)); |
| 3062 | } |
| 3063 | } |
| 3064 | |
| 3065 | for (auto rule: deny) { |
| 3066 | if (rule == "local") { |
| 3067 | denyCidrs.addAll(localCidrs()); |
| 3068 | } else if (rule == "network") { |
| 3069 | KJ_FAIL_REQUIRE("don't deny 'network', allow 'local' instead"); |
| 3070 | } else if (rule == "private") { |
| 3071 | denyCidrs.addAll(privateCidrs()); |
| 3072 | } else if (rule == "public") { |
| 3073 | // Tricky: What if we allow 'network' and deny 'public'? |
| 3074 | KJ_FAIL_REQUIRE("don't deny 'public', allow 'private' instead"); |
| 3075 | } else if (rule == "unix") { |
| 3076 | allowUnix = false; |
| 3077 | } else if (rule == "unix-abstract") { |
| 3078 | allowAbstractUnix = false; |
| 3079 | } else { |
| 3080 | denyCidrs.add(CidrRange(rule)); |
| 3081 | } |
| 3082 | } |
| 3083 | } |
| 3084 | |
| 3085 | bool NetworkFilter::shouldAllow(const struct sockaddr* addr, uint addrlen) { |
| 3086 | KJ_REQUIRE(addrlen >= sizeof(addr->sa_family)); |
| 3087 | |
| 3088 | #if !_WIN32 |
| 3089 | if (addr->sa_family == AF_UNIX) { |
| 3090 | auto path = safeUnixPath(reinterpret_cast<const struct sockaddr_un*>(addr), addrlen); |
| 3091 | if (path.size() > 0 && path[0] == '\0') { |
| 3092 | return allowAbstractUnix; |
| 3093 | } else { |
| 3094 | return allowUnix; |
| 3095 | } |
| 3096 | } |
| 3097 | #endif |
| 3098 | |
| 3099 | bool allowed = false; |
| 3100 | uint allowSpecificity = 0; |
| 3101 | |
| 3102 | if (allowPublic) { |
| 3103 | if ((addr->sa_family == AF_INET || addr->sa_family == AF_INET6) && |
| 3104 | !matchesAny(privateCidrs(), addr) && !matchesAny(localCidrs(), addr)) { |
| 3105 | allowed = true; |
| 3106 | // Don't adjust allowSpecificity as this match has an effective specificity of zero. |
| 3107 | } |
| 3108 | } |
| 3109 | |
| 3110 | if (allowNetwork) { |
| 3111 | if ((addr->sa_family == AF_INET || addr->sa_family == AF_INET6) && |
| 3112 | !matchesAny(localCidrs(), addr)) { |
| 3113 | allowed = true; |
| 3114 | // Don't adjust allowSpecificity as this match has an effective specificity of zero. |
| 3115 | } |
| 3116 | } |
| 3117 | |
| 3118 | for (auto& cidr: allowCidrs) { |
| 3119 | if (cidr.matches(addr)) { |
| 3120 | allowSpecificity = kj::max(allowSpecificity, cidr.getSpecificity()); |
| 3121 | allowed = true; |
| 3122 | } |
| 3123 | } |
| 3124 | if (!allowed) return false; |
| 3125 | for (auto& cidr: denyCidrs) { |
| 3126 | if (cidr.matches(addr)) { |
| 3127 | if (cidr.getSpecificity() >= allowSpecificity) return false; |
| 3128 | } |
| 3129 | } |
| 3130 | |
| 3131 | KJ_IF_MAYBE(n, next) { |
| 3132 | return n->shouldAllow(addr, addrlen); |
| 3133 | } else { |
| 3134 | return true; |
| 3135 | } |
| 3136 | } |
| 3137 | |
| 3138 | bool NetworkFilter::shouldAllowParse(const struct sockaddr* addr, uint addrlen) { |
| 3139 | bool matched = false; |
| 3140 | #if !_WIN32 |
| 3141 | if (addr->sa_family == AF_UNIX) { |
| 3142 | auto path = safeUnixPath(reinterpret_cast<const struct sockaddr_un*>(addr), addrlen); |
| 3143 | if (path.size() > 0 && path[0] == '\0') { |
| 3144 | if (allowAbstractUnix) matched = true; |
| 3145 | } else { |
| 3146 | if (allowUnix) matched = true; |
| 3147 | } |
| 3148 | } else { |
| 3149 | #endif |
| 3150 | if ((addr->sa_family == AF_INET || addr->sa_family == AF_INET6) && |
| 3151 | (allowPublic || allowNetwork)) { |
| 3152 | matched = true; |
| 3153 | } |
| 3154 | for (auto& cidr: allowCidrs) { |
| 3155 | if (cidr.matchesFamily(addr->sa_family)) { |
| 3156 | matched = true; |
| 3157 | } |
| 3158 | } |
| 3159 | #if !_WIN32 |
| 3160 | } |
| 3161 | #endif |
| 3162 | |
| 3163 | if (matched) { |
| 3164 | KJ_IF_MAYBE(n, next) { |
| 3165 | return n->shouldAllowParse(addr, addrlen); |
| 3166 | } else { |
| 3167 | return true; |
| 3168 | } |
| 3169 | } else { |
| 3170 | // No allow rule matches this address family, so don't even allow parsing it. |
| 3171 | return false; |
| 3172 | } |
| 3173 | } |
| 3174 | |
| 3175 | } // namespace _ (private) |
| 3176 | |
| 3177 | // ======================================================================================= |
| 3178 | // PeerIdentity implementations |
| 3179 | |
| 3180 | namespace { |
| 3181 | |
| 3182 | class NetworkPeerIdentityImpl final: public NetworkPeerIdentity { |
| 3183 | public: |
| 3184 | NetworkPeerIdentityImpl(kj::Own<NetworkAddress> addr): addr(kj::mv(addr)) {} |
| 3185 | |
| 3186 | kj::String toString() override { return addr->toString(); } |
| 3187 | NetworkAddress& getAddress() override { return *addr; } |
| 3188 | |
| 3189 | private: |
| 3190 | kj::Own<NetworkAddress> addr; |
| 3191 | }; |
| 3192 | |
| 3193 | class LocalPeerIdentityImpl final: public LocalPeerIdentity { |
| 3194 | public: |
| 3195 | LocalPeerIdentityImpl(Credentials creds): creds(creds) {} |
| 3196 | |
| 3197 | kj::String toString() override { |
| 3198 | char pidBuffer[16]; |
| 3199 | kj::StringPtr pidStr = nullptr; |
| 3200 | KJ_IF_MAYBE(p, creds.pid) { |
| 3201 | pidStr = strPreallocated(pidBuffer, " pid:", *p); |
| 3202 | } |
| 3203 | |
| 3204 | char uidBuffer[16]; |
| 3205 | kj::StringPtr uidStr = nullptr; |
| 3206 | KJ_IF_MAYBE(u, creds.uid) { |
| 3207 | uidStr = strPreallocated(uidBuffer, " uid:", *u); |
| 3208 | } |
| 3209 | |
| 3210 | return kj::str("(local peer", pidStr, uidStr, ")"); |
| 3211 | } |
| 3212 | |
| 3213 | Credentials getCredentials() override { return creds; } |
| 3214 | |
| 3215 | private: |
| 3216 | Credentials creds; |
| 3217 | }; |
| 3218 | |
| 3219 | class UnknownPeerIdentityImpl final: public UnknownPeerIdentity { |
| 3220 | public: |
| 3221 | kj::String toString() override { |
| 3222 | return kj::str("(unknown peer)"); |
| 3223 | } |
| 3224 | }; |
| 3225 | |
| 3226 | } // namespace |
| 3227 | |
| 3228 | kj::Own<NetworkPeerIdentity> NetworkPeerIdentity::newInstance(kj::Own<NetworkAddress> addr) { |
| 3229 | return kj::heap<NetworkPeerIdentityImpl>(kj::mv(addr)); |
| 3230 | } |
| 3231 | |
| 3232 | kj::Own<LocalPeerIdentity> LocalPeerIdentity::newInstance(LocalPeerIdentity::Credentials creds) { |
| 3233 | return kj::heap<LocalPeerIdentityImpl>(creds); |
| 3234 | } |
| 3235 | |
| 3236 | kj::Own<UnknownPeerIdentity> UnknownPeerIdentity::newInstance() { |
| 3237 | static UnknownPeerIdentityImpl instance; |
| 3238 | return { &instance, NullDisposer::instance }; |
| 3239 | } |
| 3240 | |
| 3241 | Promise<AuthenticatedStream> ConnectionReceiver::acceptAuthenticated() { |
| 3242 | return accept().then([](Own<AsyncIoStream> stream) { |
| 3243 | return AuthenticatedStream { kj::mv(stream), UnknownPeerIdentity::newInstance() }; |
| 3244 | }); |
| 3245 | } |
| 3246 | |
| 3247 | Promise<AuthenticatedStream> NetworkAddress::connectAuthenticated() { |
| 3248 | return connect().then([](Own<AsyncIoStream> stream) { |
| 3249 | return AuthenticatedStream { kj::mv(stream), UnknownPeerIdentity::newInstance() }; |
| 3250 | }); |
| 3251 | } |
| 3252 | |
| 3253 | } // namespace kj |