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