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