Coverage Report

Created: 2026-07-25 06:50

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/gdal/port/cpl_string.cpp
Line
Count
Source
1
/**********************************************************************
2
 *
3
 * Name:     cpl_string.cpp
4
 * Project:  CPL - Common Portability Library
5
 * Purpose:  String and Stringlist manipulation functions.
6
 * Author:   Daniel Morissette, danmo@videotron.ca
7
 *
8
 **********************************************************************
9
 * Copyright (c) 1998, Daniel Morissette
10
 * Copyright (c) 2008-2013, Even Rouault <even dot rouault at spatialys.com>
11
 *
12
 * SPDX-License-Identifier: MIT
13
 **********************************************************************
14
 *
15
 * Independent Security Audit 2003/04/04 Andrey Kiselev:
16
 *   Completed audit of this module. All functions may be used without buffer
17
 *   overflows and stack corruptions with any kind of input data strings with
18
 *   except of CPLSPrintf() and CSLAppendPrintf() (see note below).
19
 *
20
 * Security Audit 2003/03/28 warmerda:
21
 *   Completed security audit.  I believe that this module may be safely used
22
 *   to parse tokenize arbitrary input strings, assemble arbitrary sets of
23
 *   names values into string lists, unescape and escape text even if provided
24
 *   by a potentially hostile source.
25
 *
26
 *   CPLSPrintf() and CSLAppendPrintf() may not be safely invoked on
27
 *   arbitrary length inputs since it has a fixed size output buffer on system
28
 *   without vsnprintf().
29
 *
30
 **********************************************************************/
31
32
#undef WARN_STANDARD_PRINTF
33
34
#include "cpl_port.h"
35
#include "cpl_string.h"
36
37
#include <algorithm>
38
#include <cctype>
39
#include <climits>
40
#include <cmath>
41
#include <cstdlib>
42
#include <cstring>
43
44
#include <limits>
45
46
#include "cpl_config.h"
47
#include "cpl_multiproc.h"
48
#include "cpl_vsi.h"
49
50
#if !defined(va_copy) && defined(__va_copy)
51
#define va_copy __va_copy
52
#endif
53
54
/*=====================================================================
55
                    StringList manipulation functions.
56
 =====================================================================*/
57
58
/**********************************************************************
59
 *                       CSLAddString()
60
 **********************************************************************/
61
62
/** Append a string to a StringList and return a pointer to the modified
63
 * StringList.
64
 *
65
 * If the input StringList is NULL, then a new StringList is created.
66
 * Note that CSLAddString performance when building a list is in O(n^2)
67
 * which can cause noticeable slow down when n > 10000.
68
 */
69
char **CSLAddString(char **papszStrList, const char *pszNewString)
70
2.37k
{
71
2.37k
    char **papszRet = CSLAddStringMayFail(papszStrList, pszNewString);
72
2.37k
    if (papszRet == nullptr && pszNewString != nullptr)
73
0
        abort();
74
2.37k
    return papszRet;
75
2.37k
}
76
77
/** Same as CSLAddString() but may return NULL in case of (memory) failure */
78
char **CSLAddStringMayFail(char **papszStrList, const char *pszNewString)
79
2.37k
{
80
2.37k
    if (pszNewString == nullptr)
81
0
        return papszStrList;  // Nothing to do!
82
83
2.37k
    char *pszDup = VSI_STRDUP_VERBOSE(pszNewString);
84
2.37k
    if (pszDup == nullptr)
85
0
        return nullptr;
86
87
    // Allocate room for the new string.
88
2.37k
    char **papszStrListNew = nullptr;
89
2.37k
    int nItems = 0;
90
91
2.37k
    if (papszStrList == nullptr)
92
1
        papszStrListNew =
93
1
            static_cast<char **>(VSI_CALLOC_VERBOSE(2, sizeof(char *)));
94
2.37k
    else
95
2.37k
    {
96
2.37k
        nItems = CSLCount(papszStrList);
97
2.37k
        papszStrListNew = static_cast<char **>(
98
2.37k
            VSI_REALLOC_VERBOSE(papszStrList, (nItems + 2) * sizeof(char *)));
99
2.37k
    }
100
2.37k
    if (papszStrListNew == nullptr)
101
0
    {
102
0
        VSIFree(pszDup);
103
0
        return nullptr;
104
0
    }
105
106
    // Copy the string in the list.
107
2.37k
    papszStrListNew[nItems] = pszDup;
108
2.37k
    papszStrListNew[nItems + 1] = nullptr;
109
110
2.37k
    return papszStrListNew;
111
2.37k
}
112
113
/************************************************************************/
114
/*                              CSLCount()                              */
115
/************************************************************************/
116
117
/**
118
 * Return number of items in a string list.
119
 *
120
 * Returns the number of items in a string list, not counting the
121
 * terminating NULL.  Passing in NULL is safe, and will result in a count
122
 * of zero.
123
 *
124
 * Lists are counted by iterating through them so long lists will
125
 * take more time than short lists.  Care should be taken to avoid using
126
 * CSLCount() as an end condition for loops as it will result in O(n^2)
127
 * behavior.
128
 *
129
 * @param papszStrList the string list to count.
130
 *
131
 * @return the number of entries.
132
 */
133
int CSLCount(CSLConstList papszStrList)
134
3.12k
{
135
3.12k
    if (!papszStrList)
136
0
        return 0;
137
138
3.12k
    int nItems = 0;
139
140
2.83M
    while (*papszStrList != nullptr)
141
2.83M
    {
142
2.83M
        ++nItems;
143
2.83M
        ++papszStrList;
144
2.83M
    }
145
146
3.12k
    return nItems;
147
3.12k
}
148
149
/************************************************************************/
150
/*                            CSLGetField()                             */
151
/************************************************************************/
152
153
/**
154
 * Fetches the indicated field, being careful not to crash if the field
155
 * doesn't exist within this string list.
156
 *
157
 * The returned pointer should not be freed, and doesn't necessarily last long.
158
 */
159
const char *CSLGetField(CSLConstList papszStrList, int iField)
160
161
0
{
162
0
    if (papszStrList == nullptr || iField < 0)
163
0
        return ("");
164
165
0
    for (int i = 0; i < iField + 1; i++)
166
0
    {
167
0
        if (papszStrList[i] == nullptr)
168
0
            return "";
169
0
    }
170
171
0
    return (papszStrList[iField]);
172
0
}
173
174
/************************************************************************/
175
/*                             CSLDestroy()                             */
176
/************************************************************************/
177
178
/**
179
 * Free string list.
180
 *
181
 * Frees the passed string list (null terminated array of strings).
182
 * It is safe to pass NULL.
183
 *
184
 * @param papszStrList the list to free.
185
 */
186
void CPL_STDCALL CSLDestroy(char **papszStrList)
187
1.13k
{
188
1.13k
    if (!papszStrList)
189
29
        return;
190
191
34.5k
    for (char **papszPtr = papszStrList; *papszPtr != nullptr; ++papszPtr)
192
33.4k
    {
193
33.4k
        CPLFree(*papszPtr);
194
33.4k
    }
195
196
1.10k
    CPLFree(papszStrList);
197
1.10k
}
198
199
/************************************************************************/
200
/*                            CSLDuplicate()                            */
201
/************************************************************************/
202
203
/**
204
 * Clone a string list.
205
 *
206
 * Efficiently allocates a copy of a string list.  The returned list is
207
 * owned by the caller and should be freed with CSLDestroy().
208
 *
209
 * @param papszStrList the input string list.
210
 *
211
 * @return newly allocated copy.
212
 */
213
214
char **CSLDuplicate(CSLConstList papszStrList)
215
755
{
216
755
    const int nLines = CSLCount(papszStrList);
217
218
755
    if (nLines == 0)
219
29
        return nullptr;
220
221
726
    CSLConstList papszSrc = papszStrList;
222
223
726
    char **papszNewList =
224
726
        static_cast<char **>(VSI_MALLOC2_VERBOSE(nLines + 1, sizeof(char *)));
225
226
726
    char **papszDst = papszNewList;
227
228
19.6k
    for (; *papszSrc != nullptr; ++papszSrc, ++papszDst)
229
18.9k
    {
230
18.9k
        *papszDst = VSI_STRDUP_VERBOSE(*papszSrc);
231
18.9k
        if (*papszDst == nullptr)
232
0
        {
233
0
            CSLDestroy(papszNewList);
234
0
            return nullptr;
235
0
        }
236
18.9k
    }
237
726
    *papszDst = nullptr;
238
239
726
    return papszNewList;
240
726
}
241
242
/************************************************************************/
243
/*                               CSLMerge                               */
244
/************************************************************************/
245
246
/**
247
 * \brief Merge two lists.
248
 *
249
 * The two lists are merged, ensuring that if any keys appear in both
250
 * that the value from the second (papszOverride) list take precedence.
251
 *
252
 * @param papszOrig the original list, being modified.
253
 * @param papszOverride the list of items being merged in.  This list
254
 * is unaltered and remains owned by the caller.
255
 *
256
 * @return updated list.
257
 */
258
259
char **CSLMerge(char **papszOrig, CSLConstList papszOverride)
260
261
0
{
262
0
    if (papszOrig == nullptr && papszOverride != nullptr)
263
0
        return CSLDuplicate(papszOverride);
264
265
0
    if (papszOverride == nullptr)
266
0
        return papszOrig;
267
268
0
    for (int i = 0; papszOverride[i] != nullptr; ++i)
269
0
    {
270
0
        char *pszKey = nullptr;
271
0
        const char *pszValue = CPLParseNameValue(papszOverride[i], &pszKey);
272
273
0
        papszOrig = CSLSetNameValue(papszOrig, pszKey, pszValue);
274
0
        CPLFree(pszKey);
275
0
    }
276
277
0
    return papszOrig;
278
0
}
279
280
/************************************************************************/
281
/*                              CSLLoad2()                              */
282
/************************************************************************/
283
284
/**
285
 * Load a text file into a string list.
286
 *
287
 * The VSI*L API is used, so VSIFOpenL() supported objects that aren't
288
 * physical files can also be accessed.  Files are returned as a string list,
289
 * with one item in the string list per line.  End of line markers are
290
 * stripped (by CPLReadLineL()).
291
 *
292
 * If reading the file fails a CPLError() will be issued and NULL returned.
293
 *
294
 * @param pszFname the name of the file to read.
295
 * @param nMaxLines maximum number of lines to read before stopping, or -1 for
296
 * no limit.
297
 * @param nMaxCols maximum number of characters in a line before stopping, or -1
298
 * for no limit.
299
 * @param papszOptions NULL-terminated array of options. Unused for now.
300
 *
301
 * @return a string list with the files lines, now owned by caller. To be freed
302
 * with CSLDestroy()
303
 *
304
 */
305
306
char **CSLLoad2(const char *pszFname, int nMaxLines, int nMaxCols,
307
                CSLConstList papszOptions)
308
0
{
309
0
    VSILFILE *fp = VSIFOpenL(pszFname, "rb");
310
311
0
    if (!fp)
312
0
    {
313
0
        if (CPLFetchBool(papszOptions, "EMIT_ERROR_IF_CANNOT_OPEN_FILE", true))
314
0
        {
315
            // Unable to open file.
316
0
            CPLError(CE_Failure, CPLE_OpenFailed,
317
0
                     "CSLLoad2(\"%s\") failed: unable to open file.", pszFname);
318
0
        }
319
0
        return nullptr;
320
0
    }
321
322
0
    char **papszStrList = nullptr;
323
0
    int nLines = 0;
324
0
    int nAllocatedLines = 0;
325
326
0
    while (!VSIFEofL(fp) && (nMaxLines == -1 || nLines < nMaxLines))
327
0
    {
328
0
        const char *pszLine = CPLReadLine2L(fp, nMaxCols, papszOptions);
329
0
        if (pszLine == nullptr)
330
0
            break;
331
332
0
        if (nLines + 1 >= nAllocatedLines)
333
0
        {
334
0
            nAllocatedLines = 16 + nAllocatedLines * 2;
335
0
            char **papszStrListNew = static_cast<char **>(
336
0
                VSIRealloc(papszStrList, nAllocatedLines * sizeof(char *)));
337
0
            if (papszStrListNew == nullptr)
338
0
            {
339
0
                CPL_IGNORE_RET_VAL(VSIFCloseL(fp));
340
0
                CPLReadLineL(nullptr);
341
0
                CPLError(CE_Failure, CPLE_OutOfMemory,
342
0
                         "CSLLoad2(\"%s\") "
343
0
                         "failed: not enough memory to allocate lines.",
344
0
                         pszFname);
345
0
                return papszStrList;
346
0
            }
347
0
            papszStrList = papszStrListNew;
348
0
        }
349
0
        papszStrList[nLines] = CPLStrdup(pszLine);
350
0
        papszStrList[nLines + 1] = nullptr;
351
0
        ++nLines;
352
0
    }
353
354
0
    CPL_IGNORE_RET_VAL(VSIFCloseL(fp));
355
356
    // Free the internal thread local line buffer.
357
0
    CPLReadLineL(nullptr);
358
359
0
    return papszStrList;
360
0
}
361
362
/************************************************************************/
363
/*                              CSLLoad()                               */
364
/************************************************************************/
365
366
/**
367
 * Load a text file into a string list.
368
 *
369
 * The VSI*L API is used, so VSIFOpenL() supported objects that aren't
370
 * physical files can also be accessed.  Files are returned as a string list,
371
 * with one item in the string list per line.  End of line markers are
372
 * stripped (by CPLReadLineL()).
373
 *
374
 * If reading the file fails a CPLError() will be issued and NULL returned.
375
 *
376
 * @param pszFname the name of the file to read.
377
 *
378
 * @return a string list with the files lines, now owned by caller. To be freed
379
 * with CSLDestroy()
380
 */
381
382
char **CSLLoad(const char *pszFname)
383
0
{
384
0
    return CSLLoad2(pszFname, -1, -1, nullptr);
385
0
}
386
387
/**********************************************************************
388
 *                       CSLSave()
389
 **********************************************************************/
390
391
/** Write a StringList to a text file.
392
 *
393
 * Returns the number of lines written, or 0 if the file could not
394
 * be written.
395
 */
396
397
int CSLSave(CSLConstList papszStrList, const char *pszFname)
398
0
{
399
0
    if (papszStrList == nullptr)
400
0
        return 0;
401
402
0
    VSILFILE *fp = VSIFOpenL(pszFname, "wt");
403
0
    if (fp == nullptr)
404
0
    {
405
        // Unable to open file.
406
0
        CPLError(CE_Failure, CPLE_OpenFailed,
407
0
                 "CSLSave(\"%s\") failed: unable to open output file.",
408
0
                 pszFname);
409
0
        return 0;
410
0
    }
411
412
0
    int nLines = 0;
413
0
    while (*papszStrList != nullptr)
414
0
    {
415
0
        if (VSIFPrintfL(fp, "%s\n", *papszStrList) < 1)
416
0
        {
417
0
            CPLError(CE_Failure, CPLE_FileIO,
418
0
                     "CSLSave(\"%s\") failed: unable to write to output file.",
419
0
                     pszFname);
420
0
            break;  // A Problem happened... abort.
421
0
        }
422
423
0
        ++nLines;
424
0
        ++papszStrList;
425
0
    }
426
427
0
    if (VSIFCloseL(fp) != 0)
428
0
    {
429
0
        CPLError(CE_Failure, CPLE_FileIO,
430
0
                 "CSLSave(\"%s\") failed: unable to write to output file.",
431
0
                 pszFname);
432
0
    }
433
434
0
    return nLines;
435
0
}
436
437
/**********************************************************************
438
 *                       CSLPrint()
439
 **********************************************************************/
440
441
/** Print a StringList to fpOut.  If fpOut==NULL, then output is sent
442
 * to stdout.
443
 *
444
 * Returns the number of lines printed.
445
 */
446
int CSLPrint(CSLConstList papszStrList, FILE *fpOut)
447
0
{
448
0
    if (!papszStrList)
449
0
        return 0;
450
451
0
    if (fpOut == nullptr)
452
0
        fpOut = stdout;
453
454
0
    int nLines = 0;
455
456
0
    while (*papszStrList != nullptr)
457
0
    {
458
0
        if (VSIFPrintf(fpOut, "%s\n", *papszStrList) < 0)
459
0
            return nLines;
460
0
        ++nLines;
461
0
        ++papszStrList;
462
0
    }
463
464
0
    return nLines;
465
0
}
466
467
/**********************************************************************
468
 *                       CSLInsertStrings()
469
 **********************************************************************/
470
471
/** Copies the contents of a StringList inside another StringList
472
 * before the specified line.
473
 *
474
 * nInsertAtLineNo is a 0-based line index before which the new strings
475
 * should be inserted.  If this value is -1 or is larger than the actual
476
 * number of strings in the list then the strings are added at the end
477
 * of the source StringList.
478
 *
479
 * Returns the modified StringList.
480
 */
481
482
char **CSLInsertStrings(char **papszStrList, int nInsertAtLineNo,
483
                        CSLConstList papszNewLines)
