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