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
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
 * This file is part of the LibreOffice project.
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 *
 * This file incorporates work covered by the following license notice:
 *
 *   Licensed to the Apache Software Foundation (ASF) under one or more
 *   contributor license agreements. See the NOTICE file distributed
 *   with this work for additional information regarding copyright
 *   ownership. The ASF licenses this file to you under the Apache
 *   License, Version 2.0 (the "License"); you may not use this file
 *   except in compliance with the License. You may obtain a copy of
 *   the License at http://www.apache.org/licenses/LICENSE-2.0 .
 */

#include <algorithm>
#include <stdio.h>
#include <string.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <errno.h>
#include <unistd.h>
#include <limits.h>

#include <tools/stream.hxx>
#include <vector>

#include <osl/mutex.hxx>
#include <osl/thread.h>
#include <sal/log.hxx>

// class FileBase
#include <osl/file.hxx>
#include <osl/detail/file.h>
#include <rtl/instance.hxx>
#include <rtl/strbuf.hxx>

using namespace osl;

// InternalLock ----------------------------------------------------------------

namespace {

struct LockMutex : public rtl::Static< osl::Mutex, LockMutex > {};

struct InternalStreamLock
{
    sal_uInt64         m_nStartPos;
    sal_uInt64         m_nEndPos;
    SvFileStream*      m_pStream;
    osl::DirectoryItem m_aItem;

    InternalStreamLock( sal_uInt64, sal_uInt64, SvFileStream* );
    ~InternalStreamLock();
};

struct LockList : public rtl::Static< std::vector<InternalStreamLock>, LockList > {};

InternalStreamLock::InternalStreamLock(
    sal_uInt64 const nStart,
    sal_uInt64 const nEnd,
    SvFileStream* pStream ) :
        m_nStartPos( nStart ),
        m_nEndPos( nEnd ),
        m_pStream( pStream )
{
    osl::DirectoryItem::get( m_pStream->GetFileName(), m_aItem );
#if OSL_DEBUG_LEVEL > 1
    OString aFileName(OUStringToOString(m_pStream->GetFileName(),
                                                  osl_getThreadTextEncoding()));
    fprintf( stderr, "locked %s", aFileName.getStr() );
    if( m_nStartPos || m_nEndPos )
        fprintf(stderr, " [ %ld ... %ld ]", m_nStartPos, m_nEndPos );
    fprintf( stderr, "\n" );
#endif
}

InternalStreamLock::~InternalStreamLock()
{
#if OSL_DEBUG_LEVEL > 1
    OString aFileName(OUStringToOString(m_pStream->GetFileName(),
                                                  osl_getThreadTextEncoding()));
    fprintf( stderr, "unlocked %s", aFileName.getStr() );
    if( m_nStartPos || m_nEndPos )
        fprintf(stderr, " [ %ld ... %ld ]", m_nStartPos, m_nEndPos );
    fprintf( stderr, "\n" );
#endif
}

bool lockFile( sal_uInt64 const nStart, sal_uInt64 const nEnd, SvFileStream* pStream )
{
    osl::DirectoryItem aItem;
    if (osl::DirectoryItem::get( pStream->GetFileName(), aItem) != osl::FileBase::E_None )
    {
        SAL_INFO("tools.stream", "Failed to lookup stream for locking");
        return true;
    }

    osl::FileStatus aStatus( osl_FileStatus_Mask_Type );
    if ( aItem.getFileStatus( aStatus ) != osl::FileBase::E_None )
    {
        SAL_INFO("tools.stream", "Failed to stat stream for locking");
        return true;
    }
    if( aStatus.getFileType() == osl::FileStatus::Directory )
        return true;

    osl::MutexGuard aGuard( LockMutex::get() );
    std::vector<InternalStreamLock> &rLockList = LockList::get();
    for( const auto& rLock : rLockList )
    {
        if( aItem.isIdenticalTo( rLock.m_aItem ) )
        {
            StreamMode nLockMode = rLock.m_pStream->GetStreamMode();
            StreamMode nNewMode = pStream->GetStreamMode();
            bool bDenyByOptions = (nLockMode & StreamMode::SHARE_DENYALL) ||
                ( (nLockMode & StreamMode::SHARE_DENYWRITE) && (nNewMode & StreamMode::WRITE) ) ||
                ( (nLockMode & StreamMode::SHARE_DENYREAD) && (nNewMode & StreamMode::READ) );

            if( bDenyByOptions )
            {
                if( rLock.m_nStartPos == 0 && rLock.m_nEndPos == 0 ) // whole file is already locked
                    return false;
                if( nStart == 0 && nEnd == 0) // cannot lock whole file
                    return false;

                if( ( nStart < rLock.m_nStartPos && nEnd > rLock.m_nStartPos ) ||
                    ( nStart < rLock.m_nEndPos && nEnd > rLock.m_nEndPos ) )
                    return false;
            }
        }
    }
    rLockList.push_back( InternalStreamLock( nStart, nEnd, pStream ) );
    return true;
}

void unlockFile( sal_uInt64 const nStart, sal_uInt64 const nEnd, SvFileStream const * pStream )
{
    osl::MutexGuard aGuard( LockMutex::get() );
    std::vector<InternalStreamLock> &rLockList = LockList::get();
    rLockList.erase(std::remove_if(rLockList.begin(), rLockList.end(),
        [&pStream, &nStart, &nEnd](const InternalStreamLock& rLock) {
            return rLock.m_pStream == pStream
                && ((nStart == 0 && nEnd == 0)
                    || (rLock.m_nStartPos == nStart && rLock.m_nEndPos == nEnd));
        }), rLockList.end());
}

}

