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