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