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