2 * Copyright 2015 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>
26 // Due to the way kernel headers are included, this may or may not be defined.
27 // Number pulled from 3.10 kernel headers.
29 #define SO_REUSEPORT 15
34 AsyncUDPSocket::AsyncUDPSocket(EventBase* evb)
35 : EventHandler(CHECK_NOTNULL(evb)),
38 readCallback_(nullptr) {
39 DCHECK(evb->isInEventBaseThread());
42 AsyncUDPSocket::~AsyncUDPSocket() {
48 void AsyncUDPSocket::bind(const folly::SocketAddress& address) {
49 int socket = ::socket(address.getFamily(), SOCK_DGRAM, IPPROTO_UDP);
51 throw AsyncSocketException(AsyncSocketException::NOT_OPEN,
52 "error creating async udp socket",
56 auto g = folly::makeGuard([&] { ::close(socket); });
58 // put the socket in non-blocking mode
59 int ret = fcntl(socket, F_SETFL, O_NONBLOCK);
61 throw AsyncSocketException(AsyncSocketException::NOT_OPEN,
62 "failed to put socket in non-blocking mode",
66 // put the socket in reuse mode
68 if (setsockopt(socket,
72 sizeof(value)) != 0) {
73 throw AsyncSocketException(AsyncSocketException::NOT_OPEN,
74 "failed to put socket in reuse mode",
79 // put the socket in port reuse mode
81 if (setsockopt(socket,
85 sizeof(value)) != 0) {
87 throw AsyncSocketException(AsyncSocketException::NOT_OPEN,
88 "failed to put socket in reuse_port mode",
94 // If we're using IPv6, make sure we don't accept V4-mapped connections
95 if (address.getFamily() == AF_INET6) {
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",
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(),
120 ownership_ = FDOwnership::OWNS;
122 // attach to EventHandler
123 EventHandler::changeHandlerFD(fd_);
125 if (address.getPort() != 0) {
126 localAddress_ = address;
128 localAddress_.setFromLocalAddress(fd_);
132 void AsyncUDPSocket::setFD(int fd, FDOwnership ownership) {
133 CHECK_EQ(-1, fd_) << "Already bound to another FD";
136 ownership_ = ownership;
138 EventHandler::changeHandlerFD(fd_);
139 localAddress_.setFromLocalAddress(fd_);
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.
149 size_t iovec_len = buf->fillIov(vec, sizeof(vec)/sizeof(vec[0]));
150 if (UNLIKELY(iovec_len == 0)) {
152 vec[0].iov_base = const_cast<uint8_t*>(buf->data());
153 vec[0].iov_len = buf->length();
157 return writev(address, vec, iovec_len);
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";
164 sockaddr_storage addrStorage;
165 address.getAddress(&addrStorage);
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;
176 return ::sendmsg(fd_, &msg, 0);
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";
183 readCallback_ = CHECK_NOTNULL(cob);
184 if (!updateRegistration()) {
185 AsyncSocketException ex(AsyncSocketException::NOT_OPEN,
186 "failed to register for accept events");
188 readCallback_ = nullptr;
189 cob->onReadError(ex);
194 void AsyncUDPSocket::pauseRead() {
195 // It is ok to pause an already paused socket
196 readCallback_ = nullptr;
197 updateRegistration();
200 void AsyncUDPSocket::close() {
201 DCHECK(eventBase_->isInEventBaseThread());
204 auto cob = readCallback_;
205 readCallback_ = nullptr;
210 // Unregister any events we are registered for
213 if (fd_ != -1 && ownership_ == FDOwnership::OWNS) {
220 void AsyncUDPSocket::handlerReady(uint16_t events) noexcept {
221 if (events & EventHandler::READ) {
222 DCHECK(readCallback_);
227 void AsyncUDPSocket::handleRead() noexcept {
231 readCallback_->getReadBuffer(&buf, &len);
232 if (buf == nullptr || len == 0) {
233 AsyncSocketException ex(
234 AsyncSocketException::BAD_ARGS,
235 "AsyncUDPSocket::getReadBuffer() returned empty buffer");
238 auto cob = readCallback_;
239 readCallback_ = nullptr;
241 cob->onReadError(ex);
242 updateRegistration();
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();
252 ssize_t bytesRead = ::recvfrom(fd_, buf, len, MSG_TRUNC, rawAddr, &addrLen);
253 if (bytesRead >= 0) {
254 clientAddress_.setFromSockaddr(rawAddr, addrLen);
257 bool truncated = false;
258 if ((size_t)bytesRead > len) {
263 readCallback_->onDataAvailable(clientAddress_, bytesRead, truncated);
266 if (errno == EAGAIN || errno == EWOULDBLOCK) {
267 // No data could be read without blocking the socket
271 AsyncSocketException ex(AsyncSocketException::INTERNAL_ERROR,
272 "::recvfrom() failed",
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;
281 cob->onReadError(ex);
282 updateRegistration();
286 bool AsyncUDPSocket::updateRegistration() noexcept {
287 uint16_t flags = NONE;
293 return registerHandler(flags | PERSIST);