forked from basvk/PIC-Websockets
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhttp.c
2690 lines (2244 loc) · 96.1 KB
/
http.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
Summary:
Module for Microchip TCP/IP Stack
Description:
- Serves dynamic pages to web browsers such as Microsoft Internet
Explorer, Mozilla Firefox, etc.
- Reference: RFC 2616
*******************************************************************************/
/*******************************************************************************
File Name: HTTP.c
Copyright © 2012 released Microchip Technology Inc. All rights
reserved.
Microchip licenses to you the right to use, modify, copy and distribute
Software only when embedded on a Microchip microcontroller or digital signal
controller that is integrated into your product or third party product
(pursuant to the sublicense terms in the accompanying license agreement).
You should refer to the license agreement accompanying this Software for
additional information regarding your rights and obligations.
SOFTWARE AND DOCUMENTATION ARE PROVIDED “AS IS” WITHOUT WARRANTY OF ANY KIND,
EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION, ANY WARRANTY OF
MERCHANTABILITY, TITLE, NON-INFRINGEMENT AND FITNESS FOR A PARTICULAR PURPOSE.
IN NO EVENT SHALL MICROCHIP OR ITS LICENSORS BE LIABLE OR OBLIGATED UNDER
CONTRACT, NEGLIGENCE, STRICT LIABILITY, CONTRIBUTION, BREACH OF WARRANTY, OR
OTHER LEGAL EQUITABLE THEORY ANY DIRECT OR INDIRECT DAMAGES OR EXPENSES
INCLUDING BUT NOT LIMITED TO ANY INCIDENTAL, SPECIAL, INDIRECT, PUNITIVE OR
CONSEQUENTIAL DAMAGES, LOST PROFITS OR LOST DATA, COST OF PROCUREMENT OF
SUBSTITUTE GOODS, TECHNOLOGY, SERVICES, OR ANY CLAIMS BY THIRD PARTIES
(INCLUDING BUT NOT LIMITED TO ANY DEFENSE THEREOF), OR OTHER SIMILAR COSTS.
*******************************************************************************/
#define TCPIP_THIS_MODULE_ID TCPIP_MODULE_HTTP_SERVER
#include "tcpip/src/tcpip_private.h"
#define NVM_DRIVER_V080_WORKAROUND
#if defined(TCPIP_STACK_USE_HTTP_SERVER)
#define HTTP_SEND_DATABUF_SIZE 256
#define HTTP_INC_DATABUF_SIZE 256
#if defined (NVM_DRIVER_V080_WORKAROUND)
#define MPFS_UPLOAD_DISK_NO 0
#endif
#define MPFS_SIGNATURE "MPFS\x02\x01"
// size of the MPFS upload operation write buffer
#define MPFS_UPLOAD_WRITE_BUFFER_SIZE (4 * 1024)
#include "tcpip/src/common/sys_fs_wrapper.h"
#include "http_private.h"
#if defined TCPIP_HTTP_USE_WEBSOCKETS
#include "WebSocket.h"
//uint16_t WebSocketEventRequest[TCPIP_HTTP_MAX_CONNECTIONS];
#endif
extern void TCPIP_HTTP_Print(HTTP_CONN_HANDLE connHandle,uint32_t callbackID);
#define SYS_FS_ATTR_ZIP_COMPRESSED ((uint16_t)0x0001)
//#define HTTP_FILE_ERR_DEBUG
/****************************************************************************
Section:
String Constants
***************************************************************************/
static const uint8_t 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 const char * const httpFileExtensions[HTTP_UNKNOWN+2] =
{
"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
"js", // HTTP_JS
"cla", // HTTP_JAVA
"wav", // HTTP_WAV
"svg", // HTTP_SVG
"\0\0\0" // HTTP_UNKNOWN
};
// Content-type strings corresponding to HTTP_FILE_TYPE
static const char * const httpContentTypes[HTTP_UNKNOWN+2] =
{
"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/x-javascript", // HTTP_JS
"application/java-vm", // HTTP_JAVA
"audio/x-wave", // HTTP_WAV
"image/svg+xml", // HTTP_SVG
"" // HTTP_UNKNOWN
};
/****************************************************************************
Section:
Commands and Server Responses
***************************************************************************/
// Initial response strings (Corresponding to HTTP_STATUS)
static const char * const HTTPResponseHeaders[] =
{
"HTTP/1.1 200 OK\r\nConnection: close\r\n",
#if defined (TCPIP_HTTP_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(TCPIP_HTTP_FILE_UPLOAD_ENABLE)
"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=\"/" TCPIP_HTTP_FILE_UPLOAD_NAME "\">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",
"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",
#if defined(TCPIP_HTTP_FILE_UPLOAD_ENABLE)
"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=\"/" TCPIP_HTTP_FILE_UPLOAD_NAME "\" 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=\"/" TCPIP_HTTP_FILE_UPLOAD_NAME "\">Try again?</a></body></html>",
#endif
};
/****************************************************************************
Section:
Header Parsing Configuration
***************************************************************************/
// Header strings for which we'd like to parse
static const char * const HTTPRequestHeaders[] =
{
"Cookie:",
"Authorization:",
"Content-Length:",
"Sec-WebSocket-Key:"
};
/****************************************************************************
Section:
HTTP Connection State Global Variables
***************************************************************************/
static HTTP_CONN* httpConnCtrl = 0; // all http connections
static uint8_t* httpConnData = 0; // http connections data space
static uint16_t httpConnDataSize = 0; // associated data size
static int httpConnNo = 0; // number of HTTP connections
static int httpInitCount = 0; // module init counter
static HTTP_MODULE_FLAGS httpConfigFlags = 0; // run time flags
static tcpipSignalHandle httpSignalHandle = 0;
/****************************************************************************
Section:
Function Prototypes
***************************************************************************/
static void _HTTP_HeaderParseLookup(HTTP_CONN* pHttpCon, int i);
#if defined(TCPIP_HTTP_USE_COOKIES)
static void _HTTP_HeaderParseCookie(HTTP_CONN* pHttpCon);
#endif
#if defined(TCPIP_HTTP_USE_AUTHENTICATION)
static void _HTTP_HeaderParseAuthorization(HTTP_CONN* pHttpCon);
#endif
#if defined(TCPIP_HTTP_USE_POST)
static void _HTTP_HeaderParseContentLength(HTTP_CONN* pHttpCon);
static HTTP_READ_STATUS _HTTP_ReadTo(HTTP_CONN* pHttpCon, uint8_t delim, uint8_t* buf, uint16_t len);
#endif
#if defined (TCPIP_HTTP_USE_WEBSOCKETS)
static void _HTTP_HeaderParseWebsocketKey(HTTP_CONN* pHttpCon);
#endif
static void TCPIP_HTTP_Process(void);
static void TCPIP_HTTP_ProcessConnection(HTTP_CONN* pHttpCon);
static bool TCPIP_HTTP_FileSend(HTTP_CONN* pHttpCon);
static bool TCPIP_HTTP_WebPageIsDynamic(HTTP_CONN* pHttpCon);
static void _HTTPSocketRxSignalHandler(TCP_SOCKET hTCP, TCPIP_NET_HANDLE hNet, TCPIP_TCP_SIGNAL_TYPE sigType, const void* param);
#if (TCPIP_STACK_DOWN_OPERATION != 0)
static void _HTTP_Cleanup(const TCPIP_STACK_MODULE_CTRL* const stackCtrl);
static void _HTTP_CloseConnections(TCPIP_NET_IF* pNetIf);
#else
#define _HTTP_Cleanup(stackCtrl)
#endif // (TCPIP_STACK_DOWN_OPERATION != 0)
#if defined(TCPIP_HTTP_FILE_UPLOAD_ENABLE) && !defined(DRV_WIFI_OTA_ENABLE)
static HTTP_IO_RESULT TCPIP_HTTP_MPFSUpload(HTTP_CONN* pHttpCon);
#endif
#define mMIN(a, b) ((a<b)?a:b)
static int8_t fileErr = 0;
static void _HTTP_FileRdCheck(int condt, char *file, int32_t line)
{
if (condt == 0) {
#if defined(HTTP_FILE_ERR_DEBUG)
SYS_CONSOLE_PRINT("%s, at line: %d\r\n", file, line);
#endif
fileErr = 1;
//while(1);
}
}
// if pNetIf == 0, all connections are closed, stack is going down
#if (TCPIP_STACK_DOWN_OPERATION != 0)
static void _HTTP_CloseConnections(TCPIP_NET_IF* pNetIf)
{
HTTP_CONN* pHttpCon;
int connIx;
pHttpCon = httpConnCtrl + 0;
for (connIx = 0; connIx < httpConnNo; connIx++)
{
// Close the connections that were associated with this interface
if (pHttpCon->socket != INVALID_SOCKET)
{
if (pNetIf == 0 || TCPIP_TCP_SocketNetGet(pHttpCon->socket) == pNetIf)
{
if(pHttpCon->file != SYS_FS_HANDLE_INVALID)
{
SYS_FS_FileClose(pHttpCon->file);
pHttpCon->file = SYS_FS_HANDLE_INVALID;
}
if(pNetIf == 0)
{ // stack going down
if(pHttpCon->socketSignal != 0)
{
TCPIP_TCP_SignalHandlerDeregister(pHttpCon->socket, pHttpCon->socketSignal);
}
TCPIP_TCP_Close(pHttpCon->socket);
pHttpCon->socket = INVALID_SOCKET;
}
else
{ // TCPIP_STACK_ACTION_IF_DOWN - interface down
TCPIP_TCP_Disconnect(pHttpCon->socket);
}
}
}
pHttpCon++;
}
}
static void _HTTP_Cleanup(const TCPIP_STACK_MODULE_CTRL* const stackCtrl)
{
if(httpConnData && httpConnCtrl)
{
_HTTP_CloseConnections(0);
}
if(httpConnData)
{
TCPIP_HEAP_Free(stackCtrl->memH, httpConnData);
httpConnData = 0;
}
if(httpConnCtrl)
{
TCPIP_HEAP_Free(stackCtrl->memH, httpConnCtrl);
httpConnCtrl = 0;
}
if(httpSignalHandle)
{
_TCPIPStackSignalHandlerDeregister(httpSignalHandle);
httpSignalHandle = 0;
}
httpConnNo = 0;
}
#endif // (TCPIP_STACK_DOWN_OPERATION != 0)
/*****************************************************************************
Function:
bool TCPIP_HTTP_Initialize(const TCPIP_STACK_MODULE_CTRL* const stackCtrl,
const TCPIP_HTTP_MODULE_CONFIG* httpInitData)
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.
Precondition:
TCP must already be initialized.
Parameters:
None
Returns:
true if initialization succeeded,
false otherwise
Remarks:
This function is called only one during lifetime of the application.
***************************************************************************/
bool TCPIP_HTTP_Initialize(const TCPIP_STACK_MODULE_CTRL* const stackCtrl,
const TCPIP_HTTP_MODULE_CONFIG* httpInitData)
{
bool initFail;
int connIx, nConns;
HTTP_CONN* pHttpCon;
uint8_t* pHttpData;
if(stackCtrl->stackAction == TCPIP_STACK_ACTION_IF_UP)
{ // interface restart
return true;
}
// stack init
initFail = false;
while(httpInitCount == 0)
{ // first time we're run
if(httpInitData == 0 || httpInitData->nConnections == 0)
{
return false;
}
nConns = httpInitData->nConnections;
httpConfigFlags = httpInitData->configFlags;
httpConnCtrl = (HTTP_CONN*)TCPIP_HEAP_Calloc(stackCtrl->memH, nConns, sizeof(*httpConnCtrl));
httpConnData = (uint8_t*)TCPIP_HEAP_Malloc(stackCtrl->memH, nConns * httpInitData->dataLen);
if(httpConnCtrl == 0 || httpConnData == 0)
{ // failed
SYS_ERROR(SYS_ERROR_ERROR, " HTTP: Dynamic allocation failed");
initFail = true;
break;
}
// create the HTTP timer
httpSignalHandle =_TCPIPStackSignalHandlerRegister(TCPIP_THIS_MODULE_ID, TCPIP_HTTP_Task, TCPIP_HTTP_TASK_RATE);
if(httpSignalHandle == 0)
{ // cannot create the HTTP timer
initFail = true;
break;
}
// initialize all connections
httpConnDataSize = httpInitData->dataLen;
pHttpCon = httpConnCtrl + 0;
for(connIx = 0; connIx < nConns; connIx++, pHttpCon++)
{
pHttpCon->socket = INVALID_SOCKET;
pHttpCon->file = SYS_FS_HANDLE_INVALID;
}
httpConnNo = nConns;
pHttpCon = httpConnCtrl + 0;
pHttpData = httpConnData;
for(connIx = 0; connIx < nConns; connIx++)
{
pHttpCon->sm = SM_HTTP_IDLE;
pHttpCon->socket = TCPIP_TCP_ServerOpen(IP_ADDRESS_TYPE_ANY, TCPIP_HTTP_SERVER_PORT, 0);
if( pHttpCon->socket == INVALID_SOCKET)
{ // failed to open the socket
SYS_ERROR(SYS_ERROR_ERROR, " HTTP: Socket creation failed");
initFail = true;
break;
}
#if (TCPIP_TCP_DYNAMIC_OPTIONS != 0)
// set socket options
if((httpConfigFlags & HTTP_MODULE_FLAG_NO_DELAY) != 0)
{
void* tcpForceFlush = (void*)1;
TCPIP_TCP_OptionsSet(pHttpCon->socket, TCP_OPTION_NODELAY, tcpForceFlush);
}
if(httpInitData->sktTxBuffSize != 0)
{
void* tcpBuffSize = (void*)(unsigned int)httpInitData->sktTxBuffSize;
TCPIP_TCP_OptionsSet(pHttpCon->socket, TCP_OPTION_TX_BUFF, tcpBuffSize);
}
if(httpInitData->sktRxBuffSize != 0)
{
void* tcpBuffSize = (void*)(unsigned int)httpInitData->sktRxBuffSize;
TCPIP_TCP_OptionsSet(pHttpCon->socket, TCP_OPTION_RX_BUFF, tcpBuffSize);
}
#endif // (TCPIP_TCP_DYNAMIC_OPTIONS != 0)
pHttpCon->socketSignal = TCPIP_TCP_SignalHandlerRegister(pHttpCon->socket, TCPIP_TCP_SIGNAL_RX_DATA, _HTTPSocketRxSignalHandler, 0);
if(pHttpCon->socketSignal == 0)
{
SYS_ERROR(SYS_ERROR_ERROR, " HTTP: Signal creation failed");
initFail = true;
break;
}
pHttpCon->data = pHttpData;
pHttpCon->connIx = (uint16_t)connIx;
pHttpCon++;
pHttpData += httpInitData->dataLen;
}
break;
}
if(initFail)
{
_HTTP_Cleanup(stackCtrl);
return false;
}
httpInitCount++;
return true;
}
/*****************************************************************************
Function:
bool TCPIP_HTTP_Deinitialize(void)
Summary:
DeInitializes the HTTP server module.
Description:
Takes down all HTTP sockets, the state machine and file handles for
each connection.
Precondition:
None
Parameters:
None
Returns:
None
Remarks:
This function is called only one during lifetime of the application.
***************************************************************************/
#if (TCPIP_STACK_DOWN_OPERATION != 0)
void TCPIP_HTTP_Deinitialize(const TCPIP_STACK_MODULE_CTRL* const stackCtrl)
{
// if(stackCtrl->stackAction == TCPIP_STACK_ACTION_DEINIT) // stack shut down
// if(stackCtrl->stackAction == TCPIP_STACK_ACTION_IF_DOWN) // interface down
// one way or another this interface is going down
if(httpInitCount > 0)
{ // we're up and running
_HTTP_CloseConnections(stackCtrl->pNetIf);
if(stackCtrl->stackAction == TCPIP_STACK_ACTION_DEINIT)
{ // stack shut down
if(--httpInitCount == 0)
{ // all closed
// release resources
_HTTP_Cleanup(stackCtrl);
}
}
}
}
#endif // (TCPIP_STACK_DOWN_OPERATION != 0)
void TCPIP_HTTP_Task(void)
{
TCPIP_MODULE_SIGNAL sigPend;
sigPend = _TCPIPStackModuleSignalGet(TCPIP_THIS_MODULE_ID, TCPIP_MODULE_SIGNAL_MASK_ALL);
if(sigPend != 0)
{ // some signal occurred
TCPIP_HTTP_Process();
}
}
// send a signal to the HTTP module that data is available
// no manager alert needed since this normally results as a higher layer (TCP) signal
static void _HTTPSocketRxSignalHandler(TCP_SOCKET hTCP, TCPIP_NET_HANDLE hNet, TCPIP_TCP_SIGNAL_TYPE sigType, const void* param)
{
if(sigType == TCPIP_TCP_SIGNAL_RX_DATA)
{
_TCPIPStackModuleSignalRequest(TCPIP_THIS_MODULE_ID, TCPIP_MODULE_SIGNAL_RX_PENDING, true);
}
}
static void TCPIP_HTTP_Process(void)
{
HTTP_CONN* pHttpCon;
int conn;
pHttpCon = httpConnCtrl + 0;
for(conn = 0; conn < httpConnNo; conn++, pHttpCon++)
{
if(pHttpCon->socket == INVALID_SOCKET)
continue;
// If a socket is disconnected at any time
// forget about it and return to idle state.
if(TCPIP_TCP_WasReset(pHttpCon->socket))
{
pHttpCon->sm = SM_HTTP_IDLE;
pHttpCon->file_sm = SM_IDLE;
// Make sure any opened files are closed
if(pHttpCon->file != SYS_FS_HANDLE_INVALID)
{
SYS_FS_FileClose(pHttpCon->file);
pHttpCon->file = SYS_FS_HANDLE_INVALID;
// Important to clear related control variables,
// or serving continuous refresh(F5) by IE etc... will meet issue
memset((void *)&pHttpCon->TxFile, 0, sizeof(FILE_CTRL));
}
#if (TCPIP_TCP_DYNAMIC_OPTIONS != 0)
if((httpConfigFlags & HTTP_MODULE_FLAG_ADJUST_SKT_FIFOS) != 0)
{
// Adjust FIFO sizes to half and half.
TCPIP_TCP_FifoSizeAdjust(pHttpCon->socket, 1, 0, TCP_ADJUST_PRESERVE_RX);
}
#endif // (TCPIP_TCP_DYNAMIC_OPTIONS != 0)
}
// Determine if this connection is eligible for processing
if(pHttpCon->sm != SM_HTTP_IDLE || TCPIP_TCP_GetIsReady(pHttpCon->socket))
{
TCPIP_HTTP_ProcessConnection(pHttpCon);
}
}
}
/*****************************************************************************
Function:
static void TCPIP_HTTP_ProcessConnection(HTTP_CONN* pHttpCon)
Description:
Performs any pending operations for the currently loaded HTTP connection.
Precondition:
TCPIP_HTTP_Initialize() has been called.
Parameters:
None
Returns:
None
***************************************************************************/
static void TCPIP_HTTP_ProcessConnection(HTTP_CONN* pHttpCon)
{
uint16_t lenA, lenB;
int i;
uint8_t c;
bool isDone;
uint8_t * ptr = NULL;
uint8_t *ext;
uint8_t buffer[TCPIP_HTTP_MAX_HEADER_LEN+1];
SYS_FS_FSTAT fs_attr = {0};
do
{
isDone = true;
switch(pHttpCon->sm)
{
case SM_HTTP_IDLE:
// Check how much data is waiting
lenA = TCPIP_TCP_GetIsReady(pHttpCon->socket);
// If a connection has been made, then process the request
if(lenA)
{// Clear out state info and move to next state
pHttpCon->ptrData = pHttpCon->data;
pHttpCon->sm = SM_HTTP_PARSE_REQUEST;
pHttpCon->isAuthorized = 0xff;
pHttpCon->hasArgs = 0;
pHttpCon->httpTick = SYS_TMR_TickCountGet() + TCPIP_HTTP_TIMEOUT * SYS_TMR_TickCounterFrequencyGet();
pHttpCon->callbackPos = 0xffffffff;
pHttpCon->byteCount = 0;
pHttpCon->nameHash = 0;
#if defined(TCPIP_HTTP_USE_POST)
pHttpCon->smPost = 0x00;
#endif
#if defined (TCPIP_HTTP_USE_WEBSOCKETS)
pHttpCon->webSocketKey[0] = '\0';
pHttpCon->subscriptions = 0;
#endif
pHttpCon->TxFile.fileTxDone = 0;
#if (TCPIP_TCP_DYNAMIC_OPTIONS != 0)
if((httpConfigFlags & HTTP_MODULE_FLAG_ADJUST_SKT_FIFOS) != 0)
{
// Adjust the TCP FIFOs for optimal reception of
// the next HTTP request from the browser
TCPIP_TCP_FifoSizeAdjust(pHttpCon->socket, 1, 0, TCP_ADJUST_PRESERVE_RX | TCP_ADJUST_GIVE_REST_TO_RX);
}
#endif // (TCPIP_TCP_DYNAMIC_OPTIONS != 0)
}
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(TCPIP_TCP_Find(pHttpCon->socket, '\n', 0, 0, false) == 0xffff)
{// First line isn't here yet
if(TCPIP_TCP_FifoRxFreeGet(pHttpCon->socket) == 0u)
{// If the FIFO is full, we overflowed
pHttpCon->httpStatus = HTTP_OVERFLOW;
pHttpCon->sm = SM_HTTP_SERVE_HEADERS;
isDone = false;
}
if((int32_t)(SYS_TMR_TickCountGet() - pHttpCon->httpTick) > 0)
{// A timeout has occurred
TCPIP_TCP_Disconnect(pHttpCon->socket);
pHttpCon->sm = SM_HTTP_DISCONNECT;
isDone = false;
}
break;
}
// Reset the watchdog timer
pHttpCon->httpTick = SYS_TMR_TickCountGet() + TCPIP_HTTP_TIMEOUT * SYS_TMR_TickCounterFrequencyGet();
// Determine the request method
lenA = TCPIP_TCP_Find(pHttpCon->socket, ' ', 0, 0, false);
if(lenA > 5u)
lenA = 5;
TCPIP_TCP_ArrayGet(pHttpCon->socket, pHttpCon->data, lenA+1);
if ( memcmp(pHttpCon->data, (const void*)"GET", 3) == 0)
pHttpCon->httpStatus = HTTP_GET;
#if defined(TCPIP_HTTP_USE_POST)
else if ( memcmp(pHttpCon->data, (const void*)"POST", 4) == 0)
pHttpCon->httpStatus = HTTP_POST;
#endif
else
{// Unrecognized method, so return not implemented
pHttpCon->httpStatus = HTTP_NOT_IMPLEMENTED;
pHttpCon->sm = SM_HTTP_SERVE_HEADERS;
isDone = false;
break;
}
// Find end of filename
lenA = TCPIP_TCP_Find(pHttpCon->socket, ' ', 0, 0, false);
lenB = TCPIP_TCP_Find(pHttpCon->socket, '?', 0, lenA, false);
lenA = mMIN(lenA, lenB);
// If the file name is too long, then reject the request
if(lenA > httpConnDataSize - TCPIP_HTTP_DEFAULT_LEN - 1)
{
pHttpCon->httpStatus = HTTP_OVERFLOW;
pHttpCon->sm = SM_HTTP_SERVE_HEADERS;
isDone = false;
break;
}
// Read in the filename and decode
lenB = TCPIP_TCP_ArrayGet(pHttpCon->socket, pHttpCon->data, lenA);
pHttpCon->data[lenB] = '\0';
TCPIP_HTTP_URLDecode(pHttpCon->data);
// Decode may have changed the string length - update it here
lenB = strlen((char*)pHttpCon->data);
// Check if this is an MPFS Upload
#if defined(TCPIP_HTTP_FILE_UPLOAD_ENABLE)
if(memcmp(&pHttpCon->data[1], TCPIP_HTTP_FILE_UPLOAD_NAME, sizeof(TCPIP_HTTP_FILE_UPLOAD_NAME)) == 0)
{// Read remainder of line, and bypass all file opening, etc.
#if defined(TCPIP_HTTP_USE_AUTHENTICATION)
pHttpCon->isAuthorized = TCPIP_HTTP_FileAuthenticate(pHttpCon, &pHttpCon->data[1]);
#endif
if(pHttpCon->httpStatus == HTTP_GET)
pHttpCon->httpStatus = HTTP_MPFS_FORM;
else
pHttpCon->httpStatus = HTTP_MPFS_UP;
pHttpCon->sm = 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(pHttpCon->data[lenB-1] != '/') {
pHttpCon->file = SYS_FS_FileOpen_Wrapper((char *)&pHttpCon->data[1], SYS_FS_FILE_OPEN_READ);
if(strlen((char*)pHttpCon->data + 1) > sizeof(pHttpCon->fileName))
{
SYS_ERROR(SYS_ERROR_WARNING, " HTTP: URL exceeds allocated space!");
}
strncpy(pHttpCon->fileName, (char*)pHttpCon->data + 1, sizeof(pHttpCon->fileName));
}
// If the open fails, then add our default name and try again
if(pHttpCon->file == SYS_FS_HANDLE_INVALID)
{
// Add the directory delimiter if needed
if(pHttpCon->data[lenB-1] != '/')
pHttpCon->data[lenB++] = '/';
// Add our default file name
strncpy((char*)pHttpCon->data + lenB, TCPIP_HTTP_DEFAULT_FILE, httpConnDataSize - lenB);
lenB += strlen(TCPIP_HTTP_DEFAULT_FILE);
// Try to open again
pHttpCon->file = SYS_FS_FileOpen_Wrapper((char *)&pHttpCon->data[1],SYS_FS_FILE_OPEN_READ);
strncpy(pHttpCon->fileName, (char*)pHttpCon->data + 1, sizeof(pHttpCon->fileName));
}
//Calculate 2 Bytes HashIndex for pHttpCon->file->name
// Calculate the name hash to speed up searching
for(pHttpCon->nameHash = 0, ptr = (uint8_t*)(&pHttpCon->data[1]); ptr !=(uint8_t*) (&pHttpCon->data[lenB]); ptr++)
{
if(*ptr != 0x20)
{
pHttpCon->nameHash += *ptr;
pHttpCon->nameHash <<= 1;
}
}
// Find the extension in the filename
for(ext = pHttpCon->data + lenB-1; ext != pHttpCon->data; ext--)
if(*ext == '.')
break;
// Compare to known extensions to determine Content-Type
ext++;
for(pHttpCon->fileType = HTTP_TXT; pHttpCon->fileType < HTTP_UNKNOWN; pHttpCon->fileType++)
if(!strcmp((char *)ext, (const void*)httpFileExtensions[pHttpCon->fileType]))
break;
// Perform first round authentication (pass file name only)
#if defined(TCPIP_HTTP_USE_AUTHENTICATION)
pHttpCon->isAuthorized = TCPIP_HTTP_FileAuthenticate(pHttpCon, &pHttpCon->data[1]);
#endif
// If the file was found, see if it has an index
// Index file is not needed any more, because of FileRcrd.bin and DynRcrd.bin used
// Read GET args, up to buffer size - 1
lenA = TCPIP_TCP_Find(pHttpCon->socket, ' ', 0, 0, false);
if(lenA != 0)
{
pHttpCon->hasArgs = 1;
// Trash the '?'
TCPIP_TCP_Get(pHttpCon->socket, &c);
// Verify there's enough space
lenA--;
if(lenA >= httpConnDataSize - 2)
{
pHttpCon->httpStatus = HTTP_OVERFLOW;
pHttpCon->sm = SM_HTTP_SERVE_HEADERS;
isDone = false;
break;
}
// Read in the arguments and '&'-terminate in anticipation of cookies
pHttpCon->ptrData += TCPIP_TCP_ArrayGet(pHttpCon->socket, pHttpCon->data, lenA);
*(pHttpCon->ptrData++) = '&';
}
// Clear the rest of the line
lenA = TCPIP_TCP_Find(pHttpCon->socket, '\n', 0, 0, false);
TCPIP_TCP_ArrayGet(pHttpCon->socket, NULL, lenA + 1);
// Move to parsing the headers
pHttpCon->sm = 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 = TCPIP_TCP_Find(pHttpCon->socket, '\n', 0, 0, false);
if(lenA == 0xffff)
{// If not, make sure we can receive more data
if(TCPIP_TCP_FifoRxFreeGet(pHttpCon->socket) == 0u)
{// Overflow
pHttpCon->httpStatus = HTTP_OVERFLOW;
pHttpCon->sm = SM_HTTP_SERVE_HEADERS;
isDone = false;
}
if((int32_t)(SYS_TMR_TickCountGet() - pHttpCon->httpTick) > 0)
{// A timeout has occured
TCPIP_TCP_Disconnect(pHttpCon->socket);
pHttpCon->sm = SM_HTTP_DISCONNECT;
isDone = false;
}
break;
}
// Reset the watchdog timer
pHttpCon->httpTick = SYS_TMR_TickCountGet() + TCPIP_HTTP_TIMEOUT * SYS_TMR_TickCounterFrequencyGet();
// If a CRLF is immediate, then headers are done
if(lenA == 1u)
{// Remove the CRLF and move to next state
TCPIP_TCP_ArrayGet(pHttpCon->socket, NULL, 2);
pHttpCon->sm = SM_HTTP_AUTHENTICATE;
isDone = false;
break;
}
// Find the header name, and use isDone as a flag to indicate a match
lenB = TCPIP_TCP_Find(pHttpCon->socket, ':', 0, lenA, false) + 2;
isDone = false;
// If name is too long or this line isn't a header, ignore it
if(lenB > sizeof(buffer))
{
TCPIP_TCP_ArrayGet(pHttpCon->socket, NULL, lenA+1);
continue;
}
// Read in the header name
TCPIP_TCP_ArrayGet(pHttpCon->socket, 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(strcmp((char*)buffer, (const char *)HTTPRequestHeaders[i]) == 0)
{// Parse the header and stop the loop
_HTTP_HeaderParseLookup(pHttpCon, 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 = TCPIP_TCP_Find(pHttpCon->socket, '\n', 0, 0, false);
}
TCPIP_TCP_ArrayGet(pHttpCon->socket, NULL, lenA+1);
}
break;
case SM_HTTP_AUTHENTICATE:
#if defined(TCPIP_HTTP_USE_AUTHENTICATION)
// Check current authorization state
if(pHttpCon->isAuthorized < 0x80)
{// 401 error
pHttpCon->httpStatus = HTTP_UNAUTHORIZED;
pHttpCon->sm = SM_HTTP_SERVE_HEADERS;
isDone = false;
break;
}
#endif
// Parse the args string
*pHttpCon->ptrData = '\0';
pHttpCon->ptrData = TCPIP_HTTP_URLDecode(pHttpCon->data);
// If this is an MPFS upload form request, bypass to headers
#if defined(TCPIP_HTTP_FILE_UPLOAD_ENABLE)
if(pHttpCon->httpStatus == HTTP_MPFS_FORM)
{
pHttpCon->sm = SM_HTTP_SERVE_HEADERS;
isDone = false;
break;
}
#endif
// Move on to GET args, unless there are none
pHttpCon->sm = SM_HTTP_PROCESS_GET;
if(pHttpCon->hasArgs == 0)
{
pHttpCon->sm = SM_HTTP_PROCESS_POST;
}
#if defined (TCPIP_HTTP_USE_WEBSOCKETS)
if (pHttpCon->webSocketKey[0] != '\0')
{
pHttpCon->sm = SM_HTTP_INIT_WEBSOCKET;
}
#endif
isDone = false;
pHttpCon->hasArgs = 0;
break;
#if defined (TCPIP_HTTP_USE_WEBSOCKETS)
case SM_HTTP_INIT_WEBSOCKET:
if (TCPIP_WS_doHandShake(pHttpCon) == 0) {
pHttpCon->sm = SM_HTTP_PROC_WEBSOCKET;
}
break;
case SM_HTTP_PROC_WEBSOCKET:
pHttpCon->sm = TCPIP_WS_Process(pHttpCon);
break;
#endif
case SM_HTTP_PROCESS_GET:
// Run the application callback TCPIP_HTTP_GetExecute()
if(TCPIP_HTTP_GetExecute(pHttpCon) == HTTP_IO_WAITING)
{// If waiting for asynchronous process, return to main app
break;
}
// Move on to POST data
pHttpCon->sm = SM_HTTP_PROCESS_POST;
case SM_HTTP_PROCESS_POST:
#if defined(TCPIP_HTTP_USE_POST)
// See if we have any new data
if(TCPIP_TCP_GetIsReady(pHttpCon->socket) == pHttpCon->callbackPos)
{
if((int32_t)(SYS_TMR_TickCountGet() - pHttpCon->httpTick) > 0)
{// If a timeout has occured, disconnect
TCPIP_TCP_Disconnect(pHttpCon->socket);
pHttpCon->sm = SM_HTTP_DISCONNECT;
isDone = false;
break;
}
}
if(pHttpCon->httpStatus == HTTP_POST
#if defined(TCPIP_HTTP_FILE_UPLOAD_ENABLE)
|| (pHttpCon->httpStatus >= HTTP_MPFS_UP && pHttpCon->httpStatus <= HTTP_MPFS_ERROR)
#endif
)
{
// Run the application callback TCPIP_HTTP_PostExecute()
#ifndef DRV_WIFI_OTA_ENABLE
#if defined(TCPIP_HTTP_FILE_UPLOAD_ENABLE) && defined(NVM_DRIVER_V080_WORKAROUND)
if(pHttpCon->httpStatus >= HTTP_MPFS_UP && pHttpCon->httpStatus <= HTTP_MPFS_ERROR)
{
c = TCPIP_HTTP_MPFSUpload(pHttpCon);
if(c == (uint8_t)HTTP_IO_DONE)
{
pHttpCon->sm = SM_HTTP_SERVE_HEADERS;
isDone = false;
break;
}
}
else
#endif // defined(TCPIP_HTTP_FILE_UPLOAD_ENABLE) && defined(NVM_DRIVER_V080_WORKAROUND)
#endif
c = TCPIP_HTTP_PostExecute(pHttpCon);
#ifdef DRV_WIFI_OTA_ENABLE
if(c == (uint8_t)HTTP_IO_DONE)
{
pHttpCon->sm = SM_HTTP_SERVE_HEADERS;