opt proxygen with newly added OpenSSL functions
[folly.git] / folly / io / async / AsyncTransport.h
1 /*
2  * Copyright 2015 Facebook, Inc.
3  *
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
7  *
8  *   http://www.apache.org/licenses/LICENSE-2.0
9  *
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.
15  */
16
17 #pragma once
18
19 #include <memory>
20 #include <sys/uio.h>
21
22 #include <folly/io/async/DelayedDestruction.h>
23 #include <folly/io/async/EventBase.h>
24 #include <folly/io/async/AsyncSocketBase.h>
25
26 #include <openssl/ssl.h>
27
28 constexpr bool kOpenSslModeMoveBufferOwnership =
29 #ifdef SSL_MODE_MOVE_BUFFER_OWNERSHIP
30   true
31 #else
32   false
33 #endif
34 ;
35
36 namespace folly {
37
38 class AsyncSocketException;
39 class EventBase;
40 class IOBuf;
41 class SocketAddress;
42
43 /*
44  * flags given by the application for write* calls
45  */
46 enum class WriteFlags : uint32_t {
47   NONE = 0x00,
48   /*
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.)
51    */
52   CORK = 0x01,
53   /*
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.
57    */
58   EOR = 0x02,
59 };
60
61 /*
62  * union operator
63  */
64 inline WriteFlags operator|(WriteFlags a, WriteFlags b) {
65   return static_cast<WriteFlags>(
66     static_cast<uint32_t>(a) | static_cast<uint32_t>(b));
67 }
68
69 /*
70  * intersection operator
71  */
72 inline WriteFlags operator&(WriteFlags a, WriteFlags b) {
73   return static_cast<WriteFlags>(
74     static_cast<uint32_t>(a) & static_cast<uint32_t>(b));
75 }
76
77 /*
78  * exclusion parameter
79  */
80 inline WriteFlags operator~(WriteFlags a) {
81   return static_cast<WriteFlags>(~static_cast<uint32_t>(a));
82 }
83
84 /*
85  * unset operator
86  */
87 inline WriteFlags unSet(WriteFlags a, WriteFlags b) {
88   return a & ~b;
89 }
90
91 /*
92  * inclusion operator
93  */
94 inline bool isSet(WriteFlags a, WriteFlags b) {
95   return (a & b) == b;
96 }
97
98
99 /**
100  * AsyncTransport defines an asynchronous API for streaming I/O.
101  *
102  * This class provides an API to for asynchronously waiting for data
103  * on a streaming transport, and for asynchronously sending data.
104  *
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.
109  *
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.
119  *
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.
125  */
126 class AsyncTransport : public DelayedDestruction, public AsyncSocketBase {
127  public:
128   typedef std::unique_ptr<AsyncTransport, Destructor> UniquePtr;
129
130   /**
131    * Close the transport.
132    *
133    * This gracefully closes the transport, waiting for all pending write
134    * requests to complete before actually closing the underlying transport.
135    *
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.
140    */
141   virtual void close() = 0;
142
143   /**
144    * Close the transport immediately.
145    *
146    * This closes the transport immediately, dropping any outstanding data
147    * waiting to be written.
148    *
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
152    * callbacks.
153    */
154   virtual void closeNow() = 0;
155
156   /**
157    * Reset the transport immediately.
158    *
159    * This closes the transport immediately, sending a reset to the remote peer
160    * if possible to indicate abnormal shutdown.
161    *
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.
165    */
166   virtual void closeWithReset() {
167     closeNow();
168   }
169
170   /**
171    * Perform a half-shutdown of the write side of the transport.
172    *
173    * The caller should not make any more calls to write() or writev() after
174    * shutdownWrite() is called.  Any future write attempts will fail
175    * immediately.
176    *
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.)
183    *
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
186    * written.
187    *
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.)
191    */
192   virtual void shutdownWrite() = 0;
193
194   /**
195    * Perform a half-shutdown of the write side of the transport.
196    *
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.
201    */
202   virtual void shutdownWriteNow() = 0;
203
204   /**
205    * Determine if transport is open and ready to read or write.
206    *
207    * Note that this function returns false on EOF; you must also call error()
208    * to distinguish between an EOF and an error.
209    *
210    * @return  true iff the transport is open and ready, false otherwise.
211    */
212   virtual bool good() const = 0;
213
214   /**
215    * Determine if the transport is readable or not.
216    *
217    * @return  true iff the transport is readable, false otherwise.
218    */
219   virtual bool readable() const = 0;
220
221   /**
222    * Determine if the there is pending data on the transport.
223    *
224    * @return  true iff the if the there is pending data, false otherwise.
225    */
226   virtual bool isPending() const {
227     return readable();
228   }
229   /**
230    * Determine if transport is connected to the endpoint
231    *
232    * @return  false iff the transport is connected, otherwise true
233    */
234   virtual bool connecting() const = 0;
235
236   /**
237    * Determine if an error has occurred with this transport.
238    *
239    * @return  true iff an error has occurred (not EOF).
240    */
241   virtual bool error() const = 0;
242
243   /**
244    * Attach the transport to a EventBase.
245    *
246    * This may only be called if the transport is not currently attached to a
247    * EventBase (by an earlier call to detachEventBase()).
248    *
249    * This method must be invoked in the EventBase's thread.
250    */
251   virtual void attachEventBase(EventBase* eventBase) = 0;
252
253   /**
254    * Detach the transport from its EventBase.
255    *
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().
259    *
260    * This method must be called from the current EventBase's thread.
261    */
262   virtual void detachEventBase() = 0;
263
264   /**
265    * Determine if the transport can be detached.
266    *
267    * This method must be called from the current EventBase's thread.
268    */
269   virtual bool isDetachable() const = 0;
270
271   /**
272    * Set the send timeout.
273    *
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.
276    *
277    * If write requests are currently pending when setSendTimeout() is called,
278    * the timeout interval is immediately restarted using the new value.
279    *
280    * @param milliseconds  The timeout duration, in milliseconds.  If 0, no
281    *                      timeout will be used.
282    */
283   virtual void setSendTimeout(uint32_t milliseconds) = 0;
284
285   /**
286    * Get the send timeout.
287    *
288    * @return Returns the current send timeout, in milliseconds.  A return value
289    *         of 0 indicates that no timeout is set.
290    */
291   virtual uint32_t getSendTimeout() const = 0;
292
293   /**
294    * Get the address of the local endpoint of this transport.
295    *
296    * This function may throw AsyncSocketException on error.
297    *
298    * @param address  The local address will be stored in the specified
299    *                 SocketAddress.
300    */
301   virtual void getLocalAddress(SocketAddress* address) const = 0;
302
303   virtual void getAddress(SocketAddress* address) const {
304     getLocalAddress(address);
305   }
306
307   /**
308    * Get the address of the remote endpoint to which this transport is
309    * connected.
310    *
311    * This function may throw AsyncSocketException on error.
312    *
313    * @param address  The remote endpoint's address will be stored in the
314    *                 specified SocketAddress.
315    */
316   virtual void getPeerAddress(SocketAddress* address) const = 0;
317
318   /**
319    * @return True iff end of record tracking is enabled
320    */
321   virtual bool isEorTrackingEnabled() const = 0;
322
323   virtual void setEorTracking(bool track) = 0;
324
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;
329
330  protected:
331   virtual ~AsyncTransport() = default;
332 };
333
334 // Transitional intermediate interface. This is deprecated.
335 // Wrapper around folly::AsyncTransport, that includes read/write callbacks
336 class AsyncTransportWrapper : virtual public AsyncTransport {
337  public:
338   typedef std::unique_ptr<AsyncTransportWrapper, Destructor> UniquePtr;
339
340   class ReadCallback {
341    public:
342     virtual ~ReadCallback() = default;
343
344     /**
345      * When data becomes available, getReadBuffer() will be invoked to get the
346      * buffer into which data should be read.
347      *
348      * This method allows the ReadCallback to delay buffer allocation until
349      * data becomes available.  This allows applications to manage large
350      * numbers of idle connections, without having to maintain a separate read
351      * buffer for each idle connection.
352      *
353      * It is possible that in some cases, getReadBuffer() may be called
354      * multiple times before readDataAvailable() is invoked.  In this case, the
355      * data will be written to the buffer returned from the most recent call to
356      * readDataAvailable().  If the previous calls to readDataAvailable()
357      * returned different buffers, the ReadCallback is responsible for ensuring
358      * that they are not leaked.
359      *
360      * If getReadBuffer() throws an exception, returns a nullptr buffer, or
361      * returns a 0 length, the ReadCallback will be uninstalled and its
362      * readError() method will be invoked.
363      *
364      * getReadBuffer() is not allowed to change the transport state before it
365      * returns.  (For example, it should never uninstall the read callback, or
366      * set a different read callback.)
367      *
368      * @param bufReturn getReadBuffer() should update *bufReturn to contain the
369      *                  address of the read buffer.  This parameter will never
370      *                  be nullptr.
371      * @param lenReturn getReadBuffer() should update *lenReturn to contain the
372      *                  maximum number of bytes that may be written to the read
373      *                  buffer.  This parameter will never be nullptr.
374      */
375     virtual void getReadBuffer(void** bufReturn, size_t* lenReturn) = 0;
376
377     /**
378      * readDataAvailable() will be invoked when data has been successfully read
379      * into the buffer returned by the last call to getReadBuffer().
380      *
381      * The read callback remains installed after readDataAvailable() returns.
382      * It must be explicitly uninstalled to stop receiving read events.
383      * getReadBuffer() will be called at least once before each call to
384      * readDataAvailable().  getReadBuffer() will also be called before any
385      * call to readEOF().
386      *
387      * @param len       The number of bytes placed in the buffer.
388      */
389
390     virtual void readDataAvailable(size_t len) noexcept = 0;
391
392     /**
393      * When data becomes available, isBufferMovable() will be invoked to figure
394      * out which API will be used, readBufferAvailable() or
395      * readDataAvailable(). If isBufferMovable() returns true, that means
396      * ReadCallback supports the IOBuf ownership transfer and
397      * readBufferAvailable() will be used.  Otherwise, not.
398
399      * By default, isBufferMovable() always return false. If
400      * readBufferAvailable() is implemented and to be invoked, You should
401      * overwrite isBufferMovable() and return true in the inherited class.
402      *
403      * This method allows the AsyncSocket/AsyncSSLSocket do buffer allocation by
404      * itself until data becomes available.  Compared with the pre/post buffer
405      * allocation in getReadBuffer()/readDataAvailabe(), readBufferAvailable()
406      * has two advantages.  First, this can avoid memcpy. E.g., in
407      * AsyncSSLSocket, the decrypted data was copied from the openssl internal
408      * buffer to the readbuf buffer.  With the buffer ownership transfer, the
409      * internal buffer can be directly "moved" to ReadCallback. Second, the
410      * memory allocation can be more precise.  The reason is
411      * AsyncSocket/AsyncSSLSocket can allocate the memory of precise size
412      * because they have more context about the available data than
413      * ReadCallback.  Think about the getReadBuffer() pre-allocate 4072 bytes
414      * buffer, but the available data is always 16KB (max OpenSSL record size).
415      */
416
417     virtual bool isBufferMovable() noexcept {
418       return false;
419     }
420
421     /**
422      * readBufferAvailable() will be invoked when data has been successfully
423      * read.
424      *
425      * Note that only either readBufferAvailable() or readDataAvailable() will
426      * be invoked according to the return value of isBufferMovable(). The timing
427      * and aftereffect of readBufferAvailable() are the same as
428      * readDataAvailable()
429      *
430      * @param readBuf The unique pointer of read buffer.
431      */
432
433     virtual void readBufferAvailable(std::unique_ptr<IOBuf> readBuf)
434       noexcept {};
435
436     /**
437      * readEOF() will be invoked when the transport is closed.
438      *
439      * The read callback will be automatically uninstalled immediately before
440      * readEOF() is invoked.
441      */
442     virtual void readEOF() noexcept = 0;
443
444     /**
445      * readError() will be invoked if an error occurs reading from the
446      * transport.
447      *
448      * The read callback will be automatically uninstalled immediately before
449      * readError() is invoked.
450      *
451      * @param ex        An exception describing the error that occurred.
452      */
453     virtual void readErr(const AsyncSocketException& ex) noexcept = 0;
454   };
455
456   class WriteCallback {
457    public:
458     virtual ~WriteCallback() = default;
459
460     /**
461      * writeSuccess() will be invoked when all of the data has been
462      * successfully written.
463      *
464      * Note that this mainly signals that the buffer containing the data to
465      * write is no longer needed and may be freed or re-used.  It does not
466      * guarantee that the data has been fully transmitted to the remote
467      * endpoint.  For example, on socket-based transports, writeSuccess() only
468      * indicates that the data has been given to the kernel for eventual
469      * transmission.
470      */
471     virtual void writeSuccess() noexcept = 0;
472
473     /**
474      * writeError() will be invoked if an error occurs writing the data.
475      *
476      * @param bytesWritten      The number of bytes that were successfull
477      * @param ex                An exception describing the error that occurred.
478      */
479     virtual void writeErr(size_t bytesWritten,
480                           const AsyncSocketException& ex) noexcept = 0;
481   };
482
483   // Read/write methods that aren't part of AsyncTransport
484   virtual void setReadCB(ReadCallback* callback) = 0;
485   virtual ReadCallback* getReadCallback() const = 0;
486
487   virtual void write(WriteCallback* callback, const void* buf, size_t bytes,
488                      WriteFlags flags = WriteFlags::NONE) = 0;
489   virtual void writev(WriteCallback* callback, const iovec* vec, size_t count,
490                       WriteFlags flags = WriteFlags::NONE) = 0;
491   virtual void writeChain(WriteCallback* callback,
492                           std::unique_ptr<IOBuf>&& buf,
493                           WriteFlags flags = WriteFlags::NONE) = 0;
494 };
495
496 } // folly