1364ed3fac93deb003a2c75ef07896e22d150838
[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   // If we're using IPv6, make sure we don't accept V4-mapped connections
95   if (address.getFamily() == AF_INET6) {
96     int flag = 1;
97     if (::setsockopt(socket, IPPROTO_IPV6, IPV6_V6ONLY,
98                      &flag, sizeof(flag))) {
99       throw AsyncSocketException(
100         AsyncSocketException::NOT_OPEN,
101         "Failed to set IPV6_V6ONLY",
102         errno);
103     }
104   }
105
106   // bind to the address
107   sockaddr_storage addrStorage;
108   address.getAddress(&addrStorage);
109   sockaddr* saddr = reinterpret_cast<sockaddr*>(&addrStorage);
110   if (::bind(socket, saddr, address.getActualSize()) != 0) {
111     throw AsyncSocketException(
112         AsyncSocketException::NOT_OPEN,
113         "failed to bind the async udp socket for:" + address.describe(),
114         errno);
115   }
116
117   // success
118   g.dismiss();
119   fd_ = socket;
120   ownership_ = FDOwnership::OWNS;
121
122   // attach to EventHandler
123   EventHandler::changeHandlerFD(fd_);
124
125   if (address.getPort() != 0) {
126     localAddress_ = address;
127   } else {
128     localAddress_.setFromLocalAddress(fd_);
129   }
130 }
131
132 void AsyncUDPSocket::setFD(int fd, FDOwnership ownership) {
133   CHECK_EQ(-1, fd_) << "Already bound to another FD";
134
135   fd_ = fd;
136   ownership_ = ownership;
137
138   EventHandler::changeHandlerFD(fd_);
139   localAddress_.setFromLocalAddress(fd_);
140 }
141
142 ssize_t AsyncUDPSocket::write(const folly::SocketAddress& address,
143                                const std::unique_ptr<folly::IOBuf>& buf) {
144   // UDP's typical MTU size is 1500, so high number of buffers
145   //   really do not make sense. Optimze for buffer chains with
146   //   buffers less than 16, which is the highest I can think of
147   //   for a real use case.
148   iovec vec[16];
149   size_t iovec_len = buf->fillIov(vec, sizeof(vec)/sizeof(vec[0]));
150   if (UNLIKELY(iovec_len == 0)) {
151     buf->coalesce();
152     vec[0].iov_base = const_cast<uint8_t*>(buf->data());
153     vec[0].iov_len = buf->length();
154     iovec_len = 1;
155   }
156
157   return writev(address, vec, iovec_len);
158 }
159
160 ssize_t AsyncUDPSocket::writev(const folly::SocketAddress& address,
161                                const struct iovec* vec, size_t iovec_len) {
162   CHECK_NE(-1, fd_) << "Socket not yet bound";
163
164   sockaddr_storage addrStorage;
165   address.getAddress(&addrStorage);
166
167   struct msghdr msg;
168   msg.msg_name = reinterpret_cast<void*>(&addrStorage);
169   msg.msg_namelen = address.getActualSize();
170   msg.msg_iov = const_cast<struct iovec*>(vec);
171   msg.msg_iovlen = iovec_len;
172   msg.msg_control = nullptr;
173   msg.msg_controllen = 0;
174   msg.msg_flags = 0;
175
176   return ::sendmsg(fd_, &msg, 0);
177 }
178
179 void AsyncUDPSocket::resumeRead(ReadCallback* cob) {
180   CHECK(!readCallback_) << "Another read callback already installed";
181   CHECK_NE(-1, fd_) << "UDP server socket not yet bind to an address";
182
183   readCallback_ = CHECK_NOTNULL(cob);
184   if (!updateRegistration()) {
185     AsyncSocketException ex(AsyncSocketException::NOT_OPEN,
186                            "failed to register for accept events");
187
188     readCallback_ = nullptr;
189     cob->onReadError(ex);
190     return;
191   }
192 }
193
194 void AsyncUDPSocket::pauseRead() {
195   // It is ok to pause an already paused socket
196   readCallback_ = nullptr;
197   updateRegistration();
198 }
199
200 void AsyncUDPSocket::close() {
201   DCHECK(eventBase_->isInEventBaseThread());
202
203   if (readCallback_) {
204     auto cob = readCallback_;
205     readCallback_ = nullptr;
206
207     cob->onReadClosed();
208   }
209
210   // Unregister any events we are registered for
211   unregisterHandler();
212
213   if (fd_ != -1 && ownership_ == FDOwnership::OWNS) {
214     ::close(fd_);
215   }
216
217   fd_ = -1;
218 }
219
220 void AsyncUDPSocket::handlerReady(uint16_t events) noexcept {
221   if (events & EventHandler::READ) {
222     DCHECK(readCallback_);
223     handleRead();
224   }
225 }
226
227 void AsyncUDPSocket::handleRead() noexcept {
228   void* buf{nullptr};
229   size_t len{0};
230
231   readCallback_->getReadBuffer(&buf, &len);
232   if (buf == nullptr || len == 0) {
233     AsyncSocketException ex(
234         AsyncSocketException::BAD_ARGS,
235         "AsyncUDPSocket::getReadBuffer() returned empty buffer");
236
237
238     auto cob = readCallback_;
239     readCallback_ = nullptr;
240
241     cob->onReadError(ex);
242     updateRegistration();
243     return;
244   }
245
246   struct sockaddr_storage addrStorage;
247   socklen_t addrLen = sizeof(addrStorage);
248   memset(&addrStorage, 0, addrLen);
249   struct sockaddr* rawAddr = reinterpret_cast<sockaddr*>(&addrStorage);
250   rawAddr->sa_family = localAddress_.getFamily();
251
252   ssize_t bytesRead = ::recvfrom(fd_, buf, len, MSG_TRUNC, rawAddr, &addrLen);
253   if (bytesRead >= 0) {
254     clientAddress_.setFromSockaddr(rawAddr, addrLen);
255
256     if (bytesRead > 0) {
257       bool truncated = false;
258       if ((size_t)bytesRead > len) {
259         truncated = true;
260         bytesRead = len;
261       }
262
263       readCallback_->onDataAvailable(clientAddress_, bytesRead, truncated);
264     }
265   } else {
266     if (errno == EAGAIN || errno == EWOULDBLOCK) {
267       // No data could be read without blocking the socket
268       return;
269     }
270
271     AsyncSocketException ex(AsyncSocketException::INTERNAL_ERROR,
272                            "::recvfrom() failed",
273                            errno);
274
275     // In case of UDP we can continue reading from the socket
276     // even if the current request fails. We notify the user
277     // so that he can do some logging/stats collection if he wants.
278     auto cob = readCallback_;
279     readCallback_ = nullptr;
280
281     cob->onReadError(ex);
282     updateRegistration();
283   }
284 }
285
286 bool AsyncUDPSocket::updateRegistration() noexcept {
287   uint16_t flags = NONE;
288
289   if (readCallback_) {
290     flags |= READ;
291   }
292
293   return registerHandler(flags | PERSIST);
294 }
295
296 } // Namespace