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"
40 #define READ_BLOCK 4096
50 const char *parts
[] = {
60 bool is_content_disposition
;
75 static const struct blobmsg_policy ses_policy
[__SES_MAX
] = {
76 [SES_ACCESS
] = { .name
= "access", .type
= BLOBMSG_TYPE_BOOL
},
80 static struct state st
;
83 session_access_cb(struct ubus_request
*req
, int type
, struct blob_attr
*msg
)
85 struct blob_attr
*tb
[__SES_MAX
];
86 bool *allow
= (bool *)req
->priv
;
91 blobmsg_parse(ses_policy
, __SES_MAX
, tb
, blob_data(msg
), blob_len(msg
));
94 *allow
= blobmsg_get_bool(tb
[SES_ACCESS
]);
98 session_access(const char *sid
, const char *scope
, const char *obj
, const char *func
)
102 struct ubus_context
*ctx
;
103 static struct blob_buf req
;
105 ctx
= ubus_connect(NULL
);
107 if (!ctx
|| ubus_lookup_id(ctx
, "session", &id
))
110 blob_buf_init(&req
, 0);
111 blobmsg_add_string(&req
, "ubus_rpc_session", sid
);
112 blobmsg_add_string(&req
, "scope", scope
);
113 blobmsg_add_string(&req
, "object", obj
);
114 blobmsg_add_string(&req
, "function", func
);
116 ubus_invoke(ctx
, id
, "access", req
.head
, session_access_cb
, &allow
, 500);
126 checksum(const char *applet
, size_t sumlen
, const char *file
)
131 static char chksum
[65];
136 switch ((pid
= fork()))
151 if (execl("/bin/busybox", "/bin/busybox", applet
, file
, NULL
))
157 memset(chksum
, 0, sizeof(chksum
));
158 r
= read(fds
[0], chksum
, sumlen
);
160 waitpid(pid
, NULL
, 0);
172 datadup(const void *in
, size_t len
)
174 char *out
= malloc(len
+ 1);
179 memcpy(out
, in
, len
);
195 (((x) <= '9') ? ((x) - '0') : \
196 (((x) <= 'F') ? ((x) - 'A' + 10) : \
199 for (c
= p
= buf
; *p
; c
++)
203 if (!isxdigit(*(p
+ 1)) || !isxdigit(*(p
+ 2)))
206 *c
= (char)(16 * hex(*(p
+ 1)) + hex(*(p
+ 2)));
227 postdecode(char **fields
, int n_fields
)
231 static char buf
[1024];
232 int i
, len
, field
, found
= 0;
234 var
= getenv("CONTENT_TYPE");
236 if (!var
|| strncmp(var
, "application/x-www-form-urlencoded", 33))
239 memset(buf
, 0, sizeof(buf
));
241 if ((len
= read(0, buf
, sizeof(buf
) - 1)) > 0)
243 for (p
= buf
, i
= 0; i
<= len
; i
++)
249 for (field
= 0; field
< (n_fields
* 2); field
+= 2)
251 if (!strcmp(p
, fields
[field
]))
253 fields
[field
+ 1] = buf
+ i
+ 1;
258 else if (buf
[i
] == '&' || buf
[i
] == '\0')
262 if (found
>= n_fields
)
270 for (field
= 0; field
< (n_fields
* 2); field
+= 2)
271 if (!urldecode(fields
[field
+ 1]))
274 return (found
>= n_fields
);
278 canonicalize_path(const char *path
, size_t len
)
280 char *canonpath
, *cp
;
283 if (path
== NULL
|| *path
== '\0')
286 canonpath
= datadup(path
, len
);
288 if (canonpath
== NULL
)
292 for (cp
= canonpath
, p
= path
, e
= path
+ len
; p
< e
; ) {
296 /* skip repeating / */
297 if ((p
+ 1 < e
) && (p
[1] == '/')) {
303 if ((p
+ 1 < e
) && (p
[1] == '.')) {
305 if ((p
+ 2 >= e
) || (p
[2] == '/')) {
310 /* collapse /x/../ */
311 if ((p
+ 2 < e
) && (p
[2] == '.') && ((p
+ 3 >= e
) || (p
[3] == '/'))) {
312 while ((cp
> canonpath
) && (*--cp
!= '/'))
324 /* remove trailing slash if not root / */
325 if ((cp
> canonpath
+ 1) && (cp
[-1] == '/'))
327 else if (cp
== canonpath
)
336 response(bool success
, const char *message
)
341 printf("Status: 200 OK\r\n");
342 printf("Content-Type: text/plain\r\n\r\n{\n");
346 if (!stat(st
.filename
, &s
))
347 printf("\t\"size\": %u,\n", (unsigned int)s
.st_size
);
349 printf("\t\"size\": null,\n");
351 chksum
= checksum("md5sum", 32, st
.filename
);
352 printf("\t\"checksum\": %s%s%s,\n",
354 chksum
? chksum
: "null",
357 chksum
= checksum("sha256sum", 64, st
.filename
);
358 printf("\t\"sha256sum\": %s%s%s\n",
360 chksum
? chksum
: "null",
366 printf("\t\"message\": \"%s\",\n", message
);
368 printf("\t\"failure\": [ %u, \"%s\" ]\n", errno
, strerror(errno
));
380 failure(int code
, int e
, const char *message
)
382 printf("Status: %d %s\r\n", code
, message
);
383 printf("Content-Type: text/plain\r\n\r\n");
384 printf("%s", message
);
387 printf(": %s", strerror(e
));
398 char buf
[READ_BLOCK
];
404 return response(false, "No file data received");
407 if (lseek(st
.tempfd
, 0, SEEK_SET
) < 0)
410 return response(false, "Failed to rewind temp file");
413 st
.filefd
= open(st
.filename
, O_CREAT
| O_TRUNC
| O_WRONLY
, 0600);
418 return response(false, "Failed to open target file");
421 while ((len
= read(st
.tempfd
, buf
, sizeof(buf
))) > 0)
423 if (write(st
.filefd
, buf
, len
) != len
)
427 return response(false, "I/O failure while writing target file");
434 if (chmod(st
.filename
, st
.filemode
))
435 return response(false, "Failed to chmod target file");
441 header_field(multipart_parser
*p
, const char *data
, size_t len
)
443 st
.is_content_disposition
= !strncasecmp(data
, "Content-Disposition", len
);
448 header_value(multipart_parser
*p
, const char *data
, size_t len
)
452 if (!st
.is_content_disposition
)
455 if (len
< 10 || strncasecmp(data
, "form-data", 9))
458 for (data
+= 9, len
-= 9; *data
== ' ' || *data
== ';'; data
++, len
--);
460 if (len
< 8 || strncasecmp(data
, "name=\"", 6))
463 for (data
+= 6, len
-= 6, i
= 0; i
<= len
; i
++)
465 if (*(data
+ i
) != '"')
468 for (j
= 1; j
< sizeof(parts
) / sizeof(parts
[0]); j
++)
469 if (!strncmp(data
, parts
[j
], i
))
479 data_begin_cb(multipart_parser
*p
)
481 char tmpname
[24] = "/tmp/luci-upload.XXXXXX";
483 if (st
.parttype
== PART_FILEDATA
)
486 return response(false, "File data without session");
489 return response(false, "File data without name");
491 if (!session_access(st
.sessionid
, "file", st
.filename
, "write"))
492 return response(false, "Access to path denied by ACL");
494 st
.tempfd
= mkstemp(tmpname
);
497 return response(false, "Failed to create temporary file");
506 data_cb(multipart_parser
*p
, const char *data
, size_t len
)
513 st
.sessionid
= datadup(data
, len
);
517 st
.filename
= canonicalize_path(data
, len
);
521 st
.filemode
= strtoul(data
, NULL
, 8);
525 if (write(st
.tempfd
, data
, len
) != wlen
)
528 return response(false, "I/O failure while writing temporary file");
532 st
.filedata
= !!wlen
;
544 data_end_cb(multipart_parser
*p
)
546 if (st
.parttype
== PART_SESSIONID
)
548 if (!session_access(st
.sessionid
, "cgi-io", "upload", "write"))
551 return response(false, "Upload permission denied");
554 else if (st
.parttype
== PART_FILEDATA
)
557 return response(false, "Internal program failure");
560 /* prepare directory */
561 for (ptr
= st
.filename
; *ptr
; ptr
++)
567 if (mkdir(st
.filename
, 0755))
570 return response(false, "Failed to create destination directory");
581 return response(true, NULL
);
584 st
.parttype
= PART_UNKNOWN
;
588 static multipart_parser
*
595 static multipart_parser_settings s
= {
596 .on_part_data
= data_cb
,
597 .on_headers_complete
= data_begin_cb
,
598 .on_part_data_end
= data_end_cb
,
599 .on_header_field
= header_field
,
600 .on_header_value
= header_value
603 var
= getenv("CONTENT_TYPE");
605 if (!var
|| strncmp(var
, "multipart/form-data;", 20))
608 for (var
+= 20; *var
&& *var
!= '='; var
++);
613 boundary
= malloc(strlen(var
) + 3);
618 strcpy(boundary
, "--");
619 strcpy(boundary
+ 2, var
);
625 p
= multipart_parser_init(boundary
, &s
);
633 main_upload(int argc
, char *argv
[])
637 char buf
[READ_BLOCK
];
645 return response(false, "Invalid request");
648 while ((len
= read(0, buf
, sizeof(buf
))) > 0)
651 rem
= multipart_parser_execute(p
, buf
, len
);
656 multipart_parser_free(p
);
662 main_download(int argc
, char **argv
)
664 char *fields
[] = { "sessionid", NULL
, "path", NULL
, "filename", NULL
, "mimetype", NULL
};
665 unsigned long long size
= 0;
666 char *p
, buf
[READ_BLOCK
];
671 postdecode(fields
, 4);
673 if (!fields
[1] || !session_access(fields
[1], "cgi-io", "download", "read"))
674 return failure(403, 0, "Download permission denied");
676 if (!fields
[3] || !session_access(fields
[1], "file", fields
[3], "read"))
677 return failure(403, 0, "Access to path denied by ACL");
679 if (stat(fields
[3], &s
))
680 return failure(404, errno
, "Failed to stat requested path");
682 if (!S_ISREG(s
.st_mode
) && !S_ISBLK(s
.st_mode
))
683 return failure(403, 0, "Requested path is not a regular file or block device");
685 for (p
= fields
[5]; p
&& *p
; p
++)
686 if (!isalnum(*p
) && !strchr(" ()<>@,;:[]?.=%-", *p
))
687 return failure(400, 0, "Invalid characters in filename");
689 for (p
= fields
[7]; p
&& *p
; p
++)
690 if (!isalnum(*p
) && !strchr(" .;=/-", *p
))
691 return failure(400, 0, "Invalid characters in mimetype");
693 rfd
= open(fields
[3], O_RDONLY
);
696 return failure(500, errno
, "Failed to open requested path");
698 if (S_ISBLK(s
.st_mode
))
699 ioctl(rfd
, BLKGETSIZE64
, &size
);
701 size
= (unsigned long long)s
.st_size
;
703 printf("Status: 200 OK\r\n");
704 printf("Content-Type: %s\r\n", fields
[7] ? fields
[7] : "application/octet-stream");
707 printf("Content-Disposition: attachment; filename=\"%s\"\r\n", fields
[5]);
709 printf("Content-Length: %llu\r\n\r\n", size
);
713 len
= sendfile(1, rfd
, NULL
, size
);
716 if (errno
== ENOSYS
|| errno
== EINVAL
) {
717 while ((len
= read(rfd
, buf
, sizeof(buf
))) > 0)
718 fwrite(buf
, len
, 1, stdout
);
724 if (errno
== EINTR
|| errno
== EAGAIN
)
740 main_backup(int argc
, char **argv
)
748 char datestr
[16] = { 0 };
749 char hostname
[64] = { 0 };
750 char *fields
[] = { "sessionid", NULL
};
752 if (!postdecode(fields
, 1) || !session_access(fields
[1], "cgi-io", "backup", "read"))
753 return failure(403, 0, "Backup permission denied");
756 return failure(500, errno
, "Failed to spawn pipe");
758 switch ((pid
= fork()))
761 return failure(500, errno
, "Failed to fork process");
773 return failure(500, errno
, "Failed chdir('/')");
775 execl("/sbin/sysupgrade", "/sbin/sysupgrade",
776 "--create-backup", "-", NULL
);
782 strftime(datestr
, sizeof(datestr
) - 1, "%Y-%m-%d", localtime(&now
));
784 if (gethostname(hostname
, sizeof(hostname
) - 1))
785 sprintf(hostname
, "OpenWrt");
787 printf("Status: 200 OK\r\n");
788 printf("Content-Type: application/x-targz\r\n");
789 printf("Content-Disposition: attachment; "
790 "filename=\"backup-%s-%s.tar.gz\"\r\n\r\n", hostname
, datestr
);
795 len
= splice(fds
[0], NULL
, 1, NULL
, READ_BLOCK
, SPLICE_F_MORE
);
798 waitpid(pid
, &status
, 0);
807 int main(int argc
, char **argv
)
809 if (strstr(argv
[0], "cgi-upload"))
810 return main_upload(argc
, argv
);
811 else if (strstr(argv
[0], "cgi-download"))
812 return main_download(argc
, argv
);
813 else if (strstr(argv
[0], "cgi-backup"))
814 return main_backup(argc
, argv
);