forked from ericyanush/8Bit-Pic-Websockets
-
Notifications
You must be signed in to change notification settings - Fork 6
/
HTTP2.c
executable file
·1923 lines (1590 loc) · 67.9 KB
/
HTTP2.c
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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
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
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*********************************************************************
*
* HyperText Transfer Protocol (HTTP) Server
* Module for Microchip TCP/IP Stack
* -Serves dynamic pages to web browsers such as Microsoft Internet
* Explorer, Mozilla Firefox, etc.
* -Reference: RFC 2616
*
**********************************************************************
* FileName: HTTP2.c
* Dependencies: TCP, MPFS2, Tick, CustomHTTPApp.c callbacks
* Processor: PIC18, PIC24F, PIC24H, dsPIC30F, dsPIC33F, PIC32
* Compiler: Microchip C32 v1.05 or higher
* Microchip C30 v3.12 or higher
* Microchip C18 v3.30 or higher
* HI-TECH PICC-18 PRO 9.63PL2 or higher
* Company: Microchip Technology, Inc.
*
* Software License Agreement
*
* Copyright (C) 2002-2009 Microchip Technology Inc. All rights
* reserved.
*
* Microchip licenses to you the right to use, modify, copy, and
* distribute:
* (i) the Software when embedded on a Microchip microcontroller or
* digital signal controller product ("Device") which is
* integrated into Licensee's product; or
* (ii) ONLY the Software driver source files ENC28J60.c, ENC28J60.h,
* ENCX24J600.c and ENCX24J600.h ported to a non-Microchip device
* used in conjunction with a Microchip ethernet controller for
* the sole purpose of interfacing with the ethernet controller.
*
* You should refer to the license agreement accompanying this
* Software for additional information regarding your rights and
* obligations.
*
* THE SOFTWARE AND DOCUMENTATION ARE PROVIDED "AS IS" WITHOUT
* WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT
* LIMITATION, ANY WARRANTY OF MERCHANTABILITY, FITNESS FOR A
* PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT SHALL
* MICROCHIP BE LIABLE FOR ANY INCIDENTAL, SPECIAL, INDIRECT OR
* CONSEQUENTIAL DAMAGES, LOST PROFITS OR LOST DATA, COST OF
* PROCUREMENT OF SUBSTITUTE GOODS, TECHNOLOGY OR SERVICES, ANY CLAIMS
* BY THIRD PARTIES (INCLUDING BUT NOT LIMITED TO ANY DEFENSE
* THEREOF), ANY CLAIMS FOR INDEMNITY OR CONTRIBUTION, OR OTHER
* SIMILAR COSTS, WHETHER ASSERTED ON THE BASIS OF CONTRACT, TORT
* (INCLUDING NEGLIGENCE), BREACH OF WARRANTY, OR OTHERWISE.
*
*
* Author Date Comment
*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
* Nilesh Rajbharti 8/14/01 Original
* Elliott Wood 6/4/07 Complete rewrite, known as HTTP2
********************************************************************/
#define __HTTP2_C
#include "TCPIP Stack/TCPIP.h"
#if defined(STACK_USE_HTTP2_SERVER)
#include "HTTPPrint.h"
#if defined STACK_USE_WEBSOCKETS
#include "WebSocket.h"
int WebSocketEventRequest[MAX_HTTP_CONNECTIONS];
#endif
/****************************************************************************
Section:
String Constants
***************************************************************************/
static ROM BYTE HTTP_CRLF[] = "\r\n"; // New line sequence
#define HTTP_CRLF_LEN 2 // Length of above string
/****************************************************************************
Section:
File and Content Type Settings
***************************************************************************/
// File type extensions corresponding to HTTP_FILE_TYPE
static ROM char * ROM httpFileExtensions[HTTP_UNKNOWN+1] =
{
"txt", // HTTP_TXT
"htm", // HTTP_HTM
"html", // HTTP_HTML
"cgi", // HTTP_CGI
"xml", // HTTP_XML
"css", // HTTP_CSS
"gif", // HTTP_GIF
"png", // HTTP_PNG
"jpg", // HTTP_JPG
"cla", // HTTP_JAVA
"wav", // HTTP_WAV
"\0\0\0" // HTTP_UNKNOWN
};
// Content-type strings corresponding to HTTP_FILE_TYPE
static ROM char * ROM httpContentTypes[HTTP_UNKNOWN+1] =
{
"text/plain", // HTTP_TXT
"text/html", // HTTP_HTM
"text/html", // HTTP_HTML
"text/html", // HTTP_CGI
"text/xml", // HTTP_XML
"text/css", // HTTP_CSS
"image/gif", // HTTP_GIF
"image/png", // HTTP_PNG
"image/jpeg", // HTTP_JPG
"application/java-vm", // HTTP_JAVA
"audio/x-wave", // HTTP_WAV
"" // HTTP_UNKNOWN
};
/****************************************************************************
Section:
Commands and Server Responses
***************************************************************************/
// Initial response strings (Corresponding to HTTP_STATUS)
static ROM char * ROM HTTPResponseHeaders[] =
{
"HTTP/1.1 200 OK\r\nConnection: close\r\n",
#if defined (STACK_USE_WEBSOCKETS)
"HTTP/1.1 200 OK\r\nPLACEHOLDER:WEBSOCKETS\r\n",
#endif
"HTTP/1.1 200 OK\r\nConnection: close\r\n",
"HTTP/1.1 400 Bad Request\r\nConnection: close\r\n\r\n400 Bad Request: can't handle Content-Length\r\n",
"HTTP/1.1 401 Unauthorized\r\nWWW-Authenticate: Basic realm=\"Protected\"\r\nConnection: close\r\n\r\n401 Unauthorized: Password required\r\n",
#if defined(HTTP_MPFS_UPLOAD)
"HTTP/1.1 404 Not found\r\nConnection: close\r\nContent-Type: text/html\r\n\r\n404: File not found<br>Use <a href=\"/" HTTP_MPFS_UPLOAD "\">MPFS Upload</a> to program web pages\r\n",
#else
"HTTP/1.1 404 Not found\r\nConnection: close\r\n\r\n404: File not found\r\n",
#endif
"HTTP/1.1 414 Request-URI Too Long\r\nConnection: close\r\n\r\n414 Request-URI Too Long: Buffer overflow detected\r\n",
"HTTP/1.1 500 Internal Server Error\r\nConnection: close\r\n\r\n500 Internal Server Error: Expected data not present\r\n",
"HTTP/1.1 501 Not Implemented\r\nConnection: close\r\n\r\n501 Not Implemented: Only GET and POST supported\r\n",
#if defined(HTTP_MPFS_UPLOAD)
"HTTP/1.1 200 OK\r\nConnection: close\r\nContent-Type: text/html\r\n\r\n<html><body style=\"margin:100px\"><form method=post action=\"/" HTTP_MPFS_UPLOAD "\" enctype=\"multipart/form-data\"><b>MPFS Image Upload</b><p><input type=file name=i size=40> <input type=submit value=\"Upload\"></form></body></html>",
"",
"HTTP/1.1 200 OK\r\nConnection: close\r\nContent-Type: text/html\r\n\r\n<html><body style=\"margin:100px\"><b>MPFS Update Successful</b><p><a href=\"/\">Site main page</a></body></html>",
"HTTP/1.1 500 Internal Server Error\r\nConnection: close\r\nContent-Type: text/html\r\n\r\n<html><body style=\"margin:100px\"><b>MPFS Image Corrupt or Wrong Version</b><p><a href=\"/" HTTP_MPFS_UPLOAD "\">Try again?</a></body></html>",
#endif
"HTTP/1.1 302 Found\r\nConnection: close\r\nLocation: ",
"HTTP/1.1 403 Forbidden\r\nConnection: close\r\n\r\n403 Forbidden: SSL Required - use HTTPS\r\n"
};
/****************************************************************************
Section:
Header Parsing Configuration
***************************************************************************/
// Header strings for which we'd like to parse
static ROM char * ROM HTTPRequestHeaders[] =
{
"Cookie:",
"Authorization:",
"Content-Length:",
"Sec-WebSocket-Key:"
};
// Set to length of longest string above
#define HTTP_MAX_HEADER_LEN (18u)
/****************************************************************************
Section:
HTTP Connection State Global Variables
***************************************************************************/
#if defined(__18CXX) && !defined(HI_TECH_C)
#pragma udata HTTP_CONNECTION_STATES
#endif
#if defined(HTTP_SAVE_CONTEXT_IN_PIC_RAM)
HTTP_CONN HTTPControlBlocks[MAX_HTTP_CONNECTIONS];
#define HTTPLoadConn(a) do{curHTTPID = (a);}while(0)
#else
HTTP_CONN curHTTP; // Current HTTP connection state
static void HTTPLoadConn(BYTE hHTTP);
#endif
HTTP_STUB httpStubs[MAX_HTTP_CONNECTIONS]; // HTTP stubs with state machine and socket
BYTE curHTTPID; // ID of the currently loaded HTTP_CONN
#if defined(__18CXX) && !defined(HI_TECH_C)
#pragma udata
#endif
/****************************************************************************
Section:
Function Prototypes
***************************************************************************/
static void HTTPHeaderParseLookup(BYTE i);
#if defined(HTTP_USE_COOKIES)
static void HTTPHeaderParseCookie(void);
#endif
#if defined(HTTP_USE_AUTHENTICATION)
static void HTTPHeaderParseAuthorization(void);
#endif
#if defined(HTTP_USE_POST)
static void HTTPHeaderParseContentLength(void);
static HTTP_READ_STATUS HTTPReadTo(BYTE delim, BYTE* buf, WORD len);
#endif
#if defined (STACK_USE_WEBSOCKETS)
static void HTTPHeaderParseWebsocketKey(void);
#endif
static void HTTPProcess(void);
static BOOL HTTPSendFile(void);
#if defined(HTTP_MPFS_UPLOAD)
static HTTP_IO_RESULT HTTPMPFSUpload(void);
#endif
#define mMIN(a, b) ((a<b)?a:b)
#define smHTTP httpStubs[curHTTPID].sm // Access the current state machine
/*****************************************************************************
Function:
void HTTPInit(void)
Summary:
Initializes the HTTP server module.
Description:
Sets all HTTP sockets to the listening state, and initializes the
state machine and file handles for each connection. If SSL is
enabled, opens a socket on that port as well.
Precondition:
TCP must already be initialized.
Parameters:
None
Returns:
None
Remarks:
This function is called only one during lifetime of the application.
***************************************************************************/
void HTTPInit(void)
{
for(curHTTPID = 0; curHTTPID < MAX_HTTP_CONNECTIONS; curHTTPID++)
{
smHTTP = SM_HTTP_IDLE;
sktHTTP = TCPOpen(0, TCP_OPEN_SERVER, HTTP_PORT, TCP_PURPOSE_HTTP_SERVER);
#if defined(STACK_USE_SSL_SERVER)
TCPAddSSLListener(sktHTTP, HTTPS_PORT);
#endif
// Save the default record (just invalid file handles)
curHTTP.file = MPFS_INVALID_HANDLE;
curHTTP.offsets = MPFS_INVALID_HANDLE;
#if !defined(HTTP_SAVE_CONTEXT_IN_PIC_RAM)
{
PTR_BASE oldPtr;
oldPtr = MACSetWritePtr(BASE_HTTPB_ADDR + curHTTPID*sizeof(HTTP_CONN));
MACPutArray((BYTE*)&curHTTP, sizeof(HTTP_CONN));
MACSetWritePtr(oldPtr);
}
#endif
}
// Set curHTTPID to zero so that first call to HTTPLoadConn() doesn't write
// dummy data outside reserved HTTP memory.
curHTTPID = 0;
}
/*****************************************************************************
Function:
void HTTPServer(void)
Summary:
Performs periodic tasks for the HTTP2 module.
Description:
Browses through each open connection and attempts to process any
pending operations.
Precondition:
HTTPInit() must already be called.
Parameters:
None
Returns:
None
Remarks:
This function acts as a task (similar to one in an RTOS). It
performs its task in a co-operative manner, and the main application
must call this function repeatedly to ensure that all open or new
connections are served in a timely fashion.
***************************************************************************/
void HTTPServer(void)
{
BYTE conn;
for(conn = 0; conn < MAX_HTTP_CONNECTIONS; conn++)
{
if(httpStubs[conn].socket == INVALID_SOCKET)
continue;
// If a socket is disconnected at any time
// forget about it and return to idle state.
// Must do this here, otherwise we will wait until a new
// connection arrives, which causes problems with Linux and with SSL
if(TCPWasReset(httpStubs[conn].socket))
{
HTTPLoadConn(conn);
smHTTP = SM_HTTP_IDLE;
// Make sure any opened files are closed
if(curHTTP.file != MPFS_INVALID_HANDLE)
{
MPFSClose(curHTTP.file);
curHTTP.file = MPFS_INVALID_HANDLE;
}
if(curHTTP.offsets != MPFS_INVALID_HANDLE)
{
MPFSClose(curHTTP.offsets);
curHTTP.offsets = MPFS_INVALID_HANDLE;
}
// Adjust FIFO sizes to half and half. Default state must remain
// here so that SSL handshakes, if required, can proceed
TCPAdjustFIFOSize(sktHTTP, 1, 0, TCP_ADJUST_PRESERVE_RX);
}
// Determine if this connection is eligible for processing
if(httpStubs[conn].sm != SM_HTTP_IDLE || TCPIsGetReady(httpStubs[conn].socket))
{
HTTPLoadConn(conn);
HTTPProcess();
}
}
}
/*****************************************************************************
Function:
static void HTTPLoadConn(BYTE hHTTP)
Summary:
Switches the currently loaded connection for the HTTP2 module.
Description:
Saves the currently loaded HTTP connection back to Ethernet buffer
RAM, then loads the selected connection into curHTTP in local RAM
for processing.
Precondition:
None
Parameters:
hHTTP - the connection ID to load
Returns:
None
***************************************************************************/
#if !defined(HTTP_SAVE_CONTEXT_IN_PIC_RAM)
static void HTTPLoadConn(BYTE hHTTP)
{
WORD oldPtr;
// Return if already loaded
if(hHTTP == curHTTPID)
return;
// Save the old one
oldPtr = MACSetWritePtr(BASE_HTTPB_ADDR + curHTTPID*sizeof(HTTP_CONN));
MACPutArray((BYTE*)&curHTTP, sizeof(HTTP_CONN));
MACSetWritePtr(oldPtr);
// Load the new one
oldPtr = MACSetReadPtr(BASE_HTTPB_ADDR + hHTTP*sizeof(HTTP_CONN));
MACGetArray((BYTE*)&curHTTP, sizeof(HTTP_CONN));
MACSetReadPtr(oldPtr);
// Remember which one is loaded
curHTTPID = hHTTP;
}
#endif
/*****************************************************************************
Function:
static void HTTPProcess(void)
Description:
Performs any pending operations for the currently loaded HTTP connection.
Precondition:
HTTPInit() and HTTPLoadConn() have been called.
Parameters:
None
Returns:
None
*
***************************************************************************/
static void HTTPProcess(void) {
WORD lenA, lenB;
BYTE c, i;
BOOL isDone;
BYTE *ext;
BYTE buffer[HTTP_MAX_HEADER_LEN + 1];
do {
isDone = TRUE;
switch (smHTTP) {
case SM_HTTP_IDLE:
// Check how much data is waiting
lenA = TCPIsGetReady(sktHTTP);
// If a connection has been made, then process the request
if (lenA) {// Clear out state info and move to next state
curHTTP.ptrData = curHTTP.data;
smHTTP = SM_HTTP_PARSE_REQUEST;
curHTTP.isAuthorized = 0xff;
curHTTP.hasArgs = FALSE;
curHTTP.callbackID = TickGet() + HTTP_TIMEOUT*TICK_SECOND;
curHTTP.callbackPos = 0xffffffff;
curHTTP.byteCount = 0;
#if defined(HTTP_USE_POST)
curHTTP.smPost = 0x00;
#endif
#if defined (STACK_USE_WEBSOCKETS)
curHTTP.webSocketKey[0] = '\0';
#endif
// Adjust the TCP FIFOs for optimal reception of
// the next HTTP request from the browser
TCPAdjustFIFOSize(sktHTTP, 1, 0, TCP_ADJUST_PRESERVE_RX | TCP_ADJUST_GIVE_REST_TO_RX);
} else
// Don't break for new connections. There may be
// an entire request in the buffer already.
break;
case SM_HTTP_PARSE_REQUEST:
// Verify the entire first line is in the FIFO
if (TCPFind(sktHTTP, '\n', 0, FALSE) == 0xffff) {// First line isn't here yet
if (TCPGetRxFIFOFree(sktHTTP) == 0u) {// If the FIFO is full, we overflowed
curHTTP.httpStatus = HTTP_OVERFLOW;
smHTTP = SM_HTTP_SERVE_HEADERS;
isDone = FALSE;
}
if ((LONG) (TickGet() - curHTTP.callbackID) > (LONG) 0) {// A timeout has occurred
TCPDisconnect(sktHTTP);
smHTTP = SM_HTTP_DISCONNECT;
isDone = FALSE;
}
break;
}
// Reset the watchdog timer
curHTTP.callbackID = TickGet() + HTTP_TIMEOUT*TICK_SECOND;
// Determine the request method
lenA = TCPFind(sktHTTP, ' ', 0, FALSE);
if (lenA > 5u)
lenA = 5;
TCPGetArray(sktHTTP, curHTTP.data, lenA + 1);
if (memcmppgm2ram(curHTTP.data, (ROM void*) "GET", 3) == 0)
curHTTP.httpStatus = HTTP_GET;
#if defined(HTTP_USE_POST)
else if (memcmppgm2ram(curHTTP.data, (ROM void*) "POST", 4) == 0)
curHTTP.httpStatus = HTTP_POST;
#endif
else {// Unrecognized method, so return not implemented
curHTTP.httpStatus = HTTP_NOT_IMPLEMENTED;
smHTTP = SM_HTTP_SERVE_HEADERS;
isDone = FALSE;
break;
}
// Find end of filename
lenA = TCPFind(sktHTTP, ' ', 0, FALSE);
lenB = TCPFindEx(sktHTTP, '?', 0, lenA, FALSE);
lenA = mMIN(lenA, lenB);
// If the file name is too long, then reject the request
if (lenA > HTTP_MAX_DATA_LEN - HTTP_DEFAULT_LEN - 1) {
curHTTP.httpStatus = HTTP_OVERFLOW;
smHTTP = SM_HTTP_SERVE_HEADERS;
isDone = FALSE;
break;
}
// Read in the filename and decode
lenB = TCPGetArray(sktHTTP, curHTTP.data, lenA);
curHTTP.data[lenB] = '\0';
HTTPURLDecode(curHTTP.data);
// Decode may have changed the string length - update it here
lenB = strlen((char*) curHTTP.data);
// Check if this is an MPFS Upload
#if defined(HTTP_MPFS_UPLOAD)
if (memcmppgm2ram(&curHTTP.data[1], HTTP_MPFS_UPLOAD, sizeof (HTTP_MPFS_UPLOAD)) == 0) {// Read remainder of line, and bypass all file opening, etc.
#if defined(HTTP_USE_AUTHENTICATION)
curHTTP.isAuthorized = HTTPNeedsAuth(&curHTTP.data[1]);
#endif
if (curHTTP.httpStatus == HTTP_GET)
curHTTP.httpStatus = HTTP_MPFS_FORM;
else
curHTTP.httpStatus = HTTP_MPFS_UP;
smHTTP = SM_HTTP_PARSE_HEADERS;
isDone = FALSE;
break;
}
#endif
// If the last character is a not a directory delimiter, then try to open the file
// String starts at 2nd character, because the first is always a '/'
if (curHTTP.data[lenB - 1] != '/')
curHTTP.file = MPFSOpen(&curHTTP.data[1]);
// If the open fails, then add our default name and try again
if (curHTTP.file == MPFS_INVALID_HANDLE) {
// Add the directory delimiter if needed
if (curHTTP.data[lenB - 1] != '/')
curHTTP.data[lenB++] = '/';
// Add our default file name
#if defined(STACK_USE_SSL_SERVER)
if (TCPIsSSL(sktHTTP)) {
strcpypgm2ram((void*) &curHTTP.data[lenB], HTTPS_DEFAULT_FILE);
lenB += strlenpgm(HTTPS_DEFAULT_FILE);
} else
#endif
{
strcpypgm2ram((void*) &curHTTP.data[lenB], HTTP_DEFAULT_FILE);
lenB += strlenpgm(HTTP_DEFAULT_FILE);
}
// Try to open again
curHTTP.file = MPFSOpen(&curHTTP.data[1]);
}
// Find the extension in the filename
for (ext = curHTTP.data + lenB - 1; ext != curHTTP.data; ext--)
if (*ext == '.')
break;
// Compare to known extensions to determine Content-Type
ext++;
for (curHTTP.fileType = HTTP_TXT; curHTTP.fileType < HTTP_UNKNOWN; curHTTP.fileType++)
if (!stricmppgm2ram(ext, (ROM void*) httpFileExtensions[curHTTP.fileType]))
break;
// Perform first round authentication (pass file name only)
#if defined(HTTP_USE_AUTHENTICATION)
curHTTP.isAuthorized = HTTPNeedsAuth(&curHTTP.data[1]);
#endif
// If the file was found, see if it has an index
if (curHTTP.file != MPFS_INVALID_HANDLE &&
(MPFSGetFlags(curHTTP.file) & MPFS2_FLAG_HASINDEX)) {
curHTTP.offsets = MPFSOpenID(MPFSGetID(curHTTP.file) + 1);
}
// Read GET args, up to buffer size - 1
lenA = TCPFind(sktHTTP, ' ', 0, FALSE);
if (lenA != 0u) {
curHTTP.hasArgs = TRUE;
// Trash the '?'
TCPGet(sktHTTP, &c);
// Verify there's enough space
lenA--;
if (lenA >= HTTP_MAX_DATA_LEN - 2) {
curHTTP.httpStatus = HTTP_OVERFLOW;
smHTTP = SM_HTTP_SERVE_HEADERS;
isDone = FALSE;
break;
}
// Read in the arguments and '&'-terminate in anticipation of cookies
curHTTP.ptrData += TCPGetArray(sktHTTP, curHTTP.data, lenA);
*(curHTTP.ptrData++) = '&';
}
// Clear the rest of the line
lenA = TCPFind(sktHTTP, '\n', 0, FALSE);
TCPGetArray(sktHTTP, NULL, lenA + 1);
// Move to parsing the headers
smHTTP = SM_HTTP_PARSE_HEADERS;
// No break, continue to parsing headers
case SM_HTTP_PARSE_HEADERS:
// Loop over all the headers
while (1) {
// Make sure entire line is in the FIFO
lenA = TCPFind(sktHTTP, '\n', 0, FALSE);
if (lenA == 0xffff) {// If not, make sure we can receive more data
if (TCPGetRxFIFOFree(sktHTTP) == 0u) {// Overflow
curHTTP.httpStatus = HTTP_OVERFLOW;
smHTTP = SM_HTTP_SERVE_HEADERS;
isDone = FALSE;
}
if ((LONG) (TickGet() - curHTTP.callbackID) > (LONG) 0) {// A timeout has occured
TCPDisconnect(sktHTTP);
smHTTP = SM_HTTP_DISCONNECT;
isDone = FALSE;
}
break;
}
// Reset the watchdog timer
curHTTP.callbackID = TickGet() + HTTP_TIMEOUT*TICK_SECOND;
// If a CRLF is immediate, then headers are done
if (lenA == 1u) {// Remove the CRLF and move to next state
TCPGetArray(sktHTTP, NULL, 2);
smHTTP = SM_HTTP_AUTHENTICATE;
isDone = FALSE;
break;
}
// Find the header name, and use isDone as a flag to indicate a match
lenB = TCPFindEx(sktHTTP, ':', 0, lenA, FALSE) + 2;
isDone = FALSE;
// If name is too long or this line isn't a header, ignore it
if (lenB > sizeof (buffer)) {
TCPGetArray(sktHTTP, NULL, lenA + 1);
continue;
}
// Read in the header name
TCPGetArray(sktHTTP, buffer, lenB);
buffer[lenB - 1] = '\0';
lenA -= lenB;
// Compare header read to ones we're interested in
for (i = 0; i < sizeof (HTTPRequestHeaders) / sizeof (HTTPRequestHeaders[0]); i++) {
if (strcmppgm2ram((char*) buffer, (ROM char *) HTTPRequestHeaders[i]) == 0) {// Parse the header and stop the loop
HTTPHeaderParseLookup(i);
isDone = TRUE;
break;
}
}
// Clear the rest of the line, and call the loop again
if (isDone) {// We already know how much to remove unless a header was found
lenA = TCPFind(sktHTTP, '\n', 0, FALSE);
}
TCPGetArray(sktHTTP, NULL, lenA + 1);
}
break;
case SM_HTTP_AUTHENTICATE:
#if defined(HTTP_USE_AUTHENTICATION)
// Check current authorization state
if (curHTTP.isAuthorized < 0x80) {// 401 error
curHTTP.httpStatus = HTTP_UNAUTHORIZED;
smHTTP = SM_HTTP_SERVE_HEADERS;
isDone = FALSE;
#if defined(HTTP_NO_AUTH_WITHOUT_SSL)
if (!TCPIsSSL(sktHTTP))
curHTTP.httpStatus = HTTP_SSL_REQUIRED;
#endif
break;
}
#endif
// Parse the args string
*curHTTP.ptrData = '\0';
curHTTP.ptrData = HTTPURLDecode(curHTTP.data);
// If this is an MPFS upload form request, bypass to headers
#if defined(HTTP_MPFS_UPLOAD)
if (curHTTP.httpStatus == HTTP_MPFS_FORM) {
smHTTP = SM_HTTP_SERVE_HEADERS;
isDone = FALSE;
break;
}
#endif
// Move on to GET args, unless there are none
smHTTP = SM_HTTP_PROCESS_GET;
if (!curHTTP.hasArgs)
smHTTP = SM_HTTP_PROCESS_POST;
#if defined (STACK_USE_WEBSOCKETS)
if (curHTTP.webSocketKey[0] != '\0')
smHTTP = SM_HTTP_INIT_WEBSOCKET;
#endif
isDone = FALSE;
curHTTP.hasArgs = FALSE;
break;
case SM_HTTP_PROCESS_GET:
// Run the application callback HTTPExecuteGet()
if (HTTPExecuteGet() == HTTP_IO_WAITING) {// If waiting for asynchronous process, return to main app
break;
}
// Move on to POST data
smHTTP = SM_HTTP_PROCESS_POST;
#ifdef STACK_USE_WEBSOCKETS
case SM_HTTP_INIT_WEBSOCKET:
Nop();
if (!TCPIsConnected(sktHTTP)) Nop();
if (doHandShake(curHTTP.webSocketKey) == 0) {
smHTTP = SM_HTTP_PROC_WEBSOCKET;
}
break;
case SM_HTTP_PROC_WEBSOCKET:
Nop();
smHTTP = WebSocketProcess(smHTTP);
break;
#endif
case SM_HTTP_PROCESS_POST:
#if defined(HTTP_USE_POST)
// See if we have any new data
if (TCPIsGetReady(sktHTTP) == curHTTP.callbackPos) {
if ((LONG) (TickGet() - curHTTP.callbackID) > (LONG) 0) {// If a timeout has occured, disconnect
TCPDisconnect(sktHTTP);
smHTTP = SM_HTTP_DISCONNECT;
isDone = FALSE;
break;
}
}
if (curHTTP.httpStatus == HTTP_POST
#if defined(HTTP_MPFS_UPLOAD)
|| (curHTTP.httpStatus >= HTTP_MPFS_UP && curHTTP.httpStatus <= HTTP_MPFS_ERROR)
#endif
) {
// Run the application callback HTTPExecutePost()
#if defined(HTTP_MPFS_UPLOAD)
if (curHTTP.httpStatus >= HTTP_MPFS_UP && curHTTP.httpStatus <= HTTP_MPFS_ERROR) {
c = HTTPMPFSUpload();
if (c == (BYTE) HTTP_IO_DONE) {
smHTTP = SM_HTTP_SERVE_HEADERS;
isDone = FALSE;
break;
}
} else
#endif
c = HTTPExecutePost();
// If waiting for asynchronous process, return to main app
if (c == (BYTE) HTTP_IO_WAITING) {// return to main app and make sure we don't get stuck by the watchdog
curHTTP.callbackPos = TCPIsGetReady(sktHTTP) - 1;
break;
} else if (c == (BYTE) HTTP_IO_NEED_DATA) {// If waiting for more data
curHTTP.callbackPos = TCPIsGetReady(sktHTTP);
curHTTP.callbackID = TickGet() + HTTP_TIMEOUT*TICK_SECOND;
// If more is expected and space is available, return to main app
if (curHTTP.byteCount > curHTTP.callbackPos && TCPGetRxFIFOFree(sktHTTP) != 0u)
break;
// Handle cases where application ran out of data or buffer space
curHTTP.httpStatus = HTTP_INTERNAL_SERVER_ERROR;
smHTTP = SM_HTTP_SERVE_HEADERS;
isDone = FALSE;
break;
}
}
#endif
// We're done with POST
smHTTP = SM_HTTP_PROCESS_REQUEST;
// No break, continue to sending request
case SM_HTTP_PROCESS_REQUEST:
// Check for 404
if (curHTTP.file == MPFS_INVALID_HANDLE) {
curHTTP.httpStatus = HTTP_NOT_FOUND;
smHTTP = SM_HTTP_SERVE_HEADERS;
isDone = FALSE;
break;
}
// Set up the dynamic substitutions
curHTTP.byteCount = 0;
if (curHTTP.offsets == MPFS_INVALID_HANDLE) {// If no index file, then set next offset to huge
curHTTP.nextCallback = 0xffffffff;
} else {// Read in the next callback index
MPFSGetLong(curHTTP.offsets, &(curHTTP.nextCallback));
}
// Move to next state
smHTTP = SM_HTTP_SERVE_HEADERS;
case SM_HTTP_SERVE_HEADERS:
// We're in write mode now:
// Adjust the TCP FIFOs for optimal transmission of
// the HTTP response to the browser
TCPAdjustFIFOSize(sktHTTP, 1, 0, TCP_ADJUST_GIVE_REST_TO_TX);
// Send headers
TCPPutROMString(sktHTTP, (ROM BYTE*) HTTPResponseHeaders[curHTTP.httpStatus]);
// If this is a redirect, print the rest of the Location: header
if (curHTTP.httpStatus == HTTP_REDIRECT) {
TCPPutString(sktHTTP, curHTTP.data);
TCPPutROMString(sktHTTP, (ROM BYTE*) "\r\n\r\n304 Redirect: ");
TCPPutString(sktHTTP, curHTTP.data);
TCPPutROMString(sktHTTP, (ROM BYTE*) HTTP_CRLF);
}
// If not GET or POST, we're done
if (curHTTP.httpStatus != HTTP_GET && curHTTP.httpStatus != HTTP_POST) {// Disconnect
smHTTP = SM_HTTP_DISCONNECT;
break;
}
// Output the content type, if known
if (curHTTP.fileType != HTTP_UNKNOWN) {
TCPPutROMString(sktHTTP, (ROM BYTE*) "Content-Type: ");
TCPPutROMString(sktHTTP, (ROM BYTE*) httpContentTypes[curHTTP.fileType]);
TCPPutROMString(sktHTTP, HTTP_CRLF);
}
// Output the gzip encoding header if needed
if (MPFSGetFlags(curHTTP.file) & MPFS2_FLAG_ISZIPPED) {
TCPPutROMString(sktHTTP, (ROM BYTE*) "Content-Encoding: gzip\r\n");
}
// Output the cache-control
TCPPutROMString(sktHTTP, (ROM BYTE*) "Cache-Control: ");
if (curHTTP.httpStatus == HTTP_POST || curHTTP.nextCallback != 0xffffffff) {// This is a dynamic page or a POST request, so no cache
TCPPutROMString(sktHTTP, (ROM BYTE*) "no-cache");
} else {// This is a static page, so save it for the specified amount of time
TCPPutROMString(sktHTTP, (ROM BYTE*) "max-age=");
TCPPutROMString(sktHTTP, (ROM BYTE*) HTTP_CACHE_LEN);
}
TCPPutROMString(sktHTTP, HTTP_CRLF);
// Check if we should output cookies
if (curHTTP.hasArgs)
smHTTP = SM_HTTP_SERVE_COOKIES;
else {// Terminate the headers
TCPPutROMString(sktHTTP, HTTP_CRLF);
smHTTP = SM_HTTP_SERVE_BODY;
}
// Move to next stage
isDone = FALSE;
break;
case SM_HTTP_SERVE_COOKIES:
#if defined(HTTP_USE_COOKIES)
// If the TX FIFO runs out of space, the client will never get CRLFCRLF
// Avoid writing huge cookies - keep it under a hundred bytes max
// Write cookies one at a time as space permits
for (curHTTP.ptrRead = curHTTP.data; curHTTP.hasArgs != 0u; curHTTP.hasArgs--) {
// Write the header
TCPPutROMString(sktHTTP, (ROM BYTE*) "Set-Cookie: ");
// Write the name, URL encoded, one character at a time
while ((c = *(curHTTP.ptrRead++))) {
if (c == ' ')
TCPPut(sktHTTP, '+');
else if (c < '0' || (c > '9' && c < 'A') || (c > 'Z' && c < 'a') || c > 'z') {
TCPPut(sktHTTP, '%');
TCPPut(sktHTTP, btohexa_high(c));
TCPPut(sktHTTP, btohexa_low(c));
} else
TCPPut(sktHTTP, c);
}
TCPPut(sktHTTP, '=');
// Write the value, URL encoded, one character at a time
while ((c = *(curHTTP.ptrRead++))) {
if (c == ' ')
TCPPut(sktHTTP, '+');
else if (c < '0' || (c > '9' && c < 'A') || (c > 'Z' && c < 'a') || c > 'z') {
TCPPut(sktHTTP, '%');
TCPPut(sktHTTP, btohexa_high(c));
TCPPut(sktHTTP, btohexa_low(c));
} else
TCPPut(sktHTTP, c);
}
// Finish the line
TCPPutROMString(sktHTTP, HTTP_CRLF);
}
#endif
// We're done, move to next state
TCPPutROMString(sktHTTP, HTTP_CRLF);
smHTTP = SM_HTTP_SERVE_BODY;
case SM_HTTP_SERVE_BODY:
isDone = FALSE;
// Try to send next packet
if (HTTPSendFile()) {// If EOF, then we're done so close and disconnect
MPFSClose(curHTTP.file);
curHTTP.file = MPFS_INVALID_HANDLE;
smHTTP = SM_HTTP_DISCONNECT;
isDone = TRUE;
}
// If the TX FIFO is full, then return to main app loop
if (TCPIsPutReady(sktHTTP) == 0u)
isDone = TRUE;
break;
case SM_HTTP_SEND_FROM_CALLBACK:
isDone = TRUE;
// Check that at least the minimum bytes are free
if (TCPIsPutReady(sktHTTP) < HTTP_MIN_CALLBACK_FREE)
break;
// Fill TX FIFO from callback
HTTPPrint(curHTTP.callbackID);
if (curHTTP.callbackPos == 0u) {// Callback finished its output, so move on
isDone = FALSE;
smHTTP = SM_HTTP_SERVE_BODY;
}// Otherwise, callback needs more buffer space, so return and wait
break;
case SM_HTTP_DISCONNECT:
// Make sure any opened files are closed
if (curHTTP.file != MPFS_INVALID_HANDLE) {
MPFSClose(curHTTP.file);
curHTTP.file = MPFS_INVALID_HANDLE;
}
if (curHTTP.offsets != MPFS_INVALID_HANDLE) {
MPFSClose(curHTTP.offsets);
curHTTP.offsets = MPFS_INVALID_HANDLE;
}
TCPDisconnect(sktHTTP);
smHTTP = SM_HTTP_IDLE;
break;
}
} while (!isDone);
}
/*****************************************************************************
Function:
static BOOL HTTPSendFile(void)
Description:
Serves up the next chunk of curHTTP's file, up to a) available TX FIFO
space or b) the next callback index, whichever comes first.
Precondition:
curHTTP.file and curHTTP.offsets have both been opened for reading.
Parameters:
None
Return Values:
TRUE - the end of the file was reached and reading is done
FALSE - more data remains to be read
***************************************************************************/
static BOOL HTTPSendFile(void)
{
WORD numBytes, len;
BYTE c, data[64];
// Determine how many bytes we can read right now
len = TCPIsPutReady(sktHTTP);
numBytes = mMIN(len, curHTTP.nextCallback - curHTTP.byteCount);
// Get/put as many bytes as possible
curHTTP.byteCount += numBytes;
while(numBytes > 0u)