aboutsummaryrefslogtreecommitdiffstats
path: root/src/Socket.cpp
blob: 08cda686b03a5f8ab9bb0d9c7475ab6e895c1394 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
/*
   Copyright (C) 2005, 2006, 2007, 2008, 2009, 2010 Her Majesty the
   Queen in Right of Canada (Communications Research Center Canada)

   Copyright (C) 2018
   Matthias P. Braendli, matthias.braendli@mpb.li

    http://opendigitalradio.org
*/

/*
   This file is part of ODR-DabMod.

   ODR-DabMod is free software: you can redistribute it and/or modify
   it under the terms of the GNU General Public License as
   published by the Free Software Foundation, either version 3 of the
   License, or (at your option) any later version.

   ODR-DabMod is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.

   You should have received a copy of the GNU General Public License
   along with ODR-DabMod.  If not, see <http://www.gnu.org/licenses/>.
 */

#include "Socket.h"
#include "Log.h"
#include <fcntl.h>

TCPSocket::TCPSocket()
{
    if ((m_sock = socket(PF_INET, SOCK_STREAM, 0)) < 0) {
        throw std::runtime_error("Can't create TCP socket");
    }

#if defined(HAVE_SO_NOSIGPIPE)
    int val = 1;
    if (setsockopt(m_sock, SOL_SOCKET, SO_NOSIGPIPE,
                &val, sizeof(val)) < 0) {
        throw std::runtime_error("Can't set SO_NOSIGPIPE");
    }
#endif
}

TCPSocket::~TCPSocket()
{
    if (m_sock != -1) {
        ::close(m_sock);
    }
}

TCPSocket::TCPSocket(TCPSocket&& other)
{
    m_sock = other.m_sock;

    if (other.m_sock != -1) {
        other.m_sock = -1;
    }
}

TCPSocket& TCPSocket::operator=(TCPSocket&& other)
{
    m_sock = other.m_sock;

    if (other.m_sock != -1) {
        other.m_sock = -1;
    }

    return *this;
}

bool TCPSocket::valid() const
{
    return m_sock != -1;
}

void TCPSocket::connect(const std::string& hostname, int port)
{
    struct sockaddr_in addr;
    addr.sin_family = PF_INET;
    addr.sin_addr.s_addr = htons(INADDR_ANY);
    addr.sin_port = htons(port);

    hostent *host = gethostbyname(hostname.c_str());
    if (host) {
        addr.sin_addr = *(in_addr *)(host->h_addr);
    }
    else {
        std::string errstr(strerror(errno));
        throw std::runtime_error(
                "could not resolve hostname " +
                hostname + ":" + std::to_string(port) +
                " : " + errstr);
    }

    int ret = ::connect(m_sock, (struct sockaddr*)&addr, sizeof(addr));
    if (ret == -1 and errno != EINPROGRESS) {
        std::string errstr(strerror(errno));
        throw std::runtime_error(
                "could not connect to " +
                hostname + ":" + std::to_string(port) +
                " : " + errstr);
    }
}

void TCPSocket::listen(int port)
{
    struct sockaddr_in addr;
    addr.sin_family = AF_INET;
    addr.sin_port = htons(port);
    addr.sin_addr.s_addr = htonl(INADDR_ANY);

    const int reuse = 1;
    if (setsockopt(m_sock, SOL_SOCKET, SO_REUSEADDR,
                &reuse, sizeof(reuse)) < 0) {
        throw std::runtime_error("Can't reuse address for TCP socket");
    }

    if (::bind(m_sock, (struct sockaddr*)&addr, sizeof(addr)) < 0) {
        close();
        throw std::runtime_error("Can't bind TCP socket");
    }

    if (::listen(m_sock, 1) < 0) {
        close();
        m_sock = -1;
        throw std::runtime_error("Can't listen TCP socket");
    }

}

void TCPSocket::close()
{
    ::close(m_sock);
    m_sock = -1;
}

