f5bb076c6394aeabec3c2098a33b44e41944eb08
[project/rpcd.git] / uci.c
1 /*
2  * rpcd - 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 <libubox/blobmsg.h>
20 #include <libubox/blobmsg_json.h>
21
22 #include <rpcd/uci.h>
23 #include <rpcd/session.h>
24
25 static struct blob_buf buf;
26 static struct uci_context *cursor;
27
28 enum {
29         RPC_G_CONFIG,
30         RPC_G_SECTION,
31         RPC_G_OPTION,
32         RPC_G_TYPE,
33         RPC_G_MATCH,
34         RPC_G_SESSION,
35         __RPC_G_MAX,
36 };
37
38 static const struct blobmsg_policy rpc_uci_get_policy[__RPC_G_MAX] = {
39         [RPC_G_CONFIG]  = { .name = "config",  .type = BLOBMSG_TYPE_STRING },
40         [RPC_G_SECTION] = { .name = "section", .type = BLOBMSG_TYPE_STRING },
41         [RPC_G_OPTION]  = { .name = "option",  .type = BLOBMSG_TYPE_STRING },
42         [RPC_G_TYPE]    = { .name = "type",    .type = BLOBMSG_TYPE_STRING },
43         [RPC_G_MATCH]   = { .name = "match",   .type = BLOBMSG_TYPE_TABLE  },
44         [RPC_G_SESSION] = { .name = "ubus_rpc_session",
45                                                .type = BLOBMSG_TYPE_STRING },
46 };
47
48 enum {
49         RPC_A_CONFIG,
50         RPC_A_TYPE,
51         RPC_A_NAME,
52         RPC_A_VALUES,
53         RPC_A_SESSION,
54         __RPC_A_MAX,
55 };
56
57 static const struct blobmsg_policy rpc_uci_add_policy[__RPC_A_MAX] = {
58         [RPC_A_CONFIG]  = { .name = "config",  .type = BLOBMSG_TYPE_STRING },
59         [RPC_A_TYPE]    = { .name = "type",    .type = BLOBMSG_TYPE_STRING },
60         [RPC_A_NAME]    = { .name = "name",    .type = BLOBMSG_TYPE_STRING },
61         [RPC_A_VALUES]  = { .name = "values",  .type = BLOBMSG_TYPE_TABLE  },
62         [RPC_A_SESSION] = { .name = "ubus_rpc_session",
63                                                .type = BLOBMSG_TYPE_STRING },
64 };
65
66 enum {
67         RPC_S_CONFIG,
68         RPC_S_SECTION,
69         RPC_S_TYPE,
70         RPC_S_MATCH,
71         RPC_S_VALUES,
72         RPC_S_SESSION,
73         __RPC_S_MAX,
74 };
75
76 static const struct blobmsg_policy rpc_uci_set_policy[__RPC_S_MAX] = {
77         [RPC_S_CONFIG]  = { .name = "config",   .type = BLOBMSG_TYPE_STRING },
78         [RPC_S_SECTION] = { .name = "section",  .type = BLOBMSG_TYPE_STRING },
79         [RPC_S_TYPE]    = { .name = "type",     .type = BLOBMSG_TYPE_STRING },
80         [RPC_S_MATCH]   = { .name = "match",    .type = BLOBMSG_TYPE_TABLE  },
81         [RPC_S_VALUES]  = { .name = "values",   .type = BLOBMSG_TYPE_TABLE  },
82         [RPC_S_SESSION] = { .name = "ubus_rpc_session",
83                                                 .type = BLOBMSG_TYPE_STRING },
84 };
85
86 enum {
87         RPC_D_CONFIG,
88         RPC_D_SECTION,
89         RPC_D_TYPE,
90         RPC_D_MATCH,
91         RPC_D_OPTION,
92         RPC_D_OPTIONS,
93         RPC_D_SESSION,
94         __RPC_D_MAX,
95 };
96
97 static const struct blobmsg_policy rpc_uci_delete_policy[__RPC_D_MAX] = {
98         [RPC_D_CONFIG]  = { .name = "config",   .type = BLOBMSG_TYPE_STRING },
99         [RPC_D_SECTION] = { .name = "section",  .type = BLOBMSG_TYPE_STRING },
100         [RPC_D_TYPE]    = { .name = "type",     .type = BLOBMSG_TYPE_STRING },
101         [RPC_D_MATCH]   = { .name = "match",    .type = BLOBMSG_TYPE_TABLE  },
102         [RPC_D_OPTION]  = { .name = "option",   .type = BLOBMSG_TYPE_STRING },
103         [RPC_D_OPTIONS] = { .name = "options",  .type = BLOBMSG_TYPE_ARRAY  },
104         [RPC_D_SESSION] = { .name = "ubus_rpc_session",
105                                                 .type = BLOBMSG_TYPE_STRING },
106 };
107
108 enum {
109         RPC_R_CONFIG,
110         RPC_R_SECTION,
111         RPC_R_OPTION,
112         RPC_R_NAME,
113         RPC_R_SESSION,
114         __RPC_R_MAX,
115 };
116
117 static const struct blobmsg_policy rpc_uci_rename_policy[__RPC_R_MAX] = {
118         [RPC_R_CONFIG]  = { .name = "config",   .type = BLOBMSG_TYPE_STRING },
119         [RPC_R_SECTION] = { .name = "section",  .type = BLOBMSG_TYPE_STRING },
120         [RPC_R_OPTION]  = { .name = "option",   .type = BLOBMSG_TYPE_STRING },
121         [RPC_R_NAME]    = { .name = "name",     .type = BLOBMSG_TYPE_STRING },
122         [RPC_R_SESSION] = { .name = "ubus_rpc_session",
123                                                 .type = BLOBMSG_TYPE_STRING },
124 };
125
126 enum {
127         RPC_O_CONFIG,
128         RPC_O_SECTIONS,
129         RPC_O_SESSION,
130         __RPC_O_MAX,
131 };
132
133 static const struct blobmsg_policy rpc_uci_order_policy[__RPC_O_MAX] = {
134         [RPC_O_CONFIG]   = { .name = "config",   .type = BLOBMSG_TYPE_STRING },
135         [RPC_O_SECTIONS] = { .name = "sections", .type = BLOBMSG_TYPE_ARRAY  },
136         [RPC_O_SESSION]  = { .name = "ubus_rpc_session",
137                                                  .type = BLOBMSG_TYPE_STRING },
138 };
139
140 enum {
141         RPC_C_CONFIG,
142         RPC_C_SESSION,
143         __RPC_C_MAX,
144 };
145
146 static const struct blobmsg_policy rpc_uci_config_policy[__RPC_C_MAX] = {
147         [RPC_C_CONFIG]   = { .name = "config",  .type = BLOBMSG_TYPE_STRING },
148         [RPC_C_SESSION]  = { .name = "ubus_rpc_session",
149                                                 .type = BLOBMSG_TYPE_STRING },
150 };
151
152 /*
153  * Turn uci error state into ubus return code
154  */
155 static int
156 rpc_uci_status(void)
157 {
158         switch (cursor->err)
159         {
160         case UCI_OK:
161                 return UBUS_STATUS_OK;
162
163         case UCI_ERR_INVAL:
164                 return UBUS_STATUS_INVALID_ARGUMENT;
165
166         case UCI_ERR_NOTFOUND:
167                 return UBUS_STATUS_NOT_FOUND;
168
169         default:
170                 return UBUS_STATUS_UNKNOWN_ERROR;
171         }
172 }
173
174 /*
175  * Setup per-session delta save directory. If the passed "sid" blob attribute
176  * pointer is NULL then the precedure was not invoked through the ubus-rpc so
177  * we do not perform session isolation and use the default save directory.
178  */
179 static void
180 rpc_uci_set_savedir(struct blob_attr *sid)
181 {
182         char path[PATH_MAX];
183
184         if (!sid)
185         {
186                 uci_set_savedir(cursor, "/tmp/.uci");
187                 return;
188         }
189
190         snprintf(path, sizeof(path) - 1,
191                  RPC_UCI_SAVEDIR_PREFIX "%s", blobmsg_get_string(sid));
192
193         uci_set_savedir(cursor, path);
194 }
195
196 /*
197  * Test read access to given config. If the passed "sid" blob attribute pointer
198  * is NULL then the precedure was not invoked through the ubus-rpc so we do not
199  * perform access control and always assume true.
200  */
201 static bool
202 rpc_uci_read_access(struct blob_attr *sid, struct blob_attr *config)
203 {
204         rpc_uci_set_savedir(sid);
205
206         if (!sid)
207                 return true;
208
209         return rpc_session_access(blobmsg_data(sid), "uci",
210                                   blobmsg_data(config), "read");
211 }
212
213 /*
214  * Test write access to given config. If the passed "sid" blob attribute pointer
215  * is NULL then the precedure was not invoked through the ubus-rpc so we do not
216  * perform access control and always assume true.
217  */
218 static bool
219 rpc_uci_write_access(struct blob_attr *sid, struct blob_attr *config)
220 {
221         rpc_uci_set_savedir(sid);
222
223         if (!sid)
224                 return true;
225
226         return rpc_session_access(blobmsg_data(sid), "uci",
227                                   blobmsg_data(config), "write");
228 }
229
230 /*
231  * Format applicable blob value as string and place a pointer to the string
232  * buffer in "p". Uses a static string buffer.
233  */
234 static bool
235 rpc_uci_format_blob(struct blob_attr *v, const char **p)
236 {
237         static char buf[21];
238
239         *p = NULL;
240
241         switch (blobmsg_type(v))
242         {
243         case BLOBMSG_TYPE_STRING:
244                 if (blobmsg_data_len(v) > 1)
245                         *p = blobmsg_data(v);
246                 break;
247
248         case BLOBMSG_TYPE_INT64:
249                 snprintf(buf, sizeof(buf), "%"PRIu64, blobmsg_get_u64(v));
250                 *p = buf;
251                 break;
252
253         case BLOBMSG_TYPE_INT32:
254                 snprintf(buf, sizeof(buf), "%u", blobmsg_get_u32(v));
255                 *p = buf;
256                 break;
257
258         case BLOBMSG_TYPE_INT16:
259                 snprintf(buf, sizeof(buf), "%u", blobmsg_get_u16(v));
260                 *p = buf;
261                 break;
262
263         case BLOBMSG_TYPE_INT8:
264                 snprintf(buf, sizeof(buf), "%u", !!blobmsg_get_u8(v));
265                 *p = buf;
266                 break;
267
268         default:
269                 break;
270         }
271
272         return !!*p;
273 }
274
275 /*
276  * Lookup the given uci_ptr and enable extended lookup format if the .section
277  * value of the uci_ptr looks like extended syntax. Uses an internal copy
278  * of the given uci_ptr to perform the lookup as failing extended section
279  * lookup operations in libuci will zero our the uci_ptr struct.
280  * Copies the internal uci_ptr back to given the uci_ptr on success.
281  */
282 static int
283 rpc_uci_lookup(struct uci_ptr *ptr)
284 {
285         int rv;
286         struct uci_ptr lookup = *ptr;
287
288         if (!lookup.s && lookup.section && *lookup.section == '@')
289                 lookup.flags |= UCI_LOOKUP_EXTENDED;
290
291         rv = uci_lookup_ptr(cursor, &lookup, NULL, true);
292
293         if (!rv)
294                 *ptr = lookup;
295
296         return rv;
297 }
298
299 /*
300  * Checks whether the given uci_option object matches the given string value.
301  *  1) If the uci_option is of type list, check whether any of the list elements
302  *     equals to the given string
303  *  2) If the uci_option is of type string, parse it into space separated tokens
304  *     and check if any of the tokens equals to the given string.
305  *  Returns true if a list element or token matched the given string.
306  */
307 static bool
308 rpc_uci_match_option(struct uci_option *o, const char *cmp)
309 {
310         struct uci_element *e;
311         char *s, *p;
312
313         if (o->type == UCI_TYPE_LIST)
314         {
315                 uci_foreach_element(&o->v.list, e)
316                         if (e->name && !strcmp(e->name, cmp))
317                                 return true;
318
319                 return false;
320         }
321
322         if (!o->v.string)
323                 return false;
324
325         s = strdup(o->v.string);
326
327         if (!s)
328                 return false;
329
330         for (p = strtok(s, " \t"); p; p = strtok(NULL, " \t"))
331         {
332                 if (!strcmp(p, cmp))
333                 {
334                         free(s);
335                         return true;
336                 }
337         }
338
339         free(s);
340         return false;
341 }
342
343 /*
344  * Checks whether the given uci_section matches the type and value blob attrs.
345  *  1) Returns false if "type" is given and the section type does not match
346  *     the value specified in the "type" string blob attribute, else continue.
347  *  2) Tests whether any key in the "matches" table blob attribute exists in
348  *     the given uci_section and whether each value is contained in the
349  *     corresponding uci option value (see rpc_uci_match_option()).
350  *  3) A missing or empty "matches" table blob attribute is always considered
351  *     to be a match.
352  * Returns true if "type" matches or is NULL and "matches" matches or is NULL.
353  */
354 static bool
355 rpc_uci_match_section(struct uci_section *s,
356                       struct blob_attr *type, struct blob_attr *matches)
357 {
358         struct uci_element *e;
359         struct blob_attr *cur;
360         const char *cmp;
361         bool match = false;
362         bool empty = true;
363         int rem;
364
365         if (type && strcmp(s->type, blobmsg_data(type)))
366                 return false;
367
368         if (!matches)
369                 return true;
370
371         blobmsg_for_each_attr(cur, matches, rem)
372         {
373                 if (!rpc_uci_format_blob(cur, &cmp))
374                         continue;
375
376                 uci_foreach_element(&s->options, e)
377                 {
378                         if (strcmp(e->name, blobmsg_name(cur)))
379                                 continue;
380
381                         if (!rpc_uci_match_option(uci_to_option(e), cmp))
382                                 return false;
383
384                         match = true;
385                 }
386
387                 empty = false;
388         }
389
390         return (empty || match);
391 }
392
393 /*
394  * Dump the given uci_option value into the global blobmsg buffer and use
395  * given "name" as key.
396  *  1) If the uci_option is of type list, put a table into the blob buffer and
397  *     add each list item as string to it.
398  *  2) If the uci_option is of type string, put its value directly into the blob
399  *     buffer.
400  */
401 static void
402 rpc_uci_dump_option(struct uci_option *o, const char *name)
403 {
404         void *c;
405         struct uci_element *e;
406
407         switch (o->type)
408         {
409         case UCI_TYPE_STRING:
410                 blobmsg_add_string(&buf, name, o->v.string);
411                 break;
412
413         case UCI_TYPE_LIST:
414                 c = blobmsg_open_array(&buf, name);
415
416                 uci_foreach_element(&o->v.list, e)
417                         blobmsg_add_string(&buf, NULL, e->name);
418
419                 blobmsg_close_array(&buf, c);
420                 break;
421
422         default:
423                 break;
424         }
425 }
426
427 /*
428  * Dump the given uci_section object into the global blobmsg buffer and use
429  * given "name" as key.
430  * Puts a table into the blob buffer and puts each section option member value
431  * as value into the table using the option name as key.
432  * Adds three special keys ".anonymous", ".type" and ".name" which specify the
433  * corresponding section properties.
434  */
435 static void
436 rpc_uci_dump_section(struct uci_section *s, const char *name, int index)
437 {
438         void *c;
439         struct uci_option *o;
440         struct uci_element *e;
441
442         c = blobmsg_open_table(&buf, name);
443
444         blobmsg_add_u8(&buf, ".anonymous", s->anonymous);
445         blobmsg_add_string(&buf, ".type", s->type);
446         blobmsg_add_string(&buf, ".name", s->e.name);
447
448         if (index >= 0)
449                 blobmsg_add_u32(&buf, ".index", index);
450
451         uci_foreach_element(&s->options, e)
452         {
453                 o = uci_to_option(e);
454                 rpc_uci_dump_option(o, o->e.name);
455         }
456
457         blobmsg_close_table(&buf, c);
458 }
459
460 /*
461  * Dump the given uci_package object into the global blobmsg buffer and use
462  * given "name" as key.
463  * Puts a table into the blob buffer and puts each package section member as
464  * value into the table using the section name as key.
465  * Only dumps sections matching the given "type" and "matches", see explaination
466  * of rpc_uci_match_section() for details.
467  */
468 static void
469 rpc_uci_dump_package(struct uci_package *p, const char *name,
470                      struct blob_attr *type, struct blob_attr *matches)
471 {
472         void *c;
473         struct uci_element *e;
474         int i = -1;
475
476         c = blobmsg_open_table(&buf, name);
477
478         uci_foreach_element(&p->sections, e)
479         {
480                 i++;
481
482                 if (!rpc_uci_match_section(uci_to_section(e), type, matches))
483                         continue;
484
485                 rpc_uci_dump_section(uci_to_section(e), e->name, i);
486         }
487
488         blobmsg_close_table(&buf, c);
489 }
490
491
492 static int
493 rpc_uci_get(struct ubus_context *ctx, struct ubus_object *obj,
494             struct ubus_request_data *req, const char *method,
495             struct blob_attr *msg)
496 {
497         struct blob_attr *tb[__RPC_G_MAX];
498         struct uci_package *p = NULL;
499         struct uci_ptr ptr = { 0 };
500
501         blobmsg_parse(rpc_uci_get_policy, __RPC_G_MAX, tb,
502                       blob_data(msg), blob_len(msg));
503
504         if (!tb[RPC_G_CONFIG])
505                 return UBUS_STATUS_INVALID_ARGUMENT;
506
507         if (!rpc_uci_read_access(tb[RPC_G_SESSION], tb[RPC_G_CONFIG]))
508                 return UBUS_STATUS_PERMISSION_DENIED;
509
510         ptr.package = blobmsg_data(tb[RPC_G_CONFIG]);
511         uci_load(cursor, ptr.package, &p);
512
513         if (!p)
514                 goto out;
515
516         if (tb[RPC_G_SECTION])
517         {
518                 ptr.section = blobmsg_data(tb[RPC_G_SECTION]);
519
520                 if (tb[RPC_G_OPTION])
521                         ptr.option = blobmsg_data(tb[RPC_G_OPTION]);
522         }
523
524         if (rpc_uci_lookup(&ptr) || !(ptr.flags & UCI_LOOKUP_COMPLETE))
525                 goto out;
526
527         blob_buf_init(&buf, 0);
528
529         switch (ptr.last->type)
530         {
531         case UCI_TYPE_PACKAGE:
532                 rpc_uci_dump_package(ptr.p, "values", tb[RPC_G_TYPE], tb[RPC_G_MATCH]);
533                 break;
534
535         case UCI_TYPE_SECTION:
536                 rpc_uci_dump_section(ptr.s, "values", -1);
537                 break;
538
539         case UCI_TYPE_OPTION:
540                 rpc_uci_dump_option(ptr.o, "value");
541                 break;
542
543         default:
544                 break;
545         }
546
547         ubus_send_reply(ctx, req, buf.head);
548
549 out:
550         if (p)
551                 uci_unload(cursor, p);
552
553         return rpc_uci_status();
554 }
555
556 static int
557 rpc_uci_add(struct ubus_context *ctx, struct ubus_object *obj,
558             struct ubus_request_data *req, const char *method,
559             struct blob_attr *msg)
560 {
561         struct blob_attr *tb[__RPC_A_MAX];
562         struct blob_attr *cur, *elem;
563         struct uci_package *p = NULL;
564         struct uci_section *s;
565         struct uci_ptr ptr = { 0 };
566         int rem, rem2;
567
568         blobmsg_parse(rpc_uci_add_policy, __RPC_A_MAX, tb,
569                       blob_data(msg), blob_len(msg));
570
571         if (!tb[RPC_A_CONFIG] || !tb[RPC_A_TYPE])
572                 return UBUS_STATUS_INVALID_ARGUMENT;
573
574         if (!rpc_uci_write_access(tb[RPC_A_SESSION], tb[RPC_A_CONFIG]))
575                 return UBUS_STATUS_PERMISSION_DENIED;
576
577         ptr.package = blobmsg_data(tb[RPC_A_CONFIG]);
578
579         uci_load(cursor, ptr.package, &p);
580
581         if (!p)
582                 goto out;
583
584         /* add named section */
585         if (tb[RPC_A_NAME])
586         {
587                 ptr.section = blobmsg_data(tb[RPC_A_NAME]);
588                 ptr.value   = blobmsg_data(tb[RPC_A_TYPE]);
589                 ptr.option  = NULL;
590
591                 if (rpc_uci_lookup(&ptr) || uci_set(cursor, &ptr))
592                         goto out;
593         }
594
595         /* add anon section */
596         else
597         {
598                 if (uci_add_section(cursor, p, blobmsg_data(tb[RPC_A_TYPE]), &s) || !s)
599                         goto out;
600
601                 ptr.section = s->e.name;
602         }
603
604         if (tb[RPC_A_VALUES])
605         {
606                 blobmsg_for_each_attr(cur, tb[RPC_A_VALUES], rem)
607                 {
608                         ptr.o = NULL;
609                         ptr.option = blobmsg_name(cur);
610
611                         if (rpc_uci_lookup(&ptr) || !ptr.s)
612                                 continue;
613
614                         switch (blobmsg_type(cur))
615                         {
616                         case BLOBMSG_TYPE_ARRAY:
617                                 blobmsg_for_each_attr(elem, cur, rem2)
618                                         if (rpc_uci_format_blob(elem, &ptr.value))
619                                                 uci_add_list(cursor, &ptr);
620                                 break;
621
622                         default:
623                                 if (rpc_uci_format_blob(cur, &ptr.value))
624                                         uci_set(cursor, &ptr);
625                                 break;
626                         }
627                 }
628         }
629
630         uci_save(cursor, p);
631
632         blob_buf_init(&buf, 0);
633         blobmsg_add_string(&buf, "section", ptr.section);
634         ubus_send_reply(ctx, req, buf.head);
635
636 out:
637         if (p)
638                 uci_unload(cursor, p);
639
640         return rpc_uci_status();
641 }
642
643 /*
644  * Turn value from a blob attribute into uci set operation
645  *  1) if the blob is of type array, delete existing option (if any) and
646  *     emit uci add_list operations for each element
647  *  2) if the blob is not an array but an option of type list exists,
648  *     delete existing list and emit uci set operation for the blob value
649  *  3) in all other cases only emit a set operation if there is no existing
650  *     option of if the existing options value differs from the blob value
651  */
652 static void
653 rpc_uci_merge_set(struct blob_attr *opt, struct uci_ptr *ptr)
654 {
655         struct blob_attr *cur;
656         int rem;
657
658         ptr->o = NULL;
659         ptr->option = blobmsg_name(opt);
660
661         if (rpc_uci_lookup(ptr) || !ptr->s)
662                 return;
663
664         if (blobmsg_type(opt) == BLOBMSG_TYPE_ARRAY)
665         {
666                 if (ptr->o)
667                         uci_delete(cursor, ptr);
668
669                 blobmsg_for_each_attr(cur, opt, rem)
670                         if (rpc_uci_format_blob(cur, &ptr->value))
671                                 uci_add_list(cursor, ptr);
672         }
673         else if (ptr->o && ptr->o->type == UCI_TYPE_LIST)
674         {
675                 uci_delete(cursor, ptr);
676
677                 if (rpc_uci_format_blob(opt, &ptr->value))
678                         uci_set(cursor, ptr);
679         }
680         else if (rpc_uci_format_blob(opt, &ptr->value))
681         {
682                 if (!ptr->o || !ptr->o->v.string || strcmp(ptr->o->v.string, ptr->value))
683                         uci_set(cursor, ptr);
684         }
685 }
686
687 static int
688 rpc_uci_set(struct ubus_context *ctx, struct ubus_object *obj,
689             struct ubus_request_data *req, const char *method,
690             struct blob_attr *msg)
691 {
692         struct blob_attr *tb[__RPC_S_MAX];
693         struct blob_attr *cur;
694         struct uci_package *p = NULL;
695         struct uci_element *e;
696         struct uci_ptr ptr = { 0 };
697         int rem;
698
699         blobmsg_parse(rpc_uci_set_policy, __RPC_S_MAX, tb,
700                       blob_data(msg), blob_len(msg));
701
702         if (!tb[RPC_S_CONFIG] || !tb[RPC_S_VALUES] ||
703                 (!tb[RPC_S_SECTION] && !tb[RPC_S_TYPE] && !tb[RPC_S_MATCH]))
704                 return UBUS_STATUS_INVALID_ARGUMENT;
705
706         if (!rpc_uci_write_access(tb[RPC_S_SESSION], tb[RPC_S_CONFIG]))
707                 return UBUS_STATUS_PERMISSION_DENIED;
708
709         ptr.package = blobmsg_data(tb[RPC_S_CONFIG]);
710         uci_load(cursor, ptr.package, &p);
711
712         if (!p)
713                 goto out;
714
715         if (tb[RPC_S_SECTION])
716         {
717                 ptr.section = blobmsg_data(tb[RPC_S_SECTION]);
718                 blobmsg_for_each_attr(cur, tb[RPC_S_VALUES], rem)
719                         rpc_uci_merge_set(cur, &ptr);
720         }
721         else
722         {
723                 uci_foreach_element(&p->sections, e)
724                 {
725                         if (!rpc_uci_match_section(uci_to_section(e),
726                                                    tb[RPC_S_TYPE], tb[RPC_S_MATCH]))
727                                 continue;
728
729                         ptr.s = NULL;
730                         ptr.section = e->name;
731
732                         blobmsg_for_each_attr(cur, tb[RPC_S_VALUES], rem)
733                                 rpc_uci_merge_set(cur, &ptr);
734                 }
735         }
736
737         uci_save(cursor, p);
738
739 out:
740         if (p)
741                 uci_unload(cursor, p);
742
743         return rpc_uci_status();
744 }
745
746 /*
747  * Delete option or section from uci specified by given blob attribute pointer
748  *  1) if the blob is of type array, delete any option named after each element
749  *  2) if the blob is of type string, delete the option named after its value
750  *  3) if the blob is NULL, delete entire section
751  */
752 static void
753 rpc_uci_merge_delete(struct blob_attr *opt, struct uci_ptr *ptr)
754 {
755         struct blob_attr *cur;
756         int rem;
757
758         if (rpc_uci_lookup(ptr) || !ptr->s)
759                 return;
760
761         if (!opt)
762         {
763                 ptr->o = NULL;
764                 ptr->option = NULL;
765
766                 uci_delete(cursor, ptr);
767         }
768         else if (blobmsg_type(opt) == BLOBMSG_TYPE_ARRAY)
769         {
770                 blobmsg_for_each_attr(cur, opt, rem)
771                 {
772                         if (blobmsg_type(cur) != BLOBMSG_TYPE_STRING)
773                                 continue;
774
775                         ptr->o = NULL;
776                         ptr->option = blobmsg_data(cur);
777
778                         if (rpc_uci_lookup(ptr) || !ptr->o)
779                                 continue;
780
781                         uci_delete(cursor, ptr);
782                 }
783         }
784         else if (blobmsg_type(opt) == BLOBMSG_TYPE_STRING)
785         {
786                 ptr->o = NULL;
787                 ptr->option = blobmsg_data(opt);
788
789                 if (rpc_uci_lookup(ptr) || !ptr->o)
790                         return;
791
792                 uci_delete(cursor, ptr);
793         }
794 }
795
796 static int
797 rpc_uci_delete(struct ubus_context *ctx, struct ubus_object *obj,
798                struct ubus_request_data *req, const char *method,
799                struct blob_attr *msg)
800 {
801         struct blob_attr *tb[__RPC_D_MAX];
802         struct uci_package *p = NULL;
803         struct uci_element *e, *tmp;
804         struct uci_ptr ptr = { 0 };
805
806         blobmsg_parse(rpc_uci_delete_policy, __RPC_D_MAX, tb,
807                       blob_data(msg), blob_len(msg));
808
809         if (!tb[RPC_D_CONFIG] ||
810                 (!tb[RPC_D_SECTION] && !tb[RPC_D_TYPE] && !tb[RPC_D_MATCH]))
811                 return UBUS_STATUS_INVALID_ARGUMENT;
812
813         if (!rpc_uci_write_access(tb[RPC_D_SESSION], tb[RPC_D_CONFIG]))
814                 return UBUS_STATUS_PERMISSION_DENIED;
815
816         ptr.package = blobmsg_data(tb[RPC_D_CONFIG]);
817         uci_load(cursor, ptr.package, &p);
818
819         if (!p)
820                 goto out;
821
822         if (tb[RPC_D_SECTION])
823         {
824                 ptr.section = blobmsg_data(tb[RPC_D_SECTION]);
825
826                 if (tb[RPC_D_OPTIONS])
827                         rpc_uci_merge_delete(tb[RPC_D_OPTIONS], &ptr);
828                 else
829                         rpc_uci_merge_delete(tb[RPC_D_OPTION], &ptr);
830         }
831         else
832         {
833                 uci_foreach_element_safe(&p->sections, tmp, e)
834                 {
835                         if (!rpc_uci_match_section(uci_to_section(e),
836                                                    tb[RPC_D_TYPE], tb[RPC_D_MATCH]))
837                                 continue;
838
839                         ptr.s = NULL;
840                         ptr.section = e->name;
841
842                         if (tb[RPC_D_OPTIONS])
843                                 rpc_uci_merge_delete(tb[RPC_D_OPTIONS], &ptr);
844                         else
845                                 rpc_uci_merge_delete(tb[RPC_D_OPTION], &ptr);
846                 }
847         }
848
849         uci_save(cursor, p);
850
851 out:
852         if (p)
853                 uci_unload(cursor, p);
854
855         return rpc_uci_status();
856 }
857
858 static int
859 rpc_uci_rename(struct ubus_context *ctx, struct ubus_object *obj,
860                struct ubus_request_data *req, const char *method,
861                struct blob_attr *msg)
862 {
863         struct blob_attr *tb[__RPC_R_MAX];
864         struct uci_package *p = NULL;
865         struct uci_ptr ptr = { 0 };
866
867         blobmsg_parse(rpc_uci_rename_policy, __RPC_R_MAX, tb,
868                       blob_data(msg), blob_len(msg));
869
870         if (!tb[RPC_R_CONFIG] || !tb[RPC_R_SECTION] || !tb[RPC_R_NAME])
871                 return UBUS_STATUS_INVALID_ARGUMENT;
872
873         if (!rpc_uci_write_access(tb[RPC_R_SESSION], tb[RPC_R_CONFIG]))
874                 return UBUS_STATUS_PERMISSION_DENIED;
875
876         ptr.package = blobmsg_data(tb[RPC_R_CONFIG]);
877         ptr.section = blobmsg_data(tb[RPC_R_SECTION]);
878         ptr.value   = blobmsg_data(tb[RPC_R_NAME]);
879
880         if (tb[RPC_R_OPTION])
881                 ptr.option = blobmsg_data(tb[RPC_R_OPTION]);
882
883         uci_load(cursor, ptr.package, &p);
884
885         if (!p)
886                 goto out;
887
888         if (uci_lookup_ptr(cursor, &ptr, NULL, true))
889                 goto out;
890
891         if ((ptr.option && !ptr.o) || !ptr.s)
892         {
893                 cursor->err = UCI_ERR_NOTFOUND;
894                 goto out;
895         }
896
897         if (uci_rename(cursor, &ptr))
898                 goto out;
899
900         uci_save(cursor, p);
901
902 out:
903         if (p)
904                 uci_unload(cursor, p);
905
906         return rpc_uci_status();
907 }
908
909 static int
910 rpc_uci_order(struct ubus_context *ctx, struct ubus_object *obj,
911               struct ubus_request_data *req, const char *method,
912               struct blob_attr *msg)
913 {
914         struct blob_attr *tb[__RPC_O_MAX];
915         struct blob_attr *cur;
916         struct uci_package *p = NULL;
917         struct uci_ptr ptr = { 0 };
918         int rem, i = 1;
919
920         blobmsg_parse(rpc_uci_order_policy, __RPC_O_MAX, tb,
921                       blob_data(msg), blob_len(msg));
922
923         if (!tb[RPC_O_CONFIG] || !tb[RPC_O_SECTIONS])
924                 return UBUS_STATUS_INVALID_ARGUMENT;
925
926         if (!rpc_uci_write_access(tb[RPC_O_SESSION], tb[RPC_O_CONFIG]))
927                 return UBUS_STATUS_PERMISSION_DENIED;
928
929         ptr.package = blobmsg_data(tb[RPC_O_CONFIG]);
930
931         uci_load(cursor, ptr.package, &p);
932
933         if (!p)
934                 goto out;
935
936         blobmsg_for_each_attr(cur, tb[RPC_O_SECTIONS], rem)
937         {
938                 if (blobmsg_type(cur) != BLOBMSG_TYPE_STRING)
939                         continue;
940
941                 ptr.s = NULL;
942                 ptr.section = blobmsg_data(cur);
943
944                 if (uci_lookup_ptr(cursor, &ptr, NULL, true) || !ptr.s)
945                         continue;
946
947                 uci_reorder_section(cursor, ptr.s, i++);
948         }
949
950         uci_save(cursor, p);
951
952 out:
953         if (p)
954                 uci_unload(cursor, p);
955
956         return rpc_uci_status();
957 }
958
959 static void
960 rpc_uci_dump_change(struct uci_delta *d)
961 {
962         void *c;
963         const char *types[] = {
964                 [UCI_CMD_REORDER]  = "order",
965                 [UCI_CMD_REMOVE]   = "remove",
966                 [UCI_CMD_RENAME]   = "rename",
967                 [UCI_CMD_ADD]      = "add",
968                 [UCI_CMD_LIST_ADD] = "list-add",
969                 [UCI_CMD_LIST_DEL] = "list-del",
970                 [UCI_CMD_CHANGE]   = "set",
971         };
972
973         if (!d->section)
974                 return;
975
976         c = blobmsg_open_array(&buf, NULL);
977
978         blobmsg_add_string(&buf, NULL, types[d->cmd]);
979         blobmsg_add_string(&buf, NULL, d->section);
980
981         if (d->e.name)
982                 blobmsg_add_string(&buf, NULL, d->e.name);
983
984         if (d->value)
985         {
986                 if (d->cmd == UCI_CMD_REORDER)
987                         blobmsg_add_u32(&buf, NULL, strtoul(d->value, NULL, 10));
988                 else
989                         blobmsg_add_string(&buf, NULL, d->value);
990         }
991
992         blobmsg_close_array(&buf, c);
993 }
994
995 static int
996 rpc_uci_changes(struct ubus_context *ctx, struct ubus_object *obj,
997                 struct ubus_request_data *req, const char *method,
998                 struct blob_attr *msg)
999 {
1000         struct blob_attr *tb[__RPC_C_MAX];
1001         struct uci_package *p = NULL;
1002         struct uci_element *e;
1003         void *c;
1004
1005         blobmsg_parse(rpc_uci_config_policy, __RPC_C_MAX, tb,
1006                       blob_data(msg), blob_len(msg));
1007
1008         if (!tb[RPC_C_CONFIG])
1009                 return UBUS_STATUS_INVALID_ARGUMENT;
1010
1011         if (!rpc_uci_read_access(tb[RPC_C_SESSION], tb[RPC_C_CONFIG]))
1012                 return UBUS_STATUS_PERMISSION_DENIED;
1013
1014         uci_load(cursor, blobmsg_data(tb[RPC_C_CONFIG]), &p);
1015
1016         if (!p)
1017                 goto out;
1018
1019         blob_buf_init(&buf, 0);
1020         c = blobmsg_open_array(&buf, "changes");
1021
1022         uci_foreach_element(&p->saved_delta, e)
1023                 rpc_uci_dump_change(uci_to_delta(e));
1024
1025         blobmsg_close_array(&buf, c);
1026
1027         ubus_send_reply(ctx, req, buf.head);
1028
1029 out:
1030         if (p)
1031                 uci_unload(cursor, p);
1032
1033         return rpc_uci_status();
1034 }
1035
1036 static void
1037 rpc_uci_trigger_event(struct ubus_context *ctx, const char *config)
1038 {
1039         char *pkg = strdup(config);
1040         static struct blob_buf b;
1041         uint32_t id;
1042
1043         if (!ubus_lookup_id(ctx, "service", &id)) {
1044                 void *c;
1045
1046                 blob_buf_init(&b, 0);
1047                 blobmsg_add_string(&b, "type", "config.change");
1048                 c = blobmsg_open_table(&b, "data");
1049                 blobmsg_add_string(&b, "package", pkg);
1050                 blobmsg_close_table(&b, c);
1051                 ubus_invoke(ctx, id, "event", b.head, NULL, 0, 1000);
1052         }
1053         free(pkg);
1054 }
1055
1056 static int
1057 rpc_uci_revert_commit(struct ubus_context *ctx, struct blob_attr *msg, bool commit)
1058 {
1059         struct blob_attr *tb[__RPC_C_MAX];
1060         struct uci_package *p = NULL;
1061         struct uci_ptr ptr = { 0 };
1062
1063         blobmsg_parse(rpc_uci_config_policy, __RPC_C_MAX, tb,
1064                       blob_data(msg), blob_len(msg));
1065
1066         if (!tb[RPC_C_CONFIG])
1067                 return UBUS_STATUS_INVALID_ARGUMENT;
1068
1069         if (!rpc_uci_write_access(tb[RPC_C_SESSION], tb[RPC_C_CONFIG]))
1070                 return UBUS_STATUS_PERMISSION_DENIED;
1071
1072         ptr.package = blobmsg_data(tb[RPC_C_CONFIG]);
1073
1074         if (commit)
1075         {
1076                 uci_load(cursor, ptr.package, &p);
1077
1078                 if (p)
1079                 {
1080                         uci_commit(cursor, &p, false);
1081                         uci_unload(cursor, p);
1082                 }
1083                 rpc_uci_trigger_event(ctx, blobmsg_get_string(tb[RPC_C_CONFIG]));
1084         }
1085         else
1086         {
1087                 if (!uci_lookup_ptr(cursor, &ptr, NULL, true) && ptr.p)
1088                         uci_revert(cursor, &ptr);
1089         }
1090
1091         return rpc_uci_status();
1092 }
1093
1094 static int
1095 rpc_uci_revert(struct ubus_context *ctx, struct ubus_object *obj,
1096                struct ubus_request_data *req, const char *method,
1097                struct blob_attr *msg)
1098 {
1099         return rpc_uci_revert_commit(ctx, msg, false);
1100 }
1101
1102 static int
1103 rpc_uci_commit(struct ubus_context *ctx, struct ubus_object *obj,
1104                struct ubus_request_data *req, const char *method,
1105                struct blob_attr *msg)
1106 {
1107         return rpc_uci_revert_commit(ctx, msg, true);
1108 }
1109
1110 static int
1111 rpc_uci_configs(struct ubus_context *ctx, struct ubus_object *obj,
1112                 struct ubus_request_data *req, const char *method,
1113                 struct blob_attr *msg)
1114 {
1115         char **configs;
1116         void *c;
1117         int i;
1118
1119         if (uci_list_configs(cursor, &configs))
1120                 goto out;
1121
1122         blob_buf_init(&buf, 0);
1123
1124         c = blobmsg_open_array(&buf, "configs");
1125
1126         for (i = 0; configs[i]; i++)
1127                 blobmsg_add_string(&buf, NULL, configs[i]);
1128
1129         blobmsg_close_array(&buf, c);
1130
1131         ubus_send_reply(ctx, req, buf.head);
1132
1133 out:
1134         return rpc_uci_status();
1135 }
1136
1137
1138 /*
1139  * Remove given delta save directory (if any).
1140  */
1141 static void
1142 rpc_uci_purge_dir(const char *path)
1143 {
1144         DIR *d;
1145         struct stat s;
1146         struct dirent *e;
1147         char file[PATH_MAX];
1148
1149         if (stat(path, &s) || !S_ISDIR(s.st_mode))
1150                 return;
1151
1152         if ((d = opendir(path)) != NULL)
1153         {
1154                 while ((e = readdir(d)) != NULL)
1155                 {
1156                         snprintf(file, sizeof(file) - 1, "%s/%s", path, e->d_name);
1157
1158                         if (stat(file, &s) || !S_ISREG(s.st_mode))
1159                                 continue;
1160
1161                         unlink(file);
1162                 }
1163
1164                 closedir(d);
1165
1166                 rmdir(path);
1167         }
1168 }
1169
1170 /*
1171  * Session destroy callback to purge associated delta directory.
1172  */
1173 static void
1174 rpc_uci_purge_savedir_cb(struct rpc_session *ses, void *priv)
1175 {
1176         char path[PATH_MAX];
1177
1178         snprintf(path, sizeof(path) - 1, RPC_UCI_SAVEDIR_PREFIX "%s", ses->id);
1179         rpc_uci_purge_dir(path);
1180 }
1181
1182 /*
1183  * Removes all delta directories which match the RPC_UCI_SAVEDIR_PREFIX.
1184  * This is used to clean up garbage when starting rpcd.
1185  */
1186 void rpc_uci_purge_savedirs(void)
1187 {
1188         int i;
1189         glob_t gl;
1190
1191         if (!glob(RPC_UCI_SAVEDIR_PREFIX "*", 0, NULL, &gl))
1192         {
1193                 for (i = 0; i < gl.gl_pathc; i++)
1194                         rpc_uci_purge_dir(gl.gl_pathv[i]);
1195
1196                 globfree(&gl);
1197         }
1198 }
1199
1200 int rpc_uci_api_init(struct ubus_context *ctx)
1201 {
1202         static const struct ubus_method uci_methods[] = {
1203                 { .name = "configs", .handler = rpc_uci_configs },
1204                 UBUS_METHOD("get",     rpc_uci_get,     rpc_uci_get_policy),
1205                 UBUS_METHOD("add",     rpc_uci_add,     rpc_uci_add_policy),
1206                 UBUS_METHOD("set",     rpc_uci_set,     rpc_uci_set_policy),
1207                 UBUS_METHOD("delete",  rpc_uci_delete,  rpc_uci_delete_policy),
1208                 UBUS_METHOD("rename",  rpc_uci_rename,  rpc_uci_rename_policy),
1209                 UBUS_METHOD("order",   rpc_uci_order,   rpc_uci_order_policy),
1210                 UBUS_METHOD("changes", rpc_uci_changes, rpc_uci_config_policy),
1211                 UBUS_METHOD("revert",  rpc_uci_revert,  rpc_uci_config_policy),
1212                 UBUS_METHOD("commit",  rpc_uci_commit,  rpc_uci_config_policy),
1213         };
1214
1215         static struct ubus_object_type uci_type =
1216                 UBUS_OBJECT_TYPE("luci-rpc-uci", uci_methods);
1217
1218         static struct ubus_object obj = {
1219                 .name = "uci",
1220                 .type = &uci_type,
1221                 .methods = uci_methods,
1222                 .n_methods = ARRAY_SIZE(uci_methods),
1223         };
1224
1225         static struct rpc_session_cb cb = {
1226                 .cb = rpc_uci_purge_savedir_cb
1227         };
1228
1229         cursor = uci_alloc_context();
1230
1231         if (!cursor)
1232                 return UBUS_STATUS_UNKNOWN_ERROR;
1233
1234         rpc_session_destroy_cb(&cb);
1235
1236         return ubus_add_object(ctx, &obj);
1237 }