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