484
0
{
485
0
    if (papszNewLines == nullptr)
486
0
        return papszStrList;  // Nothing to do!
487
488
0
    const int nToInsert = CSLCount(papszNewLines);
489
0
    if (nToInsert == 0)
490
0
        return papszStrList;  // Nothing to do!
491
492
0
    const int nSrcLines = CSLCount(papszStrList);
493
0
    const int nDstLines = nSrcLines + nToInsert;
494
495
    // Allocate room for the new strings.
496
0
    papszStrList = static_cast<char **>(
497
0
        CPLRealloc(papszStrList, (nDstLines + 1) * sizeof(char *)));
498
499
    // Make sure the array is NULL-terminated.  It may not be if
500
    // papszStrList was NULL before Realloc().
501
0
    papszStrList[nSrcLines] = nullptr;
502
503
    // Make some room in the original list at the specified location.
504
    // Note that we also have to move the NULL pointer at the end of
505
    // the source StringList.
506
0
    if (nInsertAtLineNo == -1 || nInsertAtLineNo > nSrcLines)
507
0
        nInsertAtLineNo = nSrcLines;
508
509
0
    {
510
0
        char **ppszSrc = papszStrList + nSrcLines;
511
0
        char **ppszDst = papszStrList + nDstLines;
512
513
0
        for (int i = nSrcLines; i >= nInsertAtLineNo; --i)
514
0
        {
515
0
            *ppszDst = *ppszSrc;
516
0
            --ppszDst;
517
0
            --ppszSrc;
518
0
        }
519
0
    }
520
521
    // Copy the strings to the list.
522
0
    CSLConstList ppszSrc = papszNewLines;
523
0
    char **ppszDst = papszStrList + nInsertAtLineNo;
524
525
0
    for (; *ppszSrc != nullptr; ++ppszSrc, ++ppszDst)
526
0
    {
527
0
        *ppszDst = CPLStrdup(*ppszSrc);
528
0
    }
529
530
0
    return papszStrList;
531
0
}
532
533
/**********************************************************************
534
 *                       CSLInsertString()
535
 **********************************************************************/
536
537
/** Insert a string at a given line number inside a StringList
538
 *
539
 * nInsertAtLineNo is a 0-based line index before which the new string
540
 * should be inserted.  If this value is -1 or is larger than the actual
541
 * number of strings in the list then the string is added at the end
542
 * of the source StringList.
543
 *
544
 * Returns the modified StringList.
545
 */
546
547
char **CSLInsertString(char **papszStrList, int nInsertAtLineNo,
548
                       const char *pszNewLine)
549
0
{
550
0
    char *apszList[2] = {const_cast<char *>(pszNewLine), nullptr};
551
552
0
    return CSLInsertStrings(papszStrList, nInsertAtLineNo, apszList);
553
0
}
554
555
/**********************************************************************
556
 *                       CSLRemoveStrings()
557
 **********************************************************************/
558
559
/** Remove strings inside a StringList
560
 *
561
 * nFirstLineToDelete is the 0-based line index of the first line to
562
 * remove. If this value is -1 or is larger than the actual
563
 * number of strings in list then the nNumToRemove last strings are
564
 * removed.
565
 *
566
 * If ppapszRetStrings != NULL then the deleted strings won't be
567
 * free'd, they will be stored in a new StringList and the pointer to
568
 * this new list will be returned in *ppapszRetStrings.
569
 *
570
 * Returns the modified StringList.
571
 */
572
573
char **CSLRemoveStrings(char **papszStrList, int nFirstLineToDelete,
574
                        int nNumToRemove, char ***ppapszRetStrings)
575
0
{
576
0
    const int nSrcLines = CSLCount(papszStrList);
577
578
0
    if (nNumToRemove < 1 || nSrcLines == 0)
579
0
        return papszStrList;  // Nothing to do!
580
581
    // If operation will result in an empty StringList, don't waste
582
    // time here.
583
0
    const int nDstLines = nSrcLines - nNumToRemove;
584
0
    if (nDstLines < 1)
585
0
    {
586
0
        CSLDestroy(papszStrList);
587
0
        return nullptr;
588
0
    }
589
590
    // Remove lines from the source StringList.
591
    // Either free() each line or store them to a new StringList depending on
592
    // the caller's choice.
593
0
    char **ppszDst = papszStrList + nFirstLineToDelete;
594
595
0
    if (ppapszRetStrings == nullptr)
596
0
    {
597
        // free() all the strings that will be removed.
598
0
        for (int i = 0; i < nNumToRemove; ++i)
599
0
        {
600
0
            CPLFree(*ppszDst);
601
0
            *ppszDst = nullptr;
602
0
        }
603
0
    }
604
0
    else
605
0
    {
606
        // Store the strings to remove in a new StringList.
607
0
        *ppapszRetStrings =
608
0
            static_cast<char **>(CPLCalloc(nNumToRemove + 1, sizeof(char *)));
609
610
0
        for (int i = 0; i < nNumToRemove; ++i)
611
0
        {
612
0
            (*ppapszRetStrings)[i] = *ppszDst;
613
0
            *ppszDst = nullptr;
614
0
            ++ppszDst;
615
0
        }
616
0
    }
617
618
    // Shift down all the lines that follow the lines to remove.
619
0
    if (nFirstLineToDelete == -1 || nFirstLineToDelete > nSrcLines)
620
0
        nFirstLineToDelete = nDstLines;
621
622
0
    char **ppszSrc = papszStrList + nFirstLineToDelete + nNumToRemove;
623
0
    ppszDst = papszStrList + nFirstLineToDelete;
624
625
0
    for (; *ppszSrc != nullptr; ++ppszSrc, ++ppszDst)
626
0
    {
627
0
        *ppszDst = *ppszSrc;
628
0
    }
629
    // Move the NULL pointer at the end of the StringList.
630
0
    *ppszDst = *ppszSrc;
631
632
    // At this point, we could realloc() papszStrList to a smaller size, but
633
    // since this array will likely grow again in further operations on the
634
    // StringList we'll leave it as it is.
635
0
    return papszStrList;
636
0
}
637
638
/************************************************************************/
639
/*                           CSLFindString()                            */
640
/************************************************************************/
641
642
/**
643
 * Find a string within a string list (case insensitive).
644
 *
645
 * Returns the index of the entry in the string list that contains the
646
 * target string.  The string in the string list must be a full match for
647
 * the target, but the search is case insensitive.
648
 *
649
 * @param papszList the string list to be searched.
650
 * @param pszTarget the string to be searched for.
651
 *
652
 * @return the index of the string within the list or -1 on failure.
653
 */
654
655
int CSLFindString(CSLConstList papszList, const char *pszTarget)
656
657
0
{
658
0
    if (papszList == nullptr)
659
0
        return -1;
660
661
0
    for (int i = 0; papszList[i] != nullptr; ++i)
662
0
    {
663
0
        if (EQUAL(papszList[i], pszTarget))
664
0
            return i;
665
0
    }
666
667
0
    return -1;
668
0
}
669
670
/************************************************************************/
671
/*                     CSLFindStringCaseSensitive()                     */
672
/************************************************************************/
673
674
/**
675
 * Find a string within a string list(case sensitive)
676
 *
677
 * Returns the index of the entry in the string list that contains the
678
 * target string.  The string in the string list must be a full match for
679
 * the target.
680
 *
681
 * @param papszList the string list to be searched.
682
 * @param pszTarget the string to be searched for.
683
 *
684
 * @return the index of the string within the list or -1 on failure.
685
 *
686
 */
687
688
int CSLFindStringCaseSensitive(CSLConstList papszList, const char *pszTarget)
689
690
0
{
691
0
    if (papszList == nullptr)
692
0
        return -1;
693
694
0
    for (int i = 0; papszList[i] != nullptr; ++i)
695
0
    {
696
0
        if (strcmp(papszList[i], pszTarget) == 0)
697
0
            return i;
698
0
    }
699
700
0
    return -1;
701
0
}
702
703
/************************************************************************/
704
/*                        CSLPartialFindString()                        */
705
/************************************************************************/
706
707
/**
708
 * Find a substring within a string list.
709
 *
710
 * Returns the index of the entry in the string list that contains the
711
 * target string as a substring.  The search is case sensitive (unlike
712
 * CSLFindString()).
713
 *
714
 * @param papszHaystack the string list to be searched.
715
 * @param pszNeedle the substring to be searched for.
716
 *
717
 * @return the index of the string within the list or -1 on failure.
718
 */
719
720
int CSLPartialFindString(CSLConstList papszHaystack, const char *pszNeedle)
721
0
{
722
0
    if (papszHaystack == nullptr || pszNeedle == nullptr)
723
0
        return -1;
724
725
0
    for (int i = 0; papszHaystack[i] != nullptr; ++i)
726
0
    {
727
0
        if (strstr(papszHaystack[i], pszNeedle))
728
0
            return i;
729
0
    }
730
731
0
    return -1;
732
0
}
733
734
/**********************************************************************
735
 *                       CSLTokenizeString()
736
 **********************************************************************/
737
738
/** Tokenizes a string and returns a StringList with one string for
739
 * each token.
740
 */
741
char **CSLTokenizeString(const char *pszString)
742
0
{
743
0
    return CSLTokenizeString2(pszString, " ", CSLT_HONOURSTRINGS);
744
0
}
745
746
/************************************************************************/
747
/*                      CSLTokenizeStringComplex()                      */
748
/************************************************************************/
749
750
/** Obsolete tokenizing api. Use CSLTokenizeString2() */
751
char **CSLTokenizeStringComplex(const char *pszString,
752
                                const char *pszDelimiters, int bHonourStrings,
753
                                int bAllowEmptyTokens)
754
0
{
755
0
    int nFlags = 0;
756
757
0
    if (bHonourStrings)
758
0
        nFlags |= CSLT_HONOURSTRINGS;
759
0
    if (bAllowEmptyTokens)
760
0
        nFlags |= CSLT_ALLOWEMPTYTOKENS;
761
762
0
    return CSLTokenizeString2(pszString, pszDelimiters, nFlags);
763
0
}
764
765
/************************************************************************/
766
/*                         CSLTokenizeString2()                         */
767
/************************************************************************/
768
769
/**
770
 * Tokenize a string.
771
 *
772
 * This function will split a string into tokens based on specified
773
 * delimiter(s) with a variety of options.  The returned result is a
774
 * string list that should be freed with CSLDestroy() when no longer
775
 * needed.
776
 *
777
 * The available parsing options are:
778
 *
779
 * - CSLT_ALLOWEMPTYTOKENS: allow the return of empty tokens when two
780
 * delimiters in a row occur with no other text between them.  If not set,
781
 * empty tokens will be discarded;
782
 * - CSLT_STRIPLEADSPACES: strip leading space characters from the token (as
783
 * reported by isspace());
784
 * - CSLT_STRIPENDSPACES: strip ending space characters from the token (as
785
 * reported by isspace());
786
 * - CSLT_HONOURSTRINGS: double quotes can be used to hold values that should
787
 * not be broken into multiple tokens;
788
 * - CSLT_HONOURSINGLEQUOTES: single quotes can be used to hold values that should
789
 * not be broken into multiple tokens;
790
 * - CSLT_PRESERVEQUOTES: string quotes are carried into the tokens when this
791
 * is set, otherwise they are removed;
792
 * - CSLT_PRESERVEESCAPES: if set backslash escapes (for backslash itself,
793
 * and for literal single/double quotes) will be preserved in the tokens, otherwise
794
 * the backslashes will be removed in processing.
795
 *
796
 * \b Example:
797
 *
798
 * Parse a string into tokens based on various white space (space, newline,
799
 * tab) and then print out results and cleanup.  Quotes may be used to hold
800
 * white space in tokens.
801
802
\code
803
    char **papszTokens =
804
        CSLTokenizeString2( pszCommand, " \t\n",
805
                            CSLT_HONOURSTRINGS | CSLT_ALLOWEMPTYTOKENS );
806
807
    for( int i = 0; papszTokens != NULL && papszTokens[i] != NULL; ++i )
808
        printf( "arg %d: '%s'", papszTokens[i] );  // ok
809
810
    CSLDestroy( papszTokens );
811
\endcode
812
813
 * @param pszString the string to be split into tokens.
814
 * @param pszDelimiters one or more characters to be used as token delimiters.
815
 * @param nCSLTFlags an ORing of one or more of the CSLT_ flag values.
816
 *
817
 * @return a string list of tokens owned by the caller.
818
 */
819
820
char **CSLTokenizeString2(const char *pszString, const char *pszDelimiters,
821
                          int nCSLTFlags)
822
378
{
823
378
    if (pszString == nullptr)
824
0
        return static_cast<char **>(CPLCalloc(sizeof(char *), 1));
825
826
378
    return cpl::tokenize_string(pszString, pszDelimiters, nCSLTFlags)
827
378
        .StealList();
828
378
}
829
830
namespace cpl
831
{
832
CPLStringList tokenize_string(std::string_view str, std::string_view delimiters,
833
                              int nCSLTFlags)
834
378
{
835
378
    CPLStringList oRetList;
836
378
    const bool bHonourStrings = (nCSLTFlags & CSLT_HONOURSTRINGS) != 0;
837
378
    const bool bHonourStringsSingleQuotes =
838
378
        (nCSLTFlags & CSLT_HONOURSINGLEQUOTES) != 0;
839
378
    const bool bAllowEmptyTokens = (nCSLTFlags & CSLT_ALLOWEMPTYTOKENS) != 0;
840
378
    const bool bStripLeadSpaces = (nCSLTFlags & CSLT_STRIPLEADSPACES) != 0;
841
378
    const bool bStripEndSpaces = (nCSLTFlags & CSLT_STRIPENDSPACES) != 0;
842
843
378
    size_t pos = 0;
844
378
    std::string token;
845
20.6k
    while (pos < str.size())
846
20.3k
    {
847
20.3k
        token.clear();
848
20.3k
        bool bInString = false;
849
20.3k
        bool bInStringSingleQuote = false;
850
851
        // Try to find the next delimiter, marking end of token.
852
50.7k
        while (pos < str.size())
853
50.4k
        {
854
            // End if this is a delimiter skip it and break.
855
50.4k
            if (!bInString && !bInStringSingleQuote &&
856
50.4k
                delimiters.find(str[pos]) != std::string_view::npos)
857
19.9k
            {
858
19.9k
                pos++;
859
19.9k
                break;
860
19.9k
            }
861
862
            // If this is a quote, and we are honouring constant
863
            // strings, then process the constant strings, with out delim
864
            // but don't copy over the quotes.
865
30.4k
            if (bHonourStrings && !bInStringSingleQuote && str[pos] == '"')
866
0
            {
867
0
                if (nCSLTFlags & CSLT_PRESERVEQUOTES)
868
0
                {
869
0
                    token.push_back(str[pos]);
870
0
                }
871
872
0
                bInString = !bInString;
873
0
                pos++;
874
0
                continue;
875
0
            }
876
30.4k
            else if (bHonourStringsSingleQuotes && !bHonourStrings &&
877
0
                     str[pos] == '\'')
878
0
            {
879
0
                if (nCSLTFlags & CSLT_PRESERVEQUOTES)
880
0
                {
881
0
                    token.push_back(str[pos]);
882
0
                }
883
884
0
                bInStringSingleQuote = !bInStringSingleQuote;
885
0
                pos++;
886
0
                continue;
887
0
            }
888
889
            /*
890
             * Within string constants we allow for escaped quotes, but in
891
             * processing them we will unescape the quotes and \\ sequence
892
             * reduces to \
893
             */
894
30.4k
            if (bInString && str[pos] == '\\')
895
0
            {
896
0
                if (pos + 1 < str.size() &&
897
0
                    (str[pos + 1] == '"' || str[pos + 1] == '\\'))
898
0
                {
899
0
                    if (nCSLTFlags & CSLT_PRESERVEESCAPES)
900
0
                    {
901
0
                        token.push_back(str[pos]);
902
0
                    }
903
904
0
                    ++pos;
905
0
                }
906
0
            }
907
30.4k
            else if (bInStringSingleQuote && str[pos] == '\\')
908
0
            {
909
0
                if (pos + 1 < str.size() &&
910
0
                    (str[pos + 1] == '\'' || str[pos + 1] == '\\'))
911
0
                {
912
0
                    if (nCSLTFlags & CSLT_PRESERVEESCAPES)
913
0
                    {
914
0
                        token.push_back(str[pos]);
915
0
                    }
916
917
0
                    ++pos;
918
0
                }
919
0
            }
920
921
30.4k
            token.push_back(str[pos]);
922
30.4k
            pos++;
923
30.4k
        }
924
925
        // Add the token.
926
20.3k
        std::string_view token_view(token);
927
20.3k
        if (bStripLeadSpaces)
928
0
        {
929
0
            token_view = ltrim(token_view);
930
0
        }
931
20.3k
        if (bStripEndSpaces)
932
0
        {
933
0
            token_view = rtrim(token_view);
934
0
        }
935
936
20.3k
        if (!token_view.empty() || bAllowEmptyTokens)
937
18.5k
            oRetList.AddString(token_view);
938
20.3k
    }
939
940
    /*
941
     * If the last token was empty, then we need to capture
942
     * it now, as the loop would skip it.
943
     */
944
378
    if (!str.empty() && pos == str.size() && bAllowEmptyTokens &&
945
0
        oRetList.Count() > 0 &&
946
0
        delimiters.find(str[pos - 1]) != std::string_view::npos)
947
0
    {
948
0
        oRetList.AddString("");
949
0
    }
950
951
378
    if (oRetList.List() == nullptr)
952
29
    {
953
        // Prefer to return empty lists as a pointer to
954
        // a null pointer since some client code might depend on this.
955
29
        oRetList.Assign(static_cast<char **>(CPLCalloc(sizeof(char *), 1)));
956
29
    }
957
958
378
    return CPLStringList(oRetList.StealList());
959
378
}
960
961
}  // namespace cpl
962
963
/**********************************************************************
964
 *                       CPLSPrintf()
965
 *
966
 * NOTE: This function should move to cpl_conv.cpp.
967
 **********************************************************************/