// StreamData ------------------------------------------------------------------

class StreamData
{
public:
    oslFileHandle rHandle;

    StreamData() : rHandle( nullptr ) { }
};

static ErrCode GetSvError( int nErrno )
{
    static struct { int nErr; ErrCode sv; } const errArr[] =
    {
        { 0,            ERRCODE_NONE },
        { EACCES,       SVSTREAM_ACCESS_DENIED },
        { EBADF,        SVSTREAM_INVALID_HANDLE },
#if defined(NETBSD) || \
    defined(FREEBSD) || defined(MACOSX) || defined(OPENBSD) || \
    defined(__FreeBSD_kernel__) || defined (AIX) || defined(DRAGONFLY) || \
    defined(IOS) || defined(HAIKU)
        { EDEADLK,      SVSTREAM_LOCKING_VIOLATION },
#else
        { EDEADLOCK,    SVSTREAM_LOCKING_VIOLATION },
#endif
        { EINVAL,       SVSTREAM_INVALID_PARAMETER },
        { EMFILE,       SVSTREAM_TOO_MANY_OPEN_FILES },
        { ENFILE,       SVSTREAM_TOO_MANY_OPEN_FILES },
        { ENOENT,       SVSTREAM_FILE_NOT_FOUND },
        { EPERM,        SVSTREAM_ACCESS_DENIED },
        { EROFS,        SVSTREAM_ACCESS_DENIED },
        { EAGAIN,       SVSTREAM_LOCKING_VIOLATION },
        { EISDIR,       SVSTREAM_PATH_NOT_FOUND },
        { ELOOP,        SVSTREAM_PATH_NOT_FOUND },
#if !defined(NETBSD) && !defined (FREEBSD) && \
    !defined(MACOSX) && !defined(OPENBSD) && !defined(__FreeBSD_kernel__) && \
    !defined(DRAGONFLY)
        { EMULTIHOP,    SVSTREAM_PATH_NOT_FOUND },
        { ENOLINK,      SVSTREAM_PATH_NOT_FOUND },
#endif
        { ENOTDIR,      SVSTREAM_PATH_NOT_FOUND },
        { ETXTBSY,      SVSTREAM_ACCESS_DENIED  },
        { EEXIST,       SVSTREAM_CANNOT_MAKE    },
        { ENOSPC,       SVSTREAM_DISK_FULL      },
        { int(0xFFFF),  SVSTREAM_GENERALERROR }
    };

    ErrCode nRetVal = SVSTREAM_GENERALERROR; // default error
    int i=0;
    do
    {
        if ( errArr[i].nErr == nErrno )
        {
            nRetVal = errArr[i].sv;
            break;
        }
        ++i;
    }
    while( errArr[i].nErr != 0xFFFF );
    return nRetVal;
}

