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