968
969
// For now, assume that a 8000 chars buffer will be enough.
970
constexpr int CPLSPrintf_BUF_SIZE = 8000;
971
constexpr int CPLSPrintf_BUF_Count = 10;
972
973
/** CPLSPrintf() that works with 10 static buffer.
974
 *
975
 * It returns a ref. to a static buffer that should not be freed and
976
 * is valid only until the next call to CPLSPrintf().
977
 */
978
979
const char *CPLSPrintf(CPL_FORMAT_STRING(const char *fmt), ...)
980
3.70k
{
981
3.70k
    va_list args;
982
983
    /* -------------------------------------------------------------------- */
984
    /*      Get the thread local buffer ring data.                          */
985
    /* -------------------------------------------------------------------- */
986
3.70k
    char *pachBufRingInfo = static_cast<char *>(CPLGetTLS(CTLS_CPLSPRINTF));
987
988
3.70k
    if (pachBufRingInfo == nullptr)
989
1
    {
990
1
        pachBufRingInfo = static_cast<char *>(CPLCalloc(
991
1
            1, sizeof(int) + CPLSPrintf_BUF_Count * CPLSPrintf_BUF_SIZE));
992
1
        CPLSetTLS(CTLS_CPLSPRINTF, pachBufRingInfo, TRUE);
993
1
    }
994
995
    /* -------------------------------------------------------------------- */
996
    /*      Work out which string in the "ring" we want to use this         */
997
    /*      time.                                                           */
998
    /* -------------------------------------------------------------------- */
999
3.70k
    int *pnBufIndex = reinterpret_cast<int *>(pachBufRingInfo);
1000
3.70k
    const size_t nOffset = sizeof(int) + *pnBufIndex * CPLSPrintf_BUF_SIZE;
1001
3.70k
    char *pachBuffer = pachBufRingInfo + nOffset;
1002
1003
3.70k
    *pnBufIndex = (*pnBufIndex + 1) % CPLSPrintf_BUF_Count;
1004
1005
    /* -------------------------------------------------------------------- */
1006
    /*      Format the result.                                              */
1007
    /* -------------------------------------------------------------------- */
1008
1009
3.70k
    va_start(args, fmt);
1010
1011
3.70k
    const int ret =
1012
3.70k
        CPLvsnprintf(pachBuffer, CPLSPrintf_BUF_SIZE - 1, fmt, args);
1013
3.70k
    if (ret < 0 || ret >= CPLSPrintf_BUF_SIZE - 1)
1014
0
    {
1015
0
        CPLError(CE_Failure, CPLE_AppDefined,
1016
0
                 "CPLSPrintf() called with too "
1017
0
                 "big string. Output will be truncated !");
1018
0
    }
1019
1020
3.70k
    va_end(args);
1021
1022
3.70k
    return pachBuffer;
1023
3.70k
}
1024
1025
/**********************************************************************
1026
 *                       CSLAppendPrintf()
1027
 **********************************************************************/
1028
1029
/** Use CPLSPrintf() to append a new line at the end of a StringList.
1030
 * Returns the modified StringList.
1031
 */
1032
char **CSLAppendPrintf(char **papszStrList, CPL_FORMAT_STRING(const char *fmt),
1033
                       ...)
1034
0
{
1035
0
    va_list args;
1036
1037
0
    va_start(args, fmt);
1038
0
    CPLString osWork;
1039
0
    osWork.vPrintf(fmt, args);
1040
0
    va_end(args);
1041
1042
0
    return CSLAddString(papszStrList, osWork);
1043
0
}
1044
1045
/************************************************************************/
1046
/*                            CPLVASPrintf()                            */
1047
/************************************************************************/
1048
1049
/** This is intended to serve as an easy to use C callable vasprintf()
1050
 * alternative.  Used in the GeoJSON library for instance */
1051
int CPLVASPrintf(char **buf, CPL_FORMAT_STRING(const char *fmt), va_list ap)
1052
1053
0
{
1054
0
    CPLString osWork;
1055
1056
0
    osWork.vPrintf(fmt, ap);
1057
1058
0
    if (buf)
1059
0
        *buf = CPLStrdup(osWork.c_str());
1060
1061
0
    return static_cast<int>(osWork.size());
1062
0
}
1063
1064
/************************************************************************/
1065
/*                 CPLvsnprintf_get_end_of_formatting()                 */
1066
/************************************************************************/
1067
1068
static const char *CPLvsnprintf_get_end_of_formatting(const char *fmt)
1069
19.7k
{
1070
19.7k
    char ch = '\0';
1071
    // Flag.
1072
21.6k
    for (; (ch = *fmt) != '\0'; ++fmt)
1073
21.6k
    {
1074
21.6k
        if (ch == '\'')
1075
0
            continue;  // Bad idea as this is locale specific.
1076
21.6k
        if (ch == '-' || ch == '+' || ch == ' ' || ch == '#' || ch == '0')
1077
1.96k
            continue;
1078
19.7k
        break;
1079
21.6k
    }
1080
1081
    // Field width.
1082
21.6k
    for (; (ch = *fmt) != '\0'; ++fmt)
1083
21.6k
    {
1084
21.6k
        if (ch == '$')
1085
0
            return nullptr;  // Do not support this.
1086
21.6k
        if (*fmt >= '0' && *fmt <= '9')
1087
1.96k
            continue;
1088
19.7k
        break;
1089
21.6k
    }
1090
1091
    // Precision.
1092
19.7k
    if (ch == '.')
1093
982
    {
1094
982
        ++fmt;
1095
2.94k
        for (; (ch = *fmt) != '\0'; ++fmt)
1096
2.94k
        {
1097
2.94k
            if (ch == '$')
1098
0
                return nullptr;  // Do not support this.
1099
2.94k
            if (*fmt >= '0' && *fmt <= '9')
1100
1.96k
                continue;
1101
982
            break;
1102
2.94k
        }
1103
982
    }
1104
1105
    // Length modifier.
1106
19.7k
    for (; (ch = *fmt) != '\0'; ++fmt)
1107
19.7k
    {
1108
19.7k
        if (ch == 'h' || ch == 'l' || ch == 'j' || ch == 'z' || ch == 't' ||
1109
19.7k
            ch == 'L')
1110
0
            continue;
1111
19.7k
        else if (ch == 'I' && fmt[1] == '6' && fmt[2] == '4')
1112
0
            fmt += 2;
1113
19.7k
        else
1114
19.7k
            return fmt;
1115
19.7k
    }
1116
1117
0
    return nullptr;
1118
19.7k
}
1119
1120
/************************************************************************/
1121
/*                            CPLvsnprintf()                            */
1122
/************************************************************************/
1123
1124
#define call_native_snprintf(type)                                             \
1125
7.41k
    local_ret = snprintf(str + offset_out, size - offset_out, localfmt,        \
1126
7.41k
                         va_arg(wrk_args, type))
1127
1128
/** vsnprintf() wrapper that is not sensitive to LC_NUMERIC settings.
1129
 *
1130
 * This function has the same contract as standard vsnprintf(), except that
1131
 * formatting of floating-point numbers will use decimal point, whatever the
1132
 * current locale is set.
1133
 *
1134
 * @param str output buffer
1135
 * @param size size of the output buffer (including space for terminating nul)
1136
 * @param fmt formatting string
1137
 * @param args arguments
1138
 * @return the number of characters (excluding terminating nul) that would be
1139
 * written if size is big enough. Or potentially -1 with Microsoft C runtime
1140
 * for Visual Studio < 2015.
1141
 */
1142
int CPLvsnprintf(char *str, size_t size, CPL_FORMAT_STRING(const char *fmt),
1143
                 va_list args)
1144
13.2k
{
1145
13.2k
    if (size == 0)
1146
0
        return vsnprintf(str, size, fmt, args);
1147
1148
13.2k
    va_list wrk_args;
1149
1150
13.2k
#ifdef va_copy
1151
13.2k
    va_copy(wrk_args, args);
1152
#else
1153
    wrk_args = args;
1154
#endif
1155
1156
13.2k
    const char *fmt_ori = fmt;
1157
13.2k
    size_t offset_out = 0;
1158
13.2k
    char ch = '\0';
1159
13.2k
    bool bFormatUnknown = false;
1160
1161
216k
    for (; (ch = *fmt) != '\0'; ++fmt)
1162
202k
    {
1163
202k
        if (ch == '%')
1164
19.7k
        {
1165
19.7k
            if (strncmp(fmt, "%.*f", 4) == 0)
1166
0
            {
1167
0
                const int precision = va_arg(wrk_args, int);
1168
0
                const double val = va_arg(wrk_args, double);
1169
0
                const int local_ret =
1170
0
                    snprintf(str + offset_out, size - offset_out, "%.*f",
1171
0
                             precision, val);
1172
                // MSVC vsnprintf() returns -1.
1173
0
                if (local_ret < 0 || offset_out + local_ret >= size)
1174
0
                    break;
1175
0
                for (int j = 0; j < local_ret; ++j)
1176
0
                {
1177
0
                    if (str[offset_out + j] == ',')
1178
0
                    {
1179
0
                        str[offset_out + j] = '.';
1180
0
                        break;
1181
0
                    }
1182
0
                }
1183
0
                offset_out += local_ret;
1184
0
                fmt += strlen("%.*f") - 1;
1185
0
                continue;
1186
0
            }
1187
1188
19.7k
            const char *ptrend = CPLvsnprintf_get_end_of_formatting(fmt + 1);
1189
19.7k
            if (ptrend == nullptr || ptrend - fmt >= 20)
1190
0
            {
1191
0
                bFormatUnknown = true;
1192
0
                break;
1193
0
            }
1194
19.7k
            char end = *ptrend;
1195
19.7k
            char end_m1 = ptrend[-1];
1196
1197
19.7k
            char localfmt[22] = {};
1198
19.7k
            memcpy(localfmt, fmt, ptrend - fmt + 1);
1199
19.7k
            localfmt[ptrend - fmt + 1] = '\0';
1200
1201
19.7k
            int local_ret = 0;
1202
19.7k
            if (end == '%')
1203
0
            {
1204
0
                if (offset_out == size - 1)
1205
0
                    break;
1206
0
                local_ret = 1;
1207
0
                str[offset_out] = '%';
1208
0
            }
1209
19.7k
            else if (end == 'd' || end == 'i' || end == 'c')
1210
6.43k
            {
1211
6.43k
                if (end_m1 == 'h')
1212
0
                    call_native_snprintf(int);
1213
6.43k
                else if (end_m1 == 'l' && ptrend[-2] != 'l')
1214
0
                    call_native_snprintf(long);
1215
6.43k
                else if (end_m1 == 'l' && ptrend[-2] == 'l')
1216
0
                    call_native_snprintf(GIntBig);
1217
6.43k
                else if (end_m1 == '4' && ptrend[-2] == '6' &&
1218
0
                         ptrend[-3] == 'I')
1219
                    // Microsoft I64 modifier.
1220
0
                    call_native_snprintf(GIntBig);
1221
6.43k
                else if (end_m1 == 'z')
1222
0
                    call_native_snprintf(size_t);
1223
6.43k
                else if ((end_m1 >= 'a' && end_m1 <= 'z') ||
1224
6.43k
                         (end_m1 >= 'A' && end_m1 <= 'Z'))
1225
0
                {
1226
0
                    bFormatUnknown = true;
1227
0
                    break;
1228
0
                }
1229
6.43k
                else
1230
6.43k
                    call_native_snprintf(int);
1231
6.43k
            }
1232
13.2k
            else if (end == 'o' || end == 'u' || end == 'x' || end == 'X')
1233
0
            {
1234
0
                if (end_m1 == 'h')
1235
0
                    call_native_snprintf(unsigned int);
1236
0
                else if (end_m1 == 'l' && ptrend[-2] != 'l')
1237
0
                    call_native_snprintf(unsigned long);
1238
0
                else if (end_m1 == 'l' && ptrend[-2] == 'l')
1239
0
                    call_native_snprintf(GUIntBig);
1240
0
                else if (end_m1 == '4' && ptrend[-2] == '6' &&
1241
0
                         ptrend[-3] == 'I')
1242
                    // Microsoft I64 modifier.
1243
0
                    call_native_snprintf(GUIntBig);
1244
0
                else if (end_m1 == 'z')
1245
0
                    call_native_snprintf(size_t);
1246
0
                else if ((end_m1 >= 'a' && end_m1 <= 'z') ||
1247
0
                         (end_m1 >= 'A' && end_m1 <= 'Z'))
1248
0
                {
1249
0
                    bFormatUnknown = true;
1250
0
                    break;
1251
0
                }
1252
0
                else
1253
0
                    call_native_snprintf(unsigned int);
1254
0
            }
1255
13.2k
            else if (end == 'e' || end == 'E' || end == 'f' || end == 'F' ||
1256
12.3k
                     end == 'g' || end == 'G' || end == 'a' || end == 'A')
1257
982
            {
1258
982
                if (end_m1 == 'L')
1259
0
                    call_native_snprintf(long double);
1260
982
                else
1261
982
                    call_native_snprintf(double);
1262
                // MSVC vsnprintf() returns -1.
1263
982
                if (local_ret < 0 || offset_out + local_ret >= size)
1264
0
                    break;
1265
6.87k
                for (int j = 0; j < local_ret; ++j)
1266
5.89k
                {
1267
5.89k
                    if (str[offset_out + j] == ',')
1268
0
                    {
1269
0
                        str[offset_out + j] = '.';
1270
0
                        break;
1271
0
                    }
1272
5.89k
                }
1273
982
            }
1274
12.3k
            else if (end == 's')
1275
12.3k
            {
1276
12.3k
                const char *pszPtr = va_arg(wrk_args, const char *);
1277
12.3k
                CPLAssert(pszPtr);
1278
12.3k
                local_ret = snprintf(str + offset_out, size - offset_out,
1279
12.3k
                                     localfmt, pszPtr);
1280
12.3k
            }
1281
0
            else if (end == 'p')
1282
0
            {
1283
0
                call_native_snprintf(void *);
1284
0
            }
1285
0
            else
1286
0
            {
1287
0
                bFormatUnknown = true;
1288
0
                break;
1289
0
            }
1290
            // MSVC vsnprintf() returns -1.
1291
19.7k
            if (local_ret < 0 || offset_out + local_ret >= size)
1292
2
                break;
1293
19.7k
            offset_out += local_ret;
1294
19.7k
            fmt = ptrend;
1295
19.7k
        }
1296
183k
        else
1297
183k
        {
1298
183k
            if (offset_out == size - 1)
1299
1
                break;
1300
183k
            str[offset_out++] = *fmt;
1301
183k
        }
1302
202k
    }
1303
13.2k
    if (ch == '\0' && offset_out < size)
1304
13.2k
        str[offset_out] = '\0';
1305
3
    else
1306
3
    {
1307
3
        if (bFormatUnknown)
1308
0
        {
1309
0
            CPLDebug("CPL",
1310
0
                     "CPLvsnprintf() called with unsupported "
1311
0
                     "formatting string: %s",
1312
0
                     fmt_ori);
1313
0
        }
1314
3
#ifdef va_copy
1315
3
        va_end(wrk_args);
1316
3
        va_copy(wrk_args, args);
1317
#else
1318
        wrk_args = args;
1319
#endif
1320
3
#if defined(HAVE_VSNPRINTF)
1321
3
        offset_out = vsnprintf(str, size, fmt_ori, wrk_args);
1322
#else
1323
        offset_out = vsprintf(str, fmt_ori, wrk_args);
1324
#endif
1325
3
    }
1326
1327
13.2k
#ifdef va_copy
1328
13.2k
    va_end(wrk_args);
1329
13.2k
#endif
1330
1331
13.2k
    return static_cast<int>(offset_out);
1332
13.2k
}
1333
1334
/************************************************************************/
1335
/*                            CPLsnprintf()                             */
1336
/************************************************************************/
1337
1338
#if !defined(ALIAS_CPLSNPRINTF_AS_SNPRINTF)
1339
1340
#if defined(__clang__) && __clang_major__ == 3 && __clang_minor__ <= 2
1341
#pragma clang diagnostic push
1342
#pragma clang diagnostic ignored "-Wunknown-pragmas"
1343
#pragma clang diagnostic ignored "-Wdocumentation"
1344
#endif
1345
1346
/** snprintf() wrapper that is not sensitive to LC_NUMERIC settings.
1347
 *
1348
 * This function has the same contract as standard snprintf(), except that
1349
 * formatting of floating-point numbers will use decimal point, whatever the
1350
 * current locale is set.
1351
 *
1352
 * @param str output buffer
1353
 * @param size size of the output buffer (including space for terminating nul)
1354
 * @param fmt formatting string
1355
 * @param ... arguments
1356
 * @return the number of characters (excluding terminating nul) that would be
1357
 * written if size is big enough. Or potentially -1 with Microsoft C runtime
1358
 * for Visual Studio < 2015.
1359
 */