static ErrCode GetSvError( oslFileError nErrno )
{
    static struct { oslFileError nErr; ErrCode sv; } const errArr[] =
    {
        { osl_File_E_None,        ERRCODE_NONE },
        { osl_File_E_ACCES,       SVSTREAM_ACCESS_DENIED },
        { osl_File_E_BADF,        SVSTREAM_INVALID_HANDLE },
        { osl_File_E_DEADLK,      SVSTREAM_LOCKING_VIOLATION },
        { osl_File_E_INVAL,       SVSTREAM_INVALID_PARAMETER },
        { osl_File_E_MFILE,       SVSTREAM_TOO_MANY_OPEN_FILES },
        { osl_File_E_NFILE,       SVSTREAM_TOO_MANY_OPEN_FILES },
        { osl_File_E_NOENT,       SVSTREAM_FILE_NOT_FOUND },
        { osl_File_E_PERM,        SVSTREAM_ACCESS_DENIED },
        { osl_File_E_ROFS,        SVSTREAM_ACCESS_DENIED },
        { osl_File_E_AGAIN,       SVSTREAM_LOCKING_VIOLATION },
        { osl_File_E_ISDIR,       SVSTREAM_PATH_NOT_FOUND },
        { osl_File_E_LOOP,        SVSTREAM_PATH_NOT_FOUND },
        { osl_File_E_MULTIHOP,    SVSTREAM_PATH_NOT_FOUND },
        { osl_File_E_NOLINK,      SVSTREAM_PATH_NOT_FOUND },
        { osl_File_E_NOTDIR,      SVSTREAM_PATH_NOT_FOUND },
        { osl_File_E_EXIST,       SVSTREAM_CANNOT_MAKE    },
        { osl_File_E_NOSPC,       SVSTREAM_DISK_FULL      },
        { oslFileError(0xFFFF),   SVSTREAM_GENERALERROR }
    };

    ErrCode nRetVal = SVSTREAM_GENERALERROR; // default error
    int i=0;
    do
    {
        if ( errArr[i].nErr == nErrno )
        {
            nRetVal = errArr[i].sv;
            break;
        }
        ++i;
    }
    while( errArr[i].nErr != oslFileError(0xFFFF) );
    return nRetVal;
}

SvFileStream::SvFileStream( const OUString& rFileName, StreamMode nOpenMode )
{
    bIsOpen             = false;
    m_isWritable        = false;
    pInstanceData.reset(new StreamData);

    SetBufferSize( 1024 );
    // convert URL to SystemPath, if necessary
    OUString aSystemFileName;
    if( FileBase::getSystemPathFromFileURL( rFileName , aSystemFileName )
        != FileBase::E_None )
    {
        aSystemFileName = rFileName;
    }
    Open( aSystemFileName, nOpenMode );
}

SvFileStream::SvFileStream()
{
    bIsOpen             = false;
    m_isWritable        = false;
    pInstanceData.reset(new StreamData);
    SetBufferSize( 1024 );
}

SvFileStream::~SvFileStream()
{
    Close();
}

std::size_t SvFileStream::GetData( void* pData, std::size_t nSize )
{
    SAL_INFO("tools", OString::number(static_cast<sal_Int64>(nSize)) << " Bytes from " << aFilename);

    sal_uInt64 nRead = 0;
    if ( IsOpen() )
    {
        oslFileError rc = osl_readFile(pInstanceData->rHandle,pData,static_cast<sal_uInt64>(nSize),&nRead);
        if ( rc != osl_File_E_None )
        {
            SetError( ::GetSvError( rc ));
            return -1;
        }
    }
    return static_cast<std::size_t>(nRead);
}

