8bea5a5a809622c384f00f0ee946a2c4fcdde573
[folly.git] / folly / io / async / AsyncUDPSocket.cpp
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 #include <folly/io/async/AsyncUDPSocket.h>
18
19 #include <folly/io/async/EventBase.h>
20 #include <folly/Likely.h>
21
22 #include <errno.h>
23 #include <unistd.h>
24 #include <fcntl.h>
25
26 // Due to the way kernel headers are included, this may or may not be defined.
27 // Number pulled from 3.10 kernel headers.
28 #ifndef SO_REUSEPORT
29 #define SO_REUSEPORT 15
30 #endif
31
32 namespace folly {
33
34 AsyncUDPSocket::AsyncUDPSocket(EventBase* evb)
35     : EventHandler(CHECK_NOTNULL(evb)),
36       eventBase_(evb),
37       fd_(-1),
38       readCallback_(nullptr) {
39   DCHECK(evb->isInEventBaseThread());
40 }
41
42 AsyncUDPSocket::~AsyncUDPSocket() {
43   if (fd_ != -1) {
44     close();
45   }
46 }
47
48 void AsyncUDPSocket::bind(const folly::SocketAddress& address) {
49   int socket = ::socket(address.getFamily(), SOCK_DGRAM, IPPROTO_UDP);
50   if (socket == -1) {
51     throw AsyncSocketException(AsyncSocketException::NOT_OPEN,
52                               "error creating async udp socket",
53                               errno);
54   }
55
56   auto g = folly::makeGuard([&] { ::close(socket); });
57
58   // put the socket in non-blocking mode
59   int ret = fcntl(socket, F_SETFL, O_NONBLOCK);
60   if (ret != 0) {
61     throw AsyncSocketException(AsyncSocketException::NOT_OPEN,
62                               "failed to put socket in non-blocking mode",
63                               errno);
64   }
65
66   // put the socket in reuse mode
67   int value = 1;
68   if (setsockopt(socket,
69                  SOL_SOCKET,
70                  SO_REUSEADDR,
71                  &value,
72                  sizeof(value)) != 0) {
73     throw AsyncSocketException(AsyncSocketException::NOT_OPEN,
74                               "failed to put socket in reuse mode",
75                               errno);
76   }
77
78   if (reusePort_) {
79     // put the socket in port reuse mode
80     int value = 1;
81     if (setsockopt(socket,
82                    SOL_SOCKET,
83                    SO_REUSEPORT,
84                    &value,
85                    sizeof(value)) != 0) {
86       ::close(socket);
87       throw AsyncSocketException(AsyncSocketException::NOT_OPEN,
88                                 "failed to put socket in reuse_port mode",
89                                 errno);
90
91     }
92   }
93
94   // bind to the address
95   sockaddr_storage addrStorage;
96   address.getAddress(&addrStorage);
97   sockaddr* saddr = reinterpret_cast<sockaddr*>(&addrStorage);
98   if (::bind(socket, saddr, address.getActualSize()) != 0) {
99     throw AsyncSocketException(
100         AsyncSocketException::NOT_OPEN,
101         "failed to bind the async udp socket for:" + address.describe(),
102         errno);
103   }
104
105   // success
106   g.dismiss();
107   fd_ = socket;
108   ownership_ = FDOwnership::OWNS;
109
110   // attach to EventHandler
111   EventHandler::changeHandlerFD(fd_);
112
113   if (address.getPort() != 0) {
114     localAddress_ = address;
115   } else {
116     localAddress_.setFromLocalAddress(fd_);
117   }
118 }
119
120 void AsyncUDPSocket::setFD(int fd, FDOwnership ownership) {
121   CHECK_EQ(-1, fd_) << "Already bound to another FD";
122
123   fd_ = fd;
124   ownership_ = ownership;
125
126   EventHandler::changeHandlerFD(fd_);
127   localAddress_.setFromLocalAddress(fd_);
128 }
129
130 ssize_t AsyncUDPSocket::write(const folly::SocketAddress& address,
131                                const std::unique_ptr<folly::IOBuf>& buf) {
132   CHECK_NE(-1, fd_) << "Socket not yet bound";
133
134   // UDP's typical MTU size is 1500, so high number of buffers
135   //   really do not make sense. Optimze for buffer chains with
136   //   buffers less than 16, which is the highest I can think of
137   //   for a real use case.
138   iovec vec[16];
139   size_t iovec_len = buf->fillIov(vec, sizeof(vec)/sizeof(vec[0]));
140   if (UNLIKELY(iovec_len == 0)) {
141     buf->coalesce();
142     vec[0].iov_base = const_cast<uint8_t*>(buf->data());
143     vec[0].iov_len = buf->length();
144     iovec_len = 1;
145   }
146
147   sockaddr_storage addrStorage;
148   address.getAddress(&addrStorage);
149
150   struct msghdr msg;
151   msg.msg_name = reinterpret_cast<void*>(&addrStorage);
152   msg.msg_namelen = address.getActualSize();
153   msg.msg_iov = vec;
154   msg.msg_iovlen = iovec_len;
155   msg.msg_control = nullptr;
156   msg.msg_controllen = 0;
157   msg.msg_flags = 0;
158
159   return ::sendmsg(fd_, &msg, 0);
160 }
161
162 void AsyncUDPSocket::resumeRead(ReadCallback* cob) {
163   CHECK(!readCallback_) << "Another read callback already installed";
164   CHECK_NE(-1, fd_) << "UDP server socket not yet bind to an address";
165
166   readCallback_ = CHECK_NOTNULL(cob);
167   if (!updateRegistration()) {
168     AsyncSocketException ex(AsyncSocketException::NOT_OPEN,
169                            "failed to register for accept events");
170
171     readCallback_ = nullptr;
172     cob->onReadError(ex);
173     return;
174   }
175 }
176
177 void AsyncUDPSocket::pauseRead() {
178   // It is ok to pause an already paused socket
179   readCallback_ = nullptr;
180   updateRegistration();
181 }
182
183 void AsyncUDPSocket::close() {
184   DCHECK(eventBase_->isInEventBaseThread());
185
186   if (readCallback_) {
187     auto cob = readCallback_;
188     readCallback_ = nullptr;
189
190     cob->onReadClosed();
191   }
192
193   // Unregister any events we are registered for
194   unregisterHandler();
195
196   if (fd_ != -1 && ownership_ == FDOwnership::OWNS) {
197     ::close(fd_);
198   }
199
200   fd_ = -1;
201 }
202
203 void AsyncUDPSocket::handlerReady(uint16_t events) noexcept {
204   if (events & EventHandler::READ) {
205     DCHECK(readCallback_);
206     handleRead();
207   }
208 }
209
210 void AsyncUDPSocket::handleRead() noexcept {
211   void* buf{nullptr};
212   size_t len{0};
213
214   readCallback_->getReadBuffer(&buf, &len);
215   if (buf == nullptr || len == 0) {
216     AsyncSocketException ex(
217         AsyncSocketException::BAD_ARGS,
218         "AsyncUDPSocket::getReadBuffer() returned empty buffer");
219
220
221     auto cob = readCallback_;
222     readCallback_ = nullptr;
223
224     cob->onReadError(ex);
225     updateRegistration();
226     return;
227   }
228
229   struct sockaddr_storage addrStorage;
230   socklen_t addrLen = sizeof(addrStorage);
231   memset(&addrStorage, 0, addrLen);
232   struct sockaddr* rawAddr = reinterpret_cast<sockaddr*>(&addrStorage);
233   rawAddr->sa_family = localAddress_.getFamily();
234
235   ssize_t bytesRead = ::recvfrom(fd_, buf, len, MSG_TRUNC, rawAddr, &addrLen);
236   if (bytesRead >= 0) {
237     clientAddress_.setFromSockaddr(rawAddr, addrLen);
238
239     if (bytesRead > 0) {
240       bool truncated = false;
241       if ((size_t)bytesRead > len) {
242         truncated = true;
243         bytesRead = len;
244       }
245
246       readCallback_->onDataAvailable(clientAddress_, bytesRead, truncated);
247     }
248   } else {
249     if (errno == EAGAIN || errno == EWOULDBLOCK) {
250       // No data could be read without blocking the socket
251       return;
252     }
253
254     AsyncSocketException ex(AsyncSocketException::INTERNAL_ERROR,
255                            "::recvfrom() failed",
256                            errno);
257
258     // In case of UDP we can continue reading from the socket
259     // even if the current request fails. We notify the user
260     // so that he can do some logging/stats collection if he wants.
261     auto cob = readCallback_;
262     readCallback_ = nullptr;
263
264     cob->onReadError(ex);
265     updateRegistration();
266   }
267 }
268
269 bool AsyncUDPSocket::updateRegistration() noexcept {
270   uint16_t flags = NONE;
271
272   if (readCallback_) {
273     flags |= READ;
274   }
275
276   return registerHandler(flags | PERSIST);
277 }
278
279 } // Namespace