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