Chris@63: // Copyright (c) 2013-2014 Sandstorm Development Group, Inc. and contributors Chris@63: // Licensed under the MIT License: Chris@63: // Chris@63: // Permission is hereby granted, free of charge, to any person obtaining a copy Chris@63: // of this software and associated documentation files (the "Software"), to deal Chris@63: // in the Software without restriction, including without limitation the rights Chris@63: // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell Chris@63: // copies of the Software, and to permit persons to whom the Software is Chris@63: // furnished to do so, subject to the following conditions: Chris@63: // Chris@63: // The above copyright notice and this permission notice shall be included in Chris@63: // all copies or substantial portions of the Software. Chris@63: // Chris@63: // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR Chris@63: // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, Chris@63: // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE Chris@63: // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER Chris@63: // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, Chris@63: // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN Chris@63: // THE SOFTWARE. Chris@63: Chris@63: #ifndef KJ_ASYNC_UNIX_H_ Chris@63: #define KJ_ASYNC_UNIX_H_ Chris@63: Chris@63: #if _WIN32 Chris@63: #error "This file is Unix-specific. On Windows, include async-win32.h instead." Chris@63: #endif Chris@63: Chris@63: #if defined(__GNUC__) && !KJ_HEADER_WARNINGS Chris@63: #pragma GCC system_header Chris@63: #endif Chris@63: Chris@63: #include "async.h" Chris@63: #include "time.h" Chris@63: #include "vector.h" Chris@63: #include "io.h" Chris@63: #include Chris@63: Chris@63: #if __linux__ && !__BIONIC__ && !defined(KJ_USE_EPOLL) Chris@63: // Default to epoll on Linux, except on Bionic (Android) which doesn't have signalfd.h. Chris@63: #define KJ_USE_EPOLL 1 Chris@63: #endif Chris@63: Chris@63: namespace kj { Chris@63: Chris@63: class UnixEventPort: public EventPort { Chris@63: // An EventPort implementation which can wait for events on file descriptors as well as signals. Chris@63: // This API only makes sense on Unix. Chris@63: // Chris@63: // The implementation uses `poll()` or possibly a platform-specific API (e.g. epoll, kqueue). Chris@63: // To also wait on signals without race conditions, the implementation may block signals until Chris@63: // just before `poll()` while using a signal handler which `siglongjmp()`s back to just before Chris@63: // the signal was unblocked, or it may use a nicer platform-specific API like signalfd. Chris@63: // Chris@63: // The implementation reserves a signal for internal use. By default, it uses SIGUSR1. If you Chris@63: // need to use SIGUSR1 for something else, you must offer a different signal by calling Chris@63: // setReservedSignal() at startup. Chris@63: // Chris@63: // WARNING: A UnixEventPort can only be used in the thread and process that created it. In Chris@63: // particular, note that after a fork(), a UnixEventPort created in the parent process will Chris@63: // not work correctly in the child, even if the parent ceases to use its copy. In particular Chris@63: // note that this means that server processes which daemonize themselves at startup must wait Chris@63: // until after daemonization to create a UnixEventPort. Chris@63: Chris@63: public: Chris@63: UnixEventPort(); Chris@63: ~UnixEventPort() noexcept(false); Chris@63: Chris@63: class FdObserver; Chris@63: // Class that watches an fd for readability or writability. See definition below. Chris@63: Chris@63: Promise onSignal(int signum); Chris@63: // When the given signal is delivered to this thread, return the corresponding siginfo_t. Chris@63: // The signal must have been captured using `captureSignal()`. Chris@63: // Chris@63: // If `onSignal()` has not been called, the signal will remain blocked in this thread. Chris@63: // Therefore, a signal which arrives before `onSignal()` was called will not be "missed" -- the Chris@63: // next call to 'onSignal()' will receive it. Also, you can control which thread receives a Chris@63: // process-wide signal by only calling `onSignal()` on that thread's event loop. Chris@63: // Chris@63: // The result of waiting on the same signal twice at once is undefined. Chris@63: Chris@63: static void captureSignal(int signum); Chris@63: // Arranges for the given signal to be captured and handled via UnixEventPort, so that you may Chris@63: // then pass it to `onSignal()`. This method is static because it registers a signal handler Chris@63: // which applies process-wide. If any other threads exist in the process when `captureSignal()` Chris@63: // is called, you *must* set the signal mask in those threads to block this signal, otherwise Chris@63: // terrible things will happen if the signal happens to be delivered to those threads. If at Chris@63: // all possible, call `captureSignal()` *before* creating threads, so that threads you create in Chris@63: // the future will inherit the proper signal mask. Chris@63: // Chris@63: // To un-capture a signal, simply install a different signal handler and then un-block it from Chris@63: // the signal mask. Chris@63: Chris@63: static void setReservedSignal(int signum); Chris@63: // Sets the signal number which `UnixEventPort` reserves for internal use. If your application Chris@63: // needs to use SIGUSR1, call this at startup (before any calls to `captureSignal()` and before Chris@63: // constructing an `UnixEventPort`) to offer a different signal. Chris@63: Chris@63: Timer& getTimer() { return timerImpl; } Chris@63: Chris@63: // implements EventPort ------------------------------------------------------ Chris@63: bool wait() override; Chris@63: bool poll() override; Chris@63: void wake() const override; Chris@63: Chris@63: private: Chris@63: struct TimerSet; // Defined in source file to avoid STL include. Chris@63: class TimerPromiseAdapter; Chris@63: class SignalPromiseAdapter; Chris@63: Chris@63: TimerImpl timerImpl; Chris@63: Chris@63: SignalPromiseAdapter* signalHead = nullptr; Chris@63: SignalPromiseAdapter** signalTail = &signalHead; Chris@63: Chris@63: TimePoint readClock(); Chris@63: void gotSignal(const siginfo_t& siginfo); Chris@63: Chris@63: friend class TimerPromiseAdapter; Chris@63: Chris@63: #if KJ_USE_EPOLL Chris@63: AutoCloseFd epollFd; Chris@63: AutoCloseFd signalFd; Chris@63: AutoCloseFd eventFd; // Used for cross-thread wakeups. Chris@63: Chris@63: sigset_t signalFdSigset; Chris@63: // Signal mask as currently set on the signalFd. Tracked so we can detect whether or not it Chris@63: // needs updating. Chris@63: Chris@63: bool doEpollWait(int timeout); Chris@63: Chris@63: #else Chris@63: class PollContext; Chris@63: Chris@63: FdObserver* observersHead = nullptr; Chris@63: FdObserver** observersTail = &observersHead; Chris@63: Chris@63: unsigned long long threadId; // actually pthread_t Chris@63: #endif Chris@63: }; Chris@63: Chris@63: class UnixEventPort::FdObserver { Chris@63: // Object which watches a file descriptor to determine when it is readable or writable. Chris@63: // Chris@63: // For listen sockets, "readable" means that there is a connection to accept(). For everything Chris@63: // else, it means that read() (or recv()) will return data. Chris@63: // Chris@63: // The presence of out-of-band data should NOT fire this event. However, the event may Chris@63: // occasionally fire spuriously (when there is actually no data to read), and one thing that can Chris@63: // cause such spurious events is the arrival of OOB data on certain platforms whose event Chris@63: // interfaces fail to distinguish between regular and OOB data (e.g. Mac OSX). Chris@63: // Chris@63: // WARNING: The exact behavior of this class differs across systems, since event interfaces Chris@63: // vary wildly. Be sure to read the documentation carefully and avoid depending on unspecified Chris@63: // behavior. If at all possible, use the higher-level AsyncInputStream interface instead. Chris@63: Chris@63: public: Chris@63: enum Flags { Chris@63: OBSERVE_READ = 1, Chris@63: OBSERVE_WRITE = 2, Chris@63: OBSERVE_URGENT = 4, Chris@63: OBSERVE_READ_WRITE = OBSERVE_READ | OBSERVE_WRITE Chris@63: }; Chris@63: Chris@63: FdObserver(UnixEventPort& eventPort, int fd, uint flags); Chris@63: // Begin watching the given file descriptor for readability. Only one ReadObserver may exist Chris@63: // for a given file descriptor at a time. Chris@63: Chris@63: ~FdObserver() noexcept(false); Chris@63: Chris@63: KJ_DISALLOW_COPY(FdObserver); Chris@63: Chris@63: Promise whenBecomesReadable(); Chris@63: // Resolves the next time the file descriptor transitions from having no data to read to having Chris@63: // some data to read. Chris@63: // Chris@63: // KJ uses "edge-triggered" event notification whenever possible. As a result, it is an error Chris@63: // to call this method when there is already data in the read buffer which has been there since Chris@63: // prior to the last turn of the event loop or prior to creation FdWatcher. In this case, it is Chris@63: // unspecified whether the promise will ever resolve -- it depends on the underlying event Chris@63: // mechanism being used. Chris@63: // Chris@63: // In order to avoid this problem, make sure that you only call `whenBecomesReadable()` Chris@63: // only at times when you know the buffer is empty. You know this for sure when one of the Chris@63: // following happens: Chris@63: // * read() or recv() fails with EAGAIN or EWOULDBLOCK. (You MUST have non-blocking mode Chris@63: // enabled on the fd!) Chris@63: // * The file descriptor is a regular byte-oriented object (like a socket or pipe), Chris@63: // read() or recv() returns fewer than the number of bytes requested, and `atEndHint()` Chris@63: // returns false. This can only happen if the buffer is empty but EOF is not reached. (Note, Chris@63: // though, that for record-oriented file descriptors like Linux's inotify interface, this Chris@63: // rule does not hold, because it could simply be that the next record did not fit into the Chris@63: // space available.) Chris@63: // Chris@63: // It is an error to call `whenBecomesReadable()` again when the promise returned previously Chris@63: // has not yet resolved. If you do this, the previous promise may throw an exception. Chris@63: Chris@63: inline Maybe atEndHint() { return atEnd; } Chris@63: // Returns true if the event system has indicated that EOF has been received. There may still Chris@63: // be data in the read buffer, but once that is gone, there's nothing left. Chris@63: // Chris@63: // Returns false if the event system has indicated that EOF had NOT been received as of the Chris@63: // last turn of the event loop. Chris@63: // Chris@63: // Returns nullptr if the event system does not know whether EOF has been reached. In this Chris@63: // case, the only way to know for sure is to call read() or recv() and check if it returns Chris@63: // zero. Chris@63: // Chris@63: // This hint may be useful as an optimization to avoid an unnecessary system call. Chris@63: Chris@63: Promise whenBecomesWritable(); Chris@63: // Resolves the next time the file descriptor transitions from having no space available in the Chris@63: // write buffer to having some space available. Chris@63: // Chris@63: // KJ uses "edge-triggered" event notification whenever possible. As a result, it is an error Chris@63: // to call this method when there is already space in the write buffer which has been there Chris@63: // since prior to the last turn of the event loop or prior to creation FdWatcher. In this case, Chris@63: // it is unspecified whether the promise will ever resolve -- it depends on the underlying Chris@63: // event mechanism being used. Chris@63: // Chris@63: // In order to avoid this problem, make sure that you only call `whenBecomesWritable()` Chris@63: // only at times when you know the buffer is full. You know this for sure when one of the Chris@63: // following happens: Chris@63: // * write() or send() fails with EAGAIN or EWOULDBLOCK. (You MUST have non-blocking mode Chris@63: // enabled on the fd!) Chris@63: // * write() or send() succeeds but accepts fewer than the number of bytes provided. This can Chris@63: // only happen if the buffer is full. Chris@63: // Chris@63: // It is an error to call `whenBecomesWritable()` again when the promise returned previously Chris@63: // has not yet resolved. If you do this, the previous promise may throw an exception. Chris@63: Chris@63: Promise whenUrgentDataAvailable(); Chris@63: // Resolves the next time the file descriptor's read buffer contains "urgent" data. Chris@63: // Chris@63: // The conditions for availability of urgent data are specific to the file descriptor's Chris@63: // underlying implementation. Chris@63: // Chris@63: // It is an error to call `whenUrgentDataAvailable()` again when the promise returned previously Chris@63: // has not yet resolved. If you do this, the previous promise may throw an exception. Chris@63: // Chris@63: // WARNING: This has some known weird behavior on macOS. See Chris@63: // https://github.com/sandstorm-io/capnproto/issues/374. Chris@63: Chris@63: private: Chris@63: UnixEventPort& eventPort; Chris@63: int fd; Chris@63: uint flags; Chris@63: Chris@63: kj::Maybe>> readFulfiller; Chris@63: kj::Maybe>> writeFulfiller; Chris@63: kj::Maybe>> urgentFulfiller; Chris@63: // Replaced each time `whenBecomesReadable()` or `whenBecomesWritable()` is called. Reverted to Chris@63: // null every time an event is fired. Chris@63: Chris@63: Maybe atEnd; Chris@63: Chris@63: void fire(short events); Chris@63: Chris@63: #if !KJ_USE_EPOLL Chris@63: FdObserver* next; Chris@63: FdObserver** prev; Chris@63: // Linked list of observers which currently have a non-null readFulfiller or writeFulfiller. Chris@63: // If `prev` is null then the observer is not currently in the list. Chris@63: Chris@63: short getEventMask(); Chris@63: #endif Chris@63: Chris@63: friend class UnixEventPort; Chris@63: }; Chris@63: Chris@63: } // namespace kj Chris@63: Chris@63: #endif // KJ_ASYNC_UNIX_H_