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.
19 #define _GNU_SOURCE /* splice(), SPLICE_F_MORE */
31 #include <sys/sendfile.h>
32 #include <sys/ioctl.h>
36 #include <libubox/blobmsg.h>
38 #include "multipart_parser.h"
49 const char *parts
[] = {
59 bool is_content_disposition
;
74 static const struct blobmsg_policy ses_policy
[__SES_MAX
] = {
75 [SES_ACCESS
] = { .name
= "access", .type
= BLOBMSG_TYPE_BOOL
},
79 static struct state st
;
82 session_access_cb(struct ubus_request
*req
, int type
, struct blob_attr
*msg
)
84 struct blob_attr
*tb
[__SES_MAX
];
85 bool *allow
= (bool *)req
->priv
;
90 blobmsg_parse(ses_policy
, __SES_MAX
, tb
, blob_data(msg
), blob_len(msg
));
93 *allow
= blobmsg_get_bool(tb
[SES_ACCESS
]);
97 session_access(const char *sid
, const char *scope
, const char *obj
, const char *func
)
101 struct ubus_context
*ctx
;
102 static struct blob_buf req
;
104 ctx
= ubus_connect(NULL
);
106 if (!ctx
|| ubus_lookup_id(ctx
, "session", &id
))
109 blob_buf_init(&req
, 0);
110 blobmsg_add_string(&req
, "ubus_rpc_session", sid
);
111 blobmsg_add_string(&req
, "scope", scope
);
112 blobmsg_add_string(&req
, "object", obj
);
113 blobmsg_add_string(&req
, "function", func
);
115 ubus_invoke(ctx
, id
, "access", req
.head
, session_access_cb
, &allow
, 500);
125 checksum(const char *applet
, size_t sumlen
, const char *file
)
129 static char chksum
[65];
134 switch ((pid
= fork()))
149 if (execl("/bin/busybox", "/bin/busybox", applet
, file
, NULL
))
155 memset(chksum
, 0, sizeof(chksum
));
156 read(fds
[0], chksum
, sumlen
);
157 waitpid(pid
, NULL
, 0);
166 datadup(const void *in
, size_t len
)
168 char *out
= malloc(len
+ 1);
173 memcpy(out
, in
, len
);
189 (((x) <= '9') ? ((x) - '0') : \
190 (((x) <= 'F') ? ((x) - 'A' + 10) : \
193 for (c
= p
= buf
; *p
; c
++)
197 if (!isxdigit(*(p
+ 1)) || !isxdigit(*(p
+ 2)))
200 *c
= (char)(16 * hex(*(p
+ 1)) + hex(*(p
+ 2)));
221 postdecode(char **fields
, int n_fields
)
225 static char buf
[1024];
226 int i
, len
, field
, found
= 0;
228 var
= getenv("CONTENT_TYPE");
230 if (!var
|| strncmp(var
, "application/x-www-form-urlencoded", 33))
233 memset(buf
, 0, sizeof(buf
));
235 if ((len
= read(0, buf
, sizeof(buf
) - 1)) > 0)
237 for (p
= buf
, i
= 0; i
<= len
; i
++)
243 for (field
= 0; field
< (n_fields
* 2); field
+= 2)
245 if (!strcmp(p
, fields
[field
]))
247 fields
[field
+ 1] = buf
+ i
+ 1;
252 else if (buf
[i
] == '&' || buf
[i
] == '\0')
256 if (found
>= n_fields
)
264 for (field
= 0; field
< (n_fields
* 2); field
+= 2)
265 if (!urldecode(fields
[field
+ 1]))
268 return (found
>= n_fields
);
272 canonicalize_path(const char *path
, size_t len
)
274 char *canonpath
, *cp
;
277 if (path
== NULL
|| *path
== '\0')
280 canonpath
= datadup(path
, len
);
282 if (canonpath
== NULL
)
286 for (cp
= canonpath
, p
= path
, e
= path
+ len
; p
< e
; ) {
290 /* skip repeating / */
291 if ((p
+ 1 < e
) && (p
[1] == '/')) {
297 if ((p
+ 1 < e
) && (p
[1] == '.')) {
299 if ((p
+ 2 >= e
) || (p
[2] == '/')) {
304 /* collapse /x/../ */
305 if ((p
+ 2 < e
) && (p
[2] == '.') && ((p
+ 3 >= e
) || (p
[3] == '/'))) {
306 while ((cp
> canonpath
) && (*--cp
!= '/'))
318 /* remove trailing slash if not root / */
319 if ((cp
> canonpath
+ 1) && (cp
[-1] == '/'))
321 else if (cp
== canonpath
)
330 response(bool success
, const char *message
)
335 printf("Status: 200 OK\r\n");
336 printf("Content-Type: text/plain\r\n\r\n{\n");
340 if (!stat(st
.filename
, &s
))
341 printf("\t\"size\": %u,\n", (unsigned int)s
.st_size
);
343 printf("\t\"size\": null,\n");
345 chksum
= checksum("md5sum", 32, st
.filename
);
346 printf("\t\"checksum\": %s%s%s,\n",
348 chksum
? chksum
: "null",
351 chksum
= checksum("sha256sum", 64, st
.filename
);
352 printf("\t\"sha256sum\": %s%s%s\n",
354 chksum
? chksum
: "null",
360 printf("\t\"message\": \"%s\",\n", message
);
362 printf("\t\"failure\": [ %u, \"%s\" ]\n", errno
, strerror(errno
));
374 failure(int code
, int e
, const char *message
)
376 printf("Status: %d %s\r\n", code
, message
);
377 printf("Content-Type: text/plain\r\n\r\n");
378 printf("%s", message
);
381 printf(": %s", strerror(e
));
398 return response(false, "No file data received");
401 if (lseek(st
.tempfd
, 0, SEEK_SET
) < 0)
404 return response(false, "Failed to rewind temp file");
407 st
.filefd
= open(st
.filename
, O_CREAT
| O_TRUNC
| O_WRONLY
, 0600);
412 return response(false, "Failed to open target file");
415 while ((len
= read(st
.tempfd
, buf
, sizeof(buf
))) > 0)
417 if (write(st
.filefd
, buf
, len
) != len
)
421 return response(false, "I/O failure while writing target file");
428 if (chmod(st
.filename
, st
.filemode
))
429 return response(false, "Failed to chmod target file");
435 header_field(multipart_parser
*p
, const char *data
, size_t len
)
437 st
.is_content_disposition
= !strncasecmp(data
, "Content-Disposition", len
);
442 header_value(multipart_parser
*p
, const char *data
, size_t len
)
446 if (!st
.is_content_disposition
)
449 if (len
< 10 || strncasecmp(data
, "form-data", 9))
452 for (data
+= 9, len
-= 9; *data
== ' ' || *data
== ';'; data
++, len
--);
454 if (len
< 8 || strncasecmp(data
, "name=\"", 6))
457 for (data
+= 6, len
-= 6, i
= 0; i
<= len
; i
++)
459 if (*(data
+ i
) != '"')
462 for (j
= 1; j
< sizeof(parts
) / sizeof(parts
[0]); j
++)
463 if (!strncmp(data
, parts
[j
], i
))
473 data_begin_cb(multipart_parser
*p
)
475 char tmpname
[24] = "/tmp/luci-upload.XXXXXX";
477 if (st
.parttype
== PART_FILEDATA
)
480 return response(false, "File data without session");
483 return response(false, "File data without name");
485 if (!session_access(st
.sessionid
, "file", st
.filename
, "write"))
486 return response(false, "Access to path denied by ACL");
488 st
.tempfd
= mkstemp(tmpname
);
491 return response(false, "Failed to create temporary file");
500 data_cb(multipart_parser
*p
, const char *data
, size_t len
)
505 st
.sessionid
= datadup(data
, len
);
509 st
.filename
= canonicalize_path(data
, len
);
513 st
.filemode
= strtoul(data
, NULL
, 8);
517 if (write(st
.tempfd
, data
, len
) != len
)
520 return response(false, "I/O failure while writing temporary file");
536 data_end_cb(multipart_parser
*p
)
538 if (st
.parttype
== PART_SESSIONID
)
540 if (!session_access(st
.sessionid
, "cgi-io", "upload", "write"))
543 return response(false, "Upload permission denied");
546 else if (st
.parttype
== PART_FILEDATA
)
549 return response(false, "Internal program failure");
552 /* prepare directory */
553 for (ptr
= st
.filename
; *ptr
; ptr
++)
559 if (mkdir(st
.filename
, 0755))
562 return response(false, "Failed to create destination directory");
573 return response(true, NULL
);
576 st
.parttype
= PART_UNKNOWN
;
580 static multipart_parser
*
587 static multipart_parser_settings s
= {
588 .on_part_data
= data_cb
,
589 .on_headers_complete
= data_begin_cb
,
590 .on_part_data_end
= data_end_cb
,
591 .on_header_field
= header_field
,
592 .on_header_value
= header_value
595 var
= getenv("CONTENT_TYPE");
597 if (!var
|| strncmp(var
, "multipart/form-data;", 20))
600 for (var
+= 20; *var
&& *var
!= '='; var
++);
605 boundary
= malloc(strlen(var
) + 3);
610 strcpy(boundary
, "--");
611 strcpy(boundary
+ 2, var
);
617 p
= multipart_parser_init(boundary
, &s
);
625 main_upload(int argc
, char *argv
[])
636 return response(false, "Invalid request");
639 while ((len
= read(0, buf
, sizeof(buf
))) > 0)
641 rem
= multipart_parser_execute(p
, buf
, len
);
647 multipart_parser_free(p
);
649 /* read remaining post data */
650 while ((len
= read(0, buf
, sizeof(buf
))) > 0);
656 main_download(int argc
, char **argv
)
658 char *fields
[] = { "sessionid", NULL
, "path", NULL
, "filename", NULL
, "mimetype", NULL
};
659 unsigned long long size
= 0;
665 postdecode(fields
, 4);
667 if (!fields
[1] || !session_access(fields
[1], "cgi-io", "download", "read"))
668 return failure(403, 0, "Download permission denied");
670 if (!fields
[3] || !session_access(fields
[1], "file", fields
[3], "read"))
671 return failure(403, 0, "Access to path denied by ACL");
673 if (stat(fields
[3], &s
))
674 return failure(404, errno
, "Failed to stat requested path");
676 if (!S_ISREG(s
.st_mode
) && !S_ISBLK(s
.st_mode
))
677 return failure(403, 0, "Requested path is not a regular file or block device");
679 for (p
= fields
[5]; p
&& *p
; p
++)
680 if (!isalnum(*p
) && !strchr(" ()<>@,;:[]?.=%", *p
))
681 return failure(400, 0, "Invalid characters in filename");
683 for (p
= fields
[7]; p
&& *p
; p
++)
684 if (!isalnum(*p
) && !strchr(" .;=/-", *p
))
685 return failure(400, 0, "Invalid characters in mimetype");
687 rfd
= open(fields
[3], O_RDONLY
);
690 return failure(500, errno
, "Failed to open requested path");
692 if (S_ISBLK(s
.st_mode
))
693 ioctl(rfd
, BLKGETSIZE64
, &size
);
695 size
= (unsigned long long)s
.st_size
;
697 printf("Status: 200 OK\r\n");
698 printf("Content-Type: %s\r\n", fields
[7] ? fields
[7] : "application/octet-stream");
701 printf("Content-Disposition: attachment; filename=\"%s\"\r\n", fields
[5]);
703 printf("Content-Length: %llu\r\n\r\n", size
);
707 len
= sendfile(1, rfd
, NULL
, size
);
710 if (errno
== ENOSYS
|| errno
== EINVAL
) {
711 while ((len
= read(rfd
, buf
, sizeof(buf
))) > 0)
712 fwrite(buf
, len
, 1, stdout
);
718 if (errno
== EINTR
|| errno
== EAGAIN
)
734 main_backup(int argc
, char **argv
)
741 char datestr
[16] = { 0 };
742 char hostname
[64] = { 0 };
743 char *fields
[] = { "sessionid", NULL
};
745 if (!postdecode(fields
, 1) || !session_access(fields
[1], "cgi-io", "backup", "read"))
746 return failure(403, 0, "Backup permission denied");
749 return failure(500, errno
, "Failed to spawn pipe");
751 switch ((pid
= fork()))
754 return failure(500, errno
, "Failed to fork process");
766 execl("/sbin/sysupgrade", "/sbin/sysupgrade",
767 "--create-backup", "-", NULL
);
773 strftime(datestr
, sizeof(datestr
) - 1, "%Y-%m-%d", localtime(&now
));
775 if (gethostname(hostname
, sizeof(hostname
) - 1))
776 sprintf(hostname
, "OpenWrt");
778 printf("Status: 200 OK\r\n");
779 printf("Content-Type: application/x-targz\r\n");
780 printf("Content-Disposition: attachment; "
781 "filename=\"backup-%s-%s.tar.gz\"\r\n\r\n", hostname
, datestr
);
786 len
= splice(fds
[0], NULL
, 1, NULL
, 4096, SPLICE_F_MORE
);
789 waitpid(pid
, &status
, 0);
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
);