1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
11 #include "alloc-util.h"
13 #include "errno-util.h"
18 #include "pretty-print.h"
19 #include "process-util.h"
20 #include "signal-util.h"
21 #include "socket-netlink.h"
22 #include "socket-util.h"
23 #include "string-util.h"
25 #include "terminal-util.h"
28 static char **arg_listen
= NULL
;
29 static bool arg_accept
= false;
30 static int arg_socket_type
= SOCK_STREAM
;
31 static char **arg_args
= NULL
;
32 static char **arg_setenv
= NULL
;
33 static char **arg_fdnames
= NULL
;
34 static bool arg_inetd
= false;
36 static int add_epoll(int epoll_fd
, int fd
) {
37 struct epoll_event ev
= {
42 assert(epoll_fd
>= 0);
45 if (epoll_ctl(epoll_fd
, EPOLL_CTL_ADD
, fd
, &ev
) < 0)
46 return log_error_errno(errno
, "Failed to add event on epoll fd:%d for fd:%d: %m", epoll_fd
, fd
);
51 static int open_sockets(int *epoll_fd
, bool accept
) {
53 int n
, fd
, r
, count
= 0;
55 n
= sd_listen_fds(true);
57 return log_error_errno(n
, "Failed to read listening file descriptors from environment: %m");
59 log_info("Received %i descriptors via the environment.", n
);
61 for (fd
= SD_LISTEN_FDS_START
; fd
< SD_LISTEN_FDS_START
+ n
; fd
++) {
62 r
= fd_cloexec(fd
, arg_accept
);
70 /* Close logging and all other descriptors */
72 _cleanup_free_
int *except
= NULL
;
79 for (i
= 0; i
< n
; i
++)
80 except
[i
] = SD_LISTEN_FDS_START
+ i
;
83 r
= close_all_fds(except
, n
);
85 return log_error_errno(r
, "Failed to close all file descriptors: %m");
88 /** Note: we leak some fd's on error here. I doesn't matter
89 * much, since the program will exit immediately anyway, but
90 * would be a pain to fix.
93 STRV_FOREACH(address
, arg_listen
) {
94 fd
= make_socket_fd(LOG_DEBUG
, *address
, arg_socket_type
, (arg_accept
* SOCK_CLOEXEC
));
97 return log_error_errno(fd
, "Failed to open '%s': %m", *address
);
100 assert(fd
== SD_LISTEN_FDS_START
+ count
);
107 *epoll_fd
= epoll_create1(EPOLL_CLOEXEC
);
109 return log_error_errno(errno
, "Failed to create epoll object: %m");
111 for (fd
= SD_LISTEN_FDS_START
; fd
< SD_LISTEN_FDS_START
+ count
; fd
++) {
112 _cleanup_free_
char *name
= NULL
;
114 getsockname_pretty(fd
, &name
);
115 log_info("Listening on %s as %i.", strna(name
), fd
);
117 r
= add_epoll(*epoll_fd
, fd
);
125 static int exec_process(const char *name
, char **argv
, int start_fd
, size_t n_fds
) {
126 _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
| 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
= -1;
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 while ((c
= getopt_long(argc
, argv
, "+hl:aE:d", options
, NULL
)) >= 0)
359 r
= strv_extend(&arg_listen
, optarg
);
366 if (arg_socket_type
== SOCK_SEQPACKET
)
367 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
368 "--datagram may not be combined with --seqpacket.");
370 arg_socket_type
= SOCK_DGRAM
;
374 if (arg_socket_type
== SOCK_DGRAM
)
375 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
376 "--seqpacket may not be combined with --datagram.");
378 arg_socket_type
= SOCK_SEQPACKET
;
386 r
= strv_env_replace_strdup_passthrough(&arg_setenv
, optarg
);
388 return log_error_errno(r
, "Cannot assign environment variable %s: %m", optarg
);
392 _cleanup_strv_free_
char **names
= NULL
;
395 names
= strv_split(optarg
, ":");
399 STRV_FOREACH(s
, names
)
400 if (!fdname_is_valid(*s
)) {
401 _cleanup_free_
char *esc
= NULL
;
404 log_warning("File descriptor name \"%s\" is not valid.", esc
);
407 /* Empty optargs means one empty name */
408 r
= strv_extend_strv(&arg_fdnames
,
409 strv_isempty(names
) ? STRV_MAKE("") : names
,
412 return log_error_errno(r
, "strv_extend_strv: %m");
424 assert_not_reached();
428 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
429 "%s: command to execute is missing.",
430 program_invocation_short_name
);
432 if (arg_socket_type
== SOCK_DGRAM
&& arg_accept
)
433 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
434 "Datagram sockets do not accept connections. "
435 "The --datagram and --accept options may not be combined.");
437 arg_args
= argv
+ optind
;
439 return 1 /* work to do */;
442 int main(int argc
, char **argv
) {
446 log_show_color(true);
447 log_parse_environment();
450 r
= parse_argv(argc
, argv
);
452 return r
== 0 ? EXIT_SUCCESS
: EXIT_FAILURE
;
454 r
= install_chld_handler();
458 n
= open_sockets(&epoll_fd
, arg_accept
);
462 log_error("No sockets to listen on specified or passed in.");
467 struct epoll_event event
;
469 if (epoll_wait(epoll_fd
, &event
, 1, -1) < 0) {
473 log_error_errno(errno
, "epoll_wait() failed: %m");
477 log_info("Communication attempt on fd %i.", event
.data
.fd
);
479 r
= do_accept(argv
[optind
], argv
+ optind
, event
.data
.fd
);
486 exec_process(argv
[optind
], argv
+ optind
, SD_LISTEN_FDS_START
, (size_t) n
);