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