1360
1361
int CPLsnprintf(char *str, size_t size, CPL_FORMAT_STRING(const char *fmt), ...)
1362
982
{
1363
982
    va_list args;
1364
1365
982
    va_start(args, fmt);
1366
982
    const int ret = CPLvsnprintf(str, size, fmt, args);
1367
982
    va_end(args);
1368
982
    return ret;
1369
982
}
1370
1371
#endif  //  !defined(ALIAS_CPLSNPRINTF_AS_SNPRINTF)
1372
1373
/************************************************************************/
1374
/*                             CPLsprintf()                             */
1375
/************************************************************************/
1376
1377
/** sprintf() wrapper that is not sensitive to LC_NUMERIC settings.
1378
  *
1379
  * This function has the same contract as standard sprintf(), except that
1380
  * formatting of floating-point numbers will use decimal point, whatever the
1381
  * current locale is set.
1382
  *
1383
  * @param str output buffer (must be large enough to hold the result)
1384
  * @param fmt formatting string
1385
  * @param ... arguments
1386
  * @return the number of characters (excluding terminating nul) written in
1387
` * output buffer.
1388
  */
1389
int CPLsprintf(char *str, CPL_FORMAT_STRING(const char *fmt), ...)
1390
0
{
1391
0
    va_list args;
1392
1393
0
    va_start(args, fmt);
1394
0
    const int ret = CPLvsnprintf(str, INT_MAX, fmt, args);
1395
0
    va_end(args);
1396
0
    return ret;
1397
0
}
1398
1399
/************************************************************************/
1400
/*                             CPLprintf()                              */
1401
/************************************************************************/
1402
1403
/** printf() wrapper that is not sensitive to LC_NUMERIC settings.
1404
 *
1405
 * This function has the same contract as standard printf(), except that
1406
 * formatting of floating-point numbers will use decimal point, whatever the
1407
 * current locale is set.
1408
 *
1409
 * @param fmt formatting string
1410
 * @param ... arguments
1411
 * @return the number of characters (excluding terminating nul) written in
1412
 * output buffer.
1413
 */
1414
int CPLprintf(CPL_FORMAT_STRING(const char *fmt), ...)
1415
0
{
1416
0
    va_list wrk_args, args;
1417
1418
0
    va_start(args, fmt);
1419
1420
0
#ifdef va_copy
1421
0
    va_copy(wrk_args, args);
1422
#else
1423
    wrk_args = args;
1424
#endif
1425
1426
0
    char szBuffer[4096] = {};
1427
    // Quiet coverity by staring off nul terminated.
1428
0
    int ret = CPLvsnprintf(szBuffer, sizeof(szBuffer), fmt, wrk_args);
1429
1430
0
#ifdef va_copy
1431
0
    va_end(wrk_args);
1432
0
#endif
1433
1434
0
    if (ret < int(sizeof(szBuffer)) - 1)
1435
0
        ret = printf("%s", szBuffer); /*ok*/
1436
0
    else
1437
0
    {
1438
0
#ifdef va_copy
1439
0
        va_copy(wrk_args, args);
1440
#else
1441
        wrk_args = args;
1442
#endif
1443
1444
0
        ret = vfprintf(stdout, fmt, wrk_args);
1445
1446
0
#ifdef va_copy
1447
0
        va_end(wrk_args);
1448
0
#endif
1449
0
    }
1450
1451
0
    va_end(args);
1452
1453
0
    return ret;
1454
0
}
1455
1456
/************************************************************************/
1457
/*                             CPLsscanf()                              */
1458
/************************************************************************/
1459
1460
/** \brief sscanf() wrapper that is not sensitive to LC_NUMERIC settings.
1461
 *
1462
 * This function has the same contract as standard sscanf(), except that
1463
 * formatting of floating-point numbers will use decimal point, whatever the
1464
 * current locale is set.
1465
 *
1466
 * CAUTION: only works with a very limited number of formatting strings,
1467
 * consisting only of "%lf" and regular characters.
1468
 *
1469
 * @param str input string
1470
 * @param fmt formatting string
1471
 * @param ... arguments
1472
 * @return the number of matched patterns;
1473
 */
1474
#ifdef DOXYGEN_XML
1475
int CPLsscanf(const char *str, const char *fmt, ...)
1476
#else
1477
int CPLsscanf(const char *str, CPL_SCANF_FORMAT_STRING(const char *fmt), ...)
1478
#endif
1479
0
{
1480
0
    bool error = false;
1481
0
    int ret = 0;
1482
0
    const char *fmt_ori = fmt;
1483
0
    va_list args;
1484
1485
0
    va_start(args, fmt);
1486
0
    for (; *fmt != '\0' && *str != '\0'; ++fmt)
1487
0
    {
1488
0
        if (*fmt == '%')
1489
0
        {
1490
0
            if (fmt[1] == 'l' && fmt[2] == 'f')
1491
0
            {
1492
0
                fmt += 2;
1493
0
                char *end;
1494
0
                *(va_arg(args, double *)) = CPLStrtod(str, &end);
1495
0
                if (end > str)
1496
0
                {
1497
0
                    ++ret;
1498
0
                    str = end;
1499
0
                }
1500
0
                else
1501
0
                    break;
1502
0
            }
1503
0
            else
1504
0
            {
1505
0
                error = true;
1506
0
                break;
1507
0
            }
1508
0
        }
1509
0
        else if (isspace(static_cast<unsigned char>(*fmt)))
1510
0
        {
1511
0
            while (*str != '\0' && isspace(static_cast<unsigned char>(*str)))
1512
0
                ++str;
1513
0
        }
1514
0
        else if (*str != *fmt)
1515
0
            break;
1516
0
        else
1517
0
            ++str;
1518
0
    }
1519
0
    va_end(args);
1520
1521
0
    if (error)
1522
0
    {
1523
0
        CPLError(CE_Failure, CPLE_NotSupported,
1524
0
                 "Format %s not supported by CPLsscanf()", fmt_ori);
1525
0
    }
1526
1527
0
    return ret;
1528
0
}
1529
1530
#if defined(__clang__) && __clang_major__ == 3 && __clang_minor__ <= 2
1531
#pragma clang diagnostic pop
1532
#endif
1533
1534
/************************************************************************/
1535
/*                            CPLTestBool()                             */
1536
/************************************************************************/
1537
1538
/**
1539
 * Test what boolean value contained in the string.
1540
 *
1541
 * If pszValue is "NO", "FALSE", "OFF" or "0" will be returned false.
1542
 * Otherwise, true will be returned.
1543
 *
1544
 * @param pszValue the string should be tested.
1545
 *
1546
 * @return true or false.
1547
 */
1548
1549
bool CPLTestBool(const char *pszValue)
1550
1.47k
{
1551
1.47k
    return !(EQUAL(pszValue, "NO") || EQUAL(pszValue, "FALSE") ||
1552
1.34k
             EQUAL(pszValue, "OFF") || EQUAL(pszValue, "0"));
1553
1.47k
}
1554
1555
/************************************************************************/
1556
/*                           CSLTestBoolean()                           */
1557
/************************************************************************/
1558
1559
/**
1560
 * Test what boolean value contained in the string.
1561
 *
1562
 * If pszValue is "NO", "FALSE", "OFF" or "0" will be returned FALSE.
1563
 * Otherwise, TRUE will be returned.
1564
 *
1565
 * Deprecated.  Removed in GDAL 3.x.
1566
 *
1567
 * Use CPLTestBoolean() for C and CPLTestBool() for C++.
1568
 *
1569
 * @param pszValue the string should be tested.
1570
 *
1571
 * @return TRUE or FALSE.
1572
 */
1573
1574
int CSLTestBoolean(const char *pszValue)
1575
0
{
1576
0
    return CPLTestBool(pszValue) ? TRUE : FALSE;
1577
0
}
1578
1579
/************************************************************************/
1580
/*                           CPLTestBoolean()                           */
1581
/************************************************************************/
1582
1583
/**
1584
 * Test what boolean value contained in the string.
1585
 *
1586
 * If pszValue is "NO", "FALSE", "OFF" or "0" will be returned FALSE.
1587
 * Otherwise, TRUE will be returned.
1588
 *
1589
 * Use this only in C code.  In C++, prefer CPLTestBool().
1590
 *
1591
 * @param pszValue the string should be tested.
1592
 *
1593
 * @return TRUE or FALSE.
1594
 */
1595
1596
int CPLTestBoolean(const char *pszValue)
1597
0
{
1598
0
    return CPLTestBool(pszValue) ? TRUE : FALSE;
1599
0
}
1600
1601
/**********************************************************************
1602
 *                       CPLFetchBool()
1603
 **********************************************************************/
1604
1605
/** Check for boolean key value.
1606
 *
1607
 * In a StringList of "Name=Value" pairs, look to see if there is a key
1608
 * with the given name, and if it can be interpreted as being TRUE.  If
1609
 * the key appears without any "=Value" portion it will be considered true.
1610
 * If the value is NO, FALSE or 0 it will be considered FALSE otherwise
1611
 * if the key appears in the list it will be considered TRUE.  If the key
1612
 * doesn't appear at all, the indicated default value will be returned.
1613
 *
1614
 * @param papszStrList the string list to search.
1615
 * @param pszKey the key value to look for (case insensitive).
1616
 * @param bDefault the value to return if the key isn't found at all.
1617
 *
1618
 * @return true or false
1619
 */
1620
1621
bool CPLFetchBool(CSLConstList papszStrList, const char *pszKey, bool bDefault)
1622
1623
0
{
1624
0
    if (CSLFindString(papszStrList, pszKey) != -1)
1625
0
        return true;
1626
1627
0
    const char *const pszValue = CSLFetchNameValue(papszStrList, pszKey);
1628
0
    if (pszValue == nullptr)
1629
0
        return bDefault;
1630
1631
0
    return CPLTestBool(pszValue);
1632
0
}
1633
1634
/**********************************************************************
1635
 *                       CSLFetchBoolean()
1636
 **********************************************************************/
1637
1638
/** DEPRECATED.  Check for boolean key value.
1639
 *
1640
 * In a StringList of "Name=Value" pairs, look to see if there is a key
1641
 * with the given name, and if it can be interpreted as being TRUE.  If
1642
 * the key appears without any "=Value" portion it will be considered true.
1643
 * If the value is NO, FALSE or 0 it will be considered FALSE otherwise
1644
 * if the key appears in the list it will be considered TRUE.  If the key
1645
 * doesn't appear at all, the indicated default value will be returned.
1646
 *
1647
 * @param papszStrList the string list to search.
1648
 * @param pszKey the key value to look for (case insensitive).
1649
 * @param bDefault the value to return if the key isn't found at all.
1650
 *
1651
 * @return TRUE or FALSE
1652
 */
1653
1654
int CSLFetchBoolean(CSLConstList papszStrList, const char *pszKey, int bDefault)
1655
1656
0
{
1657
0
    return CPLFetchBool(papszStrList, pszKey, CPL_TO_BOOL(bDefault));
1658
0
}
1659
1660
/************************************************************************/
1661
/*                     CSLFetchNameValueDefaulted()                     */
1662
/************************************************************************/
1663
1664
/** Same as CSLFetchNameValue() but return pszDefault in case of no match */
1665
const char *CSLFetchNameValueDef(CSLConstList papszStrList, const char *pszName,
1666
                                 const char *pszDefault)
1667
1668
0
{
1669
0
    const char *pszResult = CSLFetchNameValue(papszStrList, pszName);
1670
0
    if (pszResult != nullptr)
1671
0
        return pszResult;
1672
1673
0
    return pszDefault;
1674
0
}
1675
1676
/**********************************************************************
1677
 *                       CSLFetchNameValue()
1678
 **********************************************************************/
1679
1680
/** In a StringList of "Name=Value" pairs, look for the
1681
 * first value associated with the specified name.  The search is not
1682
 * case sensitive.
1683
 * ("Name:Value" pairs are also supported for backward compatibility
1684
 * with older stuff.)
1685
 *
1686
 * Returns a reference to the value in the StringList that the caller
1687
 * should not attempt to free.
1688
 *
1689
 * Returns NULL if the name is not found.
1690
 */
1691
1692
const char *CSLFetchNameValue(CSLConstList papszStrList, const char *pszName)
1693
35.0k
{
1694
35.0k
    if (papszStrList == nullptr || pszName == nullptr)
1695
270
        return nullptr;
1696
1697
34.7k
    const size_t nLen = strlen(pszName);
1698
27.6M
    while (*papszStrList != nullptr)
1699
27.6M
    {
1700
27.6M
        if (EQUALN(*papszStrList, pszName, nLen) &&
1701
33.9k
            ((*papszStrList)[nLen] == '=' || (*papszStrList)[nLen] == ':'))
1702
20.9k
        {
1703
20.9k
            return (*papszStrList) + nLen + 1;
1704
20.9k
        }
1705
27.6M
        ++papszStrList;
1706
27.6M
    }
1707
13.7k
    return nullptr;
1708
34.7k
}
1709
1710
/************************************************************************/
1711
/*                            CSLFindName()                             */
1712
/************************************************************************/
1713
1714
/**
1715
 * Find StringList entry with given key name.
1716
 *
1717
 * @param papszStrList the string list to search.
1718
 * @param pszName the key value to look for (case insensitive).
1719
 *
1720
 * @return -1 on failure or the list index of the first occurrence
1721
 * matching the given key.
1722
 */
1723
1724
int CSLFindName(CSLConstList papszStrList, const char *pszName)
1725
0
{
1726
0
    if (papszStrList == nullptr || pszName == nullptr)
1727
0
        return -1;
1728
1729
0
    const size_t nLen = strlen(pszName);
1730
0
    int iIndex = 0;
1731
0
    while (*papszStrList != nullptr)
1732
0
    {
1733
0
        if (EQUALN(*papszStrList, pszName, nLen) &&
1734
0
            ((*papszStrList)[nLen] == '=' || (*papszStrList)[nLen] == ':'))
1735
0
        {
1736
0
            return iIndex;
1737
0
        }
1738
0
        ++iIndex;
1739
0
        ++papszStrList;
1740
0
    }
1741
0
    return -1;
1742
0
}
1743
1744
/************************************************************************/
1745
/*                         CPLParseMemorySize()                         */
1746
/************************************************************************/
1747
1748
/** Parse a memory size from a string.
1749
 *
1750
 * The string may indicate the units of the memory (e.g., "230k", "500 MB"),
1751
 * using the prefixes "k", "m", or "g" in either lower or upper-case,
1752
 * optionally followed by a "b" or "B". The string may alternatively specify
1753
 * memory as a fraction of the usable RAM (e.g., "25%"). Spaces before the
1754
 * number, between the number and the units, or after the units are ignored,
1755
 * but other characters will cause a parsing failure. If the string cannot
1756
 * be understood, the function will return CE_Failure.
1757
 *
1758
 * @param pszValue the string to parse
1759
 * @param[out] pnValue the parsed size, converted to bytes (if unit was specified)
1760
 * @param[out] pbUnitSpecified whether the string indicated the units
1761
 *
1762
 * @return CE_None on success, CE_Failure otherwise
1763
 * @since 3.10
1764
 */
1765
CPLErr CPLParseMemorySize(const char *pszValue, GIntBig *pnValue,
1766
                          bool *pbUnitSpecified)
