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"
33 #include "signal-util.h"
34 #include "socket-util.h"
35 #include "string-util.h"
38 static char** arg_listen
= NULL
;
39 static bool arg_accept
= false;
40 static int arg_socket_type
= SOCK_STREAM
;
41 static char** arg_args
= NULL
;
42 static char** arg_setenv
= NULL
;
43 static const char *arg_fdname
= NULL
;
44 static bool arg_inetd
= false;
46 static int add_epoll(int epoll_fd
, int fd
) {
47 struct epoll_event ev
= {
52 assert(epoll_fd
>= 0);
56 r
= epoll_ctl(epoll_fd
, EPOLL_CTL_ADD
, fd
, &ev
);
58 return log_error_errno(errno
, "Failed to add event on epoll fd:%d for fd:%d: %m", epoll_fd
, fd
);
63 static int open_sockets(int *epoll_fd
, bool accept
) {
68 n
= sd_listen_fds(true);
70 return log_error_errno(n
, "Failed to read listening file descriptors from environment: %m");
72 log_info("Received %i descriptors via the environment.", n
);
74 for (fd
= SD_LISTEN_FDS_START
; fd
< SD_LISTEN_FDS_START
+ n
; fd
++) {
75 r
= fd_cloexec(fd
, arg_accept
);
83 /* Close logging and all other descriptors */
87 for (fd
= 0; fd
< SD_LISTEN_FDS_START
+ n
; fd
++)
91 close_all_fds(except
, 3 + n
);
94 /** Note: we leak some fd's on error here. I doesn't matter
95 * much, since the program will exit immediately anyway, but
96 * would be a pain to fix.
99 STRV_FOREACH(address
, arg_listen
) {
100 fd
= make_socket_fd(LOG_DEBUG
, *address
, arg_socket_type
, (arg_accept
*SOCK_CLOEXEC
));
103 return log_error_errno(fd
, "Failed to open '%s': %m", *address
);
106 assert(fd
== SD_LISTEN_FDS_START
+ count
);
113 *epoll_fd
= epoll_create1(EPOLL_CLOEXEC
);
115 return log_error_errno(errno
, "Failed to create epoll object: %m");
117 for (fd
= SD_LISTEN_FDS_START
; fd
< SD_LISTEN_FDS_START
+ count
; fd
++) {
118 _cleanup_free_
char *name
= NULL
;
120 getsockname_pretty(fd
, &name
);
121 log_info("Listening on %s as %i.", strna(name
), fd
);
123 r
= add_epoll(*epoll_fd
, fd
);
131 static int exec_process(const char* name
, char **argv
, char **env
, int start_fd
, int n_fds
) {
133 _cleanup_strv_free_
char **envp
= NULL
;
134 _cleanup_free_
char *joined
= NULL
;
135 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)
230 e
= strappend("LISTEN_FDNAMES=", arg_fdname
);
234 for (i
= 1; i
< (unsigned) n_fds
; i
++) {
237 c
= strjoin(e
, ":", arg_fdname
, NULL
);
251 joined
= strv_join(argv
, " ");
255 log_info("Execing %s (%s)", name
, joined
);
256 execvpe(name
, argv
, envp
);
258 return log_error_errno(errno
, "Failed to execp %s (%s): %m", name
, joined
);
261 static int fork_and_exec_process(const char* child
, char** argv
, char **env
, int fd
) {
262 _cleanup_free_
char *joined
= NULL
;
263 pid_t parent_pid
, child_pid
;
265 joined
= strv_join(argv
, " ");
269 parent_pid
= getpid();
273 return log_error_errno(errno
, "Failed to fork: %m");
276 if (child_pid
== 0) {
278 (void) reset_all_signal_handlers();
279 (void) reset_signal_mask();
281 /* Make sure the child goes away when the parent dies */
282 if (prctl(PR_SET_PDEATHSIG
, SIGTERM
) < 0)
285 /* Check whether our parent died before we were able
286 * to set the death signal */
287 if (getppid() != parent_pid
)
290 exec_process(child
, argv
, env
, fd
, 1);
294 log_info("Spawned %s (%s) as PID %d", child
, joined
, child_pid
);
298 static int do_accept(const char* name
, char **argv
, char **envp
, int fd
) {
299 _cleanup_free_
char *local
= NULL
, *peer
= NULL
;
300 _cleanup_close_
int fd_accepted
= -1;
302 fd_accepted
= accept4(fd
, NULL
, NULL
, 0);
304 return log_error_errno(errno
, "Failed to accept connection on fd:%d: %m", fd
);
306 getsockname_pretty(fd_accepted
, &local
);
307 getpeername_pretty(fd_accepted
, true, &peer
);
308 log_info("Connection from %s to %s", strna(peer
), strna(local
));
310 return fork_and_exec_process(name
, argv
, envp
, fd_accepted
);
313 /* SIGCHLD handler. */
314 static void sigchld_hdl(int sig
, siginfo_t
*t
, void *data
) {
317 log_info("Child %d died with code %d", t
->si_pid
, t
->si_status
);
319 /* Wait for a dead child. */
320 (void) waitpid(t
->si_pid
, NULL
, 0);
323 static int install_chld_handler(void) {
324 static const struct sigaction act
= {
325 .sa_flags
= SA_SIGINFO
,
326 .sa_sigaction
= sigchld_hdl
,
331 r
= sigaction(SIGCHLD
, &act
, 0);
333 return log_error_errno(errno
, "Failed to install SIGCHLD handler: %m");
338 static void help(void) {
339 printf("%s [OPTIONS...]\n\n"
340 "Listen on sockets and launch child on connection.\n\n"
342 " -h --help Show this help and exit\n"
343 " --version Print version string and exit\n"
344 " -l --listen=ADDR Listen for raw connections at ADDR\n"
345 " -d --datagram Listen on datagram instead of stream socket\n"
346 " --seqpacket Listen on SOCK_SEQPACKET instead of stream socket\n"
347 " -a --accept Spawn separate child for each connection\n"
348 " -E --setenv=NAME[=VALUE] Pass an environment variable to children\n"
349 " --inetd Enable inetd file descriptor passing protocol\n"
351 "Note: file descriptors from sd_listen_fds() will be passed through.\n"
352 , program_invocation_short_name
);
355 static int parse_argv(int argc
, char *argv
[]) {
363 static const struct option options
[] = {
364 { "help", no_argument
, NULL
, 'h' },
365 { "version", no_argument
, NULL
, ARG_VERSION
},
366 { "datagram", no_argument
, NULL
, 'd' },
367 { "seqpacket", no_argument
, NULL
, ARG_SEQPACKET
},
368 { "listen", required_argument
, NULL
, 'l' },
369 { "accept", no_argument
, NULL
, 'a' },
370 { "setenv", required_argument
, NULL
, 'E' },
371 { "environment", required_argument
, NULL
, 'E' }, /* legacy alias */
372 { "fdname", required_argument
, NULL
, ARG_FDNAME
},
373 { "inetd", no_argument
, NULL
, ARG_INETD
},
382 while ((c
= getopt_long(argc
, argv
, "+hl:aEd", options
, NULL
)) >= 0)
392 r
= strv_extend(&arg_listen
, optarg
);
399 if (arg_socket_type
== SOCK_SEQPACKET
) {
400 log_error("--datagram may not be combined with --seqpacket.");
404 arg_socket_type
= SOCK_DGRAM
;
408 if (arg_socket_type
== SOCK_DGRAM
) {
409 log_error("--seqpacket may not be combined with --datagram.");
413 arg_socket_type
= SOCK_SEQPACKET
;
421 r
= strv_extend(&arg_setenv
, optarg
);
428 if (!fdname_is_valid(optarg
)) {
429 log_error("File descriptor name %s is not valid, refusing.", optarg
);
444 assert_not_reached("Unhandled option");
447 if (optind
== argc
) {
448 log_error("%s: command to execute is missing.",
449 program_invocation_short_name
);
453 if (arg_socket_type
== SOCK_DGRAM
&& arg_accept
) {
454 log_error("Datagram sockets do not accept connections. "
455 "The --datagram and --accept options may not be combined.");
459 arg_args
= argv
+ optind
;
461 return 1 /* work to do */;
464 int main(int argc
, char **argv
, char **envp
) {
468 log_parse_environment();
471 r
= parse_argv(argc
, argv
);
473 return r
== 0 ? EXIT_SUCCESS
: EXIT_FAILURE
;
475 r
= install_chld_handler();
479 n
= open_sockets(&epoll_fd
, arg_accept
);
483 log_error("No sockets to listen on specified or passed in.");
488 struct epoll_event event
;
490 r
= epoll_wait(epoll_fd
, &event
, 1, -1);
495 log_error_errno(errno
, "epoll_wait() failed: %m");
499 log_info("Communication attempt on fd %i.", event
.data
.fd
);
501 r
= do_accept(argv
[optind
], argv
+ optind
, envp
, event
.data
.fd
);
508 exec_process(argv
[optind
], argv
+ optind
, envp
, SD_LISTEN_FDS_START
, n
);