instance: provide error feedback if ujail binary is missing
[oweals/procd.git] / service / instance.c
1 /*
2  * Copyright (C) 2013 Felix Fietkau <nbd@openwrt.org>
3  * Copyright (C) 2013 John Crispin <blogic@openwrt.org>
4  *
5  * This program is free software; you can redistribute it and/or modify
6  * it under the terms of the GNU Lesser General Public License version 2.1
7  * as published by the Free Software Foundation
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  */
14
15 #define _GNU_SOURCE
16 #include <sys/resource.h>
17 #include <sys/types.h>
18 #include <sys/socket.h>
19 #include <sys/stat.h>
20 #include <grp.h>
21 #include <net/if.h>
22 #include <unistd.h>
23 #include <stdint.h>
24 #include <stdio.h>
25 #include <fcntl.h>
26 #include <pwd.h>
27 #include <libgen.h>
28 #include <unistd.h>
29 #define SYSLOG_NAMES
30 #include <syslog.h>
31
32 #include <libubox/md5.h>
33
34 #include "../procd.h"
35
36 #include "service.h"
37 #include "instance.h"
38
39 #define UJAIL_BIN_PATH "/sbin/ujail"
40
41 enum {
42         INSTANCE_ATTR_COMMAND,
43         INSTANCE_ATTR_ENV,
44         INSTANCE_ATTR_DATA,
45         INSTANCE_ATTR_NETDEV,
46         INSTANCE_ATTR_FILE,
47         INSTANCE_ATTR_TRIGGER,
48         INSTANCE_ATTR_RESPAWN,
49         INSTANCE_ATTR_NICE,
50         INSTANCE_ATTR_LIMITS,
51         INSTANCE_ATTR_WATCH,
52         INSTANCE_ATTR_ERROR,
53         INSTANCE_ATTR_USER,
54         INSTANCE_ATTR_GROUP,
55         INSTANCE_ATTR_STDOUT,
56         INSTANCE_ATTR_STDERR,
57         INSTANCE_ATTR_NO_NEW_PRIVS,
58         INSTANCE_ATTR_JAIL,
59         INSTANCE_ATTR_TRACE,
60         INSTANCE_ATTR_SECCOMP,
61         INSTANCE_ATTR_PIDFILE,
62         INSTANCE_ATTR_RELOADSIG,
63         INSTANCE_ATTR_TERMTIMEOUT,
64         INSTANCE_ATTR_FACILITY,
65         __INSTANCE_ATTR_MAX
66 };
67
68 static const struct blobmsg_policy instance_attr[__INSTANCE_ATTR_MAX] = {
69         [INSTANCE_ATTR_COMMAND] = { "command", BLOBMSG_TYPE_ARRAY },
70         [INSTANCE_ATTR_ENV] = { "env", BLOBMSG_TYPE_TABLE },
71         [INSTANCE_ATTR_DATA] = { "data", BLOBMSG_TYPE_TABLE },
72         [INSTANCE_ATTR_NETDEV] = { "netdev", BLOBMSG_TYPE_ARRAY },
73         [INSTANCE_ATTR_FILE] = { "file", BLOBMSG_TYPE_ARRAY },
74         [INSTANCE_ATTR_TRIGGER] = { "triggers", BLOBMSG_TYPE_ARRAY },
75         [INSTANCE_ATTR_RESPAWN] = { "respawn", BLOBMSG_TYPE_ARRAY },
76         [INSTANCE_ATTR_NICE] = { "nice", BLOBMSG_TYPE_INT32 },
77         [INSTANCE_ATTR_LIMITS] = { "limits", BLOBMSG_TYPE_TABLE },
78         [INSTANCE_ATTR_WATCH] = { "watch", BLOBMSG_TYPE_ARRAY },
79         [INSTANCE_ATTR_ERROR] = { "error", BLOBMSG_TYPE_ARRAY },
80         [INSTANCE_ATTR_USER] = { "user", BLOBMSG_TYPE_STRING },
81         [INSTANCE_ATTR_GROUP] = { "group", BLOBMSG_TYPE_STRING },
82         [INSTANCE_ATTR_STDOUT] = { "stdout", BLOBMSG_TYPE_BOOL },
83         [INSTANCE_ATTR_STDERR] = { "stderr", BLOBMSG_TYPE_BOOL },
84         [INSTANCE_ATTR_NO_NEW_PRIVS] = { "no_new_privs", BLOBMSG_TYPE_BOOL },
85         [INSTANCE_ATTR_JAIL] = { "jail", BLOBMSG_TYPE_TABLE },
86         [INSTANCE_ATTR_TRACE] = { "trace", BLOBMSG_TYPE_BOOL },
87         [INSTANCE_ATTR_SECCOMP] = { "seccomp", BLOBMSG_TYPE_STRING },
88         [INSTANCE_ATTR_PIDFILE] = { "pidfile", BLOBMSG_TYPE_STRING },
89         [INSTANCE_ATTR_RELOADSIG] = { "reload_signal", BLOBMSG_TYPE_INT32 },
90         [INSTANCE_ATTR_TERMTIMEOUT] = { "term_timeout", BLOBMSG_TYPE_INT32 },
91         [INSTANCE_ATTR_FACILITY] = { "facility", BLOBMSG_TYPE_STRING },
92 };
93
94 enum {
95         JAIL_ATTR_NAME,
96         JAIL_ATTR_HOSTNAME,
97         JAIL_ATTR_PROCFS,
98         JAIL_ATTR_SYSFS,
99         JAIL_ATTR_UBUS,
100         JAIL_ATTR_LOG,
101         JAIL_ATTR_RONLY,
102         JAIL_ATTR_MOUNT,
103         __JAIL_ATTR_MAX,
104 };
105
106 static const struct blobmsg_policy jail_attr[__JAIL_ATTR_MAX] = {
107         [JAIL_ATTR_NAME] = { "name", BLOBMSG_TYPE_STRING },
108         [JAIL_ATTR_HOSTNAME] = { "hostname", BLOBMSG_TYPE_STRING },
109         [JAIL_ATTR_PROCFS] = { "procfs", BLOBMSG_TYPE_BOOL },
110         [JAIL_ATTR_SYSFS] = { "sysfs", BLOBMSG_TYPE_BOOL },
111         [JAIL_ATTR_UBUS] = { "ubus", BLOBMSG_TYPE_BOOL },
112         [JAIL_ATTR_LOG] = { "log", BLOBMSG_TYPE_BOOL },
113         [JAIL_ATTR_RONLY] = { "ronly", BLOBMSG_TYPE_BOOL },
114         [JAIL_ATTR_MOUNT] = { "mount", BLOBMSG_TYPE_TABLE },
115 };
116
117 struct instance_netdev {
118         struct blobmsg_list_node node;
119         int ifindex;
120 };
121
122 struct instance_file {
123         struct blobmsg_list_node node;
124         uint32_t md5[4];
125 };
126
127 struct rlimit_name {
128         const char *name;
129         int resource;
130 };
131
132 static const struct rlimit_name rlimit_names[] = {
133         { "as", RLIMIT_AS },
134         { "core", RLIMIT_CORE },
135         { "cpu", RLIMIT_CPU },
136         { "data", RLIMIT_DATA },
137         { "fsize", RLIMIT_FSIZE },
138         { "memlock", RLIMIT_MEMLOCK },
139         { "nofile", RLIMIT_NOFILE },
140         { "nproc", RLIMIT_NPROC },
141         { "rss", RLIMIT_RSS },
142         { "stack", RLIMIT_STACK },
143 #ifdef linux
144         { "nice", RLIMIT_NICE },
145         { "rtprio", RLIMIT_RTPRIO },
146         { "msgqueue", RLIMIT_MSGQUEUE },
147         { "sigpending", RLIMIT_SIGPENDING },
148 #endif
149         { NULL, 0 }
150 };
151
152 static void closefd(int fd)
153 {
154         if (fd > STDERR_FILENO)
155                 close(fd);
156 }
157
158 /* convert a string into numeric syslog facility or return -1 if no match found */
159 static int
160 syslog_facility_str_to_int(const char *facility)
161 {
162         CODE *p = facilitynames;
163
164         while (p->c_name && strcasecmp(p->c_name, facility))
165                 p++;
166
167         return p->c_val;
168 }
169
170 static void
171 instance_limits(const char *limit, const char *value)
172 {
173         int i;
174         struct rlimit rlim;
175         unsigned long cur, max;
176
177         for (i = 0; rlimit_names[i].name != NULL; i++) {
178                 if (strcmp(rlimit_names[i].name, limit))
179                         continue;
180                 if (!strcmp(value, "unlimited")) {
181                         rlim.rlim_cur = RLIM_INFINITY;
182                         rlim.rlim_max = RLIM_INFINITY;
183                 } else {
184                         if (getrlimit(rlimit_names[i].resource, &rlim))
185                                 return;
186
187                         cur = rlim.rlim_cur;
188                         max = rlim.rlim_max;
189
190                         if (sscanf(value, "%lu %lu", &cur, &max) < 1)
191                                 return;
192
193                         rlim.rlim_cur = cur;
194                         rlim.rlim_max = max;
195                 }
196
197                 setrlimit(rlimit_names[i].resource, &rlim);
198                 return;
199         }
200 }
201
202 static inline int
203 jail_run(struct service_instance *in, char **argv)
204 {
205         struct blobmsg_list_node *var;
206         struct jail *jail = &in->jail;
207         int argc = 0;
208
209         argv[argc++] = UJAIL_BIN_PATH;
210
211         if (jail->name) {
212                 argv[argc++] = "-n";
213                 argv[argc++] = jail->name;
214         }
215
216         if (jail->hostname) {
217                 argv[argc++] = "-h";
218                 argv[argc++] = jail->hostname;
219         }
220
221         if (in->seccomp) {
222                 argv[argc++] = "-S";
223                 argv[argc++] = in->seccomp;
224         }
225
226         if (in->user) {
227                 argv[argc++] = "-U";
228                 argv[argc++] = in->user;
229         }
230
231         if (in->group) {
232                 argv[argc++] = "-G";
233                 argv[argc++] = in->group;
234         }
235
236         if (in->no_new_privs)
237                 argv[argc++] = "-c";
238
239         if (jail->procfs)
240                 argv[argc++] = "-p";
241
242         if (jail->sysfs)
243                 argv[argc++] = "-s";
244
245         if (jail->ubus)
246                 argv[argc++] = "-u";
247
248         if (jail->log)
249                 argv[argc++] = "-l";
250
251         if (jail->ronly)
252                 argv[argc++] = "-o";
253
254         blobmsg_list_for_each(&jail->mount, var) {
255                 const char *type = blobmsg_data(var->data);
256
257                 if (*type == '1')
258                         argv[argc++] = "-w";
259                 else
260                         argv[argc++] = "-r";
261                 argv[argc++] = (char *) blobmsg_name(var->data);
262         }
263
264         argv[argc++] = "--";
265
266         return argc;
267 }
268
269 static int
270 instance_removepid(struct service_instance *in) {
271         if (!in->pidfile)
272                 return 0;
273         if (unlink(in->pidfile)) {
274                 ERROR("Failed to remove pidfile: %s: %m\n", in->pidfile);
275                 return 1;
276         }
277         return 0;
278 }
279
280 static int
281 instance_writepid(struct service_instance *in)
282 {
283         FILE *_pidfile;
284
285         if (!in->pidfile) {
286                 return 0;
287         }
288         _pidfile = fopen(in->pidfile, "w");
289         if (_pidfile == NULL) {
290                 ERROR("failed to open pidfile for writing: %s: %m", in->pidfile);
291                 return 1;
292         }
293         if (fprintf(_pidfile, "%d\n", in->proc.pid) < 0) {
294                 ERROR("failed to write pidfile: %s: %m", in->pidfile);
295                 fclose(_pidfile);
296                 return 2;
297         }
298         if (fclose(_pidfile)) {
299                 ERROR("failed to close pidfile: %s: %m", in->pidfile);
300                 return 3;
301         }
302
303         return 0;
304 }
305
306 static void
307 instance_run(struct service_instance *in, int _stdout, int _stderr)
308 {
309         struct blobmsg_list_node *var;
310         struct blob_attr *cur;
311         char **argv;
312         int argc = 1; /* NULL terminated */
313         int rem, _stdin;
314         bool seccomp = !in->trace && !in->has_jail && in->seccomp;
315         bool setlbf = _stdout >= 0;
316
317         if (in->nice)
318                 setpriority(PRIO_PROCESS, 0, in->nice);
319
320         blobmsg_for_each_attr(cur, in->command, rem)
321                 argc++;
322
323         blobmsg_list_for_each(&in->env, var)
324                 setenv(blobmsg_name(var->data), blobmsg_data(var->data), 1);
325
326         if (seccomp)
327                 setenv("SECCOMP_FILE", in->seccomp, 1);
328
329         if (setlbf)
330                 setenv("LD_PRELOAD", "/lib/libsetlbf.so", 1);
331
332         blobmsg_list_for_each(&in->limits, var)
333                 instance_limits(blobmsg_name(var->data), blobmsg_data(var->data));
334
335         if (in->trace || seccomp)
336                 argc += 1;
337
338         argv = alloca(sizeof(char *) * (argc + in->jail.argc));
339         argc = 0;
340
341 #ifdef SECCOMP_SUPPORT
342         if (in->trace)
343                 argv[argc++] = "/sbin/utrace";
344         else if (seccomp)
345                 argv[argc++] = "/sbin/seccomp-trace";
346 #else
347         if (in->trace || seccomp)
348                 ULOG_WARN("Seccomp support for %s::%s not available\n", in->srv->name, in->name);
349 #endif
350
351         if (in->has_jail) {
352                 argc = jail_run(in, argv);
353                 if (argc != in->jail.argc)
354                         ULOG_WARN("expected %i jail params, used %i for %s::%s\n",
355                                 in->jail.argc, argc, in->srv->name, in->name);
356         }
357
358         blobmsg_for_each_attr(cur, in->command, rem)
359                 argv[argc++] = blobmsg_data(cur);
360
361         argv[argc] = NULL;
362
363         _stdin = open("/dev/null", O_RDONLY);
364
365         if (_stdout == -1)
366                 _stdout = open("/dev/null", O_WRONLY);
367
368         if (_stderr == -1)
369                 _stderr = open("/dev/null", O_WRONLY);
370
371         if (_stdin > -1) {
372                 dup2(_stdin, STDIN_FILENO);
373                 closefd(_stdin);
374         }
375         if (_stdout > -1) {
376                 dup2(_stdout, STDOUT_FILENO);
377                 closefd(_stdout);
378         }
379         if (_stderr > -1) {
380                 dup2(_stderr, STDERR_FILENO);
381                 closefd(_stderr);
382         }
383
384         if (!in->has_jail && in->user && in->pw_gid && initgroups(in->user, in->pw_gid)) {
385                 ERROR("failed to initgroups() for user %s: %m\n", in->user);
386                 exit(127);
387         }
388         if (!in->has_jail && in->gr_gid && setgid(in->gr_gid)) {
389                 ERROR("failed to set group id %d: %m\n", in->gr_gid);
390                 exit(127);
391         }
392         if (!in->has_jail && in->uid && setuid(in->uid)) {
393                 ERROR("failed to set user id %d: %m\n", in->uid);
394                 exit(127);
395         }
396
397         execvp(argv[0], argv);
398         exit(127);
399 }
400
401 static void
402 instance_free_stdio(struct service_instance *in)
403 {
404         if (in->_stdout.fd.fd > -1) {
405                 ustream_free(&in->_stdout.stream);
406                 close(in->_stdout.fd.fd);
407                 in->_stdout.fd.fd = -1;
408         }
409
410         if (in->_stderr.fd.fd > -1) {
411                 ustream_free(&in->_stderr.stream);
412                 close(in->_stderr.fd.fd);
413                 in->_stderr.fd.fd = -1;
414         }
415 }
416
417 void
418 instance_start(struct service_instance *in)
419 {
420         int pid;
421         int opipe[2] = { -1, -1 };
422         int epipe[2] = { -1, -1 };
423
424         if (!avl_is_empty(&in->errors.avl)) {
425                 LOG("Not starting instance %s::%s, an error was indicated\n", in->srv->name, in->name);
426                 return;
427         }
428
429         if (!in->command) {
430                 LOG("Not starting instance %s::%s, command not set\n", in->srv->name, in->name);
431                 return;
432         }
433
434         if (in->proc.pending) {
435                 if (in->halt)
436                         in->restart = true;
437                 return;
438         }
439
440         instance_free_stdio(in);
441         if (in->_stdout.fd.fd > -2) {
442                 if (pipe(opipe)) {
443                         ULOG_WARN("pipe() failed: %m\n");
444                         opipe[0] = opipe[1] = -1;
445                 }
446         }
447
448         if (in->_stderr.fd.fd > -2) {
449                 if (pipe(epipe)) {
450                         ULOG_WARN("pipe() failed: %m\n");
451                         epipe[0] = epipe[1] = -1;
452                 }
453         }
454
455         in->restart = false;
456         in->halt = false;
457
458         if (!in->valid)
459                 return;
460
461         pid = fork();
462         if (pid < 0)
463                 return;
464
465         if (!pid) {
466                 uloop_done();
467                 closefd(opipe[0]);
468                 closefd(epipe[0]);
469                 instance_run(in, opipe[1], epipe[1]);
470                 return;
471         }
472
473         DEBUG(2, "Started instance %s::%s[%d]\n", in->srv->name, in->name, pid);
474         in->proc.pid = pid;
475         instance_writepid(in);
476         clock_gettime(CLOCK_MONOTONIC, &in->start);
477         uloop_process_add(&in->proc);
478
479         if (opipe[0] > -1) {
480                 ustream_fd_init(&in->_stdout, opipe[0]);
481                 closefd(opipe[1]);
482                 fcntl(opipe[0], F_SETFD, FD_CLOEXEC);
483         }
484
485         if (epipe[0] > -1) {
486                 ustream_fd_init(&in->_stderr, epipe[0]);
487                 closefd(epipe[1]);
488                 fcntl(epipe[0], F_SETFD, FD_CLOEXEC);
489         }
490
491         service_event("instance.start", in->srv->name, in->name);
492 }
493
494 static void
495 instance_stdio(struct ustream *s, int prio, struct service_instance *in)
496 {
497         char *newline, *str, *arg0, ident[32];
498         int len;
499
500         arg0 = basename(blobmsg_data(blobmsg_data(in->command)));
501         snprintf(ident, sizeof(ident), "%s[%d]", arg0, in->proc.pid);
502         ulog_open(ULOG_SYSLOG, in->syslog_facility, ident);
503
504         do {
505                 str = ustream_get_read_buf(s, &len);
506                 if (!str)
507                         break;
508
509                 newline = memchr(str, '\n', len);
510                 if (!newline && (s->r.buffer_len != len))
511                         break;
512
513                 if (newline) {
514                         *newline = 0;
515                         len = newline + 1 - str;
516                 }
517                 ulog(prio, "%s\n", str);
518
519                 ustream_consume(s, len);
520         } while (1);
521
522         ulog_open(ULOG_SYSLOG, LOG_DAEMON, "procd");
523 }
524
525 static void
526 instance_stdout(struct ustream *s, int bytes)
527 {
528         instance_stdio(s, LOG_INFO,
529                        container_of(s, struct service_instance, _stdout.stream));
530 }
531
532 static void
533 instance_stderr(struct ustream *s, int bytes)
534 {
535         instance_stdio(s, LOG_ERR,
536                        container_of(s, struct service_instance, _stderr.stream));
537 }
538
539 static void
540 instance_timeout(struct uloop_timeout *t)
541 {
542         struct service_instance *in;
543
544         in = container_of(t, struct service_instance, timeout);
545
546         if (in->halt) {
547                 LOG("Instance %s::%s pid %d not stopped on SIGTERM, sending SIGKILL instead\n",
548                                 in->srv->name, in->name, in->proc.pid);
549                 kill(in->proc.pid, SIGKILL);
550         } else if (in->restart || in->respawn)
551                 instance_start(in);
552 }
553
554 static void
555 instance_delete(struct service_instance *in)
556 {
557         struct service *s = in->srv;
558
559         avl_delete(&s->instances.avl, &in->node.avl);
560         instance_free(in);
561         service_stopped(s);
562 }
563
564 static void
565 instance_exit(struct uloop_process *p, int ret)
566 {
567         struct service_instance *in;
568         struct timespec tp;
569         long runtime;
570
571         in = container_of(p, struct service_instance, proc);
572
573         clock_gettime(CLOCK_MONOTONIC, &tp);
574         runtime = tp.tv_sec - in->start.tv_sec;
575
576         DEBUG(2, "Instance %s::%s exit with error code %d after %ld seconds\n", in->srv->name, in->name, ret, runtime);
577
578         uloop_timeout_cancel(&in->timeout);
579         service_event("instance.stop", in->srv->name, in->name);
580
581         if (in->halt) {
582                 instance_removepid(in);
583                 if (in->restart)
584                         instance_start(in);
585                 else
586                         instance_delete(in);
587         } else if (in->restart) {
588                 instance_start(in);
589         } else if (in->respawn) {
590                 if (runtime < in->respawn_threshold)
591                         in->respawn_count++;
592                 else
593                         in->respawn_count = 0;
594                 if (in->respawn_count > in->respawn_retry && in->respawn_retry > 0 ) {
595                         LOG("Instance %s::%s s in a crash loop %d crashes, %ld seconds since last crash\n",
596                                                                 in->srv->name, in->name, in->respawn_count, runtime);
597                         in->restart = in->respawn = 0;
598                         in->halt = 1;
599                         service_event("instance.fail", in->srv->name, in->name);
600                 } else {
601                         service_event("instance.respawn", in->srv->name, in->name);
602                         uloop_timeout_set(&in->timeout, in->respawn_timeout * 1000);
603                 }
604         }
605 }
606
607 void
608 instance_stop(struct service_instance *in, bool halt)
609 {
610         if (!in->proc.pending) {
611                 if (halt)
612                         instance_delete(in);
613                 return;
614         }
615         in->halt = halt;
616         in->restart = in->respawn = false;
617         kill(in->proc.pid, SIGTERM);
618         uloop_timeout_set(&in->timeout, in->term_timeout * 1000);
619 }
620
621 static void
622 instance_restart(struct service_instance *in)
623 {
624         if (!in->proc.pending)
625                 return;
626
627         if (in->reload_signal) {
628                 kill(in->proc.pid, in->reload_signal);
629                 return;
630         }
631
632         in->halt = true;
633         in->restart = true;
634         kill(in->proc.pid, SIGTERM);
635         uloop_timeout_set(&in->timeout, in->term_timeout * 1000);
636 }
637
638 static bool string_changed(const char *a, const char *b)
639 {
640         return !((!a && !b) || (a && b && !strcmp(a, b)));
641 }
642
643 static bool
644 instance_config_changed(struct service_instance *in, struct service_instance *in_new)
645 {
646         if (!in->valid)
647                 return true;
648
649         if (!blob_attr_equal(in->command, in_new->command))
650                 return true;
651
652         if (!blobmsg_list_equal(&in->env, &in_new->env))
653                 return true;
654
655         if (!blobmsg_list_equal(&in->netdev, &in_new->netdev))
656                 return true;
657
658         if (!blobmsg_list_equal(&in->file, &in_new->file))
659                 return true;
660
661         if (in->nice != in_new->nice)
662                 return true;
663
664         if (in->syslog_facility != in_new->syslog_facility)
665                 return true;
666
667         if (string_changed(in->user, in_new->user))
668                 return true;
669
670         if (string_changed(in->group, in_new->group))
671                 return true;
672
673         if (in->uid != in_new->uid)
674                 return true;
675
676         if (in->pw_gid != in_new->pw_gid)
677                 return true;
678
679         if (string_changed(in->pidfile, in_new->pidfile))
680                 return true;
681
682         if (in->respawn_retry != in_new->respawn_retry)
683                 return true;
684         if (in->respawn_threshold != in_new->respawn_threshold)
685                 return true;
686         if (in->respawn_timeout != in_new->respawn_timeout)
687                 return true;
688
689         if ((!in->seccomp && in_new->seccomp) ||
690             (in->seccomp && !in_new->seccomp) ||
691             (in->seccomp && in_new->seccomp && strcmp(in->seccomp, in_new->seccomp)))
692                 return true;
693
694         if (!blobmsg_list_equal(&in->limits, &in_new->limits))
695                 return true;
696
697         if (!blobmsg_list_equal(&in->jail.mount, &in_new->jail.mount))
698                 return true;
699
700         if (!blobmsg_list_equal(&in->errors, &in_new->errors))
701                 return true;
702
703         return false;
704 }
705
706 static bool
707 instance_netdev_cmp(struct blobmsg_list_node *l1, struct blobmsg_list_node *l2)
708 {
709         struct instance_netdev *n1 = container_of(l1, struct instance_netdev, node);
710         struct instance_netdev *n2 = container_of(l2, struct instance_netdev, node);
711
712         return n1->ifindex == n2->ifindex;
713 }
714
715 static void
716 instance_netdev_update(struct blobmsg_list_node *l)
717 {
718         struct instance_netdev *n = container_of(l, struct instance_netdev, node);
719
720         n->ifindex = if_nametoindex(n->node.avl.key);
721 }
722
723 static bool
724 instance_file_cmp(struct blobmsg_list_node *l1, struct blobmsg_list_node *l2)
725 {
726         struct instance_file *f1 = container_of(l1, struct instance_file, node);
727         struct instance_file *f2 = container_of(l2, struct instance_file, node);
728
729         return !memcmp(f1->md5, f2->md5, sizeof(f1->md5));
730 }
731
732 static void
733 instance_file_update(struct blobmsg_list_node *l)
734 {
735         struct instance_file *f = container_of(l, struct instance_file, node);
736         md5_ctx_t md5;
737         char buf[256];
738         int len, fd;
739
740         memset(f->md5, 0, sizeof(f->md5));
741
742         fd = open(l->avl.key, O_RDONLY);
743         if (fd < 0)
744                 return;
745
746         md5_begin(&md5);
747         do {
748                 len = read(fd, buf, sizeof(buf));
749                 if (len < 0) {
750                         if (errno == EINTR)
751                                 continue;
752
753                         break;
754                 }
755                 if (!len)
756                         break;
757
758                 md5_hash(buf, len, &md5);
759         } while(1);
760
761         md5_end(f->md5, &md5);
762         close(fd);
763 }
764
765 static void
766 instance_fill_any(struct blobmsg_list *l, struct blob_attr *cur)
767 {
768         if (!cur)
769                 return;
770
771         blobmsg_list_fill(l, blobmsg_data(cur), blobmsg_data_len(cur), false);
772 }
773
774 static bool
775 instance_fill_array(struct blobmsg_list *l, struct blob_attr *cur, blobmsg_update_cb cb, bool array)
776 {
777         struct blobmsg_list_node *node;
778
779         if (!cur)
780                 return true;
781
782         if (!blobmsg_check_attr_list(cur, BLOBMSG_TYPE_STRING))
783                 return false;
784
785         blobmsg_list_fill(l, blobmsg_data(cur), blobmsg_data_len(cur), array);
786         if (cb) {
787                 blobmsg_list_for_each(l, node)
788                         cb(node);
789         }
790         return true;
791 }
792
793 static int
794 instance_jail_parse(struct service_instance *in, struct blob_attr *attr)
795 {
796         struct blob_attr *tb[__JAIL_ATTR_MAX];
797         struct jail *jail = &in->jail;
798         struct stat s;
799         int r;
800
801         r = stat(UJAIL_BIN_PATH, &s);
802         if (r < 0) {
803                 ERROR("unable to find %s: %m (%d)\n", UJAIL_BIN_PATH, r);
804                 return 0;
805         }
806
807         blobmsg_parse(jail_attr, __JAIL_ATTR_MAX, tb,
808                 blobmsg_data(attr), blobmsg_data_len(attr));
809
810         jail->argc = 2;
811
812         if (tb[JAIL_ATTR_NAME]) {
813                 jail->name = strdup(blobmsg_get_string(tb[JAIL_ATTR_NAME]));
814                 jail->argc += 2;
815         }
816         if (tb[JAIL_ATTR_HOSTNAME]) {
817                 jail->hostname = strdup(blobmsg_get_string(tb[JAIL_ATTR_HOSTNAME]));
818                 jail->argc += 2;
819         }
820         if (tb[JAIL_ATTR_PROCFS]) {
821                 jail->procfs = blobmsg_get_bool(tb[JAIL_ATTR_PROCFS]);
822                 jail->argc++;
823         }
824         if (tb[JAIL_ATTR_SYSFS]) {
825                 jail->sysfs = blobmsg_get_bool(tb[JAIL_ATTR_SYSFS]);
826                 jail->argc++;
827         }
828         if (tb[JAIL_ATTR_UBUS]) {
829                 jail->ubus = blobmsg_get_bool(tb[JAIL_ATTR_UBUS]);
830                 jail->argc++;
831         }
832         if (tb[JAIL_ATTR_LOG]) {
833                 jail->log = blobmsg_get_bool(tb[JAIL_ATTR_LOG]);
834                 jail->argc++;
835         }
836         if (tb[JAIL_ATTR_RONLY]) {
837                 jail->ronly = blobmsg_get_bool(tb[JAIL_ATTR_RONLY]);
838                 jail->argc++;
839         }
840         if (tb[JAIL_ATTR_MOUNT]) {
841                 struct blob_attr *cur;
842                 int rem;
843
844                 blobmsg_for_each_attr(cur, tb[JAIL_ATTR_MOUNT], rem)
845                         jail->argc += 2;
846                 instance_fill_array(&jail->mount, tb[JAIL_ATTR_MOUNT], NULL, false);
847         }
848         if (in->seccomp)
849                 jail->argc += 2;
850
851         if (in->user)
852                 jail->argc += 2;
853
854         if (in->group)
855                 jail->argc += 2;
856
857         if (in->no_new_privs)
858                 jail->argc++;
859
860         return 1;
861 }
862
863 static bool
864 instance_config_parse_command(struct service_instance *in, struct blob_attr **tb)
865 {
866         struct blob_attr *cur, *cur2;
867         bool ret = false;
868         int rem;
869
870         cur = tb[INSTANCE_ATTR_COMMAND];
871         if (!cur) {
872                 in->command = NULL;
873                 return true;
874         }
875
876         if (!blobmsg_check_attr_list(cur, BLOBMSG_TYPE_STRING))
877                 return false;
878
879         blobmsg_for_each_attr(cur2, cur, rem) {
880                 ret = true;
881                 break;
882         }
883
884         in->command = cur;
885         return ret;
886 }
887
888 static bool
889 instance_config_parse(struct service_instance *in)
890 {
891         struct blob_attr *tb[__INSTANCE_ATTR_MAX];
892         struct blob_attr *cur, *cur2;
893         int rem;
894
895         blobmsg_parse(instance_attr, __INSTANCE_ATTR_MAX, tb,
896                 blobmsg_data(in->config), blobmsg_data_len(in->config));
897
898         if (!instance_config_parse_command(in, tb))
899                 return false;
900
901         if (tb[INSTANCE_ATTR_TERMTIMEOUT])
902                 in->term_timeout = blobmsg_get_u32(tb[INSTANCE_ATTR_TERMTIMEOUT]);
903         if (tb[INSTANCE_ATTR_RESPAWN]) {
904                 int i = 0;
905                 uint32_t vals[3] = { 3600, 5, 5};
906
907                 blobmsg_for_each_attr(cur2, tb[INSTANCE_ATTR_RESPAWN], rem) {
908                         if ((i >= 3) && (blobmsg_type(cur2) == BLOBMSG_TYPE_STRING))
909                                 continue;
910                         vals[i] = atoi(blobmsg_get_string(cur2));
911                         i++;
912                 }
913                 in->respawn = true;
914                 in->respawn_count = 0;
915                 in->respawn_threshold = vals[0];
916                 in->respawn_timeout = vals[1];
917                 in->respawn_retry = vals[2];
918         }
919         if (tb[INSTANCE_ATTR_TRIGGER]) {
920                 in->trigger = tb[INSTANCE_ATTR_TRIGGER];
921                 trigger_add(in->trigger, in);
922         }
923
924         if (tb[INSTANCE_ATTR_WATCH]) {
925                 blobmsg_for_each_attr(cur2, tb[INSTANCE_ATTR_WATCH], rem) {
926                         if (blobmsg_type(cur2) != BLOBMSG_TYPE_STRING)
927                                 continue;
928                         DEBUG(3, "watch for %s\n", blobmsg_get_string(cur2));
929                         watch_add(blobmsg_get_string(cur2), in);
930                 }
931         }
932
933         if ((cur = tb[INSTANCE_ATTR_NICE])) {
934                 in->nice = (int8_t) blobmsg_get_u32(cur);
935                 if (in->nice < -20 || in->nice > 20)
936                         return false;
937         }
938
939         if (tb[INSTANCE_ATTR_USER]) {
940                 const char *user = blobmsg_get_string(tb[INSTANCE_ATTR_USER]);
941                 struct passwd *p = getpwnam(user);
942                 if (p) {
943                         in->user = strdup(user);
944                         in->uid = p->pw_uid;
945                         in->gr_gid = in->pw_gid = p->pw_gid;
946                 }
947         }
948
949         if (tb[INSTANCE_ATTR_GROUP]) {
950                 const char *group = blobmsg_get_string(tb[INSTANCE_ATTR_GROUP]);
951                 struct group *p = getgrnam(group);
952                 if (p) {
953                         in->group = strdup(group);
954                         in->gr_gid = p->gr_gid;
955                 }
956         }
957
958         if (tb[INSTANCE_ATTR_TRACE])
959                 in->trace = blobmsg_get_bool(tb[INSTANCE_ATTR_TRACE]);
960
961         if (tb[INSTANCE_ATTR_NO_NEW_PRIVS])
962                 in->no_new_privs = blobmsg_get_bool(tb[INSTANCE_ATTR_NO_NEW_PRIVS]);
963
964         if (!in->trace && tb[INSTANCE_ATTR_SECCOMP])
965                 in->seccomp = strdup(blobmsg_get_string(tb[INSTANCE_ATTR_SECCOMP]));
966
967         if (tb[INSTANCE_ATTR_PIDFILE]) {
968                 char *pidfile = blobmsg_get_string(tb[INSTANCE_ATTR_PIDFILE]);
969                 if (pidfile)
970                         in->pidfile = strdup(pidfile);
971         }
972
973         if (tb[INSTANCE_ATTR_RELOADSIG])
974                 in->reload_signal = blobmsg_get_u32(tb[INSTANCE_ATTR_RELOADSIG]);
975
976         if (!in->trace && tb[INSTANCE_ATTR_JAIL])
977                 in->has_jail = instance_jail_parse(in, tb[INSTANCE_ATTR_JAIL]);
978
979         if (tb[INSTANCE_ATTR_STDOUT] && blobmsg_get_bool(tb[INSTANCE_ATTR_STDOUT]))
980                 in->_stdout.fd.fd = -1;
981
982         if (tb[INSTANCE_ATTR_STDERR] && blobmsg_get_bool(tb[INSTANCE_ATTR_STDERR]))
983                 in->_stderr.fd.fd = -1;
984
985         instance_fill_any(&in->data, tb[INSTANCE_ATTR_DATA]);
986
987         if (!instance_fill_array(&in->env, tb[INSTANCE_ATTR_ENV], NULL, false))
988                 return false;
989
990         if (!instance_fill_array(&in->netdev, tb[INSTANCE_ATTR_NETDEV], instance_netdev_update, true))
991                 return false;
992
993         if (!instance_fill_array(&in->file, tb[INSTANCE_ATTR_FILE], instance_file_update, true))
994                 return false;
995
996         if (!instance_fill_array(&in->limits, tb[INSTANCE_ATTR_LIMITS], NULL, false))
997                 return false;
998
999         if (!instance_fill_array(&in->errors, tb[INSTANCE_ATTR_ERROR], NULL, true))
1000                 return false;
1001
1002         if (tb[INSTANCE_ATTR_FACILITY]) {
1003                 int facility = syslog_facility_str_to_int(blobmsg_get_string(tb[INSTANCE_ATTR_FACILITY]));
1004                 if (facility != -1) {
1005                         in->syslog_facility = facility;
1006                         DEBUG(3, "setting facility '%s'\n", blobmsg_get_string(tb[INSTANCE_ATTR_FACILITY]));
1007                 } else
1008                         DEBUG(3, "unknown syslog facility '%s' given, using default (LOG_DAEMON)\n", blobmsg_get_string(tb[INSTANCE_ATTR_FACILITY]));
1009         }
1010
1011         return true;
1012 }
1013
1014 static void
1015 instance_config_cleanup(struct service_instance *in)
1016 {
1017         blobmsg_list_free(&in->env);
1018         blobmsg_list_free(&in->data);
1019         blobmsg_list_free(&in->netdev);
1020         blobmsg_list_free(&in->file);
1021         blobmsg_list_free(&in->limits);
1022         blobmsg_list_free(&in->errors);
1023         blobmsg_list_free(&in->jail.mount);
1024 }
1025
1026 static void
1027 instance_config_move_strdup(char **dst, char *src)
1028 {
1029         if (*dst) {
1030                 free(*dst);
1031                 *dst = NULL;
1032         }
1033
1034         if (!src)
1035                 return;
1036
1037         *dst = strdup(src);
1038 }
1039
1040 static void
1041 instance_config_move(struct service_instance *in, struct service_instance *in_src)
1042 {
1043         instance_config_cleanup(in);
1044         blobmsg_list_move(&in->env, &in_src->env);
1045         blobmsg_list_move(&in->data, &in_src->data);
1046         blobmsg_list_move(&in->netdev, &in_src->netdev);
1047         blobmsg_list_move(&in->file, &in_src->file);
1048         blobmsg_list_move(&in->limits, &in_src->limits);
1049         blobmsg_list_move(&in->errors, &in_src->errors);
1050         blobmsg_list_move(&in->jail.mount, &in_src->jail.mount);
1051         in->trigger = in_src->trigger;
1052         in->command = in_src->command;
1053         in->respawn = in_src->respawn;
1054         in->respawn_retry = in_src->respawn_retry;
1055         in->respawn_threshold = in_src->respawn_threshold;
1056         in->respawn_timeout = in_src->respawn_timeout;
1057         in->name = in_src->name;
1058         in->trace = in_src->trace;
1059         in->node.avl.key = in_src->node.avl.key;
1060         in->syslog_facility = in_src->syslog_facility;
1061
1062         instance_config_move_strdup(&in->pidfile, in_src->pidfile);
1063         instance_config_move_strdup(&in->seccomp, in_src->seccomp);
1064         instance_config_move_strdup(&in->jail.name, in_src->jail.name);
1065         instance_config_move_strdup(&in->jail.hostname, in_src->jail.hostname);
1066
1067         free(in->config);
1068         in->config = in_src->config;
1069         in_src->config = NULL;
1070 }
1071
1072 void
1073 instance_update(struct service_instance *in, struct service_instance *in_new)
1074 {
1075         bool changed = instance_config_changed(in, in_new);
1076         bool running = in->proc.pending;
1077         bool stopping = in->halt;
1078
1079         if (!running || stopping) {
1080                 instance_config_move(in, in_new);
1081                 instance_start(in);
1082         } else {
1083                 if (changed)
1084                         instance_restart(in);
1085                 instance_config_move(in, in_new);
1086                 /* restart happens in the child callback handler */
1087         }
1088 }
1089
1090 void
1091 instance_free(struct service_instance *in)
1092 {
1093         instance_free_stdio(in);
1094         uloop_process_delete(&in->proc);
1095         uloop_timeout_cancel(&in->timeout);
1096         trigger_del(in);
1097         watch_del(in);
1098         instance_config_cleanup(in);
1099         free(in->config);
1100         free(in->user);
1101         free(in->group);
1102         free(in->jail.name);
1103         free(in->jail.hostname);
1104         free(in->seccomp);
1105         free(in->pidfile);
1106         free(in);
1107 }
1108
1109 void
1110 instance_init(struct service_instance *in, struct service *s, struct blob_attr *config)
1111 {
1112         config = blob_memdup(config);
1113         in->srv = s;
1114         in->name = blobmsg_name(config);
1115         in->config = config;
1116         in->timeout.cb = instance_timeout;
1117         in->proc.cb = instance_exit;
1118         in->term_timeout = 5;
1119         in->syslog_facility = LOG_DAEMON;
1120
1121         in->_stdout.fd.fd = -2;
1122         in->_stdout.stream.string_data = true;
1123         in->_stdout.stream.notify_read = instance_stdout;
1124
1125         in->_stderr.fd.fd = -2;
1126         in->_stderr.stream.string_data = true;
1127         in->_stderr.stream.notify_read = instance_stderr;
1128
1129         blobmsg_list_init(&in->netdev, struct instance_netdev, node, instance_netdev_cmp);
1130         blobmsg_list_init(&in->file, struct instance_file, node, instance_file_cmp);
1131         blobmsg_list_simple_init(&in->env);
1132         blobmsg_list_simple_init(&in->data);
1133         blobmsg_list_simple_init(&in->limits);
1134         blobmsg_list_simple_init(&in->errors);
1135         blobmsg_list_simple_init(&in->jail.mount);
1136         in->valid = instance_config_parse(in);
1137 }
1138
1139 void instance_dump(struct blob_buf *b, struct service_instance *in, int verbose)
1140 {
1141         void *i;
1142
1143         if (!in->valid)
1144                 return;
1145
1146         i = blobmsg_open_table(b, in->name);
1147         blobmsg_add_u8(b, "running", in->proc.pending);
1148         if (in->proc.pending)
1149                 blobmsg_add_u32(b, "pid", in->proc.pid);
1150         if (in->command)
1151                 blobmsg_add_blob(b, in->command);
1152         blobmsg_add_u32(b, "term_timeout", in->term_timeout);
1153
1154         if (!avl_is_empty(&in->errors.avl)) {
1155                 struct blobmsg_list_node *var;
1156                 void *e = blobmsg_open_array(b, "errors");
1157                 blobmsg_list_for_each(&in->errors, var)
1158                         blobmsg_add_string(b, NULL, blobmsg_data(var->data));
1159                 blobmsg_close_table(b, e);
1160         }
1161
1162         if (!avl_is_empty(&in->env.avl)) {
1163                 struct blobmsg_list_node *var;
1164                 void *e = blobmsg_open_table(b, "env");
1165                 blobmsg_list_for_each(&in->env, var)
1166                         blobmsg_add_string(b, blobmsg_name(var->data), blobmsg_data(var->data));
1167                 blobmsg_close_table(b, e);
1168         }
1169
1170         if (!avl_is_empty(&in->data.avl)) {
1171                 struct blobmsg_list_node *var;
1172                 void *e = blobmsg_open_table(b, "data");
1173                 blobmsg_list_for_each(&in->data, var)
1174                         blobmsg_add_blob(b, var->data);
1175                 blobmsg_close_table(b, e);
1176         }
1177
1178         if (!avl_is_empty(&in->limits.avl)) {
1179                 struct blobmsg_list_node *var;
1180                 void *e = blobmsg_open_table(b, "limits");
1181                 blobmsg_list_for_each(&in->limits, var)
1182                         blobmsg_add_string(b, blobmsg_name(var->data), blobmsg_data(var->data));
1183                 blobmsg_close_table(b, e);
1184         }
1185
1186         if (in->reload_signal)
1187                 blobmsg_add_u32(b, "reload_signal", in->reload_signal);
1188
1189         if (in->respawn) {
1190                 void *r = blobmsg_open_table(b, "respawn");
1191                 blobmsg_add_u32(b, "threshold", in->respawn_threshold);
1192                 blobmsg_add_u32(b, "timeout", in->respawn_timeout);
1193                 blobmsg_add_u32(b, "retry", in->respawn_retry);
1194                 blobmsg_close_table(b, r);
1195         }
1196
1197         if (in->trace)
1198                 blobmsg_add_u8(b, "trace", true);
1199
1200         if (in->no_new_privs)
1201                 blobmsg_add_u8(b, "no_new_privs", true);
1202
1203         if (in->seccomp)
1204                 blobmsg_add_string(b, "seccomp", in->seccomp);
1205
1206         if (in->pidfile)
1207                 blobmsg_add_string(b, "pidfile", in->pidfile);
1208
1209         if (in->user)
1210                 blobmsg_add_string(b, "user", in->user);
1211
1212         if (in->group)
1213                 blobmsg_add_string(b, "group", in->group);
1214
1215         if (in->has_jail) {
1216                 void *r = blobmsg_open_table(b, "jail");
1217                 if (in->jail.name)
1218                         blobmsg_add_string(b, "name", in->jail.name);
1219                 if (in->jail.hostname)
1220                         blobmsg_add_string(b, "hostname", in->jail.hostname);
1221                 blobmsg_add_u8(b, "procfs", in->jail.procfs);
1222                 blobmsg_add_u8(b, "sysfs", in->jail.sysfs);
1223                 blobmsg_add_u8(b, "ubus", in->jail.ubus);
1224                 blobmsg_add_u8(b, "log", in->jail.log);
1225                 blobmsg_add_u8(b, "ronly", in->jail.ronly);
1226                 blobmsg_close_table(b, r);
1227                 if (!avl_is_empty(&in->jail.mount.avl)) {
1228                         struct blobmsg_list_node *var;
1229                         void *e = blobmsg_open_table(b, "mount");
1230                         blobmsg_list_for_each(&in->jail.mount, var)
1231                                 blobmsg_add_string(b, blobmsg_name(var->data), blobmsg_data(var->data));
1232                         blobmsg_close_table(b, e);
1233                 }
1234         }
1235
1236         if (verbose && in->trigger)
1237                 blobmsg_add_blob(b, in->trigger);
1238
1239         blobmsg_close_table(b, i);
1240 }