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