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