]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/activate/activate.c
tree-wide: add clickable man page link to all --help texts
[thirdparty/systemd.git] / src / activate / activate.c
1 /* SPDX-License-Identifier: LGPL-2.1+ */
2
3 #include <getopt.h>
4 #include <sys/epoll.h>
5 #include <sys/prctl.h>
6 #include <sys/socket.h>
7 #include <sys/wait.h>
8 #include <unistd.h>
9
10 #include "sd-daemon.h"
11
12 #include "alloc-util.h"
13 #include "escape.h"
14 #include "fd-util.h"
15 #include "log.h"
16 #include "macro.h"
17 #include "process-util.h"
18 #include "signal-util.h"
19 #include "socket-util.h"
20 #include "string-util.h"
21 #include "strv.h"
22 #include "terminal-util.h"
23
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;
31
32 static int add_epoll(int epoll_fd, int fd) {
33 struct epoll_event ev = {
34 .events = EPOLLIN,
35 .data.fd = fd,
36 };
37
38 assert(epoll_fd >= 0);
39 assert(fd >= 0);
40
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);
43
44 return 0;
45 }
46
47 static int open_sockets(int *epoll_fd, bool accept) {
48 char **address;
49 int n, fd, r;
50 int count = 0;
51
52 n = sd_listen_fds(true);
53 if (n < 0)
54 return log_error_errno(n, "Failed to read listening file descriptors from environment: %m");
55 if (n > 0) {
56 log_info("Received %i descriptors via the environment.", n);
57
58 for (fd = SD_LISTEN_FDS_START; fd < SD_LISTEN_FDS_START + n; fd++) {
59 r = fd_cloexec(fd, arg_accept);
60 if (r < 0)
61 return r;
62
63 count++;
64 }
65 }
66
67 /* Close logging and all other descriptors */
68 if (arg_listen) {
69 int except[3 + n];
70
71 for (fd = 0; fd < SD_LISTEN_FDS_START + n; fd++)
72 except[fd] = fd;
73
74 log_close();
75 close_all_fds(except, 3 + n);
76 }
77
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.
81 */
82
83 STRV_FOREACH(address, arg_listen) {
84 fd = make_socket_fd(LOG_DEBUG, *address, arg_socket_type, (arg_accept*SOCK_CLOEXEC));
85 if (fd < 0) {
86 log_open();
87 return log_error_errno(fd, "Failed to open '%s': %m", *address);
88 }
89
90 assert(fd == SD_LISTEN_FDS_START + count);
91 count++;
92 }
93
94 if (arg_listen)
95 log_open();
96
97 *epoll_fd = epoll_create1(EPOLL_CLOEXEC);
98 if (*epoll_fd < 0)
99 return log_error_errno(errno, "Failed to create epoll object: %m");
100
101 for (fd = SD_LISTEN_FDS_START; fd < SD_LISTEN_FDS_START + count; fd++) {
102 _cleanup_free_ char *name = NULL;
103
104 getsockname_pretty(fd, &name);
105 log_info("Listening on %s as %i.", strna(name), fd);
106
107 r = add_epoll(*epoll_fd, fd);
108 if (r < 0)
109 return r;
110 }
111
112 return count;
113 }
114
115 static int exec_process(const char* name, char **argv, char **env, int start_fd, size_t n_fds) {
116
117 _cleanup_strv_free_ char **envp = NULL;
118 _cleanup_free_ char *joined = NULL;
119 size_t n_env = 0, length;
120 const char *tocopy;
121 char **s;
122 int r;
123
124 if (arg_inetd && n_fds != 1) {
125 log_error("--inetd only supported for single file descriptors.");
126 return -EINVAL;
127 }
128
129 length = strv_length(arg_setenv);
130
131 /* PATH, TERM, HOME, USER, LISTEN_FDS, LISTEN_PID, LISTEN_FDNAMES, NULL */
132 envp = new0(char *, length + 8);
133 if (!envp)
134 return log_oom();
135
136 STRV_FOREACH(s, arg_setenv) {
137
138 if (strchr(*s, '=')) {
139 char *k;
140
141 k = strdup(*s);
142 if (!k)
143 return log_oom();
144
145 envp[n_env++] = k;
146 } else {
147 _cleanup_free_ char *p;
148 const char *n;
149
150 p = strappend(*s, "=");
151 if (!p)
152 return log_oom();
153
154 n = strv_find_prefix(env, p);
155 if (!n)
156 continue;
157
158 envp[n_env] = strdup(n);
159 if (!envp[n_env])
160 return log_oom();
161
162 n_env++;
163 }
164 }
165
166 FOREACH_STRING(tocopy, "TERM=", "PATH=", "USER=", "HOME=") {
167 const char *n;
168
169 n = strv_find_prefix(env, tocopy);
170 if (!n)
171 continue;
172
173 envp[n_env] = strdup(n);
174 if (!envp[n_env])
175 return log_oom();
176
177 n_env++;
178 }
179
180 if (arg_inetd) {
181 assert(n_fds == 1);
182
183 r = rearrange_stdio(start_fd, start_fd, STDERR_FILENO); /* invalidates start_fd on success + error */
184 if (r < 0)
185 return log_error_errno(r, "Failed to move fd to stdin+stdout: %m");
186
187 } else {
188 if (start_fd != SD_LISTEN_FDS_START) {
189 assert(n_fds == 1);
190
191 if (dup2(start_fd, SD_LISTEN_FDS_START) < 0)
192 return log_error_errno(errno, "Failed to dup connection: %m");
193
194 safe_close(start_fd);
195 start_fd = SD_LISTEN_FDS_START;
196 }
197
198 if (asprintf((char**)(envp + n_env++), "LISTEN_FDS=%zu", n_fds) < 0)
199 return log_oom();
200
201 if (asprintf((char**)(envp + n_env++), "LISTEN_PID=" PID_FMT, getpid_cached()) < 0)
202 return log_oom();
203
204 if (arg_fdnames) {
205 _cleanup_free_ char *names = NULL;
206 size_t len;
207 char *e;
208
209 len = strv_length(arg_fdnames);
210 if (len == 1) {
211 size_t i;
212
213 for (i = 1; i < n_fds; i++) {
214 r = strv_extend(&arg_fdnames, arg_fdnames[0]);
215 if (r < 0)
216 return log_error_errno(r, "Failed to extend strv: %m");
217 }
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);
220
221 names = strv_join(arg_fdnames, ":");
222 if (!names)
223 return log_oom();
224
225 e = strappend("LISTEN_FDNAMES=", names);
226 if (!e)
227 return log_oom();
228
229 envp[n_env++] = e;
230 }
231 }
232
233 joined = strv_join(argv, " ");
234 if (!joined)
235 return log_oom();
236
237 log_info("Execing %s (%s)", name, joined);
238 execvpe(name, argv, envp);
239
240 return log_error_errno(errno, "Failed to execp %s (%s): %m", name, joined);
241 }
242
243 static int fork_and_exec_process(const char* child, char** argv, char **env, int fd) {
244 _cleanup_free_ char *joined = NULL;
245 pid_t child_pid;
246 int r;
247
248 joined = strv_join(argv, " ");
249 if (!joined)
250 return log_oom();
251
252 r = safe_fork("(activate)", FORK_RESET_SIGNALS|FORK_DEATHSIG|FORK_LOG, &child_pid);
253 if (r < 0)
254 return r;
255 if (r == 0) {
256 /* In the child */
257 exec_process(child, argv, env, fd, 1);
258 _exit(EXIT_FAILURE);
259 }
260
261 log_info("Spawned %s (%s) as PID " PID_FMT ".", child, joined, child_pid);
262 return 0;
263 }
264
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;
268
269 fd_accepted = accept4(fd, NULL, NULL, 0);
270 if (fd_accepted < 0)
271 return log_error_errno(errno, "Failed to accept connection on fd:%d: %m", fd);
272
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));
276
277 return fork_and_exec_process(name, argv, envp, fd_accepted);
278 }
279
280 /* SIGCHLD handler. */
281 static void sigchld_hdl(int sig) {
282 PROTECT_ERRNO;
283
284 for (;;) {
285 siginfo_t si;
286 int r;
287
288 si.si_pid = 0;
289 r = waitid(P_ALL, 0, &si, WEXITED|WNOHANG);
290 if (r < 0) {
291 if (errno != ECHILD)
292 log_error_errno(errno, "Failed to reap children: %m");
293 return;
294 }
295 if (si.si_pid == 0)
296 return;
297
298 log_info("Child %d died with code %d", si.si_pid, si.si_status);
299 }
300 }
301
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,
306 };
307
308 if (sigaction(SIGCHLD, &act, 0) < 0)
309 return log_error_errno(errno, "Failed to install SIGCHLD handler: %m");
310
311 return 0;
312 }
313
314 static int help(void) {
315 _cleanup_free_ char *link = NULL;
316 int r;
317
318 r = terminal_urlify_man("systemd-socket-activate", "1", &link);
319 if (r < 0)
320 return log_oom();
321
322 printf("%s [OPTIONS...]\n\n"
323 "Listen on sockets and launch child on connection.\n\n"
324 "Options:\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
337 , link
338 );
339
340 return 0;
341 }
342
343 static int parse_argv(int argc, char *argv[]) {
344 enum {
345 ARG_VERSION = 0x100,
346 ARG_FDNAME,
347 ARG_SEQPACKET,
348 ARG_INETD,
349 };
350
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 },
362 {}
363 };
364
365 int c, r;
366
367 assert(argc >= 0);
368 assert(argv);
369
370 while ((c = getopt_long(argc, argv, "+hl:aE:d", options, NULL)) >= 0)
371 switch(c) {
372 case 'h':
373 return help();
374
375 case ARG_VERSION:
376 return version();
377
378 case 'l':
379 r = strv_extend(&arg_listen, optarg);
380 if (r < 0)
381 return log_oom();
382
383 break;
384
385 case 'd':
386 if (arg_socket_type == SOCK_SEQPACKET) {
387 log_error("--datagram may not be combined with --seqpacket.");
388 return -EINVAL;
389 }
390
391 arg_socket_type = SOCK_DGRAM;
392 break;
393
394 case ARG_SEQPACKET:
395 if (arg_socket_type == SOCK_DGRAM) {
396 log_error("--seqpacket may not be combined with --datagram.");
397 return -EINVAL;
398 }
399
400 arg_socket_type = SOCK_SEQPACKET;
401 break;
402
403 case 'a':
404 arg_accept = true;
405 break;
406
407 case 'E':
408 r = strv_extend(&arg_setenv, optarg);
409 if (r < 0)
410 return log_oom();
411
412 break;
413
414 case ARG_FDNAME: {
415 _cleanup_strv_free_ char **names;
416 char **s;
417
418 names = strv_split(optarg, ":");
419 if (!names)
420 return log_oom();
421
422 STRV_FOREACH(s, names)
423 if (!fdname_is_valid(*s)) {
424 _cleanup_free_ char *esc;
425
426 esc = cescape(*s);
427 log_warning("File descriptor name \"%s\" is not valid.", esc);
428 }
429
430 /* Empty optargs means one empty name */
431 r = strv_extend_strv(&arg_fdnames,
432 strv_isempty(names) ? STRV_MAKE("") : names,
433 false);
434 if (r < 0)
435 return log_error_errno(r, "strv_extend_strv: %m");
436 break;
437 }
438
439 case ARG_INETD:
440 arg_inetd = true;
441 break;
442
443 case '?':
444 return -EINVAL;
445
446 default:
447 assert_not_reached("Unhandled option");
448 }
449
450 if (optind == argc) {
451 log_error("%s: command to execute is missing.",
452 program_invocation_short_name);
453 return -EINVAL;
454 }
455
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.");
459 return -EINVAL;
460 }
461
462 arg_args = argv + optind;
463
464 return 1 /* work to do */;
465 }
466
467 int main(int argc, char **argv, char **envp) {
468 int r, n;
469 int epoll_fd = -1;
470
471 log_parse_environment();
472 log_open();
473
474 r = parse_argv(argc, argv);
475 if (r <= 0)
476 return r == 0 ? EXIT_SUCCESS : EXIT_FAILURE;
477
478 r = install_chld_handler();
479 if (r < 0)
480 return EXIT_FAILURE;
481
482 n = open_sockets(&epoll_fd, arg_accept);
483 if (n < 0)
484 return EXIT_FAILURE;
485 if (n == 0) {
486 log_error("No sockets to listen on specified or passed in.");
487 return EXIT_FAILURE;
488 }
489
490 for (;;) {
491 struct epoll_event event;
492
493 if (epoll_wait(epoll_fd, &event, 1, -1) < 0) {
494 if (errno == EINTR)
495 continue;
496
497 log_error_errno(errno, "epoll_wait() failed: %m");
498 return EXIT_FAILURE;
499 }
500
501 log_info("Communication attempt on fd %i.", event.data.fd);
502 if (arg_accept) {
503 r = do_accept(argv[optind], argv + optind, envp, event.data.fd);
504 if (r < 0)
505 return EXIT_FAILURE;
506 } else
507 break;
508 }
509
510 exec_process(argv[optind], argv + optind, envp, SD_LISTEN_FDS_START, (size_t) n);
511
512 return EXIT_SUCCESS;
513 }