Line data Source code
1 : /******************************************************************************
2 : *
3 : * Project: CPL - Common Portability Library
4 : * Purpose: Convenience functions.
5 : * Author: Frank Warmerdam, warmerdam@pobox.com
6 : *
7 : ******************************************************************************
8 : * Copyright (c) 1998, Frank Warmerdam
9 : * Copyright (c) 2007-2014, Even Rouault <even dot rouault at spatialys.com>
10 : *
11 : * SPDX-License-Identifier: MIT
12 : ****************************************************************************/
13 :
14 : #include "cpl_config.h"
15 :
16 : #if defined(HAVE_USELOCALE) && !defined(__FreeBSD__)
17 : // For uselocale, define _XOPEN_SOURCE = 700
18 : // and OpenBSD with libcxx 19.1.7 requires 800 for vasprintf
19 : // (cf https://github.com/OSGeo/gdal/issues/12619)
20 : // (not sure if the following is still up to date...) but on Solaris, we don't
21 : // have uselocale and we cannot have std=c++11 with _XOPEN_SOURCE != 600
22 : #if defined(__sun__) && __cplusplus >= 201103L
23 : #if _XOPEN_SOURCE != 600
24 : #ifdef _XOPEN_SOURCE
25 : #undef _XOPEN_SOURCE
26 : #endif
27 : #define _XOPEN_SOURCE 600
28 : #endif
29 : #else
30 : #ifdef _XOPEN_SOURCE
31 : #undef _XOPEN_SOURCE
32 : #endif
33 : #define _XOPEN_SOURCE 800
34 : #endif
35 : #endif
36 :
37 : // For atoll (at least for NetBSD)
38 : #ifndef _ISOC99_SOURCE
39 : #define _ISOC99_SOURCE
40 : #endif
41 :
42 : #ifdef MSVC_USE_VLD
43 : #include <vld.h>
44 : #endif
45 :
46 : #include "cpl_conv.h"
47 :
48 : #include <algorithm>
49 : #include <atomic>
50 : #include <cctype>
51 : #include <cerrno>
52 : #include <climits>
53 : #include <clocale>
54 : #include <cmath>
55 : #include <cstdlib>
56 : #include <cstring>
57 : #include <ctime>
58 : #include <mutex>
59 : #include <set>
60 :
61 : #if HAVE_UNISTD_H
62 : #include <unistd.h>
63 : #endif
64 : #if HAVE_XLOCALE_H
65 : #include <xlocale.h> // for LC_NUMERIC_MASK on MacOS
66 : #endif
67 :
68 : #include <sys/types.h> // open
69 :
70 : #if defined(__FreeBSD__)
71 : #include <sys/user.h> // must be after sys/types.h
72 : #include <sys/sysctl.h>
73 : #endif
74 :
75 : #include <sys/stat.h> // open
76 : #include <fcntl.h> // open, fcntl
77 :
78 : #ifdef _WIN32
79 : #include <io.h> // _isatty, _wopen
80 : #else
81 : #include <unistd.h> // isatty, fcntl
82 : #if HAVE_GETRLIMIT
83 : #include <sys/resource.h> // getrlimit
84 : #include <sys/time.h> // getrlimit
85 : #endif
86 : #endif
87 :
88 : #include <string>
89 :
90 : #if __cplusplus >= 202002L
91 : #include <bit> // For std::endian
92 : #endif
93 :
94 : #include "cpl_config.h"
95 : #include "cpl_multiproc.h"
96 : #include "cpl_string.h"
97 : #include "cpl_vsi.h"
98 : #include "cpl_vsil_curl_priv.h"
99 : #include "cpl_known_config_options.h"
100 :
101 : #ifdef DEBUG
102 : #define OGRAPISPY_ENABLED
103 : #endif
104 : #ifdef OGRAPISPY_ENABLED
105 : // Keep in sync with ograpispy.cpp
106 : void OGRAPISPYCPLSetConfigOption(const char *, const char *);
107 : void OGRAPISPYCPLSetThreadLocalConfigOption(const char *, const char *);
108 : #endif
109 :
110 : // Uncomment to get list of options that have been fetched and set.
111 : // #define DEBUG_CONFIG_OPTIONS
112 :
113 : static CPLMutex *hConfigMutex = nullptr;
114 : static volatile char **g_papszConfigOptions = nullptr;
115 : static bool gbIgnoreEnvVariables =
116 : false; // if true, only take into account configuration options set through
117 : // configuration file or
118 : // CPLSetConfigOption()/CPLSetThreadLocalConfigOption()
119 :
120 : static std::vector<std::pair<CPLSetConfigOptionSubscriber, void *>>
121 : gSetConfigOptionSubscribers{};
122 :
123 : // Used by CPLOpenShared() and friends.
124 : static CPLMutex *hSharedFileMutex = nullptr;
125 : static int nSharedFileCount = 0;
126 : static CPLSharedFileInfo *pasSharedFileList = nullptr;
127 :
128 : // Used by CPLsetlocale().
129 : static CPLMutex *hSetLocaleMutex = nullptr;
130 :
131 : // Note: ideally this should be added in CPLSharedFileInfo*
132 : // but CPLSharedFileInfo is exposed in the API, hence that trick
133 : // to hide this detail.
134 : typedef struct
135 : {
136 : GIntBig nPID; // pid of opening thread.
137 : } CPLSharedFileInfoExtra;
138 :
139 : static volatile CPLSharedFileInfoExtra *pasSharedFileListExtra = nullptr;
140 :
141 : static const char *
142 : CPLGetThreadLocalConfigOption(const char *pszKey, const char *pszDefault,
143 : bool bSubstituteNullValueMarkerWithNull);
144 :
145 : static const char *
146 : CPLGetGlobalConfigOption(const char *pszKey, const char *pszDefault,
147 : bool bSubstituteNullValueMarkerWithNull);
148 :
149 : /************************************************************************/
150 : /* CPLCalloc() */
151 : /************************************************************************/
152 :
153 : /**
154 : * Safe version of calloc().
155 : *
156 : * This function is like the C library calloc(), but raises a CE_Fatal
157 : * error with CPLError() if it fails to allocate the desired memory. It
158 : * should be used for small memory allocations that are unlikely to fail
159 : * and for which the application is unwilling to test for out of memory
160 : * conditions. It uses VSICalloc() to get the memory, so any hooking of
161 : * VSICalloc() will apply to CPLCalloc() as well. CPLFree() or VSIFree()
162 : * can be used free memory allocated by CPLCalloc().
163 : *
164 : * @param nCount number of objects to allocate.
165 : * @param nSize size (in bytes) of object to allocate.
166 : * @return pointer to newly allocated memory, only NULL if nSize * nCount is
167 : * NULL.
168 : */
169 :
170 4981530 : void *CPLCalloc(size_t nCount, size_t nSize)
171 :
172 : {
173 4981530 : if (nSize * nCount == 0)
174 9178 : return nullptr;
175 :
176 4972350 : void *pReturn = CPLMalloc(nCount * nSize);
177 4972340 : memset(pReturn, 0, nCount * nSize);
178 4972340 : return pReturn;
179 : }
180 :
181 : /************************************************************************/
182 : /* CPLMalloc() */
183 : /************************************************************************/
184 :
185 : /**
186 : * Safe version of malloc().
187 : *
188 : * This function is like the C library malloc(), but raises a CE_Fatal
189 : * error with CPLError() if it fails to allocate the desired memory. It
190 : * should be used for small memory allocations that are unlikely to fail
191 : * and for which the application is unwilling to test for out of memory
192 : * conditions. It uses VSIMalloc() to get the memory, so any hooking of
193 : * VSIMalloc() will apply to CPLMalloc() as well. CPLFree() or VSIFree()
194 : * can be used free memory allocated by CPLMalloc().
195 : *
196 : * @param nSize size (in bytes) of memory block to allocate.
197 : * @return pointer to newly allocated memory, only NULL if nSize is zero.
198 : */
199 :
200 24299800 : void *CPLMalloc(size_t nSize)
201 :
202 : {
203 24299800 : if (nSize == 0)
204 5757 : return nullptr;
205 :
206 24294000 : if ((nSize >> (8 * sizeof(nSize) - 1)) != 0)
207 : {
208 : // coverity[dead_error_begin]
209 0 : CPLError(CE_Failure, CPLE_AppDefined,
210 : "CPLMalloc(%ld): Silly size requested.",
211 : static_cast<long>(nSize));
212 0 : return nullptr;
213 : }
214 :
215 24294000 : void *pReturn = VSIMalloc(nSize);
216 24294000 : if (pReturn == nullptr)
217 : {
218 0 : if (nSize < 2000)
219 : {
220 0 : CPLEmergencyError("CPLMalloc(): Out of memory allocating a small "
221 : "number of bytes.");
222 : }
223 :
224 0 : CPLError(CE_Fatal, CPLE_OutOfMemory,
225 : "CPLMalloc(): Out of memory allocating %ld bytes.",
226 : static_cast<long>(nSize));
227 : }
228 :
229 24293900 : return pReturn;
230 : }
231 :
232 : /************************************************************************/
233 : /* CPLRealloc() */
234 : /************************************************************************/
235 :
236 : /**
237 : * Safe version of realloc().
238 : *
239 : * This function is like the C library realloc(), but raises a CE_Fatal
240 : * error with CPLError() if it fails to allocate the desired memory. It
241 : * should be used for small memory allocations that are unlikely to fail
242 : * and for which the application is unwilling to test for out of memory
243 : * conditions. It uses VSIRealloc() to get the memory, so any hooking of
244 : * VSIRealloc() will apply to CPLRealloc() as well. CPLFree() or VSIFree()
245 : * can be used free memory allocated by CPLRealloc().
246 : *
247 : * It is also safe to pass NULL in as the existing memory block for
248 : * CPLRealloc(), in which case it uses VSIMalloc() to allocate a new block.
249 : *
250 : * @param pData existing memory block which should be copied to the new block.
251 : * @param nNewSize new size (in bytes) of memory block to allocate.
252 : * @return pointer to allocated memory, only NULL if nNewSize is zero.
253 : */
254 :
255 4266840 : void *CPLRealloc(void *pData, size_t nNewSize)
256 :
257 : {
258 4266840 : if (nNewSize == 0)
259 : {
260 45 : VSIFree(pData);
261 45 : return nullptr;
262 : }
263 :
264 4266790 : if ((nNewSize >> (8 * sizeof(nNewSize) - 1)) != 0)
265 : {
266 : // coverity[dead_error_begin]
267 0 : CPLError(CE_Failure, CPLE_AppDefined,
268 : "CPLRealloc(%ld): Silly size requested.",
269 : static_cast<long>(nNewSize));
270 0 : return nullptr;
271 : }
272 :
273 4266790 : void *pReturn = nullptr;
274 :
275 4266790 : if (pData == nullptr)
276 3166810 : pReturn = VSIMalloc(nNewSize);
277 : else
278 1099980 : pReturn = VSIRealloc(pData, nNewSize);
279 :
280 4263460 : if (pReturn == nullptr)
281 : {
282 0 : if (nNewSize < 2000)
283 : {
284 0 : char szSmallMsg[80] = {};
285 :
286 0 : snprintf(szSmallMsg, sizeof(szSmallMsg),
287 : "CPLRealloc(): Out of memory allocating %ld bytes.",
288 : static_cast<long>(nNewSize));
289 0 : CPLEmergencyError(szSmallMsg);
290 : }
291 : else
292 : {
293 0 : CPLError(CE_Fatal, CPLE_OutOfMemory,
294 : "CPLRealloc(): Out of memory allocating %ld bytes.",
295 : static_cast<long>(nNewSize));
296 : }
297 : }
298 :
299 4254670 : return pReturn;
300 : }
301 :
302 : /************************************************************************/
303 : /* CPLStrdup() */
304 : /************************************************************************/
305 :
306 : /**
307 : * Safe version of strdup() function.
308 : *
309 : * This function is similar to the C library strdup() function, but if
310 : * the memory allocation fails it will issue a CE_Fatal error with
311 : * CPLError() instead of returning NULL. Memory
312 : * allocated with CPLStrdup() can be freed with CPLFree() or VSIFree().
313 : *
314 : * It is also safe to pass a NULL string into CPLStrdup(). CPLStrdup()
315 : * will allocate and return a zero length string (as opposed to a NULL
316 : * string).
317 : *
318 : * @param pszString input string to be duplicated. May be NULL.
319 : * @return pointer to a newly allocated copy of the string. Free with
320 : * CPLFree() or VSIFree().
321 : */
322 :
323 8518390 : char *CPLStrdup(const char *pszString)
324 :
325 : {
326 8518390 : if (pszString == nullptr)
327 1256940 : pszString = "";
328 :
329 8518390 : const size_t nLen = strlen(pszString);
330 8518390 : char *pszReturn = static_cast<char *>(CPLMalloc(nLen + 1));
331 8518280 : memcpy(pszReturn, pszString, nLen + 1);
332 8518280 : return (pszReturn);
333 : }
334 :
335 : /************************************************************************/
336 : /* CPLStrlwr() */
337 : /************************************************************************/
338 :
339 : /**
340 : * Convert each characters of the string to lower case.
341 : *
342 : * For example, "ABcdE" will be converted to "abcde".
343 : * Starting with GDAL 3.9, this function is no longer locale dependent.
344 : *
345 : * @param pszString input string to be converted.
346 : * @return pointer to the same string, pszString.
347 : */
348 :
349 3 : char *CPLStrlwr(char *pszString)
350 :
351 : {
352 3 : if (pszString == nullptr)
353 0 : return nullptr;
354 :
355 3 : char *pszTemp = pszString;
356 :
357 24 : while (*pszTemp)
358 : {
359 21 : *pszTemp =
360 21 : static_cast<char>(CPLTolower(static_cast<unsigned char>(*pszTemp)));
361 21 : pszTemp++;
362 : }
363 :
364 3 : return pszString;
365 : }
366 :
367 : /************************************************************************/
368 : /* CPLFGets() */
369 : /* */
370 : /* Note: LF = \n = ASCII 10 */
371 : /* CR = \r = ASCII 13 */
372 : /************************************************************************/
373 :
374 : // ASCII characters.
375 : constexpr char knLF = 10;
376 : constexpr char knCR = 13;
377 :
378 : /**
379 : * Reads in at most one less than nBufferSize characters from the fp
380 : * stream and stores them into the buffer pointed to by pszBuffer.
381 : * Reading stops after an EOF or a newline. If a newline is read, it
382 : * is _not_ stored into the buffer. A '\\0' is stored after the last
383 : * character in the buffer. All three types of newline terminators
384 : * recognized by the CPLFGets(): single '\\r' and '\\n' and '\\r\\n'
385 : * combination.
386 : *
387 : * @param pszBuffer pointer to the targeting character buffer.
388 : * @param nBufferSize maximum size of the string to read (not including
389 : * terminating '\\0').
390 : * @param fp file pointer to read from.
391 : * @return pointer to the pszBuffer containing a string read
392 : * from the file or NULL if the error or end of file was encountered.
393 : */
394 :
395 0 : char *CPLFGets(char *pszBuffer, int nBufferSize, FILE *fp)
396 :
397 : {
398 0 : if (nBufferSize == 0 || pszBuffer == nullptr || fp == nullptr)
399 0 : return nullptr;
400 :
401 : /* -------------------------------------------------------------------- */
402 : /* Let the OS level call read what it things is one line. This */
403 : /* will include the newline. On windows, if the file happens */
404 : /* to be in text mode, the CRLF will have been converted to */
405 : /* just the newline (LF). If it is in binary mode it may well */
406 : /* have both. */
407 : /* -------------------------------------------------------------------- */
408 0 : const long nOriginalOffset = VSIFTell(fp);
409 0 : if (VSIFGets(pszBuffer, nBufferSize, fp) == nullptr)
410 0 : return nullptr;
411 :
412 0 : int nActuallyRead = static_cast<int>(strlen(pszBuffer));
413 0 : if (nActuallyRead == 0)
414 0 : return nullptr;
415 :
416 : /* -------------------------------------------------------------------- */
417 : /* If we found \r and out buffer is full, it is possible there */
418 : /* is also a pending \n. Check for it. */
419 : /* -------------------------------------------------------------------- */
420 0 : if (nBufferSize == nActuallyRead + 1 &&
421 0 : pszBuffer[nActuallyRead - 1] == knCR)
422 : {
423 0 : const int chCheck = fgetc(fp);
424 0 : if (chCheck != knLF)
425 : {
426 : // unget the character.
427 0 : if (VSIFSeek(fp, nOriginalOffset + nActuallyRead, SEEK_SET) == -1)
428 : {
429 0 : CPLError(CE_Failure, CPLE_FileIO,
430 : "Unable to unget a character");
431 : }
432 : }
433 : }
434 :
435 : /* -------------------------------------------------------------------- */
436 : /* Trim off \n, \r or \r\n if it appears at the end. We don't */
437 : /* need to do any "seeking" since we want the newline eaten. */
438 : /* -------------------------------------------------------------------- */
439 0 : if (nActuallyRead > 1 && pszBuffer[nActuallyRead - 1] == knLF &&
440 0 : pszBuffer[nActuallyRead - 2] == knCR)
441 : {
442 0 : pszBuffer[nActuallyRead - 2] = '\0';
443 : }
444 0 : else if (pszBuffer[nActuallyRead - 1] == knLF ||
445 0 : pszBuffer[nActuallyRead - 1] == knCR)
446 : {
447 0 : pszBuffer[nActuallyRead - 1] = '\0';
448 : }
449 :
450 : /* -------------------------------------------------------------------- */
451 : /* Search within the string for a \r (MacOS convention */
452 : /* apparently), and if we find it we need to trim the string, */
453 : /* and seek back. */
454 : /* -------------------------------------------------------------------- */
455 0 : char *pszExtraNewline = strchr(pszBuffer, knCR);
456 :
457 0 : if (pszExtraNewline != nullptr)
458 : {
459 0 : nActuallyRead = static_cast<int>(pszExtraNewline - pszBuffer + 1);
460 :
461 0 : *pszExtraNewline = '\0';
462 0 : if (VSIFSeek(fp, nOriginalOffset + nActuallyRead - 1, SEEK_SET) != 0)
463 0 : return nullptr;
464 :
465 : // This hackery is necessary to try and find our correct
466 : // spot on win32 systems with text mode line translation going
467 : // on. Sometimes the fseek back overshoots, but it doesn't
468 : // "realize it" till a character has been read. Try to read till
469 : // we get to the right spot and get our CR.
470 0 : int chCheck = fgetc(fp);
471 0 : while ((chCheck != knCR && chCheck != EOF) ||
472 0 : VSIFTell(fp) < nOriginalOffset + nActuallyRead)
473 : {
474 : static bool bWarned = false;
475 :
476 0 : if (!bWarned)
477 : {
478 0 : bWarned = true;
479 0 : CPLDebug("CPL",
480 : "CPLFGets() correcting for DOS text mode translation "
481 : "seek problem.");
482 : }
483 0 : chCheck = fgetc(fp);
484 : }
485 : }
486 :
487 0 : return pszBuffer;
488 : }
489 :
490 : /************************************************************************/
491 : /* CPLReadLineBuffer() */
492 : /* */
493 : /* Fetch readline buffer, and ensure it is the desired size, */
494 : /* reallocating if needed. Manages TLS (thread local storage) */
495 : /* issues for the buffer. */
496 : /* We use a special trick to track the actual size of the buffer */
497 : /* The first 4 bytes are reserved to store it as a int, hence the */
498 : /* -4 / +4 hacks with the size and pointer. */
499 : /************************************************************************/
500 4358620 : static char *CPLReadLineBuffer(int nRequiredSize)
501 :
502 : {
503 :
504 : /* -------------------------------------------------------------------- */
505 : /* A required size of -1 means the buffer should be freed. */
506 : /* -------------------------------------------------------------------- */
507 4358620 : if (nRequiredSize == -1)
508 : {
509 2487 : int bMemoryError = FALSE;
510 2487 : void *pRet = CPLGetTLSEx(CTLS_RLBUFFERINFO, &bMemoryError);
511 2487 : if (pRet != nullptr)
512 : {
513 2228 : CPLFree(pRet);
514 2228 : CPLSetTLS(CTLS_RLBUFFERINFO, nullptr, FALSE);
515 : }
516 2487 : return nullptr;
517 : }
518 :
519 : /* -------------------------------------------------------------------- */
520 : /* If the buffer doesn't exist yet, create it. */
521 : /* -------------------------------------------------------------------- */
522 4356140 : int bMemoryError = FALSE;
523 : GUInt32 *pnAlloc =
524 4356140 : static_cast<GUInt32 *>(CPLGetTLSEx(CTLS_RLBUFFERINFO, &bMemoryError));
525 4356140 : if (bMemoryError)
526 0 : return nullptr;
527 :
528 4356140 : if (pnAlloc == nullptr)
529 : {
530 3871 : pnAlloc = static_cast<GUInt32 *>(VSI_MALLOC_VERBOSE(200));
531 3871 : if (pnAlloc == nullptr)
532 0 : return nullptr;
533 3871 : *pnAlloc = 196;
534 3871 : CPLSetTLS(CTLS_RLBUFFERINFO, pnAlloc, TRUE);
535 : }
536 :
537 : /* -------------------------------------------------------------------- */
538 : /* If it is too small, grow it bigger. */
539 : /* -------------------------------------------------------------------- */
540 4356140 : if (static_cast<int>(*pnAlloc) - 1 < nRequiredSize)
541 : {
542 2890 : const int nNewSize = nRequiredSize + 4 + 500;
543 2890 : if (nNewSize <= 0)
544 : {
545 0 : VSIFree(pnAlloc);
546 0 : CPLSetTLS(CTLS_RLBUFFERINFO, nullptr, FALSE);
547 0 : CPLError(CE_Failure, CPLE_OutOfMemory,
548 : "CPLReadLineBuffer(): Trying to allocate more than "
549 : "2 GB.");
550 0 : return nullptr;
551 : }
552 :
553 : GUInt32 *pnAllocNew =
554 2890 : static_cast<GUInt32 *>(VSI_REALLOC_VERBOSE(pnAlloc, nNewSize));
555 2890 : if (pnAllocNew == nullptr)
556 : {
557 0 : VSIFree(pnAlloc);
558 0 : CPLSetTLS(CTLS_RLBUFFERINFO, nullptr, FALSE);
559 0 : return nullptr;
560 : }
561 2890 : pnAlloc = pnAllocNew;
562 :
563 2890 : *pnAlloc = nNewSize - 4;
564 2890 : CPLSetTLS(CTLS_RLBUFFERINFO, pnAlloc, TRUE);
565 : }
566 :
567 4356140 : return reinterpret_cast<char *>(pnAlloc + 1);
568 : }
569 :
570 : /************************************************************************/
571 : /* CPLReadLine() */
572 : /************************************************************************/
573 :
574 : /**
575 : * Simplified line reading from text file.
576 : *
577 : * Read a line of text from the given file handle, taking care
578 : * to capture CR and/or LF and strip off ... equivalent of
579 : * DKReadLine(). Pointer to an internal buffer is returned.
580 : * The application shouldn't free it, or depend on its value
581 : * past the next call to CPLReadLine().
582 : *
583 : * Note that CPLReadLine() uses VSIFGets(), so any hooking of VSI file
584 : * services should apply to CPLReadLine() as well.
585 : *
586 : * CPLReadLine() maintains an internal buffer, which will appear as a
587 : * single block memory leak in some circumstances. CPLReadLine() may
588 : * be called with a NULL FILE * at any time to free this working buffer.
589 : *
590 : * @param fp file pointer opened with VSIFOpen().
591 : *
592 : * @return pointer to an internal buffer containing a line of text read
593 : * from the file or NULL if the end of file was encountered.
594 : */
595 :
596 5 : const char *CPLReadLine(FILE *fp)
597 :
598 : {
599 : /* -------------------------------------------------------------------- */
600 : /* Cleanup case. */
601 : /* -------------------------------------------------------------------- */
602 5 : if (fp == nullptr)
603 : {
604 5 : CPLReadLineBuffer(-1);
605 5 : return nullptr;
606 : }
607 :
608 : /* -------------------------------------------------------------------- */
609 : /* Loop reading chunks of the line till we get to the end of */
610 : /* the line. */
611 : /* -------------------------------------------------------------------- */
612 0 : size_t nBytesReadThisTime = 0;
613 0 : char *pszRLBuffer = nullptr;
614 0 : size_t nReadSoFar = 0;
615 :
616 0 : do
617 : {
618 : /* --------------------------------------------------------------------
619 : */
620 : /* Grow the working buffer if we have it nearly full. Fail out */
621 : /* of read line if we can't reallocate it big enough (for */
622 : /* instance for a _very large_ file with no newlines). */
623 : /* --------------------------------------------------------------------
624 : */
625 0 : if (nReadSoFar > 100 * 1024 * 1024)
626 : // It is dubious that we need to read a line longer than 100 MB.
627 0 : return nullptr;
628 0 : pszRLBuffer = CPLReadLineBuffer(static_cast<int>(nReadSoFar) + 129);
629 0 : if (pszRLBuffer == nullptr)
630 0 : return nullptr;
631 :
632 : /* --------------------------------------------------------------------
633 : */
634 : /* Do the actual read. */
635 : /* --------------------------------------------------------------------
636 : */
637 0 : if (CPLFGets(pszRLBuffer + nReadSoFar, 128, fp) == nullptr &&
638 : nReadSoFar == 0)
639 0 : return nullptr;
640 :
641 0 : nBytesReadThisTime = strlen(pszRLBuffer + nReadSoFar);
642 0 : nReadSoFar += nBytesReadThisTime;
643 0 : } while (nBytesReadThisTime >= 127 && pszRLBuffer[nReadSoFar - 1] != knCR &&
644 0 : pszRLBuffer[nReadSoFar - 1] != knLF);
645 :
646 0 : return pszRLBuffer;
647 : }
648 :
649 : /************************************************************************/
650 : /* CPLReadLineL() */
651 : /************************************************************************/
652 :
653 : /**
654 : * Simplified line reading from text file.
655 : *
656 : * Similar to CPLReadLine(), but reading from a large file API handle.
657 : *
658 : * @param fp file pointer opened with VSIFOpenL().
659 : *
660 : * @return pointer to an internal buffer containing a line of text read
661 : * from the file or NULL if the end of file was encountered.
662 : */
663 :
664 199237 : const char *CPLReadLineL(VSILFILE *fp)
665 : {
666 199237 : return CPLReadLine2L(fp, -1, nullptr);
667 : }
668 :
669 : /************************************************************************/
670 : /* CPLReadLine2L() */
671 : /************************************************************************/
672 :
673 : /**
674 : * Simplified line reading from text file.
675 : *
676 : * Similar to CPLReadLine(), but reading from a large file API handle.
677 : *
678 : * @param fp file pointer opened with VSIFOpenL().
679 : * @param nMaxCars maximum number of characters allowed, or -1 for no limit.
680 : * @param papszOptions NULL-terminated array of options. Unused for now.
681 :
682 : * @return pointer to an internal buffer containing a line of text read
683 : * from the file or NULL if the end of file was encountered or the maximum
684 : * number of characters allowed reached.
685 : *
686 : */
687 :
688 2715420 : const char *CPLReadLine2L(VSILFILE *fp, int nMaxCars,
689 : CPL_UNUSED CSLConstList papszOptions)
690 :
691 : {
692 : int nBufLength;
693 5430840 : return CPLReadLine3L(fp, nMaxCars, &nBufLength, papszOptions);
694 : }
695 :
696 : /************************************************************************/
697 : /* CPLReadLine3L() */
698 : /************************************************************************/
699 :
700 : /**
701 : * Simplified line reading from text file.
702 : *
703 : * Similar to CPLReadLine(), but reading from a large file API handle.
704 : *
705 : * @param fp file pointer opened with VSIFOpenL().
706 : * @param nMaxCars maximum number of characters allowed, or -1 for no limit.
707 : * @param papszOptions NULL-terminated array of options. Unused for now.
708 : * @param[out] pnBufLength size of output string (must be non-NULL)
709 :
710 : * @return pointer to an internal buffer containing a line of text read
711 : * from the file or NULL if the end of file was encountered or the maximum
712 : * number of characters allowed reached.
713 : *
714 : */
715 2780470 : const char *CPLReadLine3L(VSILFILE *fp, int nMaxCars, int *pnBufLength,
716 : CPL_UNUSED CSLConstList papszOptions)
717 : {
718 : /* -------------------------------------------------------------------- */
719 : /* Cleanup case. */
720 : /* -------------------------------------------------------------------- */
721 2780470 : if (fp == nullptr)
722 : {
723 2482 : CPLReadLineBuffer(-1);
724 2482 : return nullptr;
725 : }
726 :
727 : /* -------------------------------------------------------------------- */
728 : /* Loop reading chunks of the line till we get to the end of */
729 : /* the line. */
730 : /* -------------------------------------------------------------------- */
731 2777990 : char *pszRLBuffer = nullptr;
732 2777990 : const size_t nChunkSize = 40;
733 2777990 : char szChunk[nChunkSize] = {};
734 2777990 : size_t nChunkBytesRead = 0;
735 2777990 : size_t nChunkBytesConsumed = 0;
736 :
737 2777990 : *pnBufLength = 0;
738 2777990 : szChunk[0] = 0;
739 :
740 : while (true)
741 : {
742 : /* --------------------------------------------------------------------
743 : */
744 : /* Read a chunk from the input file. */
745 : /* --------------------------------------------------------------------
746 : */
747 4356140 : if (*pnBufLength > INT_MAX - static_cast<int>(nChunkSize) - 1)
748 : {
749 0 : CPLError(CE_Failure, CPLE_AppDefined,
750 : "Too big line : more than 2 billion characters!.");
751 0 : CPLReadLineBuffer(-1);
752 0 : return nullptr;
753 : }
754 :
755 : pszRLBuffer =
756 4356140 : CPLReadLineBuffer(static_cast<int>(*pnBufLength + nChunkSize + 1));
757 4356140 : if (pszRLBuffer == nullptr)
758 0 : return nullptr;
759 :
760 4356140 : if (nChunkBytesRead == nChunkBytesConsumed + 1)
761 : {
762 :
763 : // case where one character is left over from last read.
764 1578150 : szChunk[0] = szChunk[nChunkBytesConsumed];
765 :
766 1578150 : nChunkBytesConsumed = 0;
767 1578150 : nChunkBytesRead = VSIFReadL(szChunk + 1, 1, nChunkSize - 1, fp) + 1;
768 : }
769 : else
770 : {
771 2777990 : nChunkBytesConsumed = 0;
772 :
773 : // fresh read.
774 2777990 : nChunkBytesRead = VSIFReadL(szChunk, 1, nChunkSize, fp);
775 2777990 : if (nChunkBytesRead == 0)
776 : {
777 17158 : if (*pnBufLength == 0)
778 17158 : return nullptr;
779 :
780 0 : break;
781 : }
782 : }
783 :
784 : /* --------------------------------------------------------------------
785 : */
786 : /* copy over characters watching for end-of-line. */
787 : /* --------------------------------------------------------------------
788 : */
789 4338980 : bool bBreak = false;
790 106717000 : while (nChunkBytesConsumed < nChunkBytesRead - 1 && !bBreak)
791 : {
792 102378000 : if ((szChunk[nChunkBytesConsumed] == knCR &&
793 609123 : szChunk[nChunkBytesConsumed + 1] == knLF) ||
794 101770000 : (szChunk[nChunkBytesConsumed] == knLF &&
795 2136090 : szChunk[nChunkBytesConsumed + 1] == knCR))
796 : {
797 608827 : nChunkBytesConsumed += 2;
798 608827 : bBreak = true;
799 : }
800 101770000 : else if (szChunk[nChunkBytesConsumed] == knLF ||
801 99633500 : szChunk[nChunkBytesConsumed] == knCR)
802 : {
803 2136390 : nChunkBytesConsumed += 1;
804 2136390 : bBreak = true;
805 : }
806 : else
807 : {
808 99633200 : pszRLBuffer[(*pnBufLength)++] = szChunk[nChunkBytesConsumed++];
809 99633200 : if (nMaxCars >= 0 && *pnBufLength == nMaxCars)
810 : {
811 1 : CPLError(CE_Failure, CPLE_AppDefined,
812 : "Maximum number of characters allowed reached.");
813 1 : return nullptr;
814 : }
815 : }
816 : }
817 :
818 4338980 : if (bBreak)
819 2745210 : break;
820 :
821 : /* --------------------------------------------------------------------
822 : */
823 : /* If there is a remaining character and it is not a newline */
824 : /* consume it. If it is a newline, but we are clearly at the */
825 : /* end of the file then consume it. */
826 : /* --------------------------------------------------------------------
827 : */
828 1593760 : if (nChunkBytesConsumed == nChunkBytesRead - 1 &&
829 : nChunkBytesRead < nChunkSize)
830 : {
831 15614 : if (szChunk[nChunkBytesConsumed] == knLF ||
832 2000 : szChunk[nChunkBytesConsumed] == knCR)
833 : {
834 13614 : nChunkBytesConsumed++;
835 13614 : break;
836 : }
837 :
838 2000 : pszRLBuffer[(*pnBufLength)++] = szChunk[nChunkBytesConsumed++];
839 2000 : break;
840 : }
841 1578150 : }
842 :
843 : /* -------------------------------------------------------------------- */
844 : /* If we have left over bytes after breaking out, seek back to */
845 : /* ensure they remain to be read next time. */
846 : /* -------------------------------------------------------------------- */
847 2760830 : if (nChunkBytesConsumed < nChunkBytesRead)
848 : {
849 2737550 : const size_t nBytesToPush = nChunkBytesRead - nChunkBytesConsumed;
850 :
851 2737550 : if (VSIFSeekL(fp, VSIFTellL(fp) - nBytesToPush, SEEK_SET) != 0)
852 0 : return nullptr;
853 : }
854 :
855 2760830 : pszRLBuffer[*pnBufLength] = '\0';
856 :
857 2760830 : return pszRLBuffer;
858 : }
859 :
860 : /************************************************************************/
861 : /* CPLScanString() */
862 : /************************************************************************/
863 :
864 : /**
865 : * Scan up to a maximum number of characters from a given string,
866 : * allocate a buffer for a new string and fill it with scanned characters.
867 : *
868 : * @param pszString String containing characters to be scanned. It may be
869 : * terminated with a null character.
870 : *
871 : * @param nMaxLength The maximum number of character to read. Less
872 : * characters will be read if a null character is encountered.
873 : *
874 : * @param bTrimSpaces If TRUE, trim ending spaces from the input string.
875 : * Character considered as empty using isspace(3) function.
876 : *
877 : * @param bNormalize If TRUE, replace ':' symbol with the '_'. It is needed if
878 : * resulting string will be used in CPL dictionaries.
879 : *
880 : * @return Pointer to the resulting string buffer. Caller responsible to free
881 : * this buffer with CPLFree().
882 : */
883 :
884 5300 : char *CPLScanString(const char *pszString, int nMaxLength, int bTrimSpaces,
885 : int bNormalize)
886 : {
887 5300 : if (!pszString)
888 0 : return nullptr;
889 :
890 5300 : if (!nMaxLength)
891 2 : return CPLStrdup("");
892 :
893 5298 : char *pszBuffer = static_cast<char *>(CPLMalloc(nMaxLength + 1));
894 5298 : if (!pszBuffer)
895 0 : return nullptr;
896 :
897 5298 : strncpy(pszBuffer, pszString, nMaxLength);
898 5298 : pszBuffer[nMaxLength] = '\0';
899 :
900 5298 : if (bTrimSpaces)
901 : {
902 5298 : size_t i = strlen(pszBuffer);
903 6422 : while (i > 0)
904 : {
905 6388 : i--;
906 6388 : if (!isspace(static_cast<unsigned char>(pszBuffer[i])))
907 5264 : break;
908 1124 : pszBuffer[i] = '\0';
909 : }
910 : }
911 :
912 5298 : if (bNormalize)
913 : {
914 5180 : size_t i = strlen(pszBuffer);
915 39328 : while (i > 0)
916 : {
917 34148 : i--;
918 34148 : if (pszBuffer[i] == ':')
919 0 : pszBuffer[i] = '_';
920 : }
921 : }
922 :
923 5298 : return pszBuffer;
924 : }
925 :
926 : /************************************************************************/
927 : /* CPLScanLong() */
928 : /************************************************************************/
929 :
930 : /**
931 : * Scan up to a maximum number of characters from a string and convert
932 : * the result to a long.
933 : *
934 : * @param pszString String containing characters to be scanned. It may be
935 : * terminated with a null character.
936 : *
937 : * @param nMaxLength The maximum number of character to consider as part
938 : * of the number. Less characters will be considered if a null character
939 : * is encountered.
940 : *
941 : * @return Long value, converted from its ASCII form.
942 : */
943 :
944 551 : long CPLScanLong(const char *pszString, int nMaxLength)
945 : {
946 551 : CPLAssert(nMaxLength >= 0);
947 551 : if (pszString == nullptr)
948 0 : return 0;
949 551 : const size_t nLength = CPLStrnlen(pszString, nMaxLength);
950 1102 : const std::string osValue(pszString, nLength);
951 551 : return atol(osValue.c_str());
952 : }
953 :
954 : /************************************************************************/
955 : /* CPLScanULong() */
956 : /************************************************************************/
957 :
958 : /**
959 : * Scan up to a maximum number of characters from a string and convert
960 : * the result to a unsigned long.
961 : *
962 : * @param pszString String containing characters to be scanned. It may be
963 : * terminated with a null character.
964 : *
965 : * @param nMaxLength The maximum number of character to consider as part
966 : * of the number. Less characters will be considered if a null character
967 : * is encountered.
968 : *
969 : * @return Unsigned long value, converted from its ASCII form.
970 : */
971 :
972 0 : unsigned long CPLScanULong(const char *pszString, int nMaxLength)
973 : {
974 0 : CPLAssert(nMaxLength >= 0);
975 0 : if (pszString == nullptr)
976 0 : return 0;
977 0 : const size_t nLength = CPLStrnlen(pszString, nMaxLength);
978 0 : const std::string osValue(pszString, nLength);
979 0 : return strtoul(osValue.c_str(), nullptr, 10);
980 : }
981 :
982 : /************************************************************************/
983 : /* CPLScanUIntBig() */
984 : /************************************************************************/
985 :
986 : /**
987 : * Extract big integer from string.
988 : *
989 : * Scan up to a maximum number of characters from a string and convert
990 : * the result to a GUIntBig.
991 : *
992 : * @param pszString String containing characters to be scanned. It may be
993 : * terminated with a null character.
994 : *
995 : * @param nMaxLength The maximum number of character to consider as part
996 : * of the number. Less characters will be considered if a null character
997 : * is encountered.
998 : *
999 : * @return GUIntBig value, converted from its ASCII form.
1000 : */
1001 :
1002 15503 : GUIntBig CPLScanUIntBig(const char *pszString, int nMaxLength)
1003 : {
1004 15503 : CPLAssert(nMaxLength >= 0);
1005 15503 : if (pszString == nullptr)
1006 0 : return 0;
1007 15503 : const size_t nLength = CPLStrnlen(pszString, nMaxLength);
1008 31006 : const std::string osValue(pszString, nLength);
1009 :
1010 : /* -------------------------------------------------------------------- */
1011 : /* Fetch out the result */
1012 : /* -------------------------------------------------------------------- */
1013 15503 : return strtoull(osValue.c_str(), nullptr, 10);
1014 : }
1015 :
1016 : /************************************************************************/
1017 : /* CPLAtoGIntBig() */
1018 : /************************************************************************/
1019 :
1020 : /**
1021 : * Convert a string to a 64 bit signed integer.
1022 : *
1023 : * @param pszString String containing 64 bit signed integer.
1024 : * @return 64 bit signed integer.
1025 : */
1026 :
1027 57316 : GIntBig CPLAtoGIntBig(const char *pszString)
1028 : {
1029 57316 : return atoll(pszString);
1030 : }
1031 :
1032 : #if defined(__MINGW32__) || defined(__sun__)
1033 :
1034 : // mingw atoll() doesn't return ERANGE in case of overflow
1035 : static int CPLAtoGIntBigExHasOverflow(const char *pszString, GIntBig nVal)
1036 : {
1037 : if (strlen(pszString) <= 18)
1038 : return FALSE;
1039 : while (*pszString == ' ')
1040 : pszString++;
1041 : if (*pszString == '+')
1042 : pszString++;
1043 : char szBuffer[32] = {};
1044 : /* x86_64-w64-mingw32-g++ (GCC) 4.8.2 annoyingly warns */
1045 : #ifdef HAVE_GCC_DIAGNOSTIC_PUSH
1046 : #pragma GCC diagnostic push
1047 : #pragma GCC diagnostic ignored "-Wformat"
1048 : #endif
1049 : snprintf(szBuffer, sizeof(szBuffer), CPL_FRMT_GIB, nVal);
1050 : #ifdef HAVE_GCC_DIAGNOSTIC_PUSH
1051 : #pragma GCC diagnostic pop
1052 : #endif
1053 : return strcmp(szBuffer, pszString) != 0;
1054 : }
1055 :
1056 : #endif
1057 :
1058 : /************************************************************************/
1059 : /* CPLAtoGIntBigEx() */
1060 : /************************************************************************/
1061 :
1062 : /**
1063 : * Convert a string to a 64 bit signed integer.
1064 : *
1065 : * @param pszString String containing 64 bit signed integer.
1066 : * @param bWarn Issue a warning if an overflow occurs during conversion
1067 : * @param pbOverflow Pointer to an integer to store if an overflow occurred, or
1068 : * NULL
1069 : * @return 64 bit signed integer.
1070 : */
1071 :
1072 106749 : GIntBig CPLAtoGIntBigEx(const char *pszString, int bWarn, int *pbOverflow)
1073 : {
1074 106749 : errno = 0;
1075 106749 : GIntBig nVal = strtoll(pszString, nullptr, 10);
1076 106749 : if (errno == ERANGE
1077 : #if defined(__MINGW32__) || defined(__sun__)
1078 : || CPLAtoGIntBigExHasOverflow(pszString, nVal)
1079 : #endif
1080 : )
1081 : {
1082 4 : if (pbOverflow)
1083 2 : *pbOverflow = TRUE;
1084 4 : if (bWarn)
1085 : {
1086 2 : CPLError(CE_Warning, CPLE_AppDefined,
1087 : "64 bit integer overflow when converting %s", pszString);
1088 : }
1089 4 : while (*pszString == ' ')
1090 0 : pszString++;
1091 4 : return (*pszString == '-') ? GINTBIG_MIN : GINTBIG_MAX;
1092 : }
1093 106745 : else if (pbOverflow)
1094 : {
1095 5428 : *pbOverflow = FALSE;
1096 : }
1097 106745 : return nVal;
1098 : }
1099 :
1100 : /************************************************************************/
1101 : /* CPLScanPointer() */
1102 : /************************************************************************/
1103 :
1104 : /**
1105 : * Extract pointer from string.
1106 : *
1107 : * Scan up to a maximum number of characters from a string and convert
1108 : * the result to a pointer.
1109 : *
1110 : * @param pszString String containing characters to be scanned. It may be
1111 : * terminated with a null character.
1112 : *
1113 : * @param nMaxLength The maximum number of character to consider as part
1114 : * of the number. Less characters will be considered if a null character
1115 : * is encountered.
1116 : *
1117 : * @return pointer value, converted from its ASCII form.
1118 : */
1119 :
1120 2604 : void *CPLScanPointer(const char *pszString, int nMaxLength)
1121 : {
1122 2604 : char szTemp[128] = {};
1123 :
1124 : /* -------------------------------------------------------------------- */
1125 : /* Compute string into local buffer, and terminate it. */
1126 : /* -------------------------------------------------------------------- */
1127 2604 : if (nMaxLength > static_cast<int>(sizeof(szTemp)) - 1)
1128 0 : nMaxLength = sizeof(szTemp) - 1;
1129 :
1130 2604 : strncpy(szTemp, pszString, nMaxLength);
1131 2604 : szTemp[nMaxLength] = '\0';
1132 :
1133 : /* -------------------------------------------------------------------- */
1134 : /* On MSVC we have to scanf pointer values without the 0x */
1135 : /* prefix. */
1136 : /* -------------------------------------------------------------------- */
1137 2604 : if (STARTS_WITH_CI(szTemp, "0x"))
1138 : {
1139 2579 : void *pResult = nullptr;
1140 :
1141 : #if defined(__MSVCRT__) || (defined(_WIN32) && defined(_MSC_VER))
1142 : // cppcheck-suppress invalidscanf
1143 : sscanf(szTemp + 2, "%p", &pResult);
1144 : #else
1145 : // cppcheck-suppress invalidscanf
1146 2579 : sscanf(szTemp, "%p", &pResult);
1147 :
1148 : // Solaris actually behaves like MSVCRT.
1149 2579 : if (pResult == nullptr)
1150 : {
1151 : // cppcheck-suppress invalidscanf
1152 0 : sscanf(szTemp + 2, "%p", &pResult);
1153 : }
1154 : #endif
1155 2579 : return pResult;
1156 : }
1157 :
1158 : #if SIZEOF_VOIDP == 8
1159 25 : return reinterpret_cast<void *>(CPLScanUIntBig(szTemp, nMaxLength));
1160 : #else
1161 : return reinterpret_cast<void *>(CPLScanULong(szTemp, nMaxLength));
1162 : #endif
1163 : }
1164 :
1165 : /************************************************************************/
1166 : /* CPLScanDouble() */
1167 : /************************************************************************/
1168 :
1169 : /**
1170 : * Extract double from string.
1171 : *
1172 : * Scan up to a maximum number of characters from a string and convert the
1173 : * result to a double. This function uses CPLAtof() to convert string to
1174 : * double value, so it uses a comma as a decimal delimiter.
1175 : *
1176 : * @param pszString String containing characters to be scanned. It may be
1177 : * terminated with a null character.
1178 : *
1179 : * @param nMaxLength The maximum number of character to consider as part
1180 : * of the number. Less characters will be considered if a null character
1181 : * is encountered.
1182 : *
1183 : * @return Double value, converted from its ASCII form.
1184 : */
1185 :
1186 317 : double CPLScanDouble(const char *pszString, int nMaxLength)
1187 : {
1188 317 : char szValue[32] = {};
1189 317 : char *pszValue = nullptr;
1190 :
1191 317 : if (nMaxLength + 1 < static_cast<int>(sizeof(szValue)))
1192 317 : pszValue = szValue;
1193 : else
1194 0 : pszValue = static_cast<char *>(CPLMalloc(nMaxLength + 1));
1195 :
1196 : /* -------------------------------------------------------------------- */
1197 : /* Compute string into local buffer, and terminate it. */
1198 : /* -------------------------------------------------------------------- */
1199 317 : strncpy(pszValue, pszString, nMaxLength);
1200 317 : pszValue[nMaxLength] = '\0';
1201 :
1202 : /* -------------------------------------------------------------------- */
1203 : /* Make a pass through converting 'D's to 'E's. */
1204 : /* -------------------------------------------------------------------- */
1205 6436 : for (int i = 0; i < nMaxLength; i++)
1206 6119 : if (pszValue[i] == 'd' || pszValue[i] == 'D')
1207 45 : pszValue[i] = 'E';
1208 :
1209 : /* -------------------------------------------------------------------- */
1210 : /* The conversion itself. */
1211 : /* -------------------------------------------------------------------- */
1212 317 : const double dfValue = CPLAtof(pszValue);
1213 :
1214 317 : if (pszValue != szValue)
1215 0 : CPLFree(pszValue);
1216 317 : return dfValue;
1217 : }
1218 :
1219 : /************************************************************************/
1220 : /* CPLPrintString() */
1221 : /************************************************************************/
1222 :
1223 : /**
1224 : * Copy the string pointed to by pszSrc, NOT including the terminating
1225 : * `\\0' character, to the array pointed to by pszDest.
1226 : *
1227 : * @param pszDest Pointer to the destination string buffer. Should be
1228 : * large enough to hold the resulting string.
1229 : *
1230 : * @param pszSrc Pointer to the source buffer.
1231 : *
1232 : * @param nMaxLen Maximum length of the resulting string. If string length
1233 : * is greater than nMaxLen, it will be truncated.
1234 : *
1235 : * @return Number of characters printed.
1236 : */
1237 :
1238 13439 : int CPLPrintString(char *pszDest, const char *pszSrc, int nMaxLen)
1239 : {
1240 13439 : if (!pszDest)
1241 0 : return 0;
1242 :
1243 13439 : if (!pszSrc)
1244 : {
1245 0 : *pszDest = '\0';
1246 0 : return 1;
1247 : }
1248 :
1249 13439 : int nChars = 0;
1250 13439 : char *pszTemp = pszDest;
1251 :
1252 201203 : while (nChars < nMaxLen && *pszSrc)
1253 : {
1254 187764 : *pszTemp++ = *pszSrc++;
1255 187764 : nChars++;
1256 : }
1257 :
1258 13439 : return nChars;
1259 : }
1260 :
1261 : /************************************************************************/
1262 : /* CPLPrintStringFill() */
1263 : /************************************************************************/
1264 :
1265 : /**
1266 : * Copy the string pointed to by pszSrc, NOT including the terminating
1267 : * `\\0' character, to the array pointed to by pszDest. Remainder of the
1268 : * destination string will be filled with space characters. This is only
1269 : * difference from the PrintString().
1270 : *
1271 : * @param pszDest Pointer to the destination string buffer. Should be
1272 : * large enough to hold the resulting string.
1273 : *
1274 : * @param pszSrc Pointer to the source buffer.
1275 : *
1276 : * @param nMaxLen Maximum length of the resulting string. If string length
1277 : * is greater than nMaxLen, it will be truncated.
1278 : *
1279 : * @return Number of characters printed.
1280 : */
1281 :
1282 209 : int CPLPrintStringFill(char *pszDest, const char *pszSrc, int nMaxLen)
1283 : {
1284 209 : if (!pszDest)
1285 0 : return 0;
1286 :
1287 209 : if (!pszSrc)
1288 : {
1289 0 : memset(pszDest, ' ', nMaxLen);
1290 0 : return nMaxLen;
1291 : }
1292 :
1293 209 : char *pszTemp = pszDest;
1294 1257 : while (nMaxLen && *pszSrc)
1295 : {
1296 1048 : *pszTemp++ = *pszSrc++;
1297 1048 : nMaxLen--;
1298 : }
1299 :
1300 209 : if (nMaxLen)
1301 71 : memset(pszTemp, ' ', nMaxLen);
1302 :
1303 209 : return nMaxLen;
1304 : }
1305 :
1306 : /************************************************************************/
1307 : /* CPLPrintInt32() */
1308 : /************************************************************************/
1309 :
1310 : /**
1311 : * Print GInt32 value into specified string buffer. This string will not
1312 : * be NULL-terminated.
1313 : *
1314 : * @param pszBuffer Pointer to the destination string buffer. Should be
1315 : * large enough to hold the resulting string. Note, that the string will
1316 : * not be NULL-terminated, so user should do this himself, if needed.
1317 : *
1318 : * @param iValue Numerical value to print.
1319 : *
1320 : * @param nMaxLen Maximum length of the resulting string. If string length
1321 : * is greater than nMaxLen, it will be truncated.
1322 : *
1323 : * @return Number of characters printed.
1324 : */
1325 :
1326 9 : int CPLPrintInt32(char *pszBuffer, GInt32 iValue, int nMaxLen)
1327 : {
1328 9 : if (!pszBuffer)
1329 0 : return 0;
1330 :
1331 9 : if (nMaxLen >= 64)
1332 0 : nMaxLen = 63;
1333 :
1334 9 : char szTemp[64] = {};
1335 :
1336 : #if UINT_MAX == 65535
1337 : snprintf(szTemp, sizeof(szTemp), "%*ld", nMaxLen, iValue);
1338 : #else
1339 9 : snprintf(szTemp, sizeof(szTemp), "%*d", nMaxLen, iValue);
1340 : #endif
1341 :
1342 9 : return CPLPrintString(pszBuffer, szTemp, nMaxLen);
1343 : }
1344 :
1345 : /************************************************************************/
1346 : /* CPLPrintUIntBig() */
1347 : /************************************************************************/
1348 :
1349 : /**
1350 : * Print GUIntBig value into specified string buffer. This string will not
1351 : * be NULL-terminated.
1352 : *
1353 : * @param pszBuffer Pointer to the destination string buffer. Should be
1354 : * large enough to hold the resulting string. Note, that the string will
1355 : * not be NULL-terminated, so user should do this himself, if needed.
1356 : *
1357 : * @param iValue Numerical value to print.
1358 : *
1359 : * @param nMaxLen Maximum length of the resulting string. If string length
1360 : * is greater than nMaxLen, it will be truncated.
1361 : *
1362 : * @return Number of characters printed.
1363 : */
1364 :
1365 24 : int CPLPrintUIntBig(char *pszBuffer, GUIntBig iValue, int nMaxLen)
1366 : {
1367 24 : if (!pszBuffer)
1368 0 : return 0;
1369 :
1370 24 : if (nMaxLen >= 64)
1371 0 : nMaxLen = 63;
1372 :
1373 24 : char szTemp[64] = {};
1374 :
1375 : #if defined(__MSVCRT__) || (defined(_WIN32) && defined(_MSC_VER))
1376 : /* x86_64-w64-mingw32-g++ (GCC) 4.8.2 annoyingly warns */
1377 : #ifdef HAVE_GCC_DIAGNOSTIC_PUSH
1378 : #pragma GCC diagnostic push
1379 : #pragma GCC diagnostic ignored "-Wformat"
1380 : #pragma GCC diagnostic ignored "-Wformat-extra-args"
1381 : #endif
1382 : snprintf(szTemp, sizeof(szTemp), "%*I64u", nMaxLen, iValue);
1383 : #ifdef HAVE_GCC_DIAGNOSTIC_PUSH
1384 : #pragma GCC diagnostic pop
1385 : #endif
1386 : #else
1387 24 : snprintf(szTemp, sizeof(szTemp), "%*llu", nMaxLen, iValue);
1388 : #endif
1389 :
1390 24 : return CPLPrintString(pszBuffer, szTemp, nMaxLen);
1391 : }
1392 :
1393 : /************************************************************************/
1394 : /* CPLPrintPointer() */
1395 : /************************************************************************/
1396 :
1397 : /**
1398 : * Print pointer value into specified string buffer. This string will not
1399 : * be NULL-terminated.
1400 : *
1401 : * @param pszBuffer Pointer to the destination string buffer. Should be
1402 : * large enough to hold the resulting string. Note, that the string will
1403 : * not be NULL-terminated, so user should do this himself, if needed.
1404 : *
1405 : * @param pValue Pointer to ASCII encode.
1406 : *
1407 : * @param nMaxLen Maximum length of the resulting string. If string length
1408 : * is greater than nMaxLen, it will be truncated.
1409 : *
1410 : * @return Number of characters printed.
1411 : */
1412 :
1413 13359 : int CPLPrintPointer(char *pszBuffer, void *pValue, int nMaxLen)
1414 : {
1415 13359 : if (!pszBuffer)
1416 0 : return 0;
1417 :
1418 13359 : if (nMaxLen >= 64)
1419 10770 : nMaxLen = 63;
1420 :
1421 13359 : char szTemp[64] = {};
1422 :
1423 13359 : snprintf(szTemp, sizeof(szTemp), "%p", pValue);
1424 :
1425 : // On windows, and possibly some other platforms the sprintf("%p")
1426 : // does not prefix things with 0x so it is hard to know later if the
1427 : // value is hex encoded. Fix this up here.
1428 :
1429 13359 : if (!STARTS_WITH_CI(szTemp, "0x"))
1430 0 : snprintf(szTemp, sizeof(szTemp), "0x%p", pValue);
1431 :
1432 13359 : return CPLPrintString(pszBuffer, szTemp, nMaxLen);
1433 : }
1434 :
1435 : /************************************************************************/
1436 : /* CPLPrintDouble() */
1437 : /************************************************************************/
1438 :
1439 : /**
1440 : * Print double value into specified string buffer. Exponential character
1441 : * flag 'E' (or 'e') will be replaced with 'D', as in Fortran. Resulting
1442 : * string will not to be NULL-terminated.
1443 : *
1444 : * @param pszBuffer Pointer to the destination string buffer. Should be
1445 : * large enough to hold the resulting string. Note, that the string will
1446 : * not be NULL-terminated, so user should do this himself, if needed.
1447 : *
1448 : * @param pszFormat Format specifier (for example, "%16.9E").
1449 : *
1450 : * @param dfValue Numerical value to print.
1451 : *
1452 : * @param pszLocale Unused.
1453 : *
1454 : * @return Number of characters printed.
1455 : */
1456 :
1457 0 : int CPLPrintDouble(char *pszBuffer, const char *pszFormat, double dfValue,
1458 : CPL_UNUSED const char *pszLocale)
1459 : {
1460 0 : if (!pszBuffer)
1461 0 : return 0;
1462 :
1463 0 : const int knDoubleBufferSize = 64;
1464 0 : char szTemp[knDoubleBufferSize] = {};
1465 :
1466 0 : CPLsnprintf(szTemp, knDoubleBufferSize, pszFormat, dfValue);
1467 0 : szTemp[knDoubleBufferSize - 1] = '\0';
1468 :
1469 0 : for (int i = 0; szTemp[i] != '\0'; i++)
1470 : {
1471 0 : if (szTemp[i] == 'E' || szTemp[i] == 'e')
1472 0 : szTemp[i] = 'D';
1473 : }
1474 :
1475 0 : return CPLPrintString(pszBuffer, szTemp, 64);
1476 : }
1477 :
1478 : /************************************************************************/
1479 : /* CPLPrintTime() */
1480 : /************************************************************************/
1481 :
1482 : /**
1483 : * Print specified time value accordingly to the format options and
1484 : * specified locale name. This function does following:
1485 : *
1486 : * - if locale parameter is not NULL, the current locale setting will be
1487 : * stored and replaced with the specified one;
1488 : * - format time value with the strftime(3) function;
1489 : * - restore back current locale, if was saved.
1490 : *
1491 : * @param pszBuffer Pointer to the destination string buffer. Should be
1492 : * large enough to hold the resulting string. Note, that the string will
1493 : * not be NULL-terminated, so user should do this himself, if needed.
1494 : *
1495 : * @param nMaxLen Maximum length of the resulting string. If string length is
1496 : * greater than nMaxLen, it will be truncated.
1497 : *
1498 : * @param pszFormat Controls the output format. Options are the same as
1499 : * for strftime(3) function.
1500 : *
1501 : * @param poBrokenTime Pointer to the broken-down time structure. May be
1502 : * requested with the VSIGMTime() and VSILocalTime() functions.
1503 : *
1504 : * @param pszLocale Pointer to a character string containing locale name
1505 : * ("C", "POSIX", "us_US", "ru_RU.KOI8-R" etc.). If NULL we will not
1506 : * manipulate with locale settings and current process locale will be used for
1507 : * printing. Be aware that it may be unsuitable to use current locale for
1508 : * printing time, because all names will be printed in your native language,
1509 : * as well as time format settings also may be adjusted differently from the
1510 : * C/POSIX defaults. To solve these problems this option was introduced.
1511 : *
1512 : * @return Number of characters printed.
1513 : */
1514 :
1515 33 : int CPLPrintTime(char *pszBuffer, int nMaxLen, const char *pszFormat,
1516 : const struct tm *poBrokenTime, const char *pszLocale)
1517 : {
1518 : char *pszTemp =
1519 33 : static_cast<char *>(CPLMalloc((nMaxLen + 1) * sizeof(char)));
1520 :
1521 33 : if (pszLocale && EQUAL(pszLocale, "C") &&
1522 33 : strcmp(pszFormat, "%a, %d %b %Y %H:%M:%S GMT") == 0)
1523 : {
1524 : // Particular case when formatting RFC822 datetime, to avoid locale
1525 : // change
1526 : static const char *const aszMonthStr[] = {"Jan", "Feb", "Mar", "Apr",
1527 : "May", "Jun", "Jul", "Aug",
1528 : "Sep", "Oct", "Nov", "Dec"};
1529 : static const char *const aszDayOfWeek[] = {"Sun", "Mon", "Tue", "Wed",
1530 : "Thu", "Fri", "Sat"};
1531 66 : snprintf(pszTemp, nMaxLen + 1, "%s, %02d %s %04d %02d:%02d:%02d GMT",
1532 33 : aszDayOfWeek[std::max(0, std::min(6, poBrokenTime->tm_wday))],
1533 33 : poBrokenTime->tm_mday,
1534 33 : aszMonthStr[std::max(0, std::min(11, poBrokenTime->tm_mon))],
1535 33 : poBrokenTime->tm_year + 1900, poBrokenTime->tm_hour,
1536 66 : poBrokenTime->tm_min, poBrokenTime->tm_sec);
1537 : }
1538 : else
1539 : {
1540 : #if defined(HAVE_LOCALE_H) && defined(HAVE_SETLOCALE)
1541 : char *pszCurLocale = NULL;
1542 :
1543 : if (pszLocale || EQUAL(pszLocale, ""))
1544 : {
1545 : // Save the current locale.
1546 : pszCurLocale = CPLsetlocale(LC_ALL, NULL);
1547 : // Set locale to the specified value.
1548 : CPLsetlocale(LC_ALL, pszLocale);
1549 : }
1550 : #else
1551 : (void)pszLocale;
1552 : #endif
1553 :
1554 0 : if (!strftime(pszTemp, nMaxLen + 1, pszFormat, poBrokenTime))
1555 0 : memset(pszTemp, 0, nMaxLen + 1);
1556 :
1557 : #if defined(HAVE_LOCALE_H) && defined(HAVE_SETLOCALE)
1558 : // Restore stored locale back.
1559 : if (pszCurLocale)
1560 : CPLsetlocale(LC_ALL, pszCurLocale);
1561 : #endif
1562 : }
1563 :
1564 33 : const int nChars = CPLPrintString(pszBuffer, pszTemp, nMaxLen);
1565 :
1566 33 : CPLFree(pszTemp);
1567 :
1568 33 : return nChars;
1569 : }
1570 :
1571 : /************************************************************************/
1572 : /* CPLVerifyConfiguration() */
1573 : /************************************************************************/
1574 :
1575 0 : void CPLVerifyConfiguration()
1576 :
1577 : {
1578 : /* -------------------------------------------------------------------- */
1579 : /* Verify data types. */
1580 : /* -------------------------------------------------------------------- */
1581 : static_assert(sizeof(short) == 2); // We unfortunately rely on this
1582 : static_assert(sizeof(int) == 4); // We unfortunately rely on this
1583 : static_assert(sizeof(float) == 4); // We unfortunately rely on this
1584 : static_assert(sizeof(double) == 8); // We unfortunately rely on this
1585 : static_assert(sizeof(GInt64) == 8);
1586 : static_assert(sizeof(GInt32) == 4);
1587 : static_assert(sizeof(GInt16) == 2);
1588 : static_assert(sizeof(GByte) == 1);
1589 :
1590 : /* -------------------------------------------------------------------- */
1591 : /* Verify byte order */
1592 : /* -------------------------------------------------------------------- */
1593 : #ifdef CPL_LSB
1594 : #if __cplusplus >= 202002L
1595 : static_assert(std::endian::native == std::endian::little);
1596 : #elif defined(__BYTE_ORDER__) && defined(__ORDER_LITTLE_ENDIAN__)
1597 : static_assert(__BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__);
1598 : #endif
1599 : #elif defined(CPL_MSB)
1600 : #if __cplusplus >= 202002L
1601 : static_assert(std::endian::native == std::endian::big);
1602 : #elif defined(__BYTE_ORDER__) && defined(__ORDER_BIG_ENDIAN__)
1603 : static_assert(__BYTE_ORDER__ == __ORDER_BIG_ENDIAN__);
1604 : #endif
1605 : #else
1606 : #error "CPL_LSB or CPL_MSB must be defined"
1607 : #endif
1608 0 : }
1609 :
1610 : #ifdef DEBUG_CONFIG_OPTIONS
1611 :
1612 : static CPLMutex *hRegisterConfigurationOptionMutex = nullptr;
1613 : static std::set<CPLString> *paoGetKeys = nullptr;
1614 : static std::set<CPLString> *paoSetKeys = nullptr;
1615 :
1616 : /************************************************************************/
1617 : /* CPLShowAccessedOptions() */
1618 : /************************************************************************/
1619 :
1620 : static void CPLShowAccessedOptions()
1621 : {
1622 : std::set<CPLString>::iterator aoIter;
1623 :
1624 : printf("Configuration options accessed in reading : "); /*ok*/
1625 : aoIter = paoGetKeys->begin();
1626 : while (aoIter != paoGetKeys->end())
1627 : {
1628 : printf("%s, ", (*aoIter).c_str()); /*ok*/
1629 : ++aoIter;
1630 : }
1631 : printf("\n"); /*ok*/
1632 :
1633 : printf("Configuration options accessed in writing : "); /*ok*/
1634 : aoIter = paoSetKeys->begin();
1635 : while (aoIter != paoSetKeys->end())
1636 : {
1637 : printf("%s, ", (*aoIter).c_str()); /*ok*/
1638 : ++aoIter;
1639 : }
1640 : printf("\n"); /*ok*/
1641 :
1642 : delete paoGetKeys;
1643 : delete paoSetKeys;
1644 : paoGetKeys = nullptr;
1645 : paoSetKeys = nullptr;
1646 : }
1647 :
1648 : /************************************************************************/
1649 : /* CPLAccessConfigOption() */
1650 : /************************************************************************/
1651 :
1652 : static void CPLAccessConfigOption(const char *pszKey, bool bGet)
1653 : {
1654 : CPLMutexHolderD(&hRegisterConfigurationOptionMutex);
1655 : if (paoGetKeys == nullptr)
1656 : {
1657 : paoGetKeys = new std::set<CPLString>;
1658 : paoSetKeys = new std::set<CPLString>;
1659 : atexit(CPLShowAccessedOptions);
1660 : }
1661 : if (bGet)
1662 : paoGetKeys->insert(pszKey);
1663 : else
1664 : paoSetKeys->insert(pszKey);
1665 : }
1666 : #endif
1667 :
1668 : /************************************************************************/
1669 : /* CPLGetConfigOption() */
1670 : /************************************************************************/
1671 :
1672 : /**
1673 : * Get the value of a configuration option.
1674 : *
1675 : * The value is the value of a (key, value) option set with
1676 : * CPLSetConfigOption(), or CPLSetThreadLocalConfigOption() of the same
1677 : * thread. If the given option was no defined with
1678 : * CPLSetConfigOption(), it tries to find it in environment variables.
1679 : *
1680 : * Note: the string returned by CPLGetConfigOption() might be short-lived, and
1681 : * in particular it will become invalid after a call to CPLSetConfigOption()
1682 : * with the same key.
1683 : *
1684 : * To override temporary a potentially existing option with a new value, you
1685 : * can use the following snippet :
1686 : * \code{.cpp}
1687 : * // backup old value
1688 : * const char* pszOldValTmp = CPLGetConfigOption(pszKey, NULL);
1689 : * char* pszOldVal = pszOldValTmp ? CPLStrdup(pszOldValTmp) : NULL;
1690 : * // override with new value
1691 : * CPLSetConfigOption(pszKey, pszNewVal);
1692 : * // do something useful
1693 : * // restore old value
1694 : * CPLSetConfigOption(pszKey, pszOldVal);
1695 : * CPLFree(pszOldVal);
1696 : * \endcode
1697 : *
1698 : * @param pszKey the key of the option to retrieve
1699 : * @param pszDefault a default value if the key does not match existing defined
1700 : * options (may be NULL)
1701 : * @return the value associated to the key, or the default value if not found
1702 : *
1703 : * @see CPLSetConfigOption(), https://gdal.org/user/configoptions.html
1704 : */
1705 7189890 : const char *CPL_STDCALL CPLGetConfigOption(const char *pszKey,
1706 : const char *pszDefault)
1707 :
1708 : {
1709 7189890 : const char *pszResult = CPLGetThreadLocalConfigOption(
1710 : pszKey, nullptr, /* bSubstituteNullValueMarkerWithNull = */ false);
1711 :
1712 7188150 : if (pszResult == nullptr)
1713 : {
1714 7145080 : pszResult = CPLGetGlobalConfigOption(
1715 : pszKey, nullptr, /* bSubstituteNullValueMarkerWithNull = */ false);
1716 : }
1717 :
1718 7191620 : if (gbIgnoreEnvVariables)
1719 : {
1720 6 : const char *pszEnvVar = getenv(pszKey);
1721 6 : if (pszEnvVar != nullptr)
1722 : {
1723 1 : CPLDebug("CPL",
1724 : "Ignoring environment variable %s=%s because of "
1725 : "ignore-env-vars=yes setting in configuration file",
1726 : pszKey, pszEnvVar);
1727 : }
1728 : }
1729 7191620 : else if (pszResult == nullptr)
1730 : {
1731 7138250 : pszResult = getenv(pszKey);
1732 : }
1733 :
1734 7191810 : if (pszResult == nullptr || strcmp(pszResult, CPL_NULL_VALUE) == 0)
1735 7127020 : return pszDefault;
1736 :
1737 64792 : return pszResult;
1738 : }
1739 :
1740 : /************************************************************************/
1741 : /* CPLGetConfigOptions() */
1742 : /************************************************************************/
1743 :
1744 : /**
1745 : * Return the list of configuration options as KEY=VALUE pairs.
1746 : *
1747 : * The list is the one set through the CPLSetConfigOption() API.
1748 : *
1749 : * Options that through environment variables or with
1750 : * CPLSetThreadLocalConfigOption() will *not* be listed.
1751 : *
1752 : * @return a copy of the list, to be freed with CSLDestroy().
1753 : */
1754 57 : char **CPLGetConfigOptions(void)
1755 : {
1756 114 : CPLMutexHolderD(&hConfigMutex);
1757 114 : return CSLDuplicate(const_cast<char **>(g_papszConfigOptions));
1758 : }
1759 :
1760 : /************************************************************************/
1761 : /* CPLSetConfigOptions() */
1762 : /************************************************************************/
1763 :
1764 : /**
1765 : * Replace the full list of configuration options with the passed list of
1766 : * KEY=VALUE pairs.
1767 : *
1768 : * This has the same effect of clearing the existing list, and setting
1769 : * individually each pair with the CPLSetConfigOption() API.
1770 : *
1771 : * This does not affect options set through environment variables or with
1772 : * CPLSetThreadLocalConfigOption().
1773 : *
1774 : * The passed list is copied by the function.
1775 : *
1776 : * @param papszConfigOptions the new list (or NULL).
1777 : *
1778 : */
1779 104 : void CPLSetConfigOptions(const char *const *papszConfigOptions)
1780 : {
1781 104 : CPLMutexHolderD(&hConfigMutex);
1782 104 : CSLDestroy(const_cast<char **>(g_papszConfigOptions));
1783 104 : g_papszConfigOptions = const_cast<volatile char **>(
1784 104 : CSLDuplicate(const_cast<char **>(papszConfigOptions)));
1785 104 : }
1786 :
1787 : /************************************************************************/
1788 : /* CPLGetThreadLocalConfigOption() */
1789 : /************************************************************************/
1790 :
1791 : /** Same as CPLGetConfigOption() but only with options set with
1792 : * CPLSetThreadLocalConfigOption() */
1793 30561 : const char *CPL_STDCALL CPLGetThreadLocalConfigOption(const char *pszKey,
1794 : const char *pszDefault)
1795 :
1796 : {
1797 30561 : return CPLGetThreadLocalConfigOption(pszKey, pszDefault, true);
1798 : }
1799 :
1800 : static const char *
1801 7220210 : CPLGetThreadLocalConfigOption(const char *pszKey, const char *pszDefault,
1802 : bool bSubstituteNullValueMarkerWithNull)
1803 : {
1804 : #ifdef DEBUG_CONFIG_OPTIONS
1805 : CPLAccessConfigOption(pszKey, TRUE);
1806 : #endif
1807 :
1808 7220210 : const char *pszResult = nullptr;
1809 :
1810 7220210 : int bMemoryError = FALSE;
1811 : char **papszTLConfigOptions = reinterpret_cast<char **>(
1812 7220210 : CPLGetTLSEx(CTLS_CONFIGOPTIONS, &bMemoryError));
1813 7218870 : if (papszTLConfigOptions != nullptr)
1814 6768120 : pszResult = CSLFetchNameValue(papszTLConfigOptions, pszKey);
1815 :
1816 7219060 : if (pszResult == nullptr || (bSubstituteNullValueMarkerWithNull &&
1817 693 : strcmp(pszResult, CPL_NULL_VALUE) == 0))
1818 7174550 : return pszDefault;
1819 :
1820 44516 : return pszResult;
1821 : }
1822 :
1823 : /************************************************************************/
1824 : /* CPLGetGlobalConfigOption() */
1825 : /************************************************************************/
1826 :
1827 : /** Same as CPLGetConfigOption() but excludes environment variables and
1828 : * options set with CPLSetThreadLocalConfigOption().
1829 : * This function should generally not be used by applications, which should
1830 : * use CPLGetConfigOption() instead.
1831 : * @since 3.8 */
1832 2126 : const char *CPL_STDCALL CPLGetGlobalConfigOption(const char *pszKey,
1833 : const char *pszDefault)
1834 : {
1835 2126 : return CPLGetGlobalConfigOption(
1836 2126 : pszKey, pszDefault, /* bSubstituteNullValueMarkerWithNull = */ true);
1837 : }
1838 :
1839 : static const char *
1840 7148100 : CPLGetGlobalConfigOption(const char *pszKey, const char *pszDefault,
1841 : bool bSubstituteNullValueMarkerWithNull)
1842 : {
1843 :
1844 : #ifdef DEBUG_CONFIG_OPTIONS
1845 : CPLAccessConfigOption(pszKey, TRUE);
1846 : #endif
1847 :
1848 14298800 : CPLMutexHolderD(&hConfigMutex);
1849 :
1850 : const char *pszResult =
1851 7150700 : CSLFetchNameValue(const_cast<char **>(g_papszConfigOptions), pszKey);
1852 :
1853 7150700 : if (pszResult == nullptr || (bSubstituteNullValueMarkerWithNull &&
1854 244 : strcmp(pszResult, CPL_NULL_VALUE) == 0))
1855 7140170 : return pszDefault;
1856 :
1857 10531 : return pszResult;
1858 : }
1859 :
1860 : /************************************************************************/
1861 : /* CPLSubscribeToSetConfigOption() */
1862 : /************************************************************************/
1863 :
1864 : /**
1865 : * Install a callback that will be notified of calls to CPLSetConfigOption()/
1866 : * CPLSetThreadLocalConfigOption()
1867 : *
1868 : * @param pfnCallback Callback. Must not be NULL
1869 : * @param pUserData Callback user data. May be NULL.
1870 : * @return subscriber ID that can be used with CPLUnsubscribeToSetConfigOption()
1871 : * @since GDAL 3.7
1872 : */
1873 :
1874 1328 : int CPLSubscribeToSetConfigOption(CPLSetConfigOptionSubscriber pfnCallback,
1875 : void *pUserData)
1876 : {
1877 2656 : CPLMutexHolderD(&hConfigMutex);
1878 1333 : for (int nId = 0;
1879 1333 : nId < static_cast<int>(gSetConfigOptionSubscribers.size()); ++nId)
1880 : {
1881 6 : if (!gSetConfigOptionSubscribers[nId].first)
1882 : {
1883 1 : gSetConfigOptionSubscribers[nId].first = pfnCallback;
1884 1 : gSetConfigOptionSubscribers[nId].second = pUserData;
1885 1 : return nId;
1886 : }
1887 : }
1888 1327 : int nId = static_cast<int>(gSetConfigOptionSubscribers.size());
1889 1327 : gSetConfigOptionSubscribers.push_back(
1890 1327 : std::pair<CPLSetConfigOptionSubscriber, void *>(pfnCallback,
1891 : pUserData));
1892 1327 : return nId;
1893 : }
1894 :
1895 : /************************************************************************/
1896 : /* CPLUnsubscribeToSetConfigOption() */
1897 : /************************************************************************/
1898 :
1899 : /**
1900 : * Remove a subscriber installed with CPLSubscribeToSetConfigOption()
1901 : *
1902 : * @param nId Subscriber id returned by CPLSubscribeToSetConfigOption()
1903 : * @since GDAL 3.7
1904 : */
1905 :
1906 4 : void CPLUnsubscribeToSetConfigOption(int nId)
1907 : {
1908 8 : CPLMutexHolderD(&hConfigMutex);
1909 4 : if (nId == static_cast<int>(gSetConfigOptionSubscribers.size()) - 1)
1910 : {
1911 3 : gSetConfigOptionSubscribers.resize(gSetConfigOptionSubscribers.size() -
1912 : 1);
1913 : }
1914 2 : else if (nId >= 0 &&
1915 1 : nId < static_cast<int>(gSetConfigOptionSubscribers.size()))
1916 : {
1917 1 : gSetConfigOptionSubscribers[nId].first = nullptr;
1918 : }
1919 4 : }
1920 :
1921 : /************************************************************************/
1922 : /* NotifyOtherComponentsConfigOptionChanged() */
1923 : /************************************************************************/
1924 :
1925 72024 : static void NotifyOtherComponentsConfigOptionChanged(const char *pszKey,
1926 : const char *pszValue,
1927 : bool bThreadLocal)
1928 : {
1929 : // When changing authentication parameters of virtual file systems,
1930 : // partially invalidate cached state about file availability.
1931 72024 : if (STARTS_WITH_CI(pszKey, "AWS_") || STARTS_WITH_CI(pszKey, "GS_") ||
1932 68939 : STARTS_WITH_CI(pszKey, "GOOGLE_") ||
1933 68900 : STARTS_WITH_CI(pszKey, "GDAL_HTTP_HEADER_FILE") ||
1934 68899 : STARTS_WITH_CI(pszKey, "AZURE_") ||
1935 68697 : (STARTS_WITH_CI(pszKey, "SWIFT_") && !EQUAL(pszKey, "SWIFT_MAX_KEYS")))
1936 : {
1937 3431 : VSICurlAuthParametersChanged();
1938 : }
1939 :
1940 71992 : if (!gSetConfigOptionSubscribers.empty())
1941 : {
1942 141864 : for (const auto &iter : gSetConfigOptionSubscribers)
1943 : {
1944 71017 : if (iter.first)
1945 71151 : iter.first(pszKey, pszValue, bThreadLocal, iter.second);
1946 : }
1947 : }
1948 71662 : }
1949 :
1950 : /************************************************************************/
1951 : /* CPLIsDebugEnabled() */
1952 : /************************************************************************/
1953 :
1954 : static int gnDebug = -1;
1955 :
1956 : /** Returns whether CPL_DEBUG is enabled.
1957 : *
1958 : * @since 3.11
1959 : */
1960 78059 : bool CPLIsDebugEnabled()
1961 : {
1962 78059 : if (gnDebug < 0)
1963 : {
1964 : // Check that apszKnownConfigOptions is correctly sorted with
1965 : // STRCASECMP() criterion.
1966 521874 : for (size_t i = 1; i < CPL_ARRAYSIZE(apszKnownConfigOptions); ++i)
1967 : {
1968 521400 : if (STRCASECMP(apszKnownConfigOptions[i - 1],
1969 : apszKnownConfigOptions[i]) >= 0)
1970 : {
1971 0 : CPLError(CE_Failure, CPLE_AppDefined,
1972 : "ERROR: apszKnownConfigOptions[] isn't correctly "
1973 : "sorted: %s >= %s",
1974 0 : apszKnownConfigOptions[i - 1],
1975 0 : apszKnownConfigOptions[i]);
1976 : }
1977 : }
1978 474 : gnDebug = CPLTestBool(CPLGetConfigOption("CPL_DEBUG", "OFF"));
1979 : }
1980 :
1981 78032 : return gnDebug != 0;
1982 : }
1983 :
1984 : /************************************************************************/
1985 : /* CPLDeclareKnownConfigOption() */
1986 : /************************************************************************/
1987 :
1988 : static std::mutex goMutexDeclaredKnownConfigOptions;
1989 : static std::set<CPLString> goSetKnownConfigOptions;
1990 :
1991 : /** Declare that the specified configuration option is known.
1992 : *
1993 : * This is useful to avoid a warning to be emitted on unknown configuration
1994 : * options when CPL_DEBUG is enabled.
1995 : *
1996 : * @param pszKey Name of the configuration option to declare.
1997 : * @param pszDefinition Unused for now. Must be set to nullptr.
1998 : * @since 3.11
1999 : */
2000 1 : void CPLDeclareKnownConfigOption(const char *pszKey,
2001 : [[maybe_unused]] const char *pszDefinition)
2002 : {
2003 1 : std::lock_guard oLock(goMutexDeclaredKnownConfigOptions);
2004 1 : goSetKnownConfigOptions.insert(CPLString(pszKey).toupper());
2005 1 : }
2006 :
2007 : /************************************************************************/
2008 : /* CPLGetKnownConfigOptions() */
2009 : /************************************************************************/
2010 :
2011 : /** Return the list of known configuration options.
2012 : *
2013 : * Must be freed with CSLDestroy().
2014 : * @since 3.11
2015 : */
2016 4 : char **CPLGetKnownConfigOptions()
2017 : {
2018 8 : std::lock_guard oLock(goMutexDeclaredKnownConfigOptions);
2019 8 : CPLStringList aosList;
2020 4408 : for (const char *pszKey : apszKnownConfigOptions)
2021 4404 : aosList.AddString(pszKey);
2022 5 : for (const auto &osKey : goSetKnownConfigOptions)
2023 1 : aosList.AddString(osKey);
2024 8 : return aosList.StealList();
2025 : }
2026 :
2027 : /************************************************************************/
2028 : /* CPLSetConfigOptionDetectUnknownConfigOption() */
2029 : /************************************************************************/
2030 :
2031 72085 : static void CPLSetConfigOptionDetectUnknownConfigOption(const char *pszKey,
2032 : const char *pszValue)
2033 : {
2034 72085 : if (EQUAL(pszKey, "CPL_DEBUG"))
2035 : {
2036 128 : gnDebug = pszValue ? CPLTestBool(pszValue) : false;
2037 : }
2038 71957 : else if (CPLIsDebugEnabled())
2039 : {
2040 272 : if (!std::binary_search(std::begin(apszKnownConfigOptions),
2041 : std::end(apszKnownConfigOptions), pszKey,
2042 3012 : [](const char *a, const char *b)
2043 3012 : { return STRCASECMP(a, b) < 0; }))
2044 : {
2045 : bool bFound;
2046 : {
2047 4 : std::lock_guard oLock(goMutexDeclaredKnownConfigOptions);
2048 8 : bFound = cpl::contains(goSetKnownConfigOptions,
2049 4 : CPLString(pszKey).toupper());
2050 : }
2051 4 : if (!bFound)
2052 : {
2053 2 : const char *pszOldValue = CPLGetConfigOption(pszKey, nullptr);
2054 2 : if (!((!pszValue && !pszOldValue) ||
2055 1 : (pszValue && pszOldValue &&
2056 0 : EQUAL(pszValue, pszOldValue))))
2057 : {
2058 2 : CPLError(CE_Warning, CPLE_AppDefined,
2059 : "Unknown configuration option '%s'.", pszKey);
2060 : }
2061 : }
2062 : }
2063 : }
2064 72027 : }
2065 :
2066 : /************************************************************************/
2067 : /* CPLSetConfigOption() */
2068 : /************************************************************************/
2069 :
2070 : /**
2071 : * Set a configuration option for GDAL/OGR use.
2072 : *
2073 : * Those options are defined as a (key, value) couple. The value corresponding
2074 : * to a key can be got later with the CPLGetConfigOption() method.
2075 : *
2076 : * This mechanism is similar to environment variables, but options set with
2077 : * CPLSetConfigOption() overrides, for CPLGetConfigOption() point of view,
2078 : * values defined in the environment.
2079 : *
2080 : * If CPLSetConfigOption() is called several times with the same key, the
2081 : * value provided during the last call will be used.
2082 : *
2083 : * Options can also be passed on the command line of most GDAL utilities
2084 : * with '\--config KEY VALUE' (or '\--config KEY=VALUE' since GDAL 3.10).
2085 : * For example, ogrinfo \--config CPL_DEBUG ON ~/data/test/point.shp
2086 : *
2087 : * This function can also be used to clear a setting by passing NULL as the
2088 : * value (note: passing NULL will not unset an existing environment variable;
2089 : * it will just unset a value previously set by CPLSetConfigOption()).
2090 : *
2091 : * Note that setting the GDAL_CACHEMAX configuration option after at least one
2092 : * raster has been read will be without effect. Use GDALSetCacheMax64()
2093 : * instead.
2094 : *
2095 : * Starting with GDAL 3.11, if CPL_DEBUG is enabled prior to this call, and
2096 : * CPLSetConfigOption() is called with a key that is neither a known
2097 : * configuration option of GDAL itself, or one that has been declared with
2098 : * CPLDeclareKnownConfigOption(), a warning will be emitted.
2099 : *
2100 : * Starting with GDAL 3.13, the CPL_NULL_VALUE macro can be used as the value
2101 : * to indicate that callers of CPLGetConfigOption() should see the default value,
2102 : * instead of the value of the corresponding environment variable.
2103 : *
2104 : * @param pszKey the key of the option
2105 : * @param pszValue the value of the option, NULL to clear a setting, or
2106 : * macro CPL_NULL_VALUE.
2107 : * @see https://gdal.org/user/configoptions.html
2108 : */
2109 5578 : void CPL_STDCALL CPLSetConfigOption(const char *pszKey, const char *pszValue)
2110 :
2111 : {
2112 : #ifdef DEBUG_CONFIG_OPTIONS
2113 : CPLAccessConfigOption(pszKey, FALSE);
2114 : #endif
2115 11156 : CPLMutexHolderD(&hConfigMutex);
2116 :
2117 : #ifdef OGRAPISPY_ENABLED
2118 5578 : OGRAPISPYCPLSetConfigOption(pszKey, pszValue);
2119 : #endif
2120 :
2121 5578 : CPLSetConfigOptionDetectUnknownConfigOption(pszKey, pszValue);
2122 :
2123 5578 : g_papszConfigOptions = const_cast<volatile char **>(CSLSetNameValue(
2124 : const_cast<char **>(g_papszConfigOptions), pszKey, pszValue));
2125 :
2126 5578 : NotifyOtherComponentsConfigOptionChanged(pszKey, pszValue,
2127 : /*bTheadLocal=*/false);
2128 5578 : }
2129 :
2130 : /************************************************************************/
2131 : /* CPLSetThreadLocalTLSFreeFunc() */
2132 : /************************************************************************/
2133 :
2134 : /* non-stdcall wrapper function for CSLDestroy() (#5590) */
2135 25 : static void CPLSetThreadLocalTLSFreeFunc(void *pData)
2136 : {
2137 25 : CSLDestroy(reinterpret_cast<char **>(pData));
2138 25 : }
2139 :
2140 : /************************************************************************/
2141 : /* CPLSetThreadLocalConfigOption() */
2142 : /************************************************************************/
2143 :
2144 : /**
2145 : * Set a configuration option for GDAL/OGR use.
2146 : *
2147 : * Those options are defined as a (key, value) couple. The value corresponding
2148 : * to a key can be got later with the CPLGetConfigOption() method.
2149 : *
2150 : * This function sets the configuration option that only applies in the
2151 : * current thread, as opposed to CPLSetConfigOption() which sets an option
2152 : * that applies on all threads. CPLSetThreadLocalConfigOption() will override
2153 : * the effect of CPLSetConfigOption) for the current thread.
2154 : *
2155 : * This function can also be used to clear a setting by passing NULL as the
2156 : * value (note: passing NULL will not unset an existing environment variable or
2157 : * a value set through CPLSetConfigOption();
2158 : * it will just unset a value previously set by
2159 : * CPLSetThreadLocalConfigOption()).
2160 : *
2161 : * Note that setting the GDAL_CACHEMAX configuration option after at least one
2162 : * raster has been read will be without effect. Use GDALSetCacheMax64()
2163 : * instead.
2164 : *
2165 : * Starting with GDAL 3.13, the CPL_NULL_VALUE macro can be used as the value
2166 : * to indicate that callers of CPLGetConfigOption() should see the default value,
2167 : * instead of the value of the corresponding environment variable.
2168 : *
2169 : * @param pszKey the key of the option
2170 : * @param pszValue the value of the option, NULL to clear a setting, or
2171 : * macro CPL_NULL_VALUE.
2172 : */
2173 :
2174 66333 : void CPL_STDCALL CPLSetThreadLocalConfigOption(const char *pszKey,
2175 : const char *pszValue)
2176 :
2177 : {
2178 : #ifdef DEBUG_CONFIG_OPTIONS
2179 : CPLAccessConfigOption(pszKey, FALSE);
2180 : #endif
2181 :
2182 : #ifdef OGRAPISPY_ENABLED
2183 66333 : OGRAPISPYCPLSetThreadLocalConfigOption(pszKey, pszValue);
2184 : #endif
2185 :
2186 66521 : int bMemoryError = FALSE;
2187 : char **papszTLConfigOptions = reinterpret_cast<char **>(
2188 66521 : CPLGetTLSEx(CTLS_CONFIGOPTIONS, &bMemoryError));
2189 66496 : if (bMemoryError)
2190 0 : return;
2191 :
2192 66496 : CPLSetConfigOptionDetectUnknownConfigOption(pszKey, pszValue);
2193 :
2194 : papszTLConfigOptions =
2195 66463 : CSLSetNameValue(papszTLConfigOptions, pszKey, pszValue);
2196 :
2197 66447 : CPLSetTLSWithFreeFunc(CTLS_CONFIGOPTIONS, papszTLConfigOptions,
2198 : CPLSetThreadLocalTLSFreeFunc);
2199 :
2200 66288 : NotifyOtherComponentsConfigOptionChanged(pszKey, pszValue,
2201 : /*bTheadLocal=*/true);
2202 : }
2203 :
2204 : /************************************************************************/
2205 : /* CPLGetThreadLocalConfigOptions() */
2206 : /************************************************************************/
2207 :
2208 : /**
2209 : * Return the list of thread local configuration options as KEY=VALUE pairs.
2210 : *
2211 : * Options that through environment variables or with
2212 : * CPLSetConfigOption() will *not* be listed.
2213 : *
2214 : * @return a copy of the list, to be freed with CSLDestroy().
2215 : */
2216 742469 : char **CPLGetThreadLocalConfigOptions(void)
2217 : {
2218 742469 : int bMemoryError = FALSE;
2219 : char **papszTLConfigOptions = reinterpret_cast<char **>(
2220 742469 : CPLGetTLSEx(CTLS_CONFIGOPTIONS, &bMemoryError));
2221 741290 : if (bMemoryError)
2222 0 : return nullptr;
2223 741290 : return CSLDuplicate(papszTLConfigOptions);
2224 : }
2225 :
2226 : /************************************************************************/
2227 : /* CPLSetThreadLocalConfigOptions() */
2228 : /************************************************************************/
2229 :
2230 : /**
2231 : * Replace the full list of thread local configuration options with the
2232 : * passed list of KEY=VALUE pairs.
2233 : *
2234 : * This has the same effect of clearing the existing list, and setting
2235 : * individually each pair with the CPLSetThreadLocalConfigOption() API.
2236 : *
2237 : * This does not affect options set through environment variables or with
2238 : * CPLSetConfigOption().
2239 : *
2240 : * The passed list is copied by the function.
2241 : *
2242 : * @param papszConfigOptions the new list (or NULL).
2243 : *
2244 : */
2245 1475980 : void CPLSetThreadLocalConfigOptions(const char *const *papszConfigOptions)
2246 : {
2247 1475980 : int bMemoryError = FALSE;
2248 : char **papszTLConfigOptions = reinterpret_cast<char **>(
2249 1475980 : CPLGetTLSEx(CTLS_CONFIGOPTIONS, &bMemoryError));
2250 1467000 : if (bMemoryError)
2251 0 : return;
2252 1467000 : CSLDestroy(papszTLConfigOptions);
2253 : papszTLConfigOptions =
2254 1462250 : CSLDuplicate(const_cast<char **>(papszConfigOptions));
2255 1466440 : CPLSetTLSWithFreeFunc(CTLS_CONFIGOPTIONS, papszTLConfigOptions,
2256 : CPLSetThreadLocalTLSFreeFunc);
2257 : }
2258 :
2259 : /************************************************************************/
2260 : /* CPLFreeConfig() */
2261 : /************************************************************************/
2262 :
2263 1564 : void CPL_STDCALL CPLFreeConfig()
2264 :
2265 : {
2266 : {
2267 3128 : CPLMutexHolderD(&hConfigMutex);
2268 :
2269 1564 : CSLDestroy(const_cast<char **>(g_papszConfigOptions));
2270 1564 : g_papszConfigOptions = nullptr;
2271 :
2272 1564 : int bMemoryError = FALSE;
2273 : char **papszTLConfigOptions = reinterpret_cast<char **>(
2274 1564 : CPLGetTLSEx(CTLS_CONFIGOPTIONS, &bMemoryError));
2275 1564 : if (papszTLConfigOptions != nullptr)
2276 : {
2277 211 : CSLDestroy(papszTLConfigOptions);
2278 211 : CPLSetTLS(CTLS_CONFIGOPTIONS, nullptr, FALSE);
2279 : }
2280 : }
2281 1564 : CPLDestroyMutex(hConfigMutex);
2282 1564 : hConfigMutex = nullptr;
2283 1564 : }
2284 :
2285 : /************************************************************************/
2286 : /* CPLLoadConfigOptionsFromFile() */
2287 : /************************************************************************/
2288 :
2289 : /** Load configuration from a given configuration file.
2290 :
2291 : A configuration file is a text file in a .ini style format, that lists
2292 : configuration options and their values.
2293 : Lines starting with # are comment lines.
2294 :
2295 : Example:
2296 : \verbatim
2297 : [configoptions]
2298 : # set BAR as the value of configuration option FOO
2299 : FOO=BAR
2300 : \endverbatim
2301 :
2302 : Starting with GDAL 3.5, a configuration file can also contain credentials
2303 : (or more generally options related to a virtual file system) for a given path
2304 : prefix, that can also be set with VSISetPathSpecificOption(). Credentials should
2305 : be put under a [credentials] section, and for each path prefix, under a relative
2306 : subsection whose name starts with "[." (e.g. "[.some_arbitrary_name]"), and
2307 : whose first key is "path".
2308 :
2309 : Example:
2310 : \verbatim
2311 : [credentials]
2312 :
2313 : [.private_bucket]
2314 : path=/vsis3/my_private_bucket
2315 : AWS_SECRET_ACCESS_KEY=...
2316 : AWS_ACCESS_KEY_ID=...
2317 :
2318 : [.sentinel_s2_l1c]
2319 : path=/vsis3/sentinel-s2-l1c
2320 : AWS_REQUEST_PAYER=requester
2321 : \endverbatim
2322 :
2323 : Starting with GDAL 3.6, a leading [directives] section might be added with
2324 : a "ignore-env-vars=yes" setting to indicate that, starting with that point,
2325 : all environment variables should be ignored, and only configuration options
2326 : defined in the [configoptions] sections or through the CPLSetConfigOption() /
2327 : CPLSetThreadLocalConfigOption() functions should be taken into account.
2328 :
2329 : This function is typically called by CPLLoadConfigOptionsFromPredefinedFiles()
2330 :
2331 : @param pszFilename File where to load configuration from.
2332 : @param bOverrideEnvVars Whether configuration options from the configuration
2333 : file should override environment variables.
2334 : @since GDAL 3.3
2335 : */
2336 3604 : void CPLLoadConfigOptionsFromFile(const char *pszFilename, int bOverrideEnvVars)
2337 : {
2338 3604 : VSILFILE *fp = VSIFOpenL(pszFilename, "rb");
2339 3604 : if (fp == nullptr)
2340 3595 : return;
2341 9 : CPLDebug("CPL", "Loading configuration from %s", pszFilename);
2342 : const char *pszLine;
2343 : enum class Section
2344 : {
2345 : NONE,
2346 : GENERAL,
2347 : CONFIG_OPTIONS,
2348 : CREDENTIALS,
2349 : };
2350 9 : Section eCurrentSection = Section::NONE;
2351 9 : bool bInSubsection = false;
2352 18 : std::string osPath;
2353 9 : int nSectionCounter = 0;
2354 :
2355 56 : const auto IsSpaceOnly = [](const char *pszStr)
2356 : {
2357 56 : for (; *pszStr; ++pszStr)
2358 : {
2359 47 : if (!isspace(static_cast<unsigned char>(*pszStr)))
2360 41 : return false;
2361 : }
2362 9 : return true;
2363 : };
2364 :
2365 59 : while ((pszLine = CPLReadLine2L(fp, -1, nullptr)) != nullptr)
2366 : {
2367 50 : if (IsSpaceOnly(pszLine))
2368 : {
2369 : // Blank line
2370 : }
2371 41 : else if (pszLine[0] == '#')
2372 : {
2373 : // Comment line
2374 : }
2375 35 : else if (strcmp(pszLine, "[configoptions]") == 0)
2376 : {
2377 6 : nSectionCounter++;
2378 6 : eCurrentSection = Section::CONFIG_OPTIONS;
2379 : }
2380 29 : else if (strcmp(pszLine, "[credentials]") == 0)
2381 : {
2382 4 : nSectionCounter++;
2383 4 : eCurrentSection = Section::CREDENTIALS;
2384 4 : bInSubsection = false;
2385 4 : osPath.clear();
2386 : }
2387 25 : else if (strcmp(pszLine, "[directives]") == 0)
2388 : {
2389 2 : nSectionCounter++;
2390 2 : if (nSectionCounter != 1)
2391 : {
2392 0 : CPLError(CE_Warning, CPLE_AppDefined,
2393 : "The [directives] section should be the first one in "
2394 : "the file, otherwise some its settings might not be "
2395 : "used correctly.");
2396 : }
2397 2 : eCurrentSection = Section::GENERAL;
2398 : }
2399 23 : else if (eCurrentSection == Section::GENERAL)
2400 : {
2401 2 : char *pszKey = nullptr;
2402 2 : const char *pszValue = CPLParseNameValue(pszLine, &pszKey);
2403 2 : if (pszKey && pszValue)
2404 : {
2405 2 : if (strcmp(pszKey, "ignore-env-vars") == 0)
2406 : {
2407 2 : gbIgnoreEnvVariables = CPLTestBool(pszValue);
2408 : }
2409 : else
2410 : {
2411 0 : CPLError(CE_Warning, CPLE_AppDefined,
2412 : "Ignoring %s line in [directives] section",
2413 : pszLine);
2414 : }
2415 : }
2416 2 : CPLFree(pszKey);
2417 : }
2418 21 : else if (eCurrentSection == Section::CREDENTIALS)
2419 : {
2420 15 : if (strncmp(pszLine, "[.", 2) == 0)
2421 : {
2422 4 : bInSubsection = true;
2423 4 : osPath.clear();
2424 : }
2425 11 : else if (bInSubsection)
2426 : {
2427 10 : char *pszKey = nullptr;
2428 10 : const char *pszValue = CPLParseNameValue(pszLine, &pszKey);
2429 10 : if (pszKey && pszValue)
2430 : {
2431 10 : if (strcmp(pszKey, "path") == 0)
2432 : {
2433 4 : if (!osPath.empty())
2434 : {
2435 1 : CPLError(
2436 : CE_Warning, CPLE_AppDefined,
2437 : "Duplicated 'path' key in the same subsection. "
2438 : "Ignoring %s=%s",
2439 : pszKey, pszValue);
2440 : }
2441 : else
2442 : {
2443 3 : osPath = pszValue;
2444 : }
2445 : }
2446 6 : else if (osPath.empty())
2447 : {
2448 1 : CPLError(CE_Warning, CPLE_AppDefined,
2449 : "First entry in a credentials subsection "
2450 : "should be 'path'.");
2451 : }
2452 : else
2453 : {
2454 5 : VSISetPathSpecificOption(osPath.c_str(), pszKey,
2455 : pszValue);
2456 : }
2457 : }
2458 10 : CPLFree(pszKey);
2459 : }
2460 1 : else if (pszLine[0] == '[')
2461 : {
2462 0 : eCurrentSection = Section::NONE;
2463 : }
2464 : else
2465 : {
2466 1 : CPLError(CE_Warning, CPLE_AppDefined,
2467 : "Ignoring content in [credential] section that is not "
2468 : "in a [.xxxxx] subsection");
2469 : }
2470 : }
2471 6 : else if (pszLine[0] == '[')
2472 : {
2473 0 : eCurrentSection = Section::NONE;
2474 : }
2475 6 : else if (eCurrentSection == Section::CONFIG_OPTIONS)
2476 : {
2477 6 : char *pszKey = nullptr;
2478 6 : const char *pszValue = CPLParseNameValue(pszLine, &pszKey);
2479 6 : if (pszKey && pszValue)
2480 : {
2481 11 : if (bOverrideEnvVars || gbIgnoreEnvVariables ||
2482 5 : getenv(pszKey) == nullptr)
2483 : {
2484 5 : CPLDebugOnly("CPL", "Setting configuration option %s=%s",
2485 : pszKey, pszValue);
2486 5 : CPLSetConfigOption(pszKey, pszValue);
2487 : }
2488 : else
2489 : {
2490 1 : CPLDebug("CPL",
2491 : "Ignoring configuration option %s=%s from "
2492 : "configuration file as it is already set "
2493 : "as an environment variable",
2494 : pszKey, pszValue);
2495 : }
2496 : }
2497 6 : CPLFree(pszKey);
2498 : }
2499 : }
2500 9 : VSIFCloseL(fp);
2501 : }
2502 :
2503 : /************************************************************************/
2504 : /* CPLLoadConfigOptionsFromPredefinedFiles() */
2505 : /************************************************************************/
2506 :
2507 : /** Load configuration from a set of predefined files.
2508 : *
2509 : * If the environment variable (or configuration option) GDAL_CONFIG_FILE is
2510 : * set, then CPLLoadConfigOptionsFromFile() will be called with the value of
2511 : * this configuration option as the file location.
2512 : *
2513 : * Otherwise, for Unix builds, CPLLoadConfigOptionsFromFile() will be called
2514 : * with ${sysconfdir}/gdal/gdalrc first where ${sysconfdir} evaluates
2515 : * to ${prefix}/etc, unless the \--sysconfdir switch of configure has been
2516 : * invoked.
2517 : *
2518 : * Then CPLLoadConfigOptionsFromFile() will be called with ${HOME}/.gdal/gdalrc
2519 : * on Unix builds (potentially overriding what was loaded with the sysconfdir)
2520 : * or ${USERPROFILE}/.gdal/gdalrc on Windows builds.
2521 : *
2522 : * CPLLoadConfigOptionsFromFile() will be called with bOverrideEnvVars = false,
2523 : * that is the value of environment variables previously set will be used
2524 : * instead of the value set in the configuration files (unless the configuration
2525 : * file contains a leading [directives] section with a "ignore-env-vars=yes"
2526 : * setting).
2527 : *
2528 : * This function is automatically called by GDALDriverManager() constructor
2529 : *
2530 : * @since GDAL 3.3
2531 : */
2532 1799 : void CPLLoadConfigOptionsFromPredefinedFiles()
2533 : {
2534 1799 : const char *pszFile = CPLGetConfigOption("GDAL_CONFIG_FILE", nullptr);
2535 1799 : if (pszFile != nullptr)
2536 : {
2537 2 : CPLLoadConfigOptionsFromFile(pszFile, false);
2538 : }
2539 : else
2540 : {
2541 : #ifdef SYSCONFDIR
2542 1797 : CPLLoadConfigOptionsFromFile(
2543 3594 : CPLFormFilenameSafe(
2544 3594 : CPLFormFilenameSafe(SYSCONFDIR, "gdal", nullptr).c_str(),
2545 : "gdalrc", nullptr)
2546 : .c_str(),
2547 : false);
2548 : #endif
2549 :
2550 : #ifdef _WIN32
2551 : const char *pszHome = CPLGetConfigOption("USERPROFILE", nullptr);
2552 : #else
2553 1797 : const char *pszHome = CPLGetConfigOption("HOME", nullptr);
2554 : #endif
2555 1797 : if (pszHome != nullptr)
2556 : {
2557 1797 : CPLLoadConfigOptionsFromFile(
2558 3594 : CPLFormFilenameSafe(
2559 3594 : CPLFormFilenameSafe(pszHome, ".gdal", nullptr).c_str(),
2560 : "gdalrc", nullptr)
2561 : .c_str(),
2562 : false);
2563 : }
2564 : }
2565 1799 : }
2566 :
2567 : /************************************************************************/
2568 : /* CPLStat() */
2569 : /************************************************************************/
2570 :
2571 : /** Same as VSIStat() except it works on "C:" as if it were "C:\". */
2572 :
2573 0 : int CPLStat(const char *pszPath, VSIStatBuf *psStatBuf)
2574 :
2575 : {
2576 0 : if (strlen(pszPath) == 2 && pszPath[1] == ':')
2577 : {
2578 0 : char szAltPath[4] = {pszPath[0], pszPath[1], '\\', '\0'};
2579 0 : return VSIStat(szAltPath, psStatBuf);
2580 : }
2581 :
2582 0 : return VSIStat(pszPath, psStatBuf);
2583 : }
2584 :
2585 : /************************************************************************/
2586 : /* proj_strtod() */
2587 : /************************************************************************/
2588 18 : static double proj_strtod(char *nptr, char **endptr)
2589 :
2590 : {
2591 18 : char c = '\0';
2592 18 : char *cp = nptr;
2593 :
2594 : // Scan for characters which cause problems with VC++ strtod().
2595 84 : while ((c = *cp) != '\0')
2596 : {
2597 72 : if (c == 'd' || c == 'D')
2598 : {
2599 : // Found one, so NUL it out, call strtod(),
2600 : // then restore it and return.
2601 6 : *cp = '\0';
2602 6 : const double result = CPLStrtod(nptr, endptr);
2603 6 : *cp = c;
2604 6 : return result;
2605 : }
2606 66 : ++cp;
2607 : }
2608 :
2609 : // No offending characters, just handle normally.
2610 :
2611 12 : return CPLStrtod(nptr, endptr);
2612 : }
2613 :
2614 : /************************************************************************/
2615 : /* CPLDMSToDec() */
2616 : /************************************************************************/
2617 :
2618 : static const char *sym = "NnEeSsWw";
2619 : constexpr double vm[] = {1.0, 0.0166666666667, 0.00027777778};
2620 :
2621 : /** CPLDMSToDec */
2622 6 : double CPLDMSToDec(const char *is)
2623 :
2624 : {
2625 : // Copy string into work space.
2626 6 : while (isspace(static_cast<unsigned char>(*is)))
2627 0 : ++is;
2628 :
2629 6 : const char *p = is;
2630 6 : char work[64] = {};
2631 6 : char *s = work;
2632 6 : int n = sizeof(work);
2633 60 : for (; isgraph(*p) && --n;)
2634 54 : *s++ = *p++;
2635 6 : *s = '\0';
2636 : // It is possible that a really odd input (like lots of leading
2637 : // zeros) could be truncated in copying into work. But...
2638 6 : s = work;
2639 6 : int sign = *s;
2640 :
2641 6 : if (sign == '+' || sign == '-')
2642 0 : s++;
2643 : else
2644 6 : sign = '+';
2645 :
2646 6 : int nl = 0;
2647 6 : double v = 0.0;
2648 24 : for (; nl < 3; nl = n + 1)
2649 : {
2650 18 : if (!(isdigit(static_cast<unsigned char>(*s)) || *s == '.'))
2651 0 : break;
2652 18 : const double tv = proj_strtod(s, &s);
2653 18 : if (tv == HUGE_VAL)
2654 0 : return tv;
2655 18 : switch (*s)
2656 : {
2657 6 : case 'D':
2658 : case 'd':
2659 6 : n = 0;
2660 6 : break;
2661 6 : case '\'':
2662 6 : n = 1;
2663 6 : break;
2664 6 : case '"':
2665 6 : n = 2;
2666 6 : break;
2667 0 : case 'r':
2668 : case 'R':
2669 0 : if (nl)
2670 : {
2671 0 : return 0.0;
2672 : }
2673 0 : ++s;
2674 0 : v = tv;
2675 0 : goto skip;
2676 0 : default:
2677 0 : v += tv * vm[nl];
2678 0 : skip:
2679 0 : n = 4;
2680 0 : continue;
2681 : }
2682 18 : if (n < nl)
2683 : {
2684 0 : return 0.0;
2685 : }
2686 18 : v += tv * vm[n];
2687 18 : ++s;
2688 : }
2689 : // Postfix sign.
2690 6 : if (*s && ((p = strchr(sym, *s))) != nullptr)
2691 : {
2692 0 : sign = (p - sym) >= 4 ? '-' : '+';
2693 0 : ++s;
2694 : }
2695 6 : if (sign == '-')
2696 0 : v = -v;
2697 :
2698 6 : return v;
2699 : }
2700 :
2701 : /************************************************************************/
2702 : /* CPLDecToDMS() */
2703 : /************************************************************************/
2704 :
2705 : /** Translate a decimal degrees value to a DMS string with hemisphere. */
2706 :
2707 620 : const char *CPLDecToDMS(double dfAngle, const char *pszAxis, int nPrecision)
2708 :
2709 : {
2710 620 : VALIDATE_POINTER1(pszAxis, "CPLDecToDMS", "");
2711 :
2712 620 : if (std::isnan(dfAngle))
2713 0 : return "Invalid angle";
2714 :
2715 620 : const double dfEpsilon = (0.5 / 3600.0) * pow(0.1, nPrecision);
2716 620 : const double dfABSAngle = std::abs(dfAngle) + dfEpsilon;
2717 620 : if (dfABSAngle > 361.0)
2718 : {
2719 0 : return "Invalid angle";
2720 : }
2721 :
2722 620 : const int nDegrees = static_cast<int>(dfABSAngle);
2723 620 : const int nMinutes = static_cast<int>((dfABSAngle - nDegrees) * 60);
2724 620 : double dfSeconds = dfABSAngle * 3600 - nDegrees * 3600 - nMinutes * 60;
2725 :
2726 620 : if (dfSeconds > dfEpsilon * 3600.0)
2727 614 : dfSeconds -= dfEpsilon * 3600.0;
2728 :
2729 620 : const char *pszHemisphere = nullptr;
2730 620 : if (EQUAL(pszAxis, "Long") && dfAngle < 0.0)
2731 273 : pszHemisphere = "W";
2732 347 : else if (EQUAL(pszAxis, "Long"))
2733 37 : pszHemisphere = "E";
2734 310 : else if (dfAngle < 0.0)
2735 22 : pszHemisphere = "S";
2736 : else
2737 288 : pszHemisphere = "N";
2738 :
2739 620 : char szFormat[30] = {};
2740 620 : CPLsnprintf(szFormat, sizeof(szFormat), "%%3dd%%2d\'%%%d.%df\"%s",
2741 : nPrecision + 3, nPrecision, pszHemisphere);
2742 :
2743 : static CPL_THREADLOCAL char szBuffer[50] = {};
2744 620 : CPLsnprintf(szBuffer, sizeof(szBuffer), szFormat, nDegrees, nMinutes,
2745 : dfSeconds);
2746 :
2747 620 : return szBuffer;
2748 : }
2749 :
2750 : /************************************************************************/
2751 : /* CPLPackedDMSToDec() */
2752 : /************************************************************************/
2753 :
2754 : /**
2755 : * Convert a packed DMS value (DDDMMMSSS.SS) into decimal degrees.
2756 : *
2757 : * This function converts a packed DMS angle to seconds. The standard
2758 : * packed DMS format is:
2759 : *
2760 : * degrees * 1000000 + minutes * 1000 + seconds
2761 : *
2762 : * Example: angle = 120025045.25 yields
2763 : * deg = 120
2764 : * min = 25
2765 : * sec = 45.25
2766 : *
2767 : * The algorithm used for the conversion is as follows:
2768 : *
2769 : * 1. The absolute value of the angle is used.
2770 : *
2771 : * 2. The degrees are separated out:
2772 : * deg = angle/1000000 (fractional portion truncated)
2773 : *
2774 : * 3. The minutes are separated out:
2775 : * min = (angle - deg * 1000000) / 1000 (fractional portion truncated)
2776 : *
2777 : * 4. The seconds are then computed:
2778 : * sec = angle - deg * 1000000 - min * 1000
2779 : *
2780 : * 5. The total angle in seconds is computed:
2781 : * sec = deg * 3600.0 + min * 60.0 + sec
2782 : *
2783 : * 6. The sign of sec is set to that of the input angle.
2784 : *
2785 : * Packed DMS values used by the USGS GCTP package and probably by other
2786 : * software.
2787 : *
2788 : * NOTE: This code does not validate input value. If you give the wrong
2789 : * value, you will get the wrong result.
2790 : *
2791 : * @param dfPacked Angle in packed DMS format.
2792 : *
2793 : * @return Angle in decimal degrees.
2794 : *
2795 : */
2796 :
2797 36 : double CPLPackedDMSToDec(double dfPacked)
2798 : {
2799 36 : const double dfSign = dfPacked < 0.0 ? -1 : 1;
2800 :
2801 36 : double dfSeconds = std::abs(dfPacked);
2802 36 : double dfDegrees = floor(dfSeconds / 1000000.0);
2803 36 : dfSeconds -= dfDegrees * 1000000.0;
2804 36 : const double dfMinutes = floor(dfSeconds / 1000.0);
2805 36 : dfSeconds -= dfMinutes * 1000.0;
2806 36 : dfSeconds = dfSign * (dfDegrees * 3600.0 + dfMinutes * 60.0 + dfSeconds);
2807 36 : dfDegrees = dfSeconds / 3600.0;
2808 :
2809 36 : return dfDegrees;
2810 : }
2811 :
2812 : /************************************************************************/
2813 : /* CPLDecToPackedDMS() */
2814 : /************************************************************************/
2815 : /**
2816 : * Convert decimal degrees into packed DMS value (DDDMMMSSS.SS).
2817 : *
2818 : * This function converts a value, specified in decimal degrees into
2819 : * packed DMS angle. The standard packed DMS format is:
2820 : *
2821 : * degrees * 1000000 + minutes * 1000 + seconds
2822 : *
2823 : * See also CPLPackedDMSToDec().
2824 : *
2825 : * @param dfDec Angle in decimal degrees.
2826 : *
2827 : * @return Angle in packed DMS format.
2828 : *
2829 : */
2830 :
2831 8 : double CPLDecToPackedDMS(double dfDec)
2832 : {
2833 8 : const double dfSign = dfDec < 0.0 ? -1 : 1;
2834 :
2835 8 : dfDec = std::abs(dfDec);
2836 8 : const double dfDegrees = floor(dfDec);
2837 8 : const double dfMinutes = floor((dfDec - dfDegrees) * 60.0);
2838 8 : const double dfSeconds = (dfDec - dfDegrees) * 3600.0 - dfMinutes * 60.0;
2839 :
2840 8 : return dfSign * (dfDegrees * 1000000.0 + dfMinutes * 1000.0 + dfSeconds);
2841 : }
2842 :
2843 : /************************************************************************/
2844 : /* CPLStringToComplex() */
2845 : /************************************************************************/
2846 :
2847 : /** Fetch the real and imaginary part of a serialized complex number */
2848 4695 : CPLErr CPL_DLL CPLStringToComplex(const char *pszString, double *pdfReal,
2849 : double *pdfImag)
2850 :
2851 : {
2852 4695 : while (*pszString == ' ')
2853 1 : pszString++;
2854 :
2855 : char *end;
2856 4694 : *pdfReal = CPLStrtod(pszString, &end);
2857 :
2858 4694 : int iPlus = -1;
2859 4694 : int iImagEnd = -1;
2860 :
2861 4694 : if (pszString == end)
2862 : {
2863 5 : goto error;
2864 : }
2865 :
2866 4689 : *pdfImag = 0.0;
2867 :
2868 4743 : for (int i = static_cast<int>(end - pszString);
2869 4743 : i < 100 && pszString[i] != '\0' && pszString[i] != ' '; i++)
2870 : {
2871 56 : if (pszString[i] == '+')
2872 : {
2873 8 : if (iPlus != -1)
2874 0 : goto error;
2875 8 : iPlus = i;
2876 : }
2877 56 : if (pszString[i] == '-')
2878 : {
2879 2 : if (iPlus != -1)
2880 1 : goto error;
2881 1 : iPlus = i;
2882 : }
2883 55 : if (pszString[i] == 'i')
2884 : {
2885 9 : if (iPlus == -1)
2886 1 : goto error;
2887 8 : iImagEnd = i;
2888 : }
2889 : }
2890 :
2891 : // If we have a "+" or "-" we must also have an "i"
2892 4687 : if ((iPlus == -1) != (iImagEnd == -1))
2893 : {
2894 1 : goto error;
2895 : }
2896 :
2897 : // Parse imaginary component, if any
2898 4686 : if (iPlus > -1)
2899 : {
2900 7 : *pdfImag = CPLStrtod(pszString + iPlus, &end);
2901 : }
2902 :
2903 : // Check everything remaining is whitespace
2904 4691 : for (; *end != '\0'; end++)
2905 : {
2906 11 : if (!isspace(*end) && end - pszString != iImagEnd)
2907 : {
2908 6 : goto error;
2909 : }
2910 : }
2911 :
2912 4680 : return CE_None;
2913 :
2914 14 : error:
2915 14 : CPLError(CE_Failure, CPLE_AppDefined, "Failed to parse number: %s",
2916 : pszString);
2917 14 : return CE_Failure;
2918 : }
2919 :
2920 : /************************************************************************/
2921 : /* CPLOpenShared() */
2922 : /************************************************************************/
2923 :
2924 : /**
2925 : * Open a shared file handle.
2926 : *
2927 : * Some operating systems have limits on the number of file handles that can
2928 : * be open at one time. This function attempts to maintain a registry of
2929 : * already open file handles, and reuse existing ones if the same file
2930 : * is requested by another part of the application.
2931 : *
2932 : * Note that access is only shared for access types "r", "rb", "r+" and
2933 : * "rb+". All others will just result in direct VSIOpen() calls. Keep in
2934 : * mind that a file is only reused if the file name is exactly the same.
2935 : * Different names referring to the same file will result in different
2936 : * handles.
2937 : *
2938 : * The VSIFOpen() or VSIFOpenL() function is used to actually open the file,
2939 : * when an existing file handle can't be shared.
2940 : *
2941 : * @param pszFilename the name of the file to open.
2942 : * @param pszAccess the normal fopen()/VSIFOpen() style access string.
2943 : * @param bLargeIn If TRUE VSIFOpenL() (for large files) will be used instead of
2944 : * VSIFOpen().
2945 : *
2946 : * @return a file handle or NULL if opening fails.
2947 : */
2948 :
2949 39 : FILE *CPLOpenShared(const char *pszFilename, const char *pszAccess,
2950 : int bLargeIn)
2951 :
2952 : {
2953 39 : const bool bLarge = CPL_TO_BOOL(bLargeIn);
2954 78 : CPLMutexHolderD(&hSharedFileMutex);
2955 39 : const GIntBig nPID = CPLGetPID();
2956 :
2957 : /* -------------------------------------------------------------------- */
2958 : /* Is there an existing file we can use? */
2959 : /* -------------------------------------------------------------------- */
2960 39 : const bool bReuse = EQUAL(pszAccess, "rb") || EQUAL(pszAccess, "rb+");
2961 :
2962 43 : for (int i = 0; bReuse && i < nSharedFileCount; i++)
2963 : {
2964 20 : if (strcmp(pasSharedFileList[i].pszFilename, pszFilename) == 0 &&
2965 4 : !bLarge == !pasSharedFileList[i].bLarge &&
2966 16 : EQUAL(pasSharedFileList[i].pszAccess, pszAccess) &&
2967 4 : nPID == pasSharedFileListExtra[i].nPID)
2968 : {
2969 4 : pasSharedFileList[i].nRefCount++;
2970 4 : return pasSharedFileList[i].fp;
2971 : }
2972 : }
2973 :
2974 : /* -------------------------------------------------------------------- */
2975 : /* Open the file. */
2976 : /* -------------------------------------------------------------------- */
2977 : FILE *fp = bLarge
2978 35 : ? reinterpret_cast<FILE *>(VSIFOpenL(pszFilename, pszAccess))
2979 0 : : VSIFOpen(pszFilename, pszAccess);
2980 :
2981 35 : if (fp == nullptr)
2982 9 : return nullptr;
2983 :
2984 : /* -------------------------------------------------------------------- */
2985 : /* Add an entry to the list. */
2986 : /* -------------------------------------------------------------------- */
2987 26 : nSharedFileCount++;
2988 :
2989 26 : pasSharedFileList = static_cast<CPLSharedFileInfo *>(
2990 52 : CPLRealloc(const_cast<CPLSharedFileInfo *>(pasSharedFileList),
2991 26 : sizeof(CPLSharedFileInfo) * nSharedFileCount));
2992 26 : pasSharedFileListExtra = static_cast<CPLSharedFileInfoExtra *>(
2993 52 : CPLRealloc(const_cast<CPLSharedFileInfoExtra *>(pasSharedFileListExtra),
2994 26 : sizeof(CPLSharedFileInfoExtra) * nSharedFileCount));
2995 :
2996 26 : pasSharedFileList[nSharedFileCount - 1].fp = fp;
2997 26 : pasSharedFileList[nSharedFileCount - 1].nRefCount = 1;
2998 26 : pasSharedFileList[nSharedFileCount - 1].bLarge = bLarge;
2999 52 : pasSharedFileList[nSharedFileCount - 1].pszFilename =
3000 26 : CPLStrdup(pszFilename);
3001 26 : pasSharedFileList[nSharedFileCount - 1].pszAccess = CPLStrdup(pszAccess);
3002 26 : pasSharedFileListExtra[nSharedFileCount - 1].nPID = nPID;
3003 :
3004 26 : return fp;
3005 : }
3006 :
3007 : /************************************************************************/
3008 : /* CPLCloseShared() */
3009 : /************************************************************************/
3010 :
3011 : /**
3012 : * Close shared file.
3013 : *
3014 : * Dereferences the indicated file handle, and closes it if the reference
3015 : * count has dropped to zero. A CPLError() is issued if the file is not
3016 : * in the shared file list.
3017 : *
3018 : * @param fp file handle from CPLOpenShared() to deaccess.
3019 : */
3020 :
3021 30 : void CPLCloseShared(FILE *fp)
3022 :
3023 : {
3024 30 : CPLMutexHolderD(&hSharedFileMutex);
3025 :
3026 : /* -------------------------------------------------------------------- */
3027 : /* Search for matching information. */
3028 : /* -------------------------------------------------------------------- */
3029 30 : int i = 0;
3030 32 : for (; i < nSharedFileCount && fp != pasSharedFileList[i].fp; i++)
3031 : {
3032 : }
3033 :
3034 30 : if (i == nSharedFileCount)
3035 : {
3036 0 : CPLError(CE_Failure, CPLE_AppDefined,
3037 : "Unable to find file handle %p in CPLCloseShared().", fp);
3038 0 : return;
3039 : }
3040 :
3041 : /* -------------------------------------------------------------------- */
3042 : /* Dereference and return if there are still some references. */
3043 : /* -------------------------------------------------------------------- */
3044 30 : if (--pasSharedFileList[i].nRefCount > 0)
3045 4 : return;
3046 :
3047 : /* -------------------------------------------------------------------- */
3048 : /* Close the file, and remove the information. */
3049 : /* -------------------------------------------------------------------- */
3050 26 : if (pasSharedFileList[i].bLarge)
3051 : {
3052 26 : if (VSIFCloseL(reinterpret_cast<VSILFILE *>(pasSharedFileList[i].fp)) !=
3053 : 0)
3054 : {
3055 0 : CPLError(CE_Failure, CPLE_FileIO, "Error while closing %s",
3056 0 : pasSharedFileList[i].pszFilename);
3057 : }
3058 : }
3059 : else
3060 : {
3061 0 : VSIFClose(pasSharedFileList[i].fp);
3062 : }
3063 :
3064 26 : CPLFree(pasSharedFileList[i].pszFilename);
3065 26 : CPLFree(pasSharedFileList[i].pszAccess);
3066 :
3067 26 : nSharedFileCount--;
3068 26 : memmove(
3069 26 : const_cast<CPLSharedFileInfo *>(pasSharedFileList + i),
3070 26 : const_cast<CPLSharedFileInfo *>(pasSharedFileList + nSharedFileCount),
3071 : sizeof(CPLSharedFileInfo));
3072 26 : memmove(const_cast<CPLSharedFileInfoExtra *>(pasSharedFileListExtra + i),
3073 26 : const_cast<CPLSharedFileInfoExtra *>(pasSharedFileListExtra +
3074 26 : nSharedFileCount),
3075 : sizeof(CPLSharedFileInfoExtra));
3076 :
3077 26 : if (nSharedFileCount == 0)
3078 : {
3079 23 : CPLFree(const_cast<CPLSharedFileInfo *>(pasSharedFileList));
3080 23 : pasSharedFileList = nullptr;
3081 23 : CPLFree(const_cast<CPLSharedFileInfoExtra *>(pasSharedFileListExtra));
3082 23 : pasSharedFileListExtra = nullptr;
3083 : }
3084 : }
3085 :
3086 : /************************************************************************/
3087 : /* CPLCleanupSharedFileMutex() */
3088 : /************************************************************************/
3089 :
3090 1131 : void CPLCleanupSharedFileMutex()
3091 : {
3092 1131 : if (hSharedFileMutex != nullptr)
3093 : {
3094 0 : CPLDestroyMutex(hSharedFileMutex);
3095 0 : hSharedFileMutex = nullptr;
3096 : }
3097 1131 : }
3098 :
3099 : /************************************************************************/
3100 : /* CPLGetSharedList() */
3101 : /************************************************************************/
3102 :
3103 : /**
3104 : * Fetch list of open shared files.
3105 : *
3106 : * @param pnCount place to put the count of entries.
3107 : *
3108 : * @return the pointer to the first in the array of shared file info
3109 : * structures.
3110 : */
3111 :
3112 0 : CPLSharedFileInfo *CPLGetSharedList(int *pnCount)
3113 :
3114 : {
3115 0 : if (pnCount != nullptr)
3116 0 : *pnCount = nSharedFileCount;
3117 :
3118 0 : return const_cast<CPLSharedFileInfo *>(pasSharedFileList);
3119 : }
3120 :
3121 : /************************************************************************/
3122 : /* CPLDumpSharedList() */
3123 : /************************************************************************/
3124 :
3125 : /**
3126 : * Report open shared files.
3127 : *
3128 : * Dumps all open shared files to the indicated file handle. If the
3129 : * file handle is NULL information is sent via the CPLDebug() call.
3130 : *
3131 : * @param fp File handle to write to.
3132 : */
3133 :
3134 103 : void CPLDumpSharedList(FILE *fp)
3135 :
3136 : {
3137 103 : if (nSharedFileCount > 0)
3138 : {
3139 0 : if (fp == nullptr)
3140 0 : CPLDebug("CPL", "%d Shared files open.", nSharedFileCount);
3141 : else
3142 0 : fprintf(fp, "%d Shared files open.", nSharedFileCount);
3143 : }
3144 :
3145 103 : for (int i = 0; i < nSharedFileCount; i++)
3146 : {
3147 0 : if (fp == nullptr)
3148 0 : CPLDebug("CPL", "%2d %d %4s %s", pasSharedFileList[i].nRefCount,
3149 0 : pasSharedFileList[i].bLarge,
3150 0 : pasSharedFileList[i].pszAccess,
3151 0 : pasSharedFileList[i].pszFilename);
3152 : else
3153 0 : fprintf(fp, "%2d %d %4s %s", pasSharedFileList[i].nRefCount,
3154 0 : pasSharedFileList[i].bLarge, pasSharedFileList[i].pszAccess,
3155 0 : pasSharedFileList[i].pszFilename);
3156 : }
3157 103 : }
3158 :
3159 : /************************************************************************/
3160 : /* CPLUnlinkTree() */
3161 : /************************************************************************/
3162 :
3163 : /** Recursively unlink a directory.
3164 : *
3165 : * @return 0 on successful completion, -1 if function fails.
3166 : */
3167 :
3168 53 : int CPLUnlinkTree(const char *pszPath)
3169 :
3170 : {
3171 : /* -------------------------------------------------------------------- */
3172 : /* First, ensure there is such a file. */
3173 : /* -------------------------------------------------------------------- */
3174 : VSIStatBufL sStatBuf;
3175 :
3176 53 : if (VSIStatL(pszPath, &sStatBuf) != 0)
3177 : {
3178 2 : CPLError(CE_Failure, CPLE_AppDefined,
3179 : "It seems no file system object called '%s' exists.", pszPath);
3180 :
3181 2 : return -1;
3182 : }
3183 :
3184 : /* -------------------------------------------------------------------- */
3185 : /* If it is a simple file, just delete it. */
3186 : /* -------------------------------------------------------------------- */
3187 51 : if (VSI_ISREG(sStatBuf.st_mode))
3188 : {
3189 35 : if (VSIUnlink(pszPath) != 0)
3190 : {
3191 0 : CPLError(CE_Failure, CPLE_AppDefined, "Failed to unlink %s.",
3192 : pszPath);
3193 :
3194 0 : return -1;
3195 : }
3196 :
3197 35 : return 0;
3198 : }
3199 :
3200 : /* -------------------------------------------------------------------- */
3201 : /* If it is a directory recurse then unlink the directory. */
3202 : /* -------------------------------------------------------------------- */
3203 16 : else if (VSI_ISDIR(sStatBuf.st_mode))
3204 : {
3205 16 : char **papszItems = VSIReadDir(pszPath);
3206 :
3207 32 : for (int i = 0; papszItems != nullptr && papszItems[i] != nullptr; i++)
3208 : {
3209 16 : if (papszItems[i][0] == '\0' || EQUAL(papszItems[i], ".") ||
3210 16 : EQUAL(papszItems[i], ".."))
3211 0 : continue;
3212 :
3213 : const std::string osSubPath =
3214 16 : CPLFormFilenameSafe(pszPath, papszItems[i], nullptr);
3215 :
3216 16 : const int nErr = CPLUnlinkTree(osSubPath.c_str());
3217 :
3218 16 : if (nErr != 0)
3219 : {
3220 0 : CSLDestroy(papszItems);
3221 0 : return nErr;
3222 : }
3223 : }
3224 :
3225 16 : CSLDestroy(papszItems);
3226 :
3227 16 : if (VSIRmdir(pszPath) != 0)
3228 : {
3229 0 : CPLError(CE_Failure, CPLE_AppDefined, "Failed to unlink %s.",
3230 : pszPath);
3231 :
3232 0 : return -1;
3233 : }
3234 :
3235 16 : return 0;
3236 : }
3237 :
3238 : /* -------------------------------------------------------------------- */
3239 : /* otherwise report an error. */
3240 : /* -------------------------------------------------------------------- */
3241 0 : CPLError(CE_Failure, CPLE_AppDefined,
3242 : "Failed to unlink %s.\nUnrecognised filesystem object.", pszPath);
3243 0 : return 1000;
3244 : }
3245 :
3246 : /************************************************************************/
3247 : /* CPLCopyFile() */
3248 : /************************************************************************/
3249 :
3250 : /** Copy a file */
3251 2266 : int CPLCopyFile(const char *pszNewPath, const char *pszOldPath)
3252 :
3253 : {
3254 2266 : return VSICopyFile(pszOldPath, pszNewPath, nullptr,
3255 : static_cast<vsi_l_offset>(-1), nullptr, nullptr,
3256 2266 : nullptr);
3257 : }
3258 :
3259 : /************************************************************************/
3260 : /* CPLCopyTree() */
3261 : /************************************************************************/
3262 :
3263 : /** Recursively copy a tree */
3264 4 : int CPLCopyTree(const char *pszNewPath, const char *pszOldPath)
3265 :
3266 : {
3267 : VSIStatBufL sStatBuf;
3268 4 : if (VSIStatL(pszNewPath, &sStatBuf) == 0)
3269 : {
3270 1 : CPLError(
3271 : CE_Failure, CPLE_AppDefined,
3272 : "It seems that a file system object called '%s' already exists.",
3273 : pszNewPath);
3274 :
3275 1 : return -1;
3276 : }
3277 :
3278 3 : if (VSIStatL(pszOldPath, &sStatBuf) != 0)
3279 : {
3280 1 : CPLError(CE_Failure, CPLE_AppDefined,
3281 : "It seems no file system object called '%s' exists.",
3282 : pszOldPath);
3283 :
3284 1 : return -1;
3285 : }
3286 :
3287 2 : if (VSI_ISDIR(sStatBuf.st_mode))
3288 : {
3289 1 : if (VSIMkdir(pszNewPath, 0755) != 0)
3290 : {
3291 0 : CPLError(CE_Failure, CPLE_AppDefined,
3292 : "Cannot create directory '%s'.", pszNewPath);
3293 :
3294 0 : return -1;
3295 : }
3296 :
3297 1 : char **papszItems = VSIReadDir(pszOldPath);
3298 :
3299 4 : for (int i = 0; papszItems != nullptr && papszItems[i] != nullptr; i++)
3300 : {
3301 3 : if (EQUAL(papszItems[i], ".") || EQUAL(papszItems[i], ".."))
3302 2 : continue;
3303 :
3304 : const std::string osNewSubPath =
3305 1 : CPLFormFilenameSafe(pszNewPath, papszItems[i], nullptr);
3306 : const std::string osOldSubPath =
3307 1 : CPLFormFilenameSafe(pszOldPath, papszItems[i], nullptr);
3308 :
3309 : const int nErr =
3310 1 : CPLCopyTree(osNewSubPath.c_str(), osOldSubPath.c_str());
3311 :
3312 1 : if (nErr != 0)
3313 : {
3314 0 : CSLDestroy(papszItems);
3315 0 : return nErr;
3316 : }
3317 : }
3318 1 : CSLDestroy(papszItems);
3319 :
3320 1 : return 0;
3321 : }
3322 1 : else if (VSI_ISREG(sStatBuf.st_mode))
3323 : {
3324 1 : return CPLCopyFile(pszNewPath, pszOldPath);
3325 : }
3326 : else
3327 : {
3328 0 : CPLError(CE_Failure, CPLE_AppDefined,
3329 : "Unrecognized filesystem object : '%s'.", pszOldPath);
3330 0 : return -1;
3331 : }
3332 : }
3333 :
3334 : /************************************************************************/
3335 : /* CPLMoveFile() */
3336 : /************************************************************************/
3337 :
3338 : /** Move a file */
3339 190 : int CPLMoveFile(const char *pszNewPath, const char *pszOldPath)
3340 :
3341 : {
3342 190 : if (VSIRename(pszOldPath, pszNewPath) == 0)
3343 187 : return 0;
3344 :
3345 3 : const int nRet = CPLCopyFile(pszNewPath, pszOldPath);
3346 :
3347 3 : if (nRet == 0)
3348 : {
3349 3 : if (VSIUnlink(pszOldPath) != 0)
3350 : {
3351 0 : CPLError(CE_Warning, CPLE_AppDefined, "Cannot delete '%s'",
3352 : pszOldPath);
3353 : }
3354 : }
3355 3 : return nRet;
3356 : }
3357 :
3358 : /************************************************************************/
3359 : /* CPLSymlink() */
3360 : /************************************************************************/
3361 :
3362 : /** Create a symbolic link */
3363 : #ifdef _WIN32
3364 : int CPLSymlink(const char *, const char *, CSLConstList)
3365 : {
3366 : return -1;
3367 : }
3368 : #else
3369 0 : int CPLSymlink(const char *pszOldPath, const char *pszNewPath,
3370 : CSLConstList /* papszOptions */)
3371 : {
3372 0 : return symlink(pszOldPath, pszNewPath);
3373 : }
3374 : #endif
3375 :
3376 : /************************************************************************/
3377 : /* ==================================================================== */
3378 : /* CPLLocaleC */
3379 : /* ==================================================================== */
3380 : /************************************************************************/
3381 :
3382 : //! @cond Doxygen_Suppress
3383 : /************************************************************************/
3384 : /* CPLLocaleC() */
3385 : /************************************************************************/
3386 :
3387 131 : CPLLocaleC::CPLLocaleC() : pszOldLocale(nullptr)
3388 : {
3389 131 : if (CPLTestBool(CPLGetConfigOption("GDAL_DISABLE_CPLLOCALEC", "NO")))
3390 0 : return;
3391 :
3392 131 : pszOldLocale = CPLStrdup(CPLsetlocale(LC_NUMERIC, nullptr));
3393 131 : if (EQUAL(pszOldLocale, "C") || EQUAL(pszOldLocale, "POSIX") ||
3394 0 : CPLsetlocale(LC_NUMERIC, "C") == nullptr)
3395 : {
3396 131 : CPLFree(pszOldLocale);
3397 131 : pszOldLocale = nullptr;
3398 : }
3399 : }
3400 :
3401 : /************************************************************************/
3402 : /* ~CPLLocaleC() */
3403 : /************************************************************************/
3404 :
3405 0 : CPLLocaleC::~CPLLocaleC()
3406 :
3407 : {
3408 131 : if (pszOldLocale == nullptr)
3409 131 : return;
3410 :
3411 0 : CPLsetlocale(LC_NUMERIC, pszOldLocale);
3412 0 : CPLFree(pszOldLocale);
3413 131 : }
3414 :
3415 : /************************************************************************/
3416 : /* CPLThreadLocaleCPrivate */
3417 : /************************************************************************/
3418 :
3419 : #ifdef HAVE_USELOCALE
3420 :
3421 : class CPLThreadLocaleCPrivate
3422 : {
3423 : locale_t nNewLocale;
3424 : locale_t nOldLocale;
3425 :
3426 : CPL_DISALLOW_COPY_ASSIGN(CPLThreadLocaleCPrivate)
3427 :
3428 : public:
3429 : CPLThreadLocaleCPrivate();
3430 : ~CPLThreadLocaleCPrivate();
3431 : };
3432 :
3433 0 : CPLThreadLocaleCPrivate::CPLThreadLocaleCPrivate()
3434 0 : : nNewLocale(newlocale(LC_NUMERIC_MASK, "C", nullptr)),
3435 0 : nOldLocale(uselocale(nNewLocale))
3436 : {
3437 0 : }
3438 :
3439 0 : CPLThreadLocaleCPrivate::~CPLThreadLocaleCPrivate()
3440 : {
3441 0 : uselocale(nOldLocale);
3442 0 : freelocale(nNewLocale);
3443 0 : }
3444 :
3445 : #elif defined(_MSC_VER)
3446 :
3447 : class CPLThreadLocaleCPrivate
3448 : {
3449 : int nOldValConfigThreadLocale;
3450 : char *pszOldLocale;
3451 :
3452 : CPL_DISALLOW_COPY_ASSIGN(CPLThreadLocaleCPrivate)
3453 :
3454 : public:
3455 : CPLThreadLocaleCPrivate();
3456 : ~CPLThreadLocaleCPrivate();
3457 : };
3458 :
3459 : CPLThreadLocaleCPrivate::CPLThreadLocaleCPrivate()
3460 : {
3461 : nOldValConfigThreadLocale = _configthreadlocale(_ENABLE_PER_THREAD_LOCALE);
3462 : pszOldLocale = setlocale(LC_NUMERIC, "C");
3463 : if (pszOldLocale)
3464 : pszOldLocale = CPLStrdup(pszOldLocale);
3465 : }
3466 :
3467 : CPLThreadLocaleCPrivate::~CPLThreadLocaleCPrivate()
3468 : {
3469 : if (pszOldLocale != nullptr)
3470 : {
3471 : setlocale(LC_NUMERIC, pszOldLocale);
3472 : CPLFree(pszOldLocale);
3473 : }
3474 : _configthreadlocale(nOldValConfigThreadLocale);
3475 : }
3476 :
3477 : #else
3478 :
3479 : class CPLThreadLocaleCPrivate
3480 : {
3481 : char *pszOldLocale;
3482 :
3483 : CPL_DISALLOW_COPY_ASSIGN(CPLThreadLocaleCPrivate)
3484 :
3485 : public:
3486 : CPLThreadLocaleCPrivate();
3487 : ~CPLThreadLocaleCPrivate();
3488 : };
3489 :
3490 : CPLThreadLocaleCPrivate::CPLThreadLocaleCPrivate()
3491 : : pszOldLocale(CPLStrdup(CPLsetlocale(LC_NUMERIC, nullptr)))
3492 : {
3493 : if (EQUAL(pszOldLocale, "C") || EQUAL(pszOldLocale, "POSIX") ||
3494 : CPLsetlocale(LC_NUMERIC, "C") == nullptr)
3495 : {
3496 : CPLFree(pszOldLocale);
3497 : pszOldLocale = nullptr;
3498 : }
3499 : }
3500 :
3501 : CPLThreadLocaleCPrivate::~CPLThreadLocaleCPrivate()
3502 : {
3503 : if (pszOldLocale != nullptr)
3504 : {
3505 : CPLsetlocale(LC_NUMERIC, pszOldLocale);
3506 : CPLFree(pszOldLocale);
3507 : }
3508 : }
3509 :
3510 : #endif
3511 :
3512 : /************************************************************************/
3513 : /* CPLThreadLocaleC() */
3514 : /************************************************************************/
3515 :
3516 0 : CPLThreadLocaleC::CPLThreadLocaleC() : m_private(new CPLThreadLocaleCPrivate)
3517 : {
3518 0 : }
3519 :
3520 : /************************************************************************/
3521 : /* ~CPLThreadLocaleC() */
3522 : /************************************************************************/
3523 :
3524 0 : CPLThreadLocaleC::~CPLThreadLocaleC()
3525 :
3526 : {
3527 0 : delete m_private;
3528 0 : }
3529 :
3530 : //! @endcond
3531 :
3532 : /************************************************************************/
3533 : /* CPLsetlocale() */
3534 : /************************************************************************/
3535 :
3536 : /**
3537 : * Prevents parallel executions of setlocale().
3538 : *
3539 : * Calling setlocale() concurrently from two or more threads is a
3540 : * potential data race. A mutex is used to provide a critical region so
3541 : * that only one thread at a time can be executing setlocale().
3542 : *
3543 : * The return should not be freed, and copied quickly as it may be invalidated
3544 : * by a following next call to CPLsetlocale().
3545 : *
3546 : * @param category See your compiler's documentation on setlocale.
3547 : * @param locale See your compiler's documentation on setlocale.
3548 : *
3549 : * @return See your compiler's documentation on setlocale.
3550 : */
3551 133 : char *CPLsetlocale(int category, const char *locale)
3552 : {
3553 266 : CPLMutexHolder oHolder(&hSetLocaleMutex);
3554 133 : char *pszRet = setlocale(category, locale);
3555 133 : if (pszRet == nullptr)
3556 0 : return pszRet;
3557 :
3558 : // Make it thread-locale storage.
3559 133 : return const_cast<char *>(CPLSPrintf("%s", pszRet));
3560 : }
3561 :
3562 : /************************************************************************/
3563 : /* CPLCleanupSetlocaleMutex() */
3564 : /************************************************************************/
3565 :
3566 1131 : void CPLCleanupSetlocaleMutex(void)
3567 : {
3568 1131 : if (hSetLocaleMutex != nullptr)
3569 5 : CPLDestroyMutex(hSetLocaleMutex);
3570 1131 : hSetLocaleMutex = nullptr;
3571 1131 : }
3572 :
3573 : /************************************************************************/
3574 : /* IsPowerOfTwo() */
3575 : /************************************************************************/
3576 :
3577 155 : int CPLIsPowerOfTwo(unsigned int i)
3578 : {
3579 155 : if (i == 0)
3580 0 : return FALSE;
3581 155 : return (i & (i - 1)) == 0 ? TRUE : FALSE;
3582 : }
3583 :
3584 : /************************************************************************/
3585 : /* CPLCheckForFile() */
3586 : /************************************************************************/
3587 :
3588 : /**
3589 : * Check for file existence.
3590 : *
3591 : * The function checks if a named file exists in the filesystem, hopefully
3592 : * in an efficient fashion if a sibling file list is available. It exists
3593 : * primarily to do faster file checking for functions like GDAL open methods
3594 : * that get a list of files from the target directory.
3595 : *
3596 : * If the sibling file list exists (is not NULL) it is assumed to be a list
3597 : * of files in the same directory as the target file, and it will be checked
3598 : * (case insensitively) for a match. If a match is found, pszFilename is
3599 : * updated with the correct case and TRUE is returned.
3600 : *
3601 : * If papszSiblingFiles is NULL, a VSIStatL() is used to test for the files
3602 : * existence, and no case insensitive testing is done.
3603 : *
3604 : * @param pszFilename name of file to check for - filename case updated in
3605 : * some cases.
3606 : * @param papszSiblingFiles a list of files in the same directory as
3607 : * pszFilename if available, or NULL. This list should have no path components.
3608 : *
3609 : * @return TRUE if a match is found, or FALSE if not.
3610 : */
3611 :
3612 172575 : int CPLCheckForFile(char *pszFilename, CSLConstList papszSiblingFiles)
3613 :
3614 : {
3615 : /* -------------------------------------------------------------------- */
3616 : /* Fallback case if we don't have a sibling file list. */
3617 : /* -------------------------------------------------------------------- */
3618 172575 : if (papszSiblingFiles == nullptr)
3619 : {
3620 : VSIStatBufL sStatBuf;
3621 :
3622 11793 : return VSIStatExL(pszFilename, &sStatBuf, VSI_STAT_EXISTS_FLAG) == 0;
3623 : }
3624 :
3625 : /* -------------------------------------------------------------------- */
3626 : /* We have sibling files, compare the non-path filename portion */
3627 : /* of pszFilename too all entries. */
3628 : /* -------------------------------------------------------------------- */
3629 321563 : const CPLString osFileOnly = CPLGetFilename(pszFilename);
3630 :
3631 17215400 : for (int i = 0; papszSiblingFiles[i] != nullptr; i++)
3632 : {
3633 17054800 : if (EQUAL(papszSiblingFiles[i], osFileOnly))
3634 : {
3635 310 : strcpy(pszFilename + strlen(pszFilename) - osFileOnly.size(),
3636 155 : papszSiblingFiles[i]);
3637 155 : return TRUE;
3638 : }
3639 : }
3640 :
3641 160626 : return FALSE;
3642 : }
3643 :
3644 : /************************************************************************/
3645 : /* Stub implementation of zip services if we don't have libz. */
3646 : /************************************************************************/
3647 :
3648 : #if !defined(HAVE_LIBZ)
3649 :
3650 : void *CPLCreateZip(const char *, char **)
3651 :
3652 : {
3653 : CPLError(CE_Failure, CPLE_NotSupported,
3654 : "This GDAL/OGR build does not include zlib and zip services.");
3655 : return nullptr;
3656 : }
3657 :
3658 : CPLErr CPLCreateFileInZip(void *, const char *, char **)
3659 : {
3660 : return CE_Failure;
3661 : }
3662 :
3663 : CPLErr CPLWriteFileInZip(void *, const void *, int)
3664 : {
3665 : return CE_Failure;
3666 : }
3667 :
3668 : CPLErr CPLCloseFileInZip(void *)
3669 : {
3670 : return CE_Failure;
3671 : }
3672 :
3673 : CPLErr CPLCloseZip(void *)
3674 : {
3675 : return CE_Failure;
3676 : }
3677 :
3678 : void *CPLZLibDeflate(const void *, size_t, int, void *, size_t,
3679 : size_t *pnOutBytes)
3680 : {
3681 : if (pnOutBytes != nullptr)
3682 : *pnOutBytes = 0;
3683 : return nullptr;
3684 : }
3685 :
3686 : void *CPLZLibInflate(const void *, size_t, void *, size_t, size_t *pnOutBytes)
3687 : {
3688 : if (pnOutBytes != nullptr)
3689 : *pnOutBytes = 0;
3690 : return nullptr;
3691 : }
3692 :
3693 : #endif /* !defined(HAVE_LIBZ) */
3694 :
3695 : /************************************************************************/
3696 : /* ==================================================================== */
3697 : /* CPLConfigOptionSetter */
3698 : /* ==================================================================== */
3699 : /************************************************************************/
3700 :
3701 : //! @cond Doxygen_Suppress
3702 : /************************************************************************/
3703 : /* CPLConfigOptionSetter() */
3704 : /************************************************************************/
3705 :
3706 27042 : CPLConfigOptionSetter::CPLConfigOptionSetter(const char *pszKey,
3707 : const char *pszValue,
3708 27042 : bool bSetOnlyIfUndefined)
3709 27042 : : m_pszKey(CPLStrdup(pszKey)), m_pszOldValue(nullptr),
3710 27033 : m_bRestoreOldValue(false)
3711 : {
3712 27033 : const char *pszOldValue = CPLGetThreadLocalConfigOption(pszKey, nullptr);
3713 43397 : if ((bSetOnlyIfUndefined &&
3714 37728 : CPLGetConfigOption(pszKey, nullptr) == nullptr) ||
3715 10705 : !bSetOnlyIfUndefined)
3716 : {
3717 27039 : m_bRestoreOldValue = true;
3718 27039 : if (pszOldValue)
3719 665 : m_pszOldValue = CPLStrdup(pszOldValue);
3720 27039 : CPLSetThreadLocalConfigOption(pszKey,
3721 : pszValue ? pszValue : CPL_NULL_VALUE);
3722 : }
3723 26836 : }
3724 :
3725 : /************************************************************************/
3726 : /* ~CPLConfigOptionSetter() */
3727 : /************************************************************************/
3728 :
3729 53724 : CPLConfigOptionSetter::~CPLConfigOptionSetter()
3730 : {
3731 26887 : if (m_bRestoreOldValue)
3732 : {
3733 26843 : CPLSetThreadLocalConfigOption(m_pszKey, m_pszOldValue);
3734 26843 : CPLFree(m_pszOldValue);
3735 : }
3736 26877 : CPLFree(m_pszKey);
3737 26837 : }
3738 :
3739 : //! @endcond
3740 :
3741 : /************************************************************************/
3742 : /* CPLIsInteractive() */
3743 : /************************************************************************/
3744 :
3745 : /** Returns whether the provided file refers to a terminal.
3746 : *
3747 : * This function is a wrapper of the ``isatty()`` POSIX function.
3748 : *
3749 : * @param f File to test. Typically stdin, stdout or stderr
3750 : * @return true if it is an open file referring to a terminal.
3751 : * @since GDAL 3.11
3752 : */
3753 653 : bool CPLIsInteractive(FILE *f)
3754 : {
3755 : #ifndef _WIN32
3756 653 : return isatty(static_cast<int>(fileno(f)));
3757 : #else
3758 : return _isatty(_fileno(f));
3759 : #endif
3760 : }
3761 :
3762 : /************************************************************************/
3763 : /* CPLLockFileStruct */
3764 : /************************************************************************/
3765 :
3766 : //! @cond Doxygen_Suppress
3767 : struct CPLLockFileStruct
3768 : {
3769 : std::string osLockFilename{};
3770 : std::atomic<bool> bStop = false;
3771 : CPLJoinableThread *hThread = nullptr;
3772 : };
3773 :
3774 : //! @endcond
3775 :
3776 : /************************************************************************/
3777 : /* CPLLockFileEx() */
3778 : /************************************************************************/
3779 :
3780 : /** Create and acquire a lock file.
3781 : *
3782 : * Only one caller can acquire the lock file at a time. The O_CREAT|O_EXCL
3783 : * flags of open() are used for that purpose (there might be limitations for
3784 : * network file systems).
3785 : *
3786 : * The lock file is continuously touched by a thread started by this function,
3787 : * to indicate it is still alive. If an existing lock file is found that has
3788 : * not been recently refreshed it will be considered stalled, and will be
3789 : * deleted before attempting to recreate it.
3790 : *
3791 : * This function must be paired with CPLUnlockFileEx().
3792 : *
3793 : * Available options are:
3794 : * <ul>
3795 : * <li>WAIT_TIME=value_in_sec/inf: Maximum amount of time in second that this
3796 : * function can spend waiting for the lock. If not set, default to infinity.
3797 : * </li>
3798 : * <li>STALLED_DELAY=value_in_sec: Delay in second to consider that an existing
3799 : * lock file that has not been touched since STALLED_DELAY is stalled, and can
3800 : * be re-acquired. Defaults to 10 seconds.
3801 : * </li>
3802 : * <li>VERBOSE_WAIT_MESSAGE=YES/NO: Whether to emit a CE_Warning message while
3803 : * waiting for a busy lock. Default to NO.
3804 : * </li>
3805 : * </ul>
3806 :
3807 : * @param pszLockFileName Lock file name. The directory must already exist.
3808 : * Must not be NULL.
3809 : * @param[out] phLockFileHandle Pointer to at location where to store the lock
3810 : * handle that must be passed to CPLUnlockFileEx().
3811 : * *phLockFileHandle will be null if the return
3812 : * code of that function is not CLFS_OK.
3813 : * @param papszOptions NULL terminated list of strings, or NULL.
3814 : *
3815 : * @return lock file status.
3816 : *
3817 : * @since 3.11
3818 : */
3819 15 : CPLLockFileStatus CPLLockFileEx(const char *pszLockFileName,
3820 : CPLLockFileHandle *phLockFileHandle,
3821 : CSLConstList papszOptions)
3822 : {
3823 15 : if (!pszLockFileName || !phLockFileHandle)
3824 2 : return CLFS_API_MISUSE;
3825 :
3826 13 : *phLockFileHandle = nullptr;
3827 :
3828 : const double dfWaitTime =
3829 13 : CPLAtof(CSLFetchNameValueDef(papszOptions, "WAIT_TIME", "inf"));
3830 : const double dfStalledDelay =
3831 13 : CPLAtof(CSLFetchNameValueDef(papszOptions, "STALLED_DELAY", "10"));
3832 : const bool bVerboseWait =
3833 13 : CPLFetchBool(papszOptions, "VERBOSE_WAIT_MESSAGE", false);
3834 :
3835 14 : for (int i = 0; i < 2; ++i)
3836 : {
3837 : #ifdef _WIN32
3838 : wchar_t *pwszFilename =
3839 : CPLRecodeToWChar(pszLockFileName, CPL_ENC_UTF8, CPL_ENC_UCS2);
3840 : int fd = _wopen(pwszFilename, _O_CREAT | _O_EXCL, _S_IREAD | _S_IWRITE);
3841 : CPLFree(pwszFilename);
3842 : #else
3843 14 : int fd = open(pszLockFileName, O_CREAT | O_EXCL, S_IRUSR | S_IWUSR);
3844 : #endif
3845 14 : if (fd == -1)
3846 : {
3847 3 : if (errno != EEXIST || i == 1)
3848 : {
3849 0 : return CLFS_CANNOT_CREATE_LOCK;
3850 : }
3851 : else
3852 : {
3853 : // Wait for the .lock file to have been removed or
3854 : // not refreshed since dfStalledDelay seconds.
3855 3 : double dfCurWaitTime = dfWaitTime;
3856 : VSIStatBufL sStat;
3857 15 : while (VSIStatL(pszLockFileName, &sStat) == 0 &&
3858 7 : static_cast<double>(sStat.st_mtime) + dfStalledDelay >
3859 7 : static_cast<double>(time(nullptr)))
3860 : {
3861 6 : if (dfCurWaitTime <= 1e-5)
3862 2 : return CLFS_LOCK_BUSY;
3863 :
3864 5 : if (bVerboseWait)
3865 : {
3866 4 : CPLError(CE_Warning, CPLE_AppDefined,
3867 : "Waiting for %s to be freed...",
3868 : pszLockFileName);
3869 : }
3870 : else
3871 : {
3872 1 : CPLDebug("CPL", "Waiting for %s to be freed...",
3873 : pszLockFileName);
3874 : }
3875 :
3876 5 : const double dfPauseDelay = std::min(0.5, dfWaitTime);
3877 5 : CPLSleep(dfPauseDelay);
3878 5 : dfCurWaitTime -= dfPauseDelay;
3879 : }
3880 :
3881 2 : if (VSIUnlink(pszLockFileName) != 0)
3882 : {
3883 1 : return CLFS_CANNOT_CREATE_LOCK;
3884 : }
3885 : }
3886 : }
3887 : else
3888 : {
3889 11 : close(fd);
3890 11 : break;
3891 : }
3892 : }
3893 :
3894 : // Touch regularly the lock file to show it is still alive
3895 : struct KeepAliveLockFile
3896 : {
3897 11 : static void func(void *user_data)
3898 : {
3899 11 : CPLLockFileHandle hLockFileHandle =
3900 : static_cast<CPLLockFileHandle>(user_data);
3901 23 : while (!hLockFileHandle->bStop)
3902 : {
3903 : auto f = VSIVirtualHandleUniquePtr(
3904 24 : VSIFOpenL(hLockFileHandle->osLockFilename.c_str(), "wb"));
3905 12 : if (f)
3906 : {
3907 12 : f.reset();
3908 : }
3909 12 : constexpr double REFRESH_DELAY = 0.5;
3910 12 : CPLSleep(REFRESH_DELAY);
3911 : }
3912 11 : }
3913 : };
3914 :
3915 11 : *phLockFileHandle = new CPLLockFileStruct();
3916 11 : (*phLockFileHandle)->osLockFilename = pszLockFileName;
3917 :
3918 22 : (*phLockFileHandle)->hThread =
3919 11 : CPLCreateJoinableThread(KeepAliveLockFile::func, *phLockFileHandle);
3920 11 : if ((*phLockFileHandle)->hThread == nullptr)
3921 : {
3922 0 : VSIUnlink(pszLockFileName);
3923 0 : delete *phLockFileHandle;
3924 0 : *phLockFileHandle = nullptr;
3925 0 : return CLFS_THREAD_CREATION_FAILED;
3926 : }
3927 :
3928 11 : return CLFS_OK;
3929 : }
3930 :
3931 : /************************************************************************/
3932 : /* CPLUnlockFileEx() */
3933 : /************************************************************************/
3934 :
3935 : /** Release and delete a lock file.
3936 : *
3937 : * This function must be paired with CPLLockFileEx().
3938 : *
3939 : * @param hLockFileHandle Lock handle (value of *phLockFileHandle argument
3940 : * set by CPLLockFileEx()), or NULL.
3941 : *
3942 : * @since 3.11
3943 : */
3944 12 : void CPLUnlockFileEx(CPLLockFileHandle hLockFileHandle)
3945 : {
3946 12 : if (hLockFileHandle)
3947 : {
3948 : // Remove .lock file
3949 11 : hLockFileHandle->bStop = true;
3950 11 : CPLJoinThread(hLockFileHandle->hThread);
3951 11 : VSIUnlink(hLockFileHandle->osLockFilename.c_str());
3952 :
3953 11 : delete hLockFileHandle;
3954 : }
3955 12 : }
3956 :
3957 : /************************************************************************/
3958 : /* CPLFormatReadableFileSize() */
3959 : /************************************************************************/
3960 :
3961 : template <class T>
3962 10 : static std::string CPLFormatReadableFileSizeInternal(T nSizeInBytes)
3963 : {
3964 10 : constexpr T ONE_MEGA_BYTE = 1000 * 1000;
3965 10 : constexpr T ONE_GIGA_BYTE = 1000 * ONE_MEGA_BYTE;
3966 10 : constexpr T ONE_TERA_BYTE = 1000 * ONE_GIGA_BYTE;
3967 10 : constexpr T ONE_PETA_BYTE = 1000 * ONE_TERA_BYTE;
3968 10 : constexpr T ONE_HEXA_BYTE = 1000 * ONE_PETA_BYTE;
3969 :
3970 10 : if (nSizeInBytes > ONE_HEXA_BYTE)
3971 : return CPLSPrintf("%.02f HB", static_cast<double>(nSizeInBytes) /
3972 2 : static_cast<double>(ONE_HEXA_BYTE));
3973 :
3974 8 : if (nSizeInBytes > ONE_PETA_BYTE)
3975 : return CPLSPrintf("%.02f PB", static_cast<double>(nSizeInBytes) /
3976 2 : static_cast<double>(ONE_PETA_BYTE));
3977 :
3978 6 : if (nSizeInBytes > ONE_TERA_BYTE)
3979 : return CPLSPrintf("%.02f TB", static_cast<double>(nSizeInBytes) /
3980 1 : static_cast<double>(ONE_TERA_BYTE));
3981 :
3982 5 : if (nSizeInBytes > ONE_GIGA_BYTE)
3983 : return CPLSPrintf("%.02f GB", static_cast<double>(nSizeInBytes) /
3984 3 : static_cast<double>(ONE_GIGA_BYTE));
3985 :
3986 2 : if (nSizeInBytes > ONE_MEGA_BYTE)
3987 : return CPLSPrintf("%.02f MB", static_cast<double>(nSizeInBytes) /
3988 1 : static_cast<double>(ONE_MEGA_BYTE));
3989 :
3990 : return CPLSPrintf("%03d,%03d bytes", static_cast<int>(nSizeInBytes) / 1000,
3991 1 : static_cast<int>(nSizeInBytes) % 1000);
3992 : }
3993 :
3994 : /** Return a file size in a human readable way.
3995 : *
3996 : * e.g 1200000 -> "1.20 MB"
3997 : *
3998 : * @since 3.12
3999 : */
4000 3 : std::string CPLFormatReadableFileSize(uint64_t nSizeInBytes)
4001 : {
4002 3 : return CPLFormatReadableFileSizeInternal(nSizeInBytes);
4003 : }
4004 :
4005 : /** Return a file size in a human readable way.
4006 : *
4007 : * e.g 1200000 -> "1.20 MB"
4008 : *
4009 : * @since 3.12
4010 : */
4011 7 : std::string CPLFormatReadableFileSize(double dfSizeInBytes)
4012 : {
4013 7 : return CPLFormatReadableFileSizeInternal(dfSizeInBytes);
4014 : }
4015 :
4016 : /************************************************************************/
4017 : /* CPLGetRemainingFileDescriptorCount() */
4018 : /************************************************************************/
4019 :
4020 : /** \fn CPLGetRemainingFileDescriptorCount()
4021 : *
4022 : * Return the number of file descriptors that can still be opened by the
4023 : * current process.
4024 : *
4025 : * Only implemented on non-Windows operating systems
4026 : *
4027 : * Return a negative value in case of error or not implemented.
4028 : *
4029 : * @since 3.12
4030 : */
4031 :
4032 : #if defined(__FreeBSD__)
4033 :
4034 : int CPLGetRemainingFileDescriptorCount()
4035 : {
4036 : struct rlimit limitNumberOfFilesPerProcess;
4037 : if (getrlimit(RLIMIT_NOFILE, &limitNumberOfFilesPerProcess) != 0)
4038 : {
4039 : return -1;
4040 : }
4041 : const int maxNumberOfFilesPerProcess =
4042 : static_cast<int>(limitNumberOfFilesPerProcess.rlim_cur);
4043 :
4044 : const pid_t pid = getpid();
4045 : int mib[4] = {CTL_KERN, KERN_PROC, KERN_PROC_FILEDESC,
4046 : static_cast<int>(pid)};
4047 :
4048 : size_t len = 0;
4049 :
4050 : if (sysctl(mib, 4, nullptr, &len, nullptr, 0) == -1)
4051 : {
4052 : return -1;
4053 : }
4054 :
4055 : return maxNumberOfFilesPerProcess -
4056 : static_cast<int>(len / sizeof(struct kinfo_file));
4057 : }
4058 :
4059 : #else
4060 :
4061 118 : int CPLGetRemainingFileDescriptorCount()
4062 : {
4063 : #if !defined(_WIN32) && HAVE_GETRLIMIT
4064 : struct rlimit limitNumberOfFilesPerProcess;
4065 118 : if (getrlimit(RLIMIT_NOFILE, &limitNumberOfFilesPerProcess) != 0)
4066 : {
4067 0 : return -1;
4068 : }
4069 118 : const int maxNumberOfFilesPerProcess =
4070 118 : static_cast<int>(limitNumberOfFilesPerProcess.rlim_cur);
4071 :
4072 118 : int countFilesInUse = 0;
4073 : {
4074 118 : const char *const apszOptions[] = {"NAME_AND_TYPE_ONLY=YES", nullptr};
4075 : #ifdef __linux
4076 118 : VSIDIR *dir = VSIOpenDir("/proc/self/fd", 0, apszOptions);
4077 : #else
4078 : // MacOSX
4079 : VSIDIR *dir = VSIOpenDir("/dev/fd", 0, apszOptions);
4080 : #endif
4081 118 : if (dir)
4082 : {
4083 1610 : while (VSIGetNextDirEntry(dir))
4084 1492 : ++countFilesInUse;
4085 118 : countFilesInUse -= 2; // do not count . and ..
4086 118 : VSICloseDir(dir);
4087 : }
4088 : }
4089 :
4090 118 : if (countFilesInUse <= 0)
4091 : {
4092 : // Fallback if above method does not work
4093 0 : for (int fd = 0; fd < maxNumberOfFilesPerProcess; fd++)
4094 : {
4095 0 : errno = 0;
4096 0 : if (fcntl(fd, F_GETFD) != -1 || errno != EBADF)
4097 : {
4098 0 : countFilesInUse++;
4099 : }
4100 : }
4101 : }
4102 :
4103 118 : return maxNumberOfFilesPerProcess - countFilesInUse;
4104 : #else
4105 : return -1;
4106 : #endif
4107 : }
4108 :
4109 : #endif
|