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