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