1767
0
{
1768
0
    const char *start = pszValue;
1769
0
    char *end = nullptr;
1770
1771
    // trim leading whitespace
1772
0
    while (*start == ' ')
1773
0
    {
1774
0
        start++;
1775
0
    }
1776
1777
0
    auto len = CPLStrnlen(start, 100);
1778
0
    double value = CPLStrtodM(start, &end);
1779
0
    const char *unit = nullptr;
1780
0
    bool unitIsNotPercent = false;
1781
1782
0
    if (end == start)
1783
0
    {
1784
0
        CPLError(CE_Failure, CPLE_IllegalArg, "Received non-numeric value: %s",
1785
0
                 pszValue);
1786
0
        return CE_Failure;
1787
0
    }
1788
1789
0
    if (value < 0 || !std::isfinite(value))
1790
0
    {
1791
0
        CPLError(CE_Failure, CPLE_IllegalArg,
1792
0
                 "Memory size must be a positive number or zero.");
1793
0
        return CE_Failure;
1794
0
    }
1795
1796
0
    for (const char *c = end; c < start + len; c++)
1797
0
    {
1798
0
        if (unit == nullptr)
1799
0
        {
1800
            // check various suffixes and convert number into bytes
1801
0
            if (*c == '%')
1802
0
            {
1803
0
                if (value < 0 || value > 100)
1804
0
                {
1805
0
                    CPLError(CE_Failure, CPLE_IllegalArg,
1806
0
                             "Memory percentage must be between 0 and 100.");
1807
0
                    return CE_Failure;
1808
0
                }
1809
0
                auto bytes = CPLGetUsablePhysicalRAM();
1810
0
                if (bytes == 0)
1811
0
                {
1812
0
                    CPLError(CE_Failure, CPLE_NotSupported,
1813
0
                             "Cannot determine usable physical RAM");
1814
0
                    return CE_Failure;
1815
0
                }
1816
0
                value *= static_cast<double>(bytes / 100);
1817
0
                unit = c;
1818
0
            }
1819
0
            else
1820
0
            {
1821
0
                switch (*c)
1822
0
                {
1823
0
                    case 'G':
1824
0
                    case 'g':
1825
0
                        value *= 1024;
1826
0
                        [[fallthrough]];
1827
0
                    case 'M':
1828
0
                    case 'm':
1829
0
                        value *= 1024;
1830
0
                        [[fallthrough]];
1831
0
                    case 'K':
1832
0
                    case 'k':
1833
0
                        value *= 1024;
1834
0
                        unit = c;
1835
0
                        unitIsNotPercent = true;
1836
0
                        break;
1837
0
                    case ' ':
1838
0
                        break;
1839
0
                    default:
1840
0
                        CPLError(CE_Failure, CPLE_IllegalArg,
1841
0
                                 "Failed to parse memory size: %s", pszValue);
1842
0
                        return CE_Failure;
1843
0
                }
1844
0
            }
1845
0
        }
1846
0
        else if (unitIsNotPercent && c == unit + 1 && (*c == 'b' || *c == 'B'))
1847
0
        {
1848
            // ignore 'B' or 'b' as part of unit
1849
0
            continue;
1850
0
        }
1851
0
        else if (*c != ' ')
1852
0
        {
1853
0
            CPLError(CE_Failure, CPLE_IllegalArg,
1854
0
                     "Failed to parse memory size: %s", pszValue);
1855
0
            return CE_Failure;
1856
0
        }
1857
0
    }
1858
1859
0
    if (value > static_cast<double>(std::numeric_limits<GIntBig>::max()) ||
1860
0
        value > static_cast<double>(std::numeric_limits<size_t>::max()))
1861
0
    {
1862
0
        CPLError(CE_Failure, CPLE_IllegalArg, "Memory size is too large: %s",
1863
0
                 pszValue);
1864
0
        return CE_Failure;
1865
0
    }
1866
1867
0
    *pnValue = static_cast<GIntBig>(value);
1868
0
    if (pbUnitSpecified)
1869
0
    {
1870
0
        *pbUnitSpecified = (unit != nullptr);
1871
0
    }
1872
0
    return CE_None;
1873
0
}
1874
1875
/**********************************************************************
1876
 *                       CPLParseNameValue()
1877
 **********************************************************************/
1878
1879
/**
1880
 * Parse NAME=VALUE string into name and value components.
1881
 *
1882
 * Note that if ppszKey is non-NULL, the key (or name) portion will be
1883
 * allocated using CPLMalloc() and returned in that pointer.  It is the
1884
 * application's responsibility to free this string, but the application should
1885
 * not modify or free the returned value portion.
1886
 *
1887
 * This function also supports "NAME:VALUE" strings and will strip white
1888
 * space from around the delimiter when forming name and value strings.
1889
 *
1890
 * Eventually CSLFetchNameValue() and friends may be modified to use
1891
 * CPLParseNameValue().
1892
 *
1893
 * @param pszNameValue string in "NAME=VALUE" format.
1894
 * @param ppszKey optional pointer though which to return the name
1895
 * portion.
1896
 *
1897
 * @return the value portion (pointing into the original string).
1898
 */
1899
1900
const char *CPLParseNameValue(const char *pszNameValue, char **ppszKey)
1901
0
{
1902
0
    for (int i = 0; pszNameValue[i] != '\0'; ++i)
1903
0
    {
1904
0
        if (pszNameValue[i] == '=' || pszNameValue[i] == ':')
1905
0
        {
1906
0
            const char *pszValue = pszNameValue + i + 1;
1907
0
            while (*pszValue == ' ' || *pszValue == '\t')
1908
0
                ++pszValue;
1909
1910
0
            if (ppszKey != nullptr)
1911
0
            {
1912
0
                *ppszKey = static_cast<char *>(CPLMalloc(i + 1));
1913
0
                memcpy(*ppszKey, pszNameValue, i);
1914
0
                (*ppszKey)[i] = '\0';
1915
0
                while (i > 0 &&
1916
0
                       ((*ppszKey)[i - 1] == ' ' || (*ppszKey)[i - 1] == '\t'))
1917
0
                {
1918
0
                    (*ppszKey)[i - 1] = '\0';
1919
0
                    i--;
1920
0
                }
1921
0
            }
1922
1923
0
            return pszValue;
1924
0
        }
1925
0
    }
1926
1927
0
    return nullptr;
1928
0
}
1929
1930
namespace cpl
1931
{
1932
std::pair<std::string_view, std::string_view>
1933
parse_name_value(std::string_view svNameValue)
1934
0
{
1935
0
    for (size_t i = 0; i < svNameValue.size(); ++i)
1936
0
    {
1937
0
        if (svNameValue[i] == '=' || svNameValue[i] == ':')
1938
0
        {
1939
0
            auto parsed = std::make_pair(trim(svNameValue.substr(0, i)),
1940
0
                                         trim(svNameValue.substr(i + 1)));
1941
1942
0
            if (!parsed.first.empty())
1943
0
            {
1944
0
                return parsed;
1945
0
            }
1946
0
            else
1947
0
            {
1948
0
                return std::make_pair(std::string_view(), std::string_view());
1949
0
            }
1950
0
        }
1951
0
    }
1952
1953
0
    return std::make_pair(std::string_view(), std::string_view());
1954
0
}
1955
1956
std::pair<std::string_view, std::string_view>
1957
parse_name_value(const char *pszNameValue)
1958
0
{
1959
0
    return parse_name_value(std::string_view(pszNameValue));
1960
0
}
1961
1962
}  // namespace cpl
1963
1964
/**********************************************************************
1965
 *                       CPLParseNameValueSep()
1966
 **********************************************************************/
1967
/**
1968
 * Parse NAME<Sep>VALUE string into name and value components.
1969
 *
1970
 * This is derived directly from CPLParseNameValue() which will separate
1971
 * on '=' OR ':', here chSep is required for specifying the separator
1972
 * explicitly.
1973
 *
1974
 * @param pszNameValue string in "NAME=VALUE" format.
1975
 * @param ppszKey optional pointer though which to return the name
1976
 * portion.
1977
 * @param chSep required single char separator
1978
 * @return the value portion (pointing into original string).
1979
 */
1980
1981
const char *CPLParseNameValueSep(const char *pszNameValue, char **ppszKey,
1982
                                 char chSep)
1983
0
{
1984
0
    for (int i = 0; pszNameValue[i] != '\0'; ++i)
1985
0
    {
1986
0
        if (pszNameValue[i] == chSep)
1987
0
        {
1988
0
            const char *pszValue = pszNameValue + i + 1;
1989
0
            while (*pszValue == ' ' || *pszValue == '\t')
1990
0
                ++pszValue;
1991
1992
0
            if (ppszKey != nullptr)
1993
0
            {
1994
0
                *ppszKey = static_cast<char *>(CPLMalloc(i + 1));
1995
0
                memcpy(*ppszKey, pszNameValue, i);
1996
0
                (*ppszKey)[i] = '\0';
1997
0
                while (i > 0 &&
1998
0
                       ((*ppszKey)[i - 1] == ' ' || (*ppszKey)[i - 1] == '\t'))
1999
0
                {
2000
0
                    (*ppszKey)[i - 1] = '\0';
2001
0
                    i--;
2002
0
                }
2003
0
            }
2004
2005
0
            return pszValue;
2006
0
        }
2007
0
    }
2008
2009
0
    return nullptr;
2010
0
}
2011
2012
/**********************************************************************
2013
 *                       CSLFetchNameValueMultiple()
2014
 **********************************************************************/
2015
2016
/** In a StringList of "Name=Value" pairs, look for all the
2017
 * values with the specified name.  The search is not case
2018
 * sensitive.
2019
 * ("Name:Value" pairs are also supported for backward compatibility
2020
 * with older stuff.)
2021
 *
2022
 * Returns StringList with one entry for each occurrence of the
2023
 * specified name.  The StringList should eventually be destroyed
2024
 * by calling CSLDestroy().
2025
 *
2026
 * Returns NULL if the name is not found.
2027
 */
2028
2029
char **CSLFetchNameValueMultiple(CSLConstList papszStrList, const char *pszName)
2030
0
{
2031
0
    if (papszStrList == nullptr || pszName == nullptr)
2032
0
        return nullptr;
2033
2034
0
    const size_t nLen = strlen(pszName);
2035
0
    char **papszValues = nullptr;
2036
0
    while (*papszStrList != nullptr)
2037
0
    {
2038
0
        if (EQUALN(*papszStrList, pszName, nLen) &&
2039
0
            ((*papszStrList)[nLen] == '=' || (*papszStrList)[nLen] == ':'))
2040
0
        {
2041
0
            papszValues = CSLAddString(papszValues, (*papszStrList) + nLen + 1);
2042
0
        }
2043
0
        ++papszStrList;
2044
0
    }
2045
2046
0
    return papszValues;
2047
0
}
2048
2049
/**********************************************************************
2050
 *                       CSLAddNameValue()
2051
 **********************************************************************/
2052
2053
/** Add a new entry to a StringList of "Name=Value" pairs,
2054
 * ("Name:Value" pairs are also supported for backward compatibility
2055
 * with older stuff.)
2056
 *
2057
 * This function does not check if a "Name=Value" pair already exists
2058
 * for that name and can generate multiple entries for the same name.
2059
 * Use CSLSetNameValue() if you want each name to have only one value.
2060
 *
2061
 * Returns the modified StringList.
2062
 */
2063
2064
char **CSLAddNameValue(char **papszStrList, const char *pszName,
2065
                       const char *pszValue)
2066
2.37k
{
2067
2.37k
    if (pszName == nullptr || pszValue == nullptr)
2068
0
        return papszStrList;
2069
2070
2.37k
    const size_t nLen = strlen(pszName) + strlen(pszValue) + 2;
2071
2.37k
    char *pszLine = static_cast<char *>(CPLMalloc(nLen));
2072
2.37k
    snprintf(pszLine, nLen, "%s=%s", pszName, pszValue);
2073
2.37k
    papszStrList = CSLAddString(papszStrList, pszLine);
2074
2.37k
    CPLFree(pszLine);
2075
2076
2.37k
    return papszStrList;
2077
2.37k
}
2078
2079
/************************************************************************/
2080
/*                          CSLSetNameValue()                           */
2081
/************************************************************************/
2082
2083
/**
2084
 * Assign value to name in StringList.
2085
 *
2086
 * Set the value for a given name in a StringList of "Name=Value" pairs
2087
 * ("Name:Value" pairs are also supported for backward compatibility
2088
 * with older stuff.)
2089
 *
2090
 * If there is already a value for that name in the list then the value
2091
 * is changed, otherwise a new "Name=Value" pair is added.
2092
 *
2093
 * @param papszList the original list, the modified version is returned.
2094
 * @param pszName the name to be assigned a value.  This should be a well
2095
 * formed token (no spaces or very special characters).
2096
 * @param pszValue the value to assign to the name.  This should not contain
2097
 * any newlines (CR or LF) but is otherwise pretty much unconstrained.  If
2098
 * NULL any corresponding value will be removed.
2099
 *
2100
 * @return modified StringList.
2101
 */
2102
2103
char **CSLSetNameValue(char **papszList, const char *pszName,
2104
                       const char *pszValue)
2105
8.91k
{
2106
8.91k
    if (pszName == nullptr)
2107
0
        return papszList;
2108
2109
8.91k
    size_t nLen = strlen(pszName);
2110
10.6k
    while (nLen > 0 && pszName[nLen - 1] == ' ')
2111
1.74k
        nLen--;
2112
8.91k
    char **papszPtr = papszList;
2113
5.99M
    while (papszPtr && *papszPtr != nullptr)
2114
5.98M
    {
2115
5.98M
        if (EQUALN(*papszPtr, pszName, nLen))
2116
11.7k
        {
2117
11.7k
            size_t i;
2118
13.0k
            for (i = nLen; (*papszPtr)[i] == ' '; ++i)
2119
1.24k
            {
2120
1.24k
            }
2121
11.7k
            if ((*papszPtr)[i] == '=' || (*papszPtr)[i] == ':')
2122
6.54k
            {
2123
                // Found it.
2124
                // Change the value... make sure to keep the ':' or '='.
2125
6.54k
                const char cSep = (*papszPtr)[i];
2126
2127
6.54k
                CPLFree(*papszPtr);
2128
2129
                // If the value is NULL, remove this entry completely.
2130
6.54k
                if (pszValue == nullptr)
2131
0
                {
2132
0
                    while (papszPtr[1] != nullptr)
2133
0
                    {
2134
0
                        *papszPtr = papszPtr[1];
2135
0
                        ++papszPtr;
2136
0
                    }
2137
0
                    *papszPtr = nullptr;
2138
0
                }
2139
2140
                // Otherwise replace with new value.
2141
6.54k
                else
2142
6.54k
                {
2143
6.54k
                    const size_t nLen2 = strlen(pszName) + strlen(pszValue) + 2;
2144
6.54k
                    *papszPtr = static_cast<char *>(CPLMalloc(nLen2));
2145
6.54k
                    snprintf(*papszPtr, nLen2, "%s%c%s", pszName, cSep,
2146
6.54k
                             pszValue);
2147
6.54k
                }
2148
6.54k
                return papszList;
2149
6.54k
            }
2150
11.7k
        }
2151
5.98M
        ++papszPtr;
2152
5.98M
    }
2153
2154
2.37k
    if (pszValue == nullptr)
2155
0
        return papszList;
2156
2157
    // The name does not exist yet.  Create a new entry.
2158
2.37k
    return CSLAddNameValue(papszList, pszName, pszValue);
2159
2.37k
}
2160
2161
/************************************************************************/
2162
/*                      CSLSetNameValueSeparator()                      */
2163
/************************************************************************/
2164
2165
/**
2166
 * Replace the default separator (":" or "=") with the passed separator
2167
 * in the given name/value list.
2168
 *
2169
 * Note that if a separator other than ":" or "=" is used, the resulting
2170
 * list will not be manipulable by the CSL name/value functions any more.
2171
 *
2172
 * The CPLParseNameValue() function is used to break the existing lines,
2173
 * and it also strips white space from around the existing delimiter, thus
2174
 * the old separator, and any white space will be replaced by the new
2175
 * separator.  For formatting purposes it may be desirable to include some
2176
 * white space in the new separator.  e.g. ": " or " = ".
2177
 *
2178
 * @param papszList the list to update.  Component strings may be freed
2179
 * but the list array will remain at the same location.
2180
 *
2181
 * @param pszSeparator the new separator string to insert.
2182
 */
2183
2184
void CSLSetNameValueSeparator(char **papszList, const char *pszSeparator)
2185
2186
0
{
2187
0
    const int nLines = CSLCount(papszList);
2188
2189
0
    for (int iLine = 0; iLine < nLines; ++iLine)
2190
0
    {
2191
0
        char *pszKey = nullptr;
2192
0
        const char *pszValue = CPLParseNameValue(papszList[iLine], &pszKey);
2193
0
        if (pszValue == nullptr || pszKey == nullptr)
2194
0
        {
2195
0
            CPLFree(pszKey);
2196
0
            continue;
2197
0
        }
2198
2199
0
        char *pszNewLine = static_cast<char *>(CPLMalloc(
2200
0
            strlen(pszValue) + strlen(pszKey) + strlen(pszSeparator) + 1));
2201
0
        strcpy(pszNewLine, pszKey);
2202
0
        strcat(pszNewLine, pszSeparator);
2203
0
        strcat(pszNewLine, pszValue);
2204
0
        CPLFree(papszList[iLine]);
2205
0
        papszList[iLine] = pszNewLine;
2206
0
        CPLFree(pszKey);
2207
0
    }
2208
0
}
2209
2210
/************************************************************************/
2211
/*                          CPLEscapeString()                           */
2212
/************************************************************************/
2213
2214
/**
2215
 * Apply escaping to string to preserve special characters.
2216
 *
2217
 * This function will "escape" a variety of special characters
2218
 * to make the string suitable to embed within a string constant
2219
 * or to write within a text stream but in a form that can be
2220
 * reconstituted to its original form.  The escaping will even preserve
2221
 * zero bytes allowing preservation of raw binary data.
2222
 *
2223
 * CPLES_BackslashQuotable(0): This scheme turns a binary string into
2224
 * a form suitable to be placed within double quotes as a string constant.
2225
 * The backslash, quote, '\\0' and newline characters are all escaped in
2226
 * the usual C style.
2227
 *
2228
 * CPLES_XML(1): This scheme converts the '<', '>', '"' and '&' characters into
2229
 * their XML/HTML equivalent (&lt;, &gt;, &quot; and &amp;) making a string safe
2230
 * to embed as CDATA within an XML element.  The '\\0' is not escaped and
2231
 * should not be included in the input.
2232
 *
2233
 * CPLES_URL(2): Everything except alphanumerics and the characters
2234
 * '$', '-', '_', '.', '+', '!', '*', ''', '(', ')' and ',' (see RFC1738) are
2235
 * converted to a percent followed by a two digit hex encoding of the character
2236
 * (leading zero supplied if needed).  This is the mechanism used for encoding
2237
 * values to be passed in URLs. Note that this is different from what
2238
 * CPLString::URLEncode() does.
2239
 *
2240
 * CPLES_SQL(3): All single quotes are replaced with two single quotes.
2241
 * Suitable for use when constructing literal values for SQL commands where
2242
 * the literal will be enclosed in single quotes.
2243
 *
2244
 * CPLES_CSV(4): If the values contains commas, semicolons, tabs, double quotes,
2245
 * or newlines it placed in double quotes, and double quotes in the value are
2246
 * doubled. Suitable for use when constructing field values for .csv files.
2247
 * Note that CPLUnescapeString() currently does not support this format, only
2248
 * CPLEscapeString().  See cpl_csv.cpp for CSV parsing support.
2249
 *
2250
 * CPLES_SQLI(7): All double quotes are replaced with two double quotes.
2251
 * Suitable for use when constructing identifiers for SQL commands where
2252
 * the literal will be enclosed in double quotes.
2253
 *
2254
 * @param pszInput the string to escape.
2255
 * @param nLength The number of bytes of data to preserve.  If this is -1
2256
 * the strlen(pszString) function will be used to compute the length.
2257
 * @param nScheme the encoding scheme to use.
2258
 *
2259
 * @return an escaped, zero terminated string that should be freed with
2260
 * CPLFree() when no longer needed.
2261
 */
