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