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