HTTPServerApp.c 11 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
/*
             LUFA Library
     Copyright (C) Dean Camera, 2010.
              
  dean [at] fourwalledcubicle [dot] com
      www.fourwalledcubicle.com
*/

/*
  Copyright 2010  Dean Camera (dean [at] fourwalledcubicle [dot] com)

  Permission to use, copy, modify, distribute, and sell this 
  software and its documentation for any purpose is hereby granted
  without fee, provided that the above copyright notice appear in 
  all copies and that both that the copyright notice and this
  permission notice and warranty disclaimer appear in supporting 
  documentation, and that the name of the author not be used in 
  advertising or publicity pertaining to distribution of the 
  software without specific, written prior permission.

  The author disclaim all warranties with regard to this
  software, including all implied warranties of merchantability
  and fitness.  In no event shall the author be liable for any
  special, indirect or consequential damages or any damages
  whatsoever resulting from loss of use, data or profits, whether
  in an action of contract, negligence or other tortious action,
  arising out of or in connection with the use or performance of
  this software.
*/

/** \file
 *
 *  Simple HTTP Webserver Application. When connected to the uIP stack,
34
 *  this will serve out files to HTTP clients on port 80.
35
36
 */
 
37
#define  INCLUDE_FROM_HTTPSERVERAPP_C
38
39
40
41
42
#include "HTTPServerApp.h"

/** HTTP server response header, for transmission before the page contents. This indicates to the host that a page exists at the
 *  given location, and gives extra connection information.
 */
43
44
45
46
47
const char PROGMEM HTTP200Header[] = "HTTP/1.1 200 OK\r\n"
                                     "Server: LUFA " LUFA_VERSION_STRING "\r\n"
                                     "Connection: close\r\n"
                                     "MIME-version: 1.0\r\n"
                                     "Content-Type: ";
48
49
50
51

/** HTTP server response header, for transmission before a resource not found error. This indicates to the host that the given
 *  given URL is invalid, and gives extra error information.
 */
52
53
54
55
56
const char PROGMEM HTTP404Header[] = "HTTP/1.1 404 Not Found\r\n"
                                     "Server: LUFA " LUFA_VERSION_STRING "\r\n"
                                     "Connection: close\r\n"
                                     "MIME-version: 1.0\r\n"
                                     "Content-Type: text/plain\r\n\r\n"
57
                                     "Error 404: File Not Found: /";
58

59
60
/** Default MIME type sent if no other MIME type can be determined. */
const char PROGMEM DefaultMIMEType[] = "text/plain";
61

62
63
64
/** Default filename to fetch when a directory is requested */
const char PROGMEM DefaultDirFileName[] = "index.htm";

65
/** List of MIME types for each supported file extension. */
66
const MIME_Type_t MIMETypes[] =
67
68
69
70
71
72
	{
		{.Extension = "htm", .MIMEType = "text/html"},
		{.Extension = "jpg", .MIMEType = "image/jpeg"},
		{.Extension = "gif", .MIMEType = "image/gif"},
		{.Extension = "bmp", .MIMEType = "image/bmp"},
		{.Extension = "png", .MIMEType = "image/png"},
73
		{.Extension = "ico", .MIMEType = "image/x-icon"},
74
75
76
77
78
		{.Extension = "exe", .MIMEType = "application/octet-stream"},
		{.Extension = "gz",  .MIMEType = "application/x-gzip"},
		{.Extension = "zip", .MIMEType = "application/zip"},
		{.Extension = "pdf", .MIMEType = "application/pdf"},
	};
79

80
/** FATFs structure to hold the internal state of the FAT driver for the dataflash contents. */
81
82
FATFS DiskFATState;

83

84
/** Initialization function for the simple HTTP webserver. */
85
void HTTPServerApp_Init(void)
86
87
88
89
90
91
92
93
94
95
96
{
	/* Listen on port 80 for HTTP connections from hosts */
	uip_listen(HTONS(HTTP_SERVER_PORT));
	
	/* Mount the dataflash disk via FatFS */
	f_mount(0, &DiskFATState);
}

/** uIP stack application callback for the simple HTTP webserver. This function must be called each time the
 *  TCP/IP stack needs a TCP packet to be processed.
 */
