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