2 * Copyright 2015 Facebook, Inc.
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
22 #include <folly/io/async/DelayedDestruction.h>
23 #include <folly/io/async/EventBase.h>
24 #include <folly/io/async/AsyncSocketBase.h>
26 #include <openssl/ssl.h>
28 constexpr bool kOpenSslModeMoveBufferOwnership =
29 #ifdef SSL_MODE_MOVE_BUFFER_OWNERSHIP
38 class AsyncSocketException;
44 * flags given by the application for write* calls
46 enum class WriteFlags : uint32_t {
49 * Whether to delay the output until a subsequent non-corked write.
50 * (Note: may not be supported in all subclasses or on all platforms.)
54 * for a socket that has ACK latency enabled, it will cause the kernel
55 * to fire a TCP ESTATS event when the last byte of the given write call
56 * will be acknowledged.
64 inline WriteFlags operator|(WriteFlags a, WriteFlags b) {
65 return static_cast<WriteFlags>(
66 static_cast<uint32_t>(a) | static_cast<uint32_t>(b));
70 * intersection operator
72 inline WriteFlags operator&(WriteFlags a, WriteFlags b) {
73 return static_cast<WriteFlags>(
74 static_cast<uint32_t>(a) & static_cast<uint32_t>(b));
80 inline WriteFlags operator~(WriteFlags a) {
81 return static_cast<WriteFlags>(~static_cast<uint32_t>(a));
87 inline WriteFlags unSet(WriteFlags a, WriteFlags b) {
94 inline bool isSet(WriteFlags a, WriteFlags b) {
100 * AsyncTransport defines an asynchronous API for streaming I/O.
102 * This class provides an API to for asynchronously waiting for data
103 * on a streaming transport, and for asynchronously sending data.
105 * The APIs for reading and writing are intentionally asymmetric. Waiting for
106 * data to read is a persistent API: a callback is installed, and is notified
107 * whenever new data is available. It continues to be notified of new events
108 * until it is uninstalled.
110 * AsyncTransport does not provide read timeout functionality, because it
111 * typically cannot determine when the timeout should be active. Generally, a
112 * timeout should only be enabled when processing is blocked waiting on data
113 * from the remote endpoint. For server-side applications, the timeout should
114 * not be active if the server is currently processing one or more outstanding
115 * requests on this transport. For client-side applications, the timeout
116 * should not be active if there are no requests pending on the transport.
117 * Additionally, if a client has multiple pending requests, it will ususally
118 * want a separate timeout for each request, rather than a single read timeout.
120 * The write API is fairly intuitive: a user can request to send a block of
121 * data, and a callback will be informed once the entire block has been
122 * transferred to the kernel, or on error. AsyncTransport does provide a send
123 * timeout, since most callers want to give up if the remote end stops
124 * responding and no further progress can be made sending the data.
126 class AsyncTransport : public DelayedDestruction, public AsyncSocketBase {
128 typedef std::unique_ptr<AsyncTransport, Destructor> UniquePtr;
131 * Close the transport.
133 * This gracefully closes the transport, waiting for all pending write
134 * requests to complete before actually closing the underlying transport.
136 * If a read callback is set, readEOF() will be called immediately. If there
137 * are outstanding write requests, the close will be delayed until all
138 * remaining writes have completed. No new writes may be started after
139 * close() has been called.
141 virtual void close() = 0;
144 * Close the transport immediately.
146 * This closes the transport immediately, dropping any outstanding data
147 * waiting to be written.
149 * If a read callback is set, readEOF() will be called immediately.
150 * If there are outstanding write requests, these requests will be aborted
151 * and writeError() will be invoked immediately on all outstanding write
154 virtual void closeNow() = 0;
157 * Reset the transport immediately.
159 * This closes the transport immediately, sending a reset to the remote peer
160 * if possible to indicate abnormal shutdown.
162 * Note that not all subclasses implement this reset functionality: some
163 * subclasses may treat reset() the same as closeNow(). Subclasses that use
164 * TCP transports should terminate the connection with a TCP reset.
166 virtual void closeWithReset() {
171 * Perform a half-shutdown of the write side of the transport.
173 * The caller should not make any more calls to write() or writev() after
174 * shutdownWrite() is called. Any future write attempts will fail
177 * Not all transport types support half-shutdown. If the underlying
178 * transport does not support half-shutdown, it will fully shutdown both the
179 * read and write sides of the transport. (Fully shutting down the socket is
180 * better than doing nothing at all, since the caller may rely on the
181 * shutdownWrite() call to notify the other end of the connection that no
182 * more data can be read.)
184 * If there is pending data still waiting to be written on the transport,
185 * the actual shutdown will be delayed until the pending data has been
188 * Note: There is no corresponding shutdownRead() equivalent. Simply
189 * uninstall the read callback if you wish to stop reading. (On TCP sockets
190 * at least, shutting down the read side of the socket is a no-op anyway.)
192 virtual void shutdownWrite() = 0;
195 * Perform a half-shutdown of the write side of the transport.
197 * shutdownWriteNow() is identical to shutdownWrite(), except that it
198 * immediately performs the shutdown, rather than waiting for pending writes
199 * to complete. Any pending write requests will be immediately failed when
200 * shutdownWriteNow() is called.
202 virtual void shutdownWriteNow() = 0;
205 * Determine if transport is open and ready to read or write.
207 * Note that this function returns false on EOF; you must also call error()
208 * to distinguish between an EOF and an error.
210 * @return true iff the transport is open and ready, false otherwise.
212 virtual bool good() const = 0;
215 * Determine if the transport is readable or not.
217 * @return true iff the transport is readable, false otherwise.
219 virtual bool readable() const = 0;
222 * Determine if the there is pending data on the transport.
224 * @return true iff the if the there is pending data, false otherwise.
226 virtual bool isPending() const {
230 * Determine if transport is connected to the endpoint
232 * @return false iff the transport is connected, otherwise true
234 virtual bool connecting() const = 0;
237 * Determine if an error has occurred with this transport.
239 * @return true iff an error has occurred (not EOF).
241 virtual bool error() const = 0;
244 * Attach the transport to a EventBase.
246 * This may only be called if the transport is not currently attached to a
247 * EventBase (by an earlier call to detachEventBase()).
249 * This method must be invoked in the EventBase's thread.
251 virtual void attachEventBase(EventBase* eventBase) = 0;
254 * Detach the transport from its EventBase.
256 * This may only be called when the transport is idle and has no reads or
257 * writes pending. Once detached, the transport may not be used again until
258 * it is re-attached to a EventBase by calling attachEventBase().
260 * This method must be called from the current EventBase's thread.
262 virtual void detachEventBase() = 0;
265 * Determine if the transport can be detached.
267 * This method must be called from the current EventBase's thread.
269 virtual bool isDetachable() const = 0;
272 * Set the send timeout.
274 * If write requests do not make any progress for more than the specified
275 * number of milliseconds, fail all pending writes and close the transport.
277 * If write requests are currently pending when setSendTimeout() is called,
278 * the timeout interval is immediately restarted using the new value.
280 * @param milliseconds The timeout duration, in milliseconds. If 0, no
281 * timeout will be used.
283 virtual void setSendTimeout(uint32_t milliseconds) = 0;
286 * Get the send timeout.
288 * @return Returns the current send timeout, in milliseconds. A return value
289 * of 0 indicates that no timeout is set.
291 virtual uint32_t getSendTimeout() const = 0;
294 * Get the address of the local endpoint of this transport.
296 * This function may throw AsyncSocketException on error.
298 * @param address The local address will be stored in the specified
301 virtual void getLocalAddress(SocketAddress* address) const = 0;
303 virtual void getAddress(SocketAddress* address) const {
304 getLocalAddress(address);
308 * Get the address of the remote endpoint to which this transport is
311 * This function may throw AsyncSocketException on error.
313 * @param address The remote endpoint's address will be stored in the
314 * specified SocketAddress.
316 virtual void getPeerAddress(SocketAddress* address) const = 0;
319 * @return True iff end of record tracking is enabled
321 virtual bool isEorTrackingEnabled() const = 0;
323 virtual void setEorTracking(bool track) = 0;
325 virtual size_t getAppBytesWritten() const = 0;
326 virtual size_t getRawBytesWritten() const = 0;
327 virtual size_t getAppBytesReceived() const = 0;
328 virtual size_t getRawBytesReceived() const = 0;
331 virtual ~AsyncTransport() = default;
338 virtual ~ReadCallback() = default;
341 * When data becomes available, getReadBuffer() will be invoked to get the
342 * buffer into which data should be read.
344 * This method allows the ReadCallback to delay buffer allocation until
345 * data becomes available. This allows applications to manage large
346 * numbers of idle connections, without having to maintain a separate read
347 * buffer for each idle connection.
349 * It is possible that in some cases, getReadBuffer() may be called
350 * multiple times before readDataAvailable() is invoked. In this case, the
351 * data will be written to the buffer returned from the most recent call to
352 * readDataAvailable(). If the previous calls to readDataAvailable()
353 * returned different buffers, the ReadCallback is responsible for ensuring
354 * that they are not leaked.
356 * If getReadBuffer() throws an exception, returns a nullptr buffer, or
357 * returns a 0 length, the ReadCallback will be uninstalled and its
358 * readError() method will be invoked.
360 * getReadBuffer() is not allowed to change the transport state before it
361 * returns. (For example, it should never uninstall the read callback, or
362 * set a different read callback.)
364 * @param bufReturn getReadBuffer() should update *bufReturn to contain the
365 * address of the read buffer. This parameter will never
367 * @param lenReturn getReadBuffer() should update *lenReturn to contain the
368 * maximum number of bytes that may be written to the read
369 * buffer. This parameter will never be nullptr.
371 virtual void getReadBuffer(void** bufReturn, size_t* lenReturn) = 0;
374 * readDataAvailable() will be invoked when data has been successfully read
375 * into the buffer returned by the last call to getReadBuffer().
377 * The read callback remains installed after readDataAvailable() returns.
378 * It must be explicitly uninstalled to stop receiving read events.
379 * getReadBuffer() will be called at least once before each call to
380 * readDataAvailable(). getReadBuffer() will also be called before any
383 * @param len The number of bytes placed in the buffer.
386 virtual void readDataAvailable(size_t len) noexcept = 0;
389 * When data becomes available, isBufferMovable() will be invoked to figure
390 * out which API will be used, readBufferAvailable() or
391 * readDataAvailable(). If isBufferMovable() returns true, that means
392 * ReadCallback supports the IOBuf ownership transfer and
393 * readBufferAvailable() will be used. Otherwise, not.
395 * By default, isBufferMovable() always return false. If
396 * readBufferAvailable() is implemented and to be invoked, You should
397 * overwrite isBufferMovable() and return true in the inherited class.
399 * This method allows the AsyncSocket/AsyncSSLSocket do buffer allocation by
400 * itself until data becomes available. Compared with the pre/post buffer
401 * allocation in getReadBuffer()/readDataAvailabe(), readBufferAvailable()
402 * has two advantages. First, this can avoid memcpy. E.g., in
403 * AsyncSSLSocket, the decrypted data was copied from the openssl internal
404 * buffer to the readbuf buffer. With the buffer ownership transfer, the
405 * internal buffer can be directly "moved" to ReadCallback. Second, the
406 * memory allocation can be more precise. The reason is
407 * AsyncSocket/AsyncSSLSocket can allocate the memory of precise size
408 * because they have more context about the available data than
409 * ReadCallback. Think about the getReadBuffer() pre-allocate 4072 bytes
410 * buffer, but the available data is always 16KB (max OpenSSL record size).
413 virtual bool isBufferMovable() noexcept {
418 * readBufferAvailable() will be invoked when data has been successfully
421 * Note that only either readBufferAvailable() or readDataAvailable() will
422 * be invoked according to the return value of isBufferMovable(). The timing
423 * and aftereffect of readBufferAvailable() are the same as
424 * readDataAvailable()
426 * @param readBuf The unique pointer of read buffer.
429 virtual void readBufferAvailable(std::unique_ptr<IOBuf> /*readBuf*/)
433 * readEOF() will be invoked when the transport is closed.
435 * The read callback will be automatically uninstalled immediately before
436 * readEOF() is invoked.
438 virtual void readEOF() noexcept = 0;
441 * readError() will be invoked if an error occurs reading from the
444 * The read callback will be automatically uninstalled immediately before
445 * readError() is invoked.
447 * @param ex An exception describing the error that occurred.
449 virtual void readErr(const AsyncSocketException& ex) noexcept = 0;
452 // Read methods that aren't part of AsyncTransport.
453 virtual void setReadCB(ReadCallback* callback) = 0;
454 virtual ReadCallback* getReadCallback() const = 0;
457 virtual ~AsyncReader() = default;
462 class WriteCallback {
464 virtual ~WriteCallback() = default;
467 * writeSuccess() will be invoked when all of the data has been
468 * successfully written.
470 * Note that this mainly signals that the buffer containing the data to
471 * write is no longer needed and may be freed or re-used. It does not
472 * guarantee that the data has been fully transmitted to the remote
473 * endpoint. For example, on socket-based transports, writeSuccess() only
474 * indicates that the data has been given to the kernel for eventual
477 virtual void writeSuccess() noexcept = 0;
480 * writeError() will be invoked if an error occurs writing the data.
482 * @param bytesWritten The number of bytes that were successfull
483 * @param ex An exception describing the error that occurred.
485 virtual void writeErr(size_t bytesWritten,
486 const AsyncSocketException& ex) noexcept = 0;
489 // Write methods that aren't part of AsyncTransport
490 virtual void write(WriteCallback* callback, const void* buf, size_t bytes,
491 WriteFlags flags = WriteFlags::NONE) = 0;
492 virtual void writev(WriteCallback* callback, const iovec* vec, size_t count,
493 WriteFlags flags = WriteFlags::NONE) = 0;
494 virtual void writeChain(WriteCallback* callback,
495 std::unique_ptr<IOBuf>&& buf,
496 WriteFlags flags = WriteFlags::NONE) = 0;
499 virtual ~AsyncWriter() = default;
502 // Transitional intermediate interface. This is deprecated.
503 // Wrapper around folly::AsyncTransport, that includes read/write callbacks
504 class AsyncTransportWrapper : virtual public AsyncTransport,
505 virtual public AsyncReader,
506 virtual public AsyncWriter {
508 using UniquePtr = std::unique_ptr<AsyncTransportWrapper, Destructor>;
510 // Alias for inherited members from AsyncReader and AsyncWriter
511 // to keep compatibility.
512 using ReadCallback = AsyncReader::ReadCallback;
513 using WriteCallback = AsyncWriter::WriteCallback;
514 virtual void setReadCB(ReadCallback* callback) override = 0;
515 virtual ReadCallback* getReadCallback() const override = 0;
516 virtual void write(WriteCallback* callback, const void* buf, size_t bytes,
517 WriteFlags flags = WriteFlags::NONE) override = 0;
518 virtual void writev(WriteCallback* callback, const iovec* vec, size_t count,
519 WriteFlags flags = WriteFlags::NONE) override = 0;
520 virtual void writeChain(WriteCallback* callback,
521 std::unique_ptr<IOBuf>&& buf,
522 WriteFlags flags = WriteFlags::NONE) override = 0;