2262
2263
char *CPLEscapeString(const char *pszInput, int nLength, int nScheme)
2264
0
{
2265
0
    const size_t szLength =
2266
0
        (nLength < 0) ? strlen(pszInput) : static_cast<size_t>(nLength);
2267
0
#define nLength no_longer_use_me
2268
2269
0
    size_t nSizeAlloc = 1;
2270
#if SIZEOF_VOIDP < 8
2271
    bool bWrapAround = false;
2272
    const auto IncSizeAlloc = [&nSizeAlloc, &bWrapAround](size_t inc)
2273
    {
2274
        constexpr size_t SZ_MAX = std::numeric_limits<size_t>::max();
2275
        if (nSizeAlloc > SZ_MAX - inc)
2276
        {
2277
            bWrapAround = true;
2278
            nSizeAlloc = 0;
2279
        }
2280
        nSizeAlloc += inc;
2281
    };
2282
#else
2283
0
    const auto IncSizeAlloc = [&nSizeAlloc](size_t inc) { nSizeAlloc += inc; };
2284
0
#endif
2285
2286
0
    if (nScheme == CPLES_BackslashQuotable)
2287
0
    {
2288
0
        for (size_t iIn = 0; iIn < szLength; iIn++)
2289
0
        {
2290
0
            if (pszInput[iIn] == '\0' || pszInput[iIn] == '\n' ||
2291
0
                pszInput[iIn] == '"' || pszInput[iIn] == '\\')
2292
0
                IncSizeAlloc(2);
2293
0
            else
2294
0
                IncSizeAlloc(1);
2295
0
        }
2296
0
    }
2297
0
    else if (nScheme == CPLES_XML || nScheme == CPLES_XML_BUT_QUOTES)
2298
0
    {
2299
0
        for (size_t iIn = 0; iIn < szLength; ++iIn)
2300
0
        {
2301
0
            if (pszInput[iIn] == '<')
2302
0
            {
2303
0
                IncSizeAlloc(4);
2304
0
            }
2305
0
            else if (pszInput[iIn] == '>')
2306
0
            {
2307
0
                IncSizeAlloc(4);
2308
0
            }
2309
0
            else if (pszInput[iIn] == '&')
2310
0
            {
2311
0
                IncSizeAlloc(5);
2312
0
            }
2313
0
            else if (pszInput[iIn] == '"' && nScheme != CPLES_XML_BUT_QUOTES)
2314
0
            {
2315
0
                IncSizeAlloc(6);
2316
0
            }
2317
            // Python 2 does not display the UTF-8 character corresponding
2318
            // to the byte-order mark (BOM), so escape it.
2319
0
            else if ((reinterpret_cast<const unsigned char *>(pszInput))[iIn] ==
2320
0
                         0xEF &&
2321
0
                     (reinterpret_cast<const unsigned char *>(
2322
0
                         pszInput))[iIn + 1] == 0xBB &&
2323
0
                     (reinterpret_cast<const unsigned char *>(
2324
0
                         pszInput))[iIn + 2] == 0xBF)
2325
0
            {
2326
0
                IncSizeAlloc(8);
2327
0
                iIn += 2;
2328
0
            }
2329
0
            else if ((reinterpret_cast<const unsigned char *>(pszInput))[iIn] <
2330
0
                         0x20 &&
2331
0
                     pszInput[iIn] != 0x9 && pszInput[iIn] != 0xA &&
2332
0
                     pszInput[iIn] != 0xD)
2333
0
            {
2334
                // These control characters are unrepresentable in XML format,
2335
                // so we just drop them.  #4117
2336
0
            }
2337
0
            else
2338
0
            {
2339
0
                IncSizeAlloc(1);
2340
0
            }
2341
0
        }
2342
0
    }
2343
0
    else if (nScheme == CPLES_URL)  // Untested at implementation.
2344
0
    {
2345
0
        for (size_t iIn = 0; iIn < szLength; ++iIn)
2346
0
        {
2347
0
            if ((pszInput[iIn] >= 'a' && pszInput[iIn] <= 'z') ||
2348
0
                (pszInput[iIn] >= 'A' && pszInput[iIn] <= 'Z') ||
2349
0
                (pszInput[iIn] >= '0' && pszInput[iIn] <= '9') ||
2350
0
                pszInput[iIn] == '$' || pszInput[iIn] == '-' ||
2351
0
                pszInput[iIn] == '_' || pszInput[iIn] == '.' ||
2352
0
                pszInput[iIn] == '+' || pszInput[iIn] == '!' ||
2353
0
                pszInput[iIn] == '*' || pszInput[iIn] == '\'' ||
2354
0
                pszInput[iIn] == '(' || pszInput[iIn] == ')' ||
2355
0
                pszInput[iIn] == ',')
2356
0
            {
2357
0
                IncSizeAlloc(1);
2358
0
            }
2359
0
            else
2360
0
            {
2361
0
                IncSizeAlloc(3);
2362
0
            }
2363
0
        }
2364
0
    }
2365
0
    else if (nScheme == CPLES_SQL || nScheme == CPLES_SQLI)
2366
0
    {
2367
0
        const char chQuote = nScheme == CPLES_SQL ? '\'' : '\"';
2368
0
        for (size_t iIn = 0; iIn < szLength; ++iIn)
2369
0
        {
2370
0
            if (pszInput[iIn] == chQuote)
2371
0
            {
2372
0
                IncSizeAlloc(2);
2373
0
            }
2374
0
            else
2375
0
            {
2376
0
                IncSizeAlloc(1);
2377
0
            }
2378
0
        }
2379
0
    }
2380
0
    else if (nScheme == CPLES_CSV || nScheme == CPLES_CSV_FORCE_QUOTING)
2381
0
    {
2382
0
        if (nScheme == CPLES_CSV && strcspn(pszInput, "\",;\t\n\r") == szLength)
2383
0
        {
2384
0
            char *pszOutput =
2385
0
                static_cast<char *>(VSI_MALLOC_VERBOSE(szLength + 1));
2386
0
            if (pszOutput == nullptr)
2387
0
                return nullptr;
2388
0
            memcpy(pszOutput, pszInput, szLength + 1);
2389
0
            return pszOutput;
2390
0
        }
2391
0
        else
2392
0
        {
2393
0
            IncSizeAlloc(1);
2394
0
            for (size_t iIn = 0; iIn < szLength; ++iIn)
2395
0
            {
2396
0
                if (pszInput[iIn] == '\"')
2397
0
                {
2398
0
                    IncSizeAlloc(2);
2399
0
                }
2400
0
                else
2401
0
                    IncSizeAlloc(1);
2402
0
            }
2403
0
            IncSizeAlloc(1);
2404
0
        }
2405
0
    }
2406
0
    else
2407
0
    {
2408
0
        CPLError(CE_Failure, CPLE_AppDefined,
2409
0
                 "Undefined escaping scheme (%d) in CPLEscapeString()",
2410
0
                 nScheme);
2411
0
        return CPLStrdup("");
2412
0
    }
2413
2414
#if SIZEOF_VOIDP < 8
2415
    if (bWrapAround)
2416
    {
2417
        CPLError(CE_Failure, CPLE_OutOfMemory,
2418
                 "Out of memory in CPLEscapeString()");
2419
        return nullptr;
2420
    }
2421
#endif
2422
2423
0
    char *pszOutput = static_cast<char *>(VSI_MALLOC_VERBOSE(nSizeAlloc));
2424
0
    if (pszOutput == nullptr)
2425
0
        return nullptr;
2426
2427
0
    size_t iOut = 0;
2428
2429
0
    if (nScheme == CPLES_BackslashQuotable)
2430
0
    {
2431
0
        for (size_t iIn = 0; iIn < szLength; iIn++)
2432
0
        {
2433
0
            if (pszInput[iIn] == '\0')
2434
0
            {
2435
0
                pszOutput[iOut++] = '\\';
2436
0
                pszOutput[iOut++] = '0';
2437
0
            }
2438
0
            else if (pszInput[iIn] == '\n')
2439
0
            {
2440
0
                pszOutput[iOut++] = '\\';
2441
0
                pszOutput[iOut++] = 'n';
2442
0
            }
2443
0
            else if (pszInput[iIn] == '"')
2444
0
            {
2445
0
                pszOutput[iOut++] = '\\';
2446
0
                pszOutput[iOut++] = '\"';
2447
0
            }
2448
0
            else if (pszInput[iIn] == '\\')
2449
0
            {
2450
0
                pszOutput[iOut++] = '\\';
2451
0
                pszOutput[iOut++] = '\\';
2452
0
            }
2453
0
            else
2454
0
                pszOutput[iOut++] = pszInput[iIn];
2455
0
        }
2456
0
        pszOutput[iOut++] = '\0';
2457
0
    }
2458
0
    else if (nScheme == CPLES_XML || nScheme == CPLES_XML_BUT_QUOTES)
2459
0
    {
2460
0
        for (size_t iIn = 0; iIn < szLength; ++iIn)
2461
0
        {
2462
0
            if (pszInput[iIn] == '<')
2463
0
            {
2464
0
                pszOutput[iOut++] = '&';
2465
0
                pszOutput[iOut++] = 'l';
2466
0
                pszOutput[iOut++] = 't';
2467
0
                pszOutput[iOut++] = ';';
2468
0
            }
2469
0
            else if (pszInput[iIn] == '>')
2470
0
            {
2471
0
                pszOutput[iOut++] = '&';
2472
0
                pszOutput[iOut++] = 'g';
2473
0
                pszOutput[iOut++] = 't';
2474
0
                pszOutput[iOut++] = ';';
2475
0
            }
2476
0
            else if (pszInput[iIn] == '&')
2477
0
            {
2478
0
                pszOutput[iOut++] = '&';
2479
0
                pszOutput[iOut++] = 'a';
2480
0
                pszOutput[iOut++] = 'm';
2481
0
                pszOutput[iOut++] = 'p';
2482
0
                pszOutput[iOut++] = ';';
2483
0
            }
2484
0
            else if (pszInput[iIn] == '"' && nScheme != CPLES_XML_BUT_QUOTES)
2485
0
            {
2486
0
                pszOutput[iOut++] = '&';
2487
0
                pszOutput[iOut++] = 'q';
2488
0
                pszOutput[iOut++] = 'u';
2489
0
                pszOutput[iOut++] = 'o';
2490
0
                pszOutput[iOut++] = 't';
2491
0
                pszOutput[iOut++] = ';';
2492
0
            }
2493
            // Python 2 does not display the UTF-8 character corresponding
2494
            // to the byte-order mark (BOM), so escape it.
2495
0
            else if ((reinterpret_cast<const unsigned char *>(pszInput))[iIn] ==
2496
0
                         0xEF &&
2497
0
                     (reinterpret_cast<const unsigned char *>(
2498
0
                         pszInput))[iIn + 1] == 0xBB &&
2499
0
                     (reinterpret_cast<const unsigned char *>(
2500
0
                         pszInput))[iIn + 2] == 0xBF)
2501
0
            {
2502
0
                pszOutput[iOut++] = '&';
2503
0
                pszOutput[iOut++] = '#';
2504
0
                pszOutput[iOut++] = 'x';
2505
0
                pszOutput[iOut++] = 'F';
2506
0
                pszOutput[iOut++] = 'E';
2507
0
                pszOutput[iOut++] = 'F';
2508
0
                pszOutput[iOut++] = 'F';
2509
0
                pszOutput[iOut++] = ';';
2510
0
                iIn += 2;
2511
0
            }
2512
0
            else if ((reinterpret_cast<const unsigned char *>(pszInput))[iIn] <
2513
0
                         0x20 &&
2514
0
                     pszInput[iIn] != 0x9 && pszInput[iIn] != 0xA &&
2515
0
                     pszInput[iIn] != 0xD)
2516
0
            {
2517
                // These control characters are unrepresentable in XML format,
2518
                // so we just drop them.  #4117
2519
0
            }
2520
0
            else
2521
0
            {
2522
0
                pszOutput[iOut++] = pszInput[iIn];
2523
0
            }
2524
0
        }
2525
0
        pszOutput[iOut++] = '\0';
2526
0
    }
2527
0
    else if (nScheme == CPLES_URL)  // Untested at implementation.
2528
0
    {
2529
0
        for (size_t iIn = 0; iIn < szLength; ++iIn)
2530
0
        {
2531
0
            if ((pszInput[iIn] >= 'a' && pszInput[iIn] <= 'z') ||
2532
0
                (pszInput[iIn] >= 'A' && pszInput[iIn] <= 'Z') ||
2533
0
                (pszInput[iIn] >= '0' && pszInput[iIn] <= '9') ||
2534
0
                pszInput[iIn] == '$' || pszInput[iIn] == '-' ||
2535
0
                pszInput[iIn] == '_' || pszInput[iIn] == '.' ||
2536
0
                pszInput[iIn] == '+' || pszInput[iIn] == '!' ||
2537
0
                pszInput[iIn] == '*' || pszInput[iIn] == '\'' ||
2538
0
                pszInput[iIn] == '(' || pszInput[iIn] == ')' ||
2539
0
                pszInput[iIn] == ',')
2540
0
            {
2541
0
                pszOutput[iOut++] = pszInput[iIn];
2542
0
            }
2543
0
            else
2544
0
            {
2545
0
                snprintf(pszOutput + iOut, nSizeAlloc - iOut, "%%%02X",
2546
0
                         static_cast<unsigned char>(pszInput[iIn]));
2547
0
                iOut += 3;
2548
0
            }
2549
0
        }
2550
0
        pszOutput[iOut++] = '\0';
2551
0
    }
2552
0
    else if (nScheme == CPLES_SQL || nScheme == CPLES_SQLI)
2553
0
    {
2554
0
        const char chQuote = nScheme == CPLES_SQL ? '\'' : '\"';
2555
0
        for (size_t iIn = 0; iIn < szLength; ++iIn)
2556
0
        {
2557
0
            if (pszInput[iIn] == chQuote)
2558
0
            {
2559
0
                pszOutput[iOut++] = chQuote;
2560
0
                pszOutput[iOut++] = chQuote;
2561
0
            }
2562
0
            else
2563
0
            {
2564
0
                pszOutput[iOut++] = pszInput[iIn];
2565
0
            }
2566
0
        }
2567
0
        pszOutput[iOut++] = '\0';
2568
0
    }
2569
0
    else if (nScheme == CPLES_CSV || nScheme == CPLES_CSV_FORCE_QUOTING)
2570
0
    {
2571
0
        pszOutput[iOut++] = '\"';
2572
2573
0
        for (size_t iIn = 0; iIn < szLength; ++iIn)
2574
0
        {
2575
0
            if (pszInput[iIn] == '\"')
2576
0
            {
2577
0
                pszOutput[iOut++] = '\"';
2578
0
                pszOutput[iOut++] = '\"';
2579
0
            }
2580
0
            else
2581
0
                pszOutput[iOut++] = pszInput[iIn];
2582
0
        }
2583
0
        pszOutput[iOut++] = '\"';
2584
0
        pszOutput[iOut++] = '\0';
2585
0
    }
2586
2587
0
    return pszOutput;
2588
0
#undef nLength
2589
0
}
2590
2591
/************************************************************************/
2592
/*                         CPLUnescapeString()                          */
2593
/************************************************************************/
2594
2595
/**
2596
 * Unescape a string.
2597
 *
2598
 * This function does the opposite of CPLEscapeString().  Given a string
2599
 * with special values escaped according to some scheme, it will return a
2600
 * new copy of the string returned to its original form.
2601
 *
2602
 * @param pszInput the input string.  This is a zero terminated string.
2603
 * @param pnLength location to return the length of the unescaped string,
2604
 * which may in some cases include embedded '\\0' characters.
2605
 * @param nScheme the escaped scheme to undo (see CPLEscapeString() for a
2606
 * list).  Does not yet support CSV.
2607
 *
2608
 * @return a copy of the unescaped string that should be freed by the
2609
 * application using CPLFree() when no longer needed.
2610
 */
