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