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