summaryrefslogtreecommitdiff
path: root/package/source/zippackage/ZipPackageFolder.cxx
blob: 8026ffc5cbf91f98eee5f60134565dc0ba8fa3a0 (plain)
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
/* -*- 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 <string.h>

#include <ZipPackageFolder.hxx>
#include <ZipFile.hxx>
#include <ZipOutputStream.hxx>
#include <ZipPackageStream.hxx>
#include <PackageConstants.hxx>
#include "ZipPackageFolderEnumeration.hxx"
#include <com/sun/star/packages/zip/ZipConstants.hpp>
#include <com/sun/star/embed/StorageFormats.hpp>
#include <cppuhelper/supportsservice.hxx>
#include <cppuhelper/typeprovider.hxx>
#include <osl/diagnose.h>
#include <sal/log.hxx>
#include <rtl/digest.h>
#include "ContentInfo.hxx"
#include <com/sun/star/beans/PropertyValue.hpp>
#include <EncryptedDataHeader.hxx>
#include <rtl/instance.hxx>

#include <o3tl/make_unique.hxx>

using namespace com::sun::star;
using namespace com::sun::star::packages::zip::ZipConstants;
using namespace com::sun::star::packages::zip;
using namespace com::sun::star::packages;
using namespace com::sun::star::container;
using namespace com::sun::star::beans;
using namespace com::sun::star::lang;
using namespace com::sun::star::io;
using namespace cppu;

#if OSL_DEBUG_LEVEL > 0
#define THROW_WHERE SAL_WHERE
#else
#define THROW_WHERE ""
#endif

namespace { struct lcl_CachedImplId : public rtl::Static< cppu::OImplementationId, lcl_CachedImplId > {}; }

ZipPackageFolder::ZipPackageFolder( const css::uno::Reference < css::uno::XComponentContext >& xContext,
                                    sal_Int32 nFormat,
                                    bool bAllowRemoveOnInsert )
{
    m_xContext = xContext;
    m_nFormat = nFormat;
    mbAllowRemoveOnInsert = bAllowRemoveOnInsert;
    SetFolder ( true );
    aEntry.nVersion     = -1;
    aEntry.nFlag        = 0;
    aEntry.nMethod      = STORED;
    aEntry.nTime        = -1;
    aEntry.nCrc         = 0;
    aEntry.nCompressedSize = 0;
    aEntry.nSize        = 0;
    aEntry.nOffset      = -1;
}

ZipPackageFolder::~ZipPackageFolder()
{
}

bool ZipPackageFolder::LookForUnexpectedODF12Streams( const OUString& aPath )
{
    bool bHasUnexpected = false;

    for ( ContentHash::const_iterator aCI = maContents.begin(), aEnd = maContents.end();
          !bHasUnexpected && aCI != aEnd;
          ++aCI)
    {
        const OUString &rShortName = (*aCI).first;
        const ZipContentInfo &rInfo = *(*aCI).second;

        if ( rInfo.bFolder )
        {
            if ( aPath == "META-INF/" )
            {
                // META-INF is not allowed to contain subfolders
                bHasUnexpected = true;
            }
            else
            {
                OUString sOwnPath = aPath + rShortName + "/";
                bHasUnexpected = rInfo.pFolder->LookForUnexpectedODF12Streams( sOwnPath );
            }
        }
        else
        {
            if ( aPath == "META-INF/" )
            {
                if ( rShortName != "manifest.xml"
                  && rShortName.indexOf( "signatures" ) == -1 )
                {
                    // a stream from META-INF with unexpected name
                    bHasUnexpected = true;
                }

                // streams from META-INF with expected names are allowed not to be registered in manifest.xml
            }
            else if ( !rInfo.pStream->IsFromManifest() )
            {
                // the stream is not in META-INF and is not registered in manifest.xml,
                // check whether it is an internal part of the package format
                if ( !aPath.isEmpty() || rShortName != "mimetype" )
                {
                    // if it is not "mimetype" from the root it is not a part of the package
                    bHasUnexpected = true;
                }
            }
        }
    }

    return bHasUnexpected;
}

void ZipPackageFolder::setChildStreamsTypeByExtension( const beans::StringPair& aPair )
{
    OUString aExt;
    if ( aPair.First.toChar() == '.' )
        aExt = aPair.First;
    else
        aExt = "." + aPair.First;

    for ( ContentHash::const_iterator aCI = maContents.begin(), aEnd = maContents.end();
          aCI != aEnd;
          ++aCI)
    {
        const OUString &rShortName = (*aCI).first;
        const ZipContentInfo &rInfo = *(*aCI).second;

        if ( rInfo.bFolder )
            rInfo.pFolder->setChildStreamsTypeByExtension( aPair );
        else
        {
            sal_Int32 nPathLength = rShortName.getLength();
            sal_Int32 nExtLength = aExt.getLength();
            if ( nPathLength >= nExtLength && rShortName.match( aExt, nPathLength - nExtLength ) )
                rInfo.pStream->SetMediaType( aPair.Second );
        }
    }
}

css::uno::Sequence < sal_Int8 > ZipPackageFolder::static_getImplementationId()
{
    return lcl_CachedImplId::get().getImplementationId();
}

    // XNameContainer
void SAL_CALL ZipPackageFolder::insertByName( const OUString& aName, const uno::Any& aElement )
{
    if (hasByName(aName))
        throw ElementExistException(THROW_WHERE );

    uno::Reference < XUnoTunnel > xRef;
    aElement >>= xRef;
    if ( !(aElement >>= xRef) )
        throw IllegalArgumentException(THROW_WHERE, uno::Reference< uno::XInterface >(), 0 );

    sal_Int64 nTest;
    ZipPackageEntry *pEntry;
    if ( ( nTest = xRef->getSomething ( ZipPackageFolder::static_getImplementationId() ) ) != 0 )
    {
        ZipPackageFolder *pFolder = reinterpret_cast < ZipPackageFolder * > ( nTest );
        pEntry = static_cast < ZipPackageEntry * > ( pFolder );
    }
    else if ( ( nTest = xRef->getSomething ( ZipPackageStream::static_getImplementationId() ) ) != 0 )
    {
        ZipPackageStream *pStream = reinterpret_cast < ZipPackageStream * > ( nTest );
        pEntry = static_cast < ZipPackageEntry * > ( pStream );
    }
    else
       throw IllegalArgumentException(THROW_WHERE, uno::Reference< uno::XInterface >(), 0 );

    if (pEntry->getName() != aName )
        pEntry->setName (aName);
    doInsertByName ( pEntry, true );
}

void SAL_CALL ZipPackageFolder::removeByName( const OUString& Name )
{
    ContentHash::iterator aIter = maContents.find ( Name );
    if ( aIter == maContents.end() )
        throw NoSuchElementException(THROW_WHERE );
    maContents.erase( aIter );
}
    // XEnumerationAccess
uno::Reference< XEnumeration > SAL_CALL ZipPackageFolder::createEnumeration(  )
{
    return uno::Reference < XEnumeration> (new ZipPackageFolderEnumeration(maContents));
}
    // XElementAccess
uno::Type SAL_CALL ZipPackageFolder::getElementType(  )
{
    return cppu::UnoType<XUnoTunnel>::get();
}
sal_Bool SAL_CALL ZipPackageFolder::hasElements(  )
{
    return !maContents.empty();
}
    // XNameAccess
ZipContentInfo& ZipPackageFolder::doGetByName( const OUString& aName )
{
    ContentHash::iterator aIter = maContents.find ( aName );
    if ( aIter == maContents.end())
        throw NoSuchElementException(THROW_WHERE );
    return *aIter->second;
}

uno::Any SAL_CALL ZipPackageFolder::getByName( const OUString& aName )
{
    return uno::makeAny ( doGetByName ( aName ).xTunnel );
}
uno::Sequence< OUString > SAL_CALL ZipPackageFolder::getElementNames(  )
{
    sal_uInt32 i=0, nSize = maContents.size();
    uno::Sequence < OUString > aSequence ( nSize );
    for ( ContentHash::const_iterator aIterator = maContents.begin(), aEnd = maContents.end();
          aIterator != aEnd;
          ++i, ++aIterator)
        aSequence[i] = (*aIterator).first;
    return aSequence;
}
sal_Bool SAL_CALL ZipPackageFolder::hasByName( const OUString& aName )
{
    return maContents.find ( aName ) != maContents.end ();
}
    // XNameReplace
void SAL_CALL ZipPackageFolder::replaceByName( const OUString& aName, const uno::Any& aElement )
{
    if ( !hasByName( aName ) )
        throw NoSuchElementException(THROW_WHERE );

    removeByName( aName );
    insertByName(aName, aElement);
}

bool ZipPackageFolder::saveChild(
        const OUString &rPath,
        std::vector < uno::Sequence < PropertyValue > > &rManList,
        ZipOutputStream & rZipOut,
        const uno::Sequence < sal_Int8 >& rEncryptionKey,
        sal_Int32 nPBKDF2IterationCount,
        const rtlRandomPool &rRandomPool)
{
    const OUString sMediaTypeProperty ("MediaType");
    const OUString sVersionProperty ("Version");
    const OUString sFullPathProperty ("FullPath");

    uno::Sequence < PropertyValue > aPropSet (PKG_SIZE_NOENCR_MNFST);
    OUString sTempName = rPath + "/";

    if ( !GetMediaType().isEmpty() )
    {
        aPropSet[PKG_MNFST_MEDIATYPE].Name = sMediaTypeProperty;
        aPropSet[PKG_MNFST_MEDIATYPE].Value <<= GetMediaType();
        aPropSet[PKG_MNFST_VERSION].Name = sVersionProperty;
        aPropSet[PKG_MNFST_VERSION].Value <<= GetVersion();
        aPropSet[PKG_MNFST_FULLPATH].Name = sFullPathProperty;
        aPropSet[PKG_MNFST_FULLPATH].Value <<= sTempName;
    }
    else
        aPropSet.realloc( 0 );

    saveContents( sTempName, rManList, rZipOut, rEncryptionKey, nPBKDF2IterationCount, rRandomPool);

    // folder can have a mediatype only in package format
    if ( aPropSet.getLength() && ( m_nFormat == embed::StorageFormats::PACKAGE ) )
        rManList.push_back( aPropSet );

    return true;
}

void ZipPackageFolder::saveContents(
        const OUString &rPath,
        std::vector < uno::Sequence < PropertyValue > > &rManList,
        ZipOutputStream & rZipOut,
        const uno::Sequence < sal_Int8 >& rEncryptionKey,
        sal_Int32 nPBKDF2IterationCount,
        const rtlRandomPool &rRandomPool ) const
{
    bool bWritingFailed = false;

    if ( maContents.empty() && !rPath.isEmpty() && m_nFormat != embed::StorageFormats::OFOPXML )
    {
        // it is an empty subfolder, use workaround to store it
        ZipEntry* pTempEntry = new ZipEntry(aEntry);
        pTempEntry->nPathLen = static_cast<sal_Int16>( OUStringToOString( rPath, RTL_TEXTENCODING_UTF8 ).getLength() );
        pTempEntry->nExtraLen = -1;
        pTempEntry->sPath = rPath;

        try
        {
            ZipOutputStream::setEntry(pTempEntry);
            rZipOut.writeLOC(pTempEntry);
            rZipOut.rawCloseEntry();
        }
        catch ( ZipException& )
        {
            bWritingFailed = true;
        }
        catch ( IOException& )
        {
            bWritingFailed = true;
        }
    }

    bool bMimeTypeStreamStored = false;
    OUString aMimeTypeStreamName("mimetype");
    if ( m_nFormat == embed::StorageFormats::ZIP && rPath.isEmpty() )
    {
        // let the "mimetype" stream in root folder be stored as the first stream if it is zip format
        ContentHash::const_iterator aIter = maContents.find ( aMimeTypeStreamName );
        if ( aIter != maContents.end() && !(*aIter).second->bFolder )
        {
            bMimeTypeStreamStored = true;
            bWritingFailed = !aIter->second->pStream->saveChild(
                rPath + aIter->first, rManList, rZipOut, rEncryptionKey, nPBKDF2IterationCount, rRandomPool );
        }
    }

    for ( ContentHash::const_iterator aCI = maContents.begin(), aEnd = maContents.end();
          aCI != aEnd;
          ++aCI)
    {
        const OUString &rShortName = (*aCI).first;
        const ZipContentInfo &rInfo = *(*aCI).second;

        if ( !bMimeTypeStreamStored || rShortName != aMimeTypeStreamName )
        {
            if (rInfo.bFolder)
            {
                bWritingFailed = !rInfo.pFolder->saveChild(
                    rPath + rShortName, rManList, rZipOut, rEncryptionKey, nPBKDF2IterationCount, rRandomPool );
            }
            else
            {
                bWritingFailed = !rInfo.pStream->saveChild(
                    rPath + rShortName, rManList, rZipOut, rEncryptionKey, nPBKDF2IterationCount, rRandomPool );
            }
        }
    }

    if( bWritingFailed )
        throw uno::RuntimeException(THROW_WHERE );
}

sal_Int64 SAL_CALL ZipPackageFolder::getSomething( const uno::Sequence< sal_Int8 >& aIdentifier )
{
    sal_Int64 nMe = 0;
    if ( aIdentifier.getLength() == 16 &&
         0 == memcmp(static_getImplementationId().getConstArray(),  aIdentifier.getConstArray(), 16 ) )
        nMe = reinterpret_cast < sal_Int64 > ( this );
    return nMe;
}
void SAL_CALL ZipPackageFolder::setPropertyValue( const OUString& aPropertyName, const uno::Any& aValue )
{
    if ( aPropertyName == "MediaType" )
    {
        // TODO/LATER: activate when zip ucp is ready
        // if ( m_nFormat != embed::StorageFormats::PACKAGE )
        //  throw UnknownPropertyException(THROW_WHERE );

        aValue >>= msMediaType;
    }
    else if ( aPropertyName == "Version" )
        aValue >>= m_sVersion;
    else if ( aPropertyName == "Size" )
        aValue >>= aEntry.nSize;
    else
        throw UnknownPropertyException(THROW_WHERE );
}
uno::Any SAL_CALL ZipPackageFolder::getPropertyValue( const OUString& PropertyName )
{
    if ( PropertyName == "MediaType" )
    {
        // TODO/LATER: activate when zip ucp is ready
        // if ( m_nFormat != embed::StorageFormats::PACKAGE )
        //  throw UnknownPropertyException(THROW_WHERE );

        return uno::makeAny ( msMediaType );
    }
    else if ( PropertyName == "Version" )
        return uno::makeAny( m_sVersion );
    else if ( PropertyName == "Size" )
        return uno::makeAny ( aEntry.nSize );
    else
        throw UnknownPropertyException(THROW_WHERE );
}

void ZipPackageFolder::doInsertByName ( ZipPackageEntry *pEntry, bool bSetParent )
{
    if ( pEntry->IsFolder() )
        maContents[pEntry->getName()] = o3tl::make_unique<ZipContentInfo>(static_cast<ZipPackageFolder*>(pEntry));
    else
        maContents[pEntry->getName()] = o3tl::make_unique<ZipContentInfo>(static_cast<ZipPackageStream*>(pEntry));
    if ( bSetParent )
        pEntry->setParent ( *this );
}

OUString ZipPackageFolder::getImplementationName()
{
    return OUString("ZipPackageFolder");
}

uno::Sequence< OUString > ZipPackageFolder::getSupportedServiceNames()
{
    uno::Sequence< OUString > aNames { "com.sun.star.packages.PackageFolder" };
    return aNames;
}

sal_Bool SAL_CALL ZipPackageFolder::supportsService( OUString const & rServiceName )
{
    return cppu::supportsService(this, rServiceName);
}

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