1 /* SPDX-License-Identifier: LGPL-2.1+ */
6 #include <sys/socket.h>
10 #include "sd-daemon.h"
12 #include "alloc-util.h"
17 #include "process-util.h"
18 #include "signal-util.h"
19 #include "socket-util.h"
20 #include "string-util.h"
22 #include "terminal-util.h"
24 static char** arg_listen
= NULL
;
25 static bool arg_accept
= false;
26 static int arg_socket_type
= SOCK_STREAM
;
27 static char** arg_args
= NULL
;
28 static char** arg_setenv
= NULL
;
29 static char **arg_fdnames
= NULL
;
30 static bool arg_inetd
= false;
32 static int add_epoll(int epoll_fd
, int fd
) {
33 struct epoll_event ev
= {
38 assert(epoll_fd
>= 0);
41 if (epoll_ctl(epoll_fd
, EPOLL_CTL_ADD
, fd
, &ev
) < 0)
42 return log_error_errno(errno
, "Failed to add event on epoll fd:%d for fd:%d: %m", epoll_fd
, fd
);
47 static int open_sockets(int *epoll_fd
, bool accept
) {
52 n
= sd_listen_fds(true);
54 return log_error_errno(n
, "Failed to read listening file descriptors from environment: %m");
56 log_info("Received %i descriptors via the environment.", n
);
58 for (fd
= SD_LISTEN_FDS_START
; fd
< SD_LISTEN_FDS_START
+ n
; fd
++) {
59 r
= fd_cloexec(fd
, arg_accept
);
67 /* Close logging and all other descriptors */
71 for (fd
= 0; fd
< SD_LISTEN_FDS_START
+ n
; fd
++)
75 close_all_fds(except
, 3 + n
);
78 /** Note: we leak some fd's on error here. I doesn't matter
79 * much, since the program will exit immediately anyway, but
80 * would be a pain to fix.
83 STRV_FOREACH(address
, arg_listen
) {
84 fd
= make_socket_fd(LOG_DEBUG
, *address
, arg_socket_type
, (arg_accept
*SOCK_CLOEXEC
));
87 return log_error_errno(fd
, "Failed to open '%s': %m", *address
);
90 assert(fd
== SD_LISTEN_FDS_START
+ count
);
97 *epoll_fd
= epoll_create1(EPOLL_CLOEXEC
);
99 return log_error_errno(errno
, "Failed to create epoll object: %m");
101 for (fd
= SD_LISTEN_FDS_START
; fd
< SD_LISTEN_FDS_START
+ count
; fd
++) {
102 _cleanup_free_
char *name
= NULL
;
104 getsockname_pretty(fd
, &name
);
105 log_info("Listening on %s as %i.", strna(name
), fd
);
107 r
= add_epoll(*epoll_fd
, fd
);
115 static int exec_process(const char* name
, char **argv
, char **env
, int start_fd
, size_t n_fds
) {
117 _cleanup_strv_free_
char **envp
= NULL
;
118 _cleanup_free_
char *joined
= NULL
;
119 size_t n_env
= 0, length
;
124 if (arg_inetd
&& n_fds
!= 1) {
125 log_error("--inetd only supported for single file descriptors.");
129 length
= strv_length(arg_setenv
);
131 /* PATH, TERM, HOME, USER, LISTEN_FDS, LISTEN_PID, LISTEN_FDNAMES, NULL */
132 envp
= new0(char *, length
+ 8);
136 STRV_FOREACH(s
, arg_setenv
) {
138 if (strchr(*s
, '=')) {
147 _cleanup_free_
char *p
;
150 p
= strappend(*s
, "=");
154 n
= strv_find_prefix(env
, p
);
158 envp
[n_env
] = strdup(n
);
166 FOREACH_STRING(tocopy
, "TERM=", "PATH=", "USER=", "HOME=") {
169 n
= strv_find_prefix(env
, tocopy
);
173 envp
[n_env
] = strdup(n
);
183 r
= rearrange_stdio(start_fd
, start_fd
, STDERR_FILENO
); /* invalidates start_fd on success + error */
185 return log_error_errno(r
, "Failed to move fd to stdin+stdout: %m");
188 if (start_fd
!= SD_LISTEN_FDS_START
) {
191 if (dup2(start_fd
, SD_LISTEN_FDS_START
) < 0)
192 return log_error_errno(errno
, "Failed to dup connection: %m");
194 safe_close(start_fd
);
195 start_fd
= SD_LISTEN_FDS_START
;
198 if (asprintf((char**)(envp
+ n_env
++), "LISTEN_FDS=%zu", n_fds
) < 0)
201 if (asprintf((char**)(envp
+ n_env
++), "LISTEN_PID=" PID_FMT
, getpid_cached()) < 0)
205 _cleanup_free_
char *names
= NULL
;
209 len
= strv_length(arg_fdnames
);
213 for (i
= 1; i
< n_fds
; i
++) {
214 r
= strv_extend(&arg_fdnames
, arg_fdnames
[0]);
216 return log_error_errno(r
, "Failed to extend strv: %m");
218 } else if (len
!= n_fds
)
219 log_warning("The number of fd names is different than number of fds: %zu vs %zu", len
, n_fds
);
221 names
= strv_join(arg_fdnames
, ":");
225 e
= strappend("LISTEN_FDNAMES=", names
);
233 joined
= strv_join(argv
, " ");
237 log_info("Execing %s (%s)", name
, joined
);
238 execvpe(name
, argv
, envp
);
240 return log_error_errno(errno
, "Failed to execp %s (%s): %m", name
, joined
);
243 static int fork_and_exec_process(const char* child
, char** argv
, char **env
, int fd
) {
244 _cleanup_free_
char *joined
= NULL
;
248 joined
= strv_join(argv
, " ");
252 r
= safe_fork("(activate)", FORK_RESET_SIGNALS
|FORK_DEATHSIG
|FORK_LOG
, &child_pid
);
257 exec_process(child
, argv
, env
, fd
, 1);
261 log_info("Spawned %s (%s) as PID " PID_FMT
".", child
, joined
, child_pid
);
265 static int do_accept(const char* name
, char **argv
, char **envp
, int fd
) {
266 _cleanup_free_
char *local
= NULL
, *peer
= NULL
;
267 _cleanup_close_
int fd_accepted
= -1;
269 fd_accepted
= accept4(fd
, NULL
, NULL
, 0);
271 return log_error_errno(errno
, "Failed to accept connection on fd:%d: %m", fd
);
273 getsockname_pretty(fd_accepted
, &local
);
274 getpeername_pretty(fd_accepted
, true, &peer
);
275 log_info("Connection from %s to %s", strna(peer
), strna(local
));
277 return fork_and_exec_process(name
, argv
, envp
, fd_accepted
);
280 /* SIGCHLD handler. */
281 static void sigchld_hdl(int sig
) {
289 r
= waitid(P_ALL
, 0, &si
, WEXITED
|WNOHANG
);
292 log_error_errno(errno
, "Failed to reap children: %m");
298 log_info("Child %d died with code %d", si
.si_pid
, si
.si_status
);
302 static int install_chld_handler(void) {
303 static const struct sigaction act
= {
304 .sa_flags
= SA_NOCLDSTOP
|SA_RESTART
,
305 .sa_handler
= sigchld_hdl
,
308 if (sigaction(SIGCHLD
, &act
, 0) < 0)
309 return log_error_errno(errno
, "Failed to install SIGCHLD handler: %m");
314 static int help(void) {
315 _cleanup_free_
char *link
= NULL
;
318 r
= terminal_urlify_man("systemd-socket-activate", "1", &link
);
322 printf("%s [OPTIONS...]\n\n"
323 "Listen on sockets and launch child on connection.\n\n"
325 " -h --help Show this help and exit\n"
326 " --version Print version string and exit\n"
327 " -l --listen=ADDR Listen for raw connections at ADDR\n"
328 " -d --datagram Listen on datagram instead of stream socket\n"
329 " --seqpacket Listen on SOCK_SEQPACKET instead of stream socket\n"
330 " -a --accept Spawn separate child for each connection\n"
331 " -E --setenv=NAME[=VALUE] Pass an environment variable to children\n"
332 " --fdname=NAME[:NAME...] Specify names for file descriptors\n"
333 " --inetd Enable inetd file descriptor passing protocol\n"
334 "\nNote: file descriptors from sd_listen_fds() will be passed through.\n"
335 "\nSee the %s for details.\n"
336 , program_invocation_short_name
343 static int parse_argv(int argc
, char *argv
[]) {
351 static const struct option options
[] = {
352 { "help", no_argument
, NULL
, 'h' },
353 { "version", no_argument
, NULL
, ARG_VERSION
},
354 { "datagram", no_argument
, NULL
, 'd' },
355 { "seqpacket", no_argument
, NULL
, ARG_SEQPACKET
},
356 { "listen", required_argument
, NULL
, 'l' },
357 { "accept", no_argument
, NULL
, 'a' },
358 { "setenv", required_argument
, NULL
, 'E' },
359 { "environment", required_argument
, NULL
, 'E' }, /* legacy alias */
360 { "fdname", required_argument
, NULL
, ARG_FDNAME
},
361 { "inetd", no_argument
, NULL
, ARG_INETD
},
370 while ((c
= getopt_long(argc
, argv
, "+hl:aE:d", options
, NULL
)) >= 0)
379 r
= strv_extend(&arg_listen
, optarg
);
386 if (arg_socket_type
== SOCK_SEQPACKET
) {
387 log_error("--datagram may not be combined with --seqpacket.");
391 arg_socket_type
= SOCK_DGRAM
;
395 if (arg_socket_type
== SOCK_DGRAM
) {
396 log_error("--seqpacket may not be combined with --datagram.");
400 arg_socket_type
= SOCK_SEQPACKET
;
408 r
= strv_extend(&arg_setenv
, optarg
);
415 _cleanup_strv_free_
char **names
;
418 names
= strv_split(optarg
, ":");
422 STRV_FOREACH(s
, names
)
423 if (!fdname_is_valid(*s
)) {
424 _cleanup_free_
char *esc
;
427 log_warning("File descriptor name \"%s\" is not valid.", esc
);
430 /* Empty optargs means one empty name */
431 r
= strv_extend_strv(&arg_fdnames
,
432 strv_isempty(names
) ? STRV_MAKE("") : names
,
435 return log_error_errno(r
, "strv_extend_strv: %m");
447 assert_not_reached("Unhandled option");
450 if (optind
== argc
) {
451 log_error("%s: command to execute is missing.",
452 program_invocation_short_name
);
456 if (arg_socket_type
== SOCK_DGRAM
&& arg_accept
) {
457 log_error("Datagram sockets do not accept connections. "
458 "The --datagram and --accept options may not be combined.");
462 arg_args
= argv
+ optind
;
464 return 1 /* work to do */;
467 int main(int argc
, char **argv
, char **envp
) {
471 log_parse_environment();
474 r
= parse_argv(argc
, argv
);
476 return r
== 0 ? EXIT_SUCCESS
: EXIT_FAILURE
;
478 r
= install_chld_handler();
482 n
= open_sockets(&epoll_fd
, arg_accept
);
486 log_error("No sockets to listen on specified or passed in.");
491 struct epoll_event event
;
493 if (epoll_wait(epoll_fd
, &event
, 1, -1) < 0) {
497 log_error_errno(errno
, "epoll_wait() failed: %m");
501 log_info("Communication attempt on fd %i.", event
.data
.fd
);
503 r
= do_accept(argv
[optind
], argv
+ optind
, envp
, event
.data
.fd
);
510 exec_process(argv
[optind
], argv
+ optind
, envp
, SD_LISTEN_FDS_START
, (size_t) n
);