-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathhttpClient.c
More file actions
1564 lines (1464 loc) · 60.2 KB
/
httpClient.c
File metadata and controls
1564 lines (1464 loc) · 60.2 KB
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
/***************************************************************************
* B. *
* Copyright (C) 2005 by Ismail Kizir *
***************************************************************************/
#include "Config.h"
#include "httpClient.h"
#include "portable_endian.h"
#include "mystrings.h"
#include "IOBuffers.h"
#include "Multiplexer.h"
#include "mytemplate.h"
#include "httpCommon.h"
#include "KVList.h"
//#include <openssl/sha.h>
#include "MyAtomic.h"
#include "MyHashZStr.h"
#include "HohhaX25519.h"
#include "crypto_kem.h"
#include "CustomEnc.h"
#include "CharSets.h"
// If you want to use
#if defined(USE_HUGE_LIBBASE64_LIBRARY)
#include "libbase64.h"
#else
#include "HohhaXor.h"
#endif
#include <stdio.h>
#include <string.h>
#include <strings.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <mymisc.h>
#include <mystrings.h>
#include <stdarg.h>
#include <sys/types.h>
#include <unistd.h>
#include<netinet/in.h>
#include <ctype.h>
#include <sys/mman.h>
#include <mime.h>
#include <netdb.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <stdlib.h>
//#define DEBUG
//#define HDEBUG
// Some variables are defined in httpCommon.c
//#define MAX_NUM_REQUEST_HEADERS 24
//#define MAX_NUM_RESPONSE_HEADERS 24
#define MAX_NUM_UPLOADED_FILES 32
#define MAX_NUM_GPC_VARS 256
//#define MAX_GPC_VAR_NAME_LEN 63
#define MAX_POST_SIZE 1024*1024
#define DEFAULT_GPC_VAR_VALUE_INITIAL_BUFSIZE 4096
#define MAX_GPC_VAR_VALUE_LEN 4096
#define cstJUST_INITIALIZED 0
#define cstRESOLVING_DNS 1
#define cstCONNECTING 2
#define cstREADY_FOR_QUERY 3
#define cstHTTP_REQUEST_SEND_WAITING_FOR_REPLY 4
#define cstPARSING_HTTP_VERSION 5
#define cstPARSING_HTTP_STATUS_CODE 6
#define cstPARSING_HTTP_STATUS_STRING 7
#define cstPARSING_HEADER_VAR_NAME 8
#define cstPARSING_HEADER_VAR_VALUE 9
#define cstPARSING_COOKIE_NAME 10
#define cstPARSING_COOKIE_VALUE 11
#define cstPARSING_COOKIE_PROPERTY_NAME 12
#define cstPARSING_COOKIE_PROPERTY_VALUE 13
#define cstPARSING_POST_VAR_NAME 14
#define cstPARSING_POST_VAR_VALUE 15
#define cstPARSING_FIRST_MULTIPART_BOUNDARY 16
#define cstPARSING_MULTIPART_HEADERS 17 // Content-disposition: blah blah
#define cstPARSING_MULTIPART_BODY 18
static TBool chttpNewDataIsAvailable (TIOBuf *io, TMemInputBuffer *mib);
TSocketProfileTCP HTTP_CLIENT_DEFAULT_SOCKET_PROFILE = {
.ExtraSocketProfileData = NULL,
.TimeoutBeforeLogin = 5000,
.SocketKernelSendBufSize = 0,
.SocketKernelRecvBufSize = 0,
.CommProtocol = protoRaw,
.RequiresLogin = IOB_LOGIN_NOT_REQUIRED,
.FreeThisStructure = 1, // By default, it must always be created dynamically
.fncGetHohhaEncryptionKeyWebSocket = NULL,
.fncOnFlushComplete = NULL,
.fncIOBufNewRawDataIsAvailable = chttpNewDataIsAvailable,
.fncOnSocketIsReadyToWrite = NULL,
.fncOnClose = NULL,
.fncOutputObjectStats = NULL,
.fncOnOutgoingConnectSuccess = NULL,
.fncIOBufPostInit = NULL,
.ConnectTimeout = 60000,
.IndividualAddrPortConnectTimeout = 30000,
.Timeout = 15000,
.InitialOutputBufSize = 4000,
.NetServiceType = NET_SERVICE_HTTP,
.CompressionType = IOB_COMP_DEFLATE, // It will be automatically negotiated if it's not IOB_COMP_NONE!
.IncomingConn = 0,
.isSSL = 0 // This is 0 by default. ocConnect will set it to 1 automatically
};
TSocketProfileTCP *chttpGetDefaultSockProfile(void)
{
return &HTTP_CLIENT_DEFAULT_SOCKET_PROFILE;
}
static inline void chttpSetParserError(TCHttp *s, uint16_t E)
{
s->ParserError = E;
}
#if !defined(DEBUG)
static
#endif
void chttpInternalfncOnClose(TIOBuf *io, uint32_t Reason)
{
TCHttp *CHTTP = (TCHttp *)io->ExtraData.p;
if (CHTTP)
{
// TMultiplexer *mpx = CAST(io->SocketProfile->Multiplexer, TMultiplexer *);
//DBGPRINT(DBGLVL_DBG, "\n\n\n!!!!! chttpOnConnectionLost called. REASON: %u MpxCurCyleNo: %llu !!!!!\n\n\n", (unsigned)Reason, (unsigned long long int)mpxGetCycleNo(chttpGetMultiplexer(CHTTP)));
if (CHTTP->fncOnRequestCompleted)
{
chttpSetParserError(CHTTP, HTTP_PARSER_ERROR_NOT_CONNECTED);
CHTTP->fncOnRequestCompleted(CHTTP);
}
chttpDestroyAndFree(CHTTP);
}
}
// Private functions
static int32_t chttpGetChar(TCHttp *s);
static int32_t chttpGetRawChar(TCHttp *s)
{
if (mibThereIsDataToRead(s->LastInputChunk))
{
s->LastCharRead = s->LastInputChunk->DataBuf[s->LastInputChunk->ReadingPos++];
return s->LastCharRead;
}
return IOB_END_OF_BUFFER;
}
/**
* chttpCreateOutgoingConn creates a new TOutgoingConn structure with an appropriate socket profile to be used as TCHttp's outgoing connection object
* @param mpx Multiplexer
* @param isSecure 1 if it will be an SSL(https or wss) connection; 0 if not! USE ONLY 1 or 0 values! It's not a boolean
* @param TCBFncParam ExtraData is the parameters to pass to OutgoingConn object to be created
* @return new TOutgoingConn object pointer
*/
TOutgoingConn *chttpCreateOutgoingConn(TMultiplexer *mpx, uint8_t isSecure, TCBFncParam ExtraData)
{
assert(isSecure <= 1);
TOutgoingConn *OConn = ocInitNew(
mpx,
&HTTP_CLIENT_DEFAULT_SOCKET_PROFILE,
ExtraData);
return OConn;
}
/**
* chttpInit initializes a client http object with an already connected io
* @param s Previously allocated TCHttp pointer
* @param io Already connected TIOBuf pointer
* @param Host Host: xxx header to be sent with http requests
* @return
*/
int32_t chttpInit(TCHttp *s, TIOBuf *io, const char *Host, TCBFncParam ExtraData)
{ // Called as a TfncIOBufPostInit function after IOBufStruct init. The caller will be called by inheriting objects
A_memset(s, 0, sizeof(TCHttp));
// We set TCHttp's io property to io object
#if defined(MULTIPLE_CONCURRENT_MULTIPLEXERS)
s->mpx = iobGetMultiplexer(io);
#endif
s->ExtraData = ExtraData;
s->io = io; //ocInitNew(mpx, &HTTP_CLIENT_DEFAULT_SOCKET_PROFILE, s);
s->RequestContentType = MIME_APPLICATION_X_WWW_FORM_URLENCODED;
iobIncRefCounter(io);
io->ExtraData.p = s;
io->SocketProfile->fncOnClose = chttpInternalfncOnClose;
io->SocketProfile->fncIOBufNewRawDataIsAvailable = chttpNewDataIsAvailable;
InitChunk(&s->ChunkInfo, 4000);
uint32_t HostLen = (uint32_t)strlen(Host);
if (HostLen > LEN_CONST("http://"))
{
if (memcmp(Host, "http://", LEN_CONST("http://")) == 0)
s->Host = ChunkStrDupLen(&s->ChunkInfo, Host + LEN_CONST("http://"), HostLen - LEN_CONST("http://"));
else if (memcmp(Host, "https://", LEN_CONST("https://")) == 0)
s->Host = ChunkStrDupLen(&s->ChunkInfo, Host + LEN_CONST("https://"), HostLen - LEN_CONST("https://"));
else s->Host = ChunkStrDupLen(&s->ChunkInfo, Host, HostLen);
} else s->Host = ChunkStrDupLen(&s->ChunkInfo, Host, HostLen);
kvInit(&s->RequestGetOrPOSTVars);
kvInit(&s->RequestHeaders);
kvInit(&s->ResponseHeaders);
kvInit(&s->ResponseCookies);
s->LastElementData = smbInitNew(DEFAULT_GPC_VAR_VALUE_INITIAL_BUFSIZE);
if (!s->LastElementData)
return -1;
//chttpSetState(s, stPARSING_METHOD);
return 1; // Returns a positive value on success
}
/**
* chttpInitNew Allocates a new TCHttp structure from io's underlying memory manager
* and initializes a client http object with an already connected io
* @param io Already connected TIOBuf pointer
* @param Host Host: xxx header to be sent with http requests
* @return
*/
TCHttp *chttpInitNew(TIOBuf *io, const char *Host, TCBFncParam ExtraData)
{
TCHttp *chttp;
chttp = (TCHttp *)mAlloc(sizeof(TCHttp));
if (!chttp)
return NULL;
if (chttpInit(chttp, io, Host, ExtraData) < 0)
{
mFree(chttp);
return NULL;
}
chttp->FreeThisStructure = 1;
return chttp;
}
void chttpAddRequestHeader(TCHttp *s,const char *K, const uint32_t MallocForKey, const char *V, const uint32_t MallocForValue)
{
TKeyValue *KV = (TKeyValue *)chttpMAlloc(s, sizeof(TKeyValue));
KV->KeyStrLen = (uint32_t)strlen(K);
KV->ValueStrLen = (uint32_t)strlen(V);
KV->KeyAsStrPtr = (MallocForKey ? chttpStrDupLen(s, K, KV->KeyStrLen) : K);
KV->ValueAsStrPtr = (MallocForValue ? chttpStrDupLen(s, V, KV->ValueStrLen) : V);
kvGetOrSetWithStrKey(&s->RequestHeaders, KV);
}
/**
* chttpAddAuthenticationCredentials adds basic authentication credentials to request
* as described in rfc2617: https://tools.ietf.org/html/rfc2617
* @param s TCHttp *
* @param UserName const char *
* @param Password
* @return TRUE if Authorization header successfully added. FALSE if parameters are invalid
*/
TBool chttpAddAuthenticationCredentials(TCHttp *s, const char *UserName, const char *Password)
{
char S[192], S1[512];
if (UserName && Password)
{
size_t UserNameLen = strlen(UserName), PasswordLen = strlen(Password);
if (likely(UserNameLen && PasswordLen && UserNameLen <= 80 && PasswordLen <= 80))
{
memcpy(S, UserName, UserNameLen);
S[UserNameLen] = ':';
memcpy(S + UserNameLen + 1, Password, PasswordLen+1);
memcpy(S1, "Basic ", 6);
size_t EncodedStrLen;
// If you want to use
#if defined(USE_HUGE_LIBBASE64_LIBRARY)
int Flags = 0; // BASE64_FORCE_SSE42
base64_encode(S, (UserNameLen + PasswordLen +1), S1 + 6, &EncodedStrLen, Flags);
#else
base64_encodestate Base64EncodeState;
base64_init_encodestate(&Base64EncodeState);
EncodedStrLen = base64_encode_block(S, (UserNameLen + PasswordLen +1), S1 + 6, &Base64EncodeState);
#endif
// Base64_encode doesn't put a zero pad(\0) at the end of string. We must do it
S1[6 + EncodedStrLen] = '\0';
#if defined(HCDEBUG)
//DBGPRINT(DBGLVL_DBG, "http auth credentials to send: %s Encoded base64 len: %llu\n", S1, (unsigned long long int)EncodedStrLen);
#endif
chttpAddRequestHeader(s, "Authorization", FALSE, S1, TRUE);
return TRUE;
}
}
return FALSE;
}
void chttpAddResponseHeaderInt64 (TCHttp *s, const char *K, uint32_t MAllocForKey, int64_t Num)
{
char NumBuf[48];
sprintf(NumBuf,"%lld", (long long int)Num);
chttpAddResponseHeader (s, K, MAllocForKey, NumBuf, TRUE);
}
void chttpAddResponseHeader(TCHttp *s, const char *K, uint32_t MallocForKey, const char *V, uint32_t MallocForValue)
{
TKeyValue *KV = kvGetWithStrKey(&s->ResponseHeaders, K);
if (KV == NULL)
{ // No header with same key previously received
KV = (TKeyValue *)chttpMAlloc(s, sizeof(TKeyValue));
KV->KeyStrLen = (unsigned)strlen(K);
KV->ValueStrLen = (unsigned)strlen(V);
KV->KeyAsStrPtr = (MallocForKey ? chttpStrDup(s, K) : K);
KV->ValueAsStrPtr = (MallocForValue ? chttpStrDup(s, V) : V);
kvGetOrSetWithStrKey(&s->ResponseHeaders, KV);
}
else {
// Already found. We add comma and the value
char *ss = chttpMAlloc(s, strlen(V) + KV->ValueStrLen + 2);
KV->ValueStrLen = (uint32_t)sprintf(ss, "%s,%s", KV->ValueAsStrPtr, V);
KV->ValueAsStrPtr = ss;
}
}
void chttpAddRequestGetOrPOSTVar(TCHttp *s,const char *K, uint32_t MallocForKey, const char *V, uint32_t MallocForValue)
{
TKeyValue *KV = (TKeyValue *)chttpMAlloc(s, sizeof(TKeyValue));
KV->KeyStrLen = (uint32_t)strlen(K);
KV->ValueStrLen = (uint32_t)strlen(V);
KV->KeyAsStrPtr = (MallocForKey ? chttpStrDupLen(s, K, KV->KeyStrLen) : K);
KV->ValueAsStrPtr = (MallocForValue ? chttpStrDupLen(s, V, KV->ValueStrLen) : V);
kvGetOrSetWithStrKey(&s->RequestGetOrPOSTVars, KV);
}
void chttpAddRequestGetOrPOSTVarBin(TCHttp *s,const char *K, const uint32_t MallocForKey, const char *V, const uint32_t ValueLen, const uint32_t MallocForValue)
{
TKeyValue *KV = (TKeyValue *)chttpMAlloc(s, sizeof(TKeyValue));
KV->KeyStrLen = (unsigned)strlen(K);
KV->ValueStrLen = ValueLen;
KV->KeyAsStrPtr = (MallocForKey ? chttpStrDupLen(s, K, KV->KeyStrLen) : K);
if (MallocForValue)
{
KV->ValueAsStrPtr = (const char *)chttpMAlloc(s, ValueLen);
memcpy((void *)KV->ValueAsStrPtr, V, ValueLen);
} else KV->ValueAsStrPtr = V;
KV->ValueAsStrPtr = (MallocForValue ? chttpStrDupLen(s, V, ValueLen) : V);
kvGetOrSetWithStrKey(&s->RequestGetOrPOSTVars, KV);
}
void chttpAddRequestGetOrPOSTVarInt64 (TCHttp *s, const char *K, uint32_t MAllocForKey, int64_t Num)
{
char NumBuf[48];
TKeyValue *KV = (TKeyValue *)chttpMAlloc(s, sizeof(TKeyValue));
KV->KeyStrLen = (unsigned)strlen(K);
KV->ValueStrLen = (unsigned)Int64ToStr(Num, NumBuf);
KV->KeyAsStrPtr = (MAllocForKey ? chttpStrDupLen(s, K, KV->KeyStrLen) : K);
KV->ValueAsStrPtr = chttpStrDupLen(s, NumBuf, KV->ValueStrLen);
kvGetOrSetWithStrKey(&s->RequestGetOrPOSTVars, KV);
}
void chttpAddRequestGetOrPOSTVarUInt64 (TCHttp *s, const char *K, uint32_t MAllocForKey, int64_t Num)
{
char NumBuf[48];
TKeyValue *KV = (TKeyValue *)chttpMAlloc(s, sizeof(TKeyValue));
KV->KeyStrLen = (unsigned)strlen(K);
KV->ValueStrLen = UInt64ToStr(Num, NumBuf);
KV->KeyAsStrPtr = (MAllocForKey ? chttpStrDupLen(s, K, KV->KeyStrLen) : K);
KV->ValueAsStrPtr = chttpStrDupLen(s, NumBuf, KV->ValueStrLen);
kvGetOrSetWithStrKey(&s->RequestGetOrPOSTVars, KV);
}
/**
* chttpAddRequestGetOrPOSTVarBase64 adds a request var as a base64 encoded string
* @param s TCHttp *
* @param K Key name
* @param MallocForKey TRUE if memory will be allocated
* @param V Value buffer pointer
* @param VLen Length of value buffer.
*/
void chttpAddRequestGetOrPOSTVarBase64(TCHttp *s, const char *K, uint32_t MallocForKey, const void *V, const uint32_t VLen)
{
TKeyValue *KV = (TKeyValue *)chttpMAlloc(s, sizeof(TKeyValue));
KV->KeyStrLen = (unsigned)strlen(K);
KV->KeyAsStrPtr = (MallocForKey ? chttpStrDupLen(s, K, KV->KeyStrLen) : K);
size_t N, ReqSpc = BASE64_ENCODED_LEN(VLen) + 1;
KV->ValueAsStrPtr = chttpMAlloc(s, ReqSpc);
base64_encode((const char *)V, VLen, (char *)KV->ValueAsStrPtr, &N, 0);
*((char *)KV->ValueAsStrPtr + N) = '\0';
KV->ValueStrLen = N;
kvGetOrSetWithStrKey(&s->RequestGetOrPOSTVars, KV);
}
#if !defined(DEBUG)
static
#endif
int32_t chttpGetChar(TCHttp *s)
{
int32_t PrevChar, CurChar;
char *tmpptr;
lblGetCharEntry:
PrevChar = chttpGetLastRawCharRead(s);
if (s->ChunkReadState == CRS_READING_CHUNK_HEADER)
{
while ((CurChar = chttpGetRawChar(s)) != IOB_END_OF_BUFFER)
{
if (CurChar == '\n' && PrevChar == '\r')
{
s->CurrentChunkLen = strtol((const char *)smbGetBuf(s->ChunkHeaderAndTrailerData), &tmpptr, 16);
s->CurrentChunkNumRead = 0;
s->ChunkReadState = CRS_READING_CHUNK_BODY;
smbClear(s->ChunkHeaderAndTrailerData);
if (s->CurrentChunkLen == 0)
{
s->ConsumedAllData = 1;
return IOB_END_OF_BUFFER;
}
break;
} else smbSendChar(s->ChunkHeaderAndTrailerData, CurChar);
PrevChar = CurChar;
}
if (CurChar == IOB_END_OF_BUFFER)
return IOB_END_OF_BUFFER;
}
lblReadBody:
CurChar = chttpGetRawChar(s);
if (CurChar == IOB_END_OF_BUFFER)
return IOB_END_OF_BUFFER;
s->CurrentChunkNumRead++;
if (s->ChunkReadState == CRS_READING_CHUNK_BODY)
{
if (s->CurrentChunkNumRead <= s->CurrentChunkLen)
return CurChar;
// We read all data in this chunk.
if (CurChar != '\n' && CurChar != '\r')
{
chttpSetParserError(s, HTTP_PARSER_ERROR_INVALID_CHUNK_BODY);
return IOB_END_OF_BUFFER;
}
if (s->CurrentChunkNumRead - s->CurrentChunkLen == 1)
goto lblReadBody;
// We consumed everything in this chunk. Let's wait for the next chunk
s->ChunkReadState = CRS_READING_CHUNK_HEADER;
goto lblGetCharEntry;
}
// Not a chunked read. We also use s->CurrentChunkNumRead to count.
if (s->ResponseContentLength && s->ResponseContentLength == s->CurrentChunkNumRead)
s->ConsumedAllData = 1;
return CurChar;
}
const char *chttpFetchRequestGetOrPostVarStr(TCHttp *s, const char *varname, char *buf, uint32_t maxlen)
{ //
const char *v;
v = chttpFetchRequestGetOrPostVar(s, varname);
if (v != NULL)
{
strncpy(buf, v, maxlen);
if (strlen(v) > maxlen)
buf[maxlen] = '\0';
return buf;
}
return NULL;
}
const char *chttpGetConnectionStateStr(uint32_t ConnectionState)
{
switch (ConnectionState)
{
case cstJUST_INITIALIZED: return "stJUST_INITIALIZED";
case cstCONNECTING: return "cstCONNECTING";
case cstRESOLVING_DNS: return "cstRESOLVING_DNS";
case cstPARSING_HTTP_VERSION: return "cstPARSING_HTTP_VERSION";
case cstPARSING_HTTP_STATUS_CODE: return "cstPARSING_HTTP_STATUS_CODE";
case cstPARSING_HTTP_STATUS_STRING: return "cstPARSING_HTTP_STATUS_STRING";
}
return "UNKNOWN STATE";
}
TBool chttpAddFileToUpload(TCHttp *s, const char *FileFullPath, uint32_t MimeType)
{ // http://stackoverflow.com/questions/8659808/how-does-http-file-upload-work
THttpCUplFile *U = (THttpCUplFile *)chttpMAlloc(s, sizeof(THttpCUplFile));
U->FileName = chttpStrDup(s, FileFullPath);
U->FileContent = mbInitNewByReadingFile(FileFullPath, 0, 0, MAP_POPULATE, TRUE);
if (U->FileContent)
{
U->MimeType = MimeType;
U->Next = s->FilesToUpload;
s->FilesToUpload = U;
return TRUE;
}
return FALSE;
}
/**
* @brief chttpExtractCharSet extracts character set from Content-Type header
* @param s TCHttp *
* @return TCharSet
*/
TCharSet chttpExtractCharSet(TCHttp *chttp)
{
const char *s = chttpGetResponseHeader(chttp, "Content-Type");
if (s)
{
//ext/html; charset=iso-8859-1
s = strcasestr(s, "charset");
if (s)
{
while(*s && (*s == '=' || isspace(*s)))
s++;
if (*s)
{
char TBuf[64], *dp=TBuf;
while (*s && !isspace(*s) && *s != '\n' && *s != '\r' && (dp-TBuf < 63))
{
*dp = *s;
++dp;
++s;
}
*dp = '\0';
return charsetParse(TBuf);
}
}
}
return CHARSET_NONE;
}
void chttpPrintResponseHeaders(TCHttp *s)
{
TKeyValue *KV;
TDLLNode *Node;
chttpForEachResponseHeaderFIFO(s, Node)
{
KV = (TKeyValue *)dllGetContainerStructPtr(Node, TKeyValue);
DBGPRINT(DBGLVL_DBG, "%s: %s\n", KV->KeyAsStrPtr, KV->ValueAsStrPtr);
}
}
/**
* Internally called by chttpStateMachine when parsing of http headers is done
* @param s
* @return If TRUE, we stop parsing. If FALSE, we continue parsing body
*/
#if !defined(DEBUG)
static
#endif
void chttpHeaderParseCompleted(TCHttp *s)
{
const char *tmpptr;
#if defined(HCDEBUG)
dbglogSend3("chttpHeaderParseCompleted called\n");
chttpPrintResponseHeaders(s);
#endif
smbClear(s->LastElementData); // We clear LastElementData now. It will contain response body
s->HeaderParseCompleted = 1;
s->CurrentChunkNumRead = 0; // This is a very important variable to count how many chars are read in the body or in the current chunk in the body
tmpptr = chttpGetResponseHeader(s, "Transfer-Encoding");
if (tmpptr != NULL)
{
if (strcasecmp(tmpptr, "chunked") == 0)
{
s->ChunkReadState = CRS_READING_CHUNK_HEADER;
s->ChunkHeaderAndTrailerData = smbInitNew(128);
}
}
tmpptr = chttpGetResponseHeader(s, "Connection");
if (tmpptr != NULL)
{
//DBGPRINT(DBGLVL_DBG, "httpGetResponseHeader(s, 'Connection'): '%s'\n",tmpptr);
if (strcasecmp(tmpptr,"keep-alive") == 0)
{
s->KeepAlive = 1;
#if defined(HDEBUG)
dbglogSend3("KEEP ALIVE!!!!!!!!!!!\n");
#endif
} else s->KeepAlive = 0;
}
else {
// For http 1.1, all connections are persistent by default!!
// https://en.wikipedia.org/wiki/HTTP_persistent_connection:
if (chttpGetResponseProtocol(s) >= HTTP_VERSION_1_1)
s->KeepAlive = 1;
}
tmpptr = chttpGetResponseHeader(s, "Content-length");
if (tmpptr != NULL)
s->ResponseContentLength = strtoul(tmpptr, NULL, 10);
else s->ResponseContentLength = 0;
#if defined(HDEBUG)
DBGPRINT(DBGLVL_DBG, "Done parsing headers. Method: %u Content-length: %llu\n",chttpGetRequestMethod(s), (unsigned long long int)s->ResponseContentLength);
#endif
//httpDumpGPCVars(s,NULL);
if (chttpGetRequestMethod(s) == HTTP_METHOD_GET)
{
tmpptr = chttpGetResponseHeader(s, "Upgrade");
if (tmpptr != NULL)
{
s->ConsumedAllData = 1;
if (strcasecmp(tmpptr,"websocket") != 0)
{
chttpSetParserError(s, HTTP_PARSER_ERROR_METHOD_NOT_IMPLEMENTED);
return;
}
}
if (s->ResponseContentLength == 0 && s->ChunkReadState != CRS_READING_CHUNK_HEADER)
s->ConsumedAllData = 1;
return;
}
else if (chttpGetRequestMethod(s) == HTTP_METHOD_HEAD || chttpGetRequestMethod(s) == HTTP_METHOD_OPTIONS)
s->ConsumedAllData = 1;
}
#if !defined(DEBUG)
static
#endif
TBool chttpNewDataIsAvailable (TIOBuf *io, TMemInputBuffer *mib)
{
assert (io && io->ExtraData.p);
TCHttp *s = CAST(io->ExtraData.p, TCHttp *);
if (unlikely(!s))
return FALSE;
s->LastInputChunk = mib;
#if defined(HDEBUG)
DBGPRINT(DBGLVL_DBG, "MpxCycle#%llu chttpNewDataIsAvailable: %u bytes: [%.*s]\n", (unsigned long long)mpxGetCycleNo(iobGetMultiplexer(io)), DataSize, (int)(DataSize>1024 ? 1024 : DataSize),DataBuf);
#endif
if (chttpGetState(s) == cstHTTP_REQUEST_SEND_WAITING_FOR_REPLY)
chttpSetState(s, cstPARSING_HTTP_VERSION);
char *tmpptr;
uint16_t State;
int32_t CurElemLen;
int16_t CRLF, CurChar;
int16_t PrevChar;
#define AddCurCharToLastElem() smbSendChar(s->LastElementData, (uint8_t)CurChar)
#define ClearLastElem() smbClear(s->LastElementData)
PrevChar = 0;
do
{
CurChar = chttpGetChar(s);
if (CurChar == IOB_END_OF_BUFFER)
break;
if (s->HeaderParseCompleted)
{
AddCurCharToLastElem();
}
else
{
CRLF = (CurChar == '\n' && PrevChar == '\r');// || (CurChar == '\n' && PrevChar == '\r'));
CurElemLen = smbGetLen(s->LastElementData);
State = chttpGetState(s);
switch(State)
{
case cstPARSING_HTTP_VERSION:
if (CurChar == 32)
{
s->HttpResponseVersion = HTTP_VERSION_UNDEFINED;
if (smbGetCharAt(s->LastElementData,5) == '1' && (smbGetCharAt(s->LastElementData,6) == '.'))
{
if (smbGetCharAt(s->LastElementData,7) == '0')
s->HttpResponseVersion = HTTP_VERSION_1_0;
else if (smbGetCharAt(s->LastElementData,7) == '1')
s->HttpResponseVersion = HTTP_VERSION_1_1;
}
//DBGPRINT(DBGLVL_DBG, "Protocol : %u %c %c %c\n",s->HttpRequestVersion,mbGetCharAt(s->LastElementData,5),mbGetCharAt(s->LastElementData,6),mbGetCharAt(s->LastElementData,7));
if (unlikely(s->HttpResponseVersion == HTTP_VERSION_UNDEFINED))
chttpSetParserError(s, HTTP_PARSER_ERROR_INVALID_HTTP_VERSION);
else chttpSetState(s, cstPARSING_HTTP_STATUS_CODE);
}
else {
if (unlikely(CurElemLen > 9))
chttpSetParserError(s, HTTP_PARSER_ERROR_INVALID_HTTP_VERSION);
else AddCurCharToLastElem();
}
break;
case cstPARSING_HTTP_STATUS_CODE:
if (CurChar == ' ' || CRLF)
{
smbTerminateStringSafe(s->LastElementData);
s->ResponseStatusCode = (uint16_t)atoi((const char *)smbGetBuf(s->LastElementData));
chttpSetState(s, cstPARSING_HTTP_STATUS_STRING);
}
else {
if (unlikely(CurElemLen > 9))
chttpSetParserError(s, HTTP_PARSER_ERROR_INVALID_HTTP_STATUS_CODE);
else AddCurCharToLastElem();
}
break;
case cstPARSING_HTTP_STATUS_STRING:
if (CRLF)
{
smbTerminateStringSafe(s->LastElementData);
chttpSetState(s, cstPARSING_HEADER_VAR_NAME);
}
else {
if (unlikely(CurElemLen > 500))
chttpSetParserError(s, HTTP_PARSER_ERROR_INVALID_HTTP_STATUS_CODE);
else AddCurCharToLastElem();
}
break;
case cstPARSING_HEADER_VAR_NAME:
if (CurElemLen > MAX_GPC_VAR_NAME_LEN) // Maximum variable name length is 64 characters
{
#if defined(HDEBUG)
dbglogSend3("Variable name is too long or too short for a request header variable\n");
#endif
chttpSetParserError(s, HTTP_PARSER_ERROR_VARNAME_TOO_LONG);
}
else if (CurChar == ':')
{
if (CurElemLen)
{
smbTerminateStringSafe(s->LastElementData);
if (strcasecmp((const char *)smbGetBuf(s->LastElementData),"Set-Cookie") == 0)
{ // This is a cookie. We must process it differently
chttpSetState(s, cstPARSING_COOKIE_NAME);
s->LastCookie = (TClientHTTPCookie *)chttpMAlloc(s, sizeof(TClientHTTPCookie));
memset(s->LastCookie, 0, sizeof(TClientHTTPCookie));
}
else {
s->LastVarName = chttpMAlloc(s, CurElemLen+1);
UnEscapeStr(
(const char *)smbGetBuf(s->LastElementData),
s->LastVarName,
CurElemLen+1);
chttpSetState(s, cstPARSING_HEADER_VAR_VALUE);
}
}
else {
chttpSetParserError(s, HTTP_PARSER_ERROR_HEADER_VARNAME_NOT_FOUND);
}
}
else if (CRLF)
{ // An empty line means we're done processing header!
chttpHeaderParseCompleted(s);
}
else AddCurCharToLastElem();
break;
case cstPARSING_HEADER_VAR_VALUE:
if (unlikely(CurElemLen > MAX_GPC_VAR_VALUE_LEN)) // Maximum variable name length is 64 characters
{
chttpSetParserError(s, HTTP_PARSER_ERROR_VARNAME_TOO_LONG);
}
else if (CRLF)
{
smbSetCharAt(s->LastElementData, CurElemLen-1, '\0'); // We must delete \r at the end
tmpptr = chttpMAlloc(s, CurElemLen);
UnEscapeStr((const char *)smbGetBuf(s->LastElementData), tmpptr, CurElemLen);
chttpAddResponseHeader(s, s->LastVarName, FALSE, tmpptr, FALSE);
chttpSetState(s, cstPARSING_HEADER_VAR_NAME);
}
else {
if (!(!CurElemLen && CurChar == ' ')) // We skip the first possible space before var value as in "Header: Value"
AddCurCharToLastElem();
}
break;
case cstPARSING_COOKIE_NAME:
if (unlikely(CurElemLen > MAX_GPC_VAR_NAME_LEN)) // Maximum variable name length is 64 characters
{
#if defined(HDEBUG)
dbglogSend3("Variable name is too long or too short for a uri variable\n");
#endif
chttpSetParserError(s, HTTP_PARSER_ERROR_VARNAME_TOO_LONG);
}
else if (CurChar == '=')
{
if (likely(CurElemLen))
{
smbSendChar(s->LastElementData, '\0'); // Let's terminate string by adding \0 to the end.
s->LastCookie->Name = chttpMAlloc(s, CurElemLen+1);
UnEscapeStr((const char *)smbGetBuf(s->LastElementData), (char *)s->LastCookie->Name, CurElemLen+1);
TKeyValue *KV = (TKeyValue *)chttpMAlloc(s, sizeof(TKeyValue));
KV->KeyAsStrPtr = s->LastCookie->Name;
KV->ValueAsVoidPtr = (void *)s->LastCookie;
kvGetOrSetWithStrKey(&s->ResponseCookies, KV);
chttpSetState(s, cstPARSING_COOKIE_VALUE);
}
else {
// Normally this should not happen but let's try to fix it!
ClearLastElem();
}
}
else if (CurChar == ';')
{
ClearLastElem();
}
else if (CRLF)
{
chttpSetState(s, cstPARSING_HEADER_VAR_NAME);
}
else AddCurCharToLastElem();
break;
case cstPARSING_COOKIE_VALUE:
if (unlikely(CurElemLen > MAX_GPC_VAR_VALUE_LEN)) // Maximum variable name length is 64 characters
{
chttpSetParserError(s, HTTP_PARSER_ERROR_VARNAME_TOO_LONG);
}
else if (CurChar == ';')
{
if (unlikely(CurElemLen == 0))
chttpSetParserError(s, HTTP_PARSER_ERROR_HEADER_VARNAME_NOT_FOUND);
smbSendChar(s->LastElementData, '\0'); // Let's terminate string by adding \0 to the end.
s->LastCookie->Value = chttpMAlloc(s, CurElemLen+1);
UnEscapeStr((const char *)smbGetBuf(s->LastElementData), (char *)s->LastCookie->Value, CurElemLen+1);
chttpSetState(s, cstPARSING_COOKIE_PROPERTY_NAME);
}
else if (CRLF)
{
if (unlikely(CurElemLen == 0))
chttpSetParserError(s, HTTP_PARSER_ERROR_HEADER_VARNAME_NOT_FOUND);
smbSetCharAt(s->LastElementData, CurElemLen-1, '\0'); // We must delete : at the end
s->LastCookie->Value = chttpMAlloc(s, CurElemLen+1);
UnEscapeStr((const char *)smbGetBuf(s->LastElementData), (char *)s->LastCookie->Value, CurElemLen+1);
chttpSetState(s, cstPARSING_HEADER_VAR_NAME);
} else AddCurCharToLastElem();
break;
case cstPARSING_COOKIE_PROPERTY_NAME:
if (unlikely(CurElemLen > MAX_GPC_VAR_NAME_LEN)) // Maximum variable name length is 64 characters
chttpSetParserError(s, HTTP_PARSER_ERROR_VARNAME_TOO_LONG);
else if (CurChar == '=')
{
smbSendChar(s->LastElementData, '\0'); // Let's terminate string by adding \0 to the end.
s->LastCookie->LastPropertyName = chttpStrDupLen(s, (const char *)smbGetBuf(s->LastElementData), smbGetLen(s->LastElementData));
chttpSetState(s, cstPARSING_COOKIE_PROPERTY_VALUE);
}
else if (CRLF)
{
if (unlikely(CurElemLen == 0))
chttpSetParserError(s, HTTP_PARSER_ERROR_HEADER_VARNAME_NOT_FOUND);
smbSetCharAt(s->LastElementData, CurElemLen-1, '\0'); // We must delete : at the end
chttpSetState(s, cstPARSING_HEADER_VAR_NAME);
tmpptr = (char *)smbGetBuf(s->LastElementData);
if (strcasecmp(tmpptr, "Secure") == 0)
s->LastCookie->Secure = 1;
else if (strcasecmp(tmpptr, "HttpOnly") == 0)
s->LastCookie->HttpOnly = 1;
}
else if (CurChar == ';')
{
smbSendChar(s->LastElementData, '\0'); // Let's terminate string by adding \0 to the end.
tmpptr = (char *)smbGetBuf(s->LastElementData);
if (strcasecmp(tmpptr, "Secure") == 0)
s->LastCookie->Secure = 1;
else if (strcasecmp(tmpptr, "HttpOnly") == 0)
s->LastCookie->HttpOnly = 1;
ClearLastElem();
} else AddCurCharToLastElem();
break;
case cstPARSING_COOKIE_PROPERTY_VALUE:
if (unlikely(CurElemLen > MAX_GPC_VAR_NAME_LEN)) // Maximum variable name length is 64 characters
chttpSetParserError(s, HTTP_PARSER_ERROR_VARNAME_TOO_LONG);
else if (CurChar == ';' || CRLF)
{
if (CRLF)
{
smbSetCharAt(s->LastElementData, CurElemLen-1, '\0'); // We must delete : at the end
chttpSetState(s, cstPARSING_HEADER_VAR_NAME);
}
else {
smbSendChar(s->LastElementData, '\0'); // Let's terminate string by adding \0 to the end.
chttpSetState(s, cstPARSING_COOKIE_PROPERTY_NAME);
}
tmpptr = chttpStrDup(s, (const char *)smbGetBuf(s->LastElementData));
if (strcasecmp(s->LastCookie->Name, "Expires") == 0)
s->LastCookie->Expires = tmpptr;
else if (strcasecmp(tmpptr, "Path") == 0)
s->LastCookie->Path = tmpptr;
else if (strcasecmp(tmpptr, "Domain") == 0)
s->LastCookie->Domain = tmpptr;
}
else AddCurCharToLastElem();
break;
}
// If we are just entering to a new state, we must clear state data buffer
if (State != chttpGetState(s))
{
#if defined(DEBUG)
//if (s->HeaderParseCompleted)
//DBGPRINT(DBGLVL_DBG, "State changed from %s to %s. Data : %s\n",httpGetConnectionStateStr(State),httpGetConnectionStateStr(httpGetState(s)),mbGetVal(s->LastElementData));
#endif
ClearLastElem();
PrevChar = 0;
} else PrevChar = CurChar;
}
} while (s->ParserError == HTTP_PARSER_ERROR_NONE && !s->ConsumedAllData);
if (unlikely(s->ChunkHeaderAndTrailerData && smbGetLen(s->ChunkHeaderAndTrailerData) > 128))
chttpSetParserError(s, HTTP_PARSER_ERROR_INVALID_CHUNK_BODY);
/*if (s->ParserError)
{
DBGPRINT(DBGLVL_DBG, "chttp Parser err: %u Str: %.*s\n", s->ParserError, (int)DataSize, DataBuf);
}*/
if (s->ConsumedAllData || s->ParserError != HTTP_PARSER_ERROR_NONE)
{
if (s->ParserError == HTTP_PARSER_ERROR_NONE && smbGetLen(s->LastElementData)>0)
{
// Let's check content encoding
// If it's gzip or deflate, we need to decompress content
const char *ContentEncoding = chttpGetResponseHeader(s,"Content-Encoding");
int32_t CompressionMethod = ZLIB_COMPRESSION_NONE;
if (ContentEncoding)
{
//DBGPRINT(DBGLVL_DBG, "ContentEncoding: %s\n", ContentEncoding);
if (strcasecmp(ContentEncoding, "gzip") == 0)
CompressionMethod = ZLIB_COMPRESSION_GZIP;
else if (strcasecmp(ContentEncoding, "deflate") == 0)
CompressionMethod = ZLIB_COMPRESSION_DEFLATE;
smbZlibDecompressSameBuf(s->LastElementData, CompressionMethod, 15);
smbTerminateStringSafe(s->LastElementData);
}
}
s->fncOnRequestCompleted(s);
chttpDestroyAndFree(s);
return TRUE;
}
return FALSE;
}
/**
* ConstructCommonHeaderStr construct the common request header lines for both GET and POST requests
* @param s TCHttp *
* @param InitialBufSize unsigned int; the initial size of the output buffer to be constructed
* @param CompleteHeader If TRUE, this is for a get request; the complete header will be returned with an empty CRLF line at the end
* @return
*/
#if !defined(DEBUG)
static
#endif
TMemBuf *ConstructCommonHeaderStr(TCHttp *s, unsigned int InitialBufSize)
{ // GET /path/to/file/index.html HTTP/1.0
// RFC says that we must always send the maximum http version we can handle
TKeyValue *KV;
TDLLNode *Node;
TMemBuf *O = mbInitNew(InitialBufSize);
// If there is no post variables, we don't need to use post!
if (s->RequestMethod == HTTP_METHOD_POST && kvIsEmpty(&s->RequestGetOrPOSTVars))
s->RequestMethod = HTTP_METHOD_GET;
// TParsedURI *A = ocGetLastConnectedAddr(s->OConn); // A->OriginalAddrStr
//assert(A != NULL);
if (!chttpGetRequestHeader(s, "User-Agent"))
chttpAddRequestHeader(s, "User-Agent", FALSE, "NewsSearchCrawler", FALSE);
//if (!chttpGetRequestHeader(s, "Accept-Encoding"))
//chttpAddRequestHeader(s, "Accept-Encoding", FALSE, "gzip", FALSE);
if (!chttpGetRequestHeader(s, "Accept"))
chttpAddRequestHeader(s, "Accept", FALSE, "*/*", FALSE);
if (!chttpGetRequestHeader(s, "Connection"))
chttpAddRequestHeader(s, "Connection", FALSE, "Keep-Alive", FALSE);
if (s->RequestMethod != HTTP_METHOD_GET || kvIsEmpty(&s->RequestGetOrPOSTVars))
mbPrint(O, "%s %s HTTP/1.1\r\nHost: %s\r\n",
httpGetMethodStr(s->RequestMethod),
s->URIWithoutHost, s->Host);
else
{ // Get method. And we have some GET parameters to append to URI
mbPrint(O, "%s %s?", httpGetMethodStr(s->RequestMethod), s->URIWithoutHost);
unsigned t=0;
kvForEachFIFO(&s->RequestGetOrPOSTVars, Node)
{
KV = (TKeyValue *)dllGetContainerStructPtr(Node, TKeyValue);
if (t)
mbSendChar(O, '&');
mbEscapeStr(O, (const uint8_t *)KV->KeyAsStrPtr, 0);
mbSendChar(O, '=');
mbEscapeStr(O, (const uint8_t *)KV->ValueAsStrPtr, 0);
t++;
}
mbPrint(O, " HTTP/1.1\r\nHost: %s\r\n",
httpGetMethodStr(s->RequestMethod),
s->Host);
}
// Then, we send the headers
kvForEachFIFO(&s->RequestHeaders, Node)
{
KV = (TKeyValue *)dllGetContainerStructPtr(Node, TKeyValue);
mbPrint(O, "%s: %s\r\n", KV->KeyAsStrPtr, KV->ValueAsStrPtr);
}
//DBGPRINT(DBGLVL_DBG, "%.*s\n", (int)smbGetLen(O), O->smb.StrBuf);
return O;
}
static void chttpAddCustomEncryptedLoginPacket(TCHttp *s, TCustomEncParamsForClient *P, TSimpleMemBuf *LoginPacket)
{
const uint8_t EncType = cencGetEncTypeClient(P);
TSimpleMemBuf smb;
smbInit(&smb, 1600);
cencPack(&smb, P, smbGetBuf(LoginPacket), (unsigned)smbGetLen(LoginPacket));
DBGPRINT(DBGLVL_DBG, "Sending EncPack: %.*B\n", (int)smbGetLenAsUInt32(&smb), smbGetBuf(&smb));
if (EncType == CUSTOM_ENC_TYPE_X25519_AND_NTRUPRIME)
{ // It will be custom encrypted connection with X25519 and NTRU Prime DH key exchange