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