]> git.ipfire.org Git - thirdparty/systemd.git/blame - src/core/socket.c
Merge pull request #18380 from yuwata/test-network-ipv6-proxy-ndp
[thirdparty/systemd.git] / src / core / socket.c
CommitLineData
db9ecf05 1/* SPDX-License-Identifier: LGPL-2.1-or-later */
a7334b09 2
e8da24a6 3#include <arpa/inet.h>
83c60c9f
LP
4#include <errno.h>
5#include <fcntl.h>
916abb21 6#include <mqueue.h>
e8da24a6 7#include <netinet/tcp.h>
e8da24a6
LP
8#include <sys/epoll.h>
9#include <sys/stat.h>
10#include <unistd.h>
62bc4efc 11#include <linux/sctp.h>
83c60c9f 12
b5efdb8a 13#include "alloc-util.h"
a79279c7 14#include "bpf-firewall.h"
e8da24a6
LP
15#include "bus-error.h"
16#include "bus-util.h"
17#include "copy.h"
18#include "dbus-socket.h"
6fcbec6f 19#include "dbus-unit.h"
e8da24a6 20#include "def.h"
86e045ec 21#include "errno-list.h"
e8da24a6 22#include "exit-status.h"
3ffd4af2 23#include "fd-util.h"
f97b34a6 24#include "format-util.h"
95f7fbbf 25#include "fs-util.h"
a79279c7 26#include "in-addr-util.h"
60d9771c 27#include "io-util.h"
da96ad5a 28#include "ip-protocol-list.h"
e8da24a6 29#include "label.h"
83c60c9f 30#include "log.h"
49e942b2 31#include "mkdir.h"
6bedfcbb 32#include "parse-util.h"
9eb977db 33#include "path-util.h"
7b3e062c 34#include "process-util.h"
d7b8eec7 35#include "selinux-util.h"
d68c645b 36#include "serialize.h"
24882e06 37#include "signal-util.h"
e8da24a6 38#include "smack-util.h"
d68c645b 39#include "socket.h"
5c3fa98d 40#include "socket-netlink.h"
e8da24a6 41#include "special.h"
8b43440b 42#include "string-table.h"
07630cea 43#include "string-util.h"
e8da24a6
LP
44#include "strv.h"
45#include "unit-name.h"
e8da24a6 46#include "unit.h"
b1d4f8e1 47#include "user-util.h"
83c60c9f 48
166cf510
ZJS
49struct SocketPeer {
50 unsigned n_ref;
51
52 Socket *socket;
53 union sockaddr_union peer;
41733ae1 54 socklen_t peer_salen;
166cf510
ZJS
55};
56
acbb0225 57static const UnitActiveState state_translation_table[_SOCKET_STATE_MAX] = {
87f0e418
LP
58 [SOCKET_DEAD] = UNIT_INACTIVE,
59 [SOCKET_START_PRE] = UNIT_ACTIVATING,
3900e5fd 60 [SOCKET_START_CHOWN] = UNIT_ACTIVATING,
87f0e418
LP
61 [SOCKET_START_POST] = UNIT_ACTIVATING,
62 [SOCKET_LISTENING] = UNIT_ACTIVE,
63 [SOCKET_RUNNING] = UNIT_ACTIVE,
64 [SOCKET_STOP_PRE] = UNIT_DEACTIVATING,
65 [SOCKET_STOP_PRE_SIGTERM] = UNIT_DEACTIVATING,
66 [SOCKET_STOP_PRE_SIGKILL] = UNIT_DEACTIVATING,
67 [SOCKET_STOP_POST] = UNIT_DEACTIVATING,
80876c20
LP
68 [SOCKET_FINAL_SIGTERM] = UNIT_DEACTIVATING,
69 [SOCKET_FINAL_SIGKILL] = UNIT_DEACTIVATING,
c968d76a
YW
70 [SOCKET_FAILED] = UNIT_FAILED,
71 [SOCKET_CLEANING] = UNIT_MAINTENANCE,
83c60c9f 72};
5cb5a6ff 73
718db961
LP
74static int socket_dispatch_io(sd_event_source *source, int fd, uint32_t revents, void *userdata);
75static int socket_dispatch_timer(sd_event_source *source, usec_t usec, void *userdata);
3e5f04bf 76static void flush_ports(Socket *s);
718db961 77
a16e1123
LP
78static void socket_init(Unit *u) {
79 Socket *s = SOCKET(u);
80
81 assert(u);
ac155bb8 82 assert(u->load_state == UNIT_STUB);
a16e1123 83
a16e1123 84 s->backlog = SOMAXCONN;
1f19a534 85 s->timeout_usec = u->manager->default_timeout_start_usec;
a16e1123 86 s->directory_mode = 0755;
9131f660 87 s->socket_mode = 0666;
a16e1123 88
6cf6bbc2
LP
89 s->max_connections = 64;
90
4fd5948e 91 s->priority = -1;
4fd5948e
LP
92 s->ip_tos = -1;
93 s->ip_ttl = -1;
4fd5948e 94 s->mark = -1;
4fd5948e 95
ac155bb8
MS
96 s->exec_context.std_output = u->manager->default_std_output;
97 s->exec_context.std_error = u->manager->default_std_error;
085afe36 98
a16e1123 99 s->control_command_id = _SOCKET_EXEC_COMMAND_INVALID;
8b26cdbd 100
1f15ce28
LP
101 s->trigger_limit.interval = USEC_INFINITY;
102 s->trigger_limit.burst = (unsigned) -1;
a16e1123 103}
acbb0225 104
5e94833f
LP
105static void socket_unwatch_control_pid(Socket *s) {
106 assert(s);
107
108 if (s->control_pid <= 0)
109 return;
110
111 unit_unwatch_pid(UNIT(s), s->control_pid);
112 s->control_pid = 0;
113}
114
15087cdb 115static void socket_cleanup_fd_list(SocketPort *p) {
3ffd4af2 116 assert(p);
15087cdb 117
3ffd4af2 118 close_many(p->auxiliary_fds, p->n_auxiliary_fds);
15087cdb
PS
119 p->auxiliary_fds = mfree(p->auxiliary_fds);
120 p->n_auxiliary_fds = 0;
121}
122
74051b9b 123void socket_free_ports(Socket *s) {
034c6ed7
LP
124 SocketPort *p;
125
126 assert(s);
127
128 while ((p = s->ports)) {
71fda00f 129 LIST_REMOVE(port, s->ports, p);
034c6ed7 130
718db961
LP
131 sd_event_source_unref(p->event_source);
132
15087cdb 133 socket_cleanup_fd_list(p);
03e334a1 134 safe_close(p->fd);
034c6ed7
LP
135 free(p->path);
136 free(p);
137 }
74051b9b
LP
138}
139
140static void socket_done(Unit *u) {
141 Socket *s = SOCKET(u);
9d565427 142 SocketPeer *p;
74051b9b
LP
143
144 assert(s);
145
146 socket_free_ports(s);
034c6ed7 147
9a73653c 148 while ((p = set_steal_first(s->peers_by_address)))
9d565427
SS
149 p->socket = NULL;
150
9a73653c 151 s->peers_by_address = set_free(s->peers_by_address);
9d565427 152
e8a565cb 153 s->exec_runtime = exec_runtime_unref(s->exec_runtime, false);
e537352b 154 exec_command_free_array(s->exec_command, _SOCKET_EXEC_COMMAND_MAX);
034c6ed7
LP
155 s->control_command = NULL;
156
29206d46
LP
157 dynamic_creds_unref(&s->dynamic_creds);
158
5e94833f 159 socket_unwatch_control_pid(s);
034c6ed7 160
57020a3a 161 unit_ref_unset(&s->service);
034c6ed7 162
a1e58e8e
LP
163 s->tcp_congestion = mfree(s->tcp_congestion);
164 s->bind_to_device = mfree(s->bind_to_device);
acbb0225 165
0a78712e
DM
166 s->smack = mfree(s->smack);
167 s->smack_ip_in = mfree(s->smack_ip_in);
168 s->smack_ip_out = mfree(s->smack_ip_out);
0eb59ccf 169
811ba7a0
LP
170 strv_free(s->symlinks);
171
0a78712e
DM
172 s->user = mfree(s->user);
173 s->group = mfree(s->group);
3900e5fd 174
a97b23d6
DM
175 s->fdname = mfree(s->fdname);
176
718db961
LP
177 s->timer_event_source = sd_event_source_unref(s->timer_event_source);
178}
179
36c16a7c 180static int socket_arm_timer(Socket *s, usec_t usec) {
718db961
LP
181 int r;
182
183 assert(s);
184
718db961 185 if (s->timer_event_source) {
36c16a7c 186 r = sd_event_source_set_time(s->timer_event_source, usec);
718db961
LP
187 if (r < 0)
188 return r;
189
190 return sd_event_source_set_enabled(s->timer_event_source, SD_EVENT_ONESHOT);
191 }
192
36c16a7c
LP
193 if (usec == USEC_INFINITY)
194 return 0;
195
7dfbe2e3 196 r = sd_event_add_time(
6a0f1f6d
LP
197 UNIT(s)->manager->event,
198 &s->timer_event_source,
199 CLOCK_MONOTONIC,
36c16a7c 200 usec, 0,
6a0f1f6d 201 socket_dispatch_timer, s);
7dfbe2e3
TG
202 if (r < 0)
203 return r;
204
205 (void) sd_event_source_set_description(s->timer_event_source, "socket-timer");
206
207 return 0;
5cb5a6ff
LP
208}
209
4f2d528d
LP
210static bool have_non_accept_socket(Socket *s) {
211 SocketPort *p;
212
213 assert(s);
214
215 if (!s->accept)
216 return true;
217
dd5ad9d4
LP
218 LIST_FOREACH(port, p, s->ports) {
219
220 if (p->type != SOCKET_SOCKET)
221 return true;
222
4f2d528d
LP
223 if (!socket_address_can_accept(&p->address))
224 return true;
dd5ad9d4 225 }
4f2d528d
LP
226
227 return false;
228}
229
eef85c4a 230static int socket_add_mount_dependencies(Socket *s) {
6e2ef85b 231 SocketPort *p;
6e2ef85b
LP
232 int r;
233
234 assert(s);
6e2ef85b 235
a57f7e2c
LP
236 LIST_FOREACH(port, p, s->ports) {
237 const char *path = NULL;
6e2ef85b 238
a57f7e2c
LP
239 if (p->type == SOCKET_SOCKET)
240 path = socket_address_get_path(&p->address);
60252446 241 else if (IN_SET(p->type, SOCKET_FIFO, SOCKET_SPECIAL, SOCKET_USB_FUNCTION))
a57f7e2c 242 path = p->path;
6e2ef85b 243
a57f7e2c
LP
244 if (!path)
245 continue;
6e2ef85b 246
eef85c4a 247 r = unit_require_mounts_for(UNIT(s), path, UNIT_DEPENDENCY_FILE);
b87705cd 248 if (r < 0)
6e2ef85b 249 return r;
b87705cd 250 }
6e2ef85b
LP
251
252 return 0;
253}
254
eef85c4a 255static int socket_add_device_dependencies(Socket *s) {
6e2ef85b 256 char *t;
6e2ef85b
LP
257
258 assert(s);
259
7d0c710d 260 if (!s->bind_to_device || streq(s->bind_to_device, "lo"))
6e2ef85b
LP
261 return 0;
262
63c372cb 263 t = strjoina("/sys/subsystem/net/devices/", s->bind_to_device);
d336ba9f 264 return unit_add_node_dependency(UNIT(s), t, UNIT_BINDS_TO, UNIT_DEPENDENCY_FILE);
6e2ef85b
LP
265}
266
a40eb732
LP
267static int socket_add_default_dependencies(Socket *s) {
268 int r;
269 assert(s);
270
4c9ea260
LP
271 if (!UNIT(s)->default_dependencies)
272 return 0;
273
35d8c19a 274 r = unit_add_dependency_by_name(UNIT(s), UNIT_BEFORE, SPECIAL_SOCKETS_TARGET, true, UNIT_DEPENDENCY_DEFAULT);
e3d84721
LP
275 if (r < 0)
276 return r;
2a77d31d 277
463d0d15 278 if (MANAGER_IS_SYSTEM(UNIT(s)->manager)) {
5a724170 279 r = unit_add_two_dependencies_by_name(UNIT(s), UNIT_AFTER, UNIT_REQUIRES, SPECIAL_SYSINIT_TARGET, true, UNIT_DEPENDENCY_DEFAULT);
e3d84721 280 if (r < 0)
a40eb732 281 return r;
2a77d31d 282 }
a40eb732 283
5a724170 284 return unit_add_two_dependencies_by_name(UNIT(s), UNIT_BEFORE, UNIT_CONFLICTS, SPECIAL_SHUTDOWN_TARGET, true, UNIT_DEPENDENCY_DEFAULT);
a40eb732
LP
285}
286
44a6b1b6 287_pure_ static bool socket_has_exec(Socket *s) {
4cfc6dbe
LP
288 unsigned i;
289 assert(s);
290
291 for (i = 0; i < _SOCKET_EXEC_COMMAND_MAX; i++)
292 if (s->exec_command[i])
293 return true;
294
295 return false;
296}
297
e821075a
LP
298static int socket_add_extras(Socket *s) {
299 Unit *u = UNIT(s);
e537352b 300 int r;
44d8db9e 301
e821075a 302 assert(s);
57020a3a 303
1f15ce28
LP
304 /* Pick defaults for the trigger limit, if nothing was explicitly configured. We pick a relatively high limit
305 * in Accept=yes mode, and a lower limit for Accept=no. Reason: in Accept=yes mode we are invoking accept()
306 * ourselves before the trigger limit can hit, thus incoming connections are taken off the socket queue quickly
307 * and reliably. This is different for Accept=no, where the spawned service has to take the incoming traffic
308 * off the queues, which it might not necessarily do. Moreover, while Accept=no services are supposed to
309 * process whatever is queued in one go, and thus should normally never have to be started frequently. This is
310 * different for Accept=yes where each connection is processed by a new service instance, and thus frequent
311 * service starts are typical. */
312
313 if (s->trigger_limit.interval == USEC_INFINITY)
314 s->trigger_limit.interval = 2 * USEC_PER_SEC;
315
316 if (s->trigger_limit.burst == (unsigned) -1) {
317 if (s->accept)
318 s->trigger_limit.burst = 200;
319 else
320 s->trigger_limit.burst = 20;
321 }
322
e821075a 323 if (have_non_accept_socket(s)) {
23a177ef 324
e821075a
LP
325 if (!UNIT_DEREF(s->service)) {
326 Unit *x;
57020a3a 327
e821075a 328 r = unit_load_related_unit(u, ".service", &x);
57020a3a 329 if (r < 0)
4f2d528d 330 return r;
e821075a 331
7f7d01ed 332 unit_ref_set(&s->service, u, x);
4f2d528d 333 }
44d8db9e 334
eef85c4a 335 r = unit_add_two_dependencies(u, UNIT_BEFORE, UNIT_TRIGGERS, UNIT_DEREF(s->service), true, UNIT_DEPENDENCY_IMPLICIT);
e821075a 336 if (r < 0)
6e2ef85b 337 return r;
e821075a 338 }
6e2ef85b 339
eef85c4a 340 r = socket_add_mount_dependencies(s);
e821075a
LP
341 if (r < 0)
342 return r;
6e2ef85b 343
eef85c4a 344 r = socket_add_device_dependencies(s);
e821075a
LP
345 if (r < 0)
346 return r;
347
598459ce 348 r = unit_patch_contexts(u);
e821075a
LP
349 if (r < 0)
350 return r;
351
352 if (socket_has_exec(s)) {
353 r = unit_add_exec_dependencies(u, &s->exec_context);
354 if (r < 0)
355 return r;
e821075a 356 }
a016b922 357
88af31f9
LP
358 r = unit_set_default_slice(u);
359 if (r < 0)
360 return r;
361
4c9ea260
LP
362 r = socket_add_default_dependencies(s);
363 if (r < 0)
364 return r;
e821075a
LP
365
366 return 0;
367}
368
811ba7a0
LP
369static const char *socket_find_symlink_target(Socket *s) {
370 const char *found = NULL;
371 SocketPort *p;
372
373 LIST_FOREACH(port, p, s->ports) {
374 const char *f = NULL;
375
376 switch (p->type) {
377
378 case SOCKET_FIFO:
379 f = p->path;
380 break;
381
382 case SOCKET_SOCKET:
b9495e8d 383 f = socket_address_get_path(&p->address);
811ba7a0
LP
384 break;
385
386 default:
387 break;
388 }
389
390 if (f) {
391 if (found)
392 return NULL;
393
394 found = f;
395 }
396 }
397
398 return found;
399}
400
e821075a
LP
401static int socket_verify(Socket *s) {
402 assert(s);
75193d41 403 assert(UNIT(s)->load_state == UNIT_LOADED);
e821075a 404
d85ff944
YW
405 if (!s->ports)
406 return log_unit_error_errno(UNIT(s), SYNTHETIC_ERRNO(ENOEXEC), "Unit has no Listen setting (ListenStream=, ListenDatagram=, ListenFIFO=, ...). Refusing.");
e821075a 407
d85ff944
YW
408 if (s->accept && have_non_accept_socket(s))
409 return log_unit_error_errno(UNIT(s), SYNTHETIC_ERRNO(ENOEXEC), "Unit configured for accepting sockets, but sockets are non-accepting. Refusing.");
e821075a 410
d85ff944
YW
411 if (s->accept && s->max_connections <= 0)
412 return log_unit_error_errno(UNIT(s), SYNTHETIC_ERRNO(ENOEXEC), "MaxConnection= setting too small. Refusing.");
e06c73cc 413
d85ff944
YW
414 if (s->accept && UNIT_DEREF(s->service))
415 return log_unit_error_errno(UNIT(s), SYNTHETIC_ERRNO(ENOEXEC), "Explicit service configuration for accepting socket units not supported. Refusing.");
e821075a 416
d85ff944
YW
417 if (s->exec_context.pam_name && s->kill_context.kill_mode != KILL_CONTROL_GROUP)
418 return log_unit_error_errno(UNIT(s), SYNTHETIC_ERRNO(ENOEXEC), "Unit has PAM enabled. Kill mode must be set to 'control-group'. Refusing.");
e821075a 419
d85ff944
YW
420 if (!strv_isempty(s->symlinks) && !socket_find_symlink_target(s))
421 return log_unit_error_errno(UNIT(s), SYNTHETIC_ERRNO(ENOEXEC), "Unit has symlinks set but none or more than one node in the file system. Refusing.");
811ba7a0 422
e821075a
LP
423 return 0;
424}
425
7a08d314 426static void peer_address_hash_func(const SocketPeer *s, struct siphash *state) {
9d565427
SS
427 assert(s);
428
429 if (s->peer.sa.sa_family == AF_INET)
430 siphash24_compress(&s->peer.in.sin_addr, sizeof(s->peer.in.sin_addr), state);
41733ae1 431 else if (s->peer.sa.sa_family == AF_INET6)
9d565427 432 siphash24_compress(&s->peer.in6.sin6_addr, sizeof(s->peer.in6.sin6_addr), state);
359a5bcf
SH
433 else if (s->peer.sa.sa_family == AF_VSOCK)
434 siphash24_compress(&s->peer.vm.svm_cid, sizeof(s->peer.vm.svm_cid), state);
41733ae1
LP
435 else
436 assert_not_reached("Unknown address family.");
9d565427
SS
437}
438
7a08d314 439static int peer_address_compare_func(const SocketPeer *x, const SocketPeer *y) {
a0edd02e 440 int r;
9d565427 441
a0edd02e
FB
442 r = CMP(x->peer.sa.sa_family, y->peer.sa.sa_family);
443 if (r != 0)
444 return r;
9d565427
SS
445
446 switch(x->peer.sa.sa_family) {
447 case AF_INET:
448 return memcmp(&x->peer.in.sin_addr, &y->peer.in.sin_addr, sizeof(x->peer.in.sin_addr));
449 case AF_INET6:
450 return memcmp(&x->peer.in6.sin6_addr, &y->peer.in6.sin6_addr, sizeof(x->peer.in6.sin6_addr));
359a5bcf 451 case AF_VSOCK:
6dd91b36 452 return CMP(x->peer.vm.svm_cid, y->peer.vm.svm_cid);
9d565427 453 }
166cf510 454 assert_not_reached("Black sheep in the family!");
9d565427
SS
455}
456
7a08d314 457DEFINE_PRIVATE_HASH_OPS(peer_address_hash_ops, SocketPeer, peer_address_hash_func, peer_address_compare_func);
9d565427 458
e821075a
LP
459static int socket_load(Unit *u) {
460 Socket *s = SOCKET(u);
461 int r;
462
463 assert(u);
464 assert(u->load_state == UNIT_STUB);
465
9a73653c 466 r = set_ensure_allocated(&s->peers_by_address, &peer_address_hash_ops);
9d565427
SS
467 if (r < 0)
468 return r;
469
c3620770 470 r = unit_load_fragment_and_dropin(u, true);
e821075a
LP
471 if (r < 0)
472 return r;
473
75193d41
ZJS
474 if (u->load_state != UNIT_LOADED)
475 return 0;
476
477 /* This is a new unit? Then let's add in some extras */
478 r = socket_add_extras(s);
479 if (r < 0)
480 return r;
23a177ef 481
4f2d528d 482 return socket_verify(s);
44d8db9e
LP
483}
484
166cf510
ZJS
485static SocketPeer *socket_peer_new(void) {
486 SocketPeer *p;
487
488 p = new0(SocketPeer, 1);
489 if (!p)
490 return NULL;
491
492 p->n_ref = 1;
493
494 return p;
495}
496
8301aa0b
YW
497static SocketPeer *socket_peer_free(SocketPeer *p) {
498 assert(p);
166cf510
ZJS
499
500 if (p->socket)
501 set_remove(p->socket->peers_by_address, p);
502
503 return mfree(p);
504}
505
8301aa0b
YW
506DEFINE_TRIVIAL_REF_UNREF_FUNC(SocketPeer, socket_peer, socket_peer_free);
507
3ebcd323 508int socket_acquire_peer(Socket *s, int fd, SocketPeer **p) {
166cf510
ZJS
509 _cleanup_(socket_peer_unrefp) SocketPeer *remote = NULL;
510 SocketPeer sa = {}, *i;
511 socklen_t salen = sizeof(sa.peer);
512 int r;
513
514 assert(fd >= 0);
515 assert(s);
516
fe79f107 517 if (getpeername(fd, &sa.peer.sa, &salen) < 0)
fc2d74ab 518 return log_unit_error_errno(UNIT(s), errno, "getpeername failed: %m");
166cf510 519
359a5bcf 520 if (!IN_SET(sa.peer.sa.sa_family, AF_INET, AF_INET6, AF_VSOCK)) {
166cf510
ZJS
521 *p = NULL;
522 return 0;
523 }
524
525 i = set_get(s->peers_by_address, &sa);
526 if (i) {
527 *p = socket_peer_ref(i);
528 return 1;
529 }
530
531 remote = socket_peer_new();
532 if (!remote)
533 return log_oom();
534
535 remote->peer = sa.peer;
41733ae1 536 remote->peer_salen = salen;
166cf510
ZJS
537
538 r = set_put(s->peers_by_address, remote);
539 if (r < 0)
540 return r;
541
542 remote->socket = s;
543
1cc6c93a 544 *p = TAKE_PTR(remote);
166cf510
ZJS
545
546 return 1;
547}
548
44a6b1b6 549_const_ static const char* listen_lookup(int family, int type) {
7a22745a
LP
550
551 if (family == AF_NETLINK)
552 return "ListenNetlink";
542563ba
LP
553
554 if (type == SOCK_STREAM)
555 return "ListenStream";
556 else if (type == SOCK_DGRAM)
557 return "ListenDatagram";
558 else if (type == SOCK_SEQPACKET)
559 return "ListenSequentialPacket";
560
034c6ed7 561 assert_not_reached("Unknown socket type");
542563ba
LP
562 return NULL;
563}
564
87f0e418 565static void socket_dump(Unit *u, FILE *f, const char *prefix) {
209e9dcd 566 char time_string[FORMAT_TIMESPAN_MAX];
5cb5a6ff 567 SocketExecCommand c;
87f0e418 568 Socket *s = SOCKET(u);
542563ba 569 SocketPort *p;
827d9bf2 570 const char *prefix2, *str;
5cb5a6ff
LP
571
572 assert(s);
fa068367 573 assert(f);
5cb5a6ff 574
4c940960 575 prefix = strempty(prefix);
63c372cb 576 prefix2 = strjoina(prefix, "\t");
c43d20a0 577
5cb5a6ff
LP
578 fprintf(f,
579 "%sSocket State: %s\n"
81a5c6d0 580 "%sResult: %s\n"
c968d76a 581 "%sClean Result: %s\n"
542563ba 582 "%sBindIPv6Only: %s\n"
b5a0699f
LP
583 "%sBacklog: %u\n"
584 "%sSocketMode: %04o\n"
4fd5948e
LP
585 "%sDirectoryMode: %04o\n"
586 "%sKeepAlive: %s\n"
4427c3f4 587 "%sNoDelay: %s\n"
cebf8b20 588 "%sFreeBind: %s\n"
6b6d2dee 589 "%sTransparent: %s\n"
ec6370a2 590 "%sBroadcast: %s\n"
ede3deb4 591 "%sPassCredentials: %s\n"
54ecda32 592 "%sPassSecurity: %s\n"
a3d19f5d 593 "%sPassPacketInfo: %s\n"
bd1fe7c7 594 "%sTCPCongestion: %s\n"
16115b0a 595 "%sRemoveOnStop: %s\n"
55301ec0 596 "%sWritable: %s\n"
827d9bf2 597 "%sFileDescriptorName: %s\n"
16115b0a 598 "%sSELinuxContextFromNet: %s\n",
a16e1123 599 prefix, socket_state_to_string(s->state),
81a5c6d0 600 prefix, socket_result_to_string(s->result),
c968d76a 601 prefix, socket_result_to_string(s->clean_result),
c0120d99 602 prefix, socket_address_bind_ipv6_only_to_string(s->bind_ipv6_only),
b5a0699f
LP
603 prefix, s->backlog,
604 prefix, s->socket_mode,
4fd5948e
LP
605 prefix, s->directory_mode,
606 prefix, yes_no(s->keep_alive),
4427c3f4 607 prefix, yes_no(s->no_delay),
cebf8b20 608 prefix, yes_no(s->free_bind),
6b6d2dee 609 prefix, yes_no(s->transparent),
ec6370a2 610 prefix, yes_no(s->broadcast),
d68af586 611 prefix, yes_no(s->pass_cred),
54ecda32 612 prefix, yes_no(s->pass_sec),
a3d19f5d 613 prefix, yes_no(s->pass_pktinfo),
bd1fe7c7 614 prefix, strna(s->tcp_congestion),
16115b0a 615 prefix, yes_no(s->remove_on_stop),
55301ec0 616 prefix, yes_no(s->writable),
8dd4c05b 617 prefix, socket_fdname(s),
16115b0a 618 prefix, yes_no(s->selinux_context_from_net));
542563ba 619
9b191525
LP
620 if (s->timestamping != SOCKET_TIMESTAMPING_OFF)
621 fprintf(f,
622 "%sTimestamping: %s\n",
623 prefix, socket_timestamping_to_string(s->timestamping));
624
70123e68
LP
625 if (s->control_pid > 0)
626 fprintf(f,
de0671ee
ZJS
627 "%sControl PID: "PID_FMT"\n",
628 prefix, s->control_pid);
70123e68 629
acbb0225
LP
630 if (s->bind_to_device)
631 fprintf(f,
632 "%sBindToDevice: %s\n",
633 prefix, s->bind_to_device);
634
4f2d528d
LP
635 if (s->accept)
636 fprintf(f,
6cf6bbc2
LP
637 "%sAccepted: %u\n"
638 "%sNConnections: %u\n"
827d9bf2
YW
639 "%sMaxConnections: %u\n"
640 "%sMaxConnectionsPerSource: %u\n",
6cf6bbc2
LP
641 prefix, s->n_accepted,
642 prefix, s->n_connections,
827d9bf2
YW
643 prefix, s->max_connections,
644 prefix, s->max_connections_per_source);
3e5f04bf
RM
645 else
646 fprintf(f,
647 "%sFlushPending: %s\n",
648 prefix, yes_no(s->flush_pending));
649
4f2d528d 650
4fd5948e
LP
651 if (s->priority >= 0)
652 fprintf(f,
653 "%sPriority: %i\n",
654 prefix, s->priority);
655
656 if (s->receive_buffer > 0)
657 fprintf(f,
658 "%sReceiveBuffer: %zu\n",
659 prefix, s->receive_buffer);
660
661 if (s->send_buffer > 0)
662 fprintf(f,
663 "%sSendBuffer: %zu\n",
664 prefix, s->send_buffer);
665
666 if (s->ip_tos >= 0)
667 fprintf(f,
668 "%sIPTOS: %i\n",
669 prefix, s->ip_tos);
670
671 if (s->ip_ttl >= 0)
672 fprintf(f,
673 "%sIPTTL: %i\n",
674 prefix, s->ip_ttl);
675
676 if (s->pipe_size > 0)
677 fprintf(f,
678 "%sPipeSize: %zu\n",
679 prefix, s->pipe_size);
680
681 if (s->mark >= 0)
682 fprintf(f,
683 "%sMark: %i\n",
684 prefix, s->mark);
685
916abb21
LP
686 if (s->mq_maxmsg > 0)
687 fprintf(f,
688 "%sMessageQueueMaxMessages: %li\n",
689 prefix, s->mq_maxmsg);
690
691 if (s->mq_msgsize > 0)
692 fprintf(f,
693 "%sMessageQueueMessageSize: %li\n",
694 prefix, s->mq_msgsize);
695
718db961 696 if (s->reuse_port)
f7db7a69
SL
697 fprintf(f,
698 "%sReusePort: %s\n",
718db961 699 prefix, yes_no(s->reuse_port));
f7db7a69 700
0eb59ccf
AK
701 if (s->smack)
702 fprintf(f,
703 "%sSmackLabel: %s\n",
704 prefix, s->smack);
705
706 if (s->smack_ip_in)
707 fprintf(f,
708 "%sSmackLabelIPIn: %s\n",
709 prefix, s->smack_ip_in);
710
711 if (s->smack_ip_out)
712 fprintf(f,
713 "%sSmackLabelIPOut: %s\n",
714 prefix, s->smack_ip_out);
715
3900e5fd
LP
716 if (!isempty(s->user) || !isempty(s->group))
717 fprintf(f,
d2a50e3b
LP
718 "%sSocketUser: %s\n"
719 "%sSocketGroup: %s\n",
3900e5fd
LP
720 prefix, strna(s->user),
721 prefix, strna(s->group));
722
3cd761e4 723 if (s->keep_alive_time > 0)
209e9dcd 724 fprintf(f,
3cd761e4
LP
725 "%sKeepAliveTimeSec: %s\n",
726 prefix, format_timespan(time_string, FORMAT_TIMESPAN_MAX, s->keep_alive_time, USEC_PER_SEC));
209e9dcd 727
7be9df7d 728 if (s->keep_alive_interval > 0)
209e9dcd 729 fprintf(f,
3cd761e4
LP
730 "%sKeepAliveIntervalSec: %s\n",
731 prefix, format_timespan(time_string, FORMAT_TIMESPAN_MAX, s->keep_alive_interval, USEC_PER_SEC));
209e9dcd 732
7be9df7d 733 if (s->keep_alive_cnt > 0)
209e9dcd
SS
734 fprintf(f,
735 "%sKeepAliveProbes: %u\n",
736 prefix, s->keep_alive_cnt);
737
7be9df7d 738 if (s->defer_accept > 0)
cc567c9b 739 fprintf(f,
3cd761e4
LP
740 "%sDeferAcceptSec: %s\n",
741 prefix, format_timespan(time_string, FORMAT_TIMESPAN_MAX, s->defer_accept, USEC_PER_SEC));
cc567c9b 742
034c6ed7 743 LIST_FOREACH(port, p, s->ports) {
5cb5a6ff 744
7be9df7d
YW
745 switch (p->type) {
746 case SOCKET_SOCKET: {
747 _cleanup_free_ char *k = NULL;
542563ba
LP
748 const char *t;
749 int r;
542563ba 750
e53fc357
LP
751 r = socket_address_print(&p->address, &k);
752 if (r < 0)
4bbccb02 753 t = strerror_safe(r);
542563ba
LP
754 else
755 t = k;
756
7a22745a 757 fprintf(f, "%s%s: %s\n", prefix, listen_lookup(socket_address_family(&p->address), p->address.type), t);
7be9df7d
YW
758 break;
759 }
760 case SOCKET_SPECIAL:
b0a3f2bc 761 fprintf(f, "%sListenSpecial: %s\n", prefix, p->path);
7be9df7d
YW
762 break;
763 case SOCKET_USB_FUNCTION:
60252446 764 fprintf(f, "%sListenUSBFunction: %s\n", prefix, p->path);
7be9df7d
YW
765 break;
766 case SOCKET_MQUEUE:
916abb21 767 fprintf(f, "%sListenMessageQueue: %s\n", prefix, p->path);
7be9df7d
YW
768 break;
769 default:
542563ba 770 fprintf(f, "%sListenFIFO: %s\n", prefix, p->path);
7be9df7d 771 }
542563ba 772 }
5cb5a6ff 773
1745fa70
EV
774 fprintf(f,
775 "%sTriggerLimitIntervalSec: %s\n"
776 "%sTriggerLimitBurst: %u\n",
777 prefix, format_timespan(time_string, FORMAT_TIMESPAN_MAX, s->trigger_limit.interval, USEC_PER_SEC),
778 prefix, s->trigger_limit.burst);
779
da96ad5a 780 str = ip_protocol_to_name(s->socket_protocol);
827d9bf2
YW
781 if (str)
782 fprintf(f, "%sSocketProtocol: %s\n", prefix, str);
783
784 if (!strv_isempty(s->symlinks)) {
785 char **q;
786
787 fprintf(f, "%sSymlinks:", prefix);
788 STRV_FOREACH(q, s->symlinks)
789 fprintf(f, " %s", *q);
790
791 fprintf(f, "\n");
792 }
793
794 fprintf(f,
795 "%sTimeoutSec: %s\n",
796 prefix, format_timespan(time_string, FORMAT_TIMESPAN_MAX, s->timeout_usec, USEC_PER_SEC));
797
5cb5a6ff 798 exec_context_dump(&s->exec_context, f, prefix);
4819ff03 799 kill_context_dump(&s->kill_context, f, prefix);
5cb5a6ff 800
e537352b 801 for (c = 0; c < _SOCKET_EXEC_COMMAND_MAX; c++) {
c43d20a0
LP
802 if (!s->exec_command[c])
803 continue;
5cb5a6ff 804
40d50879 805 fprintf(f, "%s-> %s:\n",
a16e1123 806 prefix, socket_exec_command_to_string(c));
c43d20a0
LP
807
808 exec_command_dump_list(s->exec_command[c], f, prefix2);
5cb5a6ff 809 }
18f573aa 810
bc0623df 811 cgroup_context_dump(UNIT(s), f, prefix);
5cb5a6ff
LP
812}
813
4f2d528d
LP
814static int instance_from_socket(int fd, unsigned nr, char **instance) {
815 socklen_t l;
816 char *r;
9d16d0c7 817 union sockaddr_union local, remote;
4f2d528d
LP
818
819 assert(fd >= 0);
820 assert(instance);
821
822 l = sizeof(local);
823 if (getsockname(fd, &local.sa, &l) < 0)
824 return -errno;
825
826 l = sizeof(remote);
827 if (getpeername(fd, &remote.sa, &l) < 0)
828 return -errno;
829
830 switch (local.sa.sa_family) {
831
832 case AF_INET: {
833 uint32_t
8e38570e
LP
834 a = be32toh(local.in.sin_addr.s_addr),
835 b = be32toh(remote.in.sin_addr.s_addr);
4f2d528d
LP
836
837 if (asprintf(&r,
77b088c2
LP
838 "%u-%u.%u.%u.%u:%u-%u.%u.%u.%u:%u",
839 nr,
4f2d528d 840 a >> 24, (a >> 16) & 0xFF, (a >> 8) & 0xFF, a & 0xFF,
8e38570e 841 be16toh(local.in.sin_port),
4f2d528d 842 b >> 24, (b >> 16) & 0xFF, (b >> 8) & 0xFF, b & 0xFF,
8e38570e 843 be16toh(remote.in.sin_port)) < 0)
4f2d528d
LP
844 return -ENOMEM;
845
846 break;
847 }
848
849 case AF_INET6: {
c65a0b14 850 static const unsigned char ipv4_prefix[] = {
2b061f5a
LP
851 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xFF, 0xFF
852 };
853
854 if (memcmp(&local.in6.sin6_addr, ipv4_prefix, sizeof(ipv4_prefix)) == 0 &&
855 memcmp(&remote.in6.sin6_addr, ipv4_prefix, sizeof(ipv4_prefix)) == 0) {
856 const uint8_t
857 *a = local.in6.sin6_addr.s6_addr+12,
858 *b = remote.in6.sin6_addr.s6_addr+12;
859
860 if (asprintf(&r,
77b088c2
LP
861 "%u-%u.%u.%u.%u:%u-%u.%u.%u.%u:%u",
862 nr,
2b061f5a 863 a[0], a[1], a[2], a[3],
8e38570e 864 be16toh(local.in6.sin6_port),
2b061f5a 865 b[0], b[1], b[2], b[3],
8e38570e 866 be16toh(remote.in6.sin6_port)) < 0)
2b061f5a
LP
867 return -ENOMEM;
868 } else {
869 char a[INET6_ADDRSTRLEN], b[INET6_ADDRSTRLEN];
870
871 if (asprintf(&r,
77b088c2
LP
872 "%u-%s:%u-%s:%u",
873 nr,
2b061f5a 874 inet_ntop(AF_INET6, &local.in6.sin6_addr, a, sizeof(a)),
8e38570e 875 be16toh(local.in6.sin6_port),
2b061f5a 876 inet_ntop(AF_INET6, &remote.in6.sin6_addr, b, sizeof(b)),
8e38570e 877 be16toh(remote.in6.sin6_port)) < 0)
2b061f5a
LP
878 return -ENOMEM;
879 }
4f2d528d
LP
880
881 break;
882 }
883
884 case AF_UNIX: {
885 struct ucred ucred;
eff05270 886 int k;
4f2d528d 887
eff05270 888 k = getpeercred(fd, &ucred);
d38f6e34
ZJS
889 if (k >= 0) {
890 if (asprintf(&r,
891 "%u-"PID_FMT"-"UID_FMT,
892 nr, ucred.pid, ucred.uid) < 0)
893 return -ENOMEM;
894 } else if (k == -ENODATA) {
895 /* This handles the case where somebody is
896 * connecting from another pid/uid namespace
897 * (e.g. from outside of our container). */
898 if (asprintf(&r,
899 "%u-unknown",
900 nr) < 0)
901 return -ENOMEM;
902 } else
eff05270 903 return k;
2f20a8eb 904
2f20a8eb 905 break;
4f2d528d
LP
906 }
907
359a5bcf
SH
908 case AF_VSOCK:
909 if (asprintf(&r,
910 "%u-%u:%u-%u:%u",
911 nr,
912 local.vm.svm_cid, local.vm.svm_port,
913 remote.vm.svm_cid, remote.vm.svm_port) < 0)
914 return -ENOMEM;
915
916 break;
917
4f2d528d
LP
918 default:
919 assert_not_reached("Unhandled socket type.");
920 }
921
922 *instance = r;
923 return 0;
924}
925
034c6ed7 926static void socket_close_fds(Socket *s) {
83c60c9f 927 SocketPort *p;
811ba7a0 928 char **i;
83c60c9f
LP
929
930 assert(s);
931
034c6ed7 932 LIST_FOREACH(port, p, s->ports) {
18e854f8 933 bool was_open;
718db961 934
18e854f8 935 was_open = p->fd >= 0;
83c60c9f 936
18e854f8 937 p->event_source = sd_event_source_unref(p->event_source);
03e334a1 938 p->fd = safe_close(p->fd);
15087cdb 939 socket_cleanup_fd_list(p);
a16e1123 940
18e854f8
LP
941 /* One little note: we should normally not delete any sockets in the file system here! After all some
942 * other process we spawned might still have a reference of this fd and wants to continue to use
943 * it. Therefore we normally delete sockets in the file system before we create a new one, not after we
944 * stopped using one! That all said, if the user explicitly requested this, we'll delete them here
945 * anyway, but only then. */
bd1fe7c7 946
18e854f8
LP
947 if (!was_open || !s->remove_on_stop)
948 continue;
949
950 switch (p->type) {
bd1fe7c7 951
18e854f8
LP
952 case SOCKET_FIFO:
953 (void) unlink(p->path);
954 break;
bd1fe7c7 955
18e854f8
LP
956 case SOCKET_MQUEUE:
957 (void) mq_unlink(p->path);
958 break;
bd1fe7c7 959
18e854f8
LP
960 case SOCKET_SOCKET:
961 (void) socket_address_unlink(&p->address);
962 break;
bd1fe7c7 963
18e854f8
LP
964 default:
965 break;
bd1fe7c7 966 }
83c60c9f 967 }
811ba7a0
LP
968
969 if (s->remove_on_stop)
970 STRV_FOREACH(i, s->symlinks)
18e854f8 971 (void) unlink(*i);
83c60c9f
LP
972}
973
5d0fe423 974static void socket_apply_socket_options(Socket *s, SocketPort *p, int fd) {
d53e386d
LP
975 int r;
976
4fd5948e 977 assert(s);
5d0fe423 978 assert(p);
4fd5948e
LP
979 assert(fd >= 0);
980
981 if (s->keep_alive) {
2ff48e98
LP
982 r = setsockopt_int(fd, SOL_SOCKET, SO_KEEPALIVE, true);
983 if (r < 0)
984 log_unit_warning_errno(UNIT(s), r, "SO_KEEPALIVE failed: %m");
4fd5948e
LP
985 }
986
7be9df7d 987 if (s->keep_alive_time > 0) {
9e5b6496
YW
988 r = setsockopt_int(fd, SOL_TCP, TCP_KEEPIDLE, s->keep_alive_time / USEC_PER_SEC);
989 if (r < 0)
990 log_unit_warning_errno(UNIT(s), r, "TCP_KEEPIDLE failed: %m");
209e9dcd
SS
991 }
992
7be9df7d 993 if (s->keep_alive_interval > 0) {
9e5b6496
YW
994 r = setsockopt_int(fd, SOL_TCP, TCP_KEEPINTVL, s->keep_alive_interval / USEC_PER_SEC);
995 if (r < 0)
996 log_unit_warning_errno(UNIT(s), r, "TCP_KEEPINTVL failed: %m");
209e9dcd
SS
997 }
998
7be9df7d 999 if (s->keep_alive_cnt > 0) {
9e5b6496
YW
1000 r = setsockopt_int(fd, SOL_TCP, TCP_KEEPCNT, s->keep_alive_cnt);
1001 if (r < 0)
1002 log_unit_warning_errno(UNIT(s), r, "TCP_KEEPCNT failed: %m");
209e9dcd
SS
1003 }
1004
7be9df7d 1005 if (s->defer_accept > 0) {
9e5b6496
YW
1006 r = setsockopt_int(fd, SOL_TCP, TCP_DEFER_ACCEPT, s->defer_accept / USEC_PER_SEC);
1007 if (r < 0)
1008 log_unit_warning_errno(UNIT(s), r, "TCP_DEFER_ACCEPT failed: %m");
cc567c9b
SS
1009 }
1010
4427c3f4 1011 if (s->no_delay) {
62bc4efc 1012 if (s->socket_protocol == IPPROTO_SCTP) {
2ff48e98
LP
1013 r = setsockopt_int(fd, SOL_SCTP, SCTP_NODELAY, true);
1014 if (r < 0)
1015 log_unit_warning_errno(UNIT(s), r, "SCTP_NODELAY failed: %m");
62bc4efc 1016 } else {
2ff48e98
LP
1017 r = setsockopt_int(fd, SOL_TCP, TCP_NODELAY, true);
1018 if (r < 0)
1019 log_unit_warning_errno(UNIT(s), r, "TCP_NODELAY failed: %m");
62bc4efc 1020 }
4427c3f4
SS
1021 }
1022
ec6370a2 1023 if (s->broadcast) {
2ff48e98
LP
1024 r = setsockopt_int(fd, SOL_SOCKET, SO_BROADCAST, true);
1025 if (r < 0)
1026 log_unit_warning_errno(UNIT(s), r, "SO_BROADCAST failed: %m");
ec6370a2
LP
1027 }
1028
d68af586 1029 if (s->pass_cred) {
2ff48e98
LP
1030 r = setsockopt_int(fd, SOL_SOCKET, SO_PASSCRED, true);
1031 if (r < 0)
1032 log_unit_warning_errno(UNIT(s), r, "SO_PASSCRED failed: %m");
d68af586
MS
1033 }
1034
54ecda32 1035 if (s->pass_sec) {
2ff48e98
LP
1036 r = setsockopt_int(fd, SOL_SOCKET, SO_PASSSEC, true);
1037 if (r < 0)
1038 log_unit_warning_errno(UNIT(s), r, "SO_PASSSEC failed: %m");
54ecda32
LP
1039 }
1040
a3d19f5d 1041 if (s->pass_pktinfo) {
5d0fe423 1042 r = socket_set_recvpktinfo(fd, socket_address_family(&p->address), true);
a3d19f5d
LP
1043 if (r < 0)
1044 log_unit_warning_errno(UNIT(s), r, "Failed to enable packet info socket option: %m");
1045 }
1046
9b191525
LP
1047 if (s->timestamping != SOCKET_TIMESTAMPING_OFF) {
1048 r = setsockopt_int(fd, SOL_SOCKET,
1049 s->timestamping == SOCKET_TIMESTAMPING_NS ? SO_TIMESTAMPNS : SO_TIMESTAMP,
1050 true);
1051 if (r < 0)
1052 log_unit_warning_errno(UNIT(s), r, "Failed to enable timestamping socket option, ignoring: %m");
1053 }
1054
9e5b6496
YW
1055 if (s->priority >= 0) {
1056 r = setsockopt_int(fd, SOL_SOCKET, SO_PRIORITY, s->priority);
1057 if (r < 0)
1058 log_unit_warning_errno(UNIT(s), r, "SO_PRIORITY failed: %m");
1059 }
4fd5948e
LP
1060
1061 if (s->receive_buffer > 0) {
ded71ab3
YW
1062 r = fd_set_rcvbuf(fd, s->receive_buffer, false);
1063 if (r < 0)
35b4e3c1
LP
1064 log_unit_full_errno(UNIT(s), ERRNO_IS_PRIVILEGE(r) ? LOG_DEBUG : LOG_WARNING, r,
1065 "SO_RCVBUF/SO_RCVBUFFORCE failed: %m");
4fd5948e
LP
1066 }
1067
1068 if (s->send_buffer > 0) {
4934ba21 1069 r = fd_set_sndbuf(fd, s->send_buffer, false);
ded71ab3 1070 if (r < 0)
35b4e3c1
LP
1071 log_unit_full_errno(UNIT(s), ERRNO_IS_PRIVILEGE(r) ? LOG_DEBUG : LOG_WARNING, r,
1072 "SO_SNDBUF/SO_SNDBUFFORCE failed: %m");
4fd5948e
LP
1073 }
1074
9e5b6496
YW
1075 if (s->mark >= 0) {
1076 r = setsockopt_int(fd, SOL_SOCKET, SO_MARK, s->mark);
1077 if (r < 0)
1078 log_unit_warning_errno(UNIT(s), r, "SO_MARK failed: %m");
1079 }
4fd5948e 1080
9e5b6496
YW
1081 if (s->ip_tos >= 0) {
1082 r = setsockopt_int(fd, IPPROTO_IP, IP_TOS, s->ip_tos);
1083 if (r < 0)
1084 log_unit_warning_errno(UNIT(s), r, "IP_TOS failed: %m");
1085 }
4fd5948e 1086
46925ac5 1087 if (s->ip_ttl >= 0) {
5d0fe423
LP
1088 r = socket_set_ttl(fd, socket_address_family(&p->address), s->ip_ttl);
1089 if (r < 0)
9e5b6496 1090 log_unit_warning_errno(UNIT(s), r, "IP_TTL/IPV6_UNICAST_HOPS failed: %m");
46925ac5 1091 }
cebf8b20
TT
1092
1093 if (s->tcp_congestion)
1094 if (setsockopt(fd, SOL_TCP, TCP_CONGESTION, s->tcp_congestion, strlen(s->tcp_congestion)+1) < 0)
f2341e0a 1095 log_unit_warning_errno(UNIT(s), errno, "TCP_CONGESTION failed: %m");
0eb59ccf 1096
d53e386d 1097 if (s->smack_ip_in) {
5ab58c20 1098 r = mac_smack_apply_fd(fd, SMACK_ATTR_IPIN, s->smack_ip_in);
d53e386d 1099 if (r < 0)
f2341e0a 1100 log_unit_error_errno(UNIT(s), r, "mac_smack_apply_ip_in_fd: %m");
d53e386d 1101 }
9a4e038c 1102
d53e386d 1103 if (s->smack_ip_out) {
5ab58c20 1104 r = mac_smack_apply_fd(fd, SMACK_ATTR_IPOUT, s->smack_ip_out);
d53e386d 1105 if (r < 0)
f2341e0a 1106 log_unit_error_errno(UNIT(s), r, "mac_smack_apply_ip_out_fd: %m");
d53e386d 1107 }
4fd5948e
LP
1108}
1109
b15bdda8 1110static void socket_apply_fifo_options(Socket *s, int fd) {
d53e386d
LP
1111 int r;
1112
4fd5948e
LP
1113 assert(s);
1114 assert(fd >= 0);
1115
1116 if (s->pipe_size > 0)
1117 if (fcntl(fd, F_SETPIPE_SZ, s->pipe_size) < 0)
ed460b07 1118 log_unit_warning_errno(UNIT(s), errno, "Setting pipe size failed, ignoring: %m");
0eb59ccf 1119
d53e386d 1120 if (s->smack) {
5ab58c20 1121 r = mac_smack_apply_fd(fd, SMACK_ATTR_ACCESS, s->smack);
d53e386d 1122 if (r < 0)
ed460b07 1123 log_unit_error_errno(UNIT(s), r, "SMACK relabelling failed, ignoring: %m");
d53e386d 1124 }
4fd5948e
LP
1125}
1126
b15bdda8
LP
1127static int fifo_address_create(
1128 const char *path,
1129 mode_t directory_mode,
e8da24a6 1130 mode_t socket_mode) {
b15bdda8 1131
e8da24a6 1132 _cleanup_close_ int fd = -1;
b15bdda8 1133 mode_t old_mask;
e8da24a6
LP
1134 struct stat st;
1135 int r;
b15bdda8
LP
1136
1137 assert(path);
b15bdda8 1138
1af87ab7 1139 (void) mkdir_parents_label(path, directory_mode);
b15bdda8 1140
ecabcf8b 1141 r = mac_selinux_create_file_prepare(path, S_IFIFO);
e9a5ef7c 1142 if (r < 0)
e8da24a6 1143 return r;
b15bdda8
LP
1144
1145 /* Enforce the right access mode for the fifo */
7be9df7d 1146 old_mask = umask(~socket_mode);
b15bdda8
LP
1147
1148 /* Include the original umask in our mask */
e8da24a6 1149 (void) umask(~socket_mode | old_mask);
b15bdda8
LP
1150
1151 r = mkfifo(path, socket_mode);
e8da24a6 1152 (void) umask(old_mask);
b15bdda8 1153
94bc2731 1154 if (r < 0 && errno != EEXIST) {
b15bdda8
LP
1155 r = -errno;
1156 goto fail;
1157 }
1158
e8da24a6 1159 fd = open(path, O_RDWR | O_CLOEXEC | O_NOCTTY | O_NONBLOCK | O_NOFOLLOW);
3cc2aff1 1160 if (fd < 0) {
b15bdda8
LP
1161 r = -errno;
1162 goto fail;
1163 }
1164
ecabcf8b 1165 mac_selinux_create_file_clear();
7a58bfa4 1166
b15bdda8
LP
1167 if (fstat(fd, &st) < 0) {
1168 r = -errno;
1169 goto fail;
1170 }
1171
1172 if (!S_ISFIFO(st.st_mode) ||
de0200fc 1173 (st.st_mode & 0777) != (socket_mode & ~old_mask) ||
e4f44e73
DR
1174 st.st_uid != getuid() ||
1175 st.st_gid != getgid()) {
b15bdda8
LP
1176 r = -EEXIST;
1177 goto fail;
1178 }
1179
c10d6bdb 1180 return TAKE_FD(fd);
b15bdda8
LP
1181
1182fail:
ecabcf8b 1183 mac_selinux_create_file_clear();
b15bdda8
LP
1184 return r;
1185}
1186
55301ec0 1187static int special_address_create(const char *path, bool writable) {
e8da24a6 1188 _cleanup_close_ int fd = -1;
b0a3f2bc
LP
1189 struct stat st;
1190
1191 assert(path);
b0a3f2bc 1192
55301ec0 1193 fd = open(path, (writable ? O_RDWR : O_RDONLY)|O_CLOEXEC|O_NOCTTY|O_NONBLOCK|O_NOFOLLOW);
e8da24a6
LP
1194 if (fd < 0)
1195 return -errno;
b0a3f2bc 1196
e8da24a6
LP
1197 if (fstat(fd, &st) < 0)
1198 return -errno;
b0a3f2bc
LP
1199
1200 /* Check whether this is a /proc, /sys or /dev file or char device */
e8da24a6
LP
1201 if (!S_ISREG(st.st_mode) && !S_ISCHR(st.st_mode))
1202 return -EEXIST;
b0a3f2bc 1203
c10d6bdb 1204 return TAKE_FD(fd);
b0a3f2bc
LP
1205}
1206
36078102 1207static int usbffs_address_create(const char *path) {
60252446
PS
1208 _cleanup_close_ int fd = -1;
1209 struct stat st;
1210
1211 assert(path);
60252446
PS
1212
1213 fd = open(path, O_RDWR|O_CLOEXEC|O_NOCTTY|O_NONBLOCK|O_NOFOLLOW);
1214 if (fd < 0)
1215 return -errno;
1216
1217 if (fstat(fd, &st) < 0)
1218 return -errno;
1219
13e785f7 1220 /* Check whether this is a regular file (ffs endpoint) */
60252446
PS
1221 if (!S_ISREG(st.st_mode))
1222 return -EEXIST;
1223
c10d6bdb 1224 return TAKE_FD(fd);
60252446
PS
1225}
1226
916abb21
LP
1227static int mq_address_create(
1228 const char *path,
1229 mode_t mq_mode,
1230 long maxmsg,
e8da24a6 1231 long msgsize) {
916abb21 1232
e8da24a6 1233 _cleanup_close_ int fd = -1;
916abb21
LP
1234 struct stat st;
1235 mode_t old_mask;
1236 struct mq_attr _attr, *attr = NULL;
1237
1238 assert(path);
916abb21
LP
1239
1240 if (maxmsg > 0 && msgsize > 0) {
e8da24a6
LP
1241 _attr = (struct mq_attr) {
1242 .mq_flags = O_NONBLOCK,
1243 .mq_maxmsg = maxmsg,
1244 .mq_msgsize = msgsize,
1245 };
916abb21
LP
1246 attr = &_attr;
1247 }
1248
1249 /* Enforce the right access mode for the mq */
7be9df7d 1250 old_mask = umask(~mq_mode);
916abb21
LP
1251
1252 /* Include the original umask in our mask */
e8da24a6 1253 (void) umask(~mq_mode | old_mask);
916abb21 1254 fd = mq_open(path, O_RDONLY|O_CLOEXEC|O_NONBLOCK|O_CREAT, mq_mode, attr);
e8da24a6 1255 (void) umask(old_mask);
916abb21 1256
e8da24a6
LP
1257 if (fd < 0)
1258 return -errno;
916abb21 1259
e8da24a6
LP
1260 if (fstat(fd, &st) < 0)
1261 return -errno;
916abb21
LP
1262
1263 if ((st.st_mode & 0777) != (mq_mode & ~old_mask) ||
1264 st.st_uid != getuid() ||
e8da24a6
LP
1265 st.st_gid != getgid())
1266 return -EEXIST;
916abb21 1267
c10d6bdb 1268 return TAKE_FD(fd);
916abb21
LP
1269}
1270
811ba7a0
LP
1271static int socket_symlink(Socket *s) {
1272 const char *p;
1273 char **i;
95f7fbbf 1274 int r;
811ba7a0
LP
1275
1276 assert(s);
1277
1278 p = socket_find_symlink_target(s);
1279 if (!p)
1280 return 0;
1281
95f7fbbf 1282 STRV_FOREACH(i, s->symlinks) {
1af87ab7
LP
1283 (void) mkdir_parents_label(*i, s->directory_mode);
1284
6c9c51e5 1285 r = symlink_idempotent(p, *i, false);
22b20752
LP
1286
1287 if (r == -EEXIST && s->remove_on_stop) {
1288 /* If there's already something where we want to create the symlink, and the destructive
1289 * RemoveOnStop= mode is set, then we might as well try to remove what already exists and try
1290 * again. */
1291
1292 if (unlink(*i) >= 0)
6c9c51e5 1293 r = symlink_idempotent(p, *i, false);
22b20752
LP
1294 }
1295
95f7fbbf
LP
1296 if (r < 0)
1297 log_unit_warning_errno(UNIT(s), r, "Failed to create symlink %s → %s, ignoring: %m", p, *i);
1298 }
811ba7a0
LP
1299
1300 return 0;
1301}
1302
36078102 1303static int usbffs_write_descs(int fd, Service *s) {
6b7e5923
PS
1304 int r;
1305
1306 if (!s->usb_function_descriptors || !s->usb_function_strings)
1307 return -EINVAL;
1308
1c876927 1309 r = copy_file_fd(s->usb_function_descriptors, fd, 0);
6b7e5923 1310 if (r < 0)
e8da24a6 1311 return r;
6b7e5923 1312
1c876927 1313 return copy_file_fd(s->usb_function_strings, fd, 0);
6b7e5923
PS
1314}
1315
36078102 1316static int usbffs_select_ep(const struct dirent *d) {
60252446
PS
1317 return d->d_name[0] != '.' && !streq(d->d_name, "ep0");
1318}
1319
36078102 1320static int usbffs_dispatch_eps(SocketPort *p) {
60252446 1321 _cleanup_free_ struct dirent **ent = NULL;
da6053d0
LP
1322 size_t n, k, i;
1323 int r;
60252446 1324
00bb64ec 1325 r = scandir(p->path, &ent, usbffs_select_ep, alphasort);
60252446
PS
1326 if (r < 0)
1327 return -errno;
1328
da6053d0 1329 n = (size_t) r;
60252446 1330 p->auxiliary_fds = new(int, n);
0de48764
YW
1331 if (!p->auxiliary_fds) {
1332 r = -ENOMEM;
1333 goto clear;
1334 }
60252446
PS
1335
1336 p->n_auxiliary_fds = n;
1337
1338 k = 0;
1339 for (i = 0; i < n; ++i) {
1340 _cleanup_free_ char *ep = NULL;
1341
00bb64ec 1342 ep = path_make_absolute(ent[i]->d_name, p->path);
0de48764
YW
1343 if (!ep) {
1344 r = -ENOMEM;
1345 goto fail;
1346 }
60252446 1347
858d36c1 1348 path_simplify(ep, false);
60252446 1349
36078102 1350 r = usbffs_address_create(ep);
60252446
PS
1351 if (r < 0)
1352 goto fail;
1353
da6053d0 1354 p->auxiliary_fds[k++] = r;
60252446
PS
1355 }
1356
0de48764
YW
1357 r = 0;
1358 goto clear;
60252446
PS
1359
1360fail:
e8da24a6 1361 close_many(p->auxiliary_fds, k);
60252446
PS
1362 p->auxiliary_fds = mfree(p->auxiliary_fds);
1363 p->n_auxiliary_fds = 0;
1364
0de48764
YW
1365clear:
1366 for (i = 0; i < n; ++i)
1367 free(ent[i]);
1368
60252446
PS
1369 return r;
1370}
1371
934ef6a5
ZJS
1372int socket_load_service_unit(Socket *s, int cfd, Unit **ret) {
1373 /* Figure out what the unit that will be used to handle the connections on the socket looks like.
1374 *
1375 * If cfd < 0, then we don't have a connection yet. In case of Accept=yes sockets, use a fake
1376 * instance name.
1377 */
1378
1379 if (UNIT_ISSET(s->service)) {
1380 *ret = UNIT_DEREF(s->service);
1381 return 0;
1382 }
1383
1384 if (!s->accept)
1385 return -ENODATA;
1386
1387 /* Build the instance name and load the unit */
1388 _cleanup_free_ char *prefix = NULL, *instance = NULL, *name = NULL;
1389 int r;
1390
1391 r = unit_name_to_prefix(UNIT(s)->id, &prefix);
1392 if (r < 0)
1393 return r;
1394
1395 if (cfd >= 0) {
1396 r = instance_from_socket(cfd, s->n_accepted, &instance);
86e045ec
ZJS
1397 if (ERRNO_IS_DISCONNECT(r))
1398 /* ENOTCONN is legitimate if TCP RST was received. Other socket families might return
1399 * different errors. This connection is over, but the socket unit lives on. */
934ef6a5 1400 return log_unit_debug_errno(UNIT(s), r,
86e045ec
ZJS
1401 "Got %s on incoming socket, assuming aborted connection attempt, ignoring.",
1402 errno_to_name(r));
934ef6a5
ZJS
1403 if (r < 0)
1404 return r;
1405 }
1406
1407 /* For accepting sockets, we don't know how the instance will be called until we get a connection and
1408 * can figure out what the peer name is. So let's use "internal" as the instance to make it clear
1409 * that this is not an actual peer name. We use "unknown" when we cannot figure out the peer. */
1410 r = unit_name_build(prefix, instance ?: "internal", ".service", &name);
1411 if (r < 0)
1412 return r;
1413
1414 return manager_load_unit(UNIT(s)->manager, name, NULL, NULL, ret);
1415}
1416
d24e561d 1417static int socket_determine_selinux_label(Socket *s, char **ret) {
d24e561d
LP
1418 int r;
1419
1420 assert(s);
1421 assert(ret);
1422
1423 if (s->selinux_context_from_net) {
934ef6a5 1424 /* If this is requested, get the label from the network label */
d24e561d
LP
1425
1426 r = mac_selinux_get_our_label(ret);
1427 if (r == -EOPNOTSUPP)
1428 goto no_label;
1429
1430 } else {
934ef6a5 1431 /* Otherwise, get it from the executable we are about to start. */
d24e561d 1432
934ef6a5
ZJS
1433 Unit *service;
1434 ExecCommand *c;
1435 _cleanup_free_ char *path = NULL;
1436
1437 r = socket_load_service_unit(s, -1, &service);
1438 if (r == -ENODATA)
d24e561d 1439 goto no_label;
934ef6a5
ZJS
1440 if (r < 0)
1441 return r;
d24e561d 1442
934ef6a5 1443 c = SERVICE(service)->exec_command[SERVICE_EXEC_START];
d24e561d
LP
1444 if (!c)
1445 goto no_label;
1446
934ef6a5 1447 r = chase_symlinks(c->path, SERVICE(service)->exec_context.root_directory, CHASE_PREFIX_ROOT, &path, NULL);
2ef044ea
FB
1448 if (r < 0)
1449 goto no_label;
1450
416be1a0 1451 r = mac_selinux_get_create_label_from_exe(path, ret);
4c701096 1452 if (IN_SET(r, -EPERM, -EOPNOTSUPP))
d24e561d
LP
1453 goto no_label;
1454 }
1455
1456 return r;
1457
1458no_label:
1459 *ret = NULL;
1460 return 0;
1461}
1462
a79279c7
LP
1463static int socket_address_listen_do(
1464 Socket *s,
1465 const SocketAddress *address,
1466 const char *label) {
1467
1468 assert(s);
1469 assert(address);
1470
1471 return socket_address_listen(
1472 address,
1473 SOCK_CLOEXEC|SOCK_NONBLOCK,
1474 s->backlog,
1475 s->bind_ipv6_only,
1476 s->bind_to_device,
1477 s->reuse_port,
1478 s->free_bind,
1479 s->transparent,
1480 s->directory_mode,
1481 s->socket_mode,
1482 label);
1483}
1484
65486032
YW
1485#define log_address_error_errno(u, address, error, fmt) \
1486 ({ \
1487 _cleanup_free_ char *_t = NULL; \
1488 \
1489 (void) socket_address_print(address, &_t); \
1490 log_unit_error_errno(u, error, fmt, strna(_t)); \
1491 })
ae05e1b6 1492
7619cb32
LP
1493static int fork_needed(const SocketAddress *address, const ExecContext *context) {
1494 int r;
1495
1496 assert(address);
1497 assert(context);
1498
1499 /* Check if we need to do the cgroup or netns stuff. If not we can do things much simpler. */
1500
1501 if (IN_SET(address->sockaddr.sa.sa_family, AF_INET, AF_INET6)) {
1502 r = bpf_firewall_supported();
1503 if (r < 0)
1504 return r;
1505 if (r != BPF_FIREWALL_UNSUPPORTED) /* If BPF firewalling isn't supported anyway — there's no point in this forking complexity */
1506 return true;
1507 }
1508
1509 return context->private_network || context->network_namespace_path;
1510}
1511
a79279c7
LP
1512static int socket_address_listen_in_cgroup(
1513 Socket *s,
1514 const SocketAddress *address,
1515 const char *label) {
1516
1517 _cleanup_close_pair_ int pair[2] = { -1, -1 };
1518 int fd, r;
1519 pid_t pid;
1520
1521 assert(s);
1522 assert(address);
1523
7619cb32
LP
1524 /* This is a wrapper around socket_address_listen(), that forks off a helper process inside the
1525 * socket's cgroup and network namespace in which the socket is actually created. This way we ensure
1526 * the socket is actually properly attached to the unit's cgroup for the purpose of BPF filtering and
1527 * such. */
a79279c7 1528
7619cb32 1529 r = fork_needed(address, &s->exec_context);
a79279c7
LP
1530 if (r < 0)
1531 return r;
7619cb32
LP
1532 if (r == 0) {
1533 /* Shortcut things... */
1534 fd = socket_address_listen_do(s, address, label);
1535 if (fd < 0)
1536 return log_address_error_errno(UNIT(s), address, fd, "Failed to create listening socket (%s): %m");
1537
1538 return fd;
1539 }
1540
1541 r = unit_setup_exec_runtime(UNIT(s));
1542 if (r < 0)
1543 return log_unit_error_errno(UNIT(s), r, "Failed acquire runtime: %m");
1544
1545 if (s->exec_context.network_namespace_path &&
1546 s->exec_runtime &&
1547 s->exec_runtime->netns_storage_socket[0] >= 0) {
1548 r = open_netns_path(s->exec_runtime->netns_storage_socket, s->exec_context.network_namespace_path);
1549 if (r < 0)
1550 return log_unit_error_errno(UNIT(s), r, "Failed to open network namespace path %s: %m", s->exec_context.network_namespace_path);
1551 }
a79279c7
LP
1552
1553 if (socketpair(AF_UNIX, SOCK_SEQPACKET|SOCK_CLOEXEC, 0, pair) < 0)
1554 return log_unit_error_errno(UNIT(s), errno, "Failed to create communication channel: %m");
1555
4c253ed1 1556 r = unit_fork_helper_process(UNIT(s), "(sd-listen)", &pid);
a79279c7
LP
1557 if (r < 0)
1558 return log_unit_error_errno(UNIT(s), r, "Failed to fork off listener stub process: %m");
1559 if (r == 0) {
1560 /* Child */
1561
1562 pair[0] = safe_close(pair[0]);
1563
7619cb32
LP
1564 if ((s->exec_context.private_network || s->exec_context.network_namespace_path) &&
1565 s->exec_runtime &&
1566 s->exec_runtime->netns_storage_socket[0] >= 0) {
1567
1568 if (ns_type_supported(NAMESPACE_NET)) {
1569 r = setup_netns(s->exec_runtime->netns_storage_socket);
1570 if (r < 0) {
1571 log_unit_error_errno(UNIT(s), r, "Failed to join network namespace: %m");
1572 _exit(EXIT_NETWORK);
1573 }
1574 } else if (s->exec_context.network_namespace_path) {
1575 log_unit_error(UNIT(s), "Network namespace path configured but network namespaces not supported.");
1576 _exit(EXIT_NETWORK);
1577 } else
1578 log_unit_warning(UNIT(s), "PrivateNetwork=yes is configured, but the kernel does not support network namespaces, ignoring.");
1579 }
1580
a79279c7
LP
1581 fd = socket_address_listen_do(s, address, label);
1582 if (fd < 0) {
ae05e1b6 1583 log_address_error_errno(UNIT(s), address, fd, "Failed to create listening socket (%s): %m");
a79279c7
LP
1584 _exit(EXIT_FAILURE);
1585 }
1586
1587 r = send_one_fd(pair[1], fd, 0);
1588 if (r < 0) {
ae05e1b6 1589 log_address_error_errno(UNIT(s), address, r, "Failed to send listening socket (%s) to parent: %m");
a79279c7
LP
1590 _exit(EXIT_FAILURE);
1591 }
1592
1593 _exit(EXIT_SUCCESS);
1594 }
1595
1596 pair[1] = safe_close(pair[1]);
1597 fd = receive_one_fd(pair[0], 0);
1598
1599 /* We synchronously wait for the helper, as it shouldn't be slow */
d2e0ac3d 1600 r = wait_for_terminate_and_check("(sd-listen)", pid, WAIT_LOG_ABNORMAL);
a79279c7
LP
1601 if (r < 0) {
1602 safe_close(fd);
1603 return r;
1604 }
1605
1606 if (fd < 0)
ae05e1b6 1607 return log_address_error_errno(UNIT(s), address, fd, "Failed to receive listening socket (%s): %m");
a79279c7
LP
1608
1609 return fd;
a79279c7
LP
1610}
1611
e5417345
YW
1612DEFINE_TRIVIAL_CLEANUP_FUNC(Socket *, socket_close_fds);
1613
1614static int socket_open_fds(Socket *_s) {
1615 _cleanup_(socket_close_fdsp) Socket *s = _s;
710a6b50
LP
1616 _cleanup_(mac_selinux_freep) char *label = NULL;
1617 bool know_label = false;
83c60c9f
LP
1618 SocketPort *p;
1619 int r;
1620
1621 assert(s);
1622
034c6ed7 1623 LIST_FOREACH(port, p, s->ports) {
83c60c9f 1624
034c6ed7
LP
1625 if (p->fd >= 0)
1626 continue;
83c60c9f 1627
00411a13
LP
1628 switch (p->type) {
1629
1630 case SOCKET_SOCKET:
049f8642 1631
7f416dae 1632 if (!know_label) {
934ef6a5
ZJS
1633 /* Figure out the label, if we don't it know yet. We do it once for the first
1634 * socket where we need this and remember it for the rest. */
7f416dae 1635
d24e561d
LP
1636 r = socket_determine_selinux_label(s, &label);
1637 if (r < 0)
ae05e1b6 1638 return log_unit_error_errno(UNIT(s), r, "Failed to determine SELinux label: %m");
049f8642
LP
1639
1640 know_label = true;
1641 }
1642
74bb646e 1643 /* Apply the socket protocol */
d24e561d 1644 switch (p->address.type) {
d2a50e3b 1645
74bb646e
SS
1646 case SOCK_STREAM:
1647 case SOCK_SEQPACKET:
d24e561d
LP
1648 if (s->socket_protocol == IPPROTO_SCTP)
1649 p->address.protocol = s->socket_protocol;
74bb646e 1650 break;
d2a50e3b 1651
74bb646e 1652 case SOCK_DGRAM:
d24e561d
LP
1653 if (s->socket_protocol == IPPROTO_UDPLITE)
1654 p->address.protocol = s->socket_protocol;
74bb646e
SS
1655 break;
1656 }
1657
d501e52b
YW
1658 p->fd = socket_address_listen_in_cgroup(s, &p->address, label);
1659 if (p->fd < 0)
1660 return p->fd;
83c60c9f 1661
5d0fe423 1662 socket_apply_socket_options(s, p, p->fd);
811ba7a0 1663 socket_symlink(s);
00411a13 1664 break;
4fd5948e 1665
00411a13 1666 case SOCKET_SPECIAL:
b0a3f2bc 1667
d501e52b
YW
1668 p->fd = special_address_create(p->path, s->writable);
1669 if (p->fd < 0)
1670 return log_unit_error_errno(UNIT(s), p->fd, "Failed to open special file %s: %m", p->path);
00411a13 1671 break;
b0a3f2bc 1672
00411a13 1673 case SOCKET_FIFO:
83c60c9f 1674
d501e52b 1675 p->fd = fifo_address_create(
175a3d25
LP
1676 p->path,
1677 s->directory_mode,
e8da24a6 1678 s->socket_mode);
d501e52b
YW
1679 if (p->fd < 0)
1680 return log_unit_error_errno(UNIT(s), p->fd, "Failed to open FIFO %s: %m", p->path);
83c60c9f 1681
b15bdda8 1682 socket_apply_fifo_options(s, p->fd);
811ba7a0 1683 socket_symlink(s);
00411a13 1684 break;
811ba7a0 1685
00411a13 1686 case SOCKET_MQUEUE:
83c60c9f 1687
d501e52b 1688 p->fd = mq_address_create(
175a3d25
LP
1689 p->path,
1690 s->socket_mode,
1691 s->mq_maxmsg,
e8da24a6 1692 s->mq_msgsize);
d501e52b
YW
1693 if (p->fd < 0)
1694 return log_unit_error_errno(UNIT(s), p->fd, "Failed to open message queue %s: %m", p->path);
00411a13 1695 break;
e8da24a6 1696
d2a50e3b 1697 case SOCKET_USB_FUNCTION: {
27a6ea91 1698 _cleanup_free_ char *ep = NULL;
60252446 1699
27a6ea91 1700 ep = path_make_absolute("ep0", p->path);
72585a58
YW
1701 if (!ep)
1702 return -ENOMEM;
27a6ea91 1703
d501e52b
YW
1704 p->fd = usbffs_address_create(ep);
1705 if (p->fd < 0)
1706 return p->fd;
60252446 1707
36078102 1708 r = usbffs_write_descs(p->fd, SERVICE(UNIT_DEREF(s->service)));
6b7e5923 1709 if (r < 0)
e5417345 1710 return r;
6b7e5923 1711
36078102 1712 r = usbffs_dispatch_eps(p);
60252446 1713 if (r < 0)
e5417345 1714 return r;
00411a13
LP
1715
1716 break;
27a6ea91 1717 }
00411a13 1718 default:
b15bdda8 1719 assert_not_reached("Unknown port type");
00411a13 1720 }
034c6ed7
LP
1721 }
1722
e5417345 1723 s = NULL;
034c6ed7 1724 return 0;
034c6ed7
LP
1725}
1726
1727static void socket_unwatch_fds(Socket *s) {
1728 SocketPort *p;
718db961 1729 int r;
9152c765 1730
034c6ed7
LP
1731 assert(s);
1732
1733 LIST_FOREACH(port, p, s->ports) {
1734 if (p->fd < 0)
1735 continue;
1736
a4152e3f
LP
1737 if (!p->event_source)
1738 continue;
1739
1740 r = sd_event_source_set_enabled(p->event_source, SD_EVENT_OFF);
1741 if (r < 0)
f2341e0a 1742 log_unit_debug_errno(UNIT(s), r, "Failed to disable event source: %m");
83c60c9f 1743 }
034c6ed7
LP
1744}
1745
1746static int socket_watch_fds(Socket *s) {
1747 SocketPort *p;
1748 int r;
1749
1750 assert(s);
83c60c9f 1751
034c6ed7
LP
1752 LIST_FOREACH(port, p, s->ports) {
1753 if (p->fd < 0)
1754 continue;
1755
cbf60d0a 1756 if (p->event_source) {
718db961 1757 r = sd_event_source_set_enabled(p->event_source, SD_EVENT_ON);
cbf60d0a
LP
1758 if (r < 0)
1759 goto fail;
1760 } else {
151b9b96 1761 r = sd_event_add_io(UNIT(s)->manager->event, &p->event_source, p->fd, EPOLLIN, socket_dispatch_io, p);
cbf60d0a
LP
1762 if (r < 0)
1763 goto fail;
4f2d528d 1764
cbf60d0a 1765 (void) sd_event_source_set_description(p->event_source, "socket-port-io");
718db961 1766 }
034c6ed7 1767 }
83c60c9f 1768
542563ba 1769 return 0;
83c60c9f 1770
034c6ed7 1771fail:
cbf60d0a 1772 log_unit_warning_errno(UNIT(s), r, "Failed to watch listening fds: %m");
034c6ed7
LP
1773 socket_unwatch_fds(s);
1774 return r;
1775}
1776
01a8b467
LP
1777enum {
1778 SOCKET_OPEN_NONE,
1779 SOCKET_OPEN_SOME,
1780 SOCKET_OPEN_ALL,
1781};
1782
1783static int socket_check_open(Socket *s) {
1784 bool have_open = false, have_closed = false;
1785 SocketPort *p;
1786
1787 assert(s);
1788
1789 LIST_FOREACH(port, p, s->ports) {
1790 if (p->fd < 0)
1791 have_closed = true;
1792 else
1793 have_open = true;
1794
1795 if (have_open && have_closed)
1796 return SOCKET_OPEN_SOME;
1797 }
1798
1799 if (have_open)
1800 return SOCKET_OPEN_ALL;
1801
1802 return SOCKET_OPEN_NONE;
1803}
1804
034c6ed7
LP
1805static void socket_set_state(Socket *s, SocketState state) {
1806 SocketState old_state;
1807 assert(s);
1808
6fcbec6f
LP
1809 if (s->state != state)
1810 bus_unit_send_pending_change_signal(UNIT(s), false);
1811
034c6ed7
LP
1812 old_state = s->state;
1813 s->state = state;
1814
bd1fe7c7
LP
1815 if (!IN_SET(state,
1816 SOCKET_START_PRE,
3900e5fd 1817 SOCKET_START_CHOWN,
bd1fe7c7
LP
1818 SOCKET_START_POST,
1819 SOCKET_STOP_PRE,
1820 SOCKET_STOP_PRE_SIGTERM,
1821 SOCKET_STOP_PRE_SIGKILL,
1822 SOCKET_STOP_POST,
1823 SOCKET_FINAL_SIGTERM,
c968d76a
YW
1824 SOCKET_FINAL_SIGKILL,
1825 SOCKET_CLEANING)) {
718db961
LP
1826
1827 s->timer_event_source = sd_event_source_unref(s->timer_event_source);
5e94833f 1828 socket_unwatch_control_pid(s);
034c6ed7 1829 s->control_command = NULL;
a16e1123 1830 s->control_command_id = _SOCKET_EXEC_COMMAND_INVALID;
e537352b 1831 }
034c6ed7 1832
a16e1123
LP
1833 if (state != SOCKET_LISTENING)
1834 socket_unwatch_fds(s);
1835
bd1fe7c7 1836 if (!IN_SET(state,
3900e5fd 1837 SOCKET_START_CHOWN,
bd1fe7c7
LP
1838 SOCKET_START_POST,
1839 SOCKET_LISTENING,
1840 SOCKET_RUNNING,
1841 SOCKET_STOP_PRE,
1842 SOCKET_STOP_PRE_SIGTERM,
c968d76a
YW
1843 SOCKET_STOP_PRE_SIGKILL,
1844 SOCKET_CLEANING))
034c6ed7
LP
1845 socket_close_fds(s);
1846
e537352b 1847 if (state != old_state)
f2341e0a 1848 log_unit_debug(UNIT(s), "Changed %s -> %s", socket_state_to_string(old_state), socket_state_to_string(state));
acbb0225 1849
2ad2e41a 1850 unit_notify(UNIT(s), state_translation_table[old_state], state_translation_table[state], 0);
034c6ed7
LP
1851}
1852
be847e82 1853static int socket_coldplug(Unit *u) {
a16e1123
LP
1854 Socket *s = SOCKET(u);
1855 int r;
1856
1857 assert(s);
1858 assert(s->state == SOCKET_DEAD);
1859
e821075a
LP
1860 if (s->deserialized_state == s->state)
1861 return 0;
a16e1123 1862
c386f588
LP
1863 if (s->control_pid > 0 &&
1864 pid_is_unwaited(s->control_pid) &&
1865 IN_SET(s->deserialized_state,
3900e5fd
LP
1866 SOCKET_START_PRE,
1867 SOCKET_START_CHOWN,
1868 SOCKET_START_POST,
1869 SOCKET_STOP_PRE,
1870 SOCKET_STOP_PRE_SIGTERM,
1871 SOCKET_STOP_PRE_SIGKILL,
1872 SOCKET_STOP_POST,
1873 SOCKET_FINAL_SIGTERM,
c968d76a
YW
1874 SOCKET_FINAL_SIGKILL,
1875 SOCKET_CLEANING)) {
a16e1123 1876
f75f613d 1877 r = unit_watch_pid(UNIT(s), s->control_pid, false);
e821075a
LP
1878 if (r < 0)
1879 return r;
a16e1123 1880
36c16a7c 1881 r = socket_arm_timer(s, usec_add(u->state_change_timestamp.monotonic, s->timeout_usec));
e821075a
LP
1882 if (r < 0)
1883 return r;
1884 }
a16e1123 1885
3900e5fd
LP
1886 if (IN_SET(s->deserialized_state,
1887 SOCKET_START_CHOWN,
1888 SOCKET_START_POST,
1889 SOCKET_LISTENING,
01a8b467
LP
1890 SOCKET_RUNNING)) {
1891
1892 /* Originally, we used to simply reopen all sockets here that we didn't have file descriptors
5238e957 1893 * for. However, this is problematic, as we won't traverse through the SOCKET_START_CHOWN state for
01a8b467
LP
1894 * them, and thus the UID/GID wouldn't be right. Hence, instead simply check if we have all fds open,
1895 * and if there's a mismatch, warn loudly. */
1896
1897 r = socket_check_open(s);
1898 if (r == SOCKET_OPEN_NONE)
1899 log_unit_warning(UNIT(s),
1900 "Socket unit configuration has changed while unit has been running, "
1901 "no open socket file descriptor left. "
1902 "The socket unit is not functional until restarted.");
1903 else if (r == SOCKET_OPEN_SOME)
1904 log_unit_warning(UNIT(s),
1905 "Socket unit configuration has changed while unit has been running, "
1906 "and some socket file descriptors have not been opened yet. "
1907 "The socket unit is not fully functional until restarted.");
e821075a 1908 }
a16e1123 1909
e821075a
LP
1910 if (s->deserialized_state == SOCKET_LISTENING) {
1911 r = socket_watch_fds(s);
1912 if (r < 0)
1913 return r;
a16e1123
LP
1914 }
1915
c968d76a 1916 if (!IN_SET(s->deserialized_state, SOCKET_DEAD, SOCKET_FAILED, SOCKET_CLEANING)) {
29206d46 1917 (void) unit_setup_dynamic_creds(u);
e8a565cb
YW
1918 (void) unit_setup_exec_runtime(u);
1919 }
29206d46 1920
e821075a 1921 socket_set_state(s, s->deserialized_state);
a16e1123
LP
1922 return 0;
1923}
1924
e537352b 1925static int socket_spawn(Socket *s, ExecCommand *c, pid_t *_pid) {
3c7416b6 1926
b9c04eaf 1927 _cleanup_(exec_params_clear) ExecParameters exec_params = {
5686391b
LP
1928 .flags = EXEC_APPLY_SANDBOXING|EXEC_APPLY_CHROOT|EXEC_APPLY_TTY_STDIN,
1929 .stdin_fd = -1,
1930 .stdout_fd = -1,
1931 .stderr_fd = -1,
1932 .exec_fd = -1,
9fa95f85 1933 };
3c7416b6
LP
1934 pid_t pid;
1935 int r;
034c6ed7
LP
1936
1937 assert(s);
1938 assert(c);
1939 assert(_pid);
1940
3c7416b6 1941 r = unit_prepare_exec(UNIT(s));
29206d46
LP
1942 if (r < 0)
1943 return r;
1944
36c16a7c 1945 r = socket_arm_timer(s, usec_add(now(CLOCK_MONOTONIC), s->timeout_usec));
36697dc0 1946 if (r < 0)
36c16a7c 1947 return r;
034c6ed7 1948
1ad6e8b3
LP
1949 r = unit_set_exec_params(UNIT(s), &exec_params);
1950 if (r < 0)
1951 return r;
3536f49e 1952
f2341e0a
LP
1953 r = exec_spawn(UNIT(s),
1954 c,
9e2f7c11 1955 &s->exec_context,
9fa95f85 1956 &exec_params,
613b411c 1957 s->exec_runtime,
29206d46 1958 &s->dynamic_creds,
9e2f7c11 1959 &pid);
cee288ad 1960 if (r < 0)
36c16a7c 1961 return r;
9e2f7c11 1962
f75f613d 1963 r = unit_watch_pid(UNIT(s), pid, true);
9e2f7c11 1964 if (r < 0)
36c16a7c 1965 return r;
034c6ed7 1966
3900e5fd 1967 *_pid = pid;
3536f49e 1968
3900e5fd 1969 return 0;
3900e5fd
LP
1970}
1971
1972static int socket_chown(Socket *s, pid_t *_pid) {
1973 pid_t pid;
1974 int r;
1975
36c16a7c 1976 r = socket_arm_timer(s, usec_add(now(CLOCK_MONOTONIC), s->timeout_usec));
3900e5fd
LP
1977 if (r < 0)
1978 goto fail;
1979
1980 /* We have to resolve the user names out-of-process, hence
1981 * let's fork here. It's messy, but well, what can we do? */
1982
4c253ed1 1983 r = unit_fork_helper_process(UNIT(s), "(sd-chown)", &pid);
a79279c7
LP
1984 if (r < 0)
1985 return r;
1986 if (r == 0) {
fed1e721
LP
1987 uid_t uid = UID_INVALID;
1988 gid_t gid = GID_INVALID;
a79279c7 1989 SocketPort *p;
3900e5fd 1990
a79279c7 1991 /* Child */
3900e5fd
LP
1992
1993 if (!isempty(s->user)) {
1994 const char *user = s->user;
1995
fafff8f1 1996 r = get_user_creds(&user, &uid, &gid, NULL, NULL, 0);
3900e5fd 1997 if (r < 0) {
a79279c7
LP
1998 log_unit_error_errno(UNIT(s), r, "Failed to resolve user %s: %m", user);
1999 _exit(EXIT_USER);
3900e5fd
LP
2000 }
2001 }
2002
2003 if (!isempty(s->group)) {
2004 const char *group = s->group;
2005
fafff8f1 2006 r = get_group_creds(&group, &gid, 0);
3900e5fd 2007 if (r < 0) {
a79279c7
LP
2008 log_unit_error_errno(UNIT(s), r, "Failed to resolve group %s: %m", group);
2009 _exit(EXIT_GROUP);
3900e5fd
LP
2010 }
2011 }
2012
2013 LIST_FOREACH(port, p, s->ports) {
e5a1c18d 2014 const char *path = NULL;
3900e5fd
LP
2015
2016 if (p->type == SOCKET_SOCKET)
2017 path = socket_address_get_path(&p->address);
2018 else if (p->type == SOCKET_FIFO)
2019 path = p->path;
2020
2021 if (!path)
2022 continue;
2023
2024 if (chown(path, uid, gid) < 0) {
a79279c7
LP
2025 log_unit_error_errno(UNIT(s), errno, "Failed to chown(): %m");
2026 _exit(EXIT_CHOWN);
3900e5fd
LP
2027 }
2028 }
2029
a79279c7 2030 _exit(EXIT_SUCCESS);
3900e5fd
LP
2031 }
2032
f75f613d 2033 r = unit_watch_pid(UNIT(s), pid, true);
718db961 2034 if (r < 0)
034c6ed7 2035 goto fail;
83c60c9f 2036
034c6ed7 2037 *_pid = pid;
034c6ed7
LP
2038 return 0;
2039
2040fail:
718db961 2041 s->timer_event_source = sd_event_source_unref(s->timer_event_source);
83c60c9f 2042 return r;
542563ba
LP
2043}
2044
cfc4eb4c 2045static void socket_enter_dead(Socket *s, SocketResult f) {
034c6ed7
LP
2046 assert(s);
2047
a0fef983 2048 if (s->result == SOCKET_SUCCESS)
cfc4eb4c 2049 s->result = f;
034c6ed7 2050
523ee2d4
LP
2051 if (s->result == SOCKET_SUCCESS)
2052 unit_log_success(UNIT(s));
2053 else
7c047d74 2054 unit_log_failure(UNIT(s), socket_result_to_string(s->result));
ed77d407 2055
4c425434
LP
2056 unit_warn_leftover_processes(UNIT(s), unit_log_leftover_process_stop);
2057
29206d46
LP
2058 socket_set_state(s, s->result != SOCKET_SUCCESS ? SOCKET_FAILED : SOCKET_DEAD);
2059
e8a565cb 2060 s->exec_runtime = exec_runtime_unref(s->exec_runtime, true);
613b411c 2061
bb0c0d6f 2062 unit_destroy_runtime_data(UNIT(s), &s->exec_context);
e66cf1a3 2063
00d9ef85
LP
2064 unit_unref_uid_gid(UNIT(s), true);
2065
29206d46 2066 dynamic_creds_destroy(&s->dynamic_creds);
034c6ed7
LP
2067}
2068
cfc4eb4c 2069static void socket_enter_signal(Socket *s, SocketState state, SocketResult f);
80876c20 2070
cfc4eb4c 2071static void socket_enter_stop_post(Socket *s, SocketResult f) {
034c6ed7
LP
2072 int r;
2073 assert(s);
2074
a0fef983 2075 if (s->result == SOCKET_SUCCESS)
cfc4eb4c 2076 s->result = f;
034c6ed7 2077
5e94833f 2078 socket_unwatch_control_pid(s);
a16e1123 2079 s->control_command_id = SOCKET_EXEC_STOP_POST;
3900e5fd 2080 s->control_command = s->exec_command[SOCKET_EXEC_STOP_POST];
a16e1123 2081
3900e5fd
LP
2082 if (s->control_command) {
2083 r = socket_spawn(s, s->control_command, &s->control_pid);
2084 if (r < 0)
034c6ed7
LP
2085 goto fail;
2086
80876c20
LP
2087 socket_set_state(s, SOCKET_STOP_POST);
2088 } else
cfc4eb4c 2089 socket_enter_signal(s, SOCKET_FINAL_SIGTERM, SOCKET_SUCCESS);
034c6ed7
LP
2090
2091 return;
2092
2093fail:
f2341e0a 2094 log_unit_warning_errno(UNIT(s), r, "Failed to run 'stop-post' task: %m");
cfc4eb4c 2095 socket_enter_signal(s, SOCKET_FINAL_SIGTERM, SOCKET_FAILURE_RESOURCES);
034c6ed7
LP
2096}
2097
a232ebcc
ZJS
2098static int state_to_kill_operation(Socket *s, SocketState state) {
2099 if (state == SOCKET_STOP_PRE_SIGTERM && unit_has_job_type(UNIT(s), JOB_RESTART))
2100 return KILL_RESTART;
2101
2102 if (state == SOCKET_FINAL_SIGTERM)
2103 return KILL_TERMINATE;
2104
2105 return KILL_KILL;
2106}
2107
cfc4eb4c 2108static void socket_enter_signal(Socket *s, SocketState state, SocketResult f) {
034c6ed7
LP
2109 int r;
2110
2111 assert(s);
2112
a0fef983 2113 if (s->result == SOCKET_SUCCESS)
cfc4eb4c 2114 s->result = f;
034c6ed7 2115
cd2086fe
LP
2116 r = unit_kill_context(
2117 UNIT(s),
2118 &s->kill_context,
a232ebcc 2119 state_to_kill_operation(s, state),
cd2086fe
LP
2120 -1,
2121 s->control_pid,
2122 false);
2123 if (r < 0)
2124 goto fail;
034c6ed7 2125
cd2086fe 2126 if (r > 0) {
36c16a7c 2127 r = socket_arm_timer(s, usec_add(now(CLOCK_MONOTONIC), s->timeout_usec));
36697dc0 2128 if (r < 0)
80876c20 2129 goto fail;
d6ea93e3 2130
80876c20 2131 socket_set_state(s, state);
ac84d1fb
LP
2132 } else if (state == SOCKET_STOP_PRE_SIGTERM)
2133 socket_enter_signal(s, SOCKET_STOP_PRE_SIGKILL, SOCKET_SUCCESS);
2134 else if (state == SOCKET_STOP_PRE_SIGKILL)
cfc4eb4c 2135 socket_enter_stop_post(s, SOCKET_SUCCESS);
ac84d1fb
LP
2136 else if (state == SOCKET_FINAL_SIGTERM)
2137 socket_enter_signal(s, SOCKET_FINAL_SIGKILL, SOCKET_SUCCESS);
80876c20 2138 else
cfc4eb4c 2139 socket_enter_dead(s, SOCKET_SUCCESS);
034c6ed7
LP
2140
2141 return;
2142
2143fail:
f2341e0a 2144 log_unit_warning_errno(UNIT(s), r, "Failed to kill processes: %m");
034c6ed7 2145
3742095b 2146 if (IN_SET(state, SOCKET_STOP_PRE_SIGTERM, SOCKET_STOP_PRE_SIGKILL))
cfc4eb4c 2147 socket_enter_stop_post(s, SOCKET_FAILURE_RESOURCES);
034c6ed7 2148 else
cfc4eb4c 2149 socket_enter_dead(s, SOCKET_FAILURE_RESOURCES);
034c6ed7
LP
2150}
2151
cfc4eb4c 2152static void socket_enter_stop_pre(Socket *s, SocketResult f) {
034c6ed7
LP
2153 int r;
2154 assert(s);
2155
a0fef983 2156 if (s->result == SOCKET_SUCCESS)
cfc4eb4c 2157 s->result = f;
034c6ed7 2158
5e94833f 2159 socket_unwatch_control_pid(s);
a16e1123 2160 s->control_command_id = SOCKET_EXEC_STOP_PRE;
3900e5fd 2161 s->control_command = s->exec_command[SOCKET_EXEC_STOP_PRE];
a16e1123 2162
3900e5fd
LP
2163 if (s->control_command) {
2164 r = socket_spawn(s, s->control_command, &s->control_pid);
2165 if (r < 0)
034c6ed7
LP
2166 goto fail;
2167
80876c20
LP
2168 socket_set_state(s, SOCKET_STOP_PRE);
2169 } else
cfc4eb4c 2170 socket_enter_stop_post(s, SOCKET_SUCCESS);
034c6ed7
LP
2171
2172 return;
2173
2174fail:
f2341e0a 2175 log_unit_warning_errno(UNIT(s), r, "Failed to run 'stop-pre' task: %m");
cfc4eb4c 2176 socket_enter_stop_post(s, SOCKET_FAILURE_RESOURCES);
034c6ed7
LP
2177}
2178
e9af15c3
LP
2179static void socket_enter_listening(Socket *s) {
2180 int r;
2181 assert(s);
2182
3e5f04bf
RM
2183 if (!s->accept && s->flush_pending) {
2184 log_unit_debug(UNIT(s), "Flushing socket before listening.");
2185 flush_ports(s);
2186 }
2187
cfc4eb4c
LP
2188 r = socket_watch_fds(s);
2189 if (r < 0) {
f2341e0a 2190 log_unit_warning_errno(UNIT(s), r, "Failed to watch sockets: %m");
e9af15c3
LP
2191 goto fail;
2192 }
2193
2194 socket_set_state(s, SOCKET_LISTENING);
2195 return;
2196
2197fail:
cfc4eb4c 2198 socket_enter_stop_pre(s, SOCKET_FAILURE_RESOURCES);
e9af15c3
LP
2199}
2200
034c6ed7
LP
2201static void socket_enter_start_post(Socket *s) {
2202 int r;
2203 assert(s);
2204
3900e5fd
LP
2205 socket_unwatch_control_pid(s);
2206 s->control_command_id = SOCKET_EXEC_START_POST;
2207 s->control_command = s->exec_command[SOCKET_EXEC_START_POST];
2208
2209 if (s->control_command) {
2210 r = socket_spawn(s, s->control_command, &s->control_pid);
2211 if (r < 0) {
f2341e0a 2212 log_unit_warning_errno(UNIT(s), r, "Failed to run 'start-post' task: %m");
3900e5fd
LP
2213 goto fail;
2214 }
2215
2216 socket_set_state(s, SOCKET_START_POST);
2217 } else
2218 socket_enter_listening(s);
2219
2220 return;
2221
2222fail:
2223 socket_enter_stop_pre(s, SOCKET_FAILURE_RESOURCES);
2224}
2225
2226static void socket_enter_start_chown(Socket *s) {
2227 int r;
2228
2229 assert(s);
2230
cfc4eb4c
LP
2231 r = socket_open_fds(s);
2232 if (r < 0) {
f2341e0a 2233 log_unit_warning_errno(UNIT(s), r, "Failed to listen on sockets: %m");
034c6ed7
LP
2234 goto fail;
2235 }
2236
3900e5fd 2237 if (!isempty(s->user) || !isempty(s->group)) {
5e94833f 2238
3900e5fd
LP
2239 socket_unwatch_control_pid(s);
2240 s->control_command_id = SOCKET_EXEC_START_CHOWN;
2241 s->control_command = NULL;
a16e1123 2242
3900e5fd 2243 r = socket_chown(s, &s->control_pid);
cfc4eb4c 2244 if (r < 0) {
f2341e0a 2245 log_unit_warning_errno(UNIT(s), r, "Failed to fork 'start-chown' task: %m");
034c6ed7
LP
2246 goto fail;
2247 }
2248
3900e5fd 2249 socket_set_state(s, SOCKET_START_CHOWN);
80876c20 2250 } else
3900e5fd 2251 socket_enter_start_post(s);
034c6ed7
LP
2252
2253 return;
2254
2255fail:
cfc4eb4c 2256 socket_enter_stop_pre(s, SOCKET_FAILURE_RESOURCES);
034c6ed7
LP
2257}
2258
2259static void socket_enter_start_pre(Socket *s) {
2260 int r;
2261 assert(s);
2262
5e94833f 2263 socket_unwatch_control_pid(s);
a4634b21 2264
4c425434 2265 unit_warn_leftover_processes(UNIT(s), unit_log_leftover_process_start);
a4634b21 2266
a16e1123 2267 s->control_command_id = SOCKET_EXEC_START_PRE;
3900e5fd 2268 s->control_command = s->exec_command[SOCKET_EXEC_START_PRE];
a16e1123 2269
3900e5fd 2270 if (s->control_command) {
e821075a 2271 r = socket_spawn(s, s->control_command, &s->control_pid);
3900e5fd 2272 if (r < 0) {
f2341e0a 2273 log_unit_warning_errno(UNIT(s), r, "Failed to run 'start-pre' task: %m");
034c6ed7 2274 goto fail;
3900e5fd 2275 }
034c6ed7 2276
80876c20
LP
2277 socket_set_state(s, SOCKET_START_PRE);
2278 } else
3900e5fd 2279 socket_enter_start_chown(s);
034c6ed7
LP
2280
2281 return;
2282
2283fail:
cfc4eb4c 2284 socket_enter_dead(s, SOCKET_FAILURE_RESOURCES);
034c6ed7
LP
2285}
2286
60d9771c
LP
2287static void flush_ports(Socket *s) {
2288 SocketPort *p;
2289
2290 /* Flush all incoming traffic, regardless if actual bytes or new connections, so that this socket isn't busy
2291 * anymore */
2292
2293 LIST_FOREACH(port, p, s->ports) {
2294 if (p->fd < 0)
2295 continue;
2296
2297 (void) flush_accept(p->fd);
2298 (void) flush_fd(p->fd);
2299 }
2300}
2301
5cf09553
ZJS
2302static void socket_enter_running(Socket *s, int cfd_in) {
2303 /* Note that this call takes possession of the connection fd passed. It either has to assign it
2304 * somewhere or close it. */
2305 _cleanup_close_ int cfd = cfd_in;
2306
4afd3348 2307 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
034c6ed7
LP
2308 int r;
2309
2310 assert(s);
2311
60d9771c 2312 /* We don't take connections anymore if we are supposed to shut down anyway */
31afa0a4 2313 if (unit_stop_pending(UNIT(s))) {
e821075a 2314
f2341e0a 2315 log_unit_debug(UNIT(s), "Suppressing connection request since unit stop is scheduled.");
5d909e3e 2316
7c610628 2317 if (cfd >= 0)
a98f7575 2318 goto refuse;
7c610628 2319
5cf09553 2320 flush_ports(s);
ba3e67a7
LP
2321 return;
2322 }
2323
7994ac1d 2324 if (!ratelimit_below(&s->trigger_limit)) {
8b26cdbd
LP
2325 log_unit_warning(UNIT(s), "Trigger limit hit, refusing further activation.");
2326 socket_enter_stop_pre(s, SOCKET_FAILURE_TRIGGER_LIMIT_HIT);
a98f7575 2327 goto refuse;
8b26cdbd
LP
2328 }
2329
4f2d528d 2330 if (cfd < 0) {
f976f3f6 2331 bool pending = false;
eef85c4a 2332 Unit *other;
eef85c4a 2333 void *v;
f976f3f6
LP
2334
2335 /* If there's already a start pending don't bother to
2336 * do anything */
90e74a66 2337 HASHMAP_FOREACH_KEY(v, other, UNIT(s)->dependencies[UNIT_TRIGGERS])
e821075a 2338 if (unit_active_or_pending(other)) {
57020a3a
LP
2339 pending = true;
2340 break;
2341 }
f976f3f6 2342
1a710b43 2343 if (!pending) {
640ace4a 2344 if (!UNIT_ISSET(s->service)) {
86e045ec
ZJS
2345 r = log_unit_error_errno(UNIT(s), SYNTHETIC_ERRNO(ENOENT),
2346 "Service to activate vanished, refusing activation.");
640ace4a
LP
2347 goto fail;
2348 }
2349
50cbaba4 2350 r = manager_add_job(UNIT(s)->manager, JOB_START, UNIT_DEREF(s->service), JOB_REPLACE, NULL, &error, NULL);
1a710b43 2351 if (r < 0)
f976f3f6 2352 goto fail;
1a710b43 2353 }
4f2d528d
LP
2354
2355 socket_set_state(s, SOCKET_RUNNING);
2356 } else {
9d565427 2357 _cleanup_(socket_peer_unrefp) SocketPeer *p = NULL;
b669c20f 2358 Unit *service;
4f2d528d 2359
6cf6bbc2 2360 if (s->n_connections >= s->max_connections) {
ea8f50f8 2361 log_unit_warning(UNIT(s), "Too many incoming connections (%u), dropping connection.",
166cf510 2362 s->n_connections);
a98f7575 2363 goto refuse;
6cf6bbc2
LP
2364 }
2365
9d565427 2366 if (s->max_connections_per_source > 0) {
166cf510 2367 r = socket_acquire_peer(s, cfd, &p);
86e045ec 2368 if (ERRNO_IS_DISCONNECT(r))
5cf09553 2369 return;
86e045ec
ZJS
2370 if (r < 0) /* We didn't have enough resources to acquire peer information, let's fail. */
2371 goto fail;
934ef6a5 2372 if (r > 0 && p->n_ref > s->max_connections_per_source) {
ea8f50f8
ZJS
2373 _cleanup_free_ char *t = NULL;
2374
41733ae1 2375 (void) sockaddr_pretty(&p->peer.sa, p->peer_salen, true, false, &t);
ea8f50f8 2376
166cf510 2377 log_unit_warning(UNIT(s),
ea8f50f8
ZJS
2378 "Too many incoming connections (%u) from source %s, dropping connection.",
2379 p->n_ref, strnull(t));
a98f7575 2380 goto refuse;
9d565427
SS
2381 }
2382 }
2383
b669c20f 2384 r = socket_load_service_unit(s, cfd, &service);
86e045ec 2385 if (ERRNO_IS_DISCONNECT(r))
5cf09553 2386 return;
e55001eb 2387 if (r < 0)
4f2d528d 2388 goto fail;
b15bdda8 2389
b669c20f
ZJS
2390 r = unit_add_two_dependencies(UNIT(s), UNIT_BEFORE, UNIT_TRIGGERS, service,
2391 false, UNIT_DEPENDENCY_IMPLICIT);
2392 if (r < 0)
2393 goto fail;
6c073082 2394
e4f67317 2395 s->n_accepted++;
b15bdda8 2396
b669c20f 2397 r = service_set_socket_fd(SERVICE(service), cfd, s, s->selinux_context_from_net);
86e045ec 2398 if (ERRNO_IS_DISCONNECT(r))
5cf09553 2399 return;
1a710b43 2400 if (r < 0)
4f2d528d
LP
2401 goto fail;
2402
934ef6a5 2403 TAKE_FD(cfd); /* We passed ownership of the fd to the service now. Forget it here. */
313cefa1 2404 s->n_connections++;
6cf6bbc2 2405
b669c20f 2406 SERVICE(service)->peer = TAKE_PTR(p); /* Pass ownership of the peer reference */
9d565427 2407
b669c20f 2408 r = manager_add_job(UNIT(s)->manager, JOB_START, service, JOB_REPLACE, NULL, &error, NULL);
3e7a1f50 2409 if (r < 0) {
934ef6a5
ZJS
2410 /* We failed to activate the new service, but it still exists. Let's make sure the
2411 * service closes and forgets the connection fd again, immediately. */
b669c20f 2412 service_close_socket_fd(SERVICE(service));
4f2d528d 2413 goto fail;
3e7a1f50 2414 }
c4e2ceae
LP
2415
2416 /* Notify clients about changed counters */
2417 unit_add_to_dbus_queue(UNIT(s));
4f2d528d 2418 }
034c6ed7 2419
5cf09553 2420 TAKE_FD(cfd);
034c6ed7
LP
2421 return;
2422
a98f7575
MM
2423refuse:
2424 s->n_refused++;
a98f7575
MM
2425 return;
2426
034c6ed7 2427fail:
86e045ec
ZJS
2428 if (ERRNO_IS_RESOURCE(r))
2429 log_unit_warning(UNIT(s), "Failed to queue service startup job: %s",
2430 bus_error_message(&error, r));
2431 else
2432 log_unit_warning(UNIT(s), "Failed to queue service startup job (Maybe the service file is missing or not a %s unit?): %s",
2433 cfd >= 0 ? "template" : "non-template",
2434 bus_error_message(&error, r));
e821075a 2435
60089004 2436 socket_enter_stop_pre(s, SOCKET_FAILURE_RESOURCES);
034c6ed7
LP
2437}
2438
cfc4eb4c 2439static void socket_run_next(Socket *s) {
034c6ed7
LP
2440 int r;
2441
2442 assert(s);
2443 assert(s->control_command);
2444 assert(s->control_command->command_next);
2445
5e94833f
LP
2446 socket_unwatch_control_pid(s);
2447
034c6ed7
LP
2448 s->control_command = s->control_command->command_next;
2449
e821075a
LP
2450 r = socket_spawn(s, s->control_command, &s->control_pid);
2451 if (r < 0)
034c6ed7
LP
2452 goto fail;
2453
2454 return;
2455
2456fail:
f2341e0a 2457 log_unit_warning_errno(UNIT(s), r, "Failed to run next task: %m");
80876c20
LP
2458
2459 if (s->state == SOCKET_START_POST)
cfc4eb4c 2460 socket_enter_stop_pre(s, SOCKET_FAILURE_RESOURCES);
034c6ed7 2461 else if (s->state == SOCKET_STOP_POST)
cfc4eb4c 2462 socket_enter_dead(s, SOCKET_FAILURE_RESOURCES);
034c6ed7 2463 else
cfc4eb4c 2464 socket_enter_signal(s, SOCKET_FINAL_SIGTERM, SOCKET_FAILURE_RESOURCES);
034c6ed7
LP
2465}
2466
87f0e418
LP
2467static int socket_start(Unit *u) {
2468 Socket *s = SOCKET(u);
07299350 2469 int r;
83c60c9f
LP
2470
2471 assert(s);
2472
034c6ed7
LP
2473 /* We cannot fulfill this request right now, try again later
2474 * please! */
3900e5fd
LP
2475 if (IN_SET(s->state,
2476 SOCKET_STOP_PRE,
2477 SOCKET_STOP_PRE_SIGKILL,
2478 SOCKET_STOP_PRE_SIGTERM,
2479 SOCKET_STOP_POST,
2480 SOCKET_FINAL_SIGTERM,
c968d76a
YW
2481 SOCKET_FINAL_SIGKILL,
2482 SOCKET_CLEANING))
034c6ed7
LP
2483 return -EAGAIN;
2484
a4152e3f 2485 /* Already on it! */
3900e5fd
LP
2486 if (IN_SET(s->state,
2487 SOCKET_START_PRE,
2488 SOCKET_START_CHOWN,
2489 SOCKET_START_POST))
034c6ed7 2490 return 0;
83c60c9f 2491
034c6ed7 2492 /* Cannot run this without the service being around */
9444b1f2 2493 if (UNIT_ISSET(s->service)) {
57020a3a
LP
2494 Service *service;
2495
2496 service = SERVICE(UNIT_DEREF(s->service));
2497
d85ff944
YW
2498 if (UNIT(service)->load_state != UNIT_LOADED)
2499 return log_unit_error_errno(u, SYNTHETIC_ERRNO(ENOENT), "Socket service %s not loaded, refusing.", UNIT(service)->id);
4f2d528d 2500
35b8ca3a 2501 /* If the service is already active we cannot start the
4f2d528d 2502 * socket */
d85ff944
YW
2503 if (!IN_SET(service->state, SERVICE_DEAD, SERVICE_FAILED, SERVICE_AUTO_RESTART))
2504 return log_unit_error_errno(u, SYNTHETIC_ERRNO(EBUSY), "Socket service %s already active, refusing.", UNIT(service)->id);
4f2d528d 2505 }
e537352b 2506
3742095b 2507 assert(IN_SET(s->state, SOCKET_DEAD, SOCKET_FAILED));
83c60c9f 2508
97a3f4ee 2509 r = unit_test_start_limit(u);
07299350
LP
2510 if (r < 0) {
2511 socket_enter_dead(s, SOCKET_FAILURE_START_LIMIT_HIT);
2512 return r;
2513 }
2514
4b58153d
LP
2515 r = unit_acquire_invocation_id(u);
2516 if (r < 0)
2517 return r;
2518
cfc4eb4c 2519 s->result = SOCKET_SUCCESS;
6a1d4d9f 2520 exec_command_reset_status_list_array(s->exec_command, _SOCKET_EXEC_COMMAND_MAX);
3c7416b6
LP
2521
2522 u->reset_accounting = true;
5ad096b3 2523
034c6ed7 2524 socket_enter_start_pre(s);
82a2b6bb 2525 return 1;
034c6ed7 2526}
83c60c9f 2527
87f0e418
LP
2528static int socket_stop(Unit *u) {
2529 Socket *s = SOCKET(u);
034c6ed7
LP
2530
2531 assert(s);
2532
e537352b 2533 /* Already on it */
3900e5fd
LP
2534 if (IN_SET(s->state,
2535 SOCKET_STOP_PRE,
2536 SOCKET_STOP_PRE_SIGTERM,
2537 SOCKET_STOP_PRE_SIGKILL,
2538 SOCKET_STOP_POST,
2539 SOCKET_FINAL_SIGTERM,
2540 SOCKET_FINAL_SIGKILL))
e537352b
LP
2541 return 0;
2542
3f6c78dc
LP
2543 /* If there's already something running we go directly into
2544 * kill mode. */
3900e5fd
LP
2545 if (IN_SET(s->state,
2546 SOCKET_START_PRE,
2547 SOCKET_START_CHOWN,
2548 SOCKET_START_POST)) {
cfc4eb4c 2549 socket_enter_signal(s, SOCKET_STOP_PRE_SIGTERM, SOCKET_SUCCESS);
3f6c78dc
LP
2550 return -EAGAIN;
2551 }
2552
c968d76a
YW
2553 /* If we are currently cleaning, then abort it, brutally. */
2554 if (s->state == SOCKET_CLEANING) {
2555 socket_enter_signal(s, SOCKET_FINAL_SIGKILL, SOCKET_SUCCESS);
2556 return 0;
2557 }
2558
3742095b 2559 assert(IN_SET(s->state, SOCKET_LISTENING, SOCKET_RUNNING));
83c60c9f 2560
cfc4eb4c 2561 socket_enter_stop_pre(s, SOCKET_SUCCESS);
82a2b6bb 2562 return 1;
542563ba
LP
2563}
2564
a16e1123
LP
2565static int socket_serialize(Unit *u, FILE *f, FDSet *fds) {
2566 Socket *s = SOCKET(u);
2567 SocketPort *p;
2568 int r;
2569
2570 assert(u);
2571 assert(f);
2572 assert(fds);
2573
d68c645b
LP
2574 (void) serialize_item(f, "state", socket_state_to_string(s->state));
2575 (void) serialize_item(f, "result", socket_result_to_string(s->result));
2576 (void) serialize_item_format(f, "n-accepted", "%u", s->n_accepted);
2577 (void) serialize_item_format(f, "n-refused", "%u", s->n_refused);
a16e1123
LP
2578
2579 if (s->control_pid > 0)
d68c645b 2580 (void) serialize_item_format(f, "control-pid", PID_FMT, s->control_pid);
a16e1123
LP
2581
2582 if (s->control_command_id >= 0)
d68c645b 2583 (void) serialize_item(f, "control-command", socket_exec_command_to_string(s->control_command_id));
a16e1123
LP
2584
2585 LIST_FOREACH(port, p, s->ports) {
2586 int copy;
2587
2588 if (p->fd < 0)
2589 continue;
2590
613b411c
LP
2591 copy = fdset_put_dup(fds, p->fd);
2592 if (copy < 0)
fc2d74ab 2593 return log_unit_warning_errno(u, copy, "Failed to serialize socket fd: %m");
a16e1123
LP
2594
2595 if (p->type == SOCKET_SOCKET) {
613b411c 2596 _cleanup_free_ char *t = NULL;
a16e1123 2597
ee092817
LP
2598 r = socket_address_print(&p->address, &t);
2599 if (r < 0)
fc2d74ab 2600 return log_unit_error_errno(u, r, "Failed to format socket address: %m");
a16e1123 2601
7a22745a 2602 if (socket_address_family(&p->address) == AF_NETLINK)
d68c645b 2603 (void) serialize_item_format(f, "netlink", "%i %s", copy, t);
7a22745a 2604 else
d68c645b 2605 (void) serialize_item_format(f, "socket", "%i %i %s", copy, p->address.type, t);
b0a3f2bc 2606 } else if (p->type == SOCKET_SPECIAL)
d68c645b 2607 (void) serialize_item_format(f, "special", "%i %s", copy, p->path);
ee092817 2608 else if (p->type == SOCKET_MQUEUE)
d68c645b 2609 (void) serialize_item_format(f, "mqueue", "%i %s", copy, p->path);
60252446 2610 else if (p->type == SOCKET_USB_FUNCTION)
d68c645b 2611 (void) serialize_item_format(f, "ffs", "%i %s", copy, p->path);
b0a3f2bc 2612 else {
a16e1123 2613 assert(p->type == SOCKET_FIFO);
d68c645b 2614 (void) serialize_item_format(f, "fifo", "%i %s", copy, p->path);
a16e1123
LP
2615 }
2616 }
2617
2618 return 0;
2619}
2620
80a58668 2621static void socket_port_take_fd(SocketPort *p, FDSet *fds, int fd) {
d68c645b
LP
2622 assert(p);
2623
80a58668
ZJS
2624 safe_close(p->fd);
2625 p->fd = fdset_remove(fds, fd);
2626}
2627
a16e1123
LP
2628static int socket_deserialize_item(Unit *u, const char *key, const char *value, FDSet *fds) {
2629 Socket *s = SOCKET(u);
a16e1123
LP
2630
2631 assert(u);
2632 assert(key);
2633 assert(value);
a16e1123
LP
2634
2635 if (streq(key, "state")) {
2636 SocketState state;
2637
ee092817
LP
2638 state = socket_state_from_string(value);
2639 if (state < 0)
f2341e0a 2640 log_unit_debug(u, "Failed to parse state value: %s", value);
a16e1123
LP
2641 else
2642 s->deserialized_state = state;
cfc4eb4c
LP
2643 } else if (streq(key, "result")) {
2644 SocketResult f;
a16e1123 2645
cfc4eb4c
LP
2646 f = socket_result_from_string(value);
2647 if (f < 0)
f2341e0a 2648 log_unit_debug(u, "Failed to parse result value: %s", value);
cfc4eb4c
LP
2649 else if (f != SOCKET_SUCCESS)
2650 s->result = f;
a16e1123
LP
2651
2652 } else if (streq(key, "n-accepted")) {
2653 unsigned k;
2654
e364ad06 2655 if (safe_atou(value, &k) < 0)
f2341e0a 2656 log_unit_debug(u, "Failed to parse n-accepted value: %s", value);
a16e1123
LP
2657 else
2658 s->n_accepted += k;
a98f7575
MM
2659 } else if (streq(key, "n-refused")) {
2660 unsigned k;
2661
2662 if (safe_atou(value, &k) < 0)
2663 log_unit_debug(u, "Failed to parse n-refused value: %s", value);
2664 else
2665 s->n_refused += k;
a16e1123 2666 } else if (streq(key, "control-pid")) {
5925dd3c 2667 pid_t pid;
a16e1123 2668
e364ad06 2669 if (parse_pid(value, &pid) < 0)
f2341e0a 2670 log_unit_debug(u, "Failed to parse control-pid value: %s", value);
a16e1123 2671 else
5925dd3c 2672 s->control_pid = pid;
a16e1123
LP
2673 } else if (streq(key, "control-command")) {
2674 SocketExecCommand id;
2675
66870f90
ZJS
2676 id = socket_exec_command_from_string(value);
2677 if (id < 0)
f2341e0a 2678 log_unit_debug(u, "Failed to parse exec-command value: %s", value);
a16e1123
LP
2679 else {
2680 s->control_command_id = id;
2681 s->control_command = s->exec_command[id];
2682 }
2683 } else if (streq(key, "fifo")) {
2684 int fd, skip = 0;
2685 SocketPort *p;
2686
2687 if (sscanf(value, "%i %n", &fd, &skip) < 1 || fd < 0 || !fdset_contains(fds, fd))
f2341e0a 2688 log_unit_debug(u, "Failed to parse fifo value: %s", value);
80a58668 2689 else
a16e1123 2690 LIST_FOREACH(port, p, s->ports)
b0a3f2bc 2691 if (p->type == SOCKET_FIFO &&
e3f791a2 2692 path_equal_or_files_same(p->path, value+skip, 0)) {
80a58668 2693 socket_port_take_fd(p, fds, fd);
b0a3f2bc 2694 break;
80a58668 2695 }
b0a3f2bc
LP
2696
2697 } else if (streq(key, "special")) {
2698 int fd, skip = 0;
2699 SocketPort *p;
2700
2701 if (sscanf(value, "%i %n", &fd, &skip) < 1 || fd < 0 || !fdset_contains(fds, fd))
f2341e0a 2702 log_unit_debug(u, "Failed to parse special value: %s", value);
80a58668 2703 else
b0a3f2bc
LP
2704 LIST_FOREACH(port, p, s->ports)
2705 if (p->type == SOCKET_SPECIAL &&
e3f791a2 2706 path_equal_or_files_same(p->path, value+skip, 0)) {
80a58668 2707 socket_port_take_fd(p, fds, fd);
a16e1123 2708 break;
80a58668 2709 }
a16e1123 2710
ee092817
LP
2711 } else if (streq(key, "mqueue")) {
2712 int fd, skip = 0;
2713 SocketPort *p;
2714
2715 if (sscanf(value, "%i %n", &fd, &skip) < 1 || fd < 0 || !fdset_contains(fds, fd))
f2341e0a 2716 log_unit_debug(u, "Failed to parse mqueue value: %s", value);
80a58668 2717 else
ee092817
LP
2718 LIST_FOREACH(port, p, s->ports)
2719 if (p->type == SOCKET_MQUEUE &&
80a58668
ZJS
2720 streq(p->path, value+skip)) {
2721 socket_port_take_fd(p, fds, fd);
ee092817 2722 break;
80a58668 2723 }
ee092817 2724
a16e1123 2725 } else if (streq(key, "socket")) {
27ca8d7a 2726 int fd, type, skip = 0;
a16e1123
LP
2727 SocketPort *p;
2728
27ca8d7a 2729 if (sscanf(value, "%i %i %n", &fd, &type, &skip) < 2 || fd < 0 || type < 0 || !fdset_contains(fds, fd))
f2341e0a 2730 log_unit_debug(u, "Failed to parse socket value: %s", value);
80a58668 2731 else
a16e1123 2732 LIST_FOREACH(port, p, s->ports)
80a58668
ZJS
2733 if (socket_address_is(&p->address, value+skip, type)) {
2734 socket_port_take_fd(p, fds, fd);
a16e1123 2735 break;
80a58668 2736 }
a16e1123 2737
7a22745a
LP
2738 } else if (streq(key, "netlink")) {
2739 int fd, skip = 0;
2740 SocketPort *p;
2741
2742 if (sscanf(value, "%i %n", &fd, &skip) < 1 || fd < 0 || !fdset_contains(fds, fd))
f2341e0a 2743 log_unit_debug(u, "Failed to parse socket value: %s", value);
80a58668 2744 else
7a22745a 2745 LIST_FOREACH(port, p, s->ports)
80a58668
ZJS
2746 if (socket_address_is_netlink(&p->address, value+skip)) {
2747 socket_port_take_fd(p, fds, fd);
7a22745a 2748 break;
80a58668 2749 }
60252446
PS
2750
2751 } else if (streq(key, "ffs")) {
2752 int fd, skip = 0;
2753 SocketPort *p;
2754
2755 if (sscanf(value, "%i %n", &fd, &skip) < 1 || fd < 0 || !fdset_contains(fds, fd))
2756 log_unit_debug(u, "Failed to parse ffs value: %s", value);
80a58668 2757 else
60252446
PS
2758 LIST_FOREACH(port, p, s->ports)
2759 if (p->type == SOCKET_USB_FUNCTION &&
e3f791a2 2760 path_equal_or_files_same(p->path, value+skip, 0)) {
80a58668 2761 socket_port_take_fd(p, fds, fd);
60252446 2762 break;
80a58668 2763 }
60252446 2764
a16e1123 2765 } else
f2341e0a 2766 log_unit_debug(UNIT(s), "Unknown serialization key: %s", key);
a16e1123
LP
2767
2768 return 0;
2769}
2770
9ff1a6f1 2771static void socket_distribute_fds(Unit *u, FDSet *fds) {
01e10de3
LP
2772 Socket *s = SOCKET(u);
2773 SocketPort *p;
2774
2775 assert(u);
2776
2777 LIST_FOREACH(port, p, s->ports) {
01e10de3
LP
2778 int fd;
2779
2780 if (p->type != SOCKET_SOCKET)
2781 continue;
2782
2783 if (p->fd >= 0)
2784 continue;
2785
90e74a66 2786 FDSET_FOREACH(fd, fds) {
01e10de3
LP
2787 if (socket_address_matches_fd(&p->address, fd)) {
2788 p->fd = fdset_remove(fds, fd);
2789 s->deserialized_state = SOCKET_LISTENING;
2790 break;
2791 }
2792 }
2793 }
01e10de3
LP
2794}
2795
44a6b1b6 2796_pure_ static UnitActiveState socket_active_state(Unit *u) {
87f0e418 2797 assert(u);
5cb5a6ff 2798
acbb0225 2799 return state_translation_table[SOCKET(u)->state];
5cb5a6ff
LP
2800}
2801
44a6b1b6 2802_pure_ static const char *socket_sub_state_to_string(Unit *u) {
10a94420
LP
2803 assert(u);
2804
a16e1123 2805 return socket_state_to_string(SOCKET(u)->state);
10a94420
LP
2806}
2807
67419600
OS
2808const char* socket_port_type_to_string(SocketPort *p) {
2809
2810 assert(p);
2811
2812 switch (p->type) {
718db961
LP
2813
2814 case SOCKET_SOCKET:
2815
2816 switch (p->address.type) {
2817
2818 case SOCK_STREAM:
2819 return "Stream";
2820
2821 case SOCK_DGRAM:
2822 return "Datagram";
2823
2824 case SOCK_SEQPACKET:
2825 return "SequentialPacket";
2826
2827 case SOCK_RAW:
2828 if (socket_address_family(&p->address) == AF_NETLINK)
2829 return "Netlink";
2830
4831981d 2831 _fallthrough_;
718db961
LP
2832 default:
2833 return NULL;
2834 }
2835
2836 case SOCKET_SPECIAL:
2837 return "Special";
2838
2839 case SOCKET_MQUEUE:
2840 return "MessageQueue";
2841
2842 case SOCKET_FIFO:
2843 return "FIFO";
2844
60252446
PS
2845 case SOCKET_USB_FUNCTION:
2846 return "USBFunction";
2847
718db961
LP
2848 default:
2849 return NULL;
67419600
OS
2850 }
2851}
2852
038ed5a4
YW
2853SocketType socket_port_type_from_string(const char *s) {
2854 assert(s);
2855
e045e325
YW
2856 if (STR_IN_SET(s, "Stream", "Datagram", "SequentialPacket", "Netlink"))
2857 return SOCKET_SOCKET;
2858 else if (streq(s, "Special"))
2859 return SOCKET_SPECIAL;
2860 else if (streq(s, "MessageQueue"))
2861 return SOCKET_MQUEUE;
2862 else if (streq(s, "FIFO"))
2863 return SOCKET_FIFO;
2864 else if (streq(s, "USBFunction"))
2865 return SOCKET_USB_FUNCTION;
038ed5a4
YW
2866 else
2867 return _SOCKET_TYPE_INVALID;
2868}
2869
f2f725e5 2870_pure_ static bool socket_may_gc(Unit *u) {
6cf6bbc2
LP
2871 Socket *s = SOCKET(u);
2872
2873 assert(u);
2874
f2f725e5 2875 return s->n_connections == 0;
6cf6bbc2
LP
2876}
2877
a79279c7
LP
2878static int socket_accept_do(Socket *s, int fd) {
2879 int cfd;
2880
2881 assert(s);
2882 assert(fd >= 0);
2883
4ff9bc2e
LP
2884 cfd = accept4(fd, NULL, NULL, SOCK_NONBLOCK|SOCK_CLOEXEC);
2885 if (cfd < 0)
2886 /* Convert transient network errors into clean and well-defined EAGAIN */
2887 return ERRNO_IS_ACCEPT_AGAIN(errno) ? -EAGAIN : -errno;
a79279c7
LP
2888
2889 return cfd;
2890}
2891
2892static int socket_accept_in_cgroup(Socket *s, SocketPort *p, int fd) {
2893 _cleanup_close_pair_ int pair[2] = { -1, -1 };
2894 int cfd, r;
2895 pid_t pid;
2896
2897 assert(s);
2898 assert(p);
2899 assert(fd >= 0);
2900
5238e957 2901 /* Similar to socket_address_listen_in_cgroup(), but for accept() rather than socket(): make sure that any
a79279c7
LP
2902 * connection socket is also properly associated with the cgroup. */
2903
2904 if (!IN_SET(p->address.sockaddr.sa.sa_family, AF_INET, AF_INET6))
2905 goto shortcut;
2906
2907 r = bpf_firewall_supported();
2908 if (r < 0)
2909 return r;
2ae7ee58 2910 if (r == BPF_FIREWALL_UNSUPPORTED)
a79279c7
LP
2911 goto shortcut;
2912
2913 if (socketpair(AF_UNIX, SOCK_SEQPACKET|SOCK_CLOEXEC, 0, pair) < 0)
2914 return log_unit_error_errno(UNIT(s), errno, "Failed to create communication channel: %m");
2915
4c253ed1 2916 r = unit_fork_helper_process(UNIT(s), "(sd-accept)", &pid);
a79279c7
LP
2917 if (r < 0)
2918 return log_unit_error_errno(UNIT(s), r, "Failed to fork off accept stub process: %m");
2919 if (r == 0) {
2920 /* Child */
2921
2922 pair[0] = safe_close(pair[0]);
2923
2924 cfd = socket_accept_do(s, fd);
4ff9bc2e
LP
2925 if (cfd == -EAGAIN) /* spurious accept() */
2926 _exit(EXIT_SUCCESS);
a79279c7
LP
2927 if (cfd < 0) {
2928 log_unit_error_errno(UNIT(s), cfd, "Failed to accept connection socket: %m");
2929 _exit(EXIT_FAILURE);
2930 }
2931
2932 r = send_one_fd(pair[1], cfd, 0);
2933 if (r < 0) {
2934 log_unit_error_errno(UNIT(s), r, "Failed to send connection socket to parent: %m");
2935 _exit(EXIT_FAILURE);
2936 }
2937
2938 _exit(EXIT_SUCCESS);
2939 }
2940
2941 pair[1] = safe_close(pair[1]);
2942 cfd = receive_one_fd(pair[0], 0);
2943
2944 /* We synchronously wait for the helper, as it shouldn't be slow */
d2e0ac3d 2945 r = wait_for_terminate_and_check("(sd-accept)", pid, WAIT_LOG_ABNORMAL);
a79279c7
LP
2946 if (r < 0) {
2947 safe_close(cfd);
2948 return r;
2949 }
2950
4ff9bc2e
LP
2951 /* If we received no fd, we got EIO here. If this happens with a process exit code of EXIT_SUCCESS
2952 * this is a spurious accept(), let's convert that back to EAGAIN here. */
2953 if (cfd == -EIO)
2954 return -EAGAIN;
a79279c7
LP
2955 if (cfd < 0)
2956 return log_unit_error_errno(UNIT(s), cfd, "Failed to receive connection socket: %m");
2957
2958 return cfd;
2959
2960shortcut:
2961 cfd = socket_accept_do(s, fd);
4ff9bc2e
LP
2962 if (cfd == -EAGAIN) /* spurious accept(), skip it silently */
2963 return -EAGAIN;
a79279c7
LP
2964 if (cfd < 0)
2965 return log_unit_error_errno(UNIT(s), cfd, "Failed to accept connection socket: %m");
2966
2967 return cfd;
2968}
2969
718db961
LP
2970static int socket_dispatch_io(sd_event_source *source, int fd, uint32_t revents, void *userdata) {
2971 SocketPort *p = userdata;
4f2d528d 2972 int cfd = -1;
9152c765 2973
718db961 2974 assert(p);
8d567588 2975 assert(fd >= 0);
9152c765 2976
718db961
LP
2977 if (p->socket->state != SOCKET_LISTENING)
2978 return 0;
871d7de4 2979
f2341e0a 2980 log_unit_debug(UNIT(p->socket), "Incoming traffic");
9152c765 2981
718db961 2982 if (revents != EPOLLIN) {
718db961 2983 if (revents & EPOLLHUP)
f2341e0a 2984 log_unit_error(UNIT(p->socket), "Got POLLHUP on a listening socket. The service probably invoked shutdown() on it, and should better not do that.");
641e01dc 2985 else
f2341e0a 2986 log_unit_error(UNIT(p->socket), "Got unexpected poll event (0x%x) on socket.", revents);
8d567588 2987 goto fail;
4f2d528d
LP
2988 }
2989
718db961
LP
2990 if (p->socket->accept &&
2991 p->type == SOCKET_SOCKET &&
2992 socket_address_can_accept(&p->address)) {
2993
a79279c7 2994 cfd = socket_accept_in_cgroup(p->socket, p, fd);
4ff9bc2e
LP
2995 if (cfd == -EAGAIN) /* Spurious accept() */
2996 return 0;
a79279c7
LP
2997 if (cfd < 0)
2998 goto fail;
4fd5948e 2999
5d0fe423 3000 socket_apply_socket_options(p->socket, p, cfd);
4f2d528d 3001 }
9152c765 3002
718db961
LP
3003 socket_enter_running(p->socket, cfd);
3004 return 0;
8d567588
LP
3005
3006fail:
718db961
LP
3007 socket_enter_stop_pre(p->socket, SOCKET_FAILURE_RESOURCES);
3008 return 0;
9152c765
LP
3009}
3010
87f0e418
LP
3011static void socket_sigchld_event(Unit *u, pid_t pid, int code, int status) {
3012 Socket *s = SOCKET(u);
cfc4eb4c 3013 SocketResult f;
5cb5a6ff
LP
3014
3015 assert(s);
034c6ed7 3016 assert(pid >= 0);
5cb5a6ff 3017
8c47c732
LP
3018 if (pid != s->control_pid)
3019 return;
542563ba 3020
034c6ed7
LP
3021 s->control_pid = 0;
3022
1f0958f6 3023 if (is_clean_exit(code, status, EXIT_CLEAN_COMMAND, NULL))
cfc4eb4c
LP
3024 f = SOCKET_SUCCESS;
3025 else if (code == CLD_EXITED)
3026 f = SOCKET_FAILURE_EXIT_CODE;
3027 else if (code == CLD_KILLED)
3028 f = SOCKET_FAILURE_SIGNAL;
3029 else if (code == CLD_DUMPED)
3030 f = SOCKET_FAILURE_CORE_DUMP;
3031 else
a4152e3f 3032 assert_not_reached("Unknown sigchld code");
8c47c732 3033
b708e7ce 3034 if (s->control_command) {
6ea832a2 3035 exec_status_exit(&s->control_command->exec_status, &s->exec_context, pid, code, status);
a16e1123 3036
3ed0cd26 3037 if (s->control_command->flags & EXEC_COMMAND_IGNORE_FAILURE)
cfc4eb4c 3038 f = SOCKET_SUCCESS;
b708e7ce
LP
3039 }
3040
91bbd9b7 3041 unit_log_process_exit(
5cc2cd1c 3042 u,
91bbd9b7
LP
3043 "Control process",
3044 socket_exec_command_to_string(s->control_command_id),
5cc2cd1c 3045 f == SOCKET_SUCCESS,
91bbd9b7 3046 code, status);
034c6ed7 3047
a0fef983 3048 if (s->result == SOCKET_SUCCESS)
cfc4eb4c
LP
3049 s->result = f;
3050
3051 if (s->control_command &&
3052 s->control_command->command_next &&
3053 f == SOCKET_SUCCESS) {
3054
f2341e0a 3055 log_unit_debug(u, "Running next command for state %s", socket_state_to_string(s->state));
cfc4eb4c 3056 socket_run_next(s);
acbb0225 3057 } else {
a16e1123
LP
3058 s->control_command = NULL;
3059 s->control_command_id = _SOCKET_EXEC_COMMAND_INVALID;
3060
034c6ed7
LP
3061 /* No further commands for this step, so let's figure
3062 * out what to do next */
5cb5a6ff 3063
f2341e0a 3064 log_unit_debug(u, "Got final SIGCHLD for state %s", socket_state_to_string(s->state));
acbb0225 3065
034c6ed7
LP
3066 switch (s->state) {
3067
3068 case SOCKET_START_PRE:
cfc4eb4c 3069 if (f == SOCKET_SUCCESS)
3900e5fd 3070 socket_enter_start_chown(s);
034c6ed7 3071 else
cfc4eb4c 3072 socket_enter_signal(s, SOCKET_FINAL_SIGTERM, f);
034c6ed7
LP
3073 break;
3074
3900e5fd
LP
3075 case SOCKET_START_CHOWN:
3076 if (f == SOCKET_SUCCESS)
3077 socket_enter_start_post(s);
3078 else
3079 socket_enter_stop_pre(s, f);
3080 break;
3081
034c6ed7 3082 case SOCKET_START_POST:
cfc4eb4c 3083 if (f == SOCKET_SUCCESS)
e9af15c3 3084 socket_enter_listening(s);
034c6ed7 3085 else
cfc4eb4c 3086 socket_enter_stop_pre(s, f);
034c6ed7
LP
3087 break;
3088
3089 case SOCKET_STOP_PRE:
3090 case SOCKET_STOP_PRE_SIGTERM:
3091 case SOCKET_STOP_PRE_SIGKILL:
cfc4eb4c 3092 socket_enter_stop_post(s, f);
034c6ed7
LP
3093 break;
3094
3095 case SOCKET_STOP_POST:
80876c20
LP
3096 case SOCKET_FINAL_SIGTERM:
3097 case SOCKET_FINAL_SIGKILL:
cfc4eb4c 3098 socket_enter_dead(s, f);
034c6ed7
LP
3099 break;
3100
c968d76a
YW
3101 case SOCKET_CLEANING:
3102
3103 if (s->clean_result == SOCKET_SUCCESS)
3104 s->clean_result = f;
3105
3106 socket_enter_dead(s, SOCKET_SUCCESS);
3107 break;
3108
034c6ed7
LP
3109 default:
3110 assert_not_reached("Uh, control process died at wrong time.");
3111 }
3112 }
c4e2ceae
LP
3113
3114 /* Notify clients about changed exit status */
3115 unit_add_to_dbus_queue(u);
034c6ed7 3116}
5cb5a6ff 3117
718db961
LP
3118static int socket_dispatch_timer(sd_event_source *source, usec_t usec, void *userdata) {
3119 Socket *s = SOCKET(userdata);
5cb5a6ff 3120
034c6ed7 3121 assert(s);
718db961 3122 assert(s->timer_event_source == source);
034c6ed7
LP
3123
3124 switch (s->state) {
3125
3126 case SOCKET_START_PRE:
f2341e0a 3127 log_unit_warning(UNIT(s), "Starting timed out. Terminating.");
cfc4eb4c 3128 socket_enter_signal(s, SOCKET_FINAL_SIGTERM, SOCKET_FAILURE_TIMEOUT);
da19d5c1 3129 break;
80876c20 3130
3900e5fd 3131 case SOCKET_START_CHOWN:
034c6ed7 3132 case SOCKET_START_POST:
f2341e0a 3133 log_unit_warning(UNIT(s), "Starting timed out. Stopping.");
cfc4eb4c 3134 socket_enter_stop_pre(s, SOCKET_FAILURE_TIMEOUT);
034c6ed7
LP
3135 break;
3136
3137 case SOCKET_STOP_PRE:
f2341e0a 3138 log_unit_warning(UNIT(s), "Stopping timed out. Terminating.");
cfc4eb4c 3139 socket_enter_signal(s, SOCKET_STOP_PRE_SIGTERM, SOCKET_FAILURE_TIMEOUT);
034c6ed7
LP
3140 break;
3141
3142 case SOCKET_STOP_PRE_SIGTERM:
4819ff03 3143 if (s->kill_context.send_sigkill) {
f2341e0a 3144 log_unit_warning(UNIT(s), "Stopping timed out. Killing.");
cfc4eb4c 3145 socket_enter_signal(s, SOCKET_STOP_PRE_SIGKILL, SOCKET_FAILURE_TIMEOUT);
ba035df2 3146 } else {
f2341e0a 3147 log_unit_warning(UNIT(s), "Stopping timed out. Skipping SIGKILL. Ignoring.");
cfc4eb4c 3148 socket_enter_stop_post(s, SOCKET_FAILURE_TIMEOUT);
ba035df2 3149 }
034c6ed7
LP
3150 break;
3151
3152 case SOCKET_STOP_PRE_SIGKILL:
f2341e0a 3153 log_unit_warning(UNIT(s), "Processes still around after SIGKILL. Ignoring.");
cfc4eb4c 3154 socket_enter_stop_post(s, SOCKET_FAILURE_TIMEOUT);
034c6ed7
LP
3155 break;
3156
3157 case SOCKET_STOP_POST:
f2341e0a 3158 log_unit_warning(UNIT(s), "Stopping timed out (2). Terminating.");
cfc4eb4c 3159 socket_enter_signal(s, SOCKET_FINAL_SIGTERM, SOCKET_FAILURE_TIMEOUT);
034c6ed7
LP
3160 break;
3161
80876c20 3162 case SOCKET_FINAL_SIGTERM:
4819ff03 3163 if (s->kill_context.send_sigkill) {
f2341e0a 3164 log_unit_warning(UNIT(s), "Stopping timed out (2). Killing.");
cfc4eb4c 3165 socket_enter_signal(s, SOCKET_FINAL_SIGKILL, SOCKET_FAILURE_TIMEOUT);
ba035df2 3166 } else {
f2341e0a 3167 log_unit_warning(UNIT(s), "Stopping timed out (2). Skipping SIGKILL. Ignoring.");
cfc4eb4c 3168 socket_enter_dead(s, SOCKET_FAILURE_TIMEOUT);
ba035df2 3169 }
034c6ed7
LP
3170 break;
3171
80876c20 3172 case SOCKET_FINAL_SIGKILL:
f2341e0a 3173 log_unit_warning(UNIT(s), "Still around after SIGKILL (2). Entering failed mode.");
cfc4eb4c 3174 socket_enter_dead(s, SOCKET_FAILURE_TIMEOUT);
034c6ed7
LP
3175 break;
3176
c968d76a
YW
3177 case SOCKET_CLEANING:
3178 log_unit_warning(UNIT(s), "Cleaning timed out. killing.");
3179
3180 if (s->clean_result == SOCKET_SUCCESS)
3181 s->clean_result = SOCKET_FAILURE_TIMEOUT;
3182
3183 socket_enter_signal(s, SOCKET_FINAL_SIGKILL, 0);
3184 break;
3185
034c6ed7
LP
3186 default:
3187 assert_not_reached("Timeout at wrong time.");
3188 }
718db961
LP
3189
3190 return 0;
5cb5a6ff
LP
3191}
3192
79c7626d 3193int socket_collect_fds(Socket *s, int **fds) {
da6053d0 3194 size_t k = 0, n = 0;
44d8db9e 3195 SocketPort *p;
da6053d0 3196 int *rfds;
44d8db9e
LP
3197
3198 assert(s);
3199 assert(fds);
44d8db9e
LP
3200
3201 /* Called from the service code for requesting our fds */
3202
15087cdb 3203 LIST_FOREACH(port, p, s->ports) {
44d8db9e 3204 if (p->fd >= 0)
79c7626d
LP
3205 n++;
3206 n += p->n_auxiliary_fds;
15087cdb 3207 }
44d8db9e 3208
79c7626d 3209 if (n <= 0) {
de3756ab 3210 *fds = NULL;
de3756ab
LP
3211 return 0;
3212 }
3213
79c7626d 3214 rfds = new(int, n);
e5403f09 3215 if (!rfds)
44d8db9e
LP
3216 return -ENOMEM;
3217
15087cdb 3218 LIST_FOREACH(port, p, s->ports) {
da6053d0 3219 size_t i;
79c7626d 3220
44d8db9e
LP
3221 if (p->fd >= 0)
3222 rfds[k++] = p->fd;
15087cdb
PS
3223 for (i = 0; i < p->n_auxiliary_fds; ++i)
3224 rfds[k++] = p->auxiliary_fds[i];
3225 }
44d8db9e 3226
79c7626d 3227 assert(k == n);
44d8db9e
LP
3228
3229 *fds = rfds;
da6053d0 3230 return (int) n;
44d8db9e
LP
3231}
3232
e821075a
LP
3233static void socket_reset_failed(Unit *u) {
3234 Socket *s = SOCKET(u);
3235
3236 assert(s);
3237
3238 if (s->state == SOCKET_FAILED)
3239 socket_set_state(s, SOCKET_DEAD);
3240
3241 s->result = SOCKET_SUCCESS;
c968d76a 3242 s->clean_result = SOCKET_SUCCESS;
e821075a
LP
3243}
3244
6cf6bbc2
LP
3245void socket_connection_unref(Socket *s) {
3246 assert(s);
3247
3248 /* The service is dead. Yay!
3249 *
35b8ca3a 3250 * This is strictly for one-instance-per-connection
6cf6bbc2
LP
3251 * services. */
3252
3253 assert(s->n_connections > 0);
3254 s->n_connections--;
3255
f2341e0a 3256 log_unit_debug(UNIT(s), "One connection closed, %u left.", s->n_connections);
5632e374
LP
3257}
3258
d137a488
UTL
3259static void socket_trigger_notify(Unit *u, Unit *other) {
3260 Socket *s = SOCKET(u);
d137a488
UTL
3261
3262 assert(u);
3263 assert(other);
3264
d14e3a0d 3265 /* Filter out invocations with bogus state */
0377cd29
LP
3266 assert(UNIT_IS_LOAD_COMPLETE(other->load_state));
3267 assert(other->type == UNIT_SERVICE);
d14e3a0d
LP
3268
3269 /* Don't propagate state changes from the service if we are already down */
3270 if (!IN_SET(s->state, SOCKET_RUNNING, SOCKET_LISTENING))
d137a488
UTL
3271 return;
3272
d14e3a0d
LP
3273 /* We don't care for the service state if we are in Accept=yes mode */
3274 if (s->accept)
3275 return;
3276
3277 /* Propagate start limit hit state */
6bf0f408
LP
3278 if (other->start_limit_hit) {
3279 socket_enter_stop_pre(s, SOCKET_FAILURE_SERVICE_START_LIMIT_HIT);
d137a488 3280 return;
6bf0f408 3281 }
d137a488 3282
d14e3a0d
LP
3283 /* Don't propagate anything if there's still a job queued */
3284 if (other->job)
6bf0f408 3285 return;
d137a488 3286
6bf0f408
LP
3287 if (IN_SET(SERVICE(other)->state,
3288 SERVICE_DEAD, SERVICE_FAILED,
3289 SERVICE_FINAL_SIGTERM, SERVICE_FINAL_SIGKILL,
3290 SERVICE_AUTO_RESTART))
3291 socket_enter_listening(s);
d137a488 3292
6bf0f408 3293 if (SERVICE(other)->state == SERVICE_RUNNING)
d137a488
UTL
3294 socket_set_state(s, SOCKET_RUNNING);
3295}
3296
718db961 3297static int socket_kill(Unit *u, KillWho who, int signo, sd_bus_error *error) {
814cc562 3298 return unit_kill_common(u, who, signo, -1, SOCKET(u)->control_pid, error);
8a0867d6
LP
3299}
3300
7a7821c8 3301static int socket_get_timeout(Unit *u, usec_t *timeout) {
68db7a3b 3302 Socket *s = SOCKET(u);
7a7821c8 3303 usec_t t;
68db7a3b
ZJS
3304 int r;
3305
3306 if (!s->timer_event_source)
3307 return 0;
3308
7a7821c8 3309 r = sd_event_source_get_time(s->timer_event_source, &t);
68db7a3b
ZJS
3310 if (r < 0)
3311 return r;
7a7821c8
LP
3312 if (t == USEC_INFINITY)
3313 return 0;
68db7a3b 3314
7a7821c8 3315 *timeout = t;
68db7a3b
ZJS
3316 return 1;
3317}
3318
8dd4c05b
LP
3319char *socket_fdname(Socket *s) {
3320 assert(s);
3321
3322 /* Returns the name to use for $LISTEN_NAMES. If the user
3323 * didn't specify anything specifically, use the socket unit's
3324 * name as fallback. */
3325
84500122 3326 return s->fdname ?: UNIT(s)->id;
8dd4c05b
LP
3327}
3328
291d565a
LP
3329static int socket_control_pid(Unit *u) {
3330 Socket *s = SOCKET(u);
3331
3332 assert(s);
3333
3334 return s->control_pid;
3335}
3336
c968d76a
YW
3337static int socket_clean(Unit *u, ExecCleanMask mask) {
3338 _cleanup_strv_free_ char **l = NULL;
3339 Socket *s = SOCKET(u);
3340 int r;
3341
3342 assert(s);
3343 assert(mask != 0);
3344
3345 if (s->state != SOCKET_DEAD)
3346 return -EBUSY;
3347
3348 r = exec_context_get_clean_directories(&s->exec_context, u->manager->prefix, mask, &l);
3349 if (r < 0)
3350 return r;
3351
3352 if (strv_isempty(l))
3353 return -EUNATCH;
3354
3355 socket_unwatch_control_pid(s);
3356 s->clean_result = SOCKET_SUCCESS;
3357 s->control_command = NULL;
3358 s->control_command_id = _SOCKET_EXEC_COMMAND_INVALID;
3359
3360 r = socket_arm_timer(s, usec_add(now(CLOCK_MONOTONIC), s->exec_context.timeout_clean_usec));
3361 if (r < 0)
3362 goto fail;
3363
3364 r = unit_fork_and_watch_rm_rf(u, l, &s->control_pid);
3365 if (r < 0)
3366 goto fail;
3367
3368 socket_set_state(s, SOCKET_CLEANING);
3369
3370 return 0;
3371
3372fail:
3373 log_unit_warning_errno(u, r, "Failed to initiate cleaning: %m");
3374 s->clean_result = SOCKET_FAILURE_RESOURCES;
3375 s->timer_event_source = sd_event_source_unref(s->timer_event_source);
3376 return r;
3377}
3378
3379static int socket_can_clean(Unit *u, ExecCleanMask *ret) {
3380 Socket *s = SOCKET(u);
3381
3382 assert(s);
3383
3384 return exec_context_get_clean_mask(&s->exec_context, ret);
3385}
3386
a16e1123 3387static const char* const socket_exec_command_table[_SOCKET_EXEC_COMMAND_MAX] = {
836bb1cd
YW
3388 [SOCKET_EXEC_START_PRE] = "ExecStartPre",
3389 [SOCKET_EXEC_START_CHOWN] = "ExecStartChown",
3390 [SOCKET_EXEC_START_POST] = "ExecStartPost",
3391 [SOCKET_EXEC_STOP_PRE] = "ExecStopPre",
3392 [SOCKET_EXEC_STOP_POST] = "ExecStopPost"
a16e1123
LP
3393};
3394
3395DEFINE_STRING_TABLE_LOOKUP(socket_exec_command, SocketExecCommand);
3396
cfc4eb4c
LP
3397static const char* const socket_result_table[_SOCKET_RESULT_MAX] = {
3398 [SOCKET_SUCCESS] = "success",
3399 [SOCKET_FAILURE_RESOURCES] = "resources",
3400 [SOCKET_FAILURE_TIMEOUT] = "timeout",
3401 [SOCKET_FAILURE_EXIT_CODE] = "exit-code",
3402 [SOCKET_FAILURE_SIGNAL] = "signal",
c2f34808 3403 [SOCKET_FAILURE_CORE_DUMP] = "core-dump",
07299350 3404 [SOCKET_FAILURE_START_LIMIT_HIT] = "start-limit-hit",
8b26cdbd 3405 [SOCKET_FAILURE_TRIGGER_LIMIT_HIT] = "trigger-limit-hit",
6bf0f408 3406 [SOCKET_FAILURE_SERVICE_START_LIMIT_HIT] = "service-start-limit-hit"
cfc4eb4c
LP
3407};
3408
3409DEFINE_STRING_TABLE_LOOKUP(socket_result, SocketResult);
3410
9b191525
LP
3411static const char* const socket_timestamping_table[_SOCKET_TIMESTAMPING_MAX] = {
3412 [SOCKET_TIMESTAMPING_OFF] = "off",
3413 [SOCKET_TIMESTAMPING_US] = "us",
3414 [SOCKET_TIMESTAMPING_NS] = "ns",
3415};
3416
3417DEFINE_STRING_TABLE_LOOKUP(socket_timestamping, SocketTimestamping);
3418
3419SocketTimestamping socket_timestamping_from_string_harder(const char *p) {
3420 SocketTimestamping t;
3421 int r;
3422
3423 if (!p)
3424 return _SOCKET_TIMESTAMPING_INVALID;
3425
3426 t = socket_timestamping_from_string(p);
3427 if (t >= 0)
3428 return t;
3429
3430 /* Let's alternatively support the various other aliases parse_time() accepts for ns and µs here,
3431 * too. */
3432 if (streq(p, "nsec"))
3433 return SOCKET_TIMESTAMPING_NS;
3434 if (STR_IN_SET(p, "usec", "µs"))
3435 return SOCKET_TIMESTAMPING_US;
3436
3437 r = parse_boolean(p);
3438 if (r < 0)
3439 return _SOCKET_TIMESTAMPING_INVALID;
3440
3441 return r ? SOCKET_TIMESTAMPING_NS : SOCKET_TIMESTAMPING_OFF; /* If boolean yes, default to ns accuracy */
3442}
3443
87f0e418 3444const UnitVTable socket_vtable = {
7d17cfbc 3445 .object_size = sizeof(Socket),
718db961
LP
3446 .exec_context_offset = offsetof(Socket, exec_context),
3447 .cgroup_context_offset = offsetof(Socket, cgroup_context),
3448 .kill_context_offset = offsetof(Socket, kill_context),
613b411c 3449 .exec_runtime_offset = offsetof(Socket, exec_runtime),
29206d46 3450 .dynamic_creds_offset = offsetof(Socket, dynamic_creds),
3ef63c31 3451
f975e971
LP
3452 .sections =
3453 "Unit\0"
3454 "Socket\0"
3455 "Install\0",
4ad49000 3456 .private_section = "Socket",
71645aca 3457
9c0320e7 3458 .can_transient = true,
c80a9a33
LP
3459 .can_trigger = true,
3460 .can_fail = true,
9c0320e7 3461
034c6ed7
LP
3462 .init = socket_init,
3463 .done = socket_done,
a16e1123
LP
3464 .load = socket_load,
3465
3466 .coldplug = socket_coldplug,
034c6ed7 3467
5cb5a6ff
LP
3468 .dump = socket_dump,
3469
542563ba
LP
3470 .start = socket_start,
3471 .stop = socket_stop,
5cb5a6ff 3472
718db961 3473 .kill = socket_kill,
c968d76a
YW
3474 .clean = socket_clean,
3475 .can_clean = socket_can_clean,
718db961 3476
68db7a3b
ZJS
3477 .get_timeout = socket_get_timeout,
3478
a16e1123
LP
3479 .serialize = socket_serialize,
3480 .deserialize_item = socket_deserialize_item,
01e10de3 3481 .distribute_fds = socket_distribute_fds,
a16e1123 3482
5cb5a6ff 3483 .active_state = socket_active_state,
10a94420 3484 .sub_state_to_string = socket_sub_state_to_string,
5cb5a6ff 3485
52a12341
YW
3486 .will_restart = unit_will_restart_default,
3487
f2f725e5 3488 .may_gc = socket_may_gc,
6cf6bbc2 3489
034c6ed7 3490 .sigchld_event = socket_sigchld_event,
4139c1b2 3491
d137a488
UTL
3492 .trigger_notify = socket_trigger_notify,
3493
fdf20a31 3494 .reset_failed = socket_reset_failed,
5632e374 3495
291d565a
LP
3496 .control_pid = socket_control_pid,
3497
74c964d3
LP
3498 .bus_set_property = bus_socket_set_property,
3499 .bus_commit_properties = bus_socket_commit_properties,
c6918296
MS
3500
3501 .status_message_formats = {
3502 /*.starting_stopping = {
3503 [0] = "Starting socket %s...",
3504 [1] = "Stopping socket %s...",
3505 },*/
3506 .finished_start_job = {
3507 [JOB_DONE] = "Listening on %s.",
3508 [JOB_FAILED] = "Failed to listen on %s.",
c6918296
MS
3509 [JOB_TIMEOUT] = "Timed out starting %s.",
3510 },
3511 .finished_stop_job = {
3512 [JOB_DONE] = "Closed %s.",
3513 [JOB_FAILED] = "Failed stopping %s.",
3514 [JOB_TIMEOUT] = "Timed out stopping %s.",
3515 },
3516 },
5cb5a6ff 3517};