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 const char *system_rootfs_type(void) {
48 const char proc_mounts
[] = "/proc/self/mounts";
49 static char fstype
[16] = { 0 };
50 char *mountstr
= NULL
, *mp
= "/", *pos
, *tmp
;
62 mounts
= fopen(proc_mounts
, "r");
66 while ((nread
= getline(&mountstr
, &len
, mounts
)) != -1) {
69 pos
= strchr(mountstr
, ' ');
74 pos
= strchr(tmp
, ' ');
83 pos
= strchr(tmp
, ' ');
89 if (!strcmp(tmp
, "overlay")) {
91 * there is no point in parsing overlay option string for
92 * lowerdir, as that can point to "/" being a previous
93 * overlay mount (after firstboot or sysuprade config
94 * restore). Hence just assume the lowerdir is "/rom" and
95 * restart searching for that instead.
98 fseek(mounts
, 0, SEEK_SET
);
107 strncpy(fstype
, tmp
, sizeof(fstype
) - 1);
109 fstype
[sizeof(fstype
) - 1]= '\0';
119 static int system_board(struct ubus_context
*ctx
, struct ubus_object
*obj
,
120 struct ubus_request_data
*req
, const char *method
,
121 struct blob_attr
*msg
)
125 char *key
, *val
, *next
;
126 const char *rootfs_type
= system_rootfs_type();
127 struct utsname utsname
;
130 blob_buf_init(&b
, 0);
132 if (uname(&utsname
) >= 0)
134 blobmsg_add_string(&b
, "kernel", utsname
.release
);
135 blobmsg_add_string(&b
, "hostname", utsname
.nodename
);
138 if ((f
= fopen("/proc/cpuinfo", "r")) != NULL
)
140 while(fgets(line
, sizeof(line
), f
))
142 key
= strtok(line
, "\t:");
143 val
= strtok(NULL
, "\t\n");
149 if (!strcasecmp(key
, "CPU revision")) {
150 snprintf(line
, sizeof(line
), "ARMv8 Processor rev %lu", strtoul(val
+ 2, NULL
, 16));
151 blobmsg_add_string(&b
, "system", line
);
155 if (!strcasecmp(key
, "system type") ||
156 !strcasecmp(key
, "processor") ||
157 !strcasecmp(key
, "cpu") ||
158 !strcasecmp(key
, "model name"))
160 strtoul(val
+ 2, &key
, 0);
162 if (key
== (val
+ 2) || *key
!= 0)
164 blobmsg_add_string(&b
, "system", val
+ 2);
174 if ((f
= fopen("/tmp/sysinfo/model", "r")) != NULL
||
175 (f
= fopen("/proc/device-tree/model", "r")) != NULL
)
177 if (fgets(line
, sizeof(line
), f
))
179 val
= strtok(line
, "\t\n");
182 blobmsg_add_string(&b
, "model", val
);
187 else if ((f
= fopen("/proc/cpuinfo", "r")) != NULL
)
189 while(fgets(line
, sizeof(line
), f
))
191 key
= strtok(line
, "\t:");
192 val
= strtok(NULL
, "\t\n");
197 if (!strcasecmp(key
, "machine") ||
198 !strcasecmp(key
, "hardware"))
200 blobmsg_add_string(&b
, "model", val
+ 2);
208 if ((f
= fopen("/tmp/sysinfo/board_name", "r")) != NULL
)
210 if (fgets(line
, sizeof(line
), f
))
212 val
= strtok(line
, "\t\n");
215 blobmsg_add_string(&b
, "board_name", val
);
220 else if ((f
= fopen("/proc/device-tree/compatible", "r")) != NULL
)
222 if (fgets(line
, sizeof(line
), f
))
224 val
= strtok(line
, "\t\n");
229 while ((next
= strchr(next
, ',')) != NULL
)
235 blobmsg_add_string(&b
, "board_name", val
);
243 blobmsg_add_string(&b
, "rootfs_type", rootfs_type
);
245 if ((f
= fopen("/etc/openwrt_release", "r")) != NULL
)
247 c
= blobmsg_open_table(&b
, "release");
249 while (fgets(line
, sizeof(line
), f
))
255 val
= strchr(line
, '=');
261 if (!strcasecmp(key
, "DISTRIB_ID"))
262 key
= "distribution";
263 else if (!strcasecmp(key
, "DISTRIB_RELEASE"))
265 else if (!strcasecmp(key
, "DISTRIB_REVISION"))
267 else if (!strcasecmp(key
, "DISTRIB_CODENAME"))
269 else if (!strcasecmp(key
, "DISTRIB_TARGET"))
271 else if (!strcasecmp(key
, "DISTRIB_DESCRIPTION"))
276 dest
= blobmsg_alloc_string_buffer(&b
, key
, strlen(val
));
278 ERROR("Failed to allocate blob.\n");
282 while (val
&& (ch
= *(val
++)) != 0) {
286 next
= strchr(val
, ch
);
295 dest
+= strlen(dest
);
298 *(dest
++) = *(val
++);
302 blobmsg_add_string_buffer(&b
);
305 blobmsg_close_array(&b
, c
);
310 ubus_send_reply(ctx
, req
, b
.head
);
312 return UBUS_STATUS_OK
;
315 static int system_info(struct ubus_context
*ctx
, struct ubus_object
*obj
,
316 struct ubus_request_data
*req
, const char *method
,
317 struct blob_attr
*msg
)
326 unsigned long long available
, cached
;
330 return UBUS_STATUS_UNKNOWN_ERROR
;
332 if ((f
= fopen("/proc/meminfo", "r")) == NULL
)
333 return UBUS_STATUS_UNKNOWN_ERROR
;
335 /* if linux < 3.14 MemAvailable is not in meminfo */
339 while (fgets(line
, sizeof(line
), f
))
341 key
= strtok(line
, " :");
342 val
= strtok(NULL
, " ");
347 if (!strcasecmp(key
, "MemAvailable"))
348 available
= 1024 * atoll(val
);
349 else if (!strcasecmp(key
, "Cached"))
350 cached
= 1024 * atoll(val
);
358 if (!(tm
= localtime(&now
)))
359 return UBUS_STATUS_UNKNOWN_ERROR
;
361 blob_buf_init(&b
, 0);
363 blobmsg_add_u32(&b
, "localtime", now
+ tm
->tm_gmtoff
);
366 blobmsg_add_u32(&b
, "uptime", info
.uptime
);
368 c
= blobmsg_open_array(&b
, "load");
369 blobmsg_add_u32(&b
, NULL
, info
.loads
[0]);
370 blobmsg_add_u32(&b
, NULL
, info
.loads
[1]);
371 blobmsg_add_u32(&b
, NULL
, info
.loads
[2]);
372 blobmsg_close_array(&b
, c
);
374 c
= blobmsg_open_table(&b
, "memory");
375 blobmsg_add_u64(&b
, "total",
376 (uint64_t)info
.mem_unit
* (uint64_t)info
.totalram
);
377 blobmsg_add_u64(&b
, "free",
378 (uint64_t)info
.mem_unit
* (uint64_t)info
.freeram
);
379 blobmsg_add_u64(&b
, "shared",
380 (uint64_t)info
.mem_unit
* (uint64_t)info
.sharedram
);
381 blobmsg_add_u64(&b
, "buffered",
382 (uint64_t)info
.mem_unit
* (uint64_t)info
.bufferram
);
383 blobmsg_add_u64(&b
, "available", available
);
384 blobmsg_add_u64(&b
, "cached", cached
);
385 blobmsg_close_table(&b
, c
);
387 c
= blobmsg_open_table(&b
, "swap");
388 blobmsg_add_u64(&b
, "total",
389 (uint64_t)info
.mem_unit
* (uint64_t)info
.totalswap
);
390 blobmsg_add_u64(&b
, "free",
391 (uint64_t)info
.mem_unit
* (uint64_t)info
.freeswap
);
392 blobmsg_close_table(&b
, c
);
395 ubus_send_reply(ctx
, req
, b
.head
);
397 return UBUS_STATUS_OK
;
400 static int system_reboot(struct ubus_context
*ctx
, struct ubus_object
*obj
,
401 struct ubus_request_data
*req
, const char *method
,
402 struct blob_attr
*msg
)
404 procd_shutdown(RB_AUTOBOOT
);
416 static const struct blobmsg_policy watchdog_policy
[__WDT_MAX
] = {
417 [WDT_FREQUENCY
] = { .name
= "frequency", .type
= BLOBMSG_TYPE_INT32
},
418 [WDT_TIMEOUT
] = { .name
= "timeout", .type
= BLOBMSG_TYPE_INT32
},
419 [WDT_MAGICCLOSE
] = { .name
= "magicclose", .type
= BLOBMSG_TYPE_BOOL
},
420 [WDT_STOP
] = { .name
= "stop", .type
= BLOBMSG_TYPE_BOOL
},
423 static int watchdog_set(struct ubus_context
*ctx
, struct ubus_object
*obj
,
424 struct ubus_request_data
*req
, const char *method
,
425 struct blob_attr
*msg
)
427 struct blob_attr
*tb
[__WDT_MAX
];
431 return UBUS_STATUS_INVALID_ARGUMENT
;
433 blobmsg_parse(watchdog_policy
, __WDT_MAX
, tb
, blob_data(msg
), blob_len(msg
));
434 if (tb
[WDT_FREQUENCY
]) {
435 unsigned int timeout
= tb
[WDT_TIMEOUT
] ? blobmsg_get_u32(tb
[WDT_TIMEOUT
]) :
437 unsigned int freq
= blobmsg_get_u32(tb
[WDT_FREQUENCY
]);
440 if (freq
> timeout
/ 2)
442 watchdog_frequency(freq
);
446 if (tb
[WDT_TIMEOUT
]) {
447 unsigned int timeout
= blobmsg_get_u32(tb
[WDT_TIMEOUT
]);
448 unsigned int frequency
= watchdog_frequency(0);
450 if (timeout
<= frequency
)
451 timeout
= frequency
* 2;
452 watchdog_timeout(timeout
);
455 if (tb
[WDT_MAGICCLOSE
])
456 watchdog_set_magicclose(blobmsg_get_bool(tb
[WDT_MAGICCLOSE
]));
459 watchdog_set_stopped(blobmsg_get_bool(tb
[WDT_STOP
]));
461 if (watchdog_fd() == NULL
)
463 else if (watchdog_get_stopped())
468 blob_buf_init(&b
, 0);
469 blobmsg_add_string(&b
, "status", status
);
470 blobmsg_add_u32(&b
, "timeout", watchdog_timeout(0));
471 blobmsg_add_u32(&b
, "frequency", watchdog_frequency(0));
472 blobmsg_add_u8(&b
, "magicclose", watchdog_get_magicclose());
473 ubus_send_reply(ctx
, req
, b
.head
);
484 static const struct blobmsg_policy signal_policy
[__SIGNAL_MAX
] = {
485 [SIGNAL_PID
] = { .name
= "pid", .type
= BLOBMSG_TYPE_INT32
},
486 [SIGNAL_NUM
] = { .name
= "signum", .type
= BLOBMSG_TYPE_INT32
},
489 static int proc_signal(struct ubus_context
*ctx
, struct ubus_object
*obj
,
490 struct ubus_request_data
*req
, const char *method
,
491 struct blob_attr
*msg
)
493 struct blob_attr
*tb
[__SIGNAL_MAX
];
496 return UBUS_STATUS_INVALID_ARGUMENT
;
498 blobmsg_parse(signal_policy
, __SIGNAL_MAX
, tb
, blob_data(msg
), blob_len(msg
));
499 if (!tb
[SIGNAL_PID
|| !tb
[SIGNAL_NUM
]])
500 return UBUS_STATUS_INVALID_ARGUMENT
;
502 kill(blobmsg_get_u32(tb
[SIGNAL_PID
]), blobmsg_get_u32(tb
[SIGNAL_NUM
]));
507 __attribute__((format (printf
, 2, 3)))
508 static enum vjson_state
vjson_error(char **b
, const char *fmt
, ...)
510 static char buf
[256] = { 0 };
511 const char *pfx
= "Firmware image couldn't be validated: ";
515 r
= snprintf(buf
, sizeof(buf
), "%s", pfx
);
517 *b
= "vjson_error() snprintf failed";
522 r
= vsnprintf(buf
+r
, sizeof(buf
)-r
, fmt
, va
);
524 *b
= "vjson_error() vsnprintf failed";
533 static enum vjson_state
vjson_parse_token(json_tokener
*tok
, char *buf
, ssize_t len
, char **err
)
535 json_object
*jsobj
= NULL
;
537 jsobj
= json_tokener_parse_ex(tok
, buf
, len
);
538 if (json_tokener_get_error(tok
) == json_tokener_continue
)
539 return VJSON_CONTINUE
;
541 if (json_tokener_get_error(tok
) == json_tokener_success
) {
542 if (json_object_get_type(jsobj
) != json_type_object
) {
543 json_object_put(jsobj
);
544 return vjson_error(err
, "result is not an JSON object");
547 blobmsg_add_object(&b
, jsobj
);
548 json_object_put(jsobj
);
549 return VJSON_SUCCESS
;
552 return vjson_error(err
, "failed to parse JSON: %s (%d)",
553 json_tokener_error_desc(json_tokener_get_error(tok
)),
554 json_tokener_get_error(tok
));
557 static enum vjson_state
vjson_parse(int fd
, char **err
)
559 enum vjson_state r
= VJSON_ERROR
;
560 size_t read_count
= 0;
561 char buf
[64] = { 0 };
566 tok
= json_tokener_new();
568 return vjson_error(err
, "json_tokener_new() failed");
570 vjson_error(err
, "incomplete JSON input");
572 while ((len
= read(fd
, buf
, sizeof(buf
)))) {
573 if (len
< 0 && errno
== EINTR
)
578 json_tokener_free(tok
);
579 return vjson_error(err
, "read() failed: %s (%d)",
580 strerror(_errno
), _errno
);
584 r
= vjson_parse_token(tok
, buf
, len
, err
);
585 if (r
!= VJSON_CONTINUE
)
588 memset(buf
, 0, sizeof(buf
));
592 vjson_error(err
, "no JSON input");
594 json_tokener_free(tok
);
599 * validate_firmware_image_call - perform validation & store result in global b
601 * @file: firmware image path
603 static enum vjson_state
validate_firmware_image_call(const char *file
, char **err
)
605 const char *path
= "/usr/libexec/validate_firmware_image";
606 enum vjson_state ret
= VJSON_ERROR
;
611 blob_buf_init(&b
, 0);
612 vjson_error(err
, "unhandled error");
616 return vjson_error(err
, "pipe() failed: %s (%d)",
617 strerror(_errno
), _errno
);
627 return vjson_error(err
, "fork() failed: %s (%d)",
628 strerror(_errno
), _errno
);
630 /* Set stdin & stderr to /dev/null */
631 fd
= open("/dev/null", O_RDWR
);
638 /* Set stdout to the shared pipe */
643 execl(path
, path
, file
, NULL
);
650 ret
= vjson_parse(fds
[0], err
);
657 VALIDATE_FIRMWARE_IMAGE_PATH
,
658 __VALIDATE_FIRMWARE_IMAGE_MAX
,
661 static const struct blobmsg_policy validate_firmware_image_policy
[__VALIDATE_FIRMWARE_IMAGE_MAX
] = {
662 [VALIDATE_FIRMWARE_IMAGE_PATH
] = { .name
= "path", .type
= BLOBMSG_TYPE_STRING
},
665 static int validate_firmware_image(struct ubus_context
*ctx
,
666 struct ubus_object
*obj
,
667 struct ubus_request_data
*req
,
668 const char *method
, struct blob_attr
*msg
)
670 struct blob_attr
*tb
[__VALIDATE_FIRMWARE_IMAGE_MAX
];
671 enum vjson_state ret
= VJSON_ERROR
;
675 return UBUS_STATUS_INVALID_ARGUMENT
;
677 blobmsg_parse(validate_firmware_image_policy
, __VALIDATE_FIRMWARE_IMAGE_MAX
, tb
, blob_data(msg
), blob_len(msg
));
678 if (!tb
[VALIDATE_FIRMWARE_IMAGE_PATH
])
679 return UBUS_STATUS_INVALID_ARGUMENT
;
681 ret
= validate_firmware_image_call(blobmsg_get_string(tb
[VALIDATE_FIRMWARE_IMAGE_PATH
]), &err
);
682 if (ret
!= VJSON_SUCCESS
)
683 return UBUS_STATUS_UNKNOWN_ERROR
;
685 ubus_send_reply(ctx
, req
, b
.head
);
687 return UBUS_STATUS_OK
;
700 static const struct blobmsg_policy sysupgrade_policy
[__SYSUPGRADE_MAX
] = {
701 [SYSUPGRADE_PATH
] = { .name
= "path", .type
= BLOBMSG_TYPE_STRING
},
702 [SYSUPGRADE_FORCE
] = { .name
= "force", .type
= BLOBMSG_TYPE_BOOL
},
703 [SYSUPGRADE_BACKUP
] = { .name
= "backup", .type
= BLOBMSG_TYPE_STRING
},
704 [SYSUPGRADE_PREFIX
] = { .name
= "prefix", .type
= BLOBMSG_TYPE_STRING
},
705 [SYSUPGRADE_COMMAND
] = { .name
= "command", .type
= BLOBMSG_TYPE_STRING
},
706 [SYSUPGRADE_OPTIONS
] = { .name
= "options", .type
= BLOBMSG_TYPE_TABLE
},
709 static void sysupgrade_error(struct ubus_context
*ctx
,
710 struct ubus_request_data
*req
,
715 blob_buf_init(&b
, 0);
717 c
= blobmsg_open_table(&b
, "error");
718 blobmsg_add_string(&b
, "message", message
);
719 blobmsg_close_table(&b
, c
);
721 ubus_send_reply(ctx
, req
, b
.head
);
724 static int sysupgrade(struct ubus_context
*ctx
, struct ubus_object
*obj
,
725 struct ubus_request_data
*req
, const char *method
,
726 struct blob_attr
*msg
)
730 VALIDATION_FORCEABLE
,
731 VALIDATION_ALLOW_BACKUP
,
734 static const struct blobmsg_policy validation_policy
[__VALIDATION_MAX
] = {
735 [VALIDATION_VALID
] = { .name
= "valid", .type
= BLOBMSG_TYPE_BOOL
},
736 [VALIDATION_FORCEABLE
] = { .name
= "forceable", .type
= BLOBMSG_TYPE_BOOL
},
737 [VALIDATION_ALLOW_BACKUP
] = { .name
= "allow_backup", .type
= BLOBMSG_TYPE_BOOL
},
739 struct blob_attr
*validation
[__VALIDATION_MAX
];
740 struct blob_attr
*tb
[__SYSUPGRADE_MAX
];
741 bool valid
, forceable
, allow_backup
;
742 enum vjson_state ret
= VJSON_ERROR
;
746 return UBUS_STATUS_INVALID_ARGUMENT
;
748 blobmsg_parse(sysupgrade_policy
, __SYSUPGRADE_MAX
, tb
, blob_data(msg
), blob_len(msg
));
749 if (!tb
[SYSUPGRADE_PATH
] || !tb
[SYSUPGRADE_PREFIX
])
750 return UBUS_STATUS_INVALID_ARGUMENT
;
752 ret
= validate_firmware_image_call(blobmsg_get_string(tb
[SYSUPGRADE_PATH
]), &err
);
753 if (ret
!= VJSON_SUCCESS
) {
754 sysupgrade_error(ctx
, req
, err
);
755 return UBUS_STATUS_UNKNOWN_ERROR
;
758 blobmsg_parse(validation_policy
, __VALIDATION_MAX
, validation
, blob_data(b
.head
), blob_len(b
.head
));
760 if (!validation
[VALIDATION_VALID
] || !validation
[VALIDATION_FORCEABLE
] ||
761 !validation
[VALIDATION_ALLOW_BACKUP
]) {
762 sysupgrade_error(ctx
, req
, "Validation script provided invalid input");
763 return UBUS_STATUS_INVALID_ARGUMENT
;
766 valid
= validation
[VALIDATION_VALID
] && blobmsg_get_bool(validation
[VALIDATION_VALID
]);
767 forceable
= validation
[VALIDATION_FORCEABLE
] && blobmsg_get_bool(validation
[VALIDATION_FORCEABLE
]);
768 allow_backup
= validation
[VALIDATION_ALLOW_BACKUP
] && blobmsg_get_bool(validation
[VALIDATION_ALLOW_BACKUP
]);
772 sysupgrade_error(ctx
, req
, "Firmware image is broken and cannot be installed");
773 return UBUS_STATUS_NOT_SUPPORTED
;
774 } else if (!tb
[SYSUPGRADE_FORCE
] || !blobmsg_get_bool(tb
[SYSUPGRADE_FORCE
])) {
775 sysupgrade_error(ctx
, req
, "Firmware image is invalid");
776 return UBUS_STATUS_NOT_SUPPORTED
;
778 } else if (!allow_backup
&& tb
[SYSUPGRADE_BACKUP
]) {
779 sysupgrade_error(ctx
, req
, "Firmware image doesn't allow preserving a backup");
780 return UBUS_STATUS_NOT_SUPPORTED
;
783 sysupgrade_exec_upgraded(blobmsg_get_string(tb
[SYSUPGRADE_PREFIX
]),
784 blobmsg_get_string(tb
[SYSUPGRADE_PATH
]),
785 tb
[SYSUPGRADE_BACKUP
] ? blobmsg_get_string(tb
[SYSUPGRADE_BACKUP
]) : NULL
,
786 tb
[SYSUPGRADE_COMMAND
] ? blobmsg_get_string(tb
[SYSUPGRADE_COMMAND
]) : NULL
,
787 tb
[SYSUPGRADE_OPTIONS
]);
789 /* sysupgrade_exec_upgraded() will never return unless something has gone wrong */
790 return UBUS_STATUS_UNKNOWN_ERROR
;
794 procd_subscribe_cb(struct ubus_context
*ctx
, struct ubus_object
*obj
)
796 notify
= obj
->has_subscribers
;
800 static const struct ubus_method system_methods
[] = {
801 UBUS_METHOD_NOARG("board", system_board
),
802 UBUS_METHOD_NOARG("info", system_info
),
803 UBUS_METHOD_NOARG("reboot", system_reboot
),
804 UBUS_METHOD("watchdog", watchdog_set
, watchdog_policy
),
805 UBUS_METHOD("signal", proc_signal
, signal_policy
),
806 UBUS_METHOD("validate_firmware_image", validate_firmware_image
, validate_firmware_image_policy
),
807 UBUS_METHOD("sysupgrade", sysupgrade
, sysupgrade_policy
),
810 static struct ubus_object_type system_object_type
=
811 UBUS_OBJECT_TYPE("system", system_methods
);
813 static struct ubus_object system_object
= {
815 .type
= &system_object_type
,
816 .methods
= system_methods
,
817 .n_methods
= ARRAY_SIZE(system_methods
),
818 .subscribe_cb
= procd_subscribe_cb
,
822 procd_bcast_event(char *event
, struct blob_attr
*msg
)
829 ret
= ubus_notify(_ctx
, &system_object
, event
, msg
, -1);
831 fprintf(stderr
, "Failed to notify log: %s\n", ubus_strerror(ret
));
834 void ubus_init_system(struct ubus_context
*ctx
)
840 initramfs
= !!getenv("INITRAMFS");
842 unsetenv("INITRAMFS");
844 ret
= ubus_add_object(ctx
, &system_object
);
846 ERROR("Failed to add object: %s\n", ubus_strerror(ret
));