File: cpl_vsil_stdin.cpp

package info (click to toggle)
gdal 3.6.2%2Bdfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 89,664 kB
  • sloc: cpp: 1,136,033; ansic: 197,355; python: 35,910; java: 5,511; xml: 4,011; sh: 3,950; cs: 2,443; yacc: 1,047; makefile: 288
file content (670 lines) | stat: -rw-r--r-- 21,389 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
/**********************************************************************
 *
 * Project:  CPL - Common Portability Library
 * Purpose:  Implement VSI large file api for stdin
 * Author:   Even Rouault, <even dot rouault at spatialys.com>
 *
 **********************************************************************
 * Copyright (c) 2010-2012, Even Rouault <even dot rouault at spatialys.com>
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included
 * in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
 * DEALINGS IN THE SOFTWARE.
 ****************************************************************************/

//! @cond Doxygen_Suppress

#include "cpl_port.h"
#include "cpl_vsi.h"

#include <cstddef>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#if HAVE_FCNTL_H
#include <fcntl.h>
#endif
#if HAVE_SYS_STAT_H
#include <sys/stat.h>
#endif

#include <algorithm>
#include <limits>

#include "cpl_conv.h"
#include "cpl_error.h"
#include "cpl_vsi_virtual.h"

#ifdef WIN32
#include <io.h>
#include <fcntl.h>
#endif

static std::string gosStdinFilename{};
static FILE *gStdinFile = stdin;
static GByte *gpabyBuffer = nullptr;
static size_t gnBufferLimit = 0;  // maximum that can be allocated
static size_t gnBufferAlloc = 0;  // current allocation
static size_t gnBufferLen = 0;    // number of valid bytes in gpabyBuffer
static uint64_t gnRealPos = 0;    // current offset on stdin
static bool gbHasSoughtToEnd = false;
static uint64_t gnFileSize = 0;

/************************************************************************/
/*                           VSIStdinInit()                             */
/************************************************************************/

static void VSIStdinInit()
{
    if (gpabyBuffer == nullptr)
    {
#ifdef WIN32
        setmode(fileno(stdin), O_BINARY);
#endif
        constexpr size_t MAX_INITIAL_ALLOC = 1024 * 1024;
        gnBufferAlloc = std::min(gnBufferAlloc, MAX_INITIAL_ALLOC);
        gpabyBuffer = static_cast<GByte *>(CPLMalloc(gnBufferAlloc));
    }
}

/************************************************************************/
/* ==================================================================== */
/*                       VSIStdinFilesystemHandler                     */
/* ==================================================================== */
/************************************************************************/

class VSIStdinFilesystemHandler final : public VSIFilesystemHandler
{
    CPL_DISALLOW_COPY_ASSIGN(VSIStdinFilesystemHandler)

  public:
    VSIStdinFilesystemHandler();
    ~VSIStdinFilesystemHandler() override;

    VSIVirtualHandle *Open(const char *pszFilename, const char *pszAccess,
                           bool bSetError,
                           CSLConstList /* papszOptions */) override;
    int Stat(const char *pszFilename, VSIStatBufL *pStatBuf,
             int nFlags) override;
    bool SupportsSequentialWrite(const char * /* pszPath */,
                                 bool /* bAllowLocalTempFile */) override
    {
        return false;
    }
    bool SupportsRandomWrite(const char * /* pszPath */,
                             bool /* bAllowLocalTempFile */) override
    {
        return false;
    }
};

/************************************************************************/
/* ==================================================================== */
/*                        VSIStdinHandle                               */
/* ==================================================================== */
/************************************************************************/

class VSIStdinHandle final : public VSIVirtualHandle
{
  private:
    CPL_DISALLOW_COPY_ASSIGN(VSIStdinHandle)

    bool m_bEOF = false;
    uint64_t m_nCurOff = 0;
    size_t ReadAndCache(void *pBuffer, size_t nToRead);

  public:
    VSIStdinHandle() = default;
    ~VSIStdinHandle() override
    {
        VSIStdinHandle::Close();
    }

