TYPE3
[iec.git] / src / type3_AndroidCloud / anbox-master / android / service / local_socket_connection.cpp
1 /*
2  * Copyright (C) 2016 Simon Fels <morphis@gravedo.de>
3  *
4  * This program is free software: you can redistribute it and/or modify it
5  * under the terms of the GNU General Public License version 3, as published
6  * by the Free Software Foundation.
7  *
8  * This program is distributed in the hope that it will be useful, but
9  * WITHOUT ANY WARRANTY; without even the implied warranties of
10  * MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR
11  * PURPOSE.  See the GNU General Public License for more details.
12  *
13  * You should have received a copy of the GNU General Public License along
14  * with this program.  If not, see <http://www.gnu.org/licenses/>.
15  *
16  */
17
18 #include "android/service/local_socket_connection.h"
19
20 #include <sys/types.h>
21 #include <sys/socket.h>
22 #include <sys/un.h>
23 #include <unistd.h>
24 #include <errno.h>
25
26 #define LOG_TAG "Anboxd"
27 #include <cutils/log.h>
28
29 namespace {
30 bool socket_error_is_transient(int error_code) {
31     return (error_code == EINTR);
32 }
33 }
34
35 namespace anbox {
36 LocalSocketConnection::LocalSocketConnection(const std::string &path) :
37     fd_(Fd::invalid) {
38
39     struct sockaddr_un socket_address;
40     memset(&socket_address, 0, sizeof(socket_address));
41
42     socket_address.sun_family = AF_UNIX;
43     memcpy(socket_address.sun_path, path.data(), path.size());
44
45     fd_ = Fd{socket(AF_UNIX, SOCK_STREAM, 0)};
46     if (connect(fd_, reinterpret_cast<sockaddr*>(&socket_address), sizeof(socket_address)) < 0)
47         throw std::runtime_error("Failed to connect to server socket");
48 }
49
50 LocalSocketConnection::~LocalSocketConnection() {
51     if (fd_ > 0)
52         ::close(fd_);
53 }
54
55 ssize_t LocalSocketConnection::read_all(std::uint8_t *buffer, const size_t &size) {
56     ssize_t bytes_read = ::recv(fd_, reinterpret_cast<void*>(buffer), size, 0);
57     return bytes_read;
58 }
59
60 void LocalSocketConnection::send(char const* data, size_t length) {
61     size_t bytes_written{0};
62
63     while(bytes_written < length) {
64         ssize_t const result = ::send(fd_,
65                                       data + bytes_written,
66                                       length - bytes_written,
67                                       MSG_NOSIGNAL);
68         if (result < 0) {
69             if (socket_error_is_transient(errno))
70                 continue;
71             else
72                 throw std::runtime_error("Failed to send message to server");
73         }
74
75         bytes_written += result;
76     }
77 }
78
79 ssize_t LocalSocketConnection::send_raw(char const* data, size_t length) {
80   (void)data;
81   (void)length;
82   return -EIO;
83 }
84 } // namespace anbox