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