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