blob: d49f47ff24caa17644faaa76ffa40147296d4782 [file] [log] [blame]
David Pursell572bce22016-01-15 14:19:56 -08001/*
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
David Pursellc3a46692016-01-29 08:10:50 -080031#include <android-base/errors.h>
David Pursell572bce22016-01-15 14:19:56 -080032#include <android-base/stringprintf.h>
33
34Socket::Socket(cutils_socket_t sock) : sock_(sock) {}
35
36Socket::~Socket() {
37 Close();
38}
39
40int 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
51bool Socket::SetReceiveTimeout(int timeout_ms) {
52 if (timeout_ms != receive_timeout_ms_) {
53 if (socket_set_receive_timeout(sock_, timeout_ms) == 0) {
54 receive_timeout_ms_ = timeout_ms;
55 return true;
56 }
57 return false;
58 }
59
60 return true;
61}
62
63ssize_t Socket::ReceiveAll(void* data, size_t length, int timeout_ms) {
64 size_t total = 0;
65
66 while (total < length) {
67 ssize_t bytes = Receive(reinterpret_cast<char*>(data) + total, length - total, timeout_ms);
68
69 if (bytes == -1) {
70 if (total == 0) {
71 return -1;
72 }
73 break;
74 }
75 total += bytes;
76 }
77
78 return total;
79}
80
David Pursellc3a46692016-01-29 08:10:50 -080081int Socket::GetLocalPort() {
82 return socket_get_local_port(sock_);
83}
84
David Pursell572bce22016-01-15 14:19:56 -080085// Implements the Socket interface for UDP.
86class UdpSocket : public Socket {
87 public:
88 enum class Type { kClient, kServer };
89
90 UdpSocket(Type type, cutils_socket_t sock);
91
David Pursellb34e4a02016-02-01 09:42:09 -080092 bool Send(const void* data, size_t length) override;
93 bool Send(std::vector<cutils_socket_buffer_t> buffers) override;
David Pursell572bce22016-01-15 14:19:56 -080094 ssize_t Receive(void* data, size_t length, int timeout_ms) override;
95
96 private:
97 std::unique_ptr<sockaddr_storage> addr_;
98 socklen_t addr_size_ = 0;
99
100 DISALLOW_COPY_AND_ASSIGN(UdpSocket);
101};
102
103UdpSocket::UdpSocket(Type type, cutils_socket_t sock) : Socket(sock) {
104 // Only servers need to remember addresses; clients are connected to a server in NewClient()
105 // so will send to that server without needing to specify the address again.
106 if (type == Type::kServer) {
107 addr_.reset(new sockaddr_storage);
108 addr_size_ = sizeof(*addr_);
109 memset(addr_.get(), 0, addr_size_);
110 }
111}
112
David Pursellb34e4a02016-02-01 09:42:09 -0800113bool UdpSocket::Send(const void* data, size_t length) {
David Pursell572bce22016-01-15 14:19:56 -0800114 return TEMP_FAILURE_RETRY(sendto(sock_, reinterpret_cast<const char*>(data), length, 0,
David Pursellb34e4a02016-02-01 09:42:09 -0800115 reinterpret_cast<sockaddr*>(addr_.get()), addr_size_)) ==
116 static_cast<ssize_t>(length);
117}
118
119bool UdpSocket::Send(std::vector<cutils_socket_buffer_t> buffers) {
120 size_t total_length = 0;
121 for (const auto& buffer : buffers) {
122 total_length += buffer.length;
123 }
124
125 return TEMP_FAILURE_RETRY(socket_send_buffers_function_(
126 sock_, buffers.data(), buffers.size())) == static_cast<ssize_t>(total_length);
David Pursell572bce22016-01-15 14:19:56 -0800127}
128
129ssize_t UdpSocket::Receive(void* data, size_t length, int timeout_ms) {
130 if (!SetReceiveTimeout(timeout_ms)) {
131 return -1;
132 }
133
134 socklen_t* addr_size_ptr = nullptr;
135 if (addr_ != nullptr) {
136 // Reset addr_size as it may have been modified by previous recvfrom() calls.
137 addr_size_ = sizeof(*addr_);
138 addr_size_ptr = &addr_size_;
139 }
140
141 return TEMP_FAILURE_RETRY(recvfrom(sock_, reinterpret_cast<char*>(data), length, 0,
142 reinterpret_cast<sockaddr*>(addr_.get()), addr_size_ptr));
143}
144
145// Implements the Socket interface for TCP.
146class TcpSocket : public Socket {
147 public:
148 TcpSocket(cutils_socket_t sock) : Socket(sock) {}
149
David Pursellb34e4a02016-02-01 09:42:09 -0800150 bool Send(const void* data, size_t length) override;
151 bool Send(std::vector<cutils_socket_buffer_t> buffers) override;
David Pursell572bce22016-01-15 14:19:56 -0800152 ssize_t Receive(void* data, size_t length, int timeout_ms) override;
153
154 std::unique_ptr<Socket> Accept() override;
155
156 private:
157 DISALLOW_COPY_AND_ASSIGN(TcpSocket);
158};
159
David Pursellb34e4a02016-02-01 09:42:09 -0800160bool TcpSocket::Send(const void* data, size_t length) {
161 while (length > 0) {
162 ssize_t sent =
163 TEMP_FAILURE_RETRY(send(sock_, reinterpret_cast<const char*>(data), length, 0));
David Pursell572bce22016-01-15 14:19:56 -0800164
David Pursellb34e4a02016-02-01 09:42:09 -0800165 if (sent == -1) {
166 return false;
David Pursell572bce22016-01-15 14:19:56 -0800167 }
David Pursellb34e4a02016-02-01 09:42:09 -0800168 length -= sent;
David Pursell572bce22016-01-15 14:19:56 -0800169 }
170
David Pursellb34e4a02016-02-01 09:42:09 -0800171 return true;
172}
173
174bool TcpSocket::Send(std::vector<cutils_socket_buffer_t> buffers) {
175 while (!buffers.empty()) {
176 ssize_t sent = TEMP_FAILURE_RETRY(
177 socket_send_buffers_function_(sock_, buffers.data(), buffers.size()));
178
179 if (sent == -1) {
180 return false;
181 }
182
183 // Adjust the buffers to skip past the bytes we've just sent.
184 auto iter = buffers.begin();
185 while (sent > 0) {
186 if (iter->length > static_cast<size_t>(sent)) {
187 // Incomplete buffer write; adjust the buffer to point to the next byte to send.
188 iter->length -= sent;
189 iter->data = reinterpret_cast<const char*>(iter->data) + sent;
190 break;
191 }
192
193 // Complete buffer write; move on to the next buffer.
194 sent -= iter->length;
195 ++iter;
196 }
197
198 // Shortcut the common case: we've written everything remaining.
199 if (iter == buffers.end()) {
200 break;
201 }
202 buffers.erase(buffers.begin(), iter);
203 }
204
205 return true;
David Pursell572bce22016-01-15 14:19:56 -0800206}
207
208ssize_t TcpSocket::Receive(void* data, size_t length, int timeout_ms) {
209 if (!SetReceiveTimeout(timeout_ms)) {
210 return -1;
211 }
212
213 return TEMP_FAILURE_RETRY(recv(sock_, reinterpret_cast<char*>(data), length, 0));
214}
215
216std::unique_ptr<Socket> TcpSocket::Accept() {
217 cutils_socket_t handler = accept(sock_, nullptr, nullptr);
218 if (handler == INVALID_SOCKET) {
219 return nullptr;
220 }
221 return std::unique_ptr<TcpSocket>(new TcpSocket(handler));
222}
223
224std::unique_ptr<Socket> Socket::NewClient(Protocol protocol, const std::string& host, int port,
225 std::string* error) {
226 if (protocol == Protocol::kUdp) {
227 cutils_socket_t sock = socket_network_client(host.c_str(), port, SOCK_DGRAM);
228 if (sock != INVALID_SOCKET) {
229 return std::unique_ptr<UdpSocket>(new UdpSocket(UdpSocket::Type::kClient, sock));
230 }
231 } else {
232 cutils_socket_t sock = socket_network_client(host.c_str(), port, SOCK_STREAM);
233 if (sock != INVALID_SOCKET) {
234 return std::unique_ptr<TcpSocket>(new TcpSocket(sock));
235 }
236 }
237
238 if (error) {
239 *error = android::base::StringPrintf("Failed to connect to %s:%d", host.c_str(), port);
240 }
241 return nullptr;
242}
243
244// This functionality is currently only used by tests so we don't need any error messages.
245std::unique_ptr<Socket> Socket::NewServer(Protocol protocol, int port) {
246 if (protocol == Protocol::kUdp) {
247 cutils_socket_t sock = socket_inaddr_any_server(port, SOCK_DGRAM);
248 if (sock != INVALID_SOCKET) {
249 return std::unique_ptr<UdpSocket>(new UdpSocket(UdpSocket::Type::kServer, sock));
250 }
251 } else {
252 cutils_socket_t sock = socket_inaddr_any_server(port, SOCK_STREAM);
253 if (sock != INVALID_SOCKET) {
254 return std::unique_ptr<TcpSocket>(new TcpSocket(sock));
255 }
256 }
257
258 return nullptr;
259}
David Pursellc3a46692016-01-29 08:10:50 -0800260
261std::string Socket::GetErrorMessage() {
262#if defined(_WIN32)
263 DWORD error_code = WSAGetLastError();
264#else
265 int error_code = errno;
266#endif
267 return android::base::SystemErrorCodeToString(error_code);
268}