1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
11 #include "alloc-util.h"
12 #include "errno-util.h"
17 #include "pretty-print.h"
18 #include "process-util.h"
19 #include "signal-util.h"
20 #include "socket-netlink.h"
21 #include "socket-util.h"
22 #include "string-util.h"
24 #include "terminal-util.h"
27 static char **arg_listen
= NULL
;
28 static bool arg_accept
= false;
29 static int arg_socket_type
= SOCK_STREAM
;
30 static char **arg_args
= NULL
;
31 static char **arg_setenv
= NULL
;
32 static char **arg_fdnames
= NULL
;
33 static bool arg_inetd
= false;
35 static int add_epoll(int epoll_fd
, int fd
) {
36 struct epoll_event ev
= {
41 assert(epoll_fd
>= 0);
44 if (epoll_ctl(epoll_fd
, EPOLL_CTL_ADD
, fd
, &ev
) < 0)
45 return log_error_errno(errno
, "Failed to add event on epoll fd:%d for fd:%d: %m", epoll_fd
, fd
);
50 static int open_sockets(int *epoll_fd
, bool accept
) {
52 int n
, fd
, r
, count
= 0;
54 n
= sd_listen_fds(true);
56 return log_error_errno(n
, "Failed to read listening file descriptors from environment: %m");
58 log_info("Received %i descriptors via the environment.", n
);
60 for (fd
= SD_LISTEN_FDS_START
; fd
< SD_LISTEN_FDS_START
+ n
; fd
++) {
61 r
= fd_cloexec(fd
, arg_accept
);
69 /* Close logging and all other descriptors */
71 _cleanup_free_
int *except
= NULL
;
78 for (i
= 0; i
< n
; i
++)
79 except
[i
] = SD_LISTEN_FDS_START
+ i
;
82 r
= close_all_fds(except
, n
);
84 return log_error_errno(r
, "Failed to close all file descriptors: %m");
87 /** Note: we leak some fd's on error here. I doesn't matter
88 * much, since the program will exit immediately anyway, but
89 * would be a pain to fix.
92 STRV_FOREACH(address
, arg_listen
) {
93 fd
= make_socket_fd(LOG_DEBUG
, *address
, arg_socket_type
, (arg_accept
* SOCK_CLOEXEC
));
96 return log_error_errno(fd
, "Failed to open '%s': %m", *address
);
99 assert(fd
== SD_LISTEN_FDS_START
+ count
);
106 *epoll_fd
= epoll_create1(EPOLL_CLOEXEC
);
108 return log_error_errno(errno
, "Failed to create epoll object: %m");
110 for (fd
= SD_LISTEN_FDS_START
; fd
< SD_LISTEN_FDS_START
+ count
; fd
++) {
111 _cleanup_free_
char *name
= NULL
;
113 getsockname_pretty(fd
, &name
);
114 log_info("Listening on %s as %i.", strna(name
), fd
);
116 r
= add_epoll(*epoll_fd
, fd
);
124 static int exec_process(const char *name
, char **argv
, char **env
, int start_fd
, size_t n_fds
) {
125 _cleanup_strv_free_
char **envp
= NULL
;
126 _cleanup_free_
char *joined
= NULL
;
127 size_t n_env
= 0, length
;
132 if (arg_inetd
&& n_fds
!= 1)
133 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
134 "--inetd only supported for single file descriptors.");
136 length
= strv_length(arg_setenv
);
138 /* PATH, TERM, HOME, USER, LISTEN_FDS, LISTEN_PID, LISTEN_FDNAMES, NULL */
139 envp
= new0(char *, length
+ 8);
143 STRV_FOREACH(s
, arg_setenv
) {
145 if (strchr(*s
, '=')) {
154 _cleanup_free_
char *p
;
157 p
= strjoin(*s
, "=");
161 n
= strv_find_prefix(env
, p
);
165 envp
[n_env
] = strdup(n
);
173 FOREACH_STRING(tocopy
, "TERM=", "PATH=", "USER=", "HOME=") {
176 n
= strv_find_prefix(env
, tocopy
);
180 envp
[n_env
] = strdup(n
);
190 r
= rearrange_stdio(start_fd
, start_fd
, STDERR_FILENO
); /* invalidates start_fd on success + error */
192 return log_error_errno(r
, "Failed to move fd to stdin+stdout: %m");
195 if (start_fd
!= SD_LISTEN_FDS_START
) {
198 if (dup2(start_fd
, SD_LISTEN_FDS_START
) < 0)
199 return log_error_errno(errno
, "Failed to dup connection: %m");
201 safe_close(start_fd
);
204 if (asprintf((char **) (envp
+ n_env
++), "LISTEN_FDS=%zu", n_fds
) < 0)
207 if (asprintf((char **) (envp
+ n_env
++), "LISTEN_PID=" PID_FMT
, getpid_cached()) < 0)
211 _cleanup_free_
char *names
= NULL
;
215 len
= strv_length(arg_fdnames
);
217 for (size_t i
= 1; i
< n_fds
; i
++) {
218 r
= strv_extend(&arg_fdnames
, arg_fdnames
[0]);
222 else if (len
!= n_fds
)
223 log_warning("The number of fd names is different than number of fds: %zu vs %zu", len
, n_fds
);
225 names
= strv_join(arg_fdnames
, ":");
229 e
= strjoin("LISTEN_FDNAMES=", names
);
237 joined
= strv_join(argv
, " ");
241 log_info("Execing %s (%s)", name
, joined
);
242 execvpe(name
, argv
, envp
);
244 return log_error_errno(errno
, "Failed to execp %s (%s): %m", name
, joined
);
247 static int fork_and_exec_process(const char *child
, char **argv
, char **env
, int fd
) {
248 _cleanup_free_
char *joined
= NULL
;
252 joined
= strv_join(argv
, " ");
256 r
= safe_fork("(activate)",
257 FORK_RESET_SIGNALS
| FORK_DEATHSIG
| FORK_RLIMIT_NOFILE_SAFE
| FORK_LOG
,
263 exec_process(child
, argv
, env
, fd
, 1);
267 log_info("Spawned %s (%s) as PID " PID_FMT
".", child
, joined
, child_pid
);
271 static int do_accept(const char *name
, char **argv
, char **envp
, int fd
) {
272 _cleanup_free_
char *local
= NULL
, *peer
= NULL
;
273 _cleanup_close_
int fd_accepted
= -1;
275 fd_accepted
= accept4(fd
, NULL
, NULL
, 0);
276 if (fd_accepted
< 0) {
277 if (ERRNO_IS_ACCEPT_AGAIN(errno
))
280 return log_error_errno(errno
, "Failed to accept connection on fd:%d: %m", fd
);
283 (void) getsockname_pretty(fd_accepted
, &local
);
284 (void) getpeername_pretty(fd_accepted
, true, &peer
);
285 log_info("Connection from %s to %s", strna(peer
), strna(local
));
287 return fork_and_exec_process(name
, argv
, envp
, fd_accepted
);
290 /* SIGCHLD handler. */
291 static void sigchld_hdl(int sig
) {
299 r
= waitid(P_ALL
, 0, &si
, WEXITED
| WNOHANG
);
302 log_error_errno(errno
, "Failed to reap children: %m");
308 log_info("Child %d died with code %d", si
.si_pid
, si
.si_status
);
312 static int install_chld_handler(void) {
313 static const struct sigaction act
= {
314 .sa_flags
= SA_NOCLDSTOP
| SA_RESTART
,
315 .sa_handler
= sigchld_hdl
,
318 if (sigaction(SIGCHLD
, &act
, 0) < 0)
319 return log_error_errno(errno
, "Failed to install SIGCHLD handler: %m");
324 static int help(void) {
325 _cleanup_free_
char *link
= NULL
;
328 r
= terminal_urlify_man("systemd-socket-activate", "1", &link
);
332 printf("%s [OPTIONS...]\n"
333 "\n%sListen on sockets and launch child on connection.%s\n"
335 " -h --help Show this help and exit\n"
336 " --version Print version string and exit\n"
337 " -l --listen=ADDR Listen for raw connections at ADDR\n"
338 " -d --datagram Listen on datagram instead of stream socket\n"
339 " --seqpacket Listen on SOCK_SEQPACKET instead of stream socket\n"
340 " -a --accept Spawn separate child for each connection\n"
341 " -E --setenv=NAME[=VALUE] Pass an environment variable to children\n"
342 " --fdname=NAME[:NAME...] Specify names for file descriptors\n"
343 " --inetd Enable inetd file descriptor passing protocol\n"
344 "\nNote: file descriptors from sd_listen_fds() will be passed through.\n"
345 "\nSee the %s for details.\n",
346 program_invocation_short_name
,
354 static int parse_argv(int argc
, char *argv
[]) {
362 static const struct option options
[] = {
363 { "help", no_argument
, NULL
, 'h' },
364 { "version", no_argument
, NULL
, ARG_VERSION
},
365 { "datagram", no_argument
, NULL
, 'd' },
366 { "seqpacket", no_argument
, NULL
, ARG_SEQPACKET
},
367 { "listen", required_argument
, NULL
, 'l' },
368 { "accept", no_argument
, NULL
, 'a' },
369 { "setenv", required_argument
, NULL
, 'E' },
370 { "environment", required_argument
, NULL
, 'E' }, /* legacy alias */
371 { "fdname", required_argument
, NULL
, ARG_FDNAME
},
372 { "inetd", no_argument
, NULL
, ARG_INETD
},
381 while ((c
= getopt_long(argc
, argv
, "+hl:aE:d", options
, NULL
)) >= 0)
390 r
= strv_extend(&arg_listen
, optarg
);
397 if (arg_socket_type
== SOCK_SEQPACKET
)
398 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
399 "--datagram may not be combined with --seqpacket.");
401 arg_socket_type
= SOCK_DGRAM
;
405 if (arg_socket_type
== SOCK_DGRAM
)
406 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
407 "--seqpacket may not be combined with --datagram.");
409 arg_socket_type
= SOCK_SEQPACKET
;
417 r
= strv_extend(&arg_setenv
, optarg
);
424 _cleanup_strv_free_
char **names
;
427 names
= strv_split(optarg
, ":");
431 STRV_FOREACH(s
, names
)
432 if (!fdname_is_valid(*s
)) {
433 _cleanup_free_
char *esc
;
436 log_warning("File descriptor name \"%s\" is not valid.", esc
);
439 /* Empty optargs means one empty name */
440 r
= strv_extend_strv(&arg_fdnames
,
441 strv_isempty(names
) ? STRV_MAKE("") : names
,
444 return log_error_errno(r
, "strv_extend_strv: %m");
456 assert_not_reached("Unhandled option");
460 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
461 "%s: command to execute is missing.",
462 program_invocation_short_name
);
464 if (arg_socket_type
== SOCK_DGRAM
&& arg_accept
)
465 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
466 "Datagram sockets do not accept connections. "
467 "The --datagram and --accept options may not be combined.");
469 arg_args
= argv
+ optind
;
471 return 1 /* work to do */;
474 int main(int argc
, char **argv
, char **envp
) {
478 log_show_color(true);
479 log_parse_environment();
482 r
= parse_argv(argc
, argv
);
484 return r
== 0 ? EXIT_SUCCESS
: EXIT_FAILURE
;
486 r
= install_chld_handler();
490 n
= open_sockets(&epoll_fd
, arg_accept
);
494 log_error("No sockets to listen on specified or passed in.");
499 struct epoll_event event
;
501 if (epoll_wait(epoll_fd
, &event
, 1, -1) < 0) {
505 log_error_errno(errno
, "epoll_wait() failed: %m");
509 log_info("Communication attempt on fd %i.", event
.data
.fd
);
511 r
= do_accept(argv
[optind
], argv
+ optind
, envp
, event
.data
.fd
);
518 exec_process(argv
[optind
], argv
+ optind
, envp
, SD_LISTEN_FDS_START
, (size_t) n
);