forked from OSGeo/gdal
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcpl_http.cpp
2683 lines (2382 loc) · 99.8 KB
/
cpl_http.cpp
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
/******************************************************************************
*
* Project: libcurl based HTTP client
* Purpose: libcurl based HTTP client
* Author: Frank Warmerdam, [email protected]
*
******************************************************************************
* Copyright (c) 2006, Frank Warmerdam
* Copyright (c) 2008-2013, Even Rouault <even dot rouault at spatialys.com>
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
****************************************************************************/
#include "cpl_port.h"
#include "cpl_http.h"
#include <cstddef>
#include <cstring>
#include <algorithm>
#include <array>
#include <map>
#include <mutex>
#include <string>
#include <vector>
#include "cpl_http.h"
#include "cpl_error.h"
#include "cpl_multiproc.h"
// gcc or clang complains about C-style cast in #define like CURL_ZERO_TERMINATED
#if defined(__GNUC__)
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wold-style-cast"
#endif
#ifdef HAVE_CURL
#include "cpl_curl_priv.h"
#ifdef HAVE_OPENSSL_CRYPTO
#include <openssl/err.h>
#include <openssl/ssl.h>
#include <openssl/engine.h>
#include <openssl/x509v3.h>
#if defined(WIN32)
#include <wincrypt.h>
#endif
#endif
#ifdef HAVE_SIGACTION
#include <signal.h>
#endif
#define unchecked_curl_easy_setopt(handle,opt,param) CPL_IGNORE_RET_VAL(curl_easy_setopt(handle,opt,param))
#endif // HAVE_CURL
CPL_CVSID("$Id$")
// list of named persistent http sessions
#ifdef HAVE_CURL
static std::map<CPLString, CURL*>* poSessionMap = nullptr;
static std::map<CPLString, CURLM*>* poSessionMultiMap = nullptr;
static CPLMutex *hSessionMapMutex = nullptr;
static bool bHasCheckVersion = false;
static bool bSupportGZip = false;
static bool bSupportHTTP2 = false;
#if defined(WIN32) && defined(HAVE_OPENSSL_CRYPTO)
static std::vector<X509*> *poWindowsCertificateList = nullptr;
#if ( OPENSSL_VERSION_NUMBER < 0x10100000L )
#define EVP_PKEY_get0_RSA(x) (x->pkey.rsa)
#define EVP_PKEY_get0_DSA(x) (x->pkey.dsa)
#define X509_get_extension_flags(x) (x->ex_flags)
#define X509_get_key_usage(x) (x->ex_kusage)
#define X509_get_extended_key_usage(x) (x->ex_xkusage)
#endif
#endif // defined(WIN32) && defined(HAVE_OPENSSL_CRYPTO)
#if defined(HAVE_OPENSSL_CRYPTO) && OPENSSL_VERSION_NUMBER < 0x10100000
// Ported from https://curl.haxx.se/libcurl/c/opensslthreadlock.html
static CPLMutex** pahSSLMutex = nullptr;
static void CPLOpenSSLLockingFunction(int mode, int n,
const char * /*file*/, int /*line*/)
{
if(mode & CRYPTO_LOCK)
{
CPLAcquireMutex( pahSSLMutex[n], 3600.0 );
}
else
{
CPLReleaseMutex( pahSSLMutex[n] );
}
}
static unsigned long CPLOpenSSLIdCallback(void)
{
return static_cast<unsigned long>(CPLGetPID());
}
static void CPLOpenSSLInit()
{
if( strstr(curl_version(), "OpenSSL") &&
CPLTestBool(CPLGetConfigOption("CPL_OPENSSL_INIT_ENABLED", "YES")) &&
CRYPTO_get_id_callback() == nullptr )
{
pahSSLMutex = static_cast<CPLMutex**>(
CPLMalloc( CRYPTO_num_locks() * sizeof(CPLMutex*) ) );
for(int i = 0; i < CRYPTO_num_locks(); i++)
{
pahSSLMutex[i] = CPLCreateMutex();
CPLReleaseMutex( pahSSLMutex[i] );
}
CRYPTO_set_id_callback(CPLOpenSSLIdCallback);
CRYPTO_set_locking_callback(CPLOpenSSLLockingFunction);
}
}
static void CPLOpenSSLCleanup()
{
if( pahSSLMutex )
{
for(int i = 0; i < CRYPTO_num_locks(); i++)
{
CPLDestroyMutex(pahSSLMutex[i]);
}
CPLFree(pahSSLMutex);
pahSSLMutex = nullptr;
CRYPTO_set_id_callback(nullptr);
CRYPTO_set_locking_callback(nullptr);
}
}
#endif
#if defined(WIN32) && defined (HAVE_OPENSSL_CRYPTO)
/************************************************************************/
/* CPLWindowsCertificateListCleanup() */
/************************************************************************/
static void CPLWindowsCertificateListCleanup()
{
if( poWindowsCertificateList )
{
for( auto&& pX509: *poWindowsCertificateList )
{
X509_free(pX509);
}
delete poWindowsCertificateList;
poWindowsCertificateList = nullptr;
}
}
/************************************************************************/
/* LoadCAPICertificates() */
/************************************************************************/
static
CPLErr LoadCAPICertificates(const char *pszName,
std::vector<X509*> *poCertificateList)
{
CPLAssert(pszName);
CPLAssert(poCertificateList);
HCERTSTORE pCertStore = CertOpenSystemStore(
reinterpret_cast<HCRYPTPROV_LEGACY>(nullptr), pszName);
if( pCertStore == nullptr )
{
CPLError(CE_Failure, CPLE_AppDefined,
"CPLLoadCAPICertificates(): Unable open system "
"certificate store %s.", pszName);
return CE_Failure;
}
PCCERT_CONTEXT pCertificate = CertEnumCertificatesInStore( pCertStore, nullptr );
while( pCertificate != nullptr )
{
X509 *pX509 = d2i_X509( nullptr,
const_cast<unsigned char const **>(&pCertificate->pbCertEncoded),
pCertificate->cbCertEncoded );
if( pX509 == nullptr )
{
CPLError(CE_Warning, CPLE_AppDefined,
"CPLLoadCAPICertificates(): CertEnumCertificatesInStore() "
"returned a null certificate, skipping." );
}
else
{
#ifdef DEBUG_VERBOSE
char szSubject[256] = {0};
CPLString osSubject;
X509_NAME *pName = X509_get_subject_name( pX509 );
if( pName )
{
X509_NAME_oneline(pName, szSubject, sizeof(szSubject));
osSubject = szSubject;
}
if( !osSubject.empty() )
CPLDebug("HTTP", "SSL Certificate: %s", osSubject.c_str());
#endif
poCertificateList->push_back(pX509);
}
pCertificate = CertEnumCertificatesInStore(pCertStore, pCertificate);
}
CertCloseStore(pCertStore, 0);
return CE_None;
}
/************************************************************************/
/* CPL_ssl_ctx_callback() */
/************************************************************************/
// Load certificates from Windows Crypto API store.
static
CURLcode CPL_ssl_ctx_callback(CURL *, void *pSSL, void *)
{
SSL_CTX *pSSL_CTX = static_cast<SSL_CTX*>(pSSL);
if( pSSL_CTX == nullptr )
{
CPLError(CE_Failure, CPLE_AppDefined,
"CPL_ssl_ctx_callback(): OpenSSL context pointer is NULL.");
return CURLE_ABORTED_BY_CALLBACK;
}
static std::mutex goMutex;
{
std::lock_guard<std::mutex> oLock(goMutex);
if( poWindowsCertificateList == nullptr )
{
poWindowsCertificateList = new std::vector<X509*>();
if( !poWindowsCertificateList )
{
CPLError(CE_Failure, CPLE_AppDefined,
"CPL_ssl_ctx_callback(): Unable to allocate "
"structure to hold certificates.");
return CURLE_FAILED_INIT;
}
const std::array<const char*, 3> aszStores
{{"CA", "AuthRoot", "ROOT"}};
for( auto&& pszStore: aszStores )
{
if( LoadCAPICertificates(pszStore, poWindowsCertificateList)
== CE_Failure )
{
CPLError(CE_Failure, CPLE_AppDefined,
"CPL_ssl_ctx_callback(): Unable to load certificates "
"from '%s' store.", pszStore);
return CURLE_FAILED_INIT;
}
}
CPLDebug("HTTP",
"Loading %d certificates from Windows store.",
static_cast<int>(poWindowsCertificateList->size()));
}
}
X509_STORE *pX509Store = SSL_CTX_get_cert_store(pSSL_CTX);
for( X509 *x509 : *poWindowsCertificateList )
X509_STORE_add_cert(pX509Store, x509);
return CURLE_OK;
}
#endif // defined(WIN32) && defined (HAVE_OPENSSL_CRYPTO)
/************************************************************************/
/* CheckCurlFeatures() */
/************************************************************************/
static void CheckCurlFeatures()
{
CPLMutexHolder oHolder( &hSessionMapMutex );
if( !bHasCheckVersion )
{
const char* pszVersion = curl_version();
CPLDebug("HTTP", "%s", pszVersion);
bSupportGZip = strstr(pszVersion, "zlib/") != nullptr;
bSupportHTTP2 = strstr(curl_version(), "nghttp2/") != nullptr;
bHasCheckVersion = true;
curl_version_info_data* data = curl_version_info(CURLVERSION_NOW);
if( data->version_num < LIBCURL_VERSION_NUM )
{
CPLError(CE_Warning, CPLE_AppDefined,
"GDAL was built against curl %d.%d.%d, but is "
"running against %s. Runtime failure is likely !",
LIBCURL_VERSION_MAJOR,
LIBCURL_VERSION_MINOR,
LIBCURL_VERSION_PATCH,
data->version);
}
else if( data->version_num > LIBCURL_VERSION_NUM )
{
CPLDebug("HTTP",
"GDAL was built against curl %d.%d.%d, but is "
"running against %s.",
LIBCURL_VERSION_MAJOR,
LIBCURL_VERSION_MINOR,
LIBCURL_VERSION_PATCH,
data->version);
}
#if defined(HAVE_OPENSSL_CRYPTO) && OPENSSL_VERSION_NUMBER < 0x10100000
CPLOpenSSLInit();
#endif
}
}
/************************************************************************/
/* CPLWriteFct() */
/* */
/* Append incoming text to our collection buffer, reallocating */
/* it larger as needed. */
/************************************************************************/
class CPLHTTPResultWithLimit
{
public:
CPLHTTPResult* psResult = nullptr;
int nMaxFileSize = 0;
};
static size_t
CPLWriteFct(void *buffer, size_t size, size_t nmemb, void *reqInfo)
{
CPLHTTPResultWithLimit *psResultWithLimit =
static_cast<CPLHTTPResultWithLimit *>(reqInfo);
CPLHTTPResult* psResult = psResultWithLimit->psResult;
int nBytesToWrite = static_cast<int>(nmemb)*static_cast<int>(size);
int nNewSize = psResult->nDataLen + nBytesToWrite + 1;
if( nNewSize > psResult->nDataAlloc )
{
psResult->nDataAlloc = static_cast<int>(nNewSize * 1.25 + 100);
GByte* pabyNewData = static_cast<GByte *>(
VSIRealloc(psResult->pabyData, psResult->nDataAlloc));
if( pabyNewData == nullptr )
{
VSIFree(psResult->pabyData);
psResult->pabyData = nullptr;
psResult->pszErrBuf = CPLStrdup(CPLString().Printf("Out of memory allocating %d bytes for HTTP data buffer.", psResult->nDataAlloc));
psResult->nDataAlloc = psResult->nDataLen = 0;
return 0;
}
psResult->pabyData = pabyNewData;
}
memcpy( psResult->pabyData + psResult->nDataLen, buffer, nBytesToWrite );
psResult->nDataLen += nBytesToWrite;
psResult->pabyData[psResult->nDataLen] = 0;
if( psResultWithLimit->nMaxFileSize > 0 &&
psResult->nDataLen > psResultWithLimit->nMaxFileSize )
{
CPLError(CE_Failure, CPLE_AppDefined, "Maximum file size reached");
return 0;
}
return nmemb;
}
/************************************************************************/
/* CPLHdrWriteFct() */
/************************************************************************/
static size_t CPLHdrWriteFct( void *buffer, size_t size, size_t nmemb,
void *reqInfo )
{
CPLHTTPResult *psResult = static_cast<CPLHTTPResult *>(reqInfo);
// Copy the buffer to a char* and initialize with zeros (zero
// terminate as well).
size_t nBytes = size * nmemb;
char* pszHdr = static_cast<char *>(CPLCalloc(1, nBytes+1));
memcpy(pszHdr, buffer, nBytes);
size_t nIdx = nBytes - 1;
// Remove end of line characters
while( nIdx > 0 && (pszHdr[nIdx] == '\r' || pszHdr[nIdx] == '\n') )
{
pszHdr[nIdx] = 0;
nIdx --;
}
char *pszKey = nullptr;
const char *pszValue = CPLParseNameValue(pszHdr, &pszKey );
if( pszKey && pszValue )
{
psResult->papszHeaders =
CSLAddNameValue(psResult->papszHeaders, pszKey, pszValue);
}
CPLFree(pszHdr);
CPLFree(pszKey);
return nmemb;
}
#if CURL_AT_LEAST_VERSION(7,56,0)
/************************************************************************/
/* CPLHTTPReadFunction() */
/************************************************************************/
static size_t CPLHTTPReadFunction(char *buffer, size_t size, size_t nitems, void *arg)
{
return VSIFReadL(buffer, size, nitems, static_cast<VSILFILE*>(arg));
}
/************************************************************************/
/* CPLHTTPSeekFunction() */
/************************************************************************/
static int CPLHTTPSeekFunction(void *arg, curl_off_t offset, int origin)
{
if( VSIFSeekL( static_cast<VSILFILE*>(arg), offset, origin ) == 0 )
return CURL_SEEKFUNC_OK;
else
return CURL_SEEKFUNC_FAIL;
}
/************************************************************************/
/* CPLHTTPFreeFunction() */
/************************************************************************/
static void CPLHTTPFreeFunction(void *arg)
{
VSIFCloseL(static_cast<VSILFILE*>(arg));
}
#endif // CURL_AT_LEAST_VERSION(7,56,0)
typedef struct {
GDALProgressFunc pfnProgress;
void *pProgressArg;
} CurlProcessData, *CurlProcessDataL;
static int NewProcessFunction(void *p,
curl_off_t dltotal, curl_off_t dlnow,
curl_off_t ultotal, curl_off_t ulnow)
{
CurlProcessDataL pData = static_cast<CurlProcessDataL>(p);
if( nullptr != pData && pData->pfnProgress ) {
if( dltotal > 0 )
{
const double dfDone = double(dlnow) / dltotal;
return pData->pfnProgress(dfDone, "Downloading ...",
pData->pProgressArg) == TRUE ? 0 : 1;
}
else if( ultotal > 0 )
{
const double dfDone = double(ulnow) / ultotal;
return pData->pfnProgress(dfDone, "Uploading ...",
pData->pProgressArg) == TRUE ? 0 : 1;
}
}
return 0;
}
static int ProcessFunction(void *p, double dltotal, double dlnow,
double ultotal, double ulnow)
{
return NewProcessFunction(p, static_cast<curl_off_t>(dltotal),
static_cast<curl_off_t>(dlnow),
static_cast<curl_off_t>(ultotal),
static_cast<curl_off_t>(ulnow));
}
#endif /* def HAVE_CURL */
/************************************************************************/
/* CPLHTTPGetOptionsFromEnv() */
/************************************************************************/
typedef struct
{
const char* pszEnvVar;
const char* pszOptionName;
} TupleEnvVarOptionName;
constexpr TupleEnvVarOptionName asAssocEnvVarOptionName[] =
{
{ "GDAL_HTTP_VERSION", "HTTP_VERSION" },
{ "GDAL_HTTP_CONNECTTIMEOUT", "CONNECTTIMEOUT" },
{ "GDAL_HTTP_TIMEOUT", "TIMEOUT" },
{ "GDAL_HTTP_LOW_SPEED_TIME", "LOW_SPEED_TIME" },
{ "GDAL_HTTP_LOW_SPEED_LIMIT", "LOW_SPEED_LIMIT" },
{ "GDAL_HTTP_USERPWD", "USERPWD" },
{ "GDAL_HTTP_PROXY", "PROXY" },
{ "GDAL_HTTPS_PROXY", "HTTPS_PROXY" },
{ "GDAL_HTTP_PROXYUSERPWD", "PROXYUSERPWD" },
{ "GDAL_PROXY_AUTH", "PROXYAUTH" },
{ "GDAL_HTTP_NETRC", "NETRC" },
{ "GDAL_HTTP_MAX_RETRY", "MAX_RETRY" },
{ "GDAL_HTTP_RETRY_DELAY", "RETRY_DELAY" },
{ "GDAL_CURL_CA_BUNDLE", "CAINFO" },
{ "CURL_CA_BUNDLE", "CAINFO" },
{ "SSL_CERT_FILE", "CAINFO" },
{ "GDAL_HTTP_HEADER_FILE", "HEADER_FILE" },
{ "GDAL_HTTP_CAPATH", "CAPATH" },
{ "GDAL_HTTP_SSL_VERIFYSTATUS", "SSL_VERIFYSTATUS" },
{ "GDAL_HTTP_USE_CAPI_STORE", "USE_CAPI_STORE" },
};
char** CPLHTTPGetOptionsFromEnv()
{
char** papszOptions = nullptr;
for( size_t i = 0; i < CPL_ARRAYSIZE(asAssocEnvVarOptionName); ++i )
{
const char* pszVal = CPLGetConfigOption(
asAssocEnvVarOptionName[i].pszEnvVar, nullptr);
if( pszVal != nullptr )
{
papszOptions = CSLSetNameValue(papszOptions,
asAssocEnvVarOptionName[i].pszOptionName, pszVal);
}
}
return papszOptions;
}
/************************************************************************/
/* CPLHTTPGetNewRetryDelay() */
/************************************************************************/
double CPLHTTPGetNewRetryDelay(int response_code, double dfOldDelay,
const char* pszErrBuf,
const char* pszCurlError)
{
if( response_code == 429 || response_code == 500 ||
(response_code >= 502 && response_code <= 504) ||
// S3 sends some client timeout errors as 400 Client Error
(response_code == 400 && pszErrBuf && strstr(pszErrBuf, "RequestTimeout")) ||
(pszCurlError && (strstr(pszCurlError, "Connection timed out")
|| strstr(pszCurlError, "Operation timed out")
|| strstr(pszCurlError, "Connection was reset"))) )
{
// 'Operation tmied out': seen during some long running operation 'hang'
// no error but no response from server and we are in the cURL loop
// infinitely.
// 'Connection was reset': was found with Azure: server resets
// connection during TLS handshake (10054 error code). It seems like
// the server process crashed or something forced TCP reset;
// the request succeeds on retry.
// Use an exponential backoff factor of 2 plus some random jitter
// We don't care about cryptographic quality randomness, hence:
// coverity[dont_call]
return dfOldDelay * (2 + rand() * 0.5 / RAND_MAX);
}
else
{
return 0;
}
}
#ifdef HAVE_CURL
/************************************************************************/
/* CPLHTTPEmitFetchDebug() */
/************************************************************************/
static void CPLHTTPEmitFetchDebug(const char* pszURL,
const char* pszExtraDebug = "")
{
const char* pszArobase = strchr(pszURL, '@');
const char* pszSlash = strchr(pszURL, '/');
const char* pszColon = (pszSlash) ? strchr(pszSlash, ':') : nullptr;
if( pszArobase != nullptr && pszColon != nullptr && pszArobase - pszColon > 0 )
{
/* http://user:[email protected] */
char* pszSanitizedURL = CPLStrdup(pszURL);
pszSanitizedURL[pszColon-pszURL] = 0;
CPLDebug( "HTTP", "Fetch(%s:#password#%s%s)",
pszSanitizedURL, pszArobase, pszExtraDebug );
CPLFree(pszSanitizedURL);
}
else
{
CPLDebug( "HTTP", "Fetch(%s%s)", pszURL, pszExtraDebug );
}
}
#endif
#ifdef HAVE_CURL
/************************************************************************/
/* class CPLHTTPPostFields */
/************************************************************************/
class CPLHTTPPostFields
{
public:
CPLHTTPPostFields() = default;
CPLHTTPPostFields & operator=(const CPLHTTPPostFields&) = delete;
CPLHTTPPostFields(const CPLHTTPPostFields&) = delete;
CPLErr Fill(CURL *http_handle, CSLConstList papszOptions)
{
// Fill POST form if present
const char* pszFormFilePath = CSLFetchNameValue( papszOptions,
"FORM_FILE_PATH" );
const char* pszParametersCount = CSLFetchNameValue( papszOptions,
"FORM_ITEM_COUNT" );
if( pszFormFilePath != nullptr || pszParametersCount != nullptr )
{
#if CURL_AT_LEAST_VERSION(7,56,0)
mime = curl_mime_init(http_handle);
curl_mimepart *mimepart = curl_mime_addpart(mime);
#else // CURL_AT_LEAST_VERSION(7,56,0)
struct curl_httppost *lastptr = nullptr;
#endif // CURL_AT_LEAST_VERSION(7,56,0)
if( pszFormFilePath != nullptr )
{
const char* pszFormFileName = CSLFetchNameValue( papszOptions,
"FORM_FILE_NAME" );
const char* pszFilename = CPLGetFilename( pszFormFilePath );
if( pszFormFileName == nullptr )
{
pszFormFileName = pszFilename;
}
VSIStatBufL sStat;
if( VSIStatL( pszFormFilePath, &sStat ) == 0)
{
#if CURL_AT_LEAST_VERSION(7,56,0)
VSILFILE *mime_fp = VSIFOpenL( pszFormFilePath, "rb" );
if( mime_fp != nullptr )
{
curl_mime_name(mimepart, pszFormFileName);
CPL_IGNORE_RET_VAL(curl_mime_filename(mimepart, pszFilename));
curl_mime_data_cb(mimepart, sStat.st_size,
CPLHTTPReadFunction, CPLHTTPSeekFunction,
CPLHTTPFreeFunction, mime_fp);
}
else
{
osErrMsg = CPLSPrintf("Failed to open file %s",
pszFormFilePath);
return CE_Failure;
}
#else // CURL_AT_LEAST_VERSION(7,56,0)
curl_formadd(&formpost, &lastptr,
CURLFORM_COPYNAME, pszFormFileName,
CURLFORM_FILE, pszFormFilePath,
CURLFORM_END);
#endif // CURL_AT_LEAST_VERSION(7,56,0)
CPLDebug("HTTP", "Send file: %s, COPYNAME: %s",
pszFormFilePath, pszFormFileName);
}
else
{
osErrMsg = CPLSPrintf("File '%s' not found",
pszFormFilePath);
return CE_Failure;
}
}
int nParametersCount = 0;
if( pszParametersCount != nullptr )
{
nParametersCount = atoi( pszParametersCount );
}
for(int i = 0; i < nParametersCount; ++i)
{
const char *pszKey = CSLFetchNameValue( papszOptions,
CPLSPrintf("FORM_KEY_%d", i) );
const char *pszValue = CSLFetchNameValue( papszOptions,
CPLSPrintf("FORM_VALUE_%d", i) );
if (nullptr == pszKey)
{
osErrMsg = CPLSPrintf("Key #%d is not exists. Maybe wrong count of form items",
i);
return CE_Failure;
}
if (nullptr == pszValue)
{
osErrMsg = CPLSPrintf("Value #%d is not exists. Maybe wrong count of form items",
i);
return CE_Failure;
}
#if CURL_AT_LEAST_VERSION(7,56,0)
mimepart = curl_mime_addpart(mime);
curl_mime_name(mimepart, pszKey);
CPL_IGNORE_RET_VAL(curl_mime_data(mimepart, pszValue, CURL_ZERO_TERMINATED));
#else // CURL_AT_LEAST_VERSION(7,56,0)
curl_formadd(&formpost, &lastptr,
CURLFORM_COPYNAME, pszKey,
CURLFORM_COPYCONTENTS, pszValue,
CURLFORM_END);
#endif // CURL_AT_LEAST_VERSION(7,56,0)
CPLDebug("HTTP", "COPYNAME: %s, COPYCONTENTS: %s", pszKey, pszValue);
}
#if CURL_AT_LEAST_VERSION(7,56,0)
unchecked_curl_easy_setopt(http_handle, CURLOPT_MIMEPOST, mime);
#else // CURL_AT_LEAST_VERSION(7,56,0)
unchecked_curl_easy_setopt(http_handle, CURLOPT_HTTPPOST, formpost);
#endif // CURL_AT_LEAST_VERSION(7,56,0)
}
return CE_None;
}
~CPLHTTPPostFields()
{
#if CURL_AT_LEAST_VERSION(7,56,0)
if( mime != nullptr )
{
curl_mime_free(mime);
}
#else // CURL_AT_LEAST_VERSION(7,56,0)
if( formpost != nullptr)
{
curl_formfree(formpost);
}
#endif // CURL_AT_LEAST_VERSION(7,56,0)
}
std::string GetErrorMessage() const { return osErrMsg; }
private:
#if CURL_AT_LEAST_VERSION(7,56,0)
curl_mime *mime = nullptr;
#else // CURL_AT_LEAST_VERSION(7,56,0)
struct curl_httppost *formpost = nullptr;
#endif // CURL_AT_LEAST_VERSION(7,56,0)
std::string osErrMsg{};
};
/************************************************************************/
/* CPLHTTPFetchCleanup() */
/************************************************************************/
static void CPLHTTPFetchCleanup(CURL *http_handle, struct curl_slist* headers,
const char *pszPersistent, CSLConstList papszOptions)
{
if( CSLFetchNameValue(papszOptions, "POSTFIELDS") )
unchecked_curl_easy_setopt(http_handle, CURLOPT_POST, 0 );
unchecked_curl_easy_setopt(http_handle, CURLOPT_HTTPHEADER, nullptr);
if( !pszPersistent )
curl_easy_cleanup( http_handle );
curl_slist_free_all(headers);
}
#endif // HAVE_CURL
struct CPLHTTPFetchContext
{
std::vector< std::pair<CPLHTTPFetchCallbackFunc, void*> > stack{};
};
/************************************************************************/
/* GetHTTPFetchContext() */
/************************************************************************/
static CPLHTTPFetchContext* GetHTTPFetchContext(bool bAlloc)
{
int bError = FALSE;
CPLHTTPFetchContext *psCtx =
static_cast<CPLHTTPFetchContext *>(
CPLGetTLSEx( CTLS_HTTPFETCHCALLBACK, &bError ) );
if( bError )
return nullptr;
if( psCtx == nullptr && bAlloc)
{
const auto FreeFunc = [](void* pData)
{
delete static_cast<CPLHTTPFetchContext*>(pData);
};
psCtx = new CPLHTTPFetchContext();
CPLSetTLSWithFreeFuncEx( CTLS_HTTPFETCHCALLBACK, psCtx, FreeFunc, &bError );
if( bError )
{
delete psCtx;
psCtx = nullptr;
}
}
return psCtx;
}
/************************************************************************/
/* CPLHTTPSetFetchCallback() */
/************************************************************************/
static CPLHTTPFetchCallbackFunc gpsHTTPFetchCallbackFunc = nullptr;
static void* gpHTTPFetchCallbackUserData = nullptr;
/** Installs an alternate callback to the default implementation of CPLHTTPFetchEx().
*
* This callback will be used by all threads, unless contextual callbacks are
* installed with CPLHTTPPushFetchCallback().
*
* It is the responsibility of the caller to make sure this function is not
* called concurrently, or during CPLHTTPFetchEx() execution.
*
* @param pFunc Callback function to be called with CPLHTTPFetchEx() is called
* (or NULL to restore default handler)
* @param pUserData Last argument to provide to the pFunc callback.
*
* @since GDAL 3.2
*/
void CPLHTTPSetFetchCallback( CPLHTTPFetchCallbackFunc pFunc, void* pUserData )
{
gpsHTTPFetchCallbackFunc = pFunc;
gpHTTPFetchCallbackUserData = pUserData;
}
/************************************************************************/
/* CPLHTTPPushFetchCallback() */
/************************************************************************/
/** Installs an alternate callback to the default implementation of CPLHTTPFetchEx().
*
* This callback will only be used in the thread where this function has been
* called. It must be un-installed by CPLHTTPPopFetchCallback(), which must also
* be called from the same thread.
*
* @param pFunc Callback function to be called with CPLHTTPFetchEx() is called.
* @param pUserData Last argument to provide to the pFunc callback.
* @return TRUE in case of success.
*
* @since GDAL 3.2
*/
int CPLHTTPPushFetchCallback( CPLHTTPFetchCallbackFunc pFunc, void* pUserData )
{
auto psCtx = GetHTTPFetchContext(true);
if( psCtx == nullptr )
return false;
psCtx->stack.emplace_back(
std::pair<CPLHTTPFetchCallbackFunc, void*>(pFunc, pUserData) );
return true;
}
/************************************************************************/
/* CPLHTTPPopFetchCallback() */
/************************************************************************/
/** Uninstalls a callback set by CPLHTTPPushFetchCallback().
*
* @see CPLHTTPPushFetchCallback()
* @return TRUE in case of success.
* @since GDAL 3.2
*/
int CPLHTTPPopFetchCallback(void)
{
auto psCtx = GetHTTPFetchContext(false);
if( psCtx == nullptr || psCtx->stack.empty() )
{
CPLError(CE_Failure, CPLE_AppDefined,
"CPLHTTPPushFetchCallback / CPLHTTPPopFetchCallback not balanced");
return false;
}
else
{
psCtx->stack.pop_back();
return true;
}
}
/************************************************************************/
/* CPLHTTPFetch() */
/************************************************************************/
/**
* \brief Fetch a document from an url and return in a string.
*
* @param pszURL valid URL recognized by underlying download library (libcurl)
* @param papszOptions option list as a NULL-terminated array of strings. May be NULL.
* The following options are handled :
* <ul>
* <li>CONNECTTIMEOUT=val, where val is in seconds (possibly with decimals).
* This is the maximum delay for the connection to be established before
* being aborted (GDAL >= 2.2).</li>
* <li>TIMEOUT=val, where val is in seconds. This is the maximum delay for the whole
* request to complete before being aborted.</li>
* <li>LOW_SPEED_TIME=val, where val is in seconds. This is the maximum time where the
* transfer speed should be below the LOW_SPEED_LIMIT (if not specified 1b/s),
* before the transfer to be considered too slow and aborted. (GDAL >= 2.1)</li>
* <li>LOW_SPEED_LIMIT=val, where val is in bytes/second. See LOW_SPEED_TIME. Has only
* effect if LOW_SPEED_TIME is specified too. (GDAL >= 2.1)</li>
* <li>HEADERS=val, where val is an extra header to use when getting a web page.
* For example "Accept: application/x-ogcwkt"</li>
* <li>HEADER_FILE=filename: filename of a text file with "key: value" headers.
* (GDAL >= 2.2)</li>
* <li>HTTPAUTH=[BASIC/NTLM/NEGOTIATE/ANY] to specify an authentication scheme to use.</li>
* <li>USERPWD=userid:password to specify a user and password for authentication</li>
* <li>GSSAPI_DELEGATION=[NONE/POLICY/ALWAYS] set allowed GSS-API delegation.
* Relevant only with HTTPAUTH=NEGOTIATE (GDAL >= 3.3).</li>
* <li>POSTFIELDS=val, where val is a nul-terminated string to be passed to the server
* with a POST request.</li>
* <li>PROXY=val, to make requests go through a proxy server, where val is of the
* form proxy.server.com:port_number. This option affects both HTTP and HTTPS
* URLs.</li>
* <li>HTTPS_PROXY=val (GDAL >= 2.4), the same meaning as PROXY, but this option is taken into account only
* for HTTPS URLs.</li>
* <li>PROXYUSERPWD=val, where val is of the form username:password</li>
* <li>PROXYAUTH=[BASIC/NTLM/DIGEST/NEGOTIATE/ANY] to specify an proxy authentication scheme to use.</li>
* <li>NETRC=[YES/NO] to enable or disable use of $HOME/.netrc, default YES.</li>
* <li>CUSTOMREQUEST=val, where val is GET, PUT, POST, DELETE, etc.. (GDAL >= 1.9.0)</li>
* <li>FORM_FILE_NAME=val, where val is upload file name. If this option and
* FORM_FILE_PATH present, request type will set to POST.</li>
* <li>FORM_FILE_PATH=val, where val is upload file path.</li>
* <li>FORM_KEY_0=val...FORM_KEY_N, where val is name of form item.</li>
* <li>FORM_VALUE_0=val...FORM_VALUE_N, where val is value of the form item.</li>
* <li>FORM_ITEM_COUNT=val, where val is count of form items.</li>
* <li>COOKIE=val, where val is formatted as COOKIE1=VALUE1; COOKIE2=VALUE2; ...</li>
* <li>COOKIEFILE=val, where val is file name to read cookies from (GDAL >= 2.4)</li>
* <li>COOKIEJAR=val, where val is file name to store cookies to (GDAL >= 2.4)</li>
* <li>MAX_RETRY=val, where val is the maximum number of retry attempts if a 429, 502, 503 or
* 504 HTTP error occurs. Default is 0. (GDAL >= 2.0)</li>
* <li>RETRY_DELAY=val, where val is the number of seconds between retry attempts.
* Default is 30. (GDAL >= 2.0)</li>
* <li>MAX_FILE_SIZE=val, where val is a number of bytes (GDAL >= 2.2)</li>
* <li>CAINFO=/path/to/bundle.crt. This is path to Certificate Authority (CA)
* bundle file. By default, it will be looked for in a system location. If
* the CAINFO option is not defined, GDAL will also look in the the
* CURL_CA_BUNDLE and SSL_CERT_FILE environment variables respectively
* and use the first one found as the CAINFO value (GDAL >= 2.1.3). The
* GDAL_CURL_CA_BUNDLE environment variable may also be used to set the
* CAINFO value in GDAL >= 3.2.</li>
* <li>HTTP_VERSION=1.0/1.1/2/2TLS (GDAL >= 2.3). Specify HTTP version to use.
* Will default to 1.1 generally (except on some controlled environments,
* like Google Compute Engine VMs, where 2TLS will be the default).
* Support for HTTP/2 requires curl 7.33 or later, built against nghttp2.
* "2TLS" means that HTTP/2 will be attempted for HTTPS connections only. Whereas
* "2" means that HTTP/2 will be attempted for HTTP or HTTPS.</li>
* <li>SSL_VERIFYSTATUS=YES/NO (GDAL >= 2.3, and curl >= 7.41): determines whether
* the status of the server cert using the "Certificate Status Request" TLS
* extension (aka. OCSP stapling) should be checked. If this option is enabled
* but the server does not support the TLS extension, the verification will fail.
* Default to NO.</li>
* <li>USE_CAPI_STORE=YES/NO (GDAL >= 2.3, Windows only): whether CA certificates from
* the Windows certificate store. Defaults to NO.</li>
* </ul>
*
* Alternatively, if not defined in the papszOptions arguments, the
* CONNECTTIMEOUT, TIMEOUT,
* LOW_SPEED_TIME, LOW_SPEED_LIMIT, USERPWD, PROXY, HTTPS_PROXY, PROXYUSERPWD, PROXYAUTH, NETRC,
* MAX_RETRY and RETRY_DELAY, HEADER_FILE, HTTP_VERSION, SSL_VERIFYSTATUS, USE_CAPI_STORE,
* GSSAPI_DELEGATION
* values are searched in the configuration
* options respectively named GDAL_HTTP_CONNECTTIMEOUT, GDAL_HTTP_TIMEOUT,
* GDAL_HTTP_LOW_SPEED_TIME, GDAL_HTTP_LOW_SPEED_LIMIT, GDAL_HTTP_USERPWD,
* GDAL_HTTP_PROXY, GDAL_HTTPS_PROXY, GDAL_HTTP_PROXYUSERPWD, GDAL_PROXY_AUTH,
* GDAL_HTTP_NETRC, GDAL_HTTP_MAX_RETRY, GDAL_HTTP_RETRY_DELAY,
* GDAL_HTTP_HEADER_FILE, GDAL_HTTP_VERSION, GDAL_HTTP_SSL_VERIFYSTATUS,
* GDAL_HTTP_USE_CAPI_STORE, GDAL_GSSAPI_DELEGATION
*
* Starting with GDAL 3.6, the GDAL_HTTP_HEADERS configuration option can also be
* used to specify a comma separated list of key: value pairs. This is an
* alternative to the GDAL_HTTP_HEADER_FILE mechanism. If a comma or a double-quote
* character is needed in the value, then the key: value pair must be
* enclosed in double-quote characters. In that situation, backslash and double
* quote character must be backslash-escaped.
* e.g GDAL_HTTP_HEADERS=Foo: Bar,"Baz: escaped backslash \\, escaped double-quote \", end of value",Another: Header
*
* @return a CPLHTTPResult* structure that must be freed by
* CPLHTTPDestroyResult(), or NULL if libcurl support is disabled
*/
CPLHTTPResult *CPLHTTPFetch( const char *pszURL, CSLConstList papszOptions )
{
return CPLHTTPFetchEx( pszURL, papszOptions, nullptr, nullptr, nullptr, nullptr);
}
/**
* Fetch a document from an url and return in a string.
* @param pszURL Url to fetch document from web.
* @param papszOptions Option list as a NULL-terminated array of strings. Available keys see in CPLHTTPFetch.
* @param pfnProgress Callback for reporting algorithm progress matching the GDALProgressFunc() semantics. May be NULL.
* @param pProgressArg Callback argument passed to pfnProgress.