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