180814287SRaphael Isemann //===-- UDPSocket.cpp -----------------------------------------------------===//
2e98628ceSOleksiy Vyalov //
32946cd70SChandler Carruth // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
42946cd70SChandler Carruth // See https://llvm.org/LICENSE.txt for license information.
52946cd70SChandler Carruth // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6e98628ceSOleksiy Vyalov //
7e98628ceSOleksiy Vyalov //===----------------------------------------------------------------------===//
8e98628ceSOleksiy Vyalov 
9e98628ceSOleksiy Vyalov #include "lldb/Host/common/UDPSocket.h"
10e98628ceSOleksiy Vyalov 
11e98628ceSOleksiy Vyalov #include "lldb/Host/Config.h"
12*c34698a8SPavel Labath #include "lldb/Utility/LLDBLog.h"
136f9e6901SZachary Turner #include "lldb/Utility/Log.h"
14e98628ceSOleksiy Vyalov 
153011d55fSJonas Devlieghere #if LLDB_ENABLE_POSIX
16e98628ceSOleksiy Vyalov #include <arpa/inet.h>
17e98628ceSOleksiy Vyalov #include <sys/socket.h>
18e98628ceSOleksiy Vyalov #endif
19e98628ceSOleksiy Vyalov 
20e98628ceSOleksiy Vyalov #include <memory>
21e98628ceSOleksiy Vyalov 
22e98628ceSOleksiy Vyalov using namespace lldb;
23e98628ceSOleksiy Vyalov using namespace lldb_private;
24e98628ceSOleksiy Vyalov 
2593c1b3caSPavel Labath static const int kDomain = AF_INET;
2693c1b3caSPavel Labath static const int kType = SOCK_DGRAM;
27e98628ceSOleksiy Vyalov 
2859dd7fd1SJim Ingham static const char *g_not_supported_error = "Not supported";
298d0c7fafSChris Bieneman 
UDPSocket(NativeSocket socket)308d0c7fafSChris Bieneman UDPSocket::UDPSocket(NativeSocket socket) : Socket(ProtocolUdp, true, true) {
318d0c7fafSChris Bieneman   m_socket = socket;
328d0c7fafSChris Bieneman }
3311827799SChris Bieneman 
UDPSocket(bool should_close,bool child_processes_inherit)3411827799SChris Bieneman UDPSocket::UDPSocket(bool should_close, bool child_processes_inherit)
3511827799SChris Bieneman     : Socket(ProtocolUdp, should_close, child_processes_inherit) {}
3611827799SChris Bieneman 
Send(const void * buf,const size_t num_bytes)37b9c1b51eSKate Stone size_t UDPSocket::Send(const void *buf, const size_t num_bytes) {
38b9c1b51eSKate Stone   return ::sendto(m_socket, static_cast<const char *>(buf), num_bytes, 0,
3990dce06fSJason Molenda                   m_sockaddr, m_sockaddr.GetLength());
40e98628ceSOleksiy Vyalov }
41e98628ceSOleksiy Vyalov 
Connect(llvm::StringRef name)4297206d57SZachary Turner Status UDPSocket::Connect(llvm::StringRef name) {
4397206d57SZachary Turner   return Status("%s", g_not_supported_error);
448d0c7fafSChris Bieneman }
458d0c7fafSChris Bieneman 
Listen(llvm::StringRef name,int backlog)4697206d57SZachary Turner Status UDPSocket::Listen(llvm::StringRef name, int backlog) {
4797206d57SZachary Turner   return Status("%s", g_not_supported_error);
488d0c7fafSChris Bieneman }
498d0c7fafSChris Bieneman 
Accept(Socket * & socket)5097206d57SZachary Turner Status UDPSocket::Accept(Socket *&socket) {
5197206d57SZachary Turner   return Status("%s", g_not_supported_error);
528d0c7fafSChris Bieneman }
538d0c7fafSChris Bieneman 
54c9e6b701SPavel Labath llvm::Expected<std::unique_ptr<UDPSocket>>
Connect(llvm::StringRef name,bool child_processes_inherit)55c9e6b701SPavel Labath UDPSocket::Connect(llvm::StringRef name, bool child_processes_inherit) {
56c9e6b701SPavel Labath   std::unique_ptr<UDPSocket> socket;
578d0c7fafSChris Bieneman 
58a007a6d8SPavel Labath   Log *log = GetLog(LLDBLog::Connection);
59c9e6b701SPavel Labath   LLDB_LOG(log, "host/port = {0}", name);
60e98628ceSOleksiy Vyalov 
6197206d57SZachary Turner   Status error;
62073c5d0eSMichał Górny   llvm::Expected<HostAndPort> host_port = DecodeHostAndPort(name);
63073c5d0eSMichał Górny   if (!host_port)
64073c5d0eSMichał Górny     return host_port.takeError();
65e98628ceSOleksiy Vyalov 
6605097246SAdrian Prantl   // At this point we have setup the receive port, now we need to setup the UDP
6705097246SAdrian Prantl   // send socket
68e98628ceSOleksiy Vyalov 
69e98628ceSOleksiy Vyalov   struct addrinfo hints;
70e98628ceSOleksiy Vyalov   struct addrinfo *service_info_list = nullptr;
71e98628ceSOleksiy Vyalov 
72e98628ceSOleksiy Vyalov   ::memset(&hints, 0, sizeof(hints));
73e98628ceSOleksiy Vyalov   hints.ai_family = kDomain;
74e98628ceSOleksiy Vyalov   hints.ai_socktype = kType;
75073c5d0eSMichał Górny   int err = ::getaddrinfo(host_port->hostname.c_str(), std::to_string(host_port->port).c_str(), &hints,
76b9c1b51eSKate Stone                           &service_info_list);
77b9c1b51eSKate Stone   if (err != 0) {
78b9c1b51eSKate Stone     error.SetErrorStringWithFormat(
798b98f12aSMartin Storsjo #if defined(_WIN32) && defined(UNICODE)
80073c5d0eSMichał Górny         "getaddrinfo(%s, %d, &hints, &info) returned error %i (%S)",
815a8ad459SZachary Turner #else
82073c5d0eSMichał Górny         "getaddrinfo(%s, %d, &hints, &info) returned error %i (%s)",
835a8ad459SZachary Turner #endif
84073c5d0eSMichał Górny         host_port->hostname.c_str(), host_port->port, err, gai_strerror(err));
85c9e6b701SPavel Labath     return error.ToError();
86e98628ceSOleksiy Vyalov   }
87e98628ceSOleksiy Vyalov 
88e98628ceSOleksiy Vyalov   for (struct addrinfo *service_info_ptr = service_info_list;
89e98628ceSOleksiy Vyalov        service_info_ptr != nullptr;
90b9c1b51eSKate Stone        service_info_ptr = service_info_ptr->ai_next) {
918d0c7fafSChris Bieneman     auto send_fd = CreateSocket(
92b9c1b51eSKate Stone         service_info_ptr->ai_family, service_info_ptr->ai_socktype,
938d0c7fafSChris Bieneman         service_info_ptr->ai_protocol, child_processes_inherit, error);
94b9c1b51eSKate Stone     if (error.Success()) {
95c9e6b701SPavel Labath       socket.reset(new UDPSocket(send_fd));
96c9e6b701SPavel Labath       socket->m_sockaddr = service_info_ptr;
97e98628ceSOleksiy Vyalov       break;
98b9c1b51eSKate Stone     } else
99e98628ceSOleksiy Vyalov       continue;
100e98628ceSOleksiy Vyalov   }
101e98628ceSOleksiy Vyalov 
102e98628ceSOleksiy Vyalov   ::freeaddrinfo(service_info_list);
103e98628ceSOleksiy Vyalov 
104c9e6b701SPavel Labath   if (!socket)
105c9e6b701SPavel Labath     return error.ToError();
106e98628ceSOleksiy Vyalov 
10790dce06fSJason Molenda   SocketAddress bind_addr;
10890dce06fSJason Molenda 
10990dce06fSJason Molenda   // Only bind to the loopback address if we are expecting a connection from
11090dce06fSJason Molenda   // localhost to avoid any firewall issues.
111073c5d0eSMichał Górny   const bool bind_addr_success = (host_port->hostname == "127.0.0.1" || host_port->hostname == "localhost")
112073c5d0eSMichał Górny                                      ? bind_addr.SetToLocalhost(kDomain, host_port->port)
113073c5d0eSMichał Górny                                      : bind_addr.SetToAnyAddress(kDomain, host_port->port);
11490dce06fSJason Molenda 
11590dce06fSJason Molenda   if (!bind_addr_success) {
11690dce06fSJason Molenda     error.SetErrorString("Failed to get hostspec to bind for");
117c9e6b701SPavel Labath     return error.ToError();
11890dce06fSJason Molenda   }
11990dce06fSJason Molenda 
12090dce06fSJason Molenda   bind_addr.SetPort(0); // Let the source port # be determined dynamically
12190dce06fSJason Molenda 
122c9e6b701SPavel Labath   err = ::bind(socket->GetNativeSocket(), bind_addr, bind_addr.GetLength());
12390dce06fSJason Molenda 
1248d0c7fafSChris Bieneman   struct sockaddr_in source_info;
1258d0c7fafSChris Bieneman   socklen_t address_len = sizeof (struct sockaddr_in);
126c9e6b701SPavel Labath   err = ::getsockname(socket->GetNativeSocket(),
127c9e6b701SPavel Labath                       (struct sockaddr *)&source_info, &address_len);
12811827799SChris Bieneman 
129c9e6b701SPavel Labath   return std::move(socket);
13011827799SChris Bieneman }
131d5560951SAntonio Afonso 
GetRemoteConnectionURI() const132d5560951SAntonio Afonso std::string UDPSocket::GetRemoteConnectionURI() const {
133d5560951SAntonio Afonso   if (m_socket != kInvalidSocketValue) {
134adcd0268SBenjamin Kramer     return std::string(llvm::formatv(
135adcd0268SBenjamin Kramer         "udp://[{0}]:{1}", m_sockaddr.GetIPAddress(), m_sockaddr.GetPort()));
136d5560951SAntonio Afonso   }
137d5560951SAntonio Afonso   return "";
138d5560951SAntonio Afonso }
139