    int Seek(vsi_l_offset nOffset, int nWhence) override;
    vsi_l_offset Tell() override;
    size_t Read(void *pBuffer, size_t nSize, size_t nMemb) override;
    size_t Write(const void *pBuffer, size_t nSize, size_t nMemb) override;
    int Eof() override;
    int Close() override;
};

/************************************************************************/
/*                              ReadAndCache()                          */
/************************************************************************/

size_t VSIStdinHandle::ReadAndCache(void *pUserBuffer, size_t nToRead)
{
    CPLAssert(m_nCurOff == gnRealPos);

    const size_t nRead = fread(pUserBuffer, 1, nToRead, gStdinFile);

    if (gnRealPos < gnBufferLimit)
    {
        bool bCopyInBuffer = true;
        const size_t nToCopy = static_cast<size_t>(
            std::min(gnBufferLimit - gnRealPos, static_cast<uint64_t>(nRead)));
        if (gnRealPos + nToCopy > gnBufferAlloc)
        {
            auto newAlloc = gnRealPos + nToCopy;
            if (newAlloc < gnBufferLimit - newAlloc / 3)
                newAlloc += newAlloc / 3;
            else
                newAlloc = gnBufferLimit;
            GByte *newBuffer = static_cast<GByte *>(VSI_REALLOC_VERBOSE(
                gpabyBuffer, static_cast<size_t>(newAlloc)));
            if (newBuffer == nullptr)
            {
                bCopyInBuffer = false;
            }
            else
            {
                gpabyBuffer = newBuffer;
                gnBufferAlloc = static_cast<size_t>(newAlloc);
            }
        }
        if (bCopyInBuffer)
        {
            memcpy(gpabyBuffer + static_cast<size_t>(gnRealPos), pUserBuffer,
                   nToCopy);
            gnBufferLen += nToCopy;
        }
    }

    m_nCurOff += nRead;
    gnRealPos = m_nCurOff;

    if (nRead < nToRead)
    {
        gnFileSize = gnRealPos;
        gbHasSoughtToEnd = true;
    }

    return nRead;
}

/************************************************************************/
/*                                Seek()                                */
/************************************************************************/

int VSIStdinHandle::Seek(vsi_l_offset nOffset, int nWhence)

{
    m_bEOF = false;

    if (nWhence == SEEK_SET && nOffset == m_nCurOff)
        return 0;

    VSIStdinInit();

    if (nWhence == SEEK_END)
    {
        if (nOffset != 0)
        {
            CPLError(CE_Failure, CPLE_NotSupported,
                     "Seek(xx != 0, SEEK_END) unsupported on /vsistdin");
            return -1;
        }

        if (gbHasSoughtToEnd)
        {
            m_nCurOff = gnFileSize;
            return 0;
        }

        nOffset = static_cast<vsi_l_offset>(-1);
    }
    else if (nWhence == SEEK_CUR)
    {
        nOffset += m_nCurOff;
    }

    if (nWhence != SEEK_END && gnRealPos >= gnBufferLimit &&
        nOffset >= gnBufferLimit)
    {
        CPLError(CE_Failure, CPLE_NotSupported,
                 "Backward Seek() unsupported on /vsistdin beyond "
                 "maximum buffer limit (" CPL_FRMT_GUIB " bytes).\n"
                 "This limit can be extended by setting the "
                 "CPL_VSISTDIN_BUFFER_LIMIT "
                 "configuration option to a number of bytes, or by using the "
                 "'/vsistdin?buffer_limit=number_of_bytes' filename.\n"
                 "A limit of -1 means unlimited.",
                 static_cast<GUIntBig>(gnBufferLimit));
        return -1;
    }

    if (nOffset < gnBufferLen)
    {
        m_nCurOff = nOffset;
        return 0;
    }

    if (nOffset == m_nCurOff)
        return 0;

    CPLDebug("VSI", "Forward seek from " CPL_FRMT_GUIB " to " CPL_FRMT_GUIB,
             static_cast<GUIntBig>(m_nCurOff), nOffset);

    char abyTemp[8192] = {};
    m_nCurOff = gnRealPos;
    while (true)
    {
        const size_t nToRead = static_cast<size_t>(
            std::min(static_cast<uint64_t>(sizeof(abyTemp)),
                     static_cast<uint64_t>(nOffset - m_nCurOff)));
        const size_t nRead = ReadAndCache(abyTemp, nToRead);

        if (nRead < nToRead)
        {
            return nWhence == SEEK_END ? 0 : -1;
        }
        if (nToRead < sizeof(abyTemp))
            break;
    }

    return 0;
}

