Socket.cpp revision 276479
1//===-- Socket.cpp ----------------------------------------------*- C++ -*-===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
10#include "lldb/Host/Socket.h"
11
12#include "lldb/Core/Log.h"
13#include "lldb/Core/RegularExpression.h"
14#include "lldb/Host/Config.h"
15#include "lldb/Host/FileSystem.h"
16#include "lldb/Host/Host.h"
17#include "lldb/Host/SocketAddress.h"
18#include "lldb/Host/TimeValue.h"
19#include "lldb/Interpreter/Args.h"
20
21#ifndef LLDB_DISABLE_POSIX
22#include <arpa/inet.h>
23#include <netdb.h>
24#include <netinet/in.h>
25#include <netinet/tcp.h>
26#include <sys/socket.h>
27#include <sys/un.h>
28#endif
29
30using namespace lldb;
31using namespace lldb_private;
32
33#if defined(_WIN32)
34typedef const char * set_socket_option_arg_type;
35typedef char * get_socket_option_arg_type;
36const NativeSocket Socket::kInvalidSocketValue = INVALID_SOCKET;
37#else // #if defined(_WIN32)
38typedef const void * set_socket_option_arg_type;
39typedef void * get_socket_option_arg_type;
40const NativeSocket Socket::kInvalidSocketValue = -1;
41#endif // #if defined(_WIN32)
42
43Socket::Socket(NativeSocket socket, SocketProtocol protocol, bool should_close)
44    : IOObject(eFDTypeSocket, should_close)
45    , m_protocol(protocol)
46    , m_socket(socket)
47{
48
49}
50
51Socket::~Socket()
52{
53    Close();
54}
55
56Error Socket::TcpConnect(llvm::StringRef host_and_port, Socket *&socket)
57{
58    // Store the result in a unique_ptr in case we error out, the memory will get correctly freed.
59    std::unique_ptr<Socket> final_socket;
60    NativeSocket sock = kInvalidSocketValue;
61    Error error;
62
63    Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_HOST));
64    if (log)
65        log->Printf ("Socket::TcpConnect (host/port = %s)", host_and_port.data());
66
67    std::string host_str;
68    std::string port_str;
69    int32_t port = INT32_MIN;
70    if (!DecodeHostAndPort (host_and_port, host_str, port_str, port, &error))
71        return error;
72
73    // Create the socket
74    sock = ::socket (AF_INET, SOCK_STREAM, IPPROTO_TCP);
75    if (sock == kInvalidSocketValue)
76    {
77        // TODO: On Windows, use WSAGetLastError().
78        error.SetErrorToErrno();
79        return error;
80    }
81
82    // Since they both refer to the same socket descriptor, arbitrarily choose the send socket to
83    // be the owner.
84    final_socket.reset(new Socket(sock, ProtocolTcp, true));
85
86    // Enable local address reuse
87    final_socket->SetOption(SOL_SOCKET, SO_REUSEADDR, 1);
88
89    struct sockaddr_in sa;
90    ::memset (&sa, 0, sizeof (sa));
91    sa.sin_family = AF_INET;
92    sa.sin_port = htons (port);
93
94    int inet_pton_result = ::inet_pton (AF_INET, host_str.c_str(), &sa.sin_addr);
95
96    if (inet_pton_result <= 0)
97    {
98        struct hostent *host_entry = gethostbyname (host_str.c_str());
99        if (host_entry)
100            host_str = ::inet_ntoa (*(struct in_addr *)*host_entry->h_addr_list);
101        inet_pton_result = ::inet_pton (AF_INET, host_str.c_str(), &sa.sin_addr);
102        if (inet_pton_result <= 0)
103        {
104            // TODO: On Windows, use WSAGetLastError()
105            if (inet_pton_result == -1)
106                error.SetErrorToErrno();
107            else
108                error.SetErrorStringWithFormat("invalid host string: '%s'", host_str.c_str());
109
110            return error;
111        }
112    }
113
114    if (-1 == ::connect (sock, (const struct sockaddr *)&sa, sizeof(sa)))
115    {
116        // TODO: On Windows, use WSAGetLastError()
117        error.SetErrorToErrno();
118        return error;
119    }
120
121    // Keep our TCP packets coming without any delays.
122    final_socket->SetOption(IPPROTO_TCP, TCP_NODELAY, 1);
123    error.Clear();
124    socket = final_socket.release();
125    return error;
126}
127
128Error Socket::TcpListen(llvm::StringRef host_and_port, Socket *&socket, Predicate<uint16_t>* predicate)
129{
130    std::unique_ptr<Socket> listen_socket;
131    NativeSocket listen_sock = kInvalidSocketValue;
132    Error error;
133
134    const sa_family_t family = AF_INET;
135    const int socktype = SOCK_STREAM;
136    const int protocol = IPPROTO_TCP;
137    listen_sock = ::socket (family, socktype, protocol);
138    if (listen_sock == kInvalidSocketValue)
139    {
140        error.SetErrorToErrno();
141        return error;
142    }
143
144    listen_socket.reset(new Socket(listen_sock, ProtocolTcp, true));
145
146    // enable local address reuse
147    listen_socket->SetOption(SOL_SOCKET, SO_REUSEADDR, 1);
148
149    Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_CONNECTION));
150    if (log)
151        log->Printf ("ConnectionFileDescriptor::SocketListen (%s)", host_and_port.data());
152
153    std::string host_str;
154    std::string port_str;
155    int32_t port = INT32_MIN;
156    if (!DecodeHostAndPort (host_and_port, host_str, port_str, port, &error))
157        return error;
158
159    SocketAddress anyaddr;
160    if (anyaddr.SetToAnyAddress (family, port))
161    {
162        int err = ::bind (listen_sock, anyaddr, anyaddr.GetLength());
163        if (err == -1)
164        {
165            // TODO: On Windows, use WSAGetLastError()
166            error.SetErrorToErrno();
167            return error;
168        }
169
170        err = ::listen (listen_sock, 1);
171        if (err == -1)
172        {
173            // TODO: On Windows, use WSAGetLastError()
174            error.SetErrorToErrno();
175            return error;
176        }
177
178        // We were asked to listen on port zero which means we
179        // must now read the actual port that was given to us
180        // as port zero is a special code for "find an open port
181        // for me".
182        if (port == 0)
183            port = listen_socket->GetPortNumber();
184
185        // Set the port predicate since when doing a listen://<host>:<port>
186        // it often needs to accept the incoming connection which is a blocking
187        // system call. Allowing access to the bound port using a predicate allows
188        // us to wait for the port predicate to be set to a non-zero value from
189        // another thread in an efficient manor.
190        if (predicate)
191            predicate->SetValue(port, eBroadcastAlways);
192
193        socket = listen_socket.release();
194    }
195
196    return error;
197}
198
199Error Socket::BlockingAccept(llvm::StringRef host_and_port, Socket *&socket)
200{
201    Error error;
202    std::string host_str;
203    std::string port_str;
204    int32_t port;
205    if (!DecodeHostAndPort(host_and_port, host_str, port_str, port, &error))
206        return error;
207
208    const sa_family_t family = AF_INET;
209    const int socktype = SOCK_STREAM;
210    const int protocol = IPPROTO_TCP;
211    SocketAddress listen_addr;
212    if (host_str.empty())
213        listen_addr.SetToLocalhost(family, port);
214    else if (host_str.compare("*") == 0)
215        listen_addr.SetToAnyAddress(family, port);
216    else
217    {
218        if (!listen_addr.getaddrinfo(host_str.c_str(), port_str.c_str(), family, socktype, protocol))
219        {
220            error.SetErrorStringWithFormat("unable to resolve hostname '%s'", host_str.c_str());
221            return error;
222        }
223    }
224
225    bool accept_connection = false;
226    std::unique_ptr<Socket> accepted_socket;
227
228    // Loop until we are happy with our connection
229    while (!accept_connection)
230    {
231        struct sockaddr_in accept_addr;
232        ::memset (&accept_addr, 0, sizeof accept_addr);
233#if !(defined (__linux__) || defined(_WIN32))
234        accept_addr.sin_len = sizeof accept_addr;
235#endif
236        socklen_t accept_addr_len = sizeof accept_addr;
237
238        int sock = ::accept (this->GetNativeSocket(), (struct sockaddr *)&accept_addr, &accept_addr_len);
239
240        if (sock == kInvalidSocketValue)
241        {
242            // TODO: On Windows, use WSAGetLastError()
243            error.SetErrorToErrno();
244            break;
245        }
246
247        bool is_same_addr = true;
248#if !(defined(__linux__) || (defined(_WIN32)))
249        is_same_addr = (accept_addr_len == listen_addr.sockaddr_in().sin_len);
250#endif
251        if (is_same_addr)
252            is_same_addr = (accept_addr.sin_addr.s_addr == listen_addr.sockaddr_in().sin_addr.s_addr);
253
254        if (is_same_addr || (listen_addr.sockaddr_in().sin_addr.s_addr == INADDR_ANY))
255        {
256            accept_connection = true;
257            // Since both sockets have the same descriptor, arbitrarily choose the send
258            // socket to be the owner.
259            accepted_socket.reset(new Socket(sock, ProtocolTcp, true));
260        }
261        else
262        {
263            const uint8_t *accept_ip = (const uint8_t *)&accept_addr.sin_addr.s_addr;
264            const uint8_t *listen_ip = (const uint8_t *)&listen_addr.sockaddr_in().sin_addr.s_addr;
265            ::fprintf (stderr, "error: rejecting incoming connection from %u.%u.%u.%u (expecting %u.%u.%u.%u)\n",
266                        accept_ip[0], accept_ip[1], accept_ip[2], accept_ip[3],
267                        listen_ip[0], listen_ip[1], listen_ip[2], listen_ip[3]);
268            accepted_socket.reset();
269        }
270    }
271
272    if (!accepted_socket)
273        return error;
274
275    // Keep our TCP packets coming without any delays.
276    accepted_socket->SetOption (IPPROTO_TCP, TCP_NODELAY, 1);
277    error.Clear();
278    socket = accepted_socket.release();
279    return error;
280
281}
282
283Error Socket::UdpConnect(llvm::StringRef host_and_port, Socket *&send_socket, Socket *&recv_socket)
284{
285    std::unique_ptr<Socket> final_send_socket;
286    std::unique_ptr<Socket> final_recv_socket;
287    NativeSocket final_send_fd = kInvalidSocketValue;
288    NativeSocket final_recv_fd = kInvalidSocketValue;
289
290    Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_CONNECTION));
291    if (log)
292        log->Printf ("Socket::UdpConnect (host/port = %s)", host_and_port.data());
293
294    Error error;
295    std::string host_str;
296    std::string port_str;
297    int32_t port = INT32_MIN;
298    if (!DecodeHostAndPort (host_and_port, host_str, port_str, port, &error))
299        return error;
300
301    // Setup the receiving end of the UDP connection on this localhost
302    // on port zero. After we bind to port zero we can read the port.
303    final_recv_fd = ::socket (AF_INET, SOCK_DGRAM, 0);
304    if (final_recv_fd == kInvalidSocketValue)
305    {
306        // Socket creation failed...
307        // TODO: On Windows, use WSAGetLastError().
308        error.SetErrorToErrno();
309    }
310    else
311    {
312        final_recv_socket.reset(new Socket(final_recv_fd, ProtocolUdp, true));
313
314        // Socket was created, now lets bind to the requested port
315        SocketAddress addr;
316        addr.SetToAnyAddress (AF_INET, 0);
317
318        if (::bind (final_recv_fd, addr, addr.GetLength()) == -1)
319        {
320            // Bind failed...
321            // TODO: On Windows use WSAGetLastError()
322            error.SetErrorToErrno();
323        }
324    }
325
326    assert(error.Fail() == !(final_recv_socket && final_recv_socket->IsValid()));
327    if (error.Fail())
328        return error;
329
330    // At this point we have setup the receive port, now we need to
331    // setup the UDP send socket
332
333    struct addrinfo hints;
334    struct addrinfo *service_info_list = NULL;
335
336    ::memset (&hints, 0, sizeof(hints));
337    hints.ai_family = AF_INET;
338    hints.ai_socktype = SOCK_DGRAM;
339    int err = ::getaddrinfo (host_str.c_str(), port_str.c_str(), &hints, &service_info_list);
340    if (err != 0)
341    {
342        error.SetErrorStringWithFormat("getaddrinfo(%s, %s, &hints, &info) returned error %i (%s)",
343                                       host_str.c_str(),
344                                       port_str.c_str(),
345                                       err,
346                                       gai_strerror(err));
347        return error;
348    }
349
350    for (struct addrinfo *service_info_ptr = service_info_list;
351         service_info_ptr != NULL;
352         service_info_ptr = service_info_ptr->ai_next)
353    {
354        final_send_fd = ::socket (service_info_ptr->ai_family,
355                                  service_info_ptr->ai_socktype,
356                                  service_info_ptr->ai_protocol);
357
358        if (final_send_fd != kInvalidSocketValue)
359        {
360            final_send_socket.reset(new Socket(final_send_fd, ProtocolUdp, true));
361            final_send_socket->m_udp_send_sockaddr = service_info_ptr;
362            break;
363        }
364        else
365            continue;
366    }
367
368    :: freeaddrinfo (service_info_list);
369
370    if (final_send_fd == kInvalidSocketValue)
371    {
372        // TODO: On Windows, use WSAGetLastError().
373        error.SetErrorToErrno();
374        return error;
375    }
376
377    send_socket = final_send_socket.release();
378    recv_socket = final_recv_socket.release();
379    error.Clear();
380    return error;
381}
382
383Error Socket::UnixDomainConnect(llvm::StringRef name, Socket *&socket)
384{
385    Error error;
386#ifndef LLDB_DISABLE_POSIX
387    std::unique_ptr<Socket> final_socket;
388
389    // Open the socket that was passed in as an option
390    struct sockaddr_un saddr_un;
391    int fd = ::socket (AF_UNIX, SOCK_STREAM, 0);
392    if (fd == kInvalidSocketValue)
393    {
394        error.SetErrorToErrno();
395        return error;
396    }
397
398    final_socket.reset(new Socket(fd, ProtocolUnixDomain, true));
399
400    saddr_un.sun_family = AF_UNIX;
401    ::strncpy(saddr_un.sun_path, name.data(), sizeof(saddr_un.sun_path) - 1);
402    saddr_un.sun_path[sizeof(saddr_un.sun_path) - 1] = '\0';
403#if defined(__APPLE__) || defined(__FreeBSD__) || defined(__NetBSD__)
404    saddr_un.sun_len = SUN_LEN (&saddr_un);
405#endif
406
407    if (::connect (fd, (struct sockaddr *)&saddr_un, SUN_LEN (&saddr_un)) < 0)
408    {
409        error.SetErrorToErrno();
410        return error;
411    }
412
413    socket = final_socket.release();
414#else
415    error.SetErrorString("Unix domain sockets are not supported on this platform.");
416#endif
417    return error;
418}
419
420Error Socket::UnixDomainAccept(llvm::StringRef name, Socket *&socket)
421{
422    Error error;
423#ifndef LLDB_DISABLE_POSIX
424    struct sockaddr_un saddr_un;
425    std::unique_ptr<Socket> listen_socket;
426    std::unique_ptr<Socket> final_socket;
427    NativeSocket listen_fd = kInvalidSocketValue;
428    NativeSocket socket_fd = kInvalidSocketValue;
429
430    listen_fd = ::socket (AF_UNIX, SOCK_STREAM, 0);
431    if (listen_fd == kInvalidSocketValue)
432    {
433        error.SetErrorToErrno();
434        return error;
435    }
436
437    listen_socket.reset(new Socket(listen_fd, ProtocolUnixDomain, true));
438
439    saddr_un.sun_family = AF_UNIX;
440    ::strncpy(saddr_un.sun_path, name.data(), sizeof(saddr_un.sun_path) - 1);
441    saddr_un.sun_path[sizeof(saddr_un.sun_path) - 1] = '\0';
442#if defined(__APPLE__) || defined(__FreeBSD__) || defined(__NetBSD__)
443    saddr_un.sun_len = SUN_LEN (&saddr_un);
444#endif
445
446    FileSystem::Unlink(name.data());
447    bool success = false;
448    if (::bind (listen_fd, (struct sockaddr *)&saddr_un, SUN_LEN (&saddr_un)) == 0)
449    {
450        if (::listen (listen_fd, 5) == 0)
451        {
452            socket_fd = ::accept (listen_fd, NULL, 0);
453            if (socket_fd > 0)
454            {
455                final_socket.reset(new Socket(socket_fd, ProtocolUnixDomain, true));
456                success = true;
457            }
458        }
459    }
460
461    if (!success)
462    {
463        error.SetErrorToErrno();
464        return error;
465    }
466    // We are done with the listen port
467    listen_socket.reset();
468
469    socket = final_socket.release();
470#else
471    error.SetErrorString("Unix domain sockets are not supported on this platform.");
472#endif
473    return error;
474}
475
476bool
477Socket::DecodeHostAndPort(llvm::StringRef host_and_port,
478                          std::string &host_str,
479                          std::string &port_str,
480                          int32_t& port,
481                          Error *error_ptr)
482{
483    static RegularExpression g_regex ("([^:]+):([0-9]+)");
484    RegularExpression::Match regex_match(2);
485    if (g_regex.Execute (host_and_port.data(), &regex_match))
486    {
487        if (regex_match.GetMatchAtIndex (host_and_port.data(), 1, host_str) &&
488            regex_match.GetMatchAtIndex (host_and_port.data(), 2, port_str))
489        {
490            port = Args::StringToSInt32 (port_str.c_str(), INT32_MIN);
491            if (port != INT32_MIN)
492            {
493                if (error_ptr)
494                    error_ptr->Clear();
495                return true;
496            }
497        }
498    }
499
500    // If this was unsuccessful, then check if it's simply a signed 32-bit integer, representing
501    // a port with an empty host.
502    host_str.clear();
503    port_str.clear();
504    port = Args::StringToSInt32(host_and_port.data(), INT32_MIN);
505    if (port != INT32_MIN)
506    {
507        port_str = host_and_port;
508        return true;
509    }
510
511    if (error_ptr)
512        error_ptr->SetErrorStringWithFormat("invalid host:port specification: '%s'", host_and_port.data());
513    return false;
514}
515
516IOObject::WaitableHandle Socket::GetWaitableHandle()
517{
518    // TODO: On Windows, use WSAEventSelect
519    return m_socket;
520}
521
522Error Socket::Read (void *buf, size_t &num_bytes)
523{
524    Error error;
525    int bytes_received = 0;
526    do
527    {
528        bytes_received = ::recv (m_socket, static_cast<char *>(buf), num_bytes, 0);
529        // TODO: Use WSAGetLastError on windows.
530    } while (bytes_received < 0 && errno == EINTR);
531
532    if (bytes_received < 0)
533    {
534        error.SetErrorToErrno();
535        num_bytes = 0;
536    }
537    else
538        num_bytes = bytes_received;
539
540    Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_HOST | LIBLLDB_LOG_COMMUNICATION));
541    if (log)
542    {
543        log->Printf ("%p Socket::Read() (socket = %" PRIu64 ", src = %p, src_len = %" PRIu64 ", flags = 0) => %" PRIi64 " (error = %s)",
544                     static_cast<void*>(this),
545                     static_cast<uint64_t>(m_socket),
546                     buf,
547                     static_cast<uint64_t>(num_bytes),
548                     static_cast<int64_t>(bytes_received),
549                     error.AsCString());
550    }
551
552    return error;
553}
554
555Error Socket::Write (const void *buf, size_t &num_bytes)
556{
557    Error error;
558    int bytes_sent = 0;
559    do
560    {
561        if (m_protocol == ProtocolUdp)
562        {
563            bytes_sent = ::sendto (m_socket,
564                                    static_cast<const char*>(buf),
565                                    num_bytes,
566                                    0,
567                                    m_udp_send_sockaddr,
568                                    m_udp_send_sockaddr.GetLength());
569        }
570        else
571            bytes_sent = ::send (m_socket, static_cast<const char *>(buf), num_bytes, 0);
572        // TODO: Use WSAGetLastError on windows.
573    } while (bytes_sent < 0 && errno == EINTR);
574
575    if (bytes_sent < 0)
576    {
577        // TODO: On Windows, use WSAGEtLastError.
578        error.SetErrorToErrno();
579        num_bytes = 0;
580    }
581    else
582        num_bytes = bytes_sent;
583
584    Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_HOST));
585    if (log)
586    {
587        log->Printf ("%p Socket::Write() (socket = %" PRIu64 ", src = %p, src_len = %" PRIu64 ", flags = 0) => %" PRIi64 " (error = %s)",
588                        static_cast<void*>(this),
589                        static_cast<uint64_t>(m_socket),
590                        buf,
591                        static_cast<uint64_t>(num_bytes),
592                        static_cast<int64_t>(bytes_sent),
593                        error.AsCString());
594    }
595
596    return error;
597}
598
599Error Socket::PreDisconnect()
600{
601    Error error;
602    return error;
603}
604
605Error Socket::Close()
606{
607    Error error;
608    if (!IsValid() || !m_should_close_fd)
609        return error;
610
611    Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_CONNECTION));
612    if (log)
613        log->Printf ("%p Socket::Close (fd = %i)", static_cast<void*>(this), m_socket);
614
615#if defined(_WIN32)
616    bool success = !!closesocket(m_socket);
617#else
618    bool success = !!::close (m_socket);
619#endif
620    // A reference to a FD was passed in, set it to an invalid value
621    m_socket = kInvalidSocketValue;
622    if (!success)
623    {
624        // TODO: On Windows, use WSAGetLastError().
625        error.SetErrorToErrno();
626    }
627
628    return error;
629}
630
631
632int Socket::GetOption(int level, int option_name, int &option_value)
633{
634    get_socket_option_arg_type option_value_p = reinterpret_cast<get_socket_option_arg_type>(&option_value);
635    socklen_t option_value_size = sizeof(int);
636	return ::getsockopt(m_socket, level, option_name, option_value_p, &option_value_size);
637}
638
639int Socket::SetOption(int level, int option_name, int option_value)
640{
641    set_socket_option_arg_type option_value_p = reinterpret_cast<get_socket_option_arg_type>(&option_value);
642	return ::setsockopt(m_socket, level, option_name, option_value_p, sizeof(option_value));
643}
644
645uint16_t Socket::GetPortNumber(const NativeSocket& socket)
646{
647    // We bound to port zero, so we need to figure out which port we actually bound to
648    if (socket >= 0)
649    {
650        SocketAddress sock_addr;
651        socklen_t sock_addr_len = sock_addr.GetMaxLength ();
652        if (::getsockname (socket, sock_addr, &sock_addr_len) == 0)
653            return sock_addr.GetPort ();
654    }
655    return 0;
656}
657
658// Return the port number that is being used by the socket.
659uint16_t Socket::GetPortNumber() const
660{
661    return GetPortNumber(m_socket);
662}
663