• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2015 The Android Open Source Project
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  *  * Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  *  * Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in
12  *    the documentation and/or other materials provided with the
13  *    distribution.
14  *
15  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
16  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
17  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
18  * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
19  * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
20  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
21  * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
22  * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
23  * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
24  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
25  * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
26  * SUCH DAMAGE.
27  */
28 
29 #include "socket.h"
30 
31 #include <android-base/errors.h>
32 #include <android-base/stringprintf.h>
33 
Socket(cutils_socket_t sock)34 Socket::Socket(cutils_socket_t sock) : sock_(sock) {}
35 
~Socket()36 Socket::~Socket() {
37     Close();
38 }
39 
Close()40 int Socket::Close() {
41     int ret = 0;
42 
43     if (sock_ != INVALID_SOCKET) {
44         ret = socket_close(sock_);
45         sock_ = INVALID_SOCKET;
46     }
47 
48     return ret;
49 }
50 
ReceiveAll(void * data,size_t length,int timeout_ms)51 ssize_t Socket::ReceiveAll(void* data, size_t length, int timeout_ms) {
52     size_t total = 0;
53 
54     while (total < length) {
55         ssize_t bytes = Receive(reinterpret_cast<char*>(data) + total, length - total, timeout_ms);
56 
57         // Returns 0 only when the peer has disconnected because our requested length is not 0. So
58         // we return immediately to avoid dead loop here.
59         if (bytes <= 0) {
60             if (total == 0) {
61                 return -1;
62             }
63             break;
64         }
65         total += bytes;
66     }
67 
68     return total;
69 }
70 
GetLocalPort()71 int Socket::GetLocalPort() {
72     return socket_get_local_port(sock_);
73 }
74 
75 // According to Windows setsockopt() documentation, if a Windows socket times out during send() or
76 // recv() the state is indeterminate and should not be used. Our UDP protocol relies on being able
77 // to re-send after a timeout, so we must use select() rather than SO_RCVTIMEO.
78 // See https://msdn.microsoft.com/en-us/library/windows/desktop/ms740476(v=vs.85).aspx.
WaitForRecv(int timeout_ms)79 bool Socket::WaitForRecv(int timeout_ms) {
80     receive_timed_out_ = false;
81 
82     // In our usage |timeout_ms| <= 0 means block forever, so just return true immediately and let
83     // the subsequent recv() do the blocking.
84     if (timeout_ms <= 0) {
85         return true;
86     }
87 
88     // select() doesn't always check this case and will block for |timeout_ms| if we let it.
89     if (sock_ == INVALID_SOCKET) {
90         return false;
91     }
92 
93     fd_set read_set;
94     FD_ZERO(&read_set);
95     FD_SET(sock_, &read_set);
96 
97     timeval timeout;
98     timeout.tv_sec = timeout_ms / 1000;
99     timeout.tv_usec = (timeout_ms % 1000) * 1000;
100 
101     int result = TEMP_FAILURE_RETRY(select(sock_ + 1, &read_set, nullptr, nullptr, &timeout));
102 
103     if (result == 0) {
104         receive_timed_out_ = true;
105     }
106     return result == 1;
107 }
108 
109 // Implements the Socket interface for UDP.
110 class UdpSocket : public Socket {
111   public:
112     enum class Type { kClient, kServer };
113 
114     UdpSocket(Type type, cutils_socket_t sock);
115 
116     bool Send(const void* data, size_t length) override;
117     bool Send(std::vector<cutils_socket_buffer_t> buffers) override;
118     ssize_t Receive(void* data, size_t length, int timeout_ms) override;
119 
120   private:
121     std::unique_ptr<sockaddr_storage> addr_;
122     socklen_t addr_size_ = 0;
123 
124     DISALLOW_COPY_AND_ASSIGN(UdpSocket);
125 };
126 
UdpSocket(Type type,cutils_socket_t sock)127 UdpSocket::UdpSocket(Type type, cutils_socket_t sock) : Socket(sock) {
128     // Only servers need to remember addresses; clients are connected to a server in NewClient()
129     // so will send to that server without needing to specify the address again.
130     if (type == Type::kServer) {
131         addr_.reset(new sockaddr_storage);
132         addr_size_ = sizeof(*addr_);
133         memset(addr_.get(), 0, addr_size_);
134     }
135 }
136 
Send(const void * data,size_t length)137 bool UdpSocket::Send(const void* data, size_t length) {
138     return TEMP_FAILURE_RETRY(sendto(sock_, reinterpret_cast<const char*>(data), length, 0,
139                                      reinterpret_cast<sockaddr*>(addr_.get()), addr_size_)) ==
140            static_cast<ssize_t>(length);
141 }
142 
Send(std::vector<cutils_socket_buffer_t> buffers)143 bool UdpSocket::Send(std::vector<cutils_socket_buffer_t> buffers) {
144     size_t total_length = 0;
145     for (const auto& buffer : buffers) {
146         total_length += buffer.length;
147     }
148 
149     return TEMP_FAILURE_RETRY(socket_send_buffers_function_(
150                    sock_, buffers.data(), buffers.size())) == static_cast<ssize_t>(total_length);
151 }
152 
Receive(void * data,size_t length,int timeout_ms)153 ssize_t UdpSocket::Receive(void* data, size_t length, int timeout_ms) {
154     if (!WaitForRecv(timeout_ms)) {
155         return -1;
156     }
157 
158     socklen_t* addr_size_ptr = nullptr;
159     if (addr_ != nullptr) {
160         // Reset addr_size as it may have been modified by previous recvfrom() calls.
161         addr_size_ = sizeof(*addr_);
162         addr_size_ptr = &addr_size_;
163     }
164 
165     return TEMP_FAILURE_RETRY(recvfrom(sock_, reinterpret_cast<char*>(data), length, 0,
166                                        reinterpret_cast<sockaddr*>(addr_.get()), addr_size_ptr));
167 }
168 
169 // Implements the Socket interface for TCP.
170 class TcpSocket : public Socket {
171   public:
TcpSocket(cutils_socket_t sock)172     explicit TcpSocket(cutils_socket_t sock) : Socket(sock) {}
173 
174     bool Send(const void* data, size_t length) override;
175     bool Send(std::vector<cutils_socket_buffer_t> buffers) override;
176     ssize_t Receive(void* data, size_t length, int timeout_ms) override;
177 
178     std::unique_ptr<Socket> Accept() override;
179 
180   private:
181     DISALLOW_COPY_AND_ASSIGN(TcpSocket);
182 };
183 
Send(const void * data,size_t length)184 bool TcpSocket::Send(const void* data, size_t length) {
185     while (length > 0) {
186         ssize_t sent =
187                 TEMP_FAILURE_RETRY(send(sock_, reinterpret_cast<const char*>(data), length, 0));
188 
189         if (sent == -1) {
190             return false;
191         }
192         length -= sent;
193     }
194 
195     return true;
196 }
197 
Send(std::vector<cutils_socket_buffer_t> buffers)198 bool TcpSocket::Send(std::vector<cutils_socket_buffer_t> buffers) {
199     while (!buffers.empty()) {
200         ssize_t sent = TEMP_FAILURE_RETRY(
201                 socket_send_buffers_function_(sock_, buffers.data(), buffers.size()));
202 
203         if (sent == -1) {
204             return false;
205         }
206 
207         // Adjust the buffers to skip past the bytes we've just sent.
208         auto iter = buffers.begin();
209         while (sent > 0) {
210             if (iter->length > static_cast<size_t>(sent)) {
211                 // Incomplete buffer write; adjust the buffer to point to the next byte to send.
212                 iter->length -= sent;
213                 iter->data = reinterpret_cast<const char*>(iter->data) + sent;
214                 break;
215             }
216 
217             // Complete buffer write; move on to the next buffer.
218             sent -= iter->length;
219             ++iter;
220         }
221 
222         // Shortcut the common case: we've written everything remaining.
223         if (iter == buffers.end()) {
224             break;
225         }
226         buffers.erase(buffers.begin(), iter);
227     }
228 
229     return true;
230 }
231 
Receive(void * data,size_t length,int timeout_ms)232 ssize_t TcpSocket::Receive(void* data, size_t length, int timeout_ms) {
233     if (!WaitForRecv(timeout_ms)) {
234         return -1;
235     }
236 
237     return TEMP_FAILURE_RETRY(recv(sock_, reinterpret_cast<char*>(data), length, 0));
238 }
239 
Accept()240 std::unique_ptr<Socket> TcpSocket::Accept() {
241     cutils_socket_t handler = accept(sock_, nullptr, nullptr);
242     if (handler == INVALID_SOCKET) {
243         return nullptr;
244     }
245     return std::unique_ptr<TcpSocket>(new TcpSocket(handler));
246 }
247 
NewClient(Protocol protocol,const std::string & host,int port,std::string * error)248 std::unique_ptr<Socket> Socket::NewClient(Protocol protocol, const std::string& host, int port,
249                                           std::string* error) {
250     if (protocol == Protocol::kUdp) {
251         cutils_socket_t sock = socket_network_client(host.c_str(), port, SOCK_DGRAM);
252         if (sock != INVALID_SOCKET) {
253             return std::unique_ptr<UdpSocket>(new UdpSocket(UdpSocket::Type::kClient, sock));
254         }
255     } else {
256         cutils_socket_t sock = socket_network_client(host.c_str(), port, SOCK_STREAM);
257         if (sock != INVALID_SOCKET) {
258             return std::unique_ptr<TcpSocket>(new TcpSocket(sock));
259         }
260     }
261 
262     if (error) {
263         *error = android::base::StringPrintf("Failed to connect to %s:%d", host.c_str(), port);
264     }
265     return nullptr;
266 }
267 
268 // This functionality is currently only used by tests so we don't need any error messages.
NewServer(Protocol protocol,int port)269 std::unique_ptr<Socket> Socket::NewServer(Protocol protocol, int port) {
270     if (protocol == Protocol::kUdp) {
271         cutils_socket_t sock = socket_inaddr_any_server(port, SOCK_DGRAM);
272         if (sock != INVALID_SOCKET) {
273             return std::unique_ptr<UdpSocket>(new UdpSocket(UdpSocket::Type::kServer, sock));
274         }
275     } else {
276         cutils_socket_t sock = socket_inaddr_any_server(port, SOCK_STREAM);
277         if (sock != INVALID_SOCKET) {
278             return std::unique_ptr<TcpSocket>(new TcpSocket(sock));
279         }
280     }
281 
282     return nullptr;
283 }
284 
GetErrorMessage()285 std::string Socket::GetErrorMessage() {
286 #if defined(_WIN32)
287     DWORD error_code = WSAGetLastError();
288 #else
289     int error_code = errno;
290 #endif
291     return android::base::SystemErrorCodeToString(error_code);
292 }
293