Socket.cpp revision 280031
1275072Semaste//===-- Socket.cpp ----------------------------------------------*- C++ -*-===//
2275072Semaste//
3275072Semaste//                     The LLVM Compiler Infrastructure
4275072Semaste//
5275072Semaste// This file is distributed under the University of Illinois Open Source
6275072Semaste// License. See LICENSE.TXT for details.
7275072Semaste//
8275072Semaste//===----------------------------------------------------------------------===//
9275072Semaste
10275072Semaste#include "lldb/Host/Socket.h"
11275072Semaste
12275072Semaste#include "lldb/Core/Log.h"
13275072Semaste#include "lldb/Core/RegularExpression.h"
14275072Semaste#include "lldb/Host/Config.h"
15275072Semaste#include "lldb/Host/FileSystem.h"
16275072Semaste#include "lldb/Host/Host.h"
17275072Semaste#include "lldb/Host/SocketAddress.h"
18275072Semaste#include "lldb/Host/TimeValue.h"
19275072Semaste#include "lldb/Interpreter/Args.h"
20275072Semaste
21280031Sdim#ifdef __ANDROID_NDK__
22280031Sdim#include <linux/tcp.h>
23280031Sdim#include <bits/error_constants.h>
24280031Sdim#include <asm-generic/errno-base.h>
25280031Sdim#include <errno.h>
26280031Sdim#include <arpa/inet.h>
27280031Sdim#endif
28280031Sdim
29275072Semaste#ifndef LLDB_DISABLE_POSIX
30275072Semaste#include <arpa/inet.h>
31275072Semaste#include <netdb.h>
32275072Semaste#include <netinet/in.h>
33275072Semaste#include <netinet/tcp.h>
34275072Semaste#include <sys/socket.h>
35275072Semaste#include <sys/un.h>
36275072Semaste#endif
37275072Semaste
38275072Semasteusing namespace lldb;
39275072Semasteusing namespace lldb_private;
40275072Semaste
41275072Semaste#if defined(_WIN32)
42275072Semastetypedef const char * set_socket_option_arg_type;
43275072Semastetypedef char * get_socket_option_arg_type;
44275072Semasteconst NativeSocket Socket::kInvalidSocketValue = INVALID_SOCKET;
45275072Semaste#else // #if defined(_WIN32)
46275072Semastetypedef const void * set_socket_option_arg_type;
47275072Semastetypedef void * get_socket_option_arg_type;
48275072Semasteconst NativeSocket Socket::kInvalidSocketValue = -1;
49275072Semaste#endif // #if defined(_WIN32)
50275072Semaste
51280031Sdim#ifdef __ANDROID__
52280031Sdim// Android does not have SUN_LEN
53280031Sdim#ifndef SUN_LEN
54280031Sdim#define SUN_LEN(ptr) ((size_t) (((struct sockaddr_un *) 0)->sun_path) + strlen((ptr)->sun_path))
55280031Sdim#endif
56280031Sdim#endif // #ifdef __ANDROID__
57280031Sdim
58280031Sdimnamespace {
59280031Sdim
60280031SdimNativeSocket CreateSocket(const int domain, const int type, const int protocol, bool child_processes_inherit)
61280031Sdim{
62280031Sdim    auto socketType = type;
63280031Sdim#ifdef SOCK_CLOEXEC
64280031Sdim    if (!child_processes_inherit) {
65280031Sdim        socketType |= SOCK_CLOEXEC;
66280031Sdim    }
67280031Sdim#endif
68280031Sdim    return ::socket (domain, socketType, protocol);
69280031Sdim}
70280031Sdim
71280031SdimNativeSocket Accept(NativeSocket sockfd, struct sockaddr *addr, socklen_t *addrlen, bool child_processes_inherit)
72280031Sdim{
73280031Sdim#ifdef SOCK_CLOEXEC
74280031Sdim    int flags = 0;
75280031Sdim    if (!child_processes_inherit) {
76280031Sdim        flags |= SOCK_CLOEXEC;
77280031Sdim    }
78280031Sdim    return ::accept4 (sockfd, addr, addrlen, flags);
79280031Sdim#else
80280031Sdim    return ::accept (sockfd, addr, addrlen);
81280031Sdim#endif
82280031Sdim}
83280031Sdim}
84280031Sdim
85275072SemasteSocket::Socket(NativeSocket socket, SocketProtocol protocol, bool should_close)
86275072Semaste    : IOObject(eFDTypeSocket, should_close)
87275072Semaste    , m_protocol(protocol)
88275072Semaste    , m_socket(socket)
89275072Semaste{
90275072Semaste
91275072Semaste}
92275072Semaste
93275072SemasteSocket::~Socket()
94275072Semaste{
95275072Semaste    Close();
96275072Semaste}
97275072Semaste
98280031SdimError Socket::TcpConnect(llvm::StringRef host_and_port, bool child_processes_inherit, Socket *&socket)
99275072Semaste{
100275072Semaste    // Store the result in a unique_ptr in case we error out, the memory will get correctly freed.
101275072Semaste    std::unique_ptr<Socket> final_socket;
102275072Semaste    NativeSocket sock = kInvalidSocketValue;
103275072Semaste    Error error;
104275072Semaste
105275072Semaste    Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_HOST));
106275072Semaste    if (log)
107275072Semaste        log->Printf ("Socket::TcpConnect (host/port = %s)", host_and_port.data());
108275072Semaste
109275072Semaste    std::string host_str;
110275072Semaste    std::string port_str;
111275072Semaste    int32_t port = INT32_MIN;
112275072Semaste    if (!DecodeHostAndPort (host_and_port, host_str, port_str, port, &error))
113275072Semaste        return error;
114275072Semaste
115275072Semaste    // Create the socket
116280031Sdim    sock = CreateSocket (AF_INET, SOCK_STREAM, IPPROTO_TCP, child_processes_inherit);
117275072Semaste    if (sock == kInvalidSocketValue)
118275072Semaste    {
119275072Semaste        // TODO: On Windows, use WSAGetLastError().
120275072Semaste        error.SetErrorToErrno();
121275072Semaste        return error;
122275072Semaste    }
123275072Semaste
124275072Semaste    // Since they both refer to the same socket descriptor, arbitrarily choose the send socket to
125275072Semaste    // be the owner.
126275072Semaste    final_socket.reset(new Socket(sock, ProtocolTcp, true));
127275072Semaste
128275072Semaste    // Enable local address reuse
129275072Semaste    final_socket->SetOption(SOL_SOCKET, SO_REUSEADDR, 1);
130275072Semaste
131275072Semaste    struct sockaddr_in sa;
132275072Semaste    ::memset (&sa, 0, sizeof (sa));
133275072Semaste    sa.sin_family = AF_INET;
134275072Semaste    sa.sin_port = htons (port);
135275072Semaste
136275072Semaste    int inet_pton_result = ::inet_pton (AF_INET, host_str.c_str(), &sa.sin_addr);
137275072Semaste
138275072Semaste    if (inet_pton_result <= 0)
139275072Semaste    {
140275072Semaste        struct hostent *host_entry = gethostbyname (host_str.c_str());
141275072Semaste        if (host_entry)
142275072Semaste            host_str = ::inet_ntoa (*(struct in_addr *)*host_entry->h_addr_list);
143275072Semaste        inet_pton_result = ::inet_pton (AF_INET, host_str.c_str(), &sa.sin_addr);
144275072Semaste        if (inet_pton_result <= 0)
145275072Semaste        {
146275072Semaste            // TODO: On Windows, use WSAGetLastError()
147275072Semaste            if (inet_pton_result == -1)
148275072Semaste                error.SetErrorToErrno();
149275072Semaste            else
150275072Semaste                error.SetErrorStringWithFormat("invalid host string: '%s'", host_str.c_str());
151275072Semaste
152275072Semaste            return error;
153275072Semaste        }
154275072Semaste    }
155275072Semaste
156275072Semaste    if (-1 == ::connect (sock, (const struct sockaddr *)&sa, sizeof(sa)))
157275072Semaste    {
158275072Semaste        // TODO: On Windows, use WSAGetLastError()
159275072Semaste        error.SetErrorToErrno();
160275072Semaste        return error;
161275072Semaste    }
162275072Semaste
163275072Semaste    // Keep our TCP packets coming without any delays.
164275072Semaste    final_socket->SetOption(IPPROTO_TCP, TCP_NODELAY, 1);
165275072Semaste    error.Clear();
166275072Semaste    socket = final_socket.release();
167275072Semaste    return error;
168275072Semaste}
169275072Semaste
170280031SdimError Socket::TcpListen(llvm::StringRef host_and_port, bool child_processes_inherit, Socket *&socket, Predicate<uint16_t>* predicate)
171275072Semaste{
172275072Semaste    std::unique_ptr<Socket> listen_socket;
173275072Semaste    NativeSocket listen_sock = kInvalidSocketValue;
174275072Semaste    Error error;
175275072Semaste
176275072Semaste    const sa_family_t family = AF_INET;
177275072Semaste    const int socktype = SOCK_STREAM;
178275072Semaste    const int protocol = IPPROTO_TCP;
179280031Sdim    listen_sock = ::CreateSocket (family, socktype, protocol, child_processes_inherit);
180275072Semaste    if (listen_sock == kInvalidSocketValue)
181275072Semaste    {
182275072Semaste        error.SetErrorToErrno();
183275072Semaste        return error;
184275072Semaste    }
185275072Semaste
186275072Semaste    listen_socket.reset(new Socket(listen_sock, ProtocolTcp, true));
187275072Semaste
188275072Semaste    // enable local address reuse
189275072Semaste    listen_socket->SetOption(SOL_SOCKET, SO_REUSEADDR, 1);
190275072Semaste
191275072Semaste    Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_CONNECTION));
192275072Semaste    if (log)
193275072Semaste        log->Printf ("ConnectionFileDescriptor::SocketListen (%s)", host_and_port.data());
194275072Semaste
195275072Semaste    std::string host_str;
196275072Semaste    std::string port_str;
197275072Semaste    int32_t port = INT32_MIN;
198275072Semaste    if (!DecodeHostAndPort (host_and_port, host_str, port_str, port, &error))
199275072Semaste        return error;
200275072Semaste
201275072Semaste    SocketAddress anyaddr;
202275072Semaste    if (anyaddr.SetToAnyAddress (family, port))
203275072Semaste    {
204275072Semaste        int err = ::bind (listen_sock, anyaddr, anyaddr.GetLength());
205275072Semaste        if (err == -1)
206275072Semaste        {
207275072Semaste            // TODO: On Windows, use WSAGetLastError()
208275072Semaste            error.SetErrorToErrno();
209275072Semaste            return error;
210275072Semaste        }
211275072Semaste
212275072Semaste        err = ::listen (listen_sock, 1);
213275072Semaste        if (err == -1)
214275072Semaste        {
215275072Semaste            // TODO: On Windows, use WSAGetLastError()
216275072Semaste            error.SetErrorToErrno();
217275072Semaste            return error;
218275072Semaste        }
219275072Semaste
220275072Semaste        // We were asked to listen on port zero which means we
221275072Semaste        // must now read the actual port that was given to us
222275072Semaste        // as port zero is a special code for "find an open port
223275072Semaste        // for me".
224275072Semaste        if (port == 0)
225275072Semaste            port = listen_socket->GetPortNumber();
226275072Semaste
227275072Semaste        // Set the port predicate since when doing a listen://<host>:<port>
228275072Semaste        // it often needs to accept the incoming connection which is a blocking
229275072Semaste        // system call. Allowing access to the bound port using a predicate allows
230275072Semaste        // us to wait for the port predicate to be set to a non-zero value from
231275072Semaste        // another thread in an efficient manor.
232275072Semaste        if (predicate)
233275072Semaste            predicate->SetValue(port, eBroadcastAlways);
234275072Semaste
235275072Semaste        socket = listen_socket.release();
236275072Semaste    }
237275072Semaste
238275072Semaste    return error;
239275072Semaste}
240275072Semaste
241280031SdimError Socket::BlockingAccept(llvm::StringRef host_and_port, bool child_processes_inherit, Socket *&socket)
242275072Semaste{
243275072Semaste    Error error;
244275072Semaste    std::string host_str;
245275072Semaste    std::string port_str;
246275072Semaste    int32_t port;
247275072Semaste    if (!DecodeHostAndPort(host_and_port, host_str, port_str, port, &error))
248275072Semaste        return error;
249275072Semaste
250275072Semaste    const sa_family_t family = AF_INET;
251275072Semaste    const int socktype = SOCK_STREAM;
252275072Semaste    const int protocol = IPPROTO_TCP;
253275072Semaste    SocketAddress listen_addr;
254275072Semaste    if (host_str.empty())
255275072Semaste        listen_addr.SetToLocalhost(family, port);
256275072Semaste    else if (host_str.compare("*") == 0)
257275072Semaste        listen_addr.SetToAnyAddress(family, port);
258275072Semaste    else
259275072Semaste    {
260275072Semaste        if (!listen_addr.getaddrinfo(host_str.c_str(), port_str.c_str(), family, socktype, protocol))
261275072Semaste        {
262275072Semaste            error.SetErrorStringWithFormat("unable to resolve hostname '%s'", host_str.c_str());
263275072Semaste            return error;
264275072Semaste        }
265275072Semaste    }
266275072Semaste
267275072Semaste    bool accept_connection = false;
268275072Semaste    std::unique_ptr<Socket> accepted_socket;
269275072Semaste
270275072Semaste    // Loop until we are happy with our connection
271275072Semaste    while (!accept_connection)
272275072Semaste    {
273275072Semaste        struct sockaddr_in accept_addr;
274275072Semaste        ::memset (&accept_addr, 0, sizeof accept_addr);
275275072Semaste#if !(defined (__linux__) || defined(_WIN32))
276275072Semaste        accept_addr.sin_len = sizeof accept_addr;
277275072Semaste#endif
278275072Semaste        socklen_t accept_addr_len = sizeof accept_addr;
279275072Semaste
280280031Sdim        int sock = Accept (this->GetNativeSocket(),
281280031Sdim                           (struct sockaddr *)&accept_addr,
282280031Sdim                           &accept_addr_len,
283280031Sdim                           child_processes_inherit);
284275072Semaste
285275072Semaste        if (sock == kInvalidSocketValue)
286275072Semaste        {
287275072Semaste            // TODO: On Windows, use WSAGetLastError()
288275072Semaste            error.SetErrorToErrno();
289275072Semaste            break;
290275072Semaste        }
291275072Semaste
292275072Semaste        bool is_same_addr = true;
293275072Semaste#if !(defined(__linux__) || (defined(_WIN32)))
294275072Semaste        is_same_addr = (accept_addr_len == listen_addr.sockaddr_in().sin_len);
295275072Semaste#endif
296275072Semaste        if (is_same_addr)
297275072Semaste            is_same_addr = (accept_addr.sin_addr.s_addr == listen_addr.sockaddr_in().sin_addr.s_addr);
298275072Semaste
299275072Semaste        if (is_same_addr || (listen_addr.sockaddr_in().sin_addr.s_addr == INADDR_ANY))
300275072Semaste        {
301275072Semaste            accept_connection = true;
302275072Semaste            // Since both sockets have the same descriptor, arbitrarily choose the send
303275072Semaste            // socket to be the owner.
304275072Semaste            accepted_socket.reset(new Socket(sock, ProtocolTcp, true));
305275072Semaste        }
306275072Semaste        else
307275072Semaste        {
308275072Semaste            const uint8_t *accept_ip = (const uint8_t *)&accept_addr.sin_addr.s_addr;
309275072Semaste            const uint8_t *listen_ip = (const uint8_t *)&listen_addr.sockaddr_in().sin_addr.s_addr;
310275072Semaste            ::fprintf (stderr, "error: rejecting incoming connection from %u.%u.%u.%u (expecting %u.%u.%u.%u)\n",
311275072Semaste                        accept_ip[0], accept_ip[1], accept_ip[2], accept_ip[3],
312275072Semaste                        listen_ip[0], listen_ip[1], listen_ip[2], listen_ip[3]);
313275072Semaste            accepted_socket.reset();
314275072Semaste        }
315275072Semaste    }
316275072Semaste
317275072Semaste    if (!accepted_socket)
318275072Semaste        return error;
319275072Semaste
320275072Semaste    // Keep our TCP packets coming without any delays.
321275072Semaste    accepted_socket->SetOption (IPPROTO_TCP, TCP_NODELAY, 1);
322275072Semaste    error.Clear();
323275072Semaste    socket = accepted_socket.release();
324275072Semaste    return error;
325275072Semaste
326275072Semaste}
327275072Semaste
328280031SdimError Socket::UdpConnect(llvm::StringRef host_and_port, bool child_processes_inherit, Socket *&send_socket, Socket *&recv_socket)
329275072Semaste{
330275072Semaste    std::unique_ptr<Socket> final_send_socket;
331275072Semaste    std::unique_ptr<Socket> final_recv_socket;
332275072Semaste    NativeSocket final_send_fd = kInvalidSocketValue;
333275072Semaste    NativeSocket final_recv_fd = kInvalidSocketValue;
334275072Semaste
335275072Semaste    Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_CONNECTION));
336275072Semaste    if (log)
337275072Semaste        log->Printf ("Socket::UdpConnect (host/port = %s)", host_and_port.data());
338275072Semaste
339275072Semaste    Error error;
340275072Semaste    std::string host_str;
341275072Semaste    std::string port_str;
342275072Semaste    int32_t port = INT32_MIN;
343275072Semaste    if (!DecodeHostAndPort (host_and_port, host_str, port_str, port, &error))
344275072Semaste        return error;
345275072Semaste
346275072Semaste    // Setup the receiving end of the UDP connection on this localhost
347275072Semaste    // on port zero. After we bind to port zero we can read the port.
348280031Sdim    final_recv_fd = ::CreateSocket (AF_INET, SOCK_DGRAM, 0, child_processes_inherit);
349275072Semaste    if (final_recv_fd == kInvalidSocketValue)
350275072Semaste    {
351275072Semaste        // Socket creation failed...
352275072Semaste        // TODO: On Windows, use WSAGetLastError().
353275072Semaste        error.SetErrorToErrno();
354275072Semaste    }
355275072Semaste    else
356275072Semaste    {
357275072Semaste        final_recv_socket.reset(new Socket(final_recv_fd, ProtocolUdp, true));
358275072Semaste
359275072Semaste        // Socket was created, now lets bind to the requested port
360275072Semaste        SocketAddress addr;
361275072Semaste        addr.SetToAnyAddress (AF_INET, 0);
362275072Semaste
363275072Semaste        if (::bind (final_recv_fd, addr, addr.GetLength()) == -1)
364275072Semaste        {
365275072Semaste            // Bind failed...
366275072Semaste            // TODO: On Windows use WSAGetLastError()
367275072Semaste            error.SetErrorToErrno();
368275072Semaste        }
369275072Semaste    }
370275072Semaste
371275072Semaste    assert(error.Fail() == !(final_recv_socket && final_recv_socket->IsValid()));
372275072Semaste    if (error.Fail())
373275072Semaste        return error;
374275072Semaste
375275072Semaste    // At this point we have setup the receive port, now we need to
376275072Semaste    // setup the UDP send socket
377275072Semaste
378275072Semaste    struct addrinfo hints;
379275072Semaste    struct addrinfo *service_info_list = NULL;
380275072Semaste
381275072Semaste    ::memset (&hints, 0, sizeof(hints));
382275072Semaste    hints.ai_family = AF_INET;
383275072Semaste    hints.ai_socktype = SOCK_DGRAM;
384275072Semaste    int err = ::getaddrinfo (host_str.c_str(), port_str.c_str(), &hints, &service_info_list);
385275072Semaste    if (err != 0)
386275072Semaste    {
387275072Semaste        error.SetErrorStringWithFormat("getaddrinfo(%s, %s, &hints, &info) returned error %i (%s)",
388275072Semaste                                       host_str.c_str(),
389275072Semaste                                       port_str.c_str(),
390275072Semaste                                       err,
391275072Semaste                                       gai_strerror(err));
392275072Semaste        return error;
393275072Semaste    }
394275072Semaste
395275072Semaste    for (struct addrinfo *service_info_ptr = service_info_list;
396275072Semaste         service_info_ptr != NULL;
397275072Semaste         service_info_ptr = service_info_ptr->ai_next)
398275072Semaste    {
399280031Sdim        final_send_fd = ::CreateSocket (service_info_ptr->ai_family,
400280031Sdim                                        service_info_ptr->ai_socktype,
401280031Sdim                                        service_info_ptr->ai_protocol,
402280031Sdim                                        child_processes_inherit);
403275072Semaste
404275072Semaste        if (final_send_fd != kInvalidSocketValue)
405275072Semaste        {
406275072Semaste            final_send_socket.reset(new Socket(final_send_fd, ProtocolUdp, true));
407275072Semaste            final_send_socket->m_udp_send_sockaddr = service_info_ptr;
408275072Semaste            break;
409275072Semaste        }
410275072Semaste        else
411275072Semaste            continue;
412275072Semaste    }
413275072Semaste
414275072Semaste    :: freeaddrinfo (service_info_list);
415275072Semaste
416275072Semaste    if (final_send_fd == kInvalidSocketValue)
417275072Semaste    {
418275072Semaste        // TODO: On Windows, use WSAGetLastError().
419275072Semaste        error.SetErrorToErrno();
420275072Semaste        return error;
421275072Semaste    }
422275072Semaste
423275072Semaste    send_socket = final_send_socket.release();
424275072Semaste    recv_socket = final_recv_socket.release();
425275072Semaste    error.Clear();
426275072Semaste    return error;
427275072Semaste}
428275072Semaste
429280031SdimError Socket::UnixDomainConnect(llvm::StringRef name, bool child_processes_inherit, Socket *&socket)
430275072Semaste{
431275072Semaste    Error error;
432275072Semaste#ifndef LLDB_DISABLE_POSIX
433275072Semaste    std::unique_ptr<Socket> final_socket;
434275072Semaste
435275072Semaste    // Open the socket that was passed in as an option
436275072Semaste    struct sockaddr_un saddr_un;
437280031Sdim    int fd = ::CreateSocket (AF_UNIX, SOCK_STREAM, 0, child_processes_inherit);
438275072Semaste    if (fd == kInvalidSocketValue)
439275072Semaste    {
440275072Semaste        error.SetErrorToErrno();
441275072Semaste        return error;
442275072Semaste    }
443275072Semaste
444275072Semaste    final_socket.reset(new Socket(fd, ProtocolUnixDomain, true));
445275072Semaste
446275072Semaste    saddr_un.sun_family = AF_UNIX;
447275072Semaste    ::strncpy(saddr_un.sun_path, name.data(), sizeof(saddr_un.sun_path) - 1);
448275072Semaste    saddr_un.sun_path[sizeof(saddr_un.sun_path) - 1] = '\0';
449275072Semaste#if defined(__APPLE__) || defined(__FreeBSD__) || defined(__NetBSD__)
450275072Semaste    saddr_un.sun_len = SUN_LEN (&saddr_un);
451275072Semaste#endif
452275072Semaste
453275072Semaste    if (::connect (fd, (struct sockaddr *)&saddr_un, SUN_LEN (&saddr_un)) < 0)
454275072Semaste    {
455275072Semaste        error.SetErrorToErrno();
456275072Semaste        return error;
457275072Semaste    }
458275072Semaste
459275072Semaste    socket = final_socket.release();
460275072Semaste#else
461275072Semaste    error.SetErrorString("Unix domain sockets are not supported on this platform.");
462275072Semaste#endif
463275072Semaste    return error;
464275072Semaste}
465275072Semaste
466280031SdimError Socket::UnixDomainAccept(llvm::StringRef name, bool child_processes_inherit, Socket *&socket)
467275072Semaste{
468275072Semaste    Error error;
469275072Semaste#ifndef LLDB_DISABLE_POSIX
470275072Semaste    struct sockaddr_un saddr_un;
471275072Semaste    std::unique_ptr<Socket> listen_socket;
472275072Semaste    std::unique_ptr<Socket> final_socket;
473275072Semaste    NativeSocket listen_fd = kInvalidSocketValue;
474275072Semaste    NativeSocket socket_fd = kInvalidSocketValue;
475275072Semaste
476280031Sdim    listen_fd = ::CreateSocket (AF_UNIX, SOCK_STREAM, 0, child_processes_inherit);
477275072Semaste    if (listen_fd == kInvalidSocketValue)
478275072Semaste    {
479275072Semaste        error.SetErrorToErrno();
480275072Semaste        return error;
481275072Semaste    }
482275072Semaste
483275072Semaste    listen_socket.reset(new Socket(listen_fd, ProtocolUnixDomain, true));
484275072Semaste
485275072Semaste    saddr_un.sun_family = AF_UNIX;
486275072Semaste    ::strncpy(saddr_un.sun_path, name.data(), sizeof(saddr_un.sun_path) - 1);
487275072Semaste    saddr_un.sun_path[sizeof(saddr_un.sun_path) - 1] = '\0';
488275072Semaste#if defined(__APPLE__) || defined(__FreeBSD__) || defined(__NetBSD__)
489275072Semaste    saddr_un.sun_len = SUN_LEN (&saddr_un);
490275072Semaste#endif
491275072Semaste
492275072Semaste    FileSystem::Unlink(name.data());
493275072Semaste    bool success = false;
494275072Semaste    if (::bind (listen_fd, (struct sockaddr *)&saddr_un, SUN_LEN (&saddr_un)) == 0)
495275072Semaste    {
496275072Semaste        if (::listen (listen_fd, 5) == 0)
497275072Semaste        {
498280031Sdim            socket_fd = Accept (listen_fd, NULL, 0, child_processes_inherit);
499275072Semaste            if (socket_fd > 0)
500275072Semaste            {
501275072Semaste                final_socket.reset(new Socket(socket_fd, ProtocolUnixDomain, true));
502275072Semaste                success = true;
503275072Semaste            }
504275072Semaste        }
505275072Semaste    }
506275072Semaste
507275072Semaste    if (!success)
508275072Semaste    {
509275072Semaste        error.SetErrorToErrno();
510275072Semaste        return error;
511275072Semaste    }
512275072Semaste    // We are done with the listen port
513275072Semaste    listen_socket.reset();
514275072Semaste
515275072Semaste    socket = final_socket.release();
516275072Semaste#else
517275072Semaste    error.SetErrorString("Unix domain sockets are not supported on this platform.");
518275072Semaste#endif
519275072Semaste    return error;
520275072Semaste}
521275072Semaste
522275072Semastebool
523275072SemasteSocket::DecodeHostAndPort(llvm::StringRef host_and_port,
524275072Semaste                          std::string &host_str,
525275072Semaste                          std::string &port_str,
526275072Semaste                          int32_t& port,
527275072Semaste                          Error *error_ptr)
528275072Semaste{
529275072Semaste    static RegularExpression g_regex ("([^:]+):([0-9]+)");
530275072Semaste    RegularExpression::Match regex_match(2);
531275072Semaste    if (g_regex.Execute (host_and_port.data(), &regex_match))
532275072Semaste    {
533275072Semaste        if (regex_match.GetMatchAtIndex (host_and_port.data(), 1, host_str) &&
534275072Semaste            regex_match.GetMatchAtIndex (host_and_port.data(), 2, port_str))
535275072Semaste        {
536275072Semaste            port = Args::StringToSInt32 (port_str.c_str(), INT32_MIN);
537275072Semaste            if (port != INT32_MIN)
538275072Semaste            {
539275072Semaste                if (error_ptr)
540275072Semaste                    error_ptr->Clear();
541275072Semaste                return true;
542275072Semaste            }
543275072Semaste        }
544275072Semaste    }
545275072Semaste
546275072Semaste    // If this was unsuccessful, then check if it's simply a signed 32-bit integer, representing
547275072Semaste    // a port with an empty host.
548275072Semaste    host_str.clear();
549275072Semaste    port_str.clear();
550275072Semaste    port = Args::StringToSInt32(host_and_port.data(), INT32_MIN);
551275072Semaste    if (port != INT32_MIN)
552275072Semaste    {
553275072Semaste        port_str = host_and_port;
554275072Semaste        return true;
555275072Semaste    }
556275072Semaste
557275072Semaste    if (error_ptr)
558275072Semaste        error_ptr->SetErrorStringWithFormat("invalid host:port specification: '%s'", host_and_port.data());
559275072Semaste    return false;
560275072Semaste}
561275072Semaste
562275072SemasteIOObject::WaitableHandle Socket::GetWaitableHandle()
563275072Semaste{
564275072Semaste    // TODO: On Windows, use WSAEventSelect
565275072Semaste    return m_socket;
566275072Semaste}
567275072Semaste
568275072SemasteError Socket::Read (void *buf, size_t &num_bytes)
569275072Semaste{
570275072Semaste    Error error;
571275072Semaste    int bytes_received = 0;
572275072Semaste    do
573275072Semaste    {
574275072Semaste        bytes_received = ::recv (m_socket, static_cast<char *>(buf), num_bytes, 0);
575275072Semaste        // TODO: Use WSAGetLastError on windows.
576275072Semaste    } while (bytes_received < 0 && errno == EINTR);
577275072Semaste
578275072Semaste    if (bytes_received < 0)
579275072Semaste    {
580275072Semaste        error.SetErrorToErrno();
581275072Semaste        num_bytes = 0;
582275072Semaste    }
583275072Semaste    else
584275072Semaste        num_bytes = bytes_received;
585275072Semaste
586275072Semaste    Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_HOST | LIBLLDB_LOG_COMMUNICATION));
587275072Semaste    if (log)
588275072Semaste    {
589275072Semaste        log->Printf ("%p Socket::Read() (socket = %" PRIu64 ", src = %p, src_len = %" PRIu64 ", flags = 0) => %" PRIi64 " (error = %s)",
590275072Semaste                     static_cast<void*>(this),
591275072Semaste                     static_cast<uint64_t>(m_socket),
592275072Semaste                     buf,
593275072Semaste                     static_cast<uint64_t>(num_bytes),
594275072Semaste                     static_cast<int64_t>(bytes_received),
595275072Semaste                     error.AsCString());
596275072Semaste    }
597275072Semaste
598275072Semaste    return error;
599275072Semaste}
600275072Semaste
601275072SemasteError Socket::Write (const void *buf, size_t &num_bytes)
602275072Semaste{
603275072Semaste    Error error;
604275072Semaste    int bytes_sent = 0;
605275072Semaste    do
606275072Semaste    {
607275072Semaste        if (m_protocol == ProtocolUdp)
608275072Semaste        {
609275072Semaste            bytes_sent = ::sendto (m_socket,
610275072Semaste                                    static_cast<const char*>(buf),
611275072Semaste                                    num_bytes,
612275072Semaste                                    0,
613275072Semaste                                    m_udp_send_sockaddr,
614275072Semaste                                    m_udp_send_sockaddr.GetLength());
615275072Semaste        }
616275072Semaste        else
617275072Semaste            bytes_sent = ::send (m_socket, static_cast<const char *>(buf), num_bytes, 0);
618275072Semaste        // TODO: Use WSAGetLastError on windows.
619275072Semaste    } while (bytes_sent < 0 && errno == EINTR);
620275072Semaste
621275072Semaste    if (bytes_sent < 0)
622275072Semaste    {
623275072Semaste        // TODO: On Windows, use WSAGEtLastError.
624275072Semaste        error.SetErrorToErrno();
625275072Semaste        num_bytes = 0;
626275072Semaste    }
627275072Semaste    else
628275072Semaste        num_bytes = bytes_sent;
629275072Semaste
630275072Semaste    Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_HOST));
631275072Semaste    if (log)
632275072Semaste    {
633275072Semaste        log->Printf ("%p Socket::Write() (socket = %" PRIu64 ", src = %p, src_len = %" PRIu64 ", flags = 0) => %" PRIi64 " (error = %s)",
634275072Semaste                        static_cast<void*>(this),
635275072Semaste                        static_cast<uint64_t>(m_socket),
636275072Semaste                        buf,
637275072Semaste                        static_cast<uint64_t>(num_bytes),
638275072Semaste                        static_cast<int64_t>(bytes_sent),
639275072Semaste                        error.AsCString());
640275072Semaste    }
641275072Semaste
642275072Semaste    return error;
643275072Semaste}
644275072Semaste
645275072SemasteError Socket::PreDisconnect()
646275072Semaste{
647275072Semaste    Error error;
648275072Semaste    return error;
649275072Semaste}
650275072Semaste
651275072SemasteError Socket::Close()
652275072Semaste{
653275072Semaste    Error error;
654275072Semaste    if (!IsValid() || !m_should_close_fd)
655275072Semaste        return error;
656275072Semaste
657275072Semaste    Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_CONNECTION));
658275072Semaste    if (log)
659275072Semaste        log->Printf ("%p Socket::Close (fd = %i)", static_cast<void*>(this), m_socket);
660275072Semaste
661275072Semaste#if defined(_WIN32)
662275072Semaste    bool success = !!closesocket(m_socket);
663275072Semaste#else
664275072Semaste    bool success = !!::close (m_socket);
665275072Semaste#endif
666275072Semaste    // A reference to a FD was passed in, set it to an invalid value
667275072Semaste    m_socket = kInvalidSocketValue;
668275072Semaste    if (!success)
669275072Semaste    {
670275072Semaste        // TODO: On Windows, use WSAGetLastError().
671275072Semaste        error.SetErrorToErrno();
672275072Semaste    }
673275072Semaste
674275072Semaste    return error;
675275072Semaste}
676275072Semaste
677275072Semaste
678275072Semasteint Socket::GetOption(int level, int option_name, int &option_value)
679275072Semaste{
680275072Semaste    get_socket_option_arg_type option_value_p = reinterpret_cast<get_socket_option_arg_type>(&option_value);
681275072Semaste    socklen_t option_value_size = sizeof(int);
682275072Semaste	return ::getsockopt(m_socket, level, option_name, option_value_p, &option_value_size);
683275072Semaste}
684275072Semaste
685275072Semasteint Socket::SetOption(int level, int option_name, int option_value)
686275072Semaste{
687275072Semaste    set_socket_option_arg_type option_value_p = reinterpret_cast<get_socket_option_arg_type>(&option_value);
688275072Semaste	return ::setsockopt(m_socket, level, option_name, option_value_p, sizeof(option_value));
689275072Semaste}
690275072Semaste
691275072Semasteuint16_t Socket::GetPortNumber(const NativeSocket& socket)
692275072Semaste{
693275072Semaste    // We bound to port zero, so we need to figure out which port we actually bound to
694275072Semaste    if (socket >= 0)
695275072Semaste    {
696275072Semaste        SocketAddress sock_addr;
697275072Semaste        socklen_t sock_addr_len = sock_addr.GetMaxLength ();
698275072Semaste        if (::getsockname (socket, sock_addr, &sock_addr_len) == 0)
699275072Semaste            return sock_addr.GetPort ();
700275072Semaste    }
701275072Semaste    return 0;
702275072Semaste}
703275072Semaste
704275072Semaste// Return the port number that is being used by the socket.
705275072Semasteuint16_t Socket::GetPortNumber() const
706275072Semaste{
707275072Semaste    return GetPortNumber(m_socket);
708275072Semaste}
709