1 /* SPDX-License-Identifier: LGPL-2.1+ */
3 This file is part of systemd.
5 Copyright 2010 Lennart Poettering
7 systemd is free software; you can redistribute it and/or modify it
8 under the terms of the GNU Lesser General Public License as published by
9 the Free Software Foundation; either version 2.1 of the License, or
10 (at your option) any later version.
12 systemd is distributed in the hope that it will be useful, but
13 WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 Lesser General Public License for more details.
17 You should have received a copy of the GNU Lesser General Public License
18 along with systemd; If not, see <http://www.gnu.org/licenses/>.
21 #include <arpa/inet.h>
25 #include <netinet/tcp.h>
27 #include <sys/epoll.h>
30 #include <linux/sctp.h>
32 #include "alloc-util.h"
33 #include "bpf-firewall.h"
34 #include "bus-error.h"
37 #include "dbus-socket.h"
39 #include "exit-status.h"
41 #include "format-util.h"
43 #include "in-addr-util.h"
49 #include "parse-util.h"
50 #include "path-util.h"
51 #include "process-util.h"
52 #include "selinux-util.h"
53 #include "signal-util.h"
54 #include "smack-util.h"
57 #include "string-table.h"
58 #include "string-util.h"
60 #include "unit-name.h"
62 #include "user-util.h"
68 union sockaddr_union peer
;
72 static const UnitActiveState state_translation_table
[_SOCKET_STATE_MAX
] = {
73 [SOCKET_DEAD
] = UNIT_INACTIVE
,
74 [SOCKET_START_PRE
] = UNIT_ACTIVATING
,
75 [SOCKET_START_CHOWN
] = UNIT_ACTIVATING
,
76 [SOCKET_START_POST
] = UNIT_ACTIVATING
,
77 [SOCKET_LISTENING
] = UNIT_ACTIVE
,
78 [SOCKET_RUNNING
] = UNIT_ACTIVE
,
79 [SOCKET_STOP_PRE
] = UNIT_DEACTIVATING
,
80 [SOCKET_STOP_PRE_SIGTERM
] = UNIT_DEACTIVATING
,
81 [SOCKET_STOP_PRE_SIGKILL
] = UNIT_DEACTIVATING
,
82 [SOCKET_STOP_POST
] = UNIT_DEACTIVATING
,
83 [SOCKET_FINAL_SIGTERM
] = UNIT_DEACTIVATING
,
84 [SOCKET_FINAL_SIGKILL
] = UNIT_DEACTIVATING
,
85 [SOCKET_FAILED
] = UNIT_FAILED
88 static int socket_dispatch_io(sd_event_source
*source
, int fd
, uint32_t revents
, void *userdata
);
89 static int socket_dispatch_timer(sd_event_source
*source
, usec_t usec
, void *userdata
);
91 static void socket_init(Unit
*u
) {
92 Socket
*s
= SOCKET(u
);
95 assert(u
->load_state
== UNIT_STUB
);
97 s
->backlog
= SOMAXCONN
;
98 s
->timeout_usec
= u
->manager
->default_timeout_start_usec
;
99 s
->directory_mode
= 0755;
100 s
->socket_mode
= 0666;
102 s
->max_connections
= 64;
109 s
->exec_context
.std_output
= u
->manager
->default_std_output
;
110 s
->exec_context
.std_error
= u
->manager
->default_std_error
;
112 s
->control_command_id
= _SOCKET_EXEC_COMMAND_INVALID
;
114 s
->trigger_limit
.interval
= USEC_INFINITY
;
115 s
->trigger_limit
.burst
= (unsigned) -1;
118 static void socket_unwatch_control_pid(Socket
*s
) {
121 if (s
->control_pid
<= 0)
124 unit_unwatch_pid(UNIT(s
), s
->control_pid
);
128 static void socket_cleanup_fd_list(SocketPort
*p
) {
131 close_many(p
->auxiliary_fds
, p
->n_auxiliary_fds
);
132 p
->auxiliary_fds
= mfree(p
->auxiliary_fds
);
133 p
->n_auxiliary_fds
= 0;
136 void socket_free_ports(Socket
*s
) {
141 while ((p
= s
->ports
)) {
142 LIST_REMOVE(port
, s
->ports
, p
);
144 sd_event_source_unref(p
->event_source
);
146 socket_cleanup_fd_list(p
);
153 static void socket_done(Unit
*u
) {
154 Socket
*s
= SOCKET(u
);
159 socket_free_ports(s
);
161 while ((p
= set_steal_first(s
->peers_by_address
)))
164 s
->peers_by_address
= set_free(s
->peers_by_address
);
166 s
->exec_runtime
= exec_runtime_unref(s
->exec_runtime
);
167 exec_command_free_array(s
->exec_command
, _SOCKET_EXEC_COMMAND_MAX
);
168 s
->control_command
= NULL
;
170 dynamic_creds_unref(&s
->dynamic_creds
);
172 socket_unwatch_control_pid(s
);
174 unit_ref_unset(&s
->service
);
176 s
->tcp_congestion
= mfree(s
->tcp_congestion
);
177 s
->bind_to_device
= mfree(s
->bind_to_device
);
179 s
->smack
= mfree(s
->smack
);
180 s
->smack_ip_in
= mfree(s
->smack_ip_in
);
181 s
->smack_ip_out
= mfree(s
->smack_ip_out
);
183 strv_free(s
->symlinks
);
185 s
->user
= mfree(s
->user
);
186 s
->group
= mfree(s
->group
);
188 s
->fdname
= mfree(s
->fdname
);
190 s
->timer_event_source
= sd_event_source_unref(s
->timer_event_source
);
193 static int socket_arm_timer(Socket
*s
, usec_t usec
) {
198 if (s
->timer_event_source
) {
199 r
= sd_event_source_set_time(s
->timer_event_source
, usec
);
203 return sd_event_source_set_enabled(s
->timer_event_source
, SD_EVENT_ONESHOT
);
206 if (usec
== USEC_INFINITY
)
209 r
= sd_event_add_time(
210 UNIT(s
)->manager
->event
,
211 &s
->timer_event_source
,
214 socket_dispatch_timer
, s
);
218 (void) sd_event_source_set_description(s
->timer_event_source
, "socket-timer");
223 int socket_instantiate_service(Socket
*s
) {
224 _cleanup_free_
char *prefix
= NULL
, *name
= NULL
;
230 /* This fills in s->service if it isn't filled in yet. For
231 * Accept=yes sockets we create the next connection service
232 * here. For Accept=no this is mostly a NOP since the service
233 * is figured out at load time anyway. */
235 if (UNIT_DEREF(s
->service
))
241 r
= unit_name_to_prefix(UNIT(s
)->id
, &prefix
);
245 if (asprintf(&name
, "%s@%u.service", prefix
, s
->n_accepted
) < 0)
248 r
= manager_load_unit(UNIT(s
)->manager
, name
, NULL
, NULL
, &u
);
252 unit_ref_set(&s
->service
, u
);
254 return unit_add_two_dependencies(UNIT(s
), UNIT_BEFORE
, UNIT_TRIGGERS
, u
, false, UNIT_DEPENDENCY_IMPLICIT
);
257 static bool have_non_accept_socket(Socket
*s
) {
265 LIST_FOREACH(port
, p
, s
->ports
) {
267 if (p
->type
!= SOCKET_SOCKET
)
270 if (!socket_address_can_accept(&p
->address
))
277 static int socket_add_mount_dependencies(Socket
*s
) {
283 LIST_FOREACH(port
, p
, s
->ports
) {
284 const char *path
= NULL
;
286 if (p
->type
== SOCKET_SOCKET
)
287 path
= socket_address_get_path(&p
->address
);
288 else if (IN_SET(p
->type
, SOCKET_FIFO
, SOCKET_SPECIAL
, SOCKET_USB_FUNCTION
))
294 r
= unit_require_mounts_for(UNIT(s
), path
, UNIT_DEPENDENCY_FILE
);
302 static int socket_add_device_dependencies(Socket
*s
) {
307 if (!s
->bind_to_device
|| streq(s
->bind_to_device
, "lo"))
310 t
= strjoina("/sys/subsystem/net/devices/", s
->bind_to_device
);
311 return unit_add_node_dependency(UNIT(s
), t
, false, UNIT_BINDS_TO
, UNIT_DEPENDENCY_FILE
);
314 static int socket_add_default_dependencies(Socket
*s
) {
318 if (!UNIT(s
)->default_dependencies
)
321 r
= unit_add_dependency_by_name(UNIT(s
), UNIT_BEFORE
, SPECIAL_SOCKETS_TARGET
, NULL
, true, UNIT_DEPENDENCY_DEFAULT
);
325 if (MANAGER_IS_SYSTEM(UNIT(s
)->manager
)) {
326 r
= unit_add_two_dependencies_by_name(UNIT(s
), UNIT_AFTER
, UNIT_REQUIRES
, SPECIAL_SYSINIT_TARGET
, NULL
, true, UNIT_DEPENDENCY_DEFAULT
);
331 return unit_add_two_dependencies_by_name(UNIT(s
), UNIT_BEFORE
, UNIT_CONFLICTS
, SPECIAL_SHUTDOWN_TARGET
, NULL
, true, UNIT_DEPENDENCY_DEFAULT
);
334 _pure_
static bool socket_has_exec(Socket
*s
) {
338 for (i
= 0; i
< _SOCKET_EXEC_COMMAND_MAX
; i
++)
339 if (s
->exec_command
[i
])
345 static int socket_add_extras(Socket
*s
) {
351 /* Pick defaults for the trigger limit, if nothing was explicitly configured. We pick a relatively high limit
352 * in Accept=yes mode, and a lower limit for Accept=no. Reason: in Accept=yes mode we are invoking accept()
353 * ourselves before the trigger limit can hit, thus incoming connections are taken off the socket queue quickly
354 * and reliably. This is different for Accept=no, where the spawned service has to take the incoming traffic
355 * off the queues, which it might not necessarily do. Moreover, while Accept=no services are supposed to
356 * process whatever is queued in one go, and thus should normally never have to be started frequently. This is
357 * different for Accept=yes where each connection is processed by a new service instance, and thus frequent
358 * service starts are typical. */
360 if (s
->trigger_limit
.interval
== USEC_INFINITY
)
361 s
->trigger_limit
.interval
= 2 * USEC_PER_SEC
;
363 if (s
->trigger_limit
.burst
== (unsigned) -1) {
365 s
->trigger_limit
.burst
= 200;
367 s
->trigger_limit
.burst
= 20;
370 if (have_non_accept_socket(s
)) {
372 if (!UNIT_DEREF(s
->service
)) {
375 r
= unit_load_related_unit(u
, ".service", &x
);
379 unit_ref_set(&s
->service
, x
);
382 r
= unit_add_two_dependencies(u
, UNIT_BEFORE
, UNIT_TRIGGERS
, UNIT_DEREF(s
->service
), true, UNIT_DEPENDENCY_IMPLICIT
);
387 r
= socket_add_mount_dependencies(s
);
391 r
= socket_add_device_dependencies(s
);
395 r
= unit_patch_contexts(u
);
399 if (socket_has_exec(s
)) {
400 r
= unit_add_exec_dependencies(u
, &s
->exec_context
);
405 r
= unit_set_default_slice(u
);
409 r
= socket_add_default_dependencies(s
);
416 static const char *socket_find_symlink_target(Socket
*s
) {
417 const char *found
= NULL
;
420 LIST_FOREACH(port
, p
, s
->ports
) {
421 const char *f
= NULL
;
430 f
= socket_address_get_path(&p
->address
);
448 static int socket_verify(Socket
*s
) {
451 if (UNIT(s
)->load_state
!= UNIT_LOADED
)
455 log_unit_error(UNIT(s
), "Unit has no Listen setting (ListenStream=, ListenDatagram=, ListenFIFO=, ...). Refusing.");
459 if (s
->accept
&& have_non_accept_socket(s
)) {
460 log_unit_error(UNIT(s
), "Unit configured for accepting sockets, but sockets are non-accepting. Refusing.");
464 if (s
->accept
&& s
->max_connections
<= 0) {
465 log_unit_error(UNIT(s
), "MaxConnection= setting too small. Refusing.");
469 if (s
->accept
&& UNIT_DEREF(s
->service
)) {
470 log_unit_error(UNIT(s
), "Explicit service configuration for accepting socket units not supported. Refusing.");
474 if (s
->exec_context
.pam_name
&& s
->kill_context
.kill_mode
!= KILL_CONTROL_GROUP
) {
475 log_unit_error(UNIT(s
), "Unit has PAM enabled. Kill mode must be set to 'control-group'. Refusing.");
479 if (!strv_isempty(s
->symlinks
) && !socket_find_symlink_target(s
)) {
480 log_unit_error(UNIT(s
), "Unit has symlinks set but none or more than one node in the file system. Refusing.");
487 static void peer_address_hash_func(const void *p
, struct siphash
*state
) {
488 const SocketPeer
*s
= p
;
492 if (s
->peer
.sa
.sa_family
== AF_INET
)
493 siphash24_compress(&s
->peer
.in
.sin_addr
, sizeof(s
->peer
.in
.sin_addr
), state
);
494 else if (s
->peer
.sa
.sa_family
== AF_INET6
)
495 siphash24_compress(&s
->peer
.in6
.sin6_addr
, sizeof(s
->peer
.in6
.sin6_addr
), state
);
496 else if (s
->peer
.sa
.sa_family
== AF_VSOCK
)
497 siphash24_compress(&s
->peer
.vm
.svm_cid
, sizeof(s
->peer
.vm
.svm_cid
), state
);
499 assert_not_reached("Unknown address family.");
502 static int peer_address_compare_func(const void *a
, const void *b
) {
503 const SocketPeer
*x
= a
, *y
= b
;
505 if (x
->peer
.sa
.sa_family
< y
->peer
.sa
.sa_family
)
507 if (x
->peer
.sa
.sa_family
> y
->peer
.sa
.sa_family
)
510 switch(x
->peer
.sa
.sa_family
) {
512 return memcmp(&x
->peer
.in
.sin_addr
, &y
->peer
.in
.sin_addr
, sizeof(x
->peer
.in
.sin_addr
));
514 return memcmp(&x
->peer
.in6
.sin6_addr
, &y
->peer
.in6
.sin6_addr
, sizeof(x
->peer
.in6
.sin6_addr
));
516 if (x
->peer
.vm
.svm_cid
< y
->peer
.vm
.svm_cid
)
518 if (x
->peer
.vm
.svm_cid
> y
->peer
.vm
.svm_cid
)
522 assert_not_reached("Black sheep in the family!");
525 const struct hash_ops peer_address_hash_ops
= {
526 .hash
= peer_address_hash_func
,
527 .compare
= peer_address_compare_func
530 static int socket_load(Unit
*u
) {
531 Socket
*s
= SOCKET(u
);
535 assert(u
->load_state
== UNIT_STUB
);
537 r
= set_ensure_allocated(&s
->peers_by_address
, &peer_address_hash_ops
);
541 r
= unit_load_fragment_and_dropin(u
);
545 if (u
->load_state
== UNIT_LOADED
) {
546 /* This is a new unit? Then let's add in some extras */
547 r
= socket_add_extras(s
);
552 return socket_verify(s
);
555 static SocketPeer
*socket_peer_new(void) {
558 p
= new0(SocketPeer
, 1);
567 SocketPeer
*socket_peer_ref(SocketPeer
*p
) {
571 assert(p
->n_ref
> 0);
577 SocketPeer
*socket_peer_unref(SocketPeer
*p
) {
581 assert(p
->n_ref
> 0);
589 set_remove(p
->socket
->peers_by_address
, p
);
594 int socket_acquire_peer(Socket
*s
, int fd
, SocketPeer
**p
) {
595 _cleanup_(socket_peer_unrefp
) SocketPeer
*remote
= NULL
;
596 SocketPeer sa
= {}, *i
;
597 socklen_t salen
= sizeof(sa
.peer
);
603 r
= getpeername(fd
, &sa
.peer
.sa
, &salen
);
605 return log_error_errno(errno
, "getpeername failed: %m");
607 if (!IN_SET(sa
.peer
.sa
.sa_family
, AF_INET
, AF_INET6
, AF_VSOCK
)) {
612 i
= set_get(s
->peers_by_address
, &sa
);
614 *p
= socket_peer_ref(i
);
618 remote
= socket_peer_new();
622 remote
->peer
= sa
.peer
;
623 remote
->peer_salen
= salen
;
625 r
= set_put(s
->peers_by_address
, remote
);
637 _const_
static const char* listen_lookup(int family
, int type
) {
639 if (family
== AF_NETLINK
)
640 return "ListenNetlink";
642 if (type
== SOCK_STREAM
)
643 return "ListenStream";
644 else if (type
== SOCK_DGRAM
)
645 return "ListenDatagram";
646 else if (type
== SOCK_SEQPACKET
)
647 return "ListenSequentialPacket";
649 assert_not_reached("Unknown socket type");
653 static void socket_dump(Unit
*u
, FILE *f
, const char *prefix
) {
654 char time_string
[FORMAT_TIMESPAN_MAX
];
656 Socket
*s
= SOCKET(u
);
663 prefix
= strempty(prefix
);
664 prefix2
= strjoina(prefix
, "\t");
667 "%sSocket State: %s\n"
669 "%sBindIPv6Only: %s\n"
671 "%sSocketMode: %04o\n"
672 "%sDirectoryMode: %04o\n"
676 "%sTransparent: %s\n"
678 "%sPassCredentials: %s\n"
679 "%sPassSecurity: %s\n"
680 "%sTCPCongestion: %s\n"
681 "%sRemoveOnStop: %s\n"
684 "%sSELinuxContextFromNet: %s\n",
685 prefix
, socket_state_to_string(s
->state
),
686 prefix
, socket_result_to_string(s
->result
),
687 prefix
, socket_address_bind_ipv6_only_to_string(s
->bind_ipv6_only
),
689 prefix
, s
->socket_mode
,
690 prefix
, s
->directory_mode
,
691 prefix
, yes_no(s
->keep_alive
),
692 prefix
, yes_no(s
->no_delay
),
693 prefix
, yes_no(s
->free_bind
),
694 prefix
, yes_no(s
->transparent
),
695 prefix
, yes_no(s
->broadcast
),
696 prefix
, yes_no(s
->pass_cred
),
697 prefix
, yes_no(s
->pass_sec
),
698 prefix
, strna(s
->tcp_congestion
),
699 prefix
, yes_no(s
->remove_on_stop
),
700 prefix
, yes_no(s
->writable
),
701 prefix
, socket_fdname(s
),
702 prefix
, yes_no(s
->selinux_context_from_net
));
704 if (s
->control_pid
> 0)
706 "%sControl PID: "PID_FMT
"\n",
707 prefix
, s
->control_pid
);
709 if (s
->bind_to_device
)
711 "%sBindToDevice: %s\n",
712 prefix
, s
->bind_to_device
);
717 "%sNConnections: %u\n"
718 "%sMaxConnections: %u\n",
719 prefix
, s
->n_accepted
,
720 prefix
, s
->n_connections
,
721 prefix
, s
->max_connections
);
723 if (s
->priority
>= 0)
726 prefix
, s
->priority
);
728 if (s
->receive_buffer
> 0)
730 "%sReceiveBuffer: %zu\n",
731 prefix
, s
->receive_buffer
);
733 if (s
->send_buffer
> 0)
735 "%sSendBuffer: %zu\n",
736 prefix
, s
->send_buffer
);
748 if (s
->pipe_size
> 0)
751 prefix
, s
->pipe_size
);
758 if (s
->mq_maxmsg
> 0)
760 "%sMessageQueueMaxMessages: %li\n",
761 prefix
, s
->mq_maxmsg
);
763 if (s
->mq_msgsize
> 0)
765 "%sMessageQueueMessageSize: %li\n",
766 prefix
, s
->mq_msgsize
);
771 prefix
, yes_no(s
->reuse_port
));
775 "%sSmackLabel: %s\n",
780 "%sSmackLabelIPIn: %s\n",
781 prefix
, s
->smack_ip_in
);
785 "%sSmackLabelIPOut: %s\n",
786 prefix
, s
->smack_ip_out
);
788 if (!isempty(s
->user
) || !isempty(s
->group
))
791 "%sSocketGroup: %s\n",
792 prefix
, strna(s
->user
),
793 prefix
, strna(s
->group
));
795 if (s
->keep_alive_time
> 0)
797 "%sKeepAliveTimeSec: %s\n",
798 prefix
, format_timespan(time_string
, FORMAT_TIMESPAN_MAX
, s
->keep_alive_time
, USEC_PER_SEC
));
800 if (s
->keep_alive_interval
)
802 "%sKeepAliveIntervalSec: %s\n",
803 prefix
, format_timespan(time_string
, FORMAT_TIMESPAN_MAX
, s
->keep_alive_interval
, USEC_PER_SEC
));
805 if (s
->keep_alive_cnt
)
807 "%sKeepAliveProbes: %u\n",
808 prefix
, s
->keep_alive_cnt
);
812 "%sDeferAcceptSec: %s\n",
813 prefix
, format_timespan(time_string
, FORMAT_TIMESPAN_MAX
, s
->defer_accept
, USEC_PER_SEC
));
815 LIST_FOREACH(port
, p
, s
->ports
) {
817 if (p
->type
== SOCKET_SOCKET
) {
822 r
= socket_address_print(&p
->address
, &k
);
828 fprintf(f
, "%s%s: %s\n", prefix
, listen_lookup(socket_address_family(&p
->address
), p
->address
.type
), t
);
830 } else if (p
->type
== SOCKET_SPECIAL
)
831 fprintf(f
, "%sListenSpecial: %s\n", prefix
, p
->path
);
832 else if (p
->type
== SOCKET_USB_FUNCTION
)
833 fprintf(f
, "%sListenUSBFunction: %s\n", prefix
, p
->path
);
834 else if (p
->type
== SOCKET_MQUEUE
)
835 fprintf(f
, "%sListenMessageQueue: %s\n", prefix
, p
->path
);
837 fprintf(f
, "%sListenFIFO: %s\n", prefix
, p
->path
);
841 "%sTriggerLimitIntervalSec: %s\n"
842 "%sTriggerLimitBurst: %u\n",
843 prefix
, format_timespan(time_string
, FORMAT_TIMESPAN_MAX
, s
->trigger_limit
.interval
, USEC_PER_SEC
),
844 prefix
, s
->trigger_limit
.burst
);
846 exec_context_dump(&s
->exec_context
, f
, prefix
);
847 kill_context_dump(&s
->kill_context
, f
, prefix
);
849 for (c
= 0; c
< _SOCKET_EXEC_COMMAND_MAX
; c
++) {
850 if (!s
->exec_command
[c
])
853 fprintf(f
, "%s-> %s:\n",
854 prefix
, socket_exec_command_to_string(c
));
856 exec_command_dump_list(s
->exec_command
[c
], f
, prefix2
);
859 cgroup_context_dump(&s
->cgroup_context
, f
, prefix
);
862 static int instance_from_socket(int fd
, unsigned nr
, char **instance
) {
865 union sockaddr_union local
, remote
;
871 if (getsockname(fd
, &local
.sa
, &l
) < 0)
875 if (getpeername(fd
, &remote
.sa
, &l
) < 0)
878 switch (local
.sa
.sa_family
) {
882 a
= be32toh(local
.in
.sin_addr
.s_addr
),
883 b
= be32toh(remote
.in
.sin_addr
.s_addr
);
886 "%u-%u.%u.%u.%u:%u-%u.%u.%u.%u:%u",
888 a
>> 24, (a
>> 16) & 0xFF, (a
>> 8) & 0xFF, a
& 0xFF,
889 be16toh(local
.in
.sin_port
),
890 b
>> 24, (b
>> 16) & 0xFF, (b
>> 8) & 0xFF, b
& 0xFF,
891 be16toh(remote
.in
.sin_port
)) < 0)
898 static const unsigned char ipv4_prefix
[] = {
899 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xFF, 0xFF
902 if (memcmp(&local
.in6
.sin6_addr
, ipv4_prefix
, sizeof(ipv4_prefix
)) == 0 &&
903 memcmp(&remote
.in6
.sin6_addr
, ipv4_prefix
, sizeof(ipv4_prefix
)) == 0) {
905 *a
= local
.in6
.sin6_addr
.s6_addr
+12,
906 *b
= remote
.in6
.sin6_addr
.s6_addr
+12;
909 "%u-%u.%u.%u.%u:%u-%u.%u.%u.%u:%u",
911 a
[0], a
[1], a
[2], a
[3],
912 be16toh(local
.in6
.sin6_port
),
913 b
[0], b
[1], b
[2], b
[3],
914 be16toh(remote
.in6
.sin6_port
)) < 0)
917 char a
[INET6_ADDRSTRLEN
], b
[INET6_ADDRSTRLEN
];
922 inet_ntop(AF_INET6
, &local
.in6
.sin6_addr
, a
, sizeof(a
)),
923 be16toh(local
.in6
.sin6_port
),
924 inet_ntop(AF_INET6
, &remote
.in6
.sin6_addr
, b
, sizeof(b
)),
925 be16toh(remote
.in6
.sin6_port
)) < 0)
936 k
= getpeercred(fd
, &ucred
);
939 "%u-"PID_FMT
"-"UID_FMT
,
940 nr
, ucred
.pid
, ucred
.uid
) < 0)
942 } else if (k
== -ENODATA
) {
943 /* This handles the case where somebody is
944 * connecting from another pid/uid namespace
945 * (e.g. from outside of our container). */
960 local
.vm
.svm_cid
, local
.vm
.svm_port
,
961 remote
.vm
.svm_cid
, remote
.vm
.svm_port
) < 0)
967 assert_not_reached("Unhandled socket type.");
974 static void socket_close_fds(Socket
*s
) {
980 LIST_FOREACH(port
, p
, s
->ports
) {
983 was_open
= p
->fd
>= 0;
985 p
->event_source
= sd_event_source_unref(p
->event_source
);
986 p
->fd
= safe_close(p
->fd
);
987 socket_cleanup_fd_list(p
);
989 /* One little note: we should normally not delete any sockets in the file system here! After all some
990 * other process we spawned might still have a reference of this fd and wants to continue to use
991 * it. Therefore we normally delete sockets in the file system before we create a new one, not after we
992 * stopped using one! That all said, if the user explicitly requested this, we'll delete them here
993 * anyway, but only then. */
995 if (!was_open
|| !s
->remove_on_stop
)
1001 (void) unlink(p
->path
);
1005 (void) mq_unlink(p
->path
);
1009 (void) socket_address_unlink(&p
->address
);
1017 if (s
->remove_on_stop
)
1018 STRV_FOREACH(i
, s
->symlinks
)
1022 static void socket_apply_socket_options(Socket
*s
, int fd
) {
1028 if (s
->keep_alive
) {
1029 int b
= s
->keep_alive
;
1030 if (setsockopt(fd
, SOL_SOCKET
, SO_KEEPALIVE
, &b
, sizeof(b
)) < 0)
1031 log_unit_warning_errno(UNIT(s
), errno
, "SO_KEEPALIVE failed: %m");
1034 if (s
->keep_alive_time
) {
1035 int value
= s
->keep_alive_time
/ USEC_PER_SEC
;
1036 if (setsockopt(fd
, SOL_TCP
, TCP_KEEPIDLE
, &value
, sizeof(value
)) < 0)
1037 log_unit_warning_errno(UNIT(s
), errno
, "TCP_KEEPIDLE failed: %m");
1040 if (s
->keep_alive_interval
) {
1041 int value
= s
->keep_alive_interval
/ USEC_PER_SEC
;
1042 if (setsockopt(fd
, SOL_TCP
, TCP_KEEPINTVL
, &value
, sizeof(value
)) < 0)
1043 log_unit_warning_errno(UNIT(s
), errno
, "TCP_KEEPINTVL failed: %m");
1046 if (s
->keep_alive_cnt
) {
1047 int value
= s
->keep_alive_cnt
;
1048 if (setsockopt(fd
, SOL_TCP
, TCP_KEEPCNT
, &value
, sizeof(value
)) < 0)
1049 log_unit_warning_errno(UNIT(s
), errno
, "TCP_KEEPCNT failed: %m");
1052 if (s
->defer_accept
) {
1053 int value
= s
->defer_accept
/ USEC_PER_SEC
;
1054 if (setsockopt(fd
, SOL_TCP
, TCP_DEFER_ACCEPT
, &value
, sizeof(value
)) < 0)
1055 log_unit_warning_errno(UNIT(s
), errno
, "TCP_DEFER_ACCEPT failed: %m");
1059 int b
= s
->no_delay
;
1061 if (s
->socket_protocol
== IPPROTO_SCTP
) {
1062 if (setsockopt(fd
, SOL_SCTP
, SCTP_NODELAY
, &b
, sizeof(b
)) < 0)
1063 log_unit_warning_errno(UNIT(s
), errno
, "SCTP_NODELAY failed: %m");
1065 if (setsockopt(fd
, SOL_TCP
, TCP_NODELAY
, &b
, sizeof(b
)) < 0)
1066 log_unit_warning_errno(UNIT(s
), errno
, "TCP_NODELAY failed: %m");
1072 if (setsockopt(fd
, SOL_SOCKET
, SO_BROADCAST
, &one
, sizeof(one
)) < 0)
1073 log_unit_warning_errno(UNIT(s
), errno
, "SO_BROADCAST failed: %m");
1078 if (setsockopt(fd
, SOL_SOCKET
, SO_PASSCRED
, &one
, sizeof(one
)) < 0)
1079 log_unit_warning_errno(UNIT(s
), errno
, "SO_PASSCRED failed: %m");
1084 if (setsockopt(fd
, SOL_SOCKET
, SO_PASSSEC
, &one
, sizeof(one
)) < 0)
1085 log_unit_warning_errno(UNIT(s
), errno
, "SO_PASSSEC failed: %m");
1088 if (s
->priority
>= 0)
1089 if (setsockopt(fd
, SOL_SOCKET
, SO_PRIORITY
, &s
->priority
, sizeof(s
->priority
)) < 0)
1090 log_unit_warning_errno(UNIT(s
), errno
, "SO_PRIORITY failed: %m");
1092 if (s
->receive_buffer
> 0) {
1093 int value
= (int) s
->receive_buffer
;
1095 /* We first try with SO_RCVBUFFORCE, in case we have the perms for that */
1097 if (setsockopt(fd
, SOL_SOCKET
, SO_RCVBUFFORCE
, &value
, sizeof(value
)) < 0)
1098 if (setsockopt(fd
, SOL_SOCKET
, SO_RCVBUF
, &value
, sizeof(value
)) < 0)
1099 log_unit_warning_errno(UNIT(s
), errno
, "SO_RCVBUF failed: %m");
1102 if (s
->send_buffer
> 0) {
1103 int value
= (int) s
->send_buffer
;
1104 if (setsockopt(fd
, SOL_SOCKET
, SO_SNDBUFFORCE
, &value
, sizeof(value
)) < 0)
1105 if (setsockopt(fd
, SOL_SOCKET
, SO_SNDBUF
, &value
, sizeof(value
)) < 0)
1106 log_unit_warning_errno(UNIT(s
), errno
, "SO_SNDBUF failed: %m");
1110 if (setsockopt(fd
, SOL_SOCKET
, SO_MARK
, &s
->mark
, sizeof(s
->mark
)) < 0)
1111 log_unit_warning_errno(UNIT(s
), errno
, "SO_MARK failed: %m");
1114 if (setsockopt(fd
, IPPROTO_IP
, IP_TOS
, &s
->ip_tos
, sizeof(s
->ip_tos
)) < 0)
1115 log_unit_warning_errno(UNIT(s
), errno
, "IP_TOS failed: %m");
1117 if (s
->ip_ttl
>= 0) {
1120 r
= setsockopt(fd
, IPPROTO_IP
, IP_TTL
, &s
->ip_ttl
, sizeof(s
->ip_ttl
));
1122 if (socket_ipv6_is_supported())
1123 x
= setsockopt(fd
, IPPROTO_IPV6
, IPV6_UNICAST_HOPS
, &s
->ip_ttl
, sizeof(s
->ip_ttl
));
1126 errno
= EAFNOSUPPORT
;
1130 log_unit_warning_errno(UNIT(s
), errno
, "IP_TTL/IPV6_UNICAST_HOPS failed: %m");
1133 if (s
->tcp_congestion
)
1134 if (setsockopt(fd
, SOL_TCP
, TCP_CONGESTION
, s
->tcp_congestion
, strlen(s
->tcp_congestion
)+1) < 0)
1135 log_unit_warning_errno(UNIT(s
), errno
, "TCP_CONGESTION failed: %m");
1137 if (s
->smack_ip_in
) {
1138 r
= mac_smack_apply_fd(fd
, SMACK_ATTR_IPIN
, s
->smack_ip_in
);
1140 log_unit_error_errno(UNIT(s
), r
, "mac_smack_apply_ip_in_fd: %m");
1143 if (s
->smack_ip_out
) {
1144 r
= mac_smack_apply_fd(fd
, SMACK_ATTR_IPOUT
, s
->smack_ip_out
);
1146 log_unit_error_errno(UNIT(s
), r
, "mac_smack_apply_ip_out_fd: %m");
1150 static void socket_apply_fifo_options(Socket
*s
, int fd
) {
1156 if (s
->pipe_size
> 0)
1157 if (fcntl(fd
, F_SETPIPE_SZ
, s
->pipe_size
) < 0)
1158 log_unit_warning_errno(UNIT(s
), errno
, "Setting pipe size failed, ignoring: %m");
1161 r
= mac_smack_apply_fd(fd
, SMACK_ATTR_ACCESS
, s
->smack
);
1163 log_unit_error_errno(UNIT(s
), r
, "SMACK relabelling failed, ignoring: %m");
1167 static int fifo_address_create(
1169 mode_t directory_mode
,
1170 mode_t socket_mode
) {
1172 _cleanup_close_
int fd
= -1;
1179 (void) mkdir_parents_label(path
, directory_mode
);
1181 r
= mac_selinux_create_file_prepare(path
, S_IFIFO
);
1185 /* Enforce the right access mode for the fifo */
1186 old_mask
= umask(~ socket_mode
);
1188 /* Include the original umask in our mask */
1189 (void) umask(~socket_mode
| old_mask
);
1191 r
= mkfifo(path
, socket_mode
);
1192 (void) umask(old_mask
);
1194 if (r
< 0 && errno
!= EEXIST
) {
1199 fd
= open(path
, O_RDWR
| O_CLOEXEC
| O_NOCTTY
| O_NONBLOCK
| O_NOFOLLOW
);
1205 mac_selinux_create_file_clear();
1207 if (fstat(fd
, &st
) < 0) {
1212 if (!S_ISFIFO(st
.st_mode
) ||
1213 (st
.st_mode
& 0777) != (socket_mode
& ~old_mask
) ||
1214 st
.st_uid
!= getuid() ||
1215 st
.st_gid
!= getgid()) {
1226 mac_selinux_create_file_clear();
1230 static int special_address_create(const char *path
, bool writable
) {
1231 _cleanup_close_
int fd
= -1;
1237 fd
= open(path
, (writable
? O_RDWR
: O_RDONLY
)|O_CLOEXEC
|O_NOCTTY
|O_NONBLOCK
|O_NOFOLLOW
);
1241 if (fstat(fd
, &st
) < 0)
1244 /* Check whether this is a /proc, /sys or /dev file or char device */
1245 if (!S_ISREG(st
.st_mode
) && !S_ISCHR(st
.st_mode
))
1254 static int usbffs_address_create(const char *path
) {
1255 _cleanup_close_
int fd
= -1;
1261 fd
= open(path
, O_RDWR
|O_CLOEXEC
|O_NOCTTY
|O_NONBLOCK
|O_NOFOLLOW
);
1265 if (fstat(fd
, &st
) < 0)
1268 /* Check whether this is a regular file (ffs endpoint) */
1269 if (!S_ISREG(st
.st_mode
))
1278 static int mq_address_create(
1284 _cleanup_close_
int fd
= -1;
1287 struct mq_attr _attr
, *attr
= NULL
;
1292 if (maxmsg
> 0 && msgsize
> 0) {
1293 _attr
= (struct mq_attr
) {
1294 .mq_flags
= O_NONBLOCK
,
1295 .mq_maxmsg
= maxmsg
,
1296 .mq_msgsize
= msgsize
,
1301 /* Enforce the right access mode for the mq */
1302 old_mask
= umask(~ mq_mode
);
1304 /* Include the original umask in our mask */
1305 (void) umask(~mq_mode
| old_mask
);
1306 fd
= mq_open(path
, O_RDONLY
|O_CLOEXEC
|O_NONBLOCK
|O_CREAT
, mq_mode
, attr
);
1307 (void) umask(old_mask
);
1312 if (fstat(fd
, &st
) < 0)
1315 if ((st
.st_mode
& 0777) != (mq_mode
& ~old_mask
) ||
1316 st
.st_uid
!= getuid() ||
1317 st
.st_gid
!= getgid())
1326 static int socket_symlink(Socket
*s
) {
1333 p
= socket_find_symlink_target(s
);
1337 STRV_FOREACH(i
, s
->symlinks
) {
1338 (void) mkdir_parents_label(*i
, s
->directory_mode
);
1340 r
= symlink_idempotent(p
, *i
);
1342 if (r
== -EEXIST
&& s
->remove_on_stop
) {
1343 /* If there's already something where we want to create the symlink, and the destructive
1344 * RemoveOnStop= mode is set, then we might as well try to remove what already exists and try
1347 if (unlink(*i
) >= 0)
1348 r
= symlink_idempotent(p
, *i
);
1352 log_unit_warning_errno(UNIT(s
), r
, "Failed to create symlink %s → %s, ignoring: %m", p
, *i
);
1358 static int usbffs_write_descs(int fd
, Service
*s
) {
1361 if (!s
->usb_function_descriptors
|| !s
->usb_function_strings
)
1364 r
= copy_file_fd(s
->usb_function_descriptors
, fd
, 0);
1368 return copy_file_fd(s
->usb_function_strings
, fd
, 0);
1371 static int usbffs_select_ep(const struct dirent
*d
) {
1372 return d
->d_name
[0] != '.' && !streq(d
->d_name
, "ep0");
1375 static int usbffs_dispatch_eps(SocketPort
*p
) {
1376 _cleanup_free_
struct dirent
**ent
= NULL
;
1379 r
= scandir(p
->path
, &ent
, usbffs_select_ep
, alphasort
);
1384 p
->auxiliary_fds
= new(int, n
);
1385 if (!p
->auxiliary_fds
)
1388 p
->n_auxiliary_fds
= n
;
1391 for (i
= 0; i
< n
; ++i
) {
1392 _cleanup_free_
char *ep
= NULL
;
1394 ep
= path_make_absolute(ent
[i
]->d_name
, p
->path
);
1398 path_kill_slashes(ep
);
1400 r
= usbffs_address_create(ep
);
1404 p
->auxiliary_fds
[k
] = r
;
1413 close_many(p
->auxiliary_fds
, k
);
1414 p
->auxiliary_fds
= mfree(p
->auxiliary_fds
);
1415 p
->n_auxiliary_fds
= 0;
1420 static int socket_determine_selinux_label(Socket
*s
, char **ret
) {
1427 if (s
->selinux_context_from_net
) {
1428 /* If this is requested, get label from the network label */
1430 r
= mac_selinux_get_our_label(ret
);
1431 if (r
== -EOPNOTSUPP
)
1435 /* Otherwise, get it from the executable we are about to start */
1436 r
= socket_instantiate_service(s
);
1440 if (!UNIT_ISSET(s
->service
))
1443 c
= SERVICE(UNIT_DEREF(s
->service
))->exec_command
[SERVICE_EXEC_START
];
1447 r
= mac_selinux_get_create_label_from_exe(c
->path
, ret
);
1448 if (IN_SET(r
, -EPERM
, -EOPNOTSUPP
))
1459 static int socket_address_listen_do(
1461 const SocketAddress
*address
,
1462 const char *label
) {
1467 return socket_address_listen(
1469 SOCK_CLOEXEC
|SOCK_NONBLOCK
,
1481 static int socket_address_listen_in_cgroup(
1483 const SocketAddress
*address
,
1484 const char *label
) {
1486 _cleanup_close_pair_
int pair
[2] = { -1, -1 };
1493 /* This is a wrapper around socket_address_listen(), that forks off a helper process inside the socket's cgroup
1494 * in which the socket is actually created. This way we ensure the socket is actually properly attached to the
1495 * unit's cgroup for the purpose of BPF filtering and such. */
1497 if (!IN_SET(address
->sockaddr
.sa
.sa_family
, AF_INET
, AF_INET6
))
1498 goto shortcut
; /* BPF filtering only applies to IPv4 + IPv6, shortcut things for other protocols */
1500 r
= bpf_firewall_supported();
1503 if (r
== 0) /* If BPF firewalling isn't supported anyway — there's no point in this forking complexity */
1506 if (socketpair(AF_UNIX
, SOCK_SEQPACKET
|SOCK_CLOEXEC
, 0, pair
) < 0)
1507 return log_unit_error_errno(UNIT(s
), errno
, "Failed to create communication channel: %m");
1509 r
= unit_fork_helper_process(UNIT(s
), &pid
);
1511 return log_unit_error_errno(UNIT(s
), r
, "Failed to fork off listener stub process: %m");
1515 pair
[0] = safe_close(pair
[0]);
1517 fd
= socket_address_listen_do(s
, address
, label
);
1519 log_unit_error_errno(UNIT(s
), fd
, "Failed to create listening socket: %m");
1520 _exit(EXIT_FAILURE
);
1523 r
= send_one_fd(pair
[1], fd
, 0);
1525 log_unit_error_errno(UNIT(s
), r
, "Failed to send listening socket to parent: %m");
1526 _exit(EXIT_FAILURE
);
1529 _exit(EXIT_SUCCESS
);
1532 pair
[1] = safe_close(pair
[1]);
1533 fd
= receive_one_fd(pair
[0], 0);
1535 /* We synchronously wait for the helper, as it shouldn't be slow */
1536 r
= wait_for_terminate_and_warn("listen-cgroup-helper", pid
, false);
1543 return log_unit_error_errno(UNIT(s
), fd
, "Failed to receive listening socket: %m");
1548 fd
= socket_address_listen_do(s
, address
, label
);
1550 return log_error_errno(fd
, "Failed to create listening socket: %m");
1555 static int socket_open_fds(Socket
*s
) {
1556 _cleanup_(mac_selinux_freep
) char *label
= NULL
;
1557 bool know_label
= false;
1563 LIST_FOREACH(port
, p
, s
->ports
) {
1573 /* Figure out label, if we don't it know yet. We do it once, for the first socket where
1574 * we need this and remember it for the rest. */
1576 r
= socket_determine_selinux_label(s
, &label
);
1583 /* Apply the socket protocol */
1584 switch (p
->address
.type
) {
1587 case SOCK_SEQPACKET
:
1588 if (s
->socket_protocol
== IPPROTO_SCTP
)
1589 p
->address
.protocol
= s
->socket_protocol
;
1593 if (s
->socket_protocol
== IPPROTO_UDPLITE
)
1594 p
->address
.protocol
= s
->socket_protocol
;
1598 r
= socket_address_listen_in_cgroup(s
, &p
->address
, label
);
1603 socket_apply_socket_options(s
, p
->fd
);
1607 case SOCKET_SPECIAL
:
1609 p
->fd
= special_address_create(p
->path
, s
->writable
);
1618 p
->fd
= fifo_address_create(
1627 socket_apply_fifo_options(s
, p
->fd
);
1633 p
->fd
= mq_address_create(
1644 case SOCKET_USB_FUNCTION
: {
1645 _cleanup_free_
char *ep
= NULL
;
1647 ep
= path_make_absolute("ep0", p
->path
);
1649 p
->fd
= usbffs_address_create(ep
);
1655 r
= usbffs_write_descs(p
->fd
, SERVICE(UNIT_DEREF(s
->service
)));
1659 r
= usbffs_dispatch_eps(p
);
1666 assert_not_reached("Unknown port type");
1673 socket_close_fds(s
);
1677 static void socket_unwatch_fds(Socket
*s
) {
1683 LIST_FOREACH(port
, p
, s
->ports
) {
1687 if (!p
->event_source
)
1690 r
= sd_event_source_set_enabled(p
->event_source
, SD_EVENT_OFF
);
1692 log_unit_debug_errno(UNIT(s
), r
, "Failed to disable event source: %m");
1696 static int socket_watch_fds(Socket
*s
) {
1702 LIST_FOREACH(port
, p
, s
->ports
) {
1706 if (p
->event_source
) {
1707 r
= sd_event_source_set_enabled(p
->event_source
, SD_EVENT_ON
);
1711 r
= sd_event_add_io(UNIT(s
)->manager
->event
, &p
->event_source
, p
->fd
, EPOLLIN
, socket_dispatch_io
, p
);
1715 (void) sd_event_source_set_description(p
->event_source
, "socket-port-io");
1722 log_unit_warning_errno(UNIT(s
), r
, "Failed to watch listening fds: %m");
1723 socket_unwatch_fds(s
);
1733 static int socket_check_open(Socket
*s
) {
1734 bool have_open
= false, have_closed
= false;
1739 LIST_FOREACH(port
, p
, s
->ports
) {
1745 if (have_open
&& have_closed
)
1746 return SOCKET_OPEN_SOME
;
1750 return SOCKET_OPEN_ALL
;
1752 return SOCKET_OPEN_NONE
;
1755 static void socket_set_state(Socket
*s
, SocketState state
) {
1756 SocketState old_state
;
1759 old_state
= s
->state
;
1767 SOCKET_STOP_PRE_SIGTERM
,
1768 SOCKET_STOP_PRE_SIGKILL
,
1770 SOCKET_FINAL_SIGTERM
,
1771 SOCKET_FINAL_SIGKILL
)) {
1773 s
->timer_event_source
= sd_event_source_unref(s
->timer_event_source
);
1774 socket_unwatch_control_pid(s
);
1775 s
->control_command
= NULL
;
1776 s
->control_command_id
= _SOCKET_EXEC_COMMAND_INVALID
;
1779 if (state
!= SOCKET_LISTENING
)
1780 socket_unwatch_fds(s
);
1788 SOCKET_STOP_PRE_SIGTERM
,
1789 SOCKET_STOP_PRE_SIGKILL
))
1790 socket_close_fds(s
);
1792 if (state
!= old_state
)
1793 log_unit_debug(UNIT(s
), "Changed %s -> %s", socket_state_to_string(old_state
), socket_state_to_string(state
));
1795 unit_notify(UNIT(s
), state_translation_table
[old_state
], state_translation_table
[state
], true);
1798 static int socket_coldplug(Unit
*u
) {
1799 Socket
*s
= SOCKET(u
);
1803 assert(s
->state
== SOCKET_DEAD
);
1805 if (s
->deserialized_state
== s
->state
)
1808 if (s
->control_pid
> 0 &&
1809 pid_is_unwaited(s
->control_pid
) &&
1810 IN_SET(s
->deserialized_state
,
1815 SOCKET_STOP_PRE_SIGTERM
,
1816 SOCKET_STOP_PRE_SIGKILL
,
1818 SOCKET_FINAL_SIGTERM
,
1819 SOCKET_FINAL_SIGKILL
)) {
1821 r
= unit_watch_pid(UNIT(s
), s
->control_pid
);
1825 r
= socket_arm_timer(s
, usec_add(u
->state_change_timestamp
.monotonic
, s
->timeout_usec
));
1830 if (IN_SET(s
->deserialized_state
,
1836 /* Originally, we used to simply reopen all sockets here that we didn't have file descriptors
1837 * for. However, this is problematic, as we won't traverse throught the SOCKET_START_CHOWN state for
1838 * them, and thus the UID/GID wouldn't be right. Hence, instead simply check if we have all fds open,
1839 * and if there's a mismatch, warn loudly. */
1841 r
= socket_check_open(s
);
1842 if (r
== SOCKET_OPEN_NONE
)
1843 log_unit_warning(UNIT(s
),
1844 "Socket unit configuration has changed while unit has been running, "
1845 "no open socket file descriptor left. "
1846 "The socket unit is not functional until restarted.");
1847 else if (r
== SOCKET_OPEN_SOME
)
1848 log_unit_warning(UNIT(s
),
1849 "Socket unit configuration has changed while unit has been running, "
1850 "and some socket file descriptors have not been opened yet. "
1851 "The socket unit is not fully functional until restarted.");
1854 if (s
->deserialized_state
== SOCKET_LISTENING
) {
1855 r
= socket_watch_fds(s
);
1860 if (!IN_SET(s
->deserialized_state
, SOCKET_DEAD
, SOCKET_FAILED
))
1861 (void) unit_setup_dynamic_creds(u
);
1863 socket_set_state(s
, s
->deserialized_state
);
1867 static int socket_spawn(Socket
*s
, ExecCommand
*c
, pid_t
*_pid
) {
1869 ExecParameters exec_params
= {
1870 .flags
= EXEC_APPLY_SANDBOXING
|EXEC_APPLY_CHROOT
|EXEC_APPLY_TTY_STDIN
,
1882 r
= unit_prepare_exec(UNIT(s
));
1886 r
= socket_arm_timer(s
, usec_add(now(CLOCK_MONOTONIC
), s
->timeout_usec
));
1890 manager_set_exec_params(UNIT(s
)->manager
, &exec_params
);
1891 unit_set_exec_params(UNIT(s
), &exec_params
);
1893 exec_params
.argv
= c
->argv
;
1895 r
= exec_spawn(UNIT(s
),
1905 r
= unit_watch_pid(UNIT(s
), pid
);
1907 /* FIXME: we need to do something here */
1915 static int socket_chown(Socket
*s
, pid_t
*_pid
) {
1919 r
= socket_arm_timer(s
, usec_add(now(CLOCK_MONOTONIC
), s
->timeout_usec
));
1923 /* We have to resolve the user names out-of-process, hence
1924 * let's fork here. It's messy, but well, what can we do? */
1926 r
= unit_fork_helper_process(UNIT(s
), &pid
);
1930 uid_t uid
= UID_INVALID
;
1931 gid_t gid
= GID_INVALID
;
1936 if (!isempty(s
->user
)) {
1937 const char *user
= s
->user
;
1939 r
= get_user_creds(&user
, &uid
, &gid
, NULL
, NULL
);
1941 log_unit_error_errno(UNIT(s
), r
, "Failed to resolve user %s: %m", user
);
1946 if (!isempty(s
->group
)) {
1947 const char *group
= s
->group
;
1949 r
= get_group_creds(&group
, &gid
);
1951 log_unit_error_errno(UNIT(s
), r
, "Failed to resolve group %s: %m", group
);
1956 LIST_FOREACH(port
, p
, s
->ports
) {
1957 const char *path
= NULL
;
1959 if (p
->type
== SOCKET_SOCKET
)
1960 path
= socket_address_get_path(&p
->address
);
1961 else if (p
->type
== SOCKET_FIFO
)
1967 if (chown(path
, uid
, gid
) < 0) {
1968 log_unit_error_errno(UNIT(s
), errno
, "Failed to chown(): %m");
1973 _exit(EXIT_SUCCESS
);
1976 r
= unit_watch_pid(UNIT(s
), pid
);
1984 s
->timer_event_source
= sd_event_source_unref(s
->timer_event_source
);
1988 static void socket_enter_dead(Socket
*s
, SocketResult f
) {
1991 if (s
->result
== SOCKET_SUCCESS
)
1994 if (s
->result
!= SOCKET_SUCCESS
)
1995 log_unit_warning(UNIT(s
), "Failed with result '%s'.", socket_result_to_string(s
->result
));
1997 socket_set_state(s
, s
->result
!= SOCKET_SUCCESS
? SOCKET_FAILED
: SOCKET_DEAD
);
1999 exec_runtime_destroy(s
->exec_runtime
);
2000 s
->exec_runtime
= exec_runtime_unref(s
->exec_runtime
);
2002 exec_context_destroy_runtime_directory(&s
->exec_context
, UNIT(s
)->manager
->prefix
[EXEC_DIRECTORY_RUNTIME
]);
2004 unit_unref_uid_gid(UNIT(s
), true);
2006 dynamic_creds_destroy(&s
->dynamic_creds
);
2009 static void socket_enter_signal(Socket
*s
, SocketState state
, SocketResult f
);
2011 static void socket_enter_stop_post(Socket
*s
, SocketResult f
) {
2015 if (s
->result
== SOCKET_SUCCESS
)
2018 socket_unwatch_control_pid(s
);
2019 s
->control_command_id
= SOCKET_EXEC_STOP_POST
;
2020 s
->control_command
= s
->exec_command
[SOCKET_EXEC_STOP_POST
];
2022 if (s
->control_command
) {
2023 r
= socket_spawn(s
, s
->control_command
, &s
->control_pid
);
2027 socket_set_state(s
, SOCKET_STOP_POST
);
2029 socket_enter_signal(s
, SOCKET_FINAL_SIGTERM
, SOCKET_SUCCESS
);
2034 log_unit_warning_errno(UNIT(s
), r
, "Failed to run 'stop-post' task: %m");
2035 socket_enter_signal(s
, SOCKET_FINAL_SIGTERM
, SOCKET_FAILURE_RESOURCES
);
2038 static void socket_enter_signal(Socket
*s
, SocketState state
, SocketResult f
) {
2043 if (s
->result
== SOCKET_SUCCESS
)
2046 r
= unit_kill_context(
2049 !IN_SET(state
, SOCKET_STOP_PRE_SIGTERM
, SOCKET_FINAL_SIGTERM
) ?
2050 KILL_KILL
: KILL_TERMINATE
,
2058 r
= socket_arm_timer(s
, usec_add(now(CLOCK_MONOTONIC
), s
->timeout_usec
));
2062 socket_set_state(s
, state
);
2063 } else if (state
== SOCKET_STOP_PRE_SIGTERM
)
2064 socket_enter_signal(s
, SOCKET_STOP_PRE_SIGKILL
, SOCKET_SUCCESS
);
2065 else if (state
== SOCKET_STOP_PRE_SIGKILL
)
2066 socket_enter_stop_post(s
, SOCKET_SUCCESS
);
2067 else if (state
== SOCKET_FINAL_SIGTERM
)
2068 socket_enter_signal(s
, SOCKET_FINAL_SIGKILL
, SOCKET_SUCCESS
);
2070 socket_enter_dead(s
, SOCKET_SUCCESS
);
2075 log_unit_warning_errno(UNIT(s
), r
, "Failed to kill processes: %m");
2077 if (IN_SET(state
, SOCKET_STOP_PRE_SIGTERM
, SOCKET_STOP_PRE_SIGKILL
))
2078 socket_enter_stop_post(s
, SOCKET_FAILURE_RESOURCES
);
2080 socket_enter_dead(s
, SOCKET_FAILURE_RESOURCES
);
2083 static void socket_enter_stop_pre(Socket
*s
, SocketResult f
) {
2087 if (s
->result
== SOCKET_SUCCESS
)
2090 socket_unwatch_control_pid(s
);
2091 s
->control_command_id
= SOCKET_EXEC_STOP_PRE
;
2092 s
->control_command
= s
->exec_command
[SOCKET_EXEC_STOP_PRE
];
2094 if (s
->control_command
) {
2095 r
= socket_spawn(s
, s
->control_command
, &s
->control_pid
);
2099 socket_set_state(s
, SOCKET_STOP_PRE
);
2101 socket_enter_stop_post(s
, SOCKET_SUCCESS
);
2106 log_unit_warning_errno(UNIT(s
), r
, "Failed to run 'stop-pre' task: %m");
2107 socket_enter_stop_post(s
, SOCKET_FAILURE_RESOURCES
);
2110 static void socket_enter_listening(Socket
*s
) {
2114 r
= socket_watch_fds(s
);
2116 log_unit_warning_errno(UNIT(s
), r
, "Failed to watch sockets: %m");
2120 socket_set_state(s
, SOCKET_LISTENING
);
2124 socket_enter_stop_pre(s
, SOCKET_FAILURE_RESOURCES
);
2127 static void socket_enter_start_post(Socket
*s
) {
2131 socket_unwatch_control_pid(s
);
2132 s
->control_command_id
= SOCKET_EXEC_START_POST
;
2133 s
->control_command
= s
->exec_command
[SOCKET_EXEC_START_POST
];
2135 if (s
->control_command
) {
2136 r
= socket_spawn(s
, s
->control_command
, &s
->control_pid
);
2138 log_unit_warning_errno(UNIT(s
), r
, "Failed to run 'start-post' task: %m");
2142 socket_set_state(s
, SOCKET_START_POST
);
2144 socket_enter_listening(s
);
2149 socket_enter_stop_pre(s
, SOCKET_FAILURE_RESOURCES
);
2152 static void socket_enter_start_chown(Socket
*s
) {
2157 r
= socket_open_fds(s
);
2159 log_unit_warning_errno(UNIT(s
), r
, "Failed to listen on sockets: %m");
2163 if (!isempty(s
->user
) || !isempty(s
->group
)) {
2165 socket_unwatch_control_pid(s
);
2166 s
->control_command_id
= SOCKET_EXEC_START_CHOWN
;
2167 s
->control_command
= NULL
;
2169 r
= socket_chown(s
, &s
->control_pid
);
2171 log_unit_warning_errno(UNIT(s
), r
, "Failed to fork 'start-chown' task: %m");
2175 socket_set_state(s
, SOCKET_START_CHOWN
);
2177 socket_enter_start_post(s
);
2182 socket_enter_stop_pre(s
, SOCKET_FAILURE_RESOURCES
);
2185 static void socket_enter_start_pre(Socket
*s
) {
2189 socket_unwatch_control_pid(s
);
2191 unit_warn_leftover_processes(UNIT(s
));
2193 s
->control_command_id
= SOCKET_EXEC_START_PRE
;
2194 s
->control_command
= s
->exec_command
[SOCKET_EXEC_START_PRE
];
2196 if (s
->control_command
) {
2197 r
= socket_spawn(s
, s
->control_command
, &s
->control_pid
);
2199 log_unit_warning_errno(UNIT(s
), r
, "Failed to run 'start-pre' task: %m");
2203 socket_set_state(s
, SOCKET_START_PRE
);
2205 socket_enter_start_chown(s
);
2210 socket_enter_dead(s
, SOCKET_FAILURE_RESOURCES
);
2213 static void flush_ports(Socket
*s
) {
2216 /* Flush all incoming traffic, regardless if actual bytes or new connections, so that this socket isn't busy
2219 LIST_FOREACH(port
, p
, s
->ports
) {
2223 (void) flush_accept(p
->fd
);
2224 (void) flush_fd(p
->fd
);
2228 static void socket_enter_running(Socket
*s
, int cfd
) {
2229 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
2232 /* Note that this call takes possession of the connection fd passed. It either has to assign it somewhere or
2237 /* We don't take connections anymore if we are supposed to shut down anyway */
2238 if (unit_stop_pending(UNIT(s
))) {
2240 log_unit_debug(UNIT(s
), "Suppressing connection request since unit stop is scheduled.");
2243 cfd
= safe_close(cfd
);
2250 if (!ratelimit_test(&s
->trigger_limit
)) {
2252 log_unit_warning(UNIT(s
), "Trigger limit hit, refusing further activation.");
2253 socket_enter_stop_pre(s
, SOCKET_FAILURE_TRIGGER_LIMIT_HIT
);
2258 bool pending
= false;
2263 /* If there's already a start pending don't bother to
2265 HASHMAP_FOREACH_KEY(v
, other
, UNIT(s
)->dependencies
[UNIT_TRIGGERS
], i
)
2266 if (unit_active_or_pending(other
)) {
2272 if (!UNIT_ISSET(s
->service
)) {
2273 log_unit_error(UNIT(s
), "Service to activate vanished, refusing activation.");
2278 r
= manager_add_job(UNIT(s
)->manager
, JOB_START
, UNIT_DEREF(s
->service
), JOB_REPLACE
, &error
, NULL
);
2283 socket_set_state(s
, SOCKET_RUNNING
);
2285 _cleanup_free_
char *prefix
= NULL
, *instance
= NULL
, *name
= NULL
;
2286 _cleanup_(socket_peer_unrefp
) SocketPeer
*p
= NULL
;
2289 if (s
->n_connections
>= s
->max_connections
) {
2290 log_unit_warning(UNIT(s
), "Too many incoming connections (%u), dropping connection.",
2296 if (s
->max_connections_per_source
> 0) {
2297 r
= socket_acquire_peer(s
, cfd
, &p
);
2301 } else if (r
> 0 && p
->n_ref
> s
->max_connections_per_source
) {
2302 _cleanup_free_
char *t
= NULL
;
2304 (void) sockaddr_pretty(&p
->peer
.sa
, p
->peer_salen
, true, false, &t
);
2306 log_unit_warning(UNIT(s
),
2307 "Too many incoming connections (%u) from source %s, dropping connection.",
2308 p
->n_ref
, strnull(t
));
2314 r
= socket_instantiate_service(s
);
2318 r
= instance_from_socket(cfd
, s
->n_accepted
, &instance
);
2323 /* ENOTCONN is legitimate if TCP RST was received.
2324 * This connection is over, but the socket unit lives on. */
2325 log_unit_debug(UNIT(s
), "Got ENOTCONN on incoming socket, assuming aborted connection attempt, ignoring.");
2330 r
= unit_name_to_prefix(UNIT(s
)->id
, &prefix
);
2334 r
= unit_name_build(prefix
, instance
, ".service", &name
);
2338 r
= unit_add_name(UNIT_DEREF(s
->service
), name
);
2342 service
= SERVICE(UNIT_DEREF(s
->service
));
2343 unit_ref_unset(&s
->service
);
2346 unit_choose_id(UNIT(service
), name
);
2348 r
= service_set_socket_fd(service
, cfd
, s
, s
->selinux_context_from_net
);
2352 cfd
= -1; /* We passed ownership of the fd to the service now. Forget it here. */
2355 service
->peer
= p
; /* Pass ownership of the peer reference */
2358 r
= manager_add_job(UNIT(s
)->manager
, JOB_START
, UNIT(service
), JOB_REPLACE
, &error
, NULL
);
2360 /* We failed to activate the new service, but it still exists. Let's make sure the service
2361 * closes and forgets the connection fd again, immediately. */
2362 service_close_socket_fd(service
);
2366 /* Notify clients about changed counters */
2367 unit_add_to_dbus_queue(UNIT(s
));
2373 log_unit_warning(UNIT(s
), "Failed to queue service startup job (Maybe the service file is missing or not a %s unit?): %s",
2374 cfd
>= 0 ? "template" : "non-template",
2375 bus_error_message(&error
, r
));
2377 socket_enter_stop_pre(s
, SOCKET_FAILURE_RESOURCES
);
2381 static void socket_run_next(Socket
*s
) {
2385 assert(s
->control_command
);
2386 assert(s
->control_command
->command_next
);
2388 socket_unwatch_control_pid(s
);
2390 s
->control_command
= s
->control_command
->command_next
;
2392 r
= socket_spawn(s
, s
->control_command
, &s
->control_pid
);
2399 log_unit_warning_errno(UNIT(s
), r
, "Failed to run next task: %m");
2401 if (s
->state
== SOCKET_START_POST
)
2402 socket_enter_stop_pre(s
, SOCKET_FAILURE_RESOURCES
);
2403 else if (s
->state
== SOCKET_STOP_POST
)
2404 socket_enter_dead(s
, SOCKET_FAILURE_RESOURCES
);
2406 socket_enter_signal(s
, SOCKET_FINAL_SIGTERM
, SOCKET_FAILURE_RESOURCES
);
2409 static int socket_start(Unit
*u
) {
2410 Socket
*s
= SOCKET(u
);
2415 /* We cannot fulfill this request right now, try again later
2417 if (IN_SET(s
->state
,
2419 SOCKET_STOP_PRE_SIGKILL
,
2420 SOCKET_STOP_PRE_SIGTERM
,
2422 SOCKET_FINAL_SIGTERM
,
2423 SOCKET_FINAL_SIGKILL
))
2426 /* Already on it! */
2427 if (IN_SET(s
->state
,
2433 /* Cannot run this without the service being around */
2434 if (UNIT_ISSET(s
->service
)) {
2437 service
= SERVICE(UNIT_DEREF(s
->service
));
2439 if (UNIT(service
)->load_state
!= UNIT_LOADED
) {
2440 log_unit_error(u
, "Socket service %s not loaded, refusing.", UNIT(service
)->id
);
2444 /* If the service is already active we cannot start the
2446 if (!IN_SET(service
->state
, SERVICE_DEAD
, SERVICE_FAILED
, SERVICE_AUTO_RESTART
)) {
2447 log_unit_error(u
, "Socket service %s already active, refusing.", UNIT(service
)->id
);
2452 assert(IN_SET(s
->state
, SOCKET_DEAD
, SOCKET_FAILED
));
2454 r
= unit_start_limit_test(u
);
2456 socket_enter_dead(s
, SOCKET_FAILURE_START_LIMIT_HIT
);
2460 r
= unit_acquire_invocation_id(u
);
2464 s
->result
= SOCKET_SUCCESS
;
2466 u
->reset_accounting
= true;
2468 socket_enter_start_pre(s
);
2472 static int socket_stop(Unit
*u
) {
2473 Socket
*s
= SOCKET(u
);
2478 if (IN_SET(s
->state
,
2480 SOCKET_STOP_PRE_SIGTERM
,
2481 SOCKET_STOP_PRE_SIGKILL
,
2483 SOCKET_FINAL_SIGTERM
,
2484 SOCKET_FINAL_SIGKILL
))
2487 /* If there's already something running we go directly into
2489 if (IN_SET(s
->state
,
2492 SOCKET_START_POST
)) {
2493 socket_enter_signal(s
, SOCKET_STOP_PRE_SIGTERM
, SOCKET_SUCCESS
);
2497 assert(IN_SET(s
->state
, SOCKET_LISTENING
, SOCKET_RUNNING
));
2499 socket_enter_stop_pre(s
, SOCKET_SUCCESS
);
2503 static int socket_serialize(Unit
*u
, FILE *f
, FDSet
*fds
) {
2504 Socket
*s
= SOCKET(u
);
2512 unit_serialize_item(u
, f
, "state", socket_state_to_string(s
->state
));
2513 unit_serialize_item(u
, f
, "result", socket_result_to_string(s
->result
));
2514 unit_serialize_item_format(u
, f
, "n-accepted", "%u", s
->n_accepted
);
2516 if (s
->control_pid
> 0)
2517 unit_serialize_item_format(u
, f
, "control-pid", PID_FMT
, s
->control_pid
);
2519 if (s
->control_command_id
>= 0)
2520 unit_serialize_item(u
, f
, "control-command", socket_exec_command_to_string(s
->control_command_id
));
2522 LIST_FOREACH(port
, p
, s
->ports
) {
2528 copy
= fdset_put_dup(fds
, p
->fd
);
2532 if (p
->type
== SOCKET_SOCKET
) {
2533 _cleanup_free_
char *t
= NULL
;
2535 r
= socket_address_print(&p
->address
, &t
);
2539 if (socket_address_family(&p
->address
) == AF_NETLINK
)
2540 unit_serialize_item_format(u
, f
, "netlink", "%i %s", copy
, t
);
2542 unit_serialize_item_format(u
, f
, "socket", "%i %i %s", copy
, p
->address
.type
, t
);
2544 } else if (p
->type
== SOCKET_SPECIAL
)
2545 unit_serialize_item_format(u
, f
, "special", "%i %s", copy
, p
->path
);
2546 else if (p
->type
== SOCKET_MQUEUE
)
2547 unit_serialize_item_format(u
, f
, "mqueue", "%i %s", copy
, p
->path
);
2548 else if (p
->type
== SOCKET_USB_FUNCTION
)
2549 unit_serialize_item_format(u
, f
, "ffs", "%i %s", copy
, p
->path
);
2551 assert(p
->type
== SOCKET_FIFO
);
2552 unit_serialize_item_format(u
, f
, "fifo", "%i %s", copy
, p
->path
);
2559 static void socket_port_take_fd(SocketPort
*p
, FDSet
*fds
, int fd
) {
2561 p
->fd
= fdset_remove(fds
, fd
);
2564 static int socket_deserialize_item(Unit
*u
, const char *key
, const char *value
, FDSet
*fds
) {
2565 Socket
*s
= SOCKET(u
);
2571 if (streq(key
, "state")) {
2574 state
= socket_state_from_string(value
);
2576 log_unit_debug(u
, "Failed to parse state value: %s", value
);
2578 s
->deserialized_state
= state
;
2579 } else if (streq(key
, "result")) {
2582 f
= socket_result_from_string(value
);
2584 log_unit_debug(u
, "Failed to parse result value: %s", value
);
2585 else if (f
!= SOCKET_SUCCESS
)
2588 } else if (streq(key
, "n-accepted")) {
2591 if (safe_atou(value
, &k
) < 0)
2592 log_unit_debug(u
, "Failed to parse n-accepted value: %s", value
);
2595 } else if (streq(key
, "control-pid")) {
2598 if (parse_pid(value
, &pid
) < 0)
2599 log_unit_debug(u
, "Failed to parse control-pid value: %s", value
);
2601 s
->control_pid
= pid
;
2602 } else if (streq(key
, "control-command")) {
2603 SocketExecCommand id
;
2605 id
= socket_exec_command_from_string(value
);
2607 log_unit_debug(u
, "Failed to parse exec-command value: %s", value
);
2609 s
->control_command_id
= id
;
2610 s
->control_command
= s
->exec_command
[id
];
2612 } else if (streq(key
, "fifo")) {
2616 if (sscanf(value
, "%i %n", &fd
, &skip
) < 1 || fd
< 0 || !fdset_contains(fds
, fd
))
2617 log_unit_debug(u
, "Failed to parse fifo value: %s", value
);
2619 LIST_FOREACH(port
, p
, s
->ports
)
2620 if (p
->type
== SOCKET_FIFO
&&
2621 path_equal_or_files_same(p
->path
, value
+skip
, 0)) {
2622 socket_port_take_fd(p
, fds
, fd
);
2626 } else if (streq(key
, "special")) {
2630 if (sscanf(value
, "%i %n", &fd
, &skip
) < 1 || fd
< 0 || !fdset_contains(fds
, fd
))
2631 log_unit_debug(u
, "Failed to parse special value: %s", value
);
2633 LIST_FOREACH(port
, p
, s
->ports
)
2634 if (p
->type
== SOCKET_SPECIAL
&&
2635 path_equal_or_files_same(p
->path
, value
+skip
, 0)) {
2636 socket_port_take_fd(p
, fds
, fd
);
2640 } else if (streq(key
, "mqueue")) {
2644 if (sscanf(value
, "%i %n", &fd
, &skip
) < 1 || fd
< 0 || !fdset_contains(fds
, fd
))
2645 log_unit_debug(u
, "Failed to parse mqueue value: %s", value
);
2647 LIST_FOREACH(port
, p
, s
->ports
)
2648 if (p
->type
== SOCKET_MQUEUE
&&
2649 streq(p
->path
, value
+skip
)) {
2650 socket_port_take_fd(p
, fds
, fd
);
2654 } else if (streq(key
, "socket")) {
2655 int fd
, type
, skip
= 0;
2658 if (sscanf(value
, "%i %i %n", &fd
, &type
, &skip
) < 2 || fd
< 0 || type
< 0 || !fdset_contains(fds
, fd
))
2659 log_unit_debug(u
, "Failed to parse socket value: %s", value
);
2661 LIST_FOREACH(port
, p
, s
->ports
)
2662 if (socket_address_is(&p
->address
, value
+skip
, type
)) {
2663 socket_port_take_fd(p
, fds
, fd
);
2667 } else if (streq(key
, "netlink")) {
2671 if (sscanf(value
, "%i %n", &fd
, &skip
) < 1 || fd
< 0 || !fdset_contains(fds
, fd
))
2672 log_unit_debug(u
, "Failed to parse socket value: %s", value
);
2674 LIST_FOREACH(port
, p
, s
->ports
)
2675 if (socket_address_is_netlink(&p
->address
, value
+skip
)) {
2676 socket_port_take_fd(p
, fds
, fd
);
2680 } else if (streq(key
, "ffs")) {
2684 if (sscanf(value
, "%i %n", &fd
, &skip
) < 1 || fd
< 0 || !fdset_contains(fds
, fd
))
2685 log_unit_debug(u
, "Failed to parse ffs value: %s", value
);
2687 LIST_FOREACH(port
, p
, s
->ports
)
2688 if (p
->type
== SOCKET_USB_FUNCTION
&&
2689 path_equal_or_files_same(p
->path
, value
+skip
, 0)) {
2690 socket_port_take_fd(p
, fds
, fd
);
2695 log_unit_debug(UNIT(s
), "Unknown serialization key: %s", key
);
2700 static void socket_distribute_fds(Unit
*u
, FDSet
*fds
) {
2701 Socket
*s
= SOCKET(u
);
2706 LIST_FOREACH(port
, p
, s
->ports
) {
2710 if (p
->type
!= SOCKET_SOCKET
)
2716 FDSET_FOREACH(fd
, fds
, i
) {
2717 if (socket_address_matches_fd(&p
->address
, fd
)) {
2718 p
->fd
= fdset_remove(fds
, fd
);
2719 s
->deserialized_state
= SOCKET_LISTENING
;
2726 _pure_
static UnitActiveState
socket_active_state(Unit
*u
) {
2729 return state_translation_table
[SOCKET(u
)->state
];
2732 _pure_
static const char *socket_sub_state_to_string(Unit
*u
) {
2735 return socket_state_to_string(SOCKET(u
)->state
);
2738 const char* socket_port_type_to_string(SocketPort
*p
) {
2746 switch (p
->address
.type
) {
2754 case SOCK_SEQPACKET
:
2755 return "SequentialPacket";
2758 if (socket_address_family(&p
->address
) == AF_NETLINK
)
2766 case SOCKET_SPECIAL
:
2770 return "MessageQueue";
2775 case SOCKET_USB_FUNCTION
:
2776 return "USBFunction";
2783 SocketType
socket_port_type_from_string(const char *s
) {
2786 if (STR_IN_SET(t
, "Stream", "Datagram", "SequentialPacket", "Netlink"))
2787 return = SOCKET_SOCKET
;
2788 else if (streq(t
, "Special"))
2789 return = SOCKET_SPECIAL
;
2790 else if (streq(t
, "MessageQueue"))
2791 return = SOCKET_MQUEUE
;
2792 else if (streq(t
, "FIFO"))
2793 return = SOCKET_FIFO
;
2794 else if (streq(t
, "USBFunction"))
2795 return = SOCKET_USB_FUNCTION
;
2797 return _SOCKET_TYPE_INVALID
;
2800 _pure_
static bool socket_check_gc(Unit
*u
) {
2801 Socket
*s
= SOCKET(u
);
2805 return s
->n_connections
> 0;
2808 static int socket_accept_do(Socket
*s
, int fd
) {
2815 cfd
= accept4(fd
, NULL
, NULL
, SOCK_NONBLOCK
);
2829 static int socket_accept_in_cgroup(Socket
*s
, SocketPort
*p
, int fd
) {
2830 _cleanup_close_pair_
int pair
[2] = { -1, -1 };
2838 /* Similar to socket_address_listen_in_cgroup(), but for accept() rathern than socket(): make sure that any
2839 * connection socket is also properly associated with the cgroup. */
2841 if (!IN_SET(p
->address
.sockaddr
.sa
.sa_family
, AF_INET
, AF_INET6
))
2844 r
= bpf_firewall_supported();
2850 if (socketpair(AF_UNIX
, SOCK_SEQPACKET
|SOCK_CLOEXEC
, 0, pair
) < 0)
2851 return log_unit_error_errno(UNIT(s
), errno
, "Failed to create communication channel: %m");
2853 r
= unit_fork_helper_process(UNIT(s
), &pid
);
2855 return log_unit_error_errno(UNIT(s
), r
, "Failed to fork off accept stub process: %m");
2859 pair
[0] = safe_close(pair
[0]);
2861 cfd
= socket_accept_do(s
, fd
);
2863 log_unit_error_errno(UNIT(s
), cfd
, "Failed to accept connection socket: %m");
2864 _exit(EXIT_FAILURE
);
2867 r
= send_one_fd(pair
[1], cfd
, 0);
2869 log_unit_error_errno(UNIT(s
), r
, "Failed to send connection socket to parent: %m");
2870 _exit(EXIT_FAILURE
);
2873 _exit(EXIT_SUCCESS
);
2876 pair
[1] = safe_close(pair
[1]);
2877 cfd
= receive_one_fd(pair
[0], 0);
2879 /* We synchronously wait for the helper, as it shouldn't be slow */
2880 r
= wait_for_terminate_and_warn("accept-cgroup-helper", pid
, false);
2887 return log_unit_error_errno(UNIT(s
), cfd
, "Failed to receive connection socket: %m");
2892 cfd
= socket_accept_do(s
, fd
);
2894 return log_unit_error_errno(UNIT(s
), cfd
, "Failed to accept connection socket: %m");
2899 static int socket_dispatch_io(sd_event_source
*source
, int fd
, uint32_t revents
, void *userdata
) {
2900 SocketPort
*p
= userdata
;
2906 if (p
->socket
->state
!= SOCKET_LISTENING
)
2909 log_unit_debug(UNIT(p
->socket
), "Incoming traffic");
2911 if (revents
!= EPOLLIN
) {
2913 if (revents
& EPOLLHUP
)
2914 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.");
2916 log_unit_error(UNIT(p
->socket
), "Got unexpected poll event (0x%x) on socket.", revents
);
2920 if (p
->socket
->accept
&&
2921 p
->type
== SOCKET_SOCKET
&&
2922 socket_address_can_accept(&p
->address
)) {
2924 cfd
= socket_accept_in_cgroup(p
->socket
, p
, fd
);
2928 socket_apply_socket_options(p
->socket
, cfd
);
2931 socket_enter_running(p
->socket
, cfd
);
2935 socket_enter_stop_pre(p
->socket
, SOCKET_FAILURE_RESOURCES
);
2939 static void socket_sigchld_event(Unit
*u
, pid_t pid
, int code
, int status
) {
2940 Socket
*s
= SOCKET(u
);
2946 if (pid
!= s
->control_pid
)
2951 if (is_clean_exit(code
, status
, EXIT_CLEAN_COMMAND
, NULL
))
2953 else if (code
== CLD_EXITED
)
2954 f
= SOCKET_FAILURE_EXIT_CODE
;
2955 else if (code
== CLD_KILLED
)
2956 f
= SOCKET_FAILURE_SIGNAL
;
2957 else if (code
== CLD_DUMPED
)
2958 f
= SOCKET_FAILURE_CORE_DUMP
;
2960 assert_not_reached("Unknown sigchld code");
2962 if (s
->control_command
) {
2963 exec_status_exit(&s
->control_command
->exec_status
, &s
->exec_context
, pid
, code
, status
);
2965 if (s
->control_command
->flags
& EXEC_COMMAND_IGNORE_FAILURE
)
2969 log_unit_full(u
, f
== SOCKET_SUCCESS
? LOG_DEBUG
: LOG_NOTICE
, 0,
2970 "Control process exited, code=%s status=%i",
2971 sigchld_code_to_string(code
), status
);
2973 if (s
->result
== SOCKET_SUCCESS
)
2976 if (s
->control_command
&&
2977 s
->control_command
->command_next
&&
2978 f
== SOCKET_SUCCESS
) {
2980 log_unit_debug(u
, "Running next command for state %s", socket_state_to_string(s
->state
));
2983 s
->control_command
= NULL
;
2984 s
->control_command_id
= _SOCKET_EXEC_COMMAND_INVALID
;
2986 /* No further commands for this step, so let's figure
2987 * out what to do next */
2989 log_unit_debug(u
, "Got final SIGCHLD for state %s", socket_state_to_string(s
->state
));
2993 case SOCKET_START_PRE
:
2994 if (f
== SOCKET_SUCCESS
)
2995 socket_enter_start_chown(s
);
2997 socket_enter_signal(s
, SOCKET_FINAL_SIGTERM
, f
);
3000 case SOCKET_START_CHOWN
:
3001 if (f
== SOCKET_SUCCESS
)
3002 socket_enter_start_post(s
);
3004 socket_enter_stop_pre(s
, f
);
3007 case SOCKET_START_POST
:
3008 if (f
== SOCKET_SUCCESS
)
3009 socket_enter_listening(s
);
3011 socket_enter_stop_pre(s
, f
);
3014 case SOCKET_STOP_PRE
:
3015 case SOCKET_STOP_PRE_SIGTERM
:
3016 case SOCKET_STOP_PRE_SIGKILL
:
3017 socket_enter_stop_post(s
, f
);
3020 case SOCKET_STOP_POST
:
3021 case SOCKET_FINAL_SIGTERM
:
3022 case SOCKET_FINAL_SIGKILL
:
3023 socket_enter_dead(s
, f
);
3027 assert_not_reached("Uh, control process died at wrong time.");
3031 /* Notify clients about changed exit status */
3032 unit_add_to_dbus_queue(u
);
3035 static int socket_dispatch_timer(sd_event_source
*source
, usec_t usec
, void *userdata
) {
3036 Socket
*s
= SOCKET(userdata
);
3039 assert(s
->timer_event_source
== source
);
3043 case SOCKET_START_PRE
:
3044 log_unit_warning(UNIT(s
), "Starting timed out. Terminating.");
3045 socket_enter_signal(s
, SOCKET_FINAL_SIGTERM
, SOCKET_FAILURE_TIMEOUT
);
3048 case SOCKET_START_CHOWN
:
3049 case SOCKET_START_POST
:
3050 log_unit_warning(UNIT(s
), "Starting timed out. Stopping.");
3051 socket_enter_stop_pre(s
, SOCKET_FAILURE_TIMEOUT
);
3054 case SOCKET_STOP_PRE
:
3055 log_unit_warning(UNIT(s
), "Stopping timed out. Terminating.");
3056 socket_enter_signal(s
, SOCKET_STOP_PRE_SIGTERM
, SOCKET_FAILURE_TIMEOUT
);
3059 case SOCKET_STOP_PRE_SIGTERM
:
3060 if (s
->kill_context
.send_sigkill
) {
3061 log_unit_warning(UNIT(s
), "Stopping timed out. Killing.");
3062 socket_enter_signal(s
, SOCKET_STOP_PRE_SIGKILL
, SOCKET_FAILURE_TIMEOUT
);
3064 log_unit_warning(UNIT(s
), "Stopping timed out. Skipping SIGKILL. Ignoring.");
3065 socket_enter_stop_post(s
, SOCKET_FAILURE_TIMEOUT
);
3069 case SOCKET_STOP_PRE_SIGKILL
:
3070 log_unit_warning(UNIT(s
), "Processes still around after SIGKILL. Ignoring.");
3071 socket_enter_stop_post(s
, SOCKET_FAILURE_TIMEOUT
);
3074 case SOCKET_STOP_POST
:
3075 log_unit_warning(UNIT(s
), "Stopping timed out (2). Terminating.");
3076 socket_enter_signal(s
, SOCKET_FINAL_SIGTERM
, SOCKET_FAILURE_TIMEOUT
);
3079 case SOCKET_FINAL_SIGTERM
:
3080 if (s
->kill_context
.send_sigkill
) {
3081 log_unit_warning(UNIT(s
), "Stopping timed out (2). Killing.");
3082 socket_enter_signal(s
, SOCKET_FINAL_SIGKILL
, SOCKET_FAILURE_TIMEOUT
);
3084 log_unit_warning(UNIT(s
), "Stopping timed out (2). Skipping SIGKILL. Ignoring.");
3085 socket_enter_dead(s
, SOCKET_FAILURE_TIMEOUT
);
3089 case SOCKET_FINAL_SIGKILL
:
3090 log_unit_warning(UNIT(s
), "Still around after SIGKILL (2). Entering failed mode.");
3091 socket_enter_dead(s
, SOCKET_FAILURE_TIMEOUT
);
3095 assert_not_reached("Timeout at wrong time.");
3101 int socket_collect_fds(Socket
*s
, int **fds
) {
3102 int *rfds
, k
= 0, n
= 0;
3108 /* Called from the service code for requesting our fds */
3110 LIST_FOREACH(port
, p
, s
->ports
) {
3113 n
+= p
->n_auxiliary_fds
;
3125 LIST_FOREACH(port
, p
, s
->ports
) {
3130 for (i
= 0; i
< p
->n_auxiliary_fds
; ++i
)
3131 rfds
[k
++] = p
->auxiliary_fds
[i
];
3140 static void socket_reset_failed(Unit
*u
) {
3141 Socket
*s
= SOCKET(u
);
3145 if (s
->state
== SOCKET_FAILED
)
3146 socket_set_state(s
, SOCKET_DEAD
);
3148 s
->result
= SOCKET_SUCCESS
;
3151 void socket_connection_unref(Socket
*s
) {
3154 /* The service is dead. Yay!
3156 * This is strictly for one-instance-per-connection
3159 assert(s
->n_connections
> 0);
3162 log_unit_debug(UNIT(s
), "One connection closed, %u left.", s
->n_connections
);
3165 static void socket_trigger_notify(Unit
*u
, Unit
*other
) {
3166 Socket
*s
= SOCKET(u
);
3171 /* Filter out invocations with bogus state */
3172 if (other
->load_state
!= UNIT_LOADED
|| other
->type
!= UNIT_SERVICE
)
3175 /* Don't propagate state changes from the service if we are already down */
3176 if (!IN_SET(s
->state
, SOCKET_RUNNING
, SOCKET_LISTENING
))
3179 /* We don't care for the service state if we are in Accept=yes mode */
3183 /* Propagate start limit hit state */
3184 if (other
->start_limit_hit
) {
3185 socket_enter_stop_pre(s
, SOCKET_FAILURE_SERVICE_START_LIMIT_HIT
);
3189 /* Don't propagate anything if there's still a job queued */
3193 if (IN_SET(SERVICE(other
)->state
,
3194 SERVICE_DEAD
, SERVICE_FAILED
,
3195 SERVICE_FINAL_SIGTERM
, SERVICE_FINAL_SIGKILL
,
3196 SERVICE_AUTO_RESTART
))
3197 socket_enter_listening(s
);
3199 if (SERVICE(other
)->state
== SERVICE_RUNNING
)
3200 socket_set_state(s
, SOCKET_RUNNING
);
3203 static int socket_kill(Unit
*u
, KillWho who
, int signo
, sd_bus_error
*error
) {
3204 return unit_kill_common(u
, who
, signo
, -1, SOCKET(u
)->control_pid
, error
);
3207 static int socket_get_timeout(Unit
*u
, usec_t
*timeout
) {
3208 Socket
*s
= SOCKET(u
);
3212 if (!s
->timer_event_source
)
3215 r
= sd_event_source_get_time(s
->timer_event_source
, &t
);
3218 if (t
== USEC_INFINITY
)
3225 char *socket_fdname(Socket
*s
) {
3228 /* Returns the name to use for $LISTEN_NAMES. If the user
3229 * didn't specify anything specifically, use the socket unit's
3230 * name as fallback. */
3238 static int socket_control_pid(Unit
*u
) {
3239 Socket
*s
= SOCKET(u
);
3243 return s
->control_pid
;
3246 static const char* const socket_exec_command_table
[_SOCKET_EXEC_COMMAND_MAX
] = {
3247 [SOCKET_EXEC_START_PRE
] = "ExecStartPre",
3248 [SOCKET_EXEC_START_CHOWN
] = "ExecStartChown",
3249 [SOCKET_EXEC_START_POST
] = "ExecStartPost",
3250 [SOCKET_EXEC_STOP_PRE
] = "ExecStopPre",
3251 [SOCKET_EXEC_STOP_POST
] = "ExecStopPost"
3254 DEFINE_STRING_TABLE_LOOKUP(socket_exec_command
, SocketExecCommand
);
3256 static const char* const socket_result_table
[_SOCKET_RESULT_MAX
] = {
3257 [SOCKET_SUCCESS
] = "success",
3258 [SOCKET_FAILURE_RESOURCES
] = "resources",
3259 [SOCKET_FAILURE_TIMEOUT
] = "timeout",
3260 [SOCKET_FAILURE_EXIT_CODE
] = "exit-code",
3261 [SOCKET_FAILURE_SIGNAL
] = "signal",
3262 [SOCKET_FAILURE_CORE_DUMP
] = "core-dump",
3263 [SOCKET_FAILURE_START_LIMIT_HIT
] = "start-limit-hit",
3264 [SOCKET_FAILURE_TRIGGER_LIMIT_HIT
] = "trigger-limit-hit",
3265 [SOCKET_FAILURE_SERVICE_START_LIMIT_HIT
] = "service-start-limit-hit"
3268 DEFINE_STRING_TABLE_LOOKUP(socket_result
, SocketResult
);
3270 const UnitVTable socket_vtable
= {
3271 .object_size
= sizeof(Socket
),
3272 .exec_context_offset
= offsetof(Socket
, exec_context
),
3273 .cgroup_context_offset
= offsetof(Socket
, cgroup_context
),
3274 .kill_context_offset
= offsetof(Socket
, kill_context
),
3275 .exec_runtime_offset
= offsetof(Socket
, exec_runtime
),
3276 .dynamic_creds_offset
= offsetof(Socket
, dynamic_creds
),
3282 .private_section
= "Socket",
3284 .init
= socket_init
,
3285 .done
= socket_done
,
3286 .load
= socket_load
,
3288 .coldplug
= socket_coldplug
,
3290 .dump
= socket_dump
,
3292 .start
= socket_start
,
3293 .stop
= socket_stop
,
3295 .kill
= socket_kill
,
3297 .get_timeout
= socket_get_timeout
,
3299 .serialize
= socket_serialize
,
3300 .deserialize_item
= socket_deserialize_item
,
3301 .distribute_fds
= socket_distribute_fds
,
3303 .active_state
= socket_active_state
,
3304 .sub_state_to_string
= socket_sub_state_to_string
,
3306 .check_gc
= socket_check_gc
,
3308 .sigchld_event
= socket_sigchld_event
,
3310 .trigger_notify
= socket_trigger_notify
,
3312 .reset_failed
= socket_reset_failed
,
3314 .control_pid
= socket_control_pid
,
3316 .bus_vtable
= bus_socket_vtable
,
3317 .bus_set_property
= bus_socket_set_property
,
3318 .bus_commit_properties
= bus_socket_commit_properties
,
3320 .status_message_formats
= {
3321 /*.starting_stopping = {
3322 [0] = "Starting socket %s...",
3323 [1] = "Stopping socket %s...",
3325 .finished_start_job
= {
3326 [JOB_DONE
] = "Listening on %s.",
3327 [JOB_FAILED
] = "Failed to listen on %s.",
3328 [JOB_TIMEOUT
] = "Timed out starting %s.",
3330 .finished_stop_job
= {
3331 [JOB_DONE
] = "Closed %s.",
3332 [JOB_FAILED
] = "Failed stopping %s.",
3333 [JOB_TIMEOUT
] = "Timed out stopping %s.",