aboutsummaryrefslogtreecommitdiff
path: root/source/Host/common/TCPSocket.cpp
blob: 07b0cdf908f5cb68ef7e4cf5231c30c4036956d3 (plain) (blame)
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
276
277
278
279
280
281
282
283
284
285
//===-- TcpSocket.cpp -------------------------------------------*- C++ -*-===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

#include "lldb/Host/common/TCPSocket.h"

#include "lldb/Core/Log.h"
#include "lldb/Host/Config.h"

#ifndef LLDB_DISABLE_POSIX
#include <arpa/inet.h>
#include <netinet/tcp.h>
#include <sys/socket.h>
#endif

using namespace lldb;
using namespace lldb_private;

namespace {

const int kDomain = AF_INET;
const int kType   = SOCK_STREAM;

}

TCPSocket::TCPSocket(NativeSocket socket, bool should_close)
    : Socket(socket, ProtocolTcp, should_close)
{

}

TCPSocket::TCPSocket(bool child_processes_inherit, Error &error)
    : TCPSocket(CreateSocket(kDomain, kType, IPPROTO_TCP, child_processes_inherit, error), true)
{
}


// Return the port number that is being used by the socket.
uint16_t
TCPSocket::GetLocalPortNumber() const
{
    if (m_socket != kInvalidSocketValue)
    {
        SocketAddress sock_addr;
        socklen_t sock_addr_len = sock_addr.GetMaxLength ();
        if (::getsockname (m_socket, sock_addr, &sock_addr_len) == 0)
            return sock_addr.GetPort ();
    }
    return 0;
}

std::string
TCPSocket::GetLocalIPAddress() const
{
    // We bound to port zero, so we need to figure out which port we actually bound to
    if (m_socket != kInvalidSocketValue)
    {
        SocketAddress sock_addr;
        socklen_t sock_addr_len = sock_addr.GetMaxLength ();
        if (::getsockname (m_socket, sock_addr, &sock_addr_len) == 0)
            return sock_addr.GetIPAddress ();
    }
    return "";
}

uint16_t
TCPSocket::GetRemotePortNumber() const
{
    if (m_socket != kInvalidSocketValue)
    {
        SocketAddress sock_addr;
        socklen_t sock_addr_len = sock_addr.GetMaxLength ();
        if (::getpeername (m_socket, sock_addr, &sock_addr_len) == 0)
            return sock_addr.GetPort ();
    }
    return 0;
}

std::string
TCPSocket::GetRemoteIPAddress () const
{
    // We bound to port zero, so we need to figure out which port we actually bound to
    if (m_socket != kInvalidSocketValue)
    {
        SocketAddress sock_addr;
        socklen_t sock_addr_len = sock_addr.GetMaxLength ();
        if (::getpeername (m_socket, sock_addr, &sock_addr_len) == 0)
            return sock_addr.GetIPAddress ();
    }
    return "";
}

Error
TCPSocket::Connect(llvm::StringRef name)
{
    if (m_socket == kInvalidSocketValue)
        return Error("Invalid socket");

    Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_COMMUNICATION));
    if (log)
        log->Printf ("TCPSocket::%s (host/port = %s)", __FUNCTION__, name.data());

    Error error;
    std::string host_str;
    std::string port_str;
    int32_t port = INT32_MIN;
    if (!DecodeHostAndPort (name, host_str, port_str, port, &error))
        return error;

    struct sockaddr_in sa;
    ::memset (&sa, 0, sizeof (sa));
    sa.sin_family = kDomain;
    sa.sin_port = htons (port);

    int inet_pton_result = ::inet_pton (kDomain, host_str.c_str(), &sa.sin_addr);

    if (inet_pton_result <= 0)
    {
        struct hostent *host_entry = gethostbyname (host_str.c_str());
        if (host_entry)
            host_str = ::inet_ntoa (*(struct in_addr *)*host_entry->h_addr_list);
        inet_pton_result = ::inet_pton (kDomain, host_str.c_str(), &sa.sin_addr);
        if (inet_pton_result <= 0)
        {
            if (inet_pton_result == -1)
                SetLastError(error);
            else
                error.SetErrorStringWithFormat("invalid host string: '%s'", host_str.c_str());

            return error;
        }
    }

    if (-1 == ::connect (GetNativeSocket(), (const struct sockaddr *)&sa, sizeof(sa)))
    {
        SetLastError (error);
        return error;
    }

    // Keep our TCP packets coming without any delays.
    SetOptionNoDelay();
    error.Clear();
    return error;
}

