]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/activate/activate.c
Merge pull request #2702 from poettering/resolved-iterate-fix
[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, siginfo_t *t, void *data) {
320 PROTECT_ERRNO;
321
322 log_info("Child %d died with code %d", t->si_pid, t->si_status);
323
324 /* Wait for a dead child. */
325 (void) waitpid(t->si_pid, NULL, 0);
326 }
327
328 static int install_chld_handler(void) {
329 static const struct sigaction act = {
330 .sa_flags = SA_SIGINFO,
331 .sa_sigaction = sigchld_hdl,
332 };
333
334 int r;
335
336 r = sigaction(SIGCHLD, &act, 0);
337 if (r < 0)
338 return log_error_errno(errno, "Failed to install SIGCHLD handler: %m");
339
340 return 0;
341 }
342
343 static void help(void) {
344 printf("%s [OPTIONS...]\n\n"
345 "Listen on sockets and launch child on connection.\n\n"
346 "Options:\n"
347 " -h --help Show this help and exit\n"
348 " --version Print version string and exit\n"
349 " -l --listen=ADDR Listen for raw connections at ADDR\n"
350 " -d --datagram Listen on datagram instead of stream socket\n"
351 " --seqpacket Listen on SOCK_SEQPACKET instead of stream socket\n"
352 " -a --accept Spawn separate child for each connection\n"
353 " -E --setenv=NAME[=VALUE] Pass an environment variable to children\n"
354 " --fdname=NAME[:NAME...] Specify names for file descriptors\n"
355 " --inetd Enable inetd file descriptor passing protocol\n"
356 "\n"
357 "Note: file descriptors from sd_listen_fds() will be passed through.\n"
358 , program_invocation_short_name);
359 }
360
361 static int parse_argv(int argc, char *argv[]) {
362 enum {
363 ARG_VERSION = 0x100,
364 ARG_FDNAME,
365 ARG_SEQPACKET,
366 ARG_INETD,
367 };
368
369 static const struct option options[] = {
370 { "help", no_argument, NULL, 'h' },
371 { "version", no_argument, NULL, ARG_VERSION },
372 { "datagram", no_argument, NULL, 'd' },
373 { "seqpacket", no_argument, NULL, ARG_SEQPACKET },
374 { "listen", required_argument, NULL, 'l' },
375 { "accept", no_argument, NULL, 'a' },
376 { "setenv", required_argument, NULL, 'E' },
377 { "environment", required_argument, NULL, 'E' }, /* legacy alias */
378 { "fdname", required_argument, NULL, ARG_FDNAME },
379 { "inetd", no_argument, NULL, ARG_INETD },
380 {}
381 };
382
383 int c, r;
384
385 assert(argc >= 0);
386 assert(argv);
387
388 while ((c = getopt_long(argc, argv, "+hl:aE:d", options, NULL)) >= 0)
389 switch(c) {
390 case 'h':
391 help();
392 return 0;
393
394 case ARG_VERSION:
395 return version();
396
397 case 'l':
398 r = strv_extend(&arg_listen, optarg);
399 if (r < 0)
400 return log_oom();
401
402 break;
403
404 case 'd':
405 if (arg_socket_type == SOCK_SEQPACKET) {
406 log_error("--datagram may not be combined with --seqpacket.");
407 return -EINVAL;
408 }
409
410 arg_socket_type = SOCK_DGRAM;
411 break;
412
413 case ARG_SEQPACKET:
414 if (arg_socket_type == SOCK_DGRAM) {
415 log_error("--seqpacket may not be combined with --datagram.");
416 return -EINVAL;
417 }
418
419 arg_socket_type = SOCK_SEQPACKET;
420 break;
421
422 case 'a':
423 arg_accept = true;
424 break;
425
426 case 'E':
427 r = strv_extend(&arg_setenv, optarg);
428 if (r < 0)
429 return log_oom();
430
431 break;
432
433 case ARG_FDNAME: {
434 _cleanup_strv_free_ char **names;
435 char **s;
436
437 names = strv_split(optarg, ":");
438 if (!names)
439 return log_oom();
440
441 STRV_FOREACH(s, names)
442 if (!fdname_is_valid(*s)) {
443 _cleanup_free_ char *esc;
444
445 esc = cescape(*s);
446 log_warning("File descriptor name \"%s\" is not valid.", esc);
447 }
448
449 /* Empty optargs means one empty name */
450 r = strv_extend_strv(&arg_fdnames,
451 strv_isempty(names) ? STRV_MAKE("") : names,
452 false);
453 if (r < 0)
454 return log_error_errno(r, "strv_extend_strv: %m");
455 break;
456 }
457
458 case ARG_INETD:
459 arg_inetd = true;
460 break;
461
462 case '?':
463 return -EINVAL;
464
465 default:
466 assert_not_reached("Unhandled option");
467 }
468
469 if (optind == argc) {
470 log_error("%s: command to execute is missing.",
471 program_invocation_short_name);
472 return -EINVAL;
473 }
474
475 if (arg_socket_type == SOCK_DGRAM && arg_accept) {
476 log_error("Datagram sockets do not accept connections. "
477 "The --datagram and --accept options may not be combined.");
478 return -EINVAL;
479 }
480
481 arg_args = argv + optind;
482
483 return 1 /* work to do */;
484 }
485
486 int main(int argc, char **argv, char **envp) {
487 int r, n;
488 int epoll_fd = -1;
489
490 log_parse_environment();
491 log_open();
492
493 r = parse_argv(argc, argv);
494 if (r <= 0)
495 return r == 0 ? EXIT_SUCCESS : EXIT_FAILURE;
496
497 r = install_chld_handler();
498 if (r < 0)
499 return EXIT_FAILURE;
500
501 n = open_sockets(&epoll_fd, arg_accept);
502 if (n < 0)
503 return EXIT_FAILURE;
504 if (n == 0) {
505 log_error("No sockets to listen on specified or passed in.");
506 return EXIT_FAILURE;
507 }
508
509 for (;;) {
510 struct epoll_event event;
511
512 r = epoll_wait(epoll_fd, &event, 1, -1);
513 if (r < 0) {
514 if (errno == EINTR)
515 continue;
516
517 log_error_errno(errno, "epoll_wait() failed: %m");
518 return EXIT_FAILURE;
519 }
520
521 log_info("Communication attempt on fd %i.", event.data.fd);
522 if (arg_accept) {
523 r = do_accept(argv[optind], argv + optind, envp, event.data.fd);
524 if (r < 0)
525 return EXIT_FAILURE;
526 } else
527 break;
528 }
529
530 exec_process(argv[optind], argv + optind, envp, SD_LISTEN_FDS_START, n);
531
532 return EXIT_SUCCESS;
533 }