Keyboard firmwares for Atmel AVR and Cortex-M
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

HTTPServerApp.c 10KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284
  1. /*
  2. LUFA Library
  3. Copyright (C) Dean Camera, 2014.
  4. dean [at] fourwalledcubicle [dot] com
  5. www.lufa-lib.org
  6. */
  7. /*
  8. Copyright 2014 Dean Camera (dean [at] fourwalledcubicle [dot] com)
  9. Permission to use, copy, modify, distribute, and sell this
  10. software and its documentation for any purpose is hereby granted
  11. without fee, provided that the above copyright notice appear in
  12. all copies and that both that the copyright notice and this
  13. permission notice and warranty disclaimer appear in supporting
  14. documentation, and that the name of the author not be used in
  15. advertising or publicity pertaining to distribution of the
  16. software without specific, written prior permission.
  17. The author disclaims all warranties with regard to this
  18. software, including all implied warranties of merchantability
  19. and fitness. In no event shall the author be liable for any
  20. special, indirect or consequential damages or any damages
  21. whatsoever resulting from loss of use, data or profits, whether
  22. in an action of contract, negligence or other tortious action,
  23. arising out of or in connection with the use or performance of
  24. this software.
  25. */
  26. /** \file
  27. *
  28. * Simple HTTP Webserver Application. When connected to the uIP stack,
  29. * this will serve out files to HTTP clients on port 80.
  30. */
  31. #define INCLUDE_FROM_HTTPSERVERAPP_C
  32. #include "HTTPServerApp.h"
  33. /** HTTP server response header, for transmission before the page contents. This indicates to the host that a page exists at the
  34. * given location, and gives extra connection information.
  35. */
  36. const char PROGMEM HTTP200Header[] = "HTTP/1.1 200 OK\r\n"
  37. "Server: LUFA " LUFA_VERSION_STRING "\r\n"
  38. "Connection: close\r\n"
  39. "MIME-version: 1.0\r\n"
  40. "Content-Type: ";
  41. /** HTTP server response header, for transmission before a resource not found error. This indicates to the host that the given
  42. * URL is invalid, and gives extra error information.
  43. */
  44. const char PROGMEM HTTP404Header[] = "HTTP/1.1 404 Not Found\r\n"
  45. "Server: LUFA " LUFA_VERSION_STRING "\r\n"
  46. "Connection: close\r\n"
  47. "MIME-version: 1.0\r\n"
  48. "Content-Type: text/plain\r\n\r\n"
  49. "Error 404: File Not Found: /";
  50. /** Default filename to fetch when a directory is requested */
  51. const char PROGMEM DefaultDirFileName[] = "index.htm";
  52. /** Default MIME type sent if no other MIME type can be determined. */
  53. const char PROGMEM DefaultMIMEType[] = "text/plain";
  54. /** List of MIME types for each supported file extension. */
  55. const MIME_Type_t MIMETypes[] =
  56. {
  57. {.Extension = "htm", .MIMEType = "text/html"},
  58. {.Extension = "jpg", .MIMEType = "image/jpeg"},
  59. {.Extension = "gif", .MIMEType = "image/gif"},
  60. {.Extension = "bmp", .MIMEType = "image/bmp"},
  61. {.Extension = "png", .MIMEType = "image/png"},
  62. {.Extension = "ico", .MIMEType = "image/x-icon"},
  63. {.Extension = "exe", .MIMEType = "application/octet-stream"},
  64. {.Extension = "gz", .MIMEType = "application/x-gzip"},
  65. {.Extension = "zip", .MIMEType = "application/zip"},
  66. {.Extension = "pdf", .MIMEType = "application/pdf"},
  67. };
  68. /** FATFs structure to hold the internal state of the FAT driver for the Dataflash contents. */
  69. FATFS DiskFATState;
  70. /** Initialization function for the simple HTTP webserver. */
  71. void HTTPServerApp_Init(void)
  72. {
  73. /* Listen on port 80 for HTTP connections from hosts */
  74. uip_listen(HTONS(HTTP_SERVER_PORT));
  75. /* Mount the Dataflash disk via FatFS */
  76. f_mount(0, &DiskFATState);
  77. }
  78. /** uIP stack application callback for the simple HTTP webserver. This function must be called each time the
  79. * TCP/IP stack needs a TCP packet to be processed.
  80. */
  81. void HTTPServerApp_Callback(void)
  82. {
  83. uip_tcp_appstate_t* const AppState = &uip_conn->appstate;
  84. if (uip_aborted() || uip_timedout() || uip_closed())
  85. {
  86. /* Lock to the closed state so that no further processing will occur on the connection */
  87. AppState->HTTPServer.CurrentState = WEBSERVER_STATE_Closing;
  88. AppState->HTTPServer.NextState = WEBSERVER_STATE_Closing;
  89. }
  90. if (uip_connected())
  91. {
  92. /* New connection - initialize connection state values */
  93. AppState->HTTPServer.CurrentState = WEBSERVER_STATE_OpenRequestedFile;
  94. AppState->HTTPServer.NextState = WEBSERVER_STATE_OpenRequestedFile;
  95. AppState->HTTPServer.FileOpen = false;
  96. AppState->HTTPServer.ACKedFilePos = 0;
  97. AppState->HTTPServer.SentChunkSize = 0;
  98. }
  99. if (uip_acked())
  100. {
  101. /* Add the amount of ACKed file data to the total sent file bytes counter */
  102. AppState->HTTPServer.ACKedFilePos += AppState->HTTPServer.SentChunkSize;
  103. /* Progress to the next state once the current state's data has been ACKed */
  104. AppState->HTTPServer.CurrentState = AppState->HTTPServer.NextState;
  105. }
  106. if (uip_rexmit())
  107. {
  108. /* Return file pointer to the last ACKed position */
  109. f_lseek(&AppState->HTTPServer.FileHandle, AppState->HTTPServer.ACKedFilePos);
  110. }
  111. if (uip_rexmit() || uip_acked() || uip_newdata() || uip_connected() || uip_poll())
  112. {
  113. switch (AppState->HTTPServer.CurrentState)
  114. {
  115. case WEBSERVER_STATE_OpenRequestedFile:
  116. HTTPServerApp_OpenRequestedFile();
  117. break;
  118. case WEBSERVER_STATE_SendResponseHeader:
  119. HTTPServerApp_SendResponseHeader();
  120. break;
  121. case WEBSERVER_STATE_SendData:
  122. HTTPServerApp_SendData();
  123. break;
  124. case WEBSERVER_STATE_Closing:
  125. /* Connection is being terminated for some reason - close file handle */
  126. f_close(&AppState->HTTPServer.FileHandle);
  127. AppState->HTTPServer.FileOpen = false;
  128. /* If connection is not already closed, close it */
  129. uip_close();
  130. AppState->HTTPServer.CurrentState = WEBSERVER_STATE_Closed;
  131. AppState->HTTPServer.NextState = WEBSERVER_STATE_Closed;
  132. break;
  133. }
  134. }
  135. }
  136. /** HTTP Server State handler for the Request Process state. This state manages the processing of incoming HTTP
  137. * GET requests to the server from the receiving HTTP client.
  138. */
  139. static void HTTPServerApp_OpenRequestedFile(void)
  140. {
  141. uip_tcp_appstate_t* const AppState = &uip_conn->appstate;
  142. char* const AppData = (char*)uip_appdata;
  143. /* No HTTP header received from the client, abort processing */
  144. if (!(uip_newdata()))
  145. return;
  146. char* RequestToken = strtok(AppData, " ");
  147. char* RequestedFileName = strtok(NULL, " ");
  148. /* Must be a GET request, abort otherwise */
  149. if (strcmp_P(RequestToken, PSTR("GET")) != 0)
  150. {
  151. uip_abort();
  152. return;
  153. }
  154. /* Copy over the requested filename */
  155. strlcpy(AppState->HTTPServer.FileName, &RequestedFileName[1], sizeof(AppState->HTTPServer.FileName));
  156. /* Determine the length of the URI so that it can be checked to see if it is a directory */
  157. uint8_t FileNameLen = strlen(AppState->HTTPServer.FileName);
  158. /* If the URI is a directory, append the default filename */
  159. if ((AppState->HTTPServer.FileName[FileNameLen - 1] == '/') || !(FileNameLen))
  160. {
  161. strlcpy_P(&AppState->HTTPServer.FileName[FileNameLen], DefaultDirFileName,
  162. (sizeof(AppState->HTTPServer.FileName) - FileNameLen));
  163. }
  164. /* Try to open the file from the Dataflash disk */
  165. AppState->HTTPServer.FileOpen = (f_open(&AppState->HTTPServer.FileHandle, AppState->HTTPServer.FileName,
  166. (FA_OPEN_EXISTING | FA_READ)) == FR_OK);
  167. /* Lock to the SendResponseHeader state until connection terminated */
  168. AppState->HTTPServer.CurrentState = WEBSERVER_STATE_SendResponseHeader;
  169. AppState->HTTPServer.NextState = WEBSERVER_STATE_SendResponseHeader;
  170. }
  171. /** HTTP Server State handler for the HTTP Response Header Send state. This state manages the transmission of
  172. * the HTTP response header to the receiving HTTP client.
  173. */
  174. static void HTTPServerApp_SendResponseHeader(void)
  175. {
  176. uip_tcp_appstate_t* const AppState = &uip_conn->appstate;
  177. char* const AppData = (char*)uip_appdata;
  178. char* Extension = strpbrk(AppState->HTTPServer.FileName, ".");
  179. bool FoundMIMEType = false;
  180. /* If the file isn't already open, it wasn't found - send back a 404 error response and abort */
  181. if (!(AppState->HTTPServer.FileOpen))
  182. {
  183. /* Copy over the HTTP 404 response header and send it to the receiving client */
  184. strcpy_P(AppData, HTTP404Header);
  185. strcat(AppData, AppState->HTTPServer.FileName);
  186. uip_send(AppData, strlen(AppData));
  187. AppState->HTTPServer.NextState = WEBSERVER_STATE_Closing;
  188. return;
  189. }
  190. /* Copy over the HTTP 200 response header and send it to the receiving client */
  191. strcpy_P(AppData, HTTP200Header);
  192. /* Check to see if a MIME type for the requested file's extension was found */
  193. if (Extension != NULL)
  194. {
  195. /* Look through the MIME type list, copy over the required MIME type if found */
  196. for (uint8_t i = 0; i < (sizeof(MIMETypes) / sizeof(MIMETypes[0])); i++)
  197. {
  198. if (strcmp(&Extension[1], MIMETypes[i].Extension) == 0)
  199. {
  200. strcat(AppData, MIMETypes[i].MIMEType);
  201. FoundMIMEType = true;
  202. break;
  203. }
  204. }
  205. }
  206. /* Check if a MIME type was found and copied to the output buffer */
  207. if (!(FoundMIMEType))
  208. {
  209. /* MIME type not found - copy over the default MIME type */
  210. strcat_P(AppData, DefaultMIMEType);
  211. }
  212. /* Add the end-of-line terminator and end-of-headers terminator after the MIME type */
  213. strcat_P(AppData, PSTR("\r\n\r\n"));
  214. /* Send the MIME header to the receiving client */
  215. uip_send(AppData, strlen(AppData));
  216. /* When the MIME header is ACKed, progress to the data send stage */
  217. AppState->HTTPServer.NextState = WEBSERVER_STATE_SendData;
  218. }
  219. /** HTTP Server State handler for the Data Send state. This state manages the transmission of file chunks
  220. * to the receiving HTTP client.
  221. */
  222. static void HTTPServerApp_SendData(void)
  223. {
  224. uip_tcp_appstate_t* const AppState = &uip_conn->appstate;
  225. char* const AppData = (char*)uip_appdata;
  226. /* Get the maximum segment size for the current packet */
  227. uint16_t MaxChunkSize = uip_mss();
  228. /* Read the next chunk of data from the open file */
  229. f_read(&AppState->HTTPServer.FileHandle, AppData, MaxChunkSize, &AppState->HTTPServer.SentChunkSize);
  230. /* Send the next file chunk to the receiving client */
  231. uip_send(AppData, AppState->HTTPServer.SentChunkSize);
  232. /* Check if we are at the last chunk of the file, if so next ACK should close the connection */
  233. if (MaxChunkSize != AppState->HTTPServer.SentChunkSize)
  234. AppState->HTTPServer.NextState = WEBSERVER_STATE_Closing;
  235. }