3 Copyright (C) Dean Camera, 2010.
5 dean [at] fourwalledcubicle [dot] com
6 www.fourwalledcubicle.com
10 Copyright 2010 Dean Camera (dean [at] fourwalledcubicle [dot] com)
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.
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
33 * Simple HTTP Webserver Application. When connected to the uIP stack,
34 * this will serve out files to HTTP clients on port 80.
37 #define INCLUDE_FROM_HTTPSERVERAPP_C
38 #include "HTTPServerApp.h"
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.
43 const char PROGMEM HTTP200Header
[] = "HTTP/1.1 200 OK\r\n"
44 "Server: LUFA " LUFA_VERSION_STRING
"\r\n"
45 "Connection: close\r\n"
46 "MIME-version: 1.0\r\n"
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.
52 const char PROGMEM HTTP404Header
[] = "HTTP/1.1 404 Not Found\r\n"
53 "Server: LUFA " LUFA_VERSION_STRING
"\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: /";
59 /** Default MIME type sent if no other MIME type can be determined. */
60 const char PROGMEM DefaultMIMEType
[] = "text/plain";
62 /** Default filename to fetch when a directory is requested */
63 const char PROGMEM DefaultDirFileName
[] = "index.htm";
65 /** List of MIME types for each supported file extension. */
66 const MIME_Type_t MIMETypes
[] =
68 {.Extension
= "htm", .MIMEType
= "text/html"},
69 {.Extension
= "jpg", .MIMEType
= "image/jpeg"},
70 {.Extension
= "gif", .MIMEType
= "image/gif"},
71 {.Extension
= "bmp", .MIMEType
= "image/bmp"},
72 {.Extension
= "png", .MIMEType
= "image/png"},
73 {.Extension
= "ico", .MIMEType
= "image/x-icon"},
74 {.Extension
= "exe", .MIMEType
= "application/octet-stream"},
75 {.Extension
= "gz", .MIMEType
= "application/x-gzip"},
76 {.Extension
= "zip", .MIMEType
= "application/zip"},
77 {.Extension
= "pdf", .MIMEType
= "application/pdf"},
80 /** FAT Fs structure to hold the internal state of the FAT driver for the dataflash contents. */
84 /** Initialization function for the simple HTTP webserver. */
85 void HTTPServerApp_Init(void)
87 /* Listen on port 80 for HTTP connections from hosts */
88 uip_listen(HTONS(HTTP_SERVER_PORT
));
90 /* Mount the dataflash disk via FatFS */
91 f_mount(0, &DiskFATState
);
94 /** uIP stack application callback for the simple HTTP webserver. This function must be called each time the
95 * TCP/IP stack needs a TCP packet to be processed.
97 void HTTPServerApp_Callback(void)
99 uip_tcp_appstate_t
* const AppState
= &uip_conn
->appstate
;
101 if (uip_aborted() || uip_timedout() || uip_closed())
103 /* Connection is being terminated for some reason - close file handle */
104 f_close(&AppState
->HTTPServer
.FileHandle
);
105 AppState
->HTTPServer
.FileOpen
= false;
107 /* Lock to the closed state so that no further processing will occur on the connection */
108 AppState
->HTTPServer
.CurrentState
= WEBSERVER_STATE_Closed
;
109 AppState
->HTTPServer
.NextState
= WEBSERVER_STATE_Closed
;
114 /* New connection - initialize connection state values */
115 AppState
->HTTPServer
.CurrentState
= WEBSERVER_STATE_OpenRequestedFile
;
116 AppState
->HTTPServer
.NextState
= WEBSERVER_STATE_OpenRequestedFile
;
117 AppState
->HTTPServer
.FileOpen
= false;
118 AppState
->HTTPServer
.ACKedFilePos
= 0;
119 AppState
->HTTPServer
.SentChunkSize
= 0;
124 /* Add the amount of ACKed file data to the total sent file bytes counter */
125 AppState
->HTTPServer
.ACKedFilePos
+= AppState
->HTTPServer
.SentChunkSize
;
127 /* Progress to the next state once the current state's data has been ACKed */
128 AppState
->HTTPServer
.CurrentState
= AppState
->HTTPServer
.NextState
;
133 /* Return file pointer to the last ACKed position */
134 f_lseek(&AppState
->HTTPServer
.FileHandle
, AppState
->HTTPServer
.ACKedFilePos
);
137 if (uip_rexmit() || uip_acked() || uip_newdata() || uip_connected() || uip_poll())
139 switch (AppState
->HTTPServer
.CurrentState
)
141 case WEBSERVER_STATE_OpenRequestedFile
:
142 HTTPServerApp_OpenRequestedFile();
144 case WEBSERVER_STATE_SendResponseHeader
:
145 HTTPServerApp_SendResponseHeader();
147 case WEBSERVER_STATE_SendData
:
148 HTTPServerApp_SendData();
150 case WEBSERVER_STATE_Closing
:
153 AppState
->HTTPServer
.NextState
= WEBSERVER_STATE_Closed
;
159 /** HTTP Server State handler for the Request Process state. This state manages the processing of incoming HTTP
160 * GET requests to the server from the receiving HTTP client.
162 static void HTTPServerApp_OpenRequestedFile(void)
164 uip_tcp_appstate_t
* const AppState
= &uip_conn
->appstate
;
165 char* const AppData
= (char*)uip_appdata
;
167 /* No HTTP header received from the client, abort processing */
168 if (!(uip_newdata()))
171 char* RequestToken
= strtok(AppData
, " ");
172 char* RequestedFileName
= strtok(NULL
, " ");
174 /* Must be a GET request, abort otherwise */
175 if (strcmp(RequestToken
, "GET") != 0)
181 /* Copy over the requested filename */
182 strncpy(AppState
->HTTPServer
.FileName
, &RequestedFileName
[1], (sizeof(AppState
->HTTPServer
.FileName
) - 1));
184 /* Ensure filename is null-terminated */
185 AppState
->HTTPServer
.FileName
[(sizeof(AppState
->HTTPServer
.FileName
) - 1)] = 0x00;
187 /* If the URI is a directory, append the default filename */
188 if (AppState
->HTTPServer
.FileName
[strlen(AppState
->HTTPServer
.FileName
) - 1] == '/')
190 strncpy_P(&AppState
->HTTPServer
.FileName
[strlen(AppState
->HTTPServer
.FileName
)], DefaultDirFileName
,
191 (sizeof(AppState
->HTTPServer
.FileName
) - (strlen(AppState
->HTTPServer
.FileName
) + 1)));
193 /* Ensure altered filename is still null-terminated */
194 AppState
->HTTPServer
.FileName
[(sizeof(AppState
->HTTPServer
.FileName
) - 1)] = 0x00;
197 /* Try to open the file from the Dataflash disk */
198 AppState
->HTTPServer
.FileOpen
= (f_open(&AppState
->HTTPServer
.FileHandle
, AppState
->HTTPServer
.FileName
,
199 (FA_OPEN_EXISTING
| FA_READ
)) == FR_OK
);
201 /* Lock to the SendResponseHeader state until connection terminated */
202 AppState
->HTTPServer
.CurrentState
= WEBSERVER_STATE_SendResponseHeader
;
203 AppState
->HTTPServer
.NextState
= WEBSERVER_STATE_SendResponseHeader
;
206 /** HTTP Server State handler for the HTTP Response Header Send state. This state manages the transmission of
207 * the HTTP response header to the receiving HTTP client.
209 static void HTTPServerApp_SendResponseHeader(void)
211 uip_tcp_appstate_t
* const AppState
= &uip_conn
->appstate
;
212 char* const AppData
= (char*)uip_appdata
;
214 char* Extension
= strpbrk(AppState
->HTTPServer
.FileName
, ".");
215 bool FoundMIMEType
= false;
217 /* If the file isn't already open, it wasn't found - send back a 404 error response and abort */
218 if (!(AppState
->HTTPServer
.FileOpen
))
220 /* Copy over the HTTP 404 response header and send it to the receiving client */
221 strcpy_P(AppData
, HTTP404Header
);
222 strcpy(&AppData
[strlen(AppData
)], AppState
->HTTPServer
.FileName
);
223 uip_send(AppData
, strlen(AppData
));
225 AppState
->HTTPServer
.NextState
= WEBSERVER_STATE_Closing
;
229 /* Copy over the HTTP 200 response header and send it to the receiving client */
230 strcpy_P(AppData
, HTTP200Header
);
232 /* Check to see if a MIME type for the requested file's extension was found */
233 if (Extension
!= NULL
)
235 /* Look through the MIME type list, copy over the required MIME type if found */
236 for (int i
= 0; i
< (sizeof(MIMETypes
) / sizeof(MIMETypes
[0])); i
++)
238 if (strcmp(&Extension
[1], MIMETypes
[i
].Extension
) == 0)
240 strcpy(&AppData
[strlen(AppData
)], MIMETypes
[i
].MIMEType
);
241 FoundMIMEType
= true;
247 /* Check if a MIME type was found and copied to the output buffer */
248 if (!(FoundMIMEType
))
250 /* MIME type not found - copy over the default MIME type */
251 strcpy_P(&AppData
[strlen(AppData
)], DefaultMIMEType
);
254 /* Add the end-of line terminator and end-of-headers terminator after the MIME type */
255 strcpy(&AppData
[strlen(AppData
)], "\r\n\r\n");
257 /* Send the MIME header to the receiving client */
258 uip_send(AppData
, strlen(AppData
));
260 /* When the MIME header is ACKed, progress to the data send stage */
261 AppState
->HTTPServer
.NextState
= WEBSERVER_STATE_SendData
;
264 /** HTTP Server State handler for the Data Send state. This state manages the transmission of file chunks
265 * to the receiving HTTP client.
267 static void HTTPServerApp_SendData(void)
269 uip_tcp_appstate_t
* const AppState
= &uip_conn
->appstate
;
270 char* const AppData
= (char*)uip_appdata
;
272 /* Get the maximum segment size for the current packet */
273 uint16_t MaxChunkSize
= uip_mss();
275 /* Read the next chunk of data from the open file */
276 f_read(&AppState
->HTTPServer
.FileHandle
, AppData
, MaxChunkSize
, &AppState
->HTTPServer
.SentChunkSize
);
278 /* Send the next file chunk to the receiving client */
279 uip_send(AppData
, AppState
->HTTPServer
.SentChunkSize
);
281 /* Check if we are at the last chunk of the file, if so next ACK should close the connection */
282 if (MaxChunkSize
!= AppState
->HTTPServer
.SentChunkSize
)
283 AppState
->HTTPServer
.NextState
= WEBSERVER_STATE_Closing
;