upload.c 4.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130
  1. // Copyright (c) 2004-2012 Sergey Lyubka
  2. // This file is a part of mongoose project, http://github.com/valenok/mongoose
  3. #include <stdio.h>
  4. #include <string.h>
  5. #include <fcntl.h>
  6. #include <stdlib.h>
  7. #include <inttypes.h>
  8. #include <unistd.h>
  9. #include "mongoose.h"
  10. // Make sure that form has enctype="multipart/form-data" attribute
  11. static const char *html_form =
  12. "<html><body>Upload example."
  13. "<form method=\"POST\" action=\"/handle_post_request\" "
  14. " enctype=\"multipart/form-data\">"
  15. "<input type=\"file\" name=\"file\" /> <br/>"
  16. "<input type=\"submit\" value=\"Upload\" />"
  17. "</form></body></html>";
  18. static const char *HTTP_500 = "HTTP/1.0 500 Server Error\r\n\r\n";
  19. static void handle_file_upload(struct mg_connection *conn) {
  20. const char *cl_header;
  21. char post_data[16 * 1024], path[999], file_name[1024], mime_type[100],
  22. buf[BUFSIZ], *eop, *s, *p;
  23. FILE *fp;
  24. long long int cl, written;
  25. int fd, n, post_data_len;
  26. // Figure out total content length. Return if it is not present or invalid.
  27. cl_header = mg_get_header(conn, "Content-Length");
  28. if (cl_header == NULL || (cl = strtoll(cl_header, NULL, 10)) <= 0) {
  29. mg_printf(conn, "%s%s", HTTP_500, "Invalid Conent-Length");
  30. return;
  31. }
  32. // Read the initial chunk into memory. This should be multipart POST data.
  33. // Parse headers, where we should find file name and content-type.
  34. post_data_len = mg_read(conn, post_data, sizeof(post_data));
  35. file_name[0] = mime_type[0] = '\0';
  36. for (s = p = post_data; p < &post_data[post_data_len]; p++) {
  37. if (p[0] == '\r' && p[1] == '\n') {
  38. if (s == p) {
  39. p += 2;
  40. break; // End of headers
  41. }
  42. p[0] = p[1] = '\0';
  43. sscanf(s, "Content-Type: %99s", mime_type);
  44. // TODO(lsm): don't expect filename to be the 3rd field,
  45. // parse the header properly instead.
  46. sscanf(s, "Content-Disposition: %*s %*s filename=\"%1023[^\"]",
  47. file_name);
  48. s = p + 2;
  49. }
  50. }
  51. // Finished parsing headers. Now "p" points to the first byte of data.
  52. // Calculate file size
  53. cl -= p - post_data; // Subtract headers size
  54. cl -= strlen(post_data); // Subtract the boundary marker at the end
  55. cl -= 6; // Subtract "\r\n" before and after boundary
  56. // Construct destination file name. Write to /tmp, do not allow
  57. // paths that contain slashes.
  58. if ((s = strrchr(file_name, '/')) == NULL) {
  59. s = file_name;
  60. }
  61. snprintf(path, sizeof(path), "/tmp/%s", s);
  62. if (file_name[0] == '\0') {
  63. mg_printf(conn, "%s%s", HTTP_500, "Can't get file name");
  64. } else if (cl <= 0) {
  65. mg_printf(conn, "%s%s", HTTP_500, "Empty file");
  66. } else if ((fd = open(path, O_CREAT | O_TRUNC |
  67. O_WRONLY | O_EXLOCK | O_CLOEXEC)) < 0) {
  68. // We're opening the file with exclusive lock held. This guarantee us that
  69. // there is no other thread can save into the same file simultaneously.
  70. mg_printf(conn, "%s%s", HTTP_500, "Cannot open file");
  71. } else if ((fp = fdopen(fd, "w")) == NULL) {
  72. mg_printf(conn, "%s%s", HTTP_500, "Cannot reopen file stream");
  73. close(fd);
  74. } else {
  75. // Success. Write data into the file.
  76. eop = post_data + post_data_len;
  77. n = p + cl > eop ? (int) (eop - p) : (int) cl;
  78. (void) fwrite(p, 1, n, fp);
  79. written = n;
  80. while (written < cl &&
  81. (n = mg_read(conn, buf, cl - written > (long long) sizeof(buf) ?
  82. sizeof(buf) : cl - written)) > 0) {
  83. (void) fwrite(buf, 1, n, fp);
  84. written += n;
  85. }
  86. (void) fclose(fp);
  87. mg_printf(conn, "HTTP/1.0 200 OK\r\n\r\n"
  88. "Saved to [%s], written %llu bytes", path, cl);
  89. }
  90. }
  91. static void *callback(enum mg_event event, struct mg_connection *conn) {
  92. const struct mg_request_info *ri = mg_get_request_info(conn);
  93. if (event == MG_NEW_REQUEST) {
  94. if (!strcmp(ri->uri, "/handle_post_request")) {
  95. handle_file_upload(conn);
  96. } else {
  97. // Show HTML form.
  98. mg_printf(conn, "HTTP/1.0 200 OK\r\n"
  99. "Content-Length: %d\r\n"
  100. "Content-Type: text/html\r\n\r\n%s",
  101. (int) strlen(html_form), html_form);
  102. }
  103. // Mark as processed
  104. return "";
  105. } else {
  106. return NULL;
  107. }
  108. }
  109. int main(void) {
  110. struct mg_context *ctx;
  111. const char *options[] = {"listening_ports", "8080", NULL};
  112. ctx = mg_start(&callback, NULL, options);
  113. getchar(); // Wait until user hits "enter"
  114. mg_stop(ctx);
  115. return 0;
  116. }