1//===-- Socket.cpp --------------------------------------------------------===//
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/Socket.h"
10
11#include "lldb/Host/Config.h"
12#include "lldb/Host/Host.h"
13#include "lldb/Host/MainLoop.h"
14#include "lldb/Host/SocketAddress.h"
15#include "lldb/Host/common/TCPSocket.h"
16#include "lldb/Host/common/UDPSocket.h"
17#include "lldb/Utility/LLDBLog.h"
18#include "lldb/Utility/Log.h"
19
20#include "llvm/ADT/STLExtras.h"
21#include "llvm/ADT/StringExtras.h"
22#include "llvm/Support/Errno.h"
23#include "llvm/Support/Error.h"
24#include "llvm/Support/Regex.h"
25#include "llvm/Support/WindowsError.h"
26
27#if LLDB_ENABLE_POSIX
28#include "lldb/Host/posix/DomainSocket.h"
29
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#include <unistd.h>
37#endif
38
39#ifdef __linux__
40#include "lldb/Host/linux/AbstractSocket.h"
41#endif
42
43using namespace lldb;
44using namespace lldb_private;
45
46#if defined(_WIN32)
47typedef const char *set_socket_option_arg_type;
48typedef char *get_socket_option_arg_type;
49const NativeSocket Socket::kInvalidSocketValue = INVALID_SOCKET;
50const shared_fd_t SharedSocket::kInvalidFD = LLDB_INVALID_PIPE;
51#else // #if defined(_WIN32)
52typedef const void *set_socket_option_arg_type;
53typedef void *get_socket_option_arg_type;
54const NativeSocket Socket::kInvalidSocketValue = -1;
55const shared_fd_t SharedSocket::kInvalidFD = Socket::kInvalidSocketValue;
56#endif // #if defined(_WIN32)
57
58static bool IsInterrupted() {
59#if defined(_WIN32)
60 return ::WSAGetLastError() == WSAEINTR;
61#else
62 return errno == EINTR;
63#endif
64}
65
66SharedSocket::SharedSocket(const Socket *socket, Status &error) {
67#ifdef _WIN32
68 m_socket = socket->GetNativeSocket();
69 m_fd = kInvalidFD;
70
71 // Create a pipe to transfer WSAPROTOCOL_INFO to the child process.
72 error = m_socket_pipe.CreateNew(true);
73 if (error.Fail())
74 return;
75
76 m_fd = m_socket_pipe.GetReadPipe();
77#else
78 m_fd = socket->GetNativeSocket();
79 error = Status();
80#endif
81}
82
83Status SharedSocket::CompleteSending(lldb::pid_t child_pid) {
84#ifdef _WIN32
85 // Transfer WSAPROTOCOL_INFO to the child process.
86 m_socket_pipe.CloseReadFileDescriptor();
87
88 WSAPROTOCOL_INFO protocol_info;
89 if (::WSADuplicateSocket(m_socket, child_pid, &protocol_info) ==
90 SOCKET_ERROR) {
91 int last_error = ::WSAGetLastError();
92 return Status::FromErrorStringWithFormat(
93 "WSADuplicateSocket() failed, error: %d", last_error);
94 }
95
96 llvm::Expected<size_t> num_bytes = m_socket_pipe.Write(
97 &protocol_info, sizeof(protocol_info), std::chrono::seconds(10));
98 if (!num_bytes)
99 return Status::FromError(num_bytes.takeError());
100 if (*num_bytes != sizeof(protocol_info))
101 return Status::FromErrorStringWithFormatv(
102 "Write(WSAPROTOCOL_INFO) failed: wrote {0}/{1} bytes", *num_bytes,
103 sizeof(protocol_info));
104#endif
105 return Status();
106}
107
108Status SharedSocket::GetNativeSocket(shared_fd_t fd, NativeSocket &socket) {
109#ifdef _WIN32
110 socket = Socket::kInvalidSocketValue;
111 // Read WSAPROTOCOL_INFO from the parent process and create NativeSocket.
112 WSAPROTOCOL_INFO protocol_info;
113 {
114 Pipe socket_pipe(fd, LLDB_INVALID_PIPE);
115 llvm::Expected<size_t> num_bytes = socket_pipe.Read(
116 &protocol_info, sizeof(protocol_info), std::chrono::seconds(10));
117 if (!num_bytes)
118 return Status::FromError(num_bytes.takeError());
119 if (*num_bytes != sizeof(protocol_info)) {
120 return Status::FromErrorStringWithFormatv(
121 "Read(WSAPROTOCOL_INFO) failed: read {0}/{1} bytes", *num_bytes,
122 sizeof(protocol_info));
123 }
124 }
125 socket = ::WSASocket(FROM_PROTOCOL_INFO, FROM_PROTOCOL_INFO,
126 FROM_PROTOCOL_INFO, &protocol_info, 0, 0);
127 if (socket == INVALID_SOCKET) {
128 return Status::FromErrorStringWithFormatv(
129 "WSASocket(FROM_PROTOCOL_INFO) failed: error {0}", ::WSAGetLastError());
130 }
131 return Status();
132#else
133 socket = fd;
134 return Status();
135#endif
136}
137
138struct SocketScheme {
139 const char *m_scheme;
140 const Socket::SocketProtocol m_protocol;
141};
142
143static SocketScheme socket_schemes[] = {
144 {.m_scheme: "tcp", .m_protocol: Socket::ProtocolTcp},
145 {.m_scheme: "udp", .m_protocol: Socket::ProtocolUdp},
146 {.m_scheme: "unix", .m_protocol: Socket::ProtocolUnixDomain},
147 {.m_scheme: "unix-abstract", .m_protocol: Socket::ProtocolUnixAbstract},
148};
149
150const char *
151Socket::FindSchemeByProtocol(const Socket::SocketProtocol protocol) {
152 for (auto s : socket_schemes) {
153 if (s.m_protocol == protocol)
154 return s.m_scheme;
155 }
156 return nullptr;
157}
158
159bool Socket::FindProtocolByScheme(const char *scheme,
160 Socket::SocketProtocol &protocol) {
161 for (auto s : socket_schemes) {
162 if (!strcmp(s1: s.m_scheme, s2: scheme)) {
163 protocol = s.m_protocol;
164 return true;
165 }
166 }
167 return false;
168}
169
170Socket::Socket(SocketProtocol protocol, bool should_close)
171 : IOObject(eFDTypeSocket), m_protocol(protocol),
172 m_socket(kInvalidSocketValue), m_should_close_fd(should_close) {}
173
174Socket::~Socket() { Close(); }
175
176llvm::Error Socket::Initialize() {
177#if defined(_WIN32)
178 auto wVersion = WINSOCK_VERSION;
179 WSADATA wsaData;
180 int err = ::WSAStartup(wVersion, &wsaData);
181 if (err == 0) {
182 if (wsaData.wVersion < wVersion) {
183 WSACleanup();
184 return llvm::createStringError("WSASock version is not expected.");
185 }
186 } else {
187 return llvm::errorCodeToError(llvm::mapWindowsError(::WSAGetLastError()));
188 }
189#endif
190
191 return llvm::Error::success();
192}
193
194void Socket::Terminate() {
195#if defined(_WIN32)
196 ::WSACleanup();
197#endif
198}
199
200std::unique_ptr<Socket> Socket::Create(const SocketProtocol protocol,
201 Status &error) {
202 error.Clear();
203
204 const bool should_close = true;
205 std::unique_ptr<Socket> socket_up;
206 switch (protocol) {
207 case ProtocolTcp:
208 socket_up = std::make_unique<TCPSocket>(args: should_close);
209 break;
210 case ProtocolUdp:
211 socket_up = std::make_unique<UDPSocket>(args: should_close);
212 break;
213 case ProtocolUnixDomain:
214#if LLDB_ENABLE_POSIX
215 socket_up = std::make_unique<DomainSocket>(args: should_close);
216#else
217 error = Status::FromErrorString(
218 "Unix domain sockets are not supported on this platform.");
219#endif
220 break;
221 case ProtocolUnixAbstract:
222#ifdef __linux__
223 socket_up = std::make_unique<AbstractSocket>();
224#else
225 error = Status::FromErrorString(
226 "Abstract domain sockets are not supported on this platform.");
227#endif
228 break;
229 }
230
231 if (error.Fail())
232 socket_up.reset();
233
234 return socket_up;
235}
236
237llvm::Expected<std::unique_ptr<Socket>>
238Socket::TcpConnect(llvm::StringRef host_and_port) {
239 Log *log = GetLog(mask: LLDBLog::Connection);
240 LLDB_LOG(log, "host_and_port = {0}", host_and_port);
241
242 Status error;
243 std::unique_ptr<Socket> connect_socket = Create(protocol: ProtocolTcp, error);
244 if (error.Fail())
245 return error.ToError();
246
247 error = connect_socket->Connect(name: host_and_port);
248 if (error.Success())
249 return std::move(connect_socket);
250
251 return error.ToError();
252}
253
254llvm::Expected<std::unique_ptr<TCPSocket>>
255Socket::TcpListen(llvm::StringRef host_and_port, int backlog) {
256 Log *log = GetLog(mask: LLDBLog::Connection);
257 LLDB_LOG(log, "host_and_port = {0}", host_and_port);
258
259 std::unique_ptr<TCPSocket> listen_socket(
260 new TCPSocket(/*should_close=*/true));
261
262 Status error = listen_socket->Listen(name: host_and_port, backlog);
263 if (error.Fail())
264 return error.ToError();
265
266 return std::move(listen_socket);
267}
268
269llvm::Expected<std::unique_ptr<UDPSocket>>
270Socket::UdpConnect(llvm::StringRef host_and_port) {
271 return UDPSocket::CreateConnected(name: host_and_port);
272}
273
274llvm::Expected<Socket::HostAndPort> Socket::DecodeHostAndPort(llvm::StringRef host_and_port) {
275 static llvm::Regex g_regex("([^:]+|\\[[0-9a-fA-F:]+.*\\]):([0-9]+)");
276 HostAndPort ret;
277 llvm::SmallVector<llvm::StringRef, 3> matches;
278 if (g_regex.match(String: host_and_port, Matches: &matches)) {
279 ret.hostname = matches[1].str();
280 // IPv6 addresses are wrapped in [] when specified with ports
281 if (ret.hostname.front() == '[' && ret.hostname.back() == ']')
282 ret.hostname = ret.hostname.substr(pos: 1, n: ret.hostname.size() - 2);
283 if (to_integer(S: matches[2], Num&: ret.port, Base: 10))
284 return ret;
285 } else {
286 // If this was unsuccessful, then check if it's simply an unsigned 16-bit
287 // integer, representing a port with an empty host.
288 if (to_integer(S: host_and_port, Num&: ret.port, Base: 10))
289 return ret;
290 }
291
292 return llvm::createStringError(EC: llvm::inconvertibleErrorCode(),
293 Fmt: "invalid host:port specification: '%s'",
294 Vals: host_and_port.str().c_str());
295}
296
297IOObject::WaitableHandle Socket::GetWaitableHandle() {
298 // TODO: On Windows, use WSAEventSelect
299 return m_socket;
300}
301
302Status Socket::Read(void *buf, size_t &num_bytes) {
303 Status error;
304 int bytes_received = 0;
305 do {
306 bytes_received = ::recv(fd: m_socket, buf: static_cast<char *>(buf), n: num_bytes, flags: 0);
307 } while (bytes_received < 0 && IsInterrupted());
308
309 if (bytes_received < 0) {
310 SetLastError(error);
311 num_bytes = 0;
312 } else
313 num_bytes = bytes_received;
314
315 Log *log = GetLog(mask: LLDBLog::Communication);
316 if (log) {
317 LLDB_LOGF(log,
318 "%p Socket::Read() (socket = %" PRIu64
319 ", src = %p, src_len = %" PRIu64 ", flags = 0) => %" PRIi64
320 " (error = %s)",
321 static_cast<void *>(this), static_cast<uint64_t>(m_socket), buf,
322 static_cast<uint64_t>(num_bytes),
323 static_cast<int64_t>(bytes_received), error.AsCString());
324 }
325
326 return error;
327}
328
329Status Socket::Write(const void *buf, size_t &num_bytes) {
330 const size_t src_len = num_bytes;
331 Status error;
332 int bytes_sent = 0;
333 do {
334 bytes_sent = Send(buf, num_bytes);
335 } while (bytes_sent < 0 && IsInterrupted());
336
337 if (bytes_sent < 0) {
338 SetLastError(error);
339 num_bytes = 0;
340 } else
341 num_bytes = bytes_sent;
342
343 Log *log = GetLog(mask: LLDBLog::Communication);
344 if (log) {
345 LLDB_LOGF(log,
346 "%p Socket::Write() (socket = %" PRIu64
347 ", src = %p, src_len = %" PRIu64 ", flags = 0) => %" PRIi64
348 " (error = %s)",
349 static_cast<void *>(this), static_cast<uint64_t>(m_socket), buf,
350 static_cast<uint64_t>(src_len),
351 static_cast<int64_t>(bytes_sent), error.AsCString());
352 }
353
354 return error;
355}
356
357Status Socket::Close() {
358 Status error;
359 if (!IsValid() || !m_should_close_fd)
360 return error;
361
362 Log *log = GetLog(mask: LLDBLog::Connection);
363 LLDB_LOGF(log, "%p Socket::Close (fd = %" PRIu64 ")",
364 static_cast<void *>(this), static_cast<uint64_t>(m_socket));
365
366 bool success = CloseSocket(sockfd: m_socket) == 0;
367 // A reference to a FD was passed in, set it to an invalid value
368 m_socket = kInvalidSocketValue;
369 if (!success) {
370 SetLastError(error);
371 }
372
373 return error;
374}
375
376int Socket::GetOption(NativeSocket sockfd, int level, int option_name,
377 int &option_value) {
378 get_socket_option_arg_type option_value_p =
379 reinterpret_cast<get_socket_option_arg_type>(&option_value);
380 socklen_t option_value_size = sizeof(int);
381 return ::getsockopt(fd: sockfd, level: level, optname: option_name, optval: option_value_p,
382 optlen: &option_value_size);
383}
384
385int Socket::SetOption(NativeSocket sockfd, int level, int option_name,
386 int option_value) {
387 set_socket_option_arg_type option_value_p =
388 reinterpret_cast<set_socket_option_arg_type>(&option_value);
389 return ::setsockopt(fd: sockfd, level: level, optname: option_name, optval: option_value_p,
390 optlen: sizeof(option_value));
391}
392
393size_t Socket::Send(const void *buf, const size_t num_bytes) {
394 return ::send(fd: m_socket, buf: static_cast<const char *>(buf), n: num_bytes, flags: 0);
395}
396
397void Socket::SetLastError(Status &error) {
398#if defined(_WIN32)
399 error = Status(::WSAGetLastError(), lldb::eErrorTypeWin32);
400#else
401 error = Status::FromErrno();
402#endif
403}
404
405Status Socket::GetLastError() {
406 std::error_code EC;
407#ifdef _WIN32
408 EC = llvm::mapWindowsError(WSAGetLastError());
409#else
410 EC = std::error_code(errno, std::generic_category());
411#endif
412 return EC;
413}
414
415int Socket::CloseSocket(NativeSocket sockfd) {
416#ifdef _WIN32
417 return ::closesocket(sockfd);
418#else
419 return ::close(fd: sockfd);
420#endif
421}
422
423NativeSocket Socket::CreateSocket(const int domain, const int type,
424 const int protocol, Status &error) {
425 error.Clear();
426 auto socket_type = type;
427#ifdef SOCK_CLOEXEC
428 socket_type |= SOCK_CLOEXEC;
429#endif
430 auto sock = ::socket(domain: domain, type: socket_type, protocol: protocol);
431 if (sock == kInvalidSocketValue)
432 SetLastError(error);
433
434 return sock;
435}
436
437Status Socket::Accept(const Timeout<std::micro> &timeout, Socket *&socket) {
438 socket = nullptr;
439 MainLoop accept_loop;
440 llvm::Expected<std::vector<MainLoopBase::ReadHandleUP>> expected_handles =
441 Accept(loop&: accept_loop,
442 sock_cb: [&accept_loop, &socket](std::unique_ptr<Socket> sock) {
443 socket = sock.release();
444 accept_loop.RequestTermination();
445 });
446 if (!expected_handles)
447 return Status::FromError(error: expected_handles.takeError());
448 if (timeout) {
449 accept_loop.AddCallback(
450 callback: [](MainLoopBase &loop) { loop.RequestTermination(); }, delay: *timeout);
451 }
452 if (Status status = accept_loop.Run(); status.Fail())
453 return status;
454 if (socket)
455 return Status();
456 return Status(std::make_error_code(e: std::errc::timed_out));
457}
458
459NativeSocket Socket::AcceptSocket(NativeSocket sockfd, struct sockaddr *addr,
460 socklen_t *addrlen, Status &error) {
461 error.Clear();
462#if defined(SOCK_CLOEXEC) && defined(HAVE_ACCEPT4)
463 int flags = SOCK_CLOEXEC;
464 NativeSocket fd = llvm::sys::RetryAfterSignal(
465 static_cast<NativeSocket>(-1), ::accept4, sockfd, addr, addrlen, flags);
466#else
467 NativeSocket fd = llvm::sys::RetryAfterSignal(
468 Fail: static_cast<NativeSocket>(-1), F&: ::accept, As: sockfd, As: addr, As: addrlen);
469#endif
470 if (fd == kInvalidSocketValue)
471 SetLastError(error);
472 return fd;
473}
474
475llvm::raw_ostream &lldb_private::operator<<(llvm::raw_ostream &OS,
476 const Socket::HostAndPort &HP) {
477 return OS << '[' << HP.hostname << ']' << ':' << HP.port;
478}
479

Provided by KDAB

Privacy Policy
Update your C++ knowledge – Modern C++11/14/17 Training
Find out more

source code of lldb/source/Host/common/Socket.cpp