9c1b301e023d34ff9eeaf3431425b3ca20405aea
[project/rpcd.git] / file.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 <fcntl.h>
20 #include <errno.h>
21 #include <unistd.h>
22 #include <stdlib.h>
23 #include <string.h>
24 #include <limits.h>
25 #include <dirent.h>
26 #include <sys/stat.h>
27 #include <sys/wait.h>
28 #include <libubus.h>
29 #include <libubox/blobmsg.h>
30 #include <libubox/md5.h>
31 #include <libubox/ustream.h>
32
33 #include <rpcd/plugin.h>
34
35 /* limit of sys & proc files */
36 #define RPC_FILE_MIN_SIZE               (128)
37
38 /* limit of regular files and command output data */
39 #define RPC_FILE_MAX_SIZE               (4096 * 64)
40 #define RPC_FILE_MAX_RUNTIME    (3 * 1000)
41
42 #define ustream_for_each_read_buffer(stream, ptr, len) \
43         for (ptr = ustream_get_read_buf(stream, &len);     \
44              ptr != NULL && len > 0;                       \
45              ustream_consume(stream, len), ptr = ustream_get_read_buf(stream, &len))
46
47 #define ustream_declare(us, fd, name)                     \
48         us.stream.string_data   = true;                       \
49         us.stream.r.buffer_len  = 4096;                       \
50         us.stream.r.max_buffers = RPC_FILE_MAX_SIZE / 4096;   \
51         us.stream.notify_read   = rpc_file_##name##_read_cb;  \
52         us.stream.notify_state  = rpc_file_##name##_state_cb; \
53         ustream_fd_init(&us, fd);
54
55 struct rpc_file_exec_context {
56         struct ubus_context *context;
57         struct ubus_request_data request;
58         struct uloop_timeout timeout;
59         struct uloop_process process;
60         struct ustream_fd opipe;
61         struct ustream_fd epipe;
62         int outlen;
63         char *out;
64         int errlen;
65         char *err;
66         int stat;
67 };
68
69
70 static struct blob_buf buf;
71
72 enum {
73         RPC_F_R_PATH,
74         __RPC_F_R_MAX,
75 };
76
77 static const struct blobmsg_policy rpc_file_r_policy[__RPC_F_R_MAX] = {
78         [RPC_F_R_PATH] = { .name = "path", .type = BLOBMSG_TYPE_STRING },
79 };
80
81 enum {
82         RPC_F_RW_PATH,
83         RPC_F_RW_DATA,
84         __RPC_F_RW_MAX,
85 };
86
87 static const struct blobmsg_policy rpc_file_rw_policy[__RPC_F_RW_MAX] = {
88         [RPC_F_RW_PATH] = { .name = "path", .type = BLOBMSG_TYPE_STRING },
89         [RPC_F_RW_DATA] = { .name = "data", .type = BLOBMSG_TYPE_STRING },
90 };
91
92 enum {
93         RPC_E_CMD,
94         RPC_E_PARM,
95         RPC_E_ENV,
96         __RPC_E_MAX,
97 };
98
99 static const struct blobmsg_policy rpc_exec_policy[__RPC_E_MAX] = {
100         [RPC_E_CMD]  = { .name = "command", .type = BLOBMSG_TYPE_STRING },
101         [RPC_E_PARM] = { .name = "params",  .type = BLOBMSG_TYPE_ARRAY  },
102         [RPC_E_ENV]  = { .name = "env",     .type = BLOBMSG_TYPE_TABLE  },
103 };
104
105 static const char *d_types[] = {
106         [DT_BLK]     = "block",
107         [DT_CHR]     = "char",
108         [DT_DIR]     = "directory",
109         [DT_FIFO]    = "fifo",
110         [DT_LNK]     = "symlink",
111         [DT_REG]     = "file",
112         [DT_SOCK]    = "socket",
113         [DT_UNKNOWN] = "unknown",
114 };
115
116
117 static int
118 rpc_errno_status(void)
119 {
120         switch (errno)
121         {
122         case EACCES:
123                 return UBUS_STATUS_PERMISSION_DENIED;
124
125         case ENOTDIR:
126                 return UBUS_STATUS_INVALID_ARGUMENT;
127
128         case ENOENT:
129                 return UBUS_STATUS_NOT_FOUND;
130
131         case EINVAL:
132                 return UBUS_STATUS_INVALID_ARGUMENT;
133
134         default:
135                 return UBUS_STATUS_UNKNOWN_ERROR;
136         }
137 }
138
139 static struct blob_attr **
140 rpc_check_path(struct blob_attr *msg, char **path, struct stat *s)
141 {
142         static struct blob_attr *tb[__RPC_F_R_MAX];
143
144         blobmsg_parse(rpc_file_r_policy, __RPC_F_R_MAX, tb, blob_data(msg), blob_len(msg));
145
146         if (!tb[RPC_F_R_PATH])
147         {
148                 errno = EINVAL;
149                 return NULL;
150         }
151
152         *path = blobmsg_data(tb[RPC_F_R_PATH]);
153
154         if (stat(*path, s))
155                 return NULL;
156
157         return tb;
158 }
159
160 static int
161 rpc_file_read(struct ubus_context *ctx, struct ubus_object *obj,
162               struct ubus_request_data *req, const char *method,
163               struct blob_attr *msg)
164 {
165         int fd, rv, len;
166         char *path;
167         struct stat s;
168         char *wbuf;
169
170         if (!rpc_check_path(msg, &path, &s))
171                 return rpc_errno_status();
172
173         if (s.st_size >= RPC_FILE_MAX_SIZE)
174                 return UBUS_STATUS_NOT_SUPPORTED;
175
176         if ((fd = open(path, O_RDONLY)) < 0)
177                 return rpc_errno_status();
178
179         /* some sysfs files do not report a length */
180         if (s.st_size == 0)
181                 s.st_size = RPC_FILE_MIN_SIZE;
182
183         blob_buf_init(&buf, 0);
184
185         wbuf = blobmsg_alloc_string_buffer(&buf, "data", s.st_size + 1);
186
187         if (!wbuf)
188         {
189                 rv = UBUS_STATUS_UNKNOWN_ERROR;
190                 goto out;
191         }
192
193         if ((len = read(fd, wbuf, s.st_size)) <= 0)
194         {
195                 rv = UBUS_STATUS_NO_DATA;
196                 goto out;
197         }
198
199         *(wbuf + len) = 0;
200         blobmsg_add_string_buffer(&buf);
201
202         ubus_send_reply(ctx, req, buf.head);
203         blob_buf_free(&buf);
204         rv = UBUS_STATUS_OK;
205
206 out:
207         close(fd);
208         return rv;
209 }
210
211 static int
212 rpc_file_write(struct ubus_context *ctx, struct ubus_object *obj,
213                struct ubus_request_data *req, const char *method,
214                struct blob_attr *msg)
215 {
216         int fd;
217         struct blob_attr *tb[__RPC_F_RW_MAX];
218
219         blobmsg_parse(rpc_file_rw_policy, __RPC_F_RW_MAX, tb,
220                       blob_data(msg), blob_len(msg));
221
222         if (!tb[RPC_F_RW_PATH] || !tb[RPC_F_RW_DATA])
223                 return UBUS_STATUS_INVALID_ARGUMENT;
224
225         if ((fd = open(blobmsg_data(tb[RPC_F_RW_PATH]), O_CREAT | O_TRUNC | O_WRONLY, 0666)) < 0)
226                 return rpc_errno_status();
227
228         if (write(fd, blobmsg_data(tb[RPC_F_RW_DATA]), blobmsg_data_len(tb[RPC_F_RW_DATA])) < 0)
229                 return rpc_errno_status();
230
231         if (fsync(fd) < 0)
232                 return rpc_errno_status();
233
234         close(fd);
235         sync();
236
237         return 0;
238 }
239
240 static int
241 rpc_file_md5(struct ubus_context *ctx, struct ubus_object *obj,
242              struct ubus_request_data *req, const char *method,
243              struct blob_attr *msg)
244
245         int rv, i;
246         char *path;
247         struct stat s;
248         uint8_t md5[16];
249         char *wbuf;
250
251         if (!rpc_check_path(msg, &path, &s))
252                 return rpc_errno_status();
253
254         if (!S_ISREG(s.st_mode))
255                 return UBUS_STATUS_NOT_SUPPORTED;
256
257         if ((rv = md5sum(path, md5)) <= 0)
258                 return rpc_errno_status();
259
260         blob_buf_init(&buf, 0);
261         wbuf = blobmsg_alloc_string_buffer(&buf, "md5", 33);
262
263         for (i = 0; i < 16; i++)
264                 sprintf(wbuf + (i * 2), "%02x", (uint8_t) md5[i]);
265
266         blobmsg_add_string_buffer(&buf);
267         ubus_send_reply(ctx, req, buf.head);
268         blob_buf_free(&buf);
269
270         return UBUS_STATUS_OK;
271 }
272
273 static int
274 rpc_file_list(struct ubus_context *ctx, struct ubus_object *obj,
275               struct ubus_request_data *req, const char *method,
276               struct blob_attr *msg)
277 {
278         DIR *fd;
279         void *c, *d;
280         char *path;
281         struct stat s;
282         struct dirent *e;
283
284         if (!rpc_check_path(msg, &path, &s))
285                 return rpc_errno_status();
286
287         if ((fd = opendir(path)) == NULL)
288                 return rpc_errno_status();
289
290         blob_buf_init(&buf, 0);
291         c = blobmsg_open_array(&buf, "entries");
292
293         while ((e = readdir(fd)) != NULL)
294         {
295                 if (!strcmp(e->d_name, ".") || !strcmp(e->d_name, ".."))
296                         continue;
297
298                 d = blobmsg_open_table(&buf, NULL);
299                 blobmsg_add_string(&buf, "name", e->d_name);
300                 blobmsg_add_string(&buf, "type", d_types[e->d_type]);
301                 blobmsg_close_table(&buf, d);
302         }
303
304         closedir(fd);
305
306         blobmsg_close_array(&buf, c);
307         ubus_send_reply(ctx, req, buf.head);
308         blob_buf_free(&buf);
309
310         return 0;
311 }
312
313 static int
314 rpc_file_stat(struct ubus_context *ctx, struct ubus_object *obj,
315               struct ubus_request_data *req, const char *method,
316               struct blob_attr *msg)
317 {
318         int type;
319         char *path;
320         struct stat s;
321
322         if (!rpc_check_path(msg, &path, &s))
323                 return rpc_errno_status();
324
325         blob_buf_init(&buf, 0);
326
327         type = S_ISREG(s.st_mode) ? DT_REG :
328                 S_ISDIR(s.st_mode) ? DT_DIR :
329                  S_ISCHR(s.st_mode) ? DT_CHR :
330                   S_ISBLK(s.st_mode) ? DT_BLK :
331                    S_ISFIFO(s.st_mode) ? DT_FIFO :
332                     S_ISLNK(s.st_mode) ? DT_LNK :
333                      S_ISSOCK(s.st_mode) ? DT_SOCK :
334                       DT_UNKNOWN;
335
336         blobmsg_add_string(&buf, "path", path);
337         blobmsg_add_string(&buf, "type", d_types[type]);
338         blobmsg_add_u32(&buf, "size",  s.st_size);
339         blobmsg_add_u32(&buf, "mode",  s.st_mode);
340         blobmsg_add_u32(&buf, "atime", s.st_atime);
341         blobmsg_add_u32(&buf, "mtime", s.st_mtime);
342         blobmsg_add_u32(&buf, "ctime", s.st_ctime);
343         blobmsg_add_u32(&buf, "inode", s.st_ino);
344         blobmsg_add_u32(&buf, "uid",   s.st_uid);
345         blobmsg_add_u32(&buf, "gid",   s.st_gid);
346
347         ubus_send_reply(ctx, req, buf.head);
348         blob_buf_free(&buf);
349
350         return 0;
351 }
352
353 static const char *
354 rpc_file_exec_lookup(const char *cmd)
355 {
356         struct stat s;
357         int plen = 0, clen = strlen(cmd) + 1;
358         char *search, *p;
359         static char path[PATH_MAX];
360
361         if (!stat(cmd, &s) && S_ISREG(s.st_mode))
362                 return cmd;
363
364         search = getenv("PATH");
365
366         if (!search)
367                 search = "/bin:/usr/bin:/sbin:/usr/sbin";
368
369         p = search;
370
371         do
372         {
373                 if (*p != ':' && *p != '\0')
374                         continue;
375
376                 plen = p - search;
377
378                 if ((plen + clen) >= sizeof(path))
379                         continue;
380
381                 strncpy(path, search, plen);
382                 sprintf(path + plen, "/%s", cmd);
383
384                 if (!stat(path, &s) && S_ISREG(s.st_mode))
385                         return path;
386
387                 search = p + 1;
388         }
389         while (*p++);
390
391         return NULL;
392 }
393
394
395 static void
396 rpc_ustream_to_blobmsg(struct ustream *s, const char *name)
397 {
398         int len;
399         char *rbuf, *wbuf;
400
401         if ((len = ustream_pending_data(s, false)) > 0)
402         {
403                 wbuf = blobmsg_alloc_string_buffer(&buf, name, len + 1);
404
405                 if (!wbuf)
406                         return;
407
408                 ustream_for_each_read_buffer(s, rbuf, len)
409                 {
410                         memcpy(wbuf, rbuf, len);
411                         wbuf += len;
412                 }
413
414                 *wbuf = 0;
415                 blobmsg_add_string_buffer(&buf);
416         }
417 }
418
419 static void
420 rpc_file_exec_reply(struct rpc_file_exec_context *c, int rv)
421 {
422         uloop_timeout_cancel(&c->timeout);
423         uloop_process_delete(&c->process);
424
425         if (rv == UBUS_STATUS_OK)
426         {
427                 blob_buf_init(&buf, 0);
428
429                 blobmsg_add_u32(&buf, "code", WEXITSTATUS(c->stat));
430
431                 rpc_ustream_to_blobmsg(&c->opipe.stream, "stdout");
432                 rpc_ustream_to_blobmsg(&c->epipe.stream, "stderr");
433
434                 ubus_send_reply(c->context, &c->request, buf.head);
435                 blob_buf_free(&buf);
436         }
437
438         ubus_complete_deferred_request(c->context, &c->request, rv);
439
440         ustream_free(&c->opipe.stream);
441         ustream_free(&c->epipe.stream);
442
443         close(c->opipe.fd.fd);
444         close(c->epipe.fd.fd);
445
446         free(c);
447 }
448
449 static void
450 rpc_file_exec_timeout_cb(struct uloop_timeout *t)
451 {
452         struct rpc_file_exec_context *c =
453                 container_of(t, struct rpc_file_exec_context, timeout);
454
455         kill(c->process.pid, SIGKILL);
456         rpc_file_exec_reply(c, UBUS_STATUS_TIMEOUT);
457 }
458
459 static void
460 rpc_file_exec_process_cb(struct uloop_process *p, int stat)
461 {
462         struct rpc_file_exec_context *c =
463                 container_of(p, struct rpc_file_exec_context, process);
464
465         c->stat = stat;
466
467         ustream_poll(&c->opipe.stream);
468         ustream_poll(&c->epipe.stream);
469 }
470
471 static void
472 rpc_file_exec_opipe_read_cb(struct ustream *s, int bytes)
473 {
474         struct rpc_file_exec_context *c =
475                 container_of(s, struct rpc_file_exec_context, opipe.stream);
476
477         if (ustream_read_buf_full(s))
478                 rpc_file_exec_reply(c, UBUS_STATUS_NOT_SUPPORTED);
479 }
480
481 static void
482 rpc_file_exec_epipe_read_cb(struct ustream *s, int bytes)
483 {
484         struct rpc_file_exec_context *c =
485                 container_of(s, struct rpc_file_exec_context, epipe.stream);
486
487         if (ustream_read_buf_full(s))
488                 rpc_file_exec_reply(c, UBUS_STATUS_NOT_SUPPORTED);
489 }
490
491 static void
492 rpc_file_exec_opipe_state_cb(struct ustream *s)
493 {
494         struct rpc_file_exec_context *c =
495                 container_of(s, struct rpc_file_exec_context, opipe.stream);
496
497         if (c->opipe.stream.eof && c->epipe.stream.eof)
498                 rpc_file_exec_reply(c, UBUS_STATUS_OK);
499 }
500
501 static void
502 rpc_file_exec_epipe_state_cb(struct ustream *s)
503 {
504         struct rpc_file_exec_context *c =
505                 container_of(s, struct rpc_file_exec_context, epipe.stream);
506
507         if (c->opipe.stream.eof && c->epipe.stream.eof)
508                 rpc_file_exec_reply(c, UBUS_STATUS_OK);
509 }
510
511 static int
512 rpc_file_exec_run(const char *cmd,
513                   const struct blob_attr *arg, const struct blob_attr *env,
514                   struct ubus_context *ctx, struct ubus_request_data *req)
515 {
516         pid_t pid;
517
518         int opipe[2];
519         int epipe[2];
520
521         int rem;
522         struct blob_attr *cur;
523
524         char arglen;
525         char **args;
526
527         struct rpc_file_exec_context *c;
528
529         cmd = rpc_file_exec_lookup(cmd);
530
531         if (!cmd)
532                 return UBUS_STATUS_NOT_FOUND;
533
534         c = malloc(sizeof(*c));
535
536         if (!c)
537                 return UBUS_STATUS_UNKNOWN_ERROR;
538
539         if (pipe(opipe) || pipe(epipe))
540                 return rpc_errno_status();
541
542         switch ((pid = fork()))
543         {
544         case -1:
545                 return rpc_errno_status();
546
547         case 0:
548                 uloop_done();
549
550                 dup2(opipe[1], 1);
551                 dup2(epipe[1], 2);
552
553                 close(0);
554                 close(opipe[0]);
555                 close(opipe[1]);
556                 close(epipe[0]);
557                 close(epipe[1]);
558
559                 arglen = 2;
560                 args = malloc(sizeof(char *) * arglen);
561
562                 if (!args)
563                         return UBUS_STATUS_UNKNOWN_ERROR;
564
565                 args[0] = (char *)cmd;
566                 args[1] = NULL;
567
568                 if (arg)
569                 {
570                         blobmsg_for_each_attr(cur, arg, rem)
571                         {
572                                 if (blobmsg_type(cur) != BLOBMSG_TYPE_STRING)
573                                         continue;
574
575                                 arglen++;
576
577                                 if (!(args = realloc(args, sizeof(char *) * arglen)))
578                                         return UBUS_STATUS_UNKNOWN_ERROR;
579
580                                 args[arglen-2] = blobmsg_data(cur);
581                                 args[arglen-1] = NULL;
582                         }
583                 }
584
585                 if (env)
586                 {
587                         blobmsg_for_each_attr(cur, env, rem)
588                         {
589                                 if (blobmsg_type(cur) != BLOBMSG_TYPE_STRING)
590                                         continue;
591
592                                 setenv(blobmsg_name(cur), blobmsg_data(cur), 1);
593                         }
594                 }
595
596                 if (execv(cmd, args))
597                         return rpc_errno_status();
598
599         default:
600                 memset(c, 0, sizeof(*c));
601
602                 ustream_declare(c->opipe, opipe[0], exec_opipe);
603                 ustream_declare(c->epipe, epipe[0], exec_epipe);
604
605                 c->process.pid = pid;
606                 c->process.cb = rpc_file_exec_process_cb;
607                 uloop_process_add(&c->process);
608
609                 c->timeout.cb = rpc_file_exec_timeout_cb;
610                 uloop_timeout_set(&c->timeout, RPC_FILE_MAX_RUNTIME);
611
612                 close(opipe[1]);
613                 close(epipe[1]);
614
615                 c->context = ctx;
616                 ubus_defer_request(ctx, req, &c->request);
617         }
618
619         return UBUS_STATUS_OK;
620 }
621
622 static int
623 rpc_file_exec(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_E_MAX];
628
629         blobmsg_parse(rpc_exec_policy, __RPC_E_MAX, tb,
630                       blob_data(msg), blob_len(msg));
631
632         if (!tb[RPC_E_CMD])
633                 return UBUS_STATUS_INVALID_ARGUMENT;
634
635         return rpc_file_exec_run(blobmsg_data(tb[RPC_E_CMD]),
636                                               tb[RPC_E_PARM], tb[RPC_E_ENV], ctx, req);
637 }
638
639
640 static int
641 rpc_file_api_init(const struct rpc_daemon_ops *o, struct ubus_context *ctx)
642 {
643         static const struct ubus_method file_methods[] = {
644                 UBUS_METHOD("read",    rpc_file_read,  rpc_file_r_policy),
645                 UBUS_METHOD("write",   rpc_file_write, rpc_file_rw_policy),
646                 UBUS_METHOD("list",    rpc_file_list,  rpc_file_r_policy),
647                 UBUS_METHOD("stat",    rpc_file_stat,  rpc_file_r_policy),
648                 UBUS_METHOD("md5",     rpc_file_md5,   rpc_file_r_policy),
649                 UBUS_METHOD("exec",    rpc_file_exec,  rpc_exec_policy),
650         };
651
652         static struct ubus_object_type file_type =
653                 UBUS_OBJECT_TYPE("luci-rpc-file", file_methods);
654
655         static struct ubus_object obj = {
656                 .name = "file",
657                 .type = &file_type,
658                 .methods = file_methods,
659                 .n_methods = ARRAY_SIZE(file_methods),
660         };
661
662         return ubus_add_object(ctx, &obj);
663 }
664
665 struct rpc_plugin rpc_plugin = {
666         .init = rpc_file_api_init
667 };