chiark / gitweb /
Use @ instead = as abstract namespace socket prefix
[elogind.git] / execute.c
1 /*-*- Mode: C; c-basic-offset: 8 -*-*/
2
3 #include <assert.h>
4 #include <dirent.h>
5 #include <errno.h>
6 #include <fcntl.h>
7 #include <unistd.h>
8 #include <string.h>
9 #include <signal.h>
10 #include <sys/socket.h>
11 #include <sys/un.h>
12
13 #include "execute.h"
14 #include "strv.h"
15 #include "macro.h"
16 #include "util.h"
17 #include "log.h"
18
19 static int close_fds(int except[], unsigned n_except) {
20         DIR *d;
21         struct dirent *de;
22         int r = 0;
23
24         /* Modifies the fds array! (sorts it) */
25
26         if (!(d = opendir("/proc/self/fd")))
27                 return -errno;
28
29         while ((de = readdir(d))) {
30                 int fd;
31
32                 if (de->d_name[0] == '.')
33                         continue;
34
35                 if ((r = safe_atoi(de->d_name, &fd)) < 0)
36                         goto finish;
37
38                 if (fd < 3)
39                         continue;
40
41                 if (fd == dirfd(d))
42                         continue;
43
44                 if (except) {
45                         bool found;
46                         unsigned i;
47
48                         found = false;
49                         for (i = 0; i < n_except; i++)
50                                 if (except[i] == fd) {
51                                         found = true;
52                                         break;
53                                 }
54
55                         if (found)
56                                 continue;
57                 }
58
59                 if ((r = close_nointr(fd)) < 0)
60                         goto finish;
61         }
62
63 finish:
64         closedir(d);
65         return r;
66 }
67
68 static int shift_fds(int fds[], unsigned n_fds) {
69         int start, restart_from;
70
71         if (n_fds <= 0)
72                 return 0;
73
74         assert(fds);
75
76         start = 0;
77         for (;;) {
78                 int i;
79
80                 restart_from = -1;
81
82                 for (i = start; i < (int) n_fds; i++) {
83                         int nfd;
84
85                         /* Already at right index? */
86                         if (fds[i] == i+3)
87                                 continue;
88
89                         if ((nfd = fcntl(fds[i], F_DUPFD, i+3)) < 0)
90                                 return -errno;
91
92                         assert_se(close_nointr(fds[i]) == 0);
93                         fds[i] = nfd;
94
95                         /* Hmm, the fd we wanted isn't free? Then
96                          * let's remember that and try again from here*/
97                         if (nfd != i+3 && restart_from < 0)
98                                 restart_from = i;
99                 }
100
101                 if (restart_from < 0)
102                         break;
103
104                 start = restart_from;
105         }
106
107         return 0;
108 }
109
110 static int flags_fds(int fds[], unsigned n_fds) {
111         unsigned i;
112
113         if (n_fds <= 0)
114                 return 0;
115
116         assert(fds);
117
118         /* Drops O_NONBLOCK and FD_CLOEXEC from the file flags */
119
120         for (i = 0; i < n_fds; i++) {
121                 int flags;
122
123                 if ((flags = fcntl(fds[i], F_GETFL, 0)) < 0)
124                         return -errno;
125
126                 /* Since we are at it, let's make sure that nobody
127                  * forgot setting O_NONBLOCK for all our fds */
128
129                 if (fcntl(fds[i], F_SETFL, flags &~O_NONBLOCK) < 0)
130                         return -errno;
131
132                 if ((flags = fcntl(fds[i], F_GETFD, 0)) < 0)
133                         return -errno;
134
135                 /* Also make sure nobody forgot O_CLOEXEC for all our
136                  * fds */
137                 if (fcntl(fds[i], F_SETFD, flags &~FD_CLOEXEC) < 0)
138                         return -errno;
139         }
140
141         return 0;
142 }
143
144 static int replace_null_fd(int fd, int flags) {
145         int nfd;
146         assert(fd >= 0);
147
148         close_nointr(fd);
149
150         if ((nfd = open("/dev/null", flags|O_NOCTTY)) < 0)
151                 return -errno;
152
153         if (nfd != fd) {
154                 close_nointr_nofail(nfd);
155                 return -EIO;
156         }
157
158         return 0;
159 }
160
161 static int setup_output(const ExecContext *context, const char *ident) {
162         int r;
163
164         assert(context);
165
166         switch (context->output) {
167
168         case EXEC_CONSOLE:
169                 return 0;
170
171         case EXEC_NULL:
172
173                 if ((r = replace_null_fd(STDIN_FILENO, O_RDONLY)) < 0 ||
174                     (r = replace_null_fd(STDOUT_FILENO, O_WRONLY)) < 0 ||
175                     (r = replace_null_fd(STDERR_FILENO, O_WRONLY)) < 0)
176                         return r;
177
178                 return 0;
179
180         case EXEC_KERNEL:
181         case EXEC_SYSLOG: {
182
183                 int fd;
184                 union {
185                         struct sockaddr sa;
186                         struct sockaddr_un un;
187                 } sa;
188
189                 if ((r = replace_null_fd(STDIN_FILENO, O_RDONLY)) < 0)
190                         return r;
191
192                 close_nointr(STDOUT_FILENO);
193                 close_nointr(STDERR_FILENO);
194
195                 if ((fd = socket(AF_UNIX, SOCK_STREAM, 0)) < 0)
196                         return -errno;
197
198                 if (fd != STDOUT_FILENO) {
199                         close_nointr_nofail(fd);
200                         return -EIO;
201                 }
202
203                 zero(sa);
204                 sa.sa.sa_family = AF_UNIX;
205                 strncpy(sa.un.sun_path+1, LOGGER_SOCKET, sizeof(sa.un.sun_path)-1);
206
207                 if (connect(fd, &sa.sa, sizeof(sa)) < 0) {
208                         close_nointr_nofail(fd);
209                         return -errno;
210                 }
211
212                 if (shutdown(fd, SHUT_RD) < 0) {
213                         close_nointr_nofail(fd);
214                         return -errno;
215                 }
216
217                 if ((fd = dup(fd)) < 0) {
218                         close_nointr_nofail(fd);
219                         return -errno;
220                 }
221
222                 if (fd != STDERR_FILENO) {
223                         close_nointr_nofail(fd);
224                         return -EIO;
225                 }
226
227                 /* We speak a very simple protocol between log server
228                  * and client: one line for the log destination (kmsg
229                  * or syslog), followed by the priority field,
230                  * followed by the process name. Since we replaced
231                  * stdin/stderr we simple use stdio to write to
232                  * it. Note that we use stderr, to minimize buffer
233                  * flushing issues. */
234
235                 fprintf(stderr,
236                         "%s\n"
237                         "%i\n"
238                         "%s\n",
239                         context->output == EXEC_KERNEL ? "kmsg" : "syslog",
240                         context->syslog_priority,
241                         context->syslog_identifier ? context->syslog_identifier : ident);
242
243                 return 0;
244         }
245         }
246
247         assert_not_reached("Unknown logging type");
248 }
249
250 int exec_spawn(const ExecCommand *command, const ExecContext *context, int *fds, unsigned n_fds, pid_t *ret) {
251         pid_t pid;
252
253         assert(command);
254         assert(context);
255         assert(ret);
256         assert(fds || n_fds <= 0);
257
258         log_debug("about to execute %s", command->path);
259
260         if ((pid = fork()) < 0)
261                 return -errno;
262
263         if (pid == 0) {
264                 char **e, **f = NULL;
265                 int i, r;
266                 sigset_t ss;
267
268                 /* child */
269
270                 if (sigemptyset(&ss) < 0 ||
271                     sigprocmask(SIG_SETMASK, &ss, NULL) < 0) {
272                         r = EXIT_SIGNAL_MASK;
273                         goto fail;
274                 }
275
276                 umask(context->umask);
277
278                 if (chdir(context->directory ? context->directory : "/") < 0) {
279                         r = EXIT_CHDIR;
280                         goto fail;
281                 }
282
283                 if (setup_output(context, file_name_from_path(command->path)) < 0) {
284                         r = EXIT_OUTPUT;
285                         goto fail;
286                 }
287
288                 if (context->oom_adjust_set) {
289                         char t[16];
290
291                         snprintf(t, sizeof(t), "%i", context->oom_adjust);
292                         char_array_0(t);
293
294                         if (write_one_line_file("/proc/self/oom_adj", t) < 0) {
295                                 r = EXIT_OOM_ADJUST;
296                                 goto fail;
297                         }
298                 }
299
300                 if (context->nice_set)
301                         if (setpriority(PRIO_PROCESS, 0, context->nice) < 0) {
302                                 r = EXIT_NICE;
303                                 goto fail;
304                         }
305
306                 if (close_fds(fds, n_fds) < 0 ||
307                     shift_fds(fds, n_fds) < 0 ||
308                     flags_fds(fds, n_fds) < 0) {
309                         r = EXIT_FDS;
310                         goto fail;
311                 }
312
313                 for (i = 0; i < RLIMIT_NLIMITS; i++) {
314                         if (!context->rlimit[i])
315                                 continue;
316
317                         if (setrlimit(i, context->rlimit[i]) < 0) {
318                                 r = EXIT_LIMITS;
319                                 goto fail;
320                         }
321                 }
322
323                 if (n_fds > 0) {
324                         char a[64], b[64];
325                         char *listen_env[3] = {
326                                 a,
327                                 b,
328                                 NULL
329                         };
330
331                         snprintf(a, sizeof(a), "LISTEN_PID=%llu", (unsigned long long) getpid());
332                         snprintf(b, sizeof(b), "LISTEN_FDS=%u", n_fds);
333
334                         a[sizeof(a)-1] = 0;
335                         b[sizeof(b)-1] = 0;
336
337                         if (context->environment) {
338                                 if (!(f = strv_merge(listen_env, context->environment))) {
339                                         r = EXIT_MEMORY;
340                                         goto fail;
341                                 }
342                                 e = f;
343                         } else
344                                 e = listen_env;
345
346                 } else
347                         e = context->environment;
348
349                 execve(command->path, command->argv, e);
350                 r = EXIT_EXEC;
351
352         fail:
353                 strv_free(f);
354                 _exit(r);
355         }
356
357
358         log_debug("executed %s as %llu", command->path, (unsigned long long) pid);
359
360         *ret = pid;
361         return 0;
362 }
363
364 void exec_context_init(ExecContext *c) {
365         assert(c);
366
367         c->umask = 0002;
368         cap_clear(c->capabilities);
369         c->oom_adjust = 0;
370         c->nice = 0;
371
372         c->output = 0;
373         c->syslog_priority = LOG_DAEMON|LOG_INFO;
374 }
375
376 void exec_context_done(ExecContext *c) {
377         unsigned l;
378
379         assert(c);
380
381         strv_free(c->environment);
382         c->environment = NULL;
383
384         for (l = 0; l < ELEMENTSOF(c->rlimit); l++) {
385                 free(c->rlimit[l]);
386                 c->rlimit[l] = NULL;
387         }
388
389         free(c->directory);
390         c->directory = NULL;
391
392         free(c->syslog_identifier);
393         c->syslog_identifier = NULL;
394
395         free(c->user);
396         c->user = NULL;
397
398         free(c->group);
399         c->group = NULL;
400
401         strv_free(c->supplementary_groups);
402         c->supplementary_groups = NULL;
403 }
404
405 void exec_command_free_list(ExecCommand *c) {
406         ExecCommand *i;
407
408         while ((i = c)) {
409                 LIST_REMOVE(ExecCommand, command, c, i);
410
411                 free(i->path);
412                 strv_free(i->argv);
413                 free(i);
414         }
415 }
416
417 void exec_command_free_array(ExecCommand **c, unsigned n) {
418         unsigned i;
419
420         for (i = 0; i < n; i++) {
421                 exec_command_free_list(c[i]);
422                 c[i] = NULL;
423         }
424 }
425
426 void exec_context_dump(ExecContext *c, FILE* f, const char *prefix) {
427         assert(c);
428         assert(f);
429
430         if (!prefix)
431                 prefix = "";
432
433         fprintf(f,
434                 "%sUmask: %04o\n"
435                 "%sDirectory: %s\n",
436                 prefix, c->umask,
437                 prefix, c->directory ? c->directory : "/");
438
439         if (c->nice_set)
440                 fprintf(f,
441                         "%sNice: %i\n",
442                         prefix, c->nice);
443
444         if (c->oom_adjust_set)
445                 fprintf(f,
446                         "%sOOMAdjust: %i\n",
447                         prefix, c->oom_adjust);
448 }
449
450 void exec_status_fill(ExecStatus *s, pid_t pid, int code, int status) {
451         assert(s);
452
453         s->pid = pid;
454         s->code = code;
455         s->status = status;
456         s->timestamp = now(CLOCK_REALTIME);
457 }
458
459 char *exec_command_line(ExecCommand *c) {
460         size_t k;
461         char *n, *p, **a;
462         bool first = true;
463
464         assert(c);
465         assert(c->argv);
466
467         k = 1;
468         STRV_FOREACH(a, c->argv)
469                 k += strlen(*a)+3;
470
471         if (!(n = new(char, k)))
472                 return NULL;
473
474         p = n;
475         STRV_FOREACH(a, c->argv) {
476
477                 if (!first)
478                         *(p++) = ' ';
479                 else
480                         first = false;
481
482                 if (strpbrk(*a, WHITESPACE)) {
483                         *(p++) = '\'';
484                         p = stpcpy(p, *a);
485                         *(p++) = '\'';
486                 } else
487                         p = stpcpy(p, *a);
488
489         }
490
491         *p = 0;
492
493         /* FIXME: this doesn't really handle arguments that have
494          * spaces and ticks in them */
495
496         return n;
497 }
498
499 void exec_command_dump(ExecCommand *c, FILE *f, const char *prefix) {
500         char *cmd;
501
502         assert(c);
503         assert(f);
504
505         if (!prefix)
506                 prefix = "";
507
508         cmd = exec_command_line(c);
509
510         fprintf(f,
511                 "%sCommand Line: %s\n",
512                 prefix, cmd ? cmd : strerror(ENOMEM));
513
514         free(cmd);
515 }
516
517 void exec_command_dump_list(ExecCommand *c, FILE *f, const char *prefix) {
518         assert(f);
519
520         if (!prefix)
521                 prefix = "";
522
523         LIST_FOREACH(command, c, c)
524                 exec_command_dump(c, f, prefix);
525 }