]> git.ipfire.org Git - thirdparty/systemd.git/blame - src/core/socket.c
Merge pull request #11827 from keszybz/pkgconfig-variables
[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)
fc2d74ab 564 return log_unit_error_errno(UNIT(s), errno, "getpeername failed: %m");
166cf510 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
65486032
YW
1468#define log_address_error_errno(u, address, error, fmt) \
1469 ({ \
1470 _cleanup_free_ char *_t = NULL; \
1471 \
1472 (void) socket_address_print(address, &_t); \
1473 log_unit_error_errno(u, error, fmt, strna(_t)); \
1474 })
ae05e1b6 1475
a79279c7
LP
1476static int socket_address_listen_in_cgroup(
1477 Socket *s,
1478 const SocketAddress *address,
1479 const char *label) {
1480
1481 _cleanup_close_pair_ int pair[2] = { -1, -1 };
1482 int fd, r;
1483 pid_t pid;
1484
1485 assert(s);
1486 assert(address);
1487
1488 /* This is a wrapper around socket_address_listen(), that forks off a helper process inside the socket's cgroup
1489 * in which the socket is actually created. This way we ensure the socket is actually properly attached to the
1490 * unit's cgroup for the purpose of BPF filtering and such. */
1491
1492 if (!IN_SET(address->sockaddr.sa.sa_family, AF_INET, AF_INET6))
1493 goto shortcut; /* BPF filtering only applies to IPv4 + IPv6, shortcut things for other protocols */
1494
1495 r = bpf_firewall_supported();
1496 if (r < 0)
1497 return r;
2ae7ee58 1498 if (r == BPF_FIREWALL_UNSUPPORTED) /* If BPF firewalling isn't supported anyway — there's no point in this forking complexity */
a79279c7
LP
1499 goto shortcut;
1500
1501 if (socketpair(AF_UNIX, SOCK_SEQPACKET|SOCK_CLOEXEC, 0, pair) < 0)
1502 return log_unit_error_errno(UNIT(s), errno, "Failed to create communication channel: %m");
1503
4c253ed1 1504 r = unit_fork_helper_process(UNIT(s), "(sd-listen)", &pid);
a79279c7
LP
1505 if (r < 0)
1506 return log_unit_error_errno(UNIT(s), r, "Failed to fork off listener stub process: %m");
1507 if (r == 0) {
1508 /* Child */
1509
1510 pair[0] = safe_close(pair[0]);
1511
1512 fd = socket_address_listen_do(s, address, label);
1513 if (fd < 0) {
ae05e1b6 1514 log_address_error_errno(UNIT(s), address, fd, "Failed to create listening socket (%s): %m");
a79279c7
LP
1515 _exit(EXIT_FAILURE);
1516 }
1517
1518 r = send_one_fd(pair[1], fd, 0);
1519 if (r < 0) {
ae05e1b6 1520 log_address_error_errno(UNIT(s), address, r, "Failed to send listening socket (%s) to parent: %m");
a79279c7
LP
1521 _exit(EXIT_FAILURE);
1522 }
1523
1524 _exit(EXIT_SUCCESS);
1525 }
1526
1527 pair[1] = safe_close(pair[1]);
1528 fd = receive_one_fd(pair[0], 0);
1529
1530 /* We synchronously wait for the helper, as it shouldn't be slow */
d2e0ac3d 1531 r = wait_for_terminate_and_check("(sd-listen)", pid, WAIT_LOG_ABNORMAL);
a79279c7
LP
1532 if (r < 0) {
1533 safe_close(fd);
1534 return r;
1535 }
1536
1537 if (fd < 0)
ae05e1b6 1538 return log_address_error_errno(UNIT(s), address, fd, "Failed to receive listening socket (%s): %m");
a79279c7
LP
1539
1540 return fd;
1541
1542shortcut:
1543 fd = socket_address_listen_do(s, address, label);
1544 if (fd < 0)
ae05e1b6 1545 return log_address_error_errno(UNIT(s), address, fd, "Failed to create listening socket (%s): %m");
a79279c7
LP
1546
1547 return fd;
1548}
1549
e5417345
YW
1550DEFINE_TRIVIAL_CLEANUP_FUNC(Socket *, socket_close_fds);
1551
1552static int socket_open_fds(Socket *_s) {
1553 _cleanup_(socket_close_fdsp) Socket *s = _s;
710a6b50
LP
1554 _cleanup_(mac_selinux_freep) char *label = NULL;
1555 bool know_label = false;
83c60c9f
LP
1556 SocketPort *p;
1557 int r;
1558
1559 assert(s);
1560
034c6ed7 1561 LIST_FOREACH(port, p, s->ports) {
83c60c9f 1562
034c6ed7
LP
1563 if (p->fd >= 0)
1564 continue;
83c60c9f 1565
00411a13
LP
1566 switch (p->type) {
1567
1568 case SOCKET_SOCKET:
049f8642 1569
7f416dae 1570 if (!know_label) {
d24e561d
LP
1571 /* Figure out label, if we don't it know yet. We do it once, for the first socket where
1572 * we need this and remember it for the rest. */
7f416dae 1573
d24e561d
LP
1574 r = socket_determine_selinux_label(s, &label);
1575 if (r < 0)
ae05e1b6 1576 return log_unit_error_errno(UNIT(s), r, "Failed to determine SELinux label: %m");
049f8642
LP
1577
1578 know_label = true;
1579 }
1580
74bb646e 1581 /* Apply the socket protocol */
d24e561d 1582 switch (p->address.type) {
d2a50e3b 1583
74bb646e
SS
1584 case SOCK_STREAM:
1585 case SOCK_SEQPACKET:
d24e561d
LP
1586 if (s->socket_protocol == IPPROTO_SCTP)
1587 p->address.protocol = s->socket_protocol;
74bb646e 1588 break;
d2a50e3b 1589
74bb646e 1590 case SOCK_DGRAM:
d24e561d
LP
1591 if (s->socket_protocol == IPPROTO_UDPLITE)
1592 p->address.protocol = s->socket_protocol;
74bb646e
SS
1593 break;
1594 }
1595
d501e52b
YW
1596 p->fd = socket_address_listen_in_cgroup(s, &p->address, label);
1597 if (p->fd < 0)
1598 return p->fd;
83c60c9f 1599
4fd5948e 1600 socket_apply_socket_options(s, p->fd);
811ba7a0 1601 socket_symlink(s);
00411a13 1602 break;
4fd5948e 1603
00411a13 1604 case SOCKET_SPECIAL:
b0a3f2bc 1605
d501e52b
YW
1606 p->fd = special_address_create(p->path, s->writable);
1607 if (p->fd < 0)
1608 return log_unit_error_errno(UNIT(s), p->fd, "Failed to open special file %s: %m", p->path);
00411a13 1609 break;
b0a3f2bc 1610
00411a13 1611 case SOCKET_FIFO:
83c60c9f 1612
d501e52b 1613 p->fd = fifo_address_create(
175a3d25
LP
1614 p->path,
1615 s->directory_mode,
e8da24a6 1616 s->socket_mode);
d501e52b
YW
1617 if (p->fd < 0)
1618 return log_unit_error_errno(UNIT(s), p->fd, "Failed to open FIFO %s: %m", p->path);
83c60c9f 1619
b15bdda8 1620 socket_apply_fifo_options(s, p->fd);
811ba7a0 1621 socket_symlink(s);
00411a13 1622 break;
811ba7a0 1623
00411a13 1624 case SOCKET_MQUEUE:
83c60c9f 1625
d501e52b 1626 p->fd = mq_address_create(
175a3d25
LP
1627 p->path,
1628 s->socket_mode,
1629 s->mq_maxmsg,
e8da24a6 1630 s->mq_msgsize);
d501e52b
YW
1631 if (p->fd < 0)
1632 return log_unit_error_errno(UNIT(s), p->fd, "Failed to open message queue %s: %m", p->path);
00411a13 1633 break;
e8da24a6 1634
d2a50e3b 1635 case SOCKET_USB_FUNCTION: {
27a6ea91 1636 _cleanup_free_ char *ep = NULL;
60252446 1637
27a6ea91
GB
1638 ep = path_make_absolute("ep0", p->path);
1639
d501e52b
YW
1640 p->fd = usbffs_address_create(ep);
1641 if (p->fd < 0)
1642 return p->fd;
60252446 1643
36078102 1644 r = usbffs_write_descs(p->fd, SERVICE(UNIT_DEREF(s->service)));
6b7e5923 1645 if (r < 0)
e5417345 1646 return r;
6b7e5923 1647
36078102 1648 r = usbffs_dispatch_eps(p);
60252446 1649 if (r < 0)
e5417345 1650 return r;
00411a13
LP
1651
1652 break;
27a6ea91 1653 }
00411a13 1654 default:
b15bdda8 1655 assert_not_reached("Unknown port type");
00411a13 1656 }
034c6ed7
LP
1657 }
1658
e5417345 1659 s = NULL;
034c6ed7 1660 return 0;
034c6ed7
LP
1661}
1662
1663static void socket_unwatch_fds(Socket *s) {
1664 SocketPort *p;
718db961 1665 int r;
9152c765 1666
034c6ed7
LP
1667 assert(s);
1668
1669 LIST_FOREACH(port, p, s->ports) {
1670 if (p->fd < 0)
1671 continue;
1672
a4152e3f
LP
1673 if (!p->event_source)
1674 continue;
1675
1676 r = sd_event_source_set_enabled(p->event_source, SD_EVENT_OFF);
1677 if (r < 0)
f2341e0a 1678 log_unit_debug_errno(UNIT(s), r, "Failed to disable event source: %m");
83c60c9f 1679 }
034c6ed7
LP
1680}
1681
1682static int socket_watch_fds(Socket *s) {
1683 SocketPort *p;
1684 int r;
1685
1686 assert(s);
83c60c9f 1687
034c6ed7
LP
1688 LIST_FOREACH(port, p, s->ports) {
1689 if (p->fd < 0)
1690 continue;
1691
cbf60d0a 1692 if (p->event_source) {
718db961 1693 r = sd_event_source_set_enabled(p->event_source, SD_EVENT_ON);
cbf60d0a
LP
1694 if (r < 0)
1695 goto fail;
1696 } else {
151b9b96 1697 r = sd_event_add_io(UNIT(s)->manager->event, &p->event_source, p->fd, EPOLLIN, socket_dispatch_io, p);
cbf60d0a
LP
1698 if (r < 0)
1699 goto fail;
4f2d528d 1700
cbf60d0a 1701 (void) sd_event_source_set_description(p->event_source, "socket-port-io");
718db961 1702 }
034c6ed7 1703 }
83c60c9f 1704
542563ba 1705 return 0;
83c60c9f 1706
034c6ed7 1707fail:
cbf60d0a 1708 log_unit_warning_errno(UNIT(s), r, "Failed to watch listening fds: %m");
034c6ed7
LP
1709 socket_unwatch_fds(s);
1710 return r;
1711}
1712
01a8b467
LP
1713enum {
1714 SOCKET_OPEN_NONE,
1715 SOCKET_OPEN_SOME,
1716 SOCKET_OPEN_ALL,
1717};
1718
1719static int socket_check_open(Socket *s) {
1720 bool have_open = false, have_closed = false;
1721 SocketPort *p;
1722
1723 assert(s);
1724
1725 LIST_FOREACH(port, p, s->ports) {
1726 if (p->fd < 0)
1727 have_closed = true;
1728 else
1729 have_open = true;
1730
1731 if (have_open && have_closed)
1732 return SOCKET_OPEN_SOME;
1733 }
1734
1735 if (have_open)
1736 return SOCKET_OPEN_ALL;
1737
1738 return SOCKET_OPEN_NONE;
1739}
1740
034c6ed7
LP
1741static void socket_set_state(Socket *s, SocketState state) {
1742 SocketState old_state;
1743 assert(s);
1744
6fcbec6f
LP
1745 if (s->state != state)
1746 bus_unit_send_pending_change_signal(UNIT(s), false);
1747
034c6ed7
LP
1748 old_state = s->state;
1749 s->state = state;
1750
bd1fe7c7
LP
1751 if (!IN_SET(state,
1752 SOCKET_START_PRE,
3900e5fd 1753 SOCKET_START_CHOWN,
bd1fe7c7
LP
1754 SOCKET_START_POST,
1755 SOCKET_STOP_PRE,
1756 SOCKET_STOP_PRE_SIGTERM,
1757 SOCKET_STOP_PRE_SIGKILL,
1758 SOCKET_STOP_POST,
1759 SOCKET_FINAL_SIGTERM,
1760 SOCKET_FINAL_SIGKILL)) {
718db961
LP
1761
1762 s->timer_event_source = sd_event_source_unref(s->timer_event_source);
5e94833f 1763 socket_unwatch_control_pid(s);
034c6ed7 1764 s->control_command = NULL;
a16e1123 1765 s->control_command_id = _SOCKET_EXEC_COMMAND_INVALID;
e537352b 1766 }
034c6ed7 1767
a16e1123
LP
1768 if (state != SOCKET_LISTENING)
1769 socket_unwatch_fds(s);
1770
bd1fe7c7 1771 if (!IN_SET(state,
3900e5fd 1772 SOCKET_START_CHOWN,
bd1fe7c7
LP
1773 SOCKET_START_POST,
1774 SOCKET_LISTENING,
1775 SOCKET_RUNNING,
1776 SOCKET_STOP_PRE,
1777 SOCKET_STOP_PRE_SIGTERM,
1778 SOCKET_STOP_PRE_SIGKILL))
034c6ed7
LP
1779 socket_close_fds(s);
1780
e537352b 1781 if (state != old_state)
f2341e0a 1782 log_unit_debug(UNIT(s), "Changed %s -> %s", socket_state_to_string(old_state), socket_state_to_string(state));
acbb0225 1783
2ad2e41a 1784 unit_notify(UNIT(s), state_translation_table[old_state], state_translation_table[state], 0);
034c6ed7
LP
1785}
1786
be847e82 1787static int socket_coldplug(Unit *u) {
a16e1123
LP
1788 Socket *s = SOCKET(u);
1789 int r;
1790
1791 assert(s);
1792 assert(s->state == SOCKET_DEAD);
1793
e821075a
LP
1794 if (s->deserialized_state == s->state)
1795 return 0;
a16e1123 1796
c386f588
LP
1797 if (s->control_pid > 0 &&
1798 pid_is_unwaited(s->control_pid) &&
1799 IN_SET(s->deserialized_state,
3900e5fd
LP
1800 SOCKET_START_PRE,
1801 SOCKET_START_CHOWN,
1802 SOCKET_START_POST,
1803 SOCKET_STOP_PRE,
1804 SOCKET_STOP_PRE_SIGTERM,
1805 SOCKET_STOP_PRE_SIGKILL,
1806 SOCKET_STOP_POST,
1807 SOCKET_FINAL_SIGTERM,
1808 SOCKET_FINAL_SIGKILL)) {
a16e1123 1809
e821075a
LP
1810 r = unit_watch_pid(UNIT(s), s->control_pid);
1811 if (r < 0)
1812 return r;
a16e1123 1813
36c16a7c 1814 r = socket_arm_timer(s, usec_add(u->state_change_timestamp.monotonic, s->timeout_usec));
e821075a
LP
1815 if (r < 0)
1816 return r;
1817 }
a16e1123 1818
3900e5fd
LP
1819 if (IN_SET(s->deserialized_state,
1820 SOCKET_START_CHOWN,
1821 SOCKET_START_POST,
1822 SOCKET_LISTENING,
01a8b467
LP
1823 SOCKET_RUNNING)) {
1824
1825 /* Originally, we used to simply reopen all sockets here that we didn't have file descriptors
1826 * for. However, this is problematic, as we won't traverse throught the SOCKET_START_CHOWN state for
1827 * them, and thus the UID/GID wouldn't be right. Hence, instead simply check if we have all fds open,
1828 * and if there's a mismatch, warn loudly. */
1829
1830 r = socket_check_open(s);
1831 if (r == SOCKET_OPEN_NONE)
1832 log_unit_warning(UNIT(s),
1833 "Socket unit configuration has changed while unit has been running, "
1834 "no open socket file descriptor left. "
1835 "The socket unit is not functional until restarted.");
1836 else if (r == SOCKET_OPEN_SOME)
1837 log_unit_warning(UNIT(s),
1838 "Socket unit configuration has changed while unit has been running, "
1839 "and some socket file descriptors have not been opened yet. "
1840 "The socket unit is not fully functional until restarted.");
e821075a 1841 }
a16e1123 1842
e821075a
LP
1843 if (s->deserialized_state == SOCKET_LISTENING) {
1844 r = socket_watch_fds(s);
1845 if (r < 0)
1846 return r;
a16e1123
LP
1847 }
1848
e8a565cb 1849 if (!IN_SET(s->deserialized_state, SOCKET_DEAD, SOCKET_FAILED)) {
29206d46 1850 (void) unit_setup_dynamic_creds(u);
e8a565cb
YW
1851 (void) unit_setup_exec_runtime(u);
1852 }
29206d46 1853
e821075a 1854 socket_set_state(s, s->deserialized_state);
a16e1123
LP
1855 return 0;
1856}
1857
e537352b 1858static int socket_spawn(Socket *s, ExecCommand *c, pid_t *_pid) {
3c7416b6 1859
b9c04eaf 1860 _cleanup_(exec_params_clear) ExecParameters exec_params = {
5686391b
LP
1861 .flags = EXEC_APPLY_SANDBOXING|EXEC_APPLY_CHROOT|EXEC_APPLY_TTY_STDIN,
1862 .stdin_fd = -1,
1863 .stdout_fd = -1,
1864 .stderr_fd = -1,
1865 .exec_fd = -1,
9fa95f85 1866 };
3c7416b6
LP
1867 pid_t pid;
1868 int r;
034c6ed7
LP
1869
1870 assert(s);
1871 assert(c);
1872 assert(_pid);
1873
3c7416b6 1874 r = unit_prepare_exec(UNIT(s));
29206d46
LP
1875 if (r < 0)
1876 return r;
1877
36c16a7c 1878 r = socket_arm_timer(s, usec_add(now(CLOCK_MONOTONIC), s->timeout_usec));
36697dc0 1879 if (r < 0)
36c16a7c 1880 return r;
034c6ed7 1881
1ad6e8b3
LP
1882 r = unit_set_exec_params(UNIT(s), &exec_params);
1883 if (r < 0)
1884 return r;
3536f49e 1885
f2341e0a
LP
1886 r = exec_spawn(UNIT(s),
1887 c,
9e2f7c11 1888 &s->exec_context,
9fa95f85 1889 &exec_params,
613b411c 1890 s->exec_runtime,
29206d46 1891 &s->dynamic_creds,
9e2f7c11 1892 &pid);
cee288ad 1893 if (r < 0)
36c16a7c 1894 return r;
9e2f7c11 1895
3900e5fd 1896 r = unit_watch_pid(UNIT(s), pid);
9e2f7c11 1897 if (r < 0)
3900e5fd 1898 /* FIXME: we need to do something here */
36c16a7c 1899 return r;
034c6ed7 1900
3900e5fd 1901 *_pid = pid;
3536f49e 1902
3900e5fd 1903 return 0;
3900e5fd
LP
1904}
1905
1906static int socket_chown(Socket *s, pid_t *_pid) {
1907 pid_t pid;
1908 int r;
1909
36c16a7c 1910 r = socket_arm_timer(s, usec_add(now(CLOCK_MONOTONIC), s->timeout_usec));
3900e5fd
LP
1911 if (r < 0)
1912 goto fail;
1913
1914 /* We have to resolve the user names out-of-process, hence
1915 * let's fork here. It's messy, but well, what can we do? */
1916
4c253ed1 1917 r = unit_fork_helper_process(UNIT(s), "(sd-chown)", &pid);
a79279c7
LP
1918 if (r < 0)
1919 return r;
1920 if (r == 0) {
fed1e721
LP
1921 uid_t uid = UID_INVALID;
1922 gid_t gid = GID_INVALID;
a79279c7 1923 SocketPort *p;
3900e5fd 1924
a79279c7 1925 /* Child */
3900e5fd
LP
1926
1927 if (!isempty(s->user)) {
1928 const char *user = s->user;
1929
fafff8f1 1930 r = get_user_creds(&user, &uid, &gid, NULL, NULL, 0);
3900e5fd 1931 if (r < 0) {
a79279c7
LP
1932 log_unit_error_errno(UNIT(s), r, "Failed to resolve user %s: %m", user);
1933 _exit(EXIT_USER);
3900e5fd
LP
1934 }
1935 }
1936
1937 if (!isempty(s->group)) {
1938 const char *group = s->group;
1939
fafff8f1 1940 r = get_group_creds(&group, &gid, 0);
3900e5fd 1941 if (r < 0) {
a79279c7
LP
1942 log_unit_error_errno(UNIT(s), r, "Failed to resolve group %s: %m", group);
1943 _exit(EXIT_GROUP);
3900e5fd
LP
1944 }
1945 }
1946
1947 LIST_FOREACH(port, p, s->ports) {
e5a1c18d 1948 const char *path = NULL;
3900e5fd
LP
1949
1950 if (p->type == SOCKET_SOCKET)
1951 path = socket_address_get_path(&p->address);
1952 else if (p->type == SOCKET_FIFO)
1953 path = p->path;
1954
1955 if (!path)
1956 continue;
1957
1958 if (chown(path, uid, gid) < 0) {
a79279c7
LP
1959 log_unit_error_errno(UNIT(s), errno, "Failed to chown(): %m");
1960 _exit(EXIT_CHOWN);
3900e5fd
LP
1961 }
1962 }
1963
a79279c7 1964 _exit(EXIT_SUCCESS);
3900e5fd
LP
1965 }
1966
718db961
LP
1967 r = unit_watch_pid(UNIT(s), pid);
1968 if (r < 0)
034c6ed7 1969 goto fail;
83c60c9f 1970
034c6ed7 1971 *_pid = pid;
034c6ed7
LP
1972 return 0;
1973
1974fail:
718db961 1975 s->timer_event_source = sd_event_source_unref(s->timer_event_source);
83c60c9f 1976 return r;
542563ba
LP
1977}
1978
cfc4eb4c 1979static void socket_enter_dead(Socket *s, SocketResult f) {
034c6ed7
LP
1980 assert(s);
1981
a0fef983 1982 if (s->result == SOCKET_SUCCESS)
cfc4eb4c 1983 s->result = f;
034c6ed7 1984
523ee2d4
LP
1985 if (s->result == SOCKET_SUCCESS)
1986 unit_log_success(UNIT(s));
1987 else
7c047d74 1988 unit_log_failure(UNIT(s), socket_result_to_string(s->result));
ed77d407 1989
29206d46
LP
1990 socket_set_state(s, s->result != SOCKET_SUCCESS ? SOCKET_FAILED : SOCKET_DEAD);
1991
e8a565cb 1992 s->exec_runtime = exec_runtime_unref(s->exec_runtime, true);
613b411c 1993
3536f49e 1994 exec_context_destroy_runtime_directory(&s->exec_context, UNIT(s)->manager->prefix[EXEC_DIRECTORY_RUNTIME]);
e66cf1a3 1995
00d9ef85
LP
1996 unit_unref_uid_gid(UNIT(s), true);
1997
29206d46 1998 dynamic_creds_destroy(&s->dynamic_creds);
034c6ed7
LP
1999}
2000
cfc4eb4c 2001static void socket_enter_signal(Socket *s, SocketState state, SocketResult f);
80876c20 2002
cfc4eb4c 2003static void socket_enter_stop_post(Socket *s, SocketResult f) {
034c6ed7
LP
2004 int r;
2005 assert(s);
2006
a0fef983 2007 if (s->result == SOCKET_SUCCESS)
cfc4eb4c 2008 s->result = f;
034c6ed7 2009
5e94833f 2010 socket_unwatch_control_pid(s);
a16e1123 2011 s->control_command_id = SOCKET_EXEC_STOP_POST;
3900e5fd 2012 s->control_command = s->exec_command[SOCKET_EXEC_STOP_POST];
a16e1123 2013
3900e5fd
LP
2014 if (s->control_command) {
2015 r = socket_spawn(s, s->control_command, &s->control_pid);
2016 if (r < 0)
034c6ed7
LP
2017 goto fail;
2018
80876c20
LP
2019 socket_set_state(s, SOCKET_STOP_POST);
2020 } else
cfc4eb4c 2021 socket_enter_signal(s, SOCKET_FINAL_SIGTERM, SOCKET_SUCCESS);
034c6ed7
LP
2022
2023 return;
2024
2025fail:
f2341e0a 2026 log_unit_warning_errno(UNIT(s), r, "Failed to run 'stop-post' task: %m");
cfc4eb4c 2027 socket_enter_signal(s, SOCKET_FINAL_SIGTERM, SOCKET_FAILURE_RESOURCES);
034c6ed7
LP
2028}
2029
cfc4eb4c 2030static void socket_enter_signal(Socket *s, SocketState state, SocketResult f) {
034c6ed7
LP
2031 int r;
2032
2033 assert(s);
2034
a0fef983 2035 if (s->result == SOCKET_SUCCESS)
cfc4eb4c 2036 s->result = f;
034c6ed7 2037
cd2086fe
LP
2038 r = unit_kill_context(
2039 UNIT(s),
2040 &s->kill_context,
ec2ce0c5 2041 !IN_SET(state, SOCKET_STOP_PRE_SIGTERM, SOCKET_FINAL_SIGTERM) ?
db2cb23b 2042 KILL_KILL : KILL_TERMINATE,
cd2086fe
LP
2043 -1,
2044 s->control_pid,
2045 false);
2046 if (r < 0)
2047 goto fail;
034c6ed7 2048
cd2086fe 2049 if (r > 0) {
36c16a7c 2050 r = socket_arm_timer(s, usec_add(now(CLOCK_MONOTONIC), s->timeout_usec));
36697dc0 2051 if (r < 0)
80876c20 2052 goto fail;
d6ea93e3 2053
80876c20 2054 socket_set_state(s, state);
ac84d1fb
LP
2055 } else if (state == SOCKET_STOP_PRE_SIGTERM)
2056 socket_enter_signal(s, SOCKET_STOP_PRE_SIGKILL, SOCKET_SUCCESS);
2057 else if (state == SOCKET_STOP_PRE_SIGKILL)
cfc4eb4c 2058 socket_enter_stop_post(s, SOCKET_SUCCESS);
ac84d1fb
LP
2059 else if (state == SOCKET_FINAL_SIGTERM)
2060 socket_enter_signal(s, SOCKET_FINAL_SIGKILL, SOCKET_SUCCESS);
80876c20 2061 else
cfc4eb4c 2062 socket_enter_dead(s, SOCKET_SUCCESS);
034c6ed7
LP
2063
2064 return;
2065
2066fail:
f2341e0a 2067 log_unit_warning_errno(UNIT(s), r, "Failed to kill processes: %m");
034c6ed7 2068
3742095b 2069 if (IN_SET(state, SOCKET_STOP_PRE_SIGTERM, SOCKET_STOP_PRE_SIGKILL))
cfc4eb4c 2070 socket_enter_stop_post(s, SOCKET_FAILURE_RESOURCES);
034c6ed7 2071 else
cfc4eb4c 2072 socket_enter_dead(s, SOCKET_FAILURE_RESOURCES);
034c6ed7
LP
2073}
2074
cfc4eb4c 2075static void socket_enter_stop_pre(Socket *s, SocketResult f) {
034c6ed7
LP
2076 int r;
2077 assert(s);
2078
a0fef983 2079 if (s->result == SOCKET_SUCCESS)
cfc4eb4c 2080 s->result = f;
034c6ed7 2081
5e94833f 2082 socket_unwatch_control_pid(s);
a16e1123 2083 s->control_command_id = SOCKET_EXEC_STOP_PRE;
3900e5fd 2084 s->control_command = s->exec_command[SOCKET_EXEC_STOP_PRE];
a16e1123 2085
3900e5fd
LP
2086 if (s->control_command) {
2087 r = socket_spawn(s, s->control_command, &s->control_pid);
2088 if (r < 0)
034c6ed7
LP
2089 goto fail;
2090
80876c20
LP
2091 socket_set_state(s, SOCKET_STOP_PRE);
2092 } else
cfc4eb4c 2093 socket_enter_stop_post(s, SOCKET_SUCCESS);
034c6ed7
LP
2094
2095 return;
2096
2097fail:
f2341e0a 2098 log_unit_warning_errno(UNIT(s), r, "Failed to run 'stop-pre' task: %m");
cfc4eb4c 2099 socket_enter_stop_post(s, SOCKET_FAILURE_RESOURCES);
034c6ed7
LP
2100}
2101
e9af15c3
LP
2102static void socket_enter_listening(Socket *s) {
2103 int r;
2104 assert(s);
2105
cfc4eb4c
LP
2106 r = socket_watch_fds(s);
2107 if (r < 0) {
f2341e0a 2108 log_unit_warning_errno(UNIT(s), r, "Failed to watch sockets: %m");
e9af15c3
LP
2109 goto fail;
2110 }
2111
2112 socket_set_state(s, SOCKET_LISTENING);
2113 return;
2114
2115fail:
cfc4eb4c 2116 socket_enter_stop_pre(s, SOCKET_FAILURE_RESOURCES);
e9af15c3
LP
2117}
2118
034c6ed7
LP
2119static void socket_enter_start_post(Socket *s) {
2120 int r;
2121 assert(s);
2122
3900e5fd
LP
2123 socket_unwatch_control_pid(s);
2124 s->control_command_id = SOCKET_EXEC_START_POST;
2125 s->control_command = s->exec_command[SOCKET_EXEC_START_POST];
2126
2127 if (s->control_command) {
2128 r = socket_spawn(s, s->control_command, &s->control_pid);
2129 if (r < 0) {
f2341e0a 2130 log_unit_warning_errno(UNIT(s), r, "Failed to run 'start-post' task: %m");
3900e5fd
LP
2131 goto fail;
2132 }
2133
2134 socket_set_state(s, SOCKET_START_POST);
2135 } else
2136 socket_enter_listening(s);
2137
2138 return;
2139
2140fail:
2141 socket_enter_stop_pre(s, SOCKET_FAILURE_RESOURCES);
2142}
2143
2144static void socket_enter_start_chown(Socket *s) {
2145 int r;
2146
2147 assert(s);
2148
cfc4eb4c
LP
2149 r = socket_open_fds(s);
2150 if (r < 0) {
f2341e0a 2151 log_unit_warning_errno(UNIT(s), r, "Failed to listen on sockets: %m");
034c6ed7
LP
2152 goto fail;
2153 }
2154
3900e5fd 2155 if (!isempty(s->user) || !isempty(s->group)) {
5e94833f 2156
3900e5fd
LP
2157 socket_unwatch_control_pid(s);
2158 s->control_command_id = SOCKET_EXEC_START_CHOWN;
2159 s->control_command = NULL;
a16e1123 2160
3900e5fd 2161 r = socket_chown(s, &s->control_pid);
cfc4eb4c 2162 if (r < 0) {
f2341e0a 2163 log_unit_warning_errno(UNIT(s), r, "Failed to fork 'start-chown' task: %m");
034c6ed7
LP
2164 goto fail;
2165 }
2166
3900e5fd 2167 socket_set_state(s, SOCKET_START_CHOWN);
80876c20 2168 } else
3900e5fd 2169 socket_enter_start_post(s);
034c6ed7
LP
2170
2171 return;
2172
2173fail:
cfc4eb4c 2174 socket_enter_stop_pre(s, SOCKET_FAILURE_RESOURCES);
034c6ed7
LP
2175}
2176
2177static void socket_enter_start_pre(Socket *s) {
2178 int r;
2179 assert(s);
2180
5e94833f 2181 socket_unwatch_control_pid(s);
a4634b21
LP
2182
2183 unit_warn_leftover_processes(UNIT(s));
2184
a16e1123 2185 s->control_command_id = SOCKET_EXEC_START_PRE;
3900e5fd 2186 s->control_command = s->exec_command[SOCKET_EXEC_START_PRE];
a16e1123 2187
3900e5fd 2188 if (s->control_command) {
e821075a 2189 r = socket_spawn(s, s->control_command, &s->control_pid);
3900e5fd 2190 if (r < 0) {
f2341e0a 2191 log_unit_warning_errno(UNIT(s), r, "Failed to run 'start-pre' task: %m");
034c6ed7 2192 goto fail;
3900e5fd 2193 }
034c6ed7 2194
80876c20
LP
2195 socket_set_state(s, SOCKET_START_PRE);
2196 } else
3900e5fd 2197 socket_enter_start_chown(s);
034c6ed7
LP
2198
2199 return;
2200
2201fail:
cfc4eb4c 2202 socket_enter_dead(s, SOCKET_FAILURE_RESOURCES);
034c6ed7
LP
2203}
2204
60d9771c
LP
2205static void flush_ports(Socket *s) {
2206 SocketPort *p;
2207
2208 /* Flush all incoming traffic, regardless if actual bytes or new connections, so that this socket isn't busy
2209 * anymore */
2210
2211 LIST_FOREACH(port, p, s->ports) {
2212 if (p->fd < 0)
2213 continue;
2214
2215 (void) flush_accept(p->fd);
2216 (void) flush_fd(p->fd);
2217 }
2218}
2219
4f2d528d 2220static void socket_enter_running(Socket *s, int cfd) {
4afd3348 2221 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
034c6ed7
LP
2222 int r;
2223
8b26cdbd
LP
2224 /* Note that this call takes possession of the connection fd passed. It either has to assign it somewhere or
2225 * close it. */
2226
034c6ed7
LP
2227 assert(s);
2228
60d9771c 2229 /* We don't take connections anymore if we are supposed to shut down anyway */
31afa0a4 2230 if (unit_stop_pending(UNIT(s))) {
e821075a 2231
f2341e0a 2232 log_unit_debug(UNIT(s), "Suppressing connection request since unit stop is scheduled.");
5d909e3e 2233
7c610628 2234 if (cfd >= 0)
a98f7575 2235 goto refuse;
60d9771c
LP
2236 else
2237 flush_ports(s);
7c610628 2238
ba3e67a7
LP
2239 return;
2240 }
2241
7994ac1d 2242 if (!ratelimit_below(&s->trigger_limit)) {
8b26cdbd
LP
2243 log_unit_warning(UNIT(s), "Trigger limit hit, refusing further activation.");
2244 socket_enter_stop_pre(s, SOCKET_FAILURE_TRIGGER_LIMIT_HIT);
a98f7575 2245 goto refuse;
8b26cdbd
LP
2246 }
2247
4f2d528d 2248 if (cfd < 0) {
f976f3f6 2249 bool pending = false;
eef85c4a
LP
2250 Unit *other;
2251 Iterator i;
2252 void *v;
f976f3f6
LP
2253
2254 /* If there's already a start pending don't bother to
2255 * do anything */
eef85c4a 2256 HASHMAP_FOREACH_KEY(v, other, UNIT(s)->dependencies[UNIT_TRIGGERS], i)
e821075a 2257 if (unit_active_or_pending(other)) {
57020a3a
LP
2258 pending = true;
2259 break;
2260 }
f976f3f6 2261
1a710b43 2262 if (!pending) {
640ace4a 2263 if (!UNIT_ISSET(s->service)) {
f2341e0a 2264 log_unit_error(UNIT(s), "Service to activate vanished, refusing activation.");
640ace4a
LP
2265 r = -ENOENT;
2266 goto fail;
2267 }
2268
4bd29fe5 2269 r = manager_add_job(UNIT(s)->manager, JOB_START, UNIT_DEREF(s->service), JOB_REPLACE, &error, NULL);
1a710b43 2270 if (r < 0)
f976f3f6 2271 goto fail;
1a710b43 2272 }
4f2d528d
LP
2273
2274 socket_set_state(s, SOCKET_RUNNING);
2275 } else {
e55001eb 2276 _cleanup_free_ char *prefix = NULL, *instance = NULL, *name = NULL;
9d565427 2277 _cleanup_(socket_peer_unrefp) SocketPeer *p = NULL;
b15bdda8 2278 Service *service;
4f2d528d 2279
6cf6bbc2 2280 if (s->n_connections >= s->max_connections) {
ea8f50f8 2281 log_unit_warning(UNIT(s), "Too many incoming connections (%u), dropping connection.",
166cf510 2282 s->n_connections);
a98f7575 2283 goto refuse;
6cf6bbc2
LP
2284 }
2285
9d565427 2286 if (s->max_connections_per_source > 0) {
166cf510 2287 r = socket_acquire_peer(s, cfd, &p);
9d565427 2288 if (r < 0) {
a98f7575 2289 goto refuse;
166cf510 2290 } else if (r > 0 && p->n_ref > s->max_connections_per_source) {
ea8f50f8
ZJS
2291 _cleanup_free_ char *t = NULL;
2292
41733ae1 2293 (void) sockaddr_pretty(&p->peer.sa, p->peer_salen, true, false, &t);
ea8f50f8 2294
166cf510 2295 log_unit_warning(UNIT(s),
ea8f50f8
ZJS
2296 "Too many incoming connections (%u) from source %s, dropping connection.",
2297 p->n_ref, strnull(t));
a98f7575 2298 goto refuse;
9d565427
SS
2299 }
2300 }
2301
1a710b43
MS
2302 r = socket_instantiate_service(s);
2303 if (r < 0)
b15bdda8
LP
2304 goto fail;
2305
1a710b43
MS
2306 r = instance_from_socket(cfd, s->n_accepted, &instance);
2307 if (r < 0) {
2308 if (r != -ENOTCONN)
2309 goto fail;
2310
2311 /* ENOTCONN is legitimate if TCP RST was received.
2312 * This connection is over, but the socket unit lives on. */
8b26cdbd 2313 log_unit_debug(UNIT(s), "Got ENOTCONN on incoming socket, assuming aborted connection attempt, ignoring.");
a98f7575 2314 goto refuse;
1a710b43 2315 }
4f2d528d 2316
7410616c
LP
2317 r = unit_name_to_prefix(UNIT(s)->id, &prefix);
2318 if (r < 0)
4f2d528d 2319 goto fail;
4f2d528d 2320
7410616c
LP
2321 r = unit_name_build(prefix, instance, ".service", &name);
2322 if (r < 0)
b6dbbe1c 2323 goto fail;
4f2d528d 2324
1a710b43 2325 r = unit_add_name(UNIT_DEREF(s->service), name);
e55001eb 2326 if (r < 0)
4f2d528d 2327 goto fail;
b15bdda8 2328
57020a3a
LP
2329 service = SERVICE(UNIT_DEREF(s->service));
2330 unit_ref_unset(&s->service);
6c073082 2331
e4f67317 2332 s->n_accepted++;
b15bdda8 2333 unit_choose_id(UNIT(service), name);
b15bdda8 2334
16115b0a 2335 r = service_set_socket_fd(service, cfd, s, s->selinux_context_from_net);
1a710b43 2336 if (r < 0)
4f2d528d
LP
2337 goto fail;
2338
8b26cdbd 2339 cfd = -1; /* We passed ownership of the fd to the service now. Forget it here. */
313cefa1 2340 s->n_connections++;
6cf6bbc2 2341
1cc6c93a 2342 service->peer = TAKE_PTR(p); /* Pass ownership of the peer reference */
9d565427 2343
4bd29fe5 2344 r = manager_add_job(UNIT(s)->manager, JOB_START, UNIT(service), JOB_REPLACE, &error, NULL);
3e7a1f50
LP
2345 if (r < 0) {
2346 /* We failed to activate the new service, but it still exists. Let's make sure the service
2347 * closes and forgets the connection fd again, immediately. */
2348 service_close_socket_fd(service);
4f2d528d 2349 goto fail;
3e7a1f50 2350 }
c4e2ceae
LP
2351
2352 /* Notify clients about changed counters */
2353 unit_add_to_dbus_queue(UNIT(s));
4f2d528d 2354 }
034c6ed7 2355
034c6ed7
LP
2356 return;
2357
a98f7575
MM
2358refuse:
2359 s->n_refused++;
2360 safe_close(cfd);
2361 return;
2362
034c6ed7 2363fail:
f2341e0a
LP
2364 log_unit_warning(UNIT(s), "Failed to queue service startup job (Maybe the service file is missing or not a %s unit?): %s",
2365 cfd >= 0 ? "template" : "non-template",
718db961 2366 bus_error_message(&error, r));
e821075a 2367
60089004 2368 socket_enter_stop_pre(s, SOCKET_FAILURE_RESOURCES);
03e334a1 2369 safe_close(cfd);
034c6ed7
LP
2370}
2371
cfc4eb4c 2372static void socket_run_next(Socket *s) {
034c6ed7
LP
2373 int r;
2374
2375 assert(s);
2376 assert(s->control_command);
2377 assert(s->control_command->command_next);
2378
5e94833f
LP
2379 socket_unwatch_control_pid(s);
2380
034c6ed7
LP
2381 s->control_command = s->control_command->command_next;
2382
e821075a
LP
2383 r = socket_spawn(s, s->control_command, &s->control_pid);
2384 if (r < 0)
034c6ed7
LP
2385 goto fail;
2386
2387 return;
2388
2389fail:
f2341e0a 2390 log_unit_warning_errno(UNIT(s), r, "Failed to run next task: %m");
80876c20
LP
2391
2392 if (s->state == SOCKET_START_POST)
cfc4eb4c 2393 socket_enter_stop_pre(s, SOCKET_FAILURE_RESOURCES);
034c6ed7 2394 else if (s->state == SOCKET_STOP_POST)
cfc4eb4c 2395 socket_enter_dead(s, SOCKET_FAILURE_RESOURCES);
034c6ed7 2396 else
cfc4eb4c 2397 socket_enter_signal(s, SOCKET_FINAL_SIGTERM, SOCKET_FAILURE_RESOURCES);
034c6ed7
LP
2398}
2399
87f0e418
LP
2400static int socket_start(Unit *u) {
2401 Socket *s = SOCKET(u);
07299350 2402 int r;
83c60c9f
LP
2403
2404 assert(s);
2405
034c6ed7
LP
2406 /* We cannot fulfill this request right now, try again later
2407 * please! */
3900e5fd
LP
2408 if (IN_SET(s->state,
2409 SOCKET_STOP_PRE,
2410 SOCKET_STOP_PRE_SIGKILL,
2411 SOCKET_STOP_PRE_SIGTERM,
2412 SOCKET_STOP_POST,
2413 SOCKET_FINAL_SIGTERM,
2414 SOCKET_FINAL_SIGKILL))
034c6ed7
LP
2415 return -EAGAIN;
2416
a4152e3f 2417 /* Already on it! */
3900e5fd
LP
2418 if (IN_SET(s->state,
2419 SOCKET_START_PRE,
2420 SOCKET_START_CHOWN,
2421 SOCKET_START_POST))
034c6ed7 2422 return 0;
83c60c9f 2423
034c6ed7 2424 /* Cannot run this without the service being around */
9444b1f2 2425 if (UNIT_ISSET(s->service)) {
57020a3a
LP
2426 Service *service;
2427
2428 service = SERVICE(UNIT_DEREF(s->service));
2429
1124fe6f 2430 if (UNIT(service)->load_state != UNIT_LOADED) {
f2341e0a 2431 log_unit_error(u, "Socket service %s not loaded, refusing.", UNIT(service)->id);
4f2d528d 2432 return -ENOENT;
4ac9236f 2433 }
4f2d528d 2434
35b8ca3a 2435 /* If the service is already active we cannot start the
4f2d528d 2436 * socket */
ec2ce0c5 2437 if (!IN_SET(service->state, SERVICE_DEAD, SERVICE_FAILED, SERVICE_AUTO_RESTART)) {
f2341e0a 2438 log_unit_error(u, "Socket service %s already active, refusing.", UNIT(service)->id);
4f2d528d 2439 return -EBUSY;
4ac9236f 2440 }
4f2d528d 2441 }
e537352b 2442
3742095b 2443 assert(IN_SET(s->state, SOCKET_DEAD, SOCKET_FAILED));
83c60c9f 2444
07299350
LP
2445 r = unit_start_limit_test(u);
2446 if (r < 0) {
2447 socket_enter_dead(s, SOCKET_FAILURE_START_LIMIT_HIT);
2448 return r;
2449 }
2450
4b58153d
LP
2451 r = unit_acquire_invocation_id(u);
2452 if (r < 0)
2453 return r;
2454
cfc4eb4c 2455 s->result = SOCKET_SUCCESS;
6a1d4d9f 2456 exec_command_reset_status_list_array(s->exec_command, _SOCKET_EXEC_COMMAND_MAX);
3c7416b6
LP
2457
2458 u->reset_accounting = true;
5ad096b3 2459
034c6ed7 2460 socket_enter_start_pre(s);
82a2b6bb 2461 return 1;
034c6ed7 2462}
83c60c9f 2463
87f0e418
LP
2464static int socket_stop(Unit *u) {
2465 Socket *s = SOCKET(u);
034c6ed7
LP
2466
2467 assert(s);
2468
e537352b 2469 /* Already on it */
3900e5fd
LP
2470 if (IN_SET(s->state,
2471 SOCKET_STOP_PRE,
2472 SOCKET_STOP_PRE_SIGTERM,
2473 SOCKET_STOP_PRE_SIGKILL,
2474 SOCKET_STOP_POST,
2475 SOCKET_FINAL_SIGTERM,
2476 SOCKET_FINAL_SIGKILL))
e537352b
LP
2477 return 0;
2478
3f6c78dc
LP
2479 /* If there's already something running we go directly into
2480 * kill mode. */
3900e5fd
LP
2481 if (IN_SET(s->state,
2482 SOCKET_START_PRE,
2483 SOCKET_START_CHOWN,
2484 SOCKET_START_POST)) {
cfc4eb4c 2485 socket_enter_signal(s, SOCKET_STOP_PRE_SIGTERM, SOCKET_SUCCESS);
3f6c78dc
LP
2486 return -EAGAIN;
2487 }
2488
3742095b 2489 assert(IN_SET(s->state, SOCKET_LISTENING, SOCKET_RUNNING));
83c60c9f 2490
cfc4eb4c 2491 socket_enter_stop_pre(s, SOCKET_SUCCESS);
82a2b6bb 2492 return 1;
542563ba
LP
2493}
2494
a16e1123
LP
2495static int socket_serialize(Unit *u, FILE *f, FDSet *fds) {
2496 Socket *s = SOCKET(u);
2497 SocketPort *p;
2498 int r;
2499
2500 assert(u);
2501 assert(f);
2502 assert(fds);
2503
d68c645b
LP
2504 (void) serialize_item(f, "state", socket_state_to_string(s->state));
2505 (void) serialize_item(f, "result", socket_result_to_string(s->result));
2506 (void) serialize_item_format(f, "n-accepted", "%u", s->n_accepted);
2507 (void) serialize_item_format(f, "n-refused", "%u", s->n_refused);
a16e1123
LP
2508
2509 if (s->control_pid > 0)
d68c645b 2510 (void) serialize_item_format(f, "control-pid", PID_FMT, s->control_pid);
a16e1123
LP
2511
2512 if (s->control_command_id >= 0)
d68c645b 2513 (void) serialize_item(f, "control-command", socket_exec_command_to_string(s->control_command_id));
a16e1123
LP
2514
2515 LIST_FOREACH(port, p, s->ports) {
2516 int copy;
2517
2518 if (p->fd < 0)
2519 continue;
2520
613b411c
LP
2521 copy = fdset_put_dup(fds, p->fd);
2522 if (copy < 0)
fc2d74ab 2523 return log_unit_warning_errno(u, copy, "Failed to serialize socket fd: %m");
a16e1123
LP
2524
2525 if (p->type == SOCKET_SOCKET) {
613b411c 2526 _cleanup_free_ char *t = NULL;
a16e1123 2527
ee092817
LP
2528 r = socket_address_print(&p->address, &t);
2529 if (r < 0)
fc2d74ab 2530 return log_unit_error_errno(u, r, "Failed to format socket address: %m");
a16e1123 2531
7a22745a 2532 if (socket_address_family(&p->address) == AF_NETLINK)
d68c645b 2533 (void) serialize_item_format(f, "netlink", "%i %s", copy, t);
7a22745a 2534 else
d68c645b 2535 (void) serialize_item_format(f, "socket", "%i %i %s", copy, p->address.type, t);
b0a3f2bc 2536 } else if (p->type == SOCKET_SPECIAL)
d68c645b 2537 (void) serialize_item_format(f, "special", "%i %s", copy, p->path);
ee092817 2538 else if (p->type == SOCKET_MQUEUE)
d68c645b 2539 (void) serialize_item_format(f, "mqueue", "%i %s", copy, p->path);
60252446 2540 else if (p->type == SOCKET_USB_FUNCTION)
d68c645b 2541 (void) serialize_item_format(f, "ffs", "%i %s", copy, p->path);
b0a3f2bc 2542 else {
a16e1123 2543 assert(p->type == SOCKET_FIFO);
d68c645b 2544 (void) serialize_item_format(f, "fifo", "%i %s", copy, p->path);
a16e1123
LP
2545 }
2546 }
2547
2548 return 0;
2549}
2550
80a58668 2551static void socket_port_take_fd(SocketPort *p, FDSet *fds, int fd) {
d68c645b
LP
2552 assert(p);
2553
80a58668
ZJS
2554 safe_close(p->fd);
2555 p->fd = fdset_remove(fds, fd);
2556}
2557
a16e1123
LP
2558static int socket_deserialize_item(Unit *u, const char *key, const char *value, FDSet *fds) {
2559 Socket *s = SOCKET(u);
a16e1123
LP
2560
2561 assert(u);
2562 assert(key);
2563 assert(value);
a16e1123
LP
2564
2565 if (streq(key, "state")) {
2566 SocketState state;
2567
ee092817
LP
2568 state = socket_state_from_string(value);
2569 if (state < 0)
f2341e0a 2570 log_unit_debug(u, "Failed to parse state value: %s", value);
a16e1123
LP
2571 else
2572 s->deserialized_state = state;
cfc4eb4c
LP
2573 } else if (streq(key, "result")) {
2574 SocketResult f;
a16e1123 2575
cfc4eb4c
LP
2576 f = socket_result_from_string(value);
2577 if (f < 0)
f2341e0a 2578 log_unit_debug(u, "Failed to parse result value: %s", value);
cfc4eb4c
LP
2579 else if (f != SOCKET_SUCCESS)
2580 s->result = f;
a16e1123
LP
2581
2582 } else if (streq(key, "n-accepted")) {
2583 unsigned k;
2584
e364ad06 2585 if (safe_atou(value, &k) < 0)
f2341e0a 2586 log_unit_debug(u, "Failed to parse n-accepted value: %s", value);
a16e1123
LP
2587 else
2588 s->n_accepted += k;
a98f7575
MM
2589 } else if (streq(key, "n-refused")) {
2590 unsigned k;
2591
2592 if (safe_atou(value, &k) < 0)
2593 log_unit_debug(u, "Failed to parse n-refused value: %s", value);
2594 else
2595 s->n_refused += k;
a16e1123 2596 } else if (streq(key, "control-pid")) {
5925dd3c 2597 pid_t pid;
a16e1123 2598
e364ad06 2599 if (parse_pid(value, &pid) < 0)
f2341e0a 2600 log_unit_debug(u, "Failed to parse control-pid value: %s", value);
a16e1123 2601 else
5925dd3c 2602 s->control_pid = pid;
a16e1123
LP
2603 } else if (streq(key, "control-command")) {
2604 SocketExecCommand id;
2605
66870f90
ZJS
2606 id = socket_exec_command_from_string(value);
2607 if (id < 0)
f2341e0a 2608 log_unit_debug(u, "Failed to parse exec-command value: %s", value);
a16e1123
LP
2609 else {
2610 s->control_command_id = id;
2611 s->control_command = s->exec_command[id];
2612 }
2613 } else if (streq(key, "fifo")) {
2614 int fd, skip = 0;
2615 SocketPort *p;
2616
2617 if (sscanf(value, "%i %n", &fd, &skip) < 1 || fd < 0 || !fdset_contains(fds, fd))
f2341e0a 2618 log_unit_debug(u, "Failed to parse fifo value: %s", value);
80a58668 2619 else
a16e1123 2620 LIST_FOREACH(port, p, s->ports)
b0a3f2bc 2621 if (p->type == SOCKET_FIFO &&
e3f791a2 2622 path_equal_or_files_same(p->path, value+skip, 0)) {
80a58668 2623 socket_port_take_fd(p, fds, fd);
b0a3f2bc 2624 break;
80a58668 2625 }
b0a3f2bc
LP
2626
2627 } else if (streq(key, "special")) {
2628 int fd, skip = 0;
2629 SocketPort *p;
2630
2631 if (sscanf(value, "%i %n", &fd, &skip) < 1 || fd < 0 || !fdset_contains(fds, fd))
f2341e0a 2632 log_unit_debug(u, "Failed to parse special value: %s", value);
80a58668 2633 else
b0a3f2bc
LP
2634 LIST_FOREACH(port, p, s->ports)
2635 if (p->type == SOCKET_SPECIAL &&
e3f791a2 2636 path_equal_or_files_same(p->path, value+skip, 0)) {
80a58668 2637 socket_port_take_fd(p, fds, fd);
a16e1123 2638 break;
80a58668 2639 }
a16e1123 2640
ee092817
LP
2641 } else if (streq(key, "mqueue")) {
2642 int fd, skip = 0;
2643 SocketPort *p;
2644
2645 if (sscanf(value, "%i %n", &fd, &skip) < 1 || fd < 0 || !fdset_contains(fds, fd))
f2341e0a 2646 log_unit_debug(u, "Failed to parse mqueue value: %s", value);
80a58668 2647 else
ee092817
LP
2648 LIST_FOREACH(port, p, s->ports)
2649 if (p->type == SOCKET_MQUEUE &&
80a58668
ZJS
2650 streq(p->path, value+skip)) {
2651 socket_port_take_fd(p, fds, fd);
ee092817 2652 break;
80a58668 2653 }
ee092817 2654
a16e1123 2655 } else if (streq(key, "socket")) {
27ca8d7a 2656 int fd, type, skip = 0;
a16e1123
LP
2657 SocketPort *p;
2658
27ca8d7a 2659 if (sscanf(value, "%i %i %n", &fd, &type, &skip) < 2 || fd < 0 || type < 0 || !fdset_contains(fds, fd))
f2341e0a 2660 log_unit_debug(u, "Failed to parse socket value: %s", value);
80a58668 2661 else
a16e1123 2662 LIST_FOREACH(port, p, s->ports)
80a58668
ZJS
2663 if (socket_address_is(&p->address, value+skip, type)) {
2664 socket_port_take_fd(p, fds, fd);
a16e1123 2665 break;
80a58668 2666 }
a16e1123 2667
7a22745a
LP
2668 } else if (streq(key, "netlink")) {
2669 int fd, skip = 0;
2670 SocketPort *p;
2671
2672 if (sscanf(value, "%i %n", &fd, &skip) < 1 || fd < 0 || !fdset_contains(fds, fd))
f2341e0a 2673 log_unit_debug(u, "Failed to parse socket value: %s", value);
80a58668 2674 else
7a22745a 2675 LIST_FOREACH(port, p, s->ports)
80a58668
ZJS
2676 if (socket_address_is_netlink(&p->address, value+skip)) {
2677 socket_port_take_fd(p, fds, fd);
7a22745a 2678 break;
80a58668 2679 }
60252446
PS
2680
2681 } else if (streq(key, "ffs")) {
2682 int fd, skip = 0;
2683 SocketPort *p;
2684
2685 if (sscanf(value, "%i %n", &fd, &skip) < 1 || fd < 0 || !fdset_contains(fds, fd))
2686 log_unit_debug(u, "Failed to parse ffs value: %s", value);
80a58668 2687 else
60252446
PS
2688 LIST_FOREACH(port, p, s->ports)
2689 if (p->type == SOCKET_USB_FUNCTION &&
e3f791a2 2690 path_equal_or_files_same(p->path, value+skip, 0)) {
80a58668 2691 socket_port_take_fd(p, fds, fd);
60252446 2692 break;
80a58668 2693 }
60252446 2694
a16e1123 2695 } else
f2341e0a 2696 log_unit_debug(UNIT(s), "Unknown serialization key: %s", key);
a16e1123
LP
2697
2698 return 0;
2699}
2700
9ff1a6f1 2701static void socket_distribute_fds(Unit *u, FDSet *fds) {
01e10de3
LP
2702 Socket *s = SOCKET(u);
2703 SocketPort *p;
2704
2705 assert(u);
2706
2707 LIST_FOREACH(port, p, s->ports) {
2708 Iterator i;
2709 int fd;
2710
2711 if (p->type != SOCKET_SOCKET)
2712 continue;
2713
2714 if (p->fd >= 0)
2715 continue;
2716
2717 FDSET_FOREACH(fd, fds, i) {
2718 if (socket_address_matches_fd(&p->address, fd)) {
2719 p->fd = fdset_remove(fds, fd);
2720 s->deserialized_state = SOCKET_LISTENING;
2721 break;
2722 }
2723 }
2724 }
01e10de3
LP
2725}
2726
44a6b1b6 2727_pure_ static UnitActiveState socket_active_state(Unit *u) {
87f0e418 2728 assert(u);
5cb5a6ff 2729
acbb0225 2730 return state_translation_table[SOCKET(u)->state];
5cb5a6ff
LP
2731}
2732
44a6b1b6 2733_pure_ static const char *socket_sub_state_to_string(Unit *u) {
10a94420
LP
2734 assert(u);
2735
a16e1123 2736 return socket_state_to_string(SOCKET(u)->state);
10a94420
LP
2737}
2738
67419600
OS
2739const char* socket_port_type_to_string(SocketPort *p) {
2740
2741 assert(p);
2742
2743 switch (p->type) {
718db961
LP
2744
2745 case SOCKET_SOCKET:
2746
2747 switch (p->address.type) {
2748
2749 case SOCK_STREAM:
2750 return "Stream";
2751
2752 case SOCK_DGRAM:
2753 return "Datagram";
2754
2755 case SOCK_SEQPACKET:
2756 return "SequentialPacket";
2757
2758 case SOCK_RAW:
2759 if (socket_address_family(&p->address) == AF_NETLINK)
2760 return "Netlink";
2761
4831981d 2762 _fallthrough_;
718db961
LP
2763 default:
2764 return NULL;
2765 }
2766
2767 case SOCKET_SPECIAL:
2768 return "Special";
2769
2770 case SOCKET_MQUEUE:
2771 return "MessageQueue";
2772
2773 case SOCKET_FIFO:
2774 return "FIFO";
2775
60252446
PS
2776 case SOCKET_USB_FUNCTION:
2777 return "USBFunction";
2778
718db961
LP
2779 default:
2780 return NULL;
67419600
OS
2781 }
2782}
2783
038ed5a4
YW
2784SocketType socket_port_type_from_string(const char *s) {
2785 assert(s);
2786
e045e325
YW
2787 if (STR_IN_SET(s, "Stream", "Datagram", "SequentialPacket", "Netlink"))
2788 return SOCKET_SOCKET;
2789 else if (streq(s, "Special"))
2790 return SOCKET_SPECIAL;
2791 else if (streq(s, "MessageQueue"))
2792 return SOCKET_MQUEUE;
2793 else if (streq(s, "FIFO"))
2794 return SOCKET_FIFO;
2795 else if (streq(s, "USBFunction"))
2796 return SOCKET_USB_FUNCTION;
038ed5a4
YW
2797 else
2798 return _SOCKET_TYPE_INVALID;
2799}
2800
f2f725e5 2801_pure_ static bool socket_may_gc(Unit *u) {
6cf6bbc2
LP
2802 Socket *s = SOCKET(u);
2803
2804 assert(u);
2805
f2f725e5 2806 return s->n_connections == 0;
6cf6bbc2
LP
2807}
2808
a79279c7
LP
2809static int socket_accept_do(Socket *s, int fd) {
2810 int cfd;
2811
2812 assert(s);
2813 assert(fd >= 0);
2814
2815 for (;;) {
2816 cfd = accept4(fd, NULL, NULL, SOCK_NONBLOCK);
2817 if (cfd < 0) {
2818 if (errno == EINTR)
2819 continue;
2820
2821 return -errno;
2822 }
2823
2824 break;
2825 }
2826
2827 return cfd;
2828}
2829
2830static int socket_accept_in_cgroup(Socket *s, SocketPort *p, int fd) {
2831 _cleanup_close_pair_ int pair[2] = { -1, -1 };
2832 int cfd, r;
2833 pid_t pid;
2834
2835 assert(s);
2836 assert(p);
2837 assert(fd >= 0);
2838
2839 /* Similar to socket_address_listen_in_cgroup(), but for accept() rathern than socket(): make sure that any
2840 * connection socket is also properly associated with the cgroup. */
2841
2842 if (!IN_SET(p->address.sockaddr.sa.sa_family, AF_INET, AF_INET6))
2843 goto shortcut;
2844
2845 r = bpf_firewall_supported();
2846 if (r < 0)
2847 return r;
2ae7ee58 2848 if (r == BPF_FIREWALL_UNSUPPORTED)
a79279c7
LP
2849 goto shortcut;
2850
2851 if (socketpair(AF_UNIX, SOCK_SEQPACKET|SOCK_CLOEXEC, 0, pair) < 0)
2852 return log_unit_error_errno(UNIT(s), errno, "Failed to create communication channel: %m");
2853
4c253ed1 2854 r = unit_fork_helper_process(UNIT(s), "(sd-accept)", &pid);
a79279c7
LP
2855 if (r < 0)
2856 return log_unit_error_errno(UNIT(s), r, "Failed to fork off accept stub process: %m");
2857 if (r == 0) {
2858 /* Child */
2859
2860 pair[0] = safe_close(pair[0]);
2861
2862 cfd = socket_accept_do(s, fd);
2863 if (cfd < 0) {
2864 log_unit_error_errno(UNIT(s), cfd, "Failed to accept connection socket: %m");
2865 _exit(EXIT_FAILURE);
2866 }
2867
2868 r = send_one_fd(pair[1], cfd, 0);
2869 if (r < 0) {
2870 log_unit_error_errno(UNIT(s), r, "Failed to send connection socket to parent: %m");
2871 _exit(EXIT_FAILURE);
2872 }
2873
2874 _exit(EXIT_SUCCESS);
2875 }
2876
2877 pair[1] = safe_close(pair[1]);
2878 cfd = receive_one_fd(pair[0], 0);
2879
2880 /* We synchronously wait for the helper, as it shouldn't be slow */
d2e0ac3d 2881 r = wait_for_terminate_and_check("(sd-accept)", pid, WAIT_LOG_ABNORMAL);
a79279c7
LP
2882 if (r < 0) {
2883 safe_close(cfd);
2884 return r;
2885 }
2886
2887 if (cfd < 0)
2888 return log_unit_error_errno(UNIT(s), cfd, "Failed to receive connection socket: %m");
2889
2890 return cfd;
2891
2892shortcut:
2893 cfd = socket_accept_do(s, fd);
2894 if (cfd < 0)
2895 return log_unit_error_errno(UNIT(s), cfd, "Failed to accept connection socket: %m");
2896
2897 return cfd;
2898}
2899
718db961
LP
2900static int socket_dispatch_io(sd_event_source *source, int fd, uint32_t revents, void *userdata) {
2901 SocketPort *p = userdata;
4f2d528d 2902 int cfd = -1;
9152c765 2903
718db961 2904 assert(p);
8d567588 2905 assert(fd >= 0);
9152c765 2906
718db961
LP
2907 if (p->socket->state != SOCKET_LISTENING)
2908 return 0;
871d7de4 2909
f2341e0a 2910 log_unit_debug(UNIT(p->socket), "Incoming traffic");
9152c765 2911
718db961 2912 if (revents != EPOLLIN) {
641e01dc 2913
718db961 2914 if (revents & EPOLLHUP)
f2341e0a 2915 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 2916 else
f2341e0a 2917 log_unit_error(UNIT(p->socket), "Got unexpected poll event (0x%x) on socket.", revents);
8d567588 2918 goto fail;
4f2d528d
LP
2919 }
2920
718db961
LP
2921 if (p->socket->accept &&
2922 p->type == SOCKET_SOCKET &&
2923 socket_address_can_accept(&p->address)) {
2924
a79279c7
LP
2925 cfd = socket_accept_in_cgroup(p->socket, p, fd);
2926 if (cfd < 0)
2927 goto fail;
4fd5948e 2928
718db961 2929 socket_apply_socket_options(p->socket, cfd);
4f2d528d 2930 }
9152c765 2931
718db961
LP
2932 socket_enter_running(p->socket, cfd);
2933 return 0;
8d567588
LP
2934
2935fail:
718db961
LP
2936 socket_enter_stop_pre(p->socket, SOCKET_FAILURE_RESOURCES);
2937 return 0;
9152c765
LP
2938}
2939
87f0e418
LP
2940static void socket_sigchld_event(Unit *u, pid_t pid, int code, int status) {
2941 Socket *s = SOCKET(u);
cfc4eb4c 2942 SocketResult f;
5cb5a6ff
LP
2943
2944 assert(s);
034c6ed7 2945 assert(pid >= 0);
5cb5a6ff 2946
8c47c732
LP
2947 if (pid != s->control_pid)
2948 return;
542563ba 2949
034c6ed7
LP
2950 s->control_pid = 0;
2951
1f0958f6 2952 if (is_clean_exit(code, status, EXIT_CLEAN_COMMAND, NULL))
cfc4eb4c
LP
2953 f = SOCKET_SUCCESS;
2954 else if (code == CLD_EXITED)
2955 f = SOCKET_FAILURE_EXIT_CODE;
2956 else if (code == CLD_KILLED)
2957 f = SOCKET_FAILURE_SIGNAL;
2958 else if (code == CLD_DUMPED)
2959 f = SOCKET_FAILURE_CORE_DUMP;
2960 else
a4152e3f 2961 assert_not_reached("Unknown sigchld code");
8c47c732 2962
b708e7ce 2963 if (s->control_command) {
6ea832a2 2964 exec_status_exit(&s->control_command->exec_status, &s->exec_context, pid, code, status);
a16e1123 2965
3ed0cd26 2966 if (s->control_command->flags & EXEC_COMMAND_IGNORE_FAILURE)
cfc4eb4c 2967 f = SOCKET_SUCCESS;
b708e7ce
LP
2968 }
2969
91bbd9b7
LP
2970 unit_log_process_exit(
2971 u, f == SOCKET_SUCCESS ? LOG_DEBUG : LOG_NOTICE,
2972 "Control process",
2973 socket_exec_command_to_string(s->control_command_id),
2974 code, status);
034c6ed7 2975
a0fef983 2976 if (s->result == SOCKET_SUCCESS)
cfc4eb4c
LP
2977 s->result = f;
2978
2979 if (s->control_command &&
2980 s->control_command->command_next &&
2981 f == SOCKET_SUCCESS) {
2982
f2341e0a 2983 log_unit_debug(u, "Running next command for state %s", socket_state_to_string(s->state));
cfc4eb4c 2984 socket_run_next(s);
acbb0225 2985 } else {
a16e1123
LP
2986 s->control_command = NULL;
2987 s->control_command_id = _SOCKET_EXEC_COMMAND_INVALID;
2988
034c6ed7
LP
2989 /* No further commands for this step, so let's figure
2990 * out what to do next */
5cb5a6ff 2991
f2341e0a 2992 log_unit_debug(u, "Got final SIGCHLD for state %s", socket_state_to_string(s->state));
acbb0225 2993
034c6ed7
LP
2994 switch (s->state) {
2995
2996 case SOCKET_START_PRE:
cfc4eb4c 2997 if (f == SOCKET_SUCCESS)
3900e5fd 2998 socket_enter_start_chown(s);
034c6ed7 2999 else
cfc4eb4c 3000 socket_enter_signal(s, SOCKET_FINAL_SIGTERM, f);
034c6ed7
LP
3001 break;
3002
3900e5fd
LP
3003 case SOCKET_START_CHOWN:
3004 if (f == SOCKET_SUCCESS)
3005 socket_enter_start_post(s);
3006 else
3007 socket_enter_stop_pre(s, f);
3008 break;
3009
034c6ed7 3010 case SOCKET_START_POST:
cfc4eb4c 3011 if (f == SOCKET_SUCCESS)
e9af15c3 3012 socket_enter_listening(s);
034c6ed7 3013 else
cfc4eb4c 3014 socket_enter_stop_pre(s, f);
034c6ed7
LP
3015 break;
3016
3017 case SOCKET_STOP_PRE:
3018 case SOCKET_STOP_PRE_SIGTERM:
3019 case SOCKET_STOP_PRE_SIGKILL:
cfc4eb4c 3020 socket_enter_stop_post(s, f);
034c6ed7
LP
3021 break;
3022
3023 case SOCKET_STOP_POST:
80876c20
LP
3024 case SOCKET_FINAL_SIGTERM:
3025 case SOCKET_FINAL_SIGKILL:
cfc4eb4c 3026 socket_enter_dead(s, f);
034c6ed7
LP
3027 break;
3028
3029 default:
3030 assert_not_reached("Uh, control process died at wrong time.");
3031 }
3032 }
c4e2ceae
LP
3033
3034 /* Notify clients about changed exit status */
3035 unit_add_to_dbus_queue(u);
034c6ed7 3036}
5cb5a6ff 3037
718db961
LP
3038static int socket_dispatch_timer(sd_event_source *source, usec_t usec, void *userdata) {
3039 Socket *s = SOCKET(userdata);
5cb5a6ff 3040
034c6ed7 3041 assert(s);
718db961 3042 assert(s->timer_event_source == source);
034c6ed7
LP
3043
3044 switch (s->state) {
3045
3046 case SOCKET_START_PRE:
f2341e0a 3047 log_unit_warning(UNIT(s), "Starting timed out. Terminating.");
cfc4eb4c 3048 socket_enter_signal(s, SOCKET_FINAL_SIGTERM, SOCKET_FAILURE_TIMEOUT);
da19d5c1 3049 break;
80876c20 3050
3900e5fd 3051 case SOCKET_START_CHOWN:
034c6ed7 3052 case SOCKET_START_POST:
f2341e0a 3053 log_unit_warning(UNIT(s), "Starting timed out. Stopping.");
cfc4eb4c 3054 socket_enter_stop_pre(s, SOCKET_FAILURE_TIMEOUT);
034c6ed7
LP
3055 break;
3056
3057 case SOCKET_STOP_PRE:
f2341e0a 3058 log_unit_warning(UNIT(s), "Stopping timed out. Terminating.");
cfc4eb4c 3059 socket_enter_signal(s, SOCKET_STOP_PRE_SIGTERM, SOCKET_FAILURE_TIMEOUT);
034c6ed7
LP
3060 break;
3061
3062 case SOCKET_STOP_PRE_SIGTERM:
4819ff03 3063 if (s->kill_context.send_sigkill) {
f2341e0a 3064 log_unit_warning(UNIT(s), "Stopping timed out. Killing.");
cfc4eb4c 3065 socket_enter_signal(s, SOCKET_STOP_PRE_SIGKILL, SOCKET_FAILURE_TIMEOUT);
ba035df2 3066 } else {
f2341e0a 3067 log_unit_warning(UNIT(s), "Stopping timed out. Skipping SIGKILL. Ignoring.");
cfc4eb4c 3068 socket_enter_stop_post(s, SOCKET_FAILURE_TIMEOUT);
ba035df2 3069 }
034c6ed7
LP
3070 break;
3071
3072 case SOCKET_STOP_PRE_SIGKILL:
f2341e0a 3073 log_unit_warning(UNIT(s), "Processes still around after SIGKILL. Ignoring.");
cfc4eb4c 3074 socket_enter_stop_post(s, SOCKET_FAILURE_TIMEOUT);
034c6ed7
LP
3075 break;
3076
3077 case SOCKET_STOP_POST:
f2341e0a 3078 log_unit_warning(UNIT(s), "Stopping timed out (2). Terminating.");
cfc4eb4c 3079 socket_enter_signal(s, SOCKET_FINAL_SIGTERM, SOCKET_FAILURE_TIMEOUT);
034c6ed7
LP
3080 break;
3081
80876c20 3082 case SOCKET_FINAL_SIGTERM:
4819ff03 3083 if (s->kill_context.send_sigkill) {
f2341e0a 3084 log_unit_warning(UNIT(s), "Stopping timed out (2). Killing.");
cfc4eb4c 3085 socket_enter_signal(s, SOCKET_FINAL_SIGKILL, SOCKET_FAILURE_TIMEOUT);
ba035df2 3086 } else {
f2341e0a 3087 log_unit_warning(UNIT(s), "Stopping timed out (2). Skipping SIGKILL. Ignoring.");
cfc4eb4c 3088 socket_enter_dead(s, SOCKET_FAILURE_TIMEOUT);
ba035df2 3089 }
034c6ed7
LP
3090 break;
3091
80876c20 3092 case SOCKET_FINAL_SIGKILL:
f2341e0a 3093 log_unit_warning(UNIT(s), "Still around after SIGKILL (2). Entering failed mode.");
cfc4eb4c 3094 socket_enter_dead(s, SOCKET_FAILURE_TIMEOUT);
034c6ed7
LP
3095 break;
3096
3097 default:
3098 assert_not_reached("Timeout at wrong time.");
3099 }
718db961
LP
3100
3101 return 0;
5cb5a6ff
LP
3102}
3103
79c7626d 3104int socket_collect_fds(Socket *s, int **fds) {
da6053d0 3105 size_t k = 0, n = 0;
44d8db9e 3106 SocketPort *p;
da6053d0 3107 int *rfds;
44d8db9e
LP
3108
3109 assert(s);
3110 assert(fds);
44d8db9e
LP
3111
3112 /* Called from the service code for requesting our fds */
3113
15087cdb 3114 LIST_FOREACH(port, p, s->ports) {
44d8db9e 3115 if (p->fd >= 0)
79c7626d
LP
3116 n++;
3117 n += p->n_auxiliary_fds;
15087cdb 3118 }
44d8db9e 3119
79c7626d 3120 if (n <= 0) {
de3756ab 3121 *fds = NULL;
de3756ab
LP
3122 return 0;
3123 }
3124
79c7626d 3125 rfds = new(int, n);
e5403f09 3126 if (!rfds)
44d8db9e
LP
3127 return -ENOMEM;
3128
15087cdb 3129 LIST_FOREACH(port, p, s->ports) {
da6053d0 3130 size_t i;
79c7626d 3131
44d8db9e
LP
3132 if (p->fd >= 0)
3133 rfds[k++] = p->fd;
15087cdb
PS
3134 for (i = 0; i < p->n_auxiliary_fds; ++i)
3135 rfds[k++] = p->auxiliary_fds[i];
3136 }
44d8db9e 3137
79c7626d 3138 assert(k == n);
44d8db9e
LP
3139
3140 *fds = rfds;
da6053d0 3141 return (int) n;
44d8db9e
LP
3142}
3143
e821075a
LP
3144static void socket_reset_failed(Unit *u) {
3145 Socket *s = SOCKET(u);
3146
3147 assert(s);
3148
3149 if (s->state == SOCKET_FAILED)
3150 socket_set_state(s, SOCKET_DEAD);
3151
3152 s->result = SOCKET_SUCCESS;
3153}
3154
6cf6bbc2
LP
3155void socket_connection_unref(Socket *s) {
3156 assert(s);
3157
3158 /* The service is dead. Yay!
3159 *
35b8ca3a 3160 * This is strictly for one-instance-per-connection
6cf6bbc2
LP
3161 * services. */
3162
3163 assert(s->n_connections > 0);
3164 s->n_connections--;
3165
f2341e0a 3166 log_unit_debug(UNIT(s), "One connection closed, %u left.", s->n_connections);
5632e374
LP
3167}
3168
d137a488
UTL
3169static void socket_trigger_notify(Unit *u, Unit *other) {
3170 Socket *s = SOCKET(u);
d137a488
UTL
3171
3172 assert(u);
3173 assert(other);
3174
d14e3a0d
LP
3175 /* Filter out invocations with bogus state */
3176 if (other->load_state != UNIT_LOADED || other->type != UNIT_SERVICE)
3177 return;
3178
3179 /* Don't propagate state changes from the service if we are already down */
3180 if (!IN_SET(s->state, SOCKET_RUNNING, SOCKET_LISTENING))
d137a488
UTL
3181 return;
3182
d14e3a0d
LP
3183 /* We don't care for the service state if we are in Accept=yes mode */
3184 if (s->accept)
3185 return;
3186
3187 /* Propagate start limit hit state */
6bf0f408
LP
3188 if (other->start_limit_hit) {
3189 socket_enter_stop_pre(s, SOCKET_FAILURE_SERVICE_START_LIMIT_HIT);
d137a488 3190 return;
6bf0f408 3191 }
d137a488 3192
d14e3a0d
LP
3193 /* Don't propagate anything if there's still a job queued */
3194 if (other->job)
6bf0f408 3195 return;
d137a488 3196
6bf0f408
LP
3197 if (IN_SET(SERVICE(other)->state,
3198 SERVICE_DEAD, SERVICE_FAILED,
3199 SERVICE_FINAL_SIGTERM, SERVICE_FINAL_SIGKILL,
3200 SERVICE_AUTO_RESTART))
3201 socket_enter_listening(s);
d137a488 3202
6bf0f408 3203 if (SERVICE(other)->state == SERVICE_RUNNING)
d137a488
UTL
3204 socket_set_state(s, SOCKET_RUNNING);
3205}
3206
718db961 3207static int socket_kill(Unit *u, KillWho who, int signo, sd_bus_error *error) {
814cc562 3208 return unit_kill_common(u, who, signo, -1, SOCKET(u)->control_pid, error);
8a0867d6
LP
3209}
3210
7a7821c8 3211static int socket_get_timeout(Unit *u, usec_t *timeout) {
68db7a3b 3212 Socket *s = SOCKET(u);
7a7821c8 3213 usec_t t;
68db7a3b
ZJS
3214 int r;
3215
3216 if (!s->timer_event_source)
3217 return 0;
3218
7a7821c8 3219 r = sd_event_source_get_time(s->timer_event_source, &t);
68db7a3b
ZJS
3220 if (r < 0)
3221 return r;
7a7821c8
LP
3222 if (t == USEC_INFINITY)
3223 return 0;
68db7a3b 3224
7a7821c8 3225 *timeout = t;
68db7a3b
ZJS
3226 return 1;
3227}
3228
8dd4c05b
LP
3229char *socket_fdname(Socket *s) {
3230 assert(s);
3231
3232 /* Returns the name to use for $LISTEN_NAMES. If the user
3233 * didn't specify anything specifically, use the socket unit's
3234 * name as fallback. */
3235
84500122 3236 return s->fdname ?: UNIT(s)->id;
8dd4c05b
LP
3237}
3238
291d565a
LP
3239static int socket_control_pid(Unit *u) {
3240 Socket *s = SOCKET(u);
3241
3242 assert(s);
3243
3244 return s->control_pid;
3245}
3246
a16e1123 3247static const char* const socket_exec_command_table[_SOCKET_EXEC_COMMAND_MAX] = {
836bb1cd
YW
3248 [SOCKET_EXEC_START_PRE] = "ExecStartPre",
3249 [SOCKET_EXEC_START_CHOWN] = "ExecStartChown",
3250 [SOCKET_EXEC_START_POST] = "ExecStartPost",
3251 [SOCKET_EXEC_STOP_PRE] = "ExecStopPre",
3252 [SOCKET_EXEC_STOP_POST] = "ExecStopPost"
a16e1123
LP
3253};
3254
3255DEFINE_STRING_TABLE_LOOKUP(socket_exec_command, SocketExecCommand);
3256
cfc4eb4c
LP
3257static const char* const socket_result_table[_SOCKET_RESULT_MAX] = {
3258 [SOCKET_SUCCESS] = "success",
3259 [SOCKET_FAILURE_RESOURCES] = "resources",
3260 [SOCKET_FAILURE_TIMEOUT] = "timeout",
3261 [SOCKET_FAILURE_EXIT_CODE] = "exit-code",
3262 [SOCKET_FAILURE_SIGNAL] = "signal",
c2f34808 3263 [SOCKET_FAILURE_CORE_DUMP] = "core-dump",
07299350 3264 [SOCKET_FAILURE_START_LIMIT_HIT] = "start-limit-hit",
8b26cdbd 3265 [SOCKET_FAILURE_TRIGGER_LIMIT_HIT] = "trigger-limit-hit",
6bf0f408 3266 [SOCKET_FAILURE_SERVICE_START_LIMIT_HIT] = "service-start-limit-hit"
cfc4eb4c
LP
3267};
3268
3269DEFINE_STRING_TABLE_LOOKUP(socket_result, SocketResult);
3270
87f0e418 3271const UnitVTable socket_vtable = {
7d17cfbc 3272 .object_size = sizeof(Socket),
718db961
LP
3273 .exec_context_offset = offsetof(Socket, exec_context),
3274 .cgroup_context_offset = offsetof(Socket, cgroup_context),
3275 .kill_context_offset = offsetof(Socket, kill_context),
613b411c 3276 .exec_runtime_offset = offsetof(Socket, exec_runtime),
29206d46 3277 .dynamic_creds_offset = offsetof(Socket, dynamic_creds),
3ef63c31 3278
f975e971
LP
3279 .sections =
3280 "Unit\0"
3281 "Socket\0"
3282 "Install\0",
4ad49000 3283 .private_section = "Socket",
71645aca 3284
9c0320e7
YW
3285 .can_transient = true,
3286
034c6ed7
LP
3287 .init = socket_init,
3288 .done = socket_done,
a16e1123
LP
3289 .load = socket_load,
3290
3291 .coldplug = socket_coldplug,
034c6ed7 3292
5cb5a6ff
LP
3293 .dump = socket_dump,
3294
542563ba
LP
3295 .start = socket_start,
3296 .stop = socket_stop,
5cb5a6ff 3297
718db961
LP
3298 .kill = socket_kill,
3299
68db7a3b
ZJS
3300 .get_timeout = socket_get_timeout,
3301
a16e1123
LP
3302 .serialize = socket_serialize,
3303 .deserialize_item = socket_deserialize_item,
01e10de3 3304 .distribute_fds = socket_distribute_fds,
a16e1123 3305
5cb5a6ff 3306 .active_state = socket_active_state,
10a94420 3307 .sub_state_to_string = socket_sub_state_to_string,
5cb5a6ff 3308
f2f725e5 3309 .may_gc = socket_may_gc,
6cf6bbc2 3310
034c6ed7 3311 .sigchld_event = socket_sigchld_event,
4139c1b2 3312
d137a488
UTL
3313 .trigger_notify = socket_trigger_notify,
3314
fdf20a31 3315 .reset_failed = socket_reset_failed,
5632e374 3316
291d565a
LP
3317 .control_pid = socket_control_pid,
3318
718db961 3319 .bus_vtable = bus_socket_vtable,
74c964d3
LP
3320 .bus_set_property = bus_socket_set_property,
3321 .bus_commit_properties = bus_socket_commit_properties,
c6918296
MS
3322
3323 .status_message_formats = {
3324 /*.starting_stopping = {
3325 [0] = "Starting socket %s...",
3326 [1] = "Stopping socket %s...",
3327 },*/
3328 .finished_start_job = {
3329 [JOB_DONE] = "Listening on %s.",
3330 [JOB_FAILED] = "Failed to listen on %s.",
c6918296
MS
3331 [JOB_TIMEOUT] = "Timed out starting %s.",
3332 },
3333 .finished_stop_job = {
3334 [JOB_DONE] = "Closed %s.",
3335 [JOB_FAILED] = "Failed stopping %s.",
3336 [JOB_TIMEOUT] = "Timed out stopping %s.",
3337 },
3338 },
5cb5a6ff 3339};