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