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