2 * Copyright (C) 2013 Felix Fietkau <nbd@openwrt.org>
3 * Copyright (C) 2013 John Crispin <blogic@openwrt.org>
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
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.
15 #include <sys/utsname.h>
17 #include <sys/sysinfo.h>
19 #include <sys/ioctl.h>
20 #include <sys/types.h>
21 #include <sys/reboot.h>
28 #include <json-c/json_tokener.h>
29 #include <libubox/blobmsg_json.h>
30 #include <libubox/uloop.h>
33 #include "sysupgrade.h"
36 static struct blob_buf b;
38 static struct ubus_context *_ctx;
46 static int system_board(struct ubus_context *ctx, struct ubus_object *obj,
47 struct ubus_request_data *req, const char *method,
48 struct blob_attr *msg)
52 char *key, *val, *next;
53 struct utsname utsname;
58 if (uname(&utsname) >= 0)
60 blobmsg_add_string(&b, "kernel", utsname.release);
61 blobmsg_add_string(&b, "hostname", utsname.nodename);
64 if ((f = fopen("/proc/cpuinfo", "r")) != NULL)
66 while(fgets(line, sizeof(line), f))
68 key = strtok(line, "\t:");
69 val = strtok(NULL, "\t\n");
74 if (!strcasecmp(key, "system type") ||
75 !strcasecmp(key, "processor") ||
76 !strcasecmp(key, "cpu") ||
77 !strcasecmp(key, "model name"))
79 strtoul(val + 2, &key, 0);
81 if (key == (val + 2) || *key != 0)
83 blobmsg_add_string(&b, "system", val + 2);
92 if ((f = fopen("/tmp/sysinfo/model", "r")) != NULL ||
93 (f = fopen("/proc/device-tree/model", "r")) != NULL)
95 if (fgets(line, sizeof(line), f))
97 val = strtok(line, "\t\n");
100 blobmsg_add_string(&b, "model", val);
105 else if ((f = fopen("/proc/cpuinfo", "r")) != NULL)
107 while(fgets(line, sizeof(line), f))
109 key = strtok(line, "\t:");
110 val = strtok(NULL, "\t\n");
115 if (!strcasecmp(key, "machine") ||
116 !strcasecmp(key, "hardware"))
118 blobmsg_add_string(&b, "model", val + 2);
126 if ((f = fopen("/tmp/sysinfo/board_name", "r")) != NULL)
128 if (fgets(line, sizeof(line), f))
130 val = strtok(line, "\t\n");
133 blobmsg_add_string(&b, "board_name", val);
138 else if ((f = fopen("/proc/device-tree/compatible", "r")) != NULL)
140 if (fgets(line, sizeof(line), f))
142 val = strtok(line, "\t\n");
147 while ((next = strchr(next, ',')) != NULL)
153 blobmsg_add_string(&b, "board_name", val);
160 if ((f = fopen("/etc/openwrt_release", "r")) != NULL)
162 c = blobmsg_open_table(&b, "release");
164 while (fgets(line, sizeof(line), f))
170 val = strchr(line, '=');
176 if (!strcasecmp(key, "DISTRIB_ID"))
177 key = "distribution";
178 else if (!strcasecmp(key, "DISTRIB_RELEASE"))
180 else if (!strcasecmp(key, "DISTRIB_REVISION"))
182 else if (!strcasecmp(key, "DISTRIB_CODENAME"))
184 else if (!strcasecmp(key, "DISTRIB_TARGET"))
186 else if (!strcasecmp(key, "DISTRIB_DESCRIPTION"))
191 dest = blobmsg_alloc_string_buffer(&b, key, strlen(val));
193 ERROR("Failed to allocate blob.\n");
197 while (val && (ch = *(val++)) != 0) {
201 next = strchr(val, ch);
210 dest += strlen(dest);
213 *(dest++) = *(val++);
217 blobmsg_add_string_buffer(&b);
220 blobmsg_close_array(&b, c);
225 ubus_send_reply(ctx, req, b.head);
227 return UBUS_STATUS_OK;
230 static int system_info(struct ubus_context *ctx, struct ubus_object *obj,
231 struct ubus_request_data *req, const char *method,
232 struct blob_attr *msg)
241 unsigned long long available, cached;
245 return UBUS_STATUS_UNKNOWN_ERROR;
247 if ((f = fopen("/proc/meminfo", "r")) == NULL)
248 return UBUS_STATUS_UNKNOWN_ERROR;
250 /* if linux < 3.14 MemAvailable is not in meminfo */
254 while (fgets(line, sizeof(line), f))
256 key = strtok(line, " :");
257 val = strtok(NULL, " ");
262 if (!strcasecmp(key, "MemAvailable"))
263 available = 1024 * atoll(val);
264 else if (!strcasecmp(key, "Cached"))
265 cached = 1024 * atoll(val);
273 if (!(tm = localtime(&now)))
274 return UBUS_STATUS_UNKNOWN_ERROR;
276 blob_buf_init(&b, 0);
278 blobmsg_add_u32(&b, "localtime", now + tm->tm_gmtoff);
281 blobmsg_add_u32(&b, "uptime", info.uptime);
283 c = blobmsg_open_array(&b, "load");
284 blobmsg_add_u32(&b, NULL, info.loads[0]);
285 blobmsg_add_u32(&b, NULL, info.loads[1]);
286 blobmsg_add_u32(&b, NULL, info.loads[2]);
287 blobmsg_close_array(&b, c);
289 c = blobmsg_open_table(&b, "memory");
290 blobmsg_add_u64(&b, "total",
291 (uint64_t)info.mem_unit * (uint64_t)info.totalram);
292 blobmsg_add_u64(&b, "free",
293 (uint64_t)info.mem_unit * (uint64_t)info.freeram);
294 blobmsg_add_u64(&b, "shared",
295 (uint64_t)info.mem_unit * (uint64_t)info.sharedram);
296 blobmsg_add_u64(&b, "buffered",
297 (uint64_t)info.mem_unit * (uint64_t)info.bufferram);
298 blobmsg_add_u64(&b, "available", available);
299 blobmsg_add_u64(&b, "cached", cached);
300 blobmsg_close_table(&b, c);
302 c = blobmsg_open_table(&b, "swap");
303 blobmsg_add_u64(&b, "total",
304 (uint64_t)info.mem_unit * (uint64_t)info.totalswap);
305 blobmsg_add_u64(&b, "free",
306 (uint64_t)info.mem_unit * (uint64_t)info.freeswap);
307 blobmsg_close_table(&b, c);
310 ubus_send_reply(ctx, req, b.head);
312 return UBUS_STATUS_OK;
315 static int system_reboot(struct ubus_context *ctx, struct ubus_object *obj,
316 struct ubus_request_data *req, const char *method,
317 struct blob_attr *msg)
319 procd_shutdown(RB_AUTOBOOT);
331 static const struct blobmsg_policy watchdog_policy[__WDT_MAX] = {
332 [WDT_FREQUENCY] = { .name = "frequency", .type = BLOBMSG_TYPE_INT32 },
333 [WDT_TIMEOUT] = { .name = "timeout", .type = BLOBMSG_TYPE_INT32 },
334 [WDT_MAGICCLOSE] = { .name = "magicclose", .type = BLOBMSG_TYPE_BOOL },
335 [WDT_STOP] = { .name = "stop", .type = BLOBMSG_TYPE_BOOL },
338 static int watchdog_set(struct ubus_context *ctx, struct ubus_object *obj,
339 struct ubus_request_data *req, const char *method,
340 struct blob_attr *msg)
342 struct blob_attr *tb[__WDT_MAX];
346 return UBUS_STATUS_INVALID_ARGUMENT;
348 blobmsg_parse(watchdog_policy, __WDT_MAX, tb, blob_data(msg), blob_len(msg));
349 if (tb[WDT_FREQUENCY]) {
350 unsigned int timeout = tb[WDT_TIMEOUT] ? blobmsg_get_u32(tb[WDT_TIMEOUT]) :
352 unsigned int freq = blobmsg_get_u32(tb[WDT_FREQUENCY]);
355 if (freq > timeout / 2)
357 watchdog_frequency(freq);
361 if (tb[WDT_TIMEOUT]) {
362 unsigned int timeout = blobmsg_get_u32(tb[WDT_TIMEOUT]);
363 unsigned int frequency = watchdog_frequency(0);
365 if (timeout <= frequency)
366 timeout = frequency * 2;
367 watchdog_timeout(timeout);
370 if (tb[WDT_MAGICCLOSE])
371 watchdog_set_magicclose(blobmsg_get_bool(tb[WDT_MAGICCLOSE]));
374 watchdog_set_stopped(blobmsg_get_bool(tb[WDT_STOP]));
376 if (watchdog_fd() == NULL)
378 else if (watchdog_get_stopped())
383 blob_buf_init(&b, 0);
384 blobmsg_add_string(&b, "status", status);
385 blobmsg_add_u32(&b, "timeout", watchdog_timeout(0));
386 blobmsg_add_u32(&b, "frequency", watchdog_frequency(0));
387 blobmsg_add_u8(&b, "magicclose", watchdog_get_magicclose());
388 ubus_send_reply(ctx, req, b.head);
399 static const struct blobmsg_policy signal_policy[__SIGNAL_MAX] = {
400 [SIGNAL_PID] = { .name = "pid", .type = BLOBMSG_TYPE_INT32 },
401 [SIGNAL_NUM] = { .name = "signum", .type = BLOBMSG_TYPE_INT32 },
404 static int proc_signal(struct ubus_context *ctx, struct ubus_object *obj,
405 struct ubus_request_data *req, const char *method,
406 struct blob_attr *msg)
408 struct blob_attr *tb[__SIGNAL_MAX];
411 return UBUS_STATUS_INVALID_ARGUMENT;
413 blobmsg_parse(signal_policy, __SIGNAL_MAX, tb, blob_data(msg), blob_len(msg));
414 if (!tb[SIGNAL_PID || !tb[SIGNAL_NUM]])
415 return UBUS_STATUS_INVALID_ARGUMENT;
417 kill(blobmsg_get_u32(tb[SIGNAL_PID]), blobmsg_get_u32(tb[SIGNAL_NUM]));
422 __attribute__((format (printf, 2, 3)))
423 static enum vjson_state vjson_error(char **b, const char *fmt, ...)
425 static char buf[256] = { 0 };
426 const char *pfx = "Firmware image couldn't be validated: ";
430 r = snprintf(buf, sizeof(buf), "%s", pfx);
432 *b = "vjson_error() snprintf failed";
437 r = vsnprintf(buf+r, sizeof(buf)-r, fmt, va);
439 *b = "vjson_error() vsnprintf failed";
448 static enum vjson_state vjson_parse_token(json_tokener *tok, char *buf, ssize_t len, char **err)
450 json_object *jsobj = NULL;
452 jsobj = json_tokener_parse_ex(tok, buf, len);
453 if (json_tokener_get_error(tok) == json_tokener_continue)
454 return VJSON_CONTINUE;
456 if (json_tokener_get_error(tok) == json_tokener_success) {
457 if (json_object_get_type(jsobj) != json_type_object) {
458 json_object_put(jsobj);
459 return vjson_error(err, "result is not an JSON object");
462 blobmsg_add_object(&b, jsobj);
463 json_object_put(jsobj);
464 return VJSON_SUCCESS;
467 return vjson_error(err, "failed to parse JSON: %s (%d)",
468 json_tokener_error_desc(json_tokener_get_error(tok)),
469 json_tokener_get_error(tok));
472 static enum vjson_state vjson_parse(int fd, char **err)
474 enum vjson_state r = VJSON_ERROR;
475 size_t read_count = 0;
476 char buf[64] = { 0 };
481 tok = json_tokener_new();
483 return vjson_error(err, "json_tokener_new() failed");
485 vjson_error(err, "incomplete JSON input");
487 while ((len = read(fd, buf, sizeof(buf)))) {
488 if (len < 0 && errno == EINTR)
493 json_tokener_free(tok);
494 return vjson_error(err, "read() failed: %s (%d)",
495 strerror(_errno), _errno);
499 r = vjson_parse_token(tok, buf, len, err);
500 if (r != VJSON_CONTINUE)
503 memset(buf, 0, sizeof(buf));
507 vjson_error(err, "no JSON input");
509 json_tokener_free(tok);
514 * validate_firmware_image_call - perform validation & store result in global b
516 * @file: firmware image path
518 static enum vjson_state validate_firmware_image_call(const char *file, char **err)
520 const char *path = "/usr/libexec/validate_firmware_image";
521 enum vjson_state ret = VJSON_ERROR;
526 blob_buf_init(&b, 0);
527 vjson_error(err, "unhandled error");
531 return vjson_error(err, "pipe() failed: %s (%d)",
532 strerror(_errno), _errno);
542 return vjson_error(err, "fork() failed: %s (%d)",
543 strerror(_errno), _errno);
545 /* Set stdin & stderr to /dev/null */
546 fd = open("/dev/null", O_RDWR);
553 /* Set stdout to the shared pipe */
558 execl(path, path, file, NULL);
565 ret = vjson_parse(fds[0], err);
572 VALIDATE_FIRMWARE_IMAGE_PATH,
573 __VALIDATE_FIRMWARE_IMAGE_MAX,
576 static const struct blobmsg_policy validate_firmware_image_policy[__VALIDATE_FIRMWARE_IMAGE_MAX] = {
577 [VALIDATE_FIRMWARE_IMAGE_PATH] = { .name = "path", .type = BLOBMSG_TYPE_STRING },
580 static int validate_firmware_image(struct ubus_context *ctx,
581 struct ubus_object *obj,
582 struct ubus_request_data *req,
583 const char *method, struct blob_attr *msg)
585 struct blob_attr *tb[__VALIDATE_FIRMWARE_IMAGE_MAX];
586 enum vjson_state ret = VJSON_ERROR;
590 return UBUS_STATUS_INVALID_ARGUMENT;
592 blobmsg_parse(validate_firmware_image_policy, __VALIDATE_FIRMWARE_IMAGE_MAX, tb, blob_data(msg), blob_len(msg));
593 if (!tb[VALIDATE_FIRMWARE_IMAGE_PATH])
594 return UBUS_STATUS_INVALID_ARGUMENT;
596 ret = validate_firmware_image_call(blobmsg_get_string(tb[VALIDATE_FIRMWARE_IMAGE_PATH]), &err);
597 if (ret != VJSON_SUCCESS)
598 return UBUS_STATUS_UNKNOWN_ERROR;
600 ubus_send_reply(ctx, req, b.head);
602 return UBUS_STATUS_OK;
615 static const struct blobmsg_policy sysupgrade_policy[__SYSUPGRADE_MAX] = {
616 [SYSUPGRADE_PATH] = { .name = "path", .type = BLOBMSG_TYPE_STRING },
617 [SYSUPGRADE_FORCE] = { .name = "force", .type = BLOBMSG_TYPE_BOOL },
618 [SYSUPGRADE_BACKUP] = { .name = "backup", .type = BLOBMSG_TYPE_STRING },
619 [SYSUPGRADE_PREFIX] = { .name = "prefix", .type = BLOBMSG_TYPE_STRING },
620 [SYSUPGRADE_COMMAND] = { .name = "command", .type = BLOBMSG_TYPE_STRING },
621 [SYSUPGRADE_OPTIONS] = { .name = "options", .type = BLOBMSG_TYPE_TABLE },
624 static void sysupgrade_error(struct ubus_context *ctx,
625 struct ubus_request_data *req,
630 blob_buf_init(&b, 0);
632 c = blobmsg_open_table(&b, "error");
633 blobmsg_add_string(&b, "message", message);
634 blobmsg_close_table(&b, c);
636 ubus_send_reply(ctx, req, b.head);
639 static int sysupgrade(struct ubus_context *ctx, struct ubus_object *obj,
640 struct ubus_request_data *req, const char *method,
641 struct blob_attr *msg)
645 VALIDATION_FORCEABLE,
646 VALIDATION_ALLOW_BACKUP,
649 static const struct blobmsg_policy validation_policy[__VALIDATION_MAX] = {
650 [VALIDATION_VALID] = { .name = "valid", .type = BLOBMSG_TYPE_BOOL },
651 [VALIDATION_FORCEABLE] = { .name = "forceable", .type = BLOBMSG_TYPE_BOOL },
652 [VALIDATION_ALLOW_BACKUP] = { .name = "allow_backup", .type = BLOBMSG_TYPE_BOOL },
654 struct blob_attr *validation[__VALIDATION_MAX];
655 struct blob_attr *tb[__SYSUPGRADE_MAX];
656 bool valid, forceable, allow_backup;
657 enum vjson_state ret = VJSON_ERROR;
661 return UBUS_STATUS_INVALID_ARGUMENT;
663 blobmsg_parse(sysupgrade_policy, __SYSUPGRADE_MAX, tb, blob_data(msg), blob_len(msg));
664 if (!tb[SYSUPGRADE_PATH] || !tb[SYSUPGRADE_PREFIX])
665 return UBUS_STATUS_INVALID_ARGUMENT;
667 ret = validate_firmware_image_call(blobmsg_get_string(tb[SYSUPGRADE_PATH]), &err);
668 if (ret != VJSON_SUCCESS) {
669 sysupgrade_error(ctx, req, err);
670 return UBUS_STATUS_UNKNOWN_ERROR;
673 blobmsg_parse(validation_policy, __VALIDATION_MAX, validation, blob_data(b.head), blob_len(b.head));
675 if (!validation[VALIDATION_VALID] || !validation[VALIDATION_FORCEABLE] ||
676 !validation[VALIDATION_ALLOW_BACKUP]) {
677 sysupgrade_error(ctx, req, "Validation script provided invalid input");
678 return UBUS_STATUS_INVALID_ARGUMENT;
681 valid = validation[VALIDATION_VALID] && blobmsg_get_bool(validation[VALIDATION_VALID]);
682 forceable = validation[VALIDATION_FORCEABLE] && blobmsg_get_bool(validation[VALIDATION_FORCEABLE]);
683 allow_backup = validation[VALIDATION_ALLOW_BACKUP] && blobmsg_get_bool(validation[VALIDATION_ALLOW_BACKUP]);
687 sysupgrade_error(ctx, req, "Firmware image is broken and cannot be installed");
688 return UBUS_STATUS_NOT_SUPPORTED;
689 } else if (!tb[SYSUPGRADE_FORCE] || !blobmsg_get_bool(tb[SYSUPGRADE_FORCE])) {
690 sysupgrade_error(ctx, req, "Firmware image is invalid");
691 return UBUS_STATUS_NOT_SUPPORTED;
693 } else if (!allow_backup && tb[SYSUPGRADE_BACKUP]) {
694 sysupgrade_error(ctx, req, "Firmware image doesn't allow preserving a backup");
695 return UBUS_STATUS_NOT_SUPPORTED;
698 sysupgrade_exec_upgraded(blobmsg_get_string(tb[SYSUPGRADE_PREFIX]),
699 blobmsg_get_string(tb[SYSUPGRADE_PATH]),
700 tb[SYSUPGRADE_BACKUP] ? blobmsg_get_string(tb[SYSUPGRADE_BACKUP]) : NULL,
701 tb[SYSUPGRADE_COMMAND] ? blobmsg_get_string(tb[SYSUPGRADE_COMMAND]) : NULL,
702 tb[SYSUPGRADE_OPTIONS]);
704 /* sysupgrade_exec_upgraded() will never return unless something has gone wrong */
705 return UBUS_STATUS_UNKNOWN_ERROR;
709 procd_subscribe_cb(struct ubus_context *ctx, struct ubus_object *obj)
711 notify = obj->has_subscribers;
715 static const struct ubus_method system_methods[] = {
716 UBUS_METHOD_NOARG("board", system_board),
717 UBUS_METHOD_NOARG("info", system_info),
718 UBUS_METHOD_NOARG("reboot", system_reboot),
719 UBUS_METHOD("watchdog", watchdog_set, watchdog_policy),
720 UBUS_METHOD("signal", proc_signal, signal_policy),
721 UBUS_METHOD("validate_firmware_image", validate_firmware_image, validate_firmware_image_policy),
722 UBUS_METHOD("sysupgrade", sysupgrade, sysupgrade_policy),
725 static struct ubus_object_type system_object_type =
726 UBUS_OBJECT_TYPE("system", system_methods);
728 static struct ubus_object system_object = {
730 .type = &system_object_type,
731 .methods = system_methods,
732 .n_methods = ARRAY_SIZE(system_methods),
733 .subscribe_cb = procd_subscribe_cb,
737 procd_bcast_event(char *event, struct blob_attr *msg)
744 ret = ubus_notify(_ctx, &system_object, event, msg, -1);
746 fprintf(stderr, "Failed to notify log: %s\n", ubus_strerror(ret));
749 void ubus_init_system(struct ubus_context *ctx)
754 ret = ubus_add_object(ctx, &system_object);
756 ERROR("Failed to add object: %s\n", ubus_strerror(ret));