-
Notifications
You must be signed in to change notification settings - Fork 61
/
CNFGHTTP.c
2017 lines (1688 loc) · 45.7 KB
/
CNFGHTTP.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
//Copyright 2015-2021 <>< Charles Lohr Under the MIT/x11 License, NewBSD License or
// ColorChord License. You Choose. This file mostly based on `cnhttp` from cntools.
#ifdef CNFGHTTP
//Pull from a buffer
#ifndef CNFGHTTP_LIVE_FS
#define USE_RAM_MFS
#endif
//single_file_http.c base from https://github.com/cntools/httptest.
//scroll to bottom for implementation.
#ifndef CUSTOM_HTTPHEADER_CODE
#define CUSTOM_HTTPHEADER_CODE PushString("Access-Control-Allow-Origin: *\r\n");
#endif
/* public api for steve reid's public domain SHA-1 implementation */
/* this file is in the public domain */
#include <stdint.h>
typedef struct {
uint32_t state[5];
uint32_t count[2];
uint8_t buffer[64];
} RD_SHA1_CTX;
#define RD_SHA1_DIGEST_SIZE 20
void static RD_SHA1_Init(RD_SHA1_CTX* context);
void static RD_SHA1_Update(RD_SHA1_CTX* context, const uint8_t* data, const unsigned long len);
void static RD_SHA1_Final(uint8_t digest[RD_SHA1_DIGEST_SIZE],RD_SHA1_CTX* context); //WARNINGThe parameters are flipped here. (CNL)
//Not to be confused with MFS for the AVR.
#ifndef _MFS_H
#define _MFS_H
#ifndef USE_RAM_MFS
#include <stdio.h>
#endif
#define MFS_SECTOR 256
#define MFS_FILENAMELEN 32-8
#define MFS_FILE_COMPRESSED_MEMORY (-2)
//Format:
// [FILE NAME (24)] [Start (4)] [Len (4)]
// NOTE: Filename must be null-terminated within the 24.
struct MFSFileEntry
{
char name[MFS_FILENAMELEN];
uint32_t start; //From beginning of mfs thing.
uint32_t len;
};
struct MFSFileInfo
{
uint32_t filelen;
#ifdef USE_RAM_MFS
uint32_t offset;
#else
FILE * file;
#endif
};
//Returns 0 on succses.
//Returns size of file if non-empty
//If positive, populates mfi.
//Returns -1 if can't find file or reached end of file list.
int8_t MFSOpenFile( const char * fname, struct MFSFileInfo * mfi );
int32_t MFSReadSector( uint8_t* data, struct MFSFileInfo * mfi ); //returns # of bytes left in file.
void MFSClose( struct MFSFileInfo * mfi );
#endif
#ifndef _CNHTTP_H
#define _CNHTTP_H
#include <stdint.h>
extern struct HTTPConnection * curhttp;
extern uint8_t * curdata;
extern uint16_t curlen;
extern uint8_t wsmask[4];
extern uint8_t wsmaskplace;
uint8_t WSPOPMASK();
#define HTTPPOP (*curdata++)
//You must provide this.
void HTTPCustomStart( );
void HTTPCustomCallback( ); //called when we can send more data
void WebSocketData( int len );
void WebSocketTick( );
void WebSocketNew();
void HTTPHandleInternalCallback( );
uint8_t hex2byte( const char * c );
void NewWebSocket();
void et_espconn_disconnect( int socket );
//Internal Functions
void HTTPTick( uint8_t timedtick );
int URLDecode( char * decodeinto, int maxlen, const char * buf );
void WebSocketGotData( uint8_t c );
void WebSocketTickInternal();
void WebSocketSend( uint8_t * data, int size );
//Host-level functions
void my_base64_encode(const unsigned char *data, unsigned int input_length, uint8_t * encoded_data );
void Uint32To10Str( char * out, uint32_t dat );
void http_recvcb(int conn, char *pusrdata, unsigned short length);
void http_disconnetcb(int conn);
int httpserver_connectcb( int socket ); // return which HTTP it is. -1 for failure
void DataStartPacket();
extern uint8_t * databuff_ptr;
void PushString( const char * data );
void PushByte( uint8_t c );
void PushBlob( const uint8_t * datam, int len );
int TCPCanSend( int socket, int size );
int TCPDoneSend( int socket );
int EndTCPWrite( int socket );
#define HTTP_CONNECTIONS 50
#ifndef MAX_HTTP_PATHLEN
#define MAX_HTTP_PATHLEN 80
#endif
#define HTTP_SERVER_TIMEOUT 500
#define HTTP_STATE_NONE 0
#define HTTP_STATE_WAIT_METHOD 1
#define HTTP_STATE_WAIT_PATH 2
#define HTTP_STATE_WAIT_PROTO 3
#define HTTP_STATE_WAIT_FLAG 4
#define HTTP_STATE_WAIT_INFLAG 5
#define HTTP_STATE_DATA_XFER 7
#define HTTP_STATE_DATA_WEBSOCKET 8
#define HTTP_WAIT_CLOSE 15
struct HTTPConnection
{
uint8_t state:4;
uint8_t state_deets;
//Provides path, i.e. "/index.html" but, for websockets, the last
//32 bytes of the buffer are used for the websockets key.
uint8_t pathbuffer[MAX_HTTP_PATHLEN];
uint8_t is_dynamic:1;
uint16_t timeout;
union data_t
{
struct MFSFileInfo filedescriptor;
struct UserData { uint16_t a, b, c; } user;
struct UserDataPtr { void * v; } userptr;
} data;
void * rcb;
void * rcbDat; //For websockets primarily.
void * ccb; //Close callback (used for websockets, primarily)
uint32_t bytesleft;
uint32_t bytessofar;
uint8_t is404:1;
uint8_t isdone:1;
uint8_t isfirst:1;
uint8_t keep_alive:1;
uint8_t need_resend:1;
uint8_t send_pending:1; //If we can send data, we should?
uint8_t is_gzip:1;
int socket;
uint8_t corked_data[4096];
int corked_data_place;
};
extern struct HTTPConnection HTTPConnections[HTTP_CONNECTIONS];
#endif
#ifndef _HTTP_BSD_H
#define _HTTP_BSD_H
//Call this to start your webserver.
int RunHTTP( int port );
int TickHTTP(); //returns -1 if problem.
//For running on a BSD Sockets System
int htsend( int socket, uint8_t * data, int datact );
void et_espconn_disconnect( int socket );
void http_recvcb(int whichhttp, char *pusrdata, unsigned short length);
void http_disconnetcb(int whichhttp);
int httpserver_connectcb( int socket ); // return which HTTP it is. -1 for failure
void DataStartPacket();
extern uint8_t * databuff_ptr;
void PushBlob( const uint8_t * data, int len );
void PushByte( uint8_t c );
void PushString( const char * data );
int TCPCanSend( int socket, int size );
int TCPDoneSend( int socket );
int EndTCPWrite( int socket );
void TermHTTPServer();
extern int cork_binary_rx;
#endif
//Copyright 2012-2016 <>< Charles Lohr Under the MIT/x11 License, NewBSD License or ColorChord License. You Choose.
#include <string.h>
#include <stdio.h>
struct HTTPConnection HTTPConnections[HTTP_CONNECTIONS];
#define HTDEBUG( x, ... ) printf( x, ##__VA_ARGS__ )
//#define HTDEBUG( x... )
//#define ISKEEPALIVE "keep-alive"
#define ISKEEPALIVE "close"
struct HTTPConnection HTTPConnections[HTTP_CONNECTIONS];
struct HTTPConnection * curhttp;
uint8_t * curdata;
uint16_t curlen;
uint8_t wsmask[4];
uint8_t wsmaskplace;
void CloseEvent();
void InternalStartHTTP( );
void HTTPHandleInternalCallback( );
void HTTPClose( )
{
//This is dead code, but it is a testament to Charles.
//Do not do this here. Wait for the ESP to tell us the
//socket is successfully closed.
//curhttp->state = HTTP_STATE_NONE;
curhttp->state = HTTP_WAIT_CLOSE;
et_espconn_disconnect( curhttp->socket );
CloseEvent();
}
void HTTPGotData( )
{
uint8_t c;
curhttp->timeout = 0;
while( curlen-- )
{
c = HTTPPOP;
// sendhex2( h->state ); sendchr( ' ' );
switch( curhttp->state )
{
case HTTP_STATE_WAIT_METHOD:
if( c == ' ' )
{
curhttp->state = HTTP_STATE_WAIT_PATH;
curhttp->state_deets = 0;
}
break;
case HTTP_STATE_WAIT_PATH:
curhttp->pathbuffer[curhttp->state_deets++] = c;
if( curhttp->state_deets == MAX_HTTP_PATHLEN )
{
curhttp->state_deets--;
}
if( c == ' ' )
{
//Tricky: If we're a websocket, we need the whole header.
curhttp->pathbuffer[curhttp->state_deets-1] = 0;
curhttp->state_deets = 0;
if( strncmp( (const char*)curhttp->pathbuffer, "/d/ws", 5 ) == 0 )
{
curhttp->state = HTTP_STATE_DATA_WEBSOCKET;
curhttp->state_deets = 0;
}
else
{
curhttp->state = HTTP_STATE_WAIT_PROTO;
}
}
break;
case HTTP_STATE_WAIT_PROTO:
if( c == '\n' )
{
curhttp->state = HTTP_STATE_WAIT_FLAG;
}
break;
case HTTP_STATE_WAIT_FLAG:
if( c == '\n' )
{
curhttp->state = HTTP_STATE_DATA_XFER;
InternalStartHTTP( );
}
else if( c != '\r' )
{
curhttp->state = HTTP_STATE_WAIT_INFLAG;
}
break;
case HTTP_STATE_WAIT_INFLAG:
if( c == '\n' )
{
curhttp->state = HTTP_STATE_WAIT_FLAG;
curhttp->state_deets = 0;
}
break;
case HTTP_STATE_DATA_XFER:
//Ignore any further data?
curlen = 0;
break;
case HTTP_STATE_DATA_WEBSOCKET:
WebSocketGotData( c );
break;
case HTTP_WAIT_CLOSE:
if( curhttp->keep_alive )
{
curhttp->state = HTTP_STATE_WAIT_METHOD;
}
else
{
HTTPClose( );
}
break;
default:
break;
};
}
}
static void DoHTTP( uint8_t timed )
{
switch( curhttp->state )
{
case HTTP_STATE_NONE: //do nothing if no state.
curhttp->send_pending = 0;
break;
case HTTP_STATE_DATA_XFER:
curhttp->send_pending = 1;
if( TCPCanSend( curhttp->socket, 1300 ) ) //TCPDoneSend
{
if( curhttp->is_dynamic )
{
HTTPCustomCallback( );
}
else
{
HTTPHandleInternalCallback( );
}
}
break;
case HTTP_WAIT_CLOSE:
curhttp->send_pending = 0;
if( TCPDoneSend( curhttp->socket ) )
{
if( curhttp->keep_alive )
{
curhttp->state = HTTP_STATE_WAIT_METHOD;
}
else
{
HTTPClose( );
}
}
break;
case HTTP_STATE_DATA_WEBSOCKET:
curhttp->send_pending = 0;
if( TCPCanSend( curhttp->socket, 1300 ) ) //TCPDoneSend
{
WebSocketTickInternal();
}
break;
default:
if( timed )
{
if( curhttp->timeout++ > HTTP_SERVER_TIMEOUT )
{
HTTPClose( );
}
}
}
}
void HTTPTick( uint8_t timed )
{
uint8_t i;
for( i = 0; i < HTTP_CONNECTIONS; i++ )
{
if( curhttp ) { HTDEBUG( "HTTPRXQ\n" ); break; }
curhttp = &HTTPConnections[i];
DoHTTP( timed );
curhttp = 0;
}
}
void HTTPHandleInternalCallback( )
{
uint16_t i, bytestoread;
if( curhttp->isdone )
{
HTTPClose( );
return;
}
if( curhttp->is404 )
{
DataStartPacket();
PushString("HTTP/1.1 404 Not Found\r\nConnection: close\r\n\r\nFile not found.");
EndTCPWrite( curhttp->socket );
curhttp->isdone = 1;
return;
}
if( curhttp->isfirst )
{
char stto[10];
uint8_t slen = strlen( curhttp->pathbuffer );
const char * k;
DataStartPacket();;
//TODO: Content Length? MIME-Type?
PushString("HTTP/1.1 200 Ok\r\n");
#ifdef CUSTOM_HTTPHEADER_CODE
CUSTOM_HTTPHEADER_CODE
#endif
if( curhttp->bytesleft < 0xfffffffe )
{
PushString("Connection: "ISKEEPALIVE"\r\nContent-Length: ");
Uint32To10Str( stto, curhttp->bytesleft );
PushBlob( stto, strlen( stto ) );
curhttp->keep_alive = 1;
}
else
{
PushString("Connection: close");
curhttp->keep_alive = 0;
}
PushString( "\r\nContent-Type: " );
//Content-Type?
while( slen && ( curhttp->pathbuffer[--slen] != '.' ) );
k = &curhttp->pathbuffer[slen+1];
if( strcmp( k, "mp3" ) == 0 ) PushString( "audio/mpeg3" );
else if( strcmp( k, "jpg" ) == 0 ) PushString( "image/jpeg" );
else if( strcmp( k, "png" ) == 0 ) PushString( "image/png" );
else if( strcmp( k, "css" ) == 0 ) PushString( "text/css" );
else if( strcmp( k, "js" ) == 0 ) PushString( "text/javascript" );
else if( strcmp( k, "gz" ) == 0 ) PushString( "text/plain\r\nContent-Encoding: gzip\r\nCache-Control: public, max-age=3600" );
else if( curhttp->bytesleft == 0xfffffffe ) PushString( "text/plain" );
else PushString( "text/html" );
if( curhttp->is_gzip ) PushString( "\r\nContent-Encoding: gzip" );
PushString( "\r\n\r\n" );
EndTCPWrite( curhttp->socket );
curhttp->isfirst = 0;
return;
}
DataStartPacket();
for( i = 0; i < 2 && curhttp->bytesleft; i++ )
{
int bpt = curhttp->bytesleft;
if( bpt > MFS_SECTOR ) bpt = MFS_SECTOR;
curhttp->bytesleft = MFSReadSector( databuff_ptr, &curhttp->data.filedescriptor );
databuff_ptr += bpt;
}
EndTCPWrite( curhttp->socket );
if( !curhttp->bytesleft )
curhttp->isdone = 1;
}
void InternalStartHTTP( )
{
int32_t clusterno;
int8_t i;
char * path = &curhttp->pathbuffer[0];
curhttp->is_gzip = 0;
if( curhttp->pathbuffer[0] == '/' )
path++;
if( path[0] == 'd' && path[1] == '/' )
{
curhttp->is_dynamic = 1;
curhttp->isfirst = 1;
curhttp->isdone = 0;
curhttp->is404 = 0;
HTTPCustomStart();
return;
}
if( !path[0] )
{
path = "index.html";
}
for( i = 0; path[i]; i++ )
if( path[i] == '?' ) path[i] = 0;
i = MFSOpenFile( path, &curhttp->data.filedescriptor );
curhttp->bytessofar = 0;
curhttp->is_gzip = 0;
if( i == MFS_FILE_COMPRESSED_MEMORY )
{
curhttp->is_gzip = 1;
}
else if( i < 0 )
{
HTDEBUG( "404(%s)\n", path );
curhttp->is404 = 1;
curhttp->isfirst = 1;
curhttp->isdone = 0;
curhttp->is_dynamic = 0;
curhttp->bytesleft = 0;
return;
}
curhttp->isfirst = 1;
curhttp->isdone = 0;
curhttp->is404 = 0;
curhttp->is_dynamic = 0;
curhttp->bytesleft = curhttp->data.filedescriptor.filelen;
}
void http_disconnetcb(int conn ) {
int r = conn;
if( r>=0 )
{
if( !HTTPConnections[r].is_dynamic ) MFSClose( &HTTPConnections[r].data.filedescriptor );
HTTPConnections[r].state = 0;
}
}
void http_recvcb(int conn, char *pusrdata, unsigned short length)
{
int whichhttp = conn;
//Though it might be possible for this to interrupt the other
//tick task, I don't know if this is actually a probelem.
//I'm adding this back-up-the-register just in case.
if( curhttp ) { HTDEBUG( "Unexpected Race Condition\n" ); return; }
curhttp = &HTTPConnections[whichhttp];
curdata = (uint8_t*)pusrdata;
curlen = length;
HTTPGotData();
curhttp = 0 ;
}
int httpserver_connectcb( int socket )
{
int i;
for( i = 0; i < HTTP_CONNECTIONS; i++ )
{
if( HTTPConnections[i].state == 0 )
{
HTTPConnections[i].socket = socket;
HTTPConnections[i].state = HTTP_STATE_WAIT_METHOD;
break;
}
}
if( i == HTTP_CONNECTIONS )
{
return -1;
}
return i;
}
int URLDecode( char * decodeinto, int maxlen, const char * buf )
{
int i = 0;
for( ; buf && *buf; buf++ )
{
char c = *buf;
if( c == '+' )
{
decodeinto[i++] = ' ';
}
else if( c == '?' || c == '&' )
{
break;
}
else if( c == '%' )
{
if( *(buf+1) && *(buf+2) )
{
decodeinto[i++] = hex2byte( buf+1 );
buf += 2;
}
}
else
{
decodeinto[i++] = c;
}
if( i >= maxlen -1 ) break;
}
decodeinto[i] = 0;
return i;
}
#ifndef RD_SHA1_HASH_LEN
#define RD_SHA1_HASH_LEN RD_SHA1_DIGEST_SIZE
#endif
void WebSocketGotData( uint8_t c )
{
switch( curhttp->state_deets )
{
case 0:
{
int i = 0;
char inkey[120];
unsigned char hash[RD_SHA1_HASH_LEN];
RD_SHA1_CTX c;
int inkeylen = 0;
curhttp->is_dynamic = 1;
while( curlen > 20 )
{
curdata++; curlen--;
if( strncmp( curdata, "Sec-WebSocket-Key: ", 19 ) == 0 )
{
break;
}
}
if( curlen <= 21 )
{
HTDEBUG( "No websocket key found.\n" );
curhttp->state = HTTP_WAIT_CLOSE;
return;
}
curdata+= 19;
curlen -= 19;
#define WS_KEY_LEN 36
#define WS_KEY "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"
#define WS_RETKEY_SIZEM1 32
while( curlen > 1 )
{
uint8_t lc = *(curdata++);
inkey[i] = lc;
curlen--;
if( lc == '\r' )
{
inkey[i] = 0;
break;
}
i++;
if( i >= sizeof( inkey ) - WS_KEY_LEN - 5 )
{
HTDEBUG( "Websocket key too big.\n" );
curhttp->state = HTTP_WAIT_CLOSE;
return;
}
}
if( curlen <= 1 )
{
HTDEBUG( "Invalid websocket key found.\n" );
curhttp->state = HTTP_WAIT_CLOSE;
return;
}
if( i + WS_KEY_LEN + 1 >= sizeof( inkey ) )
{
HTDEBUG( "WSKEY Too Big.\n" );
curhttp->state = HTTP_WAIT_CLOSE;
return;
}
memcpy( &inkey[i], WS_KEY, WS_KEY_LEN + 1 );
i += WS_KEY_LEN;
RD_SHA1_Init( &c );
RD_SHA1_Update( &c, inkey, i );
RD_SHA1_Final( hash, &c );
#if (WS_RETKEY_SIZE > MAX_HTTP_PATHLEN - 10 )
#error MAX_HTTP_PATHLEN too short.
#endif
my_base64_encode( hash, RD_SHA1_HASH_LEN, curhttp->pathbuffer + (MAX_HTTP_PATHLEN-WS_RETKEY_SIZEM1) );
curhttp->bytessofar = 0;
curhttp->bytesleft = 0;
NewWebSocket();
//Respond...
curhttp->state_deets = 1;
break;
}
case 1:
if( c == '\n' ) curhttp->state_deets = 2;
break;
case 2:
if( c == '\r' ) curhttp->state_deets = 3;
else curhttp->state_deets = 1;
break;
case 3:
if( c == '\n' ) curhttp->state_deets = 4;
else curhttp->state_deets = 1;
break;
case 5: //Established connection.
{
//XXX TODO: Seems to malfunction on large-ish packets. I know it has problems with 140-byte payloads.
do
{
if( curlen < 5 ) //Can't interpret packet.
break;
uint8_t fin = c & 1;
uint8_t opcode = c << 4;
uint16_t payloadlen = *(curdata++);
curlen--;
if( !(payloadlen & 0x80) )
{
HTDEBUG( "Unmasked packet (%d)\n", payloadlen );
curhttp->state = HTTP_WAIT_CLOSE;
break;
}
if( opcode == 128 )
{
//Close connection.
//HTDEBUG( "CLOSE\n" );
//curhttp->state = HTTP_WAIT_CLOSE;
//break;
}
payloadlen &= 0x7f;
if( payloadlen == 127 )
{
//Very long payload.
//Not supported.
HTDEBUG( "Unsupported payload packet.\n" );
curhttp->state = HTTP_WAIT_CLOSE;
break;
}
else if( payloadlen == 126 )
{
payloadlen = (curdata[0] << 8) | curdata[1];
curdata += 2;
curlen -= 2;
}
wsmask[0] = curdata[0];
wsmask[1] = curdata[1];
wsmask[2] = curdata[2];
wsmask[3] = curdata[3];
curdata += 4;
curlen -= 4;
wsmaskplace = 0;
//XXX Warning: When packets get larger, they may split the
//websockets packets into multiple parts. We could handle this
//but at the cost of prescious RAM. I am chosing to just drop those
//packets on the floor, and restarting the connection.
if( curlen < payloadlen )
{
extern int cork_binary_rx;
cork_binary_rx = 1;
//HTDEBUG( "Websocket Fragmented. %d %d\n", curlen, payloadlen );
//curhttp->state = HTTP_WAIT_CLOSE;
HTDEBUG( "Websocket Fragmented. %d %d\n", curlen, payloadlen );
curhttp->state = HTTP_WAIT_CLOSE;
return;
}
char * newcurdata = curdata + payloadlen + 1;
WebSocketData( payloadlen );
curlen -= payloadlen;
curdata = newcurdata;
}
while( curlen > 5 );
break;
}
default:
break;
}
}
void WebSocketTickInternal()
{
switch( curhttp->state_deets )
{
case 4: //Has key full HTTP header, etc. wants response.
DataStartPacket();;
PushString( "HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Accept: " );
PushString( curhttp->pathbuffer + (MAX_HTTP_PATHLEN-WS_RETKEY_SIZEM1) );
PushString( "\r\n\r\n" );
EndTCPWrite( curhttp->socket );
curhttp->state_deets = 5;
curhttp->keep_alive = 0;
break;
case 5:
WebSocketTick();
break;
}
}
void WebSocketSend( uint8_t * data, int size )
{
DataStartPacket();;
PushByte( 0x82 ); //0x81 is text.
if( size >= 126 )
{
PushByte( 0x00 | 126 );
PushByte( size>>8 );
PushByte( size&0xff );
}
else
{
PushByte( 0x00 | size );
}
PushBlob( data, size );
EndTCPWrite( curhttp->socket );
curhttp->send_pending = 1;
}
uint8_t WSPOPMASK()
{
uint8_t mask = wsmask[wsmaskplace];
wsmaskplace = (wsmaskplace+1)&3;
return (*curdata++)^(mask);
}
#if defined(WINDOWS) || defined(WIN32) || defined(WIN64) || defined(_WIN32) || defined(_WIN64)
#define _WINSOCK_DEPRECATED_NO_WARNINGS
#include <winsock2.h>
#define socklen_t uint32_t
#define SHUT_RDWR SD_BOTH
#define MSG_NOSIGNAL 0
#else
#define closesocket close
#include <sys/types.h>
#include <sys/socket.h>
#include <linux/in.h>
#include <unistd.h>
#include <sys/time.h>
uint16_t htons(uint16_t hostshort);
#endif
#include <fcntl.h>
#include <stdio.h>
#include <string.h>
#include <time.h>
static int serverSocket;
uint8_t * databuff_ptr;
uint8_t databuff[1536];
int cork_binary_rx;
#ifndef HTTP_POLL_TIMEOUT
#define HTTP_POLL_TIMEOUT 0 //This is a little weird, it's an adaptation from cnhttp.
#endif
#define DESTROY_SOCKETS_LIST 200
int destroy_sockets[DESTROY_SOCKETS_LIST];
int destroy_socket_head = 0;
int sockets[HTTP_CONNECTIONS];
void et_espconn_disconnect( int socket )
{
shutdown( socket, SHUT_RDWR );
int i;
//printf( "Shut: %d\n", socket );
for( i = 0; i < HTTP_CONNECTIONS; i++ )
{
if( sockets[i] == socket )
{
http_disconnetcb( i );
sockets[i] = 0;
}
}
if( destroy_sockets[destroy_socket_head] ) closesocket( destroy_sockets[destroy_socket_head] );
destroy_sockets[destroy_socket_head] = socket;
destroy_socket_head = (destroy_socket_head+1)%DESTROY_SOCKETS_LIST;
}
void DataStartPacket()
{
databuff_ptr = databuff;
}
void PushByte( uint8_t c )
{
if( databuff_ptr - databuff + 1 >= sizeof( databuff ) ) return;
*(databuff_ptr++) = c;
}
void PushBlob( const uint8_t * data, int len )
{
if( databuff_ptr - databuff + len >= sizeof( databuff ) ) return;
memcpy( databuff_ptr, data, len );
databuff_ptr += len;
}
void PushString( const char * data )
{
int len = strlen( data );
if( databuff_ptr - databuff + len >= sizeof( databuff ) ) return;
memcpy( databuff_ptr, data, len );
databuff_ptr += len;
}
int TCPCanSend( int socket, int size )
{
fd_set write_fd_set;
struct timeval tv;
tv.tv_sec = 0;
tv.tv_usec = 0;
FD_ZERO (&write_fd_set);
FD_SET (socket, &write_fd_set);
int r = select (FD_SETSIZE, NULL, &write_fd_set, NULL, &tv);
if (r < 0)
{
perror ("select");
return -1;
}
return r;
}
int TCPCanRead( int sock )
{
fd_set read_fd_set;
struct timeval tv;
tv.tv_sec = 0;
tv.tv_usec = 0;
FD_ZERO (&read_fd_set);
FD_SET (sock, &read_fd_set);
int r;
r = select (FD_SETSIZE, &read_fd_set, NULL, NULL, &tv);
if (r < 0)
{
perror ("select");
return -1;
}
return r;
}
int TCPException( int sock )
{
int error_code;
int error_code_size = sizeof(error_code);