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