1 /* SPDX-License-Identifier: LGPL-2.1+ */
3 Copyright © 2013 Zbigniew Jędrzejewski-Szmek
9 #include <sys/socket.h>
13 #include "sd-daemon.h"
15 #include "alloc-util.h"
20 #include "process-util.h"
21 #include "signal-util.h"
22 #include "socket-util.h"
23 #include "string-util.h"
26 static char** arg_listen
= NULL
;
27 static bool arg_accept
= false;
28 static int arg_socket_type
= SOCK_STREAM
;
29 static char** arg_args
= NULL
;
30 static char** arg_setenv
= NULL
;
31 static char **arg_fdnames
= NULL
;
32 static bool arg_inetd
= false;
34 static int add_epoll(int epoll_fd
, int fd
) {
35 struct epoll_event ev
= {
40 assert(epoll_fd
>= 0);
43 if (epoll_ctl(epoll_fd
, EPOLL_CTL_ADD
, fd
, &ev
) < 0)
44 return log_error_errno(errno
, "Failed to add event on epoll fd:%d for fd:%d: %m", epoll_fd
, fd
);
49 static int open_sockets(int *epoll_fd
, bool accept
) {
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 */
73 for (fd
= 0; fd
< SD_LISTEN_FDS_START
+ n
; fd
++)
77 close_all_fds(except
, 3 + n
);
80 /** Note: we leak some fd's on error here. I doesn't matter
81 * much, since the program will exit immediately anyway, but
82 * would be a pain to fix.
85 STRV_FOREACH(address
, arg_listen
) {
86 fd
= make_socket_fd(LOG_DEBUG
, *address
, arg_socket_type
, (arg_accept
*SOCK_CLOEXEC
));
89 return log_error_errno(fd
, "Failed to open '%s': %m", *address
);
92 assert(fd
== SD_LISTEN_FDS_START
+ count
);
99 *epoll_fd
= epoll_create1(EPOLL_CLOEXEC
);
101 return log_error_errno(errno
, "Failed to create epoll object: %m");
103 for (fd
= SD_LISTEN_FDS_START
; fd
< SD_LISTEN_FDS_START
+ count
; fd
++) {
104 _cleanup_free_
char *name
= NULL
;
106 getsockname_pretty(fd
, &name
);
107 log_info("Listening on %s as %i.", strna(name
), fd
);
109 r
= add_epoll(*epoll_fd
, fd
);
117 static int exec_process(const char* name
, char **argv
, char **env
, int start_fd
, size_t n_fds
) {
119 _cleanup_strv_free_
char **envp
= NULL
;
120 _cleanup_free_
char *joined
= NULL
;
121 size_t n_env
= 0, length
;
126 if (arg_inetd
&& n_fds
!= 1) {
127 log_error("--inetd only supported for single file descriptors.");
131 length
= strv_length(arg_setenv
);
133 /* PATH, TERM, HOME, USER, LISTEN_FDS, LISTEN_PID, LISTEN_FDNAMES, NULL */
134 envp
= new0(char *, length
+ 8);
138 STRV_FOREACH(s
, arg_setenv
) {
140 if (strchr(*s
, '=')) {
149 _cleanup_free_
char *p
;
152 p
= strappend(*s
, "=");
156 n
= strv_find_prefix(env
, p
);
160 envp
[n_env
] = strdup(n
);
168 FOREACH_STRING(tocopy
, "TERM=", "PATH=", "USER=", "HOME=") {
171 n
= strv_find_prefix(env
, tocopy
);
175 envp
[n_env
] = strdup(n
);
185 r
= rearrange_stdio(start_fd
, start_fd
, STDERR_FILENO
); /* invalidates start_fd on success + error */
187 return log_error_errno(r
, "Failed to move fd to stdin+stdout: %m");
190 if (start_fd
!= SD_LISTEN_FDS_START
) {
193 if (dup2(start_fd
, SD_LISTEN_FDS_START
) < 0)
194 return log_error_errno(errno
, "Failed to dup connection: %m");
196 safe_close(start_fd
);
197 start_fd
= SD_LISTEN_FDS_START
;
200 if (asprintf((char**)(envp
+ n_env
++), "LISTEN_FDS=%zu", n_fds
) < 0)
203 if (asprintf((char**)(envp
+ n_env
++), "LISTEN_PID=" PID_FMT
, getpid_cached()) < 0)
207 _cleanup_free_
char *names
= NULL
;
211 len
= strv_length(arg_fdnames
);
215 for (i
= 1; i
< n_fds
; i
++) {
216 r
= strv_extend(&arg_fdnames
, arg_fdnames
[0]);
218 return log_error_errno(r
, "Failed to extend strv: %m");
220 } else if (len
!= n_fds
)
221 log_warning("The number of fd names is different than number of fds: %zu vs %zu", len
, n_fds
);
223 names
= strv_join(arg_fdnames
, ":");
227 e
= strappend("LISTEN_FDNAMES=", names
);
235 joined
= strv_join(argv
, " ");
239 log_info("Execing %s (%s)", name
, joined
);
240 execvpe(name
, argv
, envp
);
242 return log_error_errno(errno
, "Failed to execp %s (%s): %m", name
, joined
);
245 static int fork_and_exec_process(const char* child
, char** argv
, char **env
, int fd
) {
246 _cleanup_free_
char *joined
= NULL
;
250 joined
= strv_join(argv
, " ");
254 r
= safe_fork("(activate)", FORK_RESET_SIGNALS
|FORK_DEATHSIG
|FORK_LOG
, &child_pid
);
259 exec_process(child
, argv
, env
, fd
, 1);
263 log_info("Spawned %s (%s) as PID " PID_FMT
".", child
, joined
, child_pid
);
267 static int do_accept(const char* name
, char **argv
, char **envp
, int fd
) {
268 _cleanup_free_
char *local
= NULL
, *peer
= NULL
;
269 _cleanup_close_
int fd_accepted
= -1;
271 fd_accepted
= accept4(fd
, NULL
, NULL
, 0);
273 return log_error_errno(errno
, "Failed to accept connection on fd:%d: %m", fd
);
275 getsockname_pretty(fd_accepted
, &local
);
276 getpeername_pretty(fd_accepted
, true, &peer
);
277 log_info("Connection from %s to %s", strna(peer
), strna(local
));
279 return fork_and_exec_process(name
, argv
, envp
, fd_accepted
);
282 /* SIGCHLD handler. */
283 static void sigchld_hdl(int sig
) {
291 r
= waitid(P_ALL
, 0, &si
, WEXITED
|WNOHANG
);
294 log_error_errno(errno
, "Failed to reap children: %m");
300 log_info("Child %d died with code %d", si
.si_pid
, si
.si_status
);
304 static int install_chld_handler(void) {
305 static const struct sigaction act
= {
306 .sa_flags
= SA_NOCLDSTOP
|SA_RESTART
,
307 .sa_handler
= sigchld_hdl
,
310 if (sigaction(SIGCHLD
, &act
, 0) < 0)
311 return log_error_errno(errno
, "Failed to install SIGCHLD handler: %m");
316 static void help(void) {
317 printf("%s [OPTIONS...]\n\n"
318 "Listen on sockets and launch child on connection.\n\n"
320 " -h --help Show this help and exit\n"
321 " --version Print version string and exit\n"
322 " -l --listen=ADDR Listen for raw connections at ADDR\n"
323 " -d --datagram Listen on datagram instead of stream socket\n"
324 " --seqpacket Listen on SOCK_SEQPACKET instead of stream socket\n"
325 " -a --accept Spawn separate child for each connection\n"
326 " -E --setenv=NAME[=VALUE] Pass an environment variable to children\n"
327 " --fdname=NAME[:NAME...] Specify names for file descriptors\n"
328 " --inetd Enable inetd file descriptor passing protocol\n"
330 "Note: file descriptors from sd_listen_fds() will be passed through.\n"
331 , program_invocation_short_name
);
334 static int parse_argv(int argc
, char *argv
[]) {
342 static const struct option options
[] = {
343 { "help", no_argument
, NULL
, 'h' },
344 { "version", no_argument
, NULL
, ARG_VERSION
},
345 { "datagram", no_argument
, NULL
, 'd' },
346 { "seqpacket", no_argument
, NULL
, ARG_SEQPACKET
},
347 { "listen", required_argument
, NULL
, 'l' },
348 { "accept", no_argument
, NULL
, 'a' },
349 { "setenv", required_argument
, NULL
, 'E' },
350 { "environment", required_argument
, NULL
, 'E' }, /* legacy alias */
351 { "fdname", required_argument
, NULL
, ARG_FDNAME
},
352 { "inetd", no_argument
, NULL
, ARG_INETD
},
361 while ((c
= getopt_long(argc
, argv
, "+hl:aE:d", options
, NULL
)) >= 0)
371 r
= strv_extend(&arg_listen
, optarg
);
378 if (arg_socket_type
== SOCK_SEQPACKET
) {
379 log_error("--datagram may not be combined with --seqpacket.");
383 arg_socket_type
= SOCK_DGRAM
;
387 if (arg_socket_type
== SOCK_DGRAM
) {
388 log_error("--seqpacket may not be combined with --datagram.");
392 arg_socket_type
= SOCK_SEQPACKET
;
400 r
= strv_extend(&arg_setenv
, optarg
);
407 _cleanup_strv_free_
char **names
;
410 names
= strv_split(optarg
, ":");
414 STRV_FOREACH(s
, names
)
415 if (!fdname_is_valid(*s
)) {
416 _cleanup_free_
char *esc
;
419 log_warning("File descriptor name \"%s\" is not valid.", esc
);
422 /* Empty optargs means one empty name */
423 r
= strv_extend_strv(&arg_fdnames
,
424 strv_isempty(names
) ? STRV_MAKE("") : names
,
427 return log_error_errno(r
, "strv_extend_strv: %m");
439 assert_not_reached("Unhandled option");
442 if (optind
== argc
) {
443 log_error("%s: command to execute is missing.",
444 program_invocation_short_name
);
448 if (arg_socket_type
== SOCK_DGRAM
&& arg_accept
) {
449 log_error("Datagram sockets do not accept connections. "
450 "The --datagram and --accept options may not be combined.");
454 arg_args
= argv
+ optind
;
456 return 1 /* work to do */;
459 int main(int argc
, char **argv
, char **envp
) {
463 log_parse_environment();
466 r
= parse_argv(argc
, argv
);
468 return r
== 0 ? EXIT_SUCCESS
: EXIT_FAILURE
;
470 r
= install_chld_handler();
474 n
= open_sockets(&epoll_fd
, arg_accept
);
478 log_error("No sockets to listen on specified or passed in.");
483 struct epoll_event event
;
485 if (epoll_wait(epoll_fd
, &event
, 1, -1) < 0) {
489 log_error_errno(errno
, "epoll_wait() failed: %m");
493 log_info("Communication attempt on fd %i.", event
.data
.fd
);
495 r
= do_accept(argv
[optind
], argv
+ optind
, envp
, event
.data
.fd
);
502 exec_process(argv
[optind
], argv
+ optind
, envp
, SD_LISTEN_FDS_START
, (size_t) n
);