file: exec: properly free memory on error
[oweals/rpcd.git] / file.c
1 /*
2  * rpcd - UBUS RPC server
3  *
4  *   Copyright (C) 2013-2014 Jo-Philipp Wich <jow@openwrt.org>
5  *   Copyright (C) 2016 Luka Perkov <luka@openwrt.org>
6  *
7  * Permission to use, copy, modify, and/or distribute this software for any
8  * purpose with or without fee is hereby granted, provided that the above
9  * copyright notice and this permission notice appear in all copies.
10  *
11  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
12  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
13  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
14  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
15  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
16  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
17  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
18  */
19
20 #define _GNU_SOURCE
21
22 #include <fcntl.h>
23 #include <errno.h>
24 #include <unistd.h>
25 #include <stdint.h>
26 #include <stdlib.h>
27 #include <string.h>
28 #include <limits.h>
29 #include <dirent.h>
30 #include <sys/stat.h>
31 #include <sys/wait.h>
32 #include <libubus.h>
33 #include <libubox/blobmsg.h>
34 #include <libubox/md5.h>
35 #include <libubox/ustream.h>
36 #include <libubox/utils.h>
37
38 #include <rpcd/plugin.h>
39
40 /* limit of sys & proc files */
41 #define RPC_FILE_MIN_SIZE               (4096)
42
43 /* limit of regular files and command output data */
44 #define RPC_FILE_MAX_SIZE               (4096 * 64)
45
46 #define ustream_for_each_read_buffer(stream, ptr, len) \
47         for (ptr = ustream_get_read_buf(stream, &len);     \
48              ptr != NULL && len > 0;                       \
49              ustream_consume(stream, len), ptr = ustream_get_read_buf(stream, &len))
50
51 #define ustream_declare(us, fd, name)                     \
52         us.stream.string_data   = true;                       \
53         us.stream.r.buffer_len  = 4096;                       \
54         us.stream.r.max_buffers = RPC_FILE_MAX_SIZE / 4096;   \
55         us.stream.notify_read   = rpc_file_##name##_read_cb;  \
56         us.stream.notify_state  = rpc_file_##name##_state_cb; \
57         ustream_fd_init(&us, fd);
58
59 static const struct rpc_daemon_ops *ops;
60
61 struct rpc_file_exec_context {
62         struct ubus_context *context;
63         struct ubus_request_data request;
64         struct uloop_timeout timeout;
65         struct uloop_process process;
66         struct ustream_fd opipe;
67         struct ustream_fd epipe;
68         int stat;
69 };
70
71
72 static struct blob_buf buf;
73 static char *canonpath;
74
75 enum {
76         RPC_F_R_PATH,
77         RPC_F_R_SESSION,
78         __RPC_F_R_MAX,
79 };
80
81 static const struct blobmsg_policy rpc_file_R_policy[__RPC_F_R_MAX] = {
82         [RPC_F_R_PATH]    = { .name = "path", .type = BLOBMSG_TYPE_STRING },
83         [RPC_F_R_SESSION] = { .name = "ubus_rpc_session",
84                               .type = BLOBMSG_TYPE_STRING },
85 };
86
87 enum {
88         RPC_F_RB_PATH,
89         RPC_F_RB_BASE64,
90         RPC_F_RB_SESSION,
91         __RPC_F_RB_MAX,
92 };
93
94 static const struct blobmsg_policy rpc_file_RB_policy[__RPC_F_RB_MAX] = {
95         [RPC_F_RB_PATH]    = { .name = "path",   .type = BLOBMSG_TYPE_STRING },
96         [RPC_F_RB_BASE64]  = { .name = "base64", .type = BLOBMSG_TYPE_BOOL   },
97         [RPC_F_RB_SESSION] = { .name = "ubus_rpc_session",
98                                .type = BLOBMSG_TYPE_STRING },
99 };
100
101 enum {
102         RPC_F_RW_PATH,
103         RPC_F_RW_DATA,
104         RPC_F_RW_APPEND,
105         RPC_F_RW_MODE,
106         RPC_F_RW_BASE64,
107         RPC_F_RW_SESSION,
108         __RPC_F_RW_MAX,
109 };
110
111 static const struct blobmsg_policy rpc_file_RW_policy[__RPC_F_RW_MAX] = {
112         [RPC_F_RW_PATH]    = { .name = "path",   .type = BLOBMSG_TYPE_STRING },
113         [RPC_F_RW_DATA]    = { .name = "data",   .type = BLOBMSG_TYPE_STRING },
114         [RPC_F_RW_APPEND]  = { .name = "append", .type = BLOBMSG_TYPE_BOOL  },
115         [RPC_F_RW_MODE]    = { .name = "mode",   .type = BLOBMSG_TYPE_INT32  },
116         [RPC_F_RW_BASE64]  = { .name = "base64", .type = BLOBMSG_TYPE_BOOL   },
117         [RPC_F_RW_SESSION] = { .name = "ubus_rpc_session",
118                                .type = BLOBMSG_TYPE_STRING },
119 };
120
121 enum {
122         RPC_E_CMD,
123         RPC_E_PARM,
124         RPC_E_ENV,
125         RPC_E_SESSION,
126         __RPC_E_MAX,
127 };
128
129 static const struct blobmsg_policy rpc_exec_policy[__RPC_E_MAX] = {
130         [RPC_E_CMD]     = { .name = "command", .type = BLOBMSG_TYPE_STRING },
131         [RPC_E_PARM]    = { .name = "params",  .type = BLOBMSG_TYPE_ARRAY  },
132         [RPC_E_ENV]     = { .name = "env",     .type = BLOBMSG_TYPE_TABLE  },
133         [RPC_E_SESSION] = { .name = "ubus_rpc_session",
134                             .type = BLOBMSG_TYPE_STRING },
135 };
136
137 static const char *d_types[] = {
138         [DT_BLK]     = "block",
139         [DT_CHR]     = "char",
140         [DT_DIR]     = "directory",
141         [DT_FIFO]    = "fifo",
142         [DT_LNK]     = "symlink",
143         [DT_REG]     = "file",
144         [DT_SOCK]    = "socket",
145         [DT_UNKNOWN] = "unknown",
146 };
147
148
149 static int
150 rpc_errno_status(void)
151 {
152         switch (errno)
153         {
154         case EACCES:
155                 return UBUS_STATUS_PERMISSION_DENIED;
156
157         case ENOTDIR:
158                 return UBUS_STATUS_INVALID_ARGUMENT;
159
160         case ENOENT:
161                 return UBUS_STATUS_NOT_FOUND;
162
163         case EINVAL:
164                 return UBUS_STATUS_INVALID_ARGUMENT;
165
166         default:
167                 return UBUS_STATUS_UNKNOWN_ERROR;
168         }
169 }
170
171 static bool
172 rpc_file_access(const struct blob_attr *sid,
173                 const char *path, const char *perm)
174 {
175         if (!sid)
176                 return true;
177
178         return ops->session_access(blobmsg_data(sid), "file", path, perm);
179 }
180
181 static char *
182 rpc_canonicalize_path(const char *path)
183 {
184         char *cp;
185         const char *p;
186
187         if (path == NULL || *path == '\0')
188                 return NULL;
189
190         if (canonpath != NULL)
191                 free(canonpath);
192
193         canonpath = strdup(path);
194
195         if (canonpath == NULL)
196                 return NULL;
197
198         /* normalize */
199         for (cp = canonpath, p = path; *p != '\0'; ) {
200                 if (*p != '/')
201                         goto next;
202
203                 /* skip repeating / */
204                 if (p[1] == '/') {
205                         p++;
206                         continue;
207                 }
208
209                 /* /./ or /../ */
210                 if (p[1] == '.') {
211                         /* skip /./ */
212                         if ((p[2] == '\0') || (p[2] == '/')) {
213                                 p += 2;
214                                 continue;
215                         }
216
217                         /* collapse /x/../ */
218                         if ((p[2] == '.') && ((p[3] == '\0') || (p[3] == '/'))) {
219                                 while ((cp > canonpath) && (*--cp != '/'))
220                                         ;
221
222                                 p += 3;
223                                 continue;
224                         }
225                 }
226
227 next:
228                 *cp++ = *p++;
229         }
230
231         /* remove trailing slash if not root / */
232         if ((cp > canonpath + 1) && (cp[-1] == '/'))
233                 cp--;
234         else if (cp == canonpath)
235                 *cp++ = '/';
236
237         *cp = '\0';
238
239         return canonpath;
240 }
241
242 static struct blob_attr **
243 __rpc_check_path(const struct blobmsg_policy *policy, size_t policy_len,
244                  int policy_path_idx, int policy_sid_idx, const char *perm,
245                  struct blob_attr *msg, char **path, struct stat *s)
246 {
247         static struct blob_attr *tb[__RPC_F_RW_MAX]; /* largest _MAX constant */
248
249         blobmsg_parse(policy, policy_len, tb, blob_data(msg), blob_len(msg));
250
251         if (!tb[policy_path_idx])
252         {
253                 errno = EINVAL;
254                 return NULL;
255         }
256
257         *path = rpc_canonicalize_path(blobmsg_get_string(tb[policy_path_idx]));
258
259         if (*path == NULL)
260         {
261                 errno = ENOMEM;
262                 return NULL;
263         }
264
265         if (!rpc_file_access(tb[policy_sid_idx], *path, perm))
266         {
267                 errno = EACCES;
268                 return NULL;
269         }
270
271         if (s != NULL && stat(*path, s) != 0)
272                 return NULL;
273
274         return tb;
275 }
276
277 #define rpc_check_path(msg, policy_selector, perm, path, s) \
278         __rpc_check_path(rpc_file_ ## policy_selector ## _policy, \
279                 ARRAY_SIZE(rpc_file_ ## policy_selector ## _policy), \
280                 RPC_F_ ## policy_selector ## _PATH, \
281                 RPC_F_ ## policy_selector ## _SESSION, \
282                 perm, msg, path, s)
283
284 static int
285 rpc_file_read(struct ubus_context *ctx, struct ubus_object *obj,
286               struct ubus_request_data *req, const char *method,
287               struct blob_attr *msg)
288 {
289         struct blob_attr **tb;
290         bool base64 = false;
291         int fd, rv;
292         ssize_t len;
293         char *path;
294         struct stat s;
295         char *wbuf;
296
297         tb = rpc_check_path(msg, RB, "read", &path, &s);
298
299         if (tb == NULL)
300                 return rpc_errno_status();
301
302         if (s.st_size >= RPC_FILE_MAX_SIZE)
303                 return UBUS_STATUS_NOT_SUPPORTED;
304
305         if ((fd = open(path, O_RDONLY)) < 0)
306                 return rpc_errno_status();
307
308         /* some sysfs files do not report a length */
309         if (s.st_size == 0)
310                 s.st_size = RPC_FILE_MIN_SIZE;
311
312         blob_buf_init(&buf, 0);
313
314         if (tb[RPC_F_RB_BASE64])
315                 base64 = blobmsg_get_bool(tb[RPC_F_RB_BASE64]);
316
317         len = s.st_size + 1;
318         if (base64)
319                 len = B64_ENCODE_LEN(s.st_size);
320         wbuf = blobmsg_alloc_string_buffer(&buf, "data", len);
321
322         if (!wbuf)
323         {
324                 rv = UBUS_STATUS_UNKNOWN_ERROR;
325                 goto out;
326         }
327
328         if ((len = read(fd, wbuf, s.st_size)) <= 0)
329         {
330                 rv = UBUS_STATUS_NO_DATA;
331                 goto out;
332         }
333
334         if (base64)
335         {
336                 uint8_t *data = calloc(len, sizeof(uint8_t));
337                 if (!data)
338                 {
339                         rv = UBUS_STATUS_UNKNOWN_ERROR;
340                         goto out;
341                 }
342                 memcpy(data, wbuf, len);
343
344                 len = b64_encode(data, len, wbuf, B64_ENCODE_LEN(len));
345                 free(data);
346                 if (len < 0)
347                 {
348                         rv = UBUS_STATUS_UNKNOWN_ERROR;
349                         goto out;
350                 }
351         }
352
353         *(wbuf + len) = '\0';
354         blobmsg_add_string_buffer(&buf);
355
356         ubus_send_reply(ctx, req, buf.head);
357         rv = UBUS_STATUS_OK;
358
359 out:
360         blob_buf_free(&buf);
361         close(fd);
362         return rv;
363 }
364
365 static int
366 rpc_file_write(struct ubus_context *ctx, struct ubus_object *obj,
367                struct ubus_request_data *req, const char *method,
368                struct blob_attr *msg)
369 {
370         struct blob_attr **tb;
371         int append = O_TRUNC;
372         mode_t prev_mode, mode = 0666;
373         int fd, rv = 0;
374         char *path = NULL;
375         void *data = NULL;
376         ssize_t data_len = 0;
377
378         tb = rpc_check_path(msg, RW, "write", &path, NULL);
379
380         if (tb == NULL)
381                 return rpc_errno_status();
382
383         if (!tb[RPC_F_RW_DATA])
384                 return UBUS_STATUS_INVALID_ARGUMENT;
385
386         data = blobmsg_data(tb[RPC_F_RW_DATA]);
387         data_len = blobmsg_data_len(tb[RPC_F_RW_DATA]) - 1;
388
389         if (tb[RPC_F_RW_APPEND] && blobmsg_get_bool(tb[RPC_F_RW_APPEND]))
390                 append = O_APPEND;
391
392         if (tb[RPC_F_RW_MODE])
393                 mode = blobmsg_get_u32(tb[RPC_F_RW_MODE]);
394
395         prev_mode = umask(0);
396         fd = open(path, O_CREAT | O_WRONLY | append, mode);
397         umask(prev_mode);
398         if (fd < 0)
399                 return rpc_errno_status();
400
401         if (tb[RPC_F_RW_BASE64] && blobmsg_get_bool(tb[RPC_F_RW_BASE64]))
402         {
403                 data_len = b64_decode(data, data, data_len);
404                 if (data_len < 0)
405                 {
406                         rv = UBUS_STATUS_UNKNOWN_ERROR;
407                         goto out;
408                 }
409         }
410
411         if (write(fd, data, data_len) < 0)
412                 rv = -1;
413
414 out:
415         if (fsync(fd) < 0)
416                 rv = -1;
417
418         close(fd);
419         sync();
420
421         if (rv)
422                 return rpc_errno_status();
423
424         return 0;
425 }
426
427 static int
428 rpc_file_md5(struct ubus_context *ctx, struct ubus_object *obj,
429              struct ubus_request_data *req, const char *method,
430              struct blob_attr *msg)
431 {
432         int rv, i;
433         char *path;
434         struct stat s;
435         uint8_t md5[16];
436         char *wbuf;
437
438         if (!rpc_check_path(msg, R, "read", &path, &s))
439                 return rpc_errno_status();
440
441         if (!S_ISREG(s.st_mode))
442                 return UBUS_STATUS_NOT_SUPPORTED;
443
444         if ((rv = md5sum(path, md5)) <= 0)
445                 return rpc_errno_status();
446
447         blob_buf_init(&buf, 0);
448         wbuf = blobmsg_alloc_string_buffer(&buf, "md5", 33);
449
450         for (i = 0; i < 16; i++)
451                 sprintf(wbuf + (i * 2), "%02x", (uint8_t) md5[i]);
452
453         blobmsg_add_string_buffer(&buf);
454         ubus_send_reply(ctx, req, buf.head);
455         blob_buf_free(&buf);
456
457         return UBUS_STATUS_OK;
458 }
459
460 static void
461 _rpc_file_add_stat(struct stat *s)
462 {
463         int type;
464
465         type = S_ISREG(s->st_mode) ? DT_REG :
466                 S_ISDIR(s->st_mode) ? DT_DIR :
467                  S_ISCHR(s->st_mode) ? DT_CHR :
468                   S_ISBLK(s->st_mode) ? DT_BLK :
469                    S_ISFIFO(s->st_mode) ? DT_FIFO :
470                     S_ISLNK(s->st_mode) ? DT_LNK :
471                      S_ISSOCK(s->st_mode) ? DT_SOCK :
472                       DT_UNKNOWN;
473
474         blobmsg_add_string(&buf, "type", d_types[type]);
475         blobmsg_add_u32(&buf, "size",  s->st_size);
476         blobmsg_add_u32(&buf, "mode",  s->st_mode);
477         blobmsg_add_u32(&buf, "atime", s->st_atime);
478         blobmsg_add_u32(&buf, "mtime", s->st_mtime);
479         blobmsg_add_u32(&buf, "ctime", s->st_ctime);
480         blobmsg_add_u32(&buf, "inode", s->st_ino);
481         blobmsg_add_u32(&buf, "uid",   s->st_uid);
482         blobmsg_add_u32(&buf, "gid",   s->st_gid);
483 }
484
485 static int
486 rpc_file_list(struct ubus_context *ctx, struct ubus_object *obj,
487               struct ubus_request_data *req, const char *method,
488               struct blob_attr *msg)
489 {
490         DIR *fd;
491         void *c, *d;
492         struct stat s;
493         struct dirent *e;
494         char *path, *entrypath;
495
496         if (!rpc_check_path(msg, R, "list", &path, NULL))
497                 return rpc_errno_status();
498
499         if ((fd = opendir(path)) == NULL)
500                 return rpc_errno_status();
501
502         blob_buf_init(&buf, 0);
503         c = blobmsg_open_array(&buf, "entries");
504
505         while ((e = readdir(fd)) != NULL)
506         {
507                 if (!strcmp(e->d_name, ".") || !strcmp(e->d_name, ".."))
508                         continue;
509
510                 if (asprintf(&entrypath, "%s/%s", path, e->d_name) < 0)
511                         continue;
512
513                 if (!stat(entrypath, &s))
514                 {
515                         d = blobmsg_open_table(&buf, NULL);
516                         blobmsg_add_string(&buf, "name", e->d_name);
517                         _rpc_file_add_stat(&s);
518                         blobmsg_close_table(&buf, d);
519                 }
520
521                 free(entrypath);
522         }
523
524         closedir(fd);
525
526         blobmsg_close_array(&buf, c);
527         ubus_send_reply(ctx, req, buf.head);
528         blob_buf_free(&buf);
529
530         return 0;
531 }
532
533 static int
534 rpc_file_stat(struct ubus_context *ctx, struct ubus_object *obj,
535               struct ubus_request_data *req, const char *method,
536               struct blob_attr *msg)
537 {
538         char *path;
539         struct stat s;
540
541         if (!rpc_check_path(msg, R, "list", &path, &s))
542                 return rpc_errno_status();
543
544         blob_buf_init(&buf, 0);
545
546         blobmsg_add_string(&buf, "path", path);
547         _rpc_file_add_stat(&s);
548
549         ubus_send_reply(ctx, req, buf.head);
550         blob_buf_free(&buf);
551
552         return 0;
553 }
554
555 static int
556 rpc_file_remove_recursive(const char *path);
557
558 static int
559 rpc_file_remove_recursive(const char *path)
560 {
561         DIR *fd;
562         int err = 0;
563         struct stat s;
564         struct dirent *e;
565         char *entrypath;
566
567         if ((fd = opendir(path)) == NULL)
568                 return rpc_errno_status();
569
570         for (e = readdir(fd); e != NULL && err == 0; e = readdir(fd))
571         {
572                 if (!strcmp(e->d_name, ".") || !strcmp(e->d_name, ".."))
573                         continue;
574
575                 if (asprintf(&entrypath, "%s/%s", path, e->d_name) >= 0)
576                 {
577                         if (!lstat(entrypath, &s))
578                         {
579                                 if (S_ISDIR(s.st_mode))
580                                         err = rpc_file_remove_recursive(entrypath);
581                                 else if (unlink(entrypath))
582                                         err = rpc_errno_status();
583                         }
584
585                         free(entrypath);
586                 }
587                 else
588                 {
589                         err = UBUS_STATUS_UNKNOWN_ERROR;
590                 }
591         }
592
593         closedir(fd);
594
595         if (!err && rmdir(path))
596                 return rpc_errno_status();
597
598         return err;
599 }
600
601 static int
602 rpc_file_remove(struct ubus_context *ctx, struct ubus_object *obj,
603                 struct ubus_request_data *req, const char *method,
604                 struct blob_attr *msg)
605 {
606         struct stat s;
607         char *path = NULL;
608
609         if (!rpc_check_path(msg, R, "write", &path, NULL))
610                 return rpc_errno_status();
611
612         if (lstat(path, &s))
613                 return rpc_errno_status();
614
615         if (S_ISDIR(s.st_mode))
616                 return rpc_file_remove_recursive(path);
617
618         if (unlink(path))
619                 return rpc_errno_status();
620
621         return 0;
622 }
623
624 static const char *
625 rpc_file_exec_lookup(const char *cmd)
626 {
627         struct stat s;
628         int plen = 0, clen = strlen(cmd) + 1;
629         char *search, *p;
630         static char path[PATH_MAX];
631
632         if (!stat(cmd, &s) && S_ISREG(s.st_mode))
633                 return cmd;
634
635         search = getenv("PATH");
636
637         if (!search)
638                 search = "/bin:/usr/bin:/sbin:/usr/sbin";
639
640         p = search;
641
642         do
643         {
644                 if (*p != ':' && *p != '\0')
645                         continue;
646
647                 plen = p - search;
648
649                 if ((plen + clen) >= sizeof(path))
650                         continue;
651
652                 strncpy(path, search, plen);
653                 sprintf(path + plen, "/%s", cmd);
654
655                 if (!stat(path, &s) && S_ISREG(s.st_mode))
656                         return path;
657
658                 search = p + 1;
659         }
660         while (*p++);
661
662         return NULL;
663 }
664
665
666 static void
667 rpc_ustream_to_blobmsg(struct ustream *s, const char *name)
668 {
669         int len;
670         char *rbuf, *wbuf;
671
672         if ((len = ustream_pending_data(s, false)) > 0)
673         {
674                 wbuf = blobmsg_alloc_string_buffer(&buf, name, len + 1);
675
676                 if (!wbuf)
677                         return;
678
679                 ustream_for_each_read_buffer(s, rbuf, len)
680                 {
681                         memcpy(wbuf, rbuf, len);
682                         wbuf += len;
683                 }
684
685                 *wbuf = 0;
686                 blobmsg_add_string_buffer(&buf);
687         }
688 }
689
690 static void
691 rpc_file_exec_reply(struct rpc_file_exec_context *c, int rv)
692 {
693         uloop_timeout_cancel(&c->timeout);
694         uloop_process_delete(&c->process);
695
696         if (rv == UBUS_STATUS_OK)
697         {
698                 blob_buf_init(&buf, 0);
699
700                 blobmsg_add_u32(&buf, "code", WEXITSTATUS(c->stat));
701
702                 rpc_ustream_to_blobmsg(&c->opipe.stream, "stdout");
703                 rpc_ustream_to_blobmsg(&c->epipe.stream, "stderr");
704
705                 ubus_send_reply(c->context, &c->request, buf.head);
706                 blob_buf_free(&buf);
707         }
708
709         ubus_complete_deferred_request(c->context, &c->request, rv);
710
711         ustream_free(&c->opipe.stream);
712         ustream_free(&c->epipe.stream);
713
714         close(c->opipe.fd.fd);
715         close(c->epipe.fd.fd);
716
717         free(c);
718 }
719
720 static void
721 rpc_file_exec_timeout_cb(struct uloop_timeout *t)
722 {
723         struct rpc_file_exec_context *c =
724                 container_of(t, struct rpc_file_exec_context, timeout);
725
726         kill(c->process.pid, SIGKILL);
727         rpc_file_exec_reply(c, UBUS_STATUS_TIMEOUT);
728 }
729
730 static void
731 rpc_file_exec_process_cb(struct uloop_process *p, int stat)
732 {
733         struct rpc_file_exec_context *c =
734                 container_of(p, struct rpc_file_exec_context, process);
735
736         c->stat = stat;
737
738         ustream_poll(&c->opipe.stream);
739         ustream_poll(&c->epipe.stream);
740 }
741
742 static void
743 rpc_file_exec_opipe_read_cb(struct ustream *s, int bytes)
744 {
745         struct rpc_file_exec_context *c =
746                 container_of(s, struct rpc_file_exec_context, opipe.stream);
747
748         if (ustream_read_buf_full(s))
749                 rpc_file_exec_reply(c, UBUS_STATUS_NOT_SUPPORTED);
750 }
751
752 static void
753 rpc_file_exec_epipe_read_cb(struct ustream *s, int bytes)
754 {
755         struct rpc_file_exec_context *c =
756                 container_of(s, struct rpc_file_exec_context, epipe.stream);
757
758         if (ustream_read_buf_full(s))
759                 rpc_file_exec_reply(c, UBUS_STATUS_NOT_SUPPORTED);
760 }
761
762 static void
763 rpc_file_exec_opipe_state_cb(struct ustream *s)
764 {
765         struct rpc_file_exec_context *c =
766                 container_of(s, struct rpc_file_exec_context, opipe.stream);
767
768         if (c->opipe.stream.eof && c->epipe.stream.eof)
769                 rpc_file_exec_reply(c, UBUS_STATUS_OK);
770 }
771
772 static void
773 rpc_file_exec_epipe_state_cb(struct ustream *s)
774 {
775         struct rpc_file_exec_context *c =
776                 container_of(s, struct rpc_file_exec_context, epipe.stream);
777
778         if (c->opipe.stream.eof && c->epipe.stream.eof)
779                 rpc_file_exec_reply(c, UBUS_STATUS_OK);
780 }
781
782 static void
783 rpc_fdclose(int fd)
784 {
785         if (fd > 2)
786                 close(fd);
787 }
788
789 static int
790 rpc_file_exec_run(const char *cmd, const struct blob_attr *sid,
791                   const struct blob_attr *arg, const struct blob_attr *env,
792                   struct ubus_context *ctx, struct ubus_request_data *req)
793 {
794         pid_t pid;
795
796         int devnull;
797         int opipe[2];
798         int epipe[2];
799
800         int rem;
801         struct blob_attr *cur;
802
803         uint8_t arglen;
804         char *executable, **args, **tmp;
805
806         struct rpc_file_exec_context *c;
807
808         cmd = rpc_file_exec_lookup(cmd);
809
810         if (!cmd)
811                 return UBUS_STATUS_NOT_FOUND;
812
813         executable = rpc_canonicalize_path(cmd);
814
815         if (executable == NULL)
816                 return UBUS_STATUS_UNKNOWN_ERROR;
817
818         if (!rpc_file_access(sid, executable, "exec"))
819                 return UBUS_STATUS_PERMISSION_DENIED;
820
821         c = malloc(sizeof(*c));
822
823         if (!c)
824                 return UBUS_STATUS_UNKNOWN_ERROR;
825
826         if (pipe(opipe))
827                 goto fail_opipe;
828
829         if (pipe(epipe))
830                 goto fail_epipe;
831
832         switch ((pid = fork()))
833         {
834         case -1:
835                 goto fail_fork;
836
837         case 0:
838                 uloop_done();
839
840                 devnull = open("/dev/null", O_RDWR);
841
842                 if (devnull == -1)
843                         return UBUS_STATUS_UNKNOWN_ERROR;
844
845                 dup2(devnull, 0);
846                 dup2(opipe[1], 1);
847                 dup2(epipe[1], 2);
848
849                 rpc_fdclose(devnull);
850                 rpc_fdclose(opipe[0]);
851                 rpc_fdclose(opipe[1]);
852                 rpc_fdclose(epipe[0]);
853                 rpc_fdclose(epipe[1]);
854
855                 arglen = 2;
856                 args = malloc(sizeof(char *) * arglen);
857
858                 if (!args)
859                         return UBUS_STATUS_UNKNOWN_ERROR;
860
861                 args[0] = (char *)executable;
862                 args[1] = NULL;
863
864                 if (arg)
865                 {
866                         blobmsg_for_each_attr(cur, arg, rem)
867                         {
868                                 if (blobmsg_type(cur) != BLOBMSG_TYPE_STRING)
869                                         continue;
870
871                                 if (arglen == 255)
872                                 {
873                                         free(args);
874                                         return UBUS_STATUS_INVALID_ARGUMENT;
875                                 }
876
877                                 arglen++;
878                                 tmp = realloc(args, sizeof(char *) * arglen);
879
880                                 if (!tmp)
881                                 {
882                                         free(args);
883                                         return UBUS_STATUS_UNKNOWN_ERROR;
884                                 }
885
886                                 args = tmp;
887                                 args[arglen-2] = blobmsg_data(cur);
888                                 args[arglen-1] = NULL;
889                         }
890                 }
891
892                 if (env)
893                 {
894                         blobmsg_for_each_attr(cur, env, rem)
895                         {
896                                 if (blobmsg_type(cur) != BLOBMSG_TYPE_STRING)
897                                         continue;
898
899                                 setenv(blobmsg_name(cur), blobmsg_data(cur), 1);
900                         }
901                 }
902
903                 if (execv(executable, args))
904                         return rpc_errno_status();
905
906         default:
907                 memset(c, 0, sizeof(*c));
908
909                 ustream_declare(c->opipe, opipe[0], exec_opipe);
910                 ustream_declare(c->epipe, epipe[0], exec_epipe);
911
912                 c->process.pid = pid;
913                 c->process.cb = rpc_file_exec_process_cb;
914                 uloop_process_add(&c->process);
915
916                 c->timeout.cb = rpc_file_exec_timeout_cb;
917                 uloop_timeout_set(&c->timeout, *ops->exec_timeout);
918
919                 close(opipe[1]);
920                 close(epipe[1]);
921
922                 c->context = ctx;
923                 ubus_defer_request(ctx, req, &c->request);
924         }
925
926         return UBUS_STATUS_OK;
927
928 fail_fork:
929         close(epipe[0]);
930         close(epipe[1]);
931
932 fail_epipe:
933         close(opipe[0]);
934         close(opipe[1]);
935
936 fail_opipe:
937         free(c);
938         return rpc_errno_status();
939 }
940
941 static int
942 rpc_file_exec(struct ubus_context *ctx, struct ubus_object *obj,
943               struct ubus_request_data *req, const char *method,
944               struct blob_attr *msg)
945 {
946         struct blob_attr *tb[__RPC_E_MAX];
947
948         blobmsg_parse(rpc_exec_policy, __RPC_E_MAX, tb,
949                       blob_data(msg), blob_len(msg));
950
951         if (!tb[RPC_E_CMD])
952                 return UBUS_STATUS_INVALID_ARGUMENT;
953
954         return rpc_file_exec_run(blobmsg_data(tb[RPC_E_CMD]), tb[RPC_E_SESSION],
955                                  tb[RPC_E_PARM], tb[RPC_E_ENV], ctx, req);
956 }
957
958
959 static int
960 rpc_file_api_init(const struct rpc_daemon_ops *o, struct ubus_context *ctx)
961 {
962         static const struct ubus_method file_methods[] = {
963                 UBUS_METHOD("read",    rpc_file_read,   rpc_file_RB_policy),
964                 UBUS_METHOD("write",   rpc_file_write,  rpc_file_RW_policy),
965                 UBUS_METHOD("list",    rpc_file_list,   rpc_file_R_policy),
966                 UBUS_METHOD("stat",    rpc_file_stat,   rpc_file_R_policy),
967                 UBUS_METHOD("md5",     rpc_file_md5,    rpc_file_R_policy),
968                 UBUS_METHOD("remove",  rpc_file_remove, rpc_file_R_policy),
969                 UBUS_METHOD("exec",    rpc_file_exec,   rpc_exec_policy),
970         };
971
972         static struct ubus_object_type file_type =
973                 UBUS_OBJECT_TYPE("luci-rpc-file", file_methods);
974
975         static struct ubus_object obj = {
976                 .name = "file",
977                 .type = &file_type,
978                 .methods = file_methods,
979                 .n_methods = ARRAY_SIZE(file_methods),
980         };
981
982         ops = o;
983
984         return ubus_add_object(ctx, &obj);
985 }
986
987 struct rpc_plugin rpc_plugin = {
988         .init = rpc_file_api_init
989 };