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