2 * cgi-io - LuCI non-RPC helper
4 * Copyright (C) 2013 Jo-Philipp Wich <jo@mein.io>
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.
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.
29 #include <sys/sendfile.h>
30 #include <sys/ioctl.h>
34 #include <libubox/blobmsg.h>
36 #include "multipart_parser.h"
47 const char *parts
[] = {
57 bool is_content_disposition
;
72 static const struct blobmsg_policy ses_policy
[__SES_MAX
] = {
73 [SES_ACCESS
] = { .name
= "access", .type
= BLOBMSG_TYPE_BOOL
},
77 static struct state st
;
80 session_access_cb(struct ubus_request
*req
, int type
, struct blob_attr
*msg
)
82 struct blob_attr
*tb
[__SES_MAX
];
83 bool *allow
= (bool *)req
->priv
;
88 blobmsg_parse(ses_policy
, __SES_MAX
, tb
, blob_data(msg
), blob_len(msg
));
91 *allow
= blobmsg_get_bool(tb
[SES_ACCESS
]);
95 session_access(const char *sid
, const char *scope
, const char *obj
, const char *func
)
99 struct ubus_context
*ctx
;
100 static struct blob_buf req
;
102 ctx
= ubus_connect(NULL
);
104 if (!ctx
|| ubus_lookup_id(ctx
, "session", &id
))
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
);
113 ubus_invoke(ctx
, id
, "access", req
.head
, session_access_cb
, &allow
, 500);
123 checksum(const char *applet
, size_t sumlen
, const char *file
)
127 static char chksum
[65];
132 switch ((pid
= fork()))
147 if (execl("/bin/busybox", "/bin/busybox", applet
, file
, NULL
))
153 memset(chksum
, 0, sizeof(chksum
));
154 read(fds
[0], chksum
, sumlen
);
155 waitpid(pid
, NULL
, 0);
164 datadup(const void *in
, size_t len
)
166 char *out
= malloc(len
+ 1);
171 memcpy(out
, in
, len
);
187 (((x) <= '9') ? ((x) - '0') : \
188 (((x) <= 'F') ? ((x) - 'A' + 10) : \
191 for (c
= p
= buf
; *p
; c
++)
195 if (!isxdigit(*(p
+ 1)) || !isxdigit(*(p
+ 2)))
198 *c
= (char)(16 * hex(*(p
+ 1)) + hex(*(p
+ 2)));
219 postdecode(char **fields
, int n_fields
)
223 static char buf
[1024];
224 int i
, len
, field
, found
= 0;
226 var
= getenv("CONTENT_TYPE");
228 if (!var
|| strncmp(var
, "application/x-www-form-urlencoded", 33))
231 memset(buf
, 0, sizeof(buf
));
233 if ((len
= read(0, buf
, sizeof(buf
) - 1)) > 0)
235 for (p
= buf
, i
= 0; i
<= len
; i
++)
241 for (field
= 0; field
< (n_fields
* 2); field
+= 2)
243 if (!strcmp(p
, fields
[field
]))
245 fields
[field
+ 1] = buf
+ i
+ 1;
250 else if (buf
[i
] == '&' || buf
[i
] == '\0')
254 if (found
>= n_fields
)
262 for (field
= 0; field
< (n_fields
* 2); field
+= 2)
263 if (!urldecode(fields
[field
+ 1]))
266 return (found
>= n_fields
);
270 canonicalize_path(const char *path
, size_t len
)
272 char *canonpath
, *cp
;
275 if (path
== NULL
|| *path
== '\0')
278 canonpath
= datadup(path
, len
);
280 if (canonpath
== NULL
)
284 for (cp
= canonpath
, p
= path
, e
= path
+ len
; p
< e
; ) {
288 /* skip repeating / */
289 if ((p
+ 1 < e
) && (p
[1] == '/')) {
295 if ((p
+ 1 < e
) && (p
[1] == '.')) {
297 if ((p
+ 2 >= e
) || (p
[2] == '/')) {
302 /* collapse /x/../ */
303 if ((p
+ 2 < e
) && (p
[2] == '.') && ((p
+ 3 >= e
) || (p
[3] == '/'))) {
304 while ((cp
> canonpath
) && (*--cp
!= '/'))
316 /* remove trailing slash if not root / */
317 if ((cp
> canonpath
+ 1) && (cp
[-1] == '/'))
319 else if (cp
== canonpath
)
328 response(bool success
, const char *message
)
333 printf("Status: 200 OK\r\n");
334 printf("Content-Type: text/plain\r\n\r\n{\n");
338 if (!stat(st
.filename
, &s
))
339 printf("\t\"size\": %u,\n", (unsigned int)s
.st_size
);
341 printf("\t\"size\": null,\n");
343 chksum
= checksum("md5sum", 32, st
.filename
);
344 printf("\t\"checksum\": %s%s%s,\n",
346 chksum
? chksum
: "null",
349 chksum
= checksum("sha256sum", 64, st
.filename
);
350 printf("\t\"sha256sum\": %s%s%s\n",
352 chksum
? chksum
: "null",
358 printf("\t\"message\": \"%s\",\n", message
);
360 printf("\t\"failure\": [ %u, \"%s\" ]\n", errno
, strerror(errno
));
372 failure(int e
, const char *message
)
374 printf("Status: 500 Internal Server failure\r\n");
375 printf("Content-Type: text/plain\r\n\r\n");
376 printf("%s", message
);
379 printf(": %s", strerror(e
));
394 return response(false, "No file data received");
397 if (lseek(st
.tempfd
, 0, SEEK_SET
) < 0)
400 return response(false, "Failed to rewind temp file");
403 st
.filefd
= open(st
.filename
, O_CREAT
| O_TRUNC
| O_WRONLY
, 0600);
408 return response(false, "Failed to open target file");
411 while ((len
= read(st
.tempfd
, buf
, sizeof(buf
))) > 0)
413 if (write(st
.filefd
, buf
, len
) != len
)
417 return response(false, "I/O failure while writing target file");
424 if (chmod(st
.filename
, st
.filemode
))
425 return response(false, "Failed to chmod target file");
431 header_field(multipart_parser
*p
, const char *data
, size_t len
)
433 st
.is_content_disposition
= !strncasecmp(data
, "Content-Disposition", len
);
438 header_value(multipart_parser
*p
, const char *data
, size_t len
)
442 if (!st
.is_content_disposition
)
445 if (len
< 10 || strncasecmp(data
, "form-data", 9))
448 for (data
+= 9, len
-= 9; *data
== ' ' || *data
== ';'; data
++, len
--);
450 if (len
< 8 || strncasecmp(data
, "name=\"", 6))
453 for (data
+= 6, len
-= 6, i
= 0; i
<= len
; i
++)
455 if (*(data
+ i
) != '"')
458 for (j
= 1; j
< sizeof(parts
) / sizeof(parts
[0]); j
++)
459 if (!strncmp(data
, parts
[j
], i
))
469 data_begin_cb(multipart_parser
*p
)
471 char tmpname
[24] = "/tmp/luci-upload.XXXXXX";
473 if (st
.parttype
== PART_FILEDATA
)
476 return response(false, "File data without session");
479 return response(false, "File data without name");
481 if (!session_access(st
.sessionid
, "file", st
.filename
, "write"))
482 return response(false, "Access to path denied by ACL");
484 st
.tempfd
= mkstemp(tmpname
);
487 return response(false, "Failed to create temporary file");
496 data_cb(multipart_parser
*p
, const char *data
, size_t len
)
501 st
.sessionid
= datadup(data
, len
);
505 st
.filename
= canonicalize_path(data
, len
);
509 st
.filemode
= strtoul(data
, NULL
, 8);
513 if (write(st
.tempfd
, data
, len
) != len
)
516 return response(false, "I/O failure while writing temporary file");
532 data_end_cb(multipart_parser
*p
)
534 if (st
.parttype
== PART_SESSIONID
)
536 if (!session_access(st
.sessionid
, "cgi-io", "upload", "write"))
539 return response(false, "Upload permission denied");
542 else if (st
.parttype
== PART_FILEDATA
)
545 return response(false, "Internal program failure");
548 /* prepare directory */
549 for (ptr
= st
.filename
; *ptr
; ptr
++)
555 if (mkdir(st
.filename
, 0755))
558 return response(false, "Failed to create destination directory");
569 return response(true, NULL
);
572 st
.parttype
= PART_UNKNOWN
;
576 static multipart_parser
*
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
591 var
= getenv("CONTENT_TYPE");
593 if (!var
|| strncmp(var
, "multipart/form-data;", 20))
596 for (var
+= 20; *var
&& *var
!= '='; var
++);
601 boundary
= malloc(strlen(var
) + 3);
606 strcpy(boundary
, "--");
607 strcpy(boundary
+ 2, var
);
613 p
= multipart_parser_init(boundary
, &s
);
621 main_upload(int argc
, char *argv
[])
632 return response(false, "Invalid request");
635 while ((len
= read(0, buf
, sizeof(buf
))) > 0)
637 rem
= multipart_parser_execute(p
, buf
, len
);
643 multipart_parser_free(p
);
645 /* read remaining post data */
646 while ((len
= read(0, buf
, sizeof(buf
))) > 0);
652 main_download(int argc
, char **argv
)
654 char *fields
[] = { "sessionid", NULL
, "path", NULL
, "filename", NULL
, "mimetype", NULL
};
655 unsigned long long size
= 0;
661 postdecode(fields
, 4);
663 if (!fields
[1] || !session_access(fields
[1], "cgi-io", "download", "read"))
664 return failure(0, "Download permission denied");
666 if (!fields
[3] || !session_access(fields
[1], "file", fields
[3], "read"))
667 return failure(0, "Access to path denied by ACL");
669 if (stat(fields
[3], &s
))
670 return failure(errno
, "Failed to stat requested path");
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");
675 for (p
= fields
[5]; p
&& *p
; p
++)
676 if (!isalnum(*p
) && !strchr(" ()<>@,;:[]?.=%", *p
))
677 return failure(0, "Invalid characters in filename");
679 for (p
= fields
[7]; p
&& *p
; p
++)
680 if (!isalnum(*p
) && !strchr(" .;=/-", *p
))
681 return failure(0, "Invalid characters in mimetype");
683 rfd
= open(fields
[3], O_RDONLY
);
686 return failure(errno
, "Failed to open requested path");
688 if (S_ISBLK(s
.st_mode
))
689 ioctl(rfd
, BLKGETSIZE64
, &size
);
691 size
= (unsigned long long)s
.st_size
;
693 printf("Status: 200 OK\r\n");
694 printf("Content-Type: %s\r\n", fields
[7] ? fields
[7] : "application/octet-stream");
697 printf("Content-Disposition: attachment; filename=\"%s\"\r\n", fields
[5]);
699 printf("Content-Length: %llu\r\n\r\n", size
);
703 len
= sendfile(1, rfd
, NULL
, size
);
706 if (errno
== ENOSYS
|| errno
== EINVAL
) {
707 while ((len
= read(rfd
, buf
, sizeof(buf
))) > 0)
708 fwrite(buf
, len
, 1, stdout
);
714 if (errno
== EINTR
|| errno
== EAGAIN
)
730 main_backup(int argc
, char **argv
)
738 char datestr
[16] = { 0 };
739 char hostname
[64] = { 0 };
740 char *fields
[] = { "sessionid", NULL
};
742 if (!postdecode(fields
, 1) || !session_access(fields
[1], "cgi-io", "backup", "read"))
743 return failure(0, "Backup permission denied");
746 return failure(errno
, "Failed to spawn pipe");
748 switch ((pid
= fork()))
751 return failure(errno
, "Failed to fork process");
763 execl("/sbin/sysupgrade", "/sbin/sysupgrade",
764 "--create-backup", "-", NULL
);
769 fcntl(fds
[0], F_SETFL
, fcntl(fds
[0], F_GETFL
) | O_NONBLOCK
);
771 strftime(datestr
, sizeof(datestr
) - 1, "%Y-%m-%d", localtime(&now
));
773 if (gethostname(hostname
, sizeof(hostname
) - 1))
774 sprintf(hostname
, "OpenWrt");
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
);
782 waitpid(pid
, &status
, 0);
784 while ((len
= read(fds
[0], buf
, sizeof(buf
))) > 0) {
785 fwrite(buf
, len
, 1, stdout
);
789 } while (!WIFEXITED(status
));
798 int main(int argc
, char **argv
)
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
);