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