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