/************************************************************************/
/*                                Tell()                                */
/************************************************************************/

vsi_l_offset VSIStdinHandle::Tell()
{
    return m_nCurOff;
}

/************************************************************************/
/*                                Read()                                */
/************************************************************************/

size_t VSIStdinHandle::Read(void *pBuffer, size_t nSize, size_t nCount)

{
    VSIStdinInit();

    const size_t nBytesToRead = nSize * nCount;
    if (nBytesToRead == 0)
        return 0;

    if (m_nCurOff < gnRealPos && gnRealPos >= gnBufferLimit &&
        m_nCurOff + nBytesToRead > gnBufferLimit)
    {
        CPLError(CE_Failure, CPLE_NotSupported,
                 "Backward Seek() unsupported on /vsistdin beyond "
                 "maximum buffer limit (" CPL_FRMT_GUIB " bytes).\n"
                 "This limit can be extended by setting the "
                 "CPL_VSISTDIN_BUFFER_LIMIT "
                 "configuration option to a number of bytes, or by using the "
                 "'/vsistdin?buffer_limit=number_of_bytes' filename.\n"
                 "A limit of -1 means unlimited.",
                 static_cast<GUIntBig>(gnBufferLimit));
        return 0;
    }

    if (m_nCurOff < gnBufferLen)
    {
        const size_t nAlreadyCached =
            static_cast<size_t>(gnBufferLen - m_nCurOff);
        if (nBytesToRead <= nAlreadyCached)
        {
            memcpy(pBuffer, gpabyBuffer + static_cast<size_t>(m_nCurOff),
                   nBytesToRead);
            m_nCurOff += nBytesToRead;
            return nCount;
        }

        memcpy(pBuffer, gpabyBuffer + static_cast<size_t>(m_nCurOff),
               nAlreadyCached);
        m_nCurOff += nAlreadyCached;

        const size_t nRead =
            ReadAndCache(static_cast<GByte *>(pBuffer) + nAlreadyCached,
                         nBytesToRead - nAlreadyCached);
        m_bEOF = nRead < nBytesToRead - nAlreadyCached;

        return (nRead + nAlreadyCached) / nSize;
    }

    const size_t nRead = ReadAndCache(pBuffer, nBytesToRead);
    m_bEOF = nRead < nBytesToRead;
    return nRead / nSize;
}

/************************************************************************/
/*                               Write()                                */
/************************************************************************/

size_t VSIStdinHandle::Write(const void * /* pBuffer */, size_t /* nSize */,
                             size_t /* nCount */)
{
    CPLError(CE_Failure, CPLE_NotSupported, "Write() unsupported on /vsistdin");
    return 0;
}

/************************************************************************/
/*                                Eof()                                 */
/************************************************************************/

int VSIStdinHandle::Eof()

{
    return m_bEOF;
}

/************************************************************************/
/*                               Close()                                */
/************************************************************************/

int VSIStdinHandle::Close()

{
    if (!gosStdinFilename.empty() &&
        CPLTestBool(CPLGetConfigOption("CPL_VSISTDIN_FILE_CLOSE", "NO")))
    {
        if (gStdinFile != stdin)
            fclose(gStdinFile);
        gStdinFile = stdin;
        gosStdinFilename.clear();
        gnRealPos = ftell(stdin);
        gnBufferLen = 0;
        gbHasSoughtToEnd = false;
        gnFileSize = 0;
    }
    return 0;
}

/************************************************************************/
/* ==================================================================== */
/*                       VSIStdinFilesystemHandler                     */
/* ==================================================================== */
/************************************************************************/

/************************************************************************/
/*                        VSIStdinFilesystemHandler()                   */
/************************************************************************/