2611
2612
CPL_NOSANITIZE_UNSIGNED_INT_OVERFLOW
2613
char *CPLUnescapeString(const char *pszInput, int *pnLength, int nScheme)
2614
2615
0
{
2616
0
    int iOut = 0;
2617
2618
    // TODO: Why times 4?
2619
0
    char *pszOutput = static_cast<char *>(CPLMalloc(4 * strlen(pszInput) + 1));
2620
0
    pszOutput[0] = '\0';
2621
2622
0
    if (nScheme == CPLES_BackslashQuotable)
2623
0
    {
2624
0
        for (int iIn = 0; pszInput[iIn] != '\0'; ++iIn)
2625
0
        {
2626
0
            if (pszInput[iIn] == '\\')
2627
0
            {
2628
0
                ++iIn;
2629
0
                if (pszInput[iIn] == '\0')
2630
0
                    break;
2631
0
                if (pszInput[iIn] == 'n')
2632
0
                    pszOutput[iOut++] = '\n';
2633
0
                else if (pszInput[iIn] == '0')
2634
0
                    pszOutput[iOut++] = '\0';
2635
0
                else
2636
0
                    pszOutput[iOut++] = pszInput[iIn];
2637
0
            }
2638
0
            else
2639
0
            {
2640
0
                pszOutput[iOut++] = pszInput[iIn];
2641
0
            }
2642
0
        }
2643
0
    }
2644
0
    else if (nScheme == CPLES_XML || nScheme == CPLES_XML_BUT_QUOTES)
2645
0
    {
2646
0
        char ch = '\0';
2647
0
        for (int iIn = 0; (ch = pszInput[iIn]) != '\0'; ++iIn)
2648
0
        {
2649
0
            if (ch != '&')
2650
0
            {
2651
0
                pszOutput[iOut++] = ch;
2652
0
            }
2653
0
            else if (STARTS_WITH_CI(pszInput + iIn, "&lt;"))
2654
0
            {
2655
0
                pszOutput[iOut++] = '<';
2656
0
                iIn += 3;
2657
0
            }
2658
0
            else if (STARTS_WITH_CI(pszInput + iIn, "&gt;"))
2659
0
            {
2660
0
                pszOutput[iOut++] = '>';
2661
0
                iIn += 3;
2662
0
            }
2663
0
            else if (STARTS_WITH_CI(pszInput + iIn, "&amp;"))
2664
0
            {
2665
0
                pszOutput[iOut++] = '&';
2666
0
                iIn += 4;
2667
0
            }
2668
0
            else if (STARTS_WITH_CI(pszInput + iIn, "&apos;"))
2669
0
            {
2670
0
                pszOutput[iOut++] = '\'';
2671
0
                iIn += 5;
2672
0
            }
2673
0
            else if (STARTS_WITH_CI(pszInput + iIn, "&quot;"))
2674
0
            {
2675
0
                pszOutput[iOut++] = '"';
2676
0
                iIn += 5;
2677
0
            }
2678
0
            else if (STARTS_WITH_CI(pszInput + iIn, "&#x"))
2679
0
            {
2680
0
                wchar_t anVal[2] = {0, 0};
2681
0
                iIn += 3;
2682
2683
0
                unsigned int nVal = 0;
2684
0
                while (true)
2685
0
                {
2686
0
                    ch = pszInput[iIn++];
2687
0
                    if (ch >= 'a' && ch <= 'f')
2688
0
                        nVal = nVal * 16U +
2689
0
                               static_cast<unsigned int>(ch - 'a' + 10);
2690
0
                    else if (ch >= 'A' && ch <= 'F')
2691
0
                        nVal = nVal * 16U +
2692
0
                               static_cast<unsigned int>(ch - 'A' + 10);
2693
0
                    else if (ch >= '0' && ch <= '9')
2694
0
                        nVal = nVal * 16U + static_cast<unsigned int>(ch - '0');
2695
0
                    else
2696
0
                        break;
2697
0
                }
2698
0
                anVal[0] = static_cast<wchar_t>(nVal);
2699
0
                if (ch != ';')
2700
0
                    break;
2701
0
                iIn--;
2702
2703
0
                char *pszUTF8 =
2704
0
                    CPLRecodeFromWChar(anVal, "WCHAR_T", CPL_ENC_UTF8);
2705
0
                int nLen = static_cast<int>(strlen(pszUTF8));
2706
0
                memcpy(pszOutput + iOut, pszUTF8, nLen);
2707
0
                CPLFree(pszUTF8);
2708
0
                iOut += nLen;
2709
0
            }
2710
0
            else if (STARTS_WITH_CI(pszInput + iIn, "&#"))
2711
0
            {
2712
0
                wchar_t anVal[2] = {0, 0};
2713
0
                iIn += 2;
2714
2715
0
                unsigned int nVal = 0;
2716
0
                while (true)
2717
0
                {
2718
0
                    ch = pszInput[iIn++];
2719
0
                    if (ch >= '0' && ch <= '9')
2720
0
                        nVal = nVal * 10U + static_cast<unsigned int>(ch - '0');
2721
0
                    else
2722
0
                        break;
2723
0
                }
2724
0
                anVal[0] = static_cast<wchar_t>(nVal);
2725
0
                if (ch != ';')
2726
0
                    break;
2727
0
                iIn--;
2728
2729
0
                char *pszUTF8 =
2730
0
                    CPLRecodeFromWChar(anVal, "WCHAR_T", CPL_ENC_UTF8);
2731
0
                const int nLen = static_cast<int>(strlen(pszUTF8));
2732
0
                memcpy(pszOutput + iOut, pszUTF8, nLen);
2733
0
                CPLFree(pszUTF8);
2734
0
                iOut += nLen;
2735
0
            }
2736
0
            else
2737
0
            {
2738
                // Illegal escape sequence.
2739
0
                CPLDebug("CPL",
2740
0
                         "Error unescaping CPLES_XML text, '&' character "
2741
0
                         "followed by unhandled escape sequence.");
2742
0
                break;
2743
0
            }
2744
0
        }
2745
0
    }
2746
0
    else if (nScheme == CPLES_URL)
2747
0
    {
2748
0
        for (int iIn = 0; pszInput[iIn] != '\0'; ++iIn)
2749
0
        {
2750
0
            if (pszInput[iIn] == '%' && pszInput[iIn + 1] != '\0' &&
2751
0
                pszInput[iIn + 2] != '\0')
2752
0
            {
2753
0
                int nHexChar = 0;
2754
2755
0
                if (pszInput[iIn + 1] >= 'A' && pszInput[iIn + 1] <= 'F')
2756
0
                    nHexChar += 16 * (pszInput[iIn + 1] - 'A' + 10);
2757
0
                else if (pszInput[iIn + 1] >= 'a' && pszInput[iIn + 1] <= 'f')
2758
0
                    nHexChar += 16 * (pszInput[iIn + 1] - 'a' + 10);
2759
0
                else if (pszInput[iIn + 1] >= '0' && pszInput[iIn + 1] <= '9')
2760
0
                    nHexChar += 16 * (pszInput[iIn + 1] - '0');
2761
0
                else
2762
0
                    CPLDebug("CPL",
2763
0
                             "Error unescaping CPLES_URL text, percent not "
2764
0
                             "followed by two hex digits.");
2765
2766
0
                if (pszInput[iIn + 2] >= 'A' && pszInput[iIn + 2] <= 'F')
2767
0
                    nHexChar += pszInput[iIn + 2] - 'A' + 10;
2768
0
                else if (pszInput[iIn + 2] >= 'a' && pszInput[iIn + 2] <= 'f')
2769
0
                    nHexChar += pszInput[iIn + 2] - 'a' + 10;
2770
0
                else if (pszInput[iIn + 2] >= '0' && pszInput[iIn + 2] <= '9')
2771
0
                    nHexChar += pszInput[iIn + 2] - '0';
2772
0
                else
2773
0
                    CPLDebug("CPL",
2774
0
                             "Error unescaping CPLES_URL text, percent not "
2775
0
                             "followed by two hex digits.");
2776
2777
0
                pszOutput[iOut++] = static_cast<char>(nHexChar);
2778
0
                iIn += 2;
2779
0
            }
2780
0
            else if (pszInput[iIn] == '+')
2781
0
            {
2782
0
                pszOutput[iOut++] = ' ';
2783
0
            }
2784
0
            else
2785
0
            {
2786
0
                pszOutput[iOut++] = pszInput[iIn];
2787
0
            }
2788
0
        }
2789
0
    }
2790
0
    else if (nScheme == CPLES_SQL || nScheme == CPLES_SQLI)
2791
0
    {
2792
0
        char szQuote = nScheme == CPLES_SQL ? '\'' : '\"';
2793
0
        for (int iIn = 0; pszInput[iIn] != '\0'; ++iIn)
2794
0
        {
2795
0
            if (pszInput[iIn] == szQuote && pszInput[iIn + 1] == szQuote)
2796
0
            {
2797
0
                ++iIn;
2798
0
                pszOutput[iOut++] = pszInput[iIn];
2799
0
            }
2800
0
            else
2801
0
            {
2802
0
                pszOutput[iOut++] = pszInput[iIn];
2803
0
            }
2804
0
        }
2805
0
    }
2806
0
    else if (nScheme == CPLES_CSV)
2807
0
    {
2808
0
        CPLError(CE_Fatal, CPLE_NotSupported,
2809
0
                 "CSV Unescaping not yet implemented.");
2810
0
    }
2811
0
    else
2812
0
    {
2813
0
        CPLError(CE_Fatal, CPLE_NotSupported, "Unknown escaping style.");
2814
0
    }
2815
2816
0
    pszOutput[iOut] = '\0';
2817
2818
0
    if (pnLength != nullptr)
2819
0
        *pnLength = iOut;
2820
2821
0
    return pszOutput;
2822
0
}
2823
2824
/************************************************************************/
2825
/*                           CPLBinaryToHex()                           */
2826
/************************************************************************/
2827
2828
/**
2829
 * Binary to hexadecimal translation.
2830
 *
2831
 * @param nBytes number of bytes of binary data in pabyData.
2832
 * @param pabyData array of data bytes to translate.
2833
 *
2834
 * @return hexadecimal translation, zero terminated.  Free with CPLFree().
2835
 */
2836
2837
char *CPLBinaryToHex(int nBytes, const GByte *pabyData)
2838
2839
0
{
2840
0
    CPLAssert(nBytes >= 0);
2841
0
    char *pszHex = static_cast<char *>(
2842
0
        VSI_MALLOC_VERBOSE(static_cast<size_t>(nBytes) * 2 + 1));
2843
0
    if (!pszHex)
2844
0
    {
2845
0
        pszHex = CPLStrdup("");
2846
0
        return pszHex;
2847
0
    }
2848
0
    pszHex[nBytes * 2] = '\0';
2849
2850
0
    constexpr char achHex[] = "0123456789ABCDEF";
2851
2852
0
    for (size_t i = 0; i < static_cast<size_t>(nBytes); ++i)
2853
0
    {
2854
0
        const int nLow = pabyData[i] & 0x0f;
2855
0
        const int nHigh = (pabyData[i] & 0xf0) >> 4;
2856
2857
0
        pszHex[i * 2] = achHex[nHigh];
2858
0
        pszHex[i * 2 + 1] = achHex[nLow];
2859
0
    }
2860
2861
0
    return pszHex;
2862
0
}
2863
2864
/************************************************************************/
2865
/*                           CPLHexToBinary()                           */
2866
/************************************************************************/
2867
2868
constexpr unsigned char hex2char[256] = {
2869
    // Not Hex characters.
2870
    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
2871
    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
2872
    // 0-9
2873
    0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 0, 0, 0, 0, 0,
2874
    // A-F
2875
    0, 10, 11, 12, 13, 14, 15, 0, 0, 0, 0, 0, 0, 0, 0, 0,
2876
    // Not Hex characters.
2877
    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
2878
    // a-f
2879
    0, 10, 11, 12, 13, 14, 15, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
2880
    0, 0, 0, 0, 0, 0, 0, 0, 0,
2881
    // Not Hex characters (upper 128 characters).
2882
    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
2883
    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
2884
    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
2885
    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
2886
    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
2887
    0, 0, 0};
2888
2889
/**
2890
 * Hexadecimal to binary translation
2891
 *
2892
 * @param pszHex the input hex encoded string.
2893
 * @param pnBytes the returned count of decoded bytes placed here.
2894
 *
2895
 * @return returns binary buffer of data - free with CPLFree().
2896
 */
2897
2898
GByte *CPLHexToBinary(const char *pszHex, int *pnBytes)
2899
0
{
2900
0
    const GByte *pabyHex = reinterpret_cast<const GByte *>(pszHex);
2901
0
    const size_t nHexLen = strlen(pszHex);
2902
2903
0
    GByte *pabyWKB = static_cast<GByte *>(CPLMalloc(nHexLen / 2 + 2));
2904
2905
0
    for (size_t i = 0; i < nHexLen / 2; ++i)
2906
0
    {
2907
0
        const unsigned char h1 = hex2char[pabyHex[2 * i]];
2908
0
        const unsigned char h2 = hex2char[pabyHex[2 * i + 1]];
2909
2910
        // First character is high bits, second is low bits.
2911
0
        pabyWKB[i] = static_cast<GByte>((h1 << 4) | h2);
2912
0
    }
2913
0
    pabyWKB[nHexLen / 2] = 0;
2914
0
    *pnBytes = static_cast<int>(nHexLen / 2);
2915
2916
0
    return pabyWKB;
2917
0
}
2918
2919
/************************************************************************/
2920
/*                          CPLGetValueType()                           */
2921
/************************************************************************/
2922
2923
/**
2924
 * Detect the type of the value contained in a string, whether it is
2925
 * a real, an integer or a string
2926
 * Leading and trailing spaces are skipped in the analysis.
2927
 *
2928
 * Note: in the context of this function, integer must be understood in a
2929
 * broad sense. It does not mean that the value can fit into a 32 bit integer
2930
 * for example. It might be larger.
2931
 *
2932
 * @param pszValue the string to analyze
2933
 *
2934
 * @return returns the type of the value contained in the string.
2935
 */
