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/Host.h"
16 #include "lldb/Host/SocketAddress.h"
17 #include "lldb/Host/StringConvert.h"
18 #include "lldb/Host/TimeValue.h"
19 #include "lldb/Host/common/TCPSocket.h"
20 #include "lldb/Host/common/UDPSocket.h"
21 
22 #ifndef LLDB_DISABLE_POSIX
23 #include "lldb/Host/posix/DomainSocket.h"
24 
25 #include <arpa/inet.h>
26 #include <netdb.h>
27 #include <netinet/in.h>
28 #include <netinet/tcp.h>
29 #include <sys/socket.h>
30 #include <sys/un.h>
31 #endif
32 
33 #ifdef __linux__
34 #include "lldb/Host/linux/AbstractSocket.h"
35 #endif
36 
37 #ifdef __ANDROID_NDK__
38 #include <linux/tcp.h>
39 #include <bits/error_constants.h>
40 #include <asm-generic/errno-base.h>
41 #include <errno.h>
42 #include <arpa/inet.h>
43 #if defined(ANDROID_ARM_BUILD_STATIC) || defined(ANDROID_MIPS_BUILD_STATIC)
44 #include <unistd.h>
45 #include <sys/syscall.h>
46 #include <fcntl.h>
47 #endif // ANDROID_ARM_BUILD_STATIC || ANDROID_MIPS_BUILD_STATIC
48 #endif // __ANDROID_NDK__
49 
50 using namespace lldb;
51 using namespace lldb_private;
52 
53 #if defined(_WIN32)
54 typedef const char * set_socket_option_arg_type;
55 typedef char * get_socket_option_arg_type;
56 const NativeSocket Socket::kInvalidSocketValue = INVALID_SOCKET;
57 #else // #if defined(_WIN32)
58 typedef const void * set_socket_option_arg_type;
59 typedef void * get_socket_option_arg_type;
60 const NativeSocket Socket::kInvalidSocketValue = -1;
61 #endif // #if defined(_WIN32)
62 
63 namespace {
64 
65 bool IsInterrupted()
66 {
67 #if defined(_WIN32)
68     return ::WSAGetLastError() == WSAEINTR;
69 #else
70     return errno == EINTR;
71 #endif
72 }
73 
74 }
75 
76 Socket::Socket(NativeSocket socket, SocketProtocol protocol, bool should_close)
77     : IOObject(eFDTypeSocket, should_close)
78     , m_protocol(protocol)
79     , m_socket(socket)
80 {
81 
82 }
83 
84 Socket::~Socket()
85 {
86     Close();
87 }
88 
89 std::unique_ptr<Socket> Socket::Create(const SocketProtocol protocol, bool child_processes_inherit, Error &error)
90 {
91     error.Clear();
92 
93     std::unique_ptr<Socket> socket_up;
94     switch (protocol)
95     {
96     case ProtocolTcp:
97         socket_up.reset(new TCPSocket(child_processes_inherit, error));
98         break;
99     case ProtocolUdp:
100         socket_up.reset(new UDPSocket(child_processes_inherit, error));
101         break;
102     case ProtocolUnixDomain:
103 #ifndef LLDB_DISABLE_POSIX
104         socket_up.reset(new DomainSocket(child_processes_inherit, error));
105 #else
106         error.SetErrorString("Unix domain sockets are not supported on this platform.");
107 #endif
108         break;
109     case ProtocolUnixAbstract:
110 #ifdef __linux__
111         socket_up.reset(new AbstractSocket(child_processes_inherit, error));
112 #else
113         error.SetErrorString("Abstract domain sockets are not supported on this platform.");
114 #endif
115         break;
116     }
117 
118     if (error.Fail())
119         socket_up.reset();
120 
121     return socket_up;
122 }
123 
124 Error Socket::TcpConnect(llvm::StringRef host_and_port, bool child_processes_inherit, Socket *&socket)
125 {
126     Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_COMMUNICATION));
127     if (log)
128         log->Printf ("Socket::%s (host/port = %s)", __FUNCTION__, host_and_port.data());
129 
130     Error error;
131     std::unique_ptr<Socket> connect_socket(Create(ProtocolTcp, child_processes_inherit, error));
132     if (error.Fail())
133         return error;
134 
135     error = connect_socket->Connect(host_and_port);
136     if (error.Success())
137       socket = connect_socket.release();
138 
139     return error;
140 }
141 
142 Error
143 Socket::TcpListen (llvm::StringRef host_and_port,
144                    bool child_processes_inherit,
145                    Socket *&socket,
146                    Predicate<uint16_t>* predicate,
147                    int backlog)
148 {
149     Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_CONNECTION));
150     if (log)
151         log->Printf ("Socket::%s (%s)", __FUNCTION__, host_and_port.data());
152 
153     Error error;
154     std::string host_str;
155     std::string port_str;
156     int32_t port = INT32_MIN;
157     if (!DecodeHostAndPort (host_and_port, host_str, port_str, port, &error))
158         return error;
159 
160     std::unique_ptr<TCPSocket> listen_socket(new TCPSocket(child_processes_inherit, error));
161     if (error.Fail())
162         return error;
163 
164     error = listen_socket->Listen(host_and_port, backlog);
165     if (error.Success())
166     {
167         // We were asked to listen on port zero which means we
168         // must now read the actual port that was given to us
169         // as port zero is a special code for "find an open port
170         // for me".
171         if (port == 0)
172             port = listen_socket->GetLocalPortNumber();
173 
174         // Set the port predicate since when doing a listen://<host>:<port>
175         // it often needs to accept the incoming connection which is a blocking
176         // system call. Allowing access to the bound port using a predicate allows
177         // us to wait for the port predicate to be set to a non-zero value from
178         // another thread in an efficient manor.
179         if (predicate)
180             predicate->SetValue (port, eBroadcastAlways);
181         socket = listen_socket.release();
182     }
183 
184     return error;
185 }
186 
187 Error Socket::UdpConnect(llvm::StringRef host_and_port, bool child_processes_inherit, Socket *&send_socket, Socket *&recv_socket)
188 {
189     Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_CONNECTION));
190     if (log)
191         log->Printf ("Socket::%s (host/port = %s)", __FUNCTION__, host_and_port.data());
192 
193     return UDPSocket::Connect(host_and_port, child_processes_inherit, send_socket, recv_socket);
194 }
195 
196 Error Socket::UnixDomainConnect(llvm::StringRef name, bool child_processes_inherit, Socket *&socket)
197 {
198     Error error;
199     std::unique_ptr<Socket> connect_socket(Create(ProtocolUnixDomain, child_processes_inherit, error));
200     if (error.Fail())
201         return error;
202 
203     error = connect_socket->Connect(name);
204     if (error.Success())
205       socket = connect_socket.release();
206 
207     return error;
208 }
209 
210 Error Socket::UnixDomainAccept(llvm::StringRef name, bool child_processes_inherit, Socket *&socket)
211 {
212     Error error;
213     std::unique_ptr<Socket> listen_socket(Create(ProtocolUnixDomain, child_processes_inherit, error));
214     if (error.Fail())
215         return error;
216 
217     error = listen_socket->Listen(name, 5);
218     if (error.Fail())
219         return error;
220 
221     error = listen_socket->Accept(name, child_processes_inherit, socket);
222     return error;
223 }
224 
225 Error
226 Socket::UnixAbstractConnect(llvm::StringRef name, bool child_processes_inherit, Socket *&socket)
227 {
228     Error error;
229     std::unique_ptr<Socket> connect_socket(Create(ProtocolUnixAbstract, child_processes_inherit, error));
230     if (error.Fail())
231         return error;
232 
233     error = connect_socket->Connect(name);
234     if (error.Success())
235       socket = connect_socket.release();
236     return error;
237 }
238 
239 Error
240 Socket::UnixAbstractAccept(llvm::StringRef name, bool child_processes_inherit, Socket *&socket)
241 {
242     Error error;
243     std::unique_ptr<Socket> listen_socket(Create(ProtocolUnixAbstract,child_processes_inherit, error));
244     if (error.Fail())
245         return error;
246 
247     error = listen_socket->Listen(name, 5);
248     if (error.Fail())
249         return error;
250 
251     error = listen_socket->Accept(name, child_processes_inherit, socket);
252     return error;
253 }
254 
255 bool
256 Socket::DecodeHostAndPort(llvm::StringRef host_and_port,
257                           std::string &host_str,
258                           std::string &port_str,
259                           int32_t& port,
260                           Error *error_ptr)
261 {
262     static RegularExpression g_regex ("([^:]+):([0-9]+)");
263     RegularExpression::Match regex_match(2);
264     if (g_regex.Execute (host_and_port.data(), &regex_match))
265     {
266         if (regex_match.GetMatchAtIndex (host_and_port.data(), 1, host_str) &&
267             regex_match.GetMatchAtIndex (host_and_port.data(), 2, port_str))
268         {
269             bool ok = false;
270             port = StringConvert::ToUInt32 (port_str.c_str(), UINT32_MAX, 10, &ok);
271             if (ok && port <= UINT16_MAX)
272             {
273                 if (error_ptr)
274                     error_ptr->Clear();
275                 return true;
276             }
277             // port is too large
278             if (error_ptr)
279                 error_ptr->SetErrorStringWithFormat("invalid host:port specification: '%s'", host_and_port.data());
280             return false;
281         }
282     }
283 
284     // If this was unsuccessful, then check if it's simply a signed 32-bit integer, representing
285     // a port with an empty host.
286     host_str.clear();
287     port_str.clear();
288     bool ok = false;
289     port = StringConvert::ToUInt32 (host_and_port.data(), UINT32_MAX, 10, &ok);
290     if (ok && port < UINT16_MAX)
291     {
292         port_str = host_and_port;
293         if (error_ptr)
294             error_ptr->Clear();
295         return true;
296     }
297 
298     if (error_ptr)
299         error_ptr->SetErrorStringWithFormat("invalid host:port specification: '%s'", host_and_port.data());
300     return false;
301 }
302 
303 IOObject::WaitableHandle Socket::GetWaitableHandle()
304 {
305     // TODO: On Windows, use WSAEventSelect
306     return m_socket;
307 }
308 
309 Error Socket::Read (void *buf, size_t &num_bytes)
310 {
311     Error error;
312     int bytes_received = 0;
313     do
314     {
315         bytes_received = ::recv (m_socket, static_cast<char *>(buf), num_bytes, 0);
316     } while (bytes_received < 0 && IsInterrupted ());
317 
318     if (bytes_received < 0)
319     {
320         SetLastError (error);
321         num_bytes = 0;
322     }
323     else
324         num_bytes = bytes_received;
325 
326     Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_COMMUNICATION));
327     if (log)
328     {
329         log->Printf ("%p Socket::Read() (socket = %" PRIu64 ", src = %p, src_len = %" PRIu64 ", flags = 0) => %" PRIi64 " (error = %s)",
330                      static_cast<void*>(this),
331                      static_cast<uint64_t>(m_socket),
332                      buf,
333                      static_cast<uint64_t>(num_bytes),
334                      static_cast<int64_t>(bytes_received),
335                      error.AsCString());
336     }
337 
338     return error;
339 }
340 
341 Error Socket::Write (const void *buf, size_t &num_bytes)
342 {
343     Error error;
344     int bytes_sent = 0;
345     do
346     {
347         bytes_sent = Send(buf, num_bytes);
348     } while (bytes_sent < 0 && IsInterrupted ());
349 
350     if (bytes_sent < 0)
351     {
352         SetLastError (error);
353         num_bytes = 0;
354     }
355     else
356         num_bytes = bytes_sent;
357 
358     Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_COMMUNICATION));
359     if (log)
360     {
361         log->Printf ("%p Socket::Write() (socket = %" PRIu64 ", src = %p, src_len = %" PRIu64 ", flags = 0) => %" PRIi64 " (error = %s)",
362                         static_cast<void*>(this),
363                         static_cast<uint64_t>(m_socket),
364                         buf,
365                         static_cast<uint64_t>(num_bytes),
366                         static_cast<int64_t>(bytes_sent),
367                         error.AsCString());
368     }
369 
370     return error;
371 }
372 
373 Error Socket::PreDisconnect()
374 {
375     Error error;
376     return error;
377 }
378 
379 Error Socket::Close()
380 {
381     Error error;
382     if (!IsValid() || !m_should_close_fd)
383         return error;
384 
385     Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_CONNECTION));
386     if (log)
387         log->Printf ("%p Socket::Close (fd = %i)", static_cast<void*>(this), m_socket);
388 
389 #if defined(_WIN32)
390     bool success = !!closesocket(m_socket);
391 #else
392     bool success = !!::close (m_socket);
393 #endif
394     // A reference to a FD was passed in, set it to an invalid value
395     m_socket = kInvalidSocketValue;
396     if (!success)
397     {
398         SetLastError (error);
399     }
400 
401     return error;
402 }
403 
404 
405 int Socket::GetOption(int level, int option_name, int &option_value)
406 {
407     get_socket_option_arg_type option_value_p = reinterpret_cast<get_socket_option_arg_type>(&option_value);
408     socklen_t option_value_size = sizeof(int);
409     return ::getsockopt(m_socket, level, option_name, option_value_p, &option_value_size);
410 }
411 
412 int Socket::SetOption(int level, int option_name, int option_value)
413 {
414     set_socket_option_arg_type option_value_p = reinterpret_cast<get_socket_option_arg_type>(&option_value);
415     return ::setsockopt(m_socket, level, option_name, option_value_p, sizeof(option_value));
416 }
417 
418 size_t Socket::Send(const void *buf, const size_t num_bytes)
419 {
420     return ::send (m_socket, static_cast<const char *>(buf), num_bytes, 0);
421 }
422 
423 void Socket::SetLastError(Error &error)
424 {
425 #if defined(_WIN32)
426     error.SetError(::WSAGetLastError(), lldb::eErrorTypeWin32);
427 #else
428     error.SetErrorToErrno();
429 #endif
430 }
431 
432 NativeSocket
433 Socket::CreateSocket(const int domain,
434                      const int type,
435                      const int protocol,
436                      bool child_processes_inherit,
437                      Error& error)
438 {
439     error.Clear();
440     auto socketType = type;
441 #ifdef SOCK_CLOEXEC
442     if (!child_processes_inherit)
443         socketType |= SOCK_CLOEXEC;
444 #endif
445     auto sock = ::socket (domain, socketType, protocol);
446     if (sock == kInvalidSocketValue)
447         SetLastError(error);
448 
449     return sock;
450 }
451 
452 NativeSocket
453 Socket::AcceptSocket(NativeSocket sockfd,
454                      struct sockaddr *addr,
455                      socklen_t *addrlen,
456                      bool child_processes_inherit,
457                      Error& error)
458 {
459     error.Clear();
460 #if defined(ANDROID_ARM_BUILD_STATIC) || defined(ANDROID_MIPS_BUILD_STATIC)
461     // Temporary workaround for statically linking Android lldb-server with the
462     // latest API.
463     int fd = syscall(__NR_accept, sockfd, addr, addrlen);
464     if (fd >= 0 && !child_processes_inherit)
465     {
466         int flags = ::fcntl(fd, F_GETFD);
467         if (flags != -1 && ::fcntl(fd, F_SETFD, flags | FD_CLOEXEC) != -1)
468             return fd;
469         SetLastError(error);
470         close(fd);
471     }
472     return fd;
473 #elif defined(SOCK_CLOEXEC)
474     int flags = 0;
475     if (!child_processes_inherit) {
476         flags |= SOCK_CLOEXEC;
477     }
478 #if defined(__NetBSD__)
479     NativeSocket fd = ::paccept (sockfd, addr, addrlen, nullptr, flags);
480 #else
481     NativeSocket fd = ::accept4 (sockfd, addr, addrlen, flags);
482 #endif
483 #else
484     NativeSocket fd = ::accept (sockfd, addr, addrlen);
485 #endif
486     if (fd == kInvalidSocketValue)
487         SetLastError(error);
488     return fd;
489 }
490