aaba37d0d48662773d5d71b083369c096b134752
[project/cgi-io.git] / src / main.c
1 /*
2 * cgi-io - LuCI non-RPC helper
3 *
4 * Copyright (C) 2013 Jo-Philipp Wich <jo@mein.io>
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 <stdio.h>
20 #include <stdlib.h>
21 #include <stdbool.h>
22 #include <unistd.h>
23 #include <string.h>
24 #include <errno.h>
25 #include <fcntl.h>
26 #include <ctype.h>
27 #include <sys/stat.h>
28 #include <sys/wait.h>
29 #include <sys/sendfile.h>
30 #include <sys/ioctl.h>
31 #include <linux/fs.h>
32
33 #include <libubus.h>
34 #include <libubox/blobmsg.h>
35
36 #include "multipart_parser.h"
37
38
39 enum part {
40 PART_UNKNOWN,
41 PART_SESSIONID,
42 PART_FILENAME,
43 PART_FILEMODE,
44 PART_FILEDATA
45 };
46
47 const char *parts[] = {
48 "(bug)",
49 "sessionid",
50 "filename",
51 "filemode",
52 "filedata",
53 };
54
55 struct state
56 {
57 bool is_content_disposition;
58 enum part parttype;
59 char *sessionid;
60 char *filename;
61 bool filedata;
62 int filemode;
63 int filefd;
64 int tempfd;
65 };
66
67 enum {
68 SES_ACCESS,
69 __SES_MAX,
70 };
71
72 static const struct blobmsg_policy ses_policy[__SES_MAX] = {
73 [SES_ACCESS] = { .name = "access", .type = BLOBMSG_TYPE_BOOL },
74 };
75
76
77 static struct state st;
78
79 static void
80 session_access_cb(struct ubus_request *req, int type, struct blob_attr *msg)
81 {
82 struct blob_attr *tb[__SES_MAX];
83 bool *allow = (bool *)req->priv;
84
85 if (!msg)
86 return;
87
88 blobmsg_parse(ses_policy, __SES_MAX, tb, blob_data(msg), blob_len(msg));
89
90 if (tb[SES_ACCESS])
91 *allow = blobmsg_get_bool(tb[SES_ACCESS]);
92 }
93
94 static bool
95 session_access(const char *sid, const char *scope, const char *obj, const char *func)
96 {
97 uint32_t id;
98 bool allow = false;
99 struct ubus_context *ctx;
100 static struct blob_buf req;
101
102 ctx = ubus_connect(NULL);
103
104 if (!ctx || ubus_lookup_id(ctx, "session", &id))
105 goto out;
106
107 blob_buf_init(&req, 0);
108 blobmsg_add_string(&req, "ubus_rpc_session", sid);
109 blobmsg_add_string(&req, "scope", scope);
110 blobmsg_add_string(&req, "object", obj);
111 blobmsg_add_string(&req, "function", func);
112
113 ubus_invoke(ctx, id, "access", req.head, session_access_cb, &allow, 500);
114
115 out:
116 if (ctx)
117 ubus_free(ctx);
118
119 return allow;
120 }
121
122 static char *
123 checksum(const char *applet, size_t sumlen, const char *file)
124 {
125 pid_t pid;
126 int fds[2];
127 static char chksum[65];
128
129 if (pipe(fds))
130 return NULL;
131
132 switch ((pid = fork()))
133 {
134 case -1:
135 return NULL;
136
137 case 0:
138 uloop_done();
139
140 dup2(fds[1], 1);
141
142 close(0);
143 close(2);
144 close(fds[0]);
145 close(fds[1]);
146
147 if (execl("/bin/busybox", "/bin/busybox", applet, file, NULL))
148 return NULL;
149
150 break;
151
152 default:
153 memset(chksum, 0, sizeof(chksum));
154 read(fds[0], chksum, sumlen);
155 waitpid(pid, NULL, 0);
156 close(fds[0]);
157 close(fds[1]);
158 }
159
160 return chksum;
161 }
162
163 static char *
164 datadup(const void *in, size_t len)
165 {
166 char *out = malloc(len + 1);
167
168 if (!out)
169 return NULL;
170
171 memcpy(out, in, len);
172
173 *(out + len) = 0;
174
175 return out;
176 }
177
178 static bool
179 urldecode(char *buf)
180 {
181 char *c, *p;
182
183 if (!buf || !*buf)
184 return true;
185
186 #define hex(x) \
187 (((x) <= '9') ? ((x) - '0') : \
188 (((x) <= 'F') ? ((x) - 'A' + 10) : \
189 ((x) - 'a' + 10)))
190
191 for (c = p = buf; *p; c++)
192 {
193 if (*p == '%')
194 {
195 if (!isxdigit(*(p + 1)) || !isxdigit(*(p + 2)))
196 return false;
197
198 *c = (char)(16 * hex(*(p + 1)) + hex(*(p + 2)));
199
200 p += 3;
201 }
202 else if (*p == '+')
203 {
204 *c = ' ';
205 p++;
206 }
207 else
208 {
209 *c = *p++;
210 }
211 }
212
213 *c = 0;
214
215 return true;
216 }
217
218 static bool
219 postdecode(char **fields, int n_fields)
220 {
221 char *p;
222 const char *var;
223 static char buf[1024];
224 int i, len, field, found = 0;
225
226 var = getenv("CONTENT_TYPE");
227
228 if (!var || strncmp(var, "application/x-www-form-urlencoded", 33))
229 return false;
230
231 memset(buf, 0, sizeof(buf));
232
233 if ((len = read(0, buf, sizeof(buf) - 1)) > 0)
234 {
235 for (p = buf, i = 0; i <= len; i++)
236 {
237 if (buf[i] == '=')
238 {
239 buf[i] = 0;
240
241 for (field = 0; field < (n_fields * 2); field += 2)
242 {
243 if (!strcmp(p, fields[field]))
244 {
245 fields[field + 1] = buf + i + 1;
246 found++;
247 }
248 }
249 }
250 else if (buf[i] == '&' || buf[i] == '\0')
251 {
252 buf[i] = 0;
253
254 if (found >= n_fields)
255 break;
256
257 p = buf + i + 1;
258 }
259 }
260 }
261
262 for (field = 0; field < (n_fields * 2); field += 2)
263 if (!urldecode(fields[field + 1]))
264 return false;
265
266 return (found >= n_fields);
267 }
268
269 static char *
270 canonicalize_path(const char *path, size_t len)
271 {
272 char *canonpath, *cp;
273 const char *p, *e;
274
275 if (path == NULL || *path == '\0')
276 return NULL;
277
278 canonpath = datadup(path, len);
279
280 if (canonpath == NULL)
281 return NULL;
282
283 /* normalize */
284 for (cp = canonpath, p = path, e = path + len; p < e; ) {
285 if (*p != '/')
286 goto next;
287
288 /* skip repeating / */
289 if ((p + 1 < e) && (p[1] == '/')) {
290 p++;
291 continue;
292 }
293
294 /* /./ or /../ */
295 if ((p + 1 < e) && (p[1] == '.')) {
296 /* skip /./ */
297 if ((p + 2 >= e) || (p[2] == '/')) {
298 p += 2;
299 continue;
300 }
301
302 /* collapse /x/../ */
303 if ((p + 2 < e) && (p[2] == '.') && ((p + 3 >= e) || (p[3] == '/'))) {
304 while ((cp > canonpath) && (*--cp != '/'))
305 ;
306
307 p += 3;
308 continue;
309 }
310 }
311
312 next:
313 *cp++ = *p++;
314 }
315
316 /* remove trailing slash if not root / */
317 if ((cp > canonpath + 1) && (cp[-1] == '/'))
318 cp--;
319 else if (cp == canonpath)
320 *cp++ = '/';
321
322 *cp = '\0';
323
324 return canonpath;
325 }
326
327 static int
328 response(bool success, const char *message)
329 {
330 char *chksum;
331 struct stat s;
332
333 printf("Status: 200 OK\r\n");
334 printf("Content-Type: text/plain\r\n\r\n{\n");
335
336 if (success)
337 {
338 if (!stat(st.filename, &s))
339 printf("\t\"size\": %u,\n", (unsigned int)s.st_size);
340 else
341 printf("\t\"size\": null,\n");
342
343 chksum = checksum("md5sum", 32, st.filename);
344 printf("\t\"checksum\": %s%s%s,\n",
345 chksum ? "\"" : "",
346 chksum ? chksum : "null",
347 chksum ? "\"" : "");
348
349 chksum = checksum("sha256sum", 64, st.filename);
350 printf("\t\"sha256sum\": %s%s%s\n",
351 chksum ? "\"" : "",
352 chksum ? chksum : "null",
353 chksum ? "\"" : "");
354 }
355 else
356 {
357 if (message)
358 printf("\t\"message\": \"%s\",\n", message);
359
360 printf("\t\"failure\": [ %u, \"%s\" ]\n", errno, strerror(errno));
361
362 if (st.filefd > -1)
363 unlink(st.filename);
364 }
365
366 printf("}\n");
367
368 return -1;
369 }
370
371 static int
372 failure(int e, const char *message)
373 {
374 printf("Status: 500 Internal Server failure\r\n");
375 printf("Content-Type: text/plain\r\n\r\n");
376 printf("%s", message);
377
378 if (e)
379 printf(": %s", strerror(e));
380
381 return -1;
382 }
383
384 static int
385 filecopy(void)
386 {
387 int len;
388 char buf[4096];
389
390 if (!st.filedata)
391 {
392 close(st.tempfd);
393 errno = EINVAL;
394 return response(false, "No file data received");
395 }
396
397 if (lseek(st.tempfd, 0, SEEK_SET) < 0)
398 {
399 close(st.tempfd);
400 return response(false, "Failed to rewind temp file");
401 }
402
403 st.filefd = open(st.filename, O_CREAT | O_TRUNC | O_WRONLY, 0600);
404
405 if (st.filefd < 0)
406 {
407 close(st.tempfd);
408 return response(false, "Failed to open target file");
409 }
410
411 while ((len = read(st.tempfd, buf, sizeof(buf))) > 0)
412 {
413 if (write(st.filefd, buf, len) != len)
414 {
415 close(st.tempfd);
416 close(st.filefd);
417 return response(false, "I/O failure while writing target file");
418 }
419 }
420
421 close(st.tempfd);
422 close(st.filefd);
423
424 if (chmod(st.filename, st.filemode))
425 return response(false, "Failed to chmod target file");
426
427 return 0;
428 }
429
430 static int
431 header_field(multipart_parser *p, const char *data, size_t len)
432 {
433 st.is_content_disposition = !strncasecmp(data, "Content-Disposition", len);
434 return 0;
435 }
436
437 static int
438 header_value(multipart_parser *p, const char *data, size_t len)
439 {
440 int i, j;
441
442 if (!st.is_content_disposition)
443 return 0;
444
445 if (len < 10 || strncasecmp(data, "form-data", 9))
446 return 0;
447
448 for (data += 9, len -= 9; *data == ' ' || *data == ';'; data++, len--);
449
450 if (len < 8 || strncasecmp(data, "name=\"", 6))
451 return 0;
452
453 for (data += 6, len -= 6, i = 0; i <= len; i++)
454 {
455 if (*(data + i) != '"')
456 continue;
457
458 for (j = 1; j < sizeof(parts) / sizeof(parts[0]); j++)
459 if (!strncmp(data, parts[j], i))
460 st.parttype = j;
461
462 break;
463 }
464
465 return 0;
466 }
467
468 static int
469 data_begin_cb(multipart_parser *p)
470 {
471 char tmpname[24] = "/tmp/luci-upload.XXXXXX";
472
473 if (st.parttype == PART_FILEDATA)
474 {
475 if (!st.sessionid)
476 return response(false, "File data without session");
477
478 if (!st.filename)
479 return response(false, "File data without name");
480
481 if (!session_access(st.sessionid, "file", st.filename, "write"))
482 return response(false, "Access to path denied by ACL");
483
484 st.tempfd = mkstemp(tmpname);
485
486 if (st.tempfd < 0)
487 return response(false, "Failed to create temporary file");
488
489 unlink(tmpname);
490 }
491
492 return 0;
493 }
494
495 static int
496 data_cb(multipart_parser *p, const char *data, size_t len)
497 {
498 switch (st.parttype)
499 {
500 case PART_SESSIONID:
501 st.sessionid = datadup(data, len);
502 break;
503
504 case PART_FILENAME:
505 st.filename = canonicalize_path(data, len);
506 break;
507
508 case PART_FILEMODE:
509 st.filemode = strtoul(data, NULL, 8);
510 break;
511
512 case PART_FILEDATA:
513 if (write(st.tempfd, data, len) != len)
514 {
515 close(st.tempfd);
516 return response(false, "I/O failure while writing temporary file");
517 }
518
519 if (!st.filedata)
520 st.filedata = !!len;
521
522 break;
523
524 default:
525 break;
526 }
527
528 return 0;
529 }
530
531 static int
532 data_end_cb(multipart_parser *p)
533 {
534 if (st.parttype == PART_SESSIONID)
535 {
536 if (!session_access(st.sessionid, "cgi-io", "upload", "write"))
537 {
538 errno = EPERM;
539 return response(false, "Upload permission denied");
540 }
541 }
542 else if (st.parttype == PART_FILEDATA)
543 {
544 if (st.tempfd < 0)
545 return response(false, "Internal program failure");
546
547 #if 0
548 /* prepare directory */
549 for (ptr = st.filename; *ptr; ptr++)
550 {
551 if (*ptr == '/')
552 {
553 *ptr = 0;
554
555 if (mkdir(st.filename, 0755))
556 {
557 unlink(st.tmpname);
558 return response(false, "Failed to create destination directory");
559 }
560
561 *ptr = '/';
562 }
563 }
564 #endif
565
566 if (filecopy())
567 return -1;
568
569 return response(true, NULL);
570 }
571
572 st.parttype = PART_UNKNOWN;
573 return 0;
574 }
575
576 static multipart_parser *
577 init_parser(void)
578 {
579 char *boundary;
580 const char *var;
581
582 multipart_parser *p;
583 static multipart_parser_settings s = {
584 .on_part_data = data_cb,
585 .on_headers_complete = data_begin_cb,
586 .on_part_data_end = data_end_cb,
587 .on_header_field = header_field,
588 .on_header_value = header_value
589 };
590
591 var = getenv("CONTENT_TYPE");
592
593 if (!var || strncmp(var, "multipart/form-data;", 20))
594 return NULL;
595
596 for (var += 20; *var && *var != '='; var++);
597
598 if (*var++ != '=')
599 return NULL;
600
601 boundary = malloc(strlen(var) + 3);
602
603 if (!boundary)
604 return NULL;
605
606 strcpy(boundary, "--");
607 strcpy(boundary + 2, var);
608
609 st.tempfd = -1;
610 st.filefd = -1;
611 st.filemode = 0600;
612
613 p = multipart_parser_init(boundary, &s);
614
615 free(boundary);
616
617 return p;
618 }
619
620 static int
621 main_upload(int argc, char *argv[])
622 {
623 int rem, len;
624 char buf[4096];
625 multipart_parser *p;
626
627 p = init_parser();
628
629 if (!p)
630 {
631 errno = EINVAL;
632 return response(false, "Invalid request");
633 }
634
635 while ((len = read(0, buf, sizeof(buf))) > 0)
636 {
637 rem = multipart_parser_execute(p, buf, len);
638
639 if (rem < len)
640 break;
641 }
642
643 multipart_parser_free(p);
644
645 /* read remaining post data */
646 while ((len = read(0, buf, sizeof(buf))) > 0);
647
648 return 0;
649 }
650
651 static int
652 main_download(int argc, char **argv)
653 {
654 char *fields[] = { "sessionid", NULL, "path", NULL, "filename", NULL, "mimetype", NULL };
655 unsigned long long size = 0;
656 char *p, buf[4096];
657 ssize_t len = 0;
658 struct stat s;
659 int rfd;
660
661 postdecode(fields, 4);
662
663 if (!fields[1] || !session_access(fields[1], "cgi-io", "download", "read"))
664 return failure(0, "Download permission denied");
665
666 if (!fields[3] || !session_access(fields[1], "file", fields[3], "read"))
667 return failure(0, "Access to path denied by ACL");
668
669 if (stat(fields[3], &s))
670 return failure(errno, "Failed to stat requested path");
671
672 if (!S_ISREG(s.st_mode) && !S_ISBLK(s.st_mode))
673 return failure(0, "Requested path is not a regular file or block device");
674
675 for (p = fields[5]; p && *p; p++)
676 if (!isalnum(*p) && !strchr(" ()<>@,;:[]?.=%", *p))
677 return failure(0, "Invalid characters in filename");
678
679 for (p = fields[7]; p && *p; p++)
680 if (!isalnum(*p) && !strchr(" .;=/-", *p))
681 return failure(0, "Invalid characters in mimetype");
682
683 rfd = open(fields[3], O_RDONLY);
684
685 if (rfd < 0)
686 return failure(errno, "Failed to open requested path");
687
688 if (S_ISBLK(s.st_mode))
689 ioctl(rfd, BLKGETSIZE64, &size);
690 else
691 size = (unsigned long long)s.st_size;
692
693 printf("Status: 200 OK\r\n");
694 printf("Content-Type: %s\r\n", fields[7] ? fields[7] : "application/octet-stream");
695
696 if (fields[5])
697 printf("Content-Disposition: attachment; filename=\"%s\"\r\n", fields[5]);
698
699 printf("Content-Length: %llu\r\n\r\n", size);
700 fflush(stdout);
701
702 while (size > 0) {
703 len = sendfile(1, rfd, NULL, size);
704
705 if (len == -1) {
706 if (errno == ENOSYS || errno == EINVAL) {
707 while ((len = read(rfd, buf, sizeof(buf))) > 0)
708 fwrite(buf, len, 1, stdout);
709
710 fflush(stdout);
711 break;
712 }
713
714 if (errno == EINTR || errno == EAGAIN)
715 continue;
716 }
717
718 if (len <= 0)
719 break;
720
721 size -= len;
722 }
723
724 close(rfd);
725
726 return 0;
727 }
728
729 static int
730 main_backup(int argc, char **argv)
731 {
732 pid_t pid;
733 time_t now;
734 int len;
735 int status;
736 int fds[2];
737 char buf[4096];
738 char datestr[16] = { 0 };
739 char hostname[64] = { 0 };
740 char *fields[] = { "sessionid", NULL };
741
742 if (!postdecode(fields, 1) || !session_access(fields[1], "cgi-io", "backup", "read"))
743 return failure(0, "Backup permission denied");
744
745 if (pipe(fds))
746 return failure(errno, "Failed to spawn pipe");
747
748 switch ((pid = fork()))
749 {
750 case -1:
751 return failure(errno, "Failed to fork process");
752
753 case 0:
754 dup2(fds[1], 1);
755
756 close(0);
757 close(2);
758 close(fds[0]);
759 close(fds[1]);
760
761 chdir("/");
762
763 execl("/sbin/sysupgrade", "/sbin/sysupgrade",
764 "--create-backup", "-", NULL);
765
766 return -1;
767
768 default:
769 fcntl(fds[0], F_SETFL, fcntl(fds[0], F_GETFL) | O_NONBLOCK);
770 now = time(NULL);
771 strftime(datestr, sizeof(datestr) - 1, "%Y-%m-%d", localtime(&now));
772
773 if (gethostname(hostname, sizeof(hostname) - 1))
774 sprintf(hostname, "OpenWrt");
775
776 printf("Status: 200 OK\r\n");
777 printf("Content-Type: application/x-targz\r\n");
778 printf("Content-Disposition: attachment; "
779 "filename=\"backup-%s-%s.tar.gz\"\r\n\r\n", hostname, datestr);
780
781 do {
782 waitpid(pid, &status, 0);
783
784 while ((len = read(fds[0], buf, sizeof(buf))) > 0) {
785 fwrite(buf, len, 1, stdout);
786 fflush(stdout);
787 }
788
789 } while (!WIFEXITED(status));
790
791 close(fds[0]);
792 close(fds[1]);
793
794 return 0;
795 }
796 }
797
798 int main(int argc, char **argv)
799 {
800 if (strstr(argv[0], "cgi-upload"))
801 return main_upload(argc, argv);
802 else if (strstr(argv[0], "cgi-download"))
803 return main_download(argc, argv);
804 else if (strstr(argv[0], "cgi-backup"))
805 return main_backup(argc, argv);
806
807 return -1;
808 }