1 //===-- UDPSocket.cpp -------------------------------------------*- C++ -*-===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #include "lldb/Host/common/UDPSocket.h"
10 
11 #include "lldb/Host/Config.h"
12 #include "lldb/Utility/Log.h"
13 
14 #ifndef LLDB_DISABLE_POSIX
15 #include <arpa/inet.h>
16 #include <sys/socket.h>
17 #endif
18 
19 #include <memory>
20 
21 using namespace lldb;
22 using namespace lldb_private;
23 
24 namespace {
25 
26 const int kDomain = AF_INET;
27 const int kType = SOCK_DGRAM;
28 
29 static const char *g_not_supported_error = "Not supported";
30 }
31 
32 UDPSocket::UDPSocket(NativeSocket socket) : Socket(ProtocolUdp, true, true) {
33   m_socket = socket;
34 }
35 
36 UDPSocket::UDPSocket(bool should_close, bool child_processes_inherit)
37     : Socket(ProtocolUdp, should_close, child_processes_inherit) {}
38 
39 size_t UDPSocket::Send(const void *buf, const size_t num_bytes) {
40   return ::sendto(m_socket, static_cast<const char *>(buf), num_bytes, 0,
41                   m_sockaddr, m_sockaddr.GetLength());
42 }
43 
44 Status UDPSocket::Connect(llvm::StringRef name) {
45   return Status("%s", g_not_supported_error);
46 }
47 
48 Status UDPSocket::Listen(llvm::StringRef name, int backlog) {
49   return Status("%s", g_not_supported_error);
50 }
51 
52 Status UDPSocket::Accept(Socket *&socket) {
53   return Status("%s", g_not_supported_error);
54 }
55 
56 Status UDPSocket::Connect(llvm::StringRef name, bool child_processes_inherit,
57                           Socket *&socket) {
58   std::unique_ptr<UDPSocket> final_socket;
59 
60   Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_CONNECTION));
61   if (log)
62     log->Printf("UDPSocket::%s (host/port = %s)", __FUNCTION__, name.data());
63 
64   Status error;
65   std::string host_str;
66   std::string port_str;
67   int32_t port = INT32_MIN;
68   if (!DecodeHostAndPort(name, host_str, port_str, port, &error))
69     return error;
70 
71   // At this point we have setup the receive port, now we need to setup the UDP
72   // send socket
73 
74   struct addrinfo hints;
75   struct addrinfo *service_info_list = nullptr;
76 
77   ::memset(&hints, 0, sizeof(hints));
78   hints.ai_family = kDomain;
79   hints.ai_socktype = kType;
80   int err = ::getaddrinfo(host_str.c_str(), port_str.c_str(), &hints,
81                           &service_info_list);
82   if (err != 0) {
83     error.SetErrorStringWithFormat(
84 #if defined(_MSC_VER) && defined(UNICODE)
85         "getaddrinfo(%s, %s, &hints, &info) returned error %i (%S)",
86 #else
87         "getaddrinfo(%s, %s, &hints, &info) returned error %i (%s)",
88 #endif
89         host_str.c_str(), port_str.c_str(), err, gai_strerror(err));
90     return error;
91   }
92 
93   for (struct addrinfo *service_info_ptr = service_info_list;
94        service_info_ptr != nullptr;
95        service_info_ptr = service_info_ptr->ai_next) {
96     auto send_fd = CreateSocket(
97         service_info_ptr->ai_family, service_info_ptr->ai_socktype,
98         service_info_ptr->ai_protocol, child_processes_inherit, error);
99     if (error.Success()) {
100       final_socket.reset(new UDPSocket(send_fd));
101       final_socket->m_sockaddr = service_info_ptr;
102       break;
103     } else
104       continue;
105   }
106 
107   ::freeaddrinfo(service_info_list);
108 
109   if (!final_socket)
110     return error;
111 
112   SocketAddress bind_addr;
113 
114   // Only bind to the loopback address if we are expecting a connection from
115   // localhost to avoid any firewall issues.
116   const bool bind_addr_success = (host_str == "127.0.0.1" || host_str == "localhost")
117                                      ? bind_addr.SetToLocalhost(kDomain, port)
118                                      : bind_addr.SetToAnyAddress(kDomain, port);
119 
120   if (!bind_addr_success) {
121     error.SetErrorString("Failed to get hostspec to bind for");
122     return error;
123   }
124 
125   bind_addr.SetPort(0); // Let the source port # be determined dynamically
126 
127   err = ::bind(final_socket->GetNativeSocket(), bind_addr, bind_addr.GetLength());
128 
129   struct sockaddr_in source_info;
130   socklen_t address_len = sizeof (struct sockaddr_in);
131   err = ::getsockname(final_socket->GetNativeSocket(), (struct sockaddr *) &source_info, &address_len);
132 
133   socket = final_socket.release();
134   error.Clear();
135   return error;
136 }
137 
138 std::string UDPSocket::GetRemoteConnectionURI() const {
139   if (m_socket != kInvalidSocketValue) {
140     return llvm::formatv("udp://[{0}]:{1}", m_sockaddr.GetIPAddress(),
141                          m_sockaddr.GetPort());
142   }
143   return "";
144 }
145