Coverage Report

Created: 2025-08-28 06:57

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