Move TAsyncTransport to folly as AsyncTransportWrapper
[folly.git] / folly / io / async / AsyncSocket.h
1 /*
2  * Copyright 2014 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 <sys/types.h>
20 #include <sys/socket.h>
21 #include <glog/logging.h>
22 #include <folly/SocketAddress.h>
23 #include <folly/io/ShutdownSocketSet.h>
24 #include <folly/io/IOBuf.h>
25 #include <folly/io/async/AsyncTimeout.h>
26 #include <folly/io/async/AsyncSocketException.h>
27 #include <folly/io/async/AsyncTransport.h>
28 #include <folly/io/async/EventHandler.h>
29 #include <folly/io/async/DelayedDestruction.h>
30
31 #include <memory>
32 #include <map>
33
34 namespace folly {
35
36 /**
37  * A class for performing asynchronous I/O on a socket.
38  *
39  * AsyncSocket allows users to asynchronously wait for data on a socket, and
40  * to asynchronously send data.
41  *
42  * The APIs for reading and writing are intentionally asymmetric.  Waiting for
43  * data to read is a persistent API: a callback is installed, and is notified
44  * whenever new data is available.  It continues to be notified of new events
45  * until it is uninstalled.
46  *
47  * AsyncSocket does not provide read timeout functionality, because it
48  * typically cannot determine when the timeout should be active.  Generally, a
49  * timeout should only be enabled when processing is blocked waiting on data
50  * from the remote endpoint.  For server sockets, the timeout should not be
51  * active if the server is currently processing one or more outstanding
52  * requests for this socket.  For client sockets, the timeout should not be
53  * active if there are no requests pending on the socket.  Additionally, if a
54  * client has multiple pending requests, it will ususally want a separate
55  * timeout for each request, rather than a single read timeout.
56  *
57  * The write API is fairly intuitive: a user can request to send a block of
58  * data, and a callback will be informed once the entire block has been
59  * transferred to the kernel, or on error.  AsyncSocket does provide a send
60  * timeout, since most callers want to give up if the remote end stops
61  * responding and no further progress can be made sending the data.
62  */
63
64 class AsyncSocket : virtual public AsyncTransportWrapper {
65  public:
66   typedef std::unique_ptr<AsyncSocket, Destructor> UniquePtr;
67
68   class ConnectCallback {
69    public:
70     virtual ~ConnectCallback() {}
71
72     /**
73      * connectSuccess() will be invoked when the connection has been
74      * successfully established.
75      */
76     virtual void connectSuccess() noexcept = 0;
77
78     /**
79      * connectErr() will be invoked if the connection attempt fails.
80      *
81      * @param ex        An exception describing the error that occurred.
82      */
83     virtual void connectErr(const AsyncSocketException& ex)
84       noexcept = 0;
85   };
86
87   explicit AsyncSocket();
88   /**
89    * Create a new unconnected AsyncSocket.
90    *
91    * connect() must later be called on this socket to establish a connection.
92    */
93   explicit AsyncSocket(EventBase* evb);
94
95   void setShutdownSocketSet(ShutdownSocketSet* ss);
96
97   /**
98    * Create a new AsyncSocket and begin the connection process.
99    *
100    * @param evb             EventBase that will manage this socket.
101    * @param address         The address to connect to.
102    * @param connectTimeout  Optional timeout in milliseconds for the connection
103    *                        attempt.
104    */
105   AsyncSocket(EventBase* evb,
106                const folly::SocketAddress& address,
107                uint32_t connectTimeout = 0);
108
109   /**
110    * Create a new AsyncSocket and begin the connection process.
111    *
112    * @param evb             EventBase that will manage this socket.
113    * @param ip              IP address to connect to (dotted-quad).
114    * @param port            Destination port in host byte order.
115    * @param connectTimeout  Optional timeout in milliseconds for the connection
116    *                        attempt.
117    */
118   AsyncSocket(EventBase* evb,
119                const std::string& ip,
120                uint16_t port,
121                uint32_t connectTimeout = 0);
122
123   /**
124    * Create a AsyncSocket from an already connected socket file descriptor.
125    *
126    * Note that while AsyncSocket enables TCP_NODELAY for sockets it creates
127    * when connecting, it does not change the socket options when given an
128    * existing file descriptor.  If callers want TCP_NODELAY enabled when using
129    * this version of the constructor, they need to explicitly call
130    * setNoDelay(true) after the constructor returns.
131    *
132    * @param evb EventBase that will manage this socket.
133    * @param fd  File descriptor to take over (should be a connected socket).
134    */
135   AsyncSocket(EventBase* evb, int fd);
136
137   /**
138    * Helper function to create a shared_ptr<AsyncSocket>.
139    *
140    * This passes in the correct destructor object, since AsyncSocket's
141    * destructor is protected and cannot be invoked directly.
142    */
143   static std::shared_ptr<AsyncSocket> newSocket(EventBase* evb) {
144     return std::shared_ptr<AsyncSocket>(new AsyncSocket(evb),
145                                            Destructor());
146   }
147
148   /**
149    * Helper function to create a shared_ptr<AsyncSocket>.
150    */
151   static std::shared_ptr<AsyncSocket> newSocket(
152       EventBase* evb,
153       const folly::SocketAddress& address,
154       uint32_t connectTimeout = 0) {
155     return std::shared_ptr<AsyncSocket>(
156         new AsyncSocket(evb, address, connectTimeout),
157         Destructor());
158   }
159
160   /**
161    * Helper function to create a shared_ptr<AsyncSocket>.
162    */
163   static std::shared_ptr<AsyncSocket> newSocket(
164       EventBase* evb,
165       const std::string& ip,
166       uint16_t port,
167       uint32_t connectTimeout = 0) {
168     return std::shared_ptr<AsyncSocket>(
169         new AsyncSocket(evb, ip, port, connectTimeout),
170         Destructor());
171   }
172
173   /**
174    * Helper function to create a shared_ptr<AsyncSocket>.
175    */
176   static std::shared_ptr<AsyncSocket> newSocket(EventBase* evb, int fd) {
177     return std::shared_ptr<AsyncSocket>(new AsyncSocket(evb, fd),
178                                            Destructor());
179   }
180
181   /**
182    * Destroy the socket.
183    *
184    * AsyncSocket::destroy() must be called to destroy the socket.
185    * The normal destructor is private, and should not be invoked directly.
186    * This prevents callers from deleting a AsyncSocket while it is invoking a
187    * callback.
188    */
189   virtual void destroy();
190
191   /**
192    * Get the EventBase used by this socket.
193    */
194   EventBase* getEventBase() const override {
195     return eventBase_;
196   }
197
198   /**
199    * Get the file descriptor used by the AsyncSocket.
200    */
201   virtual int getFd() const {
202     return fd_;
203   }
204
205   /**
206    * Extract the file descriptor from the AsyncSocket.
207    *
208    * This will immediately cause any installed callbacks to be invoked with an
209    * error.  The AsyncSocket may no longer be used after the file descriptor
210    * has been extracted.
211    *
212    * Returns the file descriptor.  The caller assumes ownership of the
213    * descriptor, and it will not be closed when the AsyncSocket is destroyed.
214    */
215   virtual int detachFd();
216
217   /**
218    * Uniquely identifies a handle to a socket option value. Each
219    * combination of level and option name corresponds to one socket
220    * option value.
221    */
222   class OptionKey {
223    public:
224     bool operator<(const OptionKey& other) const {
225       if (level == other.level) {
226         return optname < other.optname;
227       }
228       return level < other.level;
229     }
230     int apply(int fd, int val) const {
231       return setsockopt(fd, level, optname, &val, sizeof(val));
232     }
233     int level;
234     int optname;
235   };
236
237   // Maps from a socket option key to its value
238   typedef std::map<OptionKey, int> OptionMap;
239
240   static const OptionMap emptyOptionMap;
241   static const folly::SocketAddress anyAddress;
242
243   /**
244    * Initiate a connection.
245    *
246    * @param callback  The callback to inform when the connection attempt
247    *                  completes.
248    * @param address   The address to connect to.
249    * @param timeout   A timeout value, in milliseconds.  If the connection
250    *                  does not succeed within this period,
251    *                  callback->connectError() will be invoked.
252    */
253   virtual void connect(ConnectCallback* callback,
254                const folly::SocketAddress& address,
255                int timeout = 0,
256                const OptionMap &options = emptyOptionMap,
257                const folly::SocketAddress& bindAddr = anyAddress
258                ) noexcept;
259   void connect(ConnectCallback* callback, const std::string& ip, uint16_t port,
260                int timeout = 00,
261                const OptionMap &options = emptyOptionMap) noexcept;
262
263   /**
264    * Set the send timeout.
265    *
266    * If write requests do not make any progress for more than the specified
267    * number of milliseconds, fail all pending writes and close the socket.
268    *
269    * If write requests are currently pending when setSendTimeout() is called,
270    * the timeout interval is immediately restarted using the new value.
271    *
272    * (See the comments for AsyncSocket for an explanation of why AsyncSocket
273    * provides setSendTimeout() but not setRecvTimeout().)
274    *
275    * @param milliseconds  The timeout duration, in milliseconds.  If 0, no
276    *                      timeout will be used.
277    */
278   void setSendTimeout(uint32_t milliseconds) override;
279
280   /**
281    * Get the send timeout.
282    *
283    * @return Returns the current send timeout, in milliseconds.  A return value
284    *         of 0 indicates that no timeout is set.
285    */
286   uint32_t getSendTimeout() const override {
287     return sendTimeout_;
288   }
289
290   /**
291    * Set the maximum number of reads to execute from the underlying
292    * socket each time the EventBase detects that new ingress data is
293    * available. The default is unlimited, but callers can use this method
294    * to limit the amount of data read from the socket per event loop
295    * iteration.
296    *
297    * @param maxReads  Maximum number of reads per data-available event;
298    *                  a value of zero means unlimited.
299    */
300   void setMaxReadsPerEvent(uint16_t maxReads) {
301     maxReadsPerEvent_ = maxReads;
302   }
303
304   /**
305    * Get the maximum number of reads this object will execute from
306    * the underlying socket each time the EventBase detects that new
307    * ingress data is available.
308    *
309    * @returns Maximum number of reads per data-available event; a value
310    *          of zero means unlimited.
311    */
312   uint16_t getMaxReadsPerEvent() const {
313     return maxReadsPerEvent_;
314   }
315
316   // Read and write methods
317   void setReadCB(ReadCallback* callback) override;
318   ReadCallback* getReadCallback() const override;
319
320   void write(WriteCallback* callback, const void* buf, size_t bytes,
321              WriteFlags flags = WriteFlags::NONE) override;
322   void writev(WriteCallback* callback, const iovec* vec, size_t count,
323               WriteFlags flags = WriteFlags::NONE) override;
324   void writeChain(WriteCallback* callback,
325                   std::unique_ptr<folly::IOBuf>&& buf,
326                   WriteFlags flags = WriteFlags::NONE) override;
327
328   // Methods inherited from AsyncTransport
329   void close() override;
330   void closeNow() override;
331   void closeWithReset() override;
332   void shutdownWrite() override;
333   void shutdownWriteNow() override;
334
335   bool readable() const override;
336   bool isPending() const override;
337   virtual bool hangup() const;
338   bool good() const override;
339   bool error() const override;
340   void attachEventBase(EventBase* eventBase) override;
341   void detachEventBase() override;
342   bool isDetachable() const override;
343
344   void getLocalAddress(
345     folly::SocketAddress* address) const override;
346   void getPeerAddress(
347     folly::SocketAddress* address) const override;
348
349   bool isEorTrackingEnabled() const override { return false; }
350
351   void setEorTracking(bool track) override {}
352
353   bool connecting() const override {
354     return (state_ == StateEnum::CONNECTING);
355   }
356
357   size_t getAppBytesWritten() const override {
358     return appBytesWritten_;
359   }
360
361   size_t getRawBytesWritten() const override {
362     return getAppBytesWritten();
363   }
364
365   size_t getAppBytesReceived() const override {
366     return appBytesReceived_;
367   }
368
369   size_t getRawBytesReceived() const override {
370     return getAppBytesReceived();
371   }
372
373   // Methods controlling socket options
374
375   /**
376    * Force writes to be transmitted immediately.
377    *
378    * This controls the TCP_NODELAY socket option.  When enabled, TCP segments
379    * are sent as soon as possible, even if it is not a full frame of data.
380    * When disabled, the data may be buffered briefly to try and wait for a full
381    * frame of data.
382    *
383    * By default, TCP_NODELAY is enabled for AsyncSocket objects.
384    *
385    * This method will fail if the socket is not currently open.
386    *
387    * @return Returns 0 if the TCP_NODELAY flag was successfully updated,
388    *         or a non-zero errno value on error.
389    */
390   int setNoDelay(bool noDelay);
391
392   /*
393    * Set the Flavor of Congestion Control to be used for this Socket
394    * Please check '/lib/modules/<kernel>/kernel/net/ipv4' for tcp_*.ko
395    * first to make sure the module is available for plugging in
396    * Alternatively you can choose from net.ipv4.tcp_allowed_congestion_control
397    */
398   int setCongestionFlavor(const std::string &cname);
399
400   /*
401    * Forces ACKs to be sent immediately
402    *
403    * @return Returns 0 if the TCP_QUICKACK flag was successfully updated,
404    *         or a non-zero errno value on error.
405    */
406   int setQuickAck(bool quickack);
407
408   /**
409    * Set the send bufsize
410    */
411   int setSendBufSize(size_t bufsize);
412
413   /**
414    * Set the recv bufsize
415    */
416   int setRecvBufSize(size_t bufsize);
417
418   /**
419    * Sets a specific tcp personality
420    * Available only on kernels 3.2 and greater
421    */
422   #define SO_SET_NAMESPACE        41
423   int setTCPProfile(int profd);
424
425
426   /**
427    * Generic API for reading a socket option.
428    *
429    * @param level     same as the "level" parameter in getsockopt().
430    * @param optname   same as the "optname" parameter in getsockopt().
431    * @param optval    pointer to the variable in which the option value should
432    *                  be returned.
433    * @param optlen    value-result argument, initially containing the size of
434    *                  the buffer pointed to by optval, and modified on return
435    *                  to indicate the actual size of the value returned.
436    * @return          same as the return value of getsockopt().
437    */
438   template <typename T>
439   int getSockOpt(int level, int optname, T* optval, socklen_t* optlen) {
440     return getsockopt(fd_, level, optname, (void*) optval, optlen);
441   }
442
443   /**
444    * Generic API for setting a socket option.
445    *
446    * @param level     same as the "level" parameter in getsockopt().
447    * @param optname   same as the "optname" parameter in getsockopt().
448    * @param optval    the option value to set.
449    * @return          same as the return value of setsockopt().
450    */
451   template <typename T>
452   int setSockOpt(int  level,  int  optname,  const T *optval) {
453     return setsockopt(fd_, level, optname, optval, sizeof(T));
454   }
455
456   enum class StateEnum : uint8_t {
457     UNINIT,
458     CONNECTING,
459     ESTABLISHED,
460     CLOSED,
461     ERROR
462   };
463
464  protected:
465   enum ReadResultEnum {
466     READ_EOF = 0,
467     READ_ERROR = -1,
468     READ_BLOCKING = -2,
469   };
470
471   /**
472    * Protected destructor.
473    *
474    * Users of AsyncSocket must never delete it directly.  Instead, invoke
475    * destroy() instead.  (See the documentation in DelayedDestruction.h for
476    * more details.)
477    */
478   ~AsyncSocket();
479
480   friend std::ostream& operator << (std::ostream& os, const StateEnum& state);
481
482   enum ShutdownFlags {
483     /// shutdownWrite() called, but we are still waiting on writes to drain
484     SHUT_WRITE_PENDING = 0x01,
485     /// writes have been completely shut down
486     SHUT_WRITE = 0x02,
487     /**
488      * Reads have been shutdown.
489      *
490      * At the moment we don't distinguish between remote read shutdown
491      * (received EOF from the remote end) and local read shutdown.  We can
492      * only receive EOF when a read callback is set, and we immediately inform
493      * it of the EOF.  Therefore there doesn't seem to be any reason to have a
494      * separate state of "received EOF but the local side may still want to
495      * read".
496      *
497      * We also don't currently provide any API for only shutting down the read
498      * side of a socket.  (This is a no-op as far as TCP is concerned, anyway.)
499      */
500     SHUT_READ = 0x04,
501   };
502
503   class WriteRequest;
504
505   class WriteTimeout : public AsyncTimeout {
506    public:
507     WriteTimeout(AsyncSocket* socket, EventBase* eventBase)
508       : AsyncTimeout(eventBase)
509       , socket_(socket) {}
510
511     virtual void timeoutExpired() noexcept {
512       socket_->timeoutExpired();
513     }
514
515    private:
516     AsyncSocket* socket_;
517   };
518
519   class IoHandler : public EventHandler {
520    public:
521     IoHandler(AsyncSocket* socket, EventBase* eventBase)
522       : EventHandler(eventBase, -1)
523       , socket_(socket) {}
524     IoHandler(AsyncSocket* socket, EventBase* eventBase, int fd)
525       : EventHandler(eventBase, fd)
526       , socket_(socket) {}
527
528     virtual void handlerReady(uint16_t events) noexcept {
529       socket_->ioReady(events);
530     }
531
532    private:
533     AsyncSocket* socket_;
534   };
535
536   void init();
537
538   // event notification methods
539   void ioReady(uint16_t events) noexcept;
540   virtual void checkForImmediateRead() noexcept;
541   virtual void handleInitialReadWrite() noexcept;
542   virtual void handleRead() noexcept;
543   virtual void handleWrite() noexcept;
544   virtual void handleConnect() noexcept;
545   void timeoutExpired() noexcept;
546
547   /**
548    * Attempt to read from the socket.
549    *
550    * @param buf      The buffer to read data into.
551    * @param buflen   The length of the buffer.
552    *
553    * @return Returns the number of bytes read, or READ_EOF on EOF, or
554    * READ_ERROR on error, or READ_BLOCKING if the operation will
555    * block.
556    */
557   virtual ssize_t performRead(void* buf, size_t buflen);
558
559   /**
560    * Populate an iovec array from an IOBuf and attempt to write it.
561    *
562    * @param callback Write completion/error callback.
563    * @param vec      Target iovec array; caller retains ownership.
564    * @param count    Number of IOBufs to write, beginning at start of buf.
565    * @param buf      Chain of iovecs.
566    * @param flags    set of flags for the underlying write calls, like cork
567    */
568   void writeChainImpl(WriteCallback* callback, iovec* vec,
569                       size_t count, std::unique_ptr<folly::IOBuf>&& buf,
570                       WriteFlags flags);
571
572   /**
573    * Write as much data as possible to the socket without blocking,
574    * and queue up any leftover data to send when the socket can
575    * handle writes again.
576    *
577    * @param callback The callback to invoke when the write is completed.
578    * @param vec      Array of buffers to write; this method will make a
579    *                 copy of the vector (but not the buffers themselves)
580    *                 if the write has to be completed asynchronously.
581    * @param count    Number of elements in vec.
582    * @param buf      The IOBuf that manages the buffers referenced by
583    *                 vec, or a pointer to nullptr if the buffers are not
584    *                 associated with an IOBuf.  Note that ownership of
585    *                 the IOBuf is transferred here; upon completion of
586    *                 the write, the AsyncSocket deletes the IOBuf.
587    * @param flags    Set of write flags.
588    */
589   void writeImpl(WriteCallback* callback, const iovec* vec, size_t count,
590                  std::unique_ptr<folly::IOBuf>&& buf,
591                  WriteFlags flags = WriteFlags::NONE);
592
593   /**
594    * Attempt to write to the socket.
595    *
596    * @param vec             The iovec array pointing to the buffers to write.
597    * @param count           The length of the iovec array.
598    * @param flags           Set of write flags.
599    * @param countWritten    On return, the value pointed to by this parameter
600    *                          will contain the number of iovec entries that were
601    *                          fully written.
602    * @param partialWritten  On return, the value pointed to by this parameter
603    *                          will contain the number of bytes written in the
604    *                          partially written iovec entry.
605    *
606    * @return Returns the total number of bytes written, or -1 on error.  If no
607    *     data can be written immediately, 0 is returned.
608    */
609   virtual ssize_t performWrite(const iovec* vec, uint32_t count,
610                                WriteFlags flags, uint32_t* countWritten,
611                                uint32_t* partialWritten);
612
613   bool updateEventRegistration();
614
615   /**
616    * Update event registration.
617    *
618    * @param enable Flags of events to enable. Set it to 0 if no events
619    * need to be enabled in this call.
620    * @param disable Flags of events
621    * to disable. Set it to 0 if no events need to be disabled in this
622    * call.
623    *
624    * @return true iff the update is successful.
625    */
626   bool updateEventRegistration(uint16_t enable, uint16_t disable);
627
628   // Actually close the file descriptor and set it to -1 so we don't
629   // accidentally close it again.
630   void doClose();
631
632   // error handling methods
633   void startFail();
634   void finishFail();
635   void fail(const char* fn, const AsyncSocketException& ex);
636   void failConnect(const char* fn, const AsyncSocketException& ex);
637   void failRead(const char* fn, const AsyncSocketException& ex);
638   void failWrite(const char* fn, WriteCallback* callback, size_t bytesWritten,
639                  const AsyncSocketException& ex);
640   void failWrite(const char* fn, const AsyncSocketException& ex);
641   void failAllWrites(const AsyncSocketException& ex);
642   void invalidState(ConnectCallback* callback);
643   void invalidState(ReadCallback* callback);
644   void invalidState(WriteCallback* callback);
645
646   std::string withAddr(const std::string& s);
647
648   StateEnum state_;                     ///< StateEnum describing current state
649   uint8_t shutdownFlags_;               ///< Shutdown state (ShutdownFlags)
650   uint16_t eventFlags_;                 ///< EventBase::HandlerFlags settings
651   int fd_;                              ///< The socket file descriptor
652   mutable
653     folly::SocketAddress addr_;    ///< The address we tried to connect to
654   uint32_t sendTimeout_;                ///< The send timeout, in milliseconds
655   uint16_t maxReadsPerEvent_;           ///< Max reads per event loop iteration
656   EventBase* eventBase_;               ///< The EventBase
657   WriteTimeout writeTimeout_;           ///< A timeout for connect and write
658   IoHandler ioHandler_;                 ///< A EventHandler to monitor the fd
659
660   ConnectCallback* connectCallback_;    ///< ConnectCallback
661   ReadCallback* readCallback_;          ///< ReadCallback
662   WriteRequest* writeReqHead_;          ///< Chain of WriteRequests
663   WriteRequest* writeReqTail_;          ///< End of WriteRequest chain
664   ShutdownSocketSet* shutdownSocketSet_;
665   size_t appBytesReceived_;             ///< Num of bytes received from socket
666   size_t appBytesWritten_;              ///< Num of bytes written to socket
667 };
668
669
670 } // folly