std::size_t SvFileStream::PutData( const void* pData, std::size_t nSize )
{
    SAL_INFO("tools", OString::number(static_cast<sal_Int64>(nSize)) << " Bytes to " << aFilename);

    sal_uInt64 nWrite = 0;
    if ( IsOpen() )
    {
        oslFileError rc = osl_writeFile(pInstanceData->rHandle,pData,static_cast<sal_uInt64>(nSize),&nWrite);
        if ( rc != osl_File_E_None )
        {
            SetError( ::GetSvError( rc ) );
            return -1;
        }
        else if( !nWrite )
            SetError( SVSTREAM_DISK_FULL );
    }
    return static_cast<std::size_t>(nWrite);
}

sal_uInt64 SvFileStream::SeekPos(sal_uInt64 const nPos)
{
    // check if a truncated STREAM_SEEK_TO_END was passed
    assert(nPos != sal_uInt64(sal_uInt32(STREAM_SEEK_TO_END)));
    if ( IsOpen() )
    {
        oslFileError rc;
        sal_uInt64 nNewPos;
        if ( nPos != STREAM_SEEK_TO_END )
            rc = osl_setFilePos( pInstanceData->rHandle, osl_Pos_Absolut, nPos );
        else
            rc = osl_setFilePos( pInstanceData->rHandle, osl_Pos_End, 0 );

        if ( rc != osl_File_E_None )
        {
            SetError( SVSTREAM_SEEK_ERROR );
            return 0L;
        }
        if ( nPos != STREAM_SEEK_TO_END )
            return nPos;
        rc = osl_getFilePos( pInstanceData->rHandle, &nNewPos );<--- Variable 'rc' is assigned a value that is never used.
        return nNewPos;
    }
    SetError( SVSTREAM_GENERALERROR );
    return 0L;
}

void SvFileStream::FlushData()
{
    // does not exist locally
}

bool SvFileStream::LockRange(sal_uInt64 const nByteOffset, std::size_t nBytes)
{
    int nLockMode = 0;

    if ( ! IsOpen() )
        return false;

    if (m_eStreamMode & StreamMode::SHARE_DENYALL)
    {
        if (m_isWritable)
            nLockMode = F_WRLCK;
        else
            nLockMode = F_RDLCK;
    }

    if (m_eStreamMode & StreamMode::SHARE_DENYREAD)
    {
        if (m_isWritable)
            nLockMode = F_WRLCK;
        else
        {
            SetError(SVSTREAM_LOCKING_VIOLATION);
            return false;
        }
    }

    if (m_eStreamMode & StreamMode::SHARE_DENYWRITE)
    {
        if (m_isWritable)
            nLockMode = F_WRLCK;
        else
            nLockMode = F_RDLCK;
    }

    if (!nLockMode)
        return true;

    if( !lockFile( nByteOffset, nByteOffset+nBytes, this ) )
    {
#if OSL_DEBUG_LEVEL > 1
        fprintf( stderr, "InternalLock on %s [ %ld ... %ld ] failed\n",
                 OUStringToOString(aFilename, osl_getThreadTextEncoding()).getStr(), nByteOffset, nByteOffset+nBytes );
#endif
        return false;
    }

    return true;
}

bool SvFileStream::UnlockRange(sal_uInt64 const nByteOffset, std::size_t nBytes)
{
    if ( ! IsOpen() )
        return false;

    unlockFile( nByteOffset, nByteOffset+nBytes, this );

    return true;
}

bool SvFileStream::LockFile()
{
  return LockRange( 0UL, 0UL );
}

void SvFileStream::UnlockFile()
{
    UnlockRange( 0UL, 0UL );
}

