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
;
47 static int system_board(struct ubus_context
*ctx
, struct ubus_object
*obj
,
48 struct ubus_request_data
*req
, const char *method
,
49 struct blob_attr
*msg
)
53 char *key
, *val
, *next
;
54 struct utsname utsname
;
60 blobmsg_add_u8(&b
, "initramfs", 1);
62 if (uname(&utsname
) >= 0)
64 blobmsg_add_string(&b
, "kernel", utsname
.release
);
65 blobmsg_add_string(&b
, "hostname", utsname
.nodename
);
68 if ((f
= fopen("/proc/cpuinfo", "r")) != NULL
)
70 while(fgets(line
, sizeof(line
), f
))
72 key
= strtok(line
, "\t:");
73 val
= strtok(NULL
, "\t\n");
79 if (!strcasecmp(key
, "CPU revision")) {
80 snprintf(line
, sizeof(line
), "ARMv8 Processor rev %lu", strtoul(val
+ 2, NULL
, 16));
81 blobmsg_add_string(&b
, "system", line
);
85 if (!strcasecmp(key
, "system type") ||
86 !strcasecmp(key
, "processor") ||
87 !strcasecmp(key
, "cpu") ||
88 !strcasecmp(key
, "model name"))
90 strtoul(val
+ 2, &key
, 0);
92 if (key
== (val
+ 2) || *key
!= 0)
94 blobmsg_add_string(&b
, "system", val
+ 2);
104 if ((f
= fopen("/tmp/sysinfo/model", "r")) != NULL
||
105 (f
= fopen("/proc/device-tree/model", "r")) != NULL
)
107 if (fgets(line
, sizeof(line
), f
))
109 val
= strtok(line
, "\t\n");
112 blobmsg_add_string(&b
, "model", val
);
117 else if ((f
= fopen("/proc/cpuinfo", "r")) != NULL
)
119 while(fgets(line
, sizeof(line
), f
))
121 key
= strtok(line
, "\t:");
122 val
= strtok(NULL
, "\t\n");
127 if (!strcasecmp(key
, "machine") ||
128 !strcasecmp(key
, "hardware"))
130 blobmsg_add_string(&b
, "model", val
+ 2);
138 if ((f
= fopen("/tmp/sysinfo/board_name", "r")) != NULL
)
140 if (fgets(line
, sizeof(line
), f
))
142 val
= strtok(line
, "\t\n");
145 blobmsg_add_string(&b
, "board_name", val
);
150 else if ((f
= fopen("/proc/device-tree/compatible", "r")) != NULL
)
152 if (fgets(line
, sizeof(line
), f
))
154 val
= strtok(line
, "\t\n");
159 while ((next
= strchr(next
, ',')) != NULL
)
165 blobmsg_add_string(&b
, "board_name", val
);
172 if ((f
= fopen("/etc/openwrt_release", "r")) != NULL
)
174 c
= blobmsg_open_table(&b
, "release");
176 while (fgets(line
, sizeof(line
), f
))
182 val
= strchr(line
, '=');
188 if (!strcasecmp(key
, "DISTRIB_ID"))
189 key
= "distribution";
190 else if (!strcasecmp(key
, "DISTRIB_RELEASE"))
192 else if (!strcasecmp(key
, "DISTRIB_REVISION"))
194 else if (!strcasecmp(key
, "DISTRIB_CODENAME"))
196 else if (!strcasecmp(key
, "DISTRIB_TARGET"))
198 else if (!strcasecmp(key
, "DISTRIB_DESCRIPTION"))
203 dest
= blobmsg_alloc_string_buffer(&b
, key
, strlen(val
));
205 ERROR("Failed to allocate blob.\n");
209 while (val
&& (ch
= *(val
++)) != 0) {
213 next
= strchr(val
, ch
);
222 dest
+= strlen(dest
);
225 *(dest
++) = *(val
++);
229 blobmsg_add_string_buffer(&b
);
232 blobmsg_close_array(&b
, c
);
237 ubus_send_reply(ctx
, req
, b
.head
);
239 return UBUS_STATUS_OK
;
242 static int system_info(struct ubus_context
*ctx
, struct ubus_object
*obj
,
243 struct ubus_request_data
*req
, const char *method
,
244 struct blob_attr
*msg
)
253 unsigned long long available
, cached
;
257 return UBUS_STATUS_UNKNOWN_ERROR
;
259 if ((f
= fopen("/proc/meminfo", "r")) == NULL
)
260 return UBUS_STATUS_UNKNOWN_ERROR
;
262 /* if linux < 3.14 MemAvailable is not in meminfo */
266 while (fgets(line
, sizeof(line
), f
))
268 key
= strtok(line
, " :");
269 val
= strtok(NULL
, " ");
274 if (!strcasecmp(key
, "MemAvailable"))
275 available
= 1024 * atoll(val
);
276 else if (!strcasecmp(key
, "Cached"))
277 cached
= 1024 * atoll(val
);
285 if (!(tm
= localtime(&now
)))
286 return UBUS_STATUS_UNKNOWN_ERROR
;
288 blob_buf_init(&b
, 0);
290 blobmsg_add_u32(&b
, "localtime", now
+ tm
->tm_gmtoff
);
293 blobmsg_add_u32(&b
, "uptime", info
.uptime
);
295 c
= blobmsg_open_array(&b
, "load");
296 blobmsg_add_u32(&b
, NULL
, info
.loads
[0]);
297 blobmsg_add_u32(&b
, NULL
, info
.loads
[1]);
298 blobmsg_add_u32(&b
, NULL
, info
.loads
[2]);
299 blobmsg_close_array(&b
, c
);
301 c
= blobmsg_open_table(&b
, "memory");
302 blobmsg_add_u64(&b
, "total",
303 (uint64_t)info
.mem_unit
* (uint64_t)info
.totalram
);
304 blobmsg_add_u64(&b
, "free",
305 (uint64_t)info
.mem_unit
* (uint64_t)info
.freeram
);
306 blobmsg_add_u64(&b
, "shared",
307 (uint64_t)info
.mem_unit
* (uint64_t)info
.sharedram
);
308 blobmsg_add_u64(&b
, "buffered",
309 (uint64_t)info
.mem_unit
* (uint64_t)info
.bufferram
);
310 blobmsg_add_u64(&b
, "available", available
);
311 blobmsg_add_u64(&b
, "cached", cached
);
312 blobmsg_close_table(&b
, c
);
314 c
= blobmsg_open_table(&b
, "swap");
315 blobmsg_add_u64(&b
, "total",
316 (uint64_t)info
.mem_unit
* (uint64_t)info
.totalswap
);
317 blobmsg_add_u64(&b
, "free",
318 (uint64_t)info
.mem_unit
* (uint64_t)info
.freeswap
);
319 blobmsg_close_table(&b
, c
);
322 ubus_send_reply(ctx
, req
, b
.head
);
324 return UBUS_STATUS_OK
;
327 static int system_reboot(struct ubus_context
*ctx
, struct ubus_object
*obj
,
328 struct ubus_request_data
*req
, const char *method
,
329 struct blob_attr
*msg
)
331 procd_shutdown(RB_AUTOBOOT
);
343 static const struct blobmsg_policy watchdog_policy
[__WDT_MAX
] = {
344 [WDT_FREQUENCY
] = { .name
= "frequency", .type
= BLOBMSG_TYPE_INT32
},
345 [WDT_TIMEOUT
] = { .name
= "timeout", .type
= BLOBMSG_TYPE_INT32
},
346 [WDT_MAGICCLOSE
] = { .name
= "magicclose", .type
= BLOBMSG_TYPE_BOOL
},
347 [WDT_STOP
] = { .name
= "stop", .type
= BLOBMSG_TYPE_BOOL
},
350 static int watchdog_set(struct ubus_context
*ctx
, struct ubus_object
*obj
,
351 struct ubus_request_data
*req
, const char *method
,
352 struct blob_attr
*msg
)
354 struct blob_attr
*tb
[__WDT_MAX
];
358 return UBUS_STATUS_INVALID_ARGUMENT
;
360 blobmsg_parse(watchdog_policy
, __WDT_MAX
, tb
, blob_data(msg
), blob_len(msg
));
361 if (tb
[WDT_FREQUENCY
]) {
362 unsigned int timeout
= tb
[WDT_TIMEOUT
] ? blobmsg_get_u32(tb
[WDT_TIMEOUT
]) :
364 unsigned int freq
= blobmsg_get_u32(tb
[WDT_FREQUENCY
]);
367 if (freq
> timeout
/ 2)
369 watchdog_frequency(freq
);
373 if (tb
[WDT_TIMEOUT
]) {
374 unsigned int timeout
= blobmsg_get_u32(tb
[WDT_TIMEOUT
]);
375 unsigned int frequency
= watchdog_frequency(0);
377 if (timeout
<= frequency
)
378 timeout
= frequency
* 2;
379 watchdog_timeout(timeout
);
382 if (tb
[WDT_MAGICCLOSE
])
383 watchdog_set_magicclose(blobmsg_get_bool(tb
[WDT_MAGICCLOSE
]));
386 watchdog_set_stopped(blobmsg_get_bool(tb
[WDT_STOP
]));
388 if (watchdog_fd() == NULL
)
390 else if (watchdog_get_stopped())
395 blob_buf_init(&b
, 0);
396 blobmsg_add_string(&b
, "status", status
);
397 blobmsg_add_u32(&b
, "timeout", watchdog_timeout(0));
398 blobmsg_add_u32(&b
, "frequency", watchdog_frequency(0));
399 blobmsg_add_u8(&b
, "magicclose", watchdog_get_magicclose());
400 ubus_send_reply(ctx
, req
, b
.head
);
411 static const struct blobmsg_policy signal_policy
[__SIGNAL_MAX
] = {
412 [SIGNAL_PID
] = { .name
= "pid", .type
= BLOBMSG_TYPE_INT32
},
413 [SIGNAL_NUM
] = { .name
= "signum", .type
= BLOBMSG_TYPE_INT32
},
416 static int proc_signal(struct ubus_context
*ctx
, struct ubus_object
*obj
,
417 struct ubus_request_data
*req
, const char *method
,
418 struct blob_attr
*msg
)
420 struct blob_attr
*tb
[__SIGNAL_MAX
];
423 return UBUS_STATUS_INVALID_ARGUMENT
;
425 blobmsg_parse(signal_policy
, __SIGNAL_MAX
, tb
, blob_data(msg
), blob_len(msg
));
426 if (!tb
[SIGNAL_PID
|| !tb
[SIGNAL_NUM
]])
427 return UBUS_STATUS_INVALID_ARGUMENT
;
429 kill(blobmsg_get_u32(tb
[SIGNAL_PID
]), blobmsg_get_u32(tb
[SIGNAL_NUM
]));
434 __attribute__((format (printf
, 2, 3)))
435 static enum vjson_state
vjson_error(char **b
, const char *fmt
, ...)
437 static char buf
[256] = { 0 };
438 const char *pfx
= "Firmware image couldn't be validated: ";
442 r
= snprintf(buf
, sizeof(buf
), "%s", pfx
);
444 *b
= "vjson_error() snprintf failed";
449 r
= vsnprintf(buf
+r
, sizeof(buf
)-r
, fmt
, va
);
451 *b
= "vjson_error() vsnprintf failed";
460 static enum vjson_state
vjson_parse_token(json_tokener
*tok
, char *buf
, ssize_t len
, char **err
)
462 json_object
*jsobj
= NULL
;
464 jsobj
= json_tokener_parse_ex(tok
, buf
, len
);
465 if (json_tokener_get_error(tok
) == json_tokener_continue
)
466 return VJSON_CONTINUE
;
468 if (json_tokener_get_error(tok
) == json_tokener_success
) {
469 if (json_object_get_type(jsobj
) != json_type_object
) {
470 json_object_put(jsobj
);
471 return vjson_error(err
, "result is not an JSON object");
474 blobmsg_add_object(&b
, jsobj
);
475 json_object_put(jsobj
);
476 return VJSON_SUCCESS
;
479 return vjson_error(err
, "failed to parse JSON: %s (%d)",
480 json_tokener_error_desc(json_tokener_get_error(tok
)),
481 json_tokener_get_error(tok
));
484 static enum vjson_state
vjson_parse(int fd
, char **err
)
486 enum vjson_state r
= VJSON_ERROR
;
487 size_t read_count
= 0;
488 char buf
[64] = { 0 };
493 tok
= json_tokener_new();
495 return vjson_error(err
, "json_tokener_new() failed");
497 vjson_error(err
, "incomplete JSON input");
499 while ((len
= read(fd
, buf
, sizeof(buf
)))) {
500 if (len
< 0 && errno
== EINTR
)
505 json_tokener_free(tok
);
506 return vjson_error(err
, "read() failed: %s (%d)",
507 strerror(_errno
), _errno
);
511 r
= vjson_parse_token(tok
, buf
, len
, err
);
512 if (r
!= VJSON_CONTINUE
)
515 memset(buf
, 0, sizeof(buf
));
519 vjson_error(err
, "no JSON input");
521 json_tokener_free(tok
);
526 * validate_firmware_image_call - perform validation & store result in global b
528 * @file: firmware image path
530 static enum vjson_state
validate_firmware_image_call(const char *file
, char **err
)
532 const char *path
= "/usr/libexec/validate_firmware_image";
533 enum vjson_state ret
= VJSON_ERROR
;
538 blob_buf_init(&b
, 0);
539 vjson_error(err
, "unhandled error");
543 return vjson_error(err
, "pipe() failed: %s (%d)",
544 strerror(_errno
), _errno
);
554 return vjson_error(err
, "fork() failed: %s (%d)",
555 strerror(_errno
), _errno
);
557 /* Set stdin & stderr to /dev/null */
558 fd
= open("/dev/null", O_RDWR
);
565 /* Set stdout to the shared pipe */
570 execl(path
, path
, file
, NULL
);
577 ret
= vjson_parse(fds
[0], err
);
584 VALIDATE_FIRMWARE_IMAGE_PATH
,
585 __VALIDATE_FIRMWARE_IMAGE_MAX
,
588 static const struct blobmsg_policy validate_firmware_image_policy
[__VALIDATE_FIRMWARE_IMAGE_MAX
] = {
589 [VALIDATE_FIRMWARE_IMAGE_PATH
] = { .name
= "path", .type
= BLOBMSG_TYPE_STRING
},
592 static int validate_firmware_image(struct ubus_context
*ctx
,
593 struct ubus_object
*obj
,
594 struct ubus_request_data
*req
,
595 const char *method
, struct blob_attr
*msg
)
597 struct blob_attr
*tb
[__VALIDATE_FIRMWARE_IMAGE_MAX
];
598 enum vjson_state ret
= VJSON_ERROR
;
602 return UBUS_STATUS_INVALID_ARGUMENT
;
604 blobmsg_parse(validate_firmware_image_policy
, __VALIDATE_FIRMWARE_IMAGE_MAX
, tb
, blob_data(msg
), blob_len(msg
));
605 if (!tb
[VALIDATE_FIRMWARE_IMAGE_PATH
])
606 return UBUS_STATUS_INVALID_ARGUMENT
;
608 ret
= validate_firmware_image_call(blobmsg_get_string(tb
[VALIDATE_FIRMWARE_IMAGE_PATH
]), &err
);
609 if (ret
!= VJSON_SUCCESS
)
610 return UBUS_STATUS_UNKNOWN_ERROR
;
612 ubus_send_reply(ctx
, req
, b
.head
);
614 return UBUS_STATUS_OK
;
627 static const struct blobmsg_policy sysupgrade_policy
[__SYSUPGRADE_MAX
] = {
628 [SYSUPGRADE_PATH
] = { .name
= "path", .type
= BLOBMSG_TYPE_STRING
},
629 [SYSUPGRADE_FORCE
] = { .name
= "force", .type
= BLOBMSG_TYPE_BOOL
},
630 [SYSUPGRADE_BACKUP
] = { .name
= "backup", .type
= BLOBMSG_TYPE_STRING
},
631 [SYSUPGRADE_PREFIX
] = { .name
= "prefix", .type
= BLOBMSG_TYPE_STRING
},
632 [SYSUPGRADE_COMMAND
] = { .name
= "command", .type
= BLOBMSG_TYPE_STRING
},
633 [SYSUPGRADE_OPTIONS
] = { .name
= "options", .type
= BLOBMSG_TYPE_TABLE
},
636 static void sysupgrade_error(struct ubus_context
*ctx
,
637 struct ubus_request_data
*req
,
642 blob_buf_init(&b
, 0);
644 c
= blobmsg_open_table(&b
, "error");
645 blobmsg_add_string(&b
, "message", message
);
646 blobmsg_close_table(&b
, c
);
648 ubus_send_reply(ctx
, req
, b
.head
);
651 static int sysupgrade(struct ubus_context
*ctx
, struct ubus_object
*obj
,
652 struct ubus_request_data
*req
, const char *method
,
653 struct blob_attr
*msg
)
657 VALIDATION_FORCEABLE
,
658 VALIDATION_ALLOW_BACKUP
,
661 static const struct blobmsg_policy validation_policy
[__VALIDATION_MAX
] = {
662 [VALIDATION_VALID
] = { .name
= "valid", .type
= BLOBMSG_TYPE_BOOL
},
663 [VALIDATION_FORCEABLE
] = { .name
= "forceable", .type
= BLOBMSG_TYPE_BOOL
},
664 [VALIDATION_ALLOW_BACKUP
] = { .name
= "allow_backup", .type
= BLOBMSG_TYPE_BOOL
},
666 struct blob_attr
*validation
[__VALIDATION_MAX
];
667 struct blob_attr
*tb
[__SYSUPGRADE_MAX
];
668 bool valid
, forceable
, allow_backup
;
669 enum vjson_state ret
= VJSON_ERROR
;
673 return UBUS_STATUS_INVALID_ARGUMENT
;
675 blobmsg_parse(sysupgrade_policy
, __SYSUPGRADE_MAX
, tb
, blob_data(msg
), blob_len(msg
));
676 if (!tb
[SYSUPGRADE_PATH
] || !tb
[SYSUPGRADE_PREFIX
])
677 return UBUS_STATUS_INVALID_ARGUMENT
;
679 ret
= validate_firmware_image_call(blobmsg_get_string(tb
[SYSUPGRADE_PATH
]), &err
);
680 if (ret
!= VJSON_SUCCESS
) {
681 sysupgrade_error(ctx
, req
, err
);
682 return UBUS_STATUS_UNKNOWN_ERROR
;
685 blobmsg_parse(validation_policy
, __VALIDATION_MAX
, validation
, blob_data(b
.head
), blob_len(b
.head
));
687 if (!validation
[VALIDATION_VALID
] || !validation
[VALIDATION_FORCEABLE
] ||
688 !validation
[VALIDATION_ALLOW_BACKUP
]) {
689 sysupgrade_error(ctx
, req
, "Validation script provided invalid input");
690 return UBUS_STATUS_INVALID_ARGUMENT
;
693 valid
= validation
[VALIDATION_VALID
] && blobmsg_get_bool(validation
[VALIDATION_VALID
]);
694 forceable
= validation
[VALIDATION_FORCEABLE
] && blobmsg_get_bool(validation
[VALIDATION_FORCEABLE
]);
695 allow_backup
= validation
[VALIDATION_ALLOW_BACKUP
] && blobmsg_get_bool(validation
[VALIDATION_ALLOW_BACKUP
]);
699 sysupgrade_error(ctx
, req
, "Firmware image is broken and cannot be installed");
700 return UBUS_STATUS_NOT_SUPPORTED
;
701 } else if (!tb
[SYSUPGRADE_FORCE
] || !blobmsg_get_bool(tb
[SYSUPGRADE_FORCE
])) {
702 sysupgrade_error(ctx
, req
, "Firmware image is invalid");
703 return UBUS_STATUS_NOT_SUPPORTED
;
705 } else if (!allow_backup
&& tb
[SYSUPGRADE_BACKUP
]) {
706 sysupgrade_error(ctx
, req
, "Firmware image doesn't allow preserving a backup");
707 return UBUS_STATUS_NOT_SUPPORTED
;
710 sysupgrade_exec_upgraded(blobmsg_get_string(tb
[SYSUPGRADE_PREFIX
]),
711 blobmsg_get_string(tb
[SYSUPGRADE_PATH
]),
712 tb
[SYSUPGRADE_BACKUP
] ? blobmsg_get_string(tb
[SYSUPGRADE_BACKUP
]) : NULL
,
713 tb
[SYSUPGRADE_COMMAND
] ? blobmsg_get_string(tb
[SYSUPGRADE_COMMAND
]) : NULL
,
714 tb
[SYSUPGRADE_OPTIONS
]);
716 /* sysupgrade_exec_upgraded() will never return unless something has gone wrong */
717 return UBUS_STATUS_UNKNOWN_ERROR
;
721 procd_subscribe_cb(struct ubus_context
*ctx
, struct ubus_object
*obj
)
723 notify
= obj
->has_subscribers
;
727 static const struct ubus_method system_methods
[] = {
728 UBUS_METHOD_NOARG("board", system_board
),
729 UBUS_METHOD_NOARG("info", system_info
),
730 UBUS_METHOD_NOARG("reboot", system_reboot
),
731 UBUS_METHOD("watchdog", watchdog_set
, watchdog_policy
),
732 UBUS_METHOD("signal", proc_signal
, signal_policy
),
733 UBUS_METHOD("validate_firmware_image", validate_firmware_image
, validate_firmware_image_policy
),
734 UBUS_METHOD("sysupgrade", sysupgrade
, sysupgrade_policy
),
737 static struct ubus_object_type system_object_type
=
738 UBUS_OBJECT_TYPE("system", system_methods
);
740 static struct ubus_object system_object
= {
742 .type
= &system_object_type
,
743 .methods
= system_methods
,
744 .n_methods
= ARRAY_SIZE(system_methods
),
745 .subscribe_cb
= procd_subscribe_cb
,
749 procd_bcast_event(char *event
, struct blob_attr
*msg
)
756 ret
= ubus_notify(_ctx
, &system_object
, event
, msg
, -1);
758 fprintf(stderr
, "Failed to notify log: %s\n", ubus_strerror(ret
));
761 void ubus_init_system(struct ubus_context
*ctx
)
767 initramfs
= !!getenv("INITRAMFS");
769 unsetenv("INITRAMFS");
771 ret
= ubus_add_object(ctx
, &system_object
);
773 ERROR("Failed to add object: %s\n", ubus_strerror(ret
));