VSIStdinFilesystemHandler::VSIStdinFilesystemHandler()
{
}

/************************************************************************/
/*                       ~VSIStdinFilesystemHandler()                   */
/************************************************************************/

VSIStdinFilesystemHandler::~VSIStdinFilesystemHandler()
{
    if (gStdinFile != stdin)
        fclose(gStdinFile);
    gStdinFile = stdin;
    CPLFree(gpabyBuffer);
    gpabyBuffer = nullptr;
    gnBufferLimit = 0;
    gnBufferAlloc = 0;
    gnBufferLen = 0;
    gnRealPos = 0;
    gosStdinFilename.clear();
}

/************************************************************************/
/*                           GetBufferLimit()                           */
/************************************************************************/

static size_t GetBufferLimit(const char *pszBufferLimit)
{
    uint64_t nVal =
        static_cast<uint64_t>(std::strtoull(pszBufferLimit, nullptr, 10));

    // -1 because on 64-bit builds with size_t==uint64_t, a static analyzer
    // could complain that the ending nVal > MAX_BUFFER_LIMIT test is always
    // false
    constexpr size_t MAX_BUFFER_LIMIT = std::numeric_limits<size_t>::max() - 1;
    if (strstr(pszBufferLimit, "MB") != nullptr)
    {
        constexpr size_t ONE_MB = 1024 * 1024;
        if (nVal > MAX_BUFFER_LIMIT / ONE_MB)
        {
            nVal = MAX_BUFFER_LIMIT;
        }
        else
        {
            nVal *= ONE_MB;
        }
    }
    else if (strstr(pszBufferLimit, "GB") != nullptr)
    {
        constexpr size_t ONE_GB = 1024 * 1024 * 1024;
        if (nVal > MAX_BUFFER_LIMIT / ONE_GB)
        {
            nVal = MAX_BUFFER_LIMIT;
        }
        else
        {
            nVal *= ONE_GB;
        }
    }
    if (nVal > MAX_BUFFER_LIMIT)
    {
        nVal = MAX_BUFFER_LIMIT;
    }
    return static_cast<size_t>(nVal);
}

/************************************************************************/
/*                           ParseFilename()                            */
/************************************************************************/

static bool ParseFilename(const char *pszFilename)
{
    if (!(EQUAL(pszFilename, "/vsistdin/") ||
          ((STARTS_WITH(pszFilename, "/vsistdin/?") ||
            STARTS_WITH(pszFilename, "/vsistdin?")) &&
           strchr(pszFilename, '.') == nullptr)))
    {
        return false;
    }

    if (!CPLTestBool(CPLGetConfigOption("CPL_ALLOW_VSISTDIN", "YES")))
    {
        CPLError(CE_Failure, CPLE_NotSupported,
                 "/vsistdin/ disabled. Set CPL_ALLOW_VSISTDIN to YES to "
                 "enable it");
        return false;
    }

    const char *pszBufferLimit =
        CPLGetConfigOption("CPL_VSISTDIN_BUFFER_LIMIT", "1048576");
    size_t nBufferLimit = GetBufferLimit(pszBufferLimit);

    pszFilename += strlen("/vsistdin/");
    if (*pszFilename == '?')
        pszFilename++;
    char **papszTokens = CSLTokenizeString2(pszFilename, "&", 0);
    for (int i = 0; papszTokens[i] != nullptr; i++)
    {
        char *pszUnescaped =
            CPLUnescapeString(papszTokens[i], nullptr, CPLES_URL);
        CPLFree(papszTokens[i]);
        papszTokens[i] = pszUnescaped;
    }

    for (int i = 0; papszTokens[i]; i++)
    {
        char *pszKey = nullptr;
        const char *pszValue = CPLParseNameValue(papszTokens[i], &pszKey);
        if (pszKey && pszValue)
        {
            if (EQUAL(pszKey, "buffer_limit"))
            {
                nBufferLimit = GetBufferLimit(pszValue);
            }
            else
            {
                CPLError(CE_Warning, CPLE_NotSupported,
                         "Unsupported option: %s", pszKey);
            }
        }
        CPLFree(pszKey);
    }

    CSLDestroy(papszTokens);

    // For testing purposes
    const char *pszStdinFilename =
        CPLGetConfigOption("CPL_VSISTDIN_FILE", "stdin");
    if (EQUAL(pszStdinFilename, "stdin"))
    {
        if (!gosStdinFilename.empty())
        {
            if (gStdinFile != stdin)
                fclose(gStdinFile);
            gStdinFile = stdin;
            gosStdinFilename.clear();
            gnRealPos = ftell(stdin);
            gnBufferLen = 0;
            gbHasSoughtToEnd = false;
            gnFileSize = 0;
        }
    }
    else
    {
        bool bReset = false;
        if (gosStdinFilename != pszStdinFilename)
        {
            if (gStdinFile != stdin)
                fclose(gStdinFile);
            gStdinFile = fopen(pszStdinFilename, "rb");
            if (gStdinFile == nullptr)
            {
                gStdinFile = stdin;
                return false;
            }
            gosStdinFilename = pszStdinFilename;
            bReset = true;
        }
        else
        {
            bReset = CPLTestBool(
                CPLGetConfigOption("CPL_VSISTDIN_RESET_POSITION", "NO"));
        }
        if (bReset)
        {
            gnBufferLimit = 0;
            gnBufferLen = 0;
            gnRealPos = 0;
            gbHasSoughtToEnd = false;
            gnFileSize = 0;
        }
    }

    gnBufferLimit = std::max(gnBufferLimit, nBufferLimit);

    return true;
}

