1 /* SPDX-License-Identifier: LGPL-2.1+ */
3 This file is part of systemd.
5 Copyright 2013 Zbigniew Jędrzejewski-Szmek
10 #include <sys/prctl.h>
11 #include <sys/socket.h>
15 #include "sd-daemon.h"
17 #include "alloc-util.h"
22 #include "process-util.h"
23 #include "signal-util.h"
24 #include "socket-util.h"
25 #include "string-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
) {
56 n
= sd_listen_fds(true);
58 return log_error_errno(n
, "Failed to read listening file descriptors from environment: %m");
60 log_info("Received %i descriptors via the environment.", n
);
62 for (fd
= SD_LISTEN_FDS_START
; fd
< SD_LISTEN_FDS_START
+ n
; fd
++) {
63 r
= fd_cloexec(fd
, arg_accept
);
71 /* Close logging and all other descriptors */
75 for (fd
= 0; fd
< SD_LISTEN_FDS_START
+ n
; fd
++)
79 close_all_fds(except
, 3 + n
);
82 /** Note: we leak some fd's on error here. I doesn't matter
83 * much, since the program will exit immediately anyway, but
84 * would be a pain to fix.
87 STRV_FOREACH(address
, arg_listen
) {
88 fd
= make_socket_fd(LOG_DEBUG
, *address
, arg_socket_type
, (arg_accept
*SOCK_CLOEXEC
));
91 return log_error_errno(fd
, "Failed to open '%s': %m", *address
);
94 assert(fd
== SD_LISTEN_FDS_START
+ count
);
101 *epoll_fd
= epoll_create1(EPOLL_CLOEXEC
);
103 return log_error_errno(errno
, "Failed to create epoll object: %m");
105 for (fd
= SD_LISTEN_FDS_START
; fd
< SD_LISTEN_FDS_START
+ count
; fd
++) {
106 _cleanup_free_
char *name
= NULL
;
108 getsockname_pretty(fd
, &name
);
109 log_info("Listening on %s as %i.", strna(name
), fd
);
111 r
= add_epoll(*epoll_fd
, fd
);
119 static int exec_process(const char* name
, char **argv
, char **env
, int start_fd
, size_t n_fds
) {
121 _cleanup_strv_free_
char **envp
= NULL
;
122 _cleanup_free_
char *joined
= NULL
;
123 size_t n_env
= 0, length
;
128 if (arg_inetd
&& n_fds
!= 1) {
129 log_error("--inetd only supported for single file descriptors.");
133 length
= strv_length(arg_setenv
);
135 /* PATH, TERM, HOME, USER, LISTEN_FDS, LISTEN_PID, LISTEN_FDNAMES, NULL */
136 envp
= new0(char *, length
+ 8);
140 STRV_FOREACH(s
, arg_setenv
) {
142 if (strchr(*s
, '=')) {
151 _cleanup_free_
char *p
;
154 p
= strappend(*s
, "=");
158 n
= strv_find_prefix(env
, p
);
162 envp
[n_env
] = strdup(n
);
170 FOREACH_STRING(tocopy
, "TERM=", "PATH=", "USER=", "HOME=") {
173 n
= strv_find_prefix(env
, tocopy
);
177 envp
[n_env
] = strdup(n
);
187 r
= rearrange_stdio(start_fd
, start_fd
, STDERR_FILENO
); /* invalidates start_fd on success + error */
189 return log_error_errno(r
, "Failed to move fd to stdin+stdout: %m");
192 if (start_fd
!= SD_LISTEN_FDS_START
) {
195 if (dup2(start_fd
, SD_LISTEN_FDS_START
) < 0)
196 return log_error_errno(errno
, "Failed to dup connection: %m");
198 safe_close(start_fd
);
199 start_fd
= SD_LISTEN_FDS_START
;
202 if (asprintf((char**)(envp
+ n_env
++), "LISTEN_FDS=%zu", n_fds
) < 0)
205 if (asprintf((char**)(envp
+ n_env
++), "LISTEN_PID=" PID_FMT
, getpid_cached()) < 0)
209 _cleanup_free_
char *names
= NULL
;
213 len
= strv_length(arg_fdnames
);
217 for (i
= 1; i
< n_fds
; i
++) {
218 r
= strv_extend(&arg_fdnames
, arg_fdnames
[0]);
220 return log_error_errno(r
, "Failed to extend strv: %m");
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
= strappend("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)", FORK_RESET_SIGNALS
|FORK_DEATHSIG
|FORK_LOG
, &child_pid
);
261 exec_process(child
, argv
, env
, fd
, 1);
265 log_info("Spawned %s (%s) as PID " PID_FMT
".", child
, joined
, child_pid
);
269 static int do_accept(const char* name
, char **argv
, char **envp
, int fd
) {
270 _cleanup_free_
char *local
= NULL
, *peer
= NULL
;
271 _cleanup_close_
int fd_accepted
= -1;
273 fd_accepted
= accept4(fd
, NULL
, NULL
, 0);
275 return log_error_errno(errno
, "Failed to accept connection on fd:%d: %m", fd
);
277 getsockname_pretty(fd_accepted
, &local
);
278 getpeername_pretty(fd_accepted
, true, &peer
);
279 log_info("Connection from %s to %s", strna(peer
), strna(local
));
281 return fork_and_exec_process(name
, argv
, envp
, fd_accepted
);
284 /* SIGCHLD handler. */
285 static void sigchld_hdl(int sig
) {
293 r
= waitid(P_ALL
, 0, &si
, WEXITED
|WNOHANG
);
296 log_error_errno(errno
, "Failed to reap children: %m");
302 log_info("Child %d died with code %d", si
.si_pid
, si
.si_status
);
306 static int install_chld_handler(void) {
307 static const struct sigaction act
= {
308 .sa_flags
= SA_NOCLDSTOP
|SA_RESTART
,
309 .sa_handler
= sigchld_hdl
,
312 if (sigaction(SIGCHLD
, &act
, 0) < 0)
313 return log_error_errno(errno
, "Failed to install SIGCHLD handler: %m");
318 static void help(void) {
319 printf("%s [OPTIONS...]\n\n"
320 "Listen on sockets and launch child on connection.\n\n"
322 " -h --help Show this help and exit\n"
323 " --version Print version string and exit\n"
324 " -l --listen=ADDR Listen for raw connections at ADDR\n"
325 " -d --datagram Listen on datagram instead of stream socket\n"
326 " --seqpacket Listen on SOCK_SEQPACKET instead of stream socket\n"
327 " -a --accept Spawn separate child for each connection\n"
328 " -E --setenv=NAME[=VALUE] Pass an environment variable to children\n"
329 " --fdname=NAME[:NAME...] Specify names for file descriptors\n"
330 " --inetd Enable inetd file descriptor passing protocol\n"
332 "Note: file descriptors from sd_listen_fds() will be passed through.\n"
333 , program_invocation_short_name
);
336 static int parse_argv(int argc
, char *argv
[]) {
344 static const struct option options
[] = {
345 { "help", no_argument
, NULL
, 'h' },
346 { "version", no_argument
, NULL
, ARG_VERSION
},
347 { "datagram", no_argument
, NULL
, 'd' },
348 { "seqpacket", no_argument
, NULL
, ARG_SEQPACKET
},
349 { "listen", required_argument
, NULL
, 'l' },
350 { "accept", no_argument
, NULL
, 'a' },
351 { "setenv", required_argument
, NULL
, 'E' },
352 { "environment", required_argument
, NULL
, 'E' }, /* legacy alias */
353 { "fdname", required_argument
, NULL
, ARG_FDNAME
},
354 { "inetd", no_argument
, NULL
, ARG_INETD
},
363 while ((c
= getopt_long(argc
, argv
, "+hl:aE:d", options
, NULL
)) >= 0)
373 r
= strv_extend(&arg_listen
, optarg
);
380 if (arg_socket_type
== SOCK_SEQPACKET
) {
381 log_error("--datagram may not be combined with --seqpacket.");
385 arg_socket_type
= SOCK_DGRAM
;
389 if (arg_socket_type
== SOCK_DGRAM
) {
390 log_error("--seqpacket may not be combined with --datagram.");
394 arg_socket_type
= SOCK_SEQPACKET
;
402 r
= strv_extend(&arg_setenv
, optarg
);
409 _cleanup_strv_free_
char **names
;
412 names
= strv_split(optarg
, ":");
416 STRV_FOREACH(s
, names
)
417 if (!fdname_is_valid(*s
)) {
418 _cleanup_free_
char *esc
;
421 log_warning("File descriptor name \"%s\" is not valid.", esc
);
424 /* Empty optargs means one empty name */
425 r
= strv_extend_strv(&arg_fdnames
,
426 strv_isempty(names
) ? STRV_MAKE("") : names
,
429 return log_error_errno(r
, "strv_extend_strv: %m");
441 assert_not_reached("Unhandled option");
444 if (optind
== argc
) {
445 log_error("%s: command to execute is missing.",
446 program_invocation_short_name
);
450 if (arg_socket_type
== SOCK_DGRAM
&& arg_accept
) {
451 log_error("Datagram sockets do not accept connections. "
452 "The --datagram and --accept options may not be combined.");
456 arg_args
= argv
+ optind
;
458 return 1 /* work to do */;
461 int main(int argc
, char **argv
, char **envp
) {
465 log_parse_environment();
468 r
= parse_argv(argc
, argv
);
470 return r
== 0 ? EXIT_SUCCESS
: EXIT_FAILURE
;
472 r
= install_chld_handler();
476 n
= open_sockets(&epoll_fd
, arg_accept
);
480 log_error("No sockets to listen on specified or passed in.");
485 struct epoll_event event
;
487 if (epoll_wait(epoll_fd
, &event
, 1, -1) < 0) {
491 log_error_errno(errno
, "epoll_wait() failed: %m");
495 log_info("Communication attempt on fd %i.", event
.data
.fd
);
497 r
= do_accept(argv
[optind
], argv
+ optind
, envp
, event
.data
.fd
);
504 exec_process(argv
[optind
], argv
+ optind
, envp
, SD_LISTEN_FDS_START
, (size_t) n
);