1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
11 #include "alloc-util.h"
14 #include "errno-util.h"
19 #include "main-func.h"
20 #include "pretty-print.h"
21 #include "process-util.h"
22 #include "signal-util.h"
23 #include "socket-netlink.h"
24 #include "socket-util.h"
25 #include "string-util.h"
27 #include "terminal-util.h"
29 static char **arg_listen
= NULL
;
30 static bool arg_accept
= false;
31 static int arg_socket_type
= SOCK_STREAM
;
32 static char **arg_args
= NULL
;
33 static char **arg_setenv
= NULL
;
34 static char **arg_fdnames
= NULL
;
35 static bool arg_inetd
= false;
37 static int add_epoll(int epoll_fd
, int fd
) {
38 struct epoll_event ev
= {
43 assert(epoll_fd
>= 0);
46 if (epoll_ctl(epoll_fd
, EPOLL_CTL_ADD
, fd
, &ev
) < 0)
47 return log_error_errno(errno
, "Failed to add event on epoll fd:%d for fd:%d: %m", epoll_fd
, fd
);
52 static int open_sockets(int *ret_epoll_fd
, bool accept
) {
53 _cleanup_close_
int epoll_fd
= -EBADF
;
58 n
= sd_listen_fds(true);
60 return log_error_errno(n
, "Failed to read listening file descriptors from environment: %m");
62 log_info("Received %i descriptors via the environment.", n
);
64 for (int fd
= SD_LISTEN_FDS_START
; fd
< SD_LISTEN_FDS_START
+ n
; fd
++) {
65 r
= fd_cloexec(fd
, arg_accept
);
73 /* Close logging and all other descriptors */
75 _cleanup_free_
int *except
= new(int, n
);
79 for (int i
= 0; i
< n
; i
++)
80 except
[i
] = SD_LISTEN_FDS_START
+ i
;
83 log_set_open_when_needed(true);
86 r
= close_all_fds(except
, n
);
88 return log_error_errno(r
, "Failed to close all file descriptors: %m");
91 /* Note: we leak some fd's on error here. It doesn't matter much, since the program will exit
92 * immediately anyway, but would be a pain to fix. */
94 STRV_FOREACH(address
, arg_listen
) {
95 r
= make_socket_fd(LOG_DEBUG
, *address
, arg_socket_type
, (arg_accept
* SOCK_CLOEXEC
));
97 return log_error_errno(r
, "Failed to open '%s': %m", *address
);
99 assert(r
== SD_LISTEN_FDS_START
+ count
);
105 log_set_open_when_needed(false);
108 epoll_fd
= epoll_create1(EPOLL_CLOEXEC
);
110 return log_error_errno(errno
, "Failed to create epoll object: %m");
112 for (int fd
= SD_LISTEN_FDS_START
; fd
< SD_LISTEN_FDS_START
+ count
; fd
++) {
113 _cleanup_free_
char *name
= NULL
;
115 getsockname_pretty(fd
, &name
);
116 log_info("Listening on %s as %i.", strna(name
), fd
);
118 r
= add_epoll(epoll_fd
, fd
);
123 *ret_epoll_fd
= TAKE_FD(epoll_fd
);
127 static int exec_process(const char *name
, char **argv
, int start_fd
, size_t n_fds
) {
128 _cleanup_strv_free_
char **envp
= NULL
;
131 if (arg_inetd
&& n_fds
!= 1)
132 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
133 "--inetd only supported for single file descriptors.");
135 FOREACH_STRING(var
, "TERM", "PATH", "USER", "HOME") {
138 n
= strv_find_prefix(environ
, var
);
142 r
= strv_extend(&envp
, n
);
150 r
= rearrange_stdio(start_fd
, start_fd
, STDERR_FILENO
); /* invalidates start_fd on success + error */
152 return log_error_errno(r
, "Failed to move fd to stdin+stdout: %m");
155 if (start_fd
!= SD_LISTEN_FDS_START
) {
158 if (dup2(start_fd
, SD_LISTEN_FDS_START
) < 0)
159 return log_error_errno(errno
, "Failed to dup connection: %m");
161 safe_close(start_fd
);
164 r
= strv_extendf(&envp
, "LISTEN_FDS=%zu", n_fds
);
168 r
= strv_extendf(&envp
, "LISTEN_PID=" PID_FMT
, getpid_cached());
173 _cleanup_free_
char *names
= NULL
;
176 len
= strv_length(arg_fdnames
);
178 for (size_t i
= 1; i
< n_fds
; i
++) {
179 r
= strv_extend(&arg_fdnames
, arg_fdnames
[0]);
183 else if (len
!= n_fds
)
184 log_warning("The number of fd names is different than number of fds: %zu vs %zu", len
, n_fds
);
186 names
= strv_join(arg_fdnames
, ":");
190 char *t
= strjoin("LISTEN_FDNAMES=", names
);
194 r
= strv_consume(&envp
, t
);
200 STRV_FOREACH(s
, arg_setenv
) {
201 r
= strv_env_replace_strdup(&envp
, *s
);
206 _cleanup_free_
char *joined
= strv_join(argv
, " ");
210 log_info("Execing %s (%s)", name
, joined
);
211 execvpe(name
, argv
, envp
);
213 return log_error_errno(errno
, "Failed to execp %s (%s): %m", name
, joined
);
216 static int fork_and_exec_process(const char *child
, char **argv
, int fd
) {
217 _cleanup_free_
char *joined
= NULL
;
221 joined
= strv_join(argv
, " ");
225 r
= safe_fork("(activate)",
226 FORK_RESET_SIGNALS
| FORK_DEATHSIG_SIGTERM
| FORK_RLIMIT_NOFILE_SAFE
| FORK_LOG
,
232 exec_process(child
, argv
, fd
, 1);
236 log_info("Spawned %s (%s) as PID " PID_FMT
".", child
, joined
, child_pid
);
240 static int do_accept(const char *name
, char **argv
, int fd
) {
241 _cleanup_free_
char *local
= NULL
, *peer
= NULL
;
242 _cleanup_close_
int fd_accepted
= -EBADF
;
244 fd_accepted
= accept4(fd
, NULL
, NULL
, 0);
245 if (fd_accepted
< 0) {
246 if (ERRNO_IS_ACCEPT_AGAIN(errno
))
249 return log_error_errno(errno
, "Failed to accept connection on fd:%d: %m", fd
);
252 (void) getsockname_pretty(fd_accepted
, &local
);
253 (void) getpeername_pretty(fd_accepted
, true, &peer
);
254 log_info("Connection from %s to %s", strna(peer
), strna(local
));
256 return fork_and_exec_process(name
, argv
, fd_accepted
);
259 /* SIGCHLD handler. */
260 static void sigchld_hdl(int sig
) {
268 r
= waitid(P_ALL
, 0, &si
, WEXITED
| WNOHANG
);
271 log_error_errno(errno
, "Failed to reap children: %m");
277 log_info("Child %d died with code %d", si
.si_pid
, si
.si_status
);
281 static int install_chld_handler(void) {
282 static const struct sigaction act
= {
283 .sa_flags
= SA_NOCLDSTOP
| SA_RESTART
,
284 .sa_handler
= sigchld_hdl
,
287 if (sigaction(SIGCHLD
, &act
, 0) < 0)
288 return log_error_errno(errno
, "Failed to install SIGCHLD handler: %m");
293 static int help(void) {
294 _cleanup_free_
char *link
= NULL
;
297 r
= terminal_urlify_man("systemd-socket-activate", "1", &link
);
301 printf("%s [OPTIONS...]\n"
302 "\n%sListen on sockets and launch child on connection.%s\n"
304 " -h --help Show this help and exit\n"
305 " --version Print version string and exit\n"
306 " -l --listen=ADDR Listen for raw connections at ADDR\n"
307 " -d --datagram Listen on datagram instead of stream socket\n"
308 " --seqpacket Listen on SOCK_SEQPACKET instead of stream socket\n"
309 " -a --accept Spawn separate child for each connection\n"
310 " -E --setenv=NAME[=VALUE] Pass an environment variable to children\n"
311 " --fdname=NAME[:NAME...] Specify names for file descriptors\n"
312 " --inetd Enable inetd file descriptor passing protocol\n"
313 "\nNote: file descriptors from sd_listen_fds() will be passed through.\n"
314 "\nSee the %s for details.\n",
315 program_invocation_short_name
,
323 static int parse_argv(int argc
, char *argv
[]) {
331 static const struct option options
[] = {
332 { "help", no_argument
, NULL
, 'h' },
333 { "version", no_argument
, NULL
, ARG_VERSION
},
334 { "datagram", no_argument
, NULL
, 'd' },
335 { "seqpacket", no_argument
, NULL
, ARG_SEQPACKET
},
336 { "listen", required_argument
, NULL
, 'l' },
337 { "accept", no_argument
, NULL
, 'a' },
338 { "setenv", required_argument
, NULL
, 'E' },
339 { "environment", required_argument
, NULL
, 'E' }, /* legacy alias */
340 { "fdname", required_argument
, NULL
, ARG_FDNAME
},
341 { "inetd", no_argument
, NULL
, ARG_INETD
},
350 /* Resetting to 0 forces the invocation of an internal initialization routine of getopt_long()
351 * that checks for GNU extensions in optstring ('-' or '+' at the beginning). */
353 while ((c
= getopt_long(argc
, argv
, "+hl:aE:d", options
, NULL
)) >= 0)
362 r
= strv_extend(&arg_listen
, optarg
);
369 if (arg_socket_type
== SOCK_SEQPACKET
)
370 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
371 "--datagram may not be combined with --seqpacket.");
373 arg_socket_type
= SOCK_DGRAM
;
377 if (arg_socket_type
== SOCK_DGRAM
)
378 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
379 "--seqpacket may not be combined with --datagram.");
381 arg_socket_type
= SOCK_SEQPACKET
;
389 r
= strv_env_replace_strdup_passthrough(&arg_setenv
, optarg
);
391 return log_error_errno(r
, "Cannot assign environment variable %s: %m", optarg
);
395 _cleanup_strv_free_
char **names
= NULL
;
397 names
= strv_split(optarg
, ":");
401 STRV_FOREACH(s
, names
)
402 if (!fdname_is_valid(*s
)) {
403 _cleanup_free_
char *esc
= NULL
;
406 log_warning("File descriptor name \"%s\" is not valid.", esc
);
409 /* Empty optargs means one empty name */
410 r
= strv_extend_strv(&arg_fdnames
,
411 strv_isempty(names
) ? STRV_MAKE("") : names
,
414 return log_error_errno(r
, "strv_extend_strv: %m");
426 assert_not_reached();
430 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
431 "%s: command to execute is missing.",
432 program_invocation_short_name
);
434 if (arg_socket_type
== SOCK_DGRAM
&& arg_accept
)
435 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
436 "Datagram sockets do not accept connections. "
437 "The --datagram and --accept options may not be combined.");
439 arg_args
= argv
+ optind
;
441 return 1 /* work to do */;
444 static int run(int argc
, char **argv
) {
445 _cleanup_close_
int epoll_fd
= -EBADF
;
446 _cleanup_strv_free_
char **exec_argv
= NULL
;
449 log_show_color(true);
450 log_parse_environment();
453 r
= parse_argv(argc
, argv
);
457 exec_argv
= strv_copy(arg_args
);
461 assert(!strv_isempty(exec_argv
));
463 r
= install_chld_handler();
467 n
= open_sockets(&epoll_fd
, arg_accept
);
471 return log_error_errno(SYNTHETIC_ERRNO(ENOENT
), "No sockets to listen on specified or passed in.");
474 struct epoll_event event
;
476 if (epoll_wait(epoll_fd
, &event
, 1, -1) < 0) {
480 return log_error_errno(errno
, "epoll_wait() failed: %m");
483 log_info("Communication attempt on fd %i.", event
.data
.fd
);
485 r
= do_accept(exec_argv
[0], exec_argv
, event
.data
.fd
);
492 return exec_process(exec_argv
[0], exec_argv
, SD_LISTEN_FDS_START
, (size_t) n
);
495 DEFINE_MAIN_FUNCTION(run
);