2 * Copyright 2016 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.
17 #include <folly/io/async/AsyncUDPSocket.h>
19 #include <folly/io/async/EventBase.h>
20 #include <folly/Likely.h>
21 #include <folly/portability/Fcntl.h>
22 #include <folly/portability/Sockets.h>
23 #include <folly/portability/Unistd.h>
27 // Due to the way kernel headers are included, this may or may not be defined.
28 // Number pulled from 3.10 kernel headers.
30 #define SO_REUSEPORT 15
33 namespace fsp = folly::portability::sockets;
37 AsyncUDPSocket::AsyncUDPSocket(EventBase* evb)
38 : EventHandler(CHECK_NOTNULL(evb)),
41 readCallback_(nullptr) {
42 DCHECK(evb->isInEventBaseThread());
45 AsyncUDPSocket::~AsyncUDPSocket() {
51 void AsyncUDPSocket::bind(const folly::SocketAddress& address) {
52 int socket = fsp::socket(address.getFamily(), SOCK_DGRAM, IPPROTO_UDP);
54 throw AsyncSocketException(AsyncSocketException::NOT_OPEN,
55 "error creating async udp socket",
59 auto g = folly::makeGuard([&] { ::close(socket); });
61 // put the socket in non-blocking mode
62 int ret = fcntl(socket, F_SETFL, O_NONBLOCK);
64 throw AsyncSocketException(AsyncSocketException::NOT_OPEN,
65 "failed to put socket in non-blocking mode",
70 // put the socket in reuse mode
72 if (setsockopt(socket,
76 sizeof(value)) != 0) {
77 throw AsyncSocketException(AsyncSocketException::NOT_OPEN,
78 "failed to put socket in reuse mode",
84 // put the socket in port reuse mode
86 if (setsockopt(socket,
90 sizeof(value)) != 0) {
92 throw AsyncSocketException(AsyncSocketException::NOT_OPEN,
93 "failed to put socket in reuse_port mode",
99 // If we're using IPv6, make sure we don't accept V4-mapped connections
100 if (address.getFamily() == AF_INET6) {
102 if (setsockopt(socket, IPPROTO_IPV6, IPV6_V6ONLY, &flag, sizeof(flag))) {
103 throw AsyncSocketException(
104 AsyncSocketException::NOT_OPEN,
105 "Failed to set IPV6_V6ONLY",
110 // bind to the address
111 sockaddr_storage addrStorage;
112 address.getAddress(&addrStorage);
113 sockaddr* saddr = reinterpret_cast<sockaddr*>(&addrStorage);
114 if (fsp::bind(socket, saddr, address.getActualSize()) != 0) {
115 throw AsyncSocketException(
116 AsyncSocketException::NOT_OPEN,
117 "failed to bind the async udp socket for:" + address.describe(),
124 ownership_ = FDOwnership::OWNS;
126 // attach to EventHandler
127 EventHandler::changeHandlerFD(fd_);
129 if (address.getPort() != 0) {
130 localAddress_ = address;
132 localAddress_.setFromLocalAddress(fd_);
136 void AsyncUDPSocket::setFD(int fd, FDOwnership ownership) {
137 CHECK_EQ(-1, fd_) << "Already bound to another FD";
140 ownership_ = ownership;
142 EventHandler::changeHandlerFD(fd_);
143 localAddress_.setFromLocalAddress(fd_);
146 ssize_t AsyncUDPSocket::write(const folly::SocketAddress& address,
147 const std::unique_ptr<folly::IOBuf>& buf) {
148 // UDP's typical MTU size is 1500, so high number of buffers
149 // really do not make sense. Optimze for buffer chains with
150 // buffers less than 16, which is the highest I can think of
151 // for a real use case.
153 size_t iovec_len = buf->fillIov(vec, sizeof(vec)/sizeof(vec[0]));
154 if (UNLIKELY(iovec_len == 0)) {
156 vec[0].iov_base = const_cast<uint8_t*>(buf->data());
157 vec[0].iov_len = buf->length();
161 return writev(address, vec, iovec_len);
164 ssize_t AsyncUDPSocket::writev(const folly::SocketAddress& address,
165 const struct iovec* vec, size_t iovec_len) {
166 CHECK_NE(-1, fd_) << "Socket not yet bound";
168 sockaddr_storage addrStorage;
169 address.getAddress(&addrStorage);
172 msg.msg_name = reinterpret_cast<void*>(&addrStorage);
173 msg.msg_namelen = address.getActualSize();
174 msg.msg_iov = const_cast<struct iovec*>(vec);
175 msg.msg_iovlen = iovec_len;
176 msg.msg_control = nullptr;
177 msg.msg_controllen = 0;
180 return ::sendmsg(fd_, &msg, 0);
183 void AsyncUDPSocket::resumeRead(ReadCallback* cob) {
184 CHECK(!readCallback_) << "Another read callback already installed";
185 CHECK_NE(-1, fd_) << "UDP server socket not yet bind to an address";
187 readCallback_ = CHECK_NOTNULL(cob);
188 if (!updateRegistration()) {
189 AsyncSocketException ex(AsyncSocketException::NOT_OPEN,
190 "failed to register for accept events");
192 readCallback_ = nullptr;
193 cob->onReadError(ex);
198 void AsyncUDPSocket::pauseRead() {
199 // It is ok to pause an already paused socket
200 readCallback_ = nullptr;
201 updateRegistration();
204 void AsyncUDPSocket::close() {
205 DCHECK(eventBase_->isInEventBaseThread());
208 auto cob = readCallback_;
209 readCallback_ = nullptr;
214 // Unregister any events we are registered for
217 if (fd_ != -1 && ownership_ == FDOwnership::OWNS) {
224 void AsyncUDPSocket::handlerReady(uint16_t events) noexcept {
225 if (events & EventHandler::READ) {
226 DCHECK(readCallback_);
231 void AsyncUDPSocket::handleRead() noexcept {
235 readCallback_->getReadBuffer(&buf, &len);
236 if (buf == nullptr || len == 0) {
237 AsyncSocketException ex(
238 AsyncSocketException::BAD_ARGS,
239 "AsyncUDPSocket::getReadBuffer() returned empty buffer");
242 auto cob = readCallback_;
243 readCallback_ = nullptr;
245 cob->onReadError(ex);
246 updateRegistration();
250 struct sockaddr_storage addrStorage;
251 socklen_t addrLen = sizeof(addrStorage);
252 memset(&addrStorage, 0, addrLen);
253 struct sockaddr* rawAddr = reinterpret_cast<sockaddr*>(&addrStorage);
254 rawAddr->sa_family = localAddress_.getFamily();
256 ssize_t bytesRead = recvfrom(fd_, buf, len, MSG_TRUNC, rawAddr, &addrLen);
257 if (bytesRead >= 0) {
258 clientAddress_.setFromSockaddr(rawAddr, addrLen);
261 bool truncated = false;
262 if ((size_t)bytesRead > len) {
267 readCallback_->onDataAvailable(clientAddress_, bytesRead, truncated);
270 if (errno == EAGAIN || errno == EWOULDBLOCK) {
271 // No data could be read without blocking the socket
275 AsyncSocketException ex(AsyncSocketException::INTERNAL_ERROR,
276 "::recvfrom() failed",
279 // In case of UDP we can continue reading from the socket
280 // even if the current request fails. We notify the user
281 // so that he can do some logging/stats collection if he wants.
282 auto cob = readCallback_;
283 readCallback_ = nullptr;
285 cob->onReadError(ex);
286 updateRegistration();
290 bool AsyncUDPSocket::updateRegistration() noexcept {
291 uint16_t flags = NONE;
297 return registerHandler(flags | PERSIST);