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