TCPSocket TCPSocket::accept_with_timeout(int timeout_ms, struct sockaddr_in *client)
{
    struct pollfd fds[1];
    fds[0].fd = m_sock;
    fds[0].events = POLLIN;

    int retval = poll(fds, 1, timeout_ms);

    if (retval == -1) {
        std::string errstr(strerror(errno));
        throw std::runtime_error("TCP Socket accept error: " + errstr);
    }
    else if (retval > 0) {
        socklen_t client_len = sizeof(struct sockaddr_in);
        int sockfd = accept(m_sock, (struct sockaddr*)&client, &client_len);
        TCPSocket s(sockfd);
        return s;
    }
    else {
        TCPSocket s(-1);
        return s;
    }
}

ssize_t TCPSocket::sendall(const void *buffer, size_t buflen)
{
    uint8_t *buf = (uint8_t*)buffer;
    while (buflen > 0) {
        /* On Linux, the MSG_NOSIGNAL flag ensures that the process
         * would not receive a SIGPIPE and die.
         * Other systems have SO_NOSIGPIPE set on the socket for the
         * same effect. */
#if defined(HAVE_MSG_NOSIGNAL)
        const int flags = MSG_NOSIGNAL;
#else
        const int flags = 0;
#endif
        ssize_t sent = ::send(m_sock, buf, buflen, flags);
        if (sent < 0) {
            return -1;
        }
        else {
            buf += sent;
            buflen -= sent;
        }
    }
    return buflen;
}

ssize_t TCPSocket::recv(void *buffer, size_t length, int flags)
{
    ssize_t ret = ::recv(m_sock, buffer, length, flags);
    if (ret == -1) {
        std::string errstr(strerror(errno));
        throw std::runtime_error("TCP receive error: " + errstr);
    }
    return ret;
}

ssize_t TCPSocket::recv(void *buffer, size_t length, int flags, int timeout_ms)
{
    struct pollfd fds[1];
    fds[0].fd = m_sock;
    fds[0].events = POLLIN;

    int retval = poll(fds, 1, timeout_ms);

    if (retval == -1 and errno == EINTR) {
        throw Interrupted();
    }
    else if (retval == -1) {
        std::string errstr(strerror(errno));
        throw std::runtime_error("TCP receive with poll() error: " + errstr);
    }
    else if (retval > 0 and (fds[0].revents | POLLIN)) {
        ssize_t ret = ::recv(m_sock, buffer, length, flags);
        if (ret == -1) {
            if (errno == ECONNREFUSED) {
                return 0;
            }
            std::string errstr(strerror(errno));
            throw std::runtime_error("TCP receive after poll() error: " + errstr);
        }
        return ret;
    }
    else {
        throw Timeout();
    }
}

TCPSocket::TCPSocket(int sockfd) {
    m_sock = sockfd;
}

void TCPClient::connect(const std::string& hostname, int port)
{
    m_hostname = hostname;
    m_port = port;
    reconnect();
}

ssize_t TCPClient::recv(void *buffer, size_t length, int flags, int timeout_ms)
{
    try {
        ssize_t ret = m_sock.recv(buffer, length, flags, timeout_ms);

        if (ret == 0) {
            m_sock.close();

            TCPSocket newsock;
            m_sock = std::move(newsock);
            reconnect();
        }

        return ret;
    }
    catch (const TCPSocket::Interrupted&) {
        return -1;
    }
    catch (const TCPSocket::Timeout&) {
        return 0;
    }

    return 0;
}

void TCPClient::reconnect()
{
    int flags = fcntl(m_sock.m_sock, F_GETFL);
    if (fcntl(m_sock.m_sock, F_SETFL, flags | O_NONBLOCK) == -1) {
        std::string errstr(strerror(errno));
        throw std::runtime_error("TCP: Could not set O_NONBLOCK: " + errstr);
    }

    m_sock.connect(m_hostname, m_port);
}