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