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