luci2: add upgrade_test, upgrade_start and upgrade_abort calls
[project/rpcd.git] / luci2.c
1 /*
2  * luci-rpcd - LuCI UBUS RPC server
3  *
4  *   Copyright (C) 2013 Jo-Philipp Wich <jow@openwrt.org>
5  *
6  * Permission to use, copy, modify, and/or distribute this software for any
7  * purpose with or without fee is hereby granted, provided that the above
8  * copyright notice and this permission notice appear in all copies.
9  *
10  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
13  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
15  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
16  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17  */
18
19 #include <fcntl.h>
20 #include <errno.h>
21 #include <unistd.h>
22 #include <stdlib.h>
23 #include <string.h>
24 #include <ctype.h>
25 #include <sys/wait.h>
26 #include <sys/stat.h>
27 #include <sys/types.h>
28 #include <sys/statvfs.h>
29 #include <dirent.h>
30 #include <arpa/inet.h>
31 #include <signal.h>
32
33 #include "luci2.h"
34 #include "exec.h"
35
36 static struct blob_buf buf;
37 static struct uci_context *cursor;
38
39 enum {
40         RPC_S_PID,
41         RPC_S_SIGNAL,
42         __RPC_S_MAX,
43 };
44
45 static const struct blobmsg_policy rpc_signal_policy[__RPC_S_MAX] = {
46         [RPC_S_PID]    = { .name = "pid",    .type = BLOBMSG_TYPE_INT32 },
47         [RPC_S_SIGNAL] = { .name = "signal", .type = BLOBMSG_TYPE_INT32 },
48 };
49
50 enum {
51         RPC_I_NAME,
52         RPC_I_ACTION,
53         __RPC_I_MAX,
54 };
55
56 static const struct blobmsg_policy rpc_init_policy[__RPC_I_MAX] = {
57         [RPC_I_NAME]   = { .name = "name",   .type = BLOBMSG_TYPE_STRING },
58         [RPC_I_ACTION] = { .name = "action", .type = BLOBMSG_TYPE_STRING },
59 };
60
61 enum {
62         RPC_D_DATA,
63         __RPC_D_MAX
64 };
65
66 static const struct blobmsg_policy rpc_data_policy[__RPC_D_MAX] = {
67         [RPC_D_DATA]   = { .name = "data",  .type = BLOBMSG_TYPE_STRING },
68 };
69
70 enum {
71         RPC_K_KEYS,
72         __RPC_K_MAX
73 };
74
75 static const struct blobmsg_policy rpc_sshkey_policy[__RPC_K_MAX] = {
76         [RPC_K_KEYS]   = { .name = "keys",   .type = BLOBMSG_TYPE_ARRAY },
77 };
78
79 enum {
80         RPC_P_USER,
81         RPC_P_PASSWORD,
82         __RPC_P_MAX
83 };
84
85 static const struct blobmsg_policy rpc_password_policy[__RPC_P_MAX] = {
86         [RPC_P_USER]     = { .name = "user",     .type = BLOBMSG_TYPE_STRING },
87         [RPC_P_PASSWORD] = { .name = "password", .type = BLOBMSG_TYPE_STRING },
88 };
89
90 enum {
91         RPC_OM_LIMIT,
92         RPC_OM_OFFSET,
93         RPC_OM_PATTERN,
94         __RPC_OM_MAX
95 };
96
97 static const struct blobmsg_policy rpc_opkg_match_policy[__RPC_OM_MAX] = {
98         [RPC_OM_LIMIT]    = { .name = "limit",    .type = BLOBMSG_TYPE_INT32  },
99         [RPC_OM_OFFSET]   = { .name = "offset",   .type = BLOBMSG_TYPE_INT32  },
100         [RPC_OM_PATTERN]  = { .name = "pattern",  .type = BLOBMSG_TYPE_STRING },
101 };
102
103 enum {
104         RPC_OP_PACKAGE,
105         __RPC_OP_MAX
106 };
107
108 static const struct blobmsg_policy rpc_opkg_package_policy[__RPC_OP_MAX] = {
109         [RPC_OP_PACKAGE]  = { .name = "package",  .type = BLOBMSG_TYPE_STRING },
110 };
111
112 enum {
113         RPC_UPGRADE_KEEP,
114         __RPC_UPGRADE_MAX
115 };
116
117 static const struct blobmsg_policy rpc_upgrade_policy[__RPC_UPGRADE_MAX] = {
118         [RPC_UPGRADE_KEEP] = { .name = "keep",    .type = BLOBMSG_TYPE_BOOL },
119 };
120
121
122 static int
123 rpc_errno_status(void)
124 {
125         switch (errno)
126         {
127         case EACCES:
128                 return UBUS_STATUS_PERMISSION_DENIED;
129
130         case ENOTDIR:
131                 return UBUS_STATUS_INVALID_ARGUMENT;
132
133         case ENOENT:
134                 return UBUS_STATUS_NOT_FOUND;
135
136         case EINVAL:
137                 return UBUS_STATUS_INVALID_ARGUMENT;
138
139         default:
140                 return UBUS_STATUS_UNKNOWN_ERROR;
141         }
142 }
143
144 static void
145 log_read(FILE *log, int logsize)
146 {
147         int len;
148         char *logbuf;
149
150         if (logsize == 0)
151                 logsize = RPC_LUCI2_DEF_LOGSIZE;
152
153         len = (logsize > RPC_LUCI2_MAX_LOGSIZE) ? RPC_LUCI2_MAX_LOGSIZE : logsize;
154         logbuf = blobmsg_alloc_string_buffer(&buf, "log", len + 1);
155
156         if (!logbuf)
157                 return;
158
159         while (logsize > RPC_LUCI2_MAX_LOGSIZE)
160         {
161                 len = logsize % RPC_LUCI2_MAX_LOGSIZE;
162
163                 if (len == 0)
164                         len = RPC_LUCI2_MAX_LOGSIZE;
165
166                 fread(logbuf, 1, len, log);
167                 logsize -= len;
168         }
169
170         len = fread(logbuf, 1, logsize, log);
171         *(logbuf + len) = 0;
172
173         blobmsg_add_string_buffer(&buf);
174 }
175
176 static int
177 rpc_luci2_system_log(struct ubus_context *ctx, struct ubus_object *obj,
178                      struct ubus_request_data *req, const char *method,
179                      struct blob_attr *msg)
180 {
181         FILE *log;
182         int logsize = 0;
183         const char *logfile = NULL;
184         struct stat st;
185         struct uci_package *p;
186         struct uci_element *e;
187         struct uci_section *s;
188         struct uci_ptr ptr = { .package = "system" };
189
190         uci_load(cursor, ptr.package, &p);
191
192         if (!p)
193                 return UBUS_STATUS_NOT_FOUND;
194
195         uci_foreach_element(&p->sections, e)
196         {
197                 s = uci_to_section(e);
198
199                 if (strcmp(s->type, "system"))
200                         continue;
201
202                 ptr.o = NULL;
203                 ptr.option = "log_type";
204                 ptr.section = e->name;
205                 uci_lookup_ptr(cursor, &ptr, NULL, true);
206                 break;
207         }
208
209         if (ptr.o && ptr.o->type == UCI_TYPE_STRING &&
210             !strcmp(ptr.o->v.string, "file"))
211         {
212                 ptr.o = NULL;
213                 ptr.option = "log_file";
214                 uci_lookup_ptr(cursor, &ptr, NULL, true);
215
216                 if (ptr.o && ptr.o->type == UCI_TYPE_STRING)
217                         logfile = ptr.o->v.string;
218                 else
219                         logfile = "/var/log/messages";
220
221                 if (stat(logfile, &st) || !(log = fopen(logfile, "r")))
222                         goto fail;
223
224                 logsize = st.st_size;
225         }
226         else
227         {
228                 ptr.o = NULL;
229                 ptr.option = "log_size";
230                 uci_lookup_ptr(cursor, &ptr, NULL, true);
231
232                 if (ptr.o && ptr.o->type == UCI_TYPE_STRING)
233                         logsize = atoi(ptr.o->v.string) * 1024;
234
235                 if (!(log = popen("logread", "r")))
236                         goto fail;
237         }
238
239         blob_buf_init(&buf, 0);
240
241         log_read(log, logsize);
242         fclose(log);
243
244         uci_unload(cursor, p);
245         ubus_send_reply(ctx, req, buf.head);
246         return 0;
247
248 fail:
249         uci_unload(cursor, p);
250         return rpc_errno_status();
251 }
252
253 static int
254 rpc_luci2_system_dmesg(struct ubus_context *ctx, struct ubus_object *obj,
255                        struct ubus_request_data *req, const char *method,
256                        struct blob_attr *msg)
257 {
258         FILE *log;
259
260         if (!(log = popen("dmesg", "r")))
261                 return rpc_errno_status();
262
263         blob_buf_init(&buf, 0);
264
265         log_read(log, RPC_LUCI2_MAX_LOGSIZE);
266         fclose(log);
267
268         ubus_send_reply(ctx, req, buf.head);
269         return 0;
270 }
271
272 static int
273 rpc_luci2_system_diskfree(struct ubus_context *ctx, struct ubus_object *obj,
274                           struct ubus_request_data *req, const char *method,
275                           struct blob_attr *msg)
276 {
277         int i;
278         void *c;
279         struct statvfs s;
280         const char *fslist[] = {
281                 "/",    "root",
282                 "/tmp", "tmp",
283         };
284
285         blob_buf_init(&buf, 0);
286
287         for (i = 0; i < sizeof(fslist) / sizeof(fslist[0]); i += 2)
288         {
289                 if (statvfs(fslist[i], &s))
290                         continue;
291
292                 c = blobmsg_open_table(&buf, fslist[i+1]);
293
294                 blobmsg_add_u32(&buf, "total", s.f_blocks * s.f_frsize);
295                 blobmsg_add_u32(&buf, "free",  s.f_bfree  * s.f_frsize);
296                 blobmsg_add_u32(&buf, "used", (s.f_blocks - s.f_bfree) * s.f_frsize);
297
298                 blobmsg_close_table(&buf, c);
299         }
300
301         ubus_send_reply(ctx, req, buf.head);
302         return 0;
303 }
304
305 static int
306 rpc_luci2_process_list(struct ubus_context *ctx, struct ubus_object *obj,
307                        struct ubus_request_data *req, const char *method,
308                        struct blob_attr *msg)
309 {
310         FILE *top;
311         void *c, *d;
312         char line[1024];
313         char *pid, *ppid, *user, *stat, *vsz, *pvsz, *pcpu, *cmd;
314
315         if (!(top = popen("/bin/busybox top -bn1", "r")))
316                 return rpc_errno_status();
317
318         blob_buf_init(&buf, 0);
319         c = blobmsg_open_array(&buf, "processes");
320
321         while (fgets(line, sizeof(line) - 1, top))
322         {
323                 pid  = strtok(line, " ");
324
325                 if (*pid < '0' || *pid > '9')
326                         continue;
327
328                 ppid = strtok(NULL, " ");
329                 user = strtok(NULL, " ");
330                 stat = strtok(NULL, " ");
331
332                 if (!stat)
333                         continue;
334
335                 if (!*(stat + 1))
336                         *(stat + 1) = ' ';
337
338                 if (!*(stat + 2))
339                         *(stat + 2) = ' ';
340
341                 *(stat + 3) = 0;
342
343                 vsz  = strtok(stat + 4, " ");
344                 pvsz = strtok(NULL, " ");
345                 pcpu = strtok(NULL, " ");
346                 cmd  = strtok(NULL, "\n");
347
348                 if (!cmd)
349                         continue;
350
351                 d = blobmsg_open_table(&buf, NULL);
352
353                 blobmsg_add_u32(&buf, "pid", atoi(pid));
354                 blobmsg_add_u32(&buf, "ppid", atoi(ppid));
355                 blobmsg_add_string(&buf, "user", user);
356                 blobmsg_add_string(&buf, "stat", stat);
357                 blobmsg_add_u32(&buf, "vsize", atoi(vsz) * 1024);
358                 blobmsg_add_u32(&buf, "vsize_percent", atoi(pvsz));
359                 blobmsg_add_u32(&buf, "cpu_percent", atoi(pcpu));
360                 blobmsg_add_string(&buf, "command", cmd);
361
362                 blobmsg_close_table(&buf, d);
363         }
364
365         fclose(top);
366         blobmsg_close_array(&buf, c);
367
368         ubus_send_reply(ctx, req, buf.head);
369         return 0;
370 }
371
372 static int
373 rpc_luci2_process_signal(struct ubus_context *ctx, struct ubus_object *obj,
374                          struct ubus_request_data *req, const char *method,
375                          struct blob_attr *msg)
376 {
377         int pid, sig;
378         struct blob_attr *tb[__RPC_S_MAX];
379
380         blobmsg_parse(rpc_signal_policy, __RPC_S_MAX, tb,
381                       blob_data(msg), blob_len(msg));
382
383         if (!tb[RPC_S_SIGNAL] || !tb[RPC_S_PID])
384         {
385                 errno = EINVAL;
386                 return rpc_errno_status();
387         }
388
389         pid = blobmsg_get_u32(tb[RPC_S_PID]);
390         sig = blobmsg_get_u32(tb[RPC_S_SIGNAL]);
391
392         if (kill(pid, sig))
393                 return rpc_errno_status();
394
395         return 0;
396 }
397
398 static int
399 rpc_luci2_init_list(struct ubus_context *ctx, struct ubus_object *obj,
400                     struct ubus_request_data *req, const char *method,
401                     struct blob_attr *msg)
402 {
403         int n;
404         void *c, *t;
405         char *p, path[PATH_MAX];
406         struct stat s;
407         struct dirent *e;
408         FILE *f;
409         DIR *d;
410
411         if (!(d = opendir("/etc/init.d")))
412                 return rpc_errno_status();
413
414         blob_buf_init(&buf, 0);
415         c = blobmsg_open_array(&buf, "initscripts");
416
417         while ((e = readdir(d)) != NULL)
418         {
419                 snprintf(path, sizeof(path) - 1, "/etc/init.d/%s", e->d_name);
420
421                 if (stat(path, &s) || !S_ISREG(s.st_mode) || !(s.st_mode & S_IXUSR))
422                         continue;
423
424                 if ((f = fopen(path, "r")) != NULL)
425                 {
426                         n = -1;
427                         p = fgets(path, sizeof(path) - 1, f);
428
429                         if (!p || !strstr(p, "/etc/rc.common"))
430                                 goto skip;
431
432                         t = blobmsg_open_table(&buf, NULL);
433
434                         blobmsg_add_string(&buf, "name", e->d_name);
435
436                         while (fgets(path, sizeof(path) - 1, f))
437                         {
438                                 p = strtok(path, "= \t");
439
440                                 if (!strcmp(p, "START") && !!(p = strtok(NULL, "= \t\n")))
441                                 {
442                                         n = atoi(p);
443                                         blobmsg_add_u32(&buf, "start", n);
444                                 }
445                                 else if (!strcmp(p, "STOP") && !!(p = strtok(NULL, "= \t\n")))
446                                 {
447                                         blobmsg_add_u32(&buf, "stop", atoi(p));
448                                         break;
449                                 }
450                         }
451
452                         if (n > -1)
453                         {
454                                 snprintf(path, sizeof(path) - 1, "/etc/rc.d/S%02d%s",
455                                          n, e->d_name);
456
457                                 blobmsg_add_u8(&buf, "enabled",
458                                                (!stat(path, &s) && (s.st_mode & S_IXUSR)));
459                         }
460                         else
461                         {
462                                 blobmsg_add_u8(&buf, "enabled", 0);
463                         }
464
465                         blobmsg_close_table(&buf, t);
466
467 skip:
468                         fclose(f);
469                 }
470         }
471
472         closedir(d);
473         blobmsg_close_array(&buf, c);
474
475         ubus_send_reply(ctx, req, buf.head);
476         return 0;
477 }
478
479 static int
480 rpc_luci2_init_action(struct ubus_context *ctx, struct ubus_object *obj,
481                       struct ubus_request_data *req, const char *method,
482                       struct blob_attr *msg)
483 {
484         int fd;
485         pid_t pid;
486         struct stat s;
487         char path[PATH_MAX];
488         const char *action;
489         struct blob_attr *tb[__RPC_I_MAX];
490
491         blobmsg_parse(rpc_init_policy, __RPC_I_MAX, tb,
492                       blob_data(msg), blob_len(msg));
493
494         if (!tb[RPC_I_NAME] || !tb[RPC_I_ACTION])
495                 return UBUS_STATUS_INVALID_ARGUMENT;
496
497         action = blobmsg_data(tb[RPC_I_ACTION]);
498
499         if (strcmp(action, "start") && strcmp(action, "stop") &&
500             strcmp(action, "reload") && strcmp(action, "restart") &&
501             strcmp(action, "enable") && strcmp(action, "disable"))
502                 return UBUS_STATUS_INVALID_ARGUMENT;
503
504         snprintf(path, sizeof(path) - 1, "/etc/init.d/%s",
505                  (char *)blobmsg_data(tb[RPC_I_NAME]));
506
507         if (stat(path, &s))
508                 return rpc_errno_status();
509
510         if (!(s.st_mode & S_IXUSR))
511                 return UBUS_STATUS_PERMISSION_DENIED;
512
513         switch ((pid = fork()))
514         {
515         case -1:
516                 return rpc_errno_status();
517
518         case 0:
519                 uloop_done();
520
521                 if ((fd = open("/dev/null", O_RDWR)) > -1)
522                 {
523                         dup2(fd, 0);
524                         dup2(fd, 1);
525                         dup2(fd, 2);
526
527                         close(fd);
528                 }
529
530                 chdir("/");
531
532                 if (execl(path, path, action, NULL))
533                         return rpc_errno_status();
534
535         default:
536                 return 0;
537         }
538 }
539
540 static int
541 rpc_luci2_rclocal_get(struct ubus_context *ctx, struct ubus_object *obj,
542                       struct ubus_request_data *req, const char *method,
543                       struct blob_attr *msg)
544 {
545         FILE *f;
546         char data[4096] = { 0 };
547
548         if (!(f = fopen("/etc/rc.local", "r")))
549                 return rpc_errno_status();
550
551         fread(data, sizeof(data) - 1, 1, f);
552         fclose(f);
553
554         blob_buf_init(&buf, 0);
555         blobmsg_add_string(&buf, "data", data);
556
557         ubus_send_reply(ctx, req, buf.head);
558         return 0;
559 }
560
561 static int
562 rpc_luci2_rclocal_set(struct ubus_context *ctx, struct ubus_object *obj,
563                       struct ubus_request_data *req, const char *method,
564                       struct blob_attr *msg)
565 {
566         FILE *f;
567         struct blob_attr *tb[__RPC_D_MAX];
568
569         blobmsg_parse(rpc_data_policy, __RPC_D_MAX, tb,
570                       blob_data(msg), blob_len(msg));
571
572         if (!tb[RPC_D_DATA] || blobmsg_data_len(tb[RPC_D_DATA]) >= 4096)
573                 return UBUS_STATUS_INVALID_ARGUMENT;
574
575         if (!(f = fopen("/etc/rc.local", "w")))
576                 return rpc_errno_status();
577
578         fwrite(blobmsg_data(tb[RPC_D_DATA]),
579                blobmsg_data_len(tb[RPC_D_DATA]) - 1, 1, f);
580
581         fclose(f);
582         return 0;
583 }
584
585 static int
586 rpc_luci2_crontab_get(struct ubus_context *ctx, struct ubus_object *obj,
587                       struct ubus_request_data *req, const char *method,
588                       struct blob_attr *msg)
589 {
590         FILE *f;
591         char data[4096] = { 0 };
592
593         if (!(f = fopen("/etc/crontabs/root", "r")))
594                 return rpc_errno_status();
595
596         fread(data, sizeof(data) - 1, 1, f);
597         fclose(f);
598
599         blob_buf_init(&buf, 0);
600         blobmsg_add_string(&buf, "data", data);
601
602         ubus_send_reply(ctx, req, buf.head);
603         return 0;
604 }
605
606 static int
607 rpc_luci2_crontab_set(struct ubus_context *ctx, struct ubus_object *obj,
608                       struct ubus_request_data *req, const char *method,
609                       struct blob_attr *msg)
610 {
611         FILE *f;
612         struct stat s;
613         struct blob_attr *tb[__RPC_D_MAX];
614
615         blobmsg_parse(rpc_data_policy, __RPC_D_MAX, tb,
616                       blob_data(msg), blob_len(msg));
617
618         if (!tb[RPC_D_DATA] || blobmsg_data_len(tb[RPC_D_DATA]) >= 4096)
619                 return UBUS_STATUS_INVALID_ARGUMENT;
620
621         if (stat("/etc/crontabs", &s) && mkdir("/etc/crontabs", 0755))
622                 return rpc_errno_status();
623
624         if (!(f = fopen("/etc/crontabs/root", "w")))
625                 return rpc_errno_status();
626
627         fwrite(blobmsg_data(tb[RPC_D_DATA]),
628                blobmsg_data_len(tb[RPC_D_DATA]) - 1, 1, f);
629
630         fclose(f);
631         return 0;
632 }
633
634 static int
635 rpc_luci2_sshkeys_get(struct ubus_context *ctx, struct ubus_object *obj,
636                       struct ubus_request_data *req, const char *method,
637                       struct blob_attr *msg)
638 {
639         FILE *f;
640         void *c;
641         char *p, line[4096];
642
643         if (!(f = fopen("/etc/dropbear/authorized_keys", "r")))
644                 return rpc_errno_status();
645
646         blob_buf_init(&buf, 0);
647         c = blobmsg_open_array(&buf, "keys");
648
649         while (fgets(line, sizeof(line) - 1, f))
650         {
651                 for (p = line + strlen(line) - 1; (p > line) && isspace(*p); p--)
652                         *p = 0;
653
654                 for (p = line; isspace(*p); p++)
655                         *p = 0;
656
657                 if (*p)
658                         blobmsg_add_string(&buf, NULL, p);
659         }
660
661         blobmsg_close_array(&buf, c);
662         fclose(f);
663
664         ubus_send_reply(ctx, req, buf.head);
665         return 0;
666 }
667
668 static int
669 rpc_luci2_sshkeys_set(struct ubus_context *ctx, struct ubus_object *obj,
670                       struct ubus_request_data *req, const char *method,
671                       struct blob_attr *msg)
672 {
673         FILE *f;
674         int rem;
675         struct blob_attr *cur, *tb[__RPC_K_MAX];
676
677         blobmsg_parse(rpc_sshkey_policy, __RPC_K_MAX, tb,
678                       blob_data(msg), blob_len(msg));
679
680         if (!tb[RPC_K_KEYS])
681                 return UBUS_STATUS_INVALID_ARGUMENT;
682
683         if (!(f = fopen("/etc/dropbear/authorized_keys", "w")))
684                 return rpc_errno_status();
685
686         blobmsg_for_each_attr(cur, tb[RPC_K_KEYS], rem)
687         {
688                 if (blobmsg_type(cur) != BLOBMSG_TYPE_STRING)
689                         continue;
690
691                 fwrite(blobmsg_data(cur), blobmsg_data_len(cur) - 1, 1, f);
692                 fwrite("\n", 1, 1, f);
693         }
694
695         fclose(f);
696         return 0;
697 }
698
699 static int
700 rpc_luci2_password_set(struct ubus_context *ctx, struct ubus_object *obj,
701                        struct ubus_request_data *req, const char *method,
702                        struct blob_attr *msg)
703 {
704         pid_t pid;
705         int fd, fds[2];
706         struct stat s;
707         struct blob_attr *tb[__RPC_P_MAX];
708
709         blobmsg_parse(rpc_password_policy, __RPC_P_MAX, tb,
710                       blob_data(msg), blob_len(msg));
711
712         if (!tb[RPC_P_USER] || !tb[RPC_P_PASSWORD])
713                 return UBUS_STATUS_INVALID_ARGUMENT;
714
715         if (stat("/usr/bin/passwd", &s))
716                 return UBUS_STATUS_NOT_FOUND;
717
718         if (!(s.st_mode & S_IXUSR))
719                 return UBUS_STATUS_PERMISSION_DENIED;
720
721         if (pipe(fds))
722                 return rpc_errno_status();
723
724         switch ((pid = fork()))
725         {
726         case -1:
727                 close(fds[0]);
728                 close(fds[1]);
729                 return rpc_errno_status();
730
731         case 0:
732                 uloop_done();
733
734                 dup2(fds[0], 0);
735                 close(fds[0]);
736                 close(fds[1]);
737
738                 if ((fd = open("/dev/null", O_RDWR)) > -1)
739                 {
740                         dup2(fd, 1);
741                         dup2(fd, 2);
742                         close(fd);
743                 }
744
745                 chdir("/");
746
747                 if (execl("/usr/bin/passwd", "/usr/bin/passwd",
748                           blobmsg_data(tb[RPC_P_USER]), NULL))
749                         return rpc_errno_status();
750
751         default:
752                 close(fds[0]);
753
754                 write(fds[1], blobmsg_data(tb[RPC_P_PASSWORD]),
755                               blobmsg_data_len(tb[RPC_P_PASSWORD]) - 1);
756                 write(fds[1], "\n", 1);
757
758                 usleep(100 * 1000);
759
760                 write(fds[1], blobmsg_data(tb[RPC_P_PASSWORD]),
761                               blobmsg_data_len(tb[RPC_P_PASSWORD]) - 1);
762                 write(fds[1], "\n", 1);
763
764                 close(fds[1]);
765
766                 waitpid(pid, NULL, 0);
767
768                 return 0;
769         }
770 }
771
772 static int
773 rpc_luci2_led_list(struct ubus_context *ctx, struct ubus_object *obj,
774                    struct ubus_request_data *req, const char *method,
775                    struct blob_attr *msg)
776 {
777         DIR *d;
778         FILE *f;
779         void *list, *led, *trigger;
780         char *p, *active_trigger, line[512];
781         struct dirent *e;
782
783         if (!(d = opendir("/sys/class/leds")))
784                 return rpc_errno_status();
785
786         blob_buf_init(&buf, 0);
787         list = blobmsg_open_array(&buf, "leds");
788
789         while ((e = readdir(d)) != NULL)
790         {
791                 snprintf(line, sizeof(line) - 1, "/sys/class/leds/%s/trigger",
792                          e->d_name);
793
794                 if (!(f = fopen(line, "r")))
795                         continue;
796
797                 led = blobmsg_open_table(&buf, NULL);
798
799                 blobmsg_add_string(&buf, "name", e->d_name);
800
801                 if (fgets(line, sizeof(line) - 1, f))
802                 {
803                         trigger = blobmsg_open_array(&buf, "triggers");
804
805                         for (p = strtok(line, " \n"), active_trigger = NULL;
806                              p != NULL;
807                              p = strtok(NULL, " \n"))
808                         {
809                                 if (*p == '[')
810                                 {
811                                         *(p + strlen(p) - 1) = 0;
812                                         *p++ = 0;
813                                         active_trigger = p;
814                                 }
815
816                                 blobmsg_add_string(&buf, NULL, p);
817                         }
818
819                         blobmsg_close_array(&buf, trigger);
820
821                         if (active_trigger)
822                                 blobmsg_add_string(&buf, "active_trigger", active_trigger);
823                 }
824
825                 fclose(f);
826
827                 snprintf(line, sizeof(line) - 1, "/sys/class/leds/%s/brightness",
828                          e->d_name);
829
830                 if ((f = fopen(line, "r")) != NULL)
831                 {
832                         if (fgets(line, sizeof(line) - 1, f))
833                                 blobmsg_add_u32(&buf, "brightness", atoi(line));
834
835                         fclose(f);
836                 }
837
838                 snprintf(line, sizeof(line) - 1, "/sys/class/leds/%s/max_brightness",
839                          e->d_name);
840
841                 if ((f = fopen(line, "r")) != NULL)
842                 {
843                         if (fgets(line, sizeof(line) - 1, f))
844                                 blobmsg_add_u32(&buf, "max_brightness", atoi(line));
845
846                         fclose(f);
847                 }
848
849                 blobmsg_close_table(&buf, led);
850         }
851
852         closedir(d);
853
854         blobmsg_close_array(&buf, list);
855         ubus_send_reply(ctx, req, buf.head);
856
857         return 0;
858 }
859
860 static int
861 rpc_luci2_usb_list(struct ubus_context *ctx, struct ubus_object *obj,
862                    struct ubus_request_data *req, const char *method,
863                    struct blob_attr *msg)
864 {
865         DIR *d;
866         FILE *f;
867         int i;
868         void *list, *device;
869         char *p, line[512];
870         struct stat s;
871         struct dirent *e;
872
873         const char *attributes[] = {
874                 "manufacturer", "vendor_name",  "s",
875                 "product",      "product_name", "s",
876                 "idVendor",     "vendor_id",    "x",
877                 "idProduct",    "product_id",   "x",
878                 "serial",       "serial",       "s",
879                 "speed",        "speed",        "d",
880         };
881
882         if (!(d = opendir("/sys/bus/usb/devices")))
883                 return rpc_errno_status();
884
885         blob_buf_init(&buf, 0);
886         list = blobmsg_open_array(&buf, "devices");
887
888         while ((e = readdir(d)) != NULL)
889         {
890                 if (e->d_name[0] < '0' || e->d_name[0] > '9')
891                         continue;
892
893                 snprintf(line, sizeof(line) - 1,
894                          "/sys/bus/usb/devices/%s/%s", e->d_name, attributes[0]);
895
896                 if (stat(line, &s))
897                         continue;
898
899                 device = blobmsg_open_table(&buf, NULL);
900
901                 blobmsg_add_string(&buf, "name", e->d_name);
902
903                 for (i = 0; i < sizeof(attributes) / sizeof(attributes[0]); i += 3)
904                 {
905                         snprintf(line, sizeof(line) - 1,
906                                          "/sys/bus/usb/devices/%s/%s", e->d_name, attributes[i]);
907
908                         if (!(f = fopen(line, "r")))
909                                 continue;
910
911                         if (fgets(line, sizeof(line) - 1, f))
912                         {
913                                 switch (*attributes[i+2])
914                                 {
915                                 case 'x':
916                                         blobmsg_add_u32(&buf, attributes[i+1],
917                                                         strtoul(line, NULL, 16));
918                                         break;
919
920                                 case 'd':
921                                         blobmsg_add_u32(&buf, attributes[i+1],
922                                                         strtoul(line, NULL, 10));
923                                         break;
924
925                                 default:
926                                         if ((p = strchr(line, '\n')) != NULL)
927                                                 while (p > line && isspace(*p))
928                                                         *p-- = 0;
929
930                                         blobmsg_add_string(&buf, attributes[i+1], line);
931                                         break;
932                                 }
933                         }
934
935                         fclose(f);
936                 }
937
938                 blobmsg_close_table(&buf, device);
939         }
940
941         closedir(d);
942
943         blobmsg_close_array(&buf, list);
944         ubus_send_reply(ctx, req, buf.head);
945
946         return 0;
947 }
948
949 static int
950 rpc_luci2_upgrade_test(struct ubus_context *ctx, struct ubus_object *obj,
951                        struct ubus_request_data *req, const char *method,
952                        struct blob_attr *msg)
953 {
954         const char *cmd[4] = { "sysupgrade", "--test", "/tmp/firmware.bin", NULL };
955         return rpc_exec(cmd, NULL, NULL, NULL, NULL, ctx, req);
956 }
957
958 static int
959 rpc_luci2_upgrade_start(struct ubus_context *ctx, struct ubus_object *obj,
960                         struct ubus_request_data *req, const char *method,
961                         struct blob_attr *msg)
962 {
963         return 0;
964 }
965
966 static int
967 rpc_luci2_upgrade_abort(struct ubus_context *ctx, struct ubus_object *obj,
968                         struct ubus_request_data *req, const char *method,
969                         struct blob_attr *msg)
970 {
971         unlink("/tmp/firmware.bin");
972         return 0;
973 }
974
975
976 static FILE *
977 dnsmasq_leasefile(void)
978 {
979         FILE *leases = NULL;
980         struct uci_package *p;
981         struct uci_element *e;
982         struct uci_section *s;
983         struct uci_ptr ptr = {
984                 .package = "dhcp",
985                 .section = NULL,
986                 .option  = "leasefile"
987         };
988
989         uci_load(cursor, ptr.package, &p);
990
991         if (!p)
992                 return NULL;
993
994         uci_foreach_element(&p->sections, e)
995         {
996                 s = uci_to_section(e);
997
998                 if (strcmp(s->type, "dnsmasq"))
999                         continue;
1000
1001                 ptr.section = e->name;
1002                 uci_lookup_ptr(cursor, &ptr, NULL, true);
1003                 break;
1004         }
1005
1006         if (ptr.o && ptr.o->type == UCI_TYPE_STRING)
1007                 leases = fopen(ptr.o->v.string, "r");
1008
1009         uci_unload(cursor, p);
1010
1011         return leases;
1012 }
1013
1014 static int
1015 rpc_luci2_network_leases(struct ubus_context *ctx, struct ubus_object *obj,
1016                          struct ubus_request_data *req, const char *method,
1017                          struct blob_attr *msg)
1018 {
1019         FILE *leases;
1020         void *c, *d;
1021         char line[128];
1022         char *ts, *mac, *addr, *name;
1023         time_t now = time(NULL);
1024
1025         blob_buf_init(&buf, 0);
1026         c = blobmsg_open_array(&buf, "leases");
1027
1028         leases = dnsmasq_leasefile();
1029
1030         if (!leases)
1031                 goto out;
1032
1033         while (fgets(line, sizeof(line) - 1, leases))
1034         {
1035                 ts   = strtok(line, " \t");
1036                 mac  = strtok(NULL, " \t");
1037                 addr = strtok(NULL, " \t");
1038                 name = strtok(NULL, " \t");
1039
1040                 if (!ts || !mac || !addr || !name)
1041                         continue;
1042
1043                 if (strchr(addr, ':'))
1044                         continue;
1045
1046                 d = blobmsg_open_table(&buf, NULL);
1047
1048                 blobmsg_add_u32(&buf, "expires", atoi(ts) - now);
1049                 blobmsg_add_string(&buf, "macaddr", mac);
1050                 blobmsg_add_string(&buf, "ipaddr", addr);
1051
1052                 if (strcmp(name, "*"))
1053                         blobmsg_add_string(&buf, "hostname", name);
1054
1055                 blobmsg_close_table(&buf, d);
1056         }
1057
1058         fclose(leases);
1059
1060 out:
1061         blobmsg_close_array(&buf, c);
1062         ubus_send_reply(ctx, req, buf.head);
1063
1064         return 0;
1065 }
1066
1067 static int
1068 rpc_luci2_network_leases6(struct ubus_context *ctx, struct ubus_object *obj,
1069                           struct ubus_request_data *req, const char *method,
1070                           struct blob_attr *msg)
1071 {
1072         FILE *leases;
1073         void *c, *d;
1074         char line[128];
1075         char *ts, *mac, *addr, *name, *duid;
1076         time_t now = time(NULL);
1077
1078         blob_buf_init(&buf, 0);
1079         c = blobmsg_open_array(&buf, "leases");
1080
1081         leases = fopen("/tmp/hosts/6relayd", "r");
1082
1083         if (leases)
1084         {
1085                 while (fgets(line, sizeof(line) - 1, leases))
1086                 {
1087                         if (strncmp(line, "# ", 2))
1088                                 continue;
1089
1090                         strtok(line + 2, " \t"); /* iface */
1091
1092                         duid = strtok(NULL, " \t");
1093
1094                         strtok(NULL, " \t"); /* iaid */
1095
1096                         name = strtok(NULL, " \t");
1097                         ts   = strtok(NULL, " \t");
1098
1099                         strtok(NULL, " \t"); /* id */
1100                         strtok(NULL, " \t"); /* length */
1101
1102                         addr = strtok(NULL, " \t\n");
1103
1104                         if (!addr)
1105                                 continue;
1106
1107                         d = blobmsg_open_table(&buf, NULL);
1108
1109                         blobmsg_add_u32(&buf, "expires", atoi(ts) - now);
1110                         blobmsg_add_string(&buf, "duid", duid);
1111                         blobmsg_add_string(&buf, "ip6addr", addr);
1112
1113                         if (strcmp(name, "-"))
1114                                 blobmsg_add_string(&buf, "hostname", name);
1115
1116                         blobmsg_close_array(&buf, d);
1117                 }
1118
1119                 fclose(leases);
1120         }
1121         else
1122         {
1123                 leases = dnsmasq_leasefile();
1124
1125                 if (!leases)
1126                         goto out;
1127
1128                 while (fgets(line, sizeof(line) - 1, leases))
1129                 {
1130                         ts   = strtok(line, " \t");
1131                         mac  = strtok(NULL, " \t");
1132                         addr = strtok(NULL, " \t");
1133                         name = strtok(NULL, " \t");
1134                         duid = strtok(NULL, " \t\n");
1135
1136                         if (!ts || !mac || !addr || !duid)
1137                                 continue;
1138
1139                         if (!strchr(addr, ':'))
1140                                 continue;
1141
1142                         d = blobmsg_open_table(&buf, NULL);
1143
1144                         blobmsg_add_u32(&buf, "expires", atoi(ts) - now);
1145                         blobmsg_add_string(&buf, "macaddr", mac);
1146                         blobmsg_add_string(&buf, "ip6addr", addr);
1147
1148                         if (strcmp(name, "*"))
1149                                 blobmsg_add_string(&buf, "hostname", name);
1150
1151                         if (strcmp(duid, "*"))
1152                                 blobmsg_add_string(&buf, "duid", name);
1153
1154                         blobmsg_close_table(&buf, d);
1155                 }
1156
1157                 fclose(leases);
1158         }
1159
1160 out:
1161         blobmsg_close_array(&buf, c);
1162         ubus_send_reply(ctx, req, buf.head);
1163
1164         return 0;
1165 }
1166
1167 static int
1168 rpc_luci2_network_ct_count(struct ubus_context *ctx, struct ubus_object *obj,
1169                            struct ubus_request_data *req, const char *method,
1170                            struct blob_attr *msg)
1171 {
1172         FILE *f;
1173         char line[128];
1174
1175         blob_buf_init(&buf, 0);
1176
1177         if ((f = fopen("/proc/sys/net/netfilter/nf_conntrack_count", "r")) != NULL)
1178         {
1179                 if (fgets(line, sizeof(line) - 1, f))
1180                         blobmsg_add_u32(&buf, "count", atoi(line));
1181
1182                 fclose(f);
1183         }
1184
1185         if ((f = fopen("/proc/sys/net/netfilter/nf_conntrack_max", "r")) != NULL)
1186         {
1187                 if (fgets(line, sizeof(line) - 1, f))
1188                         blobmsg_add_u32(&buf, "limit", atoi(line));
1189
1190                 fclose(f);
1191         }
1192
1193         ubus_send_reply(ctx, req, buf.head);
1194
1195         return 0;
1196 }
1197
1198 static int
1199 rpc_luci2_network_ct_table(struct ubus_context *ctx, struct ubus_object *obj,
1200                            struct ubus_request_data *req, const char *method,
1201                            struct blob_attr *msg)
1202 {
1203         FILE *f;
1204         int i;
1205         void *c, *d;
1206         char *p, line[512];
1207         bool seen[6];
1208
1209         blob_buf_init(&buf, 0);
1210         c = blobmsg_open_array(&buf, "entries");
1211
1212         if ((f = fopen("/proc/net/nf_conntrack", "r")) != NULL)
1213         {
1214                 while (fgets(line, sizeof(line) - 1, f))
1215                 {
1216                         d = blobmsg_open_table(&buf, NULL);
1217                         memset(seen, 0, sizeof(seen));
1218
1219                         for (i = 0, p = strtok(line, " "); p; i++, p = strtok(NULL, " "))
1220                         {
1221                                 if (i == 0)
1222                                         blobmsg_add_u8(&buf, "ipv6", !strcmp(p, "ipv6"));
1223                                 else if (i == 3)
1224                                         blobmsg_add_u32(&buf, "protocol", atoi(p));
1225                                 else if (i == 4)
1226                                         blobmsg_add_u32(&buf, "expires", atoi(p));
1227                                 else if (i >= 5)
1228                                 {
1229                                         if (*p == '[')
1230                                                 continue;
1231
1232                                         if (!seen[0] && !strncmp(p, "src=", 4))
1233                                         {
1234                                                 blobmsg_add_string(&buf, "src", p + 4);
1235                                                 seen[0] = true;
1236                                         }
1237                                         else if (!seen[1] && !strncmp(p, "dst=", 4))
1238                                         {
1239                                                 blobmsg_add_string(&buf, "dest", p + 4);
1240                                                 seen[1] = true;
1241                                         }
1242                                         else if (!seen[2] && !strncmp(p, "sport=", 6))
1243                                         {
1244                                                 blobmsg_add_u32(&buf, "sport", atoi(p + 6));
1245                                                 seen[2] = true;
1246                                         }
1247                                         else if (!seen[3] && !strncmp(p, "dport=", 6))
1248                                         {
1249                                                 blobmsg_add_u32(&buf, "dport", atoi(p + 6));
1250                                                 seen[3] = true;
1251                                         }
1252                                         else if (!strncmp(p, "packets=", 8))
1253                                         {
1254                                                 blobmsg_add_u32(&buf,
1255                                                                 seen[4] ? "tx_packets" : "rx_packets",
1256                                                                 atoi(p + 8));
1257                                                 seen[4] = true;
1258                                         }
1259                                         else if (!strncmp(p, "bytes=", 6))
1260                                         {
1261                                                 blobmsg_add_u32(&buf,
1262                                                                                 seen[5] ? "tx_bytes" : "rx_bytes",
1263                                                                 atoi(p + 6));
1264                                                 seen[5] = true;
1265                                         }
1266                                 }
1267                         }
1268
1269                         blobmsg_close_table(&buf, d);
1270                 }
1271
1272                 fclose(f);
1273         }
1274
1275         blobmsg_close_array(&buf, c);
1276         ubus_send_reply(ctx, req, buf.head);
1277
1278         return 0;
1279 }
1280
1281 static int
1282 rpc_luci2_network_arp_table(struct ubus_context *ctx, struct ubus_object *obj,
1283                             struct ubus_request_data *req, const char *method,
1284                             struct blob_attr *msg)
1285 {
1286         FILE *f;
1287         void *c, *d;
1288         char *addr, *mac, *dev, line[128];
1289
1290         blob_buf_init(&buf, 0);
1291         c = blobmsg_open_array(&buf, "entries");
1292
1293         if ((f = fopen("/proc/net/arp", "r")) != NULL)
1294         {
1295                 /* skip header line */
1296                 fgets(line, sizeof(line) - 1, f);
1297
1298                 while (fgets(line, sizeof(line) - 1, f))
1299                 {
1300                         addr = strtok(line, " \t");
1301
1302                         strtok(NULL, " \t"); /* HW type */
1303                         strtok(NULL, " \t"); /* Flags */
1304
1305                         mac = strtok(NULL, " \t");
1306
1307                         strtok(NULL, " \t"); /* Mask */
1308
1309                         dev = strtok(NULL, " \t\n");
1310
1311                         if (!dev)
1312                                 continue;
1313
1314                         d = blobmsg_open_table(&buf, NULL);
1315                         blobmsg_add_string(&buf, "ipaddr", addr);
1316                         blobmsg_add_string(&buf, "macaddr", mac);
1317                         blobmsg_add_string(&buf, "device", dev);
1318                         blobmsg_close_table(&buf, d);
1319                 }
1320
1321                 fclose(f);
1322         }
1323
1324         blobmsg_close_array(&buf, c);
1325         ubus_send_reply(ctx, req, buf.head);
1326
1327         return 0;
1328 }
1329
1330 static void
1331 put_hexaddr(const char *name, const char *s, const char *m)
1332 {
1333         int bits;
1334         struct in_addr a;
1335         char as[sizeof("255.255.255.255/32\0")];
1336
1337         a.s_addr = strtoul(s, NULL, 16);
1338         inet_ntop(AF_INET, &a, as, sizeof(as));
1339
1340         if (m)
1341         {
1342                 for (a.s_addr = ntohl(strtoul(m, NULL, 16)), bits = 0;
1343                      a.s_addr & 0x80000000;
1344                      a.s_addr <<= 1)
1345                         bits++;
1346
1347                 sprintf(as + strlen(as), "/%u", bits);
1348         }
1349
1350         blobmsg_add_string(&buf, name, as);
1351 }
1352
1353 static int
1354 rpc_luci2_network_routes(struct ubus_context *ctx, struct ubus_object *obj,
1355                          struct ubus_request_data *req, const char *method,
1356                          struct blob_attr *msg)
1357 {
1358         FILE *routes;
1359         void *c, *d;
1360         char *dst, *dmask, *next, *metric, *device;
1361         char line[256];
1362         unsigned int n;
1363
1364         if (!(routes = fopen("/proc/net/route", "r")))
1365                 return rpc_errno_status();
1366
1367         blob_buf_init(&buf, 0);
1368         c = blobmsg_open_array(&buf, "routes");
1369
1370         /* skip header line */
1371         fgets(line, sizeof(line) - 1, routes);
1372
1373         while (fgets(line, sizeof(line) - 1, routes))
1374         {
1375                 device = strtok(line, "\t ");
1376                 dst    = strtok(NULL, "\t ");
1377                 next   = strtok(NULL, "\t ");
1378
1379                 strtok(NULL, "\t "); /* flags */
1380                 strtok(NULL, "\t "); /* refcount */
1381                 strtok(NULL, "\t "); /* usecount */
1382
1383                 metric = strtok(NULL, "\t ");
1384                 dmask  = strtok(NULL, "\t ");
1385
1386                 if (!dmask)
1387                         continue;
1388
1389                 d = blobmsg_open_table(&buf, NULL);
1390
1391                 put_hexaddr("target", dst, dmask);
1392                 put_hexaddr("nexthop", next, NULL);
1393
1394                 n = strtoul(metric, NULL, 10);
1395                 blobmsg_add_u32(&buf, "metric", n);
1396
1397                 blobmsg_add_string(&buf, "device", device);
1398
1399                 blobmsg_close_table(&buf, d);
1400         }
1401
1402         blobmsg_close_array(&buf, c);
1403         fclose(routes);
1404
1405         ubus_send_reply(ctx, req, buf.head);
1406         return 0;
1407 }
1408
1409 static void
1410 put_hex6addr(const char *name, const char *s, const char *m)
1411 {
1412         int i;
1413         struct in6_addr a;
1414         char as[INET6_ADDRSTRLEN + sizeof("/128")];
1415
1416 #define hex(x) \
1417         (((x) <= '9') ? ((x) - '0') : \
1418                 (((x) <= 'F') ? ((x) - 'A' + 10) : \
1419                         ((x) - 'a' + 10)))
1420
1421         for (i = 0; i < 16; i++, s += 2)
1422                 a.s6_addr[i] = (16 * hex(*s)) + hex(*(s+1));
1423
1424         inet_ntop(AF_INET6, &a, as, sizeof(as));
1425
1426         if (m)
1427                 sprintf(as + strlen(as), "/%lu", strtoul(m, NULL, 16));
1428
1429         blobmsg_add_string(&buf, name, as);
1430 }
1431
1432 static int
1433 rpc_luci2_network_routes6(struct ubus_context *ctx, struct ubus_object *obj,
1434                           struct ubus_request_data *req, const char *method,
1435                           struct blob_attr *msg)
1436 {
1437         FILE *routes;
1438         void *c, *d;
1439         char *src, *smask, *dst, *dmask, *next, *metric, *flags, *device;
1440         char line[256];
1441         unsigned int n;
1442
1443         if (!(routes = fopen("/proc/net/ipv6_route", "r")))
1444                 return rpc_errno_status();
1445
1446         blob_buf_init(&buf, 0);
1447         c = blobmsg_open_array(&buf, "routes");
1448
1449         while (fgets(line, sizeof(line) - 1, routes))
1450         {
1451                 dst    = strtok(line, " ");
1452                 dmask  = strtok(NULL, " ");
1453                 src    = strtok(NULL, " ");
1454                 smask  = strtok(NULL, " ");
1455                 next   = strtok(NULL, " ");
1456                 metric = strtok(NULL, " ");
1457
1458                 strtok(NULL, " "); /* refcount */
1459                 strtok(NULL, " "); /* usecount */
1460
1461                 flags  = strtok(NULL, " ");
1462                 device = strtok(NULL, " \n");
1463
1464                 if (!device)
1465                         continue;
1466
1467                 n = strtoul(flags, NULL, 16);
1468
1469                 if (!(n & 1))
1470                         continue;
1471
1472                 d = blobmsg_open_table(&buf, NULL);
1473
1474                 put_hex6addr("target", dst, dmask);
1475                 put_hex6addr("source", src, smask);
1476                 put_hex6addr("nexthop", next, NULL);
1477
1478                 n = strtoul(metric, NULL, 16);
1479                 blobmsg_add_u32(&buf, "metric", n);
1480
1481                 blobmsg_add_string(&buf, "device", device);
1482
1483                 blobmsg_close_table(&buf, d);
1484         }
1485
1486         blobmsg_close_array(&buf, c);
1487         fclose(routes);
1488
1489         ubus_send_reply(ctx, req, buf.head);
1490         return 0;
1491 }
1492
1493
1494 struct opkg_state {
1495         int cur_offset;
1496         int cur_count;
1497         int req_offset;
1498         int req_count;
1499         int total;
1500         bool open;
1501         void *array;
1502 };
1503
1504 static int
1505 opkg_parse_list(struct blob_buf *blob, char *buf, int len, void *priv)
1506 {
1507         struct opkg_state *s = priv;
1508
1509         char *ptr, *last;
1510         char *nl = strchr(buf, '\n');
1511         char *name = NULL, *vers = NULL, *desc = NULL;
1512         void *c;
1513
1514         if (!nl)
1515                 return 0;
1516
1517         s->total++;
1518
1519         if (s->cur_offset++ < s->req_offset)
1520                 goto skip;
1521
1522         if (s->cur_count++ >= s->req_count)
1523                 goto skip;
1524
1525         if (!s->open)
1526         {
1527                 s->open  = true;
1528                 s->array = blobmsg_open_array(blob, "packages");
1529         }
1530
1531         for (ptr = buf, last = buf, *nl = 0; ptr <= nl; ptr++)
1532         {
1533                 if (!*ptr || (*ptr == ' ' && *(ptr+1) == '-' && *(ptr+2) == ' '))
1534                 {
1535                         if (!name)
1536                         {
1537                                 name = last;
1538                                 last = ptr + 3;
1539                                 *ptr = 0;
1540                                 ptr += 2;
1541                         }
1542                         else if (!vers)
1543                         {
1544                                 vers = last;
1545                                 desc = *ptr ? (ptr + 3) : NULL;
1546                                 *ptr = 0;
1547                                 break;
1548                         }
1549                 }
1550         }
1551
1552         if (name && vers)
1553         {
1554                 c = blobmsg_open_array(blob, NULL);
1555
1556                 blobmsg_add_string(blob, NULL, name);
1557                 blobmsg_add_string(blob, NULL, vers);
1558
1559                 if (desc && *desc)
1560                         blobmsg_add_string(blob, NULL, desc);
1561
1562                 blobmsg_close_array(blob, c);
1563         }
1564
1565 skip:
1566         return (nl - buf + 1);
1567 }
1568
1569 static void
1570 opkg_finish_list(struct blob_buf *blob, int status, void *priv)
1571 {
1572         struct opkg_state *s = priv;
1573
1574         if (!s->open)
1575                 return;
1576
1577         blobmsg_close_array(blob, s->array);
1578         blobmsg_add_u32(blob, "total", s->total);
1579 }
1580
1581 static int
1582 opkg_exec_list(const char *action, struct blob_attr *msg,
1583                struct ubus_context *ctx, struct ubus_request_data *req)
1584 {
1585         struct opkg_state *state = NULL;
1586         struct blob_attr *tb[__RPC_OM_MAX];
1587         const char *cmd[5] = { "opkg", action, "-nocase", NULL, NULL };
1588
1589         blobmsg_parse(rpc_opkg_match_policy, __RPC_OM_MAX, tb,
1590                       blob_data(msg), blob_len(msg));
1591
1592         state = malloc(sizeof(*state));
1593
1594         if (!state)
1595                 return UBUS_STATUS_UNKNOWN_ERROR;
1596
1597         memset(state, 0, sizeof(*state));
1598
1599         if (tb[RPC_OM_PATTERN])
1600                 cmd[3] = blobmsg_data(tb[RPC_OM_PATTERN]);
1601
1602         if (tb[RPC_OM_LIMIT])
1603                 state->req_count = blobmsg_get_u32(tb[RPC_OM_LIMIT]);
1604
1605         if (tb[RPC_OM_OFFSET])
1606                 state->req_offset = blobmsg_get_u32(tb[RPC_OM_OFFSET]);
1607
1608         if (state->req_offset < 0)
1609                 state->req_offset = 0;
1610
1611         if (state->req_count <= 0 || state->req_count > 100)
1612                 state->req_count = 100;
1613
1614         return rpc_exec(cmd, opkg_parse_list, NULL, opkg_finish_list,
1615                         state, ctx, req);
1616 }
1617
1618
1619 static int
1620 rpc_luci2_opkg_list(struct ubus_context *ctx, struct ubus_object *obj,
1621                     struct ubus_request_data *req, const char *method,
1622                     struct blob_attr *msg)
1623 {
1624         return opkg_exec_list("list", msg, ctx, req);
1625 }
1626
1627 static int
1628 rpc_luci2_opkg_list_installed(struct ubus_context *ctx, struct ubus_object *obj,
1629                               struct ubus_request_data *req, const char *method,
1630                               struct blob_attr *msg)
1631 {
1632         return opkg_exec_list("list-installed", msg, ctx, req);
1633 }
1634
1635 static int
1636 rpc_luci2_opkg_find(struct ubus_context *ctx, struct ubus_object *obj,
1637                     struct ubus_request_data *req, const char *method,
1638                     struct blob_attr *msg)
1639 {
1640         return opkg_exec_list("find", msg, ctx, req);
1641 }
1642
1643 static int
1644 rpc_luci2_opkg_update(struct ubus_context *ctx, struct ubus_object *obj,
1645                       struct ubus_request_data *req, const char *method,
1646                       struct blob_attr *msg)
1647 {
1648         const char *cmd[3] = { "opkg", "update", NULL };
1649         return rpc_exec(cmd, NULL, NULL, NULL, NULL, ctx, req);
1650 }
1651
1652 static int
1653 rpc_luci2_opkg_install(struct ubus_context *ctx, struct ubus_object *obj,
1654                        struct ubus_request_data *req, const char *method,
1655                        struct blob_attr *msg)
1656 {
1657         struct blob_attr *tb[__RPC_OP_MAX];
1658         const char *cmd[5] = { "opkg", "--force-overwrite",
1659                                "install", NULL, NULL };
1660
1661         blobmsg_parse(rpc_opkg_package_policy, __RPC_OP_MAX, tb,
1662                       blob_data(msg), blob_len(msg));
1663
1664         if (!tb[RPC_OP_PACKAGE])
1665                 return UBUS_STATUS_INVALID_ARGUMENT;
1666
1667         cmd[3] = blobmsg_data(tb[RPC_OP_PACKAGE]);
1668
1669         return rpc_exec(cmd, NULL, NULL, NULL, NULL, ctx, req);
1670 }
1671
1672 static int
1673 rpc_luci2_opkg_remove(struct ubus_context *ctx, struct ubus_object *obj,
1674                       struct ubus_request_data *req, const char *method,
1675                       struct blob_attr *msg)
1676 {
1677         struct blob_attr *tb[__RPC_OP_MAX];
1678         const char *cmd[5] = { "opkg", "--force-removal-of-dependent-packages",
1679                                "remove", NULL, NULL };
1680
1681         blobmsg_parse(rpc_opkg_package_policy, __RPC_OP_MAX, tb,
1682                       blob_data(msg), blob_len(msg));
1683
1684         if (!tb[RPC_OP_PACKAGE])
1685                 return UBUS_STATUS_INVALID_ARGUMENT;
1686
1687         cmd[3] = blobmsg_data(tb[RPC_OP_PACKAGE]);
1688
1689         return rpc_exec(cmd, NULL, NULL, NULL, NULL, ctx, req);
1690 }
1691
1692 static int
1693 rpc_luci2_opkg_config_get(struct ubus_context *ctx, struct ubus_object *obj,
1694                           struct ubus_request_data *req, const char *method,
1695                           struct blob_attr *msg)
1696 {
1697         FILE *f;
1698         char conf[2048] = { 0 };
1699
1700         if (!(f = fopen("/etc/opkg.conf", "r")))
1701                 return rpc_errno_status();
1702
1703         fread(conf, sizeof(conf) - 1, 1, f);
1704         fclose(f);
1705
1706         blob_buf_init(&buf, 0);
1707         blobmsg_add_string(&buf, "config", conf);
1708
1709         ubus_send_reply(ctx, req, buf.head);
1710         return 0;
1711 }
1712
1713 static int
1714 rpc_luci2_opkg_config_set(struct ubus_context *ctx, struct ubus_object *obj,
1715                           struct ubus_request_data *req, const char *method,
1716                           struct blob_attr *msg)
1717 {
1718         FILE *f;
1719         struct blob_attr *tb[__RPC_D_MAX];
1720
1721         blobmsg_parse(rpc_data_policy, __RPC_D_MAX, tb,
1722                       blob_data(msg), blob_len(msg));
1723
1724         if (!tb[RPC_D_DATA])
1725                 return UBUS_STATUS_INVALID_ARGUMENT;
1726
1727         if (blobmsg_data_len(tb[RPC_D_DATA]) >= 2048)
1728                 return UBUS_STATUS_NOT_SUPPORTED;
1729
1730         if (!(f = fopen("/etc/opkg.conf", "w")))
1731                 return rpc_errno_status();
1732
1733         fwrite(blobmsg_data(tb[RPC_D_DATA]),
1734                blobmsg_data_len(tb[RPC_D_DATA]), 1, f);
1735
1736         fclose(f);
1737         return 0;
1738 }
1739
1740
1741 int rpc_luci2_api_init(struct ubus_context *ctx)
1742 {
1743         int rv = 0;
1744
1745         static const struct ubus_method luci2_system_methods[] = {
1746                 UBUS_METHOD_NOARG("syslog",       rpc_luci2_system_log),
1747                 UBUS_METHOD_NOARG("dmesg",        rpc_luci2_system_dmesg),
1748                 UBUS_METHOD_NOARG("diskfree",     rpc_luci2_system_diskfree),
1749                 UBUS_METHOD_NOARG("process_list", rpc_luci2_process_list),
1750                 UBUS_METHOD("process_signal",     rpc_luci2_process_signal,
1751                                                   rpc_signal_policy),
1752                 UBUS_METHOD_NOARG("init_list",    rpc_luci2_init_list),
1753                 UBUS_METHOD("init_action",        rpc_luci2_init_action,
1754                                                   rpc_init_policy),
1755                 UBUS_METHOD_NOARG("rclocal_get",  rpc_luci2_rclocal_get),
1756                 UBUS_METHOD("rclocal_set",        rpc_luci2_rclocal_set,
1757                                                   rpc_data_policy),
1758                 UBUS_METHOD_NOARG("crontab_get",  rpc_luci2_crontab_get),
1759                 UBUS_METHOD("crontab_set",        rpc_luci2_crontab_set,
1760                                                   rpc_data_policy),
1761                 UBUS_METHOD_NOARG("sshkeys_get",  rpc_luci2_sshkeys_get),
1762                 UBUS_METHOD("sshkeys_set",        rpc_luci2_sshkeys_set,
1763                                                   rpc_sshkey_policy),
1764                 UBUS_METHOD("password_set",       rpc_luci2_password_set,
1765                                                   rpc_password_policy),
1766                 UBUS_METHOD_NOARG("led_list",     rpc_luci2_led_list),
1767                 UBUS_METHOD_NOARG("usb_list",     rpc_luci2_usb_list),
1768                 UBUS_METHOD_NOARG("upgrade_test", rpc_luci2_upgrade_test),
1769                 UBUS_METHOD("upgrade_start",      rpc_luci2_upgrade_start,
1770                                                   rpc_upgrade_policy),
1771                 UBUS_METHOD_NOARG("upgrade_abort", rpc_luci2_upgrade_abort)
1772         };
1773
1774         static struct ubus_object_type luci2_system_type =
1775                 UBUS_OBJECT_TYPE("luci-rpc-luci2-system", luci2_system_methods);
1776
1777         static struct ubus_object system_obj = {
1778                 .name = "luci2.system",
1779                 .type = &luci2_system_type,
1780                 .methods = luci2_system_methods,
1781                 .n_methods = ARRAY_SIZE(luci2_system_methods),
1782         };
1783
1784
1785         static const struct ubus_method luci2_network_methods[] = {
1786                 UBUS_METHOD_NOARG("conntrack_count", rpc_luci2_network_ct_count),
1787                 UBUS_METHOD_NOARG("conntrack_table", rpc_luci2_network_ct_table),
1788                 UBUS_METHOD_NOARG("arp_table",       rpc_luci2_network_arp_table),
1789                 UBUS_METHOD_NOARG("dhcp_leases",     rpc_luci2_network_leases),
1790                 UBUS_METHOD_NOARG("dhcp6_leases",    rpc_luci2_network_leases6),
1791                 UBUS_METHOD_NOARG("routes",          rpc_luci2_network_routes),
1792                 UBUS_METHOD_NOARG("routes6",         rpc_luci2_network_routes6),
1793         };
1794
1795         static struct ubus_object_type luci2_network_type =
1796                 UBUS_OBJECT_TYPE("luci-rpc-luci2-network", luci2_network_methods);
1797
1798         static struct ubus_object network_obj = {
1799                 .name = "luci2.network",
1800                 .type = &luci2_network_type,
1801                 .methods = luci2_network_methods,
1802                 .n_methods = ARRAY_SIZE(luci2_network_methods),
1803         };
1804
1805
1806         static const struct ubus_method luci2_opkg_methods[] = {
1807                 UBUS_METHOD("list",                  rpc_luci2_opkg_list,
1808                                                      rpc_opkg_match_policy),
1809                 UBUS_METHOD("list_installed",        rpc_luci2_opkg_list_installed,
1810                                                      rpc_opkg_match_policy),
1811                 UBUS_METHOD("find",                  rpc_luci2_opkg_find,
1812                                                      rpc_opkg_match_policy),
1813                 UBUS_METHOD("install",               rpc_luci2_opkg_install,
1814                                                      rpc_opkg_package_policy),
1815                 UBUS_METHOD("remove",                rpc_luci2_opkg_remove,
1816                                                      rpc_opkg_package_policy),
1817                 UBUS_METHOD_NOARG("update",          rpc_luci2_opkg_update),
1818                 UBUS_METHOD_NOARG("config_get",      rpc_luci2_opkg_config_get),
1819                 UBUS_METHOD("config_set",            rpc_luci2_opkg_config_set,
1820                                                      rpc_data_policy)
1821         };
1822
1823         static struct ubus_object_type luci2_opkg_type =
1824                 UBUS_OBJECT_TYPE("luci-rpc-luci2-network", luci2_opkg_methods);
1825
1826         static struct ubus_object opkg_obj = {
1827                 .name = "luci2.opkg",
1828                 .type = &luci2_opkg_type,
1829                 .methods = luci2_opkg_methods,
1830                 .n_methods = ARRAY_SIZE(luci2_opkg_methods),
1831         };
1832
1833         cursor = uci_alloc_context();
1834
1835         if (!cursor)
1836                 return UBUS_STATUS_UNKNOWN_ERROR;
1837
1838         rv |= ubus_add_object(ctx, &system_obj);
1839         rv |= ubus_add_object(ctx, &network_obj);
1840         rv |= ubus_add_object(ctx, &opkg_obj);
1841
1842         return rv;
1843 }