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