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