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