Socket.cpp revision 288943
1139804Simp//===-- Socket.cpp ----------------------------------------------*- C++ -*-===//
21541Srgrimes//
31541Srgrimes//                     The LLVM Compiler Infrastructure
41541Srgrimes//
51541Srgrimes// This file is distributed under the University of Illinois Open Source
61541Srgrimes// License. See LICENSE.TXT for details.
71541Srgrimes//
81541Srgrimes//===----------------------------------------------------------------------===//
91541Srgrimes
101541Srgrimes#include "lldb/Host/Socket.h"
111541Srgrimes
121541Srgrimes#include "lldb/Core/Log.h"
131541Srgrimes#include "lldb/Core/RegularExpression.h"
141541Srgrimes#include "lldb/Host/Config.h"
151541Srgrimes#include "lldb/Host/FileSystem.h"
161541Srgrimes#include "lldb/Host/Host.h"
171541Srgrimes#include "lldb/Host/SocketAddress.h"
181541Srgrimes#include "lldb/Host/StringConvert.h"
191541Srgrimes#include "lldb/Host/TimeValue.h"
201541Srgrimes
211541Srgrimes#ifdef __ANDROID_NDK__
221541Srgrimes#include <linux/tcp.h>
231541Srgrimes#include <bits/error_constants.h>
241541Srgrimes#include <asm-generic/errno-base.h>
251541Srgrimes#include <errno.h>
261541Srgrimes#include <arpa/inet.h>
271541Srgrimes#endif
281541Srgrimes
291541Srgrimes#ifndef LLDB_DISABLE_POSIX
301541Srgrimes#include <arpa/inet.h>
311541Srgrimes#include <netdb.h>
321541Srgrimes#include <netinet/in.h>
331541Srgrimes#include <netinet/tcp.h>
341541Srgrimes#include <sys/socket.h>
351541Srgrimes#include <sys/un.h>
361541Srgrimes#endif
37116182Sobrien
38116182Sobrienusing namespace lldb;
39116182Sobrienusing namespace lldb_private;
40190759Srwatson
4113203Swollman#if defined(_WIN32)
4213203Swollmantypedef const char * set_socket_option_arg_type;
431541Srgrimestypedef char * get_socket_option_arg_type;
442112Swollmanconst NativeSocket Socket::kInvalidSocketValue = INVALID_SOCKET;
4569664Speter#else // #if defined(_WIN32)
46177785Skibtypedef const void * set_socket_option_arg_type;
47192895Sjamietypedef void * get_socket_option_arg_type;
4876166Smarkmconst NativeSocket Socket::kInvalidSocketValue = -1;
4989316Salfred#endif // #if defined(_WIN32)
501541Srgrimes
511541Srgrimes#ifdef __ANDROID__
521541Srgrimes// Android does not have SUN_LEN
531541Srgrimes#ifndef SUN_LEN
541541Srgrimes#define SUN_LEN(ptr) ((size_t) (((struct sockaddr_un *) 0)->sun_path) + strlen((ptr)->sun_path))
55190759Srwatson#endif
56141471Sjhb#endif // #ifdef __ANDROID__
57144613Sjeff
581541Srgrimesnamespace {
591541Srgrimes
601541SrgrimesNativeSocket CreateSocket(const int domain, const int type, const int protocol, bool child_processes_inherit)
611541Srgrimes{
62155334Srwatson    auto socketType = type;
63163606Srwatson#ifdef SOCK_CLOEXEC
64155334Srwatson    if (!child_processes_inherit) {
6592751Sjeff        socketType |= SOCK_CLOEXEC;
6632011Sbde    }
67155168Sjeff#endif
68138345Sphk    return ::socket (domain, socketType, protocol);
69138345Sphk}
70190759Srwatson
71190759SrwatsonNativeSocket Accept(NativeSocket sockfd, struct sockaddr *addr, socklen_t *addrlen, bool child_processes_inherit)
72190759Srwatson{
73190759Srwatson#ifdef SOCK_CLOEXEC
74190759Srwatson    int flags = 0;
751541Srgrimes    if (!child_processes_inherit) {
7669664Speter        flags |= SOCK_CLOEXEC;
7769664Speter    }
7892751Sjeff    return ::accept4 (sockfd, addr, addrlen, flags);
79166167Skib#else
80166167Skib    return ::accept (sockfd, addr, addrlen);
81166167Skib#endif
82166167Skib}
8369664Speter
8469664Spetervoid SetLastError(Error &error)
8569664Speter{
8669664Speter#if defined(_WIN32)
87168138Srwatson    error.SetError(::WSAGetLastError(), lldb::eErrorTypeWin32);
88168138Srwatson#else
8992654Sjeff    error.SetErrorToErrno();
9092654Sjeff#endif
91168138Srwatson}
92168138Srwatson
93168138Srwatsonbool IsInterrupted()
94176519Sattilio{
9569664Speter#if defined(_WIN32)
96177253Srwatson    return ::WSAGetLastError() == WSAEINTR;
9769664Speter#else
98183520Sjhb    return errno == EINTR;
99144613Sjeff#endif
100144613Sjeff}
101183519Sjhb
102144613Sjeff}
10369664Speter
104161010SrwatsonSocket::Socket(NativeSocket socket, SocketProtocol protocol, bool should_close)
1051541Srgrimes    : IOObject(eFDTypeSocket, should_close)
1061541Srgrimes    , m_protocol(protocol)
1071541Srgrimes    , m_socket(socket)
1081541Srgrimes{
1091541Srgrimes
1101541Srgrimes}
1111541Srgrimes
1121541SrgrimesSocket::~Socket()
1131541Srgrimes{
1141541Srgrimes    Close();
1151541Srgrimes}
1161541Srgrimes
1171541SrgrimesError Socket::TcpConnect(llvm::StringRef host_and_port, bool child_processes_inherit, Socket *&socket)
1181541Srgrimes{
1191541Srgrimes    // Store the result in a unique_ptr in case we error out, the memory will get correctly freed.
1201541Srgrimes    std::unique_ptr<Socket> final_socket;
1211541Srgrimes    NativeSocket sock = kInvalidSocketValue;
1221541Srgrimes    Error error;
1231541Srgrimes
124161011Srwatson    Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_HOST));
1251541Srgrimes    if (log)
126161011Srwatson        log->Printf ("Socket::TcpConnect (host/port = %s)", host_and_port.data());
127161011Srwatson
128161011Srwatson    std::string host_str;
1291541Srgrimes    std::string port_str;
1301541Srgrimes    int32_t port = INT32_MIN;
1311541Srgrimes    if (!DecodeHostAndPort (host_and_port, host_str, port_str, port, &error))
1321541Srgrimes        return error;
13383366Sjulian
13483366Sjulian    // Create the socket
135140714Sjeff    sock = CreateSocket (AF_INET, SOCK_STREAM, IPPROTO_TCP, child_processes_inherit);
1361541Srgrimes    if (sock == kInvalidSocketValue)
137150164Scsjp    {
138150164Scsjp        SetLastError (error);
13991419Sjhb        return error;
14083366Sjulian    }
14142408Seivind
14242453Seivind    // Since they both refer to the same socket descriptor, arbitrarily choose the send socket to
14342408Seivind    // be the owner.
14442453Seivind    final_socket.reset(new Socket(sock, ProtocolTcp, true));
145144613Sjeff
146144613Sjeff    // Enable local address reuse
14783366Sjulian    final_socket->SetOption(SOL_SOCKET, SO_REUSEADDR, 1);
1481541Srgrimes
149193028Sdes    struct sockaddr_in sa;
150193028Sdes    ::memset (&sa, 0, sizeof (sa));
151193028Sdes    sa.sin_family = AF_INET;
1521541Srgrimes    sa.sin_port = htons (port);
1531541Srgrimes
1541541Srgrimes    int inet_pton_result = ::inet_pton (AF_INET, host_str.c_str(), &sa.sin_addr);
1551541Srgrimes
1561541Srgrimes    if (inet_pton_result <= 0)
157111119Simp    {
1581541Srgrimes        struct hostent *host_entry = gethostbyname (host_str.c_str());
1591541Srgrimes        if (host_entry)
16036735Sdfr            host_str = ::inet_ntoa (*(struct in_addr *)*host_entry->h_addr_list);
1611541Srgrimes        inet_pton_result = ::inet_pton (AF_INET, host_str.c_str(), &sa.sin_addr);
1621541Srgrimes        if (inet_pton_result <= 0)
16336735Sdfr        {
16420069Sbde            if (inet_pton_result == -1)
165203410Srwatson                SetLastError(error);
166203410Srwatson            else
167203410Srwatson                error.SetErrorStringWithFormat("invalid host string: '%s'", host_str.c_str());
168203410Srwatson
169203410Srwatson            return error;
170203410Srwatson        }
171203410Srwatson    }
172203410Srwatson
173203410Srwatson    if (-1 == ::connect (sock, (const struct sockaddr *)&sa, sizeof(sa)))
174203410Srwatson    {
175155334Srwatson        SetLastError (error);
17620069Sbde        return error;
17720069Sbde    }
17820069Sbde
17920069Sbde    // Keep our TCP packets coming without any delays.
18020069Sbde    final_socket->SetOption(IPPROTO_TCP, TCP_NODELAY, 1);
18120069Sbde    error.Clear();
1821541Srgrimes    socket = final_socket.release();
18392751Sjeff    return error;
184100613Srwatson}
185100613Srwatson
186100613SrwatsonError Socket::TcpListen(
187100613Srwatson    llvm::StringRef host_and_port,
1881541Srgrimes    bool child_processes_inherit,
1891541Srgrimes    Socket *&socket,
1901541Srgrimes    Predicate<uint16_t>* predicate,
1911541Srgrimes    int backlog)
1921541Srgrimes{
19397994Sjhb    std::unique_ptr<Socket> listen_socket;
19497994Sjhb    NativeSocket listen_sock = kInvalidSocketValue;
19597994Sjhb    Error error;
19697994Sjhb
19797994Sjhb    const sa_family_t family = AF_INET;
1981541Srgrimes    const int socktype = SOCK_STREAM;
1991541Srgrimes    const int protocol = IPPROTO_TCP;
2001541Srgrimes    listen_sock = ::CreateSocket (family, socktype, protocol, child_processes_inherit);
2011541Srgrimes    if (listen_sock == kInvalidSocketValue)
202168355Srwatson    {
20333360Sdyson        SetLastError (error);
20451649Sphk        return error;
20533360Sdyson    }
206185029Spjd
207185029Spjd    listen_socket.reset(new Socket(listen_sock, ProtocolTcp, true));
208185029Spjd
209185029Spjd    // enable local address reuse
210185029Spjd    listen_socket->SetOption(SOL_SOCKET, SO_REUSEADDR, 1);
211195925Srwatson
212195925Srwatson    Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_CONNECTION));
213195925Srwatson    if (log)
214195925Srwatson        log->Printf ("Socket::TcpListen (%s)", host_and_port.data());
215195925Srwatson
216185029Spjd    std::string host_str;
217195925Srwatson    std::string port_str;
218185029Spjd    int32_t port = INT32_MIN;
219185029Spjd    if (!DecodeHostAndPort (host_and_port, host_str, port_str, port, &error))
220185029Spjd        return error;
221185029Spjd
222185029Spjd    SocketAddress anyaddr;
223185029Spjd    if (anyaddr.SetToAnyAddress (family, port))
224185029Spjd    {
225185029Spjd        int err = ::bind (listen_sock, anyaddr, anyaddr.GetLength());
226177785Skib        if (err == -1)
227177785Skib        {
228177785Skib            SetLastError (error);
229177785Skib            return error;
230177785Skib        }
231177785Skib
232177785Skib        err = ::listen (listen_sock, backlog);
233177785Skib        if (err == -1)
234177785Skib        {
235185029Spjd            SetLastError (error);
236185029Spjd            return error;
237177785Skib        }
238177785Skib
239177785Skib        // We were asked to listen on port zero which means we
240185029Spjd        // must now read the actual port that was given to us
241185029Spjd        // as port zero is a special code for "find an open port
242185029Spjd        // for me".
243185029Spjd        if (port == 0)
244185029Spjd            port = listen_socket->GetLocalPortNumber();
245177785Skib
246190759Srwatson        // Set the port predicate since when doing a listen://<host>:<port>
247190759Srwatson        // it often needs to accept the incoming connection which is a blocking
248140714Sjeff        // system call. Allowing access to the bound port using a predicate allows
2491541Srgrimes        // us to wait for the port predicate to be set to a non-zero value from
2501541Srgrimes        // another thread in an efficient manor.
2511541Srgrimes        if (predicate)
2521541Srgrimes            predicate->SetValue (port, eBroadcastAlways);
2531541Srgrimes
2541541Srgrimes        socket = listen_socket.release();
2551541Srgrimes    }
2561541Srgrimes
257140714Sjeff    return error;
2581541Srgrimes}
2591541Srgrimes
2601541SrgrimesError Socket::BlockingAccept(llvm::StringRef host_and_port, bool child_processes_inherit, Socket *&socket)
2611541Srgrimes{
2621541Srgrimes    Error error;
263140714Sjeff    std::string host_str;
2641541Srgrimes    std::string port_str;
2651541Srgrimes    int32_t port;
266140714Sjeff    if (!DecodeHostAndPort(host_and_port, host_str, port_str, port, &error))
267140714Sjeff        return error;
2681541Srgrimes
2693148Sphk    const sa_family_t family = AF_INET;
2703148Sphk    const int socktype = SOCK_STREAM;
27192751Sjeff    const int protocol = IPPROTO_TCP;
272100613Srwatson    SocketAddress listen_addr;
273100613Srwatson    if (host_str.empty())
274100613Srwatson        listen_addr.SetToLocalhost(family, port);
275100613Srwatson    else if (host_str.compare("*") == 0)
276190759Srwatson        listen_addr.SetToAnyAddress(family, port);
277190759Srwatson    else
2781541Srgrimes    {
2791541Srgrimes        if (!listen_addr.getaddrinfo(host_str.c_str(), port_str.c_str(), family, socktype, protocol))
280140714Sjeff        {
281140714Sjeff            error.SetErrorStringWithFormat("unable to resolve hostname '%s'", host_str.c_str());
2821541Srgrimes            return error;
283193027Sdes        }
2841541Srgrimes    }
2851541Srgrimes
286100613Srwatson    bool accept_connection = false;
28792751Sjeff    std::unique_ptr<Socket> accepted_socket;
288100613Srwatson
289100613Srwatson    // Loop until we are happy with our connection
290100613Srwatson    while (!accept_connection)
291100613Srwatson    {
292100613Srwatson        struct sockaddr_in accept_addr;
2931541Srgrimes        ::memset (&accept_addr, 0, sizeof accept_addr);
29432286Sdyson#if !(defined (__linux__) || defined(_WIN32))
295140714Sjeff        accept_addr.sin_len = sizeof accept_addr;
296140714Sjeff#endif
297140714Sjeff        socklen_t accept_addr_len = sizeof accept_addr;
298140714Sjeff
299190759Srwatson        int sock = Accept (this->GetNativeSocket(),
300190759Srwatson                           (struct sockaddr *)&accept_addr,
3011541Srgrimes                           &accept_addr_len,
3021541Srgrimes                           child_processes_inherit);
3031541Srgrimes
3041541Srgrimes        if (sock == kInvalidSocketValue)
3051541Srgrimes        {
3061541Srgrimes            SetLastError (error);
307101127Srwatson            break;
308105479Srwatson        }
309172930Srwatson
310105479Srwatson        bool is_same_addr = true;
311105479Srwatson#if !(defined(__linux__) || (defined(_WIN32)))
312105479Srwatson        is_same_addr = (accept_addr_len == listen_addr.sockaddr_in().sin_len);
313105479Srwatson#endif
314101127Srwatson        if (is_same_addr)
3151541Srgrimes            is_same_addr = (accept_addr.sin_addr.s_addr == listen_addr.sockaddr_in().sin_addr.s_addr);
316111119Simp
3171541Srgrimes        if (is_same_addr || (listen_addr.sockaddr_in().sin_addr.s_addr == INADDR_ANY))
3181541Srgrimes        {
3191541Srgrimes            accept_connection = true;
3201541Srgrimes            // Since both sockets have the same descriptor, arbitrarily choose the send
3211541Srgrimes            // socket to be the owner.
3221541Srgrimes            accepted_socket.reset(new Socket(sock, ProtocolTcp, true));
3231541Srgrimes        }
3241541Srgrimes        else
3251541Srgrimes        {
32683366Sjulian            const uint8_t *accept_ip = (const uint8_t *)&accept_addr.sin_addr.s_addr;
3271541Srgrimes            const uint8_t *listen_ip = (const uint8_t *)&listen_addr.sockaddr_in().sin_addr.s_addr;
3283148Sphk            ::fprintf (stderr, "error: rejecting incoming connection from %u.%u.%u.%u (expecting %u.%u.%u.%u)\n",
3293148Sphk                        accept_ip[0], accept_ip[1], accept_ip[2], accept_ip[3],
3301541Srgrimes                        listen_ip[0], listen_ip[1], listen_ip[2], listen_ip[3]);
33192751Sjeff            accepted_socket.reset();
3321541Srgrimes        }
3331541Srgrimes    }
3341541Srgrimes
33578692Sdillon    if (!accepted_socket)
33678692Sdillon        return error;
33792751Sjeff
33878692Sdillon    // Keep our TCP packets coming without any delays.
33978692Sdillon    accepted_socket->SetOption (IPPROTO_TCP, TCP_NODELAY, 1);
34078692Sdillon    error.Clear();
3411541Srgrimes    socket = accepted_socket.release();
3421541Srgrimes    return error;
34392751Sjeff
3441541Srgrimes}
3451541Srgrimes
3461541SrgrimesError Socket::UdpConnect(llvm::StringRef host_and_port, bool child_processes_inherit, Socket *&send_socket, Socket *&recv_socket)
3471541Srgrimes{
3481541Srgrimes    std::unique_ptr<Socket> final_send_socket;
34992751Sjeff    std::unique_ptr<Socket> final_recv_socket;
3501541Srgrimes    NativeSocket final_send_fd = kInvalidSocketValue;
3511541Srgrimes    NativeSocket final_recv_fd = kInvalidSocketValue;
3521541Srgrimes
3531541Srgrimes    Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_CONNECTION));
3541541Srgrimes    if (log)
3551541Srgrimes        log->Printf ("Socket::UdpConnect (host/port = %s)", host_and_port.data());
3561541Srgrimes
35792751Sjeff    Error error;
358100613Srwatson    std::string host_str;
359100613Srwatson    std::string port_str;
360100613Srwatson    int32_t port = INT32_MIN;
361100613Srwatson    if (!DecodeHostAndPort (host_and_port, host_str, port_str, port, &error))
362144833Sjeff        return error;
363144833Sjeff
3641541Srgrimes    // Setup the receiving end of the UDP connection on this localhost
365140714Sjeff    // on port zero. After we bind to port zero we can read the port.
366190759Srwatson    final_recv_fd = ::CreateSocket (AF_INET, SOCK_DGRAM, 0, child_processes_inherit);
3671541Srgrimes    if (final_recv_fd == kInvalidSocketValue)
3681541Srgrimes    {
3691541Srgrimes        // Socket creation failed...
370162288Smohans        SetLastError (error);
371162288Smohans    }
372162288Smohans    else
373184597Sjhb    {
374162310Smohans        final_recv_socket.reset(new Socket(final_recv_fd, ProtocolUdp, true));
375162310Smohans
376162288Smohans        // Socket was created, now lets bind to the requested port
377162288Smohans        SocketAddress addr;
378162288Smohans        addr.SetToAnyAddress (AF_INET, 0);
379184597Sjhb
380162288Smohans        if (::bind (final_recv_fd, addr, addr.GetLength()) == -1)
381162288Smohans        {
382189696Sjhb            // Bind failed...
383189696Sjhb            SetLastError (error);
384189696Sjhb        }
385189696Sjhb    }
386189696Sjhb
387189696Sjhb    assert(error.Fail() == !(final_recv_socket && final_recv_socket->IsValid()));
388189696Sjhb    if (error.Fail())
389189696Sjhb        return error;
390189696Sjhb
391189696Sjhb    // At this point we have setup the receive port, now we need to
392189696Sjhb    // setup the UDP send socket
393189696Sjhb
394189696Sjhb    struct addrinfo hints;
395189696Sjhb    struct addrinfo *service_info_list = NULL;
396189696Sjhb
397189696Sjhb    ::memset (&hints, 0, sizeof(hints));
398189696Sjhb    hints.ai_family = AF_INET;
399189696Sjhb    hints.ai_socktype = SOCK_DGRAM;
400189696Sjhb    int err = ::getaddrinfo (host_str.c_str(), port_str.c_str(), &hints, &service_info_list);
401189696Sjhb    if (err != 0)
402189696Sjhb    {
403189696Sjhb        error.SetErrorStringWithFormat("getaddrinfo(%s, %s, &hints, &info) returned error %i (%s)",
404189696Sjhb                                       host_str.c_str(),
405189696Sjhb                                       port_str.c_str(),
406189696Sjhb                                       err,
407189696Sjhb                                       gai_strerror(err));
408189696Sjhb        return error;
409189696Sjhb    }
410189696Sjhb
411189696Sjhb    for (struct addrinfo *service_info_ptr = service_info_list;
412189696Sjhb         service_info_ptr != NULL;
413189696Sjhb         service_info_ptr = service_info_ptr->ai_next)
414189697Sjhb    {
415189696Sjhb        final_send_fd = ::CreateSocket (service_info_ptr->ai_family,
416189696Sjhb                                        service_info_ptr->ai_socktype,
4171541Srgrimes                                        service_info_ptr->ai_protocol,
4181541Srgrimes                                        child_processes_inherit);
4191541Srgrimes
4201541Srgrimes        if (final_send_fd != kInvalidSocketValue)
4211541Srgrimes        {
4221541Srgrimes            final_send_socket.reset(new Socket(final_send_fd, ProtocolUdp, true));
4231541Srgrimes            final_send_socket->m_udp_send_sockaddr = service_info_ptr;
4241541Srgrimes            break;
4251541Srgrimes        }
4261541Srgrimes        else
4271541Srgrimes            continue;
4281541Srgrimes    }
4291541Srgrimes
4301541Srgrimes    :: freeaddrinfo (service_info_list);
4311541Srgrimes
4321541Srgrimes    if (final_send_fd == kInvalidSocketValue)
4331541Srgrimes    {
4341541Srgrimes        SetLastError (error);
4351541Srgrimes        return error;
4361541Srgrimes    }
4371541Srgrimes
4388876Srgrimes    send_socket = final_send_socket.release();
4391541Srgrimes    recv_socket = final_recv_socket.release();
4401541Srgrimes    error.Clear();
4411541Srgrimes    return error;
4421541Srgrimes}
4431541Srgrimes
4441541SrgrimesError Socket::UnixDomainConnect(llvm::StringRef name, bool child_processes_inherit, Socket *&socket)
4451541Srgrimes{
4461541Srgrimes    Error error;
4471541Srgrimes#ifndef LLDB_DISABLE_POSIX
4481541Srgrimes    std::unique_ptr<Socket> final_socket;
4491541Srgrimes
4501541Srgrimes    // Open the socket that was passed in as an option
4511541Srgrimes    struct sockaddr_un saddr_un;
4521541Srgrimes    int fd = ::CreateSocket (AF_UNIX, SOCK_STREAM, 0, child_processes_inherit);
4531541Srgrimes    if (fd == kInvalidSocketValue)
4541541Srgrimes    {
4551541Srgrimes        SetLastError (error);
456161011Srwatson        return error;
4571541Srgrimes    }
458161011Srwatson
459161011Srwatson    final_socket.reset(new Socket(fd, ProtocolUnixDomain, true));
4601541Srgrimes
4611541Srgrimes    saddr_un.sun_family = AF_UNIX;
462192895Sjamie    ::strncpy(saddr_un.sun_path, name.data(), sizeof(saddr_un.sun_path) - 1);
4631541Srgrimes    saddr_un.sun_path[sizeof(saddr_un.sun_path) - 1] = '\0';
4641541Srgrimes#if defined(__APPLE__) || defined(__FreeBSD__) || defined(__NetBSD__)
4651541Srgrimes    saddr_un.sun_len = SUN_LEN (&saddr_un);
4661541Srgrimes#endif
46765805Sbp
4681541Srgrimes    if (::connect (fd, (struct sockaddr *)&saddr_un, SUN_LEN (&saddr_un)) < 0)
469158094Sjeff    {
470158094Sjeff        SetLastError (error);
471140714Sjeff        return error;
472162288Smohans    }
473162288Smohans
4741541Srgrimes    socket = final_socket.release();
4751541Srgrimes#else
4761541Srgrimes    error.SetErrorString("Unix domain sockets are not supported on this platform.");
477158094Sjeff#endif
478158094Sjeff    return error;
479140714Sjeff}
4801541Srgrimes
481144229SjeffError Socket::UnixDomainAccept(llvm::StringRef name, bool child_processes_inherit, Socket *&socket)
482144229Sjeff{
4831541Srgrimes    Error error;
4841541Srgrimes#ifndef LLDB_DISABLE_POSIX
48522874Sbde    struct sockaddr_un saddr_un;
48622874Sbde    std::unique_ptr<Socket> listen_socket;
4871541Srgrimes    std::unique_ptr<Socket> final_socket;
4881541Srgrimes    NativeSocket listen_fd = kInvalidSocketValue;
489144286Sjeff    NativeSocket socket_fd = kInvalidSocketValue;
4901541Srgrimes
491144286Sjeff    listen_fd = ::CreateSocket (AF_UNIX, SOCK_STREAM, 0, child_processes_inherit);
492144286Sjeff    if (listen_fd == kInvalidSocketValue)
493144286Sjeff    {
494144286Sjeff        SetLastError (error);
495144613Sjeff        return error;
496144613Sjeff    }
497144613Sjeff
498144613Sjeff    listen_socket.reset(new Socket(listen_fd, ProtocolUnixDomain, true));
4991541Srgrimes
5001541Srgrimes    saddr_un.sun_family = AF_UNIX;
501175202Sattilio    ::strncpy(saddr_un.sun_path, name.data(), sizeof(saddr_un.sun_path) - 1);
502175202Sattilio    saddr_un.sun_path[sizeof(saddr_un.sun_path) - 1] = '\0';
5031541Srgrimes#if defined(__APPLE__) || defined(__FreeBSD__) || defined(__NetBSD__)
5041541Srgrimes    saddr_un.sun_len = SUN_LEN (&saddr_un);
5051541Srgrimes#endif
5061541Srgrimes
5071541Srgrimes    FileSystem::Unlink(FileSpec{name, true});
5081541Srgrimes    bool success = false;
5091541Srgrimes    if (::bind (listen_fd, (struct sockaddr *)&saddr_un, SUN_LEN (&saddr_un)) == 0)
5101541Srgrimes    {
5111541Srgrimes        if (::listen (listen_fd, 5) == 0)
5121541Srgrimes        {
5131541Srgrimes            socket_fd = Accept (listen_fd, NULL, 0, child_processes_inherit);
5141541Srgrimes            if (socket_fd > 0)
51551906Sphk            {
5161541Srgrimes                final_socket.reset(new Socket(socket_fd, ProtocolUnixDomain, true));
5171541Srgrimes                success = true;
5181541Srgrimes            }
5191541Srgrimes        }
5201541Srgrimes    }
5211541Srgrimes
5221541Srgrimes    if (!success)
5231541Srgrimes    {
5241541Srgrimes        SetLastError (error);
5251541Srgrimes        return error;
5261541Srgrimes    }
5271541Srgrimes    // We are done with the listen port
5281541Srgrimes    listen_socket.reset();
5299804Sbde
5309804Sbde    socket = final_socket.release();
5319804Sbde#else
5329804Sbde    error.SetErrorString("Unix domain sockets are not supported on this platform.");
5339804Sbde#endif
5349804Sbde    return error;
5359804Sbde}
5369804Sbde
5379804Sbdebool
5389804SbdeSocket::DecodeHostAndPort(llvm::StringRef host_and_port,
5399804Sbde                          std::string &host_str,
5409804Sbde                          std::string &port_str,
541193557Sdes                          int32_t& port,
542193028Sdes                          Error *error_ptr)
5439804Sbde{
5449804Sbde    static RegularExpression g_regex ("([^:]+):([0-9]+)");
5459804Sbde    RegularExpression::Match regex_match(2);
5469804Sbde    if (g_regex.Execute (host_and_port.data(), &regex_match))
5471541Srgrimes    {
5481541Srgrimes        if (regex_match.GetMatchAtIndex (host_and_port.data(), 1, host_str) &&
5491541Srgrimes            regex_match.GetMatchAtIndex (host_and_port.data(), 2, port_str))
5501541Srgrimes        {
5511541Srgrimes            bool ok = false;
5521541Srgrimes            port = StringConvert::ToUInt32 (port_str.c_str(), UINT32_MAX, 10, &ok);
5531541Srgrimes            if (ok && port < UINT16_MAX)
5541541Srgrimes            {
5551541Srgrimes                if (error_ptr)
5561541Srgrimes                    error_ptr->Clear();
5571541Srgrimes                return true;
5581541Srgrimes            }
5591541Srgrimes            // port is too large
560199137Skib            if (error_ptr)
561199137Skib                error_ptr->SetErrorStringWithFormat("invalid host:port specification: '%s'", host_and_port.data());
562199137Skib            return false;
563199137Skib        }
564199137Skib    }
565199137Skib
5661541Srgrimes    // If this was unsuccessful, then check if it's simply a signed 32-bit integer, representing
5671541Srgrimes    // a port with an empty host.
5681541Srgrimes    host_str.clear();
5691541Srgrimes    port_str.clear();
5701541Srgrimes    bool ok = false;
5711541Srgrimes    port = StringConvert::ToUInt32 (host_and_port.data(), UINT32_MAX, 10, &ok);
5721541Srgrimes    if (ok && port < UINT16_MAX)
57322521Sdyson    {
57422521Sdyson        port_str = host_and_port;
57522521Sdyson        if (error_ptr)
57622521Sdyson            error_ptr->Clear();
5771541Srgrimes        return true;
5781541Srgrimes    }
5791541Srgrimes
5801541Srgrimes    if (error_ptr)
5811541Srgrimes        error_ptr->SetErrorStringWithFormat("invalid host:port specification: '%s'", host_and_port.data());
5821541Srgrimes    return false;
5831541Srgrimes}
5841541Srgrimes
5851541SrgrimesIOObject::WaitableHandle Socket::GetWaitableHandle()
586155334Srwatson{
587155334Srwatson    // TODO: On Windows, use WSAEventSelect
588195926Srwatson    return m_socket;
589155334Srwatson}
590195926Srwatson
591155334SrwatsonError Socket::Read (void *buf, size_t &num_bytes)
5921541Srgrimes{
593175294Sattilio    Error error;
59454655Seivind    int bytes_received = 0;
5951541Srgrimes    do
5961541Srgrimes    {
597140714Sjeff        bytes_received = ::recv (m_socket, static_cast<char *>(buf), num_bytes, 0);
5981541Srgrimes    } while (bytes_received < 0 && IsInterrupted ());
5991541Srgrimes
6001541Srgrimes    if (bytes_received < 0)
601154649Struckman    {
602154649Struckman        SetLastError (error);
603154649Struckman        num_bytes = 0;
604154649Struckman    }
6051541Srgrimes    else
6061541Srgrimes        num_bytes = bytes_received;
607154649Struckman
6081541Srgrimes    Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_HOST | LIBLLDB_LOG_COMMUNICATION));
6091541Srgrimes    if (log)
61096755Strhodes    {
611154649Struckman        log->Printf ("%p Socket::Read() (socket = %" PRIu64 ", src = %p, src_len = %" PRIu64 ", flags = 0) => %" PRIi64 " (error = %s)",
61251649Sphk                     static_cast<void*>(this),
6131541Srgrimes                     static_cast<uint64_t>(m_socket),
6141541Srgrimes                     buf,
615154649Struckman                     static_cast<uint64_t>(num_bytes),
616154649Struckman                     static_cast<int64_t>(bytes_received),
617154690Struckman                     error.AsCString());
618154649Struckman    }
619154649Struckman
6201541Srgrimes    return error;
621192895Sjamie}
622192895Sjamie
623192895SjamieError Socket::Write (const void *buf, size_t &num_bytes)
624192895Sjamie{
62551649Sphk    Error error;
62651649Sphk    int bytes_sent = 0;
627166744Skib    do
628192895Sjamie    {
629166744Skib        if (m_protocol == ProtocolUdp)
630166744Skib        {
6311541Srgrimes            bytes_sent = ::sendto (m_socket,
6321541Srgrimes                                    static_cast<const char*>(buf),
633158142Skris                                    num_bytes,
6341541Srgrimes                                    0,
6351541Srgrimes                                    m_udp_send_sockaddr,
6361541Srgrimes                                    m_udp_send_sockaddr.GetLength());
637166744Skib        }
6381541Srgrimes        else
639155385Sjeff            bytes_sent = ::send (m_socket, static_cast<const char *>(buf), num_bytes, 0);
640190387Sjhb    } while (bytes_sent < 0 && IsInterrupted ());
64169405Salfred
64269405Salfred    if (bytes_sent < 0)
6431541Srgrimes    {
644144833Sjeff        SetLastError (error);
645158094Sjeff        num_bytes = 0;
646158094Sjeff    }
647144833Sjeff    else
6481541Srgrimes        num_bytes = bytes_sent;
649140714Sjeff
650175202Sattilio    Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_HOST));
651175202Sattilio    if (log)
652175202Sattilio    {
6531541Srgrimes        log->Printf ("%p Socket::Write() (socket = %" PRIu64 ", src = %p, src_len = %" PRIu64 ", flags = 0) => %" PRIi64 " (error = %s)",
6541541Srgrimes                        static_cast<void*>(this),
6551541Srgrimes                        static_cast<uint64_t>(m_socket),
6561541Srgrimes                        buf,
6571541Srgrimes                        static_cast<uint64_t>(num_bytes),
6581541Srgrimes                        static_cast<int64_t>(bytes_sent),
6591541Srgrimes                        error.AsCString());
660101127Srwatson    }
661105479Srwatson
662191990Sattilio    return error;
663191990Sattilio}
664105479Srwatson
665105479SrwatsonError Socket::PreDisconnect()
666105479Srwatson{
667101127Srwatson    Error error;
6681541Srgrimes    return error;
66922521Sdyson}
67024624Sdfr
671158094SjeffError Socket::Close()
672144286Sjeff{
673144286Sjeff    Error error;
674144286Sjeff    if (!IsValid() || !m_should_close_fd)
675144286Sjeff        return error;
676166167Skib
677176559Sattilio    Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_CONNECTION));
678144286Sjeff    if (log)
679175202Sattilio        log->Printf ("%p Socket::Close (fd = %i)", static_cast<void*>(this), m_socket);
680144286Sjeff
681144286Sjeff#if defined(_WIN32)
682144286Sjeff    bool success = !!closesocket(m_socket);
683144286Sjeff#else
684189696Sjhb    bool success = !!::close (m_socket);
685144286Sjeff#endif
686138345Sphk    // A reference to a FD was passed in, set it to an invalid value
687138345Sphk    m_socket = kInvalidSocketValue;
688138345Sphk    if (!success)
689162288Smohans    {
690162288Smohans        SetLastError (error);
69143301Sdillon    }
692162288Smohans
69342408Seivind    return error;
6941541Srgrimes}
6951541Srgrimes
6961541Srgrimes
6971541Srgrimesint Socket::GetOption(int level, int option_name, int &option_value)
698101308Sjeff{
6991541Srgrimes    get_socket_option_arg_type option_value_p = reinterpret_cast<get_socket_option_arg_type>(&option_value);
7001541Srgrimes    socklen_t option_value_size = sizeof(int);
701144833Sjeff	return ::getsockopt(m_socket, level, option_name, option_value_p, &option_value_size);
702158094Sjeff}
703158094Sjeff
704144833Sjeffint Socket::SetOption(int level, int option_name, int option_value)
705144203Sjeff{
706140714Sjeff    set_socket_option_arg_type option_value_p = reinterpret_cast<get_socket_option_arg_type>(&option_value);
707175202Sattilio	return ::setsockopt(m_socket, level, option_name, option_value_p, sizeof(option_value));
708175202Sattilio}
709175202Sattilio
7101541Srgrimesuint16_t Socket::GetLocalPortNumber(const NativeSocket& socket)
7111541Srgrimes{
7121541Srgrimes    // We bound to port zero, so we need to figure out which port we actually bound to
7131541Srgrimes    if (socket != kInvalidSocketValue)
7141541Srgrimes    {
7151541Srgrimes        SocketAddress sock_addr;
716193557Sdes        socklen_t sock_addr_len = sock_addr.GetMaxLength ();
717193557Sdes        if (::getsockname (socket, sock_addr, &sock_addr_len) == 0)
718193557Sdes            return sock_addr.GetPort ();
719193557Sdes    }
7201541Srgrimes    return 0;
72111644Sdg}
7221541Srgrimes
7231541Srgrimes// Return the port number that is being used by the socket.
7241541Srgrimesuint16_t Socket::GetLocalPortNumber() const
725193557Sdes{
726193557Sdes    return GetLocalPortNumber (m_socket);
727193557Sdes}
7289804Sbde
7299804Sbdestd::string  Socket::GetLocalIPAddress () const
7309804Sbde{
731144203Sjeff    // We bound to port zero, so we need to figure out which port we actually bound to
732175294Sattilio    if (m_socket != kInvalidSocketValue)
7331541Srgrimes    {
7341541Srgrimes        SocketAddress sock_addr;
7351541Srgrimes        socklen_t sock_addr_len = sock_addr.GetMaxLength ();
736161010Srwatson        if (::getsockname (m_socket, sock_addr, &sock_addr_len) == 0)
7371541Srgrimes            return sock_addr.GetIPAddress ();
7381541Srgrimes    }
7391541Srgrimes    return "";
7401541Srgrimes}
7411541Srgrimes
742140714Sjeffuint16_t Socket::GetRemotePortNumber () const
743162288Smohans{
744162288Smohans    if (m_socket != kInvalidSocketValue)
7451541Srgrimes    {
7461541Srgrimes        SocketAddress sock_addr;
7471541Srgrimes        socklen_t sock_addr_len = sock_addr.GetMaxLength ();
748144203Sjeff        if (::getpeername (m_socket, sock_addr, &sock_addr_len) == 0)
7491541Srgrimes            return sock_addr.GetPort ();
7501541Srgrimes    }
7511541Srgrimes    return 0;
7521541Srgrimes}
7531541Srgrimes
7541541Srgrimesstd::string Socket::GetRemoteIPAddress () const
7551541Srgrimes{
7561541Srgrimes    // We bound to port zero, so we need to figure out which port we actually bound to
7571541Srgrimes    if (m_socket != kInvalidSocketValue)
7581541Srgrimes    {
7591541Srgrimes        SocketAddress sock_addr;
760158094Sjeff        socklen_t sock_addr_len = sock_addr.GetMaxLength ();
7611541Srgrimes        if (::getpeername (m_socket, sock_addr, &sock_addr_len) == 0)
7621541Srgrimes            return sock_addr.GetIPAddress ();
7631541Srgrimes    }
76496755Strhodes    return "";
7651541Srgrimes}
7661541Srgrimes
7671541Srgrimes
768184554Sattilio