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.
31 #include <libubox/blobmsg.h>
33 #include "multipart_parser.h"
44 const char *parts
[] = {
54 bool is_content_disposition
;
69 static const struct blobmsg_policy ses_policy
[__SES_MAX
] = {
70 [SES_ACCESS
] = { .name
= "access", .type
= BLOBMSG_TYPE_BOOL
},
74 static struct state st
;
77 session_access_cb(struct ubus_request
*req
, int type
, struct blob_attr
*msg
)
79 struct blob_attr
*tb
[__SES_MAX
];
80 bool *allow
= (bool *)req
->priv
;
85 blobmsg_parse(ses_policy
, __SES_MAX
, tb
, blob_data(msg
), blob_len(msg
));
88 *allow
= blobmsg_get_bool(tb
[SES_ACCESS
]);
92 session_access(const char *sid
, const char *obj
, const char *func
)
96 struct ubus_context
*ctx
;
97 static struct blob_buf req
;
99 ctx
= ubus_connect(NULL
);
101 if (!ctx
|| ubus_lookup_id(ctx
, "session", &id
))
104 blob_buf_init(&req
, 0);
105 blobmsg_add_string(&req
, "ubus_rpc_session", sid
);
106 blobmsg_add_string(&req
, "scope", "cgi-io");
107 blobmsg_add_string(&req
, "object", obj
);
108 blobmsg_add_string(&req
, "function", func
);
110 ubus_invoke(ctx
, id
, "access", req
.head
, session_access_cb
, &allow
, 500);
120 checksum(const char *applet
, size_t sumlen
, const char *file
)
124 static char chksum
[65];
129 switch ((pid
= fork()))
144 if (execl("/bin/busybox", "/bin/busybox", applet
, file
, NULL
))
150 memset(chksum
, 0, sizeof(chksum
));
151 read(fds
[0], chksum
, sumlen
);
152 waitpid(pid
, NULL
, 0);
161 datadup(const void *in
, size_t len
)
163 char *out
= malloc(len
+ 1);
168 memcpy(out
, in
, len
);
184 (((x) <= '9') ? ((x) - '0') : \
185 (((x) <= 'F') ? ((x) - 'A' + 10) : \
188 for (c
= p
= buf
; *p
; c
++)
192 if (!isxdigit(*(p
+ 1)) || !isxdigit(*(p
+ 2)))
195 *c
= (char)(16 * hex(*(p
+ 1)) + hex(*(p
+ 2)));
216 postdecode(char **fields
, int n_fields
)
220 static char buf
[1024];
221 int i
, len
, field
, found
= 0;
223 var
= getenv("CONTENT_TYPE");
225 if (!var
|| strncmp(var
, "application/x-www-form-urlencoded", 33))
228 memset(buf
, 0, sizeof(buf
));
230 if ((len
= read(0, buf
, sizeof(buf
) - 1)) > 0)
232 for (p
= buf
, i
= 0; i
<= len
; i
++)
238 for (field
= 0; field
< (n_fields
* 2); field
+= 2)
240 if (!strcmp(p
, fields
[field
]))
242 fields
[field
+ 1] = buf
+ i
+ 1;
247 else if (buf
[i
] == '&' || buf
[i
] == '\0')
251 if (found
>= n_fields
)
259 for (field
= 0; field
< (n_fields
* 2); field
+= 2)
260 if (!urldecode(fields
[field
+ 1]))
263 return (found
>= n_fields
);
267 canonicalize_path(const char *path
, size_t len
)
269 char *canonpath
, *cp
;
272 if (path
== NULL
|| *path
== '\0')
275 canonpath
= datadup(path
, len
);
277 if (canonpath
== NULL
)
281 for (cp
= canonpath
, p
= path
, e
= path
+ len
; p
< e
; ) {
285 /* skip repeating / */
286 if ((p
+ 1 < e
) && (p
[1] == '/')) {
292 if ((p
+ 1 < e
) && (p
[1] == '.')) {
294 if ((p
+ 2 >= e
) || (p
[2] == '/')) {
299 /* collapse /x/../ */
300 if ((p
+ 2 < e
) && (p
[2] == '.') && ((p
+ 3 >= e
) || (p
[3] == '/'))) {
301 while ((cp
> canonpath
) && (*--cp
!= '/'))
313 /* remove trailing slash if not root / */
314 if ((cp
> canonpath
+ 1) && (cp
[-1] == '/'))
316 else if (cp
== canonpath
)
325 response(bool success
, const char *message
)
330 printf("Status: 200 OK\r\n");
331 printf("Content-Type: text/plain\r\n\r\n{\n");
335 if (!stat(st
.filename
, &s
))
336 printf("\t\"size\": %u,\n", (unsigned int)s
.st_size
);
338 printf("\t\"size\": null,\n");
340 chksum
= checksum("md5sum", 32, st
.filename
);
341 printf("\t\"checksum\": %s%s%s,\n",
343 chksum
? chksum
: "null",
346 chksum
= checksum("sha256sum", 64, st
.filename
);
347 printf("\t\"sha256sum\": %s%s%s\n",
349 chksum
? chksum
: "null",
355 printf("\t\"message\": \"%s\",\n", message
);
357 printf("\t\"failure\": [ %u, \"%s\" ]\n", errno
, strerror(errno
));
369 failure(int e
, const char *message
)
371 printf("Status: 500 Internal Server failure\r\n");
372 printf("Content-Type: text/plain\r\n\r\n");
373 printf("%s", message
);
376 printf(": %s", strerror(e
));
391 return response(false, "No file data received");
394 if (lseek(st
.tempfd
, 0, SEEK_SET
) < 0)
397 return response(false, "Failed to rewind temp file");
400 st
.filefd
= open(st
.filename
, O_CREAT
| O_TRUNC
| O_WRONLY
, 0600);
405 return response(false, "Failed to open target file");
408 while ((len
= read(st
.tempfd
, buf
, sizeof(buf
))) > 0)
410 if (write(st
.filefd
, buf
, len
) != len
)
414 return response(false, "I/O failure while writing target file");
421 if (chmod(st
.filename
, st
.filemode
))
422 return response(false, "Failed to chmod target file");
428 header_field(multipart_parser
*p
, const char *data
, size_t len
)
430 st
.is_content_disposition
= !strncasecmp(data
, "Content-Disposition", len
);
435 header_value(multipart_parser
*p
, const char *data
, size_t len
)
439 if (!st
.is_content_disposition
)
442 if (len
< 10 || strncasecmp(data
, "form-data", 9))
445 for (data
+= 9, len
-= 9; *data
== ' ' || *data
== ';'; data
++, len
--);
447 if (len
< 8 || strncasecmp(data
, "name=\"", 6))
450 for (data
+= 6, len
-= 6, i
= 0; i
<= len
; i
++)
452 if (*(data
+ i
) != '"')
455 for (j
= 1; j
< sizeof(parts
) / sizeof(parts
[0]); j
++)
456 if (!strncmp(data
, parts
[j
], i
))
466 data_begin_cb(multipart_parser
*p
)
468 char tmpname
[24] = "/tmp/luci-upload.XXXXXX";
470 if (st
.parttype
== PART_FILEDATA
)
473 return response(false, "File data without session");
476 return response(false, "File data without name");
478 if (!session_access(st
.sessionid
, st
.filename
, "write"))
479 return response(false, "Access to path denied by ACL");
481 st
.tempfd
= mkstemp(tmpname
);
484 return response(false, "Failed to create temporary file");
493 data_cb(multipart_parser
*p
, const char *data
, size_t len
)
498 st
.sessionid
= datadup(data
, len
);
502 st
.filename
= canonicalize_path(data
, len
);
506 st
.filemode
= strtoul(data
, NULL
, 8);
510 if (write(st
.tempfd
, data
, len
) != len
)
513 return response(false, "I/O failure while writing temporary file");
529 data_end_cb(multipart_parser
*p
)
531 if (st
.parttype
== PART_SESSIONID
)
533 if (!session_access(st
.sessionid
, "upload", "write"))
536 return response(false, "Upload permission denied");
539 else if (st
.parttype
== PART_FILEDATA
)
542 return response(false, "Internal program failure");
545 /* prepare directory */
546 for (ptr
= st
.filename
; *ptr
; ptr
++)
552 if (mkdir(st
.filename
, 0755))
555 return response(false, "Failed to create destination directory");
566 return response(true, NULL
);
569 st
.parttype
= PART_UNKNOWN
;
573 static multipart_parser
*
580 static multipart_parser_settings s
= {
581 .on_part_data
= data_cb
,
582 .on_headers_complete
= data_begin_cb
,
583 .on_part_data_end
= data_end_cb
,
584 .on_header_field
= header_field
,
585 .on_header_value
= header_value
588 var
= getenv("CONTENT_TYPE");
590 if (!var
|| strncmp(var
, "multipart/form-data;", 20))
593 for (var
+= 20; *var
&& *var
!= '='; var
++);
598 boundary
= malloc(strlen(var
) + 3);
603 strcpy(boundary
, "--");
604 strcpy(boundary
+ 2, var
);
610 p
= multipart_parser_init(boundary
, &s
);
618 main_upload(int argc
, char *argv
[])
629 return response(false, "Invalid request");
632 while ((len
= read(0, buf
, sizeof(buf
))) > 0)
634 rem
= multipart_parser_execute(p
, buf
, len
);
640 multipart_parser_free(p
);
642 /* read remaining post data */
643 while ((len
= read(0, buf
, sizeof(buf
))) > 0);
649 main_backup(int argc
, char **argv
)
657 char datestr
[16] = { 0 };
658 char hostname
[64] = { 0 };
659 char *fields
[] = { "sessionid", NULL
};
661 if (!postdecode(fields
, 1) || !session_access(fields
[1], "backup", "read"))
662 return failure(0, "Backup permission denied");
665 return failure(errno
, "Failed to spawn pipe");
667 switch ((pid
= fork()))
670 return failure(errno
, "Failed to fork process");
682 execl("/sbin/sysupgrade", "/sbin/sysupgrade",
683 "--create-backup", "-", NULL
);
688 fcntl(fds
[0], F_SETFL
, fcntl(fds
[0], F_GETFL
) | O_NONBLOCK
);
690 strftime(datestr
, sizeof(datestr
) - 1, "%Y-%m-%d", localtime(&now
));
692 if (gethostname(hostname
, sizeof(hostname
) - 1))
693 sprintf(hostname
, "OpenWrt");
695 printf("Status: 200 OK\r\n");
696 printf("Content-Type: application/x-targz\r\n");
697 printf("Content-Disposition: attachment; "
698 "filename=\"backup-%s-%s.tar.gz\"\r\n\r\n", hostname
, datestr
);
701 waitpid(pid
, &status
, 0);
703 while ((len
= read(fds
[0], buf
, sizeof(buf
))) > 0) {
704 fwrite(buf
, len
, 1, stdout
);
708 } while (!WIFEXITED(status
));
717 int main(int argc
, char **argv
)
719 if (strstr(argv
[0], "cgi-upload"))
720 return main_upload(argc
, argv
);
721 else if (strstr(argv
[0], "cgi-backup"))
722 return main_backup(argc
, argv
);