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 response(bool success
, const char *message
)
272 printf("Status: 200 OK\r\n");
273 printf("Content-Type: text/plain\r\n\r\n{\n");
277 if (!stat(st
.filename
, &s
))
278 printf("\t\"size\": %u,\n", (unsigned int)s
.st_size
);
280 printf("\t\"size\": null,\n");
282 chksum
= checksum("md5sum", 32, st
.filename
);
283 printf("\t\"checksum\": %s%s%s,\n",
285 chksum
? chksum
: "null",
288 chksum
= checksum("sha256sum", 64, st
.filename
);
289 printf("\t\"sha256sum\": %s%s%s\n",
291 chksum
? chksum
: "null",
297 printf("\t\"message\": \"%s\",\n", message
);
299 printf("\t\"failure\": [ %u, \"%s\" ]\n", errno
, strerror(errno
));
311 failure(int e
, const char *message
)
313 printf("Status: 500 Internal Server failure\r\n");
314 printf("Content-Type: text/plain\r\n\r\n");
315 printf("%s", message
);
318 printf(": %s", strerror(e
));
333 return response(false, "No file data received");
336 if (lseek(st
.tempfd
, 0, SEEK_SET
) < 0)
339 return response(false, "Failed to rewind temp file");
342 st
.filefd
= open(st
.filename
, O_CREAT
| O_TRUNC
| O_WRONLY
, 0600);
347 return response(false, "Failed to open target file");
350 while ((len
= read(st
.tempfd
, buf
, sizeof(buf
))) > 0)
352 if (write(st
.filefd
, buf
, len
) != len
)
356 return response(false, "I/O failure while writing target file");
363 if (chmod(st
.filename
, st
.filemode
))
364 return response(false, "Failed to chmod target file");
370 header_field(multipart_parser
*p
, const char *data
, size_t len
)
372 st
.is_content_disposition
= !strncasecmp(data
, "Content-Disposition", len
);
377 header_value(multipart_parser
*p
, const char *data
, size_t len
)
381 if (!st
.is_content_disposition
)
384 if (len
< 10 || strncasecmp(data
, "form-data", 9))
387 for (data
+= 9, len
-= 9; *data
== ' ' || *data
== ';'; data
++, len
--);
389 if (len
< 8 || strncasecmp(data
, "name=\"", 6))
392 for (data
+= 6, len
-= 6, i
= 0; i
<= len
; i
++)
394 if (*(data
+ i
) != '"')
397 for (j
= 1; j
< sizeof(parts
) / sizeof(parts
[0]); j
++)
398 if (!strncmp(data
, parts
[j
], i
))
408 data_begin_cb(multipart_parser
*p
)
410 char tmpname
[24] = "/tmp/luci-upload.XXXXXX";
412 if (st
.parttype
== PART_FILEDATA
)
415 return response(false, "File data without session");
418 return response(false, "File data without name");
420 st
.tempfd
= mkstemp(tmpname
);
423 return response(false, "Failed to create temporary file");
432 data_cb(multipart_parser
*p
, const char *data
, size_t len
)
437 st
.sessionid
= datadup(data
, len
);
441 st
.filename
= datadup(data
, len
);
445 st
.filemode
= strtoul(data
, NULL
, 8);
449 if (write(st
.tempfd
, data
, len
) != len
)
452 return response(false, "I/O failure while writing temporary file");
468 data_end_cb(multipart_parser
*p
)
470 if (st
.parttype
== PART_SESSIONID
)
472 if (!session_access(st
.sessionid
, "upload", "write"))
475 return response(false, "Upload permission denied");
478 else if (st
.parttype
== PART_FILEDATA
)
481 return response(false, "Internal program failure");
484 /* prepare directory */
485 for (ptr
= st
.filename
; *ptr
; ptr
++)
491 if (mkdir(st
.filename
, 0755))
494 return response(false, "Failed to create destination directory");
505 return response(true, NULL
);
508 st
.parttype
= PART_UNKNOWN
;
512 static multipart_parser
*
519 static multipart_parser_settings s
= {
520 .on_part_data
= data_cb
,
521 .on_headers_complete
= data_begin_cb
,
522 .on_part_data_end
= data_end_cb
,
523 .on_header_field
= header_field
,
524 .on_header_value
= header_value
527 var
= getenv("CONTENT_TYPE");
529 if (!var
|| strncmp(var
, "multipart/form-data;", 20))
532 for (var
+= 20; *var
&& *var
!= '='; var
++);
537 boundary
= malloc(strlen(var
) + 3);
542 strcpy(boundary
, "--");
543 strcpy(boundary
+ 2, var
);
549 p
= multipart_parser_init(boundary
, &s
);
557 main_upload(int argc
, char *argv
[])
568 return response(false, "Invalid request");
571 while ((len
= read(0, buf
, sizeof(buf
))) > 0)
573 rem
= multipart_parser_execute(p
, buf
, len
);
579 multipart_parser_free(p
);
581 /* read remaining post data */
582 while ((len
= read(0, buf
, sizeof(buf
))) > 0);
588 main_backup(int argc
, char **argv
)
596 char datestr
[16] = { 0 };
597 char hostname
[64] = { 0 };
598 char *fields
[] = { "sessionid", NULL
};
600 if (!postdecode(fields
, 1) || !session_access(fields
[1], "backup", "read"))
601 return failure(0, "Backup permission denied");
604 return failure(errno
, "Failed to spawn pipe");
606 switch ((pid
= fork()))
609 return failure(errno
, "Failed to fork process");
621 execl("/sbin/sysupgrade", "/sbin/sysupgrade",
622 "--create-backup", "-", NULL
);
627 fcntl(fds
[0], F_SETFL
, fcntl(fds
[0], F_GETFL
) | O_NONBLOCK
);
629 strftime(datestr
, sizeof(datestr
) - 1, "%Y-%m-%d", localtime(&now
));
631 if (gethostname(hostname
, sizeof(hostname
) - 1))
632 sprintf(hostname
, "OpenWrt");
634 printf("Status: 200 OK\r\n");
635 printf("Content-Type: application/x-targz\r\n");
636 printf("Content-Disposition: attachment; "
637 "filename=\"backup-%s-%s.tar.gz\"\r\n\r\n", hostname
, datestr
);
640 waitpid(pid
, &status
, 0);
642 while ((len
= read(fds
[0], buf
, sizeof(buf
))) > 0) {
643 fwrite(buf
, len
, 1, stdout
);
647 } while (!WIFEXITED(status
));
656 int main(int argc
, char **argv
)
658 if (strstr(argv
[0], "cgi-upload"))
659 return main_upload(argc
, argv
);
660 else if (strstr(argv
[0], "cgi-backup"))
661 return main_backup(argc
, argv
);