chiark / gitweb /
65a7fbba1eb45050bad90c03b0cd7e9b4565cc1e
[elogind.git] / execute.c
1 /*-*- Mode: C; c-basic-offset: 8 -*-*/
2
3 #include <assert.h>
4 #include <dirent.h>
5 #include <errno.h>
6 #include <fcntl.h>
7 #include <unistd.h>
8 #include <string.h>
9 #include <signal.h>
10 #include <sys/socket.h>
11 #include <sys/un.h>
12 #include <sys/prctl.h>
13 #include <sched.h>
14
15 #include "execute.h"
16 #include "strv.h"
17 #include "macro.h"
18 #include "util.h"
19 #include "log.h"
20 #include "ioprio.h"
21 #include "securebits.h"
22
23 static int close_fds(int except[], unsigned n_except) {
24         DIR *d;
25         struct dirent *de;
26         int r = 0;
27
28         /* Modifies the fds array! (sorts it) */
29
30         if (!(d = opendir("/proc/self/fd")))
31                 return -errno;
32
33         while ((de = readdir(d))) {
34                 int fd;
35
36                 if (de->d_name[0] == '.')
37                         continue;
38
39                 if ((r = safe_atoi(de->d_name, &fd)) < 0)
40                         goto finish;
41
42                 if (fd < 3)
43                         continue;
44
45                 if (fd == dirfd(d))
46                         continue;
47
48                 if (except) {
49                         bool found;
50                         unsigned i;
51
52                         found = false;
53                         for (i = 0; i < n_except; i++)
54                                 if (except[i] == fd) {
55                                         found = true;
56                                         break;
57                                 }
58
59                         if (found)
60                                 continue;
61                 }
62
63                 if ((r = close_nointr(fd)) < 0)
64                         goto finish;
65         }
66
67 finish:
68         closedir(d);
69         return r;
70 }
71
72 static int shift_fds(int fds[], unsigned n_fds) {
73         int start, restart_from;
74
75         if (n_fds <= 0)
76                 return 0;
77
78         assert(fds);
79
80         start = 0;
81         for (;;) {
82                 int i;
83
84                 restart_from = -1;
85
86                 for (i = start; i < (int) n_fds; i++) {
87                         int nfd;
88
89                         /* Already at right index? */
90                         if (fds[i] == i+3)
91                                 continue;
92
93                         if ((nfd = fcntl(fds[i], F_DUPFD, i+3)) < 0)
94                                 return -errno;
95
96                         assert_se(close_nointr(fds[i]) == 0);
97                         fds[i] = nfd;
98
99                         /* Hmm, the fd we wanted isn't free? Then
100                          * let's remember that and try again from here*/
101                         if (nfd != i+3 && restart_from < 0)
102                                 restart_from = i;
103                 }
104
105                 if (restart_from < 0)
106                         break;
107
108                 start = restart_from;
109         }
110
111         return 0;
112 }
113
114 static int flags_fds(int fds[], unsigned n_fds) {
115         unsigned i;
116
117         if (n_fds <= 0)
118                 return 0;
119
120         assert(fds);
121
122         /* Drops O_NONBLOCK and FD_CLOEXEC from the file flags */
123
124         for (i = 0; i < n_fds; i++) {
125                 int flags;
126
127                 if ((flags = fcntl(fds[i], F_GETFL, 0)) < 0)
128                         return -errno;
129
130                 /* Since we are at it, let's make sure that nobody
131                  * forgot setting O_NONBLOCK for all our fds */
132
133                 if (fcntl(fds[i], F_SETFL, flags &~O_NONBLOCK) < 0)
134                         return -errno;
135
136                 if ((flags = fcntl(fds[i], F_GETFD, 0)) < 0)
137                         return -errno;
138
139                 /* Also make sure nobody forgot O_CLOEXEC for all our
140                  * fds */
141                 if (fcntl(fds[i], F_SETFD, flags &~FD_CLOEXEC) < 0)
142                         return -errno;
143         }
144
145         return 0;
146 }
147
148 static int replace_null_fd(int fd, int flags) {
149         int nfd;
150         assert(fd >= 0);
151
152         close_nointr(fd);
153
154         if ((nfd = open("/dev/null", flags|O_NOCTTY)) < 0)
155                 return -errno;
156
157         if (nfd != fd) {
158                 close_nointr_nofail(nfd);
159                 return -EIO;
160         }
161
162         return 0;
163 }
164
165 static int setup_output(const ExecContext *context, const char *ident) {
166         int r;
167
168         assert(context);
169
170         switch (context->output) {
171
172         case EXEC_OUTPUT_CONSOLE:
173                 return 0;
174
175         case EXEC_OUTPUT_NULL:
176
177                 if ((r = replace_null_fd(STDOUT_FILENO, O_WRONLY)) < 0 ||
178                     (r = replace_null_fd(STDERR_FILENO, O_WRONLY)) < 0)
179                         return r;
180
181                 return 0;
182
183         case EXEC_OUTPUT_KERNEL:
184         case EXEC_OUTPUT_SYSLOG: {
185
186                 int fd;
187                 union {
188                         struct sockaddr sa;
189                         struct sockaddr_un un;
190                 } sa;
191
192                 close_nointr(STDOUT_FILENO);
193                 close_nointr(STDERR_FILENO);
194
195                 if ((fd = socket(AF_UNIX, SOCK_STREAM, 0)) < 0)
196                         return -errno;
197
198                 if (fd != STDOUT_FILENO) {
199                         close_nointr_nofail(fd);
200                         return -EIO;
201                 }
202
203                 zero(sa);
204                 sa.sa.sa_family = AF_UNIX;
205                 strncpy(sa.un.sun_path+1, LOGGER_SOCKET, sizeof(sa.un.sun_path)-1);
206
207                 if (connect(fd, &sa.sa, sizeof(sa)) < 0) {
208                         close_nointr_nofail(fd);
209                         return -errno;
210                 }
211
212                 if (shutdown(fd, SHUT_RD) < 0) {
213                         close_nointr_nofail(fd);
214                         return -errno;
215                 }
216
217                 if ((fd = dup(fd)) < 0) {
218                         close_nointr_nofail(fd);
219                         return -errno;
220                 }
221
222                 if (fd != STDERR_FILENO) {
223                         close_nointr_nofail(fd);
224                         return -EIO;
225                 }
226
227                 /* We speak a very simple protocol between log server
228                  * and client: one line for the log destination (kmsg
229                  * or syslog), followed by the priority field,
230                  * followed by the process name. Since we replaced
231                  * stdin/stderr we simple use stdio to write to
232                  * it. Note that we use stderr, to minimize buffer
233                  * flushing issues. */
234
235                 fprintf(stderr,
236                         "%s\n"
237                         "%i\n"
238                         "%s\n",
239                         context->output == EXEC_OUTPUT_KERNEL ? "kmsg" : "syslog",
240                         context->syslog_priority,
241                         context->syslog_identifier ? context->syslog_identifier : ident);
242
243                 return 0;
244         }
245
246         default:
247                 assert_not_reached("Unknown output type");
248         }
249 }
250
251 int setup_input(const ExecContext *context) {
252         int r;
253
254         assert(context);
255
256         switch (context->input) {
257
258         case EXEC_INPUT_CONSOLE:
259                 return 0;
260
261         case EXEC_INPUT_NULL:
262                 if ((r = replace_null_fd(STDIN_FILENO, O_RDONLY)) < 0)
263                         return r;
264
265                 return 0;
266
267         default:
268                 assert_not_reached("Unknown input type");
269         }
270 }
271
272 int exec_spawn(const ExecCommand *command, const ExecContext *context, int *fds, unsigned n_fds, pid_t *ret) {
273         pid_t pid;
274
275         assert(command);
276         assert(context);
277         assert(ret);
278         assert(fds || n_fds <= 0);
279
280         log_debug("about to execute %s", command->path);
281
282         if ((pid = fork()) < 0)
283                 return -errno;
284
285         if (pid == 0) {
286                 char **e, **f = NULL;
287                 int i, r;
288                 sigset_t ss;
289
290                 /* child */
291
292                 if (sigemptyset(&ss) < 0 ||
293                     sigprocmask(SIG_SETMASK, &ss, NULL) < 0) {
294                         r = EXIT_SIGNAL_MASK;
295                         goto fail;
296                 }
297
298                 if (setpgid(0, 0) < 0) {
299                         r = EXIT_PGID;
300                         goto fail;
301                 }
302
303                 umask(context->umask);
304
305                 if (setup_input(context) < 0) {
306                         r = EXIT_INPUT;
307                         goto fail;
308                 }
309
310                 if (setup_output(context, file_name_from_path(command->path)) < 0) {
311                         r = EXIT_OUTPUT;
312                         goto fail;
313                 }
314
315                 if (context->oom_adjust_set) {
316                         char t[16];
317
318                         snprintf(t, sizeof(t), "%i", context->oom_adjust);
319                         char_array_0(t);
320
321                         if (write_one_line_file("/proc/self/oom_adj", t) < 0) {
322                                 r = EXIT_OOM_ADJUST;
323                                 goto fail;
324                         }
325                 }
326
327                 if (context->root_directory)
328                         if (chroot(context->root_directory) < 0) {
329                                 r = EXIT_CHROOT;
330                                 goto fail;
331                         }
332
333                 if (chdir(context->working_directory ? context->working_directory : "/") < 0) {
334                         r = EXIT_CHDIR;
335                         goto fail;
336                 }
337
338                 if (context->nice_set)
339                         if (setpriority(PRIO_PROCESS, 0, context->nice) < 0) {
340                                 r = EXIT_NICE;
341                                 goto fail;
342                         }
343
344                 if (context->cpu_sched_set) {
345                         struct sched_param param;
346
347                         zero(param);
348                         param.sched_priority = context->cpu_sched_priority;
349
350                         if (sched_setscheduler(0, context->cpu_sched_policy |
351                                                (context->cpu_sched_reset_on_fork ? SCHED_RESET_ON_FORK : 0), &param) < 0) {
352                                 r = EXIT_SETSCHEDULER;
353                                 goto fail;
354                         }
355                 }
356
357                 if (context->cpu_affinity_set)
358                         if (sched_setaffinity(0, sizeof(context->cpu_affinity), &context->cpu_affinity) < 0) {
359                                 r = EXIT_CPUAFFINITY;
360                                 goto fail;
361                         }
362
363                 if (context->ioprio_set)
364                         if (ioprio_set(IOPRIO_WHO_PROCESS, 0, context->ioprio) < 0) {
365                                 r = EXIT_IOPRIO;
366                                 goto fail;
367                         }
368
369                 if (context->timer_slack_ns_set)
370                         if (prctl(PR_SET_TIMERSLACK, context->timer_slack_ns_set) < 0) {
371                                 r = EXIT_TIMERSLACK;
372                                 goto fail;
373                         }
374
375                 if (close_fds(fds, n_fds) < 0 ||
376                     shift_fds(fds, n_fds) < 0 ||
377                     flags_fds(fds, n_fds) < 0) {
378                         r = EXIT_FDS;
379                         goto fail;
380                 }
381
382                 for (i = 0; i < RLIMIT_NLIMITS; i++) {
383                         if (!context->rlimit[i])
384                                 continue;
385
386                         if (setrlimit(i, context->rlimit[i]) < 0) {
387                                 r = EXIT_LIMITS;
388                                 goto fail;
389                         }
390                 }
391
392                 if (context->secure_bits) {
393                         if (prctl(PR_SET_SECUREBITS, context->secure_bits) < 0) {
394                                 r = EXIT_SECUREBITS;
395                                 goto fail;
396                         }
397                 }
398
399                 if (n_fds > 0) {
400                         char a[64], b[64];
401                         char *listen_env[3] = {
402                                 a,
403                                 b,
404                                 NULL
405                         };
406
407                         snprintf(a, sizeof(a), "LISTEN_PID=%llu", (unsigned long long) getpid());
408                         snprintf(b, sizeof(b), "LISTEN_FDS=%u", n_fds);
409
410                         a[sizeof(a)-1] = 0;
411                         b[sizeof(b)-1] = 0;
412
413                         if (context->environment) {
414                                 if (!(f = strv_merge(listen_env, context->environment))) {
415                                         r = EXIT_MEMORY;
416                                         goto fail;
417                                 }
418                                 e = f;
419                         } else
420                                 e = listen_env;
421
422                 } else
423                         e = context->environment;
424
425                 execve(command->path, command->argv, e);
426                 r = EXIT_EXEC;
427
428         fail:
429                 strv_free(f);
430                 _exit(r);
431         }
432
433
434         log_debug("executed %s as %llu", command->path, (unsigned long long) pid);
435
436         *ret = pid;
437         return 0;
438 }
439
440 void exec_context_init(ExecContext *c) {
441         assert(c);
442
443         c->umask = 0002;
444         c->oom_adjust = 0;
445         c->oom_adjust_set = false;
446         c->nice = 0;
447         c->nice_set = false;
448         c->ioprio = IOPRIO_PRIO_VALUE(IOPRIO_CLASS_BE, 0);
449         c->ioprio_set = false;
450         c->cpu_sched_policy = SCHED_OTHER;
451         c->cpu_sched_priority = 0;
452         c->cpu_sched_set = false;
453         CPU_ZERO(&c->cpu_affinity);
454         c->cpu_affinity_set = false;
455
456         c->input = 0;
457         c->output = 0;
458         c->syslog_priority = LOG_DAEMON|LOG_INFO;
459
460         c->secure_bits = 0;
461         c->capability_bounding_set_drop = 0;
462 }
463
464 void exec_context_done(ExecContext *c) {
465         unsigned l;
466
467         assert(c);
468
469         strv_free(c->environment);
470         c->environment = NULL;
471
472         for (l = 0; l < ELEMENTSOF(c->rlimit); l++) {
473                 free(c->rlimit[l]);
474                 c->rlimit[l] = NULL;
475         }
476
477         free(c->working_directory);
478         c->working_directory = NULL;
479         free(c->root_directory);
480         c->root_directory = NULL;
481
482         free(c->syslog_identifier);
483         c->syslog_identifier = NULL;
484
485         free(c->user);
486         c->user = NULL;
487
488         free(c->group);
489         c->group = NULL;
490
491         strv_free(c->supplementary_groups);
492         c->supplementary_groups = NULL;
493
494         if (c->capabilities) {
495                 cap_free(c->capabilities);
496                 c->capabilities = NULL;
497         }
498 }
499
500 void exec_command_free_list(ExecCommand *c) {
501         ExecCommand *i;
502
503         while ((i = c)) {
504                 LIST_REMOVE(ExecCommand, command, c, i);
505
506                 free(i->path);
507                 strv_free(i->argv);
508                 free(i);
509         }
510 }
511
512 void exec_command_free_array(ExecCommand **c, unsigned n) {
513         unsigned i;
514
515         for (i = 0; i < n; i++) {
516                 exec_command_free_list(c[i]);
517                 c[i] = NULL;
518         }
519 }
520
521 void exec_context_dump(ExecContext *c, FILE* f, const char *prefix) {
522         char ** e;
523         unsigned i;
524
525         assert(c);
526         assert(f);
527
528         if (!prefix)
529                 prefix = "";
530
531         fprintf(f,
532                 "%sUMask: %04o\n"
533                 "%sWorkingDirectory: %s\n"
534                 "%sRootDirectory: %s\n",
535                 prefix, c->umask,
536                 prefix, c->working_directory ? c->working_directory : "/",
537                 prefix, c->root_directory ? c->root_directory : "/");
538
539         if (c->environment)
540                 for (e = c->environment; *e; e++)
541                         fprintf(f, "%sEnvironment: %s\n", prefix, *e);
542
543         if (c->nice_set)
544                 fprintf(f,
545                         "%sNice: %i\n",
546                         prefix, c->nice);
547
548         if (c->oom_adjust_set)
549                 fprintf(f,
550                         "%sOOMAdjust: %i\n",
551                         prefix, c->oom_adjust);
552
553         for (i = 0; i < RLIM_NLIMITS; i++)
554                 if (c->rlimit[i])
555                         fprintf(f, "%s%s: %llu\n", prefix, rlimit_to_string(i), (unsigned long long) c->rlimit[i]->rlim_max);
556
557         if (c->ioprio_set)
558                 fprintf(f,
559                         "%sIOSchedulingClass: %s\n"
560                         "%sIOPriority: %i\n",
561                         prefix, ioprio_class_to_string(IOPRIO_PRIO_CLASS(c->ioprio)),
562                         prefix, (int) IOPRIO_PRIO_DATA(c->ioprio));
563
564         if (c->cpu_sched_set)
565                 fprintf(f,
566                         "%sCPUSchedulingPolicy: %s\n"
567                         "%sCPUSchedulingPriority: %i\n"
568                         "%sCPUSchedulingResetOnFork: %s\n",
569                         prefix, sched_policy_to_string(c->cpu_sched_policy),
570                         prefix, c->cpu_sched_priority,
571                         prefix, yes_no(c->cpu_sched_reset_on_fork));
572
573         if (c->cpu_affinity_set) {
574                 fprintf(f, "%sCPUAffinity:", prefix);
575                 for (i = 0; i < CPU_SETSIZE; i++)
576                         if (CPU_ISSET(i, &c->cpu_affinity))
577                                 fprintf(f, " %i", i);
578                 fputs("\n", f);
579         }
580
581         if (c->timer_slack_ns_set)
582                 fprintf(f, "%sTimerSlackNS: %lu\n", prefix, c->timer_slack_ns);
583
584         fprintf(f,
585                 "%sInput: %s\n"
586                 "%sOutput: %s\n",
587                 prefix, exec_input_to_string(c->input),
588                 prefix, exec_output_to_string(c->output));
589
590         if (c->output == EXEC_OUTPUT_SYSLOG || c->output == EXEC_OUTPUT_KERNEL)
591                 fprintf(f,
592                         "%sSyslogFacility: %s\n"
593                         "%sSyslogLevel: %s\n",
594                         prefix, log_facility_to_string(LOG_FAC(c->syslog_priority)),
595                         prefix, log_level_to_string(LOG_PRI(c->syslog_priority)));
596
597         if (c->capabilities) {
598                 char *t;
599                 if ((t = cap_to_text(c->capabilities, NULL))) {
600                         fprintf(f, "%sCapabilities: %s\n",
601                                 prefix, t);
602                         cap_free(t);
603                 }
604         }
605
606         if (c->secure_bits)
607                 fprintf(f, "%sSecure Bits:%s%s%s%s%s%s\n",
608                         prefix,
609                         (c->secure_bits & SECURE_KEEP_CAPS) ? " keep-caps" : "",
610                         (c->secure_bits & SECURE_KEEP_CAPS_LOCKED) ? " keep-caps-locked" : "",
611                         (c->secure_bits & SECURE_NO_SETUID_FIXUP) ? " no-setuid-fixup" : "",
612                         (c->secure_bits & SECURE_NO_SETUID_FIXUP_LOCKED) ? " no-setuid-fixup-locked" : "",
613                         (c->secure_bits & SECURE_NOROOT) ? " noroot" : "",
614                         (c->secure_bits & SECURE_NOROOT_LOCKED) ? "noroot-locked" : "");
615
616         if (c->capability_bounding_set_drop) {
617                 fprintf(f, "%sCapabilityBoundingSetDrop:", prefix);
618
619                 for (i = 0; i <= CAP_LAST_CAP; i++)
620                         if (c->capability_bounding_set_drop & (1 << i)) {
621                                 char *t;
622
623                                 if ((t = cap_to_name(i))) {
624                                         fprintf(f, " %s", t);
625                                         free(t);
626                                 }
627                         }
628
629                 fputs("\n", f);
630         }
631
632         if (c->user)
633                 fprintf(f, "%sUser: %s", prefix, c->user);
634         if (c->group)
635                 fprintf(f, "%sGroup: %s", prefix, c->group);
636
637         if (c->supplementary_groups) {
638                 char **g;
639
640                 fprintf(f, "%sSupplementaryGroups:", prefix);
641
642                 STRV_FOREACH(g, c->supplementary_groups)
643                         fprintf(f, " %s", *g);
644
645                 fputs("\n", f);
646         }
647 }
648
649 void exec_status_fill(ExecStatus *s, pid_t pid, int code, int status) {
650         assert(s);
651
652         s->pid = pid;
653         s->code = code;
654         s->status = status;
655         s->timestamp = now(CLOCK_REALTIME);
656 }
657
658 char *exec_command_line(ExecCommand *c) {
659         size_t k;
660         char *n, *p, **a;
661         bool first = true;
662
663         assert(c);
664         assert(c->argv);
665
666         k = 1;
667         STRV_FOREACH(a, c->argv)
668                 k += strlen(*a)+3;
669
670         if (!(n = new(char, k)))
671                 return NULL;
672
673         p = n;
674         STRV_FOREACH(a, c->argv) {
675
676                 if (!first)
677                         *(p++) = ' ';
678                 else
679                         first = false;
680
681                 if (strpbrk(*a, WHITESPACE)) {
682                         *(p++) = '\'';
683                         p = stpcpy(p, *a);
684                         *(p++) = '\'';
685                 } else
686                         p = stpcpy(p, *a);
687
688         }
689
690         *p = 0;
691
692         /* FIXME: this doesn't really handle arguments that have
693          * spaces and ticks in them */
694
695         return n;
696 }
697
698 void exec_command_dump(ExecCommand *c, FILE *f, const char *prefix) {
699         char *cmd;
700
701         assert(c);
702         assert(f);
703
704         if (!prefix)
705                 prefix = "";
706
707         cmd = exec_command_line(c);
708
709         fprintf(f,
710                 "%sCommand Line: %s\n",
711                 prefix, cmd ? cmd : strerror(ENOMEM));
712
713         free(cmd);
714 }
715
716 void exec_command_dump_list(ExecCommand *c, FILE *f, const char *prefix) {
717         assert(f);
718
719         if (!prefix)
720                 prefix = "";
721
722         LIST_FOREACH(command, c, c)
723                 exec_command_dump(c, f, prefix);
724 }
725
726 static const char* const exec_output_table[_EXEC_OUTPUT_MAX] = {
727         [EXEC_OUTPUT_CONSOLE] = "console",
728         [EXEC_OUTPUT_NULL] = "null",
729         [EXEC_OUTPUT_SYSLOG] = "syslog",
730         [EXEC_OUTPUT_KERNEL] = "kernel"
731 };
732
733 DEFINE_STRING_TABLE_LOOKUP(exec_output, ExecOutput);
734
735 static const char* const exec_input_table[_EXEC_INPUT_MAX] = {
736         [EXEC_INPUT_NULL] = "null",
737         [EXEC_INPUT_CONSOLE] = "console"
738 };
739
740 DEFINE_STRING_TABLE_LOOKUP(exec_input, ExecInput);