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