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