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