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 #ifndef _WIN32
32 #include <sys/select.h>
33 #endif
34
35 #include <android-base/errors.h>
36 #include <android-base/stringprintf.h>
37
Socket(cutils_socket_t sock)38 Socket::Socket(cutils_socket_t sock) : sock_(sock) {}
39
~Socket()40 Socket::~Socket() {
41 Close();
42 }
43
Close()44 int Socket::Close() {
45 int ret = 0;
46
47 if (sock_ != INVALID_SOCKET) {
48 ret = socket_close(sock_);
49 sock_ = INVALID_SOCKET;
50 }
51
52 return ret;
53 }
54
ReceiveAll(void * data,size_t length,int timeout_ms)55 ssize_t Socket::ReceiveAll(void* data, size_t length, int timeout_ms) {
56 size_t total = 0;
57
58 while (total < length) {
59 ssize_t bytes = Receive(reinterpret_cast<char*>(data) + total, length - total, timeout_ms);
60
61 // Returns 0 only when the peer has disconnected because our requested length is not 0. So
62 // we return immediately to avoid dead loop here.
63 if (bytes <= 0) {
64 if (total == 0) {
65 return -1;
66 }
67 break;
68 }
69 total += bytes;
70 }
71
72 return total;
73 }
74
GetLocalPort()75 int Socket::GetLocalPort() {
76 return socket_get_local_port(sock_);
77 }
78
79 // According to Windows setsockopt() documentation, if a Windows socket times out during send() or
80 // recv() the state is indeterminate and should not be used. Our UDP protocol relies on being able
81 // to re-send after a timeout, so we must use select() rather than SO_RCVTIMEO.
82 // See https://msdn.microsoft.com/en-us/library/windows/desktop/ms740476(v=vs.85).aspx.
WaitForRecv(int timeout_ms)83 bool Socket::WaitForRecv(int timeout_ms) {
84 receive_timed_out_ = false;
85
86 // In our usage |timeout_ms| <= 0 means block forever, so just return true immediately and let
87 // the subsequent recv() do the blocking.
88 if (timeout_ms <= 0) {
89 return true;
90 }
91
92 // select() doesn't always check this case and will block for |timeout_ms| if we let it.
93 if (sock_ == INVALID_SOCKET) {
94 return false;
95 }
96
97 fd_set read_set;
98 FD_ZERO(&read_set);
99 FD_SET(sock_, &read_set);
100
101 timeval timeout;
102 timeout.tv_sec = timeout_ms / 1000;
103 timeout.tv_usec = (timeout_ms % 1000) * 1000;
104
105 int result = TEMP_FAILURE_RETRY(select(sock_ + 1, &read_set, nullptr, nullptr, &timeout));
106
107 if (result == 0) {
108 receive_timed_out_ = true;
109 }
110 return result == 1;
111 }
112
113 // Implements the Socket interface for UDP.
114 class UdpSocket : public Socket {
115 public:
116 enum class Type { kClient, kServer };
117
118 UdpSocket(Type type, cutils_socket_t sock);
119
120 bool Send(const void* data, size_t length) override;
121 bool Send(std::vector<cutils_socket_buffer_t> buffers) override;
122 ssize_t Receive(void* data, size_t length, int timeout_ms) override;
123
124 private:
125 std::unique_ptr<sockaddr_storage> addr_;
126 socklen_t addr_size_ = 0;
127
128 DISALLOW_COPY_AND_ASSIGN(UdpSocket);
129 };
130
UdpSocket(Type type,cutils_socket_t sock)131 UdpSocket::UdpSocket(Type type, cutils_socket_t sock) : Socket(sock) {
132 // Only servers need to remember addresses; clients are connected to a server in NewClient()
133 // so will send to that server without needing to specify the address again.
134 if (type == Type::kServer) {
135 addr_.reset(new sockaddr_storage);
136 addr_size_ = sizeof(*addr_);
137 memset(addr_.get(), 0, addr_size_);
138 }
139 }
140
Send(const void * data,size_t length)141 bool UdpSocket::Send(const void* data, size_t length) {
142 return TEMP_FAILURE_RETRY(sendto(sock_, reinterpret_cast<const char*>(data), length, 0,
143 reinterpret_cast<sockaddr*>(addr_.get()), addr_size_)) ==
144 static_cast<ssize_t>(length);
145 }
146
Send(std::vector<cutils_socket_buffer_t> buffers)147 bool UdpSocket::Send(std::vector<cutils_socket_buffer_t> buffers) {
148 size_t total_length = 0;
149 for (const auto& buffer : buffers) {
150 total_length += buffer.length;
151 }
152
153 return TEMP_FAILURE_RETRY(socket_send_buffers_function_(
154 sock_, buffers.data(), buffers.size())) == static_cast<ssize_t>(total_length);
155 }
156
Receive(void * data,size_t length,int timeout_ms)157 ssize_t UdpSocket::Receive(void* data, size_t length, int timeout_ms) {
158 if (!WaitForRecv(timeout_ms)) {
159 return -1;
160 }
161
162 socklen_t* addr_size_ptr = nullptr;
163 if (addr_ != nullptr) {
164 // Reset addr_size as it may have been modified by previous recvfrom() calls.
165 addr_size_ = sizeof(*addr_);
166 addr_size_ptr = &addr_size_;
167 }
168
169 return TEMP_FAILURE_RETRY(recvfrom(sock_, reinterpret_cast<char*>(data), length, 0,
170 reinterpret_cast<sockaddr*>(addr_.get()), addr_size_ptr));
171 }
172
173 // Implements the Socket interface for TCP.
174 class TcpSocket : public Socket {
175 public:
TcpSocket(cutils_socket_t sock)176 explicit TcpSocket(cutils_socket_t sock) : Socket(sock) {}
177
178 bool Send(const void* data, size_t length) override;
179 bool Send(std::vector<cutils_socket_buffer_t> buffers) override;
180 ssize_t Receive(void* data, size_t length, int timeout_ms) override;
181
182 std::unique_ptr<Socket> Accept() override;
183
184 private:
185 DISALLOW_COPY_AND_ASSIGN(TcpSocket);
186 };
187
Send(const void * data,size_t length)188 bool TcpSocket::Send(const void* data, size_t length) {
189 while (length > 0) {
190 ssize_t sent =
191 TEMP_FAILURE_RETRY(send(sock_, reinterpret_cast<const char*>(data), length, 0));
192
193 if (sent == -1) {
194 return false;
195 }
196 length -= sent;
197 }
198
199 return true;
200 }
201
Send(std::vector<cutils_socket_buffer_t> buffers)202 bool TcpSocket::Send(std::vector<cutils_socket_buffer_t> buffers) {
203 while (!buffers.empty()) {
204 ssize_t sent = TEMP_FAILURE_RETRY(
205 socket_send_buffers_function_(sock_, buffers.data(), buffers.size()));
206
207 if (sent == -1) {
208 return false;
209 }
210
211 // Adjust the buffers to skip past the bytes we've just sent.
212 auto iter = buffers.begin();
213 while (sent > 0) {
214 if (iter->length > static_cast<size_t>(sent)) {
215 // Incomplete buffer write; adjust the buffer to point to the next byte to send.
216 iter->length -= sent;
217 iter->data = reinterpret_cast<const char*>(iter->data) + sent;
218 break;
219 }
220
221 // Complete buffer write; move on to the next buffer.
222 sent -= iter->length;
223 ++iter;
224 }
225
226 // Shortcut the common case: we've written everything remaining.
227 if (iter == buffers.end()) {
228 break;
229 }
230 buffers.erase(buffers.begin(), iter);
231 }
232
233 return true;
234 }
235
Receive(void * data,size_t length,int timeout_ms)236 ssize_t TcpSocket::Receive(void* data, size_t length, int timeout_ms) {
237 if (!WaitForRecv(timeout_ms)) {
238 return -1;
239 }
240
241 return TEMP_FAILURE_RETRY(recv(sock_, reinterpret_cast<char*>(data), length, 0));
242 }
243
Accept()244 std::unique_ptr<Socket> TcpSocket::Accept() {
245 cutils_socket_t handler = accept(sock_, nullptr, nullptr);
246 if (handler == INVALID_SOCKET) {
247 return nullptr;
248 }
249 return std::unique_ptr<TcpSocket>(new TcpSocket(handler));
250 }
251
NewClient(Protocol protocol,const std::string & host,int port,std::string * error)252 std::unique_ptr<Socket> Socket::NewClient(Protocol protocol, const std::string& host, int port,
253 std::string* error) {
254 if (protocol == Protocol::kUdp) {
255 cutils_socket_t sock = socket_network_client(host.c_str(), port, SOCK_DGRAM);
256 if (sock != INVALID_SOCKET) {
257 return std::unique_ptr<UdpSocket>(new UdpSocket(UdpSocket::Type::kClient, sock));
258 }
259 } else {
260 cutils_socket_t sock = socket_network_client(host.c_str(), port, SOCK_STREAM);
261 if (sock != INVALID_SOCKET) {
262 return std::unique_ptr<TcpSocket>(new TcpSocket(sock));
263 }
264 }
265
266 if (error) {
267 *error = android::base::StringPrintf("Failed to connect to %s:%d", host.c_str(), port);
268 }
269 return nullptr;
270 }
271
272 // This functionality is currently only used by tests so we don't need any error messages.
NewServer(Protocol protocol,int port)273 std::unique_ptr<Socket> Socket::NewServer(Protocol protocol, int port) {
274 if (protocol == Protocol::kUdp) {
275 cutils_socket_t sock = socket_inaddr_any_server(port, SOCK_DGRAM);
276 if (sock != INVALID_SOCKET) {
277 return std::unique_ptr<UdpSocket>(new UdpSocket(UdpSocket::Type::kServer, sock));
278 }
279 } else {
280 cutils_socket_t sock = socket_inaddr_any_server(port, SOCK_STREAM);
281 if (sock != INVALID_SOCKET) {
282 return std::unique_ptr<TcpSocket>(new TcpSocket(sock));
283 }
284 }
285
286 return nullptr;
287 }
288
GetErrorMessage()289 std::string Socket::GetErrorMessage() {
290 #if defined(_WIN32)
291 DWORD error_code = WSAGetLastError();
292 #else
293 int error_code = errno;
294 #endif
295 return android::base::SystemErrorCodeToString(error_code);
296 }
297