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