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
)
130 static char chksum
[65];
135 switch ((pid
= fork()))
150 if (execl("/bin/busybox", "/bin/busybox", applet
, file
, NULL
))
156 memset(chksum
, 0, sizeof(chksum
));
157 read(fds
[0], chksum
, sumlen
);
158 waitpid(pid
, NULL
, 0);
167 datadup(const void *in
, size_t len
)
169 char *out
= malloc(len
+ 1);
174 memcpy(out
, in
, len
);
190 (((x) <= '9') ? ((x) - '0') : \
191 (((x) <= 'F') ? ((x) - 'A' + 10) : \
194 for (c
= p
= buf
; *p
; c
++)
198 if (!isxdigit(*(p
+ 1)) || !isxdigit(*(p
+ 2)))
201 *c
= (char)(16 * hex(*(p
+ 1)) + hex(*(p
+ 2)));
222 postdecode(char **fields
, int n_fields
)
226 static char buf
[1024];
227 int i
, len
, field
, found
= 0;
229 var
= getenv("CONTENT_TYPE");
231 if (!var
|| strncmp(var
, "application/x-www-form-urlencoded", 33))
234 memset(buf
, 0, sizeof(buf
));
236 if ((len
= read(0, buf
, sizeof(buf
) - 1)) > 0)
238 for (p
= buf
, i
= 0; i
<= len
; i
++)
244 for (field
= 0; field
< (n_fields
* 2); field
+= 2)
246 if (!strcmp(p
, fields
[field
]))
248 fields
[field
+ 1] = buf
+ i
+ 1;
253 else if (buf
[i
] == '&' || buf
[i
] == '\0')
257 if (found
>= n_fields
)
265 for (field
= 0; field
< (n_fields
* 2); field
+= 2)
266 if (!urldecode(fields
[field
+ 1]))
269 return (found
>= n_fields
);
273 canonicalize_path(const char *path
, size_t len
)
275 char *canonpath
, *cp
;
278 if (path
== NULL
|| *path
== '\0')
281 canonpath
= datadup(path
, len
);
283 if (canonpath
== NULL
)
287 for (cp
= canonpath
, p
= path
, e
= path
+ len
; p
< e
; ) {
291 /* skip repeating / */
292 if ((p
+ 1 < e
) && (p
[1] == '/')) {
298 if ((p
+ 1 < e
) && (p
[1] == '.')) {
300 if ((p
+ 2 >= e
) || (p
[2] == '/')) {
305 /* collapse /x/../ */
306 if ((p
+ 2 < e
) && (p
[2] == '.') && ((p
+ 3 >= e
) || (p
[3] == '/'))) {
307 while ((cp
> canonpath
) && (*--cp
!= '/'))
319 /* remove trailing slash if not root / */
320 if ((cp
> canonpath
+ 1) && (cp
[-1] == '/'))
322 else if (cp
== canonpath
)
331 response(bool success
, const char *message
)
336 printf("Status: 200 OK\r\n");
337 printf("Content-Type: text/plain\r\n\r\n{\n");
341 if (!stat(st
.filename
, &s
))
342 printf("\t\"size\": %u,\n", (unsigned int)s
.st_size
);
344 printf("\t\"size\": null,\n");
346 chksum
= checksum("md5sum", 32, st
.filename
);
347 printf("\t\"checksum\": %s%s%s,\n",
349 chksum
? chksum
: "null",
352 chksum
= checksum("sha256sum", 64, st
.filename
);
353 printf("\t\"sha256sum\": %s%s%s\n",
355 chksum
? chksum
: "null",
361 printf("\t\"message\": \"%s\",\n", message
);
363 printf("\t\"failure\": [ %u, \"%s\" ]\n", errno
, strerror(errno
));
375 failure(int code
, int e
, const char *message
)
377 printf("Status: %d %s\r\n", code
, message
);
378 printf("Content-Type: text/plain\r\n\r\n");
379 printf("%s", message
);
382 printf(": %s", strerror(e
));
393 char buf
[READ_BLOCK
];
399 return response(false, "No file data received");
402 if (lseek(st
.tempfd
, 0, SEEK_SET
) < 0)
405 return response(false, "Failed to rewind temp file");
408 st
.filefd
= open(st
.filename
, O_CREAT
| O_TRUNC
| O_WRONLY
, 0600);
413 return response(false, "Failed to open target file");
416 while ((len
= read(st
.tempfd
, buf
, sizeof(buf
))) > 0)
418 if (write(st
.filefd
, buf
, len
) != len
)
422 return response(false, "I/O failure while writing target file");
429 if (chmod(st
.filename
, st
.filemode
))
430 return response(false, "Failed to chmod target file");
436 header_field(multipart_parser
*p
, const char *data
, size_t len
)
438 st
.is_content_disposition
= !strncasecmp(data
, "Content-Disposition", len
);
443 header_value(multipart_parser
*p
, const char *data
, size_t len
)
447 if (!st
.is_content_disposition
)
450 if (len
< 10 || strncasecmp(data
, "form-data", 9))
453 for (data
+= 9, len
-= 9; *data
== ' ' || *data
== ';'; data
++, len
--);
455 if (len
< 8 || strncasecmp(data
, "name=\"", 6))
458 for (data
+= 6, len
-= 6, i
= 0; i
<= len
; i
++)
460 if (*(data
+ i
) != '"')
463 for (j
= 1; j
< sizeof(parts
) / sizeof(parts
[0]); j
++)
464 if (!strncmp(data
, parts
[j
], i
))
474 data_begin_cb(multipart_parser
*p
)
476 char tmpname
[24] = "/tmp/luci-upload.XXXXXX";
478 if (st
.parttype
== PART_FILEDATA
)
481 return response(false, "File data without session");
484 return response(false, "File data without name");
486 if (!session_access(st
.sessionid
, "file", st
.filename
, "write"))
487 return response(false, "Access to path denied by ACL");
489 st
.tempfd
= mkstemp(tmpname
);
492 return response(false, "Failed to create temporary file");
501 data_cb(multipart_parser
*p
, const char *data
, size_t len
)
506 st
.sessionid
= datadup(data
, len
);
510 st
.filename
= canonicalize_path(data
, len
);
514 st
.filemode
= strtoul(data
, NULL
, 8);
518 if (write(st
.tempfd
, data
, len
) != len
)
521 return response(false, "I/O failure while writing temporary file");
537 data_end_cb(multipart_parser
*p
)
539 if (st
.parttype
== PART_SESSIONID
)
541 if (!session_access(st
.sessionid
, "cgi-io", "upload", "write"))
544 return response(false, "Upload permission denied");
547 else if (st
.parttype
== PART_FILEDATA
)
550 return response(false, "Internal program failure");
553 /* prepare directory */
554 for (ptr
= st
.filename
; *ptr
; ptr
++)
560 if (mkdir(st
.filename
, 0755))
563 return response(false, "Failed to create destination directory");
574 return response(true, NULL
);
577 st
.parttype
= PART_UNKNOWN
;
581 static multipart_parser
*
588 static multipart_parser_settings s
= {
589 .on_part_data
= data_cb
,
590 .on_headers_complete
= data_begin_cb
,
591 .on_part_data_end
= data_end_cb
,
592 .on_header_field
= header_field
,
593 .on_header_value
= header_value
596 var
= getenv("CONTENT_TYPE");
598 if (!var
|| strncmp(var
, "multipart/form-data;", 20))
601 for (var
+= 20; *var
&& *var
!= '='; var
++);
606 boundary
= malloc(strlen(var
) + 3);
611 strcpy(boundary
, "--");
612 strcpy(boundary
+ 2, var
);
618 p
= multipart_parser_init(boundary
, &s
);
626 main_upload(int argc
, char *argv
[])
630 char buf
[READ_BLOCK
];
638 return response(false, "Invalid request");
641 while ((len
= read(0, buf
, sizeof(buf
))) > 0)
644 rem
= multipart_parser_execute(p
, buf
, len
);
649 multipart_parser_free(p
);
655 main_download(int argc
, char **argv
)
657 char *fields
[] = { "sessionid", NULL
, "path", NULL
, "filename", NULL
, "mimetype", NULL
};
658 unsigned long long size
= 0;
659 char *p
, buf
[READ_BLOCK
];
664 postdecode(fields
, 4);
666 if (!fields
[1] || !session_access(fields
[1], "cgi-io", "download", "read"))
667 return failure(403, 0, "Download permission denied");
669 if (!fields
[3] || !session_access(fields
[1], "file", fields
[3], "read"))
670 return failure(403, 0, "Access to path denied by ACL");
672 if (stat(fields
[3], &s
))
673 return failure(404, errno
, "Failed to stat requested path");
675 if (!S_ISREG(s
.st_mode
) && !S_ISBLK(s
.st_mode
))
676 return failure(403, 0, "Requested path is not a regular file or block device");
678 for (p
= fields
[5]; p
&& *p
; p
++)
679 if (!isalnum(*p
) && !strchr(" ()<>@,;:[]?.=%-", *p
))
680 return failure(400, 0, "Invalid characters in filename");
682 for (p
= fields
[7]; p
&& *p
; p
++)
683 if (!isalnum(*p
) && !strchr(" .;=/-", *p
))
684 return failure(400, 0, "Invalid characters in mimetype");
686 rfd
= open(fields
[3], O_RDONLY
);
689 return failure(500, errno
, "Failed to open requested path");
691 if (S_ISBLK(s
.st_mode
))
692 ioctl(rfd
, BLKGETSIZE64
, &size
);
694 size
= (unsigned long long)s
.st_size
;
696 printf("Status: 200 OK\r\n");
697 printf("Content-Type: %s\r\n", fields
[7] ? fields
[7] : "application/octet-stream");
700 printf("Content-Disposition: attachment; filename=\"%s\"\r\n", fields
[5]);
702 printf("Content-Length: %llu\r\n\r\n", size
);
706 len
= sendfile(1, rfd
, NULL
, size
);
709 if (errno
== ENOSYS
|| errno
== EINVAL
) {
710 while ((len
= read(rfd
, buf
, sizeof(buf
))) > 0)
711 fwrite(buf
, len
, 1, stdout
);
717 if (errno
== EINTR
|| errno
== EAGAIN
)
733 main_backup(int argc
, char **argv
)
740 char datestr
[16] = { 0 };
741 char hostname
[64] = { 0 };
742 char *fields
[] = { "sessionid", NULL
};
744 if (!postdecode(fields
, 1) || !session_access(fields
[1], "cgi-io", "backup", "read"))
745 return failure(403, 0, "Backup permission denied");
748 return failure(500, errno
, "Failed to spawn pipe");
750 switch ((pid
= fork()))
753 return failure(500, errno
, "Failed to fork process");
765 execl("/sbin/sysupgrade", "/sbin/sysupgrade",
766 "--create-backup", "-", NULL
);
772 strftime(datestr
, sizeof(datestr
) - 1, "%Y-%m-%d", localtime(&now
));
774 if (gethostname(hostname
, sizeof(hostname
) - 1))
775 sprintf(hostname
, "OpenWrt");
777 printf("Status: 200 OK\r\n");
778 printf("Content-Type: application/x-targz\r\n");
779 printf("Content-Disposition: attachment; "
780 "filename=\"backup-%s-%s.tar.gz\"\r\n\r\n", hostname
, datestr
);
785 len
= splice(fds
[0], NULL
, 1, NULL
, READ_BLOCK
, SPLICE_F_MORE
);
788 waitpid(pid
, &status
, 0);
797 int main(int argc
, char **argv
)
799 if (strstr(argv
[0], "cgi-upload"))
800 return main_upload(argc
, argv
);
801 else if (strstr(argv
[0], "cgi-download"))
802 return main_download(argc
, argv
);
803 else if (strstr(argv
[0], "cgi-backup"))
804 return main_backup(argc
, argv
);