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>
39 #include "multipart_parser.h"
42 #define O_TMPFILE (020000000 | O_DIRECTORY)
45 #define READ_BLOCK 4096
55 const char *parts
[] = {
65 bool is_content_disposition
;
80 static const struct blobmsg_policy ses_policy
[__SES_MAX
] = {
81 [SES_ACCESS
] = { .name
= "access", .type
= BLOBMSG_TYPE_BOOL
},
85 static struct state st
;
88 session_access_cb(struct ubus_request
*req
, int type
, struct blob_attr
*msg
)
90 struct blob_attr
*tb
[__SES_MAX
];
91 bool *allow
= (bool *)req
->priv
;
96 blobmsg_parse(ses_policy
, __SES_MAX
, tb
, blob_data(msg
), blob_len(msg
));
99 *allow
= blobmsg_get_bool(tb
[SES_ACCESS
]);
103 session_access(const char *sid
, const char *scope
, const char *obj
, const char *func
)
107 struct ubus_context
*ctx
;
108 static struct blob_buf req
;
110 ctx
= ubus_connect(NULL
);
112 if (!ctx
|| !obj
|| ubus_lookup_id(ctx
, "session", &id
))
115 blob_buf_init(&req
, 0);
116 blobmsg_add_string(&req
, "ubus_rpc_session", sid
);
117 blobmsg_add_string(&req
, "scope", scope
);
118 blobmsg_add_string(&req
, "object", obj
);
119 blobmsg_add_string(&req
, "function", func
);
121 ubus_invoke(ctx
, id
, "access", req
.head
, session_access_cb
, &allow
, 500);
131 checksum(const char *applet
, size_t sumlen
, const char *file
)
136 static char chksum
[65];
141 switch ((pid
= fork()))
156 if (execl("/bin/busybox", "/bin/busybox", applet
, file
, NULL
))
162 memset(chksum
, 0, sizeof(chksum
));
163 r
= read(fds
[0], chksum
, sumlen
);
165 waitpid(pid
, NULL
, 0);
177 response(bool success
, const char *message
)
182 printf("Status: 200 OK\r\n");
183 printf("Content-Type: text/plain\r\n\r\n{\n");
187 if (!stat(st
.filename
, &s
))
188 printf("\t\"size\": %u,\n", (unsigned int)s
.st_size
);
190 printf("\t\"size\": null,\n");
192 chksum
= checksum("md5sum", 32, st
.filename
);
193 printf("\t\"checksum\": %s%s%s,\n",
195 chksum
? chksum
: "null",
198 chksum
= checksum("sha256sum", 64, st
.filename
);
199 printf("\t\"sha256sum\": %s%s%s\n",
201 chksum
? chksum
: "null",
207 printf("\t\"message\": \"%s\",\n", message
);
209 printf("\t\"failure\": [ %u, \"%s\" ]\n", errno
, strerror(errno
));
211 if (st
.filefd
> -1 && st
.filename
)
221 failure(int code
, int e
, const char *message
)
223 printf("Status: %d %s\r\n", code
, message
);
224 printf("Content-Type: text/plain\r\n\r\n");
225 printf("%s", message
);
228 printf(": %s", strerror(e
));
239 char buf
[READ_BLOCK
];
245 return response(false, "No file data received");
248 snprintf(buf
, sizeof(buf
), "/proc/self/fd/%d", st
.tempfd
);
250 if (unlink(st
.filename
) < 0 && errno
!= ENOENT
)
253 return response(false, "Failed to unlink existing file");
256 if (linkat(AT_FDCWD
, buf
, AT_FDCWD
, st
.filename
, AT_SYMLINK_FOLLOW
) < 0)
258 if (lseek(st
.tempfd
, 0, SEEK_SET
) < 0)
261 return response(false, "Failed to rewind temp file");
264 st
.filefd
= open(st
.filename
, O_CREAT
| O_TRUNC
| O_WRONLY
, 0600);
269 return response(false, "Failed to open target file");
272 while ((len
= read(st
.tempfd
, buf
, sizeof(buf
))) > 0)
274 if (write(st
.filefd
, buf
, len
) != len
)
278 return response(false, "I/O failure while writing target file");
287 if (chmod(st
.filename
, st
.filemode
))
288 return response(false, "Failed to chmod target file");
294 header_field(multipart_parser
*p
, const char *data
, size_t len
)
296 st
.is_content_disposition
= !strncasecmp(data
, "Content-Disposition", len
);
301 header_value(multipart_parser
*p
, const char *data
, size_t len
)
305 if (!st
.is_content_disposition
)
308 if (len
< 10 || strncasecmp(data
, "form-data", 9))
311 for (data
+= 9, len
-= 9; *data
== ' ' || *data
== ';'; data
++, len
--);
313 if (len
< 8 || strncasecmp(data
, "name=\"", 6))
316 for (data
+= 6, len
-= 6, i
= 0; i
<= len
; i
++)
318 if (*(data
+ i
) != '"')
321 for (j
= 1; j
< sizeof(parts
) / sizeof(parts
[0]); j
++)
322 if (!strncmp(data
, parts
[j
], i
))
332 data_begin_cb(multipart_parser
*p
)
334 if (st
.parttype
== PART_FILEDATA
)
337 return response(false, "File data without session");
340 return response(false, "File data without name");
342 if (!session_access(st
.sessionid
, "file", st
.filename
, "write"))
343 return response(false, "Access to path denied by ACL");
345 st
.tempfd
= open("/tmp", O_TMPFILE
| O_RDWR
, S_IRUSR
| S_IWUSR
);
348 return response(false, "Failed to create temporary file");
355 data_cb(multipart_parser
*p
, const char *data
, size_t len
)
362 st
.sessionid
= datadup(data
, len
);
366 st
.filename
= canonicalize_path(data
, len
);
370 st
.filemode
= strtoul(data
, NULL
, 8);
374 if (write(st
.tempfd
, data
, len
) != wlen
)
377 return response(false, "I/O failure while writing temporary file");
381 st
.filedata
= !!wlen
;
393 data_end_cb(multipart_parser
*p
)
395 if (st
.parttype
== PART_SESSIONID
)
397 if (!session_access(st
.sessionid
, "cgi-io", "upload", "write"))
400 return response(false, "Upload permission denied");
403 else if (st
.parttype
== PART_FILEDATA
)
406 return response(false, "Internal program failure");
409 /* prepare directory */
410 for (ptr
= st
.filename
; *ptr
; ptr
++)
416 if (mkdir(st
.filename
, 0755))
419 return response(false, "Failed to create destination directory");
430 return response(true, NULL
);
433 st
.parttype
= PART_UNKNOWN
;
437 static multipart_parser
*
444 static multipart_parser_settings s
= {
445 .on_part_data
= data_cb
,
446 .on_headers_complete
= data_begin_cb
,
447 .on_part_data_end
= data_end_cb
,
448 .on_header_field
= header_field
,
449 .on_header_value
= header_value
452 var
= getenv("CONTENT_TYPE");
454 if (!var
|| strncmp(var
, "multipart/form-data;", 20))
457 for (var
+= 20; *var
&& *var
!= '='; var
++);
462 boundary
= malloc(strlen(var
) + 3);
467 strcpy(boundary
, "--");
468 strcpy(boundary
+ 2, var
);
474 p
= multipart_parser_init(boundary
, &s
);
482 main_upload(int argc
, char *argv
[])
486 char buf
[READ_BLOCK
];
494 return response(false, "Invalid request");
497 while ((len
= read(0, buf
, sizeof(buf
))) > 0)
500 rem
= multipart_parser_execute(p
, buf
, len
);
505 multipart_parser_free(p
);
511 free_charp(char **ptr
)
516 #define autochar __attribute__((__cleanup__(free_charp))) char
519 main_download(int argc
, char **argv
)
521 char *fields
[] = { "sessionid", NULL
, "path", NULL
, "filename", NULL
, "mimetype", NULL
};
522 unsigned long long size
= 0;
523 char *p
, buf
[READ_BLOCK
];
528 autochar
*post
= postdecode(fields
, 4);
531 if (!fields
[1] || !session_access(fields
[1], "cgi-io", "download", "read"))
532 return failure(403, 0, "Download permission denied");
534 if (!fields
[3] || !session_access(fields
[1], "file", fields
[3], "read"))
535 return failure(403, 0, "Access to path denied by ACL");
537 if (stat(fields
[3], &s
))
538 return failure(404, errno
, "Failed to stat requested path");
540 if (!S_ISREG(s
.st_mode
) && !S_ISBLK(s
.st_mode
))
541 return failure(403, 0, "Requested path is not a regular file or block device");
543 for (p
= fields
[5]; p
&& *p
; p
++)
544 if (!isalnum(*p
) && !strchr(" ()<>@,;:[]?.=%-", *p
))
545 return failure(400, 0, "Invalid characters in filename");
547 for (p
= fields
[7]; p
&& *p
; p
++)
548 if (!isalnum(*p
) && !strchr(" .;=/-", *p
))
549 return failure(400, 0, "Invalid characters in mimetype");
551 rfd
= open(fields
[3], O_RDONLY
);
554 return failure(500, errno
, "Failed to open requested path");
556 if (S_ISBLK(s
.st_mode
))
557 ioctl(rfd
, BLKGETSIZE64
, &size
);
559 size
= (unsigned long long)s
.st_size
;
561 printf("Status: 200 OK\r\n");
562 printf("Content-Type: %s\r\n", fields
[7] ? fields
[7] : "application/octet-stream");
565 printf("Content-Disposition: attachment; filename=\"%s\"\r\n", fields
[5]);
568 printf("Content-Length: %llu\r\n\r\n", size
);
572 len
= sendfile(1, rfd
, NULL
, size
);
575 if (errno
== ENOSYS
|| errno
== EINVAL
) {
576 while ((len
= read(rfd
, buf
, sizeof(buf
))) > 0)
577 fwrite(buf
, len
, 1, stdout
);
583 if (errno
== EINTR
|| errno
== EAGAIN
)
596 while ((len
= read(rfd
, buf
, sizeof(buf
))) > 0)
597 fwrite(buf
, len
, 1, stdout
);
608 main_backup(int argc
, char **argv
)
616 char datestr
[16] = { 0 };
617 char hostname
[64] = { 0 };
618 char *fields
[] = { "sessionid", NULL
};
620 autochar
*post
= postdecode(fields
, 1);
623 if (!fields
[1] || !session_access(fields
[1], "cgi-io", "backup", "read"))
624 return failure(403, 0, "Backup permission denied");
627 return failure(500, errno
, "Failed to spawn pipe");
629 switch ((pid
= fork()))
632 return failure(500, errno
, "Failed to fork process");
644 return failure(500, errno
, "Failed chdir('/')");
646 execl("/sbin/sysupgrade", "/sbin/sysupgrade",
647 "--create-backup", "-", NULL
);
655 strftime(datestr
, sizeof(datestr
) - 1, "%Y-%m-%d", localtime(&now
));
657 if (gethostname(hostname
, sizeof(hostname
) - 1))
658 sprintf(hostname
, "OpenWrt");
660 printf("Status: 200 OK\r\n");
661 printf("Content-Type: application/x-targz\r\n");
662 printf("Content-Disposition: attachment; "
663 "filename=\"backup-%s-%s.tar.gz\"\r\n\r\n", hostname
, datestr
);
668 len
= splice(fds
[0], NULL
, 1, NULL
, READ_BLOCK
, SPLICE_F_MORE
);
671 waitpid(pid
, &status
, 0);
681 lookup_executable(const char *cmd
)
683 size_t plen
= 0, clen
;
684 static char path
[PATH_MAX
];
691 clen
= strlen(cmd
) + 1;
693 if (!stat(cmd
, &s
) && S_ISREG(s
.st_mode
))
696 search
= getenv("PATH");
699 search
= "/bin:/usr/bin:/sbin:/usr/sbin";
704 if (*p
!= ':' && *p
!= '\0')
709 if ((plen
+ clen
) >= sizeof(path
))
712 strncpy(path
, search
, plen
);
713 sprintf(path
+ plen
, "/%s", cmd
);
715 if (!stat(path
, &s
) && S_ISREG(s
.st_mode
))
725 main_exec(int argc
, char **argv
)
727 char *fields
[] = { "sessionid", NULL
, "command", NULL
, "filename", NULL
, "mimetype", NULL
};
728 int i
, devnull
, status
, fds
[2];
729 bool allowed
= false;
735 autochar
*post
= postdecode(fields
, 4);
738 if (!fields
[1] || !session_access(fields
[1], "cgi-io", "exec", "read"))
739 return failure(403, 0, "Exec permission denied");
741 for (p
= fields
[5]; p
&& *p
; p
++)
742 if (!isalnum(*p
) && !strchr(" ()<>@,;:[]?.=%-", *p
))
743 return failure(400, 0, "Invalid characters in filename");
745 for (p
= fields
[7]; p
&& *p
; p
++)
746 if (!isalnum(*p
) && !strchr(" .;=/-", *p
))
747 return failure(400, 0, "Invalid characters in mimetype");
749 args
= fields
[3] ? parse_command(fields
[3]) : NULL
;
752 return failure(400, 0, "Invalid command parameter");
754 /* First check if we find an ACL match for the whole cmdline ... */
755 allowed
= session_access(fields
[1], "file", args
[0], "exec");
757 /* Now split the command vector... */
758 for (i
= 1; args
[i
]; i
++)
761 /* Find executable... */
762 exe
= lookup_executable(args
[0]);
766 return failure(404, 0, "Executable not found");
769 /* If there was no ACL match, check for a match on the executable */
770 if (!allowed
&& !session_access(fields
[1], "file", exe
, "exec")) {
772 return failure(403, 0, "Access to command denied by ACL");
777 return failure(500, errno
, "Failed to spawn pipe");
780 switch ((pid
= fork()))
786 return failure(500, errno
, "Failed to fork process");
789 devnull
= open("/dev/null", O_RDWR
);
805 if (chdir("/") < 0) {
807 return failure(500, errno
, "Failed chdir('/')");
810 if (execv(exe
, args
) < 0) {
812 return failure(500, errno
, "Failed execv(...)");
820 printf("Status: 200 OK\r\n");
821 printf("Content-Type: %s\r\n",
822 fields
[7] ? fields
[7] : "application/octet-stream");
825 printf("Content-Disposition: attachment; filename=\"%s\"\r\n",
832 len
= splice(fds
[0], NULL
, 1, NULL
, READ_BLOCK
, SPLICE_F_MORE
);
835 waitpid(pid
, &status
, 0);
844 int main(int argc
, char **argv
)
846 if (strstr(argv
[0], "cgi-upload"))
847 return main_upload(argc
, argv
);
848 else if (strstr(argv
[0], "cgi-download"))
849 return main_download(argc
, argv
);
850 else if (strstr(argv
[0], "cgi-backup"))
851 return main_backup(argc
, argv
);
852 else if (strstr(argv
[0], "cgi-exec"))
853 return main_exec(argc
, argv
);