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");
63 while ((nread
= getline(&mountstr
, &len
, mounts
)) != -1) {
66 pos
= strchr(mountstr
, ' ');
71 pos
= strchr(tmp
, ' ');
80 pos
= strchr(tmp
, ' ');
86 if (!strcmp(tmp
, "overlay")) {
88 * there is no point in parsing overlay option string for
89 * lowerdir, as that can point to "/" being a previous
90 * overlay mount (after firstboot or sysuprade config
91 * restore). Hence just assume the lowerdir is "/rom" and
92 * restart searching for that instead.
95 fseek(mounts
, 0, SEEK_SET
);
104 strncpy(fstype
, tmp
, sizeof(fstype
));
115 static int system_board(struct ubus_context
*ctx
, struct ubus_object
*obj
,
116 struct ubus_request_data
*req
, const char *method
,
117 struct blob_attr
*msg
)
121 char *key
, *val
, *next
;
122 const char *rootfs_type
= system_rootfs_type();
123 struct utsname utsname
;
126 blob_buf_init(&b
, 0);
128 if (uname(&utsname
) >= 0)
130 blobmsg_add_string(&b
, "kernel", utsname
.release
);
131 blobmsg_add_string(&b
, "hostname", utsname
.nodename
);
134 if ((f
= fopen("/proc/cpuinfo", "r")) != NULL
)
136 while(fgets(line
, sizeof(line
), f
))
138 key
= strtok(line
, "\t:");
139 val
= strtok(NULL
, "\t\n");
145 if (!strcasecmp(key
, "CPU revision")) {
146 snprintf(line
, sizeof(line
), "ARMv8 Processor rev %lu", strtoul(val
+ 2, NULL
, 16));
147 blobmsg_add_string(&b
, "system", line
);
151 if (!strcasecmp(key
, "system type") ||
152 !strcasecmp(key
, "processor") ||
153 !strcasecmp(key
, "cpu") ||
154 !strcasecmp(key
, "model name"))
156 strtoul(val
+ 2, &key
, 0);
158 if (key
== (val
+ 2) || *key
!= 0)
160 blobmsg_add_string(&b
, "system", val
+ 2);
170 if ((f
= fopen("/tmp/sysinfo/model", "r")) != NULL
||
171 (f
= fopen("/proc/device-tree/model", "r")) != NULL
)
173 if (fgets(line
, sizeof(line
), f
))
175 val
= strtok(line
, "\t\n");
178 blobmsg_add_string(&b
, "model", val
);
183 else if ((f
= fopen("/proc/cpuinfo", "r")) != NULL
)
185 while(fgets(line
, sizeof(line
), f
))
187 key
= strtok(line
, "\t:");
188 val
= strtok(NULL
, "\t\n");
193 if (!strcasecmp(key
, "machine") ||
194 !strcasecmp(key
, "hardware"))
196 blobmsg_add_string(&b
, "model", val
+ 2);
204 if ((f
= fopen("/tmp/sysinfo/board_name", "r")) != NULL
)
206 if (fgets(line
, sizeof(line
), f
))
208 val
= strtok(line
, "\t\n");
211 blobmsg_add_string(&b
, "board_name", val
);
216 else if ((f
= fopen("/proc/device-tree/compatible", "r")) != NULL
)
218 if (fgets(line
, sizeof(line
), f
))
220 val
= strtok(line
, "\t\n");
225 while ((next
= strchr(next
, ',')) != NULL
)
231 blobmsg_add_string(&b
, "board_name", val
);
239 blobmsg_add_string(&b
, "rootfs_type", rootfs_type
);
241 if ((f
= fopen("/etc/openwrt_release", "r")) != NULL
)
243 c
= blobmsg_open_table(&b
, "release");
245 while (fgets(line
, sizeof(line
), f
))
251 val
= strchr(line
, '=');
257 if (!strcasecmp(key
, "DISTRIB_ID"))
258 key
= "distribution";
259 else if (!strcasecmp(key
, "DISTRIB_RELEASE"))
261 else if (!strcasecmp(key
, "DISTRIB_REVISION"))
263 else if (!strcasecmp(key
, "DISTRIB_CODENAME"))
265 else if (!strcasecmp(key
, "DISTRIB_TARGET"))
267 else if (!strcasecmp(key
, "DISTRIB_DESCRIPTION"))
272 dest
= blobmsg_alloc_string_buffer(&b
, key
, strlen(val
));
274 ERROR("Failed to allocate blob.\n");
278 while (val
&& (ch
= *(val
++)) != 0) {
282 next
= strchr(val
, ch
);
291 dest
+= strlen(dest
);
294 *(dest
++) = *(val
++);
298 blobmsg_add_string_buffer(&b
);
301 blobmsg_close_array(&b
, c
);
306 ubus_send_reply(ctx
, req
, b
.head
);
308 return UBUS_STATUS_OK
;
311 static int system_info(struct ubus_context
*ctx
, struct ubus_object
*obj
,
312 struct ubus_request_data
*req
, const char *method
,
313 struct blob_attr
*msg
)
322 unsigned long long available
, cached
;
326 return UBUS_STATUS_UNKNOWN_ERROR
;
328 if ((f
= fopen("/proc/meminfo", "r")) == NULL
)
329 return UBUS_STATUS_UNKNOWN_ERROR
;
331 /* if linux < 3.14 MemAvailable is not in meminfo */
335 while (fgets(line
, sizeof(line
), f
))
337 key
= strtok(line
, " :");
338 val
= strtok(NULL
, " ");
343 if (!strcasecmp(key
, "MemAvailable"))
344 available
= 1024 * atoll(val
);
345 else if (!strcasecmp(key
, "Cached"))
346 cached
= 1024 * atoll(val
);
354 if (!(tm
= localtime(&now
)))
355 return UBUS_STATUS_UNKNOWN_ERROR
;
357 blob_buf_init(&b
, 0);
359 blobmsg_add_u32(&b
, "localtime", now
+ tm
->tm_gmtoff
);
362 blobmsg_add_u32(&b
, "uptime", info
.uptime
);
364 c
= blobmsg_open_array(&b
, "load");
365 blobmsg_add_u32(&b
, NULL
, info
.loads
[0]);
366 blobmsg_add_u32(&b
, NULL
, info
.loads
[1]);
367 blobmsg_add_u32(&b
, NULL
, info
.loads
[2]);
368 blobmsg_close_array(&b
, c
);
370 c
= blobmsg_open_table(&b
, "memory");
371 blobmsg_add_u64(&b
, "total",
372 (uint64_t)info
.mem_unit
* (uint64_t)info
.totalram
);
373 blobmsg_add_u64(&b
, "free",
374 (uint64_t)info
.mem_unit
* (uint64_t)info
.freeram
);
375 blobmsg_add_u64(&b
, "shared",
376 (uint64_t)info
.mem_unit
* (uint64_t)info
.sharedram
);
377 blobmsg_add_u64(&b
, "buffered",
378 (uint64_t)info
.mem_unit
* (uint64_t)info
.bufferram
);
379 blobmsg_add_u64(&b
, "available", available
);
380 blobmsg_add_u64(&b
, "cached", cached
);
381 blobmsg_close_table(&b
, c
);
383 c
= blobmsg_open_table(&b
, "swap");
384 blobmsg_add_u64(&b
, "total",
385 (uint64_t)info
.mem_unit
* (uint64_t)info
.totalswap
);
386 blobmsg_add_u64(&b
, "free",
387 (uint64_t)info
.mem_unit
* (uint64_t)info
.freeswap
);
388 blobmsg_close_table(&b
, c
);
391 ubus_send_reply(ctx
, req
, b
.head
);
393 return UBUS_STATUS_OK
;
396 static int system_reboot(struct ubus_context
*ctx
, struct ubus_object
*obj
,
397 struct ubus_request_data
*req
, const char *method
,
398 struct blob_attr
*msg
)
400 procd_shutdown(RB_AUTOBOOT
);
412 static const struct blobmsg_policy watchdog_policy
[__WDT_MAX
] = {
413 [WDT_FREQUENCY
] = { .name
= "frequency", .type
= BLOBMSG_TYPE_INT32
},
414 [WDT_TIMEOUT
] = { .name
= "timeout", .type
= BLOBMSG_TYPE_INT32
},
415 [WDT_MAGICCLOSE
] = { .name
= "magicclose", .type
= BLOBMSG_TYPE_BOOL
},
416 [WDT_STOP
] = { .name
= "stop", .type
= BLOBMSG_TYPE_BOOL
},
419 static int watchdog_set(struct ubus_context
*ctx
, struct ubus_object
*obj
,
420 struct ubus_request_data
*req
, const char *method
,
421 struct blob_attr
*msg
)
423 struct blob_attr
*tb
[__WDT_MAX
];
427 return UBUS_STATUS_INVALID_ARGUMENT
;
429 blobmsg_parse(watchdog_policy
, __WDT_MAX
, tb
, blob_data(msg
), blob_len(msg
));
430 if (tb
[WDT_FREQUENCY
]) {
431 unsigned int timeout
= tb
[WDT_TIMEOUT
] ? blobmsg_get_u32(tb
[WDT_TIMEOUT
]) :
433 unsigned int freq
= blobmsg_get_u32(tb
[WDT_FREQUENCY
]);
436 if (freq
> timeout
/ 2)
438 watchdog_frequency(freq
);
442 if (tb
[WDT_TIMEOUT
]) {
443 unsigned int timeout
= blobmsg_get_u32(tb
[WDT_TIMEOUT
]);
444 unsigned int frequency
= watchdog_frequency(0);
446 if (timeout
<= frequency
)
447 timeout
= frequency
* 2;
448 watchdog_timeout(timeout
);
451 if (tb
[WDT_MAGICCLOSE
])
452 watchdog_set_magicclose(blobmsg_get_bool(tb
[WDT_MAGICCLOSE
]));
455 watchdog_set_stopped(blobmsg_get_bool(tb
[WDT_STOP
]));
457 if (watchdog_fd() == NULL
)
459 else if (watchdog_get_stopped())
464 blob_buf_init(&b
, 0);
465 blobmsg_add_string(&b
, "status", status
);
466 blobmsg_add_u32(&b
, "timeout", watchdog_timeout(0));
467 blobmsg_add_u32(&b
, "frequency", watchdog_frequency(0));
468 blobmsg_add_u8(&b
, "magicclose", watchdog_get_magicclose());
469 ubus_send_reply(ctx
, req
, b
.head
);
480 static const struct blobmsg_policy signal_policy
[__SIGNAL_MAX
] = {
481 [SIGNAL_PID
] = { .name
= "pid", .type
= BLOBMSG_TYPE_INT32
},
482 [SIGNAL_NUM
] = { .name
= "signum", .type
= BLOBMSG_TYPE_INT32
},
485 static int proc_signal(struct ubus_context
*ctx
, struct ubus_object
*obj
,
486 struct ubus_request_data
*req
, const char *method
,
487 struct blob_attr
*msg
)
489 struct blob_attr
*tb
[__SIGNAL_MAX
];
492 return UBUS_STATUS_INVALID_ARGUMENT
;
494 blobmsg_parse(signal_policy
, __SIGNAL_MAX
, tb
, blob_data(msg
), blob_len(msg
));
495 if (!tb
[SIGNAL_PID
|| !tb
[SIGNAL_NUM
]])
496 return UBUS_STATUS_INVALID_ARGUMENT
;
498 kill(blobmsg_get_u32(tb
[SIGNAL_PID
]), blobmsg_get_u32(tb
[SIGNAL_NUM
]));
503 __attribute__((format (printf
, 2, 3)))
504 static enum vjson_state
vjson_error(char **b
, const char *fmt
, ...)
506 static char buf
[256] = { 0 };
507 const char *pfx
= "Firmware image couldn't be validated: ";
511 r
= snprintf(buf
, sizeof(buf
), "%s", pfx
);
513 *b
= "vjson_error() snprintf failed";
518 r
= vsnprintf(buf
+r
, sizeof(buf
)-r
, fmt
, va
);
520 *b
= "vjson_error() vsnprintf failed";
529 static enum vjson_state
vjson_parse_token(json_tokener
*tok
, char *buf
, ssize_t len
, char **err
)
531 json_object
*jsobj
= NULL
;
533 jsobj
= json_tokener_parse_ex(tok
, buf
, len
);
534 if (json_tokener_get_error(tok
) == json_tokener_continue
)
535 return VJSON_CONTINUE
;
537 if (json_tokener_get_error(tok
) == json_tokener_success
) {
538 if (json_object_get_type(jsobj
) != json_type_object
) {
539 json_object_put(jsobj
);
540 return vjson_error(err
, "result is not an JSON object");
543 blobmsg_add_object(&b
, jsobj
);
544 json_object_put(jsobj
);
545 return VJSON_SUCCESS
;
548 return vjson_error(err
, "failed to parse JSON: %s (%d)",
549 json_tokener_error_desc(json_tokener_get_error(tok
)),
550 json_tokener_get_error(tok
));
553 static enum vjson_state
vjson_parse(int fd
, char **err
)
555 enum vjson_state r
= VJSON_ERROR
;
556 size_t read_count
= 0;
557 char buf
[64] = { 0 };
562 tok
= json_tokener_new();
564 return vjson_error(err
, "json_tokener_new() failed");
566 vjson_error(err
, "incomplete JSON input");
568 while ((len
= read(fd
, buf
, sizeof(buf
)))) {
569 if (len
< 0 && errno
== EINTR
)
574 json_tokener_free(tok
);
575 return vjson_error(err
, "read() failed: %s (%d)",
576 strerror(_errno
), _errno
);
580 r
= vjson_parse_token(tok
, buf
, len
, err
);
581 if (r
!= VJSON_CONTINUE
)
584 memset(buf
, 0, sizeof(buf
));
588 vjson_error(err
, "no JSON input");
590 json_tokener_free(tok
);
595 * validate_firmware_image_call - perform validation & store result in global b
597 * @file: firmware image path
599 static enum vjson_state
validate_firmware_image_call(const char *file
, char **err
)
601 const char *path
= "/usr/libexec/validate_firmware_image";
602 enum vjson_state ret
= VJSON_ERROR
;
607 blob_buf_init(&b
, 0);
608 vjson_error(err
, "unhandled error");
612 return vjson_error(err
, "pipe() failed: %s (%d)",
613 strerror(_errno
), _errno
);
623 return vjson_error(err
, "fork() failed: %s (%d)",
624 strerror(_errno
), _errno
);
626 /* Set stdin & stderr to /dev/null */
627 fd
= open("/dev/null", O_RDWR
);
634 /* Set stdout to the shared pipe */
639 execl(path
, path
, file
, NULL
);
646 ret
= vjson_parse(fds
[0], err
);
653 VALIDATE_FIRMWARE_IMAGE_PATH
,
654 __VALIDATE_FIRMWARE_IMAGE_MAX
,
657 static const struct blobmsg_policy validate_firmware_image_policy
[__VALIDATE_FIRMWARE_IMAGE_MAX
] = {
658 [VALIDATE_FIRMWARE_IMAGE_PATH
] = { .name
= "path", .type
= BLOBMSG_TYPE_STRING
},
661 static int validate_firmware_image(struct ubus_context
*ctx
,
662 struct ubus_object
*obj
,
663 struct ubus_request_data
*req
,
664 const char *method
, struct blob_attr
*msg
)
666 struct blob_attr
*tb
[__VALIDATE_FIRMWARE_IMAGE_MAX
];
667 enum vjson_state ret
= VJSON_ERROR
;
671 return UBUS_STATUS_INVALID_ARGUMENT
;
673 blobmsg_parse(validate_firmware_image_policy
, __VALIDATE_FIRMWARE_IMAGE_MAX
, tb
, blob_data(msg
), blob_len(msg
));
674 if (!tb
[VALIDATE_FIRMWARE_IMAGE_PATH
])
675 return UBUS_STATUS_INVALID_ARGUMENT
;
677 ret
= validate_firmware_image_call(blobmsg_get_string(tb
[VALIDATE_FIRMWARE_IMAGE_PATH
]), &err
);
678 if (ret
!= VJSON_SUCCESS
)
679 return UBUS_STATUS_UNKNOWN_ERROR
;
681 ubus_send_reply(ctx
, req
, b
.head
);
683 return UBUS_STATUS_OK
;
696 static const struct blobmsg_policy sysupgrade_policy
[__SYSUPGRADE_MAX
] = {
697 [SYSUPGRADE_PATH
] = { .name
= "path", .type
= BLOBMSG_TYPE_STRING
},
698 [SYSUPGRADE_FORCE
] = { .name
= "force", .type
= BLOBMSG_TYPE_BOOL
},
699 [SYSUPGRADE_BACKUP
] = { .name
= "backup", .type
= BLOBMSG_TYPE_STRING
},
700 [SYSUPGRADE_PREFIX
] = { .name
= "prefix", .type
= BLOBMSG_TYPE_STRING
},
701 [SYSUPGRADE_COMMAND
] = { .name
= "command", .type
= BLOBMSG_TYPE_STRING
},
702 [SYSUPGRADE_OPTIONS
] = { .name
= "options", .type
= BLOBMSG_TYPE_TABLE
},
705 static void sysupgrade_error(struct ubus_context
*ctx
,
706 struct ubus_request_data
*req
,
711 blob_buf_init(&b
, 0);
713 c
= blobmsg_open_table(&b
, "error");
714 blobmsg_add_string(&b
, "message", message
);
715 blobmsg_close_table(&b
, c
);
717 ubus_send_reply(ctx
, req
, b
.head
);
720 static int sysupgrade(struct ubus_context
*ctx
, struct ubus_object
*obj
,
721 struct ubus_request_data
*req
, const char *method
,
722 struct blob_attr
*msg
)
726 VALIDATION_FORCEABLE
,
727 VALIDATION_ALLOW_BACKUP
,
730 static const struct blobmsg_policy validation_policy
[__VALIDATION_MAX
] = {
731 [VALIDATION_VALID
] = { .name
= "valid", .type
= BLOBMSG_TYPE_BOOL
},
732 [VALIDATION_FORCEABLE
] = { .name
= "forceable", .type
= BLOBMSG_TYPE_BOOL
},
733 [VALIDATION_ALLOW_BACKUP
] = { .name
= "allow_backup", .type
= BLOBMSG_TYPE_BOOL
},
735 struct blob_attr
*validation
[__VALIDATION_MAX
];
736 struct blob_attr
*tb
[__SYSUPGRADE_MAX
];
737 bool valid
, forceable
, allow_backup
;
738 enum vjson_state ret
= VJSON_ERROR
;
742 return UBUS_STATUS_INVALID_ARGUMENT
;
744 blobmsg_parse(sysupgrade_policy
, __SYSUPGRADE_MAX
, tb
, blob_data(msg
), blob_len(msg
));
745 if (!tb
[SYSUPGRADE_PATH
] || !tb
[SYSUPGRADE_PREFIX
])
746 return UBUS_STATUS_INVALID_ARGUMENT
;
748 ret
= validate_firmware_image_call(blobmsg_get_string(tb
[SYSUPGRADE_PATH
]), &err
);
749 if (ret
!= VJSON_SUCCESS
) {
750 sysupgrade_error(ctx
, req
, err
);
751 return UBUS_STATUS_UNKNOWN_ERROR
;
754 blobmsg_parse(validation_policy
, __VALIDATION_MAX
, validation
, blob_data(b
.head
), blob_len(b
.head
));
756 if (!validation
[VALIDATION_VALID
] || !validation
[VALIDATION_FORCEABLE
] ||
757 !validation
[VALIDATION_ALLOW_BACKUP
]) {
758 sysupgrade_error(ctx
, req
, "Validation script provided invalid input");
759 return UBUS_STATUS_INVALID_ARGUMENT
;
762 valid
= validation
[VALIDATION_VALID
] && blobmsg_get_bool(validation
[VALIDATION_VALID
]);
763 forceable
= validation
[VALIDATION_FORCEABLE
] && blobmsg_get_bool(validation
[VALIDATION_FORCEABLE
]);
764 allow_backup
= validation
[VALIDATION_ALLOW_BACKUP
] && blobmsg_get_bool(validation
[VALIDATION_ALLOW_BACKUP
]);
768 sysupgrade_error(ctx
, req
, "Firmware image is broken and cannot be installed");
769 return UBUS_STATUS_NOT_SUPPORTED
;
770 } else if (!tb
[SYSUPGRADE_FORCE
] || !blobmsg_get_bool(tb
[SYSUPGRADE_FORCE
])) {
771 sysupgrade_error(ctx
, req
, "Firmware image is invalid");
772 return UBUS_STATUS_NOT_SUPPORTED
;
774 } else if (!allow_backup
&& tb
[SYSUPGRADE_BACKUP
]) {
775 sysupgrade_error(ctx
, req
, "Firmware image doesn't allow preserving a backup");
776 return UBUS_STATUS_NOT_SUPPORTED
;
779 sysupgrade_exec_upgraded(blobmsg_get_string(tb
[SYSUPGRADE_PREFIX
]),
780 blobmsg_get_string(tb
[SYSUPGRADE_PATH
]),
781 tb
[SYSUPGRADE_BACKUP
] ? blobmsg_get_string(tb
[SYSUPGRADE_BACKUP
]) : NULL
,
782 tb
[SYSUPGRADE_COMMAND
] ? blobmsg_get_string(tb
[SYSUPGRADE_COMMAND
]) : NULL
,
783 tb
[SYSUPGRADE_OPTIONS
]);
785 /* sysupgrade_exec_upgraded() will never return unless something has gone wrong */
786 return UBUS_STATUS_UNKNOWN_ERROR
;
790 procd_subscribe_cb(struct ubus_context
*ctx
, struct ubus_object
*obj
)
792 notify
= obj
->has_subscribers
;
796 static const struct ubus_method system_methods
[] = {
797 UBUS_METHOD_NOARG("board", system_board
),
798 UBUS_METHOD_NOARG("info", system_info
),
799 UBUS_METHOD_NOARG("reboot", system_reboot
),
800 UBUS_METHOD("watchdog", watchdog_set
, watchdog_policy
),
801 UBUS_METHOD("signal", proc_signal
, signal_policy
),
802 UBUS_METHOD("validate_firmware_image", validate_firmware_image
, validate_firmware_image_policy
),
803 UBUS_METHOD("sysupgrade", sysupgrade
, sysupgrade_policy
),
806 static struct ubus_object_type system_object_type
=
807 UBUS_OBJECT_TYPE("system", system_methods
);
809 static struct ubus_object system_object
= {
811 .type
= &system_object_type
,
812 .methods
= system_methods
,
813 .n_methods
= ARRAY_SIZE(system_methods
),
814 .subscribe_cb
= procd_subscribe_cb
,
818 procd_bcast_event(char *event
, struct blob_attr
*msg
)
825 ret
= ubus_notify(_ctx
, &system_object
, event
, msg
, -1);
827 fprintf(stderr
, "Failed to notify log: %s\n", ubus_strerror(ret
));
830 void ubus_init_system(struct ubus_context
*ctx
)
836 initramfs
= !!getenv("INITRAMFS");
838 unsetenv("INITRAMFS");
840 ret
= ubus_add_object(ctx
, &system_object
);
842 ERROR("Failed to add object: %s\n", ubus_strerror(ret
));