2 This file is part of systemd.
4 Copyright 2013 Zbigniew Jędrzejewski-Szmek
6 systemd is free software; you can redistribute it and/or modify it
7 under the terms of the GNU Lesser General Public License as published by
8 the Free Software Foundation; either version 2.1 of the License, or
9 (at your option) any later version.
11 systemd is distributed in the hope that it will be useful, but
12 WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 Lesser General Public License for more details.
16 You should have received a copy of the GNU Lesser General Public License
17 along with systemd; If not, see <http://www.gnu.org/licenses/>.
21 #include <sys/epoll.h>
22 #include <sys/prctl.h>
23 #include <sys/socket.h>
27 #include "sd-daemon.h"
29 #include "alloc-util.h"
34 #include "signal-util.h"
35 #include "socket-util.h"
36 #include "string-util.h"
39 static char** arg_listen
= NULL
;
40 static bool arg_accept
= false;
41 static int arg_socket_type
= SOCK_STREAM
;
42 static char** arg_args
= NULL
;
43 static char** arg_setenv
= NULL
;
44 static char **arg_fdnames
= NULL
;
45 static bool arg_inetd
= false;
47 static int add_epoll(int epoll_fd
, int fd
) {
48 struct epoll_event ev
= {
53 assert(epoll_fd
>= 0);
57 r
= epoll_ctl(epoll_fd
, EPOLL_CTL_ADD
, fd
, &ev
);
59 return log_error_errno(errno
, "Failed to add event on epoll fd:%d for fd:%d: %m", epoll_fd
, fd
);
64 static int open_sockets(int *epoll_fd
, bool accept
) {
69 n
= sd_listen_fds(true);
71 return log_error_errno(n
, "Failed to read listening file descriptors from environment: %m");
73 log_info("Received %i descriptors via the environment.", n
);
75 for (fd
= SD_LISTEN_FDS_START
; fd
< SD_LISTEN_FDS_START
+ n
; fd
++) {
76 r
= fd_cloexec(fd
, arg_accept
);
84 /* Close logging and all other descriptors */
88 for (fd
= 0; fd
< SD_LISTEN_FDS_START
+ n
; fd
++)
92 close_all_fds(except
, 3 + n
);
95 /** Note: we leak some fd's on error here. I doesn't matter
96 * much, since the program will exit immediately anyway, but
97 * would be a pain to fix.
100 STRV_FOREACH(address
, arg_listen
) {
101 fd
= make_socket_fd(LOG_DEBUG
, *address
, arg_socket_type
, (arg_accept
*SOCK_CLOEXEC
));
104 return log_error_errno(fd
, "Failed to open '%s': %m", *address
);
107 assert(fd
== SD_LISTEN_FDS_START
+ count
);
114 *epoll_fd
= epoll_create1(EPOLL_CLOEXEC
);
116 return log_error_errno(errno
, "Failed to create epoll object: %m");
118 for (fd
= SD_LISTEN_FDS_START
; fd
< SD_LISTEN_FDS_START
+ count
; fd
++) {
119 _cleanup_free_
char *name
= NULL
;
121 getsockname_pretty(fd
, &name
);
122 log_info("Listening on %s as %i.", strna(name
), fd
);
124 r
= add_epoll(*epoll_fd
, fd
);
132 static int exec_process(const char* name
, char **argv
, char **env
, int start_fd
, int n_fds
) {
134 _cleanup_strv_free_
char **envp
= NULL
;
135 _cleanup_free_
char *joined
= NULL
;
136 unsigned n_env
= 0, length
;
141 if (arg_inetd
&& n_fds
!= 1) {
142 log_error("--inetd only supported for single file descriptors.");
146 length
= strv_length(arg_setenv
);
148 /* PATH, TERM, HOME, USER, LISTEN_FDS, LISTEN_PID, LISTEN_FDNAMES, NULL */
149 envp
= new0(char *, length
+ 8);
153 STRV_FOREACH(s
, arg_setenv
) {
155 if (strchr(*s
, '=')) {
164 _cleanup_free_
char *p
;
167 p
= strappend(*s
, "=");
171 n
= strv_find_prefix(env
, p
);
175 envp
[n_env
] = strdup(n
);
183 FOREACH_STRING(tocopy
, "TERM=", "PATH=", "USER=", "HOME=") {
186 n
= strv_find_prefix(env
, tocopy
);
190 envp
[n_env
] = strdup(n
);
200 r
= dup2(start_fd
, STDIN_FILENO
);
202 return log_error_errno(errno
, "Failed to dup connection to stdin: %m");
204 r
= dup2(start_fd
, STDOUT_FILENO
);
206 return log_error_errno(errno
, "Failed to dup connection to stdout: %m");
208 start_fd
= safe_close(start_fd
);
210 if (start_fd
!= SD_LISTEN_FDS_START
) {
213 r
= dup2(start_fd
, SD_LISTEN_FDS_START
);
215 return log_error_errno(errno
, "Failed to dup connection: %m");
217 safe_close(start_fd
);
218 start_fd
= SD_LISTEN_FDS_START
;
221 if (asprintf((char**)(envp
+ n_env
++), "LISTEN_FDS=%i", n_fds
) < 0)
224 if (asprintf((char**)(envp
+ n_env
++), "LISTEN_PID=" PID_FMT
, getpid()) < 0)
228 _cleanup_free_
char *names
= NULL
;
233 len
= strv_length(arg_fdnames
);
235 for (i
= 1; i
< n_fds
; i
++) {
236 r
= strv_extend(&arg_fdnames
, arg_fdnames
[0]);
238 return log_error_errno(r
, "Failed to extend strv: %m");
240 else if (len
!= (unsigned) n_fds
)
241 log_warning("The number of fd names is different than number of fds: %zu vs %d",
244 names
= strv_join(arg_fdnames
, ":");
248 e
= strappend("LISTEN_FDNAMES=", names
);
256 joined
= strv_join(argv
, " ");
260 log_info("Execing %s (%s)", name
, joined
);
261 execvpe(name
, argv
, envp
);
263 return log_error_errno(errno
, "Failed to execp %s (%s): %m", name
, joined
);
266 static int fork_and_exec_process(const char* child
, char** argv
, char **env
, int fd
) {
267 _cleanup_free_
char *joined
= NULL
;
268 pid_t parent_pid
, child_pid
;
270 joined
= strv_join(argv
, " ");
274 parent_pid
= getpid();
278 return log_error_errno(errno
, "Failed to fork: %m");
281 if (child_pid
== 0) {
283 (void) reset_all_signal_handlers();
284 (void) reset_signal_mask();
286 /* Make sure the child goes away when the parent dies */
287 if (prctl(PR_SET_PDEATHSIG
, SIGTERM
) < 0)
290 /* Check whether our parent died before we were able
291 * to set the death signal */
292 if (getppid() != parent_pid
)
295 exec_process(child
, argv
, env
, fd
, 1);
299 log_info("Spawned %s (%s) as PID %d", child
, joined
, child_pid
);
303 static int do_accept(const char* name
, char **argv
, char **envp
, int fd
) {
304 _cleanup_free_
char *local
= NULL
, *peer
= NULL
;
305 _cleanup_close_
int fd_accepted
= -1;
307 fd_accepted
= accept4(fd
, NULL
, NULL
, 0);
309 return log_error_errno(errno
, "Failed to accept connection on fd:%d: %m", fd
);
311 getsockname_pretty(fd_accepted
, &local
);
312 getpeername_pretty(fd_accepted
, true, &peer
);
313 log_info("Connection from %s to %s", strna(peer
), strna(local
));
315 return fork_and_exec_process(name
, argv
, envp
, fd_accepted
);
318 /* SIGCHLD handler. */
319 static void sigchld_hdl(int sig
) {
327 r
= waitid(P_ALL
, 0, &si
, WEXITED
|WNOHANG
);
330 log_error_errno(errno
, "Failed to reap children: %m");
336 log_info("Child %d died with code %d", si
.si_pid
, si
.si_status
);
340 static int install_chld_handler(void) {
341 static const struct sigaction act
= {
342 .sa_flags
= SA_NOCLDSTOP
,
343 .sa_handler
= sigchld_hdl
,
348 r
= sigaction(SIGCHLD
, &act
, 0);
350 return log_error_errno(errno
, "Failed to install SIGCHLD handler: %m");
355 static void help(void) {
356 printf("%s [OPTIONS...]\n\n"
357 "Listen on sockets and launch child on connection.\n\n"
359 " -h --help Show this help and exit\n"
360 " --version Print version string and exit\n"
361 " -l --listen=ADDR Listen for raw connections at ADDR\n"
362 " -d --datagram Listen on datagram instead of stream socket\n"
363 " --seqpacket Listen on SOCK_SEQPACKET instead of stream socket\n"
364 " -a --accept Spawn separate child for each connection\n"
365 " -E --setenv=NAME[=VALUE] Pass an environment variable to children\n"
366 " --fdname=NAME[:NAME...] Specify names for file descriptors\n"
367 " --inetd Enable inetd file descriptor passing protocol\n"
369 "Note: file descriptors from sd_listen_fds() will be passed through.\n"
370 , program_invocation_short_name
);
373 static int parse_argv(int argc
, char *argv
[]) {
381 static const struct option options
[] = {
382 { "help", no_argument
, NULL
, 'h' },
383 { "version", no_argument
, NULL
, ARG_VERSION
},
384 { "datagram", no_argument
, NULL
, 'd' },
385 { "seqpacket", no_argument
, NULL
, ARG_SEQPACKET
},
386 { "listen", required_argument
, NULL
, 'l' },
387 { "accept", no_argument
, NULL
, 'a' },
388 { "setenv", required_argument
, NULL
, 'E' },
389 { "environment", required_argument
, NULL
, 'E' }, /* legacy alias */
390 { "fdname", required_argument
, NULL
, ARG_FDNAME
},
391 { "inetd", no_argument
, NULL
, ARG_INETD
},
400 while ((c
= getopt_long(argc
, argv
, "+hl:aE:d", options
, NULL
)) >= 0)
410 r
= strv_extend(&arg_listen
, optarg
);
417 if (arg_socket_type
== SOCK_SEQPACKET
) {
418 log_error("--datagram may not be combined with --seqpacket.");
422 arg_socket_type
= SOCK_DGRAM
;
426 if (arg_socket_type
== SOCK_DGRAM
) {
427 log_error("--seqpacket may not be combined with --datagram.");
431 arg_socket_type
= SOCK_SEQPACKET
;
439 r
= strv_extend(&arg_setenv
, optarg
);
446 _cleanup_strv_free_
char **names
;
449 names
= strv_split(optarg
, ":");
453 STRV_FOREACH(s
, names
)
454 if (!fdname_is_valid(*s
)) {
455 _cleanup_free_
char *esc
;
458 log_warning("File descriptor name \"%s\" is not valid.", esc
);
461 /* Empty optargs means one empty name */
462 r
= strv_extend_strv(&arg_fdnames
,
463 strv_isempty(names
) ? STRV_MAKE("") : names
,
466 return log_error_errno(r
, "strv_extend_strv: %m");
478 assert_not_reached("Unhandled option");
481 if (optind
== argc
) {
482 log_error("%s: command to execute is missing.",
483 program_invocation_short_name
);
487 if (arg_socket_type
== SOCK_DGRAM
&& arg_accept
) {
488 log_error("Datagram sockets do not accept connections. "
489 "The --datagram and --accept options may not be combined.");
493 arg_args
= argv
+ optind
;
495 return 1 /* work to do */;
498 int main(int argc
, char **argv
, char **envp
) {
502 log_parse_environment();
505 r
= parse_argv(argc
, argv
);
507 return r
== 0 ? EXIT_SUCCESS
: EXIT_FAILURE
;
509 r
= install_chld_handler();
513 n
= open_sockets(&epoll_fd
, arg_accept
);
517 log_error("No sockets to listen on specified or passed in.");
522 struct epoll_event event
;
524 r
= epoll_wait(epoll_fd
, &event
, 1, -1);
529 log_error_errno(errno
, "epoll_wait() failed: %m");
533 log_info("Communication attempt on fd %i.", event
.data
.fd
);
535 r
= do_accept(argv
[optind
], argv
+ optind
, envp
, event
.data
.fd
);
542 exec_process(argv
[optind
], argv
+ optind
, envp
, SD_LISTEN_FDS_START
, n
);