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