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