2
0

system.c 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889
  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("/usr/lib/os-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, "NAME"))
  225. key = "distribution";
  226. else if (!strcasecmp(key, "VERSION"))
  227. key = "version";
  228. else if (!strcasecmp(key, "BUILD_ID"))
  229. key = "revision";
  230. else if (!strcasecmp(key, "VERSION_CODENAME"))
  231. key = "codename";
  232. else if (!strcasecmp(key, "OPENWRT_BOARD"))
  233. key = "target";
  234. else if (!strcasecmp(key, "OPENWRT_RELEASE"))
  235. key = "description";
  236. else if (!strcasecmp(key, "OPENWRT_BUILD_DATE"))
  237. key = "builddate";
  238. else
  239. continue;
  240. dest = blobmsg_alloc_string_buffer(&b, key, strlen(val));
  241. if (!dest) {
  242. ERROR("Failed to allocate blob.\n");
  243. continue;
  244. }
  245. while (val && (ch = *(val++)) != 0) {
  246. switch (ch) {
  247. case '\'':
  248. case '"':
  249. next = strchr(val, ch);
  250. if (next)
  251. *next = 0;
  252. strcpy(dest, val);
  253. if (next)
  254. val = next + 1;
  255. dest += strlen(dest);
  256. break;
  257. case '\\':
  258. *(dest++) = *(val++);
  259. break;
  260. }
  261. }
  262. blobmsg_add_string_buffer(&b);
  263. }
  264. blobmsg_close_array(&b, c);
  265. fclose(f);
  266. }
  267. ubus_send_reply(ctx, req, b.head);
  268. return UBUS_STATUS_OK;
  269. }
  270. static unsigned long
  271. kscale(unsigned long b, unsigned long bs)
  272. {
  273. return (b * (unsigned long long) bs + 1024/2) / 1024;
  274. }
  275. static int system_info(struct ubus_context *ctx, struct ubus_object *obj,
  276. struct ubus_request_data *req, const char *method,
  277. struct blob_attr *msg)
  278. {
  279. time_t now;
  280. struct tm *tm;
  281. #ifdef linux
  282. struct sysinfo info;
  283. void *c;
  284. char line[256];
  285. char *key, *val;
  286. unsigned long long available, cached;
  287. FILE *f;
  288. int i;
  289. struct statvfs s;
  290. const char *fslist[] = {
  291. "/", "root",
  292. "/tmp", "tmp",
  293. };
  294. if (sysinfo(&info))
  295. return UBUS_STATUS_UNKNOWN_ERROR;
  296. if ((f = fopen("/proc/meminfo", "r")) == NULL)
  297. return UBUS_STATUS_UNKNOWN_ERROR;
  298. /* if linux < 3.14 MemAvailable is not in meminfo */
  299. available = 0;
  300. cached = 0;
  301. while (fgets(line, sizeof(line), f))
  302. {
  303. key = strtok(line, " :");
  304. val = strtok(NULL, " ");
  305. if (!key || !val)
  306. continue;
  307. if (!strcasecmp(key, "MemAvailable"))
  308. available = 1024 * atoll(val);
  309. else if (!strcasecmp(key, "Cached"))
  310. cached = 1024 * atoll(val);
  311. }
  312. fclose(f);
  313. #endif
  314. now = time(NULL);
  315. if (!(tm = localtime(&now)))
  316. return UBUS_STATUS_UNKNOWN_ERROR;
  317. blob_buf_init(&b, 0);
  318. blobmsg_add_u32(&b, "localtime", now + tm->tm_gmtoff);
  319. #ifdef linux
  320. blobmsg_add_u32(&b, "uptime", info.uptime);
  321. c = blobmsg_open_array(&b, "load");
  322. blobmsg_add_u32(&b, NULL, info.loads[0]);
  323. blobmsg_add_u32(&b, NULL, info.loads[1]);
  324. blobmsg_add_u32(&b, NULL, info.loads[2]);
  325. blobmsg_close_array(&b, c);
  326. c = blobmsg_open_table(&b, "memory");
  327. blobmsg_add_u64(&b, "total",
  328. (uint64_t)info.mem_unit * (uint64_t)info.totalram);
  329. blobmsg_add_u64(&b, "free",
  330. (uint64_t)info.mem_unit * (uint64_t)info.freeram);
  331. blobmsg_add_u64(&b, "shared",
  332. (uint64_t)info.mem_unit * (uint64_t)info.sharedram);
  333. blobmsg_add_u64(&b, "buffered",
  334. (uint64_t)info.mem_unit * (uint64_t)info.bufferram);
  335. blobmsg_add_u64(&b, "available", available);
  336. blobmsg_add_u64(&b, "cached", cached);
  337. blobmsg_close_table(&b, c);
  338. for (i = 0; i < sizeof(fslist) / sizeof(fslist[0]); i += 2) {
  339. if (statvfs(fslist[i], &s))
  340. continue;
  341. c = blobmsg_open_table(&b, fslist[i+1]);
  342. if (!s.f_frsize)
  343. s.f_frsize = s.f_bsize;
  344. blobmsg_add_u64(&b, "total", kscale(s.f_blocks, s.f_frsize));
  345. blobmsg_add_u64(&b, "free", kscale(s.f_bfree, s.f_frsize));
  346. blobmsg_add_u64(&b, "used", kscale(s.f_blocks - s.f_bfree, s.f_frsize));
  347. blobmsg_add_u64(&b, "avail", kscale(s.f_bavail, s.f_frsize));
  348. blobmsg_close_table(&b, c);
  349. }
  350. c = blobmsg_open_table(&b, "swap");
  351. blobmsg_add_u64(&b, "total",
  352. (uint64_t)info.mem_unit * (uint64_t)info.totalswap);
  353. blobmsg_add_u64(&b, "free",
  354. (uint64_t)info.mem_unit * (uint64_t)info.freeswap);
  355. blobmsg_close_table(&b, c);
  356. #endif
  357. ubus_send_reply(ctx, req, b.head);
  358. return UBUS_STATUS_OK;
  359. }
  360. static int system_reboot(struct ubus_context *ctx, struct ubus_object *obj,
  361. struct ubus_request_data *req, const char *method,
  362. struct blob_attr *msg)
  363. {
  364. procd_shutdown(RB_AUTOBOOT);
  365. return 0;
  366. }
  367. enum {
  368. WDT_FREQUENCY,
  369. WDT_TIMEOUT,
  370. WDT_MAGICCLOSE,
  371. WDT_STOP,
  372. __WDT_MAX
  373. };
  374. static const struct blobmsg_policy watchdog_policy[__WDT_MAX] = {
  375. [WDT_FREQUENCY] = { .name = "frequency", .type = BLOBMSG_TYPE_INT32 },
  376. [WDT_TIMEOUT] = { .name = "timeout", .type = BLOBMSG_TYPE_INT32 },
  377. [WDT_MAGICCLOSE] = { .name = "magicclose", .type = BLOBMSG_TYPE_BOOL },
  378. [WDT_STOP] = { .name = "stop", .type = BLOBMSG_TYPE_BOOL },
  379. };
  380. static int watchdog_set(struct ubus_context *ctx, struct ubus_object *obj,
  381. struct ubus_request_data *req, const char *method,
  382. struct blob_attr *msg)
  383. {
  384. struct blob_attr *tb[__WDT_MAX];
  385. const char *status;
  386. if (!msg)
  387. return UBUS_STATUS_INVALID_ARGUMENT;
  388. blobmsg_parse(watchdog_policy, __WDT_MAX, tb, blob_data(msg), blob_len(msg));
  389. if (tb[WDT_FREQUENCY]) {
  390. unsigned int timeout = tb[WDT_TIMEOUT] ? blobmsg_get_u32(tb[WDT_TIMEOUT]) :
  391. watchdog_timeout(0);
  392. unsigned int freq = blobmsg_get_u32(tb[WDT_FREQUENCY]);
  393. if (freq) {
  394. if (freq > timeout / 2)
  395. freq = timeout / 2;
  396. watchdog_frequency(freq);
  397. }
  398. }
  399. if (tb[WDT_TIMEOUT]) {
  400. unsigned int timeout = blobmsg_get_u32(tb[WDT_TIMEOUT]);
  401. unsigned int frequency = watchdog_frequency(0);
  402. if (timeout <= frequency)
  403. timeout = frequency * 2;
  404. watchdog_timeout(timeout);
  405. }
  406. if (tb[WDT_MAGICCLOSE])
  407. watchdog_set_magicclose(blobmsg_get_bool(tb[WDT_MAGICCLOSE]));
  408. if (tb[WDT_STOP])
  409. watchdog_set_stopped(blobmsg_get_bool(tb[WDT_STOP]));
  410. if (watchdog_fd() == NULL)
  411. status = "offline";
  412. else if (watchdog_get_stopped())
  413. status = "stopped";
  414. else
  415. status = "running";
  416. blob_buf_init(&b, 0);
  417. blobmsg_add_string(&b, "status", status);
  418. blobmsg_add_u32(&b, "timeout", watchdog_timeout(0));
  419. blobmsg_add_u32(&b, "frequency", watchdog_frequency(0));
  420. blobmsg_add_u8(&b, "magicclose", watchdog_get_magicclose());
  421. ubus_send_reply(ctx, req, b.head);
  422. return 0;
  423. }
  424. enum {
  425. SIGNAL_PID,
  426. SIGNAL_NUM,
  427. __SIGNAL_MAX
  428. };
  429. static const struct blobmsg_policy signal_policy[__SIGNAL_MAX] = {
  430. [SIGNAL_PID] = { .name = "pid", .type = BLOBMSG_TYPE_INT32 },
  431. [SIGNAL_NUM] = { .name = "signum", .type = BLOBMSG_TYPE_INT32 },
  432. };
  433. static int proc_signal(struct ubus_context *ctx, struct ubus_object *obj,
  434. struct ubus_request_data *req, const char *method,
  435. struct blob_attr *msg)
  436. {
  437. struct blob_attr *tb[__SIGNAL_MAX];
  438. if (!msg)
  439. return UBUS_STATUS_INVALID_ARGUMENT;
  440. blobmsg_parse(signal_policy, __SIGNAL_MAX, tb, blob_data(msg), blob_len(msg));
  441. if (!tb[SIGNAL_PID || !tb[SIGNAL_NUM]])
  442. return UBUS_STATUS_INVALID_ARGUMENT;
  443. kill(blobmsg_get_u32(tb[SIGNAL_PID]), blobmsg_get_u32(tb[SIGNAL_NUM]));
  444. return 0;
  445. }
  446. __attribute__((format (printf, 2, 3)))
  447. static enum vjson_state vjson_error(char **b, const char *fmt, ...)
  448. {
  449. static char buf[256] = { 0 };
  450. const char *pfx = "Firmware image couldn't be validated: ";
  451. va_list va;
  452. int r;
  453. r = snprintf(buf, sizeof(buf), "%s", pfx);
  454. if (r < 0) {
  455. *b = "vjson_error() snprintf failed";
  456. return VJSON_ERROR;
  457. }
  458. va_start(va, fmt);
  459. r = vsnprintf(buf+r, sizeof(buf)-r, fmt, va);
  460. if (r < 0) {
  461. *b = "vjson_error() vsnprintf failed";
  462. return VJSON_ERROR;
  463. }
  464. va_end(va);
  465. *b = buf;
  466. return VJSON_ERROR;
  467. }
  468. static enum vjson_state vjson_parse_token(json_tokener *tok, char *buf, ssize_t len, char **err)
  469. {
  470. json_object *jsobj = NULL;
  471. jsobj = json_tokener_parse_ex(tok, buf, len);
  472. if (json_tokener_get_error(tok) == json_tokener_continue)
  473. return VJSON_CONTINUE;
  474. if (json_tokener_get_error(tok) == json_tokener_success) {
  475. if (json_object_get_type(jsobj) != json_type_object) {
  476. json_object_put(jsobj);
  477. return vjson_error(err, "result is not an JSON object");
  478. }
  479. blobmsg_add_object(&b, jsobj);
  480. json_object_put(jsobj);
  481. return VJSON_SUCCESS;
  482. }
  483. return vjson_error(err, "failed to parse JSON: %s (%d)",
  484. json_tokener_error_desc(json_tokener_get_error(tok)),
  485. json_tokener_get_error(tok));
  486. }
  487. static enum vjson_state vjson_parse(int fd, char **err)
  488. {
  489. enum vjson_state r = VJSON_ERROR;
  490. size_t read_count = 0;
  491. char buf[64] = { 0 };
  492. json_tokener *tok;
  493. ssize_t len;
  494. int _errno;
  495. tok = json_tokener_new();
  496. if (!tok)
  497. return vjson_error(err, "json_tokener_new() failed");
  498. vjson_error(err, "incomplete JSON input");
  499. while ((len = read(fd, buf, sizeof(buf)))) {
  500. if (len < 0 && errno == EINTR)
  501. continue;
  502. if (len < 0) {
  503. _errno = errno;
  504. json_tokener_free(tok);
  505. return vjson_error(err, "read() failed: %s (%d)",
  506. strerror(_errno), _errno);
  507. }
  508. read_count += len;
  509. r = vjson_parse_token(tok, buf, len, err);
  510. if (r != VJSON_CONTINUE)
  511. break;
  512. memset(buf, 0, sizeof(buf));
  513. }
  514. if (read_count == 0)
  515. vjson_error(err, "no JSON input");
  516. json_tokener_free(tok);
  517. return r;
  518. }
  519. /**
  520. * validate_firmware_image_call - perform validation & store result in global b
  521. *
  522. * @file: firmware image path
  523. */
  524. static enum vjson_state validate_firmware_image_call(const char *file, char **err)
  525. {
  526. const char *path = "/usr/libexec/validate_firmware_image";
  527. enum vjson_state ret = VJSON_ERROR;
  528. int _errno;
  529. int fds[2];
  530. int fd;
  531. blob_buf_init(&b, 0);
  532. vjson_error(err, "unhandled error");
  533. if (pipe(fds)) {
  534. _errno = errno;
  535. return vjson_error(err, "pipe() failed: %s (%d)",
  536. strerror(_errno), _errno);
  537. }
  538. switch (fork()) {
  539. case -1:
  540. _errno = errno;
  541. close(fds[0]);
  542. close(fds[1]);
  543. return vjson_error(err, "fork() failed: %s (%d)",
  544. strerror(_errno), _errno);
  545. case 0:
  546. /* Set stdin & stderr to /dev/null */
  547. fd = open("/dev/null", O_RDWR);
  548. if (fd >= 0) {
  549. dup2(fd, 0);
  550. dup2(fd, 2);
  551. close(fd);
  552. }
  553. /* Set stdout to the shared pipe */
  554. dup2(fds[1], 1);
  555. close(fds[0]);
  556. close(fds[1]);
  557. execl(path, path, file, NULL);
  558. exit(errno);
  559. }
  560. /* Parent process */
  561. close(fds[1]);
  562. ret = vjson_parse(fds[0], err);
  563. close(fds[0]);
  564. return ret;
  565. }
  566. enum {
  567. VALIDATE_FIRMWARE_IMAGE_PATH,
  568. __VALIDATE_FIRMWARE_IMAGE_MAX,
  569. };
  570. static const struct blobmsg_policy validate_firmware_image_policy[__VALIDATE_FIRMWARE_IMAGE_MAX] = {
  571. [VALIDATE_FIRMWARE_IMAGE_PATH] = { .name = "path", .type = BLOBMSG_TYPE_STRING },
  572. };
  573. static int validate_firmware_image(struct ubus_context *ctx,
  574. struct ubus_object *obj,
  575. struct ubus_request_data *req,
  576. const char *method, struct blob_attr *msg)
  577. {
  578. struct blob_attr *tb[__VALIDATE_FIRMWARE_IMAGE_MAX];
  579. enum vjson_state ret = VJSON_ERROR;
  580. char *err;
  581. if (!msg)
  582. return UBUS_STATUS_INVALID_ARGUMENT;
  583. blobmsg_parse(validate_firmware_image_policy, __VALIDATE_FIRMWARE_IMAGE_MAX, tb, blob_data(msg), blob_len(msg));
  584. if (!tb[VALIDATE_FIRMWARE_IMAGE_PATH])
  585. return UBUS_STATUS_INVALID_ARGUMENT;
  586. ret = validate_firmware_image_call(blobmsg_get_string(tb[VALIDATE_FIRMWARE_IMAGE_PATH]), &err);
  587. if (ret != VJSON_SUCCESS)
  588. return UBUS_STATUS_UNKNOWN_ERROR;
  589. ubus_send_reply(ctx, req, b.head);
  590. return UBUS_STATUS_OK;
  591. }
  592. enum {
  593. SYSUPGRADE_PATH,
  594. SYSUPGRADE_FORCE,
  595. SYSUPGRADE_BACKUP,
  596. SYSUPGRADE_PREFIX,
  597. SYSUPGRADE_COMMAND,
  598. SYSUPGRADE_OPTIONS,
  599. __SYSUPGRADE_MAX
  600. };
  601. static const struct blobmsg_policy sysupgrade_policy[__SYSUPGRADE_MAX] = {
  602. [SYSUPGRADE_PATH] = { .name = "path", .type = BLOBMSG_TYPE_STRING },
  603. [SYSUPGRADE_FORCE] = { .name = "force", .type = BLOBMSG_TYPE_BOOL },
  604. [SYSUPGRADE_BACKUP] = { .name = "backup", .type = BLOBMSG_TYPE_STRING },
  605. [SYSUPGRADE_PREFIX] = { .name = "prefix", .type = BLOBMSG_TYPE_STRING },
  606. [SYSUPGRADE_COMMAND] = { .name = "command", .type = BLOBMSG_TYPE_STRING },
  607. [SYSUPGRADE_OPTIONS] = { .name = "options", .type = BLOBMSG_TYPE_TABLE },
  608. };
  609. static void sysupgrade_error(struct ubus_context *ctx,
  610. struct ubus_request_data *req,
  611. const char *message)
  612. {
  613. void *c;
  614. blob_buf_init(&b, 0);
  615. c = blobmsg_open_table(&b, "error");
  616. blobmsg_add_string(&b, "message", message);
  617. blobmsg_close_table(&b, c);
  618. ubus_send_reply(ctx, req, b.head);
  619. }
  620. static int sysupgrade(struct ubus_context *ctx, struct ubus_object *obj,
  621. struct ubus_request_data *req, const char *method,
  622. struct blob_attr *msg)
  623. {
  624. enum {
  625. VALIDATION_VALID,
  626. VALIDATION_FORCEABLE,
  627. VALIDATION_ALLOW_BACKUP,
  628. __VALIDATION_MAX
  629. };
  630. static const struct blobmsg_policy validation_policy[__VALIDATION_MAX] = {
  631. [VALIDATION_VALID] = { .name = "valid", .type = BLOBMSG_TYPE_BOOL },
  632. [VALIDATION_FORCEABLE] = { .name = "forceable", .type = BLOBMSG_TYPE_BOOL },
  633. [VALIDATION_ALLOW_BACKUP] = { .name = "allow_backup", .type = BLOBMSG_TYPE_BOOL },
  634. };
  635. struct blob_attr *validation[__VALIDATION_MAX];
  636. struct blob_attr *tb[__SYSUPGRADE_MAX];
  637. bool valid, forceable, allow_backup;
  638. enum vjson_state ret = VJSON_ERROR;
  639. char *err;
  640. if (!msg)
  641. return UBUS_STATUS_INVALID_ARGUMENT;
  642. blobmsg_parse(sysupgrade_policy, __SYSUPGRADE_MAX, tb, blob_data(msg), blob_len(msg));
  643. if (!tb[SYSUPGRADE_PATH] || !tb[SYSUPGRADE_PREFIX])
  644. return UBUS_STATUS_INVALID_ARGUMENT;
  645. ret = validate_firmware_image_call(blobmsg_get_string(tb[SYSUPGRADE_PATH]), &err);
  646. if (ret != VJSON_SUCCESS) {
  647. sysupgrade_error(ctx, req, err);
  648. return UBUS_STATUS_UNKNOWN_ERROR;
  649. }
  650. blobmsg_parse(validation_policy, __VALIDATION_MAX, validation, blob_data(b.head), blob_len(b.head));
  651. if (!validation[VALIDATION_VALID] || !validation[VALIDATION_FORCEABLE] ||
  652. !validation[VALIDATION_ALLOW_BACKUP]) {
  653. sysupgrade_error(ctx, req, "Validation script provided invalid input");
  654. return UBUS_STATUS_INVALID_ARGUMENT;
  655. }
  656. valid = validation[VALIDATION_VALID] && blobmsg_get_bool(validation[VALIDATION_VALID]);
  657. forceable = validation[VALIDATION_FORCEABLE] && blobmsg_get_bool(validation[VALIDATION_FORCEABLE]);
  658. allow_backup = validation[VALIDATION_ALLOW_BACKUP] && blobmsg_get_bool(validation[VALIDATION_ALLOW_BACKUP]);
  659. if (!valid) {
  660. if (!forceable) {
  661. sysupgrade_error(ctx, req, "Firmware image is broken and cannot be installed");
  662. return UBUS_STATUS_NOT_SUPPORTED;
  663. } else if (!tb[SYSUPGRADE_FORCE] || !blobmsg_get_bool(tb[SYSUPGRADE_FORCE])) {
  664. sysupgrade_error(ctx, req, "Firmware image is invalid");
  665. return UBUS_STATUS_NOT_SUPPORTED;
  666. }
  667. } else if (!allow_backup && tb[SYSUPGRADE_BACKUP]) {
  668. sysupgrade_error(ctx, req, "Firmware image doesn't allow preserving a backup");
  669. return UBUS_STATUS_NOT_SUPPORTED;
  670. }
  671. service_stop_all();
  672. sysupgrade_exec_upgraded(blobmsg_get_string(tb[SYSUPGRADE_PREFIX]),
  673. blobmsg_get_string(tb[SYSUPGRADE_PATH]),
  674. tb[SYSUPGRADE_BACKUP] ? blobmsg_get_string(tb[SYSUPGRADE_BACKUP]) : NULL,
  675. tb[SYSUPGRADE_COMMAND] ? blobmsg_get_string(tb[SYSUPGRADE_COMMAND]) : NULL,
  676. tb[SYSUPGRADE_OPTIONS]);
  677. /* sysupgrade_exec_upgraded() will never return unless something has gone wrong */
  678. return UBUS_STATUS_UNKNOWN_ERROR;
  679. }
  680. static void
  681. procd_subscribe_cb(struct ubus_context *ctx, struct ubus_object *obj)
  682. {
  683. notify = obj->has_subscribers;
  684. }
  685. static const struct ubus_method system_methods[] = {
  686. UBUS_METHOD_NOARG("board", system_board),
  687. UBUS_METHOD_NOARG("info", system_info),
  688. UBUS_METHOD_NOARG("reboot", system_reboot),
  689. UBUS_METHOD("watchdog", watchdog_set, watchdog_policy),
  690. UBUS_METHOD("signal", proc_signal, signal_policy),
  691. UBUS_METHOD("validate_firmware_image", validate_firmware_image, validate_firmware_image_policy),
  692. UBUS_METHOD("sysupgrade", sysupgrade, sysupgrade_policy),
  693. };
  694. static struct ubus_object_type system_object_type =
  695. UBUS_OBJECT_TYPE("system", system_methods);
  696. static struct ubus_object system_object = {
  697. .name = "system",
  698. .type = &system_object_type,
  699. .methods = system_methods,
  700. .n_methods = ARRAY_SIZE(system_methods),
  701. .subscribe_cb = procd_subscribe_cb,
  702. };
  703. void
  704. procd_bcast_event(char *event, struct blob_attr *msg)
  705. {
  706. int ret;
  707. if (!notify)
  708. return;
  709. ret = ubus_notify(_ctx, &system_object, event, msg, -1);
  710. if (ret)
  711. fprintf(stderr, "Failed to notify log: %s\n", ubus_strerror(ret));
  712. }
  713. void ubus_init_system(struct ubus_context *ctx)
  714. {
  715. int ret;
  716. _ctx = ctx;
  717. initramfs = !!getenv("INITRAMFS");
  718. if (initramfs)
  719. unsetenv("INITRAMFS");
  720. ret = ubus_add_object(ctx, &system_object);
  721. if (ret)
  722. ERROR("Failed to add object: %s\n", ubus_strerror(ret));
  723. }