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