void SvFileStream::Open( const OUString& rFilename, StreamMode nOpenMode )
{
    sal_uInt32 uFlags;
    oslFileHandle nHandleTmp;

    Close();
    errno = 0;
    m_eStreamMode = nOpenMode;
    m_eStreamMode &= ~StreamMode::TRUNC; // don't truncate on reopen

    aFilename = rFilename;

    SAL_INFO("tools", aFilename);

    OUString aFileURL;
    osl::DirectoryItem aItem;
    osl::FileStatus aStatus( osl_FileStatus_Mask_Type | osl_FileStatus_Mask_LinkTargetURL );

    // FIXME: we really need to switch to a pure URL model ...
    if ( osl::File::getFileURLFromSystemPath( aFilename, aFileURL ) != osl::FileBase::E_None )
        aFileURL = aFilename;
    bool bStatValid = ( osl::DirectoryItem::get( aFileURL, aItem) == osl::FileBase::E_None &&
                        aItem.getFileStatus( aStatus ) == osl::FileBase::E_None );

    // SvFileStream can't open a directory
    if( bStatValid && aStatus.getFileType() == osl::FileStatus::Directory )
    {
        SetError( ::GetSvError( EISDIR ) );
        return;
    }

    if ( !( nOpenMode & StreamMode::WRITE ) )
        uFlags = osl_File_OpenFlag_Read;
    else if ( !( nOpenMode & StreamMode::READ ) )
        uFlags = osl_File_OpenFlag_Write;
    else
        uFlags = osl_File_OpenFlag_Read | osl_File_OpenFlag_Write;

    // Fix (MDA, 18.01.95): Don't open with O_CREAT upon RD_ONLY
    // Important for Read-Only-Filesystems (e.g,  CDROM)
    if ( (!( nOpenMode & StreamMode::NOCREATE )) && ( uFlags != osl_File_OpenFlag_Read ) )
        uFlags |= osl_File_OpenFlag_Create;
    if ( nOpenMode & StreamMode::TRUNC )
        uFlags |= osl_File_OpenFlag_Trunc;

    uFlags |= osl_File_OpenFlag_NoExcl | osl_File_OpenFlag_NoLock;

    if ( nOpenMode & StreamMode::WRITE)
    {
        if ( nOpenMode & StreamMode::COPY_ON_SYMLINK )
        {
            if ( bStatValid && aStatus.getFileType() == osl::FileStatus::Link &&
                 aStatus.getLinkTargetURL().getLength() > 0 )
            {
                // delete the symbolic link, and replace it with the contents of the link
                if (osl::File::remove( aFileURL ) == osl::FileBase::E_None )
                {
                    File::copy( aStatus.getLinkTargetURL(), aFileURL );
#if OSL_DEBUG_LEVEL > 0
                    fprintf( stderr,
                             "Removing link and replacing with file contents (%s) -> (%s).\n",
                             OUStringToOString( aStatus.getLinkTargetURL(),
                                                     RTL_TEXTENCODING_UTF8).getStr(),
                             OUStringToOString( aFileURL,
                                                     RTL_TEXTENCODING_UTF8).getStr() );
#endif
                }
            }
        }
    }

    oslFileError rc = osl_openFile( aFileURL.pData, &nHandleTmp, uFlags );
    if ( rc != osl_File_E_None )
    {
        if ( uFlags & osl_File_OpenFlag_Write )
        {
            // Change to read-only
            uFlags &= ~osl_File_OpenFlag_Write;
            rc = osl_openFile( aFileURL.pData, &nHandleTmp, uFlags );
        }
    }
    if ( rc == osl_File_E_None )
    {
        pInstanceData->rHandle = nHandleTmp;
        bIsOpen = true;
        if ( uFlags & osl_File_OpenFlag_Write )
            m_isWritable = true;

        if ( !LockFile() ) // whole file
        {
            rc = osl_closeFile( nHandleTmp );<--- Variable 'rc' is assigned a value that is never used.
            bIsOpen = false;
            m_isWritable = false;
            pInstanceData->rHandle = nullptr;
        }
    }
    else
        SetError( ::GetSvError( rc ) );
}

void SvFileStream::Close()
{
    UnlockFile();

    if ( IsOpen() )
    {
        SAL_INFO("tools", "Closing " << aFilename);
        Flush();
        osl_closeFile( pInstanceData->rHandle );
        pInstanceData->rHandle = nullptr;
    }

    bIsOpen     = false;
    m_isWritable = false;
    SvStream::ClearBuffer();
    SvStream::ClearError();
}

/// set filepointer to beginning of file
void SvFileStream::ResetError()
{
    SvStream::ClearError();
}

void SvFileStream::SetSize (sal_uInt64 const nSize)
{
    if (IsOpen())
    {
        oslFileError rc = osl_setFileSize( pInstanceData->rHandle, nSize );
        if (rc != osl_File_E_None )
        {
            SetError ( ::GetSvError( rc ));
        }
    }
}

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */