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