/************************************************************************/
/*                                Open()                                */
/************************************************************************/

VSIVirtualHandle *
VSIStdinFilesystemHandler::Open(const char *pszFilename, const char *pszAccess,
                                bool /* bSetError */,
                                CSLConstList /* papszOptions */)

{
    if (!ParseFilename(pszFilename))
    {
        return nullptr;
    }

    if (strchr(pszAccess, 'w') != nullptr || strchr(pszAccess, '+') != nullptr)
    {
        CPLError(CE_Failure, CPLE_NotSupported,
                 "Write or update mode not supported on /vsistdin");
        return nullptr;
    }

    return new VSIStdinHandle();
}

/************************************************************************/
/*                                Stat()                                */
/************************************************************************/

int VSIStdinFilesystemHandler::Stat(const char *pszFilename,
                                    VSIStatBufL *pStatBuf, int nFlags)

{
    memset(pStatBuf, 0, sizeof(VSIStatBufL));

    if (!ParseFilename(pszFilename))
    {
        return -1;
    }

    if (nFlags & VSI_STAT_SIZE_FLAG)
    {
        if (gbHasSoughtToEnd)
            pStatBuf->st_size = gnFileSize;
        else
        {
            auto handle = Open(pszFilename, "rb", false, nullptr);
            if (handle == nullptr)
                return -1;
            handle->Seek(0, SEEK_END);
            pStatBuf->st_size = handle->Tell();
            delete handle;
        }
    }

    pStatBuf->st_mode = S_IFREG;
    return 0;
}

//! @endcond

/************************************************************************/
/*                       VSIInstallStdinHandler()                       */
/************************************************************************/

/*!
 \brief Install /vsistdin/ file system handler

 A special file handler is installed that allows reading from the standard
 input stream.

 The file operations available are of course limited to Read() and
 forward Seek() (full seek in the first MB of a file by default).

 Starting with GDAL 3.6, this limit can be configured either by setting
 the CPL_VSISTDIN_BUFFER_LIMIT configuration option to a number of bytes
 (can be -1 for unlimited), or using the "/vsistdin?buffer_limit=value"
 filename.

 \verbatim embed:rst
 See :ref:`/vsistdin/ documentation <vsistdin>`
 \endverbatim

 @since GDAL 1.8.0
 */
void VSIInstallStdinHandler()

{
    auto poHandler = new VSIStdinFilesystemHandler;
    VSIFileManager::InstallHandler("/vsistdin/", poHandler);
    VSIFileManager::InstallHandler("/vsistdin?", poHandler);
}