chiark / gitweb /
implement proper logging for services
[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                 char t[16];
267                 sigset_t ss;
268
269                 /* child */
270
271                 if (sigemptyset(&ss) < 0 ||
272                     sigprocmask(SIG_SETMASK, &ss, NULL) < 0) {
273                         r = EXIT_SIGNAL_MASK;
274                         goto fail;
275                 }
276
277                 umask(context->umask);
278
279                 if (chdir(context->directory ? context->directory : "/") < 0) {
280                         r = EXIT_CHDIR;
281                         goto fail;
282                 }
283
284                 if (setup_output(context, file_name_from_path(command->path)) < 0) {
285                         r = EXIT_OUTPUT;
286                         goto fail;
287                 }
288
289                 snprintf(t, sizeof(t), "%i", context->oom_adjust);
290                 char_array_0(t);
291
292                 if (write_one_line_file("/proc/self/oom_adj", t) < 0) {
293                         r = EXIT_OOM_ADJUST;
294                         goto fail;
295                 }
296
297                 if (setpriority(PRIO_PROCESS, 0, context->nice) < 0) {
298                         r = EXIT_NICE;
299                         goto fail;
300                 }
301
302                 if (close_fds(fds, n_fds) < 0 ||
303                     shift_fds(fds, n_fds) < 0 ||
304                     flags_fds(fds, n_fds) < 0) {
305                         r = EXIT_FDS;
306                         goto fail;
307                 }
308
309                 for (i = 0; i < RLIMIT_NLIMITS; i++) {
310                         if (!context->rlimit[i])
311                                 continue;
312
313                         if (setrlimit(i, context->rlimit[i]) < 0) {
314                                 r = EXIT_LIMITS;
315                                 goto fail;
316                         }
317                 }
318
319                 if (n_fds > 0) {
320                         char a[64], b[64];
321                         char *listen_env[3] = {
322                                 a,
323                                 b,
324                                 NULL
325                         };
326
327                         snprintf(a, sizeof(a), "LISTEN_PID=%llu", (unsigned long long) getpid());
328                         snprintf(b, sizeof(b), "LISTEN_FDS=%u", n_fds);
329
330                         a[sizeof(a)-1] = 0;
331                         b[sizeof(b)-1] = 0;
332
333                         if (context->environment) {
334                                 if (!(f = strv_merge(listen_env, context->environment))) {
335                                         r = EXIT_MEMORY;
336                                         goto fail;
337                                 }
338                                 e = f;
339                         } else
340                                 e = listen_env;
341
342                 } else
343                         e = context->environment;
344
345                 execve(command->path, command->argv, e);
346                 r = EXIT_EXEC;
347
348         fail:
349                 strv_free(f);
350                 _exit(r);
351         }
352
353
354         log_debug("executed %s as %llu", command->path, (unsigned long long) pid);
355
356         *ret = pid;
357         return 0;
358 }
359
360 void exec_context_init(ExecContext *c) {
361         assert(c);
362
363         c->umask = 0002;
364         cap_clear(c->capabilities);
365         c->oom_adjust = 0;
366         c->nice = 0;
367
368         c->output = 0;
369         c->syslog_priority = LOG_DAEMON|LOG_INFO;
370 }
371
372 void exec_context_done(ExecContext *c) {
373         unsigned l;
374
375         assert(c);
376
377         strv_free(c->environment);
378         c->environment = NULL;
379
380         for (l = 0; l < ELEMENTSOF(c->rlimit); l++) {
381                 free(c->rlimit[l]);
382                 c->rlimit[l] = NULL;
383         }
384
385         free(c->directory);
386         c->directory = NULL;
387
388         free(c->syslog_identifier);
389         c->syslog_identifier = NULL;
390
391         free(c->user);
392         c->user = NULL;
393
394         free(c->group);
395         c->group = NULL;
396
397         strv_free(c->supplementary_groups);
398         c->supplementary_groups = NULL;
399 }
400
401 void exec_command_free_list(ExecCommand *c) {
402         ExecCommand *i;
403
404         while ((i = c)) {
405                 LIST_REMOVE(ExecCommand, command, c, i);
406
407                 free(i->path);
408                 strv_free(i->argv);
409                 free(i);
410         }
411 }
412
413 void exec_command_free_array(ExecCommand **c, unsigned n) {
414         unsigned i;
415
416         for (i = 0; i < n; i++) {
417                 exec_command_free_list(c[i]);
418                 c[i] = NULL;
419         }
420 }
421
422 void exec_context_dump(ExecContext *c, FILE* f, const char *prefix) {
423         assert(c);
424         assert(f);
425
426         if (!prefix)
427                 prefix = "";
428
429         fprintf(f,
430                 "%sUmask: %04o\n"
431                 "%sDirectory: %s\n"
432                 "%sNice: %i\n"
433                 "%sOOMAdjust: %i\n",
434                 prefix, c->umask,
435                 prefix, c->directory ? c->directory : "/",
436                 prefix, c->nice,
437                 prefix, c->oom_adjust);
438 }
439
440 void exec_status_fill(ExecStatus *s, pid_t pid, int code, int status) {
441         assert(s);
442
443         s->pid = pid;
444         s->code = code;
445         s->status = status;
446         s->timestamp = now(CLOCK_REALTIME);
447 }
448
449 char *exec_command_line(ExecCommand *c) {
450         size_t k;
451         char *n, *p, **a;
452         bool first = true;
453
454         assert(c);
455         assert(c->argv);
456
457         k = 1;
458         STRV_FOREACH(a, c->argv)
459                 k += strlen(*a)+3;
460
461         if (!(n = new(char, k)))
462                 return NULL;
463
464         p = n;
465         STRV_FOREACH(a, c->argv) {
466
467                 if (!first)
468                         *(p++) = ' ';
469                 else
470                         first = false;
471
472                 if (strpbrk(*a, WHITESPACE)) {
473                         *(p++) = '\'';
474                         p = stpcpy(p, *a);
475                         *(p++) = '\'';
476                 } else
477                         p = stpcpy(p, *a);
478
479         }
480
481         *p = 0;
482
483         /* FIXME: this doesn't really handle arguments that have
484          * spaces and ticks in them */
485
486         return n;
487 }
488
489 void exec_command_dump(ExecCommand *c, FILE *f, const char *prefix) {
490         char *cmd;
491
492         assert(c);
493         assert(f);
494
495         if (!prefix)
496                 prefix = "";
497
498         cmd = exec_command_line(c);
499
500         fprintf(f,
501                 "%sCommand Line: %s\n",
502                 prefix, cmd ? cmd : strerror(ENOMEM));
503
504         free(cmd);
505 }
506
507 void exec_command_dump_list(ExecCommand *c, FILE *f, const char *prefix) {
508         assert(f);
509
510         if (!prefix)
511                 prefix = "";
512
513         LIST_FOREACH(command, c, c)
514                 exec_command_dump(c, f, prefix);
515 }