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