2 This file is part of systemd.
4 Copyright 2010 Lennart Poettering
6 systemd is free software; you can redistribute it and/or modify it
7 under the terms of the GNU Lesser General Public License as published by
8 the Free Software Foundation; either version 2.1 of the License, or
9 (at your option) any later version.
11 systemd is distributed in the hope that it will be useful, but
12 WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 Lesser General Public License for more details.
16 You should have received a copy of the GNU Lesser General Public License
17 along with systemd; If not, see <http://www.gnu.org/licenses/>.
20 #include <arpa/inet.h>
24 #include <netinet/tcp.h>
26 #include <sys/epoll.h>
29 #include <linux/sctp.h>
31 #include "alloc-util.h"
32 #include "bus-error.h"
35 #include "dbus-socket.h"
37 #include "exit-status.h"
39 #include "formats-util.h"
45 #include "parse-util.h"
46 #include "path-util.h"
47 #include "process-util.h"
48 #include "selinux-util.h"
49 #include "signal-util.h"
50 #include "smack-util.h"
53 #include "string-table.h"
54 #include "string-util.h"
56 #include "unit-name.h"
57 #include "unit-printf.h"
59 #include "user-util.h"
61 static const UnitActiveState state_translation_table
[_SOCKET_STATE_MAX
] = {
62 [SOCKET_DEAD
] = UNIT_INACTIVE
,
63 [SOCKET_START_PRE
] = UNIT_ACTIVATING
,
64 [SOCKET_START_CHOWN
] = UNIT_ACTIVATING
,
65 [SOCKET_START_POST
] = UNIT_ACTIVATING
,
66 [SOCKET_LISTENING
] = UNIT_ACTIVE
,
67 [SOCKET_RUNNING
] = UNIT_ACTIVE
,
68 [SOCKET_STOP_PRE
] = UNIT_DEACTIVATING
,
69 [SOCKET_STOP_PRE_SIGTERM
] = UNIT_DEACTIVATING
,
70 [SOCKET_STOP_PRE_SIGKILL
] = UNIT_DEACTIVATING
,
71 [SOCKET_STOP_POST
] = UNIT_DEACTIVATING
,
72 [SOCKET_FINAL_SIGTERM
] = UNIT_DEACTIVATING
,
73 [SOCKET_FINAL_SIGKILL
] = UNIT_DEACTIVATING
,
74 [SOCKET_FAILED
] = UNIT_FAILED
77 static int socket_dispatch_io(sd_event_source
*source
, int fd
, uint32_t revents
, void *userdata
);
78 static int socket_dispatch_timer(sd_event_source
*source
, usec_t usec
, void *userdata
);
80 static void socket_init(Unit
*u
) {
81 Socket
*s
= SOCKET(u
);
84 assert(u
->load_state
== UNIT_STUB
);
86 s
->backlog
= SOMAXCONN
;
87 s
->timeout_usec
= u
->manager
->default_timeout_start_usec
;
88 s
->directory_mode
= 0755;
89 s
->socket_mode
= 0666;
91 s
->max_connections
= 64;
98 s
->exec_context
.std_output
= u
->manager
->default_std_output
;
99 s
->exec_context
.std_error
= u
->manager
->default_std_error
;
101 s
->control_command_id
= _SOCKET_EXEC_COMMAND_INVALID
;
103 s
->trigger_limit
.interval
= USEC_INFINITY
;
104 s
->trigger_limit
.burst
= (unsigned) -1;
107 static void socket_unwatch_control_pid(Socket
*s
) {
110 if (s
->control_pid
<= 0)
113 unit_unwatch_pid(UNIT(s
), s
->control_pid
);
117 static void socket_cleanup_fd_list(SocketPort
*p
) {
120 close_many(p
->auxiliary_fds
, p
->n_auxiliary_fds
);
121 p
->auxiliary_fds
= mfree(p
->auxiliary_fds
);
122 p
->n_auxiliary_fds
= 0;
125 void socket_free_ports(Socket
*s
) {
130 while ((p
= s
->ports
)) {
131 LIST_REMOVE(port
, s
->ports
, p
);
133 sd_event_source_unref(p
->event_source
);
135 socket_cleanup_fd_list(p
);
142 static void socket_done(Unit
*u
) {
143 Socket
*s
= SOCKET(u
);
147 socket_free_ports(s
);
149 s
->exec_runtime
= exec_runtime_unref(s
->exec_runtime
);
150 exec_command_free_array(s
->exec_command
, _SOCKET_EXEC_COMMAND_MAX
);
151 s
->control_command
= NULL
;
153 socket_unwatch_control_pid(s
);
155 unit_ref_unset(&s
->service
);
157 s
->tcp_congestion
= mfree(s
->tcp_congestion
);
158 s
->bind_to_device
= mfree(s
->bind_to_device
);
160 s
->smack
= mfree(s
->smack
);
161 s
->smack_ip_in
= mfree(s
->smack_ip_in
);
162 s
->smack_ip_out
= mfree(s
->smack_ip_out
);
164 strv_free(s
->symlinks
);
166 s
->user
= mfree(s
->user
);
167 s
->group
= mfree(s
->group
);
169 s
->fdname
= mfree(s
->fdname
);
171 s
->timer_event_source
= sd_event_source_unref(s
->timer_event_source
);
174 static int socket_arm_timer(Socket
*s
, usec_t usec
) {
179 if (s
->timer_event_source
) {
180 r
= sd_event_source_set_time(s
->timer_event_source
, usec
);
184 return sd_event_source_set_enabled(s
->timer_event_source
, SD_EVENT_ONESHOT
);
187 if (usec
== USEC_INFINITY
)
190 r
= sd_event_add_time(
191 UNIT(s
)->manager
->event
,
192 &s
->timer_event_source
,
195 socket_dispatch_timer
, s
);
199 (void) sd_event_source_set_description(s
->timer_event_source
, "socket-timer");
204 int socket_instantiate_service(Socket
*s
) {
205 _cleanup_free_
char *prefix
= NULL
, *name
= NULL
;
211 /* This fills in s->service if it isn't filled in yet. For
212 * Accept=yes sockets we create the next connection service
213 * here. For Accept=no this is mostly a NOP since the service
214 * is figured out at load time anyway. */
216 if (UNIT_DEREF(s
->service
))
222 r
= unit_name_to_prefix(UNIT(s
)->id
, &prefix
);
226 if (asprintf(&name
, "%s@%u.service", prefix
, s
->n_accepted
) < 0)
229 r
= manager_load_unit(UNIT(s
)->manager
, name
, NULL
, NULL
, &u
);
233 unit_ref_set(&s
->service
, u
);
235 return unit_add_two_dependencies(UNIT(s
), UNIT_BEFORE
, UNIT_TRIGGERS
, u
, false);
238 static bool have_non_accept_socket(Socket
*s
) {
246 LIST_FOREACH(port
, p
, s
->ports
) {
248 if (p
->type
!= SOCKET_SOCKET
)
251 if (!socket_address_can_accept(&p
->address
))
258 static int socket_add_mount_links(Socket
*s
) {
264 LIST_FOREACH(port
, p
, s
->ports
) {
265 const char *path
= NULL
;
267 if (p
->type
== SOCKET_SOCKET
)
268 path
= socket_address_get_path(&p
->address
);
269 else if (IN_SET(p
->type
, SOCKET_FIFO
, SOCKET_SPECIAL
, SOCKET_USB_FUNCTION
))
275 r
= unit_require_mounts_for(UNIT(s
), path
);
283 static int socket_add_device_link(Socket
*s
) {
288 if (!s
->bind_to_device
|| streq(s
->bind_to_device
, "lo"))
291 t
= strjoina("/sys/subsystem/net/devices/", s
->bind_to_device
);
292 return unit_add_node_link(UNIT(s
), t
, false, UNIT_BINDS_TO
);
295 static int socket_add_default_dependencies(Socket
*s
) {
299 if (!UNIT(s
)->default_dependencies
)
302 r
= unit_add_dependency_by_name(UNIT(s
), UNIT_BEFORE
, SPECIAL_SOCKETS_TARGET
, NULL
, true);
306 if (MANAGER_IS_SYSTEM(UNIT(s
)->manager
)) {
307 r
= unit_add_two_dependencies_by_name(UNIT(s
), UNIT_AFTER
, UNIT_REQUIRES
, SPECIAL_SYSINIT_TARGET
, NULL
, true);
312 return unit_add_two_dependencies_by_name(UNIT(s
), UNIT_BEFORE
, UNIT_CONFLICTS
, SPECIAL_SHUTDOWN_TARGET
, NULL
, true);
315 _pure_
static bool socket_has_exec(Socket
*s
) {
319 for (i
= 0; i
< _SOCKET_EXEC_COMMAND_MAX
; i
++)
320 if (s
->exec_command
[i
])
326 static int socket_add_extras(Socket
*s
) {
332 /* Pick defaults for the trigger limit, if nothing was explicitly configured. We pick a relatively high limit
333 * in Accept=yes mode, and a lower limit for Accept=no. Reason: in Accept=yes mode we are invoking accept()
334 * ourselves before the trigger limit can hit, thus incoming connections are taken off the socket queue quickly
335 * and reliably. This is different for Accept=no, where the spawned service has to take the incoming traffic
336 * off the queues, which it might not necessarily do. Moreover, while Accept=no services are supposed to
337 * process whatever is queued in one go, and thus should normally never have to be started frequently. This is
338 * different for Accept=yes where each connection is processed by a new service instance, and thus frequent
339 * service starts are typical. */
341 if (s
->trigger_limit
.interval
== USEC_INFINITY
)
342 s
->trigger_limit
.interval
= 2 * USEC_PER_SEC
;
344 if (s
->trigger_limit
.burst
== (unsigned) -1) {
346 s
->trigger_limit
.burst
= 200;
348 s
->trigger_limit
.burst
= 20;
351 if (have_non_accept_socket(s
)) {
353 if (!UNIT_DEREF(s
->service
)) {
356 r
= unit_load_related_unit(u
, ".service", &x
);
360 unit_ref_set(&s
->service
, x
);
363 r
= unit_add_two_dependencies(u
, UNIT_BEFORE
, UNIT_TRIGGERS
, UNIT_DEREF(s
->service
), true);
368 r
= socket_add_mount_links(s
);
372 r
= socket_add_device_link(s
);
376 r
= unit_patch_contexts(u
);
380 if (socket_has_exec(s
)) {
381 r
= unit_add_exec_dependencies(u
, &s
->exec_context
);
385 r
= unit_set_default_slice(u
);
390 r
= socket_add_default_dependencies(s
);
397 static const char *socket_find_symlink_target(Socket
*s
) {
398 const char *found
= NULL
;
401 LIST_FOREACH(port
, p
, s
->ports
) {
402 const char *f
= NULL
;
411 if (p
->address
.sockaddr
.un
.sun_path
[0] != 0)
412 f
= p
->address
.sockaddr
.un
.sun_path
;
430 static int socket_verify(Socket
*s
) {
433 if (UNIT(s
)->load_state
!= UNIT_LOADED
)
437 log_unit_error(UNIT(s
), "Unit lacks Listen setting. Refusing.");
441 if (s
->accept
&& have_non_accept_socket(s
)) {
442 log_unit_error(UNIT(s
), "Unit configured for accepting sockets, but sockets are non-accepting. Refusing.");
446 if (s
->accept
&& s
->max_connections
<= 0) {
447 log_unit_error(UNIT(s
), "MaxConnection= setting too small. Refusing.");
451 if (s
->accept
&& UNIT_DEREF(s
->service
)) {
452 log_unit_error(UNIT(s
), "Explicit service configuration for accepting socket units not supported. Refusing.");
456 if (s
->exec_context
.pam_name
&& s
->kill_context
.kill_mode
!= KILL_CONTROL_GROUP
) {
457 log_unit_error(UNIT(s
), "Unit has PAM enabled. Kill mode must be set to 'control-group'. Refusing.");
461 if (!strv_isempty(s
->symlinks
) && !socket_find_symlink_target(s
)) {
462 log_unit_error(UNIT(s
), "Unit has symlinks set but none or more than one node in the file system. Refusing.");
469 static int socket_load(Unit
*u
) {
470 Socket
*s
= SOCKET(u
);
474 assert(u
->load_state
== UNIT_STUB
);
476 r
= unit_load_fragment_and_dropin(u
);
480 if (u
->load_state
== UNIT_LOADED
) {
481 /* This is a new unit? Then let's add in some extras */
482 r
= socket_add_extras(s
);
487 return socket_verify(s
);
490 _const_
static const char* listen_lookup(int family
, int type
) {
492 if (family
== AF_NETLINK
)
493 return "ListenNetlink";
495 if (type
== SOCK_STREAM
)
496 return "ListenStream";
497 else if (type
== SOCK_DGRAM
)
498 return "ListenDatagram";
499 else if (type
== SOCK_SEQPACKET
)
500 return "ListenSequentialPacket";
502 assert_not_reached("Unknown socket type");
506 static void socket_dump(Unit
*u
, FILE *f
, const char *prefix
) {
507 char time_string
[FORMAT_TIMESPAN_MAX
];
509 Socket
*s
= SOCKET(u
);
516 prefix
= strempty(prefix
);
517 prefix2
= strjoina(prefix
, "\t");
520 "%sSocket State: %s\n"
522 "%sBindIPv6Only: %s\n"
524 "%sSocketMode: %04o\n"
525 "%sDirectoryMode: %04o\n"
529 "%sTransparent: %s\n"
531 "%sPassCredentials: %s\n"
532 "%sPassSecurity: %s\n"
533 "%sTCPCongestion: %s\n"
534 "%sRemoveOnStop: %s\n"
537 "%sSELinuxContextFromNet: %s\n",
538 prefix
, socket_state_to_string(s
->state
),
539 prefix
, socket_result_to_string(s
->result
),
540 prefix
, socket_address_bind_ipv6_only_to_string(s
->bind_ipv6_only
),
542 prefix
, s
->socket_mode
,
543 prefix
, s
->directory_mode
,
544 prefix
, yes_no(s
->keep_alive
),
545 prefix
, yes_no(s
->no_delay
),
546 prefix
, yes_no(s
->free_bind
),
547 prefix
, yes_no(s
->transparent
),
548 prefix
, yes_no(s
->broadcast
),
549 prefix
, yes_no(s
->pass_cred
),
550 prefix
, yes_no(s
->pass_sec
),
551 prefix
, strna(s
->tcp_congestion
),
552 prefix
, yes_no(s
->remove_on_stop
),
553 prefix
, yes_no(s
->writable
),
554 prefix
, socket_fdname(s
),
555 prefix
, yes_no(s
->selinux_context_from_net
));
557 if (s
->control_pid
> 0)
559 "%sControl PID: "PID_FMT
"\n",
560 prefix
, s
->control_pid
);
562 if (s
->bind_to_device
)
564 "%sBindToDevice: %s\n",
565 prefix
, s
->bind_to_device
);
570 "%sNConnections: %u\n"
571 "%sMaxConnections: %u\n",
572 prefix
, s
->n_accepted
,
573 prefix
, s
->n_connections
,
574 prefix
, s
->max_connections
);
576 if (s
->priority
>= 0)
579 prefix
, s
->priority
);
581 if (s
->receive_buffer
> 0)
583 "%sReceiveBuffer: %zu\n",
584 prefix
, s
->receive_buffer
);
586 if (s
->send_buffer
> 0)
588 "%sSendBuffer: %zu\n",
589 prefix
, s
->send_buffer
);
601 if (s
->pipe_size
> 0)
604 prefix
, s
->pipe_size
);
611 if (s
->mq_maxmsg
> 0)
613 "%sMessageQueueMaxMessages: %li\n",
614 prefix
, s
->mq_maxmsg
);
616 if (s
->mq_msgsize
> 0)
618 "%sMessageQueueMessageSize: %li\n",
619 prefix
, s
->mq_msgsize
);
624 prefix
, yes_no(s
->reuse_port
));
628 "%sSmackLabel: %s\n",
633 "%sSmackLabelIPIn: %s\n",
634 prefix
, s
->smack_ip_in
);
638 "%sSmackLabelIPOut: %s\n",
639 prefix
, s
->smack_ip_out
);
641 if (!isempty(s
->user
) || !isempty(s
->group
))
644 "%sSocketGroup: %s\n",
645 prefix
, strna(s
->user
),
646 prefix
, strna(s
->group
));
648 if (s
->keep_alive_time
> 0)
650 "%sKeepAliveTimeSec: %s\n",
651 prefix
, format_timespan(time_string
, FORMAT_TIMESPAN_MAX
, s
->keep_alive_time
, USEC_PER_SEC
));
653 if (s
->keep_alive_interval
)
655 "%sKeepAliveIntervalSec: %s\n",
656 prefix
, format_timespan(time_string
, FORMAT_TIMESPAN_MAX
, s
->keep_alive_interval
, USEC_PER_SEC
));
658 if (s
->keep_alive_cnt
)
660 "%sKeepAliveProbes: %u\n",
661 prefix
, s
->keep_alive_cnt
);
665 "%sDeferAcceptSec: %s\n",
666 prefix
, format_timespan(time_string
, FORMAT_TIMESPAN_MAX
, s
->defer_accept
, USEC_PER_SEC
));
668 LIST_FOREACH(port
, p
, s
->ports
) {
670 if (p
->type
== SOCKET_SOCKET
) {
675 r
= socket_address_print(&p
->address
, &k
);
681 fprintf(f
, "%s%s: %s\n", prefix
, listen_lookup(socket_address_family(&p
->address
), p
->address
.type
), t
);
683 } else if (p
->type
== SOCKET_SPECIAL
)
684 fprintf(f
, "%sListenSpecial: %s\n", prefix
, p
->path
);
685 else if (p
->type
== SOCKET_USB_FUNCTION
)
686 fprintf(f
, "%sListenUSBFunction: %s\n", prefix
, p
->path
);
687 else if (p
->type
== SOCKET_MQUEUE
)
688 fprintf(f
, "%sListenMessageQueue: %s\n", prefix
, p
->path
);
690 fprintf(f
, "%sListenFIFO: %s\n", prefix
, p
->path
);
694 "%sTriggerLimitIntervalSec: %s\n"
695 "%sTriggerLimitBurst: %u\n",
696 prefix
, format_timespan(time_string
, FORMAT_TIMESPAN_MAX
, s
->trigger_limit
.interval
, USEC_PER_SEC
),
697 prefix
, s
->trigger_limit
.burst
);
699 exec_context_dump(&s
->exec_context
, f
, prefix
);
700 kill_context_dump(&s
->kill_context
, f
, prefix
);
702 for (c
= 0; c
< _SOCKET_EXEC_COMMAND_MAX
; c
++) {
703 if (!s
->exec_command
[c
])
706 fprintf(f
, "%s-> %s:\n",
707 prefix
, socket_exec_command_to_string(c
));
709 exec_command_dump_list(s
->exec_command
[c
], f
, prefix2
);
713 static int instance_from_socket(int fd
, unsigned nr
, char **instance
) {
716 union sockaddr_union local
, remote
;
722 if (getsockname(fd
, &local
.sa
, &l
) < 0)
726 if (getpeername(fd
, &remote
.sa
, &l
) < 0)
729 switch (local
.sa
.sa_family
) {
733 a
= ntohl(local
.in
.sin_addr
.s_addr
),
734 b
= ntohl(remote
.in
.sin_addr
.s_addr
);
737 "%u-%u.%u.%u.%u:%u-%u.%u.%u.%u:%u",
739 a
>> 24, (a
>> 16) & 0xFF, (a
>> 8) & 0xFF, a
& 0xFF,
740 ntohs(local
.in
.sin_port
),
741 b
>> 24, (b
>> 16) & 0xFF, (b
>> 8) & 0xFF, b
& 0xFF,
742 ntohs(remote
.in
.sin_port
)) < 0)
749 static const unsigned char ipv4_prefix
[] = {
750 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xFF, 0xFF
753 if (memcmp(&local
.in6
.sin6_addr
, ipv4_prefix
, sizeof(ipv4_prefix
)) == 0 &&
754 memcmp(&remote
.in6
.sin6_addr
, ipv4_prefix
, sizeof(ipv4_prefix
)) == 0) {
756 *a
= local
.in6
.sin6_addr
.s6_addr
+12,
757 *b
= remote
.in6
.sin6_addr
.s6_addr
+12;
760 "%u-%u.%u.%u.%u:%u-%u.%u.%u.%u:%u",
762 a
[0], a
[1], a
[2], a
[3],
763 ntohs(local
.in6
.sin6_port
),
764 b
[0], b
[1], b
[2], b
[3],
765 ntohs(remote
.in6
.sin6_port
)) < 0)
768 char a
[INET6_ADDRSTRLEN
], b
[INET6_ADDRSTRLEN
];
773 inet_ntop(AF_INET6
, &local
.in6
.sin6_addr
, a
, sizeof(a
)),
774 ntohs(local
.in6
.sin6_port
),
775 inet_ntop(AF_INET6
, &remote
.in6
.sin6_addr
, b
, sizeof(b
)),
776 ntohs(remote
.in6
.sin6_port
)) < 0)
787 k
= getpeercred(fd
, &ucred
);
790 "%u-"PID_FMT
"-"UID_FMT
,
791 nr
, ucred
.pid
, ucred
.uid
) < 0)
793 } else if (k
== -ENODATA
) {
794 /* This handles the case where somebody is
795 * connecting from another pid/uid namespace
796 * (e.g. from outside of our container). */
808 assert_not_reached("Unhandled socket type.");
815 static void socket_close_fds(Socket
*s
) {
821 LIST_FOREACH(port
, p
, s
->ports
) {
824 was_open
= p
->fd
>= 0;
826 p
->event_source
= sd_event_source_unref(p
->event_source
);
827 p
->fd
= safe_close(p
->fd
);
828 socket_cleanup_fd_list(p
);
830 /* One little note: we should normally not delete any sockets in the file system here! After all some
831 * other process we spawned might still have a reference of this fd and wants to continue to use
832 * it. Therefore we normally delete sockets in the file system before we create a new one, not after we
833 * stopped using one! That all said, if the user explicitly requested this, we'll delete them here
834 * anyway, but only then. */
836 if (!was_open
|| !s
->remove_on_stop
)
842 (void) unlink(p
->path
);
846 (void) mq_unlink(p
->path
);
850 (void) socket_address_unlink(&p
->address
);
858 if (s
->remove_on_stop
)
859 STRV_FOREACH(i
, s
->symlinks
)
863 static void socket_apply_socket_options(Socket
*s
, int fd
) {
870 int b
= s
->keep_alive
;
871 if (setsockopt(fd
, SOL_SOCKET
, SO_KEEPALIVE
, &b
, sizeof(b
)) < 0)
872 log_unit_warning_errno(UNIT(s
), errno
, "SO_KEEPALIVE failed: %m");
875 if (s
->keep_alive_time
) {
876 int value
= s
->keep_alive_time
/ USEC_PER_SEC
;
877 if (setsockopt(fd
, SOL_TCP
, TCP_KEEPIDLE
, &value
, sizeof(value
)) < 0)
878 log_unit_warning_errno(UNIT(s
), errno
, "TCP_KEEPIDLE failed: %m");
881 if (s
->keep_alive_interval
) {
882 int value
= s
->keep_alive_interval
/ USEC_PER_SEC
;
883 if (setsockopt(fd
, SOL_TCP
, TCP_KEEPINTVL
, &value
, sizeof(value
)) < 0)
884 log_unit_warning_errno(UNIT(s
), errno
, "TCP_KEEPINTVL failed: %m");
887 if (s
->keep_alive_cnt
) {
888 int value
= s
->keep_alive_cnt
;
889 if (setsockopt(fd
, SOL_TCP
, TCP_KEEPCNT
, &value
, sizeof(value
)) < 0)
890 log_unit_warning_errno(UNIT(s
), errno
, "TCP_KEEPCNT failed: %m");
893 if (s
->defer_accept
) {
894 int value
= s
->defer_accept
/ USEC_PER_SEC
;
895 if (setsockopt(fd
, SOL_TCP
, TCP_DEFER_ACCEPT
, &value
, sizeof(value
)) < 0)
896 log_unit_warning_errno(UNIT(s
), errno
, "TCP_DEFER_ACCEPT failed: %m");
902 if (s
->socket_protocol
== IPPROTO_SCTP
) {
903 if (setsockopt(fd
, SOL_SCTP
, SCTP_NODELAY
, &b
, sizeof(b
)) < 0)
904 log_unit_warning_errno(UNIT(s
), errno
, "SCTP_NODELAY failed: %m");
906 if (setsockopt(fd
, SOL_TCP
, TCP_NODELAY
, &b
, sizeof(b
)) < 0)
907 log_unit_warning_errno(UNIT(s
), errno
, "TCP_NODELAY failed: %m");
913 if (setsockopt(fd
, SOL_SOCKET
, SO_BROADCAST
, &one
, sizeof(one
)) < 0)
914 log_unit_warning_errno(UNIT(s
), errno
, "SO_BROADCAST failed: %m");
919 if (setsockopt(fd
, SOL_SOCKET
, SO_PASSCRED
, &one
, sizeof(one
)) < 0)
920 log_unit_warning_errno(UNIT(s
), errno
, "SO_PASSCRED failed: %m");
925 if (setsockopt(fd
, SOL_SOCKET
, SO_PASSSEC
, &one
, sizeof(one
)) < 0)
926 log_unit_warning_errno(UNIT(s
), errno
, "SO_PASSSEC failed: %m");
929 if (s
->priority
>= 0)
930 if (setsockopt(fd
, SOL_SOCKET
, SO_PRIORITY
, &s
->priority
, sizeof(s
->priority
)) < 0)
931 log_unit_warning_errno(UNIT(s
), errno
, "SO_PRIORITY failed: %m");
933 if (s
->receive_buffer
> 0) {
934 int value
= (int) s
->receive_buffer
;
936 /* We first try with SO_RCVBUFFORCE, in case we have the perms for that */
938 if (setsockopt(fd
, SOL_SOCKET
, SO_RCVBUFFORCE
, &value
, sizeof(value
)) < 0)
939 if (setsockopt(fd
, SOL_SOCKET
, SO_RCVBUF
, &value
, sizeof(value
)) < 0)
940 log_unit_warning_errno(UNIT(s
), errno
, "SO_RCVBUF failed: %m");
943 if (s
->send_buffer
> 0) {
944 int value
= (int) s
->send_buffer
;
945 if (setsockopt(fd
, SOL_SOCKET
, SO_SNDBUFFORCE
, &value
, sizeof(value
)) < 0)
946 if (setsockopt(fd
, SOL_SOCKET
, SO_SNDBUF
, &value
, sizeof(value
)) < 0)
947 log_unit_warning_errno(UNIT(s
), errno
, "SO_SNDBUF failed: %m");
951 if (setsockopt(fd
, SOL_SOCKET
, SO_MARK
, &s
->mark
, sizeof(s
->mark
)) < 0)
952 log_unit_warning_errno(UNIT(s
), errno
, "SO_MARK failed: %m");
955 if (setsockopt(fd
, IPPROTO_IP
, IP_TOS
, &s
->ip_tos
, sizeof(s
->ip_tos
)) < 0)
956 log_unit_warning_errno(UNIT(s
), errno
, "IP_TOS failed: %m");
958 if (s
->ip_ttl
>= 0) {
961 r
= setsockopt(fd
, IPPROTO_IP
, IP_TTL
, &s
->ip_ttl
, sizeof(s
->ip_ttl
));
963 if (socket_ipv6_is_supported())
964 x
= setsockopt(fd
, IPPROTO_IPV6
, IPV6_UNICAST_HOPS
, &s
->ip_ttl
, sizeof(s
->ip_ttl
));
967 errno
= EAFNOSUPPORT
;
971 log_unit_warning_errno(UNIT(s
), errno
, "IP_TTL/IPV6_UNICAST_HOPS failed: %m");
974 if (s
->tcp_congestion
)
975 if (setsockopt(fd
, SOL_TCP
, TCP_CONGESTION
, s
->tcp_congestion
, strlen(s
->tcp_congestion
)+1) < 0)
976 log_unit_warning_errno(UNIT(s
), errno
, "TCP_CONGESTION failed: %m");
978 if (s
->smack_ip_in
) {
979 r
= mac_smack_apply_fd(fd
, SMACK_ATTR_IPIN
, s
->smack_ip_in
);
981 log_unit_error_errno(UNIT(s
), r
, "mac_smack_apply_ip_in_fd: %m");
984 if (s
->smack_ip_out
) {
985 r
= mac_smack_apply_fd(fd
, SMACK_ATTR_IPOUT
, s
->smack_ip_out
);
987 log_unit_error_errno(UNIT(s
), r
, "mac_smack_apply_ip_out_fd: %m");
991 static void socket_apply_fifo_options(Socket
*s
, int fd
) {
997 if (s
->pipe_size
> 0)
998 if (fcntl(fd
, F_SETPIPE_SZ
, s
->pipe_size
) < 0)
999 log_unit_warning_errno(UNIT(s
), errno
, "Setting pipe size failed, ignoring: %m");
1002 r
= mac_smack_apply_fd(fd
, SMACK_ATTR_ACCESS
, s
->smack
);
1004 log_unit_error_errno(UNIT(s
), r
, "SMACK relabelling failed, ignoring: %m");
1008 static int fifo_address_create(
1010 mode_t directory_mode
,
1011 mode_t socket_mode
) {
1013 _cleanup_close_
int fd
= -1;
1020 mkdir_parents_label(path
, directory_mode
);
1022 r
= mac_selinux_create_file_prepare(path
, S_IFIFO
);
1026 /* Enforce the right access mode for the fifo */
1027 old_mask
= umask(~ socket_mode
);
1029 /* Include the original umask in our mask */
1030 (void) umask(~socket_mode
| old_mask
);
1032 r
= mkfifo(path
, socket_mode
);
1033 (void) umask(old_mask
);
1035 if (r
< 0 && errno
!= EEXIST
) {
1040 fd
= open(path
, O_RDWR
| O_CLOEXEC
| O_NOCTTY
| O_NONBLOCK
| O_NOFOLLOW
);
1046 mac_selinux_create_file_clear();
1048 if (fstat(fd
, &st
) < 0) {
1053 if (!S_ISFIFO(st
.st_mode
) ||
1054 (st
.st_mode
& 0777) != (socket_mode
& ~old_mask
) ||
1055 st
.st_uid
!= getuid() ||
1056 st
.st_gid
!= getgid()) {
1067 mac_selinux_create_file_clear();
1071 static int special_address_create(const char *path
, bool writable
) {
1072 _cleanup_close_
int fd
= -1;
1078 fd
= open(path
, (writable
? O_RDWR
: O_RDONLY
)|O_CLOEXEC
|O_NOCTTY
|O_NONBLOCK
|O_NOFOLLOW
);
1082 if (fstat(fd
, &st
) < 0)
1085 /* Check whether this is a /proc, /sys or /dev file or char device */
1086 if (!S_ISREG(st
.st_mode
) && !S_ISCHR(st
.st_mode
))
1095 static int usbffs_address_create(const char *path
) {
1096 _cleanup_close_
int fd
= -1;
1102 fd
= open(path
, O_RDWR
|O_CLOEXEC
|O_NOCTTY
|O_NONBLOCK
|O_NOFOLLOW
);
1106 if (fstat(fd
, &st
) < 0)
1109 /* Check whether this is a regular file (ffs endpoint)*/
1110 if (!S_ISREG(st
.st_mode
))
1119 static int mq_address_create(
1125 _cleanup_close_
int fd
= -1;
1128 struct mq_attr _attr
, *attr
= NULL
;
1133 if (maxmsg
> 0 && msgsize
> 0) {
1134 _attr
= (struct mq_attr
) {
1135 .mq_flags
= O_NONBLOCK
,
1136 .mq_maxmsg
= maxmsg
,
1137 .mq_msgsize
= msgsize
,
1142 /* Enforce the right access mode for the mq */
1143 old_mask
= umask(~ mq_mode
);
1145 /* Include the original umask in our mask */
1146 (void) umask(~mq_mode
| old_mask
);
1147 fd
= mq_open(path
, O_RDONLY
|O_CLOEXEC
|O_NONBLOCK
|O_CREAT
, mq_mode
, attr
);
1148 (void) umask(old_mask
);
1153 if (fstat(fd
, &st
) < 0)
1156 if ((st
.st_mode
& 0777) != (mq_mode
& ~old_mask
) ||
1157 st
.st_uid
!= getuid() ||
1158 st
.st_gid
!= getgid())
1167 static int socket_symlink(Socket
*s
) {
1173 p
= socket_find_symlink_target(s
);
1177 STRV_FOREACH(i
, s
->symlinks
)
1178 symlink_label(p
, *i
);
1183 static int usbffs_write_descs(int fd
, Service
*s
) {
1186 if (!s
->usb_function_descriptors
|| !s
->usb_function_strings
)
1189 r
= copy_file_fd(s
->usb_function_descriptors
, fd
, false);
1193 return copy_file_fd(s
->usb_function_strings
, fd
, false);
1196 static int usbffs_select_ep(const struct dirent
*d
) {
1197 return d
->d_name
[0] != '.' && !streq(d
->d_name
, "ep0");
1200 static int usbffs_dispatch_eps(SocketPort
*p
) {
1201 _cleanup_free_
struct dirent
**ent
= NULL
;
1202 _cleanup_free_
char *path
= NULL
;
1205 path
= dirname_malloc(p
->path
);
1209 r
= scandir(path
, &ent
, usbffs_select_ep
, alphasort
);
1214 p
->auxiliary_fds
= new(int, n
);
1215 if (!p
->auxiliary_fds
)
1218 p
->n_auxiliary_fds
= n
;
1221 for (i
= 0; i
< n
; ++i
) {
1222 _cleanup_free_
char *ep
= NULL
;
1224 ep
= path_make_absolute(ent
[i
]->d_name
, path
);
1228 path_kill_slashes(ep
);
1230 r
= usbffs_address_create(ep
);
1234 p
->auxiliary_fds
[k
] = r
;
1243 close_many(p
->auxiliary_fds
, k
);
1244 p
->auxiliary_fds
= mfree(p
->auxiliary_fds
);
1245 p
->n_auxiliary_fds
= 0;
1250 static int socket_determine_selinux_label(Socket
*s
, char **ret
) {
1257 if (s
->selinux_context_from_net
) {
1258 /* If this is requested, get label from the network label */
1260 r
= mac_selinux_get_our_label(ret
);
1261 if (r
== -EOPNOTSUPP
)
1265 /* Otherwise, get it from the executable we are about to start */
1266 r
= socket_instantiate_service(s
);
1270 if (!UNIT_ISSET(s
->service
))
1273 c
= SERVICE(UNIT_DEREF(s
->service
))->exec_command
[SERVICE_EXEC_START
];
1277 r
= mac_selinux_get_create_label_from_exe(c
->path
, ret
);
1278 if (r
== -EPERM
|| r
== -EOPNOTSUPP
)
1289 static int socket_open_fds(Socket
*s
) {
1290 _cleanup_(mac_selinux_freep
) char *label
= NULL
;
1291 bool know_label
= false;
1297 LIST_FOREACH(port
, p
, s
->ports
) {
1307 /* Figure out label, if we don't it know yet. We do it once, for the first socket where
1308 * we need this and remember it for the rest. */
1310 r
= socket_determine_selinux_label(s
, &label
);
1317 /* Apply the socket protocol */
1318 switch (p
->address
.type
) {
1321 case SOCK_SEQPACKET
:
1322 if (s
->socket_protocol
== IPPROTO_SCTP
)
1323 p
->address
.protocol
= s
->socket_protocol
;
1327 if (s
->socket_protocol
== IPPROTO_UDPLITE
)
1328 p
->address
.protocol
= s
->socket_protocol
;
1332 r
= socket_address_listen(
1334 SOCK_CLOEXEC
|SOCK_NONBLOCK
,
1348 socket_apply_socket_options(s
, p
->fd
);
1352 case SOCKET_SPECIAL
:
1354 p
->fd
= special_address_create(p
->path
, s
->writable
);
1363 p
->fd
= fifo_address_create(
1372 socket_apply_fifo_options(s
, p
->fd
);
1378 p
->fd
= mq_address_create(
1389 case SOCKET_USB_FUNCTION
: {
1390 _cleanup_free_
char *ep
= NULL
;
1392 ep
= path_make_absolute("ep0", p
->path
);
1394 p
->fd
= usbffs_address_create(ep
);
1400 r
= usbffs_write_descs(p
->fd
, SERVICE(UNIT_DEREF(s
->service
)));
1404 r
= usbffs_dispatch_eps(p
);
1411 assert_not_reached("Unknown port type");
1418 socket_close_fds(s
);
1422 static void socket_unwatch_fds(Socket
*s
) {
1428 LIST_FOREACH(port
, p
, s
->ports
) {
1432 if (!p
->event_source
)
1435 r
= sd_event_source_set_enabled(p
->event_source
, SD_EVENT_OFF
);
1437 log_unit_debug_errno(UNIT(s
), r
, "Failed to disable event source: %m");
1441 static int socket_watch_fds(Socket
*s
) {
1447 LIST_FOREACH(port
, p
, s
->ports
) {
1451 if (p
->event_source
) {
1452 r
= sd_event_source_set_enabled(p
->event_source
, SD_EVENT_ON
);
1456 r
= sd_event_add_io(UNIT(s
)->manager
->event
, &p
->event_source
, p
->fd
, EPOLLIN
, socket_dispatch_io
, p
);
1460 (void) sd_event_source_set_description(p
->event_source
, "socket-port-io");
1467 log_unit_warning_errno(UNIT(s
), r
, "Failed to watch listening fds: %m");
1468 socket_unwatch_fds(s
);
1478 static int socket_check_open(Socket
*s
) {
1479 bool have_open
= false, have_closed
= false;
1484 LIST_FOREACH(port
, p
, s
->ports
) {
1490 if (have_open
&& have_closed
)
1491 return SOCKET_OPEN_SOME
;
1495 return SOCKET_OPEN_ALL
;
1497 return SOCKET_OPEN_NONE
;
1500 static void socket_set_state(Socket
*s
, SocketState state
) {
1501 SocketState old_state
;
1504 old_state
= s
->state
;
1512 SOCKET_STOP_PRE_SIGTERM
,
1513 SOCKET_STOP_PRE_SIGKILL
,
1515 SOCKET_FINAL_SIGTERM
,
1516 SOCKET_FINAL_SIGKILL
)) {
1518 s
->timer_event_source
= sd_event_source_unref(s
->timer_event_source
);
1519 socket_unwatch_control_pid(s
);
1520 s
->control_command
= NULL
;
1521 s
->control_command_id
= _SOCKET_EXEC_COMMAND_INVALID
;
1524 if (state
!= SOCKET_LISTENING
)
1525 socket_unwatch_fds(s
);
1533 SOCKET_STOP_PRE_SIGTERM
,
1534 SOCKET_STOP_PRE_SIGKILL
))
1535 socket_close_fds(s
);
1537 if (state
!= old_state
)
1538 log_unit_debug(UNIT(s
), "Changed %s -> %s", socket_state_to_string(old_state
), socket_state_to_string(state
));
1540 unit_notify(UNIT(s
), state_translation_table
[old_state
], state_translation_table
[state
], true);
1543 static int socket_coldplug(Unit
*u
) {
1544 Socket
*s
= SOCKET(u
);
1548 assert(s
->state
== SOCKET_DEAD
);
1550 if (s
->deserialized_state
== s
->state
)
1553 if (s
->control_pid
> 0 &&
1554 pid_is_unwaited(s
->control_pid
) &&
1555 IN_SET(s
->deserialized_state
,
1560 SOCKET_STOP_PRE_SIGTERM
,
1561 SOCKET_STOP_PRE_SIGKILL
,
1563 SOCKET_FINAL_SIGTERM
,
1564 SOCKET_FINAL_SIGKILL
)) {
1566 r
= unit_watch_pid(UNIT(s
), s
->control_pid
);
1570 r
= socket_arm_timer(s
, usec_add(u
->state_change_timestamp
.monotonic
, s
->timeout_usec
));
1575 if (IN_SET(s
->deserialized_state
,
1581 /* Originally, we used to simply reopen all sockets here that we didn't have file descriptors
1582 * for. However, this is problematic, as we won't traverse throught the SOCKET_START_CHOWN state for
1583 * them, and thus the UID/GID wouldn't be right. Hence, instead simply check if we have all fds open,
1584 * and if there's a mismatch, warn loudly. */
1586 r
= socket_check_open(s
);
1587 if (r
== SOCKET_OPEN_NONE
)
1588 log_unit_warning(UNIT(s
),
1589 "Socket unit configuration has changed while unit has been running, "
1590 "no open socket file descriptor left. "
1591 "The socket unit is not functional until restarted.");
1592 else if (r
== SOCKET_OPEN_SOME
)
1593 log_unit_warning(UNIT(s
),
1594 "Socket unit configuration has changed while unit has been running, "
1595 "and some socket file descriptors have not been opened yet. "
1596 "The socket unit is not fully functional until restarted.");
1599 if (s
->deserialized_state
== SOCKET_LISTENING
) {
1600 r
= socket_watch_fds(s
);
1605 socket_set_state(s
, s
->deserialized_state
);
1609 static int socket_spawn(Socket
*s
, ExecCommand
*c
, pid_t
*_pid
) {
1610 _cleanup_free_
char **argv
= NULL
;
1613 ExecParameters exec_params
= {
1614 .apply_permissions
= true,
1615 .apply_chroot
= true,
1616 .apply_tty_stdin
= true,
1626 (void) unit_realize_cgroup(UNIT(s
));
1627 if (s
->reset_cpu_usage
) {
1628 (void) unit_reset_cpu_usage(UNIT(s
));
1629 s
->reset_cpu_usage
= false;
1632 r
= unit_setup_exec_runtime(UNIT(s
));
1636 r
= socket_arm_timer(s
, usec_add(now(CLOCK_MONOTONIC
), s
->timeout_usec
));
1640 r
= unit_full_printf_strv(UNIT(s
), c
->argv
, &argv
);
1644 exec_params
.argv
= argv
;
1645 exec_params
.environment
= UNIT(s
)->manager
->environment
;
1646 exec_params
.confirm_spawn
= UNIT(s
)->manager
->confirm_spawn
;
1647 exec_params
.cgroup_supported
= UNIT(s
)->manager
->cgroup_supported
;
1648 exec_params
.cgroup_path
= UNIT(s
)->cgroup_path
;
1649 exec_params
.cgroup_delegate
= s
->cgroup_context
.delegate
;
1650 exec_params
.runtime_prefix
= manager_get_runtime_prefix(UNIT(s
)->manager
);
1652 r
= exec_spawn(UNIT(s
),
1661 r
= unit_watch_pid(UNIT(s
), pid
);
1663 /* FIXME: we need to do something here */
1670 static int socket_chown(Socket
*s
, pid_t
*_pid
) {
1674 r
= socket_arm_timer(s
, usec_add(now(CLOCK_MONOTONIC
), s
->timeout_usec
));
1678 /* We have to resolve the user names out-of-process, hence
1679 * let's fork here. It's messy, but well, what can we do? */
1687 uid_t uid
= UID_INVALID
;
1688 gid_t gid
= GID_INVALID
;
1691 (void) default_signals(SIGNALS_CRASH_HANDLER
, SIGNALS_IGNORE
, -1);
1692 (void) ignore_signals(SIGPIPE
, -1);
1695 if (!isempty(s
->user
)) {
1696 const char *user
= s
->user
;
1698 r
= get_user_creds(&user
, &uid
, &gid
, NULL
, NULL
);
1705 if (!isempty(s
->group
)) {
1706 const char *group
= s
->group
;
1708 r
= get_group_creds(&group
, &gid
);
1715 LIST_FOREACH(port
, p
, s
->ports
) {
1716 const char *path
= NULL
;
1718 if (p
->type
== SOCKET_SOCKET
)
1719 path
= socket_address_get_path(&p
->address
);
1720 else if (p
->type
== SOCKET_FIFO
)
1726 if (chown(path
, uid
, gid
) < 0) {
1737 log_error_errno(r
, "Failed to chown socket at step %s: %m", exit_status_to_string(ret
, EXIT_STATUS_SYSTEMD
));
1742 r
= unit_watch_pid(UNIT(s
), pid
);
1750 s
->timer_event_source
= sd_event_source_unref(s
->timer_event_source
);
1754 static void socket_enter_dead(Socket
*s
, SocketResult f
) {
1757 if (f
!= SOCKET_SUCCESS
)
1760 exec_runtime_destroy(s
->exec_runtime
);
1761 s
->exec_runtime
= exec_runtime_unref(s
->exec_runtime
);
1763 exec_context_destroy_runtime_directory(&s
->exec_context
, manager_get_runtime_prefix(UNIT(s
)->manager
));
1765 socket_set_state(s
, s
->result
!= SOCKET_SUCCESS
? SOCKET_FAILED
: SOCKET_DEAD
);
1768 static void socket_enter_signal(Socket
*s
, SocketState state
, SocketResult f
);
1770 static void socket_enter_stop_post(Socket
*s
, SocketResult f
) {
1774 if (f
!= SOCKET_SUCCESS
)
1777 socket_unwatch_control_pid(s
);
1778 s
->control_command_id
= SOCKET_EXEC_STOP_POST
;
1779 s
->control_command
= s
->exec_command
[SOCKET_EXEC_STOP_POST
];
1781 if (s
->control_command
) {
1782 r
= socket_spawn(s
, s
->control_command
, &s
->control_pid
);
1786 socket_set_state(s
, SOCKET_STOP_POST
);
1788 socket_enter_signal(s
, SOCKET_FINAL_SIGTERM
, SOCKET_SUCCESS
);
1793 log_unit_warning_errno(UNIT(s
), r
, "Failed to run 'stop-post' task: %m");
1794 socket_enter_signal(s
, SOCKET_FINAL_SIGTERM
, SOCKET_FAILURE_RESOURCES
);
1797 static void socket_enter_signal(Socket
*s
, SocketState state
, SocketResult f
) {
1802 if (f
!= SOCKET_SUCCESS
)
1805 r
= unit_kill_context(
1808 (state
!= SOCKET_STOP_PRE_SIGTERM
&& state
!= SOCKET_FINAL_SIGTERM
) ?
1809 KILL_KILL
: KILL_TERMINATE
,
1817 r
= socket_arm_timer(s
, usec_add(now(CLOCK_MONOTONIC
), s
->timeout_usec
));
1821 socket_set_state(s
, state
);
1822 } else if (state
== SOCKET_STOP_PRE_SIGTERM
)
1823 socket_enter_signal(s
, SOCKET_STOP_PRE_SIGKILL
, SOCKET_SUCCESS
);
1824 else if (state
== SOCKET_STOP_PRE_SIGKILL
)
1825 socket_enter_stop_post(s
, SOCKET_SUCCESS
);
1826 else if (state
== SOCKET_FINAL_SIGTERM
)
1827 socket_enter_signal(s
, SOCKET_FINAL_SIGKILL
, SOCKET_SUCCESS
);
1829 socket_enter_dead(s
, SOCKET_SUCCESS
);
1834 log_unit_warning_errno(UNIT(s
), r
, "Failed to kill processes: %m");
1836 if (state
== SOCKET_STOP_PRE_SIGTERM
|| state
== SOCKET_STOP_PRE_SIGKILL
)
1837 socket_enter_stop_post(s
, SOCKET_FAILURE_RESOURCES
);
1839 socket_enter_dead(s
, SOCKET_FAILURE_RESOURCES
);
1842 static void socket_enter_stop_pre(Socket
*s
, SocketResult f
) {
1846 if (f
!= SOCKET_SUCCESS
)
1849 socket_unwatch_control_pid(s
);
1850 s
->control_command_id
= SOCKET_EXEC_STOP_PRE
;
1851 s
->control_command
= s
->exec_command
[SOCKET_EXEC_STOP_PRE
];
1853 if (s
->control_command
) {
1854 r
= socket_spawn(s
, s
->control_command
, &s
->control_pid
);
1858 socket_set_state(s
, SOCKET_STOP_PRE
);
1860 socket_enter_stop_post(s
, SOCKET_SUCCESS
);
1865 log_unit_warning_errno(UNIT(s
), r
, "Failed to run 'stop-pre' task: %m");
1866 socket_enter_stop_post(s
, SOCKET_FAILURE_RESOURCES
);
1869 static void socket_enter_listening(Socket
*s
) {
1873 r
= socket_watch_fds(s
);
1875 log_unit_warning_errno(UNIT(s
), r
, "Failed to watch sockets: %m");
1879 socket_set_state(s
, SOCKET_LISTENING
);
1883 socket_enter_stop_pre(s
, SOCKET_FAILURE_RESOURCES
);
1886 static void socket_enter_start_post(Socket
*s
) {
1890 socket_unwatch_control_pid(s
);
1891 s
->control_command_id
= SOCKET_EXEC_START_POST
;
1892 s
->control_command
= s
->exec_command
[SOCKET_EXEC_START_POST
];
1894 if (s
->control_command
) {
1895 r
= socket_spawn(s
, s
->control_command
, &s
->control_pid
);
1897 log_unit_warning_errno(UNIT(s
), r
, "Failed to run 'start-post' task: %m");
1901 socket_set_state(s
, SOCKET_START_POST
);
1903 socket_enter_listening(s
);
1908 socket_enter_stop_pre(s
, SOCKET_FAILURE_RESOURCES
);
1911 static void socket_enter_start_chown(Socket
*s
) {
1916 r
= socket_open_fds(s
);
1918 log_unit_warning_errno(UNIT(s
), r
, "Failed to listen on sockets: %m");
1922 if (!isempty(s
->user
) || !isempty(s
->group
)) {
1924 socket_unwatch_control_pid(s
);
1925 s
->control_command_id
= SOCKET_EXEC_START_CHOWN
;
1926 s
->control_command
= NULL
;
1928 r
= socket_chown(s
, &s
->control_pid
);
1930 log_unit_warning_errno(UNIT(s
), r
, "Failed to fork 'start-chown' task: %m");
1934 socket_set_state(s
, SOCKET_START_CHOWN
);
1936 socket_enter_start_post(s
);
1941 socket_enter_stop_pre(s
, SOCKET_FAILURE_RESOURCES
);
1944 static void socket_enter_start_pre(Socket
*s
) {
1948 socket_unwatch_control_pid(s
);
1949 s
->control_command_id
= SOCKET_EXEC_START_PRE
;
1950 s
->control_command
= s
->exec_command
[SOCKET_EXEC_START_PRE
];
1952 if (s
->control_command
) {
1953 r
= socket_spawn(s
, s
->control_command
, &s
->control_pid
);
1955 log_unit_warning_errno(UNIT(s
), r
, "Failed to run 'start-pre' task: %m");
1959 socket_set_state(s
, SOCKET_START_PRE
);
1961 socket_enter_start_chown(s
);
1966 socket_enter_dead(s
, SOCKET_FAILURE_RESOURCES
);
1969 static void flush_ports(Socket
*s
) {
1972 /* Flush all incoming traffic, regardless if actual bytes or new connections, so that this socket isn't busy
1975 LIST_FOREACH(port
, p
, s
->ports
) {
1979 (void) flush_accept(p
->fd
);
1980 (void) flush_fd(p
->fd
);
1984 static void socket_enter_running(Socket
*s
, int cfd
) {
1985 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
1988 /* Note that this call takes possession of the connection fd passed. It either has to assign it somewhere or
1993 /* We don't take connections anymore if we are supposed to shut down anyway */
1994 if (unit_stop_pending(UNIT(s
))) {
1996 log_unit_debug(UNIT(s
), "Suppressing connection request since unit stop is scheduled.");
1999 cfd
= safe_close(cfd
);
2006 if (!ratelimit_test(&s
->trigger_limit
)) {
2008 log_unit_warning(UNIT(s
), "Trigger limit hit, refusing further activation.");
2009 socket_enter_stop_pre(s
, SOCKET_FAILURE_TRIGGER_LIMIT_HIT
);
2016 bool pending
= false;
2018 /* If there's already a start pending don't bother to
2020 SET_FOREACH(other
, UNIT(s
)->dependencies
[UNIT_TRIGGERS
], i
)
2021 if (unit_active_or_pending(other
)) {
2027 if (!UNIT_ISSET(s
->service
)) {
2028 log_unit_error(UNIT(s
), "Service to activate vanished, refusing activation.");
2033 r
= manager_add_job(UNIT(s
)->manager
, JOB_START
, UNIT_DEREF(s
->service
), JOB_REPLACE
, &error
, NULL
);
2038 socket_set_state(s
, SOCKET_RUNNING
);
2040 _cleanup_free_
char *prefix
= NULL
, *instance
= NULL
, *name
= NULL
;
2043 if (s
->n_connections
>= s
->max_connections
) {
2044 log_unit_warning(UNIT(s
), "Too many incoming connections (%u), refusing connection attempt.", s
->n_connections
);
2049 r
= socket_instantiate_service(s
);
2053 r
= instance_from_socket(cfd
, s
->n_accepted
, &instance
);
2058 /* ENOTCONN is legitimate if TCP RST was received.
2059 * This connection is over, but the socket unit lives on. */
2060 log_unit_debug(UNIT(s
), "Got ENOTCONN on incoming socket, assuming aborted connection attempt, ignoring.");
2065 r
= unit_name_to_prefix(UNIT(s
)->id
, &prefix
);
2069 r
= unit_name_build(prefix
, instance
, ".service", &name
);
2073 r
= unit_add_name(UNIT_DEREF(s
->service
), name
);
2077 service
= SERVICE(UNIT_DEREF(s
->service
));
2078 unit_ref_unset(&s
->service
);
2081 unit_choose_id(UNIT(service
), name
);
2083 r
= service_set_socket_fd(service
, cfd
, s
, s
->selinux_context_from_net
);
2087 cfd
= -1; /* We passed ownership of the fd to the service now. Forget it here. */
2090 r
= manager_add_job(UNIT(s
)->manager
, JOB_START
, UNIT(service
), JOB_REPLACE
, &error
, NULL
);
2092 /* We failed to activate the new service, but it still exists. Let's make sure the service
2093 * closes and forgets the connection fd again, immediately. */
2094 service_close_socket_fd(service
);
2098 /* Notify clients about changed counters */
2099 unit_add_to_dbus_queue(UNIT(s
));
2105 log_unit_warning(UNIT(s
), "Failed to queue service startup job (Maybe the service file is missing or not a %s unit?): %s",
2106 cfd
>= 0 ? "template" : "non-template",
2107 bus_error_message(&error
, r
));
2109 socket_enter_stop_pre(s
, SOCKET_FAILURE_RESOURCES
);
2113 static void socket_run_next(Socket
*s
) {
2117 assert(s
->control_command
);
2118 assert(s
->control_command
->command_next
);
2120 socket_unwatch_control_pid(s
);
2122 s
->control_command
= s
->control_command
->command_next
;
2124 r
= socket_spawn(s
, s
->control_command
, &s
->control_pid
);
2131 log_unit_warning_errno(UNIT(s
), r
, "Failed to run next task: %m");
2133 if (s
->state
== SOCKET_START_POST
)
2134 socket_enter_stop_pre(s
, SOCKET_FAILURE_RESOURCES
);
2135 else if (s
->state
== SOCKET_STOP_POST
)
2136 socket_enter_dead(s
, SOCKET_FAILURE_RESOURCES
);
2138 socket_enter_signal(s
, SOCKET_FINAL_SIGTERM
, SOCKET_FAILURE_RESOURCES
);
2141 static int socket_start(Unit
*u
) {
2142 Socket
*s
= SOCKET(u
);
2147 /* We cannot fulfill this request right now, try again later
2149 if (IN_SET(s
->state
,
2151 SOCKET_STOP_PRE_SIGKILL
,
2152 SOCKET_STOP_PRE_SIGTERM
,
2154 SOCKET_FINAL_SIGTERM
,
2155 SOCKET_FINAL_SIGKILL
))
2158 /* Already on it! */
2159 if (IN_SET(s
->state
,
2165 /* Cannot run this without the service being around */
2166 if (UNIT_ISSET(s
->service
)) {
2169 service
= SERVICE(UNIT_DEREF(s
->service
));
2171 if (UNIT(service
)->load_state
!= UNIT_LOADED
) {
2172 log_unit_error(u
, "Socket service %s not loaded, refusing.", UNIT(service
)->id
);
2176 /* If the service is already active we cannot start the
2178 if (service
->state
!= SERVICE_DEAD
&&
2179 service
->state
!= SERVICE_FAILED
&&
2180 service
->state
!= SERVICE_AUTO_RESTART
) {
2181 log_unit_error(u
, "Socket service %s already active, refusing.", UNIT(service
)->id
);
2186 assert(s
->state
== SOCKET_DEAD
|| s
->state
== SOCKET_FAILED
);
2188 r
= unit_start_limit_test(u
);
2190 socket_enter_dead(s
, SOCKET_FAILURE_START_LIMIT_HIT
);
2194 s
->result
= SOCKET_SUCCESS
;
2195 s
->reset_cpu_usage
= true;
2197 socket_enter_start_pre(s
);
2202 static int socket_stop(Unit
*u
) {
2203 Socket
*s
= SOCKET(u
);
2208 if (IN_SET(s
->state
,
2210 SOCKET_STOP_PRE_SIGTERM
,
2211 SOCKET_STOP_PRE_SIGKILL
,
2213 SOCKET_FINAL_SIGTERM
,
2214 SOCKET_FINAL_SIGKILL
))
2217 /* If there's already something running we go directly into
2219 if (IN_SET(s
->state
,
2222 SOCKET_START_POST
)) {
2223 socket_enter_signal(s
, SOCKET_STOP_PRE_SIGTERM
, SOCKET_SUCCESS
);
2227 assert(s
->state
== SOCKET_LISTENING
|| s
->state
== SOCKET_RUNNING
);
2229 socket_enter_stop_pre(s
, SOCKET_SUCCESS
);
2233 static int socket_serialize(Unit
*u
, FILE *f
, FDSet
*fds
) {
2234 Socket
*s
= SOCKET(u
);
2242 unit_serialize_item(u
, f
, "state", socket_state_to_string(s
->state
));
2243 unit_serialize_item(u
, f
, "result", socket_result_to_string(s
->result
));
2244 unit_serialize_item_format(u
, f
, "n-accepted", "%u", s
->n_accepted
);
2246 if (s
->control_pid
> 0)
2247 unit_serialize_item_format(u
, f
, "control-pid", PID_FMT
, s
->control_pid
);
2249 if (s
->control_command_id
>= 0)
2250 unit_serialize_item(u
, f
, "control-command", socket_exec_command_to_string(s
->control_command_id
));
2252 LIST_FOREACH(port
, p
, s
->ports
) {
2258 copy
= fdset_put_dup(fds
, p
->fd
);
2262 if (p
->type
== SOCKET_SOCKET
) {
2263 _cleanup_free_
char *t
= NULL
;
2265 r
= socket_address_print(&p
->address
, &t
);
2269 if (socket_address_family(&p
->address
) == AF_NETLINK
)
2270 unit_serialize_item_format(u
, f
, "netlink", "%i %s", copy
, t
);
2272 unit_serialize_item_format(u
, f
, "socket", "%i %i %s", copy
, p
->address
.type
, t
);
2274 } else if (p
->type
== SOCKET_SPECIAL
)
2275 unit_serialize_item_format(u
, f
, "special", "%i %s", copy
, p
->path
);
2276 else if (p
->type
== SOCKET_MQUEUE
)
2277 unit_serialize_item_format(u
, f
, "mqueue", "%i %s", copy
, p
->path
);
2278 else if (p
->type
== SOCKET_USB_FUNCTION
)
2279 unit_serialize_item_format(u
, f
, "ffs", "%i %s", copy
, p
->path
);
2281 assert(p
->type
== SOCKET_FIFO
);
2282 unit_serialize_item_format(u
, f
, "fifo", "%i %s", copy
, p
->path
);
2289 static int socket_deserialize_item(Unit
*u
, const char *key
, const char *value
, FDSet
*fds
) {
2290 Socket
*s
= SOCKET(u
);
2296 if (streq(key
, "state")) {
2299 state
= socket_state_from_string(value
);
2301 log_unit_debug(u
, "Failed to parse state value: %s", value
);
2303 s
->deserialized_state
= state
;
2304 } else if (streq(key
, "result")) {
2307 f
= socket_result_from_string(value
);
2309 log_unit_debug(u
, "Failed to parse result value: %s", value
);
2310 else if (f
!= SOCKET_SUCCESS
)
2313 } else if (streq(key
, "n-accepted")) {
2316 if (safe_atou(value
, &k
) < 0)
2317 log_unit_debug(u
, "Failed to parse n-accepted value: %s", value
);
2320 } else if (streq(key
, "control-pid")) {
2323 if (parse_pid(value
, &pid
) < 0)
2324 log_unit_debug(u
, "Failed to parse control-pid value: %s", value
);
2326 s
->control_pid
= pid
;
2327 } else if (streq(key
, "control-command")) {
2328 SocketExecCommand id
;
2330 id
= socket_exec_command_from_string(value
);
2332 log_unit_debug(u
, "Failed to parse exec-command value: %s", value
);
2334 s
->control_command_id
= id
;
2335 s
->control_command
= s
->exec_command
[id
];
2337 } else if (streq(key
, "fifo")) {
2341 if (sscanf(value
, "%i %n", &fd
, &skip
) < 1 || fd
< 0 || !fdset_contains(fds
, fd
))
2342 log_unit_debug(u
, "Failed to parse fifo value: %s", value
);
2345 LIST_FOREACH(port
, p
, s
->ports
)
2346 if (p
->type
== SOCKET_FIFO
&&
2347 path_equal_or_files_same(p
->path
, value
+skip
))
2352 p
->fd
= fdset_remove(fds
, fd
);
2356 } else if (streq(key
, "special")) {
2360 if (sscanf(value
, "%i %n", &fd
, &skip
) < 1 || fd
< 0 || !fdset_contains(fds
, fd
))
2361 log_unit_debug(u
, "Failed to parse special value: %s", value
);
2364 LIST_FOREACH(port
, p
, s
->ports
)
2365 if (p
->type
== SOCKET_SPECIAL
&&
2366 path_equal_or_files_same(p
->path
, value
+skip
))
2371 p
->fd
= fdset_remove(fds
, fd
);
2375 } else if (streq(key
, "mqueue")) {
2379 if (sscanf(value
, "%i %n", &fd
, &skip
) < 1 || fd
< 0 || !fdset_contains(fds
, fd
))
2380 log_unit_debug(u
, "Failed to parse mqueue value: %s", value
);
2383 LIST_FOREACH(port
, p
, s
->ports
)
2384 if (p
->type
== SOCKET_MQUEUE
&&
2385 streq(p
->path
, value
+skip
))
2390 p
->fd
= fdset_remove(fds
, fd
);
2394 } else if (streq(key
, "socket")) {
2395 int fd
, type
, skip
= 0;
2398 if (sscanf(value
, "%i %i %n", &fd
, &type
, &skip
) < 2 || fd
< 0 || type
< 0 || !fdset_contains(fds
, fd
))
2399 log_unit_debug(u
, "Failed to parse socket value: %s", value
);
2402 LIST_FOREACH(port
, p
, s
->ports
)
2403 if (socket_address_is(&p
->address
, value
+skip
, type
))
2408 p
->fd
= fdset_remove(fds
, fd
);
2412 } else if (streq(key
, "netlink")) {
2416 if (sscanf(value
, "%i %n", &fd
, &skip
) < 1 || fd
< 0 || !fdset_contains(fds
, fd
))
2417 log_unit_debug(u
, "Failed to parse socket value: %s", value
);
2420 LIST_FOREACH(port
, p
, s
->ports
)
2421 if (socket_address_is_netlink(&p
->address
, value
+skip
))
2426 p
->fd
= fdset_remove(fds
, fd
);
2430 } else if (streq(key
, "ffs")) {
2434 if (sscanf(value
, "%i %n", &fd
, &skip
) < 1 || fd
< 0 || !fdset_contains(fds
, fd
))
2435 log_unit_debug(u
, "Failed to parse ffs value: %s", value
);
2438 LIST_FOREACH(port
, p
, s
->ports
)
2439 if (p
->type
== SOCKET_USB_FUNCTION
&&
2440 path_equal_or_files_same(p
->path
, value
+skip
))
2445 p
->fd
= fdset_remove(fds
, fd
);
2450 log_unit_debug(UNIT(s
), "Unknown serialization key: %s", key
);
2455 static void socket_distribute_fds(Unit
*u
, FDSet
*fds
) {
2456 Socket
*s
= SOCKET(u
);
2461 LIST_FOREACH(port
, p
, s
->ports
) {
2465 if (p
->type
!= SOCKET_SOCKET
)
2471 FDSET_FOREACH(fd
, fds
, i
) {
2472 if (socket_address_matches_fd(&p
->address
, fd
)) {
2473 p
->fd
= fdset_remove(fds
, fd
);
2474 s
->deserialized_state
= SOCKET_LISTENING
;
2481 _pure_
static UnitActiveState
socket_active_state(Unit
*u
) {
2484 return state_translation_table
[SOCKET(u
)->state
];
2487 _pure_
static const char *socket_sub_state_to_string(Unit
*u
) {
2490 return socket_state_to_string(SOCKET(u
)->state
);
2493 const char* socket_port_type_to_string(SocketPort
*p
) {
2501 switch (p
->address
.type
) {
2509 case SOCK_SEQPACKET
:
2510 return "SequentialPacket";
2513 if (socket_address_family(&p
->address
) == AF_NETLINK
)
2520 case SOCKET_SPECIAL
:
2524 return "MessageQueue";
2529 case SOCKET_USB_FUNCTION
:
2530 return "USBFunction";
2537 _pure_
static bool socket_check_gc(Unit
*u
) {
2538 Socket
*s
= SOCKET(u
);
2542 return s
->n_connections
> 0;
2545 static int socket_dispatch_io(sd_event_source
*source
, int fd
, uint32_t revents
, void *userdata
) {
2546 SocketPort
*p
= userdata
;
2552 if (p
->socket
->state
!= SOCKET_LISTENING
)
2555 log_unit_debug(UNIT(p
->socket
), "Incoming traffic");
2557 if (revents
!= EPOLLIN
) {
2559 if (revents
& EPOLLHUP
)
2560 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.");
2562 log_unit_error(UNIT(p
->socket
), "Got unexpected poll event (0x%x) on socket.", revents
);
2566 if (p
->socket
->accept
&&
2567 p
->type
== SOCKET_SOCKET
&&
2568 socket_address_can_accept(&p
->address
)) {
2572 cfd
= accept4(fd
, NULL
, NULL
, SOCK_NONBLOCK
);
2578 log_unit_error_errno(UNIT(p
->socket
), errno
, "Failed to accept socket: %m");
2585 socket_apply_socket_options(p
->socket
, cfd
);
2588 socket_enter_running(p
->socket
, cfd
);
2592 socket_enter_stop_pre(p
->socket
, SOCKET_FAILURE_RESOURCES
);
2596 static void socket_sigchld_event(Unit
*u
, pid_t pid
, int code
, int status
) {
2597 Socket
*s
= SOCKET(u
);
2603 if (pid
!= s
->control_pid
)
2608 if (is_clean_exit(code
, status
, NULL
))
2610 else if (code
== CLD_EXITED
)
2611 f
= SOCKET_FAILURE_EXIT_CODE
;
2612 else if (code
== CLD_KILLED
)
2613 f
= SOCKET_FAILURE_SIGNAL
;
2614 else if (code
== CLD_DUMPED
)
2615 f
= SOCKET_FAILURE_CORE_DUMP
;
2617 assert_not_reached("Unknown sigchld code");
2619 if (s
->control_command
) {
2620 exec_status_exit(&s
->control_command
->exec_status
, &s
->exec_context
, pid
, code
, status
);
2622 if (s
->control_command
->ignore
)
2626 log_unit_full(u
, f
== SOCKET_SUCCESS
? LOG_DEBUG
: LOG_NOTICE
, 0,
2627 "Control process exited, code=%s status=%i",
2628 sigchld_code_to_string(code
), status
);
2630 if (f
!= SOCKET_SUCCESS
)
2633 if (s
->control_command
&&
2634 s
->control_command
->command_next
&&
2635 f
== SOCKET_SUCCESS
) {
2637 log_unit_debug(u
, "Running next command for state %s", socket_state_to_string(s
->state
));
2640 s
->control_command
= NULL
;
2641 s
->control_command_id
= _SOCKET_EXEC_COMMAND_INVALID
;
2643 /* No further commands for this step, so let's figure
2644 * out what to do next */
2646 log_unit_debug(u
, "Got final SIGCHLD for state %s", socket_state_to_string(s
->state
));
2650 case SOCKET_START_PRE
:
2651 if (f
== SOCKET_SUCCESS
)
2652 socket_enter_start_chown(s
);
2654 socket_enter_signal(s
, SOCKET_FINAL_SIGTERM
, f
);
2657 case SOCKET_START_CHOWN
:
2658 if (f
== SOCKET_SUCCESS
)
2659 socket_enter_start_post(s
);
2661 socket_enter_stop_pre(s
, f
);
2664 case SOCKET_START_POST
:
2665 if (f
== SOCKET_SUCCESS
)
2666 socket_enter_listening(s
);
2668 socket_enter_stop_pre(s
, f
);
2671 case SOCKET_STOP_PRE
:
2672 case SOCKET_STOP_PRE_SIGTERM
:
2673 case SOCKET_STOP_PRE_SIGKILL
:
2674 socket_enter_stop_post(s
, f
);
2677 case SOCKET_STOP_POST
:
2678 case SOCKET_FINAL_SIGTERM
:
2679 case SOCKET_FINAL_SIGKILL
:
2680 socket_enter_dead(s
, f
);
2684 assert_not_reached("Uh, control process died at wrong time.");
2688 /* Notify clients about changed exit status */
2689 unit_add_to_dbus_queue(u
);
2692 static int socket_dispatch_timer(sd_event_source
*source
, usec_t usec
, void *userdata
) {
2693 Socket
*s
= SOCKET(userdata
);
2696 assert(s
->timer_event_source
== source
);
2700 case SOCKET_START_PRE
:
2701 log_unit_warning(UNIT(s
), "Starting timed out. Terminating.");
2702 socket_enter_signal(s
, SOCKET_FINAL_SIGTERM
, SOCKET_FAILURE_TIMEOUT
);
2705 case SOCKET_START_CHOWN
:
2706 case SOCKET_START_POST
:
2707 log_unit_warning(UNIT(s
), "Starting timed out. Stopping.");
2708 socket_enter_stop_pre(s
, SOCKET_FAILURE_TIMEOUT
);
2711 case SOCKET_STOP_PRE
:
2712 log_unit_warning(UNIT(s
), "Stopping timed out. Terminating.");
2713 socket_enter_signal(s
, SOCKET_STOP_PRE_SIGTERM
, SOCKET_FAILURE_TIMEOUT
);
2716 case SOCKET_STOP_PRE_SIGTERM
:
2717 if (s
->kill_context
.send_sigkill
) {
2718 log_unit_warning(UNIT(s
), "Stopping timed out. Killing.");
2719 socket_enter_signal(s
, SOCKET_STOP_PRE_SIGKILL
, SOCKET_FAILURE_TIMEOUT
);
2721 log_unit_warning(UNIT(s
), "Stopping timed out. Skipping SIGKILL. Ignoring.");
2722 socket_enter_stop_post(s
, SOCKET_FAILURE_TIMEOUT
);
2726 case SOCKET_STOP_PRE_SIGKILL
:
2727 log_unit_warning(UNIT(s
), "Processes still around after SIGKILL. Ignoring.");
2728 socket_enter_stop_post(s
, SOCKET_FAILURE_TIMEOUT
);
2731 case SOCKET_STOP_POST
:
2732 log_unit_warning(UNIT(s
), "Stopping timed out (2). Terminating.");
2733 socket_enter_signal(s
, SOCKET_FINAL_SIGTERM
, SOCKET_FAILURE_TIMEOUT
);
2736 case SOCKET_FINAL_SIGTERM
:
2737 if (s
->kill_context
.send_sigkill
) {
2738 log_unit_warning(UNIT(s
), "Stopping timed out (2). Killing.");
2739 socket_enter_signal(s
, SOCKET_FINAL_SIGKILL
, SOCKET_FAILURE_TIMEOUT
);
2741 log_unit_warning(UNIT(s
), "Stopping timed out (2). Skipping SIGKILL. Ignoring.");
2742 socket_enter_dead(s
, SOCKET_FAILURE_TIMEOUT
);
2746 case SOCKET_FINAL_SIGKILL
:
2747 log_unit_warning(UNIT(s
), "Still around after SIGKILL (2). Entering failed mode.");
2748 socket_enter_dead(s
, SOCKET_FAILURE_TIMEOUT
);
2752 assert_not_reached("Timeout at wrong time.");
2758 int socket_collect_fds(Socket
*s
, int **fds
) {
2759 int *rfds
, k
= 0, n
= 0;
2765 /* Called from the service code for requesting our fds */
2767 LIST_FOREACH(port
, p
, s
->ports
) {
2770 n
+= p
->n_auxiliary_fds
;
2782 LIST_FOREACH(port
, p
, s
->ports
) {
2787 for (i
= 0; i
< p
->n_auxiliary_fds
; ++i
)
2788 rfds
[k
++] = p
->auxiliary_fds
[i
];
2797 static void socket_reset_failed(Unit
*u
) {
2798 Socket
*s
= SOCKET(u
);
2802 if (s
->state
== SOCKET_FAILED
)
2803 socket_set_state(s
, SOCKET_DEAD
);
2805 s
->result
= SOCKET_SUCCESS
;
2808 void socket_connection_unref(Socket
*s
) {
2811 /* The service is dead. Yay!
2813 * This is strictly for one-instance-per-connection
2816 assert(s
->n_connections
> 0);
2819 log_unit_debug(UNIT(s
), "One connection closed, %u left.", s
->n_connections
);
2822 static void socket_trigger_notify(Unit
*u
, Unit
*other
) {
2823 Socket
*s
= SOCKET(u
);
2828 /* Filter out invocations with bogus state */
2829 if (other
->load_state
!= UNIT_LOADED
|| other
->type
!= UNIT_SERVICE
)
2832 /* Don't propagate state changes from the service if we are already down */
2833 if (!IN_SET(s
->state
, SOCKET_RUNNING
, SOCKET_LISTENING
))
2836 /* We don't care for the service state if we are in Accept=yes mode */
2840 /* Propagate start limit hit state */
2841 if (other
->start_limit_hit
) {
2842 socket_enter_stop_pre(s
, SOCKET_FAILURE_SERVICE_START_LIMIT_HIT
);
2846 /* Don't propagate anything if there's still a job queued */
2850 if (IN_SET(SERVICE(other
)->state
,
2851 SERVICE_DEAD
, SERVICE_FAILED
,
2852 SERVICE_FINAL_SIGTERM
, SERVICE_FINAL_SIGKILL
,
2853 SERVICE_AUTO_RESTART
))
2854 socket_enter_listening(s
);
2856 if (SERVICE(other
)->state
== SERVICE_RUNNING
)
2857 socket_set_state(s
, SOCKET_RUNNING
);
2860 static int socket_kill(Unit
*u
, KillWho who
, int signo
, sd_bus_error
*error
) {
2861 return unit_kill_common(u
, who
, signo
, -1, SOCKET(u
)->control_pid
, error
);
2864 static int socket_get_timeout(Unit
*u
, usec_t
*timeout
) {
2865 Socket
*s
= SOCKET(u
);
2869 if (!s
->timer_event_source
)
2872 r
= sd_event_source_get_time(s
->timer_event_source
, &t
);
2875 if (t
== USEC_INFINITY
)
2882 char *socket_fdname(Socket
*s
) {
2885 /* Returns the name to use for $LISTEN_NAMES. If the user
2886 * didn't specify anything specifically, use the socket unit's
2887 * name as fallback. */
2895 static int socket_control_pid(Unit
*u
) {
2896 Socket
*s
= SOCKET(u
);
2900 return s
->control_pid
;
2903 static const char* const socket_exec_command_table
[_SOCKET_EXEC_COMMAND_MAX
] = {
2904 [SOCKET_EXEC_START_PRE
] = "StartPre",
2905 [SOCKET_EXEC_START_CHOWN
] = "StartChown",
2906 [SOCKET_EXEC_START_POST
] = "StartPost",
2907 [SOCKET_EXEC_STOP_PRE
] = "StopPre",
2908 [SOCKET_EXEC_STOP_POST
] = "StopPost"
2911 DEFINE_STRING_TABLE_LOOKUP(socket_exec_command
, SocketExecCommand
);
2913 static const char* const socket_result_table
[_SOCKET_RESULT_MAX
] = {
2914 [SOCKET_SUCCESS
] = "success",
2915 [SOCKET_FAILURE_RESOURCES
] = "resources",
2916 [SOCKET_FAILURE_TIMEOUT
] = "timeout",
2917 [SOCKET_FAILURE_EXIT_CODE
] = "exit-code",
2918 [SOCKET_FAILURE_SIGNAL
] = "signal",
2919 [SOCKET_FAILURE_CORE_DUMP
] = "core-dump",
2920 [SOCKET_FAILURE_START_LIMIT_HIT
] = "start-limit-hit",
2921 [SOCKET_FAILURE_TRIGGER_LIMIT_HIT
] = "trigger-limit-hit",
2922 [SOCKET_FAILURE_SERVICE_START_LIMIT_HIT
] = "service-start-limit-hit"
2925 DEFINE_STRING_TABLE_LOOKUP(socket_result
, SocketResult
);
2927 const UnitVTable socket_vtable
= {
2928 .object_size
= sizeof(Socket
),
2929 .exec_context_offset
= offsetof(Socket
, exec_context
),
2930 .cgroup_context_offset
= offsetof(Socket
, cgroup_context
),
2931 .kill_context_offset
= offsetof(Socket
, kill_context
),
2932 .exec_runtime_offset
= offsetof(Socket
, exec_runtime
),
2938 .private_section
= "Socket",
2940 .init
= socket_init
,
2941 .done
= socket_done
,
2942 .load
= socket_load
,
2944 .coldplug
= socket_coldplug
,
2946 .dump
= socket_dump
,
2948 .start
= socket_start
,
2949 .stop
= socket_stop
,
2951 .kill
= socket_kill
,
2953 .get_timeout
= socket_get_timeout
,
2955 .serialize
= socket_serialize
,
2956 .deserialize_item
= socket_deserialize_item
,
2957 .distribute_fds
= socket_distribute_fds
,
2959 .active_state
= socket_active_state
,
2960 .sub_state_to_string
= socket_sub_state_to_string
,
2962 .check_gc
= socket_check_gc
,
2964 .sigchld_event
= socket_sigchld_event
,
2966 .trigger_notify
= socket_trigger_notify
,
2968 .reset_failed
= socket_reset_failed
,
2970 .control_pid
= socket_control_pid
,
2972 .bus_vtable
= bus_socket_vtable
,
2973 .bus_set_property
= bus_socket_set_property
,
2974 .bus_commit_properties
= bus_socket_commit_properties
,
2976 .status_message_formats
= {
2977 /*.starting_stopping = {
2978 [0] = "Starting socket %s...",
2979 [1] = "Stopping socket %s...",
2981 .finished_start_job
= {
2982 [JOB_DONE
] = "Listening on %s.",
2983 [JOB_FAILED
] = "Failed to listen on %s.",
2984 [JOB_TIMEOUT
] = "Timed out starting %s.",
2986 .finished_stop_job
= {
2987 [JOB_DONE
] = "Closed %s.",
2988 [JOB_FAILED
] = "Failed stopping %s.",
2989 [JOB_TIMEOUT
] = "Timed out stopping %s.",