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
41 #define POST_LIMIT 131072
51 const char *parts
[] = {
61 bool is_content_disposition
;
76 static const struct blobmsg_policy ses_policy
[__SES_MAX
] = {
77 [SES_ACCESS
] = { .name
= "access", .type
= BLOBMSG_TYPE_BOOL
},
81 static struct state st
;
84 session_access_cb(struct ubus_request
*req
, int type
, struct blob_attr
*msg
)
86 struct blob_attr
*tb
[__SES_MAX
];
87 bool *allow
= (bool *)req
->priv
;
92 blobmsg_parse(ses_policy
, __SES_MAX
, tb
, blob_data(msg
), blob_len(msg
));
95 *allow
= blobmsg_get_bool(tb
[SES_ACCESS
]);
99 session_access(const char *sid
, const char *scope
, const char *obj
, const char *func
)
103 struct ubus_context
*ctx
;
104 static struct blob_buf req
;
106 ctx
= ubus_connect(NULL
);
108 if (!ctx
|| ubus_lookup_id(ctx
, "session", &id
))
111 blob_buf_init(&req
, 0);
112 blobmsg_add_string(&req
, "ubus_rpc_session", sid
);
113 blobmsg_add_string(&req
, "scope", scope
);
114 blobmsg_add_string(&req
, "object", obj
);
115 blobmsg_add_string(&req
, "function", func
);
117 ubus_invoke(ctx
, id
, "access", req
.head
, session_access_cb
, &allow
, 500);
127 checksum(const char *applet
, size_t sumlen
, const char *file
)
132 static char chksum
[65];
137 switch ((pid
= fork()))
152 if (execl("/bin/busybox", "/bin/busybox", applet
, file
, NULL
))
158 memset(chksum
, 0, sizeof(chksum
));
159 r
= read(fds
[0], chksum
, sumlen
);
161 waitpid(pid
, NULL
, 0);
173 datadup(const void *in
, size_t len
)
175 char *out
= malloc(len
+ 1);
180 memcpy(out
, in
, len
);
196 (((x) <= '9') ? ((x) - '0') : \
197 (((x) <= 'F') ? ((x) - 'A' + 10) : \
200 for (c
= p
= buf
; *p
; c
++)
204 if (!isxdigit(*(p
+ 1)) || !isxdigit(*(p
+ 2)))
207 *c
= (char)(16 * hex(*(p
+ 1)) + hex(*(p
+ 2)));
228 postdecode(char **fields
, int n_fields
)
232 int i
, field
, found
= 0;
233 ssize_t len
= 0, rlen
= 0, content_length
= 0;
235 var
= getenv("CONTENT_TYPE");
237 if (!var
|| strncmp(var
, "application/x-www-form-urlencoded", 33))
240 var
= getenv("CONTENT_LENGTH");
245 content_length
= strtol(var
, &p
, 10);
247 if (p
== var
|| content_length
<= 0 || content_length
>= POST_LIMIT
)
250 postbuf
= calloc(1, content_length
+ 1);
255 for (len
= 0; len
< content_length
; )
257 rlen
= read(0, postbuf
+ len
, content_length
- len
);
265 if (len
< content_length
)
271 for (p
= postbuf
, i
= 0; i
<= len
; i
++)
273 if (postbuf
[i
] == '=')
277 for (field
= 0; field
< (n_fields
* 2); field
+= 2)
279 if (!strcmp(p
, fields
[field
]))
281 fields
[field
+ 1] = postbuf
+ i
+ 1;
286 else if (postbuf
[i
] == '&' || postbuf
[i
] == '\0')
290 if (found
>= n_fields
)
297 for (field
= 0; field
< (n_fields
* 2); field
+= 2)
299 if (!urldecode(fields
[field
+ 1]))
310 canonicalize_path(const char *path
, size_t len
)
312 char *canonpath
, *cp
;
315 if (path
== NULL
|| *path
== '\0')
318 canonpath
= datadup(path
, len
);
320 if (canonpath
== NULL
)
324 for (cp
= canonpath
, p
= path
, e
= path
+ len
; p
< e
; ) {
328 /* skip repeating / */
329 if ((p
+ 1 < e
) && (p
[1] == '/')) {
335 if ((p
+ 1 < e
) && (p
[1] == '.')) {
337 if ((p
+ 2 >= e
) || (p
[2] == '/')) {
342 /* collapse /x/../ */
343 if ((p
+ 2 < e
) && (p
[2] == '.') && ((p
+ 3 >= e
) || (p
[3] == '/'))) {
344 while ((cp
> canonpath
) && (*--cp
!= '/'))
356 /* remove trailing slash if not root / */
357 if ((cp
> canonpath
+ 1) && (cp
[-1] == '/'))
359 else if (cp
== canonpath
)
368 response(bool success
, const char *message
)
373 printf("Status: 200 OK\r\n");
374 printf("Content-Type: text/plain\r\n\r\n{\n");
378 if (!stat(st
.filename
, &s
))
379 printf("\t\"size\": %u,\n", (unsigned int)s
.st_size
);
381 printf("\t\"size\": null,\n");
383 chksum
= checksum("md5sum", 32, st
.filename
);
384 printf("\t\"checksum\": %s%s%s,\n",
386 chksum
? chksum
: "null",
389 chksum
= checksum("sha256sum", 64, st
.filename
);
390 printf("\t\"sha256sum\": %s%s%s\n",
392 chksum
? chksum
: "null",
398 printf("\t\"message\": \"%s\",\n", message
);
400 printf("\t\"failure\": [ %u, \"%s\" ]\n", errno
, strerror(errno
));
412 failure(int code
, int e
, const char *message
)
414 printf("Status: %d %s\r\n", code
, message
);
415 printf("Content-Type: text/plain\r\n\r\n");
416 printf("%s", message
);
419 printf(": %s", strerror(e
));
430 char buf
[READ_BLOCK
];
436 return response(false, "No file data received");
439 if (lseek(st
.tempfd
, 0, SEEK_SET
) < 0)
442 return response(false, "Failed to rewind temp file");
445 st
.filefd
= open(st
.filename
, O_CREAT
| O_TRUNC
| O_WRONLY
, 0600);
450 return response(false, "Failed to open target file");
453 while ((len
= read(st
.tempfd
, buf
, sizeof(buf
))) > 0)
455 if (write(st
.filefd
, buf
, len
) != len
)
459 return response(false, "I/O failure while writing target file");
466 if (chmod(st
.filename
, st
.filemode
))
467 return response(false, "Failed to chmod target file");
473 header_field(multipart_parser
*p
, const char *data
, size_t len
)
475 st
.is_content_disposition
= !strncasecmp(data
, "Content-Disposition", len
);
480 header_value(multipart_parser
*p
, const char *data
, size_t len
)
484 if (!st
.is_content_disposition
)
487 if (len
< 10 || strncasecmp(data
, "form-data", 9))
490 for (data
+= 9, len
-= 9; *data
== ' ' || *data
== ';'; data
++, len
--);
492 if (len
< 8 || strncasecmp(data
, "name=\"", 6))
495 for (data
+= 6, len
-= 6, i
= 0; i
<= len
; i
++)
497 if (*(data
+ i
) != '"')
500 for (j
= 1; j
< sizeof(parts
) / sizeof(parts
[0]); j
++)
501 if (!strncmp(data
, parts
[j
], i
))
511 data_begin_cb(multipart_parser
*p
)
513 char tmpname
[24] = "/tmp/luci-upload.XXXXXX";
515 if (st
.parttype
== PART_FILEDATA
)
518 return response(false, "File data without session");
521 return response(false, "File data without name");
523 if (!session_access(st
.sessionid
, "file", st
.filename
, "write"))
524 return response(false, "Access to path denied by ACL");
526 st
.tempfd
= mkstemp(tmpname
);
529 return response(false, "Failed to create temporary file");
538 data_cb(multipart_parser
*p
, const char *data
, size_t len
)
545 st
.sessionid
= datadup(data
, len
);
549 st
.filename
= canonicalize_path(data
, len
);
553 st
.filemode
= strtoul(data
, NULL
, 8);
557 if (write(st
.tempfd
, data
, len
) != wlen
)
560 return response(false, "I/O failure while writing temporary file");
564 st
.filedata
= !!wlen
;
576 data_end_cb(multipart_parser
*p
)
578 if (st
.parttype
== PART_SESSIONID
)
580 if (!session_access(st
.sessionid
, "cgi-io", "upload", "write"))
583 return response(false, "Upload permission denied");
586 else if (st
.parttype
== PART_FILEDATA
)
589 return response(false, "Internal program failure");
592 /* prepare directory */
593 for (ptr
= st
.filename
; *ptr
; ptr
++)
599 if (mkdir(st
.filename
, 0755))
602 return response(false, "Failed to create destination directory");
613 return response(true, NULL
);
616 st
.parttype
= PART_UNKNOWN
;
620 static multipart_parser
*
627 static multipart_parser_settings s
= {
628 .on_part_data
= data_cb
,
629 .on_headers_complete
= data_begin_cb
,
630 .on_part_data_end
= data_end_cb
,
631 .on_header_field
= header_field
,
632 .on_header_value
= header_value
635 var
= getenv("CONTENT_TYPE");
637 if (!var
|| strncmp(var
, "multipart/form-data;", 20))
640 for (var
+= 20; *var
&& *var
!= '='; var
++);
645 boundary
= malloc(strlen(var
) + 3);
650 strcpy(boundary
, "--");
651 strcpy(boundary
+ 2, var
);
657 p
= multipart_parser_init(boundary
, &s
);
665 main_upload(int argc
, char *argv
[])
669 char buf
[READ_BLOCK
];
677 return response(false, "Invalid request");
680 while ((len
= read(0, buf
, sizeof(buf
))) > 0)
683 rem
= multipart_parser_execute(p
, buf
, len
);
688 multipart_parser_free(p
);
694 free_charp(char **ptr
)
699 #define autochar __attribute__((__cleanup__(free_charp))) char
702 main_download(int argc
, char **argv
)
704 char *fields
[] = { "sessionid", NULL
, "path", NULL
, "filename", NULL
, "mimetype", NULL
};
705 unsigned long long size
= 0;
706 char *p
, buf
[READ_BLOCK
];
711 autochar
*post
= postdecode(fields
, 4);
713 if (!fields
[1] || !session_access(fields
[1], "cgi-io", "download", "read"))
714 return failure(403, 0, "Download permission denied");
716 if (!fields
[3] || !session_access(fields
[1], "file", fields
[3], "read"))
717 return failure(403, 0, "Access to path denied by ACL");
719 if (stat(fields
[3], &s
))
720 return failure(404, errno
, "Failed to stat requested path");
722 if (!S_ISREG(s
.st_mode
) && !S_ISBLK(s
.st_mode
))
723 return failure(403, 0, "Requested path is not a regular file or block device");
725 for (p
= fields
[5]; p
&& *p
; p
++)
726 if (!isalnum(*p
) && !strchr(" ()<>@,;:[]?.=%-", *p
))
727 return failure(400, 0, "Invalid characters in filename");
729 for (p
= fields
[7]; p
&& *p
; p
++)
730 if (!isalnum(*p
) && !strchr(" .;=/-", *p
))
731 return failure(400, 0, "Invalid characters in mimetype");
733 rfd
= open(fields
[3], O_RDONLY
);
736 return failure(500, errno
, "Failed to open requested path");
738 if (S_ISBLK(s
.st_mode
))
739 ioctl(rfd
, BLKGETSIZE64
, &size
);
741 size
= (unsigned long long)s
.st_size
;
743 printf("Status: 200 OK\r\n");
744 printf("Content-Type: %s\r\n", fields
[7] ? fields
[7] : "application/octet-stream");
747 printf("Content-Disposition: attachment; filename=\"%s\"\r\n", fields
[5]);
750 printf("Content-Length: %llu\r\n\r\n", size
);
754 len
= sendfile(1, rfd
, NULL
, size
);
757 if (errno
== ENOSYS
|| errno
== EINVAL
) {
758 while ((len
= read(rfd
, buf
, sizeof(buf
))) > 0)
759 fwrite(buf
, len
, 1, stdout
);
765 if (errno
== EINTR
|| errno
== EAGAIN
)
778 while ((len
= read(rfd
, buf
, sizeof(buf
))) > 0)
779 fwrite(buf
, len
, 1, stdout
);
790 main_backup(int argc
, char **argv
)
798 char datestr
[16] = { 0 };
799 char hostname
[64] = { 0 };
800 char *fields
[] = { "sessionid", NULL
};
802 autochar
*post
= postdecode(fields
, 1);
804 if (!fields
[1] || !session_access(fields
[1], "cgi-io", "backup", "read"))
805 return failure(403, 0, "Backup permission denied");
808 return failure(500, errno
, "Failed to spawn pipe");
810 switch ((pid
= fork()))
813 return failure(500, errno
, "Failed to fork process");
825 return failure(500, errno
, "Failed chdir('/')");
827 execl("/sbin/sysupgrade", "/sbin/sysupgrade",
828 "--create-backup", "-", NULL
);
836 strftime(datestr
, sizeof(datestr
) - 1, "%Y-%m-%d", localtime(&now
));
838 if (gethostname(hostname
, sizeof(hostname
) - 1))
839 sprintf(hostname
, "OpenWrt");
841 printf("Status: 200 OK\r\n");
842 printf("Content-Type: application/x-targz\r\n");
843 printf("Content-Disposition: attachment; "
844 "filename=\"backup-%s-%s.tar.gz\"\r\n\r\n", hostname
, datestr
);
849 len
= splice(fds
[0], NULL
, 1, NULL
, READ_BLOCK
, SPLICE_F_MORE
);
852 waitpid(pid
, &status
, 0);
862 lookup_executable(const char *cmd
)
864 size_t plen
= 0, clen
= strlen(cmd
) + 1;
865 static char path
[PATH_MAX
];
869 if (!stat(cmd
, &s
) && S_ISREG(s
.st_mode
))
872 search
= getenv("PATH");
875 search
= "/bin:/usr/bin:/sbin:/usr/sbin";
880 if (*p
!= ':' && *p
!= '\0')
885 if ((plen
+ clen
) >= sizeof(path
))
888 strncpy(path
, search
, plen
);
889 sprintf(path
+ plen
, "/%s", cmd
);
891 if (!stat(path
, &s
) && S_ISREG(s
.st_mode
))
901 parse_command(const char *cmdline
)
903 const char *p
= cmdline
, *s
;
904 char **argv
= NULL
, *out
;
909 while (isspace(*cmdline
))
912 for (p
= cmdline
, s
= p
, esc
= false; p
; p
++) {
916 else if (*p
== '\\' && p
[1] != 0) {
919 else if (isspace(*p
) || *p
== 0) {
922 arglen
+= sizeof(char *) + (p
- s
) + 1;
935 argv
= calloc(1, arglen
+ sizeof(char *));
940 out
= (char *)argv
+ sizeof(char *) * (argnum
+ 1);
943 for (p
= cmdline
, s
= p
, esc
= false, argnum
= 0; p
; p
++) {
948 else if (*p
== '\\' && p
[1] != 0) {
951 else if (isspace(*p
) || *p
== 0) {
954 argv
[++argnum
] = out
;
974 main_exec(int argc
, char **argv
)
976 char *fields
[] = { "sessionid", NULL
, "command", NULL
, "filename", NULL
, "mimetype", NULL
};
977 int i
, devnull
, status
, fds
[2];
978 bool allowed
= false;
984 autochar
*post
= postdecode(fields
, 4);
986 if (!fields
[1] || !session_access(fields
[1], "cgi-io", "exec", "read"))
987 return failure(403, 0, "Exec permission denied");
989 for (p
= fields
[5]; p
&& *p
; p
++)
990 if (!isalnum(*p
) && !strchr(" ()<>@,;:[]?.=%-", *p
))
991 return failure(400, 0, "Invalid characters in filename");
993 for (p
= fields
[7]; p
&& *p
; p
++)
994 if (!isalnum(*p
) && !strchr(" .;=/-", *p
))
995 return failure(400, 0, "Invalid characters in mimetype");
997 args
= fields
[3] ? parse_command(fields
[3]) : NULL
;
1000 return failure(400, 0, "Invalid command parameter");
1002 /* First check if we find an ACL match for the whole cmdline ... */
1003 allowed
= session_access(fields
[1], "file", args
[0], "exec");
1005 /* Now split the command vector... */
1006 for (i
= 1; args
[i
]; i
++)
1009 /* Find executable... */
1010 exe
= lookup_executable(args
[0]);
1014 return failure(404, 0, "Executable not found");
1017 /* If there was no ACL match, check for a match on the executable */
1018 if (!allowed
&& !session_access(fields
[1], "file", exe
, "exec")) {
1020 return failure(403, 0, "Access to command denied by ACL");
1025 return failure(500, errno
, "Failed to spawn pipe");
1028 switch ((pid
= fork()))
1034 return failure(500, errno
, "Failed to fork process");
1037 devnull
= open("/dev/null", O_RDWR
);
1053 if (chdir("/") < 0) {
1055 return failure(500, errno
, "Failed chdir('/')");
1058 if (execv(exe
, args
) < 0) {
1060 return failure(500, errno
, "Failed execv(...)");
1068 printf("Status: 200 OK\r\n");
1069 printf("Content-Type: %s\r\n",
1070 fields
[7] ? fields
[7] : "application/octet-stream");
1073 printf("Content-Disposition: attachment; filename=\"%s\"\r\n",
1080 len
= splice(fds
[0], NULL
, 1, NULL
, READ_BLOCK
, SPLICE_F_MORE
);
1083 waitpid(pid
, &status
, 0);
1092 int main(int argc
, char **argv
)
1094 if (strstr(argv
[0], "cgi-upload"))
1095 return main_upload(argc
, argv
);
1096 else if (strstr(argv
[0], "cgi-download"))
1097 return main_download(argc
, argv
);
1098 else if (strstr(argv
[0], "cgi-backup"))
1099 return main_backup(argc
, argv
);
1100 else if (strstr(argv
[0], "cgi-exec"))
1101 return main_exec(argc
, argv
);