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"
56 #include "socket-protocol-list.h"
58 #include "string-table.h"
59 #include "string-util.h"
61 #include "unit-name.h"
63 #include "user-util.h"
69 union sockaddr_union peer
;
73 static const UnitActiveState state_translation_table
[_SOCKET_STATE_MAX
] = {
74 [SOCKET_DEAD
] = UNIT_INACTIVE
,
75 [SOCKET_START_PRE
] = UNIT_ACTIVATING
,
76 [SOCKET_START_CHOWN
] = UNIT_ACTIVATING
,
77 [SOCKET_START_POST
] = UNIT_ACTIVATING
,
78 [SOCKET_LISTENING
] = UNIT_ACTIVE
,
79 [SOCKET_RUNNING
] = UNIT_ACTIVE
,
80 [SOCKET_STOP_PRE
] = UNIT_DEACTIVATING
,
81 [SOCKET_STOP_PRE_SIGTERM
] = UNIT_DEACTIVATING
,
82 [SOCKET_STOP_PRE_SIGKILL
] = UNIT_DEACTIVATING
,
83 [SOCKET_STOP_POST
] = UNIT_DEACTIVATING
,
84 [SOCKET_FINAL_SIGTERM
] = UNIT_DEACTIVATING
,
85 [SOCKET_FINAL_SIGKILL
] = UNIT_DEACTIVATING
,
86 [SOCKET_FAILED
] = UNIT_FAILED
89 static int socket_dispatch_io(sd_event_source
*source
, int fd
, uint32_t revents
, void *userdata
);
90 static int socket_dispatch_timer(sd_event_source
*source
, usec_t usec
, void *userdata
);
92 static void socket_init(Unit
*u
) {
93 Socket
*s
= SOCKET(u
);
96 assert(u
->load_state
== UNIT_STUB
);
98 s
->backlog
= SOMAXCONN
;
99 s
->timeout_usec
= u
->manager
->default_timeout_start_usec
;
100 s
->directory_mode
= 0755;
101 s
->socket_mode
= 0666;
103 s
->max_connections
= 64;
110 s
->exec_context
.std_output
= u
->manager
->default_std_output
;
111 s
->exec_context
.std_error
= u
->manager
->default_std_error
;
113 s
->control_command_id
= _SOCKET_EXEC_COMMAND_INVALID
;
115 s
->trigger_limit
.interval
= USEC_INFINITY
;
116 s
->trigger_limit
.burst
= (unsigned) -1;
119 static void socket_unwatch_control_pid(Socket
*s
) {
122 if (s
->control_pid
<= 0)
125 unit_unwatch_pid(UNIT(s
), s
->control_pid
);
129 static void socket_cleanup_fd_list(SocketPort
*p
) {
132 close_many(p
->auxiliary_fds
, p
->n_auxiliary_fds
);
133 p
->auxiliary_fds
= mfree(p
->auxiliary_fds
);
134 p
->n_auxiliary_fds
= 0;
137 void socket_free_ports(Socket
*s
) {
142 while ((p
= s
->ports
)) {
143 LIST_REMOVE(port
, s
->ports
, p
);
145 sd_event_source_unref(p
->event_source
);
147 socket_cleanup_fd_list(p
);
154 static void socket_done(Unit
*u
) {
155 Socket
*s
= SOCKET(u
);
160 socket_free_ports(s
);
162 while ((p
= set_steal_first(s
->peers_by_address
)))
165 s
->peers_by_address
= set_free(s
->peers_by_address
);
167 s
->exec_runtime
= exec_runtime_unref(s
->exec_runtime
, false);
168 exec_command_free_array(s
->exec_command
, _SOCKET_EXEC_COMMAND_MAX
);
169 s
->control_command
= NULL
;
171 dynamic_creds_unref(&s
->dynamic_creds
);
173 socket_unwatch_control_pid(s
);
175 unit_ref_unset(&s
->service
);
177 s
->tcp_congestion
= mfree(s
->tcp_congestion
);
178 s
->bind_to_device
= mfree(s
->bind_to_device
);
180 s
->smack
= mfree(s
->smack
);
181 s
->smack_ip_in
= mfree(s
->smack_ip_in
);
182 s
->smack_ip_out
= mfree(s
->smack_ip_out
);
184 strv_free(s
->symlinks
);
186 s
->user
= mfree(s
->user
);
187 s
->group
= mfree(s
->group
);
189 s
->fdname
= mfree(s
->fdname
);
191 s
->timer_event_source
= sd_event_source_unref(s
->timer_event_source
);
194 static int socket_arm_timer(Socket
*s
, usec_t usec
) {
199 if (s
->timer_event_source
) {
200 r
= sd_event_source_set_time(s
->timer_event_source
, usec
);
204 return sd_event_source_set_enabled(s
->timer_event_source
, SD_EVENT_ONESHOT
);
207 if (usec
== USEC_INFINITY
)
210 r
= sd_event_add_time(
211 UNIT(s
)->manager
->event
,
212 &s
->timer_event_source
,
215 socket_dispatch_timer
, s
);
219 (void) sd_event_source_set_description(s
->timer_event_source
, "socket-timer");
224 int socket_instantiate_service(Socket
*s
) {
225 _cleanup_free_
char *prefix
= NULL
, *name
= NULL
;
231 /* This fills in s->service if it isn't filled in yet. For
232 * Accept=yes sockets we create the next connection service
233 * here. For Accept=no this is mostly a NOP since the service
234 * is figured out at load time anyway. */
236 if (UNIT_DEREF(s
->service
))
242 r
= unit_name_to_prefix(UNIT(s
)->id
, &prefix
);
246 if (asprintf(&name
, "%s@%u.service", prefix
, s
->n_accepted
) < 0)
249 r
= manager_load_unit(UNIT(s
)->manager
, name
, NULL
, NULL
, &u
);
253 unit_ref_set(&s
->service
, UNIT(s
), u
);
255 return unit_add_two_dependencies(UNIT(s
), UNIT_BEFORE
, UNIT_TRIGGERS
, u
, false, UNIT_DEPENDENCY_IMPLICIT
);
258 static bool have_non_accept_socket(Socket
*s
) {
266 LIST_FOREACH(port
, p
, s
->ports
) {
268 if (p
->type
!= SOCKET_SOCKET
)
271 if (!socket_address_can_accept(&p
->address
))
278 static int socket_add_mount_dependencies(Socket
*s
) {
284 LIST_FOREACH(port
, p
, s
->ports
) {
285 const char *path
= NULL
;
287 if (p
->type
== SOCKET_SOCKET
)
288 path
= socket_address_get_path(&p
->address
);
289 else if (IN_SET(p
->type
, SOCKET_FIFO
, SOCKET_SPECIAL
, SOCKET_USB_FUNCTION
))
295 r
= unit_require_mounts_for(UNIT(s
), path
, UNIT_DEPENDENCY_FILE
);
303 static int socket_add_device_dependencies(Socket
*s
) {
308 if (!s
->bind_to_device
|| streq(s
->bind_to_device
, "lo"))
311 t
= strjoina("/sys/subsystem/net/devices/", s
->bind_to_device
);
312 return unit_add_node_dependency(UNIT(s
), t
, false, UNIT_BINDS_TO
, UNIT_DEPENDENCY_FILE
);
315 static int socket_add_default_dependencies(Socket
*s
) {
319 if (!UNIT(s
)->default_dependencies
)
322 r
= unit_add_dependency_by_name(UNIT(s
), UNIT_BEFORE
, SPECIAL_SOCKETS_TARGET
, NULL
, true, UNIT_DEPENDENCY_DEFAULT
);
326 if (MANAGER_IS_SYSTEM(UNIT(s
)->manager
)) {
327 r
= unit_add_two_dependencies_by_name(UNIT(s
), UNIT_AFTER
, UNIT_REQUIRES
, SPECIAL_SYSINIT_TARGET
, NULL
, true, UNIT_DEPENDENCY_DEFAULT
);
332 return unit_add_two_dependencies_by_name(UNIT(s
), UNIT_BEFORE
, UNIT_CONFLICTS
, SPECIAL_SHUTDOWN_TARGET
, NULL
, true, UNIT_DEPENDENCY_DEFAULT
);
335 _pure_
static bool socket_has_exec(Socket
*s
) {
339 for (i
= 0; i
< _SOCKET_EXEC_COMMAND_MAX
; i
++)
340 if (s
->exec_command
[i
])
346 static int socket_add_extras(Socket
*s
) {
352 /* Pick defaults for the trigger limit, if nothing was explicitly configured. We pick a relatively high limit
353 * in Accept=yes mode, and a lower limit for Accept=no. Reason: in Accept=yes mode we are invoking accept()
354 * ourselves before the trigger limit can hit, thus incoming connections are taken off the socket queue quickly
355 * and reliably. This is different for Accept=no, where the spawned service has to take the incoming traffic
356 * off the queues, which it might not necessarily do. Moreover, while Accept=no services are supposed to
357 * process whatever is queued in one go, and thus should normally never have to be started frequently. This is
358 * different for Accept=yes where each connection is processed by a new service instance, and thus frequent
359 * service starts are typical. */
361 if (s
->trigger_limit
.interval
== USEC_INFINITY
)
362 s
->trigger_limit
.interval
= 2 * USEC_PER_SEC
;
364 if (s
->trigger_limit
.burst
== (unsigned) -1) {
366 s
->trigger_limit
.burst
= 200;
368 s
->trigger_limit
.burst
= 20;
371 if (have_non_accept_socket(s
)) {
373 if (!UNIT_DEREF(s
->service
)) {
376 r
= unit_load_related_unit(u
, ".service", &x
);
380 unit_ref_set(&s
->service
, u
, x
);
383 r
= unit_add_two_dependencies(u
, UNIT_BEFORE
, UNIT_TRIGGERS
, UNIT_DEREF(s
->service
), true, UNIT_DEPENDENCY_IMPLICIT
);
388 r
= socket_add_mount_dependencies(s
);
392 r
= socket_add_device_dependencies(s
);
396 r
= unit_patch_contexts(u
);
400 if (socket_has_exec(s
)) {
401 r
= unit_add_exec_dependencies(u
, &s
->exec_context
);
406 r
= unit_set_default_slice(u
);
410 r
= socket_add_default_dependencies(s
);
417 static const char *socket_find_symlink_target(Socket
*s
) {
418 const char *found
= NULL
;
421 LIST_FOREACH(port
, p
, s
->ports
) {
422 const char *f
= NULL
;
431 f
= socket_address_get_path(&p
->address
);
449 static int socket_verify(Socket
*s
) {
452 if (UNIT(s
)->load_state
!= UNIT_LOADED
)
456 log_unit_error(UNIT(s
), "Unit has no Listen setting (ListenStream=, ListenDatagram=, ListenFIFO=, ...). Refusing.");
460 if (s
->accept
&& have_non_accept_socket(s
)) {
461 log_unit_error(UNIT(s
), "Unit configured for accepting sockets, but sockets are non-accepting. Refusing.");
465 if (s
->accept
&& s
->max_connections
<= 0) {
466 log_unit_error(UNIT(s
), "MaxConnection= setting too small. Refusing.");
470 if (s
->accept
&& UNIT_DEREF(s
->service
)) {
471 log_unit_error(UNIT(s
), "Explicit service configuration for accepting socket units not supported. Refusing.");
475 if (s
->exec_context
.pam_name
&& s
->kill_context
.kill_mode
!= KILL_CONTROL_GROUP
) {
476 log_unit_error(UNIT(s
), "Unit has PAM enabled. Kill mode must be set to 'control-group'. Refusing.");
480 if (!strv_isempty(s
->symlinks
) && !socket_find_symlink_target(s
)) {
481 log_unit_error(UNIT(s
), "Unit has symlinks set but none or more than one node in the file system. Refusing.");
488 static void peer_address_hash_func(const void *p
, struct siphash
*state
) {
489 const SocketPeer
*s
= p
;
493 if (s
->peer
.sa
.sa_family
== AF_INET
)
494 siphash24_compress(&s
->peer
.in
.sin_addr
, sizeof(s
->peer
.in
.sin_addr
), state
);
495 else if (s
->peer
.sa
.sa_family
== AF_INET6
)
496 siphash24_compress(&s
->peer
.in6
.sin6_addr
, sizeof(s
->peer
.in6
.sin6_addr
), state
);
497 else if (s
->peer
.sa
.sa_family
== AF_VSOCK
)
498 siphash24_compress(&s
->peer
.vm
.svm_cid
, sizeof(s
->peer
.vm
.svm_cid
), state
);
500 assert_not_reached("Unknown address family.");
503 static int peer_address_compare_func(const void *a
, const void *b
) {
504 const SocketPeer
*x
= a
, *y
= b
;
506 if (x
->peer
.sa
.sa_family
< y
->peer
.sa
.sa_family
)
508 if (x
->peer
.sa
.sa_family
> y
->peer
.sa
.sa_family
)
511 switch(x
->peer
.sa
.sa_family
) {
513 return memcmp(&x
->peer
.in
.sin_addr
, &y
->peer
.in
.sin_addr
, sizeof(x
->peer
.in
.sin_addr
));
515 return memcmp(&x
->peer
.in6
.sin6_addr
, &y
->peer
.in6
.sin6_addr
, sizeof(x
->peer
.in6
.sin6_addr
));
517 if (x
->peer
.vm
.svm_cid
< y
->peer
.vm
.svm_cid
)
519 if (x
->peer
.vm
.svm_cid
> y
->peer
.vm
.svm_cid
)
523 assert_not_reached("Black sheep in the family!");
526 const struct hash_ops peer_address_hash_ops
= {
527 .hash
= peer_address_hash_func
,
528 .compare
= peer_address_compare_func
531 static int socket_load(Unit
*u
) {
532 Socket
*s
= SOCKET(u
);
536 assert(u
->load_state
== UNIT_STUB
);
538 r
= set_ensure_allocated(&s
->peers_by_address
, &peer_address_hash_ops
);
542 r
= unit_load_fragment_and_dropin(u
);
546 if (u
->load_state
== UNIT_LOADED
) {
547 /* This is a new unit? Then let's add in some extras */
548 r
= socket_add_extras(s
);
553 return socket_verify(s
);
556 static SocketPeer
*socket_peer_new(void) {
559 p
= new0(SocketPeer
, 1);
568 SocketPeer
*socket_peer_ref(SocketPeer
*p
) {
572 assert(p
->n_ref
> 0);
578 SocketPeer
*socket_peer_unref(SocketPeer
*p
) {
582 assert(p
->n_ref
> 0);
590 set_remove(p
->socket
->peers_by_address
, p
);
595 int socket_acquire_peer(Socket
*s
, int fd
, SocketPeer
**p
) {
596 _cleanup_(socket_peer_unrefp
) SocketPeer
*remote
= NULL
;
597 SocketPeer sa
= {}, *i
;
598 socklen_t salen
= sizeof(sa
.peer
);
604 r
= getpeername(fd
, &sa
.peer
.sa
, &salen
);
606 return log_error_errno(errno
, "getpeername failed: %m");
608 if (!IN_SET(sa
.peer
.sa
.sa_family
, AF_INET
, AF_INET6
, AF_VSOCK
)) {
613 i
= set_get(s
->peers_by_address
, &sa
);
615 *p
= socket_peer_ref(i
);
619 remote
= socket_peer_new();
623 remote
->peer
= sa
.peer
;
624 remote
->peer_salen
= salen
;
626 r
= set_put(s
->peers_by_address
, remote
);
638 _const_
static const char* listen_lookup(int family
, int type
) {
640 if (family
== AF_NETLINK
)
641 return "ListenNetlink";
643 if (type
== SOCK_STREAM
)
644 return "ListenStream";
645 else if (type
== SOCK_DGRAM
)
646 return "ListenDatagram";
647 else if (type
== SOCK_SEQPACKET
)
648 return "ListenSequentialPacket";
650 assert_not_reached("Unknown socket type");
654 static void socket_dump(Unit
*u
, FILE *f
, const char *prefix
) {
655 char time_string
[FORMAT_TIMESPAN_MAX
];
657 Socket
*s
= SOCKET(u
);
659 const char *prefix2
, *str
;
664 prefix
= strempty(prefix
);
665 prefix2
= strjoina(prefix
, "\t");
668 "%sSocket State: %s\n"
670 "%sBindIPv6Only: %s\n"
672 "%sSocketMode: %04o\n"
673 "%sDirectoryMode: %04o\n"
677 "%sTransparent: %s\n"
679 "%sPassCredentials: %s\n"
680 "%sPassSecurity: %s\n"
681 "%sTCPCongestion: %s\n"
682 "%sRemoveOnStop: %s\n"
684 "%sFileDescriptorName: %s\n"
685 "%sSELinuxContextFromNet: %s\n",
686 prefix
, socket_state_to_string(s
->state
),
687 prefix
, socket_result_to_string(s
->result
),
688 prefix
, socket_address_bind_ipv6_only_to_string(s
->bind_ipv6_only
),
690 prefix
, s
->socket_mode
,
691 prefix
, s
->directory_mode
,
692 prefix
, yes_no(s
->keep_alive
),
693 prefix
, yes_no(s
->no_delay
),
694 prefix
, yes_no(s
->free_bind
),
695 prefix
, yes_no(s
->transparent
),
696 prefix
, yes_no(s
->broadcast
),
697 prefix
, yes_no(s
->pass_cred
),
698 prefix
, yes_no(s
->pass_sec
),
699 prefix
, strna(s
->tcp_congestion
),
700 prefix
, yes_no(s
->remove_on_stop
),
701 prefix
, yes_no(s
->writable
),
702 prefix
, socket_fdname(s
),
703 prefix
, yes_no(s
->selinux_context_from_net
));
705 if (s
->control_pid
> 0)
707 "%sControl PID: "PID_FMT
"\n",
708 prefix
, s
->control_pid
);
710 if (s
->bind_to_device
)
712 "%sBindToDevice: %s\n",
713 prefix
, s
->bind_to_device
);
718 "%sNConnections: %u\n"
719 "%sMaxConnections: %u\n"
720 "%sMaxConnectionsPerSource: %u\n",
721 prefix
, s
->n_accepted
,
722 prefix
, s
->n_connections
,
723 prefix
, s
->max_connections
,
724 prefix
, s
->max_connections_per_source
);
726 if (s
->priority
>= 0)
729 prefix
, s
->priority
);
731 if (s
->receive_buffer
> 0)
733 "%sReceiveBuffer: %zu\n",
734 prefix
, s
->receive_buffer
);
736 if (s
->send_buffer
> 0)
738 "%sSendBuffer: %zu\n",
739 prefix
, s
->send_buffer
);
751 if (s
->pipe_size
> 0)
754 prefix
, s
->pipe_size
);
761 if (s
->mq_maxmsg
> 0)
763 "%sMessageQueueMaxMessages: %li\n",
764 prefix
, s
->mq_maxmsg
);
766 if (s
->mq_msgsize
> 0)
768 "%sMessageQueueMessageSize: %li\n",
769 prefix
, s
->mq_msgsize
);
774 prefix
, yes_no(s
->reuse_port
));
778 "%sSmackLabel: %s\n",
783 "%sSmackLabelIPIn: %s\n",
784 prefix
, s
->smack_ip_in
);
788 "%sSmackLabelIPOut: %s\n",
789 prefix
, s
->smack_ip_out
);
791 if (!isempty(s
->user
) || !isempty(s
->group
))
794 "%sSocketGroup: %s\n",
795 prefix
, strna(s
->user
),
796 prefix
, strna(s
->group
));
798 if (s
->keep_alive_time
> 0)
800 "%sKeepAliveTimeSec: %s\n",
801 prefix
, format_timespan(time_string
, FORMAT_TIMESPAN_MAX
, s
->keep_alive_time
, USEC_PER_SEC
));
803 if (s
->keep_alive_interval
)
805 "%sKeepAliveIntervalSec: %s\n",
806 prefix
, format_timespan(time_string
, FORMAT_TIMESPAN_MAX
, s
->keep_alive_interval
, USEC_PER_SEC
));
808 if (s
->keep_alive_cnt
)
810 "%sKeepAliveProbes: %u\n",
811 prefix
, s
->keep_alive_cnt
);
815 "%sDeferAcceptSec: %s\n",
816 prefix
, format_timespan(time_string
, FORMAT_TIMESPAN_MAX
, s
->defer_accept
, USEC_PER_SEC
));
818 LIST_FOREACH(port
, p
, s
->ports
) {
820 if (p
->type
== SOCKET_SOCKET
) {
825 r
= socket_address_print(&p
->address
, &k
);
831 fprintf(f
, "%s%s: %s\n", prefix
, listen_lookup(socket_address_family(&p
->address
), p
->address
.type
), t
);
833 } else if (p
->type
== SOCKET_SPECIAL
)
834 fprintf(f
, "%sListenSpecial: %s\n", prefix
, p
->path
);
835 else if (p
->type
== SOCKET_USB_FUNCTION
)
836 fprintf(f
, "%sListenUSBFunction: %s\n", prefix
, p
->path
);
837 else if (p
->type
== SOCKET_MQUEUE
)
838 fprintf(f
, "%sListenMessageQueue: %s\n", prefix
, p
->path
);
840 fprintf(f
, "%sListenFIFO: %s\n", prefix
, p
->path
);
844 "%sTriggerLimitIntervalSec: %s\n"
845 "%sTriggerLimitBurst: %u\n",
846 prefix
, format_timespan(time_string
, FORMAT_TIMESPAN_MAX
, s
->trigger_limit
.interval
, USEC_PER_SEC
),
847 prefix
, s
->trigger_limit
.burst
);
849 str
= socket_protocol_to_name(s
->socket_protocol
);
851 fprintf(f
, "%sSocketProtocol: %s\n", prefix
, str
);
853 if (!strv_isempty(s
->symlinks
)) {
856 fprintf(f
, "%sSymlinks:", prefix
);
857 STRV_FOREACH(q
, s
->symlinks
)
858 fprintf(f
, " %s", *q
);
864 "%sTimeoutSec: %s\n",
865 prefix
, format_timespan(time_string
, FORMAT_TIMESPAN_MAX
, s
->timeout_usec
, USEC_PER_SEC
));
867 exec_context_dump(&s
->exec_context
, f
, prefix
);
868 kill_context_dump(&s
->kill_context
, f
, prefix
);
870 for (c
= 0; c
< _SOCKET_EXEC_COMMAND_MAX
; c
++) {
871 if (!s
->exec_command
[c
])
874 fprintf(f
, "%s-> %s:\n",
875 prefix
, socket_exec_command_to_string(c
));
877 exec_command_dump_list(s
->exec_command
[c
], f
, prefix2
);
880 cgroup_context_dump(&s
->cgroup_context
, f
, prefix
);
883 static int instance_from_socket(int fd
, unsigned nr
, char **instance
) {
886 union sockaddr_union local
, remote
;
892 if (getsockname(fd
, &local
.sa
, &l
) < 0)
896 if (getpeername(fd
, &remote
.sa
, &l
) < 0)
899 switch (local
.sa
.sa_family
) {
903 a
= be32toh(local
.in
.sin_addr
.s_addr
),
904 b
= be32toh(remote
.in
.sin_addr
.s_addr
);
907 "%u-%u.%u.%u.%u:%u-%u.%u.%u.%u:%u",
909 a
>> 24, (a
>> 16) & 0xFF, (a
>> 8) & 0xFF, a
& 0xFF,
910 be16toh(local
.in
.sin_port
),
911 b
>> 24, (b
>> 16) & 0xFF, (b
>> 8) & 0xFF, b
& 0xFF,
912 be16toh(remote
.in
.sin_port
)) < 0)
919 static const unsigned char ipv4_prefix
[] = {
920 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xFF, 0xFF
923 if (memcmp(&local
.in6
.sin6_addr
, ipv4_prefix
, sizeof(ipv4_prefix
)) == 0 &&
924 memcmp(&remote
.in6
.sin6_addr
, ipv4_prefix
, sizeof(ipv4_prefix
)) == 0) {
926 *a
= local
.in6
.sin6_addr
.s6_addr
+12,
927 *b
= remote
.in6
.sin6_addr
.s6_addr
+12;
930 "%u-%u.%u.%u.%u:%u-%u.%u.%u.%u:%u",
932 a
[0], a
[1], a
[2], a
[3],
933 be16toh(local
.in6
.sin6_port
),
934 b
[0], b
[1], b
[2], b
[3],
935 be16toh(remote
.in6
.sin6_port
)) < 0)
938 char a
[INET6_ADDRSTRLEN
], b
[INET6_ADDRSTRLEN
];
943 inet_ntop(AF_INET6
, &local
.in6
.sin6_addr
, a
, sizeof(a
)),
944 be16toh(local
.in6
.sin6_port
),
945 inet_ntop(AF_INET6
, &remote
.in6
.sin6_addr
, b
, sizeof(b
)),
946 be16toh(remote
.in6
.sin6_port
)) < 0)
957 k
= getpeercred(fd
, &ucred
);
960 "%u-"PID_FMT
"-"UID_FMT
,
961 nr
, ucred
.pid
, ucred
.uid
) < 0)
963 } else if (k
== -ENODATA
) {
964 /* This handles the case where somebody is
965 * connecting from another pid/uid namespace
966 * (e.g. from outside of our container). */
981 local
.vm
.svm_cid
, local
.vm
.svm_port
,
982 remote
.vm
.svm_cid
, remote
.vm
.svm_port
) < 0)
988 assert_not_reached("Unhandled socket type.");
995 static void socket_close_fds(Socket
*s
) {
1001 LIST_FOREACH(port
, p
, s
->ports
) {
1004 was_open
= p
->fd
>= 0;
1006 p
->event_source
= sd_event_source_unref(p
->event_source
);
1007 p
->fd
= safe_close(p
->fd
);
1008 socket_cleanup_fd_list(p
);
1010 /* One little note: we should normally not delete any sockets in the file system here! After all some
1011 * other process we spawned might still have a reference of this fd and wants to continue to use
1012 * it. Therefore we normally delete sockets in the file system before we create a new one, not after we
1013 * stopped using one! That all said, if the user explicitly requested this, we'll delete them here
1014 * anyway, but only then. */
1016 if (!was_open
|| !s
->remove_on_stop
)
1022 (void) unlink(p
->path
);
1026 (void) mq_unlink(p
->path
);
1030 (void) socket_address_unlink(&p
->address
);
1038 if (s
->remove_on_stop
)
1039 STRV_FOREACH(i
, s
->symlinks
)
1043 static void socket_apply_socket_options(Socket
*s
, int fd
) {
1049 if (s
->keep_alive
) {
1050 int b
= s
->keep_alive
;
1051 if (setsockopt(fd
, SOL_SOCKET
, SO_KEEPALIVE
, &b
, sizeof(b
)) < 0)
1052 log_unit_warning_errno(UNIT(s
), errno
, "SO_KEEPALIVE failed: %m");
1055 if (s
->keep_alive_time
) {
1056 int value
= s
->keep_alive_time
/ USEC_PER_SEC
;
1057 if (setsockopt(fd
, SOL_TCP
, TCP_KEEPIDLE
, &value
, sizeof(value
)) < 0)
1058 log_unit_warning_errno(UNIT(s
), errno
, "TCP_KEEPIDLE failed: %m");
1061 if (s
->keep_alive_interval
) {
1062 int value
= s
->keep_alive_interval
/ USEC_PER_SEC
;
1063 if (setsockopt(fd
, SOL_TCP
, TCP_KEEPINTVL
, &value
, sizeof(value
)) < 0)
1064 log_unit_warning_errno(UNIT(s
), errno
, "TCP_KEEPINTVL failed: %m");
1067 if (s
->keep_alive_cnt
) {
1068 int value
= s
->keep_alive_cnt
;
1069 if (setsockopt(fd
, SOL_TCP
, TCP_KEEPCNT
, &value
, sizeof(value
)) < 0)
1070 log_unit_warning_errno(UNIT(s
), errno
, "TCP_KEEPCNT failed: %m");
1073 if (s
->defer_accept
) {
1074 int value
= s
->defer_accept
/ USEC_PER_SEC
;
1075 if (setsockopt(fd
, SOL_TCP
, TCP_DEFER_ACCEPT
, &value
, sizeof(value
)) < 0)
1076 log_unit_warning_errno(UNIT(s
), errno
, "TCP_DEFER_ACCEPT failed: %m");
1080 int b
= s
->no_delay
;
1082 if (s
->socket_protocol
== IPPROTO_SCTP
) {
1083 if (setsockopt(fd
, SOL_SCTP
, SCTP_NODELAY
, &b
, sizeof(b
)) < 0)
1084 log_unit_warning_errno(UNIT(s
), errno
, "SCTP_NODELAY failed: %m");
1086 if (setsockopt(fd
, SOL_TCP
, TCP_NODELAY
, &b
, sizeof(b
)) < 0)
1087 log_unit_warning_errno(UNIT(s
), errno
, "TCP_NODELAY failed: %m");
1093 if (setsockopt(fd
, SOL_SOCKET
, SO_BROADCAST
, &one
, sizeof(one
)) < 0)
1094 log_unit_warning_errno(UNIT(s
), errno
, "SO_BROADCAST failed: %m");
1099 if (setsockopt(fd
, SOL_SOCKET
, SO_PASSCRED
, &one
, sizeof(one
)) < 0)
1100 log_unit_warning_errno(UNIT(s
), errno
, "SO_PASSCRED failed: %m");
1105 if (setsockopt(fd
, SOL_SOCKET
, SO_PASSSEC
, &one
, sizeof(one
)) < 0)
1106 log_unit_warning_errno(UNIT(s
), errno
, "SO_PASSSEC failed: %m");
1109 if (s
->priority
>= 0)
1110 if (setsockopt(fd
, SOL_SOCKET
, SO_PRIORITY
, &s
->priority
, sizeof(s
->priority
)) < 0)
1111 log_unit_warning_errno(UNIT(s
), errno
, "SO_PRIORITY failed: %m");
1113 if (s
->receive_buffer
> 0) {
1114 int value
= (int) s
->receive_buffer
;
1116 /* We first try with SO_RCVBUFFORCE, in case we have the perms for that */
1118 if (setsockopt(fd
, SOL_SOCKET
, SO_RCVBUFFORCE
, &value
, sizeof(value
)) < 0)
1119 if (setsockopt(fd
, SOL_SOCKET
, SO_RCVBUF
, &value
, sizeof(value
)) < 0)
1120 log_unit_warning_errno(UNIT(s
), errno
, "SO_RCVBUF failed: %m");
1123 if (s
->send_buffer
> 0) {
1124 int value
= (int) s
->send_buffer
;
1125 if (setsockopt(fd
, SOL_SOCKET
, SO_SNDBUFFORCE
, &value
, sizeof(value
)) < 0)
1126 if (setsockopt(fd
, SOL_SOCKET
, SO_SNDBUF
, &value
, sizeof(value
)) < 0)
1127 log_unit_warning_errno(UNIT(s
), errno
, "SO_SNDBUF failed: %m");
1131 if (setsockopt(fd
, SOL_SOCKET
, SO_MARK
, &s
->mark
, sizeof(s
->mark
)) < 0)
1132 log_unit_warning_errno(UNIT(s
), errno
, "SO_MARK failed: %m");
1135 if (setsockopt(fd
, IPPROTO_IP
, IP_TOS
, &s
->ip_tos
, sizeof(s
->ip_tos
)) < 0)
1136 log_unit_warning_errno(UNIT(s
), errno
, "IP_TOS failed: %m");
1138 if (s
->ip_ttl
>= 0) {
1141 r
= setsockopt(fd
, IPPROTO_IP
, IP_TTL
, &s
->ip_ttl
, sizeof(s
->ip_ttl
));
1143 if (socket_ipv6_is_supported())
1144 x
= setsockopt(fd
, IPPROTO_IPV6
, IPV6_UNICAST_HOPS
, &s
->ip_ttl
, sizeof(s
->ip_ttl
));
1147 errno
= EAFNOSUPPORT
;
1151 log_unit_warning_errno(UNIT(s
), errno
, "IP_TTL/IPV6_UNICAST_HOPS failed: %m");
1154 if (s
->tcp_congestion
)
1155 if (setsockopt(fd
, SOL_TCP
, TCP_CONGESTION
, s
->tcp_congestion
, strlen(s
->tcp_congestion
)+1) < 0)
1156 log_unit_warning_errno(UNIT(s
), errno
, "TCP_CONGESTION failed: %m");
1158 if (s
->smack_ip_in
) {
1159 r
= mac_smack_apply_fd(fd
, SMACK_ATTR_IPIN
, s
->smack_ip_in
);
1161 log_unit_error_errno(UNIT(s
), r
, "mac_smack_apply_ip_in_fd: %m");
1164 if (s
->smack_ip_out
) {
1165 r
= mac_smack_apply_fd(fd
, SMACK_ATTR_IPOUT
, s
->smack_ip_out
);
1167 log_unit_error_errno(UNIT(s
), r
, "mac_smack_apply_ip_out_fd: %m");
1171 static void socket_apply_fifo_options(Socket
*s
, int fd
) {
1177 if (s
->pipe_size
> 0)
1178 if (fcntl(fd
, F_SETPIPE_SZ
, s
->pipe_size
) < 0)
1179 log_unit_warning_errno(UNIT(s
), errno
, "Setting pipe size failed, ignoring: %m");
1182 r
= mac_smack_apply_fd(fd
, SMACK_ATTR_ACCESS
, s
->smack
);
1184 log_unit_error_errno(UNIT(s
), r
, "SMACK relabelling failed, ignoring: %m");
1188 static int fifo_address_create(
1190 mode_t directory_mode
,
1191 mode_t socket_mode
) {
1193 _cleanup_close_
int fd
= -1;
1200 (void) mkdir_parents_label(path
, directory_mode
);
1202 r
= mac_selinux_create_file_prepare(path
, S_IFIFO
);
1206 /* Enforce the right access mode for the fifo */
1207 old_mask
= umask(~ socket_mode
);
1209 /* Include the original umask in our mask */
1210 (void) umask(~socket_mode
| old_mask
);
1212 r
= mkfifo(path
, socket_mode
);
1213 (void) umask(old_mask
);
1215 if (r
< 0 && errno
!= EEXIST
) {
1220 fd
= open(path
, O_RDWR
| O_CLOEXEC
| O_NOCTTY
| O_NONBLOCK
| O_NOFOLLOW
);
1226 mac_selinux_create_file_clear();
1228 if (fstat(fd
, &st
) < 0) {
1233 if (!S_ISFIFO(st
.st_mode
) ||
1234 (st
.st_mode
& 0777) != (socket_mode
& ~old_mask
) ||
1235 st
.st_uid
!= getuid() ||
1236 st
.st_gid
!= getgid()) {
1244 mac_selinux_create_file_clear();
1248 static int special_address_create(const char *path
, bool writable
) {
1249 _cleanup_close_
int fd
= -1;
1254 fd
= open(path
, (writable
? O_RDWR
: O_RDONLY
)|O_CLOEXEC
|O_NOCTTY
|O_NONBLOCK
|O_NOFOLLOW
);
1258 if (fstat(fd
, &st
) < 0)
1261 /* Check whether this is a /proc, /sys or /dev file or char device */
1262 if (!S_ISREG(st
.st_mode
) && !S_ISCHR(st
.st_mode
))
1268 static int usbffs_address_create(const char *path
) {
1269 _cleanup_close_
int fd
= -1;
1274 fd
= open(path
, O_RDWR
|O_CLOEXEC
|O_NOCTTY
|O_NONBLOCK
|O_NOFOLLOW
);
1278 if (fstat(fd
, &st
) < 0)
1281 /* Check whether this is a regular file (ffs endpoint) */
1282 if (!S_ISREG(st
.st_mode
))
1288 static int mq_address_create(
1294 _cleanup_close_
int fd
= -1;
1297 struct mq_attr _attr
, *attr
= NULL
;
1301 if (maxmsg
> 0 && msgsize
> 0) {
1302 _attr
= (struct mq_attr
) {
1303 .mq_flags
= O_NONBLOCK
,
1304 .mq_maxmsg
= maxmsg
,
1305 .mq_msgsize
= msgsize
,
1310 /* Enforce the right access mode for the mq */
1311 old_mask
= umask(~ mq_mode
);
1313 /* Include the original umask in our mask */
1314 (void) umask(~mq_mode
| old_mask
);
1315 fd
= mq_open(path
, O_RDONLY
|O_CLOEXEC
|O_NONBLOCK
|O_CREAT
, mq_mode
, attr
);
1316 (void) umask(old_mask
);
1321 if (fstat(fd
, &st
) < 0)
1324 if ((st
.st_mode
& 0777) != (mq_mode
& ~old_mask
) ||
1325 st
.st_uid
!= getuid() ||
1326 st
.st_gid
!= getgid())
1332 static int socket_symlink(Socket
*s
) {
1339 p
= socket_find_symlink_target(s
);
1343 STRV_FOREACH(i
, s
->symlinks
) {
1344 (void) mkdir_parents_label(*i
, s
->directory_mode
);
1346 r
= symlink_idempotent(p
, *i
);
1348 if (r
== -EEXIST
&& s
->remove_on_stop
) {
1349 /* If there's already something where we want to create the symlink, and the destructive
1350 * RemoveOnStop= mode is set, then we might as well try to remove what already exists and try
1353 if (unlink(*i
) >= 0)
1354 r
= symlink_idempotent(p
, *i
);
1358 log_unit_warning_errno(UNIT(s
), r
, "Failed to create symlink %s → %s, ignoring: %m", p
, *i
);
1364 static int usbffs_write_descs(int fd
, Service
*s
) {
1367 if (!s
->usb_function_descriptors
|| !s
->usb_function_strings
)
1370 r
= copy_file_fd(s
->usb_function_descriptors
, fd
, 0);
1374 return copy_file_fd(s
->usb_function_strings
, fd
, 0);
1377 static int usbffs_select_ep(const struct dirent
*d
) {
1378 return d
->d_name
[0] != '.' && !streq(d
->d_name
, "ep0");
1381 static int usbffs_dispatch_eps(SocketPort
*p
) {
1382 _cleanup_free_
struct dirent
**ent
= NULL
;
1385 r
= scandir(p
->path
, &ent
, usbffs_select_ep
, alphasort
);
1390 p
->auxiliary_fds
= new(int, n
);
1391 if (!p
->auxiliary_fds
)
1394 p
->n_auxiliary_fds
= n
;
1397 for (i
= 0; i
< n
; ++i
) {
1398 _cleanup_free_
char *ep
= NULL
;
1400 ep
= path_make_absolute(ent
[i
]->d_name
, p
->path
);
1404 path_kill_slashes(ep
);
1406 r
= usbffs_address_create(ep
);
1410 p
->auxiliary_fds
[k
] = r
;
1419 close_many(p
->auxiliary_fds
, k
);
1420 p
->auxiliary_fds
= mfree(p
->auxiliary_fds
);
1421 p
->n_auxiliary_fds
= 0;
1426 static int socket_determine_selinux_label(Socket
*s
, char **ret
) {
1435 if (s
->selinux_context_from_net
) {
1436 /* If this is requested, get label from the network label */
1438 r
= mac_selinux_get_our_label(ret
);
1439 if (r
== -EOPNOTSUPP
)
1443 /* Otherwise, get it from the executable we are about to start */
1444 r
= socket_instantiate_service(s
);
1448 if (!UNIT_ISSET(s
->service
))
1451 service
= SERVICE(UNIT_DEREF(s
->service
));
1452 c
= service
->exec_command
[SERVICE_EXEC_START
];
1456 path
= prefix_roota(service
->exec_context
.root_directory
, c
->path
);
1457 r
= mac_selinux_get_create_label_from_exe(path
, ret
);
1458 if (IN_SET(r
, -EPERM
, -EOPNOTSUPP
))
1469 static int socket_address_listen_do(
1471 const SocketAddress
*address
,
1472 const char *label
) {
1477 return socket_address_listen(
1479 SOCK_CLOEXEC
|SOCK_NONBLOCK
,
1491 static int socket_address_listen_in_cgroup(
1493 const SocketAddress
*address
,
1494 const char *label
) {
1496 _cleanup_close_pair_
int pair
[2] = { -1, -1 };
1503 /* This is a wrapper around socket_address_listen(), that forks off a helper process inside the socket's cgroup
1504 * in which the socket is actually created. This way we ensure the socket is actually properly attached to the
1505 * unit's cgroup for the purpose of BPF filtering and such. */
1507 if (!IN_SET(address
->sockaddr
.sa
.sa_family
, AF_INET
, AF_INET6
))
1508 goto shortcut
; /* BPF filtering only applies to IPv4 + IPv6, shortcut things for other protocols */
1510 r
= bpf_firewall_supported();
1513 if (r
== BPF_FIREWALL_UNSUPPORTED
) /* If BPF firewalling isn't supported anyway — there's no point in this forking complexity */
1516 if (socketpair(AF_UNIX
, SOCK_SEQPACKET
|SOCK_CLOEXEC
, 0, pair
) < 0)
1517 return log_unit_error_errno(UNIT(s
), errno
, "Failed to create communication channel: %m");
1519 r
= unit_fork_helper_process(UNIT(s
), "(sd-listen)", &pid
);
1521 return log_unit_error_errno(UNIT(s
), r
, "Failed to fork off listener stub process: %m");
1525 pair
[0] = safe_close(pair
[0]);
1527 fd
= socket_address_listen_do(s
, address
, label
);
1529 log_unit_error_errno(UNIT(s
), fd
, "Failed to create listening socket: %m");
1530 _exit(EXIT_FAILURE
);
1533 r
= send_one_fd(pair
[1], fd
, 0);
1535 log_unit_error_errno(UNIT(s
), r
, "Failed to send listening socket to parent: %m");
1536 _exit(EXIT_FAILURE
);
1539 _exit(EXIT_SUCCESS
);
1542 pair
[1] = safe_close(pair
[1]);
1543 fd
= receive_one_fd(pair
[0], 0);
1545 /* We synchronously wait for the helper, as it shouldn't be slow */
1546 r
= wait_for_terminate_and_check("(sd-listen)", pid
, WAIT_LOG_ABNORMAL
);
1553 return log_unit_error_errno(UNIT(s
), fd
, "Failed to receive listening socket: %m");
1558 fd
= socket_address_listen_do(s
, address
, label
);
1560 return log_error_errno(fd
, "Failed to create listening socket: %m");
1565 static int socket_open_fds(Socket
*s
) {
1566 _cleanup_(mac_selinux_freep
) char *label
= NULL
;
1567 bool know_label
= false;
1573 LIST_FOREACH(port
, p
, s
->ports
) {
1583 /* Figure out label, if we don't it know yet. We do it once, for the first socket where
1584 * we need this and remember it for the rest. */
1586 r
= socket_determine_selinux_label(s
, &label
);
1593 /* Apply the socket protocol */
1594 switch (p
->address
.type
) {
1597 case SOCK_SEQPACKET
:
1598 if (s
->socket_protocol
== IPPROTO_SCTP
)
1599 p
->address
.protocol
= s
->socket_protocol
;
1603 if (s
->socket_protocol
== IPPROTO_UDPLITE
)
1604 p
->address
.protocol
= s
->socket_protocol
;
1608 r
= socket_address_listen_in_cgroup(s
, &p
->address
, label
);
1613 socket_apply_socket_options(s
, p
->fd
);
1617 case SOCKET_SPECIAL
:
1619 p
->fd
= special_address_create(p
->path
, s
->writable
);
1628 p
->fd
= fifo_address_create(
1637 socket_apply_fifo_options(s
, p
->fd
);
1643 p
->fd
= mq_address_create(
1654 case SOCKET_USB_FUNCTION
: {
1655 _cleanup_free_
char *ep
= NULL
;
1657 ep
= path_make_absolute("ep0", p
->path
);
1659 p
->fd
= usbffs_address_create(ep
);
1665 r
= usbffs_write_descs(p
->fd
, SERVICE(UNIT_DEREF(s
->service
)));
1669 r
= usbffs_dispatch_eps(p
);
1676 assert_not_reached("Unknown port type");
1683 socket_close_fds(s
);
1687 static void socket_unwatch_fds(Socket
*s
) {
1693 LIST_FOREACH(port
, p
, s
->ports
) {
1697 if (!p
->event_source
)
1700 r
= sd_event_source_set_enabled(p
->event_source
, SD_EVENT_OFF
);
1702 log_unit_debug_errno(UNIT(s
), r
, "Failed to disable event source: %m");
1706 static int socket_watch_fds(Socket
*s
) {
1712 LIST_FOREACH(port
, p
, s
->ports
) {
1716 if (p
->event_source
) {
1717 r
= sd_event_source_set_enabled(p
->event_source
, SD_EVENT_ON
);
1721 r
= sd_event_add_io(UNIT(s
)->manager
->event
, &p
->event_source
, p
->fd
, EPOLLIN
, socket_dispatch_io
, p
);
1725 (void) sd_event_source_set_description(p
->event_source
, "socket-port-io");
1732 log_unit_warning_errno(UNIT(s
), r
, "Failed to watch listening fds: %m");
1733 socket_unwatch_fds(s
);
1743 static int socket_check_open(Socket
*s
) {
1744 bool have_open
= false, have_closed
= false;
1749 LIST_FOREACH(port
, p
, s
->ports
) {
1755 if (have_open
&& have_closed
)
1756 return SOCKET_OPEN_SOME
;
1760 return SOCKET_OPEN_ALL
;
1762 return SOCKET_OPEN_NONE
;
1765 static void socket_set_state(Socket
*s
, SocketState state
) {
1766 SocketState old_state
;
1769 old_state
= s
->state
;
1777 SOCKET_STOP_PRE_SIGTERM
,
1778 SOCKET_STOP_PRE_SIGKILL
,
1780 SOCKET_FINAL_SIGTERM
,
1781 SOCKET_FINAL_SIGKILL
)) {
1783 s
->timer_event_source
= sd_event_source_unref(s
->timer_event_source
);
1784 socket_unwatch_control_pid(s
);
1785 s
->control_command
= NULL
;
1786 s
->control_command_id
= _SOCKET_EXEC_COMMAND_INVALID
;
1789 if (state
!= SOCKET_LISTENING
)
1790 socket_unwatch_fds(s
);
1798 SOCKET_STOP_PRE_SIGTERM
,
1799 SOCKET_STOP_PRE_SIGKILL
))
1800 socket_close_fds(s
);
1802 if (state
!= old_state
)
1803 log_unit_debug(UNIT(s
), "Changed %s -> %s", socket_state_to_string(old_state
), socket_state_to_string(state
));
1805 unit_notify(UNIT(s
), state_translation_table
[old_state
], state_translation_table
[state
], true);
1808 static int socket_coldplug(Unit
*u
) {
1809 Socket
*s
= SOCKET(u
);
1813 assert(s
->state
== SOCKET_DEAD
);
1815 if (s
->deserialized_state
== s
->state
)
1818 if (s
->control_pid
> 0 &&
1819 pid_is_unwaited(s
->control_pid
) &&
1820 IN_SET(s
->deserialized_state
,
1825 SOCKET_STOP_PRE_SIGTERM
,
1826 SOCKET_STOP_PRE_SIGKILL
,
1828 SOCKET_FINAL_SIGTERM
,
1829 SOCKET_FINAL_SIGKILL
)) {
1831 r
= unit_watch_pid(UNIT(s
), s
->control_pid
);
1835 r
= socket_arm_timer(s
, usec_add(u
->state_change_timestamp
.monotonic
, s
->timeout_usec
));
1840 if (IN_SET(s
->deserialized_state
,
1846 /* Originally, we used to simply reopen all sockets here that we didn't have file descriptors
1847 * for. However, this is problematic, as we won't traverse throught the SOCKET_START_CHOWN state for
1848 * them, and thus the UID/GID wouldn't be right. Hence, instead simply check if we have all fds open,
1849 * and if there's a mismatch, warn loudly. */
1851 r
= socket_check_open(s
);
1852 if (r
== SOCKET_OPEN_NONE
)
1853 log_unit_warning(UNIT(s
),
1854 "Socket unit configuration has changed while unit has been running, "
1855 "no open socket file descriptor left. "
1856 "The socket unit is not functional until restarted.");
1857 else if (r
== SOCKET_OPEN_SOME
)
1858 log_unit_warning(UNIT(s
),
1859 "Socket unit configuration has changed while unit has been running, "
1860 "and some socket file descriptors have not been opened yet. "
1861 "The socket unit is not fully functional until restarted.");
1864 if (s
->deserialized_state
== SOCKET_LISTENING
) {
1865 r
= socket_watch_fds(s
);
1870 if (!IN_SET(s
->deserialized_state
, SOCKET_DEAD
, SOCKET_FAILED
)) {
1871 (void) unit_setup_dynamic_creds(u
);
1872 (void) unit_setup_exec_runtime(u
);
1875 socket_set_state(s
, s
->deserialized_state
);
1879 static int socket_spawn(Socket
*s
, ExecCommand
*c
, pid_t
*_pid
) {
1881 ExecParameters exec_params
= {
1882 .flags
= EXEC_APPLY_SANDBOXING
|EXEC_APPLY_CHROOT
|EXEC_APPLY_TTY_STDIN
,
1894 r
= unit_prepare_exec(UNIT(s
));
1898 r
= socket_arm_timer(s
, usec_add(now(CLOCK_MONOTONIC
), s
->timeout_usec
));
1902 unit_set_exec_params(UNIT(s
), &exec_params
);
1904 exec_params
.argv
= c
->argv
;
1906 r
= exec_spawn(UNIT(s
),
1916 r
= unit_watch_pid(UNIT(s
), pid
);
1918 /* FIXME: we need to do something here */
1926 static int socket_chown(Socket
*s
, pid_t
*_pid
) {
1930 r
= socket_arm_timer(s
, usec_add(now(CLOCK_MONOTONIC
), s
->timeout_usec
));
1934 /* We have to resolve the user names out-of-process, hence
1935 * let's fork here. It's messy, but well, what can we do? */
1937 r
= unit_fork_helper_process(UNIT(s
), "(sd-chown)", &pid
);
1941 uid_t uid
= UID_INVALID
;
1942 gid_t gid
= GID_INVALID
;
1947 if (!isempty(s
->user
)) {
1948 const char *user
= s
->user
;
1950 r
= get_user_creds(&user
, &uid
, &gid
, NULL
, NULL
);
1952 log_unit_error_errno(UNIT(s
), r
, "Failed to resolve user %s: %m", user
);
1957 if (!isempty(s
->group
)) {
1958 const char *group
= s
->group
;
1960 r
= get_group_creds(&group
, &gid
);
1962 log_unit_error_errno(UNIT(s
), r
, "Failed to resolve group %s: %m", group
);
1967 LIST_FOREACH(port
, p
, s
->ports
) {
1968 const char *path
= NULL
;
1970 if (p
->type
== SOCKET_SOCKET
)
1971 path
= socket_address_get_path(&p
->address
);
1972 else if (p
->type
== SOCKET_FIFO
)
1978 if (chown(path
, uid
, gid
) < 0) {
1979 log_unit_error_errno(UNIT(s
), errno
, "Failed to chown(): %m");
1984 _exit(EXIT_SUCCESS
);
1987 r
= unit_watch_pid(UNIT(s
), pid
);
1995 s
->timer_event_source
= sd_event_source_unref(s
->timer_event_source
);
1999 static void socket_enter_dead(Socket
*s
, SocketResult f
) {
2002 if (s
->result
== SOCKET_SUCCESS
)
2005 if (s
->result
!= SOCKET_SUCCESS
)
2006 log_unit_warning(UNIT(s
), "Failed with result '%s'.", socket_result_to_string(s
->result
));
2008 socket_set_state(s
, s
->result
!= SOCKET_SUCCESS
? SOCKET_FAILED
: SOCKET_DEAD
);
2010 s
->exec_runtime
= exec_runtime_unref(s
->exec_runtime
, true);
2012 exec_context_destroy_runtime_directory(&s
->exec_context
, UNIT(s
)->manager
->prefix
[EXEC_DIRECTORY_RUNTIME
]);
2014 unit_unref_uid_gid(UNIT(s
), true);
2016 dynamic_creds_destroy(&s
->dynamic_creds
);
2019 static void socket_enter_signal(Socket
*s
, SocketState state
, SocketResult f
);
2021 static void socket_enter_stop_post(Socket
*s
, SocketResult f
) {
2025 if (s
->result
== SOCKET_SUCCESS
)
2028 socket_unwatch_control_pid(s
);
2029 s
->control_command_id
= SOCKET_EXEC_STOP_POST
;
2030 s
->control_command
= s
->exec_command
[SOCKET_EXEC_STOP_POST
];
2032 if (s
->control_command
) {
2033 r
= socket_spawn(s
, s
->control_command
, &s
->control_pid
);
2037 socket_set_state(s
, SOCKET_STOP_POST
);
2039 socket_enter_signal(s
, SOCKET_FINAL_SIGTERM
, SOCKET_SUCCESS
);
2044 log_unit_warning_errno(UNIT(s
), r
, "Failed to run 'stop-post' task: %m");
2045 socket_enter_signal(s
, SOCKET_FINAL_SIGTERM
, SOCKET_FAILURE_RESOURCES
);
2048 static void socket_enter_signal(Socket
*s
, SocketState state
, SocketResult f
) {
2053 if (s
->result
== SOCKET_SUCCESS
)
2056 r
= unit_kill_context(
2059 !IN_SET(state
, SOCKET_STOP_PRE_SIGTERM
, SOCKET_FINAL_SIGTERM
) ?
2060 KILL_KILL
: KILL_TERMINATE
,
2068 r
= socket_arm_timer(s
, usec_add(now(CLOCK_MONOTONIC
), s
->timeout_usec
));
2072 socket_set_state(s
, state
);
2073 } else if (state
== SOCKET_STOP_PRE_SIGTERM
)
2074 socket_enter_signal(s
, SOCKET_STOP_PRE_SIGKILL
, SOCKET_SUCCESS
);
2075 else if (state
== SOCKET_STOP_PRE_SIGKILL
)
2076 socket_enter_stop_post(s
, SOCKET_SUCCESS
);
2077 else if (state
== SOCKET_FINAL_SIGTERM
)
2078 socket_enter_signal(s
, SOCKET_FINAL_SIGKILL
, SOCKET_SUCCESS
);
2080 socket_enter_dead(s
, SOCKET_SUCCESS
);
2085 log_unit_warning_errno(UNIT(s
), r
, "Failed to kill processes: %m");
2087 if (IN_SET(state
, SOCKET_STOP_PRE_SIGTERM
, SOCKET_STOP_PRE_SIGKILL
))
2088 socket_enter_stop_post(s
, SOCKET_FAILURE_RESOURCES
);
2090 socket_enter_dead(s
, SOCKET_FAILURE_RESOURCES
);
2093 static void socket_enter_stop_pre(Socket
*s
, SocketResult f
) {
2097 if (s
->result
== SOCKET_SUCCESS
)
2100 socket_unwatch_control_pid(s
);
2101 s
->control_command_id
= SOCKET_EXEC_STOP_PRE
;
2102 s
->control_command
= s
->exec_command
[SOCKET_EXEC_STOP_PRE
];
2104 if (s
->control_command
) {
2105 r
= socket_spawn(s
, s
->control_command
, &s
->control_pid
);
2109 socket_set_state(s
, SOCKET_STOP_PRE
);
2111 socket_enter_stop_post(s
, SOCKET_SUCCESS
);
2116 log_unit_warning_errno(UNIT(s
), r
, "Failed to run 'stop-pre' task: %m");
2117 socket_enter_stop_post(s
, SOCKET_FAILURE_RESOURCES
);
2120 static void socket_enter_listening(Socket
*s
) {
2124 r
= socket_watch_fds(s
);
2126 log_unit_warning_errno(UNIT(s
), r
, "Failed to watch sockets: %m");
2130 socket_set_state(s
, SOCKET_LISTENING
);
2134 socket_enter_stop_pre(s
, SOCKET_FAILURE_RESOURCES
);
2137 static void socket_enter_start_post(Socket
*s
) {
2141 socket_unwatch_control_pid(s
);
2142 s
->control_command_id
= SOCKET_EXEC_START_POST
;
2143 s
->control_command
= s
->exec_command
[SOCKET_EXEC_START_POST
];
2145 if (s
->control_command
) {
2146 r
= socket_spawn(s
, s
->control_command
, &s
->control_pid
);
2148 log_unit_warning_errno(UNIT(s
), r
, "Failed to run 'start-post' task: %m");
2152 socket_set_state(s
, SOCKET_START_POST
);
2154 socket_enter_listening(s
);
2159 socket_enter_stop_pre(s
, SOCKET_FAILURE_RESOURCES
);
2162 static void socket_enter_start_chown(Socket
*s
) {
2167 r
= socket_open_fds(s
);
2169 log_unit_warning_errno(UNIT(s
), r
, "Failed to listen on sockets: %m");
2173 if (!isempty(s
->user
) || !isempty(s
->group
)) {
2175 socket_unwatch_control_pid(s
);
2176 s
->control_command_id
= SOCKET_EXEC_START_CHOWN
;
2177 s
->control_command
= NULL
;
2179 r
= socket_chown(s
, &s
->control_pid
);
2181 log_unit_warning_errno(UNIT(s
), r
, "Failed to fork 'start-chown' task: %m");
2185 socket_set_state(s
, SOCKET_START_CHOWN
);
2187 socket_enter_start_post(s
);
2192 socket_enter_stop_pre(s
, SOCKET_FAILURE_RESOURCES
);
2195 static void socket_enter_start_pre(Socket
*s
) {
2199 socket_unwatch_control_pid(s
);
2201 unit_warn_leftover_processes(UNIT(s
));
2203 s
->control_command_id
= SOCKET_EXEC_START_PRE
;
2204 s
->control_command
= s
->exec_command
[SOCKET_EXEC_START_PRE
];
2206 if (s
->control_command
) {
2207 r
= socket_spawn(s
, s
->control_command
, &s
->control_pid
);
2209 log_unit_warning_errno(UNIT(s
), r
, "Failed to run 'start-pre' task: %m");
2213 socket_set_state(s
, SOCKET_START_PRE
);
2215 socket_enter_start_chown(s
);
2220 socket_enter_dead(s
, SOCKET_FAILURE_RESOURCES
);
2223 static void flush_ports(Socket
*s
) {
2226 /* Flush all incoming traffic, regardless if actual bytes or new connections, so that this socket isn't busy
2229 LIST_FOREACH(port
, p
, s
->ports
) {
2233 (void) flush_accept(p
->fd
);
2234 (void) flush_fd(p
->fd
);
2238 static void socket_enter_running(Socket
*s
, int cfd
) {
2239 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
2242 /* Note that this call takes possession of the connection fd passed. It either has to assign it somewhere or
2247 /* We don't take connections anymore if we are supposed to shut down anyway */
2248 if (unit_stop_pending(UNIT(s
))) {
2250 log_unit_debug(UNIT(s
), "Suppressing connection request since unit stop is scheduled.");
2253 cfd
= safe_close(cfd
);
2260 if (!ratelimit_test(&s
->trigger_limit
)) {
2262 log_unit_warning(UNIT(s
), "Trigger limit hit, refusing further activation.");
2263 socket_enter_stop_pre(s
, SOCKET_FAILURE_TRIGGER_LIMIT_HIT
);
2268 bool pending
= false;
2273 /* If there's already a start pending don't bother to
2275 HASHMAP_FOREACH_KEY(v
, other
, UNIT(s
)->dependencies
[UNIT_TRIGGERS
], i
)
2276 if (unit_active_or_pending(other
)) {
2282 if (!UNIT_ISSET(s
->service
)) {
2283 log_unit_error(UNIT(s
), "Service to activate vanished, refusing activation.");
2288 r
= manager_add_job(UNIT(s
)->manager
, JOB_START
, UNIT_DEREF(s
->service
), JOB_REPLACE
, &error
, NULL
);
2293 socket_set_state(s
, SOCKET_RUNNING
);
2295 _cleanup_free_
char *prefix
= NULL
, *instance
= NULL
, *name
= NULL
;
2296 _cleanup_(socket_peer_unrefp
) SocketPeer
*p
= NULL
;
2299 if (s
->n_connections
>= s
->max_connections
) {
2300 log_unit_warning(UNIT(s
), "Too many incoming connections (%u), dropping connection.",
2306 if (s
->max_connections_per_source
> 0) {
2307 r
= socket_acquire_peer(s
, cfd
, &p
);
2311 } else if (r
> 0 && p
->n_ref
> s
->max_connections_per_source
) {
2312 _cleanup_free_
char *t
= NULL
;
2314 (void) sockaddr_pretty(&p
->peer
.sa
, p
->peer_salen
, true, false, &t
);
2316 log_unit_warning(UNIT(s
),
2317 "Too many incoming connections (%u) from source %s, dropping connection.",
2318 p
->n_ref
, strnull(t
));
2324 r
= socket_instantiate_service(s
);
2328 r
= instance_from_socket(cfd
, s
->n_accepted
, &instance
);
2333 /* ENOTCONN is legitimate if TCP RST was received.
2334 * This connection is over, but the socket unit lives on. */
2335 log_unit_debug(UNIT(s
), "Got ENOTCONN on incoming socket, assuming aborted connection attempt, ignoring.");
2340 r
= unit_name_to_prefix(UNIT(s
)->id
, &prefix
);
2344 r
= unit_name_build(prefix
, instance
, ".service", &name
);
2348 r
= unit_add_name(UNIT_DEREF(s
->service
), name
);
2352 service
= SERVICE(UNIT_DEREF(s
->service
));
2353 unit_ref_unset(&s
->service
);
2356 unit_choose_id(UNIT(service
), name
);
2358 r
= service_set_socket_fd(service
, cfd
, s
, s
->selinux_context_from_net
);
2362 cfd
= -1; /* We passed ownership of the fd to the service now. Forget it here. */
2365 service
->peer
= p
; /* Pass ownership of the peer reference */
2368 r
= manager_add_job(UNIT(s
)->manager
, JOB_START
, UNIT(service
), JOB_REPLACE
, &error
, NULL
);
2370 /* We failed to activate the new service, but it still exists. Let's make sure the service
2371 * closes and forgets the connection fd again, immediately. */
2372 service_close_socket_fd(service
);
2376 /* Notify clients about changed counters */
2377 unit_add_to_dbus_queue(UNIT(s
));
2383 log_unit_warning(UNIT(s
), "Failed to queue service startup job (Maybe the service file is missing or not a %s unit?): %s",
2384 cfd
>= 0 ? "template" : "non-template",
2385 bus_error_message(&error
, r
));
2387 socket_enter_stop_pre(s
, SOCKET_FAILURE_RESOURCES
);
2391 static void socket_run_next(Socket
*s
) {
2395 assert(s
->control_command
);
2396 assert(s
->control_command
->command_next
);
2398 socket_unwatch_control_pid(s
);
2400 s
->control_command
= s
->control_command
->command_next
;
2402 r
= socket_spawn(s
, s
->control_command
, &s
->control_pid
);
2409 log_unit_warning_errno(UNIT(s
), r
, "Failed to run next task: %m");
2411 if (s
->state
== SOCKET_START_POST
)
2412 socket_enter_stop_pre(s
, SOCKET_FAILURE_RESOURCES
);
2413 else if (s
->state
== SOCKET_STOP_POST
)
2414 socket_enter_dead(s
, SOCKET_FAILURE_RESOURCES
);
2416 socket_enter_signal(s
, SOCKET_FINAL_SIGTERM
, SOCKET_FAILURE_RESOURCES
);
2419 static int socket_start(Unit
*u
) {
2420 Socket
*s
= SOCKET(u
);
2425 /* We cannot fulfill this request right now, try again later
2427 if (IN_SET(s
->state
,
2429 SOCKET_STOP_PRE_SIGKILL
,
2430 SOCKET_STOP_PRE_SIGTERM
,
2432 SOCKET_FINAL_SIGTERM
,
2433 SOCKET_FINAL_SIGKILL
))
2436 /* Already on it! */
2437 if (IN_SET(s
->state
,
2443 /* Cannot run this without the service being around */
2444 if (UNIT_ISSET(s
->service
)) {
2447 service
= SERVICE(UNIT_DEREF(s
->service
));
2449 if (UNIT(service
)->load_state
!= UNIT_LOADED
) {
2450 log_unit_error(u
, "Socket service %s not loaded, refusing.", UNIT(service
)->id
);
2454 /* If the service is already active we cannot start the
2456 if (!IN_SET(service
->state
, SERVICE_DEAD
, SERVICE_FAILED
, SERVICE_AUTO_RESTART
)) {
2457 log_unit_error(u
, "Socket service %s already active, refusing.", UNIT(service
)->id
);
2462 assert(IN_SET(s
->state
, SOCKET_DEAD
, SOCKET_FAILED
));
2464 r
= unit_start_limit_test(u
);
2466 socket_enter_dead(s
, SOCKET_FAILURE_START_LIMIT_HIT
);
2470 r
= unit_acquire_invocation_id(u
);
2474 s
->result
= SOCKET_SUCCESS
;
2476 u
->reset_accounting
= true;
2478 socket_enter_start_pre(s
);
2482 static int socket_stop(Unit
*u
) {
2483 Socket
*s
= SOCKET(u
);
2488 if (IN_SET(s
->state
,
2490 SOCKET_STOP_PRE_SIGTERM
,
2491 SOCKET_STOP_PRE_SIGKILL
,
2493 SOCKET_FINAL_SIGTERM
,
2494 SOCKET_FINAL_SIGKILL
))
2497 /* If there's already something running we go directly into
2499 if (IN_SET(s
->state
,
2502 SOCKET_START_POST
)) {
2503 socket_enter_signal(s
, SOCKET_STOP_PRE_SIGTERM
, SOCKET_SUCCESS
);
2507 assert(IN_SET(s
->state
, SOCKET_LISTENING
, SOCKET_RUNNING
));
2509 socket_enter_stop_pre(s
, SOCKET_SUCCESS
);
2513 static int socket_serialize(Unit
*u
, FILE *f
, FDSet
*fds
) {
2514 Socket
*s
= SOCKET(u
);
2522 unit_serialize_item(u
, f
, "state", socket_state_to_string(s
->state
));
2523 unit_serialize_item(u
, f
, "result", socket_result_to_string(s
->result
));
2524 unit_serialize_item_format(u
, f
, "n-accepted", "%u", s
->n_accepted
);
2526 if (s
->control_pid
> 0)
2527 unit_serialize_item_format(u
, f
, "control-pid", PID_FMT
, s
->control_pid
);
2529 if (s
->control_command_id
>= 0)
2530 unit_serialize_item(u
, f
, "control-command", socket_exec_command_to_string(s
->control_command_id
));
2532 LIST_FOREACH(port
, p
, s
->ports
) {
2538 copy
= fdset_put_dup(fds
, p
->fd
);
2542 if (p
->type
== SOCKET_SOCKET
) {
2543 _cleanup_free_
char *t
= NULL
;
2545 r
= socket_address_print(&p
->address
, &t
);
2549 if (socket_address_family(&p
->address
) == AF_NETLINK
)
2550 unit_serialize_item_format(u
, f
, "netlink", "%i %s", copy
, t
);
2552 unit_serialize_item_format(u
, f
, "socket", "%i %i %s", copy
, p
->address
.type
, t
);
2554 } else if (p
->type
== SOCKET_SPECIAL
)
2555 unit_serialize_item_format(u
, f
, "special", "%i %s", copy
, p
->path
);
2556 else if (p
->type
== SOCKET_MQUEUE
)
2557 unit_serialize_item_format(u
, f
, "mqueue", "%i %s", copy
, p
->path
);
2558 else if (p
->type
== SOCKET_USB_FUNCTION
)
2559 unit_serialize_item_format(u
, f
, "ffs", "%i %s", copy
, p
->path
);
2561 assert(p
->type
== SOCKET_FIFO
);
2562 unit_serialize_item_format(u
, f
, "fifo", "%i %s", copy
, p
->path
);
2569 static void socket_port_take_fd(SocketPort
*p
, FDSet
*fds
, int fd
) {
2571 p
->fd
= fdset_remove(fds
, fd
);
2574 static int socket_deserialize_item(Unit
*u
, const char *key
, const char *value
, FDSet
*fds
) {
2575 Socket
*s
= SOCKET(u
);
2581 if (streq(key
, "state")) {
2584 state
= socket_state_from_string(value
);
2586 log_unit_debug(u
, "Failed to parse state value: %s", value
);
2588 s
->deserialized_state
= state
;
2589 } else if (streq(key
, "result")) {
2592 f
= socket_result_from_string(value
);
2594 log_unit_debug(u
, "Failed to parse result value: %s", value
);
2595 else if (f
!= SOCKET_SUCCESS
)
2598 } else if (streq(key
, "n-accepted")) {
2601 if (safe_atou(value
, &k
) < 0)
2602 log_unit_debug(u
, "Failed to parse n-accepted value: %s", value
);
2605 } else if (streq(key
, "control-pid")) {
2608 if (parse_pid(value
, &pid
) < 0)
2609 log_unit_debug(u
, "Failed to parse control-pid value: %s", value
);
2611 s
->control_pid
= pid
;
2612 } else if (streq(key
, "control-command")) {
2613 SocketExecCommand id
;
2615 id
= socket_exec_command_from_string(value
);
2617 log_unit_debug(u
, "Failed to parse exec-command value: %s", value
);
2619 s
->control_command_id
= id
;
2620 s
->control_command
= s
->exec_command
[id
];
2622 } else if (streq(key
, "fifo")) {
2626 if (sscanf(value
, "%i %n", &fd
, &skip
) < 1 || fd
< 0 || !fdset_contains(fds
, fd
))
2627 log_unit_debug(u
, "Failed to parse fifo value: %s", value
);
2629 LIST_FOREACH(port
, p
, s
->ports
)
2630 if (p
->type
== SOCKET_FIFO
&&
2631 path_equal_or_files_same(p
->path
, value
+skip
, 0)) {
2632 socket_port_take_fd(p
, fds
, fd
);
2636 } else if (streq(key
, "special")) {
2640 if (sscanf(value
, "%i %n", &fd
, &skip
) < 1 || fd
< 0 || !fdset_contains(fds
, fd
))
2641 log_unit_debug(u
, "Failed to parse special value: %s", value
);
2643 LIST_FOREACH(port
, p
, s
->ports
)
2644 if (p
->type
== SOCKET_SPECIAL
&&
2645 path_equal_or_files_same(p
->path
, value
+skip
, 0)) {
2646 socket_port_take_fd(p
, fds
, fd
);
2650 } else if (streq(key
, "mqueue")) {
2654 if (sscanf(value
, "%i %n", &fd
, &skip
) < 1 || fd
< 0 || !fdset_contains(fds
, fd
))
2655 log_unit_debug(u
, "Failed to parse mqueue value: %s", value
);
2657 LIST_FOREACH(port
, p
, s
->ports
)
2658 if (p
->type
== SOCKET_MQUEUE
&&
2659 streq(p
->path
, value
+skip
)) {
2660 socket_port_take_fd(p
, fds
, fd
);
2664 } else if (streq(key
, "socket")) {
2665 int fd
, type
, skip
= 0;
2668 if (sscanf(value
, "%i %i %n", &fd
, &type
, &skip
) < 2 || fd
< 0 || type
< 0 || !fdset_contains(fds
, fd
))
2669 log_unit_debug(u
, "Failed to parse socket value: %s", value
);
2671 LIST_FOREACH(port
, p
, s
->ports
)
2672 if (socket_address_is(&p
->address
, value
+skip
, type
)) {
2673 socket_port_take_fd(p
, fds
, fd
);
2677 } else if (streq(key
, "netlink")) {
2681 if (sscanf(value
, "%i %n", &fd
, &skip
) < 1 || fd
< 0 || !fdset_contains(fds
, fd
))
2682 log_unit_debug(u
, "Failed to parse socket value: %s", value
);
2684 LIST_FOREACH(port
, p
, s
->ports
)
2685 if (socket_address_is_netlink(&p
->address
, value
+skip
)) {
2686 socket_port_take_fd(p
, fds
, fd
);
2690 } else if (streq(key
, "ffs")) {
2694 if (sscanf(value
, "%i %n", &fd
, &skip
) < 1 || fd
< 0 || !fdset_contains(fds
, fd
))
2695 log_unit_debug(u
, "Failed to parse ffs value: %s", value
);
2697 LIST_FOREACH(port
, p
, s
->ports
)
2698 if (p
->type
== SOCKET_USB_FUNCTION
&&
2699 path_equal_or_files_same(p
->path
, value
+skip
, 0)) {
2700 socket_port_take_fd(p
, fds
, fd
);
2705 log_unit_debug(UNIT(s
), "Unknown serialization key: %s", key
);
2710 static void socket_distribute_fds(Unit
*u
, FDSet
*fds
) {
2711 Socket
*s
= SOCKET(u
);
2716 LIST_FOREACH(port
, p
, s
->ports
) {
2720 if (p
->type
!= SOCKET_SOCKET
)
2726 FDSET_FOREACH(fd
, fds
, i
) {
2727 if (socket_address_matches_fd(&p
->address
, fd
)) {
2728 p
->fd
= fdset_remove(fds
, fd
);
2729 s
->deserialized_state
= SOCKET_LISTENING
;
2736 _pure_
static UnitActiveState
socket_active_state(Unit
*u
) {
2739 return state_translation_table
[SOCKET(u
)->state
];
2742 _pure_
static const char *socket_sub_state_to_string(Unit
*u
) {
2745 return socket_state_to_string(SOCKET(u
)->state
);
2748 const char* socket_port_type_to_string(SocketPort
*p
) {
2756 switch (p
->address
.type
) {
2764 case SOCK_SEQPACKET
:
2765 return "SequentialPacket";
2768 if (socket_address_family(&p
->address
) == AF_NETLINK
)
2776 case SOCKET_SPECIAL
:
2780 return "MessageQueue";
2785 case SOCKET_USB_FUNCTION
:
2786 return "USBFunction";
2793 SocketType
socket_port_type_from_string(const char *s
) {
2796 if (STR_IN_SET(s
, "Stream", "Datagram", "SequentialPacket", "Netlink"))
2797 return SOCKET_SOCKET
;
2798 else if (streq(s
, "Special"))
2799 return SOCKET_SPECIAL
;
2800 else if (streq(s
, "MessageQueue"))
2801 return SOCKET_MQUEUE
;
2802 else if (streq(s
, "FIFO"))
2804 else if (streq(s
, "USBFunction"))
2805 return SOCKET_USB_FUNCTION
;
2807 return _SOCKET_TYPE_INVALID
;
2810 _pure_
static bool socket_may_gc(Unit
*u
) {
2811 Socket
*s
= SOCKET(u
);
2815 return s
->n_connections
== 0;
2818 static int socket_accept_do(Socket
*s
, int fd
) {
2825 cfd
= accept4(fd
, NULL
, NULL
, SOCK_NONBLOCK
);
2839 static int socket_accept_in_cgroup(Socket
*s
, SocketPort
*p
, int fd
) {
2840 _cleanup_close_pair_
int pair
[2] = { -1, -1 };
2848 /* Similar to socket_address_listen_in_cgroup(), but for accept() rathern than socket(): make sure that any
2849 * connection socket is also properly associated with the cgroup. */
2851 if (!IN_SET(p
->address
.sockaddr
.sa
.sa_family
, AF_INET
, AF_INET6
))
2854 r
= bpf_firewall_supported();
2857 if (r
== BPF_FIREWALL_UNSUPPORTED
)
2860 if (socketpair(AF_UNIX
, SOCK_SEQPACKET
|SOCK_CLOEXEC
, 0, pair
) < 0)
2861 return log_unit_error_errno(UNIT(s
), errno
, "Failed to create communication channel: %m");
2863 r
= unit_fork_helper_process(UNIT(s
), "(sd-accept)", &pid
);
2865 return log_unit_error_errno(UNIT(s
), r
, "Failed to fork off accept stub process: %m");
2869 pair
[0] = safe_close(pair
[0]);
2871 cfd
= socket_accept_do(s
, fd
);
2873 log_unit_error_errno(UNIT(s
), cfd
, "Failed to accept connection socket: %m");
2874 _exit(EXIT_FAILURE
);
2877 r
= send_one_fd(pair
[1], cfd
, 0);
2879 log_unit_error_errno(UNIT(s
), r
, "Failed to send connection socket to parent: %m");
2880 _exit(EXIT_FAILURE
);
2883 _exit(EXIT_SUCCESS
);
2886 pair
[1] = safe_close(pair
[1]);
2887 cfd
= receive_one_fd(pair
[0], 0);
2889 /* We synchronously wait for the helper, as it shouldn't be slow */
2890 r
= wait_for_terminate_and_check("(sd-accept)", pid
, WAIT_LOG_ABNORMAL
);
2897 return log_unit_error_errno(UNIT(s
), cfd
, "Failed to receive connection socket: %m");
2902 cfd
= socket_accept_do(s
, fd
);
2904 return log_unit_error_errno(UNIT(s
), cfd
, "Failed to accept connection socket: %m");
2909 static int socket_dispatch_io(sd_event_source
*source
, int fd
, uint32_t revents
, void *userdata
) {
2910 SocketPort
*p
= userdata
;
2916 if (p
->socket
->state
!= SOCKET_LISTENING
)
2919 log_unit_debug(UNIT(p
->socket
), "Incoming traffic");
2921 if (revents
!= EPOLLIN
) {
2923 if (revents
& EPOLLHUP
)
2924 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.");
2926 log_unit_error(UNIT(p
->socket
), "Got unexpected poll event (0x%x) on socket.", revents
);
2930 if (p
->socket
->accept
&&
2931 p
->type
== SOCKET_SOCKET
&&
2932 socket_address_can_accept(&p
->address
)) {
2934 cfd
= socket_accept_in_cgroup(p
->socket
, p
, fd
);
2938 socket_apply_socket_options(p
->socket
, cfd
);
2941 socket_enter_running(p
->socket
, cfd
);
2945 socket_enter_stop_pre(p
->socket
, SOCKET_FAILURE_RESOURCES
);
2949 static void socket_sigchld_event(Unit
*u
, pid_t pid
, int code
, int status
) {
2950 Socket
*s
= SOCKET(u
);
2956 if (pid
!= s
->control_pid
)
2961 if (is_clean_exit(code
, status
, EXIT_CLEAN_COMMAND
, NULL
))
2963 else if (code
== CLD_EXITED
)
2964 f
= SOCKET_FAILURE_EXIT_CODE
;
2965 else if (code
== CLD_KILLED
)
2966 f
= SOCKET_FAILURE_SIGNAL
;
2967 else if (code
== CLD_DUMPED
)
2968 f
= SOCKET_FAILURE_CORE_DUMP
;
2970 assert_not_reached("Unknown sigchld code");
2972 if (s
->control_command
) {
2973 exec_status_exit(&s
->control_command
->exec_status
, &s
->exec_context
, pid
, code
, status
);
2975 if (s
->control_command
->flags
& EXEC_COMMAND_IGNORE_FAILURE
)
2979 log_unit_full(u
, f
== SOCKET_SUCCESS
? LOG_DEBUG
: LOG_NOTICE
, 0,
2980 "Control process exited, code=%s status=%i",
2981 sigchld_code_to_string(code
), status
);
2983 if (s
->result
== SOCKET_SUCCESS
)
2986 if (s
->control_command
&&
2987 s
->control_command
->command_next
&&
2988 f
== SOCKET_SUCCESS
) {
2990 log_unit_debug(u
, "Running next command for state %s", socket_state_to_string(s
->state
));
2993 s
->control_command
= NULL
;
2994 s
->control_command_id
= _SOCKET_EXEC_COMMAND_INVALID
;
2996 /* No further commands for this step, so let's figure
2997 * out what to do next */
2999 log_unit_debug(u
, "Got final SIGCHLD for state %s", socket_state_to_string(s
->state
));
3003 case SOCKET_START_PRE
:
3004 if (f
== SOCKET_SUCCESS
)
3005 socket_enter_start_chown(s
);
3007 socket_enter_signal(s
, SOCKET_FINAL_SIGTERM
, f
);
3010 case SOCKET_START_CHOWN
:
3011 if (f
== SOCKET_SUCCESS
)
3012 socket_enter_start_post(s
);
3014 socket_enter_stop_pre(s
, f
);
3017 case SOCKET_START_POST
:
3018 if (f
== SOCKET_SUCCESS
)
3019 socket_enter_listening(s
);
3021 socket_enter_stop_pre(s
, f
);
3024 case SOCKET_STOP_PRE
:
3025 case SOCKET_STOP_PRE_SIGTERM
:
3026 case SOCKET_STOP_PRE_SIGKILL
:
3027 socket_enter_stop_post(s
, f
);
3030 case SOCKET_STOP_POST
:
3031 case SOCKET_FINAL_SIGTERM
:
3032 case SOCKET_FINAL_SIGKILL
:
3033 socket_enter_dead(s
, f
);
3037 assert_not_reached("Uh, control process died at wrong time.");
3041 /* Notify clients about changed exit status */
3042 unit_add_to_dbus_queue(u
);
3045 static int socket_dispatch_timer(sd_event_source
*source
, usec_t usec
, void *userdata
) {
3046 Socket
*s
= SOCKET(userdata
);
3049 assert(s
->timer_event_source
== source
);
3053 case SOCKET_START_PRE
:
3054 log_unit_warning(UNIT(s
), "Starting timed out. Terminating.");
3055 socket_enter_signal(s
, SOCKET_FINAL_SIGTERM
, SOCKET_FAILURE_TIMEOUT
);
3058 case SOCKET_START_CHOWN
:
3059 case SOCKET_START_POST
:
3060 log_unit_warning(UNIT(s
), "Starting timed out. Stopping.");
3061 socket_enter_stop_pre(s
, SOCKET_FAILURE_TIMEOUT
);
3064 case SOCKET_STOP_PRE
:
3065 log_unit_warning(UNIT(s
), "Stopping timed out. Terminating.");
3066 socket_enter_signal(s
, SOCKET_STOP_PRE_SIGTERM
, SOCKET_FAILURE_TIMEOUT
);
3069 case SOCKET_STOP_PRE_SIGTERM
:
3070 if (s
->kill_context
.send_sigkill
) {
3071 log_unit_warning(UNIT(s
), "Stopping timed out. Killing.");
3072 socket_enter_signal(s
, SOCKET_STOP_PRE_SIGKILL
, SOCKET_FAILURE_TIMEOUT
);
3074 log_unit_warning(UNIT(s
), "Stopping timed out. Skipping SIGKILL. Ignoring.");
3075 socket_enter_stop_post(s
, SOCKET_FAILURE_TIMEOUT
);
3079 case SOCKET_STOP_PRE_SIGKILL
:
3080 log_unit_warning(UNIT(s
), "Processes still around after SIGKILL. Ignoring.");
3081 socket_enter_stop_post(s
, SOCKET_FAILURE_TIMEOUT
);
3084 case SOCKET_STOP_POST
:
3085 log_unit_warning(UNIT(s
), "Stopping timed out (2). Terminating.");
3086 socket_enter_signal(s
, SOCKET_FINAL_SIGTERM
, SOCKET_FAILURE_TIMEOUT
);
3089 case SOCKET_FINAL_SIGTERM
:
3090 if (s
->kill_context
.send_sigkill
) {
3091 log_unit_warning(UNIT(s
), "Stopping timed out (2). Killing.");
3092 socket_enter_signal(s
, SOCKET_FINAL_SIGKILL
, SOCKET_FAILURE_TIMEOUT
);
3094 log_unit_warning(UNIT(s
), "Stopping timed out (2). Skipping SIGKILL. Ignoring.");
3095 socket_enter_dead(s
, SOCKET_FAILURE_TIMEOUT
);
3099 case SOCKET_FINAL_SIGKILL
:
3100 log_unit_warning(UNIT(s
), "Still around after SIGKILL (2). Entering failed mode.");
3101 socket_enter_dead(s
, SOCKET_FAILURE_TIMEOUT
);
3105 assert_not_reached("Timeout at wrong time.");
3111 int socket_collect_fds(Socket
*s
, int **fds
) {
3112 int *rfds
, k
= 0, n
= 0;
3118 /* Called from the service code for requesting our fds */
3120 LIST_FOREACH(port
, p
, s
->ports
) {
3123 n
+= p
->n_auxiliary_fds
;
3135 LIST_FOREACH(port
, p
, s
->ports
) {
3140 for (i
= 0; i
< p
->n_auxiliary_fds
; ++i
)
3141 rfds
[k
++] = p
->auxiliary_fds
[i
];
3150 static void socket_reset_failed(Unit
*u
) {
3151 Socket
*s
= SOCKET(u
);
3155 if (s
->state
== SOCKET_FAILED
)
3156 socket_set_state(s
, SOCKET_DEAD
);
3158 s
->result
= SOCKET_SUCCESS
;
3161 void socket_connection_unref(Socket
*s
) {
3164 /* The service is dead. Yay!
3166 * This is strictly for one-instance-per-connection
3169 assert(s
->n_connections
> 0);
3172 log_unit_debug(UNIT(s
), "One connection closed, %u left.", s
->n_connections
);
3175 static void socket_trigger_notify(Unit
*u
, Unit
*other
) {
3176 Socket
*s
= SOCKET(u
);
3181 /* Filter out invocations with bogus state */
3182 if (other
->load_state
!= UNIT_LOADED
|| other
->type
!= UNIT_SERVICE
)
3185 /* Don't propagate state changes from the service if we are already down */
3186 if (!IN_SET(s
->state
, SOCKET_RUNNING
, SOCKET_LISTENING
))
3189 /* We don't care for the service state if we are in Accept=yes mode */
3193 /* Propagate start limit hit state */
3194 if (other
->start_limit_hit
) {
3195 socket_enter_stop_pre(s
, SOCKET_FAILURE_SERVICE_START_LIMIT_HIT
);
3199 /* Don't propagate anything if there's still a job queued */
3203 if (IN_SET(SERVICE(other
)->state
,
3204 SERVICE_DEAD
, SERVICE_FAILED
,
3205 SERVICE_FINAL_SIGTERM
, SERVICE_FINAL_SIGKILL
,
3206 SERVICE_AUTO_RESTART
))
3207 socket_enter_listening(s
);
3209 if (SERVICE(other
)->state
== SERVICE_RUNNING
)
3210 socket_set_state(s
, SOCKET_RUNNING
);
3213 static int socket_kill(Unit
*u
, KillWho who
, int signo
, sd_bus_error
*error
) {
3214 return unit_kill_common(u
, who
, signo
, -1, SOCKET(u
)->control_pid
, error
);
3217 static int socket_get_timeout(Unit
*u
, usec_t
*timeout
) {
3218 Socket
*s
= SOCKET(u
);
3222 if (!s
->timer_event_source
)
3225 r
= sd_event_source_get_time(s
->timer_event_source
, &t
);
3228 if (t
== USEC_INFINITY
)
3235 char *socket_fdname(Socket
*s
) {
3238 /* Returns the name to use for $LISTEN_NAMES. If the user
3239 * didn't specify anything specifically, use the socket unit's
3240 * name as fallback. */
3242 return s
->fdname
?: UNIT(s
)->id
;
3245 static int socket_control_pid(Unit
*u
) {
3246 Socket
*s
= SOCKET(u
);
3250 return s
->control_pid
;
3253 static const char* const socket_exec_command_table
[_SOCKET_EXEC_COMMAND_MAX
] = {
3254 [SOCKET_EXEC_START_PRE
] = "ExecStartPre",
3255 [SOCKET_EXEC_START_CHOWN
] = "ExecStartChown",
3256 [SOCKET_EXEC_START_POST
] = "ExecStartPost",
3257 [SOCKET_EXEC_STOP_PRE
] = "ExecStopPre",
3258 [SOCKET_EXEC_STOP_POST
] = "ExecStopPost"
3261 DEFINE_STRING_TABLE_LOOKUP(socket_exec_command
, SocketExecCommand
);
3263 static const char* const socket_result_table
[_SOCKET_RESULT_MAX
] = {
3264 [SOCKET_SUCCESS
] = "success",
3265 [SOCKET_FAILURE_RESOURCES
] = "resources",
3266 [SOCKET_FAILURE_TIMEOUT
] = "timeout",
3267 [SOCKET_FAILURE_EXIT_CODE
] = "exit-code",
3268 [SOCKET_FAILURE_SIGNAL
] = "signal",
3269 [SOCKET_FAILURE_CORE_DUMP
] = "core-dump",
3270 [SOCKET_FAILURE_START_LIMIT_HIT
] = "start-limit-hit",
3271 [SOCKET_FAILURE_TRIGGER_LIMIT_HIT
] = "trigger-limit-hit",
3272 [SOCKET_FAILURE_SERVICE_START_LIMIT_HIT
] = "service-start-limit-hit"
3275 DEFINE_STRING_TABLE_LOOKUP(socket_result
, SocketResult
);
3277 const UnitVTable socket_vtable
= {
3278 .object_size
= sizeof(Socket
),
3279 .exec_context_offset
= offsetof(Socket
, exec_context
),
3280 .cgroup_context_offset
= offsetof(Socket
, cgroup_context
),
3281 .kill_context_offset
= offsetof(Socket
, kill_context
),
3282 .exec_runtime_offset
= offsetof(Socket
, exec_runtime
),
3283 .dynamic_creds_offset
= offsetof(Socket
, dynamic_creds
),
3289 .private_section
= "Socket",
3291 .can_transient
= true,
3293 .init
= socket_init
,
3294 .done
= socket_done
,
3295 .load
= socket_load
,
3297 .coldplug
= socket_coldplug
,
3299 .dump
= socket_dump
,
3301 .start
= socket_start
,
3302 .stop
= socket_stop
,
3304 .kill
= socket_kill
,
3306 .get_timeout
= socket_get_timeout
,
3308 .serialize
= socket_serialize
,
3309 .deserialize_item
= socket_deserialize_item
,
3310 .distribute_fds
= socket_distribute_fds
,
3312 .active_state
= socket_active_state
,
3313 .sub_state_to_string
= socket_sub_state_to_string
,
3315 .may_gc
= socket_may_gc
,
3317 .sigchld_event
= socket_sigchld_event
,
3319 .trigger_notify
= socket_trigger_notify
,
3321 .reset_failed
= socket_reset_failed
,
3323 .control_pid
= socket_control_pid
,
3325 .bus_vtable
= bus_socket_vtable
,
3326 .bus_set_property
= bus_socket_set_property
,
3327 .bus_commit_properties
= bus_socket_commit_properties
,
3329 .status_message_formats
= {
3330 /*.starting_stopping = {
3331 [0] = "Starting socket %s...",
3332 [1] = "Stopping socket %s...",
3334 .finished_start_job
= {
3335 [JOB_DONE
] = "Listening on %s.",
3336 [JOB_FAILED
] = "Failed to listen on %s.",
3337 [JOB_TIMEOUT
] = "Timed out starting %s.",
3339 .finished_stop_job
= {
3340 [JOB_DONE
] = "Closed %s.",
3341 [JOB_FAILED
] = "Failed stopping %s.",
3342 [JOB_TIMEOUT
] = "Timed out stopping %s.",