2936
2937
CPLValueType CPLGetValueType(const char *pszValue)
2938
0
{
2939
    // Doubles : "+25.e+3", "-25.e-3", "25.e3", "25e3", " 25e3 "
2940
    // Not doubles: "25e 3", "25e.3", "-2-5e3", "2-5e3", "25.25.3", "-3d", "d1"
2941
    //              "XXeYYYYYYYYYYYYYYYYYYY" that evaluates to infinity
2942
2943
0
    if (pszValue == nullptr)
2944
0
        return CPL_VALUE_STRING;
2945
2946
0
    const char *pszValueInit = pszValue;
2947
2948
    // Skip leading spaces.
2949
0
    while (isspace(static_cast<unsigned char>(*pszValue)))
2950
0
        ++pszValue;
2951
2952
0
    if (*pszValue == '\0')
2953
0
        return CPL_VALUE_STRING;
2954
2955
    // Skip leading + or -.
2956
0
    if (*pszValue == '+' || *pszValue == '-')
2957
0
        ++pszValue;
2958
2959
0
    constexpr char DIGIT_ZERO = '0';
2960
0
    if (pszValue[0] == DIGIT_ZERO && pszValue[1] != '\0' && pszValue[1] != '.')
2961
0
        return CPL_VALUE_STRING;
2962
2963
0
    bool bFoundDot = false;
2964
0
    bool bFoundExponent = false;
2965
0
    bool bIsLastCharExponent = false;
2966
0
    bool bIsReal = false;
2967
0
    const char *pszAfterExponent = nullptr;
2968
0
    bool bFoundMantissa = false;
2969
2970
0
    for (; *pszValue != '\0'; ++pszValue)
2971
0
    {
2972
0
        if (isdigit(static_cast<unsigned char>(*pszValue)))
2973
0
        {
2974
0
            bIsLastCharExponent = false;
2975
0
            bFoundMantissa = true;
2976
0
        }
2977
0
        else if (isspace(static_cast<unsigned char>(*pszValue)))
2978
0
        {
2979
0
            const char *pszTmp = pszValue;
2980
0
            while (isspace(static_cast<unsigned char>(*pszTmp)))
2981
0
                ++pszTmp;
2982
0
            if (*pszTmp == 0)
2983
0
                break;
2984
0
            else
2985
0
                return CPL_VALUE_STRING;
2986
0
        }
2987
0
        else if (*pszValue == '-' || *pszValue == '+')
2988
0
        {
2989
0
            if (bIsLastCharExponent)
2990
0
            {
2991
                // Do nothing.
2992
0
            }
2993
0
            else
2994
0
            {
2995
0
                return CPL_VALUE_STRING;
2996
0
            }
2997
0
            bIsLastCharExponent = false;
2998
0
        }
2999
0
        else if (*pszValue == '.')
3000
0
        {
3001
0
            bIsReal = true;
3002
0
            if (!bFoundDot && !bIsLastCharExponent)
3003
0
                bFoundDot = true;
3004
0
            else
3005
0
                return CPL_VALUE_STRING;
3006
0
            bIsLastCharExponent = false;
3007
0
        }
3008
0
        else if (*pszValue == 'D' || *pszValue == 'd' || *pszValue == 'E' ||
3009
0
                 *pszValue == 'e')
3010
0
        {
3011
0
            if (!bFoundMantissa)
3012
0
                return CPL_VALUE_STRING;
3013
0
            if (!(pszValue[1] == '+' || pszValue[1] == '-' ||
3014
0
                  isdigit(static_cast<unsigned char>(pszValue[1]))))
3015
0
                return CPL_VALUE_STRING;
3016
3017
0
            bIsReal = true;
3018
0
            if (!bFoundExponent)
3019
0
                bFoundExponent = true;
3020
0
            else
3021
0
                return CPL_VALUE_STRING;
3022
0
            pszAfterExponent = pszValue + 1;
3023
0
            bIsLastCharExponent = true;
3024
0
        }
3025
0
        else
3026
0
        {
3027
0
            return CPL_VALUE_STRING;
3028
0
        }
3029
0
    }
3030
3031
0
    if (bIsReal && pszAfterExponent && strlen(pszAfterExponent) > 3)
3032
0
    {
3033
        // cppcheck-suppress unreadVariable
3034
0
        const double dfVal = CPLAtof(pszValueInit);
3035
0
        if (std::isinf(dfVal))
3036
0
            return CPL_VALUE_STRING;
3037
0
    }
3038
3039
0
    return bIsReal ? CPL_VALUE_REAL : CPL_VALUE_INTEGER;
3040
0
}
3041
3042
/************************************************************************/
3043
/*                             CPLStrlcpy()                             */
3044
/************************************************************************/
3045
3046
/**
3047
 * Copy source string to a destination buffer.
3048
 *
3049
 * This function ensures that the destination buffer is always NUL terminated
3050
 * (provided that its length is at least 1).
3051
 *
3052
 * This function is designed to be a safer, more consistent, and less error
3053
 * prone replacement for strncpy. Its contract is identical to libbsd's strlcpy.
3054
 *
3055
 * Truncation can be detected by testing if the return value of CPLStrlcpy
3056
 * is greater or equal to nDestSize.
3057
3058
\verbatim
3059
char szDest[5] = {};
3060
if( CPLStrlcpy(szDest, "abcde", sizeof(szDest)) >= sizeof(szDest) )
3061
    fprintf(stderr, "truncation occurred !\n");
3062
\endverbatim
3063
3064
 * @param pszDest   destination buffer
3065
 * @param pszSrc    source string. Must be NUL terminated
3066
 * @param nDestSize size of destination buffer (including space for the NUL
3067
 *     terminator character)
3068
 *
3069
 * @return the length of the source string (=strlen(pszSrc))
3070
 *
3071
 */
3072
size_t CPLStrlcpy(char *pszDest, const char *pszSrc, size_t nDestSize)
3073
0
{
3074
0
    if (nDestSize == 0)
3075
0
        return strlen(pszSrc);
3076
3077
0
    char *pszDestIter = pszDest;
3078
0
    const char *pszSrcIter = pszSrc;
3079
3080
0
    --nDestSize;
3081
0
    while (nDestSize != 0 && *pszSrcIter != '\0')
3082
0
    {
3083
0
        *pszDestIter = *pszSrcIter;
3084
0
        ++pszDestIter;
3085
0
        ++pszSrcIter;
3086
0
        --nDestSize;
3087
0
    }
3088
0
    *pszDestIter = '\0';
3089
0
    return pszSrcIter - pszSrc + strlen(pszSrcIter);
3090
0
}
3091
3092
/************************************************************************/
3093
/*                             CPLStrlcat()                             */
3094
/************************************************************************/
3095
3096
/**
3097
 * Appends a source string to a destination buffer.
3098
 *
3099
 * This function ensures that the destination buffer is always NUL terminated
3100
 * (provided that its length is at least 1 and that there is at least one byte
3101
 * free in pszDest, that is to say strlen(pszDest_before) < nDestSize)
3102
 *
3103
 * This function is designed to be a safer, more consistent, and less error
3104
 * prone replacement for strncat. Its contract is identical to libbsd's strlcat.
3105
 *
3106
 * Truncation can be detected by testing if the return value of CPLStrlcat
3107
 * is greater or equal to nDestSize.
3108
3109
\verbatim
3110
char szDest[5] = {};
3111
CPLStrlcpy(szDest, "ab", sizeof(szDest));
3112
if( CPLStrlcat(szDest, "cde", sizeof(szDest)) >= sizeof(szDest) )
3113
    fprintf(stderr, "truncation occurred !\n");
3114
\endverbatim
3115
3116
 * @param pszDest   destination buffer. Must be NUL terminated before
3117
 *         running CPLStrlcat
3118
 * @param pszSrc    source string. Must be NUL terminated
3119
 * @param nDestSize size of destination buffer (including space for the
3120
 *         NUL terminator character)
3121
 *
3122
 * @return the theoretical length of the destination string after concatenation
3123
 *         (=strlen(pszDest_before) + strlen(pszSrc)).
3124
 *         If strlen(pszDest_before) >= nDestSize, then it returns
3125
 *         nDestSize + strlen(pszSrc)
3126
 *
3127
 */
3128
size_t CPLStrlcat(char *pszDest, const char *pszSrc, size_t nDestSize)
3129
0
{
3130
0
    char *pszDestIter = pszDest;
3131
3132
0
    while (nDestSize != 0 && *pszDestIter != '\0')
3133
0
    {
3134
0
        ++pszDestIter;
3135
0
        --nDestSize;
3136
0
    }
3137
3138
0
    return pszDestIter - pszDest + CPLStrlcpy(pszDestIter, pszSrc, nDestSize);
3139
0
}
3140
3141
/************************************************************************/
3142
/*                             CPLStrnlen()                             */
3143
/************************************************************************/
3144
3145
/**
3146
 * Returns the length of a NUL terminated string by reading at most
3147
 * the specified number of bytes.
3148
 *
3149
 * The CPLStrnlen() function returns min(strlen(pszStr), nMaxLen).
3150
 * Only the first nMaxLen bytes of the string will be read. Useful to
3151
 * test if a string contains at least nMaxLen characters without reading
3152
 * the full string up to the NUL terminating character.
3153
 *
3154
 * @param pszStr    a NUL terminated string
3155
 * @param nMaxLen   maximum number of bytes to read in pszStr
3156
 *
3157
 * @return strlen(pszStr) if the length is lesser than nMaxLen, otherwise
3158
 * nMaxLen if the NUL character has not been found in the first nMaxLen bytes.
3159
 *
3160
 */
3161
3162
size_t CPLStrnlen(const char *pszStr, size_t nMaxLen)
3163
0
{
3164
0
    size_t nLen = 0;
3165
0
    while (nLen < nMaxLen && *pszStr != '\0')
3166
0
    {
3167
0
        ++nLen;
3168
0
        ++pszStr;
3169
0
    }
3170
0
    return nLen;
3171
0
}
3172
3173
/************************************************************************/
3174
/*                        CSLParseCommandLine()                         */
3175
/************************************************************************/
3176
3177
/**
3178
 * Tokenize command line arguments in a list of strings.
3179
 *
3180
 * @param pszCommandLine  command line
3181
 *
3182
 * @return NULL terminated list of strings to free with CSLDestroy()
3183
 *
3184
 */
3185
char **CSLParseCommandLine(const char *pszCommandLine)
3186
0
{
3187
0
    return CSLTokenizeString(pszCommandLine);
3188
0
}
3189
3190
/************************************************************************/
3191
/*                             CPLToupper()                             */
3192
/************************************************************************/
3193
3194
/** Converts a (ASCII) lowercase character to uppercase.
3195
 *
3196
 * Same as standard toupper(), except that it is not locale sensitive.
3197
 *
3198
 * @since GDAL 3.9
3199
 */
3200
int CPLToupper(int c)
3201
97.5k
{
3202
97.5k
    return (c >= 'a' && c <= 'z') ? (c - 'a' + 'A') : c;
3203
97.5k
}
3204
3205
/************************************************************************/
3206
/*                             CPLTolower()                             */
3207
/************************************************************************/
3208
3209
/** Converts a (ASCII) uppercase character to lowercase.
3210
 *
3211
 * Same as standard tolower(), except that it is not locale sensitive.
3212
 *
3213
 * @since GDAL 3.9
3214
 */
3215
int CPLTolower(int c)
3216
0
{
3217
0
    return (c >= 'A' && c <= 'Z') ? (c - 'A' + 'a') : c;
3218
0
}
3219
3220
/************************************************************************/
3221
/*                        CPLRemoveSQLComments()                        */
3222
/************************************************************************/
3223
3224
/** Remove SQL comments from a string
3225
 *
3226
 * @param osInput Input string.
3227
 * @since GDAL 3.11
3228
 */
3229
std::string CPLRemoveSQLComments(const std::string &osInput)
3230
0
{
3231
0
    const CPLStringList aosLines(
3232
0
        CSLTokenizeStringComplex(osInput.c_str(), "\r\n", FALSE, FALSE));
3233
0
    std::string osSQL;
3234
0
    for (const char *pszLine : aosLines)
3235
0
    {
3236
0
        char chQuote = 0;
3237
0
        int i = 0;
3238
0
        for (; pszLine[i] != '\0'; ++i)
3239
0
        {
3240
0
            if (chQuote)
3241
0
            {
3242
0
                if (pszLine[i] == chQuote)
3243
0
                {
3244
                    // Deal with escaped quote character which is repeated,
3245
                    // so 'foo''bar' or "foo""bar"
3246
0
                    if (pszLine[i + 1] == chQuote)
3247
0
                    {
3248
0
                        i++;
3249
0
                    }
3250
0
                    else
3251
0
                    {
3252
0
                        chQuote = 0;
3253
0
                    }
3254
0
                }
3255
0
            }
3256
0
            else if (pszLine[i] == '\'' || pszLine[i] == '"')
3257
0
            {
3258
0
                chQuote = pszLine[i];
3259
0
            }
3260
0
            else if (pszLine[i] == '-' && pszLine[i + 1] == '-')
3261
0
            {
3262
0
                break;
3263
0
            }
3264
0
        }
3265
0
        if (i > 0)
3266
0
        {
3267
0
            if (!osSQL.empty())
3268
0
                osSQL += ' ';
3269
0
            osSQL.append(pszLine, i);
3270
0
        }
3271
0
    }
3272
0
    return osSQL;
3273
0
}
3274
3275
namespace cpl
3276
{
3277
3278
static bool CaseInsensitiveCompare(unsigned char c1, unsigned char c2)
3279
0
{
3280
0
    return toupper(c1) == toupper(c2);
3281
0
}
3282
3283
/** Check whether the start of one string is equivalent to another string,
3284
 *  considering case.
3285
 *
3286
 * @param str string to test
3287
 * @param prefix expected prefix
3288
 * @return true if the string starts with the prefix
3289
 *
3290
 * @since GDAL 3.11
3291
 */
3292
bool starts_with(std::string_view str, std::string_view prefix)
3293
5.36k
{
3294
5.36k
    return str.size() >= prefix.size() &&
3295
0
           str.compare(0, prefix.size(), prefix) == 0;
3296
5.36k
}
3297
3298
/** Check whether the start of one string is equivalent to another string,
3299
 *  not considering case.
3300
 *
3301
 * @param str string to test
3302
 * @param prefix expected prefix
3303
 * @return true if the string starts with the prefix
3304
 *
3305
 * @since GDAL 3.14
3306
 */
3307
bool starts_with_ci(std::string_view str, std::string_view prefix)
3308
0
{
3309
0
    return str.size() >= prefix.size() &&
3310
0
           std::search(str.begin(), str.end(), prefix.begin(), prefix.end(),
3311
0
                       CaseInsensitiveCompare) != str.end();
3312
0
}
3313
3314
/** Check whether the end of one string is equivalent to another string,
3315
 *  considering case.
3316
 *
3317
 * @param str string to test
3318
 * @param suffix expected suffix
3319
 * @return true if the string ends with the suffix
3320
 *
3321
 * @since GDAL 3.11
3322
 */
3323
bool ends_with(std::string_view str, std::string_view suffix)
3324
0
{
3325
0
    return str.size() >= suffix.size() &&
3326
0
           (suffix.empty() || str.compare(str.size() - suffix.size(),
3327
0
                                          suffix.size(), suffix) == 0);
3328
0
}
3329
3330
/** Check whether the end of one string is equivalent to another string,
3331
 *  not considering case.
3332
 *
3333
 * @param str string to test
3334
 * @param suffix expected suffix
3335
 * @return true if the string ends with the suffix
3336
 *
3337
 * @since GDAL 3.14
3338
 */
3339
bool ends_with_ci(std::string_view str, std::string_view suffix)
3340
0
{
3341
0
    return str.size() >= suffix.size() &&
3342
0
           (suffix.empty() ||
3343
0
            std::search(str.end() - suffix.size(), str.end(), suffix.begin(),
3344
0
                        suffix.end(), CaseInsensitiveCompare) != str.end());
3345
0
}
3346
3347
/** Check whether two strings are equal, considering case.
3348
 *
3349
 * @param str1 first string to test
3350
 * @param str2 second string to test
3351
 * @return true if the strings are considered equal
3352
 *
3353
 * @since GDAL 3.14
3354
 */
3355
bool equals(std::string_view str1, std::string_view str2)
3356
0
{
3357
0
    return str1 == str2;
3358
0
}
3359
3360
/** Check whether two strings are equal, not considering case.
3361
 *
3362
 * @param str1 first string to test
3363
 * @param str2 second string to test
3364
 * @return true if the strings are considered equal
3365
 *
3366
 * @since GDAL 3.14
3367
 */
3368
bool equals_ci(std::string_view str1, std::string_view str2)
3369
0
{
3370
0
    return str1.size() == str2.size() &&
3371
0
           std::equal(str1.begin(), str1.end(), str2.begin(),
3372
0
                      CaseInsensitiveCompare);
3373
0
}
3374
3375
/** Remove leading and trailing whitespace from a string.
3376
 *  The returned string view will be a reference into the input.
3377
 *
3378
 * @param str string to trim
3379
 * @return trimmed string
3380
 *
3381
 * @since GDAL 3.14
3382
 */
3383
std::string_view trim(std::string_view str)
3384
0
{
3385
0
    if (str.empty())
3386
0
    {
3387
0
        return str;
3388
0
    }
3389
3390
0
    size_t start = 0;
3391
0
    while (start < str.size() &&
3392
0
           isspace(static_cast<unsigned char>(str[start])))
3393
0
    {
3394
0
        start++;
3395
0
    }
3396
3397
0
    if (start == str.size())
3398
0
    {
3399
0
        return str.substr(start, 0);
3400
0
    }
3401
3402
0
    size_t stop = str.size();
3403
0
    while (stop > start && isspace(static_cast<unsigned char>(str[stop - 1])))
3404
0
    {
3405
0
        stop--;
3406
0
    }
3407
3408
0
    return str.substr(start, stop - start);
3409
0
}
3410
3411
std::string_view trim(const char *pszStr)
3412
0
{
3413
0
    return trim(std::string_view(pszStr));
3414
0
}
3415
3416
/** Remove leading whitespace from a string.
3417
 *  The returned string view will be a reference into the input.
3418
 *
3419
 * @param str string to trim
3420
 * @return trimmed string
3421
 *
3422
 * @since GDAL 3.14
3423
 */
3424
std::string_view ltrim(std::string_view str)
3425
0
{
3426
0
    if (str.empty())
3427
0
    {
3428
0
        return str;
3429
0
    }
3430
3431
0
    size_t start = 0;
3432
0
    while (start < str.size() &&
3433
0
           isspace(static_cast<unsigned char>(str[start])))
3434
0
    {
3435
0
        start++;
3436
0
    }
3437
3438
0
    return str.substr(start);
3439
0
}
3440
3441
std::string_view ltrim(const char *pszStr)
3442
0
{
3443
0
    return ltrim(std::string_view(pszStr));
3444
0
}
3445
3446
/** Remove trailing whitespace from a string.
3447
 *  The returned string view will be a reference into the input.
3448
 *
3449
 * @param str string to trim
3450
 * @return trimmed string
3451
 *
3452
 * @since GDAL 3.14
3453
 */
3454
std::string_view rtrim(std::string_view str)
3455
0
{
3456
0
    if (str.empty())
3457
0
    {
3458
0
        return str;
3459
0
    }
3460
3461
0
    size_t stop = str.size();
3462
0
    while (stop > 0 && isspace(static_cast<unsigned char>(str[stop - 1])))
3463
0
    {
3464
0
        stop--;
3465
0
    }
3466
3467
0
    return str.substr(0, stop);
3468
0
}
3469
3470
std::string_view rtrim(const char *pszStr)
3471
0
{
3472
0
    return rtrim(std::string_view(pszStr));
3473
0
}
3474
3475
}  // namespace cpl