Error
TCPSocket::Listen(llvm::StringRef name, int backlog)
{
    Error error;

    // enable local address reuse
    SetOptionReuseAddress();

    Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_CONNECTION));
    if (log)
        log->Printf ("TCPSocket::%s (%s)", __FUNCTION__, name.data());

    std::string host_str;
    std::string port_str;
    int32_t port = INT32_MIN;
    if (!DecodeHostAndPort (name, host_str, port_str, port, &error))
        return error;

    SocketAddress bind_addr;

    // Only bind to the loopback address if we are expecting a connection from
    // localhost to avoid any firewall issues.
    const bool bind_addr_success = (host_str == "127.0.0.1") ?
                                    bind_addr.SetToLocalhost (kDomain, port) :
                                    bind_addr.SetToAnyAddress (kDomain, port);

    if (!bind_addr_success)
    {
        error.SetErrorString("Failed to bind port");
        return error;
    }

    int err = ::bind (GetNativeSocket(), bind_addr, bind_addr.GetLength());
    if (err != -1)
        err = ::listen (GetNativeSocket(), backlog);

    if (err == -1)
        SetLastError (error);

    return error;
}

Error
TCPSocket::Accept(llvm::StringRef name, bool child_processes_inherit, Socket *&conn_socket)
{
    Error error;
    std::string host_str;
    std::string port_str;
    int32_t port;
    if (!DecodeHostAndPort(name, host_str, port_str, port, &error))
        return error;

    const sa_family_t family = kDomain;
    const int socktype = kType;
    const int protocol = IPPROTO_TCP;
    SocketAddress listen_addr;
    if (host_str.empty())
        listen_addr.SetToLocalhost(family, port);
    else if (host_str.compare("*") == 0)
        listen_addr.SetToAnyAddress(family, port);
    else
    {
        if (!listen_addr.getaddrinfo(host_str.c_str(), port_str.c_str(), family, socktype, protocol))
        {
            error.SetErrorStringWithFormat("unable to resolve hostname '%s'", host_str.c_str());
            return error;
        }
    }

    bool accept_connection = false;
    std::unique_ptr<TCPSocket> accepted_socket;

    // Loop until we are happy with our connection
    while (!accept_connection)
    {
        struct sockaddr_in accept_addr;
        ::memset (&accept_addr, 0, sizeof accept_addr);
#if !(defined (__linux__) || defined(_WIN32))
        accept_addr.sin_len = sizeof accept_addr;
#endif
        socklen_t accept_addr_len = sizeof accept_addr;

        int sock = AcceptSocket (GetNativeSocket(),
                                 (struct sockaddr *)&accept_addr,
                                 &accept_addr_len,
                                 child_processes_inherit,
                                 error);

        if (error.Fail())
            break;

        bool is_same_addr = true;
#if !(defined(__linux__) || (defined(_WIN32)))
        is_same_addr = (accept_addr_len == listen_addr.sockaddr_in().sin_len);
#endif
        if (is_same_addr)
            is_same_addr = (accept_addr.sin_addr.s_addr == listen_addr.sockaddr_in().sin_addr.s_addr);

        if (is_same_addr || (listen_addr.sockaddr_in().sin_addr.s_addr == INADDR_ANY))
        {
            accept_connection = true;
            accepted_socket.reset(new TCPSocket(sock, true));
        }
        else
        {
            const uint8_t *accept_ip = (const uint8_t *)&accept_addr.sin_addr.s_addr;
            const uint8_t *listen_ip = (const uint8_t *)&listen_addr.sockaddr_in().sin_addr.s_addr;
            ::fprintf (stderr, "error: rejecting incoming connection from %u.%u.%u.%u (expecting %u.%u.%u.%u)\n",
                        accept_ip[0], accept_ip[1], accept_ip[2], accept_ip[3],
                        listen_ip[0], listen_ip[1], listen_ip[2], listen_ip[3]);
            accepted_socket.reset();
        }
    }

    if (!accepted_socket)
        return error;

    // Keep our TCP packets coming without any delays.
    accepted_socket->SetOptionNoDelay();
    error.Clear();
    conn_socket = accepted_socket.release();
    return error;
}

int
TCPSocket::SetOptionNoDelay()
{
    return SetOption (IPPROTO_TCP, TCP_NODELAY, 1);
}

int
TCPSocket::SetOptionReuseAddress()
{
    return SetOption(SOL_SOCKET, SO_REUSEADDR, 1);
}