1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
|
/*
* Copyright (c) 2018-2021, Andreas Kling <kling@serenityos.org>
* Copyright (c) 2021, sin-ack <sin-ack@protonmail.com>
*
* SPDX-License-Identifier: BSD-2-Clause
*/
#include <LibCore/Socket.h>
#include <LibCore/System.h>
namespace Core {
ErrorOr<int> Socket::create_fd(SocketDomain domain, SocketType type)
{
int socket_domain;
switch (domain) {
case SocketDomain::Inet:
socket_domain = AF_INET;
break;
case SocketDomain::Local:
socket_domain = AF_LOCAL;
break;
default:
VERIFY_NOT_REACHED();
}
int socket_type;
switch (type) {
case SocketType::Stream:
socket_type = SOCK_STREAM;
break;
case SocketType::Datagram:
socket_type = SOCK_DGRAM;
break;
default:
VERIFY_NOT_REACHED();
}
// Let's have a safe default of CLOEXEC. :^)
#ifdef SOCK_CLOEXEC
return System::socket(socket_domain, socket_type | SOCK_CLOEXEC, 0);
#else
auto fd = TRY(System::socket(socket_domain, socket_type, 0));
TRY(System::fcntl(fd, F_SETFD, FD_CLOEXEC));
return fd;
#endif
}
ErrorOr<IPv4Address> Socket::resolve_host(DeprecatedString const& host, SocketType type)
{
int socket_type;
switch (type) {
case SocketType::Stream:
socket_type = SOCK_STREAM;
break;
case SocketType::Datagram:
socket_type = SOCK_DGRAM;
break;
default:
VERIFY_NOT_REACHED();
}
struct addrinfo hints = {};
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = socket_type;
hints.ai_flags = 0;
hints.ai_protocol = 0;
auto const results = TRY(Core::System::getaddrinfo(host.characters(), nullptr, hints));
for (auto const& result : results.addresses()) {
if (result.ai_family == AF_INET) {
auto* socket_address = bit_cast<struct sockaddr_in*>(result.ai_addr);
NetworkOrdered<u32> const network_ordered_address { socket_address->sin_addr.s_addr };
return IPv4Address { network_ordered_address };
}
}
return Error::from_string_literal("Could not resolve to IPv4 address");
}
ErrorOr<void> Socket::connect_local(int fd, DeprecatedString const& path)
{
auto address = SocketAddress::local(path);
auto maybe_sockaddr = address.to_sockaddr_un();
if (!maybe_sockaddr.has_value()) {
dbgln("Core::Socket::connect_local: Could not obtain a sockaddr_un");
return Error::from_errno(EINVAL);
}
auto addr = maybe_sockaddr.release_value();
return System::connect(fd, bit_cast<struct sockaddr*>(&addr), sizeof(addr));
}
ErrorOr<void> Socket::connect_inet(int fd, SocketAddress const& address)
{
auto addr = address.to_sockaddr_in();
return System::connect(fd, bit_cast<struct sockaddr*>(&addr), sizeof(addr));
}
ErrorOr<Bytes> PosixSocketHelper::read(Bytes buffer, int flags)
{
if (!is_open()) {
return Error::from_errno(ENOTCONN);
}
ssize_t nread = TRY(System::recv(m_fd, buffer.data(), buffer.size(), flags));
m_last_read_was_eof = nread == 0;
// If a socket read is EOF, then no more data can be read from it because
// the protocol has disconnected. In this case, we can just disable the
// notifier if we have one.
if (m_last_read_was_eof && m_notifier)
m_notifier->set_enabled(false);
return buffer.trim(nread);
}
ErrorOr<size_t> PosixSocketHelper::write(ReadonlyBytes buffer, int flags)
{
if (!is_open()) {
return Error::from_errno(ENOTCONN);
}
return TRY(System::send(m_fd, buffer.data(), buffer.size(), flags));
}
void PosixSocketHelper::close()
{
if (!is_open()) {
return;
}
if (m_notifier)
m_notifier->set_enabled(false);
ErrorOr<void> result;
do {
result = System::close(m_fd);
} while (result.is_error() && result.error().code() == EINTR);
VERIFY(!result.is_error());
m_fd = -1;
}
ErrorOr<bool> PosixSocketHelper::can_read_without_blocking(int timeout) const
{
struct pollfd the_fd = { .fd = m_fd, .events = POLLIN, .revents = 0 };
ErrorOr<int> result { 0 };
do {
result = Core::System::poll({ &the_fd, 1 }, timeout);
} while (result.is_error() && result.error().code() == EINTR);
if (result.is_error())
return result.release_error();
return (the_fd.revents & POLLIN) > 0;
}
ErrorOr<void> PosixSocketHelper::set_blocking(bool enabled)
{
int value = enabled ? 0 : 1;
return System::ioctl(m_fd, FIONBIO, &value);
}
ErrorOr<void> PosixSocketHelper::set_close_on_exec(bool enabled)
{
int flags = TRY(System::fcntl(m_fd, F_GETFD));
if (enabled)
flags |= FD_CLOEXEC;
else
flags &= ~FD_CLOEXEC;
TRY(System::fcntl(m_fd, F_SETFD, flags));
return {};
}
ErrorOr<void> PosixSocketHelper::set_receive_timeout(Duration timeout)
{
auto timeout_spec = timeout.to_timespec();
return System::setsockopt(m_fd, SOL_SOCKET, SO_RCVTIMEO, &timeout_spec, sizeof(timeout_spec));
}
void PosixSocketHelper::setup_notifier()
{
if (!m_notifier)
m_notifier = Core::Notifier::construct(m_fd, Core::Notifier::Type::Read);
}
ErrorOr<NonnullOwnPtr<TCPSocket>> TCPSocket::connect(DeprecatedString const& host, u16 port)
{
auto ip_address = TRY(resolve_host(host, SocketType::Stream));
return connect(SocketAddress { ip_address, port });
}
ErrorOr<NonnullOwnPtr<TCPSocket>> TCPSocket::connect(SocketAddress const& address)
{
auto socket = TRY(adopt_nonnull_own_or_enomem(new (nothrow) TCPSocket()));
auto fd = TRY(create_fd(SocketDomain::Inet, SocketType::Stream));
socket->m_helper.set_fd(fd);
TRY(connect_inet(fd, address));
socket->setup_notifier();
return socket;
}
ErrorOr<NonnullOwnPtr<TCPSocket>> TCPSocket::adopt_fd(int fd)
{
if (fd < 0) {
return Error::from_errno(EBADF);
}
auto socket = TRY(adopt_nonnull_own_or_enomem(new (nothrow) TCPSocket()));
socket->m_helper.set_fd(fd);
socket->setup_notifier();
return socket;
}
ErrorOr<size_t> PosixSocketHelper::pending_bytes() const
{
if (!is_open()) {
return Error::from_errno(ENOTCONN);
}
int value;
TRY(System::ioctl(m_fd, FIONREAD, &value));
return static_cast<size_t>(value);
}
ErrorOr<NonnullOwnPtr<UDPSocket>> UDPSocket::connect(DeprecatedString const& host, u16 port, Optional<Duration> timeout)
{
auto ip_address = TRY(resolve_host(host, SocketType::Datagram));
return connect(SocketAddress { ip_address, port }, timeout);
}
ErrorOr<NonnullOwnPtr<UDPSocket>> UDPSocket::connect(SocketAddress const& address, Optional<Duration> timeout)
{
auto socket = TRY(adopt_nonnull_own_or_enomem(new (nothrow) UDPSocket()));
auto fd = TRY(create_fd(SocketDomain::Inet, SocketType::Datagram));
socket->m_helper.set_fd(fd);
if (timeout.has_value()) {
TRY(socket->m_helper.set_receive_timeout(timeout.value()));
}
TRY(connect_inet(fd, address));
socket->setup_notifier();
return socket;
}
ErrorOr<NonnullOwnPtr<LocalSocket>> LocalSocket::connect(DeprecatedString const& path, PreventSIGPIPE prevent_sigpipe)
{
auto socket = TRY(adopt_nonnull_own_or_enomem(new (nothrow) LocalSocket(prevent_sigpipe)));
auto fd = TRY(create_fd(SocketDomain::Local, SocketType::Stream));
socket->m_helper.set_fd(fd);
TRY(connect_local(fd, path));
socket->setup_notifier();
return socket;
}
ErrorOr<NonnullOwnPtr<LocalSocket>> LocalSocket::adopt_fd(int fd, PreventSIGPIPE prevent_sigpipe)
{
if (fd < 0) {
return Error::from_errno(EBADF);
}
auto socket = TRY(adopt_nonnull_own_or_enomem(new (nothrow) LocalSocket(prevent_sigpipe)));
socket->m_helper.set_fd(fd);
socket->setup_notifier();
return socket;
}
ErrorOr<int> LocalSocket::receive_fd(int flags)
{
#if defined(AK_OS_SERENITY)
return Core::System::recvfd(m_helper.fd(), flags);
#elif defined(AK_OS_LINUX) || defined(AK_OS_BSD_GENERIC)
union {
struct cmsghdr cmsghdr;
char control[CMSG_SPACE(sizeof(int))];
} cmsgu {};
char c = 0;
struct iovec iov {
.iov_base = &c,
.iov_len = 1,
};
struct msghdr msg = {};
msg.msg_iov = &iov;
msg.msg_iovlen = 1;
msg.msg_control = cmsgu.control;
msg.msg_controllen = sizeof(cmsgu.control);
TRY(Core::System::recvmsg(m_helper.fd(), &msg, 0));
struct cmsghdr* cmsg = CMSG_FIRSTHDR(&msg);
if (!cmsg || cmsg->cmsg_len != CMSG_LEN(sizeof(int)))
return Error::from_string_literal("Malformed message when receiving file descriptor");
VERIFY(cmsg->cmsg_level == SOL_SOCKET);
VERIFY(cmsg->cmsg_type == SCM_RIGHTS);
int fd = *((int*)CMSG_DATA(cmsg));
if (flags & O_CLOEXEC) {
auto fd_flags = TRY(Core::System::fcntl(fd, F_GETFD));
TRY(Core::System::fcntl(fd, F_SETFD, fd_flags | FD_CLOEXEC));
}
return fd;
#else
(void)flags;
return Error::from_string_literal("File descriptor passing not supported on this platform");
#endif
}
ErrorOr<void> LocalSocket::send_fd(int fd)
{
#if defined(AK_OS_SERENITY)
return Core::System::sendfd(m_helper.fd(), fd);
#elif defined(AK_OS_LINUX) || defined(AK_OS_BSD_GENERIC)
char c = 'F';
struct iovec iov {
.iov_base = &c,
.iov_len = sizeof(c)
};
union {
struct cmsghdr cmsghdr;
char control[CMSG_SPACE(sizeof(int))];
} cmsgu {};
struct msghdr msg = {};
msg.msg_iov = &iov;
msg.msg_iovlen = 1;
msg.msg_control = cmsgu.control;
msg.msg_controllen = sizeof(cmsgu.control);
struct cmsghdr* cmsg = CMSG_FIRSTHDR(&msg);
cmsg->cmsg_len = CMSG_LEN(sizeof(int));
cmsg->cmsg_level = SOL_SOCKET;
cmsg->cmsg_type = SCM_RIGHTS;
*((int*)CMSG_DATA(cmsg)) = fd;
TRY(Core::System::sendmsg(m_helper.fd(), &msg, 0));
return {};
#else
(void)fd;
return Error::from_string_literal("File descriptor passing not supported on this platform");
#endif
}
ErrorOr<pid_t> LocalSocket::peer_pid() const
{
#ifdef AK_OS_MACOS
pid_t pid;
socklen_t pid_size = sizeof(pid);
#elif defined(AK_OS_FREEBSD)
struct xucred creds = {};
socklen_t creds_size = sizeof(creds);
#elif defined(AK_OS_OPENBSD)
struct sockpeercred creds = {};
socklen_t creds_size = sizeof(creds);
#elif defined(AK_OS_NETBSD)
struct sockcred creds = {};
socklen_t creds_size = sizeof(creds);
#elif defined(AK_OS_SOLARIS)
ucred_t* creds = NULL;
socklen_t creds_size = sizeof(creds);
#else
struct ucred creds = {};
socklen_t creds_size = sizeof(creds);
#endif
#ifdef AK_OS_MACOS
TRY(System::getsockopt(m_helper.fd(), SOL_LOCAL, LOCAL_PEERPID, &pid, &pid_size));
return pid;
#elif defined(AK_OS_FREEBSD)
TRY(System::getsockopt(m_helper.fd(), SOL_LOCAL, LOCAL_PEERCRED, &creds, &creds_size));
return creds.cr_pid;
#elif defined(AK_OS_NETBSD)
TRY(System::getsockopt(m_helper.fd(), SOL_SOCKET, SCM_CREDS, &creds, &creds_size));
return creds.sc_pid;
#elif defined(AK_OS_SOLARIS)
TRY(System::getsockopt(m_helper.fd(), SOL_SOCKET, SO_RECVUCRED, &creds, &creds_size));
return ucred_getpid(creds);
#else
TRY(System::getsockopt(m_helper.fd(), SOL_SOCKET, SO_PEERCRED, &creds, &creds_size));
return creds.pid;
#endif
}
ErrorOr<Bytes> LocalSocket::read_without_waiting(Bytes buffer)
{
return m_helper.read(buffer, MSG_DONTWAIT);
}
Optional<int> LocalSocket::fd() const
{
if (!is_open())
return {};
return m_helper.fd();
}
ErrorOr<int> LocalSocket::release_fd()
{
if (!is_open()) {
return Error::from_errno(ENOTCONN);
}
auto fd = m_helper.fd();
m_helper.set_fd(-1);
return fd;
}
}
|