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