2 * Copyright 2014 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>
27 AsyncUDPSocket::AsyncUDPSocket(EventBase* evb)
28 : EventHandler(CHECK_NOTNULL(evb)),
31 readCallback_(nullptr) {
32 DCHECK(evb->isInEventBaseThread());
35 AsyncUDPSocket::~AsyncUDPSocket() {
41 void AsyncUDPSocket::bind(const folly::SocketAddress& address) {
42 int socket = ::socket(address.getFamily(), SOCK_DGRAM, IPPROTO_UDP);
44 throw AsyncSocketException(AsyncSocketException::NOT_OPEN,
45 "error creating async udp socket",
49 auto g = folly::makeGuard([&] { ::close(socket); });
51 // put the socket in non-blocking mode
52 int ret = fcntl(socket, F_SETFL, O_NONBLOCK);
54 throw AsyncSocketException(AsyncSocketException::NOT_OPEN,
55 "failed to put socket in non-blocking mode",
59 // put the socket in reuse mode
61 if (setsockopt(socket,
65 sizeof(value)) != 0) {
66 throw AsyncSocketException(AsyncSocketException::NOT_OPEN,
67 "failed to put socket in reuse mode",
71 // bind to the address
72 sockaddr_storage addrStorage;
73 address.getAddress(&addrStorage);
74 sockaddr* saddr = reinterpret_cast<sockaddr*>(&addrStorage);
75 if (::bind(socket, saddr, address.getActualSize()) != 0) {
76 throw AsyncSocketException(
77 AsyncSocketException::NOT_OPEN,
78 "failed to bind the async udp socket for:" + address.describe(),
85 ownership_ = FDOwnership::OWNS;
87 // attach to EventHandler
88 EventHandler::changeHandlerFD(fd_);
90 if (address.getPort() != 0) {
91 localAddress_ = address;
93 localAddress_.setFromLocalAddress(fd_);
97 void AsyncUDPSocket::setFD(int fd, FDOwnership ownership) {
98 CHECK_EQ(-1, fd_) << "Already bound to another FD";
101 ownership_ = ownership;
103 EventHandler::changeHandlerFD(fd_);
104 localAddress_.setFromLocalAddress(fd_);
107 ssize_t AsyncUDPSocket::write(const folly::SocketAddress& address,
108 const std::unique_ptr<folly::IOBuf>& buf) {
109 CHECK_NE(-1, fd_) << "Socket not yet bound";
111 // XXX: Use `sendmsg` instead of coalescing here
114 sockaddr_storage addrStorage;
115 address.getAddress(&addrStorage);
116 sockaddr* saddr = reinterpret_cast<sockaddr*>(&addrStorage);
123 address.getActualSize());
126 void AsyncUDPSocket::resumeRead(ReadCallback* cob) {
127 CHECK(!readCallback_) << "Another read callback already installed";
128 CHECK_NE(-1, fd_) << "UDP server socket not yet bind to an address";
130 readCallback_ = CHECK_NOTNULL(cob);
131 if (!updateRegistration()) {
132 AsyncSocketException ex(AsyncSocketException::NOT_OPEN,
133 "failed to register for accept events");
135 readCallback_ = nullptr;
136 cob->onReadError(ex);
141 void AsyncUDPSocket::pauseRead() {
142 // It is ok to pause an already paused socket
143 readCallback_ = nullptr;
144 updateRegistration();
147 void AsyncUDPSocket::close() {
148 DCHECK(eventBase_->isInEventBaseThread());
151 auto cob = readCallback_;
152 readCallback_ = nullptr;
157 // Unregister any events we are registered for
160 if (fd_ != -1 && ownership_ == FDOwnership::OWNS) {
167 void AsyncUDPSocket::handlerReady(uint16_t events) noexcept {
168 if (events & EventHandler::READ) {
169 DCHECK(readCallback_);
174 void AsyncUDPSocket::handleRead() noexcept {
178 readCallback_->getReadBuffer(&buf, &len);
179 if (buf == nullptr || len == 0) {
180 AsyncSocketException ex(
181 AsyncSocketException::BAD_ARGS,
182 "AsyncUDPSocket::getReadBuffer() returned empty buffer");
185 auto cob = readCallback_;
186 readCallback_ = nullptr;
188 cob->onReadError(ex);
189 updateRegistration();
193 struct sockaddr_storage addrStorage;
194 socklen_t addrLen = sizeof(addrStorage);
195 memset(&addrStorage, 0, addrLen);
196 struct sockaddr* rawAddr = reinterpret_cast<sockaddr*>(&addrStorage);
197 rawAddr->sa_family = localAddress_.getFamily();
199 ssize_t bytesRead = ::recvfrom(fd_, buf, len, MSG_TRUNC, rawAddr, &addrLen);
200 if (bytesRead >= 0) {
201 clientAddress_.setFromSockaddr(rawAddr, addrLen);
204 bool truncated = false;
205 if ((size_t)bytesRead > len) {
210 readCallback_->onDataAvailable(clientAddress_, bytesRead, truncated);
213 if (errno == EAGAIN || errno == EWOULDBLOCK) {
214 // No data could be read without blocking the socket
218 AsyncSocketException ex(AsyncSocketException::INTERNAL_ERROR,
219 "::recvfrom() failed",
222 // In case of UDP we can continue reading from the socket
223 // even if the current request fails. We notify the user
224 // so that he can do some logging/stats collection if he wants.
225 auto cob = readCallback_;
226 readCallback_ = nullptr;
228 cob->onReadError(ex);
229 updateRegistration();
233 bool AsyncUDPSocket::updateRegistration() noexcept {
234 uint16_t flags = NONE;
240 return registerHandler(flags | PERSIST);