chiark / gitweb /
add basic (and not very useful) D-Bus support
[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, &param) < 0) {
351                                 r = EXIT_SETSCHEDULER;
352                                 goto fail;
353                         }
354                 }
355
356                 if (context->cpu_affinity_set)
357                         if (sched_setaffinity(0, sizeof(context->cpu_affinity), &context->cpu_affinity) < 0) {
358                                 r = EXIT_CPUAFFINITY;
359                                 goto fail;
360                         }
361
362                 if (context->ioprio_set)
363                         if (ioprio_set(IOPRIO_WHO_PROCESS, 0, context->ioprio) < 0) {
364                                 r = EXIT_IOPRIO;
365                                 goto fail;
366                         }
367
368                 if (context->timer_slack_ns_set)
369                         if (prctl(PR_SET_TIMERSLACK, context->timer_slack_ns_set) < 0) {
370                                 r = EXIT_TIMERSLACK;
371                                 goto fail;
372                         }
373
374                 if (close_fds(fds, n_fds) < 0 ||
375                     shift_fds(fds, n_fds) < 0 ||
376                     flags_fds(fds, n_fds) < 0) {
377                         r = EXIT_FDS;
378                         goto fail;
379                 }
380
381                 for (i = 0; i < RLIMIT_NLIMITS; i++) {
382                         if (!context->rlimit[i])
383                                 continue;
384
385                         if (setrlimit(i, context->rlimit[i]) < 0) {
386                                 r = EXIT_LIMITS;
387                                 goto fail;
388                         }
389                 }
390
391                 if (context->secure_bits) {
392                         if (prctl(PR_SET_SECUREBITS, context->secure_bits) < 0) {
393                                 r = EXIT_SECUREBITS;
394                                 goto fail;
395                         }
396                 }
397
398                 if (n_fds > 0) {
399                         char a[64], b[64];
400                         char *listen_env[3] = {
401                                 a,
402                                 b,
403                                 NULL
404                         };
405
406                         snprintf(a, sizeof(a), "LISTEN_PID=%llu", (unsigned long long) getpid());
407                         snprintf(b, sizeof(b), "LISTEN_FDS=%u", n_fds);
408
409                         a[sizeof(a)-1] = 0;
410                         b[sizeof(b)-1] = 0;
411
412                         if (context->environment) {
413                                 if (!(f = strv_merge(listen_env, context->environment))) {
414                                         r = EXIT_MEMORY;
415                                         goto fail;
416                                 }
417                                 e = f;
418                         } else
419                                 e = listen_env;
420
421                 } else
422                         e = context->environment;
423
424                 execve(command->path, command->argv, e);
425                 r = EXIT_EXEC;
426
427         fail:
428                 strv_free(f);
429                 _exit(r);
430         }
431
432
433         log_debug("executed %s as %llu", command->path, (unsigned long long) pid);
434
435         *ret = pid;
436         return 0;
437 }
438
439 void exec_context_init(ExecContext *c) {
440         assert(c);
441
442         c->umask = 0002;
443         c->oom_adjust = 0;
444         c->oom_adjust_set = false;
445         c->nice = 0;
446         c->nice_set = false;
447         c->ioprio = IOPRIO_PRIO_VALUE(IOPRIO_CLASS_BE, 0);
448         c->ioprio_set = false;
449         c->cpu_sched_policy = SCHED_OTHER;
450         c->cpu_sched_priority = 0;
451         c->cpu_sched_set = false;
452         CPU_ZERO(&c->cpu_affinity);
453         c->cpu_affinity_set = false;
454
455         c->input = 0;
456         c->output = 0;
457         c->syslog_priority = LOG_DAEMON|LOG_INFO;
458
459         c->secure_bits = 0;
460         c->capability_bounding_set_drop = 0;
461 }
462
463 void exec_context_done(ExecContext *c) {
464         unsigned l;
465
466         assert(c);
467
468         strv_free(c->environment);
469         c->environment = NULL;
470
471         for (l = 0; l < ELEMENTSOF(c->rlimit); l++) {
472                 free(c->rlimit[l]);
473                 c->rlimit[l] = NULL;
474         }
475
476         free(c->working_directory);
477         c->working_directory = NULL;
478         free(c->root_directory);
479         c->root_directory = NULL;
480
481         free(c->syslog_identifier);
482         c->syslog_identifier = NULL;
483
484         free(c->user);
485         c->user = NULL;
486
487         free(c->group);
488         c->group = NULL;
489
490         strv_free(c->supplementary_groups);
491         c->supplementary_groups = NULL;
492
493         if (c->capabilities) {
494                 cap_free(c->capabilities);
495                 c->capabilities = NULL;
496         }
497 }
498
499 void exec_command_free_list(ExecCommand *c) {
500         ExecCommand *i;
501
502         while ((i = c)) {
503                 LIST_REMOVE(ExecCommand, command, c, i);
504
505                 free(i->path);
506                 strv_free(i->argv);
507                 free(i);
508         }
509 }
510
511 void exec_command_free_array(ExecCommand **c, unsigned n) {
512         unsigned i;
513
514         for (i = 0; i < n; i++) {
515                 exec_command_free_list(c[i]);
516                 c[i] = NULL;
517         }
518 }
519
520 void exec_context_dump(ExecContext *c, FILE* f, const char *prefix) {
521         char ** e;
522         unsigned i;
523
524         assert(c);
525         assert(f);
526
527         if (!prefix)
528                 prefix = "";
529
530         fprintf(f,
531                 "%sUMask: %04o\n"
532                 "%sWorkingDirectory: %s\n"
533                 "%sRootDirectory: %s\n",
534                 prefix, c->umask,
535                 prefix, c->working_directory ? c->working_directory : "/",
536                 prefix, c->root_directory ? c->root_directory : "/");
537
538         if (c->environment)
539                 for (e = c->environment; *e; e++)
540                         fprintf(f, "%sEnvironment: %s\n", prefix, *e);
541
542         if (c->nice_set)
543                 fprintf(f,
544                         "%sNice: %i\n",
545                         prefix, c->nice);
546
547         if (c->oom_adjust_set)
548                 fprintf(f,
549                         "%sOOMAdjust: %i\n",
550                         prefix, c->oom_adjust);
551
552         for (i = 0; i < RLIM_NLIMITS; i++)
553                 if (c->rlimit[i])
554                         fprintf(f, "%s%s: %llu\n", prefix, rlimit_to_string(i), (unsigned long long) c->rlimit[i]->rlim_max);
555
556         if (c->ioprio_set)
557                 fprintf(f,
558                         "%sIOSchedulingClass: %s\n"
559                         "%sIOPriority: %i\n",
560                         prefix, ioprio_class_to_string(IOPRIO_PRIO_CLASS(c->ioprio)),
561                         prefix, (int) IOPRIO_PRIO_DATA(c->ioprio));
562
563         if (c->cpu_sched_set)
564                 fprintf(f,
565                         "%sCPUSchedulingPolicy: %s\n"
566                         "%sCPUSchedulingPriority: %i\n",
567                         prefix, sched_policy_to_string(c->cpu_sched_policy),
568                         prefix, c->cpu_sched_priority);
569
570         if (c->cpu_affinity_set) {
571                 fprintf(f, "%sCPUAffinity:", prefix);
572                 for (i = 0; i < CPU_SETSIZE; i++)
573                         if (CPU_ISSET(i, &c->cpu_affinity))
574                                 fprintf(f, " %i", i);
575                 fputs("\n", f);
576         }
577
578         if (c->timer_slack_ns_set)
579                 fprintf(f, "%sTimerSlackNS: %lu\n", prefix, c->timer_slack_ns);
580
581         fprintf(f,
582                 "%sInput: %s\n"
583                 "%sOutput: %s\n",
584                 prefix, exec_input_to_string(c->input),
585                 prefix, exec_output_to_string(c->output));
586
587         if (c->output == EXEC_OUTPUT_SYSLOG || c->output == EXEC_OUTPUT_KERNEL)
588                 fprintf(f,
589                         "%sSyslogFacility: %s\n"
590                         "%sSyslogLevel: %s\n",
591                         prefix, log_facility_to_string(LOG_FAC(c->syslog_priority)),
592                         prefix, log_level_to_string(LOG_PRI(c->syslog_priority)));
593
594         if (c->capabilities) {
595                 char *t;
596                 if ((t = cap_to_text(c->capabilities, NULL))) {
597                         fprintf(f, "%sCapabilities: %s\n",
598                                 prefix, t);
599                         cap_free(t);
600                 }
601         }
602
603         if (c->secure_bits)
604                 fprintf(f, "%sSecure Bits:%s%s%s%s%s%s\n",
605                         prefix,
606                         (c->secure_bits & SECURE_KEEP_CAPS) ? " keep-caps" : "",
607                         (c->secure_bits & SECURE_KEEP_CAPS_LOCKED) ? " keep-caps-locked" : "",
608                         (c->secure_bits & SECURE_NO_SETUID_FIXUP) ? " no-setuid-fixup" : "",
609                         (c->secure_bits & SECURE_NO_SETUID_FIXUP_LOCKED) ? " no-setuid-fixup-locked" : "",
610                         (c->secure_bits & SECURE_NOROOT) ? " noroot" : "",
611                         (c->secure_bits & SECURE_NOROOT_LOCKED) ? "noroot-locked" : "");
612
613         if (c->capability_bounding_set_drop) {
614                 fprintf(f, "%sCapabilityBoundingSetDrop:", prefix);
615
616                 for (i = 0; i <= CAP_LAST_CAP; i++)
617                         if (c->capability_bounding_set_drop & (1 << i)) {
618                                 char *t;
619
620                                 if ((t = cap_to_name(i))) {
621                                         fprintf(f, " %s", t);
622                                         free(t);
623                                 }
624                         }
625
626                 fputs("\n", f);
627         }
628
629         if (c->user)
630                 fprintf(f, "%sUser: %s", prefix, c->user);
631         if (c->group)
632                 fprintf(f, "%sGroup: %s", prefix, c->group);
633
634         if (c->supplementary_groups) {
635                 char **g;
636
637                 fprintf(f, "%sSupplementaryGroups:", prefix);
638
639                 STRV_FOREACH(g, c->supplementary_groups)
640                         fprintf(f, " %s", *g);
641
642                 fputs("\n", f);
643         }
644 }
645
646 void exec_status_fill(ExecStatus *s, pid_t pid, int code, int status) {
647         assert(s);
648
649         s->pid = pid;
650         s->code = code;
651         s->status = status;
652         s->timestamp = now(CLOCK_REALTIME);
653 }
654
655 char *exec_command_line(ExecCommand *c) {
656         size_t k;
657         char *n, *p, **a;
658         bool first = true;
659
660         assert(c);
661         assert(c->argv);
662
663         k = 1;
664         STRV_FOREACH(a, c->argv)
665                 k += strlen(*a)+3;
666
667         if (!(n = new(char, k)))
668                 return NULL;
669
670         p = n;
671         STRV_FOREACH(a, c->argv) {
672
673                 if (!first)
674                         *(p++) = ' ';
675                 else
676                         first = false;
677
678                 if (strpbrk(*a, WHITESPACE)) {
679                         *(p++) = '\'';
680                         p = stpcpy(p, *a);
681                         *(p++) = '\'';
682                 } else
683                         p = stpcpy(p, *a);
684
685         }
686
687         *p = 0;
688
689         /* FIXME: this doesn't really handle arguments that have
690          * spaces and ticks in them */
691
692         return n;
693 }
694
695 void exec_command_dump(ExecCommand *c, FILE *f, const char *prefix) {
696         char *cmd;
697
698         assert(c);
699         assert(f);
700
701         if (!prefix)
702                 prefix = "";
703
704         cmd = exec_command_line(c);
705
706         fprintf(f,
707                 "%sCommand Line: %s\n",
708                 prefix, cmd ? cmd : strerror(ENOMEM));
709
710         free(cmd);
711 }
712
713 void exec_command_dump_list(ExecCommand *c, FILE *f, const char *prefix) {
714         assert(f);
715
716         if (!prefix)
717                 prefix = "";
718
719         LIST_FOREACH(command, c, c)
720                 exec_command_dump(c, f, prefix);
721 }
722
723 static const char* const exec_output_table[_EXEC_OUTPUT_MAX] = {
724         [EXEC_OUTPUT_CONSOLE] = "console",
725         [EXEC_OUTPUT_NULL] = "null",
726         [EXEC_OUTPUT_SYSLOG] = "syslog",
727         [EXEC_OUTPUT_KERNEL] = "kernel"
728 };
729
730 DEFINE_STRING_TABLE_LOOKUP(exec_output, ExecOutput);
731
732 static const char* const exec_input_table[_EXEC_INPUT_MAX] = {
733         [EXEC_INPUT_NULL] = "null",
734         [EXEC_INPUT_CONSOLE] = "console"
735 };
736
737 DEFINE_STRING_TABLE_LOOKUP(exec_input, ExecInput);