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