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