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