Line data Source code
1 : /******************************************************************************
2 : *
3 : * Project: CPL - Common Portability Library
4 : * Purpose: Implement VSI large file api for HTTP/FTP files
5 : * Author: Even Rouault, even.rouault at spatialys.com
6 : *
7 : ******************************************************************************
8 : * Copyright (c) 2010-2018, Even Rouault <even.rouault at spatialys.com>
9 : *
10 : * SPDX-License-Identifier: MIT
11 : ****************************************************************************/
12 :
13 : #include "cpl_port.h"
14 : #include "cpl_vsil_curl_priv.h"
15 : #include "cpl_vsil_curl_class.h"
16 :
17 : #include <algorithm>
18 : #include <array>
19 : #include <limits>
20 : #include <map>
21 : #include <memory>
22 : #include <numeric>
23 : #include <set>
24 : #include <string_view>
25 :
26 : #include "cpl_aws.h"
27 : #include "cpl_json.h"
28 : #include "cpl_json_header.h"
29 : #include "cpl_minixml.h"
30 : #include "cpl_multiproc.h"
31 : #include "cpl_string.h"
32 : #include "cpl_time.h"
33 : #include "cpl_vsi.h"
34 : #include "cpl_vsi_virtual.h"
35 : #include "cpl_http.h"
36 : #include "cpl_mem_cache.h"
37 :
38 : #ifndef S_IRUSR
39 : #define S_IRUSR 00400
40 : #define S_IWUSR 00200
41 : #define S_IXUSR 00100
42 : #define S_IRGRP 00040
43 : #define S_IWGRP 00020
44 : #define S_IXGRP 00010
45 : #define S_IROTH 00004
46 : #define S_IWOTH 00002
47 : #define S_IXOTH 00001
48 : #endif
49 :
50 : #ifndef HAVE_CURL
51 :
52 : void VSIInstallCurlFileHandler(void)
53 : {
54 : // Not supported.
55 : }
56 :
57 : void VSICurlClearCache(void)
58 : {
59 : // Not supported.
60 : }
61 :
62 : void VSICurlPartialClearCache(const char *)
63 : {
64 : // Not supported.
65 : }
66 :
67 : void VSICurlAuthParametersChanged()
68 : {
69 : // Not supported.
70 : }
71 :
72 : void VSINetworkStatsReset(void)
73 : {
74 : // Not supported
75 : }
76 :
77 : char *VSINetworkStatsGetAsSerializedJSON(char ** /* papszOptions */)
78 : {
79 : // Not supported
80 : return nullptr;
81 : }
82 :
83 : /************************************************************************/
84 : /* VSICurlInstallReadCbk() */
85 : /************************************************************************/
86 :
87 : int VSICurlInstallReadCbk(VSILFILE * /* fp */,
88 : VSICurlReadCbkFunc /* pfnReadCbk */,
89 : void * /* pfnUserData */,
90 : int /* bStopOnInterruptUntilUninstall */)
91 : {
92 : return FALSE;
93 : }
94 :
95 : /************************************************************************/
96 : /* VSICurlUninstallReadCbk() */
97 : /************************************************************************/
98 :
99 : int VSICurlUninstallReadCbk(VSILFILE * /* fp */)
100 : {
101 : return FALSE;
102 : }
103 :
104 : #else
105 :
106 : //! @cond Doxygen_Suppress
107 : #ifndef DOXYGEN_SKIP
108 :
109 : #define ENABLE_DEBUG 1
110 : #define ENABLE_DEBUG_VERBOSE 0
111 :
112 : #define unchecked_curl_easy_setopt(handle, opt, param) \
113 : CPL_IGNORE_RET_VAL(curl_easy_setopt(handle, opt, param))
114 :
115 : constexpr const char *const VSICURL_PREFIXES[] = {"/vsicurl/", "/vsicurl?"};
116 :
117 : extern "C" bool CPL_DLL GDALIsInGlobalDestructorFromDLLMain();
118 :
119 : /***********************************************************รน************/
120 : /* VSICurlAuthParametersChanged() */
121 : /************************************************************************/
122 :
123 : static unsigned int gnGenerationAuthParameters = 0;
124 :
125 3399 : void VSICurlAuthParametersChanged()
126 : {
127 3399 : gnGenerationAuthParameters++;
128 3399 : }
129 :
130 : // Do not access those variables directly !
131 : // Use VSICURLGetDownloadChunkSize() and GetMaxRegions()
132 : static int N_MAX_REGIONS_DO_NOT_USE_DIRECTLY = 0;
133 : static int DOWNLOAD_CHUNK_SIZE_DO_NOT_USE_DIRECTLY = 0;
134 :
135 : /************************************************************************/
136 : /* VSICURLReadGlobalEnvVariables() */
137 : /************************************************************************/
138 :
139 471284 : static void VSICURLReadGlobalEnvVariables()
140 : {
141 : struct Initializer
142 : {
143 1068 : Initializer()
144 : {
145 1068 : constexpr int DOWNLOAD_CHUNK_SIZE_DEFAULT = 16384;
146 : const char *pszChunkSize =
147 1068 : CPLGetConfigOption("CPL_VSIL_CURL_CHUNK_SIZE", nullptr);
148 1068 : GIntBig nChunkSize = DOWNLOAD_CHUNK_SIZE_DEFAULT;
149 :
150 1068 : if (pszChunkSize)
151 : {
152 0 : if (CPLParseMemorySize(pszChunkSize, &nChunkSize, nullptr) !=
153 : CE_None)
154 : {
155 0 : CPLError(
156 : CE_Warning, CPLE_AppDefined,
157 : "Could not parse value for CPL_VSIL_CURL_CHUNK_SIZE. "
158 : "Using default value of %d instead.",
159 : DOWNLOAD_CHUNK_SIZE_DEFAULT);
160 : }
161 : }
162 :
163 1068 : constexpr int MIN_CHUNK_SIZE = 1024;
164 1068 : constexpr int MAX_CHUNK_SIZE = 10 * 1024 * 1024;
165 1068 : if (nChunkSize < MIN_CHUNK_SIZE || nChunkSize > MAX_CHUNK_SIZE)
166 : {
167 0 : nChunkSize = DOWNLOAD_CHUNK_SIZE_DEFAULT;
168 0 : CPLError(CE_Warning, CPLE_AppDefined,
169 : "Invalid value for CPL_VSIL_CURL_CHUNK_SIZE. "
170 : "Allowed range is [%d, %d]. "
171 : "Using CPL_VSIL_CURL_CHUNK_SIZE=%d instead",
172 : MIN_CHUNK_SIZE, MAX_CHUNK_SIZE,
173 : DOWNLOAD_CHUNK_SIZE_DEFAULT);
174 : }
175 1068 : DOWNLOAD_CHUNK_SIZE_DO_NOT_USE_DIRECTLY =
176 : static_cast<int>(nChunkSize);
177 :
178 1068 : constexpr int N_MAX_REGIONS_DEFAULT = 1000;
179 1068 : constexpr int CACHE_SIZE_DEFAULT =
180 : N_MAX_REGIONS_DEFAULT * DOWNLOAD_CHUNK_SIZE_DEFAULT;
181 :
182 : const char *pszCacheSize =
183 1068 : CPLGetConfigOption("CPL_VSIL_CURL_CACHE_SIZE", nullptr);
184 1068 : GIntBig nCacheSize = CACHE_SIZE_DEFAULT;
185 :
186 1068 : if (pszCacheSize)
187 : {
188 0 : if (CPLParseMemorySize(pszCacheSize, &nCacheSize, nullptr) !=
189 : CE_None)
190 : {
191 0 : CPLError(
192 : CE_Warning, CPLE_AppDefined,
193 : "Could not parse value for CPL_VSIL_CURL_CACHE_SIZE. "
194 : "Using default value of " CPL_FRMT_GIB " instead.",
195 : nCacheSize);
196 : }
197 : }
198 :
199 1068 : const auto nMaxRAM = CPLGetUsablePhysicalRAM();
200 1068 : const auto nMinVal = DOWNLOAD_CHUNK_SIZE_DO_NOT_USE_DIRECTLY;
201 1068 : auto nMaxVal = static_cast<GIntBig>(INT_MAX) *
202 1068 : DOWNLOAD_CHUNK_SIZE_DO_NOT_USE_DIRECTLY;
203 1068 : if (nMaxRAM > 0 && nMaxVal > nMaxRAM)
204 1068 : nMaxVal = nMaxRAM;
205 1068 : if (nCacheSize < nMinVal || nCacheSize > nMaxVal)
206 : {
207 0 : nCacheSize = nCacheSize < nMinVal ? nMinVal : nMaxVal;
208 0 : CPLError(CE_Warning, CPLE_AppDefined,
209 : "Invalid value for CPL_VSIL_CURL_CACHE_SIZE. "
210 : "Allowed range is [%d, " CPL_FRMT_GIB "]. "
211 : "Using CPL_VSIL_CURL_CACHE_SIZE=" CPL_FRMT_GIB
212 : " instead",
213 : nMinVal, nMaxVal, nCacheSize);
214 : }
215 1068 : N_MAX_REGIONS_DO_NOT_USE_DIRECTLY = std::max(
216 2136 : 1, static_cast<int>(nCacheSize /
217 1068 : DOWNLOAD_CHUNK_SIZE_DO_NOT_USE_DIRECTLY));
218 1068 : }
219 : };
220 :
221 471284 : static Initializer initializer;
222 471284 : }
223 :
224 : /************************************************************************/
225 : /* VSICURLGetDownloadChunkSize() */
226 : /************************************************************************/
227 :
228 314564 : int VSICURLGetDownloadChunkSize()
229 : {
230 314564 : VSICURLReadGlobalEnvVariables();
231 314564 : return DOWNLOAD_CHUNK_SIZE_DO_NOT_USE_DIRECTLY;
232 : }
233 :
234 : /************************************************************************/
235 : /* GetMaxRegions() */
236 : /************************************************************************/
237 :
238 156720 : static int GetMaxRegions()
239 : {
240 156720 : VSICURLReadGlobalEnvVariables();
241 156720 : return N_MAX_REGIONS_DO_NOT_USE_DIRECTLY;
242 : }
243 :
244 : /************************************************************************/
245 : /* VSICurlFindStringSensitiveExceptEscapeSequences() */
246 : /************************************************************************/
247 :
248 : static int
249 156 : VSICurlFindStringSensitiveExceptEscapeSequences(CSLConstList papszList,
250 : const char *pszTarget)
251 :
252 : {
253 156 : if (papszList == nullptr)
254 120 : return -1;
255 :
256 69 : for (int i = 0; papszList[i] != nullptr; i++)
257 : {
258 59 : const char *pszIter1 = papszList[i];
259 59 : const char *pszIter2 = pszTarget;
260 59 : char ch1 = '\0';
261 59 : char ch2 = '\0';
262 : /* The comparison is case-sensitive, except for escaped */
263 : /* sequences where letters of the hexadecimal sequence */
264 : /* can be uppercase or lowercase depending on the quoting algorithm */
265 : while (true)
266 : {
267 850 : ch1 = *pszIter1;
268 850 : ch2 = *pszIter2;
269 850 : if (ch1 == '\0' || ch2 == '\0')
270 : break;
271 822 : if (ch1 == '%' && ch2 == '%' && pszIter1[1] != '\0' &&
272 0 : pszIter1[2] != '\0' && pszIter2[1] != '\0' &&
273 0 : pszIter2[2] != '\0')
274 : {
275 0 : if (!EQUALN(pszIter1 + 1, pszIter2 + 1, 2))
276 0 : break;
277 0 : pszIter1 += 2;
278 0 : pszIter2 += 2;
279 : }
280 822 : if (ch1 != ch2)
281 31 : break;
282 791 : pszIter1++;
283 791 : pszIter2++;
284 : }
285 59 : if (ch1 == ch2 && ch1 == '\0')
286 26 : return i;
287 : }
288 :
289 10 : return -1;
290 : }
291 :
292 : /************************************************************************/
293 : /* VSICurlIsFileInList() */
294 : /************************************************************************/
295 :
296 147 : static int VSICurlIsFileInList(CSLConstList papszList, const char *pszTarget)
297 : {
298 : int nRet =
299 147 : VSICurlFindStringSensitiveExceptEscapeSequences(papszList, pszTarget);
300 147 : if (nRet >= 0)
301 26 : return nRet;
302 :
303 : // If we didn't find anything, try to URL-escape the target filename.
304 121 : char *pszEscaped = CPLEscapeString(pszTarget, -1, CPLES_URL);
305 121 : if (strcmp(pszTarget, pszEscaped) != 0)
306 : {
307 9 : nRet = VSICurlFindStringSensitiveExceptEscapeSequences(papszList,
308 : pszEscaped);
309 : }
310 121 : CPLFree(pszEscaped);
311 121 : return nRet;
312 : }
313 :
314 : /************************************************************************/
315 : /* StartsWithVSICurlPrefix() */
316 : /************************************************************************/
317 :
318 : static bool
319 9696 : StartsWithVSICurlPrefix(const char *pszFilename,
320 : std::string *posFilenameAfterPrefix = nullptr)
321 : {
322 22791 : for (const char *pszPrefix : VSICURL_PREFIXES)
323 : {
324 16370 : if (STARTS_WITH(pszFilename, pszPrefix))
325 : {
326 3275 : if (posFilenameAfterPrefix)
327 19 : *posFilenameAfterPrefix = pszFilename + strlen(pszPrefix);
328 3275 : return true;
329 : }
330 : }
331 6421 : return false;
332 : }
333 :
334 : /************************************************************************/
335 : /* VSICurlGetURLFromFilename() */
336 : /************************************************************************/
337 :
338 3594 : static std::string VSICurlGetURLFromFilename(
339 : const char *pszFilename, CPLHTTPRetryParameters *poRetryParameters,
340 : bool *pbUseHead, bool *pbUseRedirectURLIfNoQueryStringParams,
341 : bool *pbListDir, bool *pbEmptyDir, CPLStringList *paosHTTPOptions,
342 : bool *pbPlanetaryComputerURLSigning, char **ppszPlanetaryComputerCollection)
343 : {
344 3594 : if (ppszPlanetaryComputerCollection)
345 1508 : *ppszPlanetaryComputerCollection = nullptr;
346 :
347 3594 : if (!StartsWithVSICurlPrefix(pszFilename))
348 400 : return pszFilename;
349 :
350 3194 : if (pbPlanetaryComputerURLSigning)
351 : {
352 : // It may be more convenient sometimes to store Planetary Computer URL
353 : // signing as a per-path specific option rather than capturing it in
354 : // the filename with the &pc_url_signing=yes option.
355 1508 : if (CPLTestBool(VSIGetPathSpecificOption(
356 : pszFilename, "VSICURL_PC_URL_SIGNING", "FALSE")))
357 : {
358 1 : *pbPlanetaryComputerURLSigning = true;
359 : }
360 : }
361 :
362 3194 : pszFilename += strlen("/vsicurl/");
363 3194 : if (!STARTS_WITH(pszFilename, "http://") &&
364 2546 : !STARTS_WITH(pszFilename, "https://") &&
365 91 : !STARTS_WITH(pszFilename, "ftp://") &&
366 91 : !STARTS_WITH(pszFilename, "file://"))
367 : {
368 91 : if (*pszFilename == '?')
369 0 : pszFilename++;
370 91 : char **papszTokens = CSLTokenizeString2(pszFilename, "&", 0);
371 336 : for (int i = 0; papszTokens[i] != nullptr; i++)
372 : {
373 : char *pszUnescaped =
374 245 : CPLUnescapeString(papszTokens[i], nullptr, CPLES_URL);
375 245 : CPLFree(papszTokens[i]);
376 245 : papszTokens[i] = pszUnescaped;
377 : }
378 :
379 182 : std::string osURL;
380 182 : std::string osHeaders;
381 336 : for (int i = 0; papszTokens[i]; i++)
382 : {
383 245 : char *pszKey = nullptr;
384 245 : const char *pszValue = CPLParseNameValue(papszTokens[i], &pszKey);
385 245 : if (pszKey && pszValue)
386 : {
387 245 : if (EQUAL(pszKey, "max_retry"))
388 : {
389 36 : if (poRetryParameters)
390 13 : poRetryParameters->nMaxRetry = atoi(pszValue);
391 : }
392 209 : else if (EQUAL(pszKey, "retry_delay"))
393 : {
394 16 : if (poRetryParameters)
395 4 : poRetryParameters->dfInitialDelay = CPLAtof(pszValue);
396 : }
397 193 : else if (EQUAL(pszKey, "retry_codes"))
398 : {
399 4 : if (poRetryParameters)
400 1 : poRetryParameters->osRetryCodes = pszValue;
401 : }
402 189 : else if (EQUAL(pszKey, "use_head"))
403 : {
404 24 : if (pbUseHead)
405 11 : *pbUseHead = CPLTestBool(pszValue);
406 : }
407 165 : else if (EQUAL(pszKey,
408 : "use_redirect_url_if_no_query_string_params"))
409 : {
410 : /* Undocumented. Used by PLScenes driver */
411 20 : if (pbUseRedirectURLIfNoQueryStringParams)
412 9 : *pbUseRedirectURLIfNoQueryStringParams =
413 9 : CPLTestBool(pszValue);
414 : }
415 145 : else if (EQUAL(pszKey, "list_dir"))
416 : {
417 0 : if (pbListDir)
418 0 : *pbListDir = CPLTestBool(pszValue);
419 : }
420 145 : else if (EQUAL(pszKey, "empty_dir"))
421 : {
422 20 : if (pbEmptyDir)
423 10 : *pbEmptyDir = CPLTestBool(pszValue);
424 : }
425 125 : else if (EQUAL(pszKey, "useragent") ||
426 125 : EQUAL(pszKey, "referer") || EQUAL(pszKey, "cookie") ||
427 125 : EQUAL(pszKey, "header_file") ||
428 125 : EQUAL(pszKey, "unsafessl") ||
429 : #ifndef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
430 125 : EQUAL(pszKey, "timeout") ||
431 125 : EQUAL(pszKey, "connecttimeout") ||
432 : #endif
433 125 : EQUAL(pszKey, "low_speed_time") ||
434 125 : EQUAL(pszKey, "low_speed_limit") ||
435 125 : EQUAL(pszKey, "proxy") || EQUAL(pszKey, "proxyauth") ||
436 125 : EQUAL(pszKey, "proxyuserpwd"))
437 : {
438 : // Above names are the ones supported by
439 : // CPLHTTPSetOptions()
440 0 : if (paosHTTPOptions)
441 : {
442 0 : paosHTTPOptions->SetNameValue(pszKey, pszValue);
443 : }
444 : }
445 125 : else if (EQUAL(pszKey, "url"))
446 : {
447 91 : osURL = pszValue;
448 : }
449 34 : else if (EQUAL(pszKey, "pc_url_signing"))
450 : {
451 20 : if (pbPlanetaryComputerURLSigning)
452 10 : *pbPlanetaryComputerURLSigning = CPLTestBool(pszValue);
453 : }
454 14 : else if (EQUAL(pszKey, "pc_collection"))
455 : {
456 10 : if (ppszPlanetaryComputerCollection)
457 : {
458 5 : CPLFree(*ppszPlanetaryComputerCollection);
459 5 : *ppszPlanetaryComputerCollection = CPLStrdup(pszValue);
460 : }
461 : }
462 4 : else if (STARTS_WITH(pszKey, "header."))
463 : {
464 4 : osHeaders += (pszKey + strlen("header."));
465 4 : osHeaders += ':';
466 4 : osHeaders += pszValue;
467 4 : osHeaders += "\r\n";
468 : }
469 : else
470 : {
471 0 : CPLError(CE_Warning, CPLE_NotSupported,
472 : "Unsupported option: %s", pszKey);
473 : }
474 : }
475 245 : CPLFree(pszKey);
476 : }
477 :
478 91 : if (paosHTTPOptions && !osHeaders.empty())
479 1 : paosHTTPOptions->SetNameValue("HEADERS", osHeaders.c_str());
480 :
481 91 : CSLDestroy(papszTokens);
482 91 : if (osURL.empty())
483 : {
484 0 : CPLError(CE_Failure, CPLE_IllegalArg, "Missing url parameter");
485 0 : return pszFilename;
486 : }
487 :
488 91 : return osURL;
489 : }
490 :
491 3103 : return pszFilename;
492 : }
493 :
494 : namespace cpl
495 : {
496 :
497 : /************************************************************************/
498 : /* VSICurlHandle() */
499 : /************************************************************************/
500 :
501 1869 : VSICurlHandle::VSICurlHandle(VSICurlFilesystemHandlerBase *poFSIn,
502 1869 : const char *pszFilename, const char *pszURLIn)
503 : : poFS(poFSIn), m_osFilename(pszFilename),
504 : m_aosHTTPOptions(CPLHTTPGetOptionsFromEnv(pszFilename)),
505 1869 : m_oRetryParameters(m_aosHTTPOptions),
506 : m_bUseHead(
507 1869 : CPLTestBool(CPLGetConfigOption("CPL_VSIL_CURL_USE_HEAD", "YES")))
508 : {
509 1868 : if (pszURLIn)
510 : {
511 360 : m_pszURL = CPLStrdup(pszURLIn);
512 : }
513 : else
514 : {
515 1508 : char *pszPCCollection = nullptr;
516 1508 : m_pszURL =
517 1508 : CPLStrdup(VSICurlGetURLFromFilename(
518 : pszFilename, &m_oRetryParameters, &m_bUseHead,
519 : &m_bUseRedirectURLIfNoQueryStringParams, nullptr,
520 : nullptr, &m_aosHTTPOptions,
521 : &m_bPlanetaryComputerURLSigning, &pszPCCollection)
522 : .c_str());
523 1508 : if (pszPCCollection)
524 5 : m_osPlanetaryComputerCollection = pszPCCollection;
525 1508 : CPLFree(pszPCCollection);
526 : }
527 :
528 1869 : m_bCached = poFSIn->AllowCachedDataFor(pszFilename);
529 1869 : poFS->GetCachedFileProp(m_pszURL, oFileProp);
530 1869 : }
531 :
532 : /************************************************************************/
533 : /* ~VSICurlHandle() */
534 : /************************************************************************/
535 :
536 3377 : VSICurlHandle::~VSICurlHandle()
537 : {
538 1869 : if (m_oThreadAdviseRead.joinable())
539 : {
540 5 : m_oThreadAdviseRead.join();
541 : }
542 1869 : if (m_hCurlMultiHandleForAdviseRead)
543 : {
544 5 : VSICURLMultiCleanup(m_hCurlMultiHandleForAdviseRead);
545 : }
546 :
547 1869 : if (!m_bCached)
548 : {
549 62 : poFS->InvalidateCachedData(m_pszURL);
550 62 : poFS->InvalidateDirContent(CPLGetDirnameSafe(m_osFilename.c_str()));
551 : }
552 1869 : CPLFree(m_pszURL);
553 3377 : }
554 :
555 : /************************************************************************/
556 : /* SetURL() */
557 : /************************************************************************/
558 :
559 10 : void VSICurlHandle::SetURL(const char *pszURLIn)
560 : {
561 10 : CPLFree(m_pszURL);
562 10 : m_pszURL = CPLStrdup(pszURLIn);
563 10 : }
564 :
565 : /************************************************************************/
566 : /* InstallReadCbk() */
567 : /************************************************************************/
568 :
569 3 : int VSICurlHandle::InstallReadCbk(VSICurlReadCbkFunc pfnReadCbkIn,
570 : void *pfnUserDataIn,
571 : int bStopOnInterruptUntilUninstallIn)
572 : {
573 3 : if (pfnReadCbk != nullptr)
574 0 : return FALSE;
575 :
576 3 : pfnReadCbk = pfnReadCbkIn;
577 3 : pReadCbkUserData = pfnUserDataIn;
578 3 : bStopOnInterruptUntilUninstall =
579 3 : CPL_TO_BOOL(bStopOnInterruptUntilUninstallIn);
580 3 : bInterrupted = false;
581 3 : return TRUE;
582 : }
583 :
584 : /************************************************************************/
585 : /* UninstallReadCbk() */
586 : /************************************************************************/
587 :
588 3 : int VSICurlHandle::UninstallReadCbk()
589 : {
590 3 : if (pfnReadCbk == nullptr)
591 0 : return FALSE;
592 :
593 3 : pfnReadCbk = nullptr;
594 3 : pReadCbkUserData = nullptr;
595 3 : bStopOnInterruptUntilUninstall = false;
596 3 : bInterrupted = false;
597 3 : return TRUE;
598 : }
599 :
600 : /************************************************************************/
601 : /* Seek() */
602 : /************************************************************************/
603 :
604 22248 : int VSICurlHandle::Seek(vsi_l_offset nOffset, int nWhence)
605 : {
606 22248 : if (nWhence == SEEK_SET)
607 : {
608 16944 : curOffset = nOffset;
609 : }
610 5304 : else if (nWhence == SEEK_CUR)
611 : {
612 4565 : curOffset = curOffset + nOffset;
613 : }
614 : else
615 : {
616 739 : curOffset = GetFileSize(false) + nOffset;
617 : }
618 22248 : bEOF = false;
619 22248 : return 0;
620 : }
621 :
622 : } // namespace cpl
623 :
624 : /************************************************************************/
625 : /* VSICurlGetTimeStampFromRFC822DateTime() */
626 : /************************************************************************/
627 :
628 1099 : static GIntBig VSICurlGetTimeStampFromRFC822DateTime(const char *pszDT)
629 : {
630 : // Sun, 03 Apr 2016 12:07:27 GMT
631 1099 : if (strlen(pszDT) >= 5 && pszDT[3] == ',' && pszDT[4] == ' ')
632 1099 : pszDT += 5;
633 1099 : int nDay = 0;
634 1099 : int nYear = 0;
635 1099 : int nHour = 0;
636 1099 : int nMinute = 0;
637 1099 : int nSecond = 0;
638 1099 : char szMonth[4] = {};
639 1099 : szMonth[3] = 0;
640 1099 : if (sscanf(pszDT, "%02d %03s %04d %02d:%02d:%02d GMT", &nDay, szMonth,
641 1099 : &nYear, &nHour, &nMinute, &nSecond) == 6)
642 : {
643 : static const char *const aszMonthStr[] = {"Jan", "Feb", "Mar", "Apr",
644 : "May", "Jun", "Jul", "Aug",
645 : "Sep", "Oct", "Nov", "Dec"};
646 :
647 1099 : int nMonthIdx0 = -1;
648 5479 : for (int i = 0; i < 12; i++)
649 : {
650 5479 : if (EQUAL(szMonth, aszMonthStr[i]))
651 : {
652 1099 : nMonthIdx0 = i;
653 1099 : break;
654 : }
655 : }
656 1099 : if (nMonthIdx0 >= 0)
657 : {
658 : struct tm brokendowntime;
659 1099 : brokendowntime.tm_year = nYear - 1900;
660 1099 : brokendowntime.tm_mon = nMonthIdx0;
661 1099 : brokendowntime.tm_mday = nDay;
662 1099 : brokendowntime.tm_hour = nHour;
663 1099 : brokendowntime.tm_min = nMinute;
664 1099 : brokendowntime.tm_sec = nSecond;
665 1099 : return CPLYMDHMSToUnixTime(&brokendowntime);
666 : }
667 : }
668 0 : return 0;
669 : }
670 :
671 : /************************************************************************/
672 : /* VSICURLInitWriteFuncStruct() */
673 : /************************************************************************/
674 :
675 2820 : void VSICURLInitWriteFuncStruct(cpl::WriteFuncStruct *psStruct, VSILFILE *fp,
676 : VSICurlReadCbkFunc pfnReadCbk,
677 : void *pReadCbkUserData)
678 : {
679 2820 : psStruct->pBuffer = nullptr;
680 2820 : psStruct->nSize = 0;
681 2820 : psStruct->bIsHTTP = false;
682 2820 : psStruct->bMultiRange = false;
683 2820 : psStruct->nStartOffset = 0;
684 2820 : psStruct->nEndOffset = 0;
685 2820 : psStruct->nHTTPCode = 0;
686 2820 : psStruct->nFirstHTTPCode = 0;
687 2820 : psStruct->nContentLength = 0;
688 2820 : psStruct->bFoundContentRange = false;
689 2820 : psStruct->bError = false;
690 2820 : psStruct->bDetectRangeDownloadingError = true;
691 2820 : psStruct->nTimestampDate = 0;
692 :
693 2820 : psStruct->fp = fp;
694 2820 : psStruct->pfnReadCbk = pfnReadCbk;
695 2820 : psStruct->pReadCbkUserData = pReadCbkUserData;
696 2820 : psStruct->bInterrupted = false;
697 2820 : }
698 :
699 : /************************************************************************/
700 : /* VSICurlHandleWriteFunc() */
701 : /************************************************************************/
702 :
703 29366 : size_t VSICurlHandleWriteFunc(void *buffer, size_t count, size_t nmemb,
704 : void *req)
705 : {
706 29366 : cpl::WriteFuncStruct *psStruct = static_cast<cpl::WriteFuncStruct *>(req);
707 29366 : const size_t nSize = count * nmemb;
708 :
709 29366 : if (psStruct->bInterrupted)
710 : {
711 9 : return 0;
712 : }
713 :
714 : char *pNewBuffer = static_cast<char *>(
715 29357 : VSIRealloc(psStruct->pBuffer, psStruct->nSize + nSize + 1));
716 29357 : if (pNewBuffer)
717 : {
718 29357 : psStruct->pBuffer = pNewBuffer;
719 29357 : memcpy(psStruct->pBuffer + psStruct->nSize, buffer, nSize);
720 29357 : psStruct->pBuffer[psStruct->nSize + nSize] = '\0';
721 29357 : if (psStruct->bIsHTTP)
722 : {
723 12529 : char *pszLine = psStruct->pBuffer + psStruct->nSize;
724 12529 : if (STARTS_WITH_CI(pszLine, "HTTP/"))
725 : {
726 1100 : char *pszSpace = strchr(pszLine, ' ');
727 1100 : if (pszSpace)
728 : {
729 1100 : const int nHTTPCode = atoi(pszSpace + 1);
730 1100 : if (psStruct->nFirstHTTPCode == 0)
731 968 : psStruct->nFirstHTTPCode = nHTTPCode;
732 1100 : psStruct->nHTTPCode = nHTTPCode;
733 : }
734 : }
735 11429 : else if (STARTS_WITH_CI(pszLine, "Content-Length: "))
736 : {
737 1001 : psStruct->nContentLength = CPLScanUIntBig(
738 1001 : pszLine + 16, static_cast<int>(strlen(pszLine + 16)));
739 : }
740 10428 : else if (STARTS_WITH_CI(pszLine, "Content-Range: "))
741 : {
742 358 : psStruct->bFoundContentRange = true;
743 : }
744 10070 : else if (STARTS_WITH_CI(pszLine, "Date: "))
745 : {
746 1099 : CPLString osDate = pszLine + strlen("Date: ");
747 1099 : size_t nSizeLine = osDate.size();
748 5495 : while (nSizeLine && (osDate[nSizeLine - 1] == '\r' ||
749 2198 : osDate[nSizeLine - 1] == '\n'))
750 : {
751 2198 : osDate.resize(nSizeLine - 1);
752 2198 : nSizeLine--;
753 : }
754 1099 : osDate.Trim();
755 :
756 : GIntBig nTimestampDate =
757 1099 : VSICurlGetTimeStampFromRFC822DateTime(osDate.c_str());
758 : #if DEBUG_VERBOSE
759 : CPLDebug("VSICURL", "Timestamp = " CPL_FRMT_GIB,
760 : nTimestampDate);
761 : #endif
762 1099 : psStruct->nTimestampDate = nTimestampDate;
763 : }
764 : /*if( nSize > 2 && pszLine[nSize - 2] == '\r' &&
765 : pszLine[nSize - 1] == '\n' )
766 : {
767 : pszLine[nSize - 2] = 0;
768 : CPLDebug("VSICURL", "%s", pszLine);
769 : pszLine[nSize - 2] = '\r';
770 : }*/
771 :
772 12529 : if (pszLine[0] == '\r' && pszLine[1] == '\n')
773 : {
774 : // Detect servers that don't support range downloading.
775 1100 : if (psStruct->nHTTPCode == 200 &&
776 368 : psStruct->bDetectRangeDownloadingError &&
777 148 : !psStruct->bMultiRange && !psStruct->bFoundContentRange &&
778 138 : (psStruct->nStartOffset != 0 ||
779 138 : psStruct->nContentLength >
780 138 : 10 * (psStruct->nEndOffset - psStruct->nStartOffset +
781 : 1)))
782 : {
783 0 : CPLError(CE_Failure, CPLE_AppDefined,
784 : "Range downloading not supported by this "
785 : "server!");
786 0 : psStruct->bError = true;
787 0 : return 0;
788 : }
789 : }
790 : }
791 : else
792 : {
793 16828 : if (psStruct->pfnReadCbk)
794 : {
795 1 : if (!psStruct->pfnReadCbk(psStruct->fp, buffer, nSize,
796 : psStruct->pReadCbkUserData))
797 : {
798 0 : psStruct->bInterrupted = true;
799 0 : return 0;
800 : }
801 : }
802 : }
803 29357 : psStruct->nSize += nSize;
804 29357 : return nmemb;
805 : }
806 : else
807 : {
808 0 : return 0;
809 : }
810 : }
811 :
812 : /************************************************************************/
813 : /* VSICurlIsS3LikeSignedURL() */
814 : /************************************************************************/
815 :
816 478 : static bool VSICurlIsS3LikeSignedURL(const char *pszURL)
817 : {
818 952 : return ((strstr(pszURL, ".s3.amazonaws.com/") != nullptr ||
819 474 : strstr(pszURL, ".s3.amazonaws.com:") != nullptr ||
820 474 : strstr(pszURL, ".storage.googleapis.com/") != nullptr ||
821 474 : strstr(pszURL, ".storage.googleapis.com:") != nullptr ||
822 474 : strstr(pszURL, ".cloudfront.net/") != nullptr ||
823 474 : strstr(pszURL, ".cloudfront.net:") != nullptr) &&
824 4 : (strstr(pszURL, "&Signature=") != nullptr ||
825 4 : strstr(pszURL, "?Signature=") != nullptr)) ||
826 1431 : strstr(pszURL, "&X-Amz-Signature=") != nullptr ||
827 953 : strstr(pszURL, "?X-Amz-Signature=") != nullptr;
828 : }
829 :
830 : /************************************************************************/
831 : /* VSICurlGetExpiresFromS3LikeSignedURL() */
832 : /************************************************************************/
833 :
834 5 : static GIntBig VSICurlGetExpiresFromS3LikeSignedURL(const char *pszURL)
835 : {
836 25 : const auto GetParamValue = [pszURL](const char *pszKey) -> const char *
837 : {
838 17 : for (const char *pszPrefix : {"&", "?"})
839 : {
840 14 : std::string osNeedle(pszPrefix);
841 14 : osNeedle += pszKey;
842 14 : osNeedle += '=';
843 14 : const char *pszStr = strstr(pszURL, osNeedle.c_str());
844 14 : if (pszStr)
845 8 : return pszStr + osNeedle.size();
846 : }
847 3 : return nullptr;
848 5 : };
849 :
850 : {
851 : // Expires= is a Unix timestamp
852 5 : const char *pszExpires = GetParamValue("Expires");
853 5 : if (pszExpires != nullptr)
854 2 : return CPLAtoGIntBig(pszExpires);
855 : }
856 :
857 : // X-Amz-Expires= is a delay, to be combined with X-Amz-Date=
858 3 : const char *pszAmzExpires = GetParamValue("X-Amz-Expires");
859 3 : if (pszAmzExpires == nullptr)
860 0 : return 0;
861 3 : const int nDelay = atoi(pszAmzExpires);
862 :
863 3 : const char *pszAmzDate = GetParamValue("X-Amz-Date");
864 3 : if (pszAmzDate == nullptr)
865 0 : return 0;
866 : // pszAmzDate should be YYYYMMDDTHHMMSSZ
867 3 : if (strlen(pszAmzDate) < strlen("YYYYMMDDTHHMMSSZ"))
868 0 : return 0;
869 3 : if (pszAmzDate[strlen("YYYYMMDDTHHMMSSZ") - 1] != 'Z')
870 0 : return 0;
871 : struct tm brokendowntime;
872 3 : brokendowntime.tm_year =
873 3 : atoi(std::string(pszAmzDate).substr(0, 4).c_str()) - 1900;
874 3 : brokendowntime.tm_mon =
875 3 : atoi(std::string(pszAmzDate).substr(4, 2).c_str()) - 1;
876 3 : brokendowntime.tm_mday = atoi(std::string(pszAmzDate).substr(6, 2).c_str());
877 3 : brokendowntime.tm_hour = atoi(std::string(pszAmzDate).substr(9, 2).c_str());
878 3 : brokendowntime.tm_min = atoi(std::string(pszAmzDate).substr(11, 2).c_str());
879 3 : brokendowntime.tm_sec = atoi(std::string(pszAmzDate).substr(13, 2).c_str());
880 3 : return CPLYMDHMSToUnixTime(&brokendowntime) + nDelay;
881 : }
882 :
883 : /************************************************************************/
884 : /* VSICURLMultiPerform() */
885 : /************************************************************************/
886 :
887 1433 : void VSICURLMultiPerform(CURLM *hCurlMultiHandle, CURL *hEasyHandle,
888 : std::atomic<bool> *pbInterrupt)
889 : {
890 1433 : int repeats = 0;
891 :
892 1433 : if (hEasyHandle)
893 1429 : curl_multi_add_handle(hCurlMultiHandle, hEasyHandle);
894 :
895 1433 : void *old_handler = CPLHTTPIgnoreSigPipe();
896 : while (true)
897 : {
898 : int still_running;
899 14052 : while (curl_multi_perform(hCurlMultiHandle, &still_running) ==
900 : CURLM_CALL_MULTI_PERFORM)
901 : {
902 : // loop
903 : }
904 14053 : if (!still_running)
905 : {
906 1433 : break;
907 : }
908 :
909 : #ifdef undef
910 : CURLMsg *msg;
911 : do
912 : {
913 : int msgq = 0;
914 : msg = curl_multi_info_read(hCurlMultiHandle, &msgq);
915 : if (msg && (msg->msg == CURLMSG_DONE))
916 : {
917 : CURL *e = msg->easy_handle;
918 : }
919 : } while (msg);
920 : #endif
921 :
922 12620 : CPLMultiPerformWait(hCurlMultiHandle, repeats);
923 :
924 12619 : if (pbInterrupt && *pbInterrupt)
925 0 : break;
926 12619 : }
927 1433 : CPLHTTPRestoreSigPipeHandler(old_handler);
928 :
929 1433 : if (hEasyHandle)
930 1429 : curl_multi_remove_handle(hCurlMultiHandle, hEasyHandle);
931 1433 : }
932 :
933 : /************************************************************************/
934 : /* VSICurlDummyWriteFunc() */
935 : /************************************************************************/
936 :
937 0 : static size_t VSICurlDummyWriteFunc(void *, size_t, size_t, void *)
938 : {
939 0 : return 0;
940 : }
941 :
942 : /************************************************************************/
943 : /* VSICURLResetHeaderAndWriterFunctions() */
944 : /************************************************************************/
945 :
946 1389 : void VSICURLResetHeaderAndWriterFunctions(CURL *hCurlHandle)
947 : {
948 1389 : unchecked_curl_easy_setopt(hCurlHandle, CURLOPT_HEADERFUNCTION,
949 : VSICurlDummyWriteFunc);
950 1389 : unchecked_curl_easy_setopt(hCurlHandle, CURLOPT_WRITEFUNCTION,
951 : VSICurlDummyWriteFunc);
952 1389 : }
953 :
954 : /************************************************************************/
955 : /* Iso8601ToUnixTime() */
956 : /************************************************************************/
957 :
958 6 : static bool Iso8601ToUnixTime(const char *pszDT, GIntBig *pnUnixTime)
959 : {
960 : int nYear;
961 : int nMonth;
962 : int nDay;
963 : int nHour;
964 : int nMinute;
965 : int nSecond;
966 6 : if (sscanf(pszDT, "%04d-%02d-%02dT%02d:%02d:%02d", &nYear, &nMonth, &nDay,
967 6 : &nHour, &nMinute, &nSecond) == 6)
968 : {
969 : struct tm brokendowntime;
970 6 : brokendowntime.tm_year = nYear - 1900;
971 6 : brokendowntime.tm_mon = nMonth - 1;
972 6 : brokendowntime.tm_mday = nDay;
973 6 : brokendowntime.tm_hour = nHour;
974 6 : brokendowntime.tm_min = nMinute;
975 6 : brokendowntime.tm_sec = nSecond;
976 6 : *pnUnixTime = CPLYMDHMSToUnixTime(&brokendowntime);
977 6 : return true;
978 : }
979 0 : return false;
980 : }
981 :
982 : namespace cpl
983 : {
984 :
985 : /************************************************************************/
986 : /* ManagePlanetaryComputerSigning() */
987 : /************************************************************************/
988 :
989 11 : void VSICurlHandle::ManagePlanetaryComputerSigning() const
990 : {
991 : // Take global lock
992 : static std::mutex goMutex;
993 22 : std::lock_guard<std::mutex> oLock(goMutex);
994 :
995 : struct PCSigningInfo
996 : {
997 : std::string osQueryString{};
998 : GIntBig nExpireTimestamp = 0;
999 : };
1000 :
1001 22 : PCSigningInfo sSigningInfo;
1002 11 : constexpr int knExpirationDelayMargin = 60;
1003 :
1004 11 : if (!m_osPlanetaryComputerCollection.empty())
1005 : {
1006 : // key is the name of a collection
1007 5 : static lru11::Cache<std::string, PCSigningInfo> goCacheCollection{1024};
1008 :
1009 5 : if (goCacheCollection.tryGet(m_osPlanetaryComputerCollection,
1010 8 : sSigningInfo) &&
1011 3 : time(nullptr) + knExpirationDelayMargin <=
1012 3 : sSigningInfo.nExpireTimestamp)
1013 : {
1014 2 : m_osQueryString = sSigningInfo.osQueryString;
1015 : }
1016 : else
1017 : {
1018 : const auto psResult =
1019 9 : CPLHTTPFetch((std::string(CPLGetConfigOption(
1020 : "VSICURL_PC_SAS_TOKEN_URL",
1021 : "https://planetarycomputer.microsoft.com/api/"
1022 6 : "sas/v1/token/")) +
1023 3 : m_osPlanetaryComputerCollection)
1024 : .c_str(),
1025 : nullptr);
1026 3 : if (psResult)
1027 : {
1028 : const auto aosKeyVals = CPLParseKeyValueJson(
1029 6 : reinterpret_cast<const char *>(psResult->pabyData));
1030 3 : const char *pszToken = aosKeyVals.FetchNameValue("token");
1031 3 : if (pszToken)
1032 : {
1033 3 : m_osQueryString = '?';
1034 3 : m_osQueryString += pszToken;
1035 :
1036 3 : sSigningInfo.osQueryString = m_osQueryString;
1037 3 : sSigningInfo.nExpireTimestamp = 0;
1038 : const char *pszExpiry =
1039 3 : aosKeyVals.FetchNameValue("msft:expiry");
1040 3 : if (pszExpiry)
1041 : {
1042 3 : Iso8601ToUnixTime(pszExpiry,
1043 : &sSigningInfo.nExpireTimestamp);
1044 : }
1045 3 : goCacheCollection.insert(m_osPlanetaryComputerCollection,
1046 : sSigningInfo);
1047 :
1048 3 : CPLDebug("VSICURL", "Got token from Planetary Computer: %s",
1049 : m_osQueryString.c_str());
1050 : }
1051 3 : CPLHTTPDestroyResult(psResult);
1052 : }
1053 : }
1054 : }
1055 : else
1056 : {
1057 : // key is a URL
1058 6 : static lru11::Cache<std::string, PCSigningInfo> goCacheURL{1024};
1059 :
1060 10 : if (goCacheURL.tryGet(m_pszURL, sSigningInfo) &&
1061 4 : time(nullptr) + knExpirationDelayMargin <=
1062 4 : sSigningInfo.nExpireTimestamp)
1063 : {
1064 3 : m_osQueryString = sSigningInfo.osQueryString;
1065 : }
1066 : else
1067 : {
1068 : const auto psResult =
1069 9 : CPLHTTPFetch((std::string(CPLGetConfigOption(
1070 : "VSICURL_PC_SAS_SIGN_HREF_URL",
1071 : "https://planetarycomputer.microsoft.com/api/"
1072 6 : "sas/v1/sign?href=")) +
1073 3 : m_pszURL)
1074 : .c_str(),
1075 : nullptr);
1076 3 : if (psResult)
1077 : {
1078 : const auto aosKeyVals = CPLParseKeyValueJson(
1079 6 : reinterpret_cast<const char *>(psResult->pabyData));
1080 3 : const char *pszHref = aosKeyVals.FetchNameValue("href");
1081 3 : if (pszHref && STARTS_WITH(pszHref, m_pszURL))
1082 : {
1083 3 : m_osQueryString = pszHref + strlen(m_pszURL);
1084 :
1085 3 : sSigningInfo.osQueryString = m_osQueryString;
1086 3 : sSigningInfo.nExpireTimestamp = 0;
1087 : const char *pszExpiry =
1088 3 : aosKeyVals.FetchNameValue("msft:expiry");
1089 3 : if (pszExpiry)
1090 : {
1091 3 : Iso8601ToUnixTime(pszExpiry,
1092 : &sSigningInfo.nExpireTimestamp);
1093 : }
1094 3 : goCacheURL.insert(m_pszURL, sSigningInfo);
1095 :
1096 3 : CPLDebug("VSICURL",
1097 : "Got signature from Planetary Computer: %s",
1098 : m_osQueryString.c_str());
1099 : }
1100 3 : CPLHTTPDestroyResult(psResult);
1101 : }
1102 : }
1103 : }
1104 11 : }
1105 :
1106 : /************************************************************************/
1107 : /* UpdateQueryString() */
1108 : /************************************************************************/
1109 :
1110 944 : void VSICurlHandle::UpdateQueryString() const
1111 : {
1112 944 : if (m_bPlanetaryComputerURLSigning)
1113 : {
1114 11 : ManagePlanetaryComputerSigning();
1115 : }
1116 : else
1117 : {
1118 933 : const char *pszQueryString = VSIGetPathSpecificOption(
1119 : m_osFilename.c_str(), "VSICURL_QUERY_STRING", nullptr);
1120 933 : if (pszQueryString)
1121 : {
1122 4 : if (m_osFilename.back() == '?')
1123 : {
1124 2 : if (pszQueryString[0] == '?')
1125 1 : m_osQueryString = pszQueryString + 1;
1126 : else
1127 1 : m_osQueryString = pszQueryString;
1128 : }
1129 : else
1130 : {
1131 2 : if (pszQueryString[0] == '?')
1132 1 : m_osQueryString = pszQueryString;
1133 : else
1134 : {
1135 1 : m_osQueryString = "?";
1136 1 : m_osQueryString.append(pszQueryString);
1137 : }
1138 : }
1139 : }
1140 : }
1141 944 : }
1142 :
1143 : /************************************************************************/
1144 : /* GetFileSizeOrHeaders() */
1145 : /************************************************************************/
1146 :
1147 1884 : vsi_l_offset VSICurlHandle::GetFileSizeOrHeaders(bool bSetError,
1148 : bool bGetHeaders)
1149 : {
1150 1884 : if (oFileProp.bHasComputedFileSize && !bGetHeaders)
1151 1422 : return oFileProp.fileSize;
1152 :
1153 924 : NetworkStatisticsFileSystem oContextFS(poFS->GetFSPrefix().c_str());
1154 924 : NetworkStatisticsFile oContextFile(m_osFilename.c_str());
1155 924 : NetworkStatisticsAction oContextAction("GetFileSize");
1156 :
1157 462 : oFileProp.bHasComputedFileSize = true;
1158 :
1159 462 : CURLM *hCurlMultiHandle = poFS->GetCurlMultiHandleFor(m_pszURL);
1160 :
1161 462 : UpdateQueryString();
1162 :
1163 924 : std::string osURL(m_pszURL + m_osQueryString);
1164 462 : int nTryCount = 0;
1165 462 : bool bRetryWithGet = false;
1166 462 : bool bRetryWithLimitedRangeGet = false;
1167 462 : bool bS3LikeRedirect = false;
1168 924 : CPLHTTPRetryContext oRetryContext(m_oRetryParameters);
1169 :
1170 472 : retry:
1171 472 : ++nTryCount;
1172 472 : CURL *hCurlHandle = curl_easy_init();
1173 :
1174 472 : struct curl_slist *headers = nullptr;
1175 472 : if (bS3LikeRedirect)
1176 : {
1177 : // Do not propagate authentication sent to the original URL to a S3-like
1178 : // redirect.
1179 2 : CPLStringList aosHTTPOptions{};
1180 4 : for (const auto &pszOption : m_aosHTTPOptions)
1181 : {
1182 2 : if (STARTS_WITH_CI(pszOption, "HTTPAUTH") ||
1183 1 : STARTS_WITH_CI(pszOption, "HTTP_BEARER"))
1184 2 : continue;
1185 0 : aosHTTPOptions.AddString(pszOption);
1186 : }
1187 2 : headers = VSICurlSetOptions(hCurlHandle, osURL.c_str(),
1188 2 : aosHTTPOptions.List());
1189 : }
1190 : else
1191 : {
1192 470 : headers = VSICurlSetOptions(hCurlHandle, osURL.c_str(),
1193 470 : m_aosHTTPOptions.List());
1194 : }
1195 :
1196 472 : WriteFuncStruct sWriteFuncHeaderData;
1197 472 : VSICURLInitWriteFuncStruct(&sWriteFuncHeaderData, nullptr, nullptr,
1198 : nullptr);
1199 472 : sWriteFuncHeaderData.bDetectRangeDownloadingError = false;
1200 472 : sWriteFuncHeaderData.bIsHTTP = STARTS_WITH(osURL.c_str(), "http");
1201 :
1202 472 : WriteFuncStruct sWriteFuncData;
1203 472 : VSICURLInitWriteFuncStruct(&sWriteFuncData, nullptr, nullptr, nullptr);
1204 :
1205 472 : std::string osVerb;
1206 472 : std::string osRange; // leave in this scope !
1207 472 : int nRoundedBufSize = 0;
1208 472 : const int knDOWNLOAD_CHUNK_SIZE = VSICURLGetDownloadChunkSize();
1209 472 : bool bHasUsedLimitedRangeGet = false;
1210 472 : if (bRetryWithLimitedRangeGet || UseLimitRangeGetInsteadOfHead())
1211 : {
1212 137 : bHasUsedLimitedRangeGet = true;
1213 137 : osVerb = "GET";
1214 : const int nBufSize = std::clamp(
1215 411 : atoi(CPLGetConfigOption("GDAL_INGESTED_BYTES_AT_OPEN", "1024")),
1216 137 : 1024, 10 * 1024 * 1024);
1217 137 : nRoundedBufSize = cpl::div_round_up(nBufSize, knDOWNLOAD_CHUNK_SIZE) *
1218 : knDOWNLOAD_CHUNK_SIZE;
1219 :
1220 : // so it gets included in Azure signature
1221 137 : osRange = CPLSPrintf("Range: bytes=0-%d", nRoundedBufSize - 1);
1222 137 : headers = curl_slist_append(headers, osRange.c_str());
1223 : }
1224 : // HACK for mbtiles driver: http://a.tiles.mapbox.com/v3/ doesn't accept
1225 : // HEAD, as it is a redirect to AWS S3 signed URL, but those are only valid
1226 : // for a given type of HTTP request, and thus GET. This is valid for any
1227 : // signed URL for AWS S3.
1228 662 : else if (bRetryWithGet ||
1229 653 : strstr(osURL.c_str(), ".tiles.mapbox.com/") != nullptr ||
1230 988 : VSICurlIsS3LikeSignedURL(osURL.c_str()) || !m_bUseHead)
1231 : {
1232 14 : sWriteFuncData.bInterrupted = true;
1233 14 : osVerb = "GET";
1234 : }
1235 : else
1236 : {
1237 321 : unchecked_curl_easy_setopt(hCurlHandle, CURLOPT_NOBODY, 1);
1238 321 : unchecked_curl_easy_setopt(hCurlHandle, CURLOPT_HTTPGET, 0);
1239 321 : unchecked_curl_easy_setopt(hCurlHandle, CURLOPT_HEADER, 1);
1240 321 : osVerb = "HEAD";
1241 : }
1242 :
1243 472 : bRetryWithLimitedRangeGet = false;
1244 :
1245 472 : if (!AllowAutomaticRedirection())
1246 88 : unchecked_curl_easy_setopt(hCurlHandle, CURLOPT_FOLLOWLOCATION, 0);
1247 :
1248 472 : unchecked_curl_easy_setopt(hCurlHandle, CURLOPT_HEADERDATA,
1249 : &sWriteFuncHeaderData);
1250 472 : unchecked_curl_easy_setopt(hCurlHandle, CURLOPT_HEADERFUNCTION,
1251 : VSICurlHandleWriteFunc);
1252 :
1253 : // Bug with older curl versions (<=7.16.4) and FTP.
1254 : // See http://curl.haxx.se/mail/lib-2007-08/0312.html
1255 472 : unchecked_curl_easy_setopt(hCurlHandle, CURLOPT_WRITEDATA, &sWriteFuncData);
1256 472 : unchecked_curl_easy_setopt(hCurlHandle, CURLOPT_WRITEFUNCTION,
1257 : VSICurlHandleWriteFunc);
1258 :
1259 472 : char szCurlErrBuf[CURL_ERROR_SIZE + 1] = {};
1260 472 : szCurlErrBuf[0] = '\0';
1261 472 : unchecked_curl_easy_setopt(hCurlHandle, CURLOPT_ERRORBUFFER, szCurlErrBuf);
1262 :
1263 472 : headers = GetCurlHeaders(osVerb, headers);
1264 472 : unchecked_curl_easy_setopt(hCurlHandle, CURLOPT_HTTPHEADER, headers);
1265 :
1266 472 : unchecked_curl_easy_setopt(hCurlHandle, CURLOPT_FILETIME, 1);
1267 :
1268 472 : VSICURLMultiPerform(hCurlMultiHandle, hCurlHandle, &m_bInterrupt);
1269 :
1270 472 : VSICURLResetHeaderAndWriterFunctions(hCurlHandle);
1271 :
1272 472 : curl_slist_free_all(headers);
1273 :
1274 472 : oFileProp.eExists = EXIST_UNKNOWN;
1275 :
1276 472 : long mtime = 0;
1277 472 : curl_easy_getinfo(hCurlHandle, CURLINFO_FILETIME, &mtime);
1278 :
1279 472 : if (osVerb == "GET")
1280 151 : NetworkStatisticsLogger::LogGET(sWriteFuncData.nSize);
1281 : else
1282 321 : NetworkStatisticsLogger::LogHEAD();
1283 :
1284 472 : if (STARTS_WITH(osURL.c_str(), "ftp"))
1285 : {
1286 0 : if (sWriteFuncData.pBuffer != nullptr)
1287 : {
1288 : const char *pszContentLength =
1289 0 : strstr(const_cast<const char *>(sWriteFuncData.pBuffer),
1290 : "Content-Length: ");
1291 0 : if (pszContentLength)
1292 : {
1293 0 : pszContentLength += strlen("Content-Length: ");
1294 0 : oFileProp.eExists = EXIST_YES;
1295 0 : oFileProp.fileSize =
1296 0 : CPLScanUIntBig(pszContentLength,
1297 0 : static_cast<int>(strlen(pszContentLength)));
1298 : if constexpr (ENABLE_DEBUG)
1299 : {
1300 0 : CPLDebug(poFS->GetDebugKey(),
1301 : "GetFileSize(%s)=" CPL_FRMT_GUIB, osURL.c_str(),
1302 : oFileProp.fileSize);
1303 : }
1304 : }
1305 : }
1306 : }
1307 :
1308 472 : double dfSize = 0;
1309 472 : long response_code = -1;
1310 472 : if (oFileProp.eExists != EXIST_YES)
1311 : {
1312 472 : curl_easy_getinfo(hCurlHandle, CURLINFO_HTTP_CODE, &response_code);
1313 :
1314 472 : bool bAlreadyLogged = false;
1315 472 : if (response_code >= 400 && szCurlErrBuf[0] == '\0')
1316 : {
1317 : const bool bLogResponse =
1318 222 : CPLTestBool(CPLGetConfigOption("CPL_CURL_VERBOSE", "NO"));
1319 222 : if (bLogResponse && sWriteFuncData.pBuffer)
1320 : {
1321 0 : const char *pszErrorMsg =
1322 : static_cast<const char *>(sWriteFuncData.pBuffer);
1323 0 : bAlreadyLogged = true;
1324 0 : CPLDebug(
1325 0 : poFS->GetDebugKey(),
1326 : "GetFileSize(%s): response_code=%d, server error msg=%s",
1327 : osURL.c_str(), static_cast<int>(response_code),
1328 0 : pszErrorMsg[0] ? pszErrorMsg : "(no message provided)");
1329 222 : }
1330 : }
1331 250 : else if (szCurlErrBuf[0] != '\0')
1332 : {
1333 15 : bAlreadyLogged = true;
1334 15 : CPLDebug(poFS->GetDebugKey(),
1335 : "GetFileSize(%s): response_code=%d, curl error msg=%s",
1336 : osURL.c_str(), static_cast<int>(response_code),
1337 : szCurlErrBuf);
1338 : }
1339 :
1340 472 : std::string osEffectiveURL;
1341 : {
1342 472 : char *pszEffectiveURL = nullptr;
1343 472 : curl_easy_getinfo(hCurlHandle, CURLINFO_EFFECTIVE_URL,
1344 : &pszEffectiveURL);
1345 472 : if (pszEffectiveURL)
1346 472 : osEffectiveURL = pszEffectiveURL;
1347 : }
1348 :
1349 944 : if (!osEffectiveURL.empty() &&
1350 472 : strstr(osEffectiveURL.c_str(), osURL.c_str()) == nullptr)
1351 : {
1352 : // Moved permanently ?
1353 65 : if (sWriteFuncHeaderData.nFirstHTTPCode == 301 ||
1354 28 : (m_bUseRedirectURLIfNoQueryStringParams &&
1355 2 : osEffectiveURL.find('?') == std::string::npos))
1356 : {
1357 15 : CPLDebug(poFS->GetDebugKey(),
1358 : "Using effective URL %s permanently",
1359 : osEffectiveURL.c_str());
1360 15 : oFileProp.osRedirectURL = osEffectiveURL;
1361 15 : poFS->SetCachedFileProp(m_pszURL, oFileProp);
1362 : }
1363 : else
1364 : {
1365 24 : CPLDebug(poFS->GetDebugKey(),
1366 : "Using effective URL %s temporarily",
1367 : osEffectiveURL.c_str());
1368 : }
1369 :
1370 : // Is this is a redirect to a S3 URL?
1371 42 : if (VSICurlIsS3LikeSignedURL(osEffectiveURL.c_str()) &&
1372 3 : !VSICurlIsS3LikeSignedURL(osURL.c_str()))
1373 : {
1374 : // Note that this is a redirect as we won't notice after the
1375 : // retry.
1376 3 : bS3LikeRedirect = true;
1377 :
1378 3 : if (!bRetryWithGet && osVerb == "HEAD" && response_code == 403)
1379 : {
1380 2 : CPLDebug(poFS->GetDebugKey(),
1381 : "Redirected to a AWS S3 signed URL. Retrying "
1382 : "with GET request instead of HEAD since the URL "
1383 : "might be valid only for GET");
1384 2 : bRetryWithGet = true;
1385 2 : osURL = std::move(osEffectiveURL);
1386 2 : CPLFree(sWriteFuncData.pBuffer);
1387 2 : CPLFree(sWriteFuncHeaderData.pBuffer);
1388 2 : curl_easy_cleanup(hCurlHandle);
1389 2 : goto retry;
1390 : }
1391 : }
1392 57 : else if (oFileProp.osRedirectURL.empty() && nTryCount == 1 &&
1393 42 : ((response_code >= 300 && response_code < 400) ||
1394 42 : (osVerb == "HEAD" && response_code == 403)))
1395 : {
1396 1 : if (response_code == 403)
1397 : {
1398 1 : CPLDebug(
1399 1 : poFS->GetDebugKey(),
1400 : "Retrying redirected URL with GET instead of HEAD");
1401 1 : bRetryWithGet = true;
1402 : }
1403 1 : osURL = std::move(osEffectiveURL);
1404 1 : CPLFree(sWriteFuncData.pBuffer);
1405 1 : CPLFree(sWriteFuncHeaderData.pBuffer);
1406 1 : curl_easy_cleanup(hCurlHandle);
1407 1 : goto retry;
1408 : }
1409 : }
1410 :
1411 3 : if (bS3LikeRedirect && response_code >= 200 && response_code < 300 &&
1412 3 : sWriteFuncHeaderData.nTimestampDate > 0 &&
1413 475 : !osEffectiveURL.empty() &&
1414 3 : CPLTestBool(
1415 : CPLGetConfigOption("CPL_VSIL_CURL_USE_S3_REDIRECT", "TRUE")))
1416 : {
1417 : const GIntBig nExpireTimestamp =
1418 3 : VSICurlGetExpiresFromS3LikeSignedURL(osEffectiveURL.c_str());
1419 3 : if (nExpireTimestamp > sWriteFuncHeaderData.nTimestampDate + 10)
1420 : {
1421 3 : const int nValidity = static_cast<int>(
1422 3 : nExpireTimestamp - sWriteFuncHeaderData.nTimestampDate);
1423 3 : CPLDebug(poFS->GetDebugKey(),
1424 : "Will use redirect URL for the next %d seconds",
1425 : nValidity);
1426 : // As our local clock might not be in sync with server clock,
1427 : // figure out the expiration timestamp in local time
1428 3 : oFileProp.bS3LikeRedirect = true;
1429 3 : oFileProp.nExpireTimestampLocal = time(nullptr) + nValidity;
1430 3 : oFileProp.osRedirectURL = osEffectiveURL;
1431 3 : poFS->SetCachedFileProp(m_pszURL, oFileProp);
1432 : }
1433 : }
1434 :
1435 : // Split a string with the raw HTTP response headers as a key/value
1436 : // CPLStringList
1437 268 : const auto TokenizeHeaders = [](const char *pszHeaders) -> CPLStringList
1438 : {
1439 268 : CPLStringList aosHeaders;
1440 2266 : while (pszHeaders)
1441 : {
1442 2266 : const char *pszDelim = strchr(pszHeaders, ':');
1443 2266 : if (!pszDelim)
1444 268 : break;
1445 1998 : const char *pszValue = pszDelim + 1;
1446 :
1447 : // Skip whitespace after colon
1448 3996 : while (*pszValue == ' ' || *pszValue == '\t')
1449 1998 : ++pszValue;
1450 :
1451 : // Find end of value
1452 1998 : const char *pszEndOfValue = pszValue;
1453 106845 : while (*pszEndOfValue &&
1454 106845 : !(*pszEndOfValue == '\r' && pszEndOfValue[1] == '\n'))
1455 104847 : ++pszEndOfValue;
1456 :
1457 : aosHeaders.SetNameValue(
1458 3996 : std::string(pszHeaders, pszDelim - pszHeaders).c_str(),
1459 5994 : std::string(pszValue, pszEndOfValue - pszValue).c_str());
1460 :
1461 1998 : if (*pszEndOfValue == '\r' && pszEndOfValue[1] == '\n')
1462 1998 : pszHeaders = pszEndOfValue + 2;
1463 : else
1464 : break;
1465 : }
1466 268 : return aosHeaders;
1467 : };
1468 :
1469 469 : if (response_code < 400)
1470 : {
1471 250 : curl_off_t nSizeTmp = 0;
1472 250 : const CURLcode code = curl_easy_getinfo(
1473 : hCurlHandle, CURLINFO_CONTENT_LENGTH_DOWNLOAD_T, &nSizeTmp);
1474 250 : CPL_IGNORE_RET_VAL(dfSize);
1475 250 : dfSize = static_cast<double>(nSizeTmp);
1476 250 : if (code == 0)
1477 : {
1478 250 : oFileProp.eExists = EXIST_YES;
1479 250 : if (dfSize < 0)
1480 : {
1481 21 : if (osVerb == "HEAD" && !bRetryWithGet &&
1482 9 : response_code == 200)
1483 : {
1484 6 : if (sWriteFuncHeaderData.pBuffer)
1485 : {
1486 : const CPLStringList aosHeaders(
1487 6 : TokenizeHeaders(sWriteFuncHeaderData.pBuffer));
1488 6 : if (strcmp(aosHeaders.FetchNameValueDef(
1489 : "accept-ranges", ""),
1490 6 : "bytes") == 0)
1491 : {
1492 2 : CPLDebug(
1493 2 : poFS->GetDebugKey(),
1494 : "HEAD did not provide file size. Retrying "
1495 : "with limited range GET");
1496 2 : bRetryWithLimitedRangeGet = true;
1497 2 : CPLFree(sWriteFuncData.pBuffer);
1498 2 : CPLFree(sWriteFuncHeaderData.pBuffer);
1499 2 : curl_easy_cleanup(hCurlHandle);
1500 2 : goto retry;
1501 : }
1502 : }
1503 :
1504 4 : CPLDebug(poFS->GetDebugKey(),
1505 : "HEAD did not provide file size. Retrying "
1506 : "with GET");
1507 4 : bRetryWithGet = true;
1508 4 : CPLFree(sWriteFuncData.pBuffer);
1509 4 : CPLFree(sWriteFuncHeaderData.pBuffer);
1510 4 : curl_easy_cleanup(hCurlHandle);
1511 4 : goto retry;
1512 : }
1513 6 : oFileProp.fileSize = 0;
1514 : }
1515 : else
1516 238 : oFileProp.fileSize = static_cast<GUIntBig>(dfSize);
1517 : }
1518 : }
1519 :
1520 463 : if (sWriteFuncHeaderData.pBuffer != nullptr &&
1521 458 : (response_code == 200 || response_code == 206))
1522 : {
1523 : {
1524 : const CPLStringList aosHeaders(
1525 476 : TokenizeHeaders(sWriteFuncHeaderData.pBuffer));
1526 3276 : for (const auto &[pszKey, pszValue] :
1527 3514 : cpl::IterateNameValue(aosHeaders))
1528 : {
1529 1638 : if (bGetHeaders)
1530 : {
1531 17 : m_aosHeaders.SetNameValue(pszKey, pszValue);
1532 : }
1533 3296 : if (EQUAL(pszKey, "Cache-Control") &&
1534 1658 : EQUAL(pszValue, "no-cache") &&
1535 20 : CPLTestBool(CPLGetConfigOption(
1536 : "CPL_VSIL_CURL_HONOR_CACHE_CONTROL", "YES")))
1537 : {
1538 20 : m_bCached = false;
1539 : }
1540 :
1541 1618 : else if (EQUAL(pszKey, "ETag"))
1542 : {
1543 96 : std::string osValue(pszValue);
1544 95 : if (osValue.size() >= 2 && osValue.front() == '"' &&
1545 47 : osValue.back() == '"')
1546 47 : osValue = osValue.substr(1, osValue.size() - 2);
1547 48 : oFileProp.ETag = std::move(osValue);
1548 : }
1549 :
1550 : // Azure Data Lake Storage
1551 1570 : else if (EQUAL(pszKey, "x-ms-resource-type"))
1552 : {
1553 11 : if (EQUAL(pszValue, "file"))
1554 : {
1555 9 : oFileProp.nMode |= S_IFREG;
1556 : }
1557 2 : else if (EQUAL(pszValue, "directory"))
1558 : {
1559 2 : oFileProp.bIsDirectory = true;
1560 2 : oFileProp.nMode |= S_IFDIR;
1561 : }
1562 : }
1563 1559 : else if (EQUAL(pszKey, "x-ms-permissions"))
1564 : {
1565 11 : oFileProp.nMode |=
1566 11 : VSICurlParseUnixPermissions(pszValue);
1567 : }
1568 :
1569 : // https://overturemapswestus2.blob.core.windows.net/release/2024-11-13.0/theme%3Ddivisions/type%3Ddivision_area
1570 : // returns a x-ms-meta-hdi_isfolder: true header
1571 1548 : else if (EQUAL(pszKey, "x-ms-meta-hdi_isfolder") &&
1572 0 : EQUAL(pszValue, "true"))
1573 : {
1574 0 : oFileProp.bIsAzureFolder = true;
1575 0 : oFileProp.bIsDirectory = true;
1576 0 : oFileProp.nMode |= S_IFDIR;
1577 : }
1578 : }
1579 : }
1580 : }
1581 :
1582 463 : if (bHasUsedLimitedRangeGet && response_code == 206)
1583 : {
1584 24 : oFileProp.eExists = EXIST_NO;
1585 24 : oFileProp.fileSize = 0;
1586 24 : if (sWriteFuncHeaderData.pBuffer != nullptr)
1587 : {
1588 : const CPLStringList aosHeaders(
1589 48 : TokenizeHeaders(sWriteFuncHeaderData.pBuffer));
1590 : const char *pszContentRange =
1591 24 : aosHeaders.FetchNameValue("content-range");
1592 : // Trailing space in string intended
1593 24 : if (pszContentRange &&
1594 24 : STARTS_WITH_CI(pszContentRange, "bytes "))
1595 : {
1596 24 : pszContentRange += strlen("bytes ");
1597 24 : pszContentRange = strchr(pszContentRange, '/');
1598 24 : if (pszContentRange)
1599 : {
1600 24 : oFileProp.eExists = EXIST_YES;
1601 24 : oFileProp.fileSize = static_cast<GUIntBig>(
1602 24 : CPLAtoGIntBig(pszContentRange + 1));
1603 : }
1604 : }
1605 :
1606 : // Add first bytes to cache
1607 24 : if (sWriteFuncData.pBuffer != nullptr)
1608 : {
1609 24 : size_t nOffset = 0;
1610 48 : while (nOffset < sWriteFuncData.nSize)
1611 : {
1612 : const size_t nToCache =
1613 48 : std::min<size_t>(sWriteFuncData.nSize - nOffset,
1614 24 : knDOWNLOAD_CHUNK_SIZE);
1615 24 : poFS->AddRegion(m_pszURL, nOffset, nToCache,
1616 24 : sWriteFuncData.pBuffer + nOffset);
1617 24 : nOffset += nToCache;
1618 : }
1619 : }
1620 24 : }
1621 : }
1622 439 : else if (IsDirectoryFromExists(osVerb.c_str(),
1623 439 : static_cast<int>(response_code)))
1624 : {
1625 10 : oFileProp.eExists = EXIST_YES;
1626 10 : oFileProp.fileSize = 0;
1627 10 : oFileProp.bIsDirectory = true;
1628 : }
1629 : // 405 = Method not allowed
1630 429 : else if (response_code == 405 && !bRetryWithGet && osVerb == "HEAD")
1631 : {
1632 1 : CPLDebug(poFS->GetDebugKey(),
1633 : "HEAD not allowed. Retrying with GET");
1634 1 : bRetryWithGet = true;
1635 1 : CPLFree(sWriteFuncData.pBuffer);
1636 1 : CPLFree(sWriteFuncHeaderData.pBuffer);
1637 1 : curl_easy_cleanup(hCurlHandle);
1638 1 : goto retry;
1639 : }
1640 428 : else if (response_code == 416)
1641 : {
1642 0 : oFileProp.eExists = EXIST_YES;
1643 0 : oFileProp.fileSize = 0;
1644 : }
1645 428 : else if (response_code != 200)
1646 : {
1647 : // Look if we should attempt a retry
1648 214 : if (oRetryContext.CanRetry(static_cast<int>(response_code),
1649 214 : sWriteFuncHeaderData.pBuffer,
1650 : szCurlErrBuf))
1651 : {
1652 0 : CPLError(CE_Warning, CPLE_AppDefined,
1653 : "HTTP error code: %d - %s. "
1654 : "Retrying again in %.1f secs",
1655 : static_cast<int>(response_code), m_pszURL,
1656 : oRetryContext.GetCurrentDelay());
1657 0 : CPLSleep(oRetryContext.GetCurrentDelay());
1658 0 : CPLFree(sWriteFuncData.pBuffer);
1659 0 : CPLFree(sWriteFuncHeaderData.pBuffer);
1660 0 : curl_easy_cleanup(hCurlHandle);
1661 0 : goto retry;
1662 : }
1663 :
1664 214 : if (sWriteFuncData.pBuffer != nullptr)
1665 : {
1666 178 : if (UseLimitRangeGetInsteadOfHead() &&
1667 5 : CanRestartOnError(sWriteFuncData.pBuffer,
1668 5 : sWriteFuncHeaderData.pBuffer, bSetError))
1669 : {
1670 1 : oFileProp.bHasComputedFileSize = false;
1671 1 : CPLFree(sWriteFuncData.pBuffer);
1672 1 : CPLFree(sWriteFuncHeaderData.pBuffer);
1673 1 : curl_easy_cleanup(hCurlHandle);
1674 1 : return GetFileSizeOrHeaders(bSetError, bGetHeaders);
1675 : }
1676 : else
1677 : {
1678 172 : CPL_IGNORE_RET_VAL(CanRestartOnError(
1679 172 : sWriteFuncData.pBuffer, sWriteFuncHeaderData.pBuffer,
1680 172 : bSetError));
1681 : }
1682 : }
1683 :
1684 : // If there was no VSI error thrown in the process,
1685 : // fail by reporting the HTTP response code.
1686 213 : if (bSetError && VSIGetLastErrorNo() == 0)
1687 : {
1688 13 : if (strlen(szCurlErrBuf) > 0)
1689 : {
1690 1 : if (response_code == 0)
1691 : {
1692 1 : VSIError(VSIE_HttpError, "CURL error: %s",
1693 : szCurlErrBuf);
1694 : }
1695 : else
1696 : {
1697 0 : VSIError(VSIE_HttpError, "HTTP response code: %d - %s",
1698 : static_cast<int>(response_code), szCurlErrBuf);
1699 : }
1700 : }
1701 : else
1702 : {
1703 12 : VSIError(VSIE_HttpError, "HTTP response code: %d",
1704 : static_cast<int>(response_code));
1705 : }
1706 : }
1707 : else
1708 : {
1709 200 : if (response_code != 400 && response_code != 404)
1710 : {
1711 23 : CPLError(CE_Warning, CPLE_AppDefined,
1712 : "HTTP response code on %s: %d", osURL.c_str(),
1713 : static_cast<int>(response_code));
1714 : }
1715 : // else a CPLDebug() is emitted below
1716 : }
1717 :
1718 213 : oFileProp.eExists = EXIST_NO;
1719 213 : oFileProp.nHTTPCode = static_cast<int>(response_code);
1720 213 : oFileProp.fileSize = 0;
1721 : }
1722 214 : else if (sWriteFuncData.pBuffer != nullptr)
1723 : {
1724 189 : ProcessGetFileSizeResult(
1725 189 : reinterpret_cast<const char *>(sWriteFuncData.pBuffer));
1726 : }
1727 :
1728 : // Try to guess if this is a directory. Generally if this is a
1729 : // directory, curl will retry with an URL with slash added.
1730 461 : if (!osEffectiveURL.empty() &&
1731 461 : strncmp(osURL.c_str(), osEffectiveURL.c_str(), osURL.size()) == 0 &&
1732 924 : osEffectiveURL[osURL.size()] == '/' &&
1733 2 : oFileProp.eExists != EXIST_NO)
1734 : {
1735 1 : oFileProp.eExists = EXIST_YES;
1736 1 : oFileProp.fileSize = 0;
1737 1 : oFileProp.bIsDirectory = true;
1738 : }
1739 460 : else if (osURL.back() == '/')
1740 : {
1741 37 : oFileProp.bIsDirectory = true;
1742 : }
1743 :
1744 461 : if (!bAlreadyLogged)
1745 : {
1746 446 : CPLDebug(poFS->GetDebugKey(),
1747 : "GetFileSize(%s)=" CPL_FRMT_GUIB " response_code=%d",
1748 : osURL.c_str(), oFileProp.fileSize,
1749 : static_cast<int>(response_code));
1750 : }
1751 : }
1752 :
1753 461 : CPLFree(sWriteFuncData.pBuffer);
1754 461 : CPLFree(sWriteFuncHeaderData.pBuffer);
1755 461 : curl_easy_cleanup(hCurlHandle);
1756 :
1757 461 : oFileProp.bHasComputedFileSize = true;
1758 461 : if (mtime > 0)
1759 33 : oFileProp.mTime = mtime;
1760 : // Do not update cached file properties if cURL returned a non-HTTP error
1761 461 : if (response_code != 0)
1762 456 : poFS->SetCachedFileProp(m_pszURL, oFileProp);
1763 :
1764 461 : return oFileProp.fileSize;
1765 : }
1766 :
1767 : /************************************************************************/
1768 : /* Exists() */
1769 : /************************************************************************/
1770 :
1771 1191 : bool VSICurlHandle::Exists(bool bSetError)
1772 : {
1773 1191 : if (oFileProp.eExists == EXIST_UNKNOWN)
1774 : {
1775 264 : GetFileSize(bSetError);
1776 : }
1777 927 : else if (oFileProp.eExists == EXIST_NO)
1778 : {
1779 : // If there was no VSI error thrown in the process,
1780 : // and we know the HTTP error code of the first request where the
1781 : // file could not be retrieved, fail by reporting the HTTP code.
1782 236 : if (bSetError && VSIGetLastErrorNo() == 0 && oFileProp.nHTTPCode)
1783 : {
1784 1 : VSIError(VSIE_HttpError, "HTTP response code: %d",
1785 : oFileProp.nHTTPCode);
1786 : }
1787 : }
1788 :
1789 1191 : return oFileProp.eExists == EXIST_YES;
1790 : }
1791 :
1792 : /************************************************************************/
1793 : /* Tell() */
1794 : /************************************************************************/
1795 :
1796 4162 : vsi_l_offset VSICurlHandle::Tell()
1797 : {
1798 4162 : return curOffset;
1799 : }
1800 :
1801 : /************************************************************************/
1802 : /* GetRedirectURLIfValid() */
1803 : /************************************************************************/
1804 :
1805 : std::string
1806 482 : VSICurlHandle::GetRedirectURLIfValid(bool &bHasExpired,
1807 : CPLStringList &aosHTTPOptions) const
1808 : {
1809 482 : bHasExpired = false;
1810 482 : poFS->GetCachedFileProp(m_pszURL, oFileProp);
1811 :
1812 482 : std::string osURL(m_pszURL + m_osQueryString);
1813 482 : if (oFileProp.bS3LikeRedirect)
1814 : {
1815 16 : if (time(nullptr) + 1 < oFileProp.nExpireTimestampLocal)
1816 : {
1817 16 : CPLDebug(poFS->GetDebugKey(),
1818 : "Using redirect URL as it looks to be still valid "
1819 : "(%d seconds left)",
1820 16 : static_cast<int>(oFileProp.nExpireTimestampLocal -
1821 16 : time(nullptr)));
1822 16 : osURL = oFileProp.osRedirectURL;
1823 : }
1824 : else
1825 : {
1826 0 : CPLDebug(poFS->GetDebugKey(),
1827 : "Redirect URL has expired. Using original URL");
1828 0 : oFileProp.bS3LikeRedirect = false;
1829 0 : poFS->SetCachedFileProp(m_pszURL, oFileProp);
1830 0 : bHasExpired = true;
1831 : }
1832 : }
1833 466 : else if (!oFileProp.osRedirectURL.empty())
1834 : {
1835 14 : osURL = oFileProp.osRedirectURL;
1836 14 : bHasExpired = false;
1837 : }
1838 :
1839 482 : if (m_pszURL != osURL)
1840 : {
1841 31 : const char *pszAuthorizationHeaderAllowed = VSIGetPathSpecificOption(
1842 : m_osFilename.c_str(),
1843 : "CPL_VSIL_CURL_AUTHORIZATION_HEADER_ALLOWED_IF_REDIRECT",
1844 : "IF_SAME_HOST");
1845 31 : if (EQUAL(pszAuthorizationHeaderAllowed, "IF_SAME_HOST"))
1846 : {
1847 50 : const auto ExtractServer = [](const std::string &s)
1848 : {
1849 50 : size_t afterHTTPPos = 0;
1850 50 : if (STARTS_WITH(s.c_str(), "http://"))
1851 26 : afterHTTPPos = strlen("http://");
1852 24 : else if (STARTS_WITH(s.c_str(), "https://"))
1853 24 : afterHTTPPos = strlen("https://");
1854 50 : const auto posSlash = s.find('/', afterHTTPPos);
1855 50 : if (posSlash != std::string::npos)
1856 50 : return s.substr(afterHTTPPos, posSlash - afterHTTPPos);
1857 : else
1858 0 : return s.substr(afterHTTPPos);
1859 : };
1860 :
1861 25 : if (ExtractServer(osURL) != ExtractServer(m_pszURL))
1862 : {
1863 : aosHTTPOptions.SetNameValue("AUTHORIZATION_HEADER_ALLOWED",
1864 20 : "NO");
1865 : }
1866 : }
1867 6 : else if (!CPLTestBool(pszAuthorizationHeaderAllowed))
1868 : {
1869 3 : aosHTTPOptions.SetNameValue("AUTHORIZATION_HEADER_ALLOWED", "NO");
1870 : }
1871 : }
1872 :
1873 482 : return osURL;
1874 : }
1875 :
1876 : /************************************************************************/
1877 : /* CurrentDownload */
1878 : /************************************************************************/
1879 :
1880 : namespace
1881 : {
1882 : struct CurrentDownload
1883 : {
1884 : VSICurlFilesystemHandlerBase *m_poFS = nullptr;
1885 : std::string m_osURL{};
1886 : vsi_l_offset m_nStartOffset = 0;
1887 : int m_nBlocks = 0;
1888 : std::string m_osAlreadyDownloadedData{};
1889 : bool m_bHasAlreadyDownloadedData = false;
1890 :
1891 403 : CurrentDownload(VSICurlFilesystemHandlerBase *poFS, const char *pszURL,
1892 : vsi_l_offset startOffset, int nBlocks)
1893 403 : : m_poFS(poFS), m_osURL(pszURL), m_nStartOffset(startOffset),
1894 403 : m_nBlocks(nBlocks)
1895 : {
1896 403 : auto res = m_poFS->NotifyStartDownloadRegion(m_osURL, m_nStartOffset,
1897 806 : m_nBlocks);
1898 403 : m_bHasAlreadyDownloadedData = res.first;
1899 403 : m_osAlreadyDownloadedData = std::move(res.second);
1900 403 : }
1901 :
1902 403 : bool HasAlreadyDownloadedData() const
1903 : {
1904 403 : return m_bHasAlreadyDownloadedData;
1905 : }
1906 :
1907 2 : const std::string &GetAlreadyDownloadedData() const
1908 : {
1909 2 : return m_osAlreadyDownloadedData;
1910 : }
1911 :
1912 396 : void SetData(const std::string &osData)
1913 : {
1914 396 : CPLAssert(!m_bHasAlreadyDownloadedData);
1915 396 : m_bHasAlreadyDownloadedData = true;
1916 396 : m_poFS->NotifyStopDownloadRegion(m_osURL, m_nStartOffset, m_nBlocks,
1917 : osData);
1918 396 : }
1919 :
1920 403 : ~CurrentDownload()
1921 403 : {
1922 403 : if (!m_bHasAlreadyDownloadedData)
1923 5 : m_poFS->NotifyStopDownloadRegion(m_osURL, m_nStartOffset, m_nBlocks,
1924 10 : std::string());
1925 403 : }
1926 :
1927 : CurrentDownload(const CurrentDownload &) = delete;
1928 : CurrentDownload &operator=(const CurrentDownload &) = delete;
1929 : };
1930 : } // namespace
1931 :
1932 : /************************************************************************/
1933 : /* NotifyStartDownloadRegion() */
1934 : /************************************************************************/
1935 :
1936 : /** Indicate intent at downloading a new region.
1937 : *
1938 : * If the region is already in download in another thread, then wait for its
1939 : * completion.
1940 : *
1941 : * Returns:
1942 : * - (false, empty string) if a new download is needed
1943 : * - (true, region_content) if we have been waiting for a download of the same
1944 : * region to be completed and got its result. Note that region_content will be
1945 : * empty if the download of that region failed.
1946 : */
1947 : std::pair<bool, std::string>
1948 403 : VSICurlFilesystemHandlerBase::NotifyStartDownloadRegion(
1949 : const std::string &osURL, vsi_l_offset startOffset, int nBlocks)
1950 : {
1951 806 : std::string osId(osURL);
1952 403 : osId += '_';
1953 403 : osId += std::to_string(startOffset);
1954 403 : osId += '_';
1955 403 : osId += std::to_string(nBlocks);
1956 :
1957 403 : m_oMutex.lock();
1958 403 : auto oIter = m_oMapRegionInDownload.find(osId);
1959 403 : if (oIter != m_oMapRegionInDownload.end())
1960 : {
1961 2 : auto ®ion = *(oIter->second);
1962 4 : std::unique_lock<std::mutex> oRegionLock(region.oMutex);
1963 2 : m_oMutex.unlock();
1964 2 : region.nWaiters++;
1965 4 : while (region.bDownloadInProgress)
1966 : {
1967 2 : region.oCond.wait(oRegionLock);
1968 : }
1969 2 : std::string osRet = region.osData;
1970 2 : region.nWaiters--;
1971 2 : region.oCond.notify_one();
1972 2 : return std::pair<bool, std::string>(true, osRet);
1973 : }
1974 : else
1975 : {
1976 401 : auto poRegionInDownload = std::make_unique<RegionInDownload>();
1977 401 : poRegionInDownload->bDownloadInProgress = true;
1978 401 : m_oMapRegionInDownload[osId] = std::move(poRegionInDownload);
1979 401 : m_oMutex.unlock();
1980 401 : return std::pair<bool, std::string>(false, std::string());
1981 : }
1982 : }
1983 :
1984 : /************************************************************************/
1985 : /* NotifyStopDownloadRegion() */
1986 : /************************************************************************/
1987 :
1988 401 : void VSICurlFilesystemHandlerBase::NotifyStopDownloadRegion(
1989 : const std::string &osURL, vsi_l_offset startOffset, int nBlocks,
1990 : const std::string &osData)
1991 : {
1992 802 : std::string osId(osURL);
1993 401 : osId += '_';
1994 401 : osId += std::to_string(startOffset);
1995 401 : osId += '_';
1996 401 : osId += std::to_string(nBlocks);
1997 :
1998 401 : m_oMutex.lock();
1999 401 : auto oIter = m_oMapRegionInDownload.find(osId);
2000 401 : CPLAssert(oIter != m_oMapRegionInDownload.end());
2001 401 : auto ®ion = *(oIter->second);
2002 : {
2003 802 : std::unique_lock<std::mutex> oRegionLock(region.oMutex);
2004 401 : if (region.nWaiters)
2005 : {
2006 2 : region.osData = osData;
2007 2 : region.bDownloadInProgress = false;
2008 2 : region.oCond.notify_all();
2009 :
2010 4 : while (region.nWaiters)
2011 : {
2012 2 : region.oCond.wait(oRegionLock);
2013 : }
2014 : }
2015 : }
2016 401 : m_oMapRegionInDownload.erase(oIter);
2017 401 : m_oMutex.unlock();
2018 401 : }
2019 :
2020 : /************************************************************************/
2021 : /* DownloadRegion() */
2022 : /************************************************************************/
2023 :
2024 403 : std::string VSICurlHandle::DownloadRegion(const vsi_l_offset startOffset,
2025 : const int nBlocks)
2026 : {
2027 403 : if (bInterrupted && bStopOnInterruptUntilUninstall)
2028 0 : return std::string();
2029 :
2030 403 : if (oFileProp.eExists == EXIST_NO)
2031 0 : return std::string();
2032 :
2033 : // Check if there is not a download of the same region in progress in
2034 : // another thread, and if so wait for it to be completed
2035 806 : CurrentDownload currentDownload(poFS, m_pszURL, startOffset, nBlocks);
2036 403 : if (currentDownload.HasAlreadyDownloadedData())
2037 : {
2038 2 : return currentDownload.GetAlreadyDownloadedData();
2039 : }
2040 :
2041 401 : begin:
2042 410 : CURLM *hCurlMultiHandle = poFS->GetCurlMultiHandleFor(m_pszURL);
2043 :
2044 410 : UpdateQueryString();
2045 :
2046 410 : bool bHasExpired = false;
2047 :
2048 410 : CPLStringList aosHTTPOptions(m_aosHTTPOptions);
2049 410 : std::string osURL(GetRedirectURLIfValid(bHasExpired, aosHTTPOptions));
2050 410 : bool bUsedRedirect = osURL != m_pszURL;
2051 :
2052 410 : WriteFuncStruct sWriteFuncData;
2053 410 : WriteFuncStruct sWriteFuncHeaderData;
2054 410 : CPLHTTPRetryContext oRetryContext(m_oRetryParameters);
2055 :
2056 420 : retry:
2057 420 : CURL *hCurlHandle = curl_easy_init();
2058 : struct curl_slist *headers =
2059 420 : VSICurlSetOptions(hCurlHandle, osURL.c_str(), aosHTTPOptions.List());
2060 :
2061 420 : if (!AllowAutomaticRedirection())
2062 74 : unchecked_curl_easy_setopt(hCurlHandle, CURLOPT_FOLLOWLOCATION, 0);
2063 :
2064 420 : VSICURLInitWriteFuncStruct(&sWriteFuncData, this, pfnReadCbk,
2065 : pReadCbkUserData);
2066 420 : unchecked_curl_easy_setopt(hCurlHandle, CURLOPT_WRITEDATA, &sWriteFuncData);
2067 420 : unchecked_curl_easy_setopt(hCurlHandle, CURLOPT_WRITEFUNCTION,
2068 : VSICurlHandleWriteFunc);
2069 :
2070 420 : VSICURLInitWriteFuncStruct(&sWriteFuncHeaderData, nullptr, nullptr,
2071 : nullptr);
2072 420 : unchecked_curl_easy_setopt(hCurlHandle, CURLOPT_HEADERDATA,
2073 : &sWriteFuncHeaderData);
2074 420 : unchecked_curl_easy_setopt(hCurlHandle, CURLOPT_HEADERFUNCTION,
2075 : VSICurlHandleWriteFunc);
2076 420 : sWriteFuncHeaderData.bIsHTTP = STARTS_WITH(m_pszURL, "http");
2077 420 : sWriteFuncHeaderData.nStartOffset = startOffset;
2078 420 : sWriteFuncHeaderData.nEndOffset =
2079 420 : startOffset +
2080 420 : static_cast<vsi_l_offset>(nBlocks) * VSICURLGetDownloadChunkSize() - 1;
2081 : // Some servers don't like we try to read after end-of-file (#5786).
2082 420 : if (oFileProp.bHasComputedFileSize &&
2083 326 : sWriteFuncHeaderData.nEndOffset >= oFileProp.fileSize)
2084 : {
2085 120 : sWriteFuncHeaderData.nEndOffset = oFileProp.fileSize - 1;
2086 : }
2087 :
2088 420 : char rangeStr[512] = {};
2089 420 : snprintf(rangeStr, sizeof(rangeStr), CPL_FRMT_GUIB "-" CPL_FRMT_GUIB,
2090 : startOffset, sWriteFuncHeaderData.nEndOffset);
2091 :
2092 : if constexpr (ENABLE_DEBUG)
2093 : {
2094 420 : CPLDebug(poFS->GetDebugKey(), "Downloading %s (%s)...", rangeStr,
2095 : osURL.c_str());
2096 : }
2097 :
2098 420 : std::string osHeaderRange; // leave in this scope
2099 420 : if (sWriteFuncHeaderData.bIsHTTP)
2100 : {
2101 420 : osHeaderRange = CPLSPrintf("Range: bytes=%s", rangeStr);
2102 : // So it gets included in Azure signature
2103 420 : headers = curl_slist_append(headers, osHeaderRange.c_str());
2104 420 : unchecked_curl_easy_setopt(hCurlHandle, CURLOPT_RANGE, nullptr);
2105 : }
2106 : else
2107 0 : unchecked_curl_easy_setopt(hCurlHandle, CURLOPT_RANGE, rangeStr);
2108 :
2109 420 : char szCurlErrBuf[CURL_ERROR_SIZE + 1] = {};
2110 420 : szCurlErrBuf[0] = '\0';
2111 420 : unchecked_curl_easy_setopt(hCurlHandle, CURLOPT_ERRORBUFFER, szCurlErrBuf);
2112 :
2113 420 : headers = GetCurlHeaders("GET", headers);
2114 420 : unchecked_curl_easy_setopt(hCurlHandle, CURLOPT_HTTPHEADER, headers);
2115 :
2116 420 : unchecked_curl_easy_setopt(hCurlHandle, CURLOPT_FILETIME, 1);
2117 :
2118 420 : VSICURLMultiPerform(hCurlMultiHandle, hCurlHandle, &m_bInterrupt);
2119 :
2120 420 : VSICURLResetHeaderAndWriterFunctions(hCurlHandle);
2121 :
2122 420 : curl_slist_free_all(headers);
2123 :
2124 420 : NetworkStatisticsLogger::LogGET(sWriteFuncData.nSize);
2125 :
2126 420 : if (sWriteFuncData.bInterrupted || m_bInterrupt)
2127 : {
2128 0 : bInterrupted = true;
2129 :
2130 : // Notify that the download of the current region is finished
2131 0 : currentDownload.SetData(std::string());
2132 :
2133 0 : CPLFree(sWriteFuncData.pBuffer);
2134 0 : CPLFree(sWriteFuncHeaderData.pBuffer);
2135 0 : curl_easy_cleanup(hCurlHandle);
2136 :
2137 0 : return std::string();
2138 : }
2139 :
2140 420 : long response_code = 0;
2141 420 : curl_easy_getinfo(hCurlHandle, CURLINFO_HTTP_CODE, &response_code);
2142 :
2143 420 : if (ENABLE_DEBUG && szCurlErrBuf[0] != '\0')
2144 : {
2145 3 : CPLDebug(poFS->GetDebugKey(),
2146 : "DownloadRegion(%s): response_code=%d, msg=%s", osURL.c_str(),
2147 : static_cast<int>(response_code), szCurlErrBuf);
2148 : }
2149 :
2150 420 : long mtime = 0;
2151 420 : curl_easy_getinfo(hCurlHandle, CURLINFO_FILETIME, &mtime);
2152 420 : if (mtime > 0)
2153 : {
2154 110 : oFileProp.mTime = mtime;
2155 110 : poFS->SetCachedFileProp(m_pszURL, oFileProp);
2156 : }
2157 :
2158 : if constexpr (ENABLE_DEBUG)
2159 : {
2160 420 : CPLDebug(poFS->GetDebugKey(), "Got response_code=%ld", response_code);
2161 : }
2162 :
2163 451 : if (bUsedRedirect &&
2164 31 : (response_code == 403 ||
2165 : // Below case is in particular for
2166 : // gdalinfo
2167 : // /vsicurl/https://lpdaac.earthdata.nasa.gov/lp-prod-protected/HLSS30.015/HLS.S30.T10TEK.2020273T190109.v1.5.B8A.tif
2168 : // --config GDAL_DISABLE_READDIR_ON_OPEN EMPTY_DIR --config
2169 : // GDAL_HTTP_COOKIEFILE /tmp/cookie.txt --config GDAL_HTTP_COOKIEJAR
2170 : // /tmp/cookie.txt We got the redirect URL from a HEAD request, but it
2171 : // is not valid for a GET. So retry with GET on original URL to get a
2172 : // redirect URL valid for it.
2173 29 : (response_code == 400 &&
2174 0 : osURL.find(".cloudfront.net") != std::string::npos)))
2175 : {
2176 2 : CPLDebug(poFS->GetDebugKey(),
2177 : "Got an error with redirect URL. Retrying with original one");
2178 2 : oFileProp.bS3LikeRedirect = false;
2179 2 : poFS->SetCachedFileProp(m_pszURL, oFileProp);
2180 2 : bUsedRedirect = false;
2181 2 : osURL = m_pszURL;
2182 2 : CPLFree(sWriteFuncData.pBuffer);
2183 2 : CPLFree(sWriteFuncHeaderData.pBuffer);
2184 2 : curl_easy_cleanup(hCurlHandle);
2185 2 : goto retry;
2186 : }
2187 :
2188 418 : if (response_code == 401 && oRetryContext.CanRetry())
2189 : {
2190 0 : CPLDebug(poFS->GetDebugKey(), "Unauthorized, trying to authenticate");
2191 0 : CPLFree(sWriteFuncData.pBuffer);
2192 0 : CPLFree(sWriteFuncHeaderData.pBuffer);
2193 0 : curl_easy_cleanup(hCurlHandle);
2194 0 : if (Authenticate(m_osFilename.c_str()))
2195 0 : goto retry;
2196 0 : return std::string();
2197 : }
2198 :
2199 418 : UpdateRedirectInfo(hCurlHandle, sWriteFuncHeaderData);
2200 :
2201 418 : if ((response_code != 200 && response_code != 206 && response_code != 225 &&
2202 22 : response_code != 226 && response_code != 426) ||
2203 396 : sWriteFuncHeaderData.bError)
2204 : {
2205 31 : if (sWriteFuncData.pBuffer != nullptr &&
2206 9 : CanRestartOnError(
2207 9 : reinterpret_cast<const char *>(sWriteFuncData.pBuffer),
2208 9 : reinterpret_cast<const char *>(sWriteFuncHeaderData.pBuffer),
2209 9 : true))
2210 : {
2211 9 : CPLFree(sWriteFuncData.pBuffer);
2212 9 : CPLFree(sWriteFuncHeaderData.pBuffer);
2213 9 : curl_easy_cleanup(hCurlHandle);
2214 9 : goto begin;
2215 : }
2216 :
2217 : // Look if we should attempt a retry
2218 13 : if (oRetryContext.CanRetry(static_cast<int>(response_code),
2219 13 : sWriteFuncHeaderData.pBuffer, szCurlErrBuf))
2220 : {
2221 8 : CPLError(CE_Warning, CPLE_AppDefined,
2222 : "HTTP error code: %d - %s. "
2223 : "Retrying again in %.1f secs",
2224 : static_cast<int>(response_code), m_pszURL,
2225 : oRetryContext.GetCurrentDelay());
2226 8 : CPLSleep(oRetryContext.GetCurrentDelay());
2227 8 : CPLFree(sWriteFuncData.pBuffer);
2228 8 : CPLFree(sWriteFuncHeaderData.pBuffer);
2229 8 : curl_easy_cleanup(hCurlHandle);
2230 8 : goto retry;
2231 : }
2232 :
2233 5 : if (response_code >= 400 && szCurlErrBuf[0] != '\0')
2234 : {
2235 0 : if (strcmp(szCurlErrBuf, "Couldn't use REST") == 0)
2236 0 : CPLError(
2237 : CE_Failure, CPLE_AppDefined,
2238 : "%d: %s, Range downloading not supported by this server!",
2239 : static_cast<int>(response_code), szCurlErrBuf);
2240 : else
2241 0 : CPLError(CE_Failure, CPLE_AppDefined, "%d: %s",
2242 : static_cast<int>(response_code), szCurlErrBuf);
2243 : }
2244 5 : else if (response_code == 416) /* Range Not Satisfiable */
2245 : {
2246 0 : if (sWriteFuncData.pBuffer)
2247 : {
2248 0 : CPLError(
2249 : CE_Failure, CPLE_AppDefined,
2250 : "%d: Range downloading not supported by this server: %s",
2251 : static_cast<int>(response_code), sWriteFuncData.pBuffer);
2252 : }
2253 : else
2254 : {
2255 0 : CPLError(CE_Failure, CPLE_AppDefined,
2256 : "%d: Range downloading not supported by this server",
2257 : static_cast<int>(response_code));
2258 : }
2259 : }
2260 5 : if (!oFileProp.bHasComputedFileSize && startOffset == 0)
2261 : {
2262 1 : oFileProp.bHasComputedFileSize = true;
2263 1 : oFileProp.fileSize = 0;
2264 1 : oFileProp.eExists = EXIST_NO;
2265 1 : poFS->SetCachedFileProp(m_pszURL, oFileProp);
2266 : }
2267 5 : CPLFree(sWriteFuncData.pBuffer);
2268 5 : CPLFree(sWriteFuncHeaderData.pBuffer);
2269 5 : curl_easy_cleanup(hCurlHandle);
2270 5 : return std::string();
2271 : }
2272 :
2273 396 : if (!oFileProp.bHasComputedFileSize && sWriteFuncHeaderData.pBuffer)
2274 : {
2275 : // Try to retrieve the filesize from the HTTP headers
2276 : // if in the form: "Content-Range: bytes x-y/filesize".
2277 : char *pszContentRange =
2278 84 : strstr(sWriteFuncHeaderData.pBuffer, "Content-Range: bytes ");
2279 84 : if (pszContentRange == nullptr)
2280 : pszContentRange =
2281 83 : strstr(sWriteFuncHeaderData.pBuffer, "content-range: bytes ");
2282 84 : if (pszContentRange)
2283 : {
2284 1 : char *pszEOL = strchr(pszContentRange, '\n');
2285 1 : if (pszEOL)
2286 : {
2287 1 : *pszEOL = 0;
2288 1 : pszEOL = strchr(pszContentRange, '\r');
2289 1 : if (pszEOL)
2290 1 : *pszEOL = 0;
2291 1 : char *pszSlash = strchr(pszContentRange, '/');
2292 1 : if (pszSlash)
2293 : {
2294 1 : pszSlash++;
2295 1 : oFileProp.fileSize = CPLScanUIntBig(
2296 1 : pszSlash, static_cast<int>(strlen(pszSlash)));
2297 : }
2298 : }
2299 : }
2300 83 : else if (STARTS_WITH(m_pszURL, "ftp"))
2301 : {
2302 : // Parse 213 answer for FTP protocol.
2303 0 : char *pszSize = strstr(sWriteFuncHeaderData.pBuffer, "213 ");
2304 0 : if (pszSize)
2305 : {
2306 0 : pszSize += 4;
2307 0 : char *pszEOL = strchr(pszSize, '\n');
2308 0 : if (pszEOL)
2309 : {
2310 0 : *pszEOL = 0;
2311 0 : pszEOL = strchr(pszSize, '\r');
2312 0 : if (pszEOL)
2313 0 : *pszEOL = 0;
2314 :
2315 0 : oFileProp.fileSize = CPLScanUIntBig(
2316 0 : pszSize, static_cast<int>(strlen(pszSize)));
2317 : }
2318 : }
2319 : }
2320 :
2321 84 : if (oFileProp.fileSize != 0)
2322 : {
2323 1 : oFileProp.eExists = EXIST_YES;
2324 :
2325 : if constexpr (ENABLE_DEBUG)
2326 : {
2327 1 : CPLDebug(poFS->GetDebugKey(),
2328 : "GetFileSize(%s)=" CPL_FRMT_GUIB " response_code=%d",
2329 : m_pszURL, oFileProp.fileSize,
2330 : static_cast<int>(response_code));
2331 : }
2332 :
2333 1 : oFileProp.bHasComputedFileSize = true;
2334 1 : poFS->SetCachedFileProp(m_pszURL, oFileProp);
2335 : }
2336 : }
2337 :
2338 396 : DownloadRegionPostProcess(startOffset, nBlocks, sWriteFuncData.pBuffer,
2339 : sWriteFuncData.nSize);
2340 :
2341 792 : std::string osRet;
2342 396 : osRet.assign(sWriteFuncData.pBuffer, sWriteFuncData.nSize);
2343 :
2344 : // Notify that the download of the current region is finished
2345 396 : currentDownload.SetData(osRet);
2346 :
2347 396 : CPLFree(sWriteFuncData.pBuffer);
2348 396 : CPLFree(sWriteFuncHeaderData.pBuffer);
2349 396 : curl_easy_cleanup(hCurlHandle);
2350 :
2351 396 : return osRet;
2352 : }
2353 :
2354 : /************************************************************************/
2355 : /* UpdateRedirectInfo() */
2356 : /************************************************************************/
2357 :
2358 482 : void VSICurlHandle::UpdateRedirectInfo(
2359 : CURL *hCurlHandle, const WriteFuncStruct &sWriteFuncHeaderData)
2360 : {
2361 964 : std::string osEffectiveURL;
2362 : {
2363 482 : char *pszEffectiveURL = nullptr;
2364 482 : curl_easy_getinfo(hCurlHandle, CURLINFO_EFFECTIVE_URL,
2365 : &pszEffectiveURL);
2366 482 : if (pszEffectiveURL)
2367 482 : osEffectiveURL = pszEffectiveURL;
2368 : }
2369 :
2370 950 : if (!oFileProp.bS3LikeRedirect && !osEffectiveURL.empty() &&
2371 468 : strstr(osEffectiveURL.c_str(), m_pszURL) == nullptr)
2372 : {
2373 108 : CPLDebug(poFS->GetDebugKey(), "Effective URL: %s",
2374 : osEffectiveURL.c_str());
2375 :
2376 108 : long response_code = 0;
2377 108 : curl_easy_getinfo(hCurlHandle, CURLINFO_HTTP_CODE, &response_code);
2378 108 : if (response_code >= 200 && response_code < 300 &&
2379 216 : sWriteFuncHeaderData.nTimestampDate > 0 &&
2380 108 : VSICurlIsS3LikeSignedURL(osEffectiveURL.c_str()) &&
2381 218 : !VSICurlIsS3LikeSignedURL(m_pszURL) &&
2382 2 : CPLTestBool(
2383 : CPLGetConfigOption("CPL_VSIL_CURL_USE_S3_REDIRECT", "TRUE")))
2384 : {
2385 : GIntBig nExpireTimestamp =
2386 2 : VSICurlGetExpiresFromS3LikeSignedURL(osEffectiveURL.c_str());
2387 2 : if (nExpireTimestamp > sWriteFuncHeaderData.nTimestampDate + 10)
2388 : {
2389 2 : const int nValidity = static_cast<int>(
2390 2 : nExpireTimestamp - sWriteFuncHeaderData.nTimestampDate);
2391 2 : CPLDebug(poFS->GetDebugKey(),
2392 : "Will use redirect URL for the next %d seconds",
2393 : nValidity);
2394 : // As our local clock might not be in sync with server clock,
2395 : // figure out the expiration timestamp in local time.
2396 2 : oFileProp.bS3LikeRedirect = true;
2397 2 : oFileProp.nExpireTimestampLocal = time(nullptr) + nValidity;
2398 2 : oFileProp.osRedirectURL = std::move(osEffectiveURL);
2399 2 : poFS->SetCachedFileProp(m_pszURL, oFileProp);
2400 : }
2401 : }
2402 : }
2403 482 : }
2404 :
2405 : /************************************************************************/
2406 : /* DownloadRegionPostProcess() */
2407 : /************************************************************************/
2408 :
2409 398 : void VSICurlHandle::DownloadRegionPostProcess(const vsi_l_offset startOffset,
2410 : const int nBlocks,
2411 : const char *pBuffer, size_t nSize)
2412 : {
2413 398 : const int knDOWNLOAD_CHUNK_SIZE = VSICURLGetDownloadChunkSize();
2414 398 : lastDownloadedOffset = startOffset + static_cast<vsi_l_offset>(nBlocks) *
2415 398 : knDOWNLOAD_CHUNK_SIZE;
2416 :
2417 398 : if (nSize > static_cast<size_t>(nBlocks) * knDOWNLOAD_CHUNK_SIZE)
2418 : {
2419 : if constexpr (ENABLE_DEBUG)
2420 : {
2421 1 : CPLDebug(
2422 1 : poFS->GetDebugKey(),
2423 : "Got more data than expected : %u instead of %u",
2424 : static_cast<unsigned int>(nSize),
2425 1 : static_cast<unsigned int>(nBlocks * knDOWNLOAD_CHUNK_SIZE));
2426 : }
2427 : }
2428 :
2429 398 : vsi_l_offset l_startOffset = startOffset;
2430 8289 : while (nSize > 0)
2431 : {
2432 : #if DEBUG_VERBOSE
2433 : if constexpr (ENABLE_DEBUG)
2434 : {
2435 : CPLDebug(poFS->GetDebugKey(), "Add region %u - %u",
2436 : static_cast<unsigned int>(startOffset),
2437 : static_cast<unsigned int>(std::min(
2438 : static_cast<size_t>(knDOWNLOAD_CHUNK_SIZE), nSize)));
2439 : }
2440 : #endif
2441 : const size_t nChunkSize =
2442 7891 : std::min(static_cast<size_t>(knDOWNLOAD_CHUNK_SIZE), nSize);
2443 7891 : poFS->AddRegion(m_pszURL, l_startOffset, nChunkSize, pBuffer);
2444 7891 : l_startOffset += nChunkSize;
2445 7891 : pBuffer += nChunkSize;
2446 7891 : nSize -= nChunkSize;
2447 : }
2448 398 : }
2449 :
2450 : /************************************************************************/
2451 : /* Read() */
2452 : /************************************************************************/
2453 :
2454 146585 : size_t VSICurlHandle::Read(void *const pBufferIn, size_t const nBytes)
2455 : {
2456 293170 : NetworkStatisticsFileSystem oContextFS(poFS->GetFSPrefix().c_str());
2457 293170 : NetworkStatisticsFile oContextFile(m_osFilename.c_str());
2458 293170 : NetworkStatisticsAction oContextAction("Read");
2459 :
2460 146585 : size_t nBufferRequestSize = nBytes;
2461 146585 : if (nBufferRequestSize == 0)
2462 2 : return 0;
2463 :
2464 146583 : void *pBuffer = pBufferIn;
2465 :
2466 : #if DEBUG_VERBOSE
2467 : CPLDebug(poFS->GetDebugKey(), "offset=%d, size=%d",
2468 : static_cast<int>(curOffset), static_cast<int>(nBufferRequestSize));
2469 : #endif
2470 :
2471 146583 : vsi_l_offset iterOffset = curOffset;
2472 146583 : const int knMAX_REGIONS = GetMaxRegions();
2473 146583 : const int knDOWNLOAD_CHUNK_SIZE = VSICURLGetDownloadChunkSize();
2474 294899 : while (nBufferRequestSize)
2475 : {
2476 : // Don't try to read after end of file.
2477 148464 : poFS->GetCachedFileProp(m_pszURL, oFileProp);
2478 148464 : if (oFileProp.bHasComputedFileSize && iterOffset >= oFileProp.fileSize)
2479 : {
2480 10 : if (iterOffset == curOffset)
2481 : {
2482 10 : CPLDebug(poFS->GetDebugKey(),
2483 : "Request at offset " CPL_FRMT_GUIB
2484 : ", after end of file",
2485 : iterOffset);
2486 : }
2487 142 : break;
2488 : }
2489 :
2490 148454 : const vsi_l_offset nOffsetToDownload =
2491 148454 : (iterOffset / knDOWNLOAD_CHUNK_SIZE) * knDOWNLOAD_CHUNK_SIZE;
2492 148454 : std::string osRegion;
2493 : std::shared_ptr<std::string> psRegion =
2494 148454 : poFS->GetRegion(m_pszURL, nOffsetToDownload);
2495 148454 : if (psRegion != nullptr)
2496 : {
2497 148048 : osRegion = *psRegion;
2498 : }
2499 : else
2500 : {
2501 406 : if (nOffsetToDownload == lastDownloadedOffset)
2502 : {
2503 : // In case of consecutive reads (of small size), we use a
2504 : // heuristic that we will read the file sequentially, so
2505 : // we double the requested size to decrease the number of
2506 : // client/server roundtrips.
2507 50 : constexpr int MAX_CHUNK_SIZE_INCREASE_FACTOR = 128;
2508 50 : if (nBlocksToDownload < MAX_CHUNK_SIZE_INCREASE_FACTOR)
2509 42 : nBlocksToDownload *= 2;
2510 : }
2511 : else
2512 : {
2513 : // Random reads. Cancel the above heuristics.
2514 356 : nBlocksToDownload = 1;
2515 : }
2516 :
2517 : // Ensure that we will request at least the number of blocks
2518 : // to satisfy the remaining buffer size to read.
2519 406 : const vsi_l_offset nEndOffsetToDownload =
2520 406 : ((iterOffset + nBufferRequestSize + knDOWNLOAD_CHUNK_SIZE - 1) /
2521 406 : knDOWNLOAD_CHUNK_SIZE) *
2522 406 : knDOWNLOAD_CHUNK_SIZE;
2523 406 : const int nMinBlocksToDownload =
2524 406 : static_cast<int>((nEndOffsetToDownload - nOffsetToDownload) /
2525 406 : knDOWNLOAD_CHUNK_SIZE);
2526 406 : if (nBlocksToDownload < nMinBlocksToDownload)
2527 91 : nBlocksToDownload = nMinBlocksToDownload;
2528 :
2529 : // Avoid reading already cached data.
2530 : // Note: this might get evicted if concurrent reads are done, but
2531 : // this should not cause bugs. Just missed optimization.
2532 18582 : for (int i = 1; i < nBlocksToDownload; i++)
2533 : {
2534 18234 : if (poFS->GetRegion(m_pszURL, nOffsetToDownload +
2535 18234 : static_cast<vsi_l_offset>(i) *
2536 18234 : knDOWNLOAD_CHUNK_SIZE) !=
2537 : nullptr)
2538 : {
2539 58 : nBlocksToDownload = i;
2540 58 : break;
2541 : }
2542 : }
2543 :
2544 : // We can't download more than knMAX_REGIONS chunks at a time,
2545 : // otherwise the cache will not be big enough to store them and
2546 : // copy their content to the target buffer.
2547 406 : if (nBlocksToDownload > knMAX_REGIONS)
2548 5 : nBlocksToDownload = knMAX_REGIONS;
2549 :
2550 406 : osRegion = DownloadRegion(nOffsetToDownload, nBlocksToDownload);
2551 406 : if (osRegion.empty())
2552 : {
2553 6 : if (!bInterrupted)
2554 6 : bError = true;
2555 6 : return 0;
2556 : }
2557 : }
2558 :
2559 148448 : const vsi_l_offset nRegionOffset = iterOffset - nOffsetToDownload;
2560 148448 : if (osRegion.size() < nRegionOffset)
2561 : {
2562 0 : if (iterOffset == curOffset)
2563 : {
2564 0 : CPLDebug(poFS->GetDebugKey(),
2565 : "Request at offset " CPL_FRMT_GUIB
2566 : ", after end of file",
2567 : iterOffset);
2568 : }
2569 0 : break;
2570 : }
2571 :
2572 : const int nToCopy = static_cast<int>(
2573 296896 : std::min(static_cast<vsi_l_offset>(nBufferRequestSize),
2574 148448 : osRegion.size() - nRegionOffset));
2575 148448 : memcpy(pBuffer, osRegion.data() + nRegionOffset, nToCopy);
2576 148448 : pBuffer = static_cast<char *>(pBuffer) + nToCopy;
2577 148448 : iterOffset += nToCopy;
2578 148448 : nBufferRequestSize -= nToCopy;
2579 148448 : if (osRegion.size() < static_cast<size_t>(knDOWNLOAD_CHUNK_SIZE) &&
2580 : nBufferRequestSize != 0)
2581 : {
2582 132 : break;
2583 : }
2584 : }
2585 :
2586 146577 : const size_t ret = static_cast<size_t>(iterOffset - curOffset);
2587 146577 : if (ret != nBytes)
2588 142 : bEOF = true;
2589 :
2590 146577 : curOffset = iterOffset;
2591 :
2592 146577 : return ret;
2593 : }
2594 :
2595 : /************************************************************************/
2596 : /* ReadMultiRange() */
2597 : /************************************************************************/
2598 :
2599 11 : int VSICurlHandle::ReadMultiRange(int const nRanges, void **const ppData,
2600 : const vsi_l_offset *const panOffsets,
2601 : const size_t *const panSizes)
2602 : {
2603 11 : if (bInterrupted && bStopOnInterruptUntilUninstall)
2604 0 : return FALSE;
2605 :
2606 11 : poFS->GetCachedFileProp(m_pszURL, oFileProp);
2607 11 : if (oFileProp.eExists == EXIST_NO)
2608 0 : return -1;
2609 :
2610 22 : NetworkStatisticsFileSystem oContextFS(poFS->GetFSPrefix().c_str());
2611 22 : NetworkStatisticsFile oContextFile(m_osFilename.c_str());
2612 22 : NetworkStatisticsAction oContextAction("ReadMultiRange");
2613 :
2614 : const char *pszMultiRangeStrategy =
2615 11 : CPLGetConfigOption("GDAL_HTTP_MULTIRANGE", "");
2616 11 : if (EQUAL(pszMultiRangeStrategy, "SINGLE_GET"))
2617 : {
2618 : // Just in case someone needs it, but the interest of this mode is
2619 : // rather dubious now. We could probably remove it
2620 0 : return ReadMultiRangeSingleGet(nRanges, ppData, panOffsets, panSizes);
2621 : }
2622 11 : else if (nRanges == 1 || EQUAL(pszMultiRangeStrategy, "SERIAL"))
2623 : {
2624 9 : return VSIVirtualHandle::ReadMultiRange(nRanges, ppData, panOffsets,
2625 9 : panSizes);
2626 : }
2627 :
2628 2 : UpdateQueryString();
2629 :
2630 2 : bool bHasExpired = false;
2631 :
2632 4 : CPLStringList aosHTTPOptions(m_aosHTTPOptions);
2633 4 : std::string osURL(GetRedirectURLIfValid(bHasExpired, aosHTTPOptions));
2634 2 : if (bHasExpired)
2635 : {
2636 0 : return VSIVirtualHandle::ReadMultiRange(nRanges, ppData, panOffsets,
2637 0 : panSizes);
2638 : }
2639 :
2640 2 : CURLM *hMultiHandle = poFS->GetCurlMultiHandleFor(osURL);
2641 : #ifdef CURLPIPE_MULTIPLEX
2642 : // Enable HTTP/2 multiplexing (ignored if an older version of HTTP is
2643 : // used)
2644 : // Not that this does not enable HTTP/1.1 pipeling, which is not
2645 : // recommended for example by Google Cloud Storage.
2646 : // For HTTP/1.1, parallel connections work better since you can get
2647 : // results out of order.
2648 2 : if (CPLTestBool(CPLGetConfigOption("GDAL_HTTP_MULTIPLEX", "YES")))
2649 : {
2650 2 : curl_multi_setopt(hMultiHandle, CURLMOPT_PIPELINING,
2651 : CURLPIPE_MULTIPLEX);
2652 : }
2653 : #endif
2654 :
2655 : struct CurlErrBuffer
2656 : {
2657 : std::array<char, CURL_ERROR_SIZE + 1> szCurlErrBuf;
2658 : };
2659 :
2660 : // Sort ranges by file offset so the merge loop below can coalesce
2661 : // adjacent ranges regardless of the order the caller passed them.
2662 : // The ppData buffer pointers travel with their offsets, so the
2663 : // distribute logic fills the correct caller buffers after reading.
2664 4 : std::vector<int> anSortOrder(nRanges);
2665 2 : std::iota(anSortOrder.begin(), anSortOrder.end(), 0);
2666 2 : std::sort(anSortOrder.begin(), anSortOrder.end(), [panOffsets](int a, int b)
2667 12 : { return panOffsets[a] < panOffsets[b]; });
2668 :
2669 4 : std::vector<void *> apSortedData(nRanges);
2670 4 : std::vector<vsi_l_offset> anSortedOffsets(nRanges);
2671 4 : std::vector<size_t> anSortedSizes(nRanges);
2672 10 : for (int i = 0; i < nRanges; ++i)
2673 : {
2674 8 : apSortedData[i] = ppData[anSortOrder[i]];
2675 8 : anSortedOffsets[i] = panOffsets[anSortOrder[i]];
2676 8 : anSortedSizes[i] = panSizes[anSortOrder[i]];
2677 : }
2678 :
2679 2 : const bool bMergeConsecutiveRanges = CPLTestBool(
2680 : CPLGetConfigOption("GDAL_HTTP_MERGE_CONSECUTIVE_RANGES", "TRUE"));
2681 :
2682 : // Build list of merged requests upfront, each with its own retry context
2683 : struct MergedRequest
2684 : {
2685 : int iFirstRange;
2686 : int iLastRange;
2687 : vsi_l_offset nStartOffset;
2688 : size_t nSize;
2689 : CPLHTTPRetryContext retryContext;
2690 : bool bToRetry = true; // true initially to trigger first attempt
2691 :
2692 8 : MergedRequest(int first, int last, vsi_l_offset start, size_t size,
2693 : const CPLHTTPRetryParameters ¶ms)
2694 8 : : iFirstRange(first), iLastRange(last), nStartOffset(start),
2695 8 : nSize(size), retryContext(params)
2696 : {
2697 8 : }
2698 : };
2699 :
2700 4 : std::vector<MergedRequest> asMergedRequests;
2701 10 : for (int i = 0; i < nRanges;)
2702 : {
2703 8 : size_t nSize = 0;
2704 8 : int iNext = i;
2705 : // Identify consecutive ranges
2706 14 : while (bMergeConsecutiveRanges && iNext + 1 < nRanges &&
2707 12 : anSortedOffsets[iNext] + anSortedSizes[iNext] ==
2708 6 : anSortedOffsets[iNext + 1])
2709 : {
2710 0 : nSize += anSortedSizes[iNext];
2711 0 : iNext++;
2712 : }
2713 8 : nSize += anSortedSizes[iNext];
2714 :
2715 8 : if (nSize == 0)
2716 : {
2717 0 : i = iNext + 1;
2718 0 : continue;
2719 : }
2720 :
2721 8 : asMergedRequests.emplace_back(i, iNext, anSortedOffsets[i], nSize,
2722 8 : m_oRetryParameters);
2723 8 : i = iNext + 1;
2724 : }
2725 :
2726 2 : if (asMergedRequests.empty())
2727 0 : return 0;
2728 :
2729 2 : int nRet = 0;
2730 2 : size_t nTotalDownloaded = 0;
2731 :
2732 : // Retry loop: re-issue only failed requests that are retryable
2733 : while (true)
2734 : {
2735 3 : const size_t nRequests = asMergedRequests.size();
2736 3 : std::vector<CURL *> aHandles(nRequests, nullptr);
2737 3 : std::vector<WriteFuncStruct> asWriteFuncData(nRequests);
2738 3 : std::vector<WriteFuncStruct> asWriteFuncHeaderData(nRequests);
2739 3 : std::vector<char *> apszRanges(nRequests, nullptr);
2740 3 : std::vector<struct curl_slist *> aHeaders(nRequests, nullptr);
2741 3 : std::vector<CurlErrBuffer> asCurlErrors(nRequests);
2742 :
2743 3 : bool bAnyHandle = false;
2744 15 : for (size_t iReq = 0; iReq < nRequests; iReq++)
2745 : {
2746 12 : if (!asMergedRequests[iReq].bToRetry)
2747 3 : continue;
2748 9 : asMergedRequests[iReq].bToRetry = false;
2749 :
2750 9 : CURL *hCurlHandle = curl_easy_init();
2751 9 : aHandles[iReq] = hCurlHandle;
2752 9 : bAnyHandle = true;
2753 :
2754 9 : struct curl_slist *headers = VSICurlSetOptions(
2755 9 : hCurlHandle, osURL.c_str(), aosHTTPOptions.List());
2756 :
2757 9 : VSICURLInitWriteFuncStruct(&asWriteFuncData[iReq], this, pfnReadCbk,
2758 : pReadCbkUserData);
2759 9 : unchecked_curl_easy_setopt(hCurlHandle, CURLOPT_WRITEDATA,
2760 : &asWriteFuncData[iReq]);
2761 9 : unchecked_curl_easy_setopt(hCurlHandle, CURLOPT_WRITEFUNCTION,
2762 : VSICurlHandleWriteFunc);
2763 :
2764 9 : VSICURLInitWriteFuncStruct(&asWriteFuncHeaderData[iReq], nullptr,
2765 : nullptr, nullptr);
2766 9 : unchecked_curl_easy_setopt(hCurlHandle, CURLOPT_HEADERDATA,
2767 : &asWriteFuncHeaderData[iReq]);
2768 9 : unchecked_curl_easy_setopt(hCurlHandle, CURLOPT_HEADERFUNCTION,
2769 : VSICurlHandleWriteFunc);
2770 9 : asWriteFuncHeaderData[iReq].bIsHTTP = STARTS_WITH(m_pszURL, "http");
2771 18 : asWriteFuncHeaderData[iReq].nStartOffset =
2772 9 : asMergedRequests[iReq].nStartOffset;
2773 18 : asWriteFuncHeaderData[iReq].nEndOffset =
2774 9 : asMergedRequests[iReq].nStartOffset +
2775 9 : asMergedRequests[iReq].nSize - 1;
2776 :
2777 9 : char rangeStr[512] = {};
2778 18 : snprintf(rangeStr, sizeof(rangeStr),
2779 : CPL_FRMT_GUIB "-" CPL_FRMT_GUIB,
2780 9 : asWriteFuncHeaderData[iReq].nStartOffset,
2781 9 : asWriteFuncHeaderData[iReq].nEndOffset);
2782 :
2783 : if constexpr (ENABLE_DEBUG)
2784 : {
2785 9 : CPLDebug(poFS->GetDebugKey(), "Downloading %s (%s)...",
2786 : rangeStr, osURL.c_str());
2787 : }
2788 :
2789 9 : if (asWriteFuncHeaderData[iReq].bIsHTTP)
2790 : {
2791 : // So it gets included in Azure signature
2792 : char *pszRange =
2793 9 : CPLStrdup(CPLSPrintf("Range: bytes=%s", rangeStr));
2794 9 : apszRanges[iReq] = pszRange;
2795 9 : headers = curl_slist_append(headers, pszRange);
2796 9 : unchecked_curl_easy_setopt(hCurlHandle, CURLOPT_RANGE, nullptr);
2797 : }
2798 : else
2799 : {
2800 0 : unchecked_curl_easy_setopt(hCurlHandle, CURLOPT_RANGE,
2801 : rangeStr);
2802 : }
2803 :
2804 9 : asCurlErrors[iReq].szCurlErrBuf[0] = '\0';
2805 9 : unchecked_curl_easy_setopt(hCurlHandle, CURLOPT_ERRORBUFFER,
2806 : &asCurlErrors[iReq].szCurlErrBuf[0]);
2807 :
2808 9 : headers = GetCurlHeaders("GET", headers);
2809 9 : unchecked_curl_easy_setopt(hCurlHandle, CURLOPT_HTTPHEADER,
2810 : headers);
2811 9 : aHeaders[iReq] = headers;
2812 9 : curl_multi_add_handle(hMultiHandle, hCurlHandle);
2813 : }
2814 :
2815 3 : if (bAnyHandle)
2816 : {
2817 3 : VSICURLMultiPerform(hMultiHandle);
2818 : }
2819 :
2820 : // Process results
2821 3 : bool bRetry = false;
2822 3 : double dfMaxDelay = 0.0;
2823 15 : for (size_t iReq = 0; iReq < nRequests; iReq++)
2824 : {
2825 12 : if (!aHandles[iReq])
2826 3 : continue;
2827 :
2828 9 : long response_code = 0;
2829 9 : curl_easy_getinfo(aHandles[iReq], CURLINFO_HTTP_CODE,
2830 : &response_code);
2831 :
2832 9 : if (ENABLE_DEBUG && asCurlErrors[iReq].szCurlErrBuf[0] != '\0')
2833 : {
2834 0 : char rangeStr[512] = {};
2835 0 : snprintf(rangeStr, sizeof(rangeStr),
2836 : CPL_FRMT_GUIB "-" CPL_FRMT_GUIB,
2837 0 : asWriteFuncHeaderData[iReq].nStartOffset,
2838 0 : asWriteFuncHeaderData[iReq].nEndOffset);
2839 :
2840 0 : const char *pszErrorMsg = &asCurlErrors[iReq].szCurlErrBuf[0];
2841 0 : CPLDebug(poFS->GetDebugKey(),
2842 : "ReadMultiRange(%s), %s: response_code=%d, msg=%s",
2843 : osURL.c_str(), rangeStr,
2844 : static_cast<int>(response_code), pszErrorMsg);
2845 : }
2846 :
2847 17 : if ((response_code != 206 && response_code != 225) ||
2848 8 : asWriteFuncHeaderData[iReq].nEndOffset + 1 !=
2849 8 : asWriteFuncHeaderData[iReq].nStartOffset +
2850 8 : asWriteFuncData[iReq].nSize)
2851 : {
2852 1 : char rangeStr[512] = {};
2853 2 : snprintf(rangeStr, sizeof(rangeStr),
2854 : CPL_FRMT_GUIB "-" CPL_FRMT_GUIB,
2855 1 : asWriteFuncHeaderData[iReq].nStartOffset,
2856 1 : asWriteFuncHeaderData[iReq].nEndOffset);
2857 :
2858 : // Look if we should attempt a retry
2859 2 : if (asMergedRequests[iReq].retryContext.CanRetry(
2860 : static_cast<int>(response_code),
2861 1 : asWriteFuncData[iReq].pBuffer,
2862 1 : &asCurlErrors[iReq].szCurlErrBuf[0]))
2863 : {
2864 1 : CPLError(
2865 : CE_Warning, CPLE_AppDefined,
2866 : "HTTP error code for %s range %s: %d. "
2867 : "Retrying again in %.1f secs",
2868 : osURL.c_str(), rangeStr,
2869 : static_cast<int>(response_code),
2870 1 : asMergedRequests[iReq].retryContext.GetCurrentDelay());
2871 1 : dfMaxDelay = std::max(
2872 : dfMaxDelay,
2873 1 : asMergedRequests[iReq].retryContext.GetCurrentDelay());
2874 1 : asMergedRequests[iReq].bToRetry = true;
2875 1 : bRetry = true;
2876 : }
2877 : else
2878 : {
2879 0 : CPLError(CE_Failure, CPLE_AppDefined,
2880 : "Request for %s failed with response_code=%ld",
2881 : rangeStr, response_code);
2882 0 : nRet = -1;
2883 : }
2884 : }
2885 8 : else if (nRet == 0)
2886 : {
2887 8 : size_t nOffset = 0;
2888 8 : size_t nRemainingSize = asWriteFuncData[iReq].nSize;
2889 8 : nTotalDownloaded += nRemainingSize;
2890 8 : for (int iRange = asMergedRequests[iReq].iFirstRange;
2891 16 : iRange <= asMergedRequests[iReq].iLastRange; iRange++)
2892 : {
2893 8 : if (nRemainingSize < anSortedSizes[iRange])
2894 : {
2895 0 : nRet = -1;
2896 0 : break;
2897 : }
2898 :
2899 8 : if (anSortedSizes[iRange] > 0)
2900 : {
2901 8 : memcpy(apSortedData[iRange],
2902 8 : asWriteFuncData[iReq].pBuffer + nOffset,
2903 8 : anSortedSizes[iRange]);
2904 : }
2905 8 : nOffset += anSortedSizes[iRange];
2906 8 : nRemainingSize -= anSortedSizes[iRange];
2907 : }
2908 : }
2909 :
2910 9 : curl_multi_remove_handle(hMultiHandle, aHandles[iReq]);
2911 9 : VSICURLResetHeaderAndWriterFunctions(aHandles[iReq]);
2912 9 : curl_easy_cleanup(aHandles[iReq]);
2913 9 : CPLFree(apszRanges[iReq]);
2914 9 : CPLFree(asWriteFuncData[iReq].pBuffer);
2915 9 : CPLFree(asWriteFuncHeaderData[iReq].pBuffer);
2916 9 : if (aHeaders[iReq])
2917 9 : curl_slist_free_all(aHeaders[iReq]);
2918 : }
2919 :
2920 3 : if (!bRetry || nRet != 0)
2921 : break;
2922 1 : CPLSleep(dfMaxDelay);
2923 1 : }
2924 :
2925 2 : NetworkStatisticsLogger::LogGET(nTotalDownloaded);
2926 :
2927 : if constexpr (ENABLE_DEBUG)
2928 : {
2929 2 : CPLDebug(poFS->GetDebugKey(), "Download completed");
2930 : }
2931 :
2932 2 : return nRet;
2933 : }
2934 :
2935 : /************************************************************************/
2936 : /* ReadMultiRangeSingleGet() */
2937 : /************************************************************************/
2938 :
2939 : // TODO: the interest of this mode is rather dubious now. We could probably
2940 : // remove it
2941 0 : int VSICurlHandle::ReadMultiRangeSingleGet(int const nRanges,
2942 : void **const ppData,
2943 : const vsi_l_offset *const panOffsets,
2944 : const size_t *const panSizes)
2945 : {
2946 0 : std::string osRanges;
2947 0 : std::string osFirstRange;
2948 0 : std::string osLastRange;
2949 0 : int nMergedRanges = 0;
2950 0 : vsi_l_offset nTotalReqSize = 0;
2951 0 : for (int i = 0; i < nRanges; i++)
2952 : {
2953 0 : std::string osCurRange;
2954 0 : if (i != 0)
2955 0 : osRanges.append(",");
2956 0 : osCurRange = CPLSPrintf(CPL_FRMT_GUIB "-", panOffsets[i]);
2957 0 : while (i + 1 < nRanges &&
2958 0 : panOffsets[i] + panSizes[i] == panOffsets[i + 1])
2959 : {
2960 0 : nTotalReqSize += panSizes[i];
2961 0 : i++;
2962 : }
2963 0 : nTotalReqSize += panSizes[i];
2964 : osCurRange.append(
2965 0 : CPLSPrintf(CPL_FRMT_GUIB, panOffsets[i] + panSizes[i] - 1));
2966 0 : nMergedRanges++;
2967 :
2968 0 : osRanges += osCurRange;
2969 :
2970 0 : if (nMergedRanges == 1)
2971 0 : osFirstRange = osCurRange;
2972 0 : osLastRange = std::move(osCurRange);
2973 : }
2974 :
2975 : const char *pszMaxRanges =
2976 0 : CPLGetConfigOption("CPL_VSIL_CURL_MAX_RANGES", "250");
2977 0 : int nMaxRanges = atoi(pszMaxRanges);
2978 0 : if (nMaxRanges <= 0)
2979 0 : nMaxRanges = 250;
2980 0 : if (nMergedRanges > nMaxRanges)
2981 : {
2982 0 : const int nHalf = nRanges / 2;
2983 0 : const int nRet = ReadMultiRange(nHalf, ppData, panOffsets, panSizes);
2984 0 : if (nRet != 0)
2985 0 : return nRet;
2986 0 : return ReadMultiRange(nRanges - nHalf, ppData + nHalf,
2987 0 : panOffsets + nHalf, panSizes + nHalf);
2988 : }
2989 :
2990 0 : CURLM *hCurlMultiHandle = poFS->GetCurlMultiHandleFor(m_pszURL);
2991 0 : CURL *hCurlHandle = curl_easy_init();
2992 :
2993 : struct curl_slist *headers =
2994 0 : VSICurlSetOptions(hCurlHandle, m_pszURL, m_aosHTTPOptions.List());
2995 :
2996 0 : WriteFuncStruct sWriteFuncData;
2997 0 : WriteFuncStruct sWriteFuncHeaderData;
2998 :
2999 0 : VSICURLInitWriteFuncStruct(&sWriteFuncData, this, pfnReadCbk,
3000 : pReadCbkUserData);
3001 0 : unchecked_curl_easy_setopt(hCurlHandle, CURLOPT_WRITEDATA, &sWriteFuncData);
3002 0 : unchecked_curl_easy_setopt(hCurlHandle, CURLOPT_WRITEFUNCTION,
3003 : VSICurlHandleWriteFunc);
3004 :
3005 0 : VSICURLInitWriteFuncStruct(&sWriteFuncHeaderData, nullptr, nullptr,
3006 : nullptr);
3007 0 : unchecked_curl_easy_setopt(hCurlHandle, CURLOPT_HEADERDATA,
3008 : &sWriteFuncHeaderData);
3009 0 : unchecked_curl_easy_setopt(hCurlHandle, CURLOPT_HEADERFUNCTION,
3010 : VSICurlHandleWriteFunc);
3011 0 : sWriteFuncHeaderData.bIsHTTP = STARTS_WITH(m_pszURL, "http");
3012 0 : sWriteFuncHeaderData.bMultiRange = nMergedRanges > 1;
3013 0 : if (nMergedRanges == 1)
3014 : {
3015 0 : sWriteFuncHeaderData.nStartOffset = panOffsets[0];
3016 0 : sWriteFuncHeaderData.nEndOffset = panOffsets[0] + nTotalReqSize - 1;
3017 : }
3018 :
3019 : if constexpr (ENABLE_DEBUG)
3020 : {
3021 0 : if (nMergedRanges == 1)
3022 0 : CPLDebug(poFS->GetDebugKey(), "Downloading %s (%s)...",
3023 : osRanges.c_str(), m_pszURL);
3024 : else
3025 0 : CPLDebug(poFS->GetDebugKey(),
3026 : "Downloading %s, ..., %s (" CPL_FRMT_GUIB " bytes, %s)...",
3027 : osFirstRange.c_str(), osLastRange.c_str(),
3028 : static_cast<GUIntBig>(nTotalReqSize), m_pszURL);
3029 : }
3030 :
3031 0 : unchecked_curl_easy_setopt(hCurlHandle, CURLOPT_RANGE, osRanges.c_str());
3032 :
3033 0 : char szCurlErrBuf[CURL_ERROR_SIZE + 1] = {};
3034 0 : unchecked_curl_easy_setopt(hCurlHandle, CURLOPT_ERRORBUFFER, szCurlErrBuf);
3035 :
3036 0 : headers = GetCurlHeaders("GET", headers);
3037 0 : unchecked_curl_easy_setopt(hCurlHandle, CURLOPT_HTTPHEADER, headers);
3038 :
3039 0 : VSICURLMultiPerform(hCurlMultiHandle, hCurlHandle);
3040 :
3041 0 : VSICURLResetHeaderAndWriterFunctions(hCurlHandle);
3042 :
3043 0 : curl_slist_free_all(headers);
3044 :
3045 0 : NetworkStatisticsLogger::LogGET(sWriteFuncData.nSize);
3046 :
3047 0 : if (sWriteFuncData.bInterrupted)
3048 : {
3049 0 : bInterrupted = true;
3050 :
3051 0 : CPLFree(sWriteFuncData.pBuffer);
3052 0 : CPLFree(sWriteFuncHeaderData.pBuffer);
3053 0 : curl_easy_cleanup(hCurlHandle);
3054 :
3055 0 : return -1;
3056 : }
3057 :
3058 0 : long response_code = 0;
3059 0 : curl_easy_getinfo(hCurlHandle, CURLINFO_HTTP_CODE, &response_code);
3060 :
3061 0 : if ((response_code != 200 && response_code != 206 && response_code != 225 &&
3062 0 : response_code != 226 && response_code != 426) ||
3063 0 : sWriteFuncHeaderData.bError)
3064 : {
3065 0 : if (response_code >= 400 && szCurlErrBuf[0] != '\0')
3066 : {
3067 0 : if (strcmp(szCurlErrBuf, "Couldn't use REST") == 0)
3068 0 : CPLError(
3069 : CE_Failure, CPLE_AppDefined,
3070 : "%d: %s, Range downloading not supported by this server!",
3071 : static_cast<int>(response_code), szCurlErrBuf);
3072 : else
3073 0 : CPLError(CE_Failure, CPLE_AppDefined, "%d: %s",
3074 : static_cast<int>(response_code), szCurlErrBuf);
3075 : }
3076 : /*
3077 : if( !bHasComputedFileSize && startOffset == 0 )
3078 : {
3079 : cachedFileProp->bHasComputedFileSize = bHasComputedFileSize = true;
3080 : cachedFileProp->fileSize = fileSize = 0;
3081 : cachedFileProp->eExists = eExists = EXIST_NO;
3082 : }
3083 : */
3084 0 : CPLFree(sWriteFuncData.pBuffer);
3085 0 : CPLFree(sWriteFuncHeaderData.pBuffer);
3086 0 : curl_easy_cleanup(hCurlHandle);
3087 0 : return -1;
3088 : }
3089 :
3090 0 : char *pBuffer = sWriteFuncData.pBuffer;
3091 0 : size_t nSize = sWriteFuncData.nSize;
3092 :
3093 : // TODO(schwehr): Localize after removing gotos.
3094 0 : int nRet = -1;
3095 : char *pszBoundary;
3096 0 : std::string osBoundary;
3097 0 : char *pszNext = nullptr;
3098 0 : int iRange = 0;
3099 0 : int iPart = 0;
3100 0 : char *pszEOL = nullptr;
3101 :
3102 : /* -------------------------------------------------------------------- */
3103 : /* No multipart if a single range has been requested */
3104 : /* -------------------------------------------------------------------- */
3105 :
3106 0 : if (nMergedRanges == 1)
3107 : {
3108 0 : size_t nAccSize = 0;
3109 0 : if (static_cast<vsi_l_offset>(nSize) < nTotalReqSize)
3110 0 : goto end;
3111 :
3112 0 : for (int i = 0; i < nRanges; i++)
3113 : {
3114 0 : memcpy(ppData[i], pBuffer + nAccSize, panSizes[i]);
3115 0 : nAccSize += panSizes[i];
3116 : }
3117 :
3118 0 : nRet = 0;
3119 0 : goto end;
3120 : }
3121 :
3122 : /* -------------------------------------------------------------------- */
3123 : /* Extract boundary name */
3124 : /* -------------------------------------------------------------------- */
3125 :
3126 0 : pszBoundary = strstr(sWriteFuncHeaderData.pBuffer,
3127 : "Content-Type: multipart/byteranges; boundary=");
3128 0 : if (pszBoundary == nullptr)
3129 : {
3130 0 : CPLError(CE_Failure, CPLE_AppDefined, "Could not find '%s'",
3131 : "Content-Type: multipart/byteranges; boundary=");
3132 0 : goto end;
3133 : }
3134 :
3135 0 : pszBoundary += strlen("Content-Type: multipart/byteranges; boundary=");
3136 :
3137 0 : pszEOL = strchr(pszBoundary, '\r');
3138 0 : if (pszEOL)
3139 0 : *pszEOL = 0;
3140 0 : pszEOL = strchr(pszBoundary, '\n');
3141 0 : if (pszEOL)
3142 0 : *pszEOL = 0;
3143 :
3144 : /* Remove optional double-quote character around boundary name */
3145 0 : if (pszBoundary[0] == '"')
3146 : {
3147 0 : pszBoundary++;
3148 0 : char *pszLastDoubleQuote = strrchr(pszBoundary, '"');
3149 0 : if (pszLastDoubleQuote)
3150 0 : *pszLastDoubleQuote = 0;
3151 : }
3152 :
3153 0 : osBoundary = "--";
3154 0 : osBoundary += pszBoundary;
3155 :
3156 : /* -------------------------------------------------------------------- */
3157 : /* Find the start of the first chunk. */
3158 : /* -------------------------------------------------------------------- */
3159 0 : pszNext = strstr(pBuffer, osBoundary.c_str());
3160 0 : if (pszNext == nullptr)
3161 : {
3162 0 : CPLError(CE_Failure, CPLE_AppDefined, "No parts found.");
3163 0 : goto end;
3164 : }
3165 :
3166 0 : pszNext += osBoundary.size();
3167 0 : while (*pszNext != '\n' && *pszNext != '\r' && *pszNext != '\0')
3168 0 : pszNext++;
3169 0 : if (*pszNext == '\r')
3170 0 : pszNext++;
3171 0 : if (*pszNext == '\n')
3172 0 : pszNext++;
3173 :
3174 : /* -------------------------------------------------------------------- */
3175 : /* Loop over parts... */
3176 : /* -------------------------------------------------------------------- */
3177 0 : while (iPart < nRanges)
3178 : {
3179 : /* --------------------------------------------------------------------
3180 : */
3181 : /* Collect headers. */
3182 : /* --------------------------------------------------------------------
3183 : */
3184 0 : bool bExpectedRange = false;
3185 :
3186 0 : while (*pszNext != '\n' && *pszNext != '\r' && *pszNext != '\0')
3187 : {
3188 0 : pszEOL = strstr(pszNext, "\n");
3189 :
3190 0 : if (pszEOL == nullptr)
3191 : {
3192 0 : CPLError(CE_Failure, CPLE_AppDefined,
3193 : "Error while parsing multipart content (at line %d)",
3194 : __LINE__);
3195 0 : goto end;
3196 : }
3197 :
3198 0 : *pszEOL = '\0';
3199 0 : bool bRestoreAntislashR = false;
3200 0 : if (pszEOL - pszNext > 1 && pszEOL[-1] == '\r')
3201 : {
3202 0 : bRestoreAntislashR = true;
3203 0 : pszEOL[-1] = '\0';
3204 : }
3205 :
3206 0 : if (STARTS_WITH_CI(pszNext, "Content-Range: bytes "))
3207 : {
3208 0 : bExpectedRange = true; /* FIXME */
3209 : }
3210 :
3211 0 : if (bRestoreAntislashR)
3212 0 : pszEOL[-1] = '\r';
3213 0 : *pszEOL = '\n';
3214 :
3215 0 : pszNext = pszEOL + 1;
3216 : }
3217 :
3218 0 : if (!bExpectedRange)
3219 : {
3220 0 : CPLError(CE_Failure, CPLE_AppDefined,
3221 : "Error while parsing multipart content (at line %d)",
3222 : __LINE__);
3223 0 : goto end;
3224 : }
3225 :
3226 0 : if (*pszNext == '\r')
3227 0 : pszNext++;
3228 0 : if (*pszNext == '\n')
3229 0 : pszNext++;
3230 :
3231 : /* --------------------------------------------------------------------
3232 : */
3233 : /* Work out the data block size. */
3234 : /* --------------------------------------------------------------------
3235 : */
3236 0 : size_t nBytesAvail = nSize - (pszNext - pBuffer);
3237 :
3238 : while (true)
3239 : {
3240 0 : if (nBytesAvail < panSizes[iRange])
3241 : {
3242 0 : CPLError(CE_Failure, CPLE_AppDefined,
3243 : "Error while parsing multipart content (at line %d)",
3244 : __LINE__);
3245 0 : goto end;
3246 : }
3247 :
3248 0 : memcpy(ppData[iRange], pszNext, panSizes[iRange]);
3249 0 : pszNext += panSizes[iRange];
3250 0 : nBytesAvail -= panSizes[iRange];
3251 0 : if (iRange + 1 < nRanges &&
3252 0 : panOffsets[iRange] + panSizes[iRange] == panOffsets[iRange + 1])
3253 : {
3254 0 : iRange++;
3255 : }
3256 : else
3257 : {
3258 : break;
3259 : }
3260 : }
3261 :
3262 0 : iPart++;
3263 0 : iRange++;
3264 :
3265 0 : while (nBytesAvail > 0 &&
3266 0 : (*pszNext != '-' ||
3267 0 : strncmp(pszNext, osBoundary.c_str(), osBoundary.size()) != 0))
3268 : {
3269 0 : pszNext++;
3270 0 : nBytesAvail--;
3271 : }
3272 :
3273 0 : if (nBytesAvail == 0)
3274 : {
3275 0 : CPLError(CE_Failure, CPLE_AppDefined,
3276 : "Error while parsing multipart content (at line %d)",
3277 : __LINE__);
3278 0 : goto end;
3279 : }
3280 :
3281 0 : pszNext += osBoundary.size();
3282 0 : if (STARTS_WITH(pszNext, "--"))
3283 : {
3284 : // End of multipart.
3285 0 : break;
3286 : }
3287 :
3288 0 : if (*pszNext == '\r')
3289 0 : pszNext++;
3290 0 : if (*pszNext == '\n')
3291 0 : pszNext++;
3292 : else
3293 : {
3294 0 : CPLError(CE_Failure, CPLE_AppDefined,
3295 : "Error while parsing multipart content (at line %d)",
3296 : __LINE__);
3297 0 : goto end;
3298 : }
3299 : }
3300 :
3301 0 : if (iPart == nMergedRanges)
3302 0 : nRet = 0;
3303 : else
3304 0 : CPLError(CE_Failure, CPLE_AppDefined,
3305 : "Got only %d parts, where %d were expected", iPart,
3306 : nMergedRanges);
3307 :
3308 0 : end:
3309 0 : CPLFree(sWriteFuncData.pBuffer);
3310 0 : CPLFree(sWriteFuncHeaderData.pBuffer);
3311 0 : curl_easy_cleanup(hCurlHandle);
3312 :
3313 0 : return nRet;
3314 : }
3315 :
3316 : /************************************************************************/
3317 : /* PRead() */
3318 : /************************************************************************/
3319 :
3320 207 : size_t VSICurlHandle::PRead(void *pBuffer, size_t nSize,
3321 : vsi_l_offset nOffset) const
3322 : {
3323 : // Try to use AdviseRead ranges fetched asynchronously
3324 207 : if (!m_aoAdviseReadRanges.empty())
3325 : {
3326 144 : for (auto &poRange : m_aoAdviseReadRanges)
3327 : {
3328 288 : if (nOffset >= poRange->nStartOffset &&
3329 144 : nOffset + nSize <= poRange->nStartOffset + poRange->nSize)
3330 : {
3331 : {
3332 288 : std::unique_lock<std::mutex> oLock(poRange->oMutex);
3333 : // coverity[missing_lock:FALSE]
3334 287 : while (!poRange->bDone)
3335 : {
3336 143 : poRange->oCV.wait(oLock);
3337 : }
3338 : }
3339 144 : if (poRange->abyData.empty())
3340 144 : return 0;
3341 :
3342 : auto nEndOffset =
3343 144 : poRange->nStartOffset + poRange->abyData.size();
3344 144 : if (nOffset >= nEndOffset)
3345 0 : return 0;
3346 : const size_t nToCopy = static_cast<size_t>(
3347 144 : std::min<vsi_l_offset>(nSize, nEndOffset - nOffset));
3348 144 : memcpy(pBuffer,
3349 144 : poRange->abyData.data() +
3350 144 : static_cast<size_t>(nOffset - poRange->nStartOffset),
3351 : nToCopy);
3352 144 : return nToCopy;
3353 : }
3354 : }
3355 : }
3356 :
3357 : // poFS has a global mutex
3358 64 : poFS->GetCachedFileProp(m_pszURL, oFileProp);
3359 64 : if (oFileProp.eExists == EXIST_NO)
3360 0 : return static_cast<size_t>(-1);
3361 :
3362 128 : NetworkStatisticsFileSystem oContextFS(poFS->GetFSPrefix().c_str());
3363 128 : NetworkStatisticsFile oContextFile(m_osFilename.c_str());
3364 128 : NetworkStatisticsAction oContextAction("PRead");
3365 :
3366 128 : CPLStringList aosHTTPOptions(m_aosHTTPOptions);
3367 128 : std::string osURL;
3368 : {
3369 64 : std::lock_guard<std::mutex> oLock(m_oMutex);
3370 64 : UpdateQueryString();
3371 : bool bHasExpired;
3372 64 : osURL = GetRedirectURLIfValid(bHasExpired, aosHTTPOptions);
3373 : }
3374 :
3375 64 : CURL *hCurlHandle = curl_easy_init();
3376 :
3377 : struct curl_slist *headers =
3378 64 : VSICurlSetOptions(hCurlHandle, osURL.c_str(), aosHTTPOptions.List());
3379 :
3380 64 : WriteFuncStruct sWriteFuncData;
3381 64 : VSICURLInitWriteFuncStruct(&sWriteFuncData, nullptr, nullptr, nullptr);
3382 64 : unchecked_curl_easy_setopt(hCurlHandle, CURLOPT_WRITEDATA, &sWriteFuncData);
3383 64 : unchecked_curl_easy_setopt(hCurlHandle, CURLOPT_WRITEFUNCTION,
3384 : VSICurlHandleWriteFunc);
3385 :
3386 64 : WriteFuncStruct sWriteFuncHeaderData;
3387 64 : VSICURLInitWriteFuncStruct(&sWriteFuncHeaderData, nullptr, nullptr,
3388 : nullptr);
3389 64 : unchecked_curl_easy_setopt(hCurlHandle, CURLOPT_HEADERDATA,
3390 : &sWriteFuncHeaderData);
3391 64 : unchecked_curl_easy_setopt(hCurlHandle, CURLOPT_HEADERFUNCTION,
3392 : VSICurlHandleWriteFunc);
3393 64 : sWriteFuncHeaderData.bIsHTTP = STARTS_WITH(m_pszURL, "http");
3394 64 : sWriteFuncHeaderData.nStartOffset = nOffset;
3395 :
3396 64 : sWriteFuncHeaderData.nEndOffset = nOffset + nSize - 1;
3397 :
3398 64 : char rangeStr[512] = {};
3399 64 : snprintf(rangeStr, sizeof(rangeStr), CPL_FRMT_GUIB "-" CPL_FRMT_GUIB,
3400 : sWriteFuncHeaderData.nStartOffset,
3401 : sWriteFuncHeaderData.nEndOffset);
3402 :
3403 : if constexpr (ENABLE_DEBUG)
3404 : {
3405 64 : CPLDebug(poFS->GetDebugKey(), "Downloading %s (%s)...", rangeStr,
3406 : osURL.c_str());
3407 : }
3408 :
3409 64 : std::string osHeaderRange;
3410 64 : if (sWriteFuncHeaderData.bIsHTTP)
3411 : {
3412 64 : osHeaderRange = CPLSPrintf("Range: bytes=%s", rangeStr);
3413 : // So it gets included in Azure signature
3414 64 : headers = curl_slist_append(headers, osHeaderRange.data());
3415 64 : unchecked_curl_easy_setopt(hCurlHandle, CURLOPT_RANGE, nullptr);
3416 : }
3417 : else
3418 : {
3419 0 : unchecked_curl_easy_setopt(hCurlHandle, CURLOPT_RANGE, rangeStr);
3420 : }
3421 :
3422 : std::array<char, CURL_ERROR_SIZE + 1> szCurlErrBuf;
3423 64 : szCurlErrBuf[0] = '\0';
3424 64 : unchecked_curl_easy_setopt(hCurlHandle, CURLOPT_ERRORBUFFER,
3425 : &szCurlErrBuf[0]);
3426 :
3427 : {
3428 64 : std::lock_guard<std::mutex> oLock(m_oMutex);
3429 : headers =
3430 64 : const_cast<VSICurlHandle *>(this)->GetCurlHeaders("GET", headers);
3431 : }
3432 64 : unchecked_curl_easy_setopt(hCurlHandle, CURLOPT_HTTPHEADER, headers);
3433 :
3434 64 : CURLM *hMultiHandle = poFS->GetCurlMultiHandleFor(osURL);
3435 64 : VSICURLMultiPerform(hMultiHandle, hCurlHandle, &m_bInterrupt);
3436 :
3437 : {
3438 128 : std::lock_guard<std::mutex> oLock(m_oMutex);
3439 64 : const_cast<VSICurlHandle *>(this)->UpdateRedirectInfo(
3440 : hCurlHandle, sWriteFuncHeaderData);
3441 : }
3442 :
3443 64 : long response_code = 0;
3444 64 : curl_easy_getinfo(hCurlHandle, CURLINFO_HTTP_CODE, &response_code);
3445 :
3446 64 : if (ENABLE_DEBUG && szCurlErrBuf[0] != '\0')
3447 : {
3448 0 : const char *pszErrorMsg = &szCurlErrBuf[0];
3449 0 : CPLDebug(poFS->GetDebugKey(), "PRead(%s), %s: response_code=%d, msg=%s",
3450 : osURL.c_str(), rangeStr, static_cast<int>(response_code),
3451 : pszErrorMsg);
3452 : }
3453 :
3454 : size_t nRet;
3455 64 : if ((response_code != 206 && response_code != 225) ||
3456 64 : sWriteFuncData.nSize == 0)
3457 : {
3458 0 : if (!m_bInterrupt)
3459 : {
3460 0 : CPLDebug(poFS->GetDebugKey(),
3461 : "Request for %s failed with response_code=%ld", rangeStr,
3462 : response_code);
3463 : }
3464 0 : nRet = static_cast<size_t>(-1);
3465 : }
3466 : else
3467 : {
3468 64 : nRet = std::min(sWriteFuncData.nSize, nSize);
3469 64 : if (nRet > 0)
3470 64 : memcpy(pBuffer, sWriteFuncData.pBuffer, nRet);
3471 : }
3472 :
3473 64 : VSICURLResetHeaderAndWriterFunctions(hCurlHandle);
3474 64 : curl_easy_cleanup(hCurlHandle);
3475 64 : CPLFree(sWriteFuncData.pBuffer);
3476 64 : CPLFree(sWriteFuncHeaderData.pBuffer);
3477 64 : curl_slist_free_all(headers);
3478 :
3479 64 : NetworkStatisticsLogger::LogGET(sWriteFuncData.nSize);
3480 :
3481 : #if 0
3482 : if( ENABLE_DEBUG )
3483 : CPLDebug(poFS->GetDebugKey(), "Download completed");
3484 : #endif
3485 :
3486 64 : return nRet;
3487 : }
3488 :
3489 : /************************************************************************/
3490 : /* GetAdviseReadTotalBytesLimit() */
3491 : /************************************************************************/
3492 :
3493 16 : size_t VSICurlHandle::GetAdviseReadTotalBytesLimit() const
3494 : {
3495 : return static_cast<size_t>(std::min<unsigned long long>(
3496 48 : std::numeric_limits<size_t>::max(),
3497 : // 100 MB
3498 16 : std::strtoull(
3499 : CPLGetConfigOption("CPL_VSIL_CURL_ADVISE_READ_TOTAL_BYTES_LIMIT",
3500 : "104857600"),
3501 16 : nullptr, 10)));
3502 : }
3503 :
3504 : /************************************************************************/
3505 : /* VSICURLMultiInit() */
3506 : /************************************************************************/
3507 :
3508 307 : static CURLM *VSICURLMultiInit()
3509 : {
3510 307 : CURLM *hCurlMultiHandle = curl_multi_init();
3511 :
3512 307 : if (const char *pszMAXCONNECTS =
3513 307 : CPLGetConfigOption("GDAL_HTTP_MAX_CACHED_CONNECTIONS", nullptr))
3514 : {
3515 1 : curl_multi_setopt(hCurlMultiHandle, CURLMOPT_MAXCONNECTS,
3516 : atoi(pszMAXCONNECTS));
3517 : }
3518 :
3519 307 : if (const char *pszMAX_TOTAL_CONNECTIONS =
3520 307 : CPLGetConfigOption("GDAL_HTTP_MAX_TOTAL_CONNECTIONS", nullptr))
3521 : {
3522 1 : curl_multi_setopt(hCurlMultiHandle, CURLMOPT_MAX_TOTAL_CONNECTIONS,
3523 : atoi(pszMAX_TOTAL_CONNECTIONS));
3524 : }
3525 :
3526 307 : return hCurlMultiHandle;
3527 : }
3528 :
3529 : /************************************************************************/
3530 : /* AdviseRead() */
3531 : /************************************************************************/
3532 :
3533 8 : void VSICurlHandle::AdviseRead(int nRanges, const vsi_l_offset *panOffsets,
3534 : const size_t *panSizes)
3535 : {
3536 8 : if (!CPLTestBool(
3537 : CPLGetConfigOption("GDAL_HTTP_ENABLE_ADVISE_READ", "TRUE")))
3538 2 : return;
3539 :
3540 6 : if (m_oThreadAdviseRead.joinable())
3541 : {
3542 1 : m_oThreadAdviseRead.join();
3543 : }
3544 :
3545 : // Give up if we need to allocate too much memory
3546 6 : vsi_l_offset nMaxSize = 0;
3547 6 : const size_t nLimit = GetAdviseReadTotalBytesLimit();
3548 150 : for (int i = 0; i < nRanges; ++i)
3549 : {
3550 144 : if (panSizes[i] > nLimit - nMaxSize)
3551 : {
3552 0 : CPLDebug(poFS->GetDebugKey(),
3553 : "Trying to request too many bytes in AdviseRead()");
3554 0 : return;
3555 : }
3556 144 : nMaxSize += panSizes[i];
3557 : }
3558 :
3559 6 : UpdateQueryString();
3560 :
3561 6 : bool bHasExpired = false;
3562 6 : CPLStringList aosHTTPOptions(m_aosHTTPOptions);
3563 : const std::string l_osURL(
3564 6 : GetRedirectURLIfValid(bHasExpired, aosHTTPOptions));
3565 6 : if (bHasExpired)
3566 : {
3567 0 : return;
3568 : }
3569 :
3570 6 : const bool bMergeConsecutiveRanges = CPLTestBool(
3571 : CPLGetConfigOption("GDAL_HTTP_MERGE_CONSECUTIVE_RANGES", "TRUE"));
3572 :
3573 : try
3574 : {
3575 6 : m_aoAdviseReadRanges.clear();
3576 6 : m_aoAdviseReadRanges.reserve(nRanges);
3577 12 : for (int i = 0; i < nRanges;)
3578 : {
3579 6 : int iNext = i;
3580 : // Identify consecutive ranges
3581 6 : constexpr size_t SIZE_COG_MARKERS = 2 * sizeof(uint32_t);
3582 6 : auto nEndOffset = panOffsets[iNext] + panSizes[iNext];
3583 144 : while (bMergeConsecutiveRanges && iNext + 1 < nRanges &&
3584 138 : panOffsets[iNext + 1] > panOffsets[iNext] &&
3585 138 : panOffsets[iNext] + panSizes[iNext] + SIZE_COG_MARKERS >=
3586 282 : panOffsets[iNext + 1] &&
3587 138 : panOffsets[iNext + 1] + panSizes[iNext + 1] > nEndOffset)
3588 : {
3589 138 : iNext++;
3590 138 : nEndOffset = panOffsets[iNext] + panSizes[iNext];
3591 : }
3592 6 : CPLAssert(panOffsets[i] <= nEndOffset);
3593 6 : const size_t nSize =
3594 6 : static_cast<size_t>(nEndOffset - panOffsets[i]);
3595 :
3596 6 : if (nSize == 0)
3597 : {
3598 0 : i = iNext + 1;
3599 0 : continue;
3600 : }
3601 :
3602 : auto newAdviseReadRange =
3603 6 : std::make_unique<AdviseReadRange>(m_oRetryParameters);
3604 6 : newAdviseReadRange->nStartOffset = panOffsets[i];
3605 6 : newAdviseReadRange->nSize = nSize;
3606 6 : newAdviseReadRange->abyData.resize(nSize);
3607 6 : m_aoAdviseReadRanges.push_back(std::move(newAdviseReadRange));
3608 :
3609 6 : i = iNext + 1;
3610 : }
3611 : }
3612 0 : catch (const std::exception &)
3613 : {
3614 0 : CPLError(CE_Failure, CPLE_OutOfMemory,
3615 : "Out of memory in VSICurlHandle::AdviseRead()");
3616 0 : m_aoAdviseReadRanges.clear();
3617 : }
3618 :
3619 6 : if (m_aoAdviseReadRanges.empty())
3620 0 : return;
3621 :
3622 : #ifdef DEBUG
3623 6 : CPLDebug(poFS->GetDebugKey(), "AdviseRead(): fetching %u ranges",
3624 6 : static_cast<unsigned>(m_aoAdviseReadRanges.size()));
3625 : #endif
3626 :
3627 12 : const auto task = [this, aosHTTPOptions = std::move(aosHTTPOptions)](
3628 477 : const std::string &osURL)
3629 : {
3630 6 : if (!m_hCurlMultiHandleForAdviseRead)
3631 5 : m_hCurlMultiHandleForAdviseRead = VSICURLMultiInit();
3632 :
3633 12 : NetworkStatisticsFileSystem oContextFS(poFS->GetFSPrefix().c_str());
3634 12 : NetworkStatisticsFile oContextFile(m_osFilename.c_str());
3635 12 : NetworkStatisticsAction oContextAction("AdviseRead");
3636 :
3637 : #ifdef CURLPIPE_MULTIPLEX
3638 : // Enable HTTP/2 multiplexing (ignored if an older version of HTTP is
3639 : // used)
3640 : // Not that this does not enable HTTP/1.1 pipeling, which is not
3641 : // recommended for example by Google Cloud Storage.
3642 : // For HTTP/1.1, parallel connections work better since you can get
3643 : // results out of order.
3644 6 : if (CPLTestBool(CPLGetConfigOption("GDAL_HTTP_MULTIPLEX", "YES")))
3645 : {
3646 6 : curl_multi_setopt(m_hCurlMultiHandleForAdviseRead,
3647 : CURLMOPT_PIPELINING, CURLPIPE_MULTIPLEX);
3648 : }
3649 : #endif
3650 :
3651 6 : size_t nTotalDownloaded = 0;
3652 :
3653 : while (true)
3654 : {
3655 :
3656 8 : std::vector<CURL *> aHandles;
3657 : std::vector<WriteFuncStruct> asWriteFuncData(
3658 8 : m_aoAdviseReadRanges.size());
3659 : std::vector<WriteFuncStruct> asWriteFuncHeaderData(
3660 8 : m_aoAdviseReadRanges.size());
3661 8 : std::vector<char *> apszRanges;
3662 8 : std::vector<struct curl_slist *> aHeaders;
3663 :
3664 : struct CurlErrBuffer
3665 : {
3666 : std::array<char, CURL_ERROR_SIZE + 1> szCurlErrBuf;
3667 : };
3668 : std::vector<CurlErrBuffer> asCurlErrors(
3669 8 : m_aoAdviseReadRanges.size());
3670 :
3671 8 : std::map<CURL *, size_t> oMapHandleToIdx;
3672 16 : for (size_t i = 0; i < m_aoAdviseReadRanges.size(); ++i)
3673 : {
3674 8 : if (!m_aoAdviseReadRanges[i]->bToRetry)
3675 : {
3676 0 : aHandles.push_back(nullptr);
3677 0 : apszRanges.push_back(nullptr);
3678 0 : aHeaders.push_back(nullptr);
3679 0 : continue;
3680 : }
3681 8 : m_aoAdviseReadRanges[i]->bToRetry = false;
3682 :
3683 8 : CURL *hCurlHandle = curl_easy_init();
3684 8 : oMapHandleToIdx[hCurlHandle] = i;
3685 8 : aHandles.push_back(hCurlHandle);
3686 :
3687 : // As the multi-range request is likely not the first one, we don't
3688 : // need to wait as we already know if pipelining is possible
3689 : // unchecked_curl_easy_setopt(hCurlHandle, CURLOPT_PIPEWAIT, 1);
3690 :
3691 8 : struct curl_slist *headers = VSICurlSetOptions(
3692 8 : hCurlHandle, osURL.c_str(), aosHTTPOptions.List());
3693 :
3694 8 : VSICURLInitWriteFuncStruct(&asWriteFuncData[i], this,
3695 : pfnReadCbk, pReadCbkUserData);
3696 8 : unchecked_curl_easy_setopt(hCurlHandle, CURLOPT_WRITEDATA,
3697 : &asWriteFuncData[i]);
3698 8 : unchecked_curl_easy_setopt(hCurlHandle, CURLOPT_WRITEFUNCTION,
3699 : VSICurlHandleWriteFunc);
3700 :
3701 8 : VSICURLInitWriteFuncStruct(&asWriteFuncHeaderData[i], nullptr,
3702 : nullptr, nullptr);
3703 8 : unchecked_curl_easy_setopt(hCurlHandle, CURLOPT_HEADERDATA,
3704 : &asWriteFuncHeaderData[i]);
3705 8 : unchecked_curl_easy_setopt(hCurlHandle, CURLOPT_HEADERFUNCTION,
3706 : VSICurlHandleWriteFunc);
3707 16 : asWriteFuncHeaderData[i].bIsHTTP =
3708 8 : STARTS_WITH(m_pszURL, "http");
3709 16 : asWriteFuncHeaderData[i].nStartOffset =
3710 8 : m_aoAdviseReadRanges[i]->nStartOffset;
3711 :
3712 16 : asWriteFuncHeaderData[i].nEndOffset =
3713 8 : m_aoAdviseReadRanges[i]->nStartOffset +
3714 8 : m_aoAdviseReadRanges[i]->nSize - 1;
3715 :
3716 8 : char rangeStr[512] = {};
3717 16 : snprintf(rangeStr, sizeof(rangeStr),
3718 : CPL_FRMT_GUIB "-" CPL_FRMT_GUIB,
3719 8 : asWriteFuncHeaderData[i].nStartOffset,
3720 8 : asWriteFuncHeaderData[i].nEndOffset);
3721 :
3722 : if constexpr (ENABLE_DEBUG)
3723 : {
3724 8 : CPLDebug(poFS->GetDebugKey(), "Downloading %s (%s)...",
3725 : rangeStr, osURL.c_str());
3726 : }
3727 :
3728 8 : if (asWriteFuncHeaderData[i].bIsHTTP)
3729 : {
3730 : std::string osHeaderRange(
3731 8 : CPLSPrintf("Range: bytes=%s", rangeStr));
3732 : // So it gets included in Azure signature
3733 8 : char *pszRange = CPLStrdup(osHeaderRange.c_str());
3734 8 : apszRanges.push_back(pszRange);
3735 8 : headers = curl_slist_append(headers, pszRange);
3736 8 : unchecked_curl_easy_setopt(hCurlHandle, CURLOPT_RANGE,
3737 : nullptr);
3738 : }
3739 : else
3740 : {
3741 0 : apszRanges.push_back(nullptr);
3742 0 : unchecked_curl_easy_setopt(hCurlHandle, CURLOPT_RANGE,
3743 : rangeStr);
3744 : }
3745 :
3746 8 : asCurlErrors[i].szCurlErrBuf[0] = '\0';
3747 8 : unchecked_curl_easy_setopt(hCurlHandle, CURLOPT_ERRORBUFFER,
3748 : &asCurlErrors[i].szCurlErrBuf[0]);
3749 :
3750 8 : headers = GetCurlHeaders("GET", headers);
3751 8 : unchecked_curl_easy_setopt(hCurlHandle, CURLOPT_HTTPHEADER,
3752 : headers);
3753 8 : aHeaders.push_back(headers);
3754 8 : curl_multi_add_handle(m_hCurlMultiHandleForAdviseRead,
3755 : hCurlHandle);
3756 : }
3757 :
3758 8 : const auto DealWithRequest = [this, &osURL, &nTotalDownloaded,
3759 : &oMapHandleToIdx, &asCurlErrors,
3760 : &asWriteFuncHeaderData,
3761 116 : &asWriteFuncData](CURL *hCurlHandle)
3762 : {
3763 8 : auto oIter = oMapHandleToIdx.find(hCurlHandle);
3764 8 : CPLAssert(oIter != oMapHandleToIdx.end());
3765 8 : const auto iReq = oIter->second;
3766 :
3767 8 : long response_code = 0;
3768 8 : curl_easy_getinfo(hCurlHandle, CURLINFO_HTTP_CODE,
3769 : &response_code);
3770 :
3771 8 : if (ENABLE_DEBUG && asCurlErrors[iReq].szCurlErrBuf[0] != '\0')
3772 : {
3773 0 : char rangeStr[512] = {};
3774 0 : snprintf(rangeStr, sizeof(rangeStr),
3775 : CPL_FRMT_GUIB "-" CPL_FRMT_GUIB,
3776 0 : asWriteFuncHeaderData[iReq].nStartOffset,
3777 0 : asWriteFuncHeaderData[iReq].nEndOffset);
3778 :
3779 : const char *pszErrorMsg =
3780 0 : &asCurlErrors[iReq].szCurlErrBuf[0];
3781 0 : CPLDebug(poFS->GetDebugKey(),
3782 : "ReadMultiRange(%s), %s: response_code=%d, msg=%s",
3783 : osURL.c_str(), rangeStr,
3784 : static_cast<int>(response_code), pszErrorMsg);
3785 : }
3786 :
3787 8 : bool bToRetry = false;
3788 14 : if ((response_code != 206 && response_code != 225) ||
3789 6 : asWriteFuncHeaderData[iReq].nEndOffset + 1 !=
3790 6 : asWriteFuncHeaderData[iReq].nStartOffset +
3791 6 : asWriteFuncData[iReq].nSize)
3792 : {
3793 2 : char rangeStr[512] = {};
3794 4 : snprintf(rangeStr, sizeof(rangeStr),
3795 : CPL_FRMT_GUIB "-" CPL_FRMT_GUIB,
3796 2 : asWriteFuncHeaderData[iReq].nStartOffset,
3797 2 : asWriteFuncHeaderData[iReq].nEndOffset);
3798 :
3799 : // Look if we should attempt a retry
3800 4 : if (m_aoAdviseReadRanges[iReq]->retryContext.CanRetry(
3801 : static_cast<int>(response_code),
3802 2 : asWriteFuncData[iReq].pBuffer,
3803 2 : &asCurlErrors[iReq].szCurlErrBuf[0]))
3804 : {
3805 2 : CPLError(CE_Warning, CPLE_AppDefined,
3806 : "HTTP error code for %s range %s: %d. "
3807 : "Retrying again in %.1f secs",
3808 : osURL.c_str(), rangeStr,
3809 : static_cast<int>(response_code),
3810 2 : m_aoAdviseReadRanges[iReq]
3811 2 : ->retryContext.GetCurrentDelay());
3812 2 : m_aoAdviseReadRanges[iReq]->dfSleepDelay =
3813 2 : m_aoAdviseReadRanges[iReq]
3814 2 : ->retryContext.GetCurrentDelay();
3815 2 : bToRetry = true;
3816 : }
3817 : else
3818 : {
3819 0 : CPLError(CE_Failure, CPLE_AppDefined,
3820 : "Request for %s range %s failed with "
3821 : "response_code=%ld",
3822 : osURL.c_str(), rangeStr, response_code);
3823 : }
3824 : }
3825 : else
3826 : {
3827 6 : const size_t nSize = asWriteFuncData[iReq].nSize;
3828 6 : memcpy(&m_aoAdviseReadRanges[iReq]->abyData[0],
3829 6 : asWriteFuncData[iReq].pBuffer, nSize);
3830 6 : m_aoAdviseReadRanges[iReq]->abyData.resize(nSize);
3831 :
3832 6 : nTotalDownloaded += nSize;
3833 : }
3834 :
3835 8 : m_aoAdviseReadRanges[iReq]->bToRetry = bToRetry;
3836 :
3837 8 : if (!bToRetry)
3838 : {
3839 : std::lock_guard<std::mutex> oLock(
3840 12 : m_aoAdviseReadRanges[iReq]->oMutex);
3841 6 : m_aoAdviseReadRanges[iReq]->bDone = true;
3842 6 : m_aoAdviseReadRanges[iReq]->oCV.notify_all();
3843 : }
3844 8 : };
3845 :
3846 8 : int repeats = 0;
3847 :
3848 8 : void *old_handler = CPLHTTPIgnoreSigPipe();
3849 : while (true)
3850 : {
3851 : int still_running;
3852 90 : while (curl_multi_perform(m_hCurlMultiHandleForAdviseRead,
3853 90 : &still_running) ==
3854 : CURLM_CALL_MULTI_PERFORM)
3855 : {
3856 : // loop
3857 : }
3858 90 : if (!still_running)
3859 : {
3860 8 : break;
3861 : }
3862 :
3863 : CURLMsg *msg;
3864 0 : do
3865 : {
3866 82 : int msgq = 0;
3867 82 : msg = curl_multi_info_read(m_hCurlMultiHandleForAdviseRead,
3868 : &msgq);
3869 82 : if (msg && (msg->msg == CURLMSG_DONE))
3870 : {
3871 0 : DealWithRequest(msg->easy_handle);
3872 : }
3873 82 : } while (msg);
3874 :
3875 82 : CPLMultiPerformWait(m_hCurlMultiHandleForAdviseRead, repeats);
3876 82 : }
3877 8 : CPLHTTPRestoreSigPipeHandler(old_handler);
3878 :
3879 8 : bool bRetry = false;
3880 8 : double dfDelay = 0.0;
3881 16 : for (size_t i = 0; i < m_aoAdviseReadRanges.size(); ++i)
3882 : {
3883 : bool bReqDone;
3884 : {
3885 : // To please Coverity Scan
3886 : std::lock_guard<std::mutex> oLock(
3887 8 : m_aoAdviseReadRanges[i]->oMutex);
3888 8 : bReqDone = m_aoAdviseReadRanges[i]->bDone;
3889 : }
3890 8 : if (!bReqDone && !m_aoAdviseReadRanges[i]->bToRetry)
3891 : {
3892 8 : DealWithRequest(aHandles[i]);
3893 : }
3894 8 : if (m_aoAdviseReadRanges[i]->bToRetry)
3895 2 : dfDelay = std::max(dfDelay,
3896 2 : m_aoAdviseReadRanges[i]->dfSleepDelay);
3897 8 : bRetry = bRetry || m_aoAdviseReadRanges[i]->bToRetry;
3898 8 : if (aHandles[i])
3899 : {
3900 8 : curl_multi_remove_handle(m_hCurlMultiHandleForAdviseRead,
3901 8 : aHandles[i]);
3902 8 : VSICURLResetHeaderAndWriterFunctions(aHandles[i]);
3903 8 : curl_easy_cleanup(aHandles[i]);
3904 : }
3905 8 : CPLFree(apszRanges[i]);
3906 8 : CPLFree(asWriteFuncData[i].pBuffer);
3907 8 : CPLFree(asWriteFuncHeaderData[i].pBuffer);
3908 8 : if (aHeaders[i])
3909 8 : curl_slist_free_all(aHeaders[i]);
3910 : }
3911 8 : if (!bRetry)
3912 6 : break;
3913 2 : CPLSleep(dfDelay);
3914 2 : }
3915 :
3916 6 : NetworkStatisticsLogger::LogGET(nTotalDownloaded);
3917 12 : };
3918 :
3919 6 : m_oThreadAdviseRead = std::thread(task, l_osURL);
3920 : }
3921 :
3922 : /************************************************************************/
3923 : /* Write() */
3924 : /************************************************************************/
3925 :
3926 0 : size_t VSICurlHandle::Write(const void * /* pBuffer */, size_t /* nBytes */)
3927 : {
3928 0 : return 0;
3929 : }
3930 :
3931 : /************************************************************************/
3932 : /* ClearErr() */
3933 : /************************************************************************/
3934 :
3935 1 : void VSICurlHandle::ClearErr()
3936 :
3937 : {
3938 1 : bEOF = false;
3939 1 : bError = false;
3940 1 : }
3941 :
3942 : /************************************************************************/
3943 : /* Error() */
3944 : /************************************************************************/
3945 :
3946 8 : int VSICurlHandle::Error()
3947 :
3948 : {
3949 8 : return bError ? TRUE : FALSE;
3950 : }
3951 :
3952 : /************************************************************************/
3953 : /* Eof() */
3954 : /************************************************************************/
3955 :
3956 16 : int VSICurlHandle::Eof()
3957 :
3958 : {
3959 16 : return bEOF ? TRUE : FALSE;
3960 : }
3961 :
3962 : /************************************************************************/
3963 : /* Flush() */
3964 : /************************************************************************/
3965 :
3966 2 : int VSICurlHandle::Flush()
3967 : {
3968 2 : return 0;
3969 : }
3970 :
3971 : /************************************************************************/
3972 : /* Close() */
3973 : /************************************************************************/
3974 :
3975 832 : int VSICurlHandle::Close()
3976 : {
3977 832 : return 0;
3978 : }
3979 :
3980 : /************************************************************************/
3981 : /* VSICurlFilesystemHandlerBase() */
3982 : /************************************************************************/
3983 :
3984 15872 : VSICurlFilesystemHandlerBase::VSICurlFilesystemHandlerBase()
3985 15872 : : oCacheFileProp{100 * 1024}, oCacheDirList{1024, 0}
3986 : {
3987 15872 : }
3988 :
3989 : /************************************************************************/
3990 : /* CachedConnection */
3991 : /************************************************************************/
3992 :
3993 : namespace
3994 : {
3995 : struct CachedConnection
3996 : {
3997 : CURLM *hCurlMultiHandle = nullptr;
3998 : void clear();
3999 :
4000 10144 : ~CachedConnection()
4001 10144 : {
4002 10144 : clear();
4003 10144 : }
4004 : };
4005 : } // namespace
4006 :
4007 : #ifdef _WIN32
4008 : // Currently thread_local and C++ objects don't work well with DLL on Windows
4009 : static void FreeCachedConnection(void *pData)
4010 : {
4011 : delete static_cast<
4012 : std::map<VSICurlFilesystemHandlerBase *, CachedConnection> *>(pData);
4013 : }
4014 :
4015 : // Per-thread and per-filesystem Curl connection cache.
4016 : static std::map<VSICurlFilesystemHandlerBase *, CachedConnection> &
4017 : GetConnectionCache()
4018 : {
4019 : static std::map<VSICurlFilesystemHandlerBase *, CachedConnection>
4020 : dummyCache;
4021 : int bMemoryErrorOccurred = false;
4022 : void *pData =
4023 : CPLGetTLSEx(CTLS_VSICURL_CACHEDCONNECTION, &bMemoryErrorOccurred);
4024 : if (bMemoryErrorOccurred)
4025 : {
4026 : return dummyCache;
4027 : }
4028 : if (pData == nullptr)
4029 : {
4030 : auto cachedConnection =
4031 : new std::map<VSICurlFilesystemHandlerBase *, CachedConnection>();
4032 : CPLSetTLSWithFreeFuncEx(CTLS_VSICURL_CACHEDCONNECTION, cachedConnection,
4033 : FreeCachedConnection, &bMemoryErrorOccurred);
4034 : if (bMemoryErrorOccurred)
4035 : {
4036 : delete cachedConnection;
4037 : return dummyCache;
4038 : }
4039 : return *cachedConnection;
4040 : }
4041 : return *static_cast<
4042 : std::map<VSICurlFilesystemHandlerBase *, CachedConnection> *>(pData);
4043 : }
4044 : #else
4045 : static thread_local std::map<VSICurlFilesystemHandlerBase *, CachedConnection>
4046 : g_tls_connectionCache;
4047 :
4048 : static std::map<VSICurlFilesystemHandlerBase *, CachedConnection> &
4049 29634 : GetConnectionCache()
4050 : {
4051 29634 : return g_tls_connectionCache;
4052 : }
4053 : #endif
4054 :
4055 : /************************************************************************/
4056 : /* clear() */
4057 : /************************************************************************/
4058 :
4059 28256 : void CachedConnection::clear()
4060 : {
4061 28256 : if (hCurlMultiHandle)
4062 : {
4063 270 : VSICURLMultiCleanup(hCurlMultiHandle);
4064 270 : hCurlMultiHandle = nullptr;
4065 : }
4066 28256 : }
4067 :
4068 : /************************************************************************/
4069 : /* ~VSICurlFilesystemHandlerBase() */
4070 : /************************************************************************/
4071 :
4072 10112 : VSICurlFilesystemHandlerBase::~VSICurlFilesystemHandlerBase()
4073 : {
4074 10112 : VSICurlFilesystemHandlerBase::ClearCache();
4075 10112 : GetConnectionCache().erase(this);
4076 :
4077 10112 : if (hMutex != nullptr)
4078 10112 : CPLDestroyMutex(hMutex);
4079 10112 : hMutex = nullptr;
4080 10112 : }
4081 :
4082 : /************************************************************************/
4083 : /* AllowCachedDataFor() */
4084 : /************************************************************************/
4085 :
4086 3762 : bool VSICurlFilesystemHandlerBase::AllowCachedDataFor(const char *pszFilename)
4087 : {
4088 3762 : bool bCachedAllowed = true;
4089 3762 : char **papszTokens = CSLTokenizeString2(
4090 : CPLGetConfigOption("CPL_VSIL_CURL_NON_CACHED", ""), ":", 0);
4091 3802 : for (int i = 0; papszTokens && papszTokens[i]; i++)
4092 : {
4093 120 : if (STARTS_WITH(pszFilename, papszTokens[i]))
4094 : {
4095 80 : bCachedAllowed = false;
4096 80 : break;
4097 : }
4098 : }
4099 3762 : CSLDestroy(papszTokens);
4100 3762 : return bCachedAllowed;
4101 : }
4102 :
4103 : /************************************************************************/
4104 : /* GetCurlMultiHandleFor() */
4105 : /************************************************************************/
4106 :
4107 1410 : CURLM *VSICurlFilesystemHandlerBase::GetCurlMultiHandleFor(
4108 : const std::string & /*osURL*/)
4109 : {
4110 1410 : auto &conn = GetConnectionCache()[this];
4111 1410 : if (conn.hCurlMultiHandle == nullptr)
4112 : {
4113 302 : conn.hCurlMultiHandle = VSICURLMultiInit();
4114 : }
4115 1410 : return conn.hCurlMultiHandle;
4116 : }
4117 :
4118 : /************************************************************************/
4119 : /* GetRegionCache() */
4120 : /************************************************************************/
4121 :
4122 : VSICurlFilesystemHandlerBase::RegionCacheType *
4123 192923 : VSICurlFilesystemHandlerBase::GetRegionCache()
4124 : {
4125 : // should be called under hMutex taken
4126 192923 : if (m_poRegionCacheDoNotUseDirectly == nullptr)
4127 : {
4128 10137 : m_poRegionCacheDoNotUseDirectly.reset(
4129 10137 : new RegionCacheType(static_cast<size_t>(GetMaxRegions())));
4130 : }
4131 192923 : return m_poRegionCacheDoNotUseDirectly.get();
4132 : }
4133 :
4134 : /************************************************************************/
4135 : /* GetRegion() */
4136 : /************************************************************************/
4137 :
4138 : std::shared_ptr<std::string>
4139 166688 : VSICurlFilesystemHandlerBase::GetRegion(const char *pszURL,
4140 : vsi_l_offset nFileOffsetStart)
4141 : {
4142 333376 : CPLMutexHolder oHolder(&hMutex);
4143 :
4144 166688 : const int knDOWNLOAD_CHUNK_SIZE = VSICURLGetDownloadChunkSize();
4145 166688 : nFileOffsetStart =
4146 166688 : (nFileOffsetStart / knDOWNLOAD_CHUNK_SIZE) * knDOWNLOAD_CHUNK_SIZE;
4147 :
4148 166688 : std::shared_ptr<std::string> out;
4149 333376 : if (GetRegionCache()->tryGet(
4150 333376 : FilenameOffsetPair(std::string(pszURL), nFileOffsetStart), out))
4151 : {
4152 148106 : return out;
4153 : }
4154 :
4155 18582 : return nullptr;
4156 : }
4157 :
4158 : /************************************************************************/
4159 : /* AddRegion() */
4160 : /************************************************************************/
4161 :
4162 7915 : void VSICurlFilesystemHandlerBase::AddRegion(const char *pszURL,
4163 : vsi_l_offset nFileOffsetStart,
4164 : size_t nSize, const char *pData)
4165 : {
4166 15830 : CPLMutexHolder oHolder(&hMutex);
4167 :
4168 7915 : auto value = std::make_shared<std::string>();
4169 7915 : value->assign(pData, nSize);
4170 : GetRegionCache()->insert(
4171 15830 : FilenameOffsetPair(std::string(pszURL), nFileOffsetStart),
4172 15830 : std::move(value));
4173 7915 : }
4174 :
4175 : /************************************************************************/
4176 : /* GetCachedFileProp() */
4177 : /************************************************************************/
4178 :
4179 152043 : bool VSICurlFilesystemHandlerBase::GetCachedFileProp(const char *pszURL,
4180 : FileProp &oFileProp)
4181 : {
4182 304086 : CPLMutexHolder oHolder(&hMutex);
4183 : bool inCache;
4184 152043 : if (oCacheFileProp.tryGet(std::string(pszURL), inCache))
4185 : {
4186 150233 : if (VSICURLGetCachedFileProp(pszURL, oFileProp))
4187 : {
4188 150233 : return true;
4189 : }
4190 0 : oCacheFileProp.remove(std::string(pszURL));
4191 : }
4192 1810 : return false;
4193 : }
4194 :
4195 : /************************************************************************/
4196 : /* SetCachedFileProp() */
4197 : /************************************************************************/
4198 :
4199 1170 : void VSICurlFilesystemHandlerBase::SetCachedFileProp(const char *pszURL,
4200 : FileProp &oFileProp)
4201 : {
4202 2340 : CPLMutexHolder oHolder(&hMutex);
4203 1170 : oCacheFileProp.insert(std::string(pszURL), true);
4204 1170 : VSICURLSetCachedFileProp(pszURL, oFileProp);
4205 1170 : }
4206 :
4207 : /************************************************************************/
4208 : /* GetCachedDirList() */
4209 : /************************************************************************/
4210 :
4211 638 : bool VSICurlFilesystemHandlerBase::GetCachedDirList(
4212 : const char *pszURL, CachedDirList &oCachedDirList)
4213 : {
4214 638 : CPLMutexHolder oHolder(&hMutex);
4215 :
4216 1459 : return oCacheDirList.tryGet(std::string(pszURL), oCachedDirList) &&
4217 : // Let a chance to use new auth parameters
4218 183 : gnGenerationAuthParameters ==
4219 1459 : oCachedDirList.nGenerationAuthParameters;
4220 : }
4221 :
4222 : /************************************************************************/
4223 : /* SetCachedDirList() */
4224 : /************************************************************************/
4225 :
4226 181 : void VSICurlFilesystemHandlerBase::SetCachedDirList(
4227 : const char *pszURL, CachedDirList &oCachedDirList)
4228 : {
4229 362 : CPLMutexHolder oHolder(&hMutex);
4230 :
4231 362 : std::string key(pszURL);
4232 362 : CachedDirList oldValue;
4233 181 : if (oCacheDirList.tryGet(key, oldValue))
4234 : {
4235 10 : nCachedFilesInDirList -= oldValue.oFileList.size();
4236 10 : oCacheDirList.remove(key);
4237 : }
4238 :
4239 181 : while ((!oCacheDirList.empty() &&
4240 63 : nCachedFilesInDirList + oCachedDirList.oFileList.size() >
4241 362 : 1024 * 1024) ||
4242 181 : oCacheDirList.size() == oCacheDirList.getMaxAllowedSize())
4243 : {
4244 0 : std::string oldestKey;
4245 0 : oCacheDirList.getOldestEntry(oldestKey, oldValue);
4246 0 : nCachedFilesInDirList -= oldValue.oFileList.size();
4247 0 : oCacheDirList.remove(oldestKey);
4248 : }
4249 181 : oCachedDirList.nGenerationAuthParameters = gnGenerationAuthParameters;
4250 :
4251 181 : nCachedFilesInDirList += oCachedDirList.oFileList.size();
4252 181 : oCacheDirList.insert(key, oCachedDirList);
4253 181 : }
4254 :
4255 : /************************************************************************/
4256 : /* ExistsInCacheDirList() */
4257 : /************************************************************************/
4258 :
4259 13 : bool VSICurlFilesystemHandlerBase::ExistsInCacheDirList(
4260 : const std::string &osDirname, bool *pbIsDir)
4261 : {
4262 26 : CachedDirList cachedDirList;
4263 13 : if (GetCachedDirList(osDirname.c_str(), cachedDirList))
4264 : {
4265 0 : if (pbIsDir)
4266 0 : *pbIsDir = !cachedDirList.oFileList.empty();
4267 0 : return false;
4268 : }
4269 : else
4270 : {
4271 13 : if (pbIsDir)
4272 13 : *pbIsDir = false;
4273 13 : return false;
4274 : }
4275 : }
4276 :
4277 : /************************************************************************/
4278 : /* InvalidateCachedData() */
4279 : /************************************************************************/
4280 :
4281 201 : void VSICurlFilesystemHandlerBase::InvalidateCachedData(const char *pszURL)
4282 : {
4283 402 : CPLMutexHolder oHolder(&hMutex);
4284 :
4285 201 : oCacheFileProp.remove(std::string(pszURL));
4286 :
4287 : // Invalidate all cached regions for this URL
4288 402 : std::list<FilenameOffsetPair> keysToRemove;
4289 402 : std::string osURL(pszURL);
4290 : auto lambda =
4291 2857 : [&keysToRemove,
4292 : &osURL](const lru11::KeyValuePair<FilenameOffsetPair,
4293 3636 : std::shared_ptr<std::string>> &kv)
4294 : {
4295 2857 : if (kv.key.filename_ == osURL)
4296 779 : keysToRemove.push_back(kv.key);
4297 3058 : };
4298 201 : auto *poRegionCache = GetRegionCache();
4299 201 : poRegionCache->cwalk(lambda);
4300 980 : for (const auto &key : keysToRemove)
4301 779 : poRegionCache->remove(key);
4302 201 : }
4303 :
4304 : /************************************************************************/
4305 : /* ClearCache() */
4306 : /************************************************************************/
4307 :
4308 18112 : void VSICurlFilesystemHandlerBase::ClearCache()
4309 : {
4310 18112 : CPLMutexHolder oHolder(&hMutex);
4311 :
4312 18112 : GetRegionCache()->clear();
4313 :
4314 : {
4315 660 : const auto lambda = [](const lru11::KeyValuePair<std::string, bool> &kv)
4316 660 : { VSICURLInvalidateCachedFileProp(kv.key.c_str()); };
4317 18112 : oCacheFileProp.cwalk(lambda);
4318 18112 : oCacheFileProp.clear();
4319 : }
4320 :
4321 18112 : oCacheDirList.clear();
4322 18112 : nCachedFilesInDirList = 0;
4323 :
4324 18112 : GetConnectionCache()[this].clear();
4325 18112 : }
4326 :
4327 : /************************************************************************/
4328 : /* PartialClearCache() */
4329 : /************************************************************************/
4330 :
4331 7 : void VSICurlFilesystemHandlerBase::PartialClearCache(
4332 : const char *pszFilenamePrefix)
4333 : {
4334 14 : CPLMutexHolder oHolder(&hMutex);
4335 :
4336 21 : std::string osURL = GetURLFromFilename(pszFilenamePrefix);
4337 : {
4338 14 : std::list<FilenameOffsetPair> keysToRemove;
4339 : auto lambda =
4340 3 : [&keysToRemove, &osURL](
4341 : const lru11::KeyValuePair<FilenameOffsetPair,
4342 8 : std::shared_ptr<std::string>> &kv)
4343 : {
4344 3 : if (strncmp(kv.key.filename_.c_str(), osURL.c_str(),
4345 3 : osURL.size()) == 0)
4346 2 : keysToRemove.push_back(kv.key);
4347 10 : };
4348 7 : auto *poRegionCache = GetRegionCache();
4349 7 : poRegionCache->cwalk(lambda);
4350 9 : for (const auto &key : keysToRemove)
4351 2 : poRegionCache->remove(key);
4352 : }
4353 :
4354 : {
4355 14 : std::list<std::string> keysToRemove;
4356 10 : auto lambda = [&keysToRemove,
4357 24 : &osURL](const lru11::KeyValuePair<std::string, bool> &kv)
4358 : {
4359 10 : if (strncmp(kv.key.c_str(), osURL.c_str(), osURL.size()) == 0)
4360 4 : keysToRemove.push_back(kv.key);
4361 17 : };
4362 7 : oCacheFileProp.cwalk(lambda);
4363 11 : for (const auto &key : keysToRemove)
4364 4 : oCacheFileProp.remove(key);
4365 : }
4366 7 : VSICURLInvalidateCachedFilePropPrefix(osURL.c_str());
4367 :
4368 : {
4369 7 : const size_t nLen = strlen(pszFilenamePrefix);
4370 14 : std::list<std::string> keysToRemove;
4371 : auto lambda =
4372 2 : [this, &keysToRemove, pszFilenamePrefix,
4373 4 : nLen](const lru11::KeyValuePair<std::string, CachedDirList> &kv)
4374 : {
4375 2 : if (strncmp(kv.key.c_str(), pszFilenamePrefix, nLen) == 0)
4376 : {
4377 1 : keysToRemove.push_back(kv.key);
4378 1 : nCachedFilesInDirList -= kv.value.oFileList.size();
4379 : }
4380 9 : };
4381 7 : oCacheDirList.cwalk(lambda);
4382 8 : for (const auto &key : keysToRemove)
4383 1 : oCacheDirList.remove(key);
4384 : }
4385 7 : }
4386 :
4387 : /************************************************************************/
4388 : /* CreateFileHandle() */
4389 : /************************************************************************/
4390 :
4391 : VSICurlHandle *
4392 1508 : VSICurlFilesystemHandlerBase::CreateFileHandle(const char *pszFilename)
4393 : {
4394 1508 : return new VSICurlHandle(this, pszFilename);
4395 : }
4396 :
4397 : /************************************************************************/
4398 : /* GetActualURL() */
4399 : /************************************************************************/
4400 :
4401 5 : const char *VSICurlFilesystemHandlerBase::GetActualURL(const char *pszFilename)
4402 : {
4403 5 : VSICurlHandle *poHandle = CreateFileHandle(pszFilename);
4404 5 : if (poHandle == nullptr)
4405 0 : return pszFilename;
4406 10 : std::string osURL(poHandle->GetURL());
4407 5 : delete poHandle;
4408 5 : return CPLSPrintf("%s", osURL.c_str());
4409 : }
4410 :
4411 : /************************************************************************/
4412 : /* GetOptions() */
4413 : /************************************************************************/
4414 :
4415 : #define VSICURL_OPTIONS \
4416 : " <Option name='GDAL_HTTP_MAX_RETRY' type='int' " \
4417 : "description='Maximum number of retries' default='0'/>" \
4418 : " <Option name='GDAL_HTTP_RETRY_DELAY' type='double' " \
4419 : "description='Retry delay in seconds' default='30'/>" \
4420 : " <Option name='GDAL_HTTP_HEADER_FILE' type='string' " \
4421 : "description='Filename of a file that contains HTTP headers to " \
4422 : "forward to the server'/>" \
4423 : " <Option name='CPL_VSIL_CURL_USE_HEAD' type='boolean' " \
4424 : "description='Whether to use HTTP HEAD verb to retrieve " \
4425 : "file information' default='YES'/>" \
4426 : " <Option name='GDAL_HTTP_MULTIRANGE' type='string-select' " \
4427 : "description='Strategy to apply to run multi-range requests' " \
4428 : "default='PARALLEL'>" \
4429 : " <Value>PARALLEL</Value>" \
4430 : " <Value>SERIAL</Value>" \
4431 : " </Option>" \
4432 : " <Option name='GDAL_HTTP_MULTIPLEX' type='boolean' " \
4433 : "description='Whether to enable HTTP/2 multiplexing' default='YES'/>" \
4434 : " <Option name='GDAL_HTTP_MERGE_CONSECUTIVE_RANGES' type='boolean' " \
4435 : "description='Whether to merge consecutive ranges in multirange " \
4436 : "requests' default='YES'/>" \
4437 : " <Option name='CPL_VSIL_CURL_NON_CACHED' type='string' " \
4438 : "description='Colon-separated list of filenames whose content" \
4439 : "must not be cached across open attempts'/>" \
4440 : " <Option name='CPL_VSIL_CURL_ALLOWED_FILENAME' type='string' " \
4441 : "description='Single filename that is allowed to be opened'/>" \
4442 : " <Option name='CPL_VSIL_CURL_ALLOWED_EXTENSIONS' type='string' " \
4443 : "description='Comma or space separated list of allowed file " \
4444 : "extensions'/>" \
4445 : " <Option name='GDAL_DISABLE_READDIR_ON_OPEN' type='string-select' " \
4446 : "description='Whether to disable establishing the list of files in " \
4447 : "the directory of the current filename' default='NO'>" \
4448 : " <Value>NO</Value>" \
4449 : " <Value>YES</Value>" \
4450 : " <Value>EMPTY_DIR</Value>" \
4451 : " </Option>" \
4452 : " <Option name='VSI_CACHE' type='boolean' " \
4453 : "description='Whether to cache in memory the contents of the opened " \
4454 : "file as soon as they are read' default='NO'/>" \
4455 : " <Option name='CPL_VSIL_CURL_CHUNK_SIZE' type='integer' " \
4456 : "description='Size in bytes of the minimum amount of data read in a " \
4457 : "file' default='16384' min='1024' max='10485760'/>" \
4458 : " <Option name='CPL_VSIL_CURL_CACHE_SIZE' type='integer' " \
4459 : "description='Size in bytes of the global /vsicurl/ cache' " \
4460 : "default='16384000'/>" \
4461 : " <Option name='CPL_VSIL_CURL_IGNORE_GLACIER_STORAGE' type='boolean' " \
4462 : "description='Whether to skip files with Glacier storage class in " \
4463 : "directory listing.' default='YES'/>" \
4464 : " <Option name='CPL_VSIL_CURL_ADVISE_READ_TOTAL_BYTES_LIMIT' " \
4465 : "type='integer' description='Maximum number of bytes AdviseRead() is " \
4466 : "allowed to fetch at once' default='104857600'/>" \
4467 : " <Option name='GDAL_HTTP_MAX_CACHED_CONNECTIONS' type='integer' " \
4468 : "description='Maximum amount of connections that libcurl may keep alive " \
4469 : "in its connection cache after use'/>" \
4470 : " <Option name='GDAL_HTTP_MAX_TOTAL_CONNECTIONS' type='integer' " \
4471 : "description='Maximum number of simultaneously open connections in " \
4472 : "total'/>"
4473 :
4474 8 : const char *VSICurlFilesystemHandlerBase::GetOptionsStatic()
4475 : {
4476 8 : return VSICURL_OPTIONS;
4477 : }
4478 :
4479 2 : const char *VSICurlFilesystemHandlerBase::GetOptions()
4480 : {
4481 2 : static std::string osOptions(std::string("<Options>") + GetOptionsStatic() +
4482 3 : "</Options>");
4483 2 : return osOptions.c_str();
4484 : }
4485 :
4486 : /************************************************************************/
4487 : /* IsAllowedFilename() */
4488 : /************************************************************************/
4489 :
4490 2129 : bool VSICurlFilesystemHandlerBase::IsAllowedFilename(const char *pszFilename)
4491 : {
4492 : const char *pszAllowedFilename =
4493 2129 : CPLGetConfigOption("CPL_VSIL_CURL_ALLOWED_FILENAME", nullptr);
4494 2129 : if (pszAllowedFilename != nullptr)
4495 : {
4496 0 : return strcmp(pszFilename, pszAllowedFilename) == 0;
4497 : }
4498 :
4499 : // Consider that only the files whose extension ends up with one that is
4500 : // listed in CPL_VSIL_CURL_ALLOWED_EXTENSIONS exist on the server. This can
4501 : // speeds up dramatically open experience, in case the server cannot return
4502 : // a file list. {noext} can be used as a special token to mean file with no
4503 : // extension.
4504 : // For example:
4505 : // gdalinfo --config CPL_VSIL_CURL_ALLOWED_EXTENSIONS ".tif"
4506 : // /vsicurl/http://igskmncngs506.cr.usgs.gov/gmted/Global_tiles_GMTED/075darcsec/bln/W030/30N030W_20101117_gmted_bln075.tif
4507 : const char *pszAllowedExtensions =
4508 2129 : CPLGetConfigOption("CPL_VSIL_CURL_ALLOWED_EXTENSIONS", nullptr);
4509 2129 : if (pszAllowedExtensions)
4510 : {
4511 : char **papszExtensions =
4512 22 : CSLTokenizeString2(pszAllowedExtensions, ", ", 0);
4513 22 : const char *queryStart = strchr(pszFilename, '?');
4514 22 : char *pszFilenameWithoutQuery = nullptr;
4515 22 : if (queryStart != nullptr)
4516 : {
4517 0 : pszFilenameWithoutQuery = CPLStrdup(pszFilename);
4518 0 : pszFilenameWithoutQuery[queryStart - pszFilename] = '\0';
4519 0 : pszFilename = pszFilenameWithoutQuery;
4520 : }
4521 22 : const size_t nURLLen = strlen(pszFilename);
4522 22 : bool bFound = false;
4523 22 : for (int i = 0; papszExtensions[i] != nullptr; i++)
4524 : {
4525 22 : const size_t nExtensionLen = strlen(papszExtensions[i]);
4526 22 : if (EQUAL(papszExtensions[i], "{noext}"))
4527 : {
4528 0 : const char *pszLastSlash = strrchr(pszFilename, '/');
4529 0 : if (pszLastSlash != nullptr &&
4530 0 : strchr(pszLastSlash, '.') == nullptr)
4531 : {
4532 0 : bFound = true;
4533 0 : break;
4534 : }
4535 : }
4536 22 : else if (nURLLen > nExtensionLen &&
4537 22 : EQUAL(pszFilename + nURLLen - nExtensionLen,
4538 : papszExtensions[i]))
4539 : {
4540 22 : bFound = true;
4541 22 : break;
4542 : }
4543 : }
4544 :
4545 22 : CSLDestroy(papszExtensions);
4546 22 : if (pszFilenameWithoutQuery)
4547 : {
4548 0 : CPLFree(pszFilenameWithoutQuery);
4549 : }
4550 :
4551 22 : return bFound;
4552 : }
4553 2107 : return TRUE;
4554 : }
4555 :
4556 : /************************************************************************/
4557 : /* Open() */
4558 : /************************************************************************/
4559 :
4560 : VSIVirtualHandleUniquePtr
4561 855 : VSICurlFilesystemHandlerBase::Open(const char *pszFilename,
4562 : const char *pszAccess, bool bSetError,
4563 : CSLConstList papszOptions)
4564 : {
4565 1710 : std::string osFilenameAfterPrefix;
4566 855 : if (cpl::starts_with(std::string_view(pszFilename), GetFSPrefix()))
4567 : {
4568 835 : osFilenameAfterPrefix = pszFilename + GetFSPrefix().size();
4569 : }
4570 20 : else if (!StartsWithVSICurlPrefix(pszFilename, &osFilenameAfterPrefix))
4571 : {
4572 1 : return nullptr;
4573 : }
4574 :
4575 854 : if (strchr(pszAccess, 'w') != nullptr || strchr(pszAccess, '+') != nullptr)
4576 : {
4577 1 : if (bSetError)
4578 : {
4579 0 : VSIError(VSIE_FileError,
4580 : "Only read-only mode is supported for /vsicurl");
4581 : }
4582 1 : return nullptr;
4583 : }
4584 858 : if (!papszOptions ||
4585 5 : !CPLTestBool(CSLFetchNameValueDef(
4586 : papszOptions, "IGNORE_FILENAME_RESTRICTIONS", "NO")))
4587 : {
4588 851 : if (!IsAllowedFilename(pszFilename))
4589 0 : return nullptr;
4590 : }
4591 :
4592 853 : bool bListDir = true;
4593 853 : bool bEmptyDir = false;
4594 853 : CPL_IGNORE_RET_VAL(VSICurlGetURLFromFilename(pszFilename, nullptr, nullptr,
4595 : nullptr, &bListDir, &bEmptyDir,
4596 : nullptr, nullptr, nullptr));
4597 :
4598 853 : const char *pszOptionVal = CSLFetchNameValueDef(
4599 : papszOptions, "DISABLE_READDIR_ON_OPEN",
4600 : VSIGetPathSpecificOption(pszFilename, "GDAL_DISABLE_READDIR_ON_OPEN",
4601 : "NO"));
4602 853 : const bool bCache = CPLTestBool(CSLFetchNameValueDef(
4603 853 : papszOptions, "CACHE", AllowCachedDataFor(pszFilename) ? "YES" : "NO"));
4604 853 : const bool bSkipReadDir = !bListDir || bEmptyDir ||
4605 849 : EQUAL(pszOptionVal, "EMPTY_DIR") ||
4606 1706 : CPLTestBool(pszOptionVal) || !bCache;
4607 :
4608 1706 : std::string osFilename(pszFilename);
4609 853 : bool bGotFileList = !bSkipReadDir;
4610 853 : bool bForceExistsCheck = false;
4611 1706 : FileProp cachedFileProp;
4612 2515 : if (!bSkipReadDir &&
4613 809 : !(GetCachedFileProp(osFilenameAfterPrefix.c_str(), cachedFileProp) &&
4614 565 : cachedFileProp.eExists == EXIST_YES) &&
4615 268 : strchr(CPLGetFilename(osFilename.c_str()), '.') != nullptr &&
4616 1809 : !STARTS_WITH(CPLGetExtensionSafe(osFilename.c_str()).c_str(), "zip") &&
4617 : // Likely a Kerchunk JSON reference file: no need to list siblings
4618 147 : !cpl::ends_with(osFilename, ".nc.zarr"))
4619 : {
4620 : // 1000 corresponds to the default page size of S3.
4621 147 : constexpr int FILE_COUNT_LIMIT = 1000;
4622 : const CPLStringList aosFileList(ReadDirInternal(
4623 294 : (CPLGetDirnameSafe(osFilename.c_str()) + '/').c_str(),
4624 147 : FILE_COUNT_LIMIT, &bGotFileList));
4625 : const bool bFound =
4626 147 : VSICurlIsFileInList(aosFileList.List(),
4627 147 : CPLGetFilename(osFilename.c_str())) != -1;
4628 147 : if (bGotFileList && !bFound && aosFileList.size() < FILE_COUNT_LIMIT)
4629 : {
4630 : // Some file servers are case insensitive, so in case there is a
4631 : // match with case difference, do a full check just in case.
4632 : // e.g.
4633 : // http://pds-geosciences.wustl.edu/mgs/mgs-m-mola-5-megdr-l3-v1/mgsl_300x/meg004/MEGA90N000CB.IMG
4634 : // that is queried by
4635 : // gdalinfo
4636 : // /vsicurl/http://pds-geosciences.wustl.edu/mgs/mgs-m-mola-5-megdr-l3-v1/mgsl_300x/meg004/mega90n000cb.lbl
4637 10 : if (aosFileList.FindString(CPLGetFilename(osFilename.c_str())) !=
4638 : -1)
4639 : {
4640 0 : bForceExistsCheck = true;
4641 : }
4642 : else
4643 : {
4644 10 : return nullptr;
4645 : }
4646 : }
4647 : }
4648 :
4649 : auto poHandle =
4650 1686 : std::unique_ptr<VSICurlHandle>(CreateFileHandle(osFilename.c_str()));
4651 843 : if (poHandle == nullptr)
4652 24 : return nullptr;
4653 819 : poHandle->SetCache(bCache);
4654 819 : if (!bGotFileList || bForceExistsCheck)
4655 : {
4656 : // If we didn't get a filelist, check that the file really exists.
4657 150 : if (!poHandle->Exists(bSetError))
4658 : {
4659 66 : return nullptr;
4660 : }
4661 : }
4662 :
4663 753 : if (CPLTestBool(CPLGetConfigOption("VSI_CACHE", "FALSE")))
4664 : return VSIVirtualHandleUniquePtr(
4665 0 : VSICreateCachedFile(poHandle.release()));
4666 : else
4667 753 : return VSIVirtualHandleUniquePtr(poHandle.release());
4668 : }
4669 :
4670 : /************************************************************************/
4671 : /* VSICurlParserFindEOL() */
4672 : /* */
4673 : /* Small helper function for VSICurlPaseHTMLFileList() to find */
4674 : /* the end of a line in the directory listing. Either a <br> */
4675 : /* or newline. */
4676 : /************************************************************************/
4677 :
4678 278898 : static char *VSICurlParserFindEOL(char *pszData)
4679 :
4680 : {
4681 278898 : while (*pszData != '\0' && *pszData != '\n' &&
4682 277328 : !STARTS_WITH_CI(pszData, "<br>"))
4683 277328 : pszData++;
4684 :
4685 1570 : if (*pszData == '\0')
4686 15 : return nullptr;
4687 :
4688 1555 : return pszData;
4689 : }
4690 :
4691 : /************************************************************************/
4692 : /* VSICurlParseHTMLDateTimeFileSize() */
4693 : /************************************************************************/
4694 :
4695 : static const char *const apszMonths[] = {
4696 : "January", "February", "March", "April", "May", "June",
4697 : "July", "August", "September", "October", "November", "December"};
4698 :
4699 20 : static bool VSICurlParseHTMLDateTimeFileSize(const char *pszStr,
4700 : struct tm &brokendowntime,
4701 : GUIntBig &nFileSize,
4702 : GIntBig &mTime)
4703 : {
4704 198 : for (int iMonth = 0; iMonth < 12; iMonth++)
4705 : {
4706 195 : char szMonth[32] = {};
4707 195 : szMonth[0] = '-';
4708 195 : memcpy(szMonth + 1, apszMonths[iMonth], 3);
4709 195 : szMonth[4] = '-';
4710 195 : szMonth[5] = '\0';
4711 195 : const char *pszMonthFound = strstr(pszStr, szMonth);
4712 195 : if (pszMonthFound)
4713 : {
4714 : // Format of Apache, like in
4715 : // http://download.osgeo.org/gdal/data/gtiff/
4716 : // "17-May-2010 12:26"
4717 17 : const auto nMonthFoundLen = strlen(pszMonthFound);
4718 17 : if (pszMonthFound - pszStr > 2 && nMonthFoundLen > 15 &&
4719 17 : pszMonthFound[-2 + 11] == ' ' && pszMonthFound[-2 + 14] == ':')
4720 : {
4721 4 : pszMonthFound -= 2;
4722 4 : int nDay = atoi(pszMonthFound);
4723 4 : int nYear = atoi(pszMonthFound + 7);
4724 4 : int nHour = atoi(pszMonthFound + 12);
4725 4 : int nMin = atoi(pszMonthFound + 15);
4726 4 : if (nDay >= 1 && nDay <= 31 && nYear >= 1900 && nHour >= 0 &&
4727 4 : nHour <= 24 && nMin >= 0 && nMin < 60)
4728 : {
4729 4 : brokendowntime.tm_year = nYear - 1900;
4730 4 : brokendowntime.tm_mon = iMonth;
4731 4 : brokendowntime.tm_mday = nDay;
4732 4 : brokendowntime.tm_hour = nHour;
4733 4 : brokendowntime.tm_min = nMin;
4734 4 : mTime = CPLYMDHMSToUnixTime(&brokendowntime);
4735 :
4736 4 : if (nMonthFoundLen > 15 + 2)
4737 : {
4738 4 : const char *pszFilesize = pszMonthFound + 15 + 2;
4739 35 : while (*pszFilesize == ' ')
4740 31 : pszFilesize++;
4741 4 : if (*pszFilesize >= '1' && *pszFilesize <= '9')
4742 2 : nFileSize = CPLScanUIntBig(
4743 : pszFilesize,
4744 2 : static_cast<int>(strlen(pszFilesize)));
4745 : }
4746 :
4747 17 : return true;
4748 : }
4749 : }
4750 13 : return false;
4751 : }
4752 :
4753 : /* Microsoft IIS */
4754 178 : snprintf(szMonth, sizeof(szMonth), " %s ", apszMonths[iMonth]);
4755 178 : pszMonthFound = strstr(pszStr, szMonth);
4756 178 : if (pszMonthFound)
4757 : {
4758 0 : int nLenMonth = static_cast<int>(strlen(apszMonths[iMonth]));
4759 0 : if (pszMonthFound - pszStr > 2 && pszMonthFound[-1] != ',' &&
4760 0 : pszMonthFound[-2] != ' ' &&
4761 0 : static_cast<int>(strlen(pszMonthFound - 2)) >
4762 0 : 2 + 1 + nLenMonth + 1 + 4 + 1 + 5 + 1 + 4)
4763 : {
4764 : /* Format of http://ortho.linz.govt.nz/tifs/1994_95/ */
4765 : /* " Friday, 21 April 2006 12:05 p.m. 48062343
4766 : * m35a_fy_94_95.tif" */
4767 0 : pszMonthFound -= 2;
4768 0 : int nDay = atoi(pszMonthFound);
4769 0 : int nCurOffset = 2 + 1 + nLenMonth + 1;
4770 0 : int nYear = atoi(pszMonthFound + nCurOffset);
4771 0 : nCurOffset += 4 + 1;
4772 0 : int nHour = atoi(pszMonthFound + nCurOffset);
4773 0 : if (nHour < 10)
4774 0 : nCurOffset += 1 + 1;
4775 : else
4776 0 : nCurOffset += 2 + 1;
4777 0 : const int nMin = atoi(pszMonthFound + nCurOffset);
4778 0 : nCurOffset += 2 + 1;
4779 0 : if (STARTS_WITH(pszMonthFound + nCurOffset, "p.m."))
4780 0 : nHour += 12;
4781 0 : else if (!STARTS_WITH(pszMonthFound + nCurOffset, "a.m."))
4782 0 : nHour = -1;
4783 0 : nCurOffset += 4;
4784 :
4785 0 : const char *pszFilesize = pszMonthFound + nCurOffset;
4786 0 : while (*pszFilesize == ' ')
4787 0 : pszFilesize++;
4788 0 : if (*pszFilesize >= '1' && *pszFilesize <= '9')
4789 0 : nFileSize = CPLScanUIntBig(
4790 0 : pszFilesize, static_cast<int>(strlen(pszFilesize)));
4791 :
4792 0 : if (nDay >= 1 && nDay <= 31 && nYear >= 1900 && nHour >= 0 &&
4793 0 : nHour <= 24 && nMin >= 0 && nMin < 60)
4794 : {
4795 0 : brokendowntime.tm_year = nYear - 1900;
4796 0 : brokendowntime.tm_mon = iMonth;
4797 0 : brokendowntime.tm_mday = nDay;
4798 0 : brokendowntime.tm_hour = nHour;
4799 0 : brokendowntime.tm_min = nMin;
4800 0 : mTime = CPLYMDHMSToUnixTime(&brokendowntime);
4801 :
4802 0 : return true;
4803 : }
4804 0 : nFileSize = 0;
4805 : }
4806 0 : else if (pszMonthFound - pszStr > 1 && pszMonthFound[-1] == ',' &&
4807 0 : static_cast<int>(strlen(pszMonthFound)) >
4808 0 : 1 + nLenMonth + 1 + 2 + 1 + 1 + 4 + 1 + 5 + 1 + 2)
4809 : {
4810 : // Format of
4811 : // http://publicfiles.dep.state.fl.us/dear/BWR_GIS/2007NWFLULC/
4812 : // " Sunday, June 20, 2010 6:46 PM 233170905
4813 : // NWF2007LULCForSDE.zip"
4814 0 : pszMonthFound += 1;
4815 0 : int nCurOffset = nLenMonth + 1;
4816 0 : int nDay = atoi(pszMonthFound + nCurOffset);
4817 0 : nCurOffset += 2 + 1 + 1;
4818 0 : int nYear = atoi(pszMonthFound + nCurOffset);
4819 0 : nCurOffset += 4 + 1;
4820 0 : int nHour = atoi(pszMonthFound + nCurOffset);
4821 0 : nCurOffset += 2 + 1;
4822 0 : const int nMin = atoi(pszMonthFound + nCurOffset);
4823 0 : nCurOffset += 2 + 1;
4824 0 : if (STARTS_WITH(pszMonthFound + nCurOffset, "PM"))
4825 0 : nHour += 12;
4826 0 : else if (!STARTS_WITH(pszMonthFound + nCurOffset, "AM"))
4827 0 : nHour = -1;
4828 0 : nCurOffset += 2;
4829 :
4830 0 : const char *pszFilesize = pszMonthFound + nCurOffset;
4831 0 : while (*pszFilesize == ' ')
4832 0 : pszFilesize++;
4833 0 : if (*pszFilesize >= '1' && *pszFilesize <= '9')
4834 0 : nFileSize = CPLScanUIntBig(
4835 0 : pszFilesize, static_cast<int>(strlen(pszFilesize)));
4836 :
4837 0 : if (nDay >= 1 && nDay <= 31 && nYear >= 1900 && nHour >= 0 &&
4838 0 : nHour <= 24 && nMin >= 0 && nMin < 60)
4839 : {
4840 0 : brokendowntime.tm_year = nYear - 1900;
4841 0 : brokendowntime.tm_mon = iMonth;
4842 0 : brokendowntime.tm_mday = nDay;
4843 0 : brokendowntime.tm_hour = nHour;
4844 0 : brokendowntime.tm_min = nMin;
4845 0 : mTime = CPLYMDHMSToUnixTime(&brokendowntime);
4846 :
4847 0 : return true;
4848 : }
4849 0 : nFileSize = 0;
4850 : }
4851 0 : return false;
4852 : }
4853 : }
4854 :
4855 3 : return false;
4856 : }
4857 :
4858 : /************************************************************************/
4859 : /* ParseHTMLFileList() */
4860 : /* */
4861 : /* Parse a file list document and return all the components. */
4862 : /************************************************************************/
4863 :
4864 15 : char **VSICurlFilesystemHandlerBase::ParseHTMLFileList(const char *pszFilename,
4865 : int nMaxFiles,
4866 : char *pszData,
4867 : bool *pbGotFileList)
4868 : {
4869 15 : *pbGotFileList = false;
4870 :
4871 : std::string osURL(VSICurlGetURLFromFilename(pszFilename, nullptr, nullptr,
4872 : nullptr, nullptr, nullptr,
4873 30 : nullptr, nullptr, nullptr));
4874 15 : const char *pszDir = nullptr;
4875 15 : if (STARTS_WITH_CI(osURL.c_str(), "http://"))
4876 8 : pszDir = strchr(osURL.c_str() + strlen("http://"), '/');
4877 7 : else if (STARTS_WITH_CI(osURL.c_str(), "https://"))
4878 7 : pszDir = strchr(osURL.c_str() + strlen("https://"), '/');
4879 0 : else if (STARTS_WITH_CI(osURL.c_str(), "ftp://"))
4880 0 : pszDir = strchr(osURL.c_str() + strlen("ftp://"), '/');
4881 15 : if (pszDir == nullptr)
4882 3 : pszDir = "";
4883 :
4884 : /* Apache / Nginx */
4885 : /* Most of the time the format is <title>Index of {pszDir[/]}</title>, but
4886 : * there are special cases like https://cdn.star.nesdis.noaa.gov/GOES18/ABI/MESO/M1/GEOCOLOR/
4887 : * where a CDN stuff makes that the title is <title>Index of /ma-cdn02/GOES/data/GOES18/ABI/MESO/M1/GEOCOLOR/</title>
4888 : */
4889 30 : const std::string osTitleIndexOfPrefix = "<title>Index of ";
4890 45 : const std::string osExpectedSuffix = std::string(pszDir).append("</title>");
4891 : const std::string osExpectedSuffixWithSlash =
4892 45 : std::string(pszDir).append("/</title>");
4893 : /* FTP */
4894 : const std::string osExpectedStringFTP =
4895 45 : std::string("FTP Listing of ").append(pszDir).append("/");
4896 : /* Apache 1.3.33 */
4897 : const std::string osExpectedStringOldApache =
4898 45 : std::string("<TITLE>Index of ").append(pszDir).append("</TITLE>");
4899 :
4900 : // The listing of
4901 : // http://dds.cr.usgs.gov/srtm/SRTM_image_sample/picture%20examples/
4902 : // has
4903 : // "<title>Index of /srtm/SRTM_image_sample/picture examples</title>"
4904 : // so we must try unescaped %20 also.
4905 : // Similar with
4906 : // http://datalib.usask.ca/gis/Data/Central_America_goodbutdoweown%3f/
4907 30 : std::string osExpectedString_unescaped;
4908 15 : if (strchr(pszDir, '%'))
4909 : {
4910 0 : char *pszUnescapedDir = CPLUnescapeString(pszDir, nullptr, CPLES_URL);
4911 0 : osExpectedString_unescaped = osTitleIndexOfPrefix;
4912 0 : osExpectedString_unescaped += pszUnescapedDir;
4913 0 : osExpectedString_unescaped += "</title>";
4914 0 : CPLFree(pszUnescapedDir);
4915 : }
4916 :
4917 15 : char *c = nullptr;
4918 15 : int nCount = 0;
4919 15 : int nCountTable = 0;
4920 30 : CPLStringList oFileList;
4921 15 : char *pszLine = pszData;
4922 15 : bool bIsHTMLDirList = false;
4923 :
4924 1570 : while ((c = VSICurlParserFindEOL(pszLine)) != nullptr)
4925 : {
4926 1555 : *c = '\0';
4927 :
4928 : // To avoid false positive on pages such as
4929 : // http://www.ngs.noaa.gov/PC_PROD/USGG2009BETA
4930 : // This is a heuristics, but normal HTML listing of files have not more
4931 : // than one table.
4932 1555 : if (strstr(pszLine, "<table"))
4933 : {
4934 4 : nCountTable++;
4935 4 : if (nCountTable == 2)
4936 : {
4937 0 : *pbGotFileList = false;
4938 0 : return nullptr;
4939 : }
4940 : }
4941 :
4942 3075 : if (!bIsHTMLDirList &&
4943 1520 : ((strstr(pszLine, osTitleIndexOfPrefix.c_str()) &&
4944 4 : (strstr(pszLine, osExpectedSuffix.c_str()) ||
4945 3 : strstr(pszLine, osExpectedSuffixWithSlash.c_str()))) ||
4946 1516 : strstr(pszLine, osExpectedStringFTP.c_str()) ||
4947 1516 : strstr(pszLine, osExpectedStringOldApache.c_str()) ||
4948 1516 : (!osExpectedString_unescaped.empty() &&
4949 0 : strstr(pszLine, osExpectedString_unescaped.c_str()))))
4950 : {
4951 4 : bIsHTMLDirList = true;
4952 4 : *pbGotFileList = true;
4953 : }
4954 : // Subversion HTTP listing
4955 : // or Microsoft-IIS/6.0 listing
4956 : // (e.g. http://ortho.linz.govt.nz/tifs/2005_06/) */
4957 1551 : else if (!bIsHTMLDirList && strstr(pszLine, "<title>"))
4958 : {
4959 : // Detect something like:
4960 : // <html><head><title>gdal - Revision 20739:
4961 : // /trunk/autotest/gcore/data</title></head> */ The annoying thing
4962 : // is that what is after ': ' is a subpart of what is after
4963 : // http://server/
4964 5 : char *pszSubDir = strstr(pszLine, ": ");
4965 5 : if (pszSubDir == nullptr)
4966 : // or <title>ortho.linz.govt.nz - /tifs/2005_06/</title>
4967 5 : pszSubDir = strstr(pszLine, "- ");
4968 5 : if (pszSubDir)
4969 : {
4970 0 : pszSubDir += 2;
4971 0 : char *pszTmp = strstr(pszSubDir, "</title>");
4972 0 : if (pszTmp)
4973 : {
4974 0 : if (pszTmp[-1] == '/')
4975 0 : pszTmp[-1] = 0;
4976 : else
4977 0 : *pszTmp = 0;
4978 0 : if (strstr(pszDir, pszSubDir))
4979 : {
4980 0 : bIsHTMLDirList = true;
4981 0 : *pbGotFileList = true;
4982 : }
4983 : }
4984 5 : }
4985 : }
4986 1546 : else if (bIsHTMLDirList &&
4987 35 : (strstr(pszLine, "<a href=\"") != nullptr ||
4988 11 : strstr(pszLine, "<A HREF=\"") != nullptr) &&
4989 : // Exclude absolute links, like to subversion home.
4990 24 : strstr(pszLine, "<a href=\"http://") == nullptr &&
4991 : // exclude parent directory.
4992 24 : strstr(pszLine, "Parent Directory") == nullptr)
4993 : {
4994 23 : char *beginFilename = strstr(pszLine, "<a href=\"");
4995 23 : if (beginFilename == nullptr)
4996 0 : beginFilename = strstr(pszLine, "<A HREF=\"");
4997 23 : beginFilename += strlen("<a href=\"");
4998 23 : char *endQuote = strchr(beginFilename, '"');
4999 23 : if (endQuote && !STARTS_WITH(beginFilename, "?C=") &&
5000 20 : !STARTS_WITH(beginFilename, "?N="))
5001 : {
5002 : struct tm brokendowntime;
5003 20 : memset(&brokendowntime, 0, sizeof(brokendowntime));
5004 20 : GUIntBig nFileSize = 0;
5005 20 : GIntBig mTime = 0;
5006 :
5007 20 : VSICurlParseHTMLDateTimeFileSize(pszLine, brokendowntime,
5008 : nFileSize, mTime);
5009 :
5010 20 : *endQuote = '\0';
5011 :
5012 : // Remove trailing slash, that are returned for directories by
5013 : // Apache.
5014 20 : bool bIsDirectory = false;
5015 20 : if (endQuote[-1] == '/')
5016 : {
5017 3 : bIsDirectory = true;
5018 3 : endQuote[-1] = 0;
5019 : }
5020 :
5021 : // shttpd links include slashes from the root directory.
5022 : // Skip them.
5023 20 : while (strchr(beginFilename, '/'))
5024 0 : beginFilename = strchr(beginFilename, '/') + 1;
5025 :
5026 20 : if (strcmp(beginFilename, ".") != 0 &&
5027 20 : strcmp(beginFilename, "..") != 0)
5028 : {
5029 : std::string osCachedFilename =
5030 17 : CPLSPrintf("%s/%s", osURL.c_str(), beginFilename);
5031 :
5032 17 : FileProp cachedFileProp;
5033 17 : GetCachedFileProp(osCachedFilename.c_str(), cachedFileProp);
5034 17 : cachedFileProp.eExists = EXIST_YES;
5035 17 : cachedFileProp.bIsDirectory = bIsDirectory;
5036 17 : cachedFileProp.mTime = static_cast<time_t>(mTime);
5037 17 : cachedFileProp.bHasComputedFileSize = nFileSize > 0;
5038 17 : cachedFileProp.fileSize = nFileSize;
5039 17 : SetCachedFileProp(osCachedFilename.c_str(), cachedFileProp);
5040 :
5041 17 : oFileList.AddString(beginFilename);
5042 : if constexpr (ENABLE_DEBUG_VERBOSE)
5043 : {
5044 : CPLDebug(
5045 : GetDebugKey(),
5046 : "File[%d] = %s, is_dir = %d, size = " CPL_FRMT_GUIB
5047 : ", time = %04d/%02d/%02d %02d:%02d:%02d",
5048 : nCount, osCachedFilename.c_str(),
5049 : bIsDirectory ? 1 : 0, nFileSize,
5050 : brokendowntime.tm_year + 1900,
5051 : brokendowntime.tm_mon + 1, brokendowntime.tm_mday,
5052 : brokendowntime.tm_hour, brokendowntime.tm_min,
5053 : brokendowntime.tm_sec);
5054 : }
5055 17 : nCount++;
5056 :
5057 17 : if (nMaxFiles > 0 && oFileList.Count() > nMaxFiles)
5058 0 : break;
5059 : }
5060 : }
5061 : }
5062 1555 : pszLine = c + 1;
5063 : }
5064 :
5065 15 : return oFileList.StealList();
5066 : }
5067 :
5068 : /************************************************************************/
5069 : /* GetStreamingFilename() */
5070 : /************************************************************************/
5071 :
5072 6020 : std::string VSICurlFilesystemHandler::GetStreamingFilename(
5073 : const std::string &osFilename) const
5074 : {
5075 6020 : if (STARTS_WITH(osFilename.c_str(), GetFSPrefix().c_str()))
5076 12039 : return "/vsicurl_streaming/" + osFilename.substr(GetFSPrefix().size());
5077 0 : return osFilename;
5078 : }
5079 :
5080 : /************************************************************************/
5081 : /* GetHintForPotentiallyRecognizedPath() */
5082 : /************************************************************************/
5083 :
5084 6022 : std::string VSICurlFilesystemHandler::GetHintForPotentiallyRecognizedPath(
5085 : const std::string &osPath)
5086 : {
5087 12039 : if (!StartsWithVSICurlPrefix(osPath.c_str()) &&
5088 12041 : !cpl::starts_with(osPath, GetStreamingFilename(GetFSPrefix())))
5089 : {
5090 18048 : for (const char *pszPrefix : {"http://", "https://"})
5091 : {
5092 12034 : if (cpl::starts_with(osPath, pszPrefix))
5093 : {
5094 2 : return GetFSPrefix() + osPath;
5095 : }
5096 : }
5097 : }
5098 6025 : return std::string();
5099 : }
5100 :
5101 : /************************************************************************/
5102 : /* VSICurlGetToken() */
5103 : /************************************************************************/
5104 :
5105 0 : static char *VSICurlGetToken(char *pszCurPtr, char **ppszNextToken)
5106 : {
5107 0 : if (pszCurPtr == nullptr)
5108 0 : return nullptr;
5109 :
5110 0 : while ((*pszCurPtr) == ' ')
5111 0 : pszCurPtr++;
5112 0 : if (*pszCurPtr == '\0')
5113 0 : return nullptr;
5114 :
5115 0 : char *pszToken = pszCurPtr;
5116 0 : while ((*pszCurPtr) != ' ' && (*pszCurPtr) != '\0')
5117 0 : pszCurPtr++;
5118 0 : if (*pszCurPtr == '\0')
5119 : {
5120 0 : *ppszNextToken = nullptr;
5121 : }
5122 : else
5123 : {
5124 0 : *pszCurPtr = '\0';
5125 0 : pszCurPtr++;
5126 0 : while ((*pszCurPtr) == ' ')
5127 0 : pszCurPtr++;
5128 0 : *ppszNextToken = pszCurPtr;
5129 : }
5130 :
5131 0 : return pszToken;
5132 : }
5133 :
5134 : /************************************************************************/
5135 : /* VSICurlParseFullFTPLine() */
5136 : /************************************************************************/
5137 :
5138 : /* Parse lines like the following ones :
5139 : -rw-r--r-- 1 10003 100 430 Jul 04 2008 COPYING
5140 : lrwxrwxrwx 1 ftp ftp 28 Jun 14 14:13 MPlayer ->
5141 : mirrors/mplayerhq.hu/MPlayer -rw-r--r-- 1 ftp ftp 725614592 May 13
5142 : 20:13 Fedora-15-x86_64-Live-KDE.iso drwxr-xr-x 280 1003 1003 6656 Aug 26
5143 : 04:17 gnu
5144 : */
5145 :
5146 0 : static bool VSICurlParseFullFTPLine(char *pszLine, char *&pszFilename,
5147 : bool &bSizeValid, GUIntBig &nSize,
5148 : bool &bIsDirectory, GIntBig &nUnixTime)
5149 : {
5150 0 : char *pszNextToken = pszLine;
5151 0 : char *pszPermissions = VSICurlGetToken(pszNextToken, &pszNextToken);
5152 0 : if (pszPermissions == nullptr || strlen(pszPermissions) != 10)
5153 0 : return false;
5154 0 : bIsDirectory = pszPermissions[0] == 'd';
5155 :
5156 0 : for (int i = 0; i < 3; i++)
5157 : {
5158 0 : if (VSICurlGetToken(pszNextToken, &pszNextToken) == nullptr)
5159 0 : return false;
5160 : }
5161 :
5162 0 : char *pszSize = VSICurlGetToken(pszNextToken, &pszNextToken);
5163 0 : if (pszSize == nullptr)
5164 0 : return false;
5165 :
5166 0 : if (pszPermissions[0] == '-')
5167 : {
5168 : // Regular file.
5169 0 : bSizeValid = true;
5170 0 : nSize = CPLScanUIntBig(pszSize, static_cast<int>(strlen(pszSize)));
5171 : }
5172 :
5173 : struct tm brokendowntime;
5174 0 : memset(&brokendowntime, 0, sizeof(brokendowntime));
5175 0 : bool bBrokenDownTimeValid = true;
5176 :
5177 0 : char *pszMonth = VSICurlGetToken(pszNextToken, &pszNextToken);
5178 0 : if (pszMonth == nullptr || strlen(pszMonth) != 3)
5179 0 : return false;
5180 :
5181 0 : int i = 0; // Used after for.
5182 0 : for (; i < 12; i++)
5183 : {
5184 0 : if (EQUALN(pszMonth, apszMonths[i], 3))
5185 0 : break;
5186 : }
5187 0 : if (i < 12)
5188 0 : brokendowntime.tm_mon = i;
5189 : else
5190 0 : bBrokenDownTimeValid = false;
5191 :
5192 0 : char *pszDay = VSICurlGetToken(pszNextToken, &pszNextToken);
5193 0 : if (pszDay == nullptr || (strlen(pszDay) != 1 && strlen(pszDay) != 2))
5194 0 : return false;
5195 0 : int nDay = atoi(pszDay);
5196 0 : if (nDay >= 1 && nDay <= 31)
5197 0 : brokendowntime.tm_mday = nDay;
5198 : else
5199 0 : bBrokenDownTimeValid = false;
5200 :
5201 0 : char *pszHourOrYear = VSICurlGetToken(pszNextToken, &pszNextToken);
5202 0 : if (pszHourOrYear == nullptr ||
5203 0 : (strlen(pszHourOrYear) != 4 && strlen(pszHourOrYear) != 5))
5204 0 : return false;
5205 0 : if (strlen(pszHourOrYear) == 4)
5206 : {
5207 0 : brokendowntime.tm_year = atoi(pszHourOrYear) - 1900;
5208 : }
5209 : else
5210 : {
5211 : time_t sTime;
5212 0 : time(&sTime);
5213 : struct tm currentBrokendowntime;
5214 0 : CPLUnixTimeToYMDHMS(static_cast<GIntBig>(sTime),
5215 : ¤tBrokendowntime);
5216 0 : brokendowntime.tm_year = currentBrokendowntime.tm_year;
5217 0 : brokendowntime.tm_hour = atoi(pszHourOrYear);
5218 0 : brokendowntime.tm_min = atoi(pszHourOrYear + 3);
5219 : }
5220 :
5221 0 : if (bBrokenDownTimeValid)
5222 0 : nUnixTime = CPLYMDHMSToUnixTime(&brokendowntime);
5223 : else
5224 0 : nUnixTime = 0;
5225 :
5226 0 : if (pszNextToken == nullptr)
5227 0 : return false;
5228 :
5229 0 : pszFilename = pszNextToken;
5230 :
5231 0 : char *pszCurPtr = pszFilename;
5232 0 : while (*pszCurPtr != '\0')
5233 : {
5234 : // In case of a link, stop before the pointed part of the link.
5235 0 : if (pszPermissions[0] == 'l' && STARTS_WITH(pszCurPtr, " -> "))
5236 : {
5237 0 : break;
5238 : }
5239 0 : pszCurPtr++;
5240 : }
5241 0 : *pszCurPtr = '\0';
5242 :
5243 0 : return true;
5244 : }
5245 :
5246 : /************************************************************************/
5247 : /* GetURLFromFilename() */
5248 : /************************************************************************/
5249 :
5250 108 : std::string VSICurlFilesystemHandlerBase::GetURLFromFilename(
5251 : const std::string &osFilename) const
5252 : {
5253 : return VSICurlGetURLFromFilename(osFilename.c_str(), nullptr, nullptr,
5254 : nullptr, nullptr, nullptr, nullptr,
5255 108 : nullptr, nullptr);
5256 : }
5257 :
5258 : /************************************************************************/
5259 : /* RegisterEmptyDir() */
5260 : /************************************************************************/
5261 :
5262 14 : void VSICurlFilesystemHandlerBase::RegisterEmptyDir(
5263 : const std::string &osDirname)
5264 : {
5265 28 : CachedDirList cachedDirList;
5266 14 : cachedDirList.bGotFileList = true;
5267 14 : cachedDirList.oFileList.AddString(".");
5268 14 : SetCachedDirList(osDirname.c_str(), cachedDirList);
5269 14 : }
5270 :
5271 : /************************************************************************/
5272 : /* GetFileList() */
5273 : /************************************************************************/
5274 :
5275 47 : char **VSICurlFilesystemHandlerBase::GetFileList(const char *pszDirname,
5276 : int nMaxFiles,
5277 : bool *pbGotFileList)
5278 : {
5279 : if constexpr (ENABLE_DEBUG)
5280 : {
5281 47 : CPLDebug(GetDebugKey(), "GetFileList(%s)", pszDirname);
5282 : }
5283 :
5284 47 : *pbGotFileList = false;
5285 :
5286 47 : bool bListDir = true;
5287 47 : bool bEmptyDir = false;
5288 : std::string osURL(VSICurlGetURLFromFilename(pszDirname, nullptr, nullptr,
5289 : nullptr, &bListDir, &bEmptyDir,
5290 94 : nullptr, nullptr, nullptr));
5291 47 : if (bEmptyDir)
5292 : {
5293 1 : *pbGotFileList = true;
5294 1 : return CSLAddString(nullptr, ".");
5295 : }
5296 46 : if (!bListDir)
5297 0 : return nullptr;
5298 :
5299 : // Deal with publicly visible Azure directories.
5300 46 : if (STARTS_WITH(osURL.c_str(), "https://"))
5301 : {
5302 : const char *pszBlobCore =
5303 7 : strstr(osURL.c_str(), ".blob.core.windows.net/");
5304 7 : if (pszBlobCore)
5305 : {
5306 1 : FileProp cachedFileProp;
5307 1 : GetCachedFileProp(osURL.c_str(), cachedFileProp);
5308 1 : if (cachedFileProp.bIsAzureFolder)
5309 : {
5310 : const char *pszURLWithoutHTTPS =
5311 0 : osURL.c_str() + strlen("https://");
5312 : const std::string osStorageAccount(
5313 0 : pszURLWithoutHTTPS, pszBlobCore - pszURLWithoutHTTPS);
5314 : CPLConfigOptionSetter oSetter1("AZURE_NO_SIGN_REQUEST", "YES",
5315 0 : false);
5316 : CPLConfigOptionSetter oSetter2("AZURE_STORAGE_ACCOUNT",
5317 0 : osStorageAccount.c_str(), false);
5318 0 : const std::string osVSIAZ(std::string("/vsiaz/").append(
5319 0 : pszBlobCore + strlen(".blob.core.windows.net/")));
5320 0 : char **papszFileList = VSIReadDirEx(osVSIAZ.c_str(), nMaxFiles);
5321 0 : if (papszFileList)
5322 : {
5323 0 : *pbGotFileList = true;
5324 0 : return papszFileList;
5325 : }
5326 : }
5327 : }
5328 : }
5329 :
5330 : // HACK (optimization in fact) for MBTiles driver.
5331 46 : if (strstr(pszDirname, ".tiles.mapbox.com") != nullptr)
5332 1 : return nullptr;
5333 :
5334 45 : if (STARTS_WITH(osURL.c_str(), "ftp://"))
5335 : {
5336 0 : WriteFuncStruct sWriteFuncData;
5337 0 : sWriteFuncData.pBuffer = nullptr;
5338 :
5339 0 : std::string osDirname(osURL);
5340 0 : osDirname += '/';
5341 :
5342 0 : char **papszFileList = nullptr;
5343 :
5344 0 : CURLM *hCurlMultiHandle = GetCurlMultiHandleFor(osDirname);
5345 0 : CURL *hCurlHandle = curl_easy_init();
5346 :
5347 0 : for (int iTry = 0; iTry < 2; iTry++)
5348 : {
5349 : struct curl_slist *headers =
5350 0 : VSICurlSetOptions(hCurlHandle, osDirname.c_str(), nullptr);
5351 :
5352 : // On the first pass, we want to try fetching all the possible
5353 : // information (filename, file/directory, size). If that does not
5354 : // work, then try again with CURLOPT_DIRLISTONLY set.
5355 0 : if (iTry == 1)
5356 : {
5357 0 : unchecked_curl_easy_setopt(hCurlHandle, CURLOPT_DIRLISTONLY, 1);
5358 : }
5359 :
5360 0 : VSICURLInitWriteFuncStruct(&sWriteFuncData, nullptr, nullptr,
5361 : nullptr);
5362 0 : unchecked_curl_easy_setopt(hCurlHandle, CURLOPT_WRITEDATA,
5363 : &sWriteFuncData);
5364 0 : unchecked_curl_easy_setopt(hCurlHandle, CURLOPT_WRITEFUNCTION,
5365 : VSICurlHandleWriteFunc);
5366 :
5367 0 : char szCurlErrBuf[CURL_ERROR_SIZE + 1] = {};
5368 0 : unchecked_curl_easy_setopt(hCurlHandle, CURLOPT_ERRORBUFFER,
5369 : szCurlErrBuf);
5370 :
5371 0 : unchecked_curl_easy_setopt(hCurlHandle, CURLOPT_HTTPHEADER,
5372 : headers);
5373 :
5374 0 : VSICURLMultiPerform(hCurlMultiHandle, hCurlHandle);
5375 :
5376 0 : curl_slist_free_all(headers);
5377 :
5378 0 : if (sWriteFuncData.pBuffer == nullptr)
5379 : {
5380 0 : curl_easy_cleanup(hCurlHandle);
5381 0 : return nullptr;
5382 : }
5383 :
5384 0 : char *pszLine = sWriteFuncData.pBuffer;
5385 0 : char *c = nullptr;
5386 0 : int nCount = 0;
5387 :
5388 0 : if (STARTS_WITH_CI(pszLine, "<!DOCTYPE HTML") ||
5389 0 : STARTS_WITH_CI(pszLine, "<HTML>"))
5390 : {
5391 : papszFileList =
5392 0 : ParseHTMLFileList(pszDirname, nMaxFiles,
5393 : sWriteFuncData.pBuffer, pbGotFileList);
5394 0 : break;
5395 : }
5396 0 : else if (iTry == 0)
5397 : {
5398 0 : CPLStringList oFileList;
5399 0 : *pbGotFileList = true;
5400 :
5401 0 : while ((c = strchr(pszLine, '\n')) != nullptr)
5402 : {
5403 0 : *c = 0;
5404 0 : if (c - pszLine > 0 && c[-1] == '\r')
5405 0 : c[-1] = 0;
5406 :
5407 0 : char *pszFilename = nullptr;
5408 0 : bool bSizeValid = false;
5409 0 : GUIntBig nFileSize = 0;
5410 0 : bool bIsDirectory = false;
5411 0 : GIntBig mUnixTime = 0;
5412 0 : if (!VSICurlParseFullFTPLine(pszLine, pszFilename,
5413 : bSizeValid, nFileSize,
5414 : bIsDirectory, mUnixTime))
5415 0 : break;
5416 :
5417 0 : if (strcmp(pszFilename, ".") != 0 &&
5418 0 : strcmp(pszFilename, "..") != 0)
5419 : {
5420 0 : if (CPLHasUnbalancedPathTraversal(pszFilename))
5421 : {
5422 0 : CPLError(CE_Warning, CPLE_AppDefined,
5423 : "Ignoring '%s' that has a path traversal "
5424 : "pattern",
5425 : pszFilename);
5426 : }
5427 : else
5428 : {
5429 : std::string osCachedFilename =
5430 0 : CPLSPrintf("%s/%s", osURL.c_str(), pszFilename);
5431 :
5432 0 : FileProp cachedFileProp;
5433 0 : GetCachedFileProp(osCachedFilename.c_str(),
5434 : cachedFileProp);
5435 0 : cachedFileProp.eExists = EXIST_YES;
5436 0 : cachedFileProp.bIsDirectory = bIsDirectory;
5437 0 : cachedFileProp.mTime =
5438 : static_cast<time_t>(mUnixTime);
5439 0 : cachedFileProp.bHasComputedFileSize = bSizeValid;
5440 0 : cachedFileProp.fileSize = nFileSize;
5441 0 : SetCachedFileProp(osCachedFilename.c_str(),
5442 : cachedFileProp);
5443 :
5444 0 : oFileList.AddString(pszFilename);
5445 : if constexpr (ENABLE_DEBUG_VERBOSE)
5446 : {
5447 : struct tm brokendowntime;
5448 : CPLUnixTimeToYMDHMS(mUnixTime, &brokendowntime);
5449 : CPLDebug(
5450 : GetDebugKey(),
5451 : "File[%d] = %s, is_dir = %d, size "
5452 : "= " CPL_FRMT_GUIB
5453 : ", time = %04d/%02d/%02d %02d:%02d:%02d",
5454 : nCount, pszFilename, bIsDirectory ? 1 : 0,
5455 : nFileSize, brokendowntime.tm_year + 1900,
5456 : brokendowntime.tm_mon + 1,
5457 : brokendowntime.tm_mday,
5458 : brokendowntime.tm_hour,
5459 : brokendowntime.tm_min,
5460 : brokendowntime.tm_sec);
5461 : }
5462 :
5463 0 : nCount++;
5464 :
5465 0 : if (nMaxFiles > 0 && oFileList.Count() > nMaxFiles)
5466 0 : break;
5467 : }
5468 : }
5469 :
5470 0 : pszLine = c + 1;
5471 : }
5472 :
5473 0 : if (c == nullptr)
5474 : {
5475 0 : papszFileList = oFileList.StealList();
5476 0 : break;
5477 : }
5478 : }
5479 : else
5480 : {
5481 0 : CPLStringList oFileList;
5482 0 : *pbGotFileList = true;
5483 :
5484 0 : while ((c = strchr(pszLine, '\n')) != nullptr)
5485 : {
5486 0 : *c = 0;
5487 0 : if (c - pszLine > 0 && c[-1] == '\r')
5488 0 : c[-1] = 0;
5489 :
5490 0 : if (strcmp(pszLine, ".") != 0 && strcmp(pszLine, "..") != 0)
5491 : {
5492 0 : oFileList.AddString(pszLine);
5493 : if constexpr (ENABLE_DEBUG_VERBOSE)
5494 : {
5495 : CPLDebug(GetDebugKey(), "File[%d] = %s", nCount,
5496 : pszLine);
5497 : }
5498 0 : nCount++;
5499 : }
5500 :
5501 0 : pszLine = c + 1;
5502 : }
5503 :
5504 0 : papszFileList = oFileList.StealList();
5505 : }
5506 :
5507 0 : CPLFree(sWriteFuncData.pBuffer);
5508 0 : sWriteFuncData.pBuffer = nullptr;
5509 : }
5510 :
5511 0 : CPLFree(sWriteFuncData.pBuffer);
5512 0 : curl_easy_cleanup(hCurlHandle);
5513 :
5514 0 : return papszFileList;
5515 : }
5516 :
5517 : // Try to recognize HTML pages that list the content of a directory.
5518 : // Currently this supports what Apache and shttpd can return.
5519 52 : else if (STARTS_WITH(osURL.c_str(), "http://") ||
5520 7 : STARTS_WITH(osURL.c_str(), "https://"))
5521 : {
5522 90 : std::string osDirname(std::move(osURL));
5523 45 : osDirname += '/';
5524 :
5525 45 : CURLM *hCurlMultiHandle = GetCurlMultiHandleFor(osDirname);
5526 45 : CURL *hCurlHandle = curl_easy_init();
5527 :
5528 : struct curl_slist *headers =
5529 45 : VSICurlSetOptions(hCurlHandle, osDirname.c_str(), nullptr);
5530 :
5531 45 : unchecked_curl_easy_setopt(hCurlHandle, CURLOPT_RANGE, nullptr);
5532 :
5533 45 : WriteFuncStruct sWriteFuncData;
5534 45 : VSICURLInitWriteFuncStruct(&sWriteFuncData, nullptr, nullptr, nullptr);
5535 45 : unchecked_curl_easy_setopt(hCurlHandle, CURLOPT_WRITEDATA,
5536 : &sWriteFuncData);
5537 45 : unchecked_curl_easy_setopt(hCurlHandle, CURLOPT_WRITEFUNCTION,
5538 : VSICurlHandleWriteFunc);
5539 :
5540 45 : char szCurlErrBuf[CURL_ERROR_SIZE + 1] = {};
5541 45 : unchecked_curl_easy_setopt(hCurlHandle, CURLOPT_ERRORBUFFER,
5542 : szCurlErrBuf);
5543 :
5544 45 : unchecked_curl_easy_setopt(hCurlHandle, CURLOPT_HTTPHEADER, headers);
5545 :
5546 45 : VSICURLMultiPerform(hCurlMultiHandle, hCurlHandle);
5547 :
5548 45 : curl_slist_free_all(headers);
5549 :
5550 45 : NetworkStatisticsLogger::LogGET(sWriteFuncData.nSize);
5551 :
5552 45 : if (sWriteFuncData.pBuffer == nullptr)
5553 : {
5554 30 : curl_easy_cleanup(hCurlHandle);
5555 30 : return nullptr;
5556 : }
5557 :
5558 15 : char **papszFileList = nullptr;
5559 15 : if (STARTS_WITH_CI(sWriteFuncData.pBuffer, "<?xml") &&
5560 1 : strstr(sWriteFuncData.pBuffer, "<ListBucketResult") != nullptr)
5561 : {
5562 0 : CPLStringList osFileList;
5563 0 : std::string osBaseURL(pszDirname);
5564 0 : osBaseURL += "/";
5565 0 : bool bIsTruncated = true;
5566 0 : bool ret = AnalyseS3FileList(
5567 0 : osBaseURL, sWriteFuncData.pBuffer, osFileList, nMaxFiles,
5568 0 : GetS3IgnoredStorageClasses(), bIsTruncated);
5569 : // If the list is truncated, then don't report it.
5570 0 : if (ret && !bIsTruncated)
5571 : {
5572 0 : if (osFileList.empty())
5573 : {
5574 : // To avoid an error to be reported
5575 0 : osFileList.AddString(".");
5576 : }
5577 0 : papszFileList = osFileList.StealList();
5578 0 : *pbGotFileList = true;
5579 0 : }
5580 : }
5581 : else
5582 : {
5583 15 : papszFileList = ParseHTMLFileList(
5584 : pszDirname, nMaxFiles, sWriteFuncData.pBuffer, pbGotFileList);
5585 : }
5586 :
5587 15 : CPLFree(sWriteFuncData.pBuffer);
5588 15 : curl_easy_cleanup(hCurlHandle);
5589 15 : return papszFileList;
5590 : }
5591 :
5592 0 : return nullptr;
5593 : }
5594 :
5595 : /************************************************************************/
5596 : /* GetS3IgnoredStorageClasses() */
5597 : /************************************************************************/
5598 :
5599 65 : std::set<std::string> VSICurlFilesystemHandlerBase::GetS3IgnoredStorageClasses()
5600 : {
5601 65 : std::set<std::string> oSetIgnoredStorageClasses;
5602 : const char *pszIgnoredStorageClasses =
5603 65 : CPLGetConfigOption("CPL_VSIL_CURL_IGNORE_STORAGE_CLASSES", nullptr);
5604 : const char *pszIgnoreGlacierStorage =
5605 65 : CPLGetConfigOption("CPL_VSIL_CURL_IGNORE_GLACIER_STORAGE", nullptr);
5606 : CPLStringList aosIgnoredStorageClasses(
5607 : CSLTokenizeString2(pszIgnoredStorageClasses ? pszIgnoredStorageClasses
5608 : : "GLACIER,DEEP_ARCHIVE",
5609 130 : ",", 0));
5610 193 : for (int i = 0; i < aosIgnoredStorageClasses.size(); ++i)
5611 128 : oSetIgnoredStorageClasses.insert(aosIgnoredStorageClasses[i]);
5612 64 : if (pszIgnoredStorageClasses == nullptr &&
5613 129 : pszIgnoreGlacierStorage != nullptr &&
5614 1 : !CPLTestBool(pszIgnoreGlacierStorage))
5615 : {
5616 1 : oSetIgnoredStorageClasses.clear();
5617 : }
5618 130 : return oSetIgnoredStorageClasses;
5619 : }
5620 :
5621 : /************************************************************************/
5622 : /* Stat() */
5623 : /************************************************************************/
5624 :
5625 1073 : int VSICurlFilesystemHandlerBase::Stat(const char *pszFilename,
5626 : VSIStatBufL *pStatBuf, int nFlags)
5627 : {
5628 1131 : if (!cpl::starts_with(std::string_view(pszFilename), GetFSPrefix()) &&
5629 58 : !StartsWithVSICurlPrefix(pszFilename))
5630 : {
5631 1 : return -1;
5632 : }
5633 :
5634 1072 : memset(pStatBuf, 0, sizeof(VSIStatBufL));
5635 :
5636 1072 : if ((nFlags & VSI_STAT_CACHE_ONLY) != 0)
5637 : {
5638 18 : cpl::FileProp oFileProp;
5639 27 : if (!GetCachedFileProp(GetURLFromFilename(pszFilename).c_str(),
5640 32 : oFileProp) ||
5641 5 : oFileProp.eExists != EXIST_YES)
5642 : {
5643 4 : return -1;
5644 : }
5645 5 : pStatBuf->st_mode = static_cast<unsigned short>(oFileProp.nMode);
5646 5 : pStatBuf->st_mtime = oFileProp.mTime;
5647 5 : pStatBuf->st_size = oFileProp.fileSize;
5648 5 : return 0;
5649 : }
5650 :
5651 2126 : NetworkStatisticsFileSystem oContextFS(GetFSPrefix().c_str());
5652 2126 : NetworkStatisticsAction oContextAction("Stat");
5653 :
5654 2126 : const std::string osFilename(pszFilename);
5655 :
5656 1063 : if (!IsAllowedFilename(pszFilename))
5657 0 : return -1;
5658 :
5659 1063 : bool bListDir = true;
5660 1063 : bool bEmptyDir = false;
5661 : std::string osURL(VSICurlGetURLFromFilename(pszFilename, nullptr, nullptr,
5662 : nullptr, &bListDir, &bEmptyDir,
5663 2126 : nullptr, nullptr, nullptr));
5664 :
5665 1063 : const char *pszOptionVal = VSIGetPathSpecificOption(
5666 : pszFilename, "GDAL_DISABLE_READDIR_ON_OPEN", "NO");
5667 : const bool bSkipReadDir =
5668 1063 : !bListDir || bEmptyDir || EQUAL(pszOptionVal, "EMPTY_DIR") ||
5669 2126 : CPLTestBool(pszOptionVal) || !AllowCachedDataFor(pszFilename);
5670 :
5671 : // Does it look like a FTP directory?
5672 1063 : if (STARTS_WITH(osURL.c_str(), "ftp://") && osFilename.back() == '/' &&
5673 0 : !bSkipReadDir)
5674 : {
5675 0 : char **papszFileList = ReadDirEx(osFilename.c_str(), 0);
5676 0 : if (papszFileList)
5677 : {
5678 0 : pStatBuf->st_mode = S_IFDIR;
5679 0 : pStatBuf->st_size = 0;
5680 :
5681 0 : CSLDestroy(papszFileList);
5682 :
5683 0 : return 0;
5684 : }
5685 0 : return -1;
5686 : }
5687 1063 : else if (strchr(CPLGetFilename(osFilename.c_str()), '.') != nullptr &&
5688 2026 : !STARTS_WITH_CI(CPLGetExtensionSafe(osFilename.c_str()).c_str(),
5689 480 : "zip") &&
5690 480 : strstr(osFilename.c_str(), ".zip.") != nullptr &&
5691 3089 : strstr(osFilename.c_str(), ".ZIP.") != nullptr && !bSkipReadDir)
5692 : {
5693 0 : bool bGotFileList = false;
5694 0 : char **papszFileList = ReadDirInternal(
5695 0 : CPLGetDirnameSafe(osFilename.c_str()).c_str(), 0, &bGotFileList);
5696 : const bool bFound =
5697 0 : VSICurlIsFileInList(papszFileList,
5698 0 : CPLGetFilename(osFilename.c_str())) != -1;
5699 0 : CSLDestroy(papszFileList);
5700 0 : if (bGotFileList && !bFound)
5701 : {
5702 0 : return -1;
5703 : }
5704 : }
5705 :
5706 1063 : VSICurlHandle *poHandle = CreateFileHandle(osFilename.c_str());
5707 1063 : if (poHandle == nullptr)
5708 22 : return -1;
5709 :
5710 1385 : if (poHandle->IsKnownFileSize() ||
5711 344 : ((nFlags & VSI_STAT_SIZE_FLAG) && !poHandle->IsDirectory() &&
5712 183 : CPLTestBool(CPLGetConfigOption("CPL_VSIL_CURL_SLOW_GET_SIZE", "YES"))))
5713 : {
5714 880 : pStatBuf->st_size = poHandle->GetFileSize(true);
5715 : }
5716 :
5717 : const int nRet =
5718 1041 : poHandle->Exists((nFlags & VSI_STAT_SET_ERROR_FLAG) > 0) ? 0 : -1;
5719 1041 : pStatBuf->st_mtime = poHandle->GetMTime();
5720 1041 : pStatBuf->st_mode = static_cast<unsigned short>(poHandle->GetMode());
5721 1041 : if (pStatBuf->st_mode == 0)
5722 1005 : pStatBuf->st_mode = poHandle->IsDirectory() ? S_IFDIR : S_IFREG;
5723 1041 : delete poHandle;
5724 1041 : return nRet;
5725 : }
5726 :
5727 : /************************************************************************/
5728 : /* ReadDirInternal() */
5729 : /************************************************************************/
5730 :
5731 293 : char **VSICurlFilesystemHandlerBase::ReadDirInternal(const char *pszDirname,
5732 : int nMaxFiles,
5733 : bool *pbGotFileList)
5734 : {
5735 586 : std::string osDirname(pszDirname);
5736 :
5737 : // Replace a/b/../c by a/c
5738 293 : const auto posSlashDotDot = osDirname.find("/..");
5739 293 : if (posSlashDotDot != std::string::npos && posSlashDotDot >= 1)
5740 : {
5741 : const auto posPrecedingSlash =
5742 0 : osDirname.find_last_of('/', posSlashDotDot - 1);
5743 0 : if (posPrecedingSlash != std::string::npos && posPrecedingSlash >= 1)
5744 : {
5745 0 : osDirname.erase(osDirname.begin() + posPrecedingSlash,
5746 0 : osDirname.begin() + posSlashDotDot + strlen("/.."));
5747 : }
5748 : }
5749 :
5750 586 : std::string osDirnameOri(osDirname);
5751 293 : if (osDirname + "/" == GetFSPrefix())
5752 : {
5753 0 : osDirname += "/";
5754 : }
5755 293 : else if (osDirname != GetFSPrefix())
5756 : {
5757 452 : while (!osDirname.empty() && osDirname.back() == '/')
5758 176 : osDirname.erase(osDirname.size() - 1);
5759 : }
5760 :
5761 293 : if (osDirname.size() < GetFSPrefix().size())
5762 : {
5763 0 : if (pbGotFileList)
5764 0 : *pbGotFileList = true;
5765 0 : return nullptr;
5766 : }
5767 :
5768 586 : NetworkStatisticsFileSystem oContextFS(GetFSPrefix().c_str());
5769 586 : NetworkStatisticsAction oContextAction("ReadDir");
5770 :
5771 586 : CPLMutexHolder oHolder(&hMutex);
5772 :
5773 : // If we know the file exists and is not a directory,
5774 : // then don't try to list its content.
5775 586 : FileProp cachedFileProp;
5776 879 : if (GetCachedFileProp(GetURLFromFilename(osDirname.c_str()).c_str(),
5777 51 : cachedFileProp) &&
5778 879 : cachedFileProp.eExists == EXIST_YES && !cachedFileProp.bIsDirectory)
5779 : {
5780 8 : if (osDirnameOri != osDirname)
5781 : {
5782 3 : if (GetCachedFileProp((GetURLFromFilename(osDirname) + "/").c_str(),
5783 1 : cachedFileProp) &&
5784 4 : cachedFileProp.eExists == EXIST_YES &&
5785 1 : !cachedFileProp.bIsDirectory)
5786 : {
5787 0 : if (pbGotFileList)
5788 0 : *pbGotFileList = true;
5789 0 : return nullptr;
5790 : }
5791 : }
5792 : else
5793 : {
5794 7 : if (pbGotFileList)
5795 0 : *pbGotFileList = true;
5796 7 : return nullptr;
5797 : }
5798 : }
5799 :
5800 572 : CachedDirList cachedDirList;
5801 286 : if (!GetCachedDirList(osDirname.c_str(), cachedDirList))
5802 : {
5803 : cachedDirList.oFileList.Assign(GetFileList(osDirname.c_str(), nMaxFiles,
5804 172 : &cachedDirList.bGotFileList),
5805 172 : true);
5806 172 : if (cachedDirList.bGotFileList && cachedDirList.oFileList.empty())
5807 : {
5808 : // To avoid an error to be reported
5809 18 : cachedDirList.oFileList.AddString(".");
5810 : }
5811 172 : if (nMaxFiles <= 0 || cachedDirList.oFileList.size() < nMaxFiles)
5812 : {
5813 : // Only cache content if we didn't hit the limitation
5814 167 : SetCachedDirList(osDirname.c_str(), cachedDirList);
5815 : }
5816 : }
5817 :
5818 286 : if (pbGotFileList)
5819 147 : *pbGotFileList = cachedDirList.bGotFileList;
5820 :
5821 286 : return CSLDuplicate(cachedDirList.oFileList.List());
5822 : }
5823 :
5824 : /************************************************************************/
5825 : /* InvalidateDirContent() */
5826 : /************************************************************************/
5827 :
5828 199 : void VSICurlFilesystemHandlerBase::InvalidateDirContent(
5829 : const std::string &osDirname)
5830 : {
5831 398 : CPLMutexHolder oHolder(&hMutex);
5832 :
5833 398 : CachedDirList oCachedDirList;
5834 199 : if (oCacheDirList.tryGet(osDirname, oCachedDirList))
5835 : {
5836 19 : nCachedFilesInDirList -= oCachedDirList.oFileList.size();
5837 19 : oCacheDirList.remove(osDirname);
5838 : }
5839 199 : }
5840 :
5841 : /************************************************************************/
5842 : /* ReadDirEx() */
5843 : /************************************************************************/
5844 :
5845 88 : char **VSICurlFilesystemHandlerBase::ReadDirEx(const char *pszDirname,
5846 : int nMaxFiles)
5847 : {
5848 88 : return ReadDirInternal(pszDirname, nMaxFiles, nullptr);
5849 : }
5850 :
5851 : /************************************************************************/
5852 : /* SiblingFiles() */
5853 : /************************************************************************/
5854 :
5855 50 : char **VSICurlFilesystemHandlerBase::SiblingFiles(const char *pszFilename)
5856 : {
5857 : /* Small optimization to avoid unnecessary stat'ing from PAux or ENVI */
5858 : /* drivers. The MBTiles driver needs no companion file. */
5859 50 : if (EQUAL(CPLGetExtensionSafe(pszFilename).c_str(), "mbtiles"))
5860 : {
5861 6 : return static_cast<char **>(CPLCalloc(1, sizeof(char *)));
5862 : }
5863 44 : return nullptr;
5864 : }
5865 :
5866 : /************************************************************************/
5867 : /* GetFileMetadata() */
5868 : /************************************************************************/
5869 :
5870 7 : char **VSICurlFilesystemHandlerBase::GetFileMetadata(const char *pszFilename,
5871 : const char *pszDomain,
5872 : CSLConstList)
5873 : {
5874 7 : if (pszDomain == nullptr || !EQUAL(pszDomain, "HEADERS"))
5875 3 : return nullptr;
5876 8 : std::unique_ptr<VSICurlHandle> poHandle(CreateFileHandle(pszFilename));
5877 4 : if (poHandle == nullptr)
5878 0 : return nullptr;
5879 :
5880 8 : NetworkStatisticsFileSystem oContextFS(GetFSPrefix().c_str());
5881 8 : NetworkStatisticsAction oContextAction("GetFileMetadata");
5882 :
5883 4 : poHandle->GetFileSizeOrHeaders(true, true);
5884 4 : return CSLDuplicate(poHandle->GetHeaders().List());
5885 : }
5886 :
5887 : /************************************************************************/
5888 : /* VSIAppendWriteHandle() */
5889 : /************************************************************************/
5890 :
5891 17 : VSIAppendWriteHandle::VSIAppendWriteHandle(VSICurlFilesystemHandlerBase *poFS,
5892 : const char *pszFSPrefix,
5893 : const char *pszFilename,
5894 17 : int nChunkSize)
5895 : : m_poFS(poFS), m_osFSPrefix(pszFSPrefix), m_osFilename(pszFilename),
5896 34 : m_oRetryParameters(CPLStringList(CPLHTTPGetOptionsFromEnv(pszFilename))),
5897 34 : m_nBufferSize(nChunkSize)
5898 : {
5899 17 : m_pabyBuffer = static_cast<GByte *>(VSIMalloc(m_nBufferSize));
5900 17 : if (m_pabyBuffer == nullptr)
5901 : {
5902 0 : CPLError(CE_Failure, CPLE_AppDefined,
5903 : "Cannot allocate working buffer for %s writing",
5904 : m_osFSPrefix.c_str());
5905 : }
5906 17 : }
5907 :
5908 : /************************************************************************/
5909 : /* ~VSIAppendWriteHandle() */
5910 : /************************************************************************/
5911 :
5912 17 : VSIAppendWriteHandle::~VSIAppendWriteHandle()
5913 : {
5914 : /* WARNING: implementation should call Close() themselves */
5915 : /* cannot be done safely from here, since Send() can be called. */
5916 17 : CPLFree(m_pabyBuffer);
5917 17 : }
5918 :
5919 : /************************************************************************/
5920 : /* Seek() */
5921 : /************************************************************************/
5922 :
5923 0 : int VSIAppendWriteHandle::Seek(vsi_l_offset nOffset, int nWhence)
5924 : {
5925 0 : if (!((nWhence == SEEK_SET && nOffset == m_nCurOffset) ||
5926 0 : (nWhence == SEEK_CUR && nOffset == 0) ||
5927 0 : (nWhence == SEEK_END && nOffset == 0)))
5928 : {
5929 0 : CPLError(CE_Failure, CPLE_NotSupported,
5930 : "Seek not supported on writable %s files",
5931 : m_osFSPrefix.c_str());
5932 0 : m_bError = true;
5933 0 : return -1;
5934 : }
5935 0 : return 0;
5936 : }
5937 :
5938 : /************************************************************************/
5939 : /* Tell() */
5940 : /************************************************************************/
5941 :
5942 0 : vsi_l_offset VSIAppendWriteHandle::Tell()
5943 : {
5944 0 : return m_nCurOffset;
5945 : }
5946 :
5947 : /************************************************************************/
5948 : /* Read() */
5949 : /************************************************************************/
5950 :
5951 0 : size_t VSIAppendWriteHandle::Read(void * /* pBuffer */, size_t /* nBytes */)
5952 : {
5953 0 : CPLError(CE_Failure, CPLE_NotSupported,
5954 : "Read not supported on writable %s files", m_osFSPrefix.c_str());
5955 0 : m_bError = true;
5956 0 : return 0;
5957 : }
5958 :
5959 : /************************************************************************/
5960 : /* ReadCallBackBuffer() */
5961 : /************************************************************************/
5962 :
5963 1 : size_t VSIAppendWriteHandle::ReadCallBackBuffer(char *buffer, size_t size,
5964 : size_t nitems, void *instream)
5965 : {
5966 1 : VSIAppendWriteHandle *poThis =
5967 : static_cast<VSIAppendWriteHandle *>(instream);
5968 1 : const int nSizeMax = static_cast<int>(size * nitems);
5969 : const int nSizeToWrite = std::min(
5970 1 : nSizeMax, poThis->m_nBufferOff - poThis->m_nBufferOffReadCallback);
5971 1 : memcpy(buffer, poThis->m_pabyBuffer + poThis->m_nBufferOffReadCallback,
5972 : nSizeToWrite);
5973 1 : poThis->m_nBufferOffReadCallback += nSizeToWrite;
5974 1 : return nSizeToWrite;
5975 : }
5976 :
5977 : /************************************************************************/
5978 : /* Write() */
5979 : /************************************************************************/
5980 :
5981 9 : size_t VSIAppendWriteHandle::Write(const void *pBuffer, size_t nBytes)
5982 : {
5983 9 : if (m_bError)
5984 0 : return 0;
5985 :
5986 9 : size_t nBytesToWrite = nBytes;
5987 9 : if (nBytesToWrite == 0)
5988 0 : return 0;
5989 :
5990 9 : const GByte *pabySrcBuffer = reinterpret_cast<const GByte *>(pBuffer);
5991 21 : while (nBytesToWrite > 0)
5992 : {
5993 12 : if (m_nBufferOff == m_nBufferSize)
5994 : {
5995 3 : if (!Send(false))
5996 : {
5997 0 : m_bError = true;
5998 0 : return 0;
5999 : }
6000 3 : m_nBufferOff = 0;
6001 : }
6002 :
6003 12 : const int nToWriteInBuffer = static_cast<int>(std::min(
6004 12 : static_cast<size_t>(m_nBufferSize - m_nBufferOff), nBytesToWrite));
6005 12 : memcpy(m_pabyBuffer + m_nBufferOff, pabySrcBuffer, nToWriteInBuffer);
6006 12 : pabySrcBuffer += nToWriteInBuffer;
6007 12 : m_nBufferOff += nToWriteInBuffer;
6008 12 : m_nCurOffset += nToWriteInBuffer;
6009 12 : nBytesToWrite -= nToWriteInBuffer;
6010 : }
6011 9 : return nBytes;
6012 : }
6013 :
6014 : /************************************************************************/
6015 : /* Close() */
6016 : /************************************************************************/
6017 :
6018 30 : int VSIAppendWriteHandle::Close()
6019 : {
6020 30 : int nRet = 0;
6021 30 : if (!m_bClosed)
6022 : {
6023 17 : m_bClosed = true;
6024 17 : if (!m_bError && !Send(true))
6025 4 : nRet = -1;
6026 : }
6027 30 : return nRet;
6028 : }
6029 :
6030 : /************************************************************************/
6031 : /* CurlRequestHelper() */
6032 : /************************************************************************/
6033 :
6034 383 : CurlRequestHelper::CurlRequestHelper()
6035 : {
6036 383 : VSICURLInitWriteFuncStruct(&sWriteFuncData, nullptr, nullptr, nullptr);
6037 383 : VSICURLInitWriteFuncStruct(&sWriteFuncHeaderData, nullptr, nullptr,
6038 : nullptr);
6039 383 : }
6040 :
6041 : /************************************************************************/
6042 : /* ~CurlRequestHelper() */
6043 : /************************************************************************/
6044 :
6045 766 : CurlRequestHelper::~CurlRequestHelper()
6046 : {
6047 383 : CPLFree(sWriteFuncData.pBuffer);
6048 383 : CPLFree(sWriteFuncHeaderData.pBuffer);
6049 383 : }
6050 :
6051 : /************************************************************************/
6052 : /* perform() */
6053 : /************************************************************************/
6054 :
6055 383 : long CurlRequestHelper::perform(CURL *hCurlHandle, struct curl_slist *headers,
6056 : VSICurlFilesystemHandlerBase *poFS,
6057 : IVSIS3LikeHandleHelper *poS3HandleHelper)
6058 : {
6059 383 : unchecked_curl_easy_setopt(hCurlHandle, CURLOPT_HTTPHEADER, headers);
6060 :
6061 383 : poS3HandleHelper->ResetQueryParameters();
6062 :
6063 383 : unchecked_curl_easy_setopt(hCurlHandle, CURLOPT_WRITEDATA, &sWriteFuncData);
6064 383 : unchecked_curl_easy_setopt(hCurlHandle, CURLOPT_WRITEFUNCTION,
6065 : VSICurlHandleWriteFunc);
6066 :
6067 383 : unchecked_curl_easy_setopt(hCurlHandle, CURLOPT_HEADERDATA,
6068 : &sWriteFuncHeaderData);
6069 383 : unchecked_curl_easy_setopt(hCurlHandle, CURLOPT_HEADERFUNCTION,
6070 : VSICurlHandleWriteFunc);
6071 :
6072 383 : szCurlErrBuf[0] = '\0';
6073 383 : unchecked_curl_easy_setopt(hCurlHandle, CURLOPT_ERRORBUFFER, szCurlErrBuf);
6074 :
6075 383 : VSICURLMultiPerform(poFS->GetCurlMultiHandleFor(poS3HandleHelper->GetURL()),
6076 : hCurlHandle);
6077 :
6078 383 : VSICURLResetHeaderAndWriterFunctions(hCurlHandle);
6079 :
6080 383 : curl_slist_free_all(headers);
6081 :
6082 383 : long response_code = 0;
6083 383 : curl_easy_getinfo(hCurlHandle, CURLINFO_HTTP_CODE, &response_code);
6084 383 : return response_code;
6085 : }
6086 :
6087 : /************************************************************************/
6088 : /* NetworkStatisticsLogger */
6089 : /************************************************************************/
6090 :
6091 : // Global variable
6092 : NetworkStatisticsLogger NetworkStatisticsLogger::gInstance{};
6093 : int NetworkStatisticsLogger::gnEnabled = -1; // unknown state
6094 :
6095 0 : static void ShowNetworkStats()
6096 : {
6097 0 : printf("Network statistics:\n%s\n", // ok
6098 0 : NetworkStatisticsLogger::GetReportAsSerializedJSON().c_str());
6099 0 : }
6100 :
6101 7 : void NetworkStatisticsLogger::ReadEnabled()
6102 : {
6103 : const bool bShowNetworkStats =
6104 7 : CPLTestBool(CPLGetConfigOption("CPL_VSIL_SHOW_NETWORK_STATS", "NO"));
6105 7 : gnEnabled =
6106 7 : (bShowNetworkStats || CPLTestBool(CPLGetConfigOption(
6107 : "CPL_VSIL_NETWORK_STATS_ENABLED", "NO")))
6108 14 : ? TRUE
6109 : : FALSE;
6110 7 : if (bShowNetworkStats)
6111 : {
6112 : static bool bRegistered = false;
6113 0 : if (!bRegistered)
6114 : {
6115 0 : bRegistered = true;
6116 0 : atexit(ShowNetworkStats);
6117 : }
6118 : }
6119 7 : }
6120 :
6121 149324 : void NetworkStatisticsLogger::EnterFileSystem(const char *pszName)
6122 : {
6123 149324 : if (!IsEnabled())
6124 149323 : return;
6125 1 : std::lock_guard<std::mutex> oLock(gInstance.m_mutex);
6126 2 : gInstance.m_mapThreadIdToContextPath[CPLGetPID()].push_back(
6127 2 : ContextPathItem(ContextPathType::FILESYSTEM, pszName));
6128 : }
6129 :
6130 149324 : void NetworkStatisticsLogger::LeaveFileSystem()
6131 : {
6132 149324 : if (!IsEnabled())
6133 149323 : return;
6134 1 : std::lock_guard<std::mutex> oLock(gInstance.m_mutex);
6135 1 : gInstance.m_mapThreadIdToContextPath[CPLGetPID()].pop_back();
6136 : }
6137 :
6138 147250 : void NetworkStatisticsLogger::EnterFile(const char *pszName)
6139 : {
6140 147250 : if (!IsEnabled())
6141 147249 : return;
6142 1 : std::lock_guard<std::mutex> oLock(gInstance.m_mutex);
6143 2 : gInstance.m_mapThreadIdToContextPath[CPLGetPID()].push_back(
6144 2 : ContextPathItem(ContextPathType::FILE, pszName));
6145 : }
6146 :
6147 147250 : void NetworkStatisticsLogger::LeaveFile()
6148 : {
6149 147250 : if (!IsEnabled())
6150 147249 : return;
6151 1 : std::lock_guard<std::mutex> oLock(gInstance.m_mutex);
6152 1 : gInstance.m_mapThreadIdToContextPath[CPLGetPID()].pop_back();
6153 : }
6154 :
6155 149324 : void NetworkStatisticsLogger::EnterAction(const char *pszName)
6156 : {
6157 149324 : if (!IsEnabled())
6158 149323 : return;
6159 1 : std::lock_guard<std::mutex> oLock(gInstance.m_mutex);
6160 2 : gInstance.m_mapThreadIdToContextPath[CPLGetPID()].push_back(
6161 2 : ContextPathItem(ContextPathType::ACTION, pszName));
6162 : }
6163 :
6164 149324 : void NetworkStatisticsLogger::LeaveAction()
6165 : {
6166 149324 : if (!IsEnabled())
6167 149323 : return;
6168 1 : std::lock_guard<std::mutex> oLock(gInstance.m_mutex);
6169 1 : gInstance.m_mapThreadIdToContextPath[CPLGetPID()].pop_back();
6170 : }
6171 :
6172 : std::vector<NetworkStatisticsLogger::Counters *>
6173 1 : NetworkStatisticsLogger::GetCountersForContext()
6174 : {
6175 1 : std::vector<Counters *> v;
6176 1 : const auto &contextPath = gInstance.m_mapThreadIdToContextPath[CPLGetPID()];
6177 :
6178 1 : Stats *curStats = &m_stats;
6179 1 : v.push_back(&(curStats->counters));
6180 :
6181 1 : bool inFileSystem = false;
6182 1 : bool inFile = false;
6183 1 : bool inAction = false;
6184 4 : for (const auto &item : contextPath)
6185 : {
6186 3 : if (item.eType == ContextPathType::FILESYSTEM)
6187 : {
6188 1 : if (inFileSystem)
6189 0 : continue;
6190 1 : inFileSystem = true;
6191 : }
6192 2 : else if (item.eType == ContextPathType::FILE)
6193 : {
6194 1 : if (inFile)
6195 0 : continue;
6196 1 : inFile = true;
6197 : }
6198 1 : else if (item.eType == ContextPathType::ACTION)
6199 : {
6200 1 : if (inAction)
6201 0 : continue;
6202 1 : inAction = true;
6203 : }
6204 :
6205 3 : curStats = &(curStats->children[item]);
6206 3 : v.push_back(&(curStats->counters));
6207 : }
6208 :
6209 1 : return v;
6210 : }
6211 :
6212 882 : void NetworkStatisticsLogger::LogGET(size_t nDownloadedBytes)
6213 : {
6214 882 : if (!IsEnabled())
6215 882 : return;
6216 0 : std::lock_guard<std::mutex> oLock(gInstance.m_mutex);
6217 0 : for (auto counters : gInstance.GetCountersForContext())
6218 : {
6219 0 : counters->nGET++;
6220 0 : counters->nGETDownloadedBytes += nDownloadedBytes;
6221 : }
6222 : }
6223 :
6224 132 : void NetworkStatisticsLogger::LogPUT(size_t nUploadedBytes)
6225 : {
6226 132 : if (!IsEnabled())
6227 131 : return;
6228 2 : std::lock_guard<std::mutex> oLock(gInstance.m_mutex);
6229 5 : for (auto counters : gInstance.GetCountersForContext())
6230 : {
6231 4 : counters->nPUT++;
6232 4 : counters->nPUTUploadedBytes += nUploadedBytes;
6233 : }
6234 : }
6235 :
6236 327 : void NetworkStatisticsLogger::LogHEAD()
6237 : {
6238 327 : if (!IsEnabled())
6239 327 : return;
6240 0 : std::lock_guard<std::mutex> oLock(gInstance.m_mutex);
6241 0 : for (auto counters : gInstance.GetCountersForContext())
6242 : {
6243 0 : counters->nHEAD++;
6244 : }
6245 : }
6246 :
6247 37 : void NetworkStatisticsLogger::LogPOST(size_t nUploadedBytes,
6248 : size_t nDownloadedBytes)
6249 : {
6250 37 : if (!IsEnabled())
6251 37 : return;
6252 0 : std::lock_guard<std::mutex> oLock(gInstance.m_mutex);
6253 0 : for (auto counters : gInstance.GetCountersForContext())
6254 : {
6255 0 : counters->nPOST++;
6256 0 : counters->nPOSTUploadedBytes += nUploadedBytes;
6257 0 : counters->nPOSTDownloadedBytes += nDownloadedBytes;
6258 : }
6259 : }
6260 :
6261 44 : void NetworkStatisticsLogger::LogDELETE()
6262 : {
6263 44 : if (!IsEnabled())
6264 44 : return;
6265 0 : std::lock_guard<std::mutex> oLock(gInstance.m_mutex);
6266 0 : for (auto counters : gInstance.GetCountersForContext())
6267 : {
6268 0 : counters->nDELETE++;
6269 : }
6270 : }
6271 :
6272 2 : void NetworkStatisticsLogger::Reset()
6273 : {
6274 2 : std::lock_guard<std::mutex> oLock(gInstance.m_mutex);
6275 2 : gInstance.m_stats = Stats();
6276 2 : gnEnabled = -1;
6277 2 : }
6278 :
6279 4 : void NetworkStatisticsLogger::Stats::AsJSON(CPLJSONObject &oJSON) const
6280 : {
6281 8 : CPLJSONObject oMethods;
6282 4 : if (counters.nHEAD)
6283 0 : oMethods.Add("HEAD/count", counters.nHEAD);
6284 4 : if (counters.nGET)
6285 0 : oMethods.Add("GET/count", counters.nGET);
6286 4 : if (counters.nGETDownloadedBytes)
6287 0 : oMethods.Add("GET/downloaded_bytes", counters.nGETDownloadedBytes);
6288 4 : if (counters.nPUT)
6289 4 : oMethods.Add("PUT/count", counters.nPUT);
6290 4 : if (counters.nPUTUploadedBytes)
6291 4 : oMethods.Add("PUT/uploaded_bytes", counters.nPUTUploadedBytes);
6292 4 : if (counters.nPOST)
6293 0 : oMethods.Add("POST/count", counters.nPOST);
6294 4 : if (counters.nPOSTUploadedBytes)
6295 0 : oMethods.Add("POST/uploaded_bytes", counters.nPOSTUploadedBytes);
6296 4 : if (counters.nPOSTDownloadedBytes)
6297 0 : oMethods.Add("POST/downloaded_bytes", counters.nPOSTDownloadedBytes);
6298 4 : if (counters.nDELETE)
6299 0 : oMethods.Add("DELETE/count", counters.nDELETE);
6300 4 : oJSON.Add("methods", oMethods);
6301 8 : CPLJSONObject oFiles;
6302 4 : bool bFilesAdded = false;
6303 7 : for (const auto &kv : children)
6304 : {
6305 6 : CPLJSONObject childJSON;
6306 3 : kv.second.AsJSON(childJSON);
6307 3 : if (kv.first.eType == ContextPathType::FILESYSTEM)
6308 : {
6309 1 : std::string osName(kv.first.osName);
6310 1 : if (!osName.empty() && osName[0] == '/')
6311 1 : osName = osName.substr(1);
6312 1 : if (!osName.empty() && osName.back() == '/')
6313 1 : osName.pop_back();
6314 1 : oJSON.Add(("handlers/" + osName).c_str(), childJSON);
6315 : }
6316 2 : else if (kv.first.eType == ContextPathType::FILE)
6317 : {
6318 1 : if (!bFilesAdded)
6319 : {
6320 1 : bFilesAdded = true;
6321 1 : oJSON.Add("files", oFiles);
6322 : }
6323 1 : oFiles.AddNoSplitName(kv.first.osName.c_str(), childJSON);
6324 : }
6325 1 : else if (kv.first.eType == ContextPathType::ACTION)
6326 : {
6327 1 : oJSON.Add(("actions/" + kv.first.osName).c_str(), childJSON);
6328 : }
6329 : }
6330 4 : }
6331 :
6332 1 : std::string NetworkStatisticsLogger::GetReportAsSerializedJSON()
6333 : {
6334 2 : std::lock_guard<std::mutex> oLock(gInstance.m_mutex);
6335 :
6336 2 : CPLJSONObject oJSON;
6337 1 : gInstance.m_stats.AsJSON(oJSON);
6338 2 : return oJSON.Format(CPLJSONObject::PrettyFormat::Pretty);
6339 : }
6340 :
6341 : } /* end of namespace cpl */
6342 :
6343 : /************************************************************************/
6344 : /* VSICurlParseUnixPermissions() */
6345 : /************************************************************************/
6346 :
6347 23 : int VSICurlParseUnixPermissions(const char *pszPermissions)
6348 : {
6349 23 : if (strlen(pszPermissions) != 9)
6350 12 : return 0;
6351 11 : int nMode = 0;
6352 11 : if (pszPermissions[0] == 'r')
6353 11 : nMode |= S_IRUSR;
6354 11 : if (pszPermissions[1] == 'w')
6355 11 : nMode |= S_IWUSR;
6356 11 : if (pszPermissions[2] == 'x')
6357 11 : nMode |= S_IXUSR;
6358 11 : if (pszPermissions[3] == 'r')
6359 11 : nMode |= S_IRGRP;
6360 11 : if (pszPermissions[4] == 'w')
6361 11 : nMode |= S_IWGRP;
6362 11 : if (pszPermissions[5] == 'x')
6363 11 : nMode |= S_IXGRP;
6364 11 : if (pszPermissions[6] == 'r')
6365 11 : nMode |= S_IROTH;
6366 11 : if (pszPermissions[7] == 'w')
6367 11 : nMode |= S_IWOTH;
6368 11 : if (pszPermissions[8] == 'x')
6369 11 : nMode |= S_IXOTH;
6370 11 : return nMode;
6371 : }
6372 :
6373 : /************************************************************************/
6374 : /* Cache of file properties. */
6375 : /************************************************************************/
6376 :
6377 : static std::mutex oCacheFilePropMutex;
6378 : static lru11::Cache<std::string, cpl::FileProp> *poCacheFileProp = nullptr;
6379 :
6380 : /************************************************************************/
6381 : /* VSICURLGetCachedFileProp() */
6382 : /************************************************************************/
6383 :
6384 150425 : bool VSICURLGetCachedFileProp(const char *pszURL, cpl::FileProp &oFileProp)
6385 : {
6386 150425 : std::lock_guard<std::mutex> oLock(oCacheFilePropMutex);
6387 451275 : return poCacheFileProp != nullptr &&
6388 451275 : poCacheFileProp->tryGet(std::string(pszURL), oFileProp) &&
6389 : // Let a chance to use new auth parameters
6390 150425 : !(oFileProp.eExists == cpl::EXIST_NO &&
6391 301141 : gnGenerationAuthParameters != oFileProp.nGenerationAuthParameters);
6392 : }
6393 :
6394 : /************************************************************************/
6395 : /* VSICURLSetCachedFileProp() */
6396 : /************************************************************************/
6397 :
6398 1435 : void VSICURLSetCachedFileProp(const char *pszURL, cpl::FileProp &oFileProp)
6399 : {
6400 1435 : std::lock_guard<std::mutex> oLock(oCacheFilePropMutex);
6401 1435 : if (poCacheFileProp == nullptr)
6402 3 : poCacheFileProp =
6403 3 : new lru11::Cache<std::string, cpl::FileProp>(100 * 1024);
6404 1435 : oFileProp.nGenerationAuthParameters = gnGenerationAuthParameters;
6405 1435 : poCacheFileProp->insert(std::string(pszURL), oFileProp);
6406 1435 : }
6407 :
6408 : /************************************************************************/
6409 : /* VSICURLInvalidateCachedFileProp() */
6410 : /************************************************************************/
6411 :
6412 731 : void VSICURLInvalidateCachedFileProp(const char *pszURL)
6413 : {
6414 1462 : std::lock_guard<std::mutex> oLock(oCacheFilePropMutex);
6415 731 : if (poCacheFileProp != nullptr)
6416 731 : poCacheFileProp->remove(std::string(pszURL));
6417 731 : }
6418 :
6419 : /************************************************************************/
6420 : /* VSICURLInvalidateCachedFilePropPrefix() */
6421 : /************************************************************************/
6422 :
6423 7 : void VSICURLInvalidateCachedFilePropPrefix(const char *pszURL)
6424 : {
6425 14 : std::lock_guard<std::mutex> oLock(oCacheFilePropMutex);
6426 7 : if (poCacheFileProp != nullptr)
6427 : {
6428 14 : std::list<std::string> keysToRemove;
6429 7 : const size_t nURLSize = strlen(pszURL);
6430 : auto lambda =
6431 125 : [&keysToRemove, &pszURL, nURLSize](
6432 130 : const lru11::KeyValuePair<std::string, cpl::FileProp> &kv)
6433 : {
6434 125 : if (strncmp(kv.key.c_str(), pszURL, nURLSize) == 0)
6435 5 : keysToRemove.push_back(kv.key);
6436 132 : };
6437 7 : poCacheFileProp->cwalk(lambda);
6438 12 : for (const auto &key : keysToRemove)
6439 5 : poCacheFileProp->remove(key);
6440 : }
6441 7 : }
6442 :
6443 : /************************************************************************/
6444 : /* VSICURLDestroyCacheFileProp() */
6445 : /************************************************************************/
6446 :
6447 1264 : void VSICURLDestroyCacheFileProp()
6448 : {
6449 1264 : std::lock_guard<std::mutex> oLock(oCacheFilePropMutex);
6450 1264 : delete poCacheFileProp;
6451 1264 : poCacheFileProp = nullptr;
6452 1264 : }
6453 :
6454 : /************************************************************************/
6455 : /* VSICURLMultiCleanup() */
6456 : /************************************************************************/
6457 :
6458 276 : void VSICURLMultiCleanup(CURLM *hCurlMultiHandle)
6459 : {
6460 : #if defined(CURL_AT_LEAST_VERSION) && defined(_WIN32)
6461 : // Since curl 8.20.0, auxiliary threads are used for DNS resolution
6462 : // Trying to join them when detaching the DLL results in a hang.
6463 : // See https://github.com/curl/curl/issues/21466#issuecomment-4372138595
6464 : #if CURL_AT_LEAST_VERSION(8, 20, 0)
6465 : if (GDALIsInGlobalDestructorFromDLLMain())
6466 : curl_multi_setopt(hCurlMultiHandle, CURLMOPT_QUICK_EXIT, 1L);
6467 : #endif
6468 : #endif
6469 :
6470 276 : void *old_handler = CPLHTTPIgnoreSigPipe();
6471 276 : curl_multi_cleanup(hCurlMultiHandle);
6472 276 : CPLHTTPRestoreSigPipeHandler(old_handler);
6473 276 : }
6474 :
6475 : /************************************************************************/
6476 : /* VSICurlInstallReadCbk() */
6477 : /************************************************************************/
6478 :
6479 3 : int VSICurlInstallReadCbk(VSILFILE *fp, VSICurlReadCbkFunc pfnReadCbk,
6480 : void *pfnUserData, int bStopOnInterruptUntilUninstall)
6481 : {
6482 3 : return reinterpret_cast<cpl::VSICurlHandle *>(fp)->InstallReadCbk(
6483 3 : pfnReadCbk, pfnUserData, bStopOnInterruptUntilUninstall);
6484 : }
6485 :
6486 : /************************************************************************/
6487 : /* VSICurlUninstallReadCbk() */
6488 : /************************************************************************/
6489 :
6490 3 : int VSICurlUninstallReadCbk(VSILFILE *fp)
6491 : {
6492 3 : return reinterpret_cast<cpl::VSICurlHandle *>(fp)->UninstallReadCbk();
6493 : }
6494 :
6495 : /************************************************************************/
6496 : /* VSICurlSetOptions() */
6497 : /************************************************************************/
6498 :
6499 1316 : struct curl_slist *VSICurlSetOptions(CURL *hCurlHandle, const char *pszURL,
6500 : const char *const *papszOptions)
6501 : {
6502 : struct curl_slist *headers = static_cast<struct curl_slist *>(
6503 1316 : CPLHTTPSetOptions(hCurlHandle, pszURL, papszOptions));
6504 :
6505 1316 : long option = CURLFTPMETHOD_SINGLECWD;
6506 1316 : unchecked_curl_easy_setopt(hCurlHandle, CURLOPT_FTP_FILEMETHOD, option);
6507 :
6508 : // ftp://ftp2.cits.rncan.gc.ca/pub/cantopo/250k_tif/
6509 : // doesn't like EPSV command,
6510 1316 : unchecked_curl_easy_setopt(hCurlHandle, CURLOPT_FTP_USE_EPSV, 0);
6511 :
6512 1316 : return headers;
6513 : }
6514 :
6515 : /************************************************************************/
6516 : /* VSICurlSetContentTypeFromExt() */
6517 : /************************************************************************/
6518 :
6519 96 : struct curl_slist *VSICurlSetContentTypeFromExt(struct curl_slist *poList,
6520 : const char *pszPath)
6521 : {
6522 96 : struct curl_slist *iter = poList;
6523 134 : while (iter != nullptr)
6524 : {
6525 38 : if (STARTS_WITH_CI(iter->data, "Content-Type"))
6526 : {
6527 0 : return poList;
6528 : }
6529 38 : iter = iter->next;
6530 : }
6531 :
6532 : static const struct
6533 : {
6534 : const char *ext;
6535 : const char *mime;
6536 : } aosExtMimePairs[] = {
6537 : {"txt", "text/plain"}, {"json", "application/json"},
6538 : {"tif", "image/tiff"}, {"tiff", "image/tiff"},
6539 : {"jpg", "image/jpeg"}, {"jpeg", "image/jpeg"},
6540 : {"jp2", "image/jp2"}, {"jpx", "image/jp2"},
6541 : {"j2k", "image/jp2"}, {"jpc", "image/jp2"},
6542 : {"png", "image/png"},
6543 : };
6544 :
6545 96 : const std::string osExt = CPLGetExtensionSafe(pszPath);
6546 96 : if (!osExt.empty())
6547 : {
6548 658 : for (const auto &pair : aosExtMimePairs)
6549 : {
6550 605 : if (EQUAL(osExt.c_str(), pair.ext))
6551 : {
6552 :
6553 : const std::string osContentType(
6554 32 : CPLSPrintf("Content-Type: %s", pair.mime));
6555 16 : poList = curl_slist_append(poList, osContentType.c_str());
6556 : #ifdef DEBUG_VERBOSE
6557 : CPLDebug("HTTP", "Setting %s, based on lookup table.",
6558 : osContentType.c_str());
6559 : #endif
6560 16 : break;
6561 : }
6562 : }
6563 : }
6564 :
6565 96 : return poList;
6566 : }
6567 :
6568 : /************************************************************************/
6569 : /* VSICurlSetCreationHeadersFromOptions() */
6570 : /************************************************************************/
6571 :
6572 83 : struct curl_slist *VSICurlSetCreationHeadersFromOptions(
6573 : struct curl_slist *headers, CSLConstList papszOptions, const char *pszPath)
6574 : {
6575 83 : bool bContentTypeFound = false;
6576 93 : for (CSLConstList papszIter = papszOptions; papszIter && *papszIter;
6577 : ++papszIter)
6578 : {
6579 10 : char *pszKey = nullptr;
6580 10 : const char *pszValue = CPLParseNameValue(*papszIter, &pszKey);
6581 10 : if (pszKey && pszValue)
6582 : {
6583 10 : if (EQUAL(pszKey, "Content-Type"))
6584 : {
6585 2 : bContentTypeFound = true;
6586 : }
6587 10 : headers = curl_slist_append(headers,
6588 : CPLSPrintf("%s: %s", pszKey, pszValue));
6589 : }
6590 10 : CPLFree(pszKey);
6591 : }
6592 :
6593 : // If Content-type not found in papszOptions, try to set it from the
6594 : // filename exstension.
6595 83 : if (!bContentTypeFound)
6596 : {
6597 81 : headers = VSICurlSetContentTypeFromExt(headers, pszPath);
6598 : }
6599 :
6600 83 : return headers;
6601 : }
6602 :
6603 : #endif // DOXYGEN_SKIP
6604 : //! @endcond
6605 :
6606 : /************************************************************************/
6607 : /* VSIInstallCurlFileHandler() */
6608 : /************************************************************************/
6609 :
6610 : /*!
6611 : \brief Install /vsicurl/ HTTP/FTP file system handler (requires libcurl)
6612 :
6613 : \verbatim embed:rst
6614 : See :ref:`/vsicurl/ documentation <vsicurl>`
6615 : \endverbatim
6616 :
6617 : */
6618 1984 : void VSIInstallCurlFileHandler(void)
6619 : {
6620 3968 : auto poHandler = std::make_shared<cpl::VSICurlFilesystemHandler>();
6621 5952 : for (const char *pszPrefix : VSICURL_PREFIXES)
6622 : {
6623 3968 : VSIFileManager::InstallHandler(pszPrefix, poHandler);
6624 : }
6625 1984 : }
6626 :
6627 : /************************************************************************/
6628 : /* VSICurlClearCache() */
6629 : /************************************************************************/
6630 :
6631 : /**
6632 : * \brief Clean local cache associated with /vsicurl/ (and related file systems)
6633 : *
6634 : * /vsicurl (and related file systems like /vsis3/, /vsigs/, /vsiaz/, /vsioss/,
6635 : * /vsiswift/) cache a number of
6636 : * metadata and data for faster execution in read-only scenarios. But when the
6637 : * content on the server-side may change during the same process, those
6638 : * mechanisms can prevent opening new files, or give an outdated version of
6639 : * them.
6640 : *
6641 : */
6642 :
6643 368 : void VSICurlClearCache(void)
6644 : {
6645 : // FIXME ? Currently we have different filesystem instances for
6646 : // vsicurl/, /vsis3/, /vsigs/ . So each one has its own cache of regions.
6647 : // File properties cache are now shared
6648 368 : char **papszPrefix = VSIFileManager::GetPrefixes();
6649 11408 : for (size_t i = 0; papszPrefix && papszPrefix[i]; ++i)
6650 : {
6651 0 : auto poFSHandler = dynamic_cast<cpl::VSICurlFilesystemHandlerBase *>(
6652 11040 : VSIFileManager::GetHandler(papszPrefix[i]));
6653 :
6654 11040 : if (poFSHandler)
6655 2944 : poFSHandler->ClearCache();
6656 : }
6657 368 : CSLDestroy(papszPrefix);
6658 :
6659 368 : VSICurlStreamingClearCache();
6660 368 : }
6661 :
6662 : /************************************************************************/
6663 : /* VSICurlPartialClearCache() */
6664 : /************************************************************************/
6665 :
6666 : /**
6667 : * \brief Clean local cache associated with /vsicurl/ (and related file systems)
6668 : * for a given filename (and its subfiles and subdirectories if it is a
6669 : * directory)
6670 : *
6671 : * /vsicurl (and related file systems like /vsis3/, /vsigs/, /vsiaz/, /vsioss/,
6672 : * /vsiswift/) cache a number of
6673 : * metadata and data for faster execution in read-only scenarios. But when the
6674 : * content on the server-side may change during the same process, those
6675 : * mechanisms can prevent opening new files, or give an outdated version of
6676 : * them.
6677 : *
6678 : * The filename prefix must start with the name of a known virtual file system
6679 : * (such as "/vsicurl/", "/vsis3/")
6680 : *
6681 : * VSICurlPartialClearCache("/vsis3/b") will clear all cached state for any file
6682 : * or directory starting with that prefix, so potentially "/vsis3/bucket",
6683 : * "/vsis3/basket/" or "/vsis3/basket/object".
6684 : *
6685 : * @param pszFilenamePrefix Filename prefix
6686 : */
6687 :
6688 5 : void VSICurlPartialClearCache(const char *pszFilenamePrefix)
6689 : {
6690 0 : auto poFSHandler = dynamic_cast<cpl::VSICurlFilesystemHandlerBase *>(
6691 5 : VSIFileManager::GetHandler(pszFilenamePrefix));
6692 :
6693 5 : if (poFSHandler)
6694 4 : poFSHandler->PartialClearCache(pszFilenamePrefix);
6695 5 : }
6696 :
6697 : /************************************************************************/
6698 : /* VSINetworkStatsReset() */
6699 : /************************************************************************/
6700 :
6701 : /**
6702 : * \brief Clear network related statistics.
6703 : *
6704 : * The effect of the CPL_VSIL_NETWORK_STATS_ENABLED configuration option
6705 : * will also be reset. That is, that the next network access will check its
6706 : * value again.
6707 : *
6708 : * @since GDAL 3.2.0
6709 : */
6710 :
6711 2 : void VSINetworkStatsReset(void)
6712 : {
6713 2 : cpl::NetworkStatisticsLogger::Reset();
6714 2 : }
6715 :
6716 : /************************************************************************/
6717 : /* VSINetworkStatsGetAsSerializedJSON() */
6718 : /************************************************************************/
6719 :
6720 : /**
6721 : * \brief Return network related statistics, as a JSON serialized object.
6722 : *
6723 : * Statistics collecting should be enabled with the
6724 : CPL_VSIL_NETWORK_STATS_ENABLED
6725 : * configuration option set to YES before any network activity starts
6726 : * (for efficiency, reading it is cached on first access, until
6727 : VSINetworkStatsReset() is called)
6728 : *
6729 : * Statistics can also be emitted on standard output at process termination if
6730 : * the CPL_VSIL_SHOW_NETWORK_STATS configuration option is set to YES.
6731 : *
6732 : * Example of output:
6733 : * \code{.js}
6734 : * {
6735 : * "methods":{
6736 : * "GET":{
6737 : * "count":6,
6738 : * "downloaded_bytes":40825
6739 : * },
6740 : * "PUT":{
6741 : * "count":1,
6742 : * "uploaded_bytes":35472
6743 : * }
6744 : * },
6745 : * "handlers":{
6746 : * "vsigs":{
6747 : * "methods":{
6748 : * "GET":{
6749 : * "count":2,
6750 : * "downloaded_bytes":446
6751 : * },
6752 : * "PUT":{
6753 : * "count":1,
6754 : * "uploaded_bytes":35472
6755 : * }
6756 : * },
6757 : * "files":{
6758 : * "\/vsigs\/spatialys\/byte.tif":{
6759 : * "methods":{
6760 : * "PUT":{
6761 : * "count":1,
6762 : * "uploaded_bytes":35472
6763 : * }
6764 : * },
6765 : * "actions":{
6766 : * "Write":{
6767 : * "methods":{
6768 : * "PUT":{
6769 : * "count":1,
6770 : * "uploaded_bytes":35472
6771 : * }
6772 : * }
6773 : * }
6774 : * }
6775 : * }
6776 : * },
6777 : * "actions":{
6778 : * "Stat":{
6779 : * "methods":{
6780 : * "GET":{
6781 : * "count":2,
6782 : * "downloaded_bytes":446
6783 : * }
6784 : * },
6785 : * "files":{
6786 : * "\/vsigs\/spatialys\/byte.tif\/":{
6787 : * "methods":{
6788 : * "GET":{
6789 : * "count":1,
6790 : * "downloaded_bytes":181
6791 : * }
6792 : * }
6793 : * }
6794 : * }
6795 : * }
6796 : * }
6797 : * },
6798 : * "vsis3":{
6799 : * [...]
6800 : * }
6801 : * }
6802 : * }
6803 : * \endcode
6804 : *
6805 : * @param papszOptions Unused.
6806 : * @return a JSON serialized string to free with VSIFree(), or nullptr
6807 : * @since GDAL 3.2.0
6808 : */
6809 :
6810 1 : char *VSINetworkStatsGetAsSerializedJSON(CPL_UNUSED char **papszOptions)
6811 : {
6812 1 : return CPLStrdup(
6813 2 : cpl::NetworkStatisticsLogger::GetReportAsSerializedJSON().c_str());
6814 : }
6815 :
6816 : #endif /* HAVE_CURL */
6817 :
6818 : #undef ENABLE_DEBUG
|