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