system.c 21 KB

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