97
void HTTPServerApp_Callback(void)
98
{
99
	uip_tcp_appstate_t* const AppState = &uip_conn->appstate;
100

101
	if (uip_aborted() || uip_timedout() || uip_closed())
102
	{
103
		/* Lock to the closed state so that no further processing will occur on the connection */
Dean Camera's avatar
Dean Camera committed
104
105
		AppState->HTTPServer.CurrentState  = WEBSERVER_STATE_Closing;
		AppState->HTTPServer.NextState     = WEBSERVER_STATE_Closing;
106
	}
107
108

	if (uip_connected())
109
	{
110
		/* New connection - initialize connection state values */
111
112
113
114
115
		AppState->HTTPServer.CurrentState  = WEBSERVER_STATE_OpenRequestedFile;
		AppState->HTTPServer.NextState     = WEBSERVER_STATE_OpenRequestedFile;
		AppState->HTTPServer.FileOpen      = false;
		AppState->HTTPServer.ACKedFilePos  = 0;
		AppState->HTTPServer.SentChunkSize = 0;
116
	}
117
118

	if (uip_acked())
119
	{
120
		/* Add the amount of ACKed file data to the total sent file bytes counter */
121
		AppState->HTTPServer.ACKedFilePos += AppState->HTTPServer.SentChunkSize;
122
123

		/* Progress to the next state once the current state's data has been ACKed */
124
		AppState->HTTPServer.CurrentState = AppState->HTTPServer.NextState;
125
	}
126

127
128
129
130
131
132
	if (uip_rexmit())
	{
		/* Return file pointer to the last ACKed position */
		f_lseek(&AppState->HTTPServer.FileHandle, AppState->HTTPServer.ACKedFilePos);	
	}

133
	if (uip_rexmit() || uip_acked() || uip_newdata() || uip_connected() || uip_poll())
134
	{
135
		switch (AppState->HTTPServer.CurrentState)
136
137
		{
			case WEBSERVER_STATE_OpenRequestedFile:
138
				HTTPServerApp_OpenRequestedFile();
139
140
				break;
			case WEBSERVER_STATE_SendResponseHeader:
141
				HTTPServerApp_SendResponseHeader();
142
143
				break;
			case WEBSERVER_STATE_SendData:
144
				HTTPServerApp_SendData();
145
146
				break;
			case WEBSERVER_STATE_Closing:
Dean Camera's avatar
Dean Camera committed
147
148
149
150
151
				/* Connection is being terminated for some reason - close file handle */
				f_close(&AppState->HTTPServer.FileHandle);
				AppState->HTTPServer.FileOpen = false;
		
				/* If connection is not already closed, close it */
152
				uip_close();
153
				
Dean Camera's avatar
Dean Camera committed
154
155
				AppState->HTTPServer.CurrentState = WEBSERVER_STATE_Closed;
				AppState->HTTPServer.NextState    = WEBSERVER_STATE_Closed;
156
157
158
159
				break;
		}		  
	}		
}
160

161
/** HTTP Server State handler for the Request Process state. This state manages the processing of incoming HTTP
162
163
 *  GET requests to the server from the receiving HTTP client.
 */
164
static void HTTPServerApp_OpenRequestedFile(void)
165
166
{
	uip_tcp_appstate_t* const AppState    = &uip_conn->appstate;
167
	char*               const AppData     = (char*)uip_appdata;
168
169
170
171
172
	
	/* No HTTP header received from the client, abort processing */
	if (!(uip_newdata()))
	  return;
	  
173
	char* RequestToken      = strtok(AppData, " ");
174
	char* RequestedFileName = strtok(NULL, " ");
175
			
176
177
178
179
180
181
182
	/* Must be a GET request, abort otherwise */
	if (strcmp(RequestToken, "GET") != 0)
	{
		uip_abort();
		return;
	}
	
183
184
185
	/* Copy over the requested filename */
	strncpy(AppState->HTTPServer.FileName, &RequestedFileName[1], (sizeof(AppState->HTTPServer.FileName) - 1));
	
186
	/* Ensure filename is null-terminated */
187
188
189
190
	AppState->HTTPServer.FileName[sizeof(AppState->HTTPServer.FileName) - 1] = 0x00;
	
	/* Determine the length of the URI so that it can be checked to see if it is a directory */
	uint8_t FileNameLen = strlen(AppState->HTTPServer.FileName);
191
192

	/* If the URI is a directory, append the default filename */
193
	if (AppState->HTTPServer.FileName[FileNameLen - 1] == '/')
194
	{
195
196
		strncpy_P(&AppState->HTTPServer.FileName[FileNameLen], DefaultDirFileName,
		          (sizeof(AppState->HTTPServer.FileName) - FileNameLen));
197
198

		/* Ensure altered filename is still null-terminated */
199
		AppState->HTTPServer.FileName[sizeof(AppState->HTTPServer.FileName) - 1] = 0x00;
200
	}
201
202
	
	/* Try to open the file from the Dataflash disk */
203
204
	AppState->HTTPServer.FileOpen     = (f_open(&AppState->HTTPServer.FileHandle, AppState->HTTPServer.FileName,
	                                            (FA_OPEN_EXISTING | FA_READ)) == FR_OK);
205
206

	/* Lock to the SendResponseHeader state until connection terminated */
207
208
	AppState->HTTPServer.CurrentState = WEBSERVER_STATE_SendResponseHeader;
	AppState->HTTPServer.NextState    = WEBSERVER_STATE_SendResponseHeader;
209
210
211
212
213
}

/** HTTP Server State handler for the HTTP Response Header Send state. This state manages the transmission of
 *  the HTTP response header to the receiving HTTP client.
 */
214
static void HTTPServerApp_SendResponseHeader(void)
215
216
{
	uip_tcp_appstate_t* const AppState    = &uip_conn->appstate;
217
	char*               const AppData     = (char*)uip_appdata;
218

219
220
	char* Extension     = strpbrk(AppState->HTTPServer.FileName, ".");
	bool  FoundMIMEType = false;
221

222
223
	/* If the file isn't already open, it wasn't found - send back a 404 error response and abort */
	if (!(AppState->HTTPServer.FileOpen))
224
	{
225
226
227
228
229
		/* Copy over the HTTP 404 response header and send it to the receiving client */
		strcpy_P(AppData, HTTP404Header);
		strcpy(&AppData[strlen(AppData)], AppState->HTTPServer.FileName);		
		uip_send(AppData, strlen(AppData));
		
230
		AppState->HTTPServer.NextState = WEBSERVER_STATE_Closing;
231
		return;
232
	}
233
234
235
	
	/* Copy over the HTTP 200 response header and send it to the receiving client */
	strcpy_P(AppData, HTTP200Header);
236

237
	/* Check to see if a MIME type for the requested file's extension was found */
238
239
240
	if (Extension != NULL)
	{
		/* Look through the MIME type list, copy over the required MIME type if found */
241
		for (uint8_t i = 0; i < (sizeof(MIMETypes) / sizeof(MIMETypes[0])); i++)
242
		{
243
			if (strcmp(&Extension[1], MIMETypes[i].Extension) == 0)
244
			{
245
246
				strcpy(&AppData[strlen(AppData)], MIMETypes[i].MIMEType);						
				FoundMIMEType = true;
247
				break;
248
			}
249
250
		} 
	}
251

252
	/* Check if a MIME type was found and copied to the output buffer */
253
	if (!(FoundMIMEType))
254
255
	{
		/* MIME type not found - copy over the default MIME type */
256
		strcpy_P(&AppData[strlen(AppData)], DefaultMIMEType);
257
	}
258
	
259
	/* Add the end-of-line terminator and end-of-headers terminator after the MIME type */
260
	strcpy(&AppData[strlen(AppData)], "\r\n\r\n");
261
262
	
	/* Send the MIME header to the receiving client */
263
	uip_send(AppData, strlen(AppData));
264
265
	
	/* When the MIME header is ACKed, progress to the data send stage */
266
	AppState->HTTPServer.NextState = WEBSERVER_STATE_SendData;
267
}
268

269
270
271
/** HTTP Server State handler for the Data Send state. This state manages the transmission of file chunks
 *  to the receiving HTTP client.
 */
272
static void HTTPServerApp_SendData(void)
273
274
{
	uip_tcp_appstate_t* const AppState    = &uip_conn->appstate;
275
	char*               const AppData     = (char*)uip_appdata;
276

277
278
	/* Get the maximum segment size for the current packet */
	uint16_t MaxChunkSize = uip_mss();
279
280

	/* Read the next chunk of data from the open file */
281
	f_read(&AppState->HTTPServer.FileHandle, AppData, MaxChunkSize, &AppState->HTTPServer.SentChunkSize);
282
283
	
	/* Send the next file chunk to the receiving client */
284
	uip_send(AppData, AppState->HTTPServer.SentChunkSize);
285
286
			
	/* Check if we are at the last chunk of the file, if so next ACK should close the connection */
287
288
	if (MaxChunkSize != AppState->HTTPServer.SentChunkSize)
	  AppState->HTTPServer.NextState = WEBSERVER_STATE_Closing;
289
}