Add TCP retransmission support to the HTTP webserver in the Webserver project, so...
[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 #include "HTTPServerApp.h"
38
39 /** HTTP server response header, for transmission before the page contents. This indicates to the host that a page exists at the
40 * given location, and gives extra connection information.
41 */
42 char PROGMEM HTTP200Header[] = "HTTP/1.1 200 OK\r\n"
43 "Server: LUFA RNDIS\r\n"
44 "Connection: close\r\n"
45 "MIME-version: 1.0\r\n"
46 "Content-Type: ";
47
48 /** HTTP server response header, for transmission before a resource not found error. This indicates to the host that the given
49 * given URL is invalid, and gives extra error information.
50 */
51 char PROGMEM HTTP404Header[] = "HTTP/1.1 404 Not Found\r\n"
52 "Server: LUFA RNDIS\r\n"
53 "Connection: close\r\n"
54 "MIME-version: 1.0\r\n"
55 "Content-Type: text/plain\r\n\r\n"
56 "Error 404: File Not Found";
57
58 /** Default MIME type sent if no other MIME type can be determined */
59 char PROGMEM DefaultMIMEType[] = "text/plain";
60
61 /** List of MIME types for each supported file extension - must be terminated with \ref END_OF_MIME_LIST entry. */
62 MIME_Type_t PROGMEM MIMETypes[] =
63 {
64 {.Extension = "htm", .MIMEType = "text/html"},
65 {.Extension = "jpg", .MIMEType = "image/jpeg"},
66 {.Extension = "gif", .MIMEType = "image/gif"},
67 {.Extension = "bmp", .MIMEType = "image/bmp"},
68 {.Extension = "png", .MIMEType = "image/png"},
69 {.Extension = "exe", .MIMEType = "application/octet-stream"},
70 {.Extension = "gz", .MIMEType = "application/x-gzip"},
71 {.Extension = "ico", .MIMEType = "image/x-icon"},
72 {.Extension = "zip", .MIMEType = "application/zip"},
73 {.Extension = "pdf", .MIMEType = "application/pdf"},
74 };
75
76 /** FAT Fs structure to hold the internal state of the FAT driver for the dataflash contents. */
77 FATFS DiskFATState;
78
79
80 /** Initialization function for the simple HTTP webserver. */
81 void WebserverApp_Init(void)
82 {
83 /* Listen on port 80 for HTTP connections from hosts */
84 uip_listen(HTONS(HTTP_SERVER_PORT));
85
86 /* Mount the dataflash disk via FatFS */
87 f_mount(0, &DiskFATState);
88 }
89
90 /** uIP stack application callback for the simple HTTP webserver. This function must be called each time the
91 * TCP/IP stack needs a TCP packet to be processed.
92 */
93 void WebserverApp_Callback(void)
94 {
95 uip_tcp_appstate_t* const AppState = &uip_conn->appstate;
96 char* AppData = (char*)uip_appdata;
97 uint16_t AppDataSize = 0;
98
99 if (uip_aborted() || uip_timedout() || uip_closed())
100 {
101 /* Check if the open file needs to be closed */
102 if (AppState->FileOpen)
103 {
104 f_close(&AppState->FileHandle);
105 AppState->FileOpen = false;
106 }
107
108 AppState->PrevState = WEBSERVER_STATE_Closed;
109 AppState->CurrentState = WEBSERVER_STATE_Closed;
110
111 return;
112 }
113 else if (uip_connected())
114 {
115 /* New connection - initialize connection state and data pointer to the appropriate HTTP header */
116 AppState->PrevState = WEBSERVER_STATE_OpenRequestedFile;
117 AppState->CurrentState = WEBSERVER_STATE_OpenRequestedFile;
118 }
119 else if (uip_rexmit())
120 {
121 /* Re-try last state */
122 AppState->CurrentState = AppState->PrevState;
123 }
124
125 switch (AppState->CurrentState)
126 {
127 case WEBSERVER_STATE_OpenRequestedFile:
128 /* Wait for the packet containing the request header */
129 if (uip_newdata())
130 {
131 /* Must be a GET request, abort otherwise */
132 if (strncmp(AppData, "GET ", (sizeof("GET ") - 1)) != 0)
133 {
134 uip_abort();
135 break;
136 }
137
138 /* Copy over the requested filename from the GET request as all-lowercase */
139 for (uint8_t i = 0; i < (sizeof(AppState->FileName) - 1); i++)
140 {
141 AppState->FileName[i] = tolower(AppData[sizeof("GET ") + i]);
142
143 if (AppState->FileName[i] == ' ')
144 {
145 AppState->FileName[i] = 0x00;
146 break;
147 }
148 }
149
150 /* Ensure requested filename is null-terminated */
151 AppState->FileName[(sizeof(AppState->FileName) - 1)] = 0x00;
152
153 /* If no filename specified, assume the default of index.htm */
154 if (AppState->FileName[0] == 0x00)
155 strcpy(AppState->FileName, "index.htm");
156
157 /* Try to open the file from the Dataflash disk */
158 AppState->FileOpen = (f_open(&AppState->FileHandle, AppState->FileName, FA_OPEN_EXISTING | FA_READ) == FR_OK);
159 AppState->CurrentFilePos = 0;
160
161 AppState->PrevState = WEBSERVER_STATE_OpenRequestedFile;
162 AppState->CurrentState = WEBSERVER_STATE_SendResponseHeader;
163 }
164
165 break;
166 case WEBSERVER_STATE_SendResponseHeader:
167 /* Determine what HTTP header should be sent to the client */
168 if (AppState->FileOpen)
169 {
170 AppDataSize = strlen_P(HTTP200Header);
171 strncpy_P(AppData, HTTP200Header, AppDataSize);
172 }
173 else
174 {
175 AppDataSize = strlen_P(HTTP404Header);
176 strncpy_P(AppData, HTTP404Header, AppDataSize);
177 }
178
179 uip_send(AppData, AppDataSize);
180
181 AppState->PrevState = WEBSERVER_STATE_SendResponseHeader;
182 AppState->CurrentState = WEBSERVER_STATE_SendMIMETypeHeader;
183 break;
184 case WEBSERVER_STATE_SendMIMETypeHeader:
185 /* File must have been found and opened for MIME header to be sent */
186 if (AppState->FileOpen)
187 {
188 char* Extension = strpbrk(AppState->FileName, ".");
189
190 /* Check to see if a file extension was found for the requested filename */
191 if (Extension != NULL)
192 {
193 /* Look through the MIME type list, copy over the required MIME type if found */
194 for (int i = 0; i < (sizeof(MIMETypes) / sizeof(MIMETypes[0])); i++)
195 {
196 if (strcmp_P(&Extension[1], MIMETypes[i].Extension) == 0)
197 {
198 AppDataSize = strlen_P(MIMETypes[i].MIMEType);
199 strncpy_P(AppData, MIMETypes[i].MIMEType, AppDataSize);
200 break;
201 }
202 }
203 }
204
205 /* Check if a MIME type was found and copied to the output buffer */
206 if (!(AppDataSize))
207 {
208 /* MIME type not found - copy over the default MIME type */
209 AppDataSize = strlen_P(DefaultMIMEType);
210 strncpy_P(AppData, DefaultMIMEType, AppDataSize);
211 }
212
213 /* Add the end-of line terminator and end-of-headers terminator after the MIME type */
214 strncpy(&AppData[AppDataSize], "\r\n\r\n", sizeof("\r\n\r\n"));
215 AppDataSize += (sizeof("\r\n\r\n") - 1);
216
217 uip_send(AppData, AppDataSize);
218 }
219
220 AppState->PrevState = WEBSERVER_STATE_SendMIMETypeHeader;
221 AppState->CurrentState = WEBSERVER_STATE_SendData;
222 break;
223 case WEBSERVER_STATE_SendData:
224 /* If end of file/file not open, progress to the close state */
225 if (!(AppState->FileOpen) && !(uip_rexmit()))
226 {
227 f_close(&AppState->FileHandle);
228 uip_close();
229
230 AppState->PrevState = WEBSERVER_STATE_Closed;
231 AppState->CurrentState = WEBSERVER_STATE_Closed;
232 break;
233 }
234
235 uint16_t MaxSegSize = uip_mss();
236
237 /* Return file pointer to the last ACKed position if retransmitting */
238 f_lseek(&AppState->FileHandle, AppState->CurrentFilePos);
239
240 /* Read the next chunk of data from the open file */
241 f_read(&AppState->FileHandle, AppData, MaxSegSize, &AppDataSize);
242 AppState->FileOpen = (AppDataSize > 0);
243
244 /* If data was read, send it to the client */
245 if (AppDataSize)
246 {
247 /* If we are not re-transmitting a lost segment, advance file position */
248 if (!(uip_rexmit()))
249 AppState->CurrentFilePos += AppDataSize;
250
251 uip_send(AppData, AppDataSize);
252 }
253
254 AppState->PrevState = WEBSERVER_STATE_SendData;
255
256 break;
257 }
258 }