system: add diskfree infos to ubus
[project/procd.git] / system.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 #include <sys/utsname.h>
16 #ifdef linux
17 #include <sys/sysinfo.h>
18 #endif
19 #include <sys/ioctl.h>
20 #include <sys/types.h>
21 #include <sys/reboot.h>
22 #include <sys/stat.h>
23 #include <sys/statvfs.h>
24 #include <fcntl.h>
25 #include <signal.h>
26 #include <unistd.h>
27 #include <stdlib.h>
28
29 #include <json-c/json_tokener.h>
30 #include <libubox/blobmsg_json.h>
31 #include <libubox/uloop.h>
32
33 #include "procd.h"
34 #include "sysupgrade.h"
35 #include "watchdog.h"
36
37 static struct blob_buf b;
38 static int notify;
39 static struct ubus_context *_ctx;
40 static int initramfs;
41
42 enum vjson_state {
43 VJSON_ERROR,
44 VJSON_CONTINUE,
45 VJSON_SUCCESS,
46 };
47
48 static const char *system_rootfs_type(void) {
49 const char proc_mounts[] = "/proc/self/mounts";
50 static char fstype[16] = { 0 };
51 char *mountstr = NULL, *mp = "/", *pos, *tmp;
52 FILE *mounts;
53 ssize_t nread;
54 size_t len = 0;
55 bool found;
56
57 if (initramfs)
58 return "initramfs";
59
60 if (fstype[0])
61 return fstype;
62
63 mounts = fopen(proc_mounts, "r");
64 if (!mounts)
65 return NULL;
66
67 while ((nread = getline(&mountstr, &len, mounts)) != -1) {
68 found = false;
69
70 pos = strchr(mountstr, ' ');
71 if (!pos)
72 continue;
73
74 tmp = pos + 1;
75 pos = strchr(tmp, ' ');
76 if (!pos)
77 continue;
78
79 *pos = '\0';
80 if (strcmp(tmp, mp))
81 continue;
82
83 tmp = pos + 1;
84 pos = strchr(tmp, ' ');
85 if (!pos)
86 continue;
87
88 *pos = '\0';
89
90 if (!strcmp(tmp, "overlay")) {
91 /*
92 * there is no point in parsing overlay option string for
93 * lowerdir, as that can point to "/" being a previous
94 * overlay mount (after firstboot or sysuprade config
95 * restore). Hence just assume the lowerdir is "/rom" and
96 * restart searching for that instead.
97 */
98 mp = "/rom";
99 fseek(mounts, 0, SEEK_SET);
100 continue;
101 }
102
103 found = true;
104 break;
105 }
106
107 if (found)
108 strncpy(fstype, tmp, sizeof(fstype) - 1);
109
110 fstype[sizeof(fstype) - 1]= '\0';
111 free(mountstr);
112 fclose(mounts);
113
114 if (found)
115 return fstype;
116 else
117 return NULL;
118 }
119
120 static int system_board(struct ubus_context *ctx, struct ubus_object *obj,
121 struct ubus_request_data *req, const char *method,
122 struct blob_attr *msg)
123 {
124 void *c;
125 char line[256];
126 char *key, *val, *next;
127 const char *rootfs_type = system_rootfs_type();
128 struct utsname utsname;
129 FILE *f;
130
131 blob_buf_init(&b, 0);
132
133 if (uname(&utsname) >= 0)
134 {
135 blobmsg_add_string(&b, "kernel", utsname.release);
136 blobmsg_add_string(&b, "hostname", utsname.nodename);
137 }
138
139 if ((f = fopen("/proc/cpuinfo", "r")) != NULL)
140 {
141 while(fgets(line, sizeof(line), f))
142 {
143 key = strtok(line, "\t:");
144 val = strtok(NULL, "\t\n");
145
146 if (!key || !val)
147 continue;
148
149 #ifdef __aarch64__
150 if (!strcasecmp(key, "CPU revision")) {
151 snprintf(line, sizeof(line), "ARMv8 Processor rev %lu", strtoul(val + 2, NULL, 16));
152 blobmsg_add_string(&b, "system", line);
153 break;
154 }
155 #else
156 if (!strcasecmp(key, "system type") ||
157 !strcasecmp(key, "processor") ||
158 !strcasecmp(key, "cpu") ||
159 !strcasecmp(key, "model name"))
160 {
161 strtoul(val + 2, &key, 0);
162
163 if (key == (val + 2) || *key != 0)
164 {
165 blobmsg_add_string(&b, "system", val + 2);
166 break;
167 }
168 }
169 #endif
170 }
171
172 fclose(f);
173 }
174
175 if ((f = fopen("/tmp/sysinfo/model", "r")) != NULL ||
176 (f = fopen("/proc/device-tree/model", "r")) != NULL)
177 {
178 if (fgets(line, sizeof(line), f))
179 {
180 val = strtok(line, "\t\n");
181
182 if (val)
183 blobmsg_add_string(&b, "model", val);
184 }
185
186 fclose(f);
187 }
188 else if ((f = fopen("/proc/cpuinfo", "r")) != NULL)
189 {
190 while(fgets(line, sizeof(line), f))
191 {
192 key = strtok(line, "\t:");
193 val = strtok(NULL, "\t\n");
194
195 if (!key || !val)
196 continue;
197
198 if (!strcasecmp(key, "machine") ||
199 !strcasecmp(key, "hardware"))
200 {
201 blobmsg_add_string(&b, "model", val + 2);
202 break;
203 }
204 }
205
206 fclose(f);
207 }
208
209 if ((f = fopen("/tmp/sysinfo/board_name", "r")) != NULL)
210 {
211 if (fgets(line, sizeof(line), f))
212 {
213 val = strtok(line, "\t\n");
214
215 if (val)
216 blobmsg_add_string(&b, "board_name", val);
217 }
218
219 fclose(f);
220 }
221 else if ((f = fopen("/proc/device-tree/compatible", "r")) != NULL)
222 {
223 if (fgets(line, sizeof(line), f))
224 {
225 val = strtok(line, "\t\n");
226
227 if (val)
228 {
229 next = val;
230 while ((next = strchr(next, ',')) != NULL)
231 {
232 *next = '-';
233 next++;
234 }
235
236 blobmsg_add_string(&b, "board_name", val);
237 }
238 }
239
240 fclose(f);
241 }
242
243 if (rootfs_type)
244 blobmsg_add_string(&b, "rootfs_type", rootfs_type);
245
246 if ((f = fopen("/etc/openwrt_release", "r")) != NULL)
247 {
248 c = blobmsg_open_table(&b, "release");
249
250 while (fgets(line, sizeof(line), f))
251 {
252 char *dest;
253 char ch;
254
255 key = line;
256 val = strchr(line, '=');
257 if (!val)
258 continue;
259
260 *(val++) = 0;
261
262 if (!strcasecmp(key, "DISTRIB_ID"))
263 key = "distribution";
264 else if (!strcasecmp(key, "DISTRIB_RELEASE"))
265 key = "version";
266 else if (!strcasecmp(key, "DISTRIB_REVISION"))
267 key = "revision";
268 else if (!strcasecmp(key, "DISTRIB_CODENAME"))
269 key = "codename";
270 else if (!strcasecmp(key, "DISTRIB_TARGET"))
271 key = "target";
272 else if (!strcasecmp(key, "DISTRIB_DESCRIPTION"))
273 key = "description";
274 else
275 continue;
276
277 dest = blobmsg_alloc_string_buffer(&b, key, strlen(val));
278 if (!dest) {
279 ERROR("Failed to allocate blob.\n");
280 continue;
281 }
282
283 while (val && (ch = *(val++)) != 0) {
284 switch (ch) {
285 case '\'':
286 case '"':
287 next = strchr(val, ch);
288 if (next)
289 *next = 0;
290
291 strcpy(dest, val);
292
293 if (next)
294 val = next + 1;
295
296 dest += strlen(dest);
297 break;
298 case '\\':
299 *(dest++) = *(val++);
300 break;
301 }
302 }
303 blobmsg_add_string_buffer(&b);
304 }
305
306 blobmsg_close_array(&b, c);
307
308 fclose(f);
309 }
310
311 ubus_send_reply(ctx, req, b.head);
312
313 return UBUS_STATUS_OK;
314 }
315
316 static unsigned long
317 kscale(unsigned long b, unsigned long bs)
318 {
319 return (b * (unsigned long long) bs + 1024/2) / 1024;
320 }
321
322 static int system_info(struct ubus_context *ctx, struct ubus_object *obj,
323 struct ubus_request_data *req, const char *method,
324 struct blob_attr *msg)
325 {
326 time_t now;
327 struct tm *tm;
328 #ifdef linux
329 struct sysinfo info;
330 void *c;
331 char line[256];
332 char *key, *val;
333 unsigned long long available, cached;
334 FILE *f;
335 int i;
336 struct statvfs s;
337 const char *fslist[] = {
338 "/", "root",
339 "/tmp", "tmp",
340 };
341
342 if (sysinfo(&info))
343 return UBUS_STATUS_UNKNOWN_ERROR;
344
345 if ((f = fopen("/proc/meminfo", "r")) == NULL)
346 return UBUS_STATUS_UNKNOWN_ERROR;
347
348 /* if linux < 3.14 MemAvailable is not in meminfo */
349 available = 0;
350 cached = 0;
351
352 while (fgets(line, sizeof(line), f))
353 {
354 key = strtok(line, " :");
355 val = strtok(NULL, " ");
356
357 if (!key || !val)
358 continue;
359
360 if (!strcasecmp(key, "MemAvailable"))
361 available = 1024 * atoll(val);
362 else if (!strcasecmp(key, "Cached"))
363 cached = 1024 * atoll(val);
364 }
365
366 fclose(f);
367 #endif
368
369 now = time(NULL);
370
371 if (!(tm = localtime(&now)))
372 return UBUS_STATUS_UNKNOWN_ERROR;
373
374 blob_buf_init(&b, 0);
375
376 blobmsg_add_u32(&b, "localtime", now + tm->tm_gmtoff);
377
378 #ifdef linux
379 blobmsg_add_u32(&b, "uptime", info.uptime);
380
381 c = blobmsg_open_array(&b, "load");
382 blobmsg_add_u32(&b, NULL, info.loads[0]);
383 blobmsg_add_u32(&b, NULL, info.loads[1]);
384 blobmsg_add_u32(&b, NULL, info.loads[2]);
385 blobmsg_close_array(&b, c);
386
387 c = blobmsg_open_table(&b, "memory");
388 blobmsg_add_u64(&b, "total",
389 (uint64_t)info.mem_unit * (uint64_t)info.totalram);
390 blobmsg_add_u64(&b, "free",
391 (uint64_t)info.mem_unit * (uint64_t)info.freeram);
392 blobmsg_add_u64(&b, "shared",
393 (uint64_t)info.mem_unit * (uint64_t)info.sharedram);
394 blobmsg_add_u64(&b, "buffered",
395 (uint64_t)info.mem_unit * (uint64_t)info.bufferram);
396 blobmsg_add_u64(&b, "available", available);
397 blobmsg_add_u64(&b, "cached", cached);
398 blobmsg_close_table(&b, c);
399
400 for (i = 0; i < sizeof(fslist) / sizeof(fslist[0]); i += 2) {
401 if (statvfs(fslist[i], &s))
402 continue;
403
404 c = blobmsg_open_table(&b, fslist[i+1]);
405
406 if (!s.f_frsize)
407 s.f_frsize = s.f_bsize;
408
409 blobmsg_add_u64(&b, "total", kscale(s.f_blocks, s.f_frsize));
410 blobmsg_add_u64(&b, "free", kscale(s.f_bfree, s.f_frsize));
411 blobmsg_add_u64(&b, "used", kscale(s.f_blocks - s.f_bfree, s.f_frsize));
412 blobmsg_add_u64(&b, "avail", kscale(s.f_bavail, s.f_frsize));
413
414 blobmsg_close_table(&b, c);
415 }
416
417 c = blobmsg_open_table(&b, "swap");
418 blobmsg_add_u64(&b, "total",
419 (uint64_t)info.mem_unit * (uint64_t)info.totalswap);
420 blobmsg_add_u64(&b, "free",
421 (uint64_t)info.mem_unit * (uint64_t)info.freeswap);
422 blobmsg_close_table(&b, c);
423 #endif
424
425 ubus_send_reply(ctx, req, b.head);
426
427 return UBUS_STATUS_OK;
428 }
429
430 static int system_reboot(struct ubus_context *ctx, struct ubus_object *obj,
431 struct ubus_request_data *req, const char *method,
432 struct blob_attr *msg)
433 {
434 procd_shutdown(RB_AUTOBOOT);
435 return 0;
436 }
437
438 enum {
439 WDT_FREQUENCY,
440 WDT_TIMEOUT,
441 WDT_MAGICCLOSE,
442 WDT_STOP,
443 __WDT_MAX
444 };
445
446 static const struct blobmsg_policy watchdog_policy[__WDT_MAX] = {
447 [WDT_FREQUENCY] = { .name = "frequency", .type = BLOBMSG_TYPE_INT32 },
448 [WDT_TIMEOUT] = { .name = "timeout", .type = BLOBMSG_TYPE_INT32 },
449 [WDT_MAGICCLOSE] = { .name = "magicclose", .type = BLOBMSG_TYPE_BOOL },
450 [WDT_STOP] = { .name = "stop", .type = BLOBMSG_TYPE_BOOL },
451 };
452
453 static int watchdog_set(struct ubus_context *ctx, struct ubus_object *obj,
454 struct ubus_request_data *req, const char *method,
455 struct blob_attr *msg)
456 {
457 struct blob_attr *tb[__WDT_MAX];
458 const char *status;
459
460 if (!msg)
461 return UBUS_STATUS_INVALID_ARGUMENT;
462
463 blobmsg_parse(watchdog_policy, __WDT_MAX, tb, blob_data(msg), blob_len(msg));
464 if (tb[WDT_FREQUENCY]) {
465 unsigned int timeout = tb[WDT_TIMEOUT] ? blobmsg_get_u32(tb[WDT_TIMEOUT]) :
466 watchdog_timeout(0);
467 unsigned int freq = blobmsg_get_u32(tb[WDT_FREQUENCY]);
468
469 if (freq) {
470 if (freq > timeout / 2)
471 freq = timeout / 2;
472 watchdog_frequency(freq);
473 }
474 }
475
476 if (tb[WDT_TIMEOUT]) {
477 unsigned int timeout = blobmsg_get_u32(tb[WDT_TIMEOUT]);
478 unsigned int frequency = watchdog_frequency(0);
479
480 if (timeout <= frequency)
481 timeout = frequency * 2;
482 watchdog_timeout(timeout);
483 }
484
485 if (tb[WDT_MAGICCLOSE])
486 watchdog_set_magicclose(blobmsg_get_bool(tb[WDT_MAGICCLOSE]));
487
488 if (tb[WDT_STOP])
489 watchdog_set_stopped(blobmsg_get_bool(tb[WDT_STOP]));
490
491 if (watchdog_fd() == NULL)
492 status = "offline";
493 else if (watchdog_get_stopped())
494 status = "stopped";
495 else
496 status = "running";
497
498 blob_buf_init(&b, 0);
499 blobmsg_add_string(&b, "status", status);
500 blobmsg_add_u32(&b, "timeout", watchdog_timeout(0));
501 blobmsg_add_u32(&b, "frequency", watchdog_frequency(0));
502 blobmsg_add_u8(&b, "magicclose", watchdog_get_magicclose());
503 ubus_send_reply(ctx, req, b.head);
504
505 return 0;
506 }
507
508 enum {
509 SIGNAL_PID,
510 SIGNAL_NUM,
511 __SIGNAL_MAX
512 };
513
514 static const struct blobmsg_policy signal_policy[__SIGNAL_MAX] = {
515 [SIGNAL_PID] = { .name = "pid", .type = BLOBMSG_TYPE_INT32 },
516 [SIGNAL_NUM] = { .name = "signum", .type = BLOBMSG_TYPE_INT32 },
517 };
518
519 static int proc_signal(struct ubus_context *ctx, struct ubus_object *obj,
520 struct ubus_request_data *req, const char *method,
521 struct blob_attr *msg)
522 {
523 struct blob_attr *tb[__SIGNAL_MAX];
524
525 if (!msg)
526 return UBUS_STATUS_INVALID_ARGUMENT;
527
528 blobmsg_parse(signal_policy, __SIGNAL_MAX, tb, blob_data(msg), blob_len(msg));
529 if (!tb[SIGNAL_PID || !tb[SIGNAL_NUM]])
530 return UBUS_STATUS_INVALID_ARGUMENT;
531
532 kill(blobmsg_get_u32(tb[SIGNAL_PID]), blobmsg_get_u32(tb[SIGNAL_NUM]));
533
534 return 0;
535 }
536
537 __attribute__((format (printf, 2, 3)))
538 static enum vjson_state vjson_error(char **b, const char *fmt, ...)
539 {
540 static char buf[256] = { 0 };
541 const char *pfx = "Firmware image couldn't be validated: ";
542 va_list va;
543 int r;
544
545 r = snprintf(buf, sizeof(buf), "%s", pfx);
546 if (r < 0) {
547 *b = "vjson_error() snprintf failed";
548 return VJSON_ERROR;
549 }
550
551 va_start(va, fmt);
552 r = vsnprintf(buf+r, sizeof(buf)-r, fmt, va);
553 if (r < 0) {
554 *b = "vjson_error() vsnprintf failed";
555 return VJSON_ERROR;
556 }
557 va_end(va);
558
559 *b = buf;
560 return VJSON_ERROR;
561 }
562
563 static enum vjson_state vjson_parse_token(json_tokener *tok, char *buf, ssize_t len, char **err)
564 {
565 json_object *jsobj = NULL;
566
567 jsobj = json_tokener_parse_ex(tok, buf, len);
568 if (json_tokener_get_error(tok) == json_tokener_continue)
569 return VJSON_CONTINUE;
570
571 if (json_tokener_get_error(tok) == json_tokener_success) {
572 if (json_object_get_type(jsobj) != json_type_object) {
573 json_object_put(jsobj);
574 return vjson_error(err, "result is not an JSON object");
575 }
576
577 blobmsg_add_object(&b, jsobj);
578 json_object_put(jsobj);
579 return VJSON_SUCCESS;
580 }
581
582 return vjson_error(err, "failed to parse JSON: %s (%d)",
583 json_tokener_error_desc(json_tokener_get_error(tok)),
584 json_tokener_get_error(tok));
585 }
586
587 static enum vjson_state vjson_parse(int fd, char **err)
588 {
589 enum vjson_state r = VJSON_ERROR;
590 size_t read_count = 0;
591 char buf[64] = { 0 };
592 json_tokener *tok;
593 ssize_t len;
594 int _errno;
595
596 tok = json_tokener_new();
597 if (!tok)
598 return vjson_error(err, "json_tokener_new() failed");
599
600 vjson_error(err, "incomplete JSON input");
601
602 while ((len = read(fd, buf, sizeof(buf)))) {
603 if (len < 0 && errno == EINTR)
604 continue;
605
606 if (len < 0) {
607 _errno = errno;
608 json_tokener_free(tok);
609 return vjson_error(err, "read() failed: %s (%d)",
610 strerror(_errno), _errno);
611 }
612
613 read_count += len;
614 r = vjson_parse_token(tok, buf, len, err);
615 if (r != VJSON_CONTINUE)
616 break;
617
618 memset(buf, 0, sizeof(buf));
619 }
620
621 if (read_count == 0)
622 vjson_error(err, "no JSON input");
623
624 json_tokener_free(tok);
625 return r;
626 }
627
628 /**
629 * validate_firmware_image_call - perform validation & store result in global b
630 *
631 * @file: firmware image path
632 */
633 static enum vjson_state validate_firmware_image_call(const char *file, char **err)
634 {
635 const char *path = "/usr/libexec/validate_firmware_image";
636 enum vjson_state ret = VJSON_ERROR;
637 int _errno;
638 int fds[2];
639 int fd;
640
641 blob_buf_init(&b, 0);
642 vjson_error(err, "unhandled error");
643
644 if (pipe(fds)) {
645 _errno = errno;
646 return vjson_error(err, "pipe() failed: %s (%d)",
647 strerror(_errno), _errno);
648 }
649
650 switch (fork()) {
651 case -1:
652 _errno = errno;
653
654 close(fds[0]);
655 close(fds[1]);
656
657 return vjson_error(err, "fork() failed: %s (%d)",
658 strerror(_errno), _errno);
659 case 0:
660 /* Set stdin & stderr to /dev/null */
661 fd = open("/dev/null", O_RDWR);
662 if (fd >= 0) {
663 dup2(fd, 0);
664 dup2(fd, 2);
665 close(fd);
666 }
667
668 /* Set stdout to the shared pipe */
669 dup2(fds[1], 1);
670 close(fds[0]);
671 close(fds[1]);
672
673 execl(path, path, file, NULL);
674 exit(errno);
675 }
676
677 /* Parent process */
678 close(fds[1]);
679
680 ret = vjson_parse(fds[0], err);
681 close(fds[0]);
682
683 return ret;
684 }
685
686 enum {
687 VALIDATE_FIRMWARE_IMAGE_PATH,
688 __VALIDATE_FIRMWARE_IMAGE_MAX,
689 };
690
691 static const struct blobmsg_policy validate_firmware_image_policy[__VALIDATE_FIRMWARE_IMAGE_MAX] = {
692 [VALIDATE_FIRMWARE_IMAGE_PATH] = { .name = "path", .type = BLOBMSG_TYPE_STRING },
693 };
694
695 static int validate_firmware_image(struct ubus_context *ctx,
696 struct ubus_object *obj,
697 struct ubus_request_data *req,
698 const char *method, struct blob_attr *msg)
699 {
700 struct blob_attr *tb[__VALIDATE_FIRMWARE_IMAGE_MAX];
701 enum vjson_state ret = VJSON_ERROR;
702 char *err;
703
704 if (!msg)
705 return UBUS_STATUS_INVALID_ARGUMENT;
706
707 blobmsg_parse(validate_firmware_image_policy, __VALIDATE_FIRMWARE_IMAGE_MAX, tb, blob_data(msg), blob_len(msg));
708 if (!tb[VALIDATE_FIRMWARE_IMAGE_PATH])
709 return UBUS_STATUS_INVALID_ARGUMENT;
710
711 ret = validate_firmware_image_call(blobmsg_get_string(tb[VALIDATE_FIRMWARE_IMAGE_PATH]), &err);
712 if (ret != VJSON_SUCCESS)
713 return UBUS_STATUS_UNKNOWN_ERROR;
714
715 ubus_send_reply(ctx, req, b.head);
716
717 return UBUS_STATUS_OK;
718 }
719
720 enum {
721 SYSUPGRADE_PATH,
722 SYSUPGRADE_FORCE,
723 SYSUPGRADE_BACKUP,
724 SYSUPGRADE_PREFIX,
725 SYSUPGRADE_COMMAND,
726 SYSUPGRADE_OPTIONS,
727 __SYSUPGRADE_MAX
728 };
729
730 static const struct blobmsg_policy sysupgrade_policy[__SYSUPGRADE_MAX] = {
731 [SYSUPGRADE_PATH] = { .name = "path", .type = BLOBMSG_TYPE_STRING },
732 [SYSUPGRADE_FORCE] = { .name = "force", .type = BLOBMSG_TYPE_BOOL },
733 [SYSUPGRADE_BACKUP] = { .name = "backup", .type = BLOBMSG_TYPE_STRING },
734 [SYSUPGRADE_PREFIX] = { .name = "prefix", .type = BLOBMSG_TYPE_STRING },
735 [SYSUPGRADE_COMMAND] = { .name = "command", .type = BLOBMSG_TYPE_STRING },
736 [SYSUPGRADE_OPTIONS] = { .name = "options", .type = BLOBMSG_TYPE_TABLE },
737 };
738
739 static void sysupgrade_error(struct ubus_context *ctx,
740 struct ubus_request_data *req,
741 const char *message)
742 {
743 void *c;
744
745 blob_buf_init(&b, 0);
746
747 c = blobmsg_open_table(&b, "error");
748 blobmsg_add_string(&b, "message", message);
749 blobmsg_close_table(&b, c);
750
751 ubus_send_reply(ctx, req, b.head);
752 }
753
754 static int sysupgrade(struct ubus_context *ctx, struct ubus_object *obj,
755 struct ubus_request_data *req, const char *method,
756 struct blob_attr *msg)
757 {
758 enum {
759 VALIDATION_VALID,
760 VALIDATION_FORCEABLE,
761 VALIDATION_ALLOW_BACKUP,
762 __VALIDATION_MAX
763 };
764 static const struct blobmsg_policy validation_policy[__VALIDATION_MAX] = {
765 [VALIDATION_VALID] = { .name = "valid", .type = BLOBMSG_TYPE_BOOL },
766 [VALIDATION_FORCEABLE] = { .name = "forceable", .type = BLOBMSG_TYPE_BOOL },
767 [VALIDATION_ALLOW_BACKUP] = { .name = "allow_backup", .type = BLOBMSG_TYPE_BOOL },
768 };
769 struct blob_attr *validation[__VALIDATION_MAX];
770 struct blob_attr *tb[__SYSUPGRADE_MAX];
771 bool valid, forceable, allow_backup;
772 enum vjson_state ret = VJSON_ERROR;
773 char *err;
774
775 if (!msg)
776 return UBUS_STATUS_INVALID_ARGUMENT;
777
778 blobmsg_parse(sysupgrade_policy, __SYSUPGRADE_MAX, tb, blob_data(msg), blob_len(msg));
779 if (!tb[SYSUPGRADE_PATH] || !tb[SYSUPGRADE_PREFIX])
780 return UBUS_STATUS_INVALID_ARGUMENT;
781
782 ret = validate_firmware_image_call(blobmsg_get_string(tb[SYSUPGRADE_PATH]), &err);
783 if (ret != VJSON_SUCCESS) {
784 sysupgrade_error(ctx, req, err);
785 return UBUS_STATUS_UNKNOWN_ERROR;
786 }
787
788 blobmsg_parse(validation_policy, __VALIDATION_MAX, validation, blob_data(b.head), blob_len(b.head));
789
790 if (!validation[VALIDATION_VALID] || !validation[VALIDATION_FORCEABLE] ||
791 !validation[VALIDATION_ALLOW_BACKUP]) {
792 sysupgrade_error(ctx, req, "Validation script provided invalid input");
793 return UBUS_STATUS_INVALID_ARGUMENT;
794 }
795
796 valid = validation[VALIDATION_VALID] && blobmsg_get_bool(validation[VALIDATION_VALID]);
797 forceable = validation[VALIDATION_FORCEABLE] && blobmsg_get_bool(validation[VALIDATION_FORCEABLE]);
798 allow_backup = validation[VALIDATION_ALLOW_BACKUP] && blobmsg_get_bool(validation[VALIDATION_ALLOW_BACKUP]);
799
800 if (!valid) {
801 if (!forceable) {
802 sysupgrade_error(ctx, req, "Firmware image is broken and cannot be installed");
803 return UBUS_STATUS_NOT_SUPPORTED;
804 } else if (!tb[SYSUPGRADE_FORCE] || !blobmsg_get_bool(tb[SYSUPGRADE_FORCE])) {
805 sysupgrade_error(ctx, req, "Firmware image is invalid");
806 return UBUS_STATUS_NOT_SUPPORTED;
807 }
808 } else if (!allow_backup && tb[SYSUPGRADE_BACKUP]) {
809 sysupgrade_error(ctx, req, "Firmware image doesn't allow preserving a backup");
810 return UBUS_STATUS_NOT_SUPPORTED;
811 }
812
813 sysupgrade_exec_upgraded(blobmsg_get_string(tb[SYSUPGRADE_PREFIX]),
814 blobmsg_get_string(tb[SYSUPGRADE_PATH]),
815 tb[SYSUPGRADE_BACKUP] ? blobmsg_get_string(tb[SYSUPGRADE_BACKUP]) : NULL,
816 tb[SYSUPGRADE_COMMAND] ? blobmsg_get_string(tb[SYSUPGRADE_COMMAND]) : NULL,
817 tb[SYSUPGRADE_OPTIONS]);
818
819 /* sysupgrade_exec_upgraded() will never return unless something has gone wrong */
820 return UBUS_STATUS_UNKNOWN_ERROR;
821 }
822
823 static void
824 procd_subscribe_cb(struct ubus_context *ctx, struct ubus_object *obj)
825 {
826 notify = obj->has_subscribers;
827 }
828
829
830 static const struct ubus_method system_methods[] = {
831 UBUS_METHOD_NOARG("board", system_board),
832 UBUS_METHOD_NOARG("info", system_info),
833 UBUS_METHOD_NOARG("reboot", system_reboot),
834 UBUS_METHOD("watchdog", watchdog_set, watchdog_policy),
835 UBUS_METHOD("signal", proc_signal, signal_policy),
836 UBUS_METHOD("validate_firmware_image", validate_firmware_image, validate_firmware_image_policy),
837 UBUS_METHOD("sysupgrade", sysupgrade, sysupgrade_policy),
838 };
839
840 static struct ubus_object_type system_object_type =
841 UBUS_OBJECT_TYPE("system", system_methods);
842
843 static struct ubus_object system_object = {
844 .name = "system",
845 .type = &system_object_type,
846 .methods = system_methods,
847 .n_methods = ARRAY_SIZE(system_methods),
848 .subscribe_cb = procd_subscribe_cb,
849 };
850
851 void
852 procd_bcast_event(char *event, struct blob_attr *msg)
853 {
854 int ret;
855
856 if (!notify)
857 return;
858
859 ret = ubus_notify(_ctx, &system_object, event, msg, -1);
860 if (ret)
861 fprintf(stderr, "Failed to notify log: %s\n", ubus_strerror(ret));
862 }
863
864 void ubus_init_system(struct ubus_context *ctx)
865 {
866 int ret;
867
868 _ctx = ctx;
869
870 initramfs = !!getenv("INITRAMFS");
871 if (initramfs)
872 unsetenv("INITRAMFS");
873
874 ret = ubus_add_object(ctx, &system_object);
875 if (ret)
876 ERROR("Failed to add object: %s\n", ubus_strerror(ret));
877 }