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