upload.c 4.5 KB

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