ad24a30a6ce68779e27ab386055b5574e50d9634
[project/procd.git] / system.c
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
15 #include <sys/utsname.h>
16 #ifdef linux
17 #include <sys/sysinfo.h>
18 #endif
19 #include <sys/ioctl.h>
20 #include <sys/types.h>
21 #include <sys/reboot.h>
22 #include <sys/stat.h>
23 #include <fcntl.h>
24 #include <signal.h>
25 #include <unistd.h>
26 #include <stdlib.h>
27
28 #include <json-c/json_tokener.h>
29 #include <libubox/blobmsg_json.h>
30 #include <libubox/uloop.h>
31
32 #include "procd.h"
33 #include "sysupgrade.h"
34 #include "watchdog.h"
35
36 static struct blob_buf b;
37 static int notify;
38 static struct ubus_context *_ctx;
39
40 static int system_board(struct ubus_context *ctx, struct ubus_object *obj,
41 struct ubus_request_data *req, const char *method,
42 struct blob_attr *msg)
43 {
44 void *c;
45 char line[256];
46 char *key, *val, *next;
47 struct utsname utsname;
48 FILE *f;
49
50 blob_buf_init(&b, 0);
51
52 if (uname(&utsname) >= 0)
53 {
54 blobmsg_add_string(&b, "kernel", utsname.release);
55 blobmsg_add_string(&b, "hostname", utsname.nodename);
56 }
57
58 if ((f = fopen("/proc/cpuinfo", "r")) != NULL)
59 {
60 while(fgets(line, sizeof(line), f))
61 {
62 key = strtok(line, "\t:");
63 val = strtok(NULL, "\t\n");
64
65 if (!key || !val)
66 continue;
67
68 if (!strcasecmp(key, "system type") ||
69 !strcasecmp(key, "processor") ||
70 !strcasecmp(key, "cpu") ||
71 !strcasecmp(key, "model name"))
72 {
73 strtoul(val + 2, &key, 0);
74
75 if (key == (val + 2) || *key != 0)
76 {
77 blobmsg_add_string(&b, "system", val + 2);
78 break;
79 }
80 }
81 }
82
83 fclose(f);
84 }
85
86 if ((f = fopen("/tmp/sysinfo/model", "r")) != NULL ||
87 (f = fopen("/proc/device-tree/model", "r")) != NULL)
88 {
89 if (fgets(line, sizeof(line), f))
90 {
91 val = strtok(line, "\t\n");
92
93 if (val)
94 blobmsg_add_string(&b, "model", val);
95 }
96
97 fclose(f);
98 }
99 else if ((f = fopen("/proc/cpuinfo", "r")) != NULL)
100 {
101 while(fgets(line, sizeof(line), f))
102 {
103 key = strtok(line, "\t:");
104 val = strtok(NULL, "\t\n");
105
106 if (!key || !val)
107 continue;
108
109 if (!strcasecmp(key, "machine") ||
110 !strcasecmp(key, "hardware"))
111 {
112 blobmsg_add_string(&b, "model", val + 2);
113 break;
114 }
115 }
116
117 fclose(f);
118 }
119
120 if ((f = fopen("/tmp/sysinfo/board_name", "r")) != NULL)
121 {
122 if (fgets(line, sizeof(line), f))
123 {
124 val = strtok(line, "\t\n");
125
126 if (val)
127 blobmsg_add_string(&b, "board_name", val);
128 }
129
130 fclose(f);
131 }
132 else if ((f = fopen("/proc/device-tree/compatible", "r")) != NULL)
133 {
134 if (fgets(line, sizeof(line), f))
135 {
136 val = strtok(line, "\t\n");
137
138 if (val)
139 {
140 next = val;
141 while ((next = strchr(next, ',')) != NULL)
142 {
143 *next = '-';
144 next++;
145 }
146
147 blobmsg_add_string(&b, "board_name", val);
148 }
149 }
150
151 fclose(f);
152 }
153
154 if ((f = fopen("/etc/openwrt_release", "r")) != NULL)
155 {
156 c = blobmsg_open_table(&b, "release");
157
158 while (fgets(line, sizeof(line), f))
159 {
160 char *dest;
161 char ch;
162
163 key = line;
164 val = strchr(line, '=');
165 if (!val)
166 continue;
167
168 *(val++) = 0;
169
170 if (!strcasecmp(key, "DISTRIB_ID"))
171 key = "distribution";
172 else if (!strcasecmp(key, "DISTRIB_RELEASE"))
173 key = "version";
174 else if (!strcasecmp(key, "DISTRIB_REVISION"))
175 key = "revision";
176 else if (!strcasecmp(key, "DISTRIB_CODENAME"))
177 key = "codename";
178 else if (!strcasecmp(key, "DISTRIB_TARGET"))
179 key = "target";
180 else if (!strcasecmp(key, "DISTRIB_DESCRIPTION"))
181 key = "description";
182 else
183 continue;
184
185 dest = blobmsg_alloc_string_buffer(&b, key, strlen(val));
186 if (!dest) {
187 ERROR("Failed to allocate blob.\n");
188 continue;
189 }
190
191 while (val && (ch = *(val++)) != 0) {
192 switch (ch) {
193 case '\'':
194 case '"':
195 next = strchr(val, ch);
196 if (next)
197 *next = 0;
198
199 strcpy(dest, val);
200
201 if (next)
202 val = next + 1;
203
204 dest += strlen(dest);
205 break;
206 case '\\':
207 *(dest++) = *(val++);
208 break;
209 }
210 }
211 blobmsg_add_string_buffer(&b);
212 }
213
214 blobmsg_close_array(&b, c);
215
216 fclose(f);
217 }
218
219 ubus_send_reply(ctx, req, b.head);
220
221 return UBUS_STATUS_OK;
222 }
223
224 static int system_info(struct ubus_context *ctx, struct ubus_object *obj,
225 struct ubus_request_data *req, const char *method,
226 struct blob_attr *msg)
227 {
228 time_t now;
229 struct tm *tm;
230 #ifdef linux
231 struct sysinfo info;
232 void *c;
233
234 if (sysinfo(&info))
235 return UBUS_STATUS_UNKNOWN_ERROR;
236 #endif
237
238 now = time(NULL);
239
240 if (!(tm = localtime(&now)))
241 return UBUS_STATUS_UNKNOWN_ERROR;
242
243 blob_buf_init(&b, 0);
244
245 blobmsg_add_u32(&b, "localtime", now + tm->tm_gmtoff);
246
247 #ifdef linux
248 blobmsg_add_u32(&b, "uptime", info.uptime);
249
250 c = blobmsg_open_array(&b, "load");
251 blobmsg_add_u32(&b, NULL, info.loads[0]);
252 blobmsg_add_u32(&b, NULL, info.loads[1]);
253 blobmsg_add_u32(&b, NULL, info.loads[2]);
254 blobmsg_close_array(&b, c);
255
256 c = blobmsg_open_table(&b, "memory");
257 blobmsg_add_u64(&b, "total", info.mem_unit * info.totalram);
258 blobmsg_add_u64(&b, "free", info.mem_unit * info.freeram);
259 blobmsg_add_u64(&b, "shared", info.mem_unit * info.sharedram);
260 blobmsg_add_u64(&b, "buffered", info.mem_unit * info.bufferram);
261 blobmsg_close_table(&b, c);
262
263 c = blobmsg_open_table(&b, "swap");
264 blobmsg_add_u64(&b, "total", info.mem_unit * info.totalswap);
265 blobmsg_add_u64(&b, "free", info.mem_unit * info.freeswap);
266 blobmsg_close_table(&b, c);
267 #endif
268
269 ubus_send_reply(ctx, req, b.head);
270
271 return UBUS_STATUS_OK;
272 }
273
274 static int system_reboot(struct ubus_context *ctx, struct ubus_object *obj,
275 struct ubus_request_data *req, const char *method,
276 struct blob_attr *msg)
277 {
278 procd_shutdown(RB_AUTOBOOT);
279 return 0;
280 }
281
282 enum {
283 WDT_FREQUENCY,
284 WDT_TIMEOUT,
285 WDT_MAGICCLOSE,
286 WDT_STOP,
287 __WDT_MAX
288 };
289
290 static const struct blobmsg_policy watchdog_policy[__WDT_MAX] = {
291 [WDT_FREQUENCY] = { .name = "frequency", .type = BLOBMSG_TYPE_INT32 },
292 [WDT_TIMEOUT] = { .name = "timeout", .type = BLOBMSG_TYPE_INT32 },
293 [WDT_MAGICCLOSE] = { .name = "magicclose", .type = BLOBMSG_TYPE_BOOL },
294 [WDT_STOP] = { .name = "stop", .type = BLOBMSG_TYPE_BOOL },
295 };
296
297 static int watchdog_set(struct ubus_context *ctx, struct ubus_object *obj,
298 struct ubus_request_data *req, const char *method,
299 struct blob_attr *msg)
300 {
301 struct blob_attr *tb[__WDT_MAX];
302 const char *status;
303
304 if (!msg)
305 return UBUS_STATUS_INVALID_ARGUMENT;
306
307 blobmsg_parse(watchdog_policy, __WDT_MAX, tb, blob_data(msg), blob_len(msg));
308 if (tb[WDT_FREQUENCY]) {
309 unsigned int timeout = tb[WDT_TIMEOUT] ? blobmsg_get_u32(tb[WDT_TIMEOUT]) :
310 watchdog_timeout(0);
311 unsigned int freq = blobmsg_get_u32(tb[WDT_FREQUENCY]);
312
313 if (freq) {
314 if (freq > timeout / 2)
315 freq = timeout / 2;
316 watchdog_frequency(freq);
317 }
318 }
319
320 if (tb[WDT_TIMEOUT]) {
321 unsigned int timeout = blobmsg_get_u32(tb[WDT_TIMEOUT]);
322 unsigned int frequency = watchdog_frequency(0);
323
324 if (timeout <= frequency)
325 timeout = frequency * 2;
326 watchdog_timeout(timeout);
327 }
328
329 if (tb[WDT_MAGICCLOSE])
330 watchdog_set_magicclose(blobmsg_get_bool(tb[WDT_MAGICCLOSE]));
331
332 if (tb[WDT_STOP])
333 watchdog_set_stopped(blobmsg_get_bool(tb[WDT_STOP]));
334
335 if (watchdog_fd() == NULL)
336 status = "offline";
337 else if (watchdog_get_stopped())
338 status = "stopped";
339 else
340 status = "running";
341
342 blob_buf_init(&b, 0);
343 blobmsg_add_string(&b, "status", status);
344 blobmsg_add_u32(&b, "timeout", watchdog_timeout(0));
345 blobmsg_add_u32(&b, "frequency", watchdog_frequency(0));
346 blobmsg_add_u8(&b, "magicclose", watchdog_get_magicclose());
347 ubus_send_reply(ctx, req, b.head);
348
349 return 0;
350 }
351
352 enum {
353 SIGNAL_PID,
354 SIGNAL_NUM,
355 __SIGNAL_MAX
356 };
357
358 static const struct blobmsg_policy signal_policy[__SIGNAL_MAX] = {
359 [SIGNAL_PID] = { .name = "pid", .type = BLOBMSG_TYPE_INT32 },
360 [SIGNAL_NUM] = { .name = "signum", .type = BLOBMSG_TYPE_INT32 },
361 };
362
363 static int proc_signal(struct ubus_context *ctx, struct ubus_object *obj,
364 struct ubus_request_data *req, const char *method,
365 struct blob_attr *msg)
366 {
367 struct blob_attr *tb[__SIGNAL_MAX];
368
369 if (!msg)
370 return UBUS_STATUS_INVALID_ARGUMENT;
371
372 blobmsg_parse(signal_policy, __SIGNAL_MAX, tb, blob_data(msg), blob_len(msg));
373 if (!tb[SIGNAL_PID || !tb[SIGNAL_NUM]])
374 return UBUS_STATUS_INVALID_ARGUMENT;
375
376 kill(blobmsg_get_u32(tb[SIGNAL_PID]), blobmsg_get_u32(tb[SIGNAL_NUM]));
377
378 return 0;
379 }
380
381 /**
382 * validate_firmware_image_call - perform validation & store result in global b
383 *
384 * @file: firmware image path
385 */
386 static int validate_firmware_image_call(const char *file)
387 {
388 const char *path = "/usr/libexec/validate_firmware_image";
389 json_object *jsobj = NULL;
390 json_tokener *tok;
391 char buf[64];
392 ssize_t len;
393 int fds[2];
394 int err;
395 int fd;
396
397 if (pipe(fds))
398 return -errno;
399
400 switch (fork()) {
401 case -1:
402 return -errno;
403 case 0:
404 /* Set stdin & stderr to /dev/null */
405 fd = open("/dev/null", O_RDWR);
406 if (fd >= 0) {
407 dup2(fd, 0);
408 dup2(fd, 2);
409 close(fd);
410 }
411
412 /* Set stdout to the shared pipe */
413 dup2(fds[1], 1);
414 close(fds[0]);
415 close(fds[1]);
416
417 execl(path, path, file, NULL);
418 exit(errno);
419 }
420
421 /* Parent process */
422
423 tok = json_tokener_new();
424 if (!tok) {
425 close(fds[0]);
426 close(fds[1]);
427 return -ENOMEM;
428 }
429
430 blob_buf_init(&b, 0);
431 while ((len = read(fds[0], buf, sizeof(buf)))) {
432 jsobj = json_tokener_parse_ex(tok, buf, len);
433
434 if (json_tokener_get_error(tok) == json_tokener_success)
435 break;
436 else if (json_tokener_get_error(tok) == json_tokener_continue)
437 continue;
438 else
439 fprintf(stderr, "Failed to parse JSON: %d\n",
440 json_tokener_get_error(tok));
441 }
442
443 close(fds[0]);
444 close(fds[1]);
445
446 err = -ENOENT;
447 if (jsobj) {
448 if (json_object_get_type(jsobj) == json_type_object) {
449 blobmsg_add_object(&b, jsobj);
450 err = 0;
451 }
452
453 json_object_put(jsobj);
454 }
455
456 json_tokener_free(tok);
457
458 return err;
459 }
460
461 enum {
462 VALIDATE_FIRMWARE_IMAGE_PATH,
463 __VALIDATE_FIRMWARE_IMAGE_MAX,
464 };
465
466 static const struct blobmsg_policy validate_firmware_image_policy[__VALIDATE_FIRMWARE_IMAGE_MAX] = {
467 [VALIDATE_FIRMWARE_IMAGE_PATH] = { .name = "path", .type = BLOBMSG_TYPE_STRING },
468 };
469
470 static int validate_firmware_image(struct ubus_context *ctx,
471 struct ubus_object *obj,
472 struct ubus_request_data *req,
473 const char *method, struct blob_attr *msg)
474 {
475 struct blob_attr *tb[__VALIDATE_FIRMWARE_IMAGE_MAX];
476
477 if (!msg)
478 return UBUS_STATUS_INVALID_ARGUMENT;
479
480 blobmsg_parse(validate_firmware_image_policy, __VALIDATE_FIRMWARE_IMAGE_MAX, tb, blob_data(msg), blob_len(msg));
481 if (!tb[VALIDATE_FIRMWARE_IMAGE_PATH])
482 return UBUS_STATUS_INVALID_ARGUMENT;
483
484 if (validate_firmware_image_call(blobmsg_get_string(tb[VALIDATE_FIRMWARE_IMAGE_PATH])))
485 return UBUS_STATUS_UNKNOWN_ERROR;
486
487 ubus_send_reply(ctx, req, b.head);
488
489 return UBUS_STATUS_OK;
490 }
491
492 enum {
493 SYSUPGRADE_PATH,
494 SYSUPGRADE_FORCE,
495 SYSUPGRADE_PREFIX,
496 SYSUPGRADE_COMMAND,
497 SYSUPGRADE_OPTIONS,
498 __SYSUPGRADE_MAX
499 };
500
501 static const struct blobmsg_policy sysupgrade_policy[__SYSUPGRADE_MAX] = {
502 [SYSUPGRADE_PATH] = { .name = "path", .type = BLOBMSG_TYPE_STRING },
503 [SYSUPGRADE_FORCE] = { .name = "force", .type = BLOBMSG_TYPE_BOOL },
504 [SYSUPGRADE_PREFIX] = { .name = "prefix", .type = BLOBMSG_TYPE_STRING },
505 [SYSUPGRADE_COMMAND] = { .name = "command", .type = BLOBMSG_TYPE_STRING },
506 [SYSUPGRADE_OPTIONS] = { .name = "options", .type = BLOBMSG_TYPE_TABLE },
507 };
508
509 static int sysupgrade(struct ubus_context *ctx, struct ubus_object *obj,
510 struct ubus_request_data *req, const char *method,
511 struct blob_attr *msg)
512 {
513 enum {
514 VALIDATION_VALID,
515 VALIDATION_FORCEABLE,
516 __VALIDATION_MAX
517 };
518 static const struct blobmsg_policy validation_policy[__VALIDATION_MAX] = {
519 [VALIDATION_VALID] = { .name = "valid", .type = BLOBMSG_TYPE_BOOL },
520 [VALIDATION_FORCEABLE] = { .name = "forceable", .type = BLOBMSG_TYPE_BOOL },
521 };
522 struct blob_attr *validation[__VALIDATION_MAX];
523 struct blob_attr *tb[__SYSUPGRADE_MAX];
524 bool valid, forceable;
525
526 if (!msg)
527 return UBUS_STATUS_INVALID_ARGUMENT;
528
529 blobmsg_parse(sysupgrade_policy, __SYSUPGRADE_MAX, tb, blob_data(msg), blob_len(msg));
530 if (!tb[SYSUPGRADE_PATH] || !tb[SYSUPGRADE_PREFIX])
531 return UBUS_STATUS_INVALID_ARGUMENT;
532
533 if (validate_firmware_image_call(blobmsg_get_string(tb[SYSUPGRADE_PATH])))
534 return UBUS_STATUS_UNKNOWN_ERROR;
535
536 blobmsg_parse(validation_policy, __VALIDATION_MAX, validation, blob_data(b.head), blob_len(b.head));
537
538 valid = validation[VALIDATION_VALID] && blobmsg_get_bool(validation[VALIDATION_VALID]);
539 forceable = validation[VALIDATION_FORCEABLE] && blobmsg_get_bool(validation[VALIDATION_FORCEABLE]);
540
541 if (!valid) {
542 if (!forceable) {
543 fprintf(stderr, "Firmware image is broken and cannot be installed\n");
544 return UBUS_STATUS_NOT_SUPPORTED;
545 } else if (!tb[SYSUPGRADE_FORCE] || !blobmsg_get_bool(tb[SYSUPGRADE_FORCE])) {
546 fprintf(stderr, "Firmware image is invalid\n");
547 return UBUS_STATUS_NOT_SUPPORTED;
548 }
549 }
550
551 sysupgrade_exec_upgraded(blobmsg_get_string(tb[SYSUPGRADE_PREFIX]),
552 blobmsg_get_string(tb[SYSUPGRADE_PATH]),
553 tb[SYSUPGRADE_COMMAND] ? blobmsg_get_string(tb[SYSUPGRADE_COMMAND]) : NULL,
554 tb[SYSUPGRADE_OPTIONS]);
555
556 /* sysupgrade_exec_upgraded() will never return unless something has gone wrong */
557 return UBUS_STATUS_UNKNOWN_ERROR;
558 }
559
560 static void
561 procd_subscribe_cb(struct ubus_context *ctx, struct ubus_object *obj)
562 {
563 notify = obj->has_subscribers;
564 }
565
566
567 static const struct ubus_method system_methods[] = {
568 UBUS_METHOD_NOARG("board", system_board),
569 UBUS_METHOD_NOARG("info", system_info),
570 UBUS_METHOD_NOARG("reboot", system_reboot),
571 UBUS_METHOD("watchdog", watchdog_set, watchdog_policy),
572 UBUS_METHOD("signal", proc_signal, signal_policy),
573 UBUS_METHOD("validate_firmware_image", validate_firmware_image, validate_firmware_image_policy),
574 UBUS_METHOD("sysupgrade", sysupgrade, sysupgrade_policy),
575 };
576
577 static struct ubus_object_type system_object_type =
578 UBUS_OBJECT_TYPE("system", system_methods);
579
580 static struct ubus_object system_object = {
581 .name = "system",
582 .type = &system_object_type,
583 .methods = system_methods,
584 .n_methods = ARRAY_SIZE(system_methods),
585 .subscribe_cb = procd_subscribe_cb,
586 };
587
588 void
589 procd_bcast_event(char *event, struct blob_attr *msg)
590 {
591 int ret;
592
593 if (!notify)
594 return;
595
596 ret = ubus_notify(_ctx, &system_object, event, msg, -1);
597 if (ret)
598 fprintf(stderr, "Failed to notify log: %s\n", ubus_strerror(ret));
599 }
600
601 void ubus_init_system(struct ubus_context *ctx)
602 {
603 int ret;
604
605 _ctx = ctx;
606 ret = ubus_add_object(ctx, &system_object);
607 if (ret)
608 ERROR("Failed to add object: %s\n", ubus_strerror(ret));
609 }