Chris@50: // Copyright (c) 2013-2014 Sandstorm Development Group, Inc. and contributors Chris@50: // Licensed under the MIT License: Chris@50: // Chris@50: // Permission is hereby granted, free of charge, to any person obtaining a copy Chris@50: // of this software and associated documentation files (the "Software"), to deal Chris@50: // in the Software without restriction, including without limitation the rights Chris@50: // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell Chris@50: // copies of the Software, and to permit persons to whom the Software is Chris@50: // furnished to do so, subject to the following conditions: Chris@50: // Chris@50: // The above copyright notice and this permission notice shall be included in Chris@50: // all copies or substantial portions of the Software. Chris@50: // Chris@50: // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR Chris@50: // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, Chris@50: // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE Chris@50: // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER Chris@50: // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, Chris@50: // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN Chris@50: // THE SOFTWARE. Chris@50: Chris@50: #ifndef KJ_ASYNC_IO_H_ Chris@50: #define KJ_ASYNC_IO_H_ Chris@50: Chris@50: #if defined(__GNUC__) && !KJ_HEADER_WARNINGS Chris@50: #pragma GCC system_header Chris@50: #endif Chris@50: Chris@50: #include "async.h" Chris@50: #include "function.h" Chris@50: #include "thread.h" Chris@50: #include "time.h" Chris@50: Chris@50: struct sockaddr; Chris@50: Chris@50: namespace kj { Chris@50: Chris@50: class UnixEventPort; Chris@50: class NetworkAddress; Chris@50: Chris@50: // ======================================================================================= Chris@50: // Streaming I/O Chris@50: Chris@50: class AsyncInputStream { Chris@50: // Asynchronous equivalent of InputStream (from io.h). Chris@50: Chris@50: public: Chris@50: virtual Promise read(void* buffer, size_t minBytes, size_t maxBytes) = 0; Chris@50: virtual Promise tryRead(void* buffer, size_t minBytes, size_t maxBytes) = 0; Chris@50: Chris@50: Promise read(void* buffer, size_t bytes); Chris@50: }; Chris@50: Chris@50: class AsyncOutputStream { Chris@50: // Asynchronous equivalent of OutputStream (from io.h). Chris@50: Chris@50: public: Chris@50: virtual Promise write(const void* buffer, size_t size) = 0; Chris@50: virtual Promise write(ArrayPtr> pieces) = 0; Chris@50: }; Chris@50: Chris@50: class AsyncIoStream: public AsyncInputStream, public AsyncOutputStream { Chris@50: // A combination input and output stream. Chris@50: Chris@50: public: Chris@50: virtual void shutdownWrite() = 0; Chris@50: // Cleanly shut down just the write end of the stream, while keeping the read end open. Chris@50: Chris@50: virtual void abortRead() {} Chris@50: // Similar to shutdownWrite, but this will shut down the read end of the stream, and should only Chris@50: // be called when an error has occurred. Chris@50: Chris@50: virtual void getsockopt(int level, int option, void* value, uint* length); Chris@50: virtual void setsockopt(int level, int option, const void* value, uint length); Chris@50: // Corresponds to getsockopt() and setsockopt() syscalls. Will throw an "unimplemented" exception Chris@50: // if the stream is not a socket or the option is not appropriate for the socket type. The Chris@50: // default implementations always throw "unimplemented". Chris@50: Chris@50: virtual void getsockname(struct sockaddr* addr, uint* length); Chris@50: virtual void getpeername(struct sockaddr* addr, uint* length); Chris@50: // Corresponds to getsockname() and getpeername() syscalls. Will throw an "unimplemented" Chris@50: // exception if the stream is not a socket. The default implementations always throw Chris@50: // "unimplemented". Chris@50: // Chris@50: // Note that we don't provide methods that return NetworkAddress because it usually wouldn't Chris@50: // be useful. You can't connect() to or listen() on these addresses, obviously, because they are Chris@50: // ephemeral addresses for a single connection. Chris@50: }; Chris@50: Chris@50: struct OneWayPipe { Chris@50: // A data pipe with an input end and an output end. (Typically backed by pipe() system call.) Chris@50: Chris@50: Own in; Chris@50: Own out; Chris@50: }; Chris@50: Chris@50: struct TwoWayPipe { Chris@50: // A data pipe that supports sending in both directions. Each end's output sends data to the Chris@50: // other end's input. (Typically backed by socketpair() system call.) Chris@50: Chris@50: Own ends[2]; Chris@50: }; Chris@50: Chris@50: class ConnectionReceiver { Chris@50: // Represents a server socket listening on a port. Chris@50: Chris@50: public: Chris@50: virtual Promise> accept() = 0; Chris@50: // Accept the next incoming connection. Chris@50: Chris@50: virtual uint getPort() = 0; Chris@50: // Gets the port number, if applicable (i.e. if listening on IP). This is useful if you didn't Chris@50: // specify a port when constructing the NetworkAddress -- one will have been assigned Chris@50: // automatically. Chris@50: Chris@50: virtual void getsockopt(int level, int option, void* value, uint* length); Chris@50: virtual void setsockopt(int level, int option, const void* value, uint length); Chris@50: // Same as the methods of AsyncIoStream. Chris@50: }; Chris@50: Chris@50: // ======================================================================================= Chris@50: // Datagram I/O Chris@50: Chris@50: class AncillaryMessage { Chris@50: // Represents an ancillary message (aka control message) received using the recvmsg() system Chris@50: // call (or equivalent). Most apps will not use this. Chris@50: Chris@50: public: Chris@50: inline AncillaryMessage(int level, int type, ArrayPtr data); Chris@50: AncillaryMessage() = default; Chris@50: Chris@50: inline int getLevel() const; Chris@50: // Originating protocol / socket level. Chris@50: Chris@50: inline int getType() const; Chris@50: // Protocol-specific message type. Chris@50: Chris@50: template Chris@50: inline Maybe as(); Chris@50: // Interpret the ancillary message as the given struct type. Most ancillary messages are some Chris@50: // sort of struct, so this is a convenient way to access it. Returns nullptr if the message Chris@50: // is smaller than the struct -- this can happen if the message was truncated due to Chris@50: // insufficient ancillary buffer space. Chris@50: Chris@50: template Chris@50: inline ArrayPtr asArray(); Chris@50: // Interpret the ancillary message as an array of items. If the message size does not evenly Chris@50: // divide into elements of type T, the remainder is discarded -- this can happen if the message Chris@50: // was truncated due to insufficient ancillary buffer space. Chris@50: Chris@50: private: Chris@50: int level; Chris@50: int type; Chris@50: ArrayPtr data; Chris@50: // Message data. In most cases you should use `as()` or `asArray()`. Chris@50: }; Chris@50: Chris@50: class DatagramReceiver { Chris@50: // Class encapsulating the recvmsg() system call. You must specify the DatagramReceiver's Chris@50: // capacity in advance; if a received packet is larger than the capacity, it will be truncated. Chris@50: Chris@50: public: Chris@50: virtual Promise receive() = 0; Chris@50: // Receive a new message, overwriting this object's content. Chris@50: // Chris@50: // receive() may reuse the same buffers for content and ancillary data with each call. Chris@50: Chris@50: template Chris@50: struct MaybeTruncated { Chris@50: T value; Chris@50: Chris@50: bool isTruncated; Chris@50: // True if the Receiver's capacity was insufficient to receive the value and therefore the Chris@50: // value is truncated. Chris@50: }; Chris@50: Chris@50: virtual MaybeTruncated> getContent() = 0; Chris@50: // Get the content of the datagram. Chris@50: Chris@50: virtual MaybeTruncated> getAncillary() = 0; Chris@50: // Ancilarry messages received with the datagram. See the recvmsg() system call and the cmsghdr Chris@50: // struct. Most apps don't need this. Chris@50: // Chris@50: // If the returned value is truncated, then the last message in the array may itself be Chris@50: // truncated, meaning its as() method will return nullptr or its asArray() method will Chris@50: // return fewer elements than expected. Truncation can also mean that additional messages were Chris@50: // available but discarded. Chris@50: Chris@50: virtual NetworkAddress& getSource() = 0; Chris@50: // Get the datagram sender's address. Chris@50: Chris@50: struct Capacity { Chris@50: size_t content = 8192; Chris@50: // How much space to allocate for the datagram content. If a datagram is received that is Chris@50: // larger than this, it will be truncated, with no way to recover the tail. Chris@50: Chris@50: size_t ancillary = 0; Chris@50: // How much space to allocate for ancillary messages. As with content, if the ancillary data Chris@50: // is larger than this, it will be truncated. Chris@50: }; Chris@50: }; Chris@50: Chris@50: class DatagramPort { Chris@50: public: Chris@50: virtual Promise send(const void* buffer, size_t size, NetworkAddress& destination) = 0; Chris@50: virtual Promise send(ArrayPtr> pieces, Chris@50: NetworkAddress& destination) = 0; Chris@50: Chris@50: virtual Own makeReceiver( Chris@50: DatagramReceiver::Capacity capacity = DatagramReceiver::Capacity()) = 0; Chris@50: // Create a new `Receiver` that can be used to receive datagrams. `capacity` specifies how much Chris@50: // space to allocate for the received message. The `DatagramPort` must outlive the `Receiver`. Chris@50: Chris@50: virtual uint getPort() = 0; Chris@50: // Gets the port number, if applicable (i.e. if listening on IP). This is useful if you didn't Chris@50: // specify a port when constructing the NetworkAddress -- one will have been assigned Chris@50: // automatically. Chris@50: Chris@50: virtual void getsockopt(int level, int option, void* value, uint* length); Chris@50: virtual void setsockopt(int level, int option, const void* value, uint length); Chris@50: // Same as the methods of AsyncIoStream. Chris@50: }; Chris@50: Chris@50: // ======================================================================================= Chris@50: // Networks Chris@50: Chris@50: class NetworkAddress { Chris@50: // Represents a remote address to which the application can connect. Chris@50: Chris@50: public: Chris@50: virtual Promise> connect() = 0; Chris@50: // Make a new connection to this address. Chris@50: // Chris@50: // The address must not be a wildcard ("*"). If it is an IP address, it must have a port number. Chris@50: Chris@50: virtual Own listen() = 0; Chris@50: // Listen for incoming connections on this address. Chris@50: // Chris@50: // The address must be local. Chris@50: Chris@50: virtual Own bindDatagramPort(); Chris@50: // Open this address as a datagram (e.g. UDP) port. Chris@50: // Chris@50: // The address must be local. Chris@50: Chris@50: virtual Own clone() = 0; Chris@50: // Returns an equivalent copy of this NetworkAddress. Chris@50: Chris@50: virtual String toString() = 0; Chris@50: // Produce a human-readable string which hopefully can be passed to Network::parseAddress() Chris@50: // to reproduce this address, although whether or not that works of course depends on the Network Chris@50: // implementation. This should be called only to display the address to human users, who will Chris@50: // hopefully know what they are able to do with it. Chris@50: }; Chris@50: Chris@50: class Network { Chris@50: // Factory for NetworkAddress instances, representing the network services offered by the Chris@50: // operating system. Chris@50: // Chris@50: // This interface typically represents broad authority, and well-designed code should limit its Chris@50: // use to high-level startup code and user interaction. Low-level APIs should accept Chris@50: // NetworkAddress instances directly and work from there, if at all possible. Chris@50: Chris@50: public: Chris@50: virtual Promise> parseAddress(StringPtr addr, uint portHint = 0) = 0; Chris@50: // Construct a network address from a user-provided string. The format of the address Chris@50: // strings is not specified at the API level, and application code should make no assumptions Chris@50: // about them. These strings should always be provided by humans, and said humans will know Chris@50: // what format to use in their particular context. Chris@50: // Chris@50: // `portHint`, if provided, specifies the "standard" IP port number for the application-level Chris@50: // service in play. If the address turns out to be an IP address (v4 or v6), and it lacks a Chris@50: // port number, this port will be used. If `addr` lacks a port number *and* `portHint` is Chris@50: // omitted, then the returned address will only support listen() and bindDatagramPort() Chris@50: // (not connect()), and an unused port will be chosen each time one of those methods is called. Chris@50: Chris@50: virtual Own getSockaddr(const void* sockaddr, uint len) = 0; Chris@50: // Construct a network address from a legacy struct sockaddr. Chris@50: }; Chris@50: Chris@50: // ======================================================================================= Chris@50: // I/O Provider Chris@50: Chris@50: class AsyncIoProvider { Chris@50: // Class which constructs asynchronous wrappers around the operating system's I/O facilities. Chris@50: // Chris@50: // Generally, the implementation of this interface must integrate closely with a particular Chris@50: // `EventLoop` implementation. Typically, the EventLoop implementation itself will provide Chris@50: // an AsyncIoProvider. Chris@50: Chris@50: public: Chris@50: virtual OneWayPipe newOneWayPipe() = 0; Chris@50: // Creates an input/output stream pair representing the ends of a one-way pipe (e.g. created with Chris@50: // the pipe(2) system call). Chris@50: Chris@50: virtual TwoWayPipe newTwoWayPipe() = 0; Chris@50: // Creates two AsyncIoStreams representing the two ends of a two-way pipe (e.g. created with Chris@50: // socketpair(2) system call). Data written to one end can be read from the other. Chris@50: Chris@50: virtual Network& getNetwork() = 0; Chris@50: // Creates a new `Network` instance representing the networks exposed by the operating system. Chris@50: // Chris@50: // DO NOT CALL THIS except at the highest levels of your code, ideally in the main() function. If Chris@50: // you call this from low-level code, then you are preventing higher-level code from injecting an Chris@50: // alternative implementation. Instead, if your code needs to use network functionality, it Chris@50: // should ask for a `Network` as a constructor or method parameter, so that higher-level code can Chris@50: // chose what implementation to use. The system network is essentially a singleton. See: Chris@50: // http://www.object-oriented-security.org/lets-argue/singletons Chris@50: // Chris@50: // Code that uses the system network should not make any assumptions about what kinds of Chris@50: // addresses it will parse, as this could differ across platforms. String addresses should come Chris@50: // strictly from the user, who will know how to write them correctly for their system. Chris@50: // Chris@50: // With that said, KJ currently supports the following string address formats: Chris@50: // - IPv4: "1.2.3.4", "1.2.3.4:80" Chris@50: // - IPv6: "1234:5678::abcd", "[1234:5678::abcd]:80" Chris@50: // - Local IP wildcard (covers both v4 and v6): "*", "*:80" Chris@50: // - Symbolic names: "example.com", "example.com:80", "example.com:http", "1.2.3.4:http" Chris@50: // - Unix domain: "unix:/path/to/socket" Chris@50: Chris@50: struct PipeThread { Chris@50: // A combination of a thread and a two-way pipe that communicates with that thread. Chris@50: // Chris@50: // The fields are intentionally ordered so that the pipe will be destroyed (and therefore Chris@50: // disconnected) before the thread is destroyed (and therefore joined). Thus if the thread Chris@50: // arranges to exit when it detects disconnect, destruction should be clean. Chris@50: Chris@50: Own thread; Chris@50: Own pipe; Chris@50: }; Chris@50: Chris@50: virtual PipeThread newPipeThread( Chris@50: Function startFunc) = 0; Chris@50: // Create a new thread and set up a two-way pipe (socketpair) which can be used to communicate Chris@50: // with it. One end of the pipe is passed to the thread's start function and the other end of Chris@50: // the pipe is returned. The new thread also gets its own `AsyncIoProvider` instance and will Chris@50: // already have an active `EventLoop` when `startFunc` is called. Chris@50: // Chris@50: // TODO(someday): I'm not entirely comfortable with this interface. It seems to be doing too Chris@50: // much at once but I'm not sure how to cleanly break it down. Chris@50: Chris@50: virtual Timer& getTimer() = 0; Chris@50: // Returns a `Timer` based on real time. Time does not pass while event handlers are running -- Chris@50: // it only updates when the event loop polls for system events. This means that calling `now()` Chris@50: // on this timer does not require a system call. Chris@50: // Chris@50: // This timer is not affected by changes to the system date. It is unspecified whether the timer Chris@50: // continues to count while the system is suspended. Chris@50: }; Chris@50: Chris@50: class LowLevelAsyncIoProvider { Chris@50: // Similar to `AsyncIoProvider`, but represents a lower-level interface that may differ on Chris@50: // different operating systems. You should prefer to use `AsyncIoProvider` over this interface Chris@50: // whenever possible, as `AsyncIoProvider` is portable and friendlier to dependency-injection. Chris@50: // Chris@50: // On Unix, this interface can be used to import native file descriptors into the async framework. Chris@50: // Different implementations of this interface might work on top of different event handling Chris@50: // primitives, such as poll vs. epoll vs. kqueue vs. some higher-level event library. Chris@50: // Chris@50: // On Windows, this interface can be used to import native HANDLEs into the async framework. Chris@50: // Different implementations of this interface might work on top of different event handling Chris@50: // primitives, such as I/O completion ports vs. completion routines. Chris@50: // Chris@50: // TODO(port): Actually implement Windows support. Chris@50: Chris@50: public: Chris@50: // --------------------------------------------------------------------------- Chris@50: // Unix-specific stuff Chris@50: Chris@50: enum Flags { Chris@50: // Flags controlling how to wrap a file descriptor. Chris@50: Chris@50: TAKE_OWNERSHIP = 1 << 0, Chris@50: // The returned object should own the file descriptor, automatically closing it when destroyed. Chris@50: // The close-on-exec flag will be set on the descriptor if it is not already. Chris@50: // Chris@50: // If this flag is not used, then the file descriptor is not automatically closed and the Chris@50: // close-on-exec flag is not modified. Chris@50: Chris@50: ALREADY_CLOEXEC = 1 << 1, Chris@50: // Indicates that the close-on-exec flag is known already to be set, so need not be set again. Chris@50: // Only relevant when combined with TAKE_OWNERSHIP. Chris@50: // Chris@50: // On Linux, all system calls which yield new file descriptors have flags or variants which Chris@50: // set the close-on-exec flag immediately. Unfortunately, other OS's do not. Chris@50: Chris@50: ALREADY_NONBLOCK = 1 << 2 Chris@50: // Indicates that the file descriptor is known already to be in non-blocking mode, so the flag Chris@50: // need not be set again. Otherwise, all wrap*Fd() methods will enable non-blocking mode Chris@50: // automatically. Chris@50: // Chris@50: // On Linux, all system calls which yield new file descriptors have flags or variants which Chris@50: // enable non-blocking mode immediately. Unfortunately, other OS's do not. Chris@50: }; Chris@50: Chris@50: virtual Own wrapInputFd(int fd, uint flags = 0) = 0; Chris@50: // Create an AsyncInputStream wrapping a file descriptor. Chris@50: // Chris@50: // `flags` is a bitwise-OR of the values of the `Flags` enum. Chris@50: Chris@50: virtual Own wrapOutputFd(int fd, uint flags = 0) = 0; Chris@50: // Create an AsyncOutputStream wrapping a file descriptor. Chris@50: // Chris@50: // `flags` is a bitwise-OR of the values of the `Flags` enum. Chris@50: Chris@50: virtual Own wrapSocketFd(int fd, uint flags = 0) = 0; Chris@50: // Create an AsyncIoStream wrapping a socket file descriptor. Chris@50: // Chris@50: // `flags` is a bitwise-OR of the values of the `Flags` enum. Chris@50: Chris@50: virtual Promise> wrapConnectingSocketFd(int fd, uint flags = 0) = 0; Chris@50: // Create an AsyncIoStream wrapping a socket that is in the process of connecting. The returned Chris@50: // promise should not resolve until connection has completed -- traditionally indicated by the Chris@50: // descriptor becoming writable. Chris@50: // Chris@50: // `flags` is a bitwise-OR of the values of the `Flags` enum. Chris@50: Chris@50: virtual Own wrapListenSocketFd(int fd, uint flags = 0) = 0; Chris@50: // Create an AsyncIoStream wrapping a listen socket file descriptor. This socket should already Chris@50: // have had `bind()` and `listen()` called on it, so it's ready for `accept()`. Chris@50: // Chris@50: // `flags` is a bitwise-OR of the values of the `Flags` enum. Chris@50: Chris@50: virtual Own wrapDatagramSocketFd(int fd, uint flags = 0); Chris@50: Chris@50: virtual Timer& getTimer() = 0; Chris@50: // Returns a `Timer` based on real time. Time does not pass while event handlers are running -- Chris@50: // it only updates when the event loop polls for system events. This means that calling `now()` Chris@50: // on this timer does not require a system call. Chris@50: // Chris@50: // This timer is not affected by changes to the system date. It is unspecified whether the timer Chris@50: // continues to count while the system is suspended. Chris@50: }; Chris@50: Chris@50: Own newAsyncIoProvider(LowLevelAsyncIoProvider& lowLevel); Chris@50: // Make a new AsyncIoProvider wrapping a `LowLevelAsyncIoProvider`. Chris@50: Chris@50: struct AsyncIoContext { Chris@50: Own lowLevelProvider; Chris@50: Own provider; Chris@50: WaitScope& waitScope; Chris@50: Chris@50: UnixEventPort& unixEventPort; Chris@50: // TEMPORARY: Direct access to underlying UnixEventPort, mainly for waiting on signals. This Chris@50: // field will go away at some point when we have a chance to improve these interfaces. Chris@50: }; Chris@50: Chris@50: AsyncIoContext setupAsyncIo(); Chris@50: // Convenience method which sets up the current thread with everything it needs to do async I/O. Chris@50: // The returned objects contain an `EventLoop` which is wrapping an appropriate `EventPort` for Chris@50: // doing I/O on the host system, so everything is ready for the thread to start making async calls Chris@50: // and waiting on promises. Chris@50: // Chris@50: // You would typically call this in your main() loop or in the start function of a thread. Chris@50: // Example: Chris@50: // Chris@50: // int main() { Chris@50: // auto ioContext = kj::setupAsyncIo(); Chris@50: // Chris@50: // // Now we can call an async function. Chris@50: // Promise textPromise = getHttp(*ioContext.provider, "http://example.com"); Chris@50: // Chris@50: // // And we can wait for the promise to complete. Note that you can only use `wait()` Chris@50: // // from the top level, not from inside a promise callback. Chris@50: // String text = textPromise.wait(ioContext.waitScope); Chris@50: // print(text); Chris@50: // return 0; Chris@50: // } Chris@50: // Chris@50: // WARNING: An AsyncIoContext can only be used in the thread and process that created it. In Chris@50: // particular, note that after a fork(), an AsyncIoContext created in the parent process will Chris@50: // not work correctly in the child, even if the parent ceases to use its copy. In particular Chris@50: // note that this means that server processes which daemonize themselves at startup must wait Chris@50: // until after daemonization to create an AsyncIoContext. Chris@50: Chris@50: // ======================================================================================= Chris@50: // inline implementation details Chris@50: Chris@50: inline AncillaryMessage::AncillaryMessage( Chris@50: int level, int type, ArrayPtr data) Chris@50: : level(level), type(type), data(data) {} Chris@50: Chris@50: inline int AncillaryMessage::getLevel() const { return level; } Chris@50: inline int AncillaryMessage::getType() const { return type; } Chris@50: Chris@50: template Chris@50: inline Maybe AncillaryMessage::as() { Chris@50: if (data.size() >= sizeof(T)) { Chris@50: return *reinterpret_cast(data.begin()); Chris@50: } else { Chris@50: return nullptr; Chris@50: } Chris@50: } Chris@50: Chris@50: template Chris@50: inline ArrayPtr AncillaryMessage::asArray() { Chris@50: return arrayPtr(reinterpret_cast(data.begin()), data.size() / sizeof(T)); Chris@50: } Chris@50: Chris@50: } // namespace kj Chris@50: Chris@50: #endif // KJ_ASYNC_IO_H_