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