forked from negrutiu/nsis-nscurl
-
Notifications
You must be signed in to change notification settings - Fork 0
/
curl.c
1547 lines (1391 loc) · 58.4 KB
/
curl.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
//? Marius Negrutiu (mailto:[email protected]) :: 2019/11/20
//? Make HTTP/S requests using libcurl
#include "main.h"
#include "curl.h"
#include "crypto.h"
#if !defined(NO_ADDITIONAL_CERT_LIST)
#include <openssl/ssl.h>
#endif
typedef struct {
volatile HMODULE hPinnedModule;
CRITICAL_SECTION csLock;
CHAR szVersion[64];
CHAR szUserAgent[128];
} CURL_GLOBALS;
CURL_GLOBALS g_Curl = {0};
#define DEFAULT_HEADERS_VIRTUAL_SIZE CURL_MAX_HTTP_HEADER /// 100KB
#define DEFAULT_UKNOWN_VIRTUAL_SIZE 1024 * 1024 * 200 /// 200MB
//x #define DEBUG_TRANSFER_SLOWDOWN 50 /// Delays during transfer
// ----------------------------------------------------------------------
// TODO: Check if remote content has changed at /RECONNECT
// TODO: Client certificate (CURLOPT_SSLCERT, CURLOPT_PROXY_SSLCERT)
// TODO: Certificate revocation (CURLOPT_CRLFILE, CURLOPT_PROXY_CRLFILE)
// TODO: Secure Proxy (CURLOPT_PROXY_CAPATH, CURLOPT_PROXY_SSL_VERIFYHOST, CURLOPT_PROXY_SSL_VERIFYPEER)
// TODO: HPKP - HTTP public key pinning (CURLOPT_PINNEDPUBLICKEY, CURLOPT_PROXY_PINNEDPUBLICKEY)
// TODO: Time conditional request (CURLOPT_TIMECONDITION, CURLOPT_TIMEVALUE)
// TODO: Query SSL info (certificate chain, cypher, etc.)
// ----------------------------------------------------------------------
//+ CurlRequestSizes
void CurlRequestComputeNumbers( _In_ PCURL_REQUEST pReq, _Out_opt_ PULONG64 piSizeTotal, _Out_opt_ PULONG64 piSizeXferred, _Out_opt_ PSHORT piPercent, _Out_opt_ PBOOL pbDown )
{
assert( pReq );
// Uploading data goes first. Downloading server's response (remote content) goes second
if (pReq->Runtime.iUlTotal == 0 && pReq->Runtime.iDlTotal == 0 && pReq->Runtime.iResumeFrom > 0) {
// Connecting (phase 0)
if (pbDown)
*pbDown = TRUE;
if (piSizeTotal)
*piSizeTotal = 0;
if (piSizeXferred)
*piSizeXferred = pReq->Runtime.iResumeFrom;
if (piPercent)
*piPercent = -1; /// Unknown size
} else if (pReq->Runtime.iDlXferred > 0 || pReq->Runtime.iDlTotal > 0 || pReq->Runtime.iResumeFrom > 0) {
// Downloading (phase 2)
if (pbDown)
*pbDown = TRUE;
if (piSizeTotal)
*piSizeTotal = pReq->Runtime.iDlTotal + pReq->Runtime.iResumeFrom;
if (piSizeXferred)
*piSizeXferred = pReq->Runtime.iDlXferred + pReq->Runtime.iResumeFrom;
if (piPercent) {
*piPercent = -1; /// Unknown size
if (pReq->Runtime.iDlTotal + pReq->Runtime.iResumeFrom > 0)
*piPercent = (SHORT)(((pReq->Runtime.iDlXferred + pReq->Runtime.iResumeFrom) * 100) / (pReq->Runtime.iDlTotal + pReq->Runtime.iResumeFrom));
}
} else {
// Uploading (phase 1)
if (pbDown)
*pbDown = FALSE;
if (piSizeTotal)
*piSizeTotal = pReq->Runtime.iUlTotal;
if (piSizeXferred)
*piSizeXferred = pReq->Runtime.iUlXferred;
if (piPercent) {
*piPercent = -1; /// Unknown size
if (pReq->Runtime.iUlTotal > 0)
*piPercent = (SHORT)((pReq->Runtime.iUlXferred * 100) / pReq->Runtime.iUlTotal);
}
}
}
//+ CurlRequestFormatError
void CurlRequestFormatError( _In_ PCURL_REQUEST pReq, _In_opt_ LPTSTR pszError, _In_opt_ ULONG iErrorLen, _Out_opt_ PBOOLEAN pbSuccess, _Out_opt_ PULONG piErrorCode )
{
if (pszError)
pszError[0] = 0;
if (pbSuccess)
*pbSuccess = TRUE;
if (piErrorCode)
*piErrorCode = 0;
if (pReq) {
if (pReq->Error.iWin32 != ERROR_SUCCESS) {
// Win32 error code
if (pbSuccess) *pbSuccess = FALSE;
if (pszError) _sntprintf( pszError, iErrorLen, _T( "0x%x \"%s\"" ), pReq->Error.iWin32, pReq->Error.pszWin32 );
if (piErrorCode) *piErrorCode = pReq->Error.iWin32;
} else if (pReq->Error.iCurl != CURLE_OK) {
// CURL error
if (pbSuccess) *pbSuccess = FALSE;
if (pszError) _sntprintf( pszError, iErrorLen, _T( "0x%x \"%hs\"" ), pReq->Error.iCurl, pReq->Error.pszCurl );
if (piErrorCode) *piErrorCode = pReq->Error.iCurl;
} else {
// HTTP status
if (piErrorCode) *piErrorCode = pReq->Error.iHttp;
if ((pReq->Error.iHttp == 0) || (pReq->Error.iHttp >= 200 && pReq->Error.iHttp < 300)) {
if (pszError) _sntprintf( pszError, iErrorLen, _T( "OK" ) );
} else {
if (pbSuccess) *pbSuccess = FALSE;
if (pszError) {
// Some servers don't return the Reason-Phrase in their Status-Line (e.g. https://files.loseapp.com/file)
if (!pReq->Error.pszHttp) {
if (pReq->Error.iHttp >= 200 && pReq->Error.iHttp < 300) {
pReq->Error.pszHttp = MyStrDup( eA2A, "OK" );
} else if (pReq->Error.iHttp == 400) {
pReq->Error.pszHttp = MyStrDup( eA2A, "Bad Request" );
} else if (pReq->Error.iHttp == 401) {
pReq->Error.pszHttp = MyStrDup( eA2A, "Unauthorized" );
} else if (pReq->Error.iHttp == 403) {
pReq->Error.pszHttp = MyStrDup( eA2A, "Forbidden" );
} else if (pReq->Error.iHttp == 404) {
pReq->Error.pszHttp = MyStrDup( eA2A, "Not Found" );
} else if (pReq->Error.iHttp == 405) {
pReq->Error.pszHttp = MyStrDup( eA2A, "Method Not Allowed" );
} else if (pReq->Error.iHttp == 500) {
pReq->Error.pszHttp = MyStrDup( eA2A, "Internal Server Error" );
} else {
pReq->Error.pszHttp = MyStrDup( eA2A, "Error" );
}
}
_sntprintf( pszError, iErrorLen, _T( "%d \"%hs\"" ), pReq->Error.iHttp, pReq->Error.pszHttp );
}
}
}
}
}
//+ CurlRequestErrorType
LPCSTR CurlRequestErrorType( _In_ PCURL_REQUEST pReq )
{
if (pReq) {
if (pReq->Error.iWin32 != ERROR_SUCCESS) {
return "win32";
} else if (pReq->Error.iCurl != CURLE_OK) {
return "curl";
} else if (pReq->Error.iHttp >= 0) {
return "http";
}
}
return "";
}
//+ CurlRequestErrorCode
ULONG CurlRequestErrorCode( _In_ PCURL_REQUEST pReq )
{
if (pReq) {
if (pReq->Error.iWin32 != ERROR_SUCCESS) {
return pReq->Error.iWin32;
} else if (pReq->Error.iCurl != CURLE_OK) {
return pReq->Error.iCurl;
} else if (pReq->Error.iHttp > 0) {
return pReq->Error.iHttp;
}
}
return 0;
}
// ____________________________________________________________________________________________________________________________________ //
// //
//++ CurlInitialize
ULONG CurlInitialize()
{
TRACE( _T( "%hs()\n" ), __FUNCTION__ );
InitializeCriticalSection( &g_Curl.csLock );
{
// Plugin version
// Default user agent
TCHAR szBuf[MAX_PATH] = _T( "" ), szVer[MAX_PATH];
GetModuleFileName( g_hInst, szBuf, ARRAYSIZE( szBuf ) );
MyReadVersionString( szBuf, _T( "FileVersion" ), szVer, ARRAYSIZE( szVer ) );
MyStrCopy( eT2A, g_Curl.szVersion, ARRAYSIZE( g_Curl.szVersion ), szVer );
_snprintf( g_Curl.szUserAgent, ARRAYSIZE( g_Curl.szUserAgent ), "nscurl/%s", g_Curl.szVersion );
}
return ERROR_SUCCESS;
}
//++ CurlDestroy
void CurlDestroy()
{
TRACE( _T( "%hs()\n" ), __FUNCTION__ );
DeleteCriticalSection( &g_Curl.csLock );
}
//++ CurlInitializeLibcurl
ULONG CurlInitializeLibcurl()
{
if (InterlockedCompareExchangePointer( (void*)&g_Curl.hPinnedModule, NULL, NULL ) == NULL) {
TCHAR szPath[MAX_PATH];
TRACE( _T( "%hs()\n" ), __FUNCTION__ );
// Initialize libcurl
curl_global_init( CURL_GLOBAL_ALL );
//! CAUTION:
//? https://curl.haxx.se/libcurl/c/curl_global_cleanup.html
//? curl_global_cleanup does not block waiting for any libcurl-created threads
//? to terminate (such as threads used for name resolving). If a module containing libcurl
//? is dynamically unloaded while libcurl-created threads are still running then your program
//? may crash or other corruption may occur. We recommend you do not run libcurl from any module
//? that may be unloaded dynamically. This behavior may be addressed in the future.
// It's confirmed that NScurl.dll crashes when unloaded after curl_global_cleanup() gets called
// Easily reproducible in XP and Vista
//! We'll pin it in memory forever and never call curl_global_cleanup()
if (GetModuleFileName( g_hInst, szPath, ARRAYSIZE( szPath ) ) > 0) {
g_Curl.hPinnedModule = LoadLibrary( szPath );
assert( g_Curl.hPinnedModule );
}
// kernel32!GetModuleHandleEx is available in XP+
//x GetModuleHandleEx( GET_MODULE_HANDLE_EX_FLAG_PIN | GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS, (LPCTSTR)__FUNCTION__, (HMODULE*)&g_Curl.hPinnedModule );
}
return ERROR_SUCCESS;
}
//++ CurlBuiltinCacert
//? Retrieve the built-in cacert.pem
ULONG CurlBuiltinCacert( _Out_ struct curl_blob *blob )
{
ULONG e = ERROR_SUCCESS;
ULONG len = 0;
assert( g_hInst != NULL );
assert( g_variables != NULL );
e = MyQueryResource( (HMODULE)g_hInst, _T( "cacert.pem" ), MAKEINTRESOURCE( 1 ), 1033, &blob->data, &len );
if (e == ERROR_SUCCESS) {
blob->len = len;
blob->flags = CURL_BLOB_NOCOPY;
}
return e;
}
//++ CurlFindHeader
void CurlFindHeader( _In_ LPCSTR pszHeaders, _In_ LPCSTR pszHeaderName, _Out_ LPTSTR pszHeaderValue, _In_ ULONG iMaxLen )
{
if (pszHeaderValue)
pszHeaderValue[0] = 0;
if (pszHeaders && *pszHeaders && pszHeaderName && *pszHeaderName) {
LPCSTR psz1, psz2;
int iHeaderLen = lstrlenA( pszHeaderName ), iLineLen;
for (psz1 = pszHeaders; psz1 && *psz1; ) {
for (psz2 = psz1; *psz2 != '\0' && *psz2 != '\r' && *psz2 != '\n'; psz2++);
iLineLen = (int)(psz2 - psz1);
if (iLineLen > iHeaderLen && psz1[iHeaderLen] == ':' && CompareStringA( CP_ACP, NORM_IGNORECASE, psz1, __min( iLineLen, iHeaderLen ), pszHeaderName, -1 ) == CSTR_EQUAL) {
for (psz1 += iHeaderLen + 1; *psz1 == ' ' || *psz1 == '\t'; psz1++);
MyStrCopyN( eA2T, pszHeaderValue, iMaxLen, psz1, (int)(psz2 - psz1) );
break;
}
for (psz1 = psz2; *psz1 == '\r' || *psz1 == '\n'; psz1++);
}
}
}
//++ CurlParseRequestParam
BOOL CurlParseRequestParam( _In_ ULONG iParamIndex, _In_ LPTSTR pszParam, _In_ int iParamMaxLen, _Out_ PCURL_REQUEST pReq )
{
BOOL bRet = TRUE;
assert( iParamMaxLen && pszParam && pReq );
if (iParamIndex == 0) {
//? Params[0] is always the HTTP method
//x assert(
//x lstrcmpi( pszParam, _T( "GET" ) ) == 0 ||
//x lstrcmpi( pszParam, _T( "POST" ) ) == 0 ||
//x lstrcmpi( pszParam, _T( "HEAD" ) ) == 0
//x );
MyFree( pReq->pszMethod );
pReq->pszMethod = MyStrDup( eT2A, pszParam );
} else if (iParamIndex == 1) {
//? Params[1] is always the URL
MyFree( pReq->pszURL );
pReq->pszURL = MyStrDup( eT2A, pszParam );
{ // Replace backslashes with slashes (\ -> /)
//? scheme://[user@]host[:port]/path[?query][#fragment]
LPSTR psz;
for (psz = (LPSTR)pReq->pszURL; *psz != '\0' && *psz != '?' && *psz != '#'; psz++)
if (*psz == '\\')
*psz = '/';
}
} else if (iParamIndex == 2) {
//? Params[2] is always the output file/memory
MyFree( pReq->pszPath );
if (lstrcmpi( pszParam, _T( "MEMORY" ) ) != 0)
pReq->pszPath = MyStrDup( eT2T, pszParam );
} else if (lstrcmpi( pszParam, _T( "/HEADER" ) ) == 0) {
if (popstring( pszParam ) == NOERROR && *pszParam) {
// The string may contain multiple headers delimited by \r\n
LPTSTR psz1, psz2;
LPSTR pszA;
for (psz1 = pszParam; *psz1; ) {
for (; (*psz1 == _T('\r')) || (*psz1 == _T('\n')); psz1++); /// Skip \r\n
for (psz2 = psz1; (*psz2 != _T('\0')) && (*psz2 != _T('\r')) && (*psz2 != _T('\n')); psz2++); /// Find next \r\n\0
if (psz2 > psz1) {
if ((pszA = MyStrDupN( eT2A, psz1, (int)(psz2 - psz1) )) != NULL) {
pReq->pOutHeaders = curl_slist_append( pReq->pOutHeaders, pszA );
MyFree( pszA );
}
}
psz1 = psz2;
}
}
} else if (lstrcmpi( pszParam, _T( "/POST" ) ) == 0) {
LPSTR pszFilename = NULL, pszType = NULL, pszName = NULL, pszData = NULL;
IDATA Data;
/// Extract optional parameters "filename=XXX" and "type=XXX"
int e = NOERROR;
while (e == NOERROR) {
if ((e = popstring( pszParam )) == NOERROR) {
if (CompareString( CP_ACP, NORM_IGNORECASE, pszParam, 9, _T( "filename=" ), -1 ) == CSTR_EQUAL) {
pszFilename = MyStrDup( eT2A, pszParam + 9 );
} else if (CompareString( CP_ACP, NORM_IGNORECASE, pszParam, 5, _T( "type=" ), -1 ) == CSTR_EQUAL) {
pszType = MyStrDup( eT2A, pszParam + 5 );
} else {
break;
}
}
}
/// Extract mandatory parameters "name" and IDATA
if (e == NOERROR) {
pszName = MyStrDup( eT2A, pszParam );
if ((e = popstring( pszParam )) == NOERROR) {
if (IDataParseParam( pszParam, iParamMaxLen, &Data )) {
// Store 5-tuple MIME form part
pReq->pPostVars = curl_slist_append( pReq->pPostVars, pszFilename ? pszFilename : "" );
pReq->pPostVars = curl_slist_append( pReq->pPostVars, pszType ? pszType : "" );
pReq->pPostVars = curl_slist_append( pReq->pPostVars, pszName ? pszName : "" );
{
CHAR szType[] = {Data.Type, '\0'};
pReq->pPostVars = curl_slist_append( pReq->pPostVars, szType );
}
{
if (Data.Type == IDATA_TYPE_STRING) {
pszData = MyStrDup( eA2A, Data.Str );
} else if (Data.Type == IDATA_TYPE_FILE) {
pszData = MyStrDup( eT2A, Data.File );
} else if (Data.Type == IDATA_TYPE_MEM) {
pszData = EncBase64( Data.Mem, (size_t)Data.Size );
} else {
assert( !"Unexpected IDATA type" );
}
assert( pszData );
pReq->pPostVars = curl_slist_append( pReq->pPostVars, pszData );
}
IDataDestroy( &Data );
}
}
}
MyFree( pszFilename );
MyFree( pszType );
MyFree( pszName );
MyFree( pszData );
} else if (lstrcmpi( pszParam, _T( "/PROXY" ) ) == 0) {
if (popstring( pszParam ) == NOERROR && *pszParam) {
MyFree( pReq->pszProxy );
pReq->pszProxy = MyStrDup( eT2A, pszParam );
}
} else if (lstrcmpi( pszParam, _T( "/DATA" ) ) == 0) {
if (popstring( pszParam ) == NOERROR && *pszParam)
IDataParseParam( pszParam, iParamMaxLen, &pReq->Data );
} else if (lstrcmpi( pszParam, _T( "/RESUME" ) ) == 0) {
pReq->bResume = TRUE;
} else if (lstrcmpi( pszParam, _T( "/INSIST" ) ) == 0) {
pReq->bInsist = TRUE;
} else if (lstrcmpi( pszParam, _T( "/CONNECTTIMEOUT" ) ) == 0 || lstrcmpi( pszParam, _T( "/TIMEOUT" ) ) == 0) {
if (popstring( pszParam ) == NOERROR && *pszParam)
pReq->iConnectTimeout = (ULONG)MyStringToMilliseconds( pszParam );
} else if (lstrcmpi( pszParam, _T( "/COMPLETETIMEOUT" ) ) == 0) {
if (popstring( pszParam ) == NOERROR && *pszParam)
pReq->iCompleteTimeout = (ULONG)MyStringToMilliseconds( pszParam );
} else if (lstrcmpi( pszParam, _T( "/LOWSPEEDLIMIT" ) ) == 0) {
ULONG bps = popint();
if (popstring( pszParam ) == NOERROR && *pszParam) {
pReq->iLowSpeedLimit = bps;
pReq->iLowSpeedTime = (ULONG)MyStringToMilliseconds( pszParam ) / 1000;
pReq->iLowSpeedTime = __max( pReq->iLowSpeedTime, 3 ); /// seconds
}
} else if (lstrcmpi( pszParam, _T( "/SPEEDCAP" ) ) == 0) {
pReq->iSpeedCap = popint();
} else if (lstrcmpi( pszParam, _T( "/DEPEND" ) ) == 0) {
pReq->iDependencyId = popint();
} else if (lstrcmpi( pszParam, _T( "/REFERER" ) ) == 0 || lstrcmpi( pszParam, _T( "/REFERRER" ) ) == 0) {
if (popstring( pszParam ) == NOERROR && *pszParam) {
MyFree( pReq->pszReferrer );
pReq->pszReferrer = MyStrDup( eT2A, pszParam );
}
} else if (lstrcmpi( pszParam, _T( "/USERAGENT" ) ) == 0) {
if (popstring( pszParam ) == NOERROR && *pszParam) {
MyFree( pReq->pszAgent );
pReq->pszAgent = MyStrDup( eT2A, pszParam );
}
} else if (lstrcmpi( pszParam, _T( "/NOREDIRECT" ) ) == 0) {
pReq->bNoRedirect = TRUE;
} else if (lstrcmpi( pszParam, _T( "/AUTH" ) ) == 0) {
int e;
pReq->iAuthType = CURLAUTH_ANY;
if ((e = popstring( pszParam )) == NOERROR) {
if (CompareString( CP_ACP, NORM_IGNORECASE, pszParam, 5, _T( "type=" ), -1 ) == CSTR_EQUAL) {
LPCTSTR pszType = pszParam + 5;
if (lstrcmpi( pszType, _T( "basic" ) ) == 0)
pReq->iAuthType = CURLAUTH_BASIC;
else if (lstrcmpi( pszType, _T( "digest" ) ) == 0)
pReq->iAuthType = CURLAUTH_DIGEST;
else if (lstrcmpi( pszType, _T( "digestie" ) ) == 0)
pReq->iAuthType = CURLAUTH_DIGEST_IE;
else if (lstrcmpi( pszType, _T( "bearer" ) ) == 0)
pReq->iAuthType = CURLAUTH_BEARER;
e = popstring( pszParam );
}
if (e == NOERROR) {
// TODO: Encrypt user/pass/token in memory
if (pReq->iAuthType == CURLAUTH_BEARER) {
pReq->pszPass = MyStrDup( eT2A, pszParam ); /// OAuth 2.0 token (stored as password)
} else {
pReq->pszUser = MyStrDup( eT2A, pszParam );
if ((e = popstring( pszParam )) == NOERROR)
pReq->pszPass = MyStrDup( eT2A, pszParam );
}
}
}
} else if (lstrcmpi( pszParam, _T( "/TLSAUTH" ) ) == 0) {
if (popstring( pszParam ) == NOERROR) {
// TODO: Encrypt user/pass/token in memory
pReq->pszTlsUser = MyStrDup( eT2A, pszParam );
if (popstring( pszParam ) == NOERROR)
pReq->pszTlsPass = MyStrDup( eT2A, pszParam );
}
} else if (lstrcmpi( pszParam, _T( "/CACERT" ) ) == 0) {
if (popstring( pszParam ) == NOERROR) { /// pszParam may be empty ("")
MyFree( pReq->pszCacert );
pReq->pszCacert = MyStrDup( eT2A, pszParam );
}
} else if (lstrcmpi( pszParam, _T( "/CERT" ) ) == 0) {
if (popstring( pszParam ) == NOERROR && *pszParam) {
/// Validate SHA1 hash
if (lstrlen( pszParam ) == 40) {
int i;
for (i = 0; isxdigit( pszParam[i] ); i++);
if (i == 40) {
LPSTR psz = MyStrDup( eT2A, pszParam );
if (psz) {
pReq->pCertList = curl_slist_append( pReq->pCertList, psz );
MyFree( psz );
}
}
}
}
} else if (lstrcmpi( pszParam, _T( "/DEBUG" ) ) == 0) {
int e = popstring( pszParam );
if (e == NOERROR && lstrcmpi( pszParam, _T( "nodata" ) ) == 0) {
pReq->bNoDebugData = TRUE;
e = popstring( pszParam );
}
if (e == NOERROR && *pszParam) {
MyFree( pReq->pszDebugFile );
pReq->pszDebugFile = MyStrDup( eT2T, pszParam );
}
} else if (lstrcmpi( pszParam, _T( "/TAG" ) ) == 0) {
if (popstring( pszParam ) == NOERROR) { /// pszParam may be empty ("")
MyFree( pReq->pszTag );
if (*pszParam)
pReq->pszTag = MyStrDup( eT2A, pszParam );
}
} else if (lstrcmpi( pszParam, _T( "/MARKOFTHEWEB" ) ) == 0 || lstrcmpi( pszParam, _T( "/Zone.Identifier" ) ) == 0) {
pReq->bMarkOfTheWeb = TRUE;
} else if (lstrcmpi( pszParam, _T( "/DOH" ) ) == 0) {
if (popstring( pszParam ) == NOERROR) { /// pszParam may be empty ("")
MyFree( pReq->pszDOH );
if (*pszParam)
pReq->pszDOH = MyStrDup( eT2A, pszParam );
}
} else {
bRet = FALSE; /// This parameter is not valid for Request
}
return bRet;
}
#if !defined(NO_ADDITIONAL_CERT_LIST)
//++ OpenSSLVerifyCallback
int OpenSSLVerifyCallback( int preverify_ok, X509_STORE_CTX *x509_ctx )
{
//? This function gets called to evaluate server's SSL certificate chain
//? The calls are made sequentially for each certificate in the chain
//? This usually happens three times per connection: #2(root certificate), #1(intermediate certificate), #0(user certificate)
//? Our logic:
//? * We return TRUE for every certificate, to get a chance to inspect the next in chain
//? * We return the final value when we reach the last certificate (depth 0)
//? If we're dealing with a TRUSTED certificate we force a positive response
//? Otherwise we return whatever verdict OpenSSL has already assigned to the chain
UCHAR Thumbprint[20]; /// sha1
char szThumbprint[41];
struct curl_slist *p;
SSL *ssl = X509_STORE_CTX_get_ex_data( x509_ctx, SSL_get_ex_data_X509_STORE_CTX_idx() );
SSL_CTX *ssl_ctx = SSL_get_SSL_CTX( ssl );
PCURL_REQUEST pReq = (PCURL_REQUEST)SSL_CTX_get_app_data( ssl_ctx );
X509 *cert = X509_STORE_CTX_get_current_cert( x509_ctx ); /// Current certificate in chain
int err = X509_STORE_CTX_get_error( x509_ctx ); /// Current OpenSSL certificate validation error
int depth = X509_STORE_CTX_get_error_depth( x509_ctx ); /// Certificate index/depth in the chain. Starts with root certificate (e.g. #2), ends with user certificate (#0)
//x X509_NAME_oneline( X509_get_subject_name( cert ), szSubject, ARRAYSIZE( szSubject ) );
//x X509_NAME_oneline( X509_get_issuer_name( cert ), szIssuer, ARRAYSIZE( szIssuer ) );
// Extract certificate SHA1 fingerprint
X509_digest( cert, EVP_sha1(), Thumbprint, NULL );
MyFormatBinaryHexA( Thumbprint, sizeof( Thumbprint ), szThumbprint, sizeof( szThumbprint ) );
// Verify against our trusted certificate list
for (p = pReq->pCertList; p; p = p->next) {
if (lstrcmpiA( p->data, szThumbprint ) == 0) {
pReq->Runtime.bTrustedCert = TRUE;
X509_STORE_CTX_set_error( x509_ctx, X509_V_OK );
break;
}
}
// Verdict
if (depth > 0) {
TRACE( _T( "Certificate( #%d, \"%hs\", PreVerify{OK:%hs, Err:%d} ) = %hs, Response{OK:%hs, Err:%d}\n" ), depth, szThumbprint, preverify_ok ? "TRUE" : "FALS", err, p ? "TRUSTED" : "UNKNOWN", "TRUE", err );
return TRUE;
} else {
if (pReq->Runtime.bTrustedCert) {
/// We've found at least one TRUSTED certificate
/// Clear all errors, return a positive verdict
X509_STORE_CTX_set_error( x509_ctx, X509_V_OK );
TRACE( _T( "Certificate( #%d, \"%hs\", PreVerify{OK:%hs, Err:%d} ) = %hs, Response{OK:%hs, Err:%d}\n" ), depth, szThumbprint, preverify_ok ? "TRUE" : "FALS", err, p ? "TRUSTED" : "UNKNOWN", "TRUE", X509_V_OK );
return TRUE;
}
/// We haven't found any TRUSTED certificate
/// Return whatever verdict already made by OpenSSL
TRACE( _T( "Certificate( #%d, \"%hs\", PreVerify{OK:%hs, Err:%d} ) = %hs, Response{OK:%hs, Err:%d}\n" ), depth, szThumbprint, preverify_ok ? "TRUE" : "FALS", err, p ? "TRUSTED" : "UNKNOWN", preverify_ok ? "TRUE" : "FALS", err );
return preverify_ok;
}
}
//++ CurlSSLCallback
//? This callback function gets called by libcurl just before the initialization of an SSL connection
CURLcode CurlSSLCallback( CURL *curl, void *ssl_ctx, void *userptr )
{
SSL_CTX *pssl = (SSL_CTX*)ssl_ctx;
SSL_CTX_set_app_data( pssl, userptr );
SSL_CTX_set_verify( pssl, SSL_VERIFY_PEER, OpenSSLVerifyCallback);
return CURLE_OK;
}
#endif
//++ CurlHeaderCallback
size_t CurlHeaderCallback( char *buffer, size_t size, size_t nitems, void *userdata )
{
PCURL_REQUEST pReq = (PCURL_REQUEST)userdata;
LPSTR psz1, psz2;
const char* range;
assert( pReq && pReq->Runtime.pCurl );
if (0 == _strnicmp(buffer, "Content-Range: ", 15)) { // icase starts_with
range = strchr(buffer + 15, '/');
if (range)
pReq->Runtime.iRangeEnd = _atoi64(++range);
}
//x TRACE( _T( "%hs( \"%hs\" )\n" ), __FUNCTION__, buffer );
// NOTE: This callback function receives incoming headers one at a time
// Headers from multiple (redirected) connections are separated by an empty line ("\r\n")
// We only want to keep the headers from the last connection
if (pReq->Runtime.InHeaders.iSize == 0 || /// First connection
(
pReq->Runtime.InHeaders.iSize > 4 &&
pReq->Runtime.InHeaders.pMem[pReq->Runtime.InHeaders.iSize - 4] == '\r' &&
pReq->Runtime.InHeaders.pMem[pReq->Runtime.InHeaders.iSize - 3] == '\n' &&
pReq->Runtime.InHeaders.pMem[pReq->Runtime.InHeaders.iSize - 2] == '\r' &&
pReq->Runtime.InHeaders.pMem[pReq->Runtime.InHeaders.iSize - 1] == '\n')
)
{
// The last received header is an empty line ("\r\n")
// Discard existing headers and start collecting a new set
VirtualMemoryReset( &pReq->Runtime.InHeaders );
// Extract HTTP status text from header
// e.g. "HTTP/1.1 200 OK" -> "OK"
// e.g. "HTTP/1.1 404 NOT FOUND" -> "NOT FOUND"
// e.g. "HTTP/1.1 200 " -> Some servers don't return the Reason-Phrase in their Status-Line (e.g. https://files.loseapp.com/file)
MyFree( pReq->Error.pszHttp );
for (psz1 = buffer; (*psz1 != ' ') && (*psz1 != '\0'); psz1++); /// Find first whitespace
if (*psz1++ == ' ') {
for (; (*psz1 != ' ') && (*psz1 != '\0'); psz1++); /// Find second whitespace
if (*psz1++ == ' ') {
for (psz2 = psz1; (*psz2 != '\r') && (*psz2 != '\n') && (*psz2 != '\0'); psz2++); /// Find trailing \r\n
if (psz2 > psz1)
pReq->Error.pszHttp = MyStrDupN( eA2A, psz1, (int)(psz2 - psz1) );
}
}
// Collect HTTP connection info
/// Server IP address
curl_easy_getinfo( pReq->Runtime.pCurl, CURLINFO_PRIMARY_IP, &psz1 );
MyFree( pReq->Runtime.pszServerIP );
pReq->Runtime.pszServerIP = MyStrDup( eA2A, psz1 );
/// Server port
curl_easy_getinfo( pReq->Runtime.pCurl, CURLINFO_PRIMARY_PORT, &pReq->Runtime.iServerPort );
// Collect last effective URL
MyFree( pReq->Runtime.pszFinalURL );
curl_easy_getinfo( pReq->Runtime.pCurl, CURLINFO_EFFECTIVE_URL, &psz1 );
pReq->Runtime.pszFinalURL = MyStrDup( eA2A, psz1 );
}
// Collect incoming headers
return VirtualMemoryAppend( &pReq->Runtime.InHeaders, buffer, size * nitems );
}
//++ CurlReadCallback
size_t CurlReadCallback( char *buffer, size_t size, size_t nitems, void *instream )
{
curl_off_t l = 0;
PCURL_REQUEST pReq = (PCURL_REQUEST)instream;
assert( pReq && pReq->Runtime.pCurl );
#ifdef DEBUG_TRANSFER_SLOWDOWN
Sleep( DEBUG_TRANSFER_SLOWDOWN );
#endif
if (pReq->Data.Type == IDATA_TYPE_STRING || pReq->Data.Type == IDATA_TYPE_MEM) {
// Input string/memory buffer
assert( pReq->Runtime.iDataPos <= pReq->Data.Size );
l = __min( size * nitems, pReq->Data.Size - pReq->Runtime.iDataPos );
CopyMemory( buffer, (PCCH)pReq->Data.Str + pReq->Runtime.iDataPos, (size_t)l );
pReq->Runtime.iDataPos += l;
} else if (pReq->Data.Type == IDATA_TYPE_FILE) {
// Input file
if (MyValidHandle( pReq->Runtime.hInFile )) {
ULONG iRead;
if (ReadFile( pReq->Runtime.hInFile, (LPVOID)buffer, size * nitems, &iRead, NULL )) {
l = iRead;
pReq->Runtime.iDataPos += iRead;
} else {
l = CURL_READFUNC_ABORT;
}
}
} else {
assert( !"Unexpected IDATA type" );
}
//x TRACE( _T( "%hs( Size:%u ) = Size:%u\n" ), __FUNCTION__, (ULONG)(size * nitems), (ULONG)l );
return (size_t)l;
}
//++ CurlWriteCallback
size_t CurlWriteCallback( char *ptr, size_t size, size_t nmemb, void *userdata )
{
PCURL_REQUEST pReq = (PCURL_REQUEST)userdata;
assert( pReq && pReq->Runtime.pCurl );
#ifdef DEBUG_TRANSFER_SLOWDOWN
Sleep( DEBUG_TRANSFER_SLOWDOWN );
#endif
if (MyValidHandle( pReq->Runtime.hOutFile )) {
// Write to output file
ULONG iWritten = 0;
if (WriteFile( pReq->Runtime.hOutFile, ptr, (ULONG)(size * nmemb), &iWritten, NULL )) {
return iWritten;
} else {
pReq->Error.iWin32 = GetLastError();
pReq->Error.pszWin32 = MyFormatError( pReq->Error.iWin32 );
}
} else {
// Initialize output virtual memory (once)
if (!pReq->Runtime.OutData.pMem) {
curl_off_t iMaxSize;
if (curl_easy_getinfo( pReq->Runtime.pCurl, CURLINFO_CONTENT_LENGTH_DOWNLOAD_T, &iMaxSize ) != CURLE_OK)
iMaxSize = DEFAULT_UKNOWN_VIRTUAL_SIZE;
if (iMaxSize == -1)
iMaxSize = DEFAULT_UKNOWN_VIRTUAL_SIZE;
VirtualMemoryInitialize( &pReq->Runtime.OutData, (SIZE_T)iMaxSize );
}
// Write to RAM
return VirtualMemoryAppend( &pReq->Runtime.OutData, ptr, size * nmemb );
}
return 0;
}
//++ CurlProgressCallback
int CurlProgressCallback( void *clientp, curl_off_t dltotal, curl_off_t dlnow, curl_off_t ultotal, curl_off_t ulnow )
{
PCURL_REQUEST pReq = (PCURL_REQUEST)clientp;
curl_off_t iSpeed;
curl_off_t iTimeElapsed, iTimeRemaining = 0;
assert( pReq && pReq->Runtime.pCurl );
if (TermSignaled())
return CURLE_ABORTED_BY_CALLBACK;
if (CurlRequestGetAbortFlag( pReq ) != FALSE)
return CURLE_ABORTED_BY_CALLBACK;
//x TRACE( _T( "%hs( DL:%I64u/%I64u, UL:%I64u/%I64u )\n" ), __FUNCTION__, dlnow, dltotal, ulnow, ultotal );
curl_easy_getinfo( pReq->Runtime.pCurl, CURLINFO_TOTAL_TIME_T, &iTimeElapsed );
if (dlnow > 0) {
/// Downloading (phase 2)
curl_easy_getinfo( pReq->Runtime.pCurl, CURLINFO_SPEED_DOWNLOAD_T, &iSpeed );
iTimeRemaining = (dltotal * iTimeElapsed) / dlnow - iTimeElapsed;
} else {
/// Uploading (phase 1)
curl_easy_getinfo( pReq->Runtime.pCurl, CURLINFO_SPEED_UPLOAD_T, &iSpeed );
if (ulnow > 0)
iTimeRemaining = (ultotal * iTimeElapsed) / ulnow - iTimeElapsed;
}
pReq->Runtime.iTimeElapsed = GetTickCount() - pReq->Runtime.iTimeStart; /// Aggregated elapsed time
pReq->Runtime.iTimeRemaining = iTimeRemaining / 1000; /// us -> ms
pReq->Runtime.iDlTotal = dltotal;
pReq->Runtime.iDlXferred = dlnow;
pReq->Runtime.iUlTotal = ultotal;
pReq->Runtime.iUlXferred = ulnow;
pReq->Runtime.iSpeed = iSpeed;
MemoryBarrier();
return CURLE_OK;
}
//++ CurlDebugCallback
int CurlDebugCallback( CURL *handle, curl_infotype type, char *data, size_t size, void *userptr )
{
PCURL_REQUEST pReq = (PCURL_REQUEST)userptr;
assert( pReq && pReq->Runtime.pCurl == handle );
if (type == CURLINFO_HEADER_OUT) {
// NOTE: This callback function receives outgoing headers all at once
// A block of outgoing headers are sent for every (redirected) connection
// We'll collect only the last block
VirtualMemoryReset( &pReq->Runtime.OutHeaders );
VirtualMemoryAppend( &pReq->Runtime.OutHeaders, data, size );
} else if (type == CURLINFO_HEADER_IN) {
// NOTE: This callback function receives incoming headers one at a time
// NOTE: Incoming header are handled by CurlHeaderCallback(..)
}
// Debug file
if (MyValidHandle( pReq->Runtime.hDebugFile )) {
ULONG iBytes;
BOOLEAN bNoData = FALSE; //? /DEBUG nodata <file>
// Prefix
{
LPSTR psz;
switch (type) {
case CURLINFO_TEXT: psz = "[-] "; break;
case CURLINFO_HEADER_IN: psz = "[<h] "; break;
case CURLINFO_HEADER_OUT: psz = "[>h] "; break;
case CURLINFO_DATA_IN: psz = "[<d] "; bNoData = pReq->bNoDebugData; break;
case CURLINFO_DATA_OUT: psz = "[>d] "; bNoData = pReq->bNoDebugData; break;
case CURLINFO_SSL_DATA_IN: psz = "[<s] "; break;
case CURLINFO_SSL_DATA_OUT: psz = "[>s] "; break;
default: psz = "[?] ";
}
WriteFile( pReq->Runtime.hDebugFile, psz, lstrlenA( psz ), &iBytes, NULL );
}
// Data
if (bNoData) {
LPSTR psz;
TCHAR szSize[64];
MyFormatBytes( size, szSize, ARRAYSIZE( szSize ) );
if ((psz = MyStrDup( eT2A, szSize )) != NULL) {
WriteFile( pReq->Runtime.hDebugFile, psz, (ULONG)lstrlenA(psz), &iBytes, NULL );
WriteFile( pReq->Runtime.hDebugFile, "\n", 1, &iBytes, NULL );
MyFree( psz );
}
} else {
const size_t iMaxLen = 1024 * 128;
const size_t iLineLen = 512;
LPSTR pszLine;
size_t iOutLen;
if ((pszLine = (LPSTR)malloc( iLineLen )) != NULL) {
for (iOutLen = 0; iOutLen < iMaxLen; ) {
size_t i, n = __min( iLineLen, size - iOutLen );
if (n == 0)
break;
for (i = 0; i < n; i++) {
pszLine[i] = data[iOutLen + i];
if (pszLine[i] == '\n') {
i++;
break;
} else if ((pszLine[i] < 32 || pszLine[i] > 126) && pszLine[i] != '\r' && pszLine[i] != '\t') {
pszLine[i] = '.';
}
}
WriteFile( pReq->Runtime.hDebugFile, pszLine, (ULONG)i, &iBytes, NULL );
if (i < 1 || pszLine[i - 1] != '\n')
WriteFile( pReq->Runtime.hDebugFile, "\n", 1, &iBytes, NULL );
iOutLen += i;
}
free( pszLine );
}
}
}
return 0;
}
//++ CurlTransfer
void CurlTransfer( _In_ PCURL_REQUEST pReq )
{
CURL *curl;
curl_mime *form = NULL;
CHAR szError[CURL_ERROR_SIZE] = ""; /// Runtime error buffer
BOOL bGET;
#define StringIsEmpty(psz) ((psz) != NULL && ((psz)[0] == 0))
if (!pReq)
return;
if (!pReq->pszURL || !*pReq->pszURL) {
pReq->Error.iWin32 = ERROR_INVALID_PARAMETER;
pReq->Error.pszWin32 = MyFormatError( pReq->Error.iWin32 );
return;
}
// HTTP GET
bGET = !pReq->pszMethod || StringIsEmpty( pReq->pszMethod ) || (lstrcmpiA( pReq->pszMethod, "GET" ) == 0);
// Input file
if (pReq->pszMethod && (
lstrcmpiA( pReq->pszMethod, "PUT" ) == 0 ||
(lstrcmpiA( pReq->pszMethod, "POST" ) == 0 && !pReq->pPostVars)
))
{
if (pReq->Data.Type == IDATA_TYPE_FILE) {
ULONG e = ERROR_SUCCESS;
pReq->Runtime.hInFile = CreateFile( (LPCTSTR)pReq->Data.File, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, NULL, OPEN_EXISTING, 0, NULL );
if (MyValidHandle( pReq->Runtime.hInFile )) {
// NOTE: kernel32!GetFileSizeEx is only available in XP+
LARGE_INTEGER l;
l.LowPart = GetFileSize( pReq->Runtime.hInFile, (PULONG)&l.HighPart );
if (l.LowPart != INVALID_FILE_SIZE) {
/// Store file size in iDataSize
pReq->Data.Size = l.QuadPart;
} else {
e = GetLastError();
}
} else {
e = GetLastError();
}
if (e != ERROR_SUCCESS && pReq->Error.iWin32 == ERROR_SUCCESS) {
pReq->Error.iWin32 = e;
pReq->Error.pszWin32 = MyFormatError( e );
TRACE( _T( "[!] CreateFile( DataFile:%s ) = %s\n" ), (LPCTSTR)pReq->Data.File, pReq->Error.pszWin32 );
}
}
}
// Output file
if (pReq->pszPath && *pReq->pszPath) {
ULONG e = ERROR_SUCCESS;
MyCreateDirectory( pReq->pszPath, TRUE ); // Create intermediate directories
pReq->Runtime.hOutFile = CreateFile( pReq->pszPath, GENERIC_WRITE, FILE_SHARE_READ, NULL, (pReq->bResume ? OPEN_ALWAYS : CREATE_ALWAYS), FILE_ATTRIBUTE_NORMAL, NULL );
if (MyValidHandle( pReq->Runtime.hOutFile )) {
/// Resume?
if (pReq->bResume) {
LARGE_INTEGER l;
l.LowPart = GetFileSize( pReq->Runtime.hOutFile, (PULONG)&l.HighPart );
if (l.LowPart != INVALID_FILE_SIZE) {
pReq->Runtime.iResumeFrom = l.QuadPart;
if (SetFilePointer( pReq->Runtime.hOutFile, 0, NULL, FILE_END ) == INVALID_SET_FILE_POINTER) {
e = GetLastError();
}
} else {
e = GetLastError();
}
}
} else {
e = GetLastError();
}
if (e == ERROR_SUCCESS && pReq->bMarkOfTheWeb) {
ULONG l = lstrlen( pReq->pszPath ) + sizeof( ":Zone.Identifier" );
LPTSTR psz = (LPTSTR)MyAlloc( l * sizeof( TCHAR ) );
if (psz) {
HANDLE h;
_sntprintf( psz, l, _T( "%s:Zone.Identifier" ), pReq->pszPath );
if ((h = CreateFile( psz, GENERIC_WRITE, FILE_SHARE_READ, NULL, CREATE_ALWAYS, 0, NULL )) != INVALID_HANDLE_VALUE) {
CHAR zone[] = "[ZoneTransfer]\r\nZoneId=3\r\n";
WriteFile( h, (LPCVOID)zone, lstrlenA( zone ), &l, NULL );
CloseHandle( h );
}
MyFree( psz );
}
}
if (e != ERROR_SUCCESS && pReq->Error.iWin32 == ERROR_SUCCESS) {
pReq->Error.iWin32 = e;
pReq->Error.pszWin32 = MyFormatError( e );
TRACE( _T( "[!] CreateFile( OutFile:%s ) = %s\n" ), pReq->pszPath, pReq->Error.pszWin32 );
}
}
// Debug file
if (pReq->pszDebugFile && *pReq->pszDebugFile) {
ULONG e = ERROR_SUCCESS;
MyCreateDirectory( pReq->pszDebugFile, TRUE ); // Create intermediate directories
pReq->Runtime.hDebugFile = CreateFile( pReq->pszDebugFile, GENERIC_WRITE, FILE_SHARE_READ, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL );
if (!MyValidHandle( pReq->Runtime.hOutFile )) {
e = GetLastError();
TRACE( _T( "[!] CreateFile( DebugFile:%s ) = 0x%x\n" ), pReq->pszDebugFile, e );
}
}
if (pReq->Error.iWin32 == ERROR_SUCCESS) {
// Transfer
curl = curl_easy_init(); // TODO: Cache
if (curl) {
/// Remember it
pReq->Runtime.pCurl = curl;
pReq->Runtime.iTimeStart = GetTickCount();
/// Error buffer
szError[0] = ANSI_NULL;
curl_easy_setopt( curl, CURLOPT_ERRORBUFFER, szError );
curl_easy_setopt( curl, CURLOPT_USERAGENT, pReq->pszAgent ? pReq->pszAgent : g_Curl.szUserAgent );
if (pReq->pszReferrer)
curl_easy_setopt( curl, CURLOPT_REFERER, pReq->pszReferrer );
if (pReq->bNoRedirect) {
curl_easy_setopt( curl, CURLOPT_FOLLOWLOCATION, FALSE );
} else {
curl_easy_setopt( curl, CURLOPT_FOLLOWLOCATION, TRUE ); /// Follow redirects
curl_easy_setopt( curl, CURLOPT_MAXREDIRS, 10 );
}
if (pReq->iConnectTimeout > 0)
curl_easy_setopt( curl, CURLOPT_CONNECTTIMEOUT_MS, pReq->iConnectTimeout );
if (pReq->iCompleteTimeout > 0)
curl_easy_setopt( curl, CURLOPT_TIMEOUT_MS, pReq->iCompleteTimeout );
if (pReq->iSpeedCap > 0) {
curl_easy_setopt( curl, CURLOPT_MAX_SEND_SPEED_LARGE, (curl_off_t)pReq->iSpeedCap );
curl_easy_setopt( curl, CURLOPT_MAX_RECV_SPEED_LARGE, (curl_off_t)pReq->iSpeedCap );
}
if (pReq->iLowSpeedLimit > 0) {
curl_easy_setopt( curl, CURLOPT_LOW_SPEED_LIMIT, (long)pReq->iLowSpeedLimit );
if (pReq->iLowSpeedTime > 0)
curl_easy_setopt( curl, CURLOPT_LOW_SPEED_TIME, (long)pReq->iLowSpeedTime );
}
if (pReq->pszDOH)
curl_easy_setopt( curl, CURLOPT_DOH_URL, pReq->pszDOH );
curl_easy_setopt( curl, CURLOPT_ACCEPT_ENCODING, "" ); /// Send Accept-Encoding header with all supported encodings
/// SSL
if (!StringIsEmpty(pReq->pszCacert) || pReq->pCertList) {
// SSL validation enabled