uci: reset uci_ptr flags when merging options during section add
[oweals/rpcd.git] / uci.c
1 /*
2  * rpcd - UBUS RPC server
3  *
4  *   Copyright (C) 2013-2014 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 <libgen.h>
20 #include <glob.h>
21
22 #include <libubox/blobmsg.h>
23 #include <libubox/blobmsg_json.h>
24
25 #include <rpcd/uci.h>
26 #include <rpcd/exec.h>
27 #include <rpcd/session.h>
28
29 static struct blob_buf buf;
30 static struct uci_context *cursor;
31 static struct uloop_timeout apply_timer;
32 static struct ubus_context *apply_ctx;
33
34 char apply_sid[RPC_SID_LEN + 1];
35
36 enum {
37         RPC_G_CONFIG,
38         RPC_G_SECTION,
39         RPC_G_OPTION,
40         RPC_G_TYPE,
41         RPC_G_MATCH,
42         RPC_G_SESSION,
43         __RPC_G_MAX,
44 };
45
46 static const struct blobmsg_policy rpc_uci_get_policy[__RPC_G_MAX] = {
47         [RPC_G_CONFIG]  = { .name = "config",  .type = BLOBMSG_TYPE_STRING },
48         [RPC_G_SECTION] = { .name = "section", .type = BLOBMSG_TYPE_STRING },
49         [RPC_G_OPTION]  = { .name = "option",  .type = BLOBMSG_TYPE_STRING },
50         [RPC_G_TYPE]    = { .name = "type",    .type = BLOBMSG_TYPE_STRING },
51         [RPC_G_MATCH]   = { .name = "match",   .type = BLOBMSG_TYPE_TABLE  },
52         [RPC_G_SESSION] = { .name = "ubus_rpc_session",
53                                                .type = BLOBMSG_TYPE_STRING },
54 };
55
56 enum {
57         RPC_A_CONFIG,
58         RPC_A_TYPE,
59         RPC_A_NAME,
60         RPC_A_VALUES,
61         RPC_A_SESSION,
62         __RPC_A_MAX,
63 };
64
65 static const struct blobmsg_policy rpc_uci_add_policy[__RPC_A_MAX] = {
66         [RPC_A_CONFIG]  = { .name = "config",  .type = BLOBMSG_TYPE_STRING },
67         [RPC_A_TYPE]    = { .name = "type",    .type = BLOBMSG_TYPE_STRING },
68         [RPC_A_NAME]    = { .name = "name",    .type = BLOBMSG_TYPE_STRING },
69         [RPC_A_VALUES]  = { .name = "values",  .type = BLOBMSG_TYPE_TABLE  },
70         [RPC_A_SESSION] = { .name = "ubus_rpc_session",
71                                                .type = BLOBMSG_TYPE_STRING },
72 };
73
74 enum {
75         RPC_S_CONFIG,
76         RPC_S_SECTION,
77         RPC_S_TYPE,
78         RPC_S_MATCH,
79         RPC_S_VALUES,
80         RPC_S_SESSION,
81         __RPC_S_MAX,
82 };
83
84 static const struct blobmsg_policy rpc_uci_set_policy[__RPC_S_MAX] = {
85         [RPC_S_CONFIG]  = { .name = "config",   .type = BLOBMSG_TYPE_STRING },
86         [RPC_S_SECTION] = { .name = "section",  .type = BLOBMSG_TYPE_STRING },
87         [RPC_S_TYPE]    = { .name = "type",     .type = BLOBMSG_TYPE_STRING },
88         [RPC_S_MATCH]   = { .name = "match",    .type = BLOBMSG_TYPE_TABLE  },
89         [RPC_S_VALUES]  = { .name = "values",   .type = BLOBMSG_TYPE_TABLE  },
90         [RPC_S_SESSION] = { .name = "ubus_rpc_session",
91                                                 .type = BLOBMSG_TYPE_STRING },
92 };
93
94 enum {
95         RPC_D_CONFIG,
96         RPC_D_SECTION,
97         RPC_D_TYPE,
98         RPC_D_MATCH,
99         RPC_D_OPTION,
100         RPC_D_OPTIONS,
101         RPC_D_SESSION,
102         __RPC_D_MAX,
103 };
104
105 static const struct blobmsg_policy rpc_uci_delete_policy[__RPC_D_MAX] = {
106         [RPC_D_CONFIG]  = { .name = "config",   .type = BLOBMSG_TYPE_STRING },
107         [RPC_D_SECTION] = { .name = "section",  .type = BLOBMSG_TYPE_STRING },
108         [RPC_D_TYPE]    = { .name = "type",     .type = BLOBMSG_TYPE_STRING },
109         [RPC_D_MATCH]   = { .name = "match",    .type = BLOBMSG_TYPE_TABLE  },
110         [RPC_D_OPTION]  = { .name = "option",   .type = BLOBMSG_TYPE_STRING },
111         [RPC_D_OPTIONS] = { .name = "options",  .type = BLOBMSG_TYPE_ARRAY  },
112         [RPC_D_SESSION] = { .name = "ubus_rpc_session",
113                                                 .type = BLOBMSG_TYPE_STRING },
114 };
115
116 enum {
117         RPC_R_CONFIG,
118         RPC_R_SECTION,
119         RPC_R_OPTION,
120         RPC_R_NAME,
121         RPC_R_SESSION,
122         __RPC_R_MAX,
123 };
124
125 static const struct blobmsg_policy rpc_uci_rename_policy[__RPC_R_MAX] = {
126         [RPC_R_CONFIG]  = { .name = "config",   .type = BLOBMSG_TYPE_STRING },
127         [RPC_R_SECTION] = { .name = "section",  .type = BLOBMSG_TYPE_STRING },
128         [RPC_R_OPTION]  = { .name = "option",   .type = BLOBMSG_TYPE_STRING },
129         [RPC_R_NAME]    = { .name = "name",     .type = BLOBMSG_TYPE_STRING },
130         [RPC_R_SESSION] = { .name = "ubus_rpc_session",
131                                                 .type = BLOBMSG_TYPE_STRING },
132 };
133
134 enum {
135         RPC_O_CONFIG,
136         RPC_O_SECTIONS,
137         RPC_O_SESSION,
138         __RPC_O_MAX,
139 };
140
141 static const struct blobmsg_policy rpc_uci_order_policy[__RPC_O_MAX] = {
142         [RPC_O_CONFIG]   = { .name = "config",   .type = BLOBMSG_TYPE_STRING },
143         [RPC_O_SECTIONS] = { .name = "sections", .type = BLOBMSG_TYPE_ARRAY  },
144         [RPC_O_SESSION]  = { .name = "ubus_rpc_session",
145                                                  .type = BLOBMSG_TYPE_STRING },
146 };
147
148 enum {
149         RPC_C_CONFIG,
150         RPC_C_SESSION,
151         __RPC_C_MAX,
152 };
153
154 static const struct blobmsg_policy rpc_uci_config_policy[__RPC_C_MAX] = {
155         [RPC_C_CONFIG]   = { .name = "config",  .type = BLOBMSG_TYPE_STRING },
156         [RPC_C_SESSION]  = { .name = "ubus_rpc_session",
157                                                 .type = BLOBMSG_TYPE_STRING },
158 };
159
160 enum {
161         RPC_T_ROLLBACK,
162         RPC_T_TIMEOUT,
163         RPC_T_SESSION,
164         __RPC_T_MAX,
165 };
166
167 static const struct blobmsg_policy rpc_uci_apply_policy[__RPC_T_MAX] = {
168         [RPC_T_ROLLBACK] = { .name = "rollback", .type = BLOBMSG_TYPE_BOOL },
169         [RPC_T_TIMEOUT]  = { .name = "timeout", .type = BLOBMSG_TYPE_INT32 },
170         [RPC_T_SESSION]  = { .name = "ubus_rpc_session",
171                                                 .type = BLOBMSG_TYPE_STRING },
172 };
173
174 enum {
175         RPC_B_SESSION,
176         __RPC_B_MAX,
177 };
178
179 static const struct blobmsg_policy rpc_uci_rollback_policy[__RPC_B_MAX] = {
180         [RPC_B_SESSION]  = { .name = "ubus_rpc_session",
181                                                 .type = BLOBMSG_TYPE_STRING },
182 };
183
184 /*
185  * Validate a uci name
186  */
187 static bool
188 rpc_uci_verify_str(const char *name, bool extended, bool type)
189 {
190         const char *c;
191         char *e;
192
193         if (!name || !*name)
194                 return false;
195
196         if (extended && *name != '@')
197                 extended = false;
198
199         for (c = name + extended; *c; c++)
200                 if (!isalnum(*c) && *c != '_' && ((!type && !extended) || *c != '-'))
201                         break;
202
203         if (extended) {
204                 if (*c != '[')
205                         return false;
206
207                 strtol(++c, &e, 10);
208
209                 return (e > c && *e == ']' && *(e+1) == 0);
210         }
211
212         return (*c == 0);
213 }
214
215 /*
216  * Check that string is a valid, shell compatible uci name
217  */
218 static bool rpc_uci_verify_name(const char *name) {
219         return rpc_uci_verify_str(name, false, false);
220 }
221
222 /*
223  * Check that string is a valid section type name
224  */
225 static bool rpc_uci_verify_type(const char *type) {
226         return rpc_uci_verify_str(type, false, true);
227 }
228
229 /*
230  * Check that the string is a valid section id, optionally in extended
231  * lookup notation
232  */
233 static bool rpc_uci_verify_section(const char *section) {
234         return rpc_uci_verify_str(section, true, false);
235 }
236
237
238 /*
239  * Turn uci error state into ubus return code
240  */
241 static int
242 rpc_uci_status(void)
243 {
244         switch (cursor->err)
245         {
246         case UCI_OK:
247                 return UBUS_STATUS_OK;
248
249         case UCI_ERR_INVAL:
250                 return UBUS_STATUS_INVALID_ARGUMENT;
251
252         case UCI_ERR_NOTFOUND:
253                 return UBUS_STATUS_NOT_FOUND;
254
255         default:
256                 return UBUS_STATUS_UNKNOWN_ERROR;
257         }
258 }
259
260 /*
261  * Clear all save directories from the uci cursor and append the given path
262  * as new save directory.
263  */
264 static void
265 rpc_uci_replace_savedir(const char *path)
266 {
267         struct uci_element *e, *tmp;
268
269         uci_foreach_element_safe(&cursor->delta_path, tmp, e) {
270                 if (e->name)
271                         free(e->name);
272
273                 free(e);
274         }
275
276         cursor->delta_path.prev = &cursor->delta_path;
277         cursor->delta_path.next = &cursor->delta_path;
278
279         if (path)
280                 uci_set_savedir(cursor, path);
281 }
282
283 /*
284  * Setup per-session delta save directory. If the passed "sid" blob attribute
285  * pointer is NULL then the precedure was not invoked through the ubus-rpc so
286  * we do not perform session isolation and use the default save directory.
287  */
288 static void
289 rpc_uci_set_savedir(struct blob_attr *sid)
290 {
291         char path[PATH_MAX];
292
293         if (!sid)
294         {
295                 rpc_uci_replace_savedir("/tmp/.uci");
296                 return;
297         }
298
299         snprintf(path, sizeof(path) - 1,
300                  RPC_UCI_SAVEDIR_PREFIX "%s", blobmsg_get_string(sid));
301
302         rpc_uci_replace_savedir(path);
303 }
304
305 /*
306  * Test read access to given config. If the passed "sid" blob attribute pointer
307  * is NULL then the precedure was not invoked through the ubus-rpc so we do not
308  * perform access control and always assume true.
309  */
310 static bool
311 rpc_uci_read_access(struct blob_attr *sid, struct blob_attr *config)
312 {
313         rpc_uci_set_savedir(sid);
314
315         if (!sid)
316                 return true;
317
318         return rpc_session_access(blobmsg_data(sid), "uci",
319                                   blobmsg_data(config), "read");
320 }
321
322 /*
323  * Test write access to given config. If the passed "sid" blob attribute pointer
324  * is NULL then the precedure was not invoked through the ubus-rpc so we do not
325  * perform access control and always assume true.
326  */
327 static bool
328 rpc_uci_write_access(struct blob_attr *sid, struct blob_attr *config)
329 {
330         rpc_uci_set_savedir(sid);
331
332         if (!sid)
333                 return true;
334
335         return rpc_session_access(blobmsg_data(sid), "uci",
336                                   blobmsg_data(config), "write");
337 }
338
339 /*
340  * Format applicable blob value as string and place a pointer to the string
341  * buffer in "p". Uses a static string buffer.
342  */
343 static bool
344 rpc_uci_format_blob(struct blob_attr *v, const char **p)
345 {
346         static char buf[21];
347
348         *p = NULL;
349
350         switch (blobmsg_type(v))
351         {
352         case BLOBMSG_TYPE_STRING:
353                 *p = blobmsg_data(v);
354                 break;
355
356         case BLOBMSG_TYPE_INT64:
357                 snprintf(buf, sizeof(buf), "%"PRIu64, blobmsg_get_u64(v));
358                 *p = buf;
359                 break;
360
361         case BLOBMSG_TYPE_INT32:
362                 snprintf(buf, sizeof(buf), "%u", blobmsg_get_u32(v));
363                 *p = buf;
364                 break;
365
366         case BLOBMSG_TYPE_INT16:
367                 snprintf(buf, sizeof(buf), "%u", blobmsg_get_u16(v));
368                 *p = buf;
369                 break;
370
371         case BLOBMSG_TYPE_INT8:
372                 snprintf(buf, sizeof(buf), "%u", !!blobmsg_get_u8(v));
373                 *p = buf;
374                 break;
375
376         default:
377                 break;
378         }
379
380         return !!*p;
381 }
382
383 /*
384  * Lookup the given uci_ptr and enable extended lookup format if the .section
385  * value of the uci_ptr looks like extended syntax. Uses an internal copy
386  * of the given uci_ptr to perform the lookup as failing extended section
387  * lookup operations in libuci will zero our the uci_ptr struct.
388  * Copies the internal uci_ptr back to given the uci_ptr on success.
389  */
390 static int
391 rpc_uci_lookup(struct uci_ptr *ptr)
392 {
393         int rv;
394         struct uci_ptr lookup = *ptr;
395
396         if (!lookup.s && lookup.section && *lookup.section == '@')
397                 lookup.flags |= UCI_LOOKUP_EXTENDED;
398
399         rv = uci_lookup_ptr(cursor, &lookup, NULL, true);
400
401         if (!rv)
402                 *ptr = lookup;
403
404         return rv;
405 }
406
407 /*
408  * Checks whether the given uci_option object matches the given string value.
409  *  1) If the uci_option is of type list, check whether any of the list elements
410  *     equals to the given string
411  *  2) If the uci_option is of type string, parse it into space separated tokens
412  *     and check if any of the tokens equals to the given string.
413  *  Returns true if a list element or token matched the given string.
414  */
415 static bool
416 rpc_uci_match_option(struct uci_option *o, const char *cmp)
417 {
418         struct uci_element *e;
419         char *s, *p;
420
421         if (o->type == UCI_TYPE_LIST)
422         {
423                 uci_foreach_element(&o->v.list, e)
424                         if (e->name && !strcmp(e->name, cmp))
425                                 return true;
426
427                 return false;
428         }
429
430         if (!o->v.string)
431                 return false;
432
433         s = strdup(o->v.string);
434
435         if (!s)
436                 return false;
437
438         for (p = strtok(s, " \t"); p; p = strtok(NULL, " \t"))
439         {
440                 if (!strcmp(p, cmp))
441                 {
442                         free(s);
443                         return true;
444                 }
445         }
446
447         free(s);
448         return false;
449 }
450
451 /*
452  * Checks whether the given uci_section matches the type and value blob attrs.
453  *  1) Returns false if "type" is given and the section type does not match
454  *     the value specified in the "type" string blob attribute, else continue.
455  *  2) Tests whether any key in the "matches" table blob attribute exists in
456  *     the given uci_section and whether each value is contained in the
457  *     corresponding uci option value (see rpc_uci_match_option()).
458  *  3) A missing or empty "matches" table blob attribute is always considered
459  *     to be a match.
460  * Returns true if "type" matches or is NULL and "matches" matches or is NULL.
461  */
462 static bool
463 rpc_uci_match_section(struct uci_section *s,
464                       struct blob_attr *type, struct blob_attr *matches)
465 {
466         struct uci_element *e;
467         struct blob_attr *cur;
468         const char *cmp;
469         bool match = false;
470         bool empty = true;
471         int rem;
472
473         if (type && strcmp(s->type, blobmsg_data(type)))
474                 return false;
475
476         if (!matches)
477                 return true;
478
479         blobmsg_for_each_attr(cur, matches, rem)
480         {
481                 if (!rpc_uci_format_blob(cur, &cmp))
482                         continue;
483
484                 uci_foreach_element(&s->options, e)
485                 {
486                         if (strcmp(e->name, blobmsg_name(cur)))
487                                 continue;
488
489                         if (!rpc_uci_match_option(uci_to_option(e), cmp))
490                                 return false;
491
492                         match = true;
493                 }
494
495                 empty = false;
496         }
497
498         return (empty || match);
499 }
500
501 /*
502  * Dump the given uci_option value into the global blobmsg buffer and use
503  * given "name" as key.
504  *  1) If the uci_option is of type list, put a table into the blob buffer and
505  *     add each list item as string to it.
506  *  2) If the uci_option is of type string, put its value directly into the blob
507  *     buffer.
508  */
509 static void
510 rpc_uci_dump_option(struct uci_option *o, const char *name)
511 {
512         void *c;
513         struct uci_element *e;
514
515         switch (o->type)
516         {
517         case UCI_TYPE_STRING:
518                 blobmsg_add_string(&buf, name, o->v.string);
519                 break;
520
521         case UCI_TYPE_LIST:
522                 c = blobmsg_open_array(&buf, name);
523
524                 uci_foreach_element(&o->v.list, e)
525                         blobmsg_add_string(&buf, NULL, e->name);
526
527                 blobmsg_close_array(&buf, c);
528                 break;
529
530         default:
531                 break;
532         }
533 }
534
535 /*
536  * Dump the given uci_section object into the global blobmsg buffer and use
537  * given "name" as key.
538  * Puts a table into the blob buffer and puts each section option member value
539  * as value into the table using the option name as key.
540  * Adds three special keys ".anonymous", ".type" and ".name" which specify the
541  * corresponding section properties.
542  */
543 static void
544 rpc_uci_dump_section(struct uci_section *s, const char *name, int index)
545 {
546         void *c;
547         struct uci_option *o;
548         struct uci_element *e;
549
550         c = blobmsg_open_table(&buf, name);
551
552         blobmsg_add_u8(&buf, ".anonymous", s->anonymous);
553         blobmsg_add_string(&buf, ".type", s->type);
554         blobmsg_add_string(&buf, ".name", s->e.name);
555
556         if (index >= 0)
557                 blobmsg_add_u32(&buf, ".index", index);
558
559         uci_foreach_element(&s->options, e)
560         {
561                 o = uci_to_option(e);
562                 rpc_uci_dump_option(o, o->e.name);
563         }
564
565         blobmsg_close_table(&buf, c);
566 }
567
568 /*
569  * Dump the given uci_package object into the global blobmsg buffer and use
570  * given "name" as key.
571  * Puts a table into the blob buffer and puts each package section member as
572  * value into the table using the section name as key.
573  * Only dumps sections matching the given "type" and "matches", see explaination
574  * of rpc_uci_match_section() for details.
575  */
576 static void
577 rpc_uci_dump_package(struct uci_package *p, const char *name,
578                      struct blob_attr *type, struct blob_attr *matches)
579 {
580         void *c;
581         struct uci_element *e;
582         int i = -1;
583
584         c = blobmsg_open_table(&buf, name);
585
586         uci_foreach_element(&p->sections, e)
587         {
588                 i++;
589
590                 if (!rpc_uci_match_section(uci_to_section(e), type, matches))
591                         continue;
592
593                 rpc_uci_dump_section(uci_to_section(e), e->name, i);
594         }
595
596         blobmsg_close_table(&buf, c);
597 }
598
599
600 static int
601 rpc_uci_getcommon(struct ubus_context *ctx, struct ubus_request_data *req,
602                   struct blob_attr *msg, bool use_state)
603 {
604         struct blob_attr *tb[__RPC_G_MAX];
605         struct uci_package *p = NULL;
606         struct uci_ptr ptr = { 0 };
607
608         blobmsg_parse(rpc_uci_get_policy, __RPC_G_MAX, tb,
609                       blob_data(msg), blob_len(msg));
610
611         if (!tb[RPC_G_CONFIG])
612                 return UBUS_STATUS_INVALID_ARGUMENT;
613
614         if (!rpc_uci_read_access(tb[RPC_G_SESSION], tb[RPC_G_CONFIG]))
615                 return UBUS_STATUS_PERMISSION_DENIED;
616
617         ptr.package = blobmsg_data(tb[RPC_G_CONFIG]);
618
619         if (use_state)
620                 uci_set_savedir(cursor, "/var/state");
621
622         if (uci_load(cursor, ptr.package, &p))
623                 return rpc_uci_status();
624
625         if (tb[RPC_G_SECTION])
626         {
627                 ptr.section = blobmsg_data(tb[RPC_G_SECTION]);
628
629                 if (tb[RPC_G_OPTION])
630                         ptr.option = blobmsg_data(tb[RPC_G_OPTION]);
631         }
632
633         if (rpc_uci_lookup(&ptr) || !(ptr.flags & UCI_LOOKUP_COMPLETE))
634                 goto out;
635
636         blob_buf_init(&buf, 0);
637
638         switch (ptr.last->type)
639         {
640         case UCI_TYPE_PACKAGE:
641                 rpc_uci_dump_package(ptr.p, "values", tb[RPC_G_TYPE], tb[RPC_G_MATCH]);
642                 break;
643
644         case UCI_TYPE_SECTION:
645                 rpc_uci_dump_section(ptr.s, "values", -1);
646                 break;
647
648         case UCI_TYPE_OPTION:
649                 rpc_uci_dump_option(ptr.o, "value");
650                 break;
651
652         default:
653                 break;
654         }
655
656         ubus_send_reply(ctx, req, buf.head);
657
658 out:
659         uci_unload(cursor, p);
660
661         return rpc_uci_status();
662 }
663
664 static int
665 rpc_uci_get(struct ubus_context *ctx, struct ubus_object *obj,
666             struct ubus_request_data *req, const char *method,
667             struct blob_attr *msg)
668 {
669         return rpc_uci_getcommon(ctx, req, msg, false);
670 }
671
672 static int
673 rpc_uci_state(struct ubus_context *ctx, struct ubus_object *obj,
674               struct ubus_request_data *req, const char *method,
675               struct blob_attr *msg)
676 {
677         return rpc_uci_getcommon(ctx, req, msg, true);
678 }
679
680 static int
681 rpc_uci_add(struct ubus_context *ctx, struct ubus_object *obj,
682             struct ubus_request_data *req, const char *method,
683             struct blob_attr *msg)
684 {
685         struct blob_attr *tb[__RPC_A_MAX];
686         struct blob_attr *cur, *elem;
687         struct uci_package *p = NULL;
688         struct uci_section *s;
689         struct uci_ptr ptr = { 0 };
690         int rem, rem2, err = 0;
691
692         blobmsg_parse(rpc_uci_add_policy, __RPC_A_MAX, tb,
693                       blob_data(msg), blob_len(msg));
694
695         if (!tb[RPC_A_CONFIG] || !tb[RPC_A_TYPE])
696                 return UBUS_STATUS_INVALID_ARGUMENT;
697
698         if (!rpc_uci_write_access(tb[RPC_A_SESSION], tb[RPC_A_CONFIG]))
699                 return UBUS_STATUS_PERMISSION_DENIED;
700
701         if (!rpc_uci_verify_type(blobmsg_data(tb[RPC_A_TYPE])))
702                 return UBUS_STATUS_INVALID_ARGUMENT;
703
704         if (tb[RPC_A_NAME] &&
705             !rpc_uci_verify_name(blobmsg_data(tb[RPC_A_NAME])))
706                 return UBUS_STATUS_INVALID_ARGUMENT;
707
708         ptr.package = blobmsg_data(tb[RPC_A_CONFIG]);
709
710         if (uci_load(cursor, ptr.package, &p))
711                 return rpc_uci_status();
712
713         /* add named section */
714         if (tb[RPC_A_NAME])
715         {
716                 ptr.section = blobmsg_data(tb[RPC_A_NAME]);
717                 ptr.value   = blobmsg_data(tb[RPC_A_TYPE]);
718                 ptr.option  = NULL;
719
720                 if (rpc_uci_lookup(&ptr) || uci_set(cursor, &ptr))
721                         goto out;
722         }
723
724         /* add anon section */
725         else
726         {
727                 if (uci_add_section(cursor, p, blobmsg_data(tb[RPC_A_TYPE]), &s) || !s)
728                         goto out;
729
730                 ptr.section = s->e.name;
731         }
732
733         if (tb[RPC_A_VALUES])
734         {
735                 blobmsg_for_each_attr(cur, tb[RPC_A_VALUES], rem)
736                 {
737                         ptr.flags = 0;
738                         ptr.o = NULL;
739                         ptr.option = blobmsg_name(cur);
740
741                         if (!rpc_uci_verify_name(ptr.option))
742                         {
743                                 if (!err)
744                                         err = UBUS_STATUS_INVALID_ARGUMENT;
745
746                                 continue;
747                         }
748
749                         if (rpc_uci_lookup(&ptr) || !ptr.s)
750                         {
751                                 if (!err)
752                                         err = UBUS_STATUS_NOT_FOUND;
753
754                                 continue;
755                         }
756
757                         switch (blobmsg_type(cur))
758                         {
759                         case BLOBMSG_TYPE_ARRAY:
760                                 blobmsg_for_each_attr(elem, cur, rem2)
761                                 {
762                                         if (!rpc_uci_format_blob(elem, &ptr.value))
763                                         {
764                                                 if (!err)
765                                                         err = UBUS_STATUS_INVALID_ARGUMENT;
766
767                                                 continue;
768                                         }
769
770                                         uci_add_list(cursor, &ptr);
771                                 }
772
773                                 break;
774
775                         default:
776                                 if (!rpc_uci_format_blob(cur, &ptr.value))
777                                 {
778                                         if (!err)
779                                                 err = UBUS_STATUS_INVALID_ARGUMENT;
780                                 }
781                                 else
782                                 {
783                                         uci_set(cursor, &ptr);
784                                 }
785
786                                 break;
787                         }
788                 }
789         }
790
791         if (!err)
792         {
793                 uci_save(cursor, p);
794
795                 blob_buf_init(&buf, 0);
796                 blobmsg_add_string(&buf, "section", ptr.section);
797                 ubus_send_reply(ctx, req, buf.head);
798         }
799
800 out:
801         uci_unload(cursor, p);
802
803         return err ? err : rpc_uci_status();
804 }
805
806 /*
807  * Turn value from a blob attribute into uci set operation
808  *  1) if the blob is of type array, delete existing option (if any) and
809  *     emit uci add_list operations for each element
810  *  2) if the blob is not an array but an option of type list exists,
811  *     delete existing list and emit uci set operation for the blob value
812  *  3) in all other cases only emit a set operation if there is no existing
813  *     option of if the existing options value differs from the blob value
814  */
815 static int
816 rpc_uci_merge_set(struct blob_attr *opt, struct uci_ptr *ptr)
817 {
818         struct blob_attr *cur;
819         int rem, rv;
820
821         ptr->flags = 0;
822         ptr->o = NULL;
823         ptr->option = blobmsg_name(opt);
824         ptr->value = NULL;
825
826         if (!rpc_uci_verify_name(ptr->option))
827                 return UBUS_STATUS_INVALID_ARGUMENT;
828
829         if (rpc_uci_lookup(ptr) || !ptr->s)
830                 return UBUS_STATUS_NOT_FOUND;
831
832         if (blobmsg_type(opt) == BLOBMSG_TYPE_ARRAY)
833         {
834                 if (ptr->o)
835                         uci_delete(cursor, ptr);
836
837                 rv = UBUS_STATUS_INVALID_ARGUMENT;
838
839                 blobmsg_for_each_attr(cur, opt, rem)
840                 {
841                         if (!rpc_uci_format_blob(cur, &ptr->value))
842                                 continue;
843
844                         uci_add_list(cursor, ptr);
845                         rv = 0;
846                 }
847
848                 return rv;
849         }
850         else if (ptr->o && ptr->o->type == UCI_TYPE_LIST)
851         {
852                 uci_delete(cursor, ptr);
853
854                 if (!rpc_uci_format_blob(opt, &ptr->value))
855                         return UBUS_STATUS_INVALID_ARGUMENT;
856
857                 uci_set(cursor, ptr);
858         }
859         else
860         {
861                 if (!rpc_uci_format_blob(opt, &ptr->value))
862                         return UBUS_STATUS_INVALID_ARGUMENT;
863
864                 if (!ptr->o || !ptr->o->v.string || strcmp(ptr->o->v.string, ptr->value))
865                         uci_set(cursor, ptr);
866         }
867
868         return 0;
869 }
870
871 static int
872 rpc_uci_set(struct ubus_context *ctx, struct ubus_object *obj,
873             struct ubus_request_data *req, const char *method,
874             struct blob_attr *msg)
875 {
876         struct blob_attr *tb[__RPC_S_MAX];
877         struct blob_attr *cur;
878         struct uci_package *p = NULL;
879         struct uci_element *e;
880         struct uci_ptr ptr = { 0 };
881         int rem, rv, err = 0;
882
883         blobmsg_parse(rpc_uci_set_policy, __RPC_S_MAX, tb,
884                       blob_data(msg), blob_len(msg));
885
886         if (!tb[RPC_S_CONFIG] || !tb[RPC_S_VALUES] ||
887                 (!tb[RPC_S_SECTION] && !tb[RPC_S_TYPE] && !tb[RPC_S_MATCH]))
888                 return UBUS_STATUS_INVALID_ARGUMENT;
889
890         if (!rpc_uci_write_access(tb[RPC_S_SESSION], tb[RPC_S_CONFIG]))
891                 return UBUS_STATUS_PERMISSION_DENIED;
892
893         if (tb[RPC_S_SECTION] &&
894             !rpc_uci_verify_section(blobmsg_data(tb[RPC_S_SECTION])))
895                 return UBUS_STATUS_INVALID_ARGUMENT;
896
897         ptr.package = blobmsg_data(tb[RPC_S_CONFIG]);
898
899         if (uci_load(cursor, ptr.package, &p))
900                 return rpc_uci_status();
901
902         if (tb[RPC_S_SECTION])
903         {
904                 ptr.section = blobmsg_data(tb[RPC_S_SECTION]);
905                 blobmsg_for_each_attr(cur, tb[RPC_S_VALUES], rem)
906                 {
907                         rv = rpc_uci_merge_set(cur, &ptr);
908
909                         if (rv)
910                                 err = rv;
911                 }
912         }
913         else
914         {
915                 uci_foreach_element(&p->sections, e)
916                 {
917                         if (!rpc_uci_match_section(uci_to_section(e),
918                                                    tb[RPC_S_TYPE], tb[RPC_S_MATCH]))
919                                 continue;
920
921                         ptr.s = NULL;
922                         ptr.section = e->name;
923
924                         blobmsg_for_each_attr(cur, tb[RPC_S_VALUES], rem)
925                         {
926                                 rv = rpc_uci_merge_set(cur, &ptr);
927
928                                 if (rv)
929                                         err = rv;
930                         }
931                 }
932         }
933
934         if (!err && !ptr.s)
935                 err = UBUS_STATUS_NOT_FOUND;
936
937         if (!err)
938                 uci_save(cursor, p);
939
940         uci_unload(cursor, p);
941
942         return err ? err : rpc_uci_status();
943 }
944
945 /*
946  * Delete option or section from uci specified by given blob attribute pointer
947  *  1) if the blob is of type array, delete any option named after each element
948  *  2) if the blob is of type string, delete the option named after its value
949  *  3) if the blob is NULL, delete entire section
950  */
951 static int
952 rpc_uci_merge_delete(struct blob_attr *opt, struct uci_ptr *ptr)
953 {
954         struct blob_attr *cur;
955         int rem, rv;
956
957         if (rpc_uci_lookup(ptr) || !ptr->s)
958                 return UBUS_STATUS_NOT_FOUND;
959
960         if (!opt)
961         {
962                 ptr->o = NULL;
963                 ptr->option = NULL;
964
965                 uci_delete(cursor, ptr);
966                 return 0;
967         }
968         else if (blobmsg_type(opt) == BLOBMSG_TYPE_ARRAY)
969         {
970                 rv = UBUS_STATUS_NOT_FOUND;
971
972                 blobmsg_for_each_attr(cur, opt, rem)
973                 {
974                         if (blobmsg_type(cur) != BLOBMSG_TYPE_STRING)
975                                 continue;
976
977                         ptr->o = NULL;
978                         ptr->option = blobmsg_data(cur);
979
980                         if (rpc_uci_lookup(ptr) || !ptr->o)
981                                 continue;
982
983                         uci_delete(cursor, ptr);
984                         rv = 0;
985                 }
986
987                 return rv;
988         }
989         else if (blobmsg_type(opt) == BLOBMSG_TYPE_STRING)
990         {
991                 ptr->o = NULL;
992                 ptr->option = blobmsg_data(opt);
993
994                 if (rpc_uci_lookup(ptr) || !ptr->o)
995                         return UBUS_STATUS_NOT_FOUND;
996
997                 uci_delete(cursor, ptr);
998                 return 0;
999         }
1000
1001         return UBUS_STATUS_INVALID_ARGUMENT;
1002 }
1003
1004 static int
1005 rpc_uci_delete(struct ubus_context *ctx, struct ubus_object *obj,
1006                struct ubus_request_data *req, const char *method,
1007                struct blob_attr *msg)
1008 {
1009         struct blob_attr *tb[__RPC_D_MAX];
1010         struct uci_package *p = NULL;
1011         struct uci_element *e, *tmp;
1012         struct uci_ptr ptr = { 0 };
1013         int err = 0;
1014
1015         blobmsg_parse(rpc_uci_delete_policy, __RPC_D_MAX, tb,
1016                       blob_data(msg), blob_len(msg));
1017
1018         if (!tb[RPC_D_CONFIG] ||
1019                 (!tb[RPC_D_SECTION] && !tb[RPC_D_TYPE] && !tb[RPC_D_MATCH]))
1020                 return UBUS_STATUS_INVALID_ARGUMENT;
1021
1022         if (!rpc_uci_write_access(tb[RPC_D_SESSION], tb[RPC_D_CONFIG]))
1023                 return UBUS_STATUS_PERMISSION_DENIED;
1024
1025         if (tb[RPC_D_TYPE] &&
1026             !rpc_uci_verify_type(blobmsg_data(tb[RPC_D_TYPE])))
1027                 return UBUS_STATUS_INVALID_ARGUMENT;
1028
1029         if (tb[RPC_D_SECTION] &&
1030             !rpc_uci_verify_section(blobmsg_data(tb[RPC_D_SECTION])))
1031                 return UBUS_STATUS_INVALID_ARGUMENT;
1032
1033         ptr.package = blobmsg_data(tb[RPC_D_CONFIG]);
1034
1035         if (uci_load(cursor, ptr.package, &p))
1036                 return rpc_uci_status();
1037
1038         if (tb[RPC_D_SECTION])
1039         {
1040                 ptr.section = blobmsg_data(tb[RPC_D_SECTION]);
1041
1042                 if (tb[RPC_D_OPTIONS])
1043                         err = rpc_uci_merge_delete(tb[RPC_D_OPTIONS], &ptr);
1044                 else
1045                         err = rpc_uci_merge_delete(tb[RPC_D_OPTION], &ptr);
1046         }
1047         else
1048         {
1049                 uci_foreach_element_safe(&p->sections, tmp, e)
1050                 {
1051                         if (!rpc_uci_match_section(uci_to_section(e),
1052                                                    tb[RPC_D_TYPE], tb[RPC_D_MATCH]))
1053                                 continue;
1054
1055                         ptr.s = NULL;
1056                         ptr.section = e->name;
1057
1058                         if (tb[RPC_D_OPTIONS])
1059                                 err = rpc_uci_merge_delete(tb[RPC_D_OPTIONS], &ptr);
1060                         else
1061                                 err = rpc_uci_merge_delete(tb[RPC_D_OPTION], &ptr);
1062                 }
1063
1064                 if (!err && !ptr.section)
1065                         err = UBUS_STATUS_NOT_FOUND;
1066         }
1067
1068         if (!err)
1069                 uci_save(cursor, p);
1070
1071         uci_unload(cursor, p);
1072
1073         return err ? err : rpc_uci_status();
1074 }
1075
1076 static int
1077 rpc_uci_rename(struct ubus_context *ctx, struct ubus_object *obj,
1078                struct ubus_request_data *req, const char *method,
1079                struct blob_attr *msg)
1080 {
1081         struct blob_attr *tb[__RPC_R_MAX];
1082         struct uci_package *p = NULL;
1083         struct uci_ptr ptr = { 0 };
1084
1085         blobmsg_parse(rpc_uci_rename_policy, __RPC_R_MAX, tb,
1086                       blob_data(msg), blob_len(msg));
1087
1088         if (!tb[RPC_R_CONFIG] || !tb[RPC_R_SECTION] || !tb[RPC_R_NAME])
1089                 return UBUS_STATUS_INVALID_ARGUMENT;
1090
1091         if (!rpc_uci_write_access(tb[RPC_R_SESSION], tb[RPC_R_CONFIG]))
1092                 return UBUS_STATUS_PERMISSION_DENIED;
1093
1094         ptr.package = blobmsg_data(tb[RPC_R_CONFIG]);
1095         ptr.section = blobmsg_data(tb[RPC_R_SECTION]);
1096         ptr.value   = blobmsg_data(tb[RPC_R_NAME]);
1097
1098         if (!rpc_uci_verify_name(ptr.value))
1099                 return UBUS_STATUS_INVALID_ARGUMENT;
1100
1101         if (tb[RPC_R_OPTION])
1102                 ptr.option = blobmsg_data(tb[RPC_R_OPTION]);
1103
1104         if (uci_load(cursor, ptr.package, &p))
1105                 return rpc_uci_status();
1106
1107         if (uci_lookup_ptr(cursor, &ptr, NULL, true))
1108                 goto out;
1109
1110         if ((ptr.option && !ptr.o) || !ptr.s)
1111         {
1112                 cursor->err = UCI_ERR_NOTFOUND;
1113                 goto out;
1114         }
1115
1116         if (uci_rename(cursor, &ptr))
1117                 goto out;
1118
1119         uci_save(cursor, p);
1120
1121 out:
1122         uci_unload(cursor, p);
1123
1124         return rpc_uci_status();
1125 }
1126
1127 static int
1128 rpc_uci_order(struct ubus_context *ctx, struct ubus_object *obj,
1129               struct ubus_request_data *req, const char *method,
1130               struct blob_attr *msg)
1131 {
1132         struct blob_attr *tb[__RPC_O_MAX];
1133         struct blob_attr *cur;
1134         struct uci_package *p = NULL;
1135         struct uci_ptr ptr = { 0 };
1136         int rem, i = 0, err = 0;
1137
1138         blobmsg_parse(rpc_uci_order_policy, __RPC_O_MAX, tb,
1139                       blob_data(msg), blob_len(msg));
1140
1141         if (!tb[RPC_O_CONFIG] || !tb[RPC_O_SECTIONS])
1142                 return UBUS_STATUS_INVALID_ARGUMENT;
1143
1144         if (!rpc_uci_write_access(tb[RPC_O_SESSION], tb[RPC_O_CONFIG]))
1145                 return UBUS_STATUS_PERMISSION_DENIED;
1146
1147         ptr.package = blobmsg_data(tb[RPC_O_CONFIG]);
1148
1149         if (uci_load(cursor, ptr.package, &p))
1150                 return rpc_uci_status();
1151
1152         blobmsg_for_each_attr(cur, tb[RPC_O_SECTIONS], rem)
1153         {
1154                 if (blobmsg_type(cur) != BLOBMSG_TYPE_STRING)
1155                 {
1156                         if (!err)
1157                                 err = UBUS_STATUS_INVALID_ARGUMENT;
1158
1159                         continue;
1160                 }
1161
1162                 ptr.s = NULL;
1163                 ptr.section = blobmsg_data(cur);
1164
1165                 if (uci_lookup_ptr(cursor, &ptr, NULL, true) || !ptr.s)
1166                 {
1167                         if (!err)
1168                                 err = UBUS_STATUS_NOT_FOUND;
1169
1170                         continue;
1171                 }
1172
1173                 uci_reorder_section(cursor, ptr.s, i++);
1174         }
1175
1176         if (!err)
1177                 uci_save(cursor, p);
1178
1179         uci_unload(cursor, p);
1180
1181         return err ? err : rpc_uci_status();
1182 }
1183
1184 static void
1185 rpc_uci_dump_change(struct uci_delta *d)
1186 {
1187         void *c;
1188         const char *types[] = {
1189                 [UCI_CMD_REORDER]  = "order",
1190                 [UCI_CMD_REMOVE]   = "remove",
1191                 [UCI_CMD_RENAME]   = "rename",
1192                 [UCI_CMD_ADD]      = "add",
1193                 [UCI_CMD_LIST_ADD] = "list-add",
1194                 [UCI_CMD_LIST_DEL] = "list-del",
1195                 [UCI_CMD_CHANGE]   = "set",
1196         };
1197
1198         if (!d->section)
1199                 return;
1200
1201         c = blobmsg_open_array(&buf, NULL);
1202
1203         blobmsg_add_string(&buf, NULL, types[d->cmd]);
1204         blobmsg_add_string(&buf, NULL, d->section);
1205
1206         if (d->e.name)
1207                 blobmsg_add_string(&buf, NULL, d->e.name);
1208
1209         if (d->value)
1210         {
1211                 if (d->cmd == UCI_CMD_REORDER)
1212                         blobmsg_add_u32(&buf, NULL, strtoul(d->value, NULL, 10));
1213                 else
1214                         blobmsg_add_string(&buf, NULL, d->value);
1215         }
1216
1217         blobmsg_close_array(&buf, c);
1218 }
1219
1220 static int
1221 rpc_uci_changes(struct ubus_context *ctx, struct ubus_object *obj,
1222                 struct ubus_request_data *req, const char *method,
1223                 struct blob_attr *msg)
1224 {
1225         struct blob_attr *tb[__RPC_C_MAX];
1226         struct uci_package *p = NULL;
1227         struct uci_element *e;
1228         char **configs;
1229         void *c, *d;
1230         int i;
1231
1232         blobmsg_parse(rpc_uci_config_policy, __RPC_C_MAX, tb,
1233                       blob_data(msg), blob_len(msg));
1234
1235         if (tb[RPC_C_CONFIG])
1236         {
1237                 if (!rpc_uci_read_access(tb[RPC_C_SESSION], tb[RPC_C_CONFIG]))
1238                         return UBUS_STATUS_PERMISSION_DENIED;
1239
1240                 if (uci_load(cursor, blobmsg_data(tb[RPC_C_CONFIG]), &p))
1241                         return rpc_uci_status();
1242
1243                 blob_buf_init(&buf, 0);
1244                 c = blobmsg_open_array(&buf, "changes");
1245
1246                 uci_foreach_element(&p->saved_delta, e)
1247                         rpc_uci_dump_change(uci_to_delta(e));
1248
1249                 blobmsg_close_array(&buf, c);
1250
1251                 uci_unload(cursor, p);
1252
1253                 ubus_send_reply(ctx, req, buf.head);
1254
1255                 return rpc_uci_status();
1256         }
1257
1258         rpc_uci_set_savedir(tb[RPC_C_SESSION]);
1259
1260         if (uci_list_configs(cursor, &configs))
1261                 return rpc_uci_status();
1262
1263         blob_buf_init(&buf, 0);
1264
1265         c = blobmsg_open_table(&buf, "changes");
1266
1267         for (i = 0; configs[i]; i++)
1268         {
1269                 if (tb[RPC_C_SESSION] &&
1270                     !rpc_session_access(blobmsg_data(tb[RPC_C_SESSION]), "uci",
1271                                         configs[i], "read"))
1272                         continue;
1273
1274                 if (uci_load(cursor, configs[i], &p))
1275                         continue;
1276
1277                 if (!uci_list_empty(&p->saved_delta))
1278                 {
1279                         d = blobmsg_open_array(&buf, configs[i]);
1280
1281                         uci_foreach_element(&p->saved_delta, e)
1282                                 rpc_uci_dump_change(uci_to_delta(e));
1283
1284                         blobmsg_close_array(&buf, d);
1285                 }
1286
1287                 uci_unload(cursor, p);
1288         }
1289
1290         free(configs);
1291
1292         blobmsg_close_table(&buf, c);
1293
1294         ubus_send_reply(ctx, req, buf.head);
1295
1296         return 0;
1297 }
1298
1299 static void
1300 rpc_uci_trigger_event(struct ubus_context *ctx, const char *config)
1301 {
1302         char *pkg = strdup(config);
1303         static struct blob_buf b;
1304         uint32_t id;
1305
1306         if (!ubus_lookup_id(ctx, "service", &id)) {
1307                 void *c;
1308
1309                 blob_buf_init(&b, 0);
1310                 blobmsg_add_string(&b, "type", "config.change");
1311                 c = blobmsg_open_table(&b, "data");
1312                 blobmsg_add_string(&b, "package", pkg);
1313                 blobmsg_close_table(&b, c);
1314                 ubus_invoke(ctx, id, "event", b.head, NULL, 0, 1000);
1315         }
1316         free(pkg);
1317 }
1318
1319 static int
1320 rpc_uci_revert_commit(struct ubus_context *ctx, struct blob_attr *msg, bool commit)
1321 {
1322         struct blob_attr *tb[__RPC_C_MAX];
1323         struct uci_package *p = NULL;
1324         struct uci_ptr ptr = { 0 };
1325
1326         if (apply_sid[0])
1327                 return UBUS_STATUS_PERMISSION_DENIED;
1328
1329         blobmsg_parse(rpc_uci_config_policy, __RPC_C_MAX, tb,
1330                       blob_data(msg), blob_len(msg));
1331
1332         if (!tb[RPC_C_CONFIG])
1333                 return UBUS_STATUS_INVALID_ARGUMENT;
1334
1335         if (!rpc_uci_write_access(tb[RPC_C_SESSION], tb[RPC_C_CONFIG]))
1336                 return UBUS_STATUS_PERMISSION_DENIED;
1337
1338         ptr.package = blobmsg_data(tb[RPC_C_CONFIG]);
1339
1340         if (commit)
1341         {
1342                 if (!uci_load(cursor, ptr.package, &p))
1343                 {
1344                         uci_commit(cursor, &p, false);
1345                         uci_unload(cursor, p);
1346                         rpc_uci_trigger_event(ctx, blobmsg_get_string(tb[RPC_C_CONFIG]));
1347                 }
1348         }
1349         else
1350         {
1351                 if (!uci_lookup_ptr(cursor, &ptr, NULL, true) && ptr.p)
1352                 {
1353                         uci_revert(cursor, &ptr);
1354                         uci_unload(cursor, ptr.p);
1355                 }
1356         }
1357
1358         return rpc_uci_status();
1359 }
1360
1361 static int
1362 rpc_uci_revert(struct ubus_context *ctx, struct ubus_object *obj,
1363                struct ubus_request_data *req, const char *method,
1364                struct blob_attr *msg)
1365 {
1366         return rpc_uci_revert_commit(ctx, msg, false);
1367 }
1368
1369 static int
1370 rpc_uci_commit(struct ubus_context *ctx, struct ubus_object *obj,
1371                struct ubus_request_data *req, const char *method,
1372                struct blob_attr *msg)
1373 {
1374         return rpc_uci_revert_commit(ctx, msg, true);
1375 }
1376
1377 static int
1378 rpc_uci_configs(struct ubus_context *ctx, struct ubus_object *obj,
1379                 struct ubus_request_data *req, const char *method,
1380                 struct blob_attr *msg)
1381 {
1382         char **configs;
1383         void *c;
1384         int i;
1385
1386         if (uci_list_configs(cursor, &configs))
1387                 goto out;
1388
1389         blob_buf_init(&buf, 0);
1390
1391         c = blobmsg_open_array(&buf, "configs");
1392
1393         for (i = 0; configs[i]; i++)
1394                 blobmsg_add_string(&buf, NULL, configs[i]);
1395
1396         free(configs);
1397
1398         blobmsg_close_array(&buf, c);
1399
1400         ubus_send_reply(ctx, req, buf.head);
1401
1402 out:
1403         return rpc_uci_status();
1404 }
1405
1406
1407 /*
1408  * Remove given delta save directory (if any).
1409  */
1410 static void
1411 rpc_uci_purge_dir(const char *path)
1412 {
1413         DIR *d;
1414         struct stat s;
1415         struct dirent *e;
1416         char file[PATH_MAX];
1417
1418         if (stat(path, &s) || !S_ISDIR(s.st_mode))
1419                 return;
1420
1421         if ((d = opendir(path)) != NULL)
1422         {
1423                 while ((e = readdir(d)) != NULL)
1424                 {
1425                         snprintf(file, sizeof(file) - 1, "%s/%s", path, e->d_name);
1426
1427                         if (stat(file, &s) || !S_ISREG(s.st_mode))
1428                                 continue;
1429
1430                         unlink(file);
1431                 }
1432
1433                 closedir(d);
1434
1435                 rmdir(path);
1436         }
1437 }
1438
1439 static int
1440 rpc_uci_apply_config(struct ubus_context *ctx, char *config)
1441 {
1442         struct uci_package *p = NULL;
1443
1444         if (!uci_load(cursor, config, &p)) {
1445                 uci_commit(cursor, &p, false);
1446                 uci_unload(cursor, p);
1447         }
1448         rpc_uci_trigger_event(ctx, config);
1449
1450         return 0;
1451 }
1452
1453 static void
1454 rpc_uci_copy_file(const char *src, const char *target, const char *file)
1455 {
1456         char tmp[256];
1457         FILE *in, *out;
1458
1459         snprintf(tmp, sizeof(tmp), "%s%s", src, file);
1460         in = fopen(tmp, "rb");
1461         snprintf(tmp, sizeof(tmp), "%s%s", target, file);
1462         out = fopen(tmp, "wb+");
1463         if (in && out)
1464                 while (!feof(in)) {
1465                         int len = fread(tmp, 1, sizeof(tmp), in);
1466
1467                         if(len > 0)
1468                                 fwrite(tmp, 1, len, out);
1469                 }
1470         if(in)
1471                 fclose(in);
1472         if(out)
1473                 fclose(out);
1474 }
1475
1476 static int
1477 rpc_uci_apply_access(const char *sid, glob_t *gl)
1478 {
1479         struct stat s;
1480         int i, c = 0;
1481
1482         if (gl->gl_pathc < 3)
1483                 return UBUS_STATUS_NO_DATA;
1484
1485         for (i = 0; i < gl->gl_pathc; i++) {
1486                 char *config = basename(gl->gl_pathv[i]);
1487
1488                 if (*config == '.')
1489                         continue;
1490                 if (stat(gl->gl_pathv[i], &s) || !s.st_size)
1491                         continue;
1492                 if (!rpc_session_access(sid, "uci", config, "write"))
1493                         return UBUS_STATUS_PERMISSION_DENIED;
1494                 c++;
1495         }
1496
1497         if (!c)
1498                 return UBUS_STATUS_NO_DATA;
1499
1500         return 0;
1501 }
1502
1503 static void
1504 rpc_uci_do_rollback(struct ubus_context *ctx, glob_t *gl)
1505 {
1506         int i, deny;
1507         char tmp[PATH_MAX];
1508
1509         /* Test apply permission to see if the initiator session still exists.
1510          * If it does, restore the delta files as well, else just restore the
1511          * main configuration files. */
1512         deny = apply_sid[0]
1513                 ? rpc_uci_apply_access(apply_sid, gl) : UBUS_STATUS_NOT_FOUND;
1514
1515         if (!deny) {
1516                 snprintf(tmp, sizeof(tmp), RPC_UCI_SAVEDIR_PREFIX "%s/", apply_sid);
1517                 mkdir(tmp, 0700);
1518         }
1519
1520         /* avoid merging unrelated uci changes when restoring old configs */
1521         rpc_uci_replace_savedir("/dev/null");
1522
1523         for (i = 0; i < gl->gl_pathc; i++) {
1524                 char *config = basename(gl->gl_pathv[i]);
1525
1526                 if (*config == '.')
1527                         continue;
1528
1529                 rpc_uci_copy_file(RPC_SNAPSHOT_FILES, RPC_UCI_DIR, config);
1530                 rpc_uci_apply_config(ctx, config);
1531
1532                 if (deny)
1533                         continue;
1534
1535                 rpc_uci_copy_file(RPC_SNAPSHOT_DELTA, tmp, config);
1536         }
1537
1538         rpc_uci_purge_dir(RPC_SNAPSHOT_FILES);
1539         rpc_uci_purge_dir(RPC_SNAPSHOT_DELTA);
1540
1541         uloop_timeout_cancel(&apply_timer);
1542         memset(apply_sid, 0, sizeof(apply_sid));
1543         apply_ctx = NULL;
1544 }
1545
1546 static void
1547 rpc_uci_apply_timeout(struct uloop_timeout *t)
1548 {
1549         glob_t gl;
1550         char tmp[PATH_MAX];
1551
1552         snprintf(tmp, sizeof(tmp), "%s/*", RPC_SNAPSHOT_FILES);
1553         if (glob(tmp, GLOB_PERIOD, NULL, &gl) < 0)
1554                 return;
1555
1556         rpc_uci_do_rollback(apply_ctx, &gl);
1557
1558         globfree(&gl);
1559 }
1560
1561 static int
1562 rpc_uci_apply(struct ubus_context *ctx, struct ubus_object *obj,
1563               struct ubus_request_data *req, const char *method,
1564               struct blob_attr *msg)
1565 {
1566         struct blob_attr *tb[__RPC_T_MAX];
1567         int timeout = RPC_APPLY_TIMEOUT;
1568         char tmp[PATH_MAX];
1569         bool rollback = false;
1570         int ret, i;
1571         char *sid;
1572         glob_t gl;
1573
1574         blobmsg_parse(rpc_uci_apply_policy, __RPC_T_MAX, tb,
1575                       blob_data(msg), blob_len(msg));
1576
1577         if (tb[RPC_T_ROLLBACK])
1578                 rollback = blobmsg_get_bool(tb[RPC_T_ROLLBACK]);
1579
1580         if (apply_sid[0] && rollback)
1581                 return UBUS_STATUS_PERMISSION_DENIED;
1582
1583         if (!tb[RPC_T_SESSION])
1584                 return UBUS_STATUS_INVALID_ARGUMENT;
1585
1586         sid = blobmsg_data(tb[RPC_T_SESSION]);
1587
1588         if (tb[RPC_T_TIMEOUT])
1589                 timeout = blobmsg_get_u32(tb[RPC_T_TIMEOUT]);
1590
1591         rpc_uci_purge_dir(RPC_SNAPSHOT_FILES);
1592         rpc_uci_purge_dir(RPC_SNAPSHOT_DELTA);
1593
1594         if (!apply_sid[0]) {
1595                 rpc_uci_set_savedir(tb[RPC_T_SESSION]);
1596
1597                 mkdir(RPC_SNAPSHOT_FILES, 0700);
1598                 mkdir(RPC_SNAPSHOT_DELTA, 0700);
1599
1600                 snprintf(tmp, sizeof(tmp), RPC_UCI_SAVEDIR_PREFIX "%s/*", sid);
1601                 if (glob(tmp, GLOB_PERIOD, NULL, &gl) < 0)
1602                         return UBUS_STATUS_NOT_FOUND;
1603
1604                 snprintf(tmp, sizeof(tmp), RPC_UCI_SAVEDIR_PREFIX "%s/", sid);
1605
1606                 ret = rpc_uci_apply_access(sid, &gl);
1607                 if (ret) {
1608                         globfree(&gl);
1609                         return ret;
1610                 }
1611
1612                 /* copy SID early because rpc_uci_apply_config() will clobber buf */
1613                 if (rollback)
1614                         strncpy(apply_sid, sid, RPC_SID_LEN);
1615
1616                 for (i = 0; i < gl.gl_pathc; i++) {
1617                         char *config = basename(gl.gl_pathv[i]);
1618                         struct stat s;
1619
1620                         if (*config == '.')
1621                                 continue;
1622
1623                         if (stat(gl.gl_pathv[i], &s) || !s.st_size)
1624                                 continue;
1625
1626                         rpc_uci_copy_file(RPC_UCI_DIR, RPC_SNAPSHOT_FILES, config);
1627                         rpc_uci_copy_file(tmp, RPC_SNAPSHOT_DELTA, config);
1628                         rpc_uci_apply_config(ctx, config);
1629                 }
1630
1631                 globfree(&gl);
1632
1633                 if (rollback) {
1634                         apply_timer.cb = rpc_uci_apply_timeout;
1635                         uloop_timeout_set(&apply_timer, timeout * 1000);
1636                         apply_ctx = ctx;
1637                 }
1638         }
1639
1640         return 0;
1641 }
1642
1643 static int
1644 rpc_uci_confirm(struct ubus_context *ctx, struct ubus_object *obj,
1645                 struct ubus_request_data *req, const char *method,
1646                 struct blob_attr *msg)
1647 {
1648         struct blob_attr *tb[__RPC_B_MAX];
1649         char *sid;
1650
1651         blobmsg_parse(rpc_uci_rollback_policy, __RPC_B_MAX, tb,
1652                       blob_data(msg), blob_len(msg));
1653
1654         if (!tb[RPC_B_SESSION])
1655                 return UBUS_STATUS_INVALID_ARGUMENT;
1656
1657         sid = blobmsg_data(tb[RPC_B_SESSION]);
1658
1659         if (!apply_sid[0])
1660                 return UBUS_STATUS_NO_DATA;
1661
1662         if (strcmp(apply_sid, sid))
1663                 return UBUS_STATUS_PERMISSION_DENIED;
1664
1665         rpc_uci_purge_dir(RPC_SNAPSHOT_FILES);
1666         rpc_uci_purge_dir(RPC_SNAPSHOT_DELTA);
1667
1668         uloop_timeout_cancel(&apply_timer);
1669         memset(apply_sid, 0, sizeof(apply_sid));
1670         apply_ctx = NULL;
1671
1672         return 0;
1673 }
1674
1675 static int
1676 rpc_uci_rollback(struct ubus_context *ctx, struct ubus_object *obj,
1677                  struct ubus_request_data *req, const char *method,
1678                  struct blob_attr *msg)
1679 {
1680         struct blob_attr *tb[__RPC_B_MAX];
1681         char tmp[PATH_MAX];
1682         glob_t gl;
1683         char *sid;
1684
1685         blobmsg_parse(rpc_uci_rollback_policy, __RPC_B_MAX, tb,
1686                       blob_data(msg), blob_len(msg));
1687
1688         if (!apply_sid[0])
1689                 return UBUS_STATUS_NO_DATA;
1690
1691         if (!tb[RPC_B_SESSION])
1692                 return UBUS_STATUS_INVALID_ARGUMENT;
1693
1694         sid = blobmsg_data(tb[RPC_B_SESSION]);
1695
1696         if (strcmp(apply_sid, sid))
1697                 return UBUS_STATUS_PERMISSION_DENIED;
1698
1699         snprintf(tmp, sizeof(tmp), "%s/*", RPC_SNAPSHOT_FILES);
1700         if (glob(tmp, GLOB_PERIOD, NULL, &gl) < 0)
1701                 return UBUS_STATUS_NOT_FOUND;
1702
1703         rpc_uci_do_rollback(ctx, &gl);
1704
1705         globfree(&gl);
1706
1707         return 0;
1708 }
1709
1710 static int
1711 rpc_uci_reload(struct ubus_context *ctx, struct ubus_object *obj,
1712                  struct ubus_request_data *req, const char *method,
1713                  struct blob_attr *msg)
1714 {
1715         char * const cmd[2] = { "/sbin/reload_config", NULL };
1716
1717         if (!fork()) {
1718                 /* wait for the RPC call to complete */
1719                 sleep(2);
1720                 return execv(cmd[0], cmd);
1721         }
1722
1723         return 0;
1724 }
1725
1726 /*
1727  * Session destroy callback to purge associated delta directory.
1728  */
1729 static void
1730 rpc_uci_purge_savedir_cb(struct rpc_session *ses, void *priv)
1731 {
1732         char path[PATH_MAX];
1733
1734         snprintf(path, sizeof(path) - 1, RPC_UCI_SAVEDIR_PREFIX "%s", ses->id);
1735         rpc_uci_purge_dir(path);
1736 }
1737
1738 /*
1739  * Removes all delta directories which match the RPC_UCI_SAVEDIR_PREFIX.
1740  * This is used to clean up garbage when starting rpcd.
1741  */
1742 void rpc_uci_purge_savedirs(void)
1743 {
1744         int i;
1745         glob_t gl;
1746
1747         if (!glob(RPC_UCI_SAVEDIR_PREFIX "*", 0, NULL, &gl))
1748         {
1749                 for (i = 0; i < gl.gl_pathc; i++)
1750                         rpc_uci_purge_dir(gl.gl_pathv[i]);
1751
1752                 globfree(&gl);
1753         }
1754 }
1755
1756 int rpc_uci_api_init(struct ubus_context *ctx)
1757 {
1758         static const struct ubus_method uci_methods[] = {
1759                 { .name = "configs", .handler = rpc_uci_configs },
1760                 UBUS_METHOD("get",      rpc_uci_get,      rpc_uci_get_policy),
1761                 UBUS_METHOD("state",    rpc_uci_state,    rpc_uci_get_policy),
1762                 UBUS_METHOD("add",      rpc_uci_add,      rpc_uci_add_policy),
1763                 UBUS_METHOD("set",      rpc_uci_set,      rpc_uci_set_policy),
1764                 UBUS_METHOD("delete",   rpc_uci_delete,   rpc_uci_delete_policy),
1765                 UBUS_METHOD("rename",   rpc_uci_rename,   rpc_uci_rename_policy),
1766                 UBUS_METHOD("order",    rpc_uci_order,    rpc_uci_order_policy),
1767                 UBUS_METHOD("changes",  rpc_uci_changes,  rpc_uci_config_policy),
1768                 UBUS_METHOD("revert",   rpc_uci_revert,   rpc_uci_config_policy),
1769                 UBUS_METHOD("commit",   rpc_uci_commit,   rpc_uci_config_policy),
1770                 UBUS_METHOD("apply",    rpc_uci_apply,    rpc_uci_apply_policy),
1771                 UBUS_METHOD("confirm",  rpc_uci_confirm,  rpc_uci_rollback_policy),
1772                 UBUS_METHOD("rollback", rpc_uci_rollback, rpc_uci_rollback_policy),
1773                 UBUS_METHOD_NOARG("reload_config", rpc_uci_reload),
1774         };
1775
1776         static struct ubus_object_type uci_type =
1777                 UBUS_OBJECT_TYPE("luci-rpc-uci", uci_methods);
1778
1779         static struct ubus_object obj = {
1780                 .name = "uci",
1781                 .type = &uci_type,
1782                 .methods = uci_methods,
1783                 .n_methods = ARRAY_SIZE(uci_methods),
1784         };
1785
1786         static struct rpc_session_cb cb = {
1787                 .cb = rpc_uci_purge_savedir_cb
1788         };
1789
1790         cursor = uci_alloc_context();
1791
1792         if (!cursor)
1793                 return UBUS_STATUS_UNKNOWN_ERROR;
1794
1795         rpc_session_destroy_cb(&cb);
1796
1797         return ubus_add_object(ctx, &obj);
1798 }