HTTPServerApp.c 8.8 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
34
35
36
37
38
39
40
41
42
43
/*
             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,
 *  this will serve out files to HTTP clients.
 */
 
#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.
 */
char PROGMEM HTTP200Header[] = "HTTP/1.1 200 OK\r\n"
                               "Server: LUFA RNDIS\r\n"
44
45
46
                               "Connection: close\r\n"
							   "MIME-version: 1.0\r\n"
							   "Content-Type: ";
47
48
49
50
51
52

/** 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.
 */
char PROGMEM HTTP404Header[] = "HTTP/1.1 404 Not Found\r\n"
                               "Server: LUFA RNDIS\r\n"
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
                               "Connection: close\r\n"
							   "MIME-version: 1.0\r\n"
							   "Content-Type: text/plain\r\n\r\n"
							   "Error 404: File Not Found";

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

/** List of MIME types for each supported file extension - must be terminated with \ref END_OF_MIME_LIST entry. */
MIME_Type_t PROGMEM MIMETypes[] =
	{
		{.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"},
		{.Extension = "exe", .MIMEType = "application/octet-stream"},
		{.Extension = "gz",  .MIMEType = "application/x-gzip"},
		{.Extension = "ico", .MIMEType = "image/x-icon"},
		{.Extension = "zip", .MIMEType = "application/zip"},
		{.Extension = "pdf", .MIMEType = "application/pdf"},
	};
75
76
77
78

/** FAT Fs structure to hold the internal state of the FAT driver for the dataflash contents. */
FATFS DiskFATState;

79

80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
/** Initialization function for the simple HTTP webserver. */
void WebserverApp_Init(void)
{
	/* 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.
 */
void WebserverApp_Callback(void)
{
	uip_tcp_appstate_t* const AppState    = &uip_conn->appstate;
	char*                     AppData     = (char*)uip_appdata;
	uint16_t                  AppDataSize = 0;

99
	if (uip_aborted() || uip_timedout() || uip_closed())
100
	{
101
102
103
104
105
106
		/* Check if the open file needs to be closed */
		if (AppState->FileOpen)
		{
			f_close(&AppState->FileHandle);
			AppState->FileOpen = false;
		}
107

108
		AppState->PrevState    = WEBSERVER_STATE_Closed;
109
110
		AppState->CurrentState = WEBSERVER_STATE_Closed;

111
112
113
114
115
		return;
	}
	else if (uip_connected())
	{
		/* New connection - initialize connection state and data pointer to the appropriate HTTP header */
116
		AppState->PrevState    = WEBSERVER_STATE_OpenRequestedFile;
117
118
		AppState->CurrentState = WEBSERVER_STATE_OpenRequestedFile;
	}
119
120
121
122
123
	else if (uip_rexmit())
	{
		/* Re-try last state */
		AppState->CurrentState = AppState->PrevState;
	}
124
125
126
127
128
	
	switch (AppState->CurrentState)
	{
		case WEBSERVER_STATE_OpenRequestedFile:
			/* Wait for the packet containing the request header */
129
			if (uip_newdata())
130
131
132
133
134
135
136
137
			{
				/* Must be a GET request, abort otherwise */
				if (strncmp(AppData, "GET ", (sizeof("GET ") - 1)) != 0)
				{
					uip_abort();
					break;
				}
		
138
139
				/* Copy over the requested filename from the GET request as all-lowercase */
				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
147
148
149
150
						break;
					}
				}
				
				/* Ensure requested filename is null-terminated */
151
				AppState->FileName[(sizeof(AppState->FileName) - 1)] = 0x00;
152
				
153
154
155
				/* If no filename specified, assume the default of index.htm */
				if (AppState->FileName[0] == 0x00)
				  strcpy(AppState->FileName, "index.htm");
156
157
				
				/* Try to open the file from the Dataflash disk */
158
159
				AppState->FileOpen       = (f_open(&AppState->FileHandle, AppState->FileName, FA_OPEN_EXISTING | FA_READ) == FR_OK);
				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
168
169
170
			/* Determine what HTTP header should be sent to the client */
			if (AppState->FileOpen)
			{
				AppDataSize = strlen_P(HTTP200Header);
171
				strncpy_P(AppData, HTTP200Header, AppDataSize);
172
173
174
175
			}
			else
			{
				AppDataSize = strlen_P(HTTP404Header);
176
				strncpy_P(AppData, HTTP404Header, AppDataSize);
177
178
179
180
			}
			
			uip_send(AppData, AppDataSize);
			
181
			AppState->PrevState    = WEBSERVER_STATE_SendResponseHeader;
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
			AppState->CurrentState = WEBSERVER_STATE_SendMIMETypeHeader;
			break;
		case WEBSERVER_STATE_SendMIMETypeHeader:
			/* File must have been found and opened for MIME header to be sent */
			if (AppState->FileOpen)
			{
				char* Extension = strpbrk(AppState->FileName, ".");
				
				/* Check to see if a file extension was found for the requested filename */
				if (Extension != NULL)
				{
					/* Look through the MIME type list, copy over the required MIME type if found */
					for (int i = 0; i < (sizeof(MIMETypes) / sizeof(MIMETypes[0])); i++)
					{
						if (strcmp_P(&Extension[1], MIMETypes[i].Extension) == 0)
						{
							AppDataSize = strlen_P(MIMETypes[i].MIMEType);
							strncpy_P(AppData, MIMETypes[i].MIMEType, AppDataSize);						
							break;
						}
					} 
				}

				/* Check if a MIME type was found and copied to the output buffer */
				if (!(AppDataSize))
				{
					/* MIME type not found - copy over the default MIME type */
					AppDataSize = strlen_P(DefaultMIMEType);
					strncpy_P(AppData, DefaultMIMEType, AppDataSize);				
				}
				
				/* Add the end-of line terminator and end-of-headers terminator after the MIME type */
				strncpy(&AppData[AppDataSize], "\r\n\r\n", sizeof("\r\n\r\n"));
				AppDataSize += (sizeof("\r\n\r\n") - 1);
				
				uip_send(AppData, AppDataSize);
			}
				
220
			AppState->PrevState    = WEBSERVER_STATE_SendMIMETypeHeader;
221
			AppState->CurrentState = WEBSERVER_STATE_SendData;				
222
223
224
			break;
		case WEBSERVER_STATE_SendData:
			/* 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
232
233
234
235
236
				AppState->CurrentState = WEBSERVER_STATE_Closed;
				break;
			}

			uint16_t MaxSegSize = uip_mss();
			
237
238
239
			/* Return file pointer to the last ACKed position if retransmitting */
			f_lseek(&AppState->FileHandle, AppState->CurrentFilePos);

240
			/* Read the next chunk of data from the open file */
241
242
			f_read(&AppState->FileHandle, AppData, MaxSegSize, &AppDataSize);
			AppState->FileOpen = (AppDataSize > 0);
243
244
245

			/* If data was read, send it to the client */
			if (AppDataSize)
246
247
248
249
250
251
252
253
254
255
			{
				/* If we are not re-transmitting a lost segment, advance file position */
				if (!(uip_rexmit()))
				  AppState->CurrentFilePos += AppDataSize;

				uip_send(AppData, AppDataSize);
			}
			
			AppState->PrevState = WEBSERVER_STATE_SendData;

256
257
258
			break;
	}
}