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