summaryrefslogtreecommitdiffstats
path: root/package/source
diff options
context:
space:
mode:
authorDaniel Baumann <daniel.baumann@progress-linux.org>2024-04-07 09:06:44 +0000
committerDaniel Baumann <daniel.baumann@progress-linux.org>2024-04-07 09:06:44 +0000
commited5640d8b587fbcfed7dd7967f3de04b37a76f26 (patch)
tree7a5f7c6c9d02226d7471cb3cc8fbbf631b415303 /package/source
parentInitial commit. (diff)
downloadlibreoffice-ed5640d8b587fbcfed7dd7967f3de04b37a76f26.tar.xz
libreoffice-ed5640d8b587fbcfed7dd7967f3de04b37a76f26.zip
Adding upstream version 4:7.4.7.upstream/4%7.4.7upstream
Signed-off-by: Daniel Baumann <daniel.baumann@progress-linux.org>
Diffstat (limited to 'package/source')
-rw-r--r--package/source/manifest/ManifestDefines.hxx95
-rw-r--r--package/source/manifest/ManifestExport.cxx489
-rw-r--r--package/source/manifest/ManifestExport.hxx38
-rw-r--r--package/source/manifest/ManifestImport.cxx550
-rw-r--r--package/source/manifest/ManifestImport.hxx102
-rw-r--r--package/source/manifest/ManifestReader.cxx105
-rw-r--r--package/source/manifest/ManifestReader.hxx54
-rw-r--r--package/source/manifest/ManifestWriter.cxx92
-rw-r--r--package/source/manifest/ManifestWriter.hxx54
-rw-r--r--package/source/xstor/disposelistener.cxx46
-rw-r--r--package/source/xstor/disposelistener.hxx44
-rw-r--r--package/source/xstor/ocompinstream.cxx602
-rw-r--r--package/source/xstor/ocompinstream.hxx109
-rw-r--r--package/source/xstor/ohierarchyholder.cxx327
-rw-r--r--package/source/xstor/ohierarchyholder.hxx115
-rw-r--r--package/source/xstor/oseekinstream.cxx144
-rw-r--r--package/source/xstor/oseekinstream.hxx60
-rw-r--r--package/source/xstor/owriteablestream.cxx3276
-rw-r--r--package/source/xstor/owriteablestream.hxx359
-rw-r--r--package/source/xstor/selfterminatefilestream.cxx105
-rw-r--r--package/source/xstor/selfterminatefilestream.hxx64
-rw-r--r--package/source/xstor/switchpersistencestream.cxx409
-rw-r--r--package/source/xstor/switchpersistencestream.hxx107
-rw-r--r--package/source/xstor/xfactory.cxx293
-rw-r--r--package/source/xstor/xfactory.hxx55
-rw-r--r--package/source/xstor/xstor.component27
-rw-r--r--package/source/xstor/xstorage.cxx5503
-rw-r--r--package/source/xstor/xstorage.hxx538
-rw-r--r--package/source/zipapi/ByteChucker.cxx51
-rw-r--r--package/source/zipapi/ByteGrabber.cxx125
-rw-r--r--package/source/zipapi/CRC32.cxx72
-rw-r--r--package/source/zipapi/Deflater.cxx148
-rw-r--r--package/source/zipapi/Inflater.cxx137
-rw-r--r--package/source/zipapi/MemoryByteGrabber.hxx88
-rw-r--r--package/source/zipapi/ThreadedDeflater.cxx220
-rw-r--r--package/source/zipapi/XBufferedThreadedStream.cxx189
-rw-r--r--package/source/zipapi/XBufferedThreadedStream.hxx83
-rw-r--r--package/source/zipapi/XUnbufferedStream.cxx323
-rw-r--r--package/source/zipapi/XUnbufferedStream.hxx93
-rw-r--r--package/source/zipapi/ZipEnumeration.cxx39
-rw-r--r--package/source/zipapi/ZipFile.cxx1263
-rw-r--r--package/source/zipapi/ZipOutputEntry.cxx400
-rw-r--r--package/source/zipapi/ZipOutputStream.cxx365
-rw-r--r--package/source/zipapi/blowfishcontext.cxx109
-rw-r--r--package/source/zipapi/blowfishcontext.hxx51
-rw-r--r--package/source/zipapi/sha1context.cxx119
-rw-r--r--package/source/zipapi/sha1context.hxx71
-rw-r--r--package/source/zippackage/ZipPackage.cxx1837
-rw-r--r--package/source/zippackage/ZipPackageBuffer.cxx128
-rw-r--r--package/source/zippackage/ZipPackageEntry.cxx125
-rw-r--r--package/source/zippackage/ZipPackageFolder.cxx424
-rw-r--r--package/source/zippackage/ZipPackageFolderEnumeration.cxx70
-rw-r--r--package/source/zippackage/ZipPackageFolderEnumeration.hxx49
-rw-r--r--package/source/zippackage/ZipPackageSink.cxx37
-rw-r--r--package/source/zippackage/ZipPackageSink.hxx38
-rw-r--r--package/source/zippackage/ZipPackageStream.cxx1315
-rw-r--r--package/source/zippackage/wrapstreamforshare.cxx151
-rw-r--r--package/source/zippackage/wrapstreamforshare.hxx59
-rw-r--r--package/source/zippackage/zipfileaccess.cxx479
59 files changed, 22420 insertions, 0 deletions
diff --git a/package/source/manifest/ManifestDefines.hxx b/package/source/manifest/ManifestDefines.hxx
new file mode 100644
index 000000000..b5006f2d1
--- /dev/null
+++ b/package/source/manifest/ManifestDefines.hxx
@@ -0,0 +1,95 @@
+/* -*- 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 .
+ */
+#pragma once
+
+#include <rtl/ustring.hxx>
+
+inline constexpr OUStringLiteral MANIFEST_NSPREFIX = u"manifest:";
+inline constexpr OUStringLiteral ELEMENT_MANIFEST = u"manifest:manifest";
+inline constexpr OUStringLiteral ATTRIBUTE_XMLNS = u"xmlns:manifest";
+inline constexpr OUStringLiteral ATTRIBUTE_XMLNS_LOEXT = u"xmlns:loext";
+inline constexpr OUStringLiteral MANIFEST_NAMESPACE = u"http://openoffice.org/2001/manifest";
+inline constexpr OUStringLiteral MANIFEST_OASIS_NAMESPACE = u"urn:oasis:names:tc:opendocument:xmlns:manifest:1.0";
+inline constexpr OUStringLiteral MANIFEST_LOEXT_NAMESPACE = u"urn:org:documentfoundation:names:experimental:office:xmlns:loext:1.0";
+inline constexpr OUStringLiteral MANIFEST_DOCTYPE = u"<!DOCTYPE manifest:manifest PUBLIC \"-//OpenOffice.org//DTD Manifest 1.0//EN\" \"Manifest.dtd\">";
+inline constexpr OUStringLiteral ATTRIBUTE_CDATA = u"CDATA";
+
+inline constexpr OUStringLiteral ELEMENT_FILE_ENTRY = u"manifest:file-entry";
+inline constexpr OUStringLiteral ATTRIBUTE_FULL_PATH = u"manifest:full-path";
+inline constexpr OUStringLiteral ATTRIBUTE_VERSION = u"manifest:version";
+inline constexpr OUStringLiteral ATTRIBUTE_MEDIA_TYPE = u"manifest:media-type";
+inline constexpr OUStringLiteral ATTRIBUTE_SIZE = u"manifest:size";
+inline constexpr OUStringLiteral ELEMENT_MANIFEST_KEYINFO = u"loext:keyinfo";
+inline constexpr OUStringLiteral ELEMENT_ENCRYPTED_KEYINFO = u"loext:KeyInfo";
+inline constexpr OUStringLiteral ELEMENT_ENCRYPTEDKEY = u"loext:encrypted-key";
+inline constexpr OUStringLiteral ELEMENT_ENCRYPTIONMETHOD = u"loext:encryption-method";
+inline constexpr OUStringLiteral ELEMENT_PGPDATA = u"loext:PGPData";
+inline constexpr OUStringLiteral ELEMENT_PGPKEYID = u"loext:PGPKeyID";
+inline constexpr OUStringLiteral ELEMENT_PGPKEYPACKET = u"loext:PGPKeyPacket";
+inline constexpr OUStringLiteral ATTRIBUTE_ALGORITHM = u"loext:PGPAlgorithm";
+inline constexpr OUStringLiteral ELEMENT_CIPHERDATA = u"loext:CipherData";
+inline constexpr OUStringLiteral ELEMENT_CIPHERVALUE = u"loext:CipherValue";
+inline constexpr OUStringLiteral ELEMENT_MANIFEST13_KEYINFO = u"manifest:keyinfo";
+inline constexpr OUStringLiteral ELEMENT_ENCRYPTEDKEY13 = u"manifest:encrypted-key";
+inline constexpr OUStringLiteral ELEMENT_ENCRYPTIONMETHOD13 = u"manifest:encryption-method";
+inline constexpr OUStringLiteral ELEMENT_PGPDATA13 = u"manifest:PGPData";
+inline constexpr OUStringLiteral ELEMENT_PGPKEYID13 = u"manifest:PGPKeyID";
+inline constexpr OUStringLiteral ELEMENT_PGPKEYPACKET13 = u"manifest:PGPKeyPacket";
+inline constexpr OUStringLiteral ATTRIBUTE_ALGORITHM13 = u"manifest:PGPAlgorithm";
+inline constexpr OUStringLiteral ELEMENT_CIPHERDATA13 = u"manifest:CipherData";
+inline constexpr OUStringLiteral ELEMENT_CIPHERVALUE13 = u"manifest:CipherValue";
+
+inline constexpr OUStringLiteral ELEMENT_ENCRYPTION_DATA = u"manifest:encryption-data";
+inline constexpr OUStringLiteral ATTRIBUTE_CHECKSUM_TYPE = u"manifest:checksum-type";
+inline constexpr OUStringLiteral ATTRIBUTE_CHECKSUM = u"manifest:checksum";
+
+inline constexpr OUStringLiteral ELEMENT_ALGORITHM = u"manifest:algorithm";
+inline constexpr OUStringLiteral ATTRIBUTE_ALGORITHM_NAME = u"manifest:algorithm-name";
+inline constexpr OUStringLiteral ATTRIBUTE_INITIALISATION_VECTOR = u"manifest:initialisation-vector";
+
+inline constexpr OUStringLiteral ELEMENT_START_KEY_GENERATION = u"manifest:start-key-generation";
+inline constexpr OUStringLiteral ATTRIBUTE_START_KEY_GENERATION_NAME = u"manifest:start-key-generation-name";
+inline constexpr OUStringLiteral ATTRIBUTE_KEY_SIZE = u"manifest:key-size";
+
+inline constexpr OUStringLiteral ELEMENT_KEY_DERIVATION = u"manifest:key-derivation";
+inline constexpr OUStringLiteral ATTRIBUTE_KEY_DERIVATION_NAME = u"manifest:key-derivation-name";
+inline constexpr OUStringLiteral ATTRIBUTE_SALT = u"manifest:salt";
+inline constexpr OUStringLiteral ATTRIBUTE_ITERATION_COUNT = u"manifest:iteration-count";
+
+/// OFFICE-3708: wrong URL cited in ODF 1.2 and used since OOo 3.4 beta
+inline constexpr OUStringLiteral SHA256_URL_ODF12 = u"http://www.w3.org/2000/09/xmldsig#sha256";
+inline constexpr OUStringLiteral SHA256_URL = u"http://www.w3.org/2001/04/xmlenc#sha256";
+inline constexpr OUStringLiteral SHA1_NAME = u"SHA1";
+inline constexpr OUStringLiteral SHA1_URL = u"http://www.w3.org/2000/09/xmldsig#sha1";
+
+inline constexpr OUStringLiteral SHA1_1K_NAME = u"SHA1/1K";
+inline constexpr OUStringLiteral SHA1_1K_URL = u"urn:oasis:names:tc:opendocument:xmlns:manifest:1.0#sha1-1k";
+inline constexpr OUStringLiteral SHA256_1K_URL = u"urn:oasis:names:tc:opendocument:xmlns:manifest:1.0#sha256-1k";
+
+inline constexpr OUStringLiteral BLOWFISH_NAME = u"Blowfish CFB";
+inline constexpr OUStringLiteral BLOWFISH_URL = u"urn:oasis:names:tc:opendocument:xmlns:manifest:1.0#blowfish";
+inline constexpr OUStringLiteral AES128_URL = u"http://www.w3.org/2001/04/xmlenc#aes128-cbc";
+inline constexpr OUStringLiteral AES192_URL = u"http://www.w3.org/2001/04/xmlenc#aes192-cbc";
+inline constexpr OUStringLiteral AES256_URL = u"http://www.w3.org/2001/04/xmlenc#aes256-cbc";
+
+inline constexpr OUStringLiteral PBKDF2_NAME = u"PBKDF2";
+inline constexpr OUStringLiteral PGP_NAME = u"PGP";
+inline constexpr OUStringLiteral PBKDF2_URL = u"urn:oasis:names:tc:opendocument:xmlns:manifest:1.0#pbkdf2";
+
+/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
diff --git a/package/source/manifest/ManifestExport.cxx b/package/source/manifest/ManifestExport.cxx
new file mode 100644
index 000000000..7e7f22a3a
--- /dev/null
+++ b/package/source/manifest/ManifestExport.cxx
@@ -0,0 +1,489 @@
+/* -*- 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 <com/sun/star/xml/sax/XExtendedDocumentHandler.hpp>
+#include <com/sun/star/xml/crypto/DigestID.hpp>
+#include <com/sun/star/xml/crypto/CipherID.hpp>
+#include <com/sun/star/beans/PropertyValue.hpp>
+#include <com/sun/star/beans/NamedValue.hpp>
+#include <com/sun/star/uno/RuntimeException.hpp>
+
+#include "ManifestDefines.hxx"
+#include "ManifestExport.hxx"
+
+#include <osl/diagnose.h>
+#include <rtl/ustrbuf.hxx>
+#include <rtl/ref.hxx>
+#include <sal/log.hxx>
+#include <comphelper/base64.hxx>
+#include <comphelper/documentconstants.hxx>
+#include <comphelper/attributelist.hxx>
+
+using namespace ::com::sun::star;
+
+#if OSL_DEBUG_LEVEL > 0
+#define THROW_WHERE SAL_WHERE
+#else
+#define THROW_WHERE ""
+#endif
+
+ManifestExport::ManifestExport( uno::Reference< xml::sax::XDocumentHandler > const & xHandler, const uno::Sequence< uno::Sequence < beans::PropertyValue > >& rManList )
+{
+ static const OUStringLiteral sKeyInfo ( u"KeyInfo" );
+ static const OUStringLiteral sPgpKeyIDProperty ( u"KeyId" );
+ static const OUStringLiteral sPgpKeyPacketProperty ( u"KeyPacket" );
+ static const OUStringLiteral sCipherValueProperty ( u"CipherValue" );
+ static const OUStringLiteral sFullPathProperty ( u"FullPath" );
+ static const OUStringLiteral sVersionProperty ( u"Version" );
+ static const OUStringLiteral sMediaTypeProperty ( u"MediaType" );
+ static const OUStringLiteral sIterationCountProperty ( u"IterationCount" );
+ static const OUStringLiteral sDerivedKeySizeProperty ( u"DerivedKeySize" );
+ static const OUStringLiteral sSaltProperty ( u"Salt" );
+ static const OUStringLiteral sInitialisationVectorProperty( u"InitialisationVector" );
+ static const OUStringLiteral sSizeProperty ( u"Size" );
+ static const OUStringLiteral sDigestProperty ( u"Digest" );
+ static const OUStringLiteral sEncryptionAlgProperty ( u"EncryptionAlgorithm" );
+ static const OUStringLiteral sStartKeyAlgProperty ( u"StartKeyAlgorithm" );
+ static const OUStringLiteral sDigestAlgProperty ( u"DigestAlgorithm" );
+
+ static const OUStringLiteral sWhiteSpace ( u" " );
+
+ const OUString sSHA256_URL_ODF12 ( SHA256_URL_ODF12 );
+ const OUString sSHA1_Name ( SHA1_NAME );
+
+ const OUString sSHA1_1k_Name ( SHA1_1K_NAME );
+ const OUString sSHA256_1k_URL ( SHA256_1K_URL );
+
+ const OUString sBlowfish_Name ( BLOWFISH_NAME );
+ const OUString sAES256_URL ( AES256_URL );
+
+ const OUString sPBKDF2_Name ( PBKDF2_NAME );
+ const OUString sPGP_Name ( PGP_NAME );
+
+ rtl::Reference<::comphelper::AttributeList> pRootAttrList = new ::comphelper::AttributeList;
+
+ // find the mediatype of the document if any
+ OUString aDocMediaType;
+ OUString aDocVersion;
+ const uno::Sequence<beans::PropertyValue>* pRootFolderPropSeq = nullptr;
+ for (const uno::Sequence < beans::PropertyValue >& rSequence : rManList)
+ {
+ OUString aMediaType;
+ OUString aPath;
+ OUString aVersion;
+
+ for (const beans::PropertyValue& rValue : rSequence)
+ {
+ if (rValue.Name == sMediaTypeProperty )
+ {
+ rValue.Value >>= aMediaType;
+ }
+ else if (rValue.Name == sFullPathProperty )
+ {
+ rValue.Value >>= aPath;
+ }
+ else if (rValue.Name == sVersionProperty )
+ {
+ rValue.Value >>= aVersion;
+ }
+
+ if ( !aPath.isEmpty() && !aMediaType.isEmpty() && !aVersion.isEmpty() )
+ break;
+ }
+
+ if ( aPath == "/" )
+ {
+ aDocMediaType = aMediaType;
+ aDocVersion = aVersion;
+ pRootFolderPropSeq = &rSequence;
+ break;
+ }
+ }
+
+ bool bProvideDTD = false;
+ bool bAcceptNonemptyVersion = false;
+ bool bStoreStartKeyGeneration = false;
+ if ( !aDocMediaType.isEmpty() )
+ {
+ if ( aDocMediaType == MIMETYPE_OASIS_OPENDOCUMENT_TEXT_ASCII
+ || aDocMediaType == MIMETYPE_OASIS_OPENDOCUMENT_TEXT_WEB_ASCII
+ || aDocMediaType == MIMETYPE_OASIS_OPENDOCUMENT_TEXT_GLOBAL_ASCII
+ || aDocMediaType == MIMETYPE_OASIS_OPENDOCUMENT_DRAWING_ASCII
+ || aDocMediaType == MIMETYPE_OASIS_OPENDOCUMENT_PRESENTATION_ASCII
+ || aDocMediaType == MIMETYPE_OASIS_OPENDOCUMENT_SPREADSHEET_ASCII
+ || aDocMediaType == MIMETYPE_OASIS_OPENDOCUMENT_CHART_ASCII
+ || aDocMediaType == MIMETYPE_OASIS_OPENDOCUMENT_DATABASE_ASCII
+ || aDocMediaType == MIMETYPE_OASIS_OPENDOCUMENT_FORMULA_ASCII
+ || aDocMediaType == MIMETYPE_OASIS_OPENDOCUMENT_TEXT_TEMPLATE_ASCII
+ || aDocMediaType == MIMETYPE_OASIS_OPENDOCUMENT_TEXT_GLOBAL_TEMPLATE_ASCII
+ || aDocMediaType == MIMETYPE_OASIS_OPENDOCUMENT_DRAWING_TEMPLATE_ASCII
+ || aDocMediaType == MIMETYPE_OASIS_OPENDOCUMENT_PRESENTATION_TEMPLATE_ASCII
+ || aDocMediaType == MIMETYPE_OASIS_OPENDOCUMENT_SPREADSHEET_TEMPLATE_ASCII
+ || aDocMediaType == MIMETYPE_OASIS_OPENDOCUMENT_CHART_TEMPLATE_ASCII
+ || aDocMediaType == MIMETYPE_OASIS_OPENDOCUMENT_FORMULA_TEMPLATE_ASCII )
+
+ {
+ // oasis format
+ pRootAttrList->AddAttribute ( ATTRIBUTE_XMLNS,
+ ATTRIBUTE_CDATA,
+ MANIFEST_OASIS_NAMESPACE );
+ bAcceptNonemptyVersion = true;
+ if ( aDocVersion.compareTo( ODFVER_012_TEXT ) >= 0 )
+ {
+ // this is ODF12 or later generation, let encrypted
+ // streams contain start-key-generation entry
+ bStoreStartKeyGeneration = true;
+ pRootAttrList->AddAttribute ( ATTRIBUTE_VERSION, ATTRIBUTE_CDATA, aDocVersion );
+ // plus gpg4libre extensions - loext NS for that
+ pRootAttrList->AddAttribute ( ATTRIBUTE_XMLNS_LOEXT,
+ ATTRIBUTE_CDATA,
+ MANIFEST_LOEXT_NAMESPACE );
+ }
+ }
+ else
+ {
+ // even if it is no SO6 format the namespace must be specified
+ // thus SO6 format is used as default one
+ pRootAttrList->AddAttribute ( ATTRIBUTE_XMLNS,
+ ATTRIBUTE_CDATA,
+ MANIFEST_NAMESPACE );
+
+ bProvideDTD = true;
+ }
+ }
+
+ xHandler->startDocument();
+ uno::Reference < xml::sax::XExtendedDocumentHandler > xExtHandler ( xHandler, uno::UNO_QUERY );
+ if ( xExtHandler.is() && bProvideDTD )
+ {
+ xExtHandler->unknown ( MANIFEST_DOCTYPE );
+ xHandler->ignorableWhitespace ( sWhiteSpace );
+ }
+ xHandler->startElement( ELEMENT_MANIFEST, pRootAttrList );
+
+ const uno::Any *pKeyInfoProperty = nullptr;
+ if ( pRootFolderPropSeq )
+ {
+ // do we have package-wide encryption info?
+ for (const beans::PropertyValue& rValue : *pRootFolderPropSeq)
+ {
+ if (rValue.Name == sKeyInfo )
+ pKeyInfoProperty = &rValue.Value;
+ }
+
+ if ( pKeyInfoProperty )
+ {
+ // yeah, so that goes directly below the manifest:manifest
+ // element
+ OUStringBuffer aBuffer;
+
+ xHandler->ignorableWhitespace ( sWhiteSpace );
+
+ // ==== manifest:keyinfo & children
+ bool const isODF13(aDocVersion.compareTo(ODFVER_013_TEXT) >= 0);
+ if (!isODF13)
+ {
+ xHandler->startElement(ELEMENT_MANIFEST_KEYINFO, nullptr);
+ }
+ xHandler->ignorableWhitespace ( sWhiteSpace );
+
+ uno::Sequence< uno::Sequence < beans::NamedValue > > aKeyInfoSequence;
+ *pKeyInfoProperty >>= aKeyInfoSequence;
+ for (const uno::Sequence<beans::NamedValue>& rKeyInfoSequence : std::as_const(aKeyInfoSequence))
+ {
+ uno::Sequence < sal_Int8 > aPgpKeyID;
+ uno::Sequence < sal_Int8 > aPgpKeyPacket;
+ uno::Sequence < sal_Int8 > aCipherValue;
+ for (const beans::NamedValue& rNValue : rKeyInfoSequence)
+ {
+ if (rNValue.Name == sPgpKeyIDProperty )
+ rNValue.Value >>= aPgpKeyID;
+ else if (rNValue.Name == sPgpKeyPacketProperty )
+ rNValue.Value >>= aPgpKeyPacket;
+ else if (rNValue.Name == sCipherValueProperty )
+ rNValue.Value >>= aCipherValue;
+ }
+
+ if (aPgpKeyID.hasElements() && aCipherValue.hasElements() )
+ {
+ // ==== manifest:encrypted-key & children - one for each recipient
+ xHandler->startElement(isODF13 ? OUString(ELEMENT_ENCRYPTEDKEY13) : OUString(ELEMENT_ENCRYPTEDKEY), nullptr);
+ xHandler->ignorableWhitespace ( sWhiteSpace );
+
+ rtl::Reference<::comphelper::AttributeList> pNewAttrList = new ::comphelper::AttributeList;
+ // TODO: the algorithm should rather be configurable
+ pNewAttrList->AddAttribute(
+ isODF13 ? OUString(ATTRIBUTE_ALGORITHM13) : OUString(ATTRIBUTE_ALGORITHM),
+ ATTRIBUTE_CDATA,
+ "http://www.w3.org/2001/04/xmlenc#rsa-oaep-mgf1p" );
+ xHandler->startElement(isODF13 ? OUString(ELEMENT_ENCRYPTIONMETHOD13) : OUString(ELEMENT_ENCRYPTIONMETHOD), pNewAttrList);
+ xHandler->endElement(isODF13 ? OUString(ELEMENT_ENCRYPTIONMETHOD13) : OUString(ELEMENT_ENCRYPTIONMETHOD));
+ xHandler->ignorableWhitespace ( sWhiteSpace );
+
+ // note: the mismatch here corresponds to ODF 1.3 cs01 schema
+ xHandler->startElement(isODF13 ? OUString(ELEMENT_MANIFEST13_KEYINFO) : OUString(ELEMENT_MANIFEST_KEYINFO), nullptr);
+ xHandler->ignorableWhitespace ( sWhiteSpace );
+
+ xHandler->startElement(isODF13 ? OUString(ELEMENT_PGPDATA13) : OUString(ELEMENT_PGPDATA), nullptr);
+ xHandler->ignorableWhitespace ( sWhiteSpace );
+
+ xHandler->startElement(isODF13 ? OUString(ELEMENT_PGPKEYID13) : OUString(ELEMENT_PGPKEYID), nullptr);
+ ::comphelper::Base64::encode(aBuffer, aPgpKeyID);
+ xHandler->characters( aBuffer.makeStringAndClear() );
+ xHandler->endElement(isODF13 ? OUString(ELEMENT_PGPKEYID13) : OUString(ELEMENT_PGPKEYID));
+ xHandler->ignorableWhitespace ( sWhiteSpace );
+
+ // key packet is optional
+ if (aPgpKeyPacket.hasElements())
+ {
+ xHandler->startElement(isODF13 ? OUString(ELEMENT_PGPKEYPACKET13) : OUString(ELEMENT_PGPKEYPACKET), nullptr);
+ ::comphelper::Base64::encode(aBuffer, aPgpKeyPacket);
+ xHandler->characters( aBuffer.makeStringAndClear() );
+ xHandler->endElement(isODF13 ? OUString(ELEMENT_PGPKEYPACKET13) : OUString(ELEMENT_PGPKEYPACKET));
+ xHandler->ignorableWhitespace ( sWhiteSpace );
+ }
+
+ xHandler->endElement(isODF13 ? OUString(ELEMENT_PGPDATA13) : OUString(ELEMENT_PGPDATA));
+ xHandler->ignorableWhitespace ( sWhiteSpace );
+
+ xHandler->endElement(isODF13 ? OUString(ELEMENT_MANIFEST13_KEYINFO) : OUString(ELEMENT_MANIFEST_KEYINFO));
+ xHandler->ignorableWhitespace ( sWhiteSpace );
+
+ xHandler->startElement(isODF13 ? OUString(ELEMENT_CIPHERDATA13) : OUString(ELEMENT_CIPHERDATA), nullptr);
+ xHandler->ignorableWhitespace ( sWhiteSpace );
+
+ xHandler->startElement(isODF13 ? OUString(ELEMENT_CIPHERVALUE13) : OUString(ELEMENT_CIPHERVALUE), nullptr);
+ ::comphelper::Base64::encode(aBuffer, aCipherValue);
+ xHandler->characters( aBuffer.makeStringAndClear() );
+ xHandler->endElement(isODF13 ? OUString(ELEMENT_CIPHERVALUE13) : OUString(ELEMENT_CIPHERVALUE));
+ xHandler->ignorableWhitespace ( sWhiteSpace );
+
+ xHandler->endElement(isODF13 ? OUString(ELEMENT_CIPHERDATA13) : OUString(ELEMENT_CIPHERDATA));
+ xHandler->ignorableWhitespace ( sWhiteSpace );
+
+ xHandler->endElement(isODF13 ? OUString(ELEMENT_ENCRYPTEDKEY13) : OUString(ELEMENT_ENCRYPTEDKEY));
+ xHandler->ignorableWhitespace ( sWhiteSpace );
+ }
+ }
+
+ if (!isODF13)
+ {
+ xHandler->endElement(ELEMENT_MANIFEST_KEYINFO);
+ }
+ xHandler->ignorableWhitespace ( sWhiteSpace );
+ }
+ }
+
+ // now write individual file entries
+ for (const uno::Sequence<beans::PropertyValue>& rSequence : rManList)
+ {
+ rtl::Reference<::comphelper::AttributeList> pAttrList = new ::comphelper::AttributeList;
+ OUString aString;
+ const uno::Any *pVector = nullptr, *pSalt = nullptr, *pIterationCount = nullptr, *pDigest = nullptr, *pDigestAlg = nullptr, *pEncryptAlg = nullptr, *pStartKeyAlg = nullptr, *pDerivedKeySize = nullptr;
+ for (const beans::PropertyValue& rValue : rSequence)
+ {
+ if (rValue.Name == sMediaTypeProperty )
+ {
+ rValue.Value >>= aString;
+ pAttrList->AddAttribute ( ATTRIBUTE_MEDIA_TYPE, ATTRIBUTE_CDATA, aString );
+ }
+ else if (rValue.Name == sVersionProperty )
+ {
+ rValue.Value >>= aString;
+ // the version is stored only if it is not empty
+ if ( bAcceptNonemptyVersion && !aString.isEmpty() )
+ pAttrList->AddAttribute ( ATTRIBUTE_VERSION, ATTRIBUTE_CDATA, aString );
+ }
+ else if (rValue.Name == sFullPathProperty )
+ {
+ rValue.Value >>= aString;
+ pAttrList->AddAttribute ( ATTRIBUTE_FULL_PATH, ATTRIBUTE_CDATA, aString );
+ }
+ else if (rValue.Name == sSizeProperty )
+ {
+ sal_Int64 nSize = 0;
+ rValue.Value >>= nSize;
+ pAttrList->AddAttribute ( ATTRIBUTE_SIZE, ATTRIBUTE_CDATA, OUString::number( nSize ) );
+ }
+ else if (rValue.Name == sInitialisationVectorProperty )
+ pVector = &rValue.Value;
+ else if (rValue.Name == sSaltProperty )
+ pSalt = &rValue.Value;
+ else if (rValue.Name == sIterationCountProperty )
+ pIterationCount = &rValue.Value;
+ else if (rValue.Name == sDigestProperty )
+ pDigest = &rValue.Value;
+ else if (rValue.Name == sDigestAlgProperty )
+ pDigestAlg = &rValue.Value;
+ else if (rValue.Name == sEncryptionAlgProperty )
+ pEncryptAlg = &rValue.Value;
+ else if (rValue.Name == sStartKeyAlgProperty )
+ pStartKeyAlg = &rValue.Value;
+ else if (rValue.Name == sDerivedKeySizeProperty )
+ pDerivedKeySize = &rValue.Value;
+ }
+
+ xHandler->ignorableWhitespace ( sWhiteSpace );
+ xHandler->startElement( ELEMENT_FILE_ENTRY , pAttrList);
+ if ( pVector && pSalt && pIterationCount && pDigest && pDigestAlg && pEncryptAlg && pStartKeyAlg && pDerivedKeySize )
+ {
+ // ==== Encryption Data
+ rtl::Reference<::comphelper::AttributeList> pNewAttrList = new ::comphelper::AttributeList;
+ OUStringBuffer aBuffer;
+ uno::Sequence < sal_Int8 > aSequence;
+
+ xHandler->ignorableWhitespace ( sWhiteSpace );
+
+ // ==== Digest
+ OUString sChecksumType;
+ sal_Int32 nDigestAlgID = 0;
+ *pDigestAlg >>= nDigestAlgID;
+ if ( nDigestAlgID == xml::crypto::DigestID::SHA256_1K )
+ sChecksumType = sSHA256_1k_URL;
+ else if ( nDigestAlgID == xml::crypto::DigestID::SHA1_1K )
+ sChecksumType = sSHA1_1k_Name;
+ else
+ throw uno::RuntimeException( THROW_WHERE "Unexpected digest algorithm is provided!" );
+
+ pNewAttrList->AddAttribute ( ATTRIBUTE_CHECKSUM_TYPE, ATTRIBUTE_CDATA, sChecksumType );
+ *pDigest >>= aSequence;
+ ::comphelper::Base64::encode(aBuffer, aSequence);
+ pNewAttrList->AddAttribute ( ATTRIBUTE_CHECKSUM, ATTRIBUTE_CDATA, aBuffer.makeStringAndClear() );
+
+ xHandler->startElement( ELEMENT_ENCRYPTION_DATA , pNewAttrList);
+
+ // ==== Algorithm
+ pNewAttrList = new ::comphelper::AttributeList;
+
+ sal_Int32 nEncAlgID = 0;
+ sal_Int32 nDerivedKeySize = 0;
+ *pEncryptAlg >>= nEncAlgID;
+ *pDerivedKeySize >>= nDerivedKeySize;
+
+ OUString sEncAlgName;
+ if ( nEncAlgID == xml::crypto::CipherID::AES_CBC_W3C_PADDING )
+ {
+ OSL_ENSURE( nDerivedKeySize, "Unexpected key size is provided!" );
+ if ( nDerivedKeySize != 32 )
+ throw uno::RuntimeException( THROW_WHERE "Unexpected key size is provided!" );
+
+ sEncAlgName = sAES256_URL;
+ }
+ else if ( nEncAlgID == xml::crypto::CipherID::BLOWFISH_CFB_8 )
+ {
+ sEncAlgName = sBlowfish_Name;
+ }
+ else
+ throw uno::RuntimeException( THROW_WHERE "Unexpected encryption algorithm is provided!" );
+
+ pNewAttrList->AddAttribute ( ATTRIBUTE_ALGORITHM_NAME, ATTRIBUTE_CDATA, sEncAlgName );
+
+ *pVector >>= aSequence;
+ ::comphelper::Base64::encode(aBuffer, aSequence);
+ pNewAttrList->AddAttribute ( ATTRIBUTE_INITIALISATION_VECTOR, ATTRIBUTE_CDATA, aBuffer.makeStringAndClear() );
+
+ xHandler->ignorableWhitespace ( sWhiteSpace );
+ xHandler->startElement( ELEMENT_ALGORITHM , pNewAttrList);
+ xHandler->ignorableWhitespace ( sWhiteSpace );
+ xHandler->endElement( ELEMENT_ALGORITHM );
+
+ if ( bStoreStartKeyGeneration )
+ {
+ // ==== Start Key Generation
+ pNewAttrList = new ::comphelper::AttributeList;
+
+ OUString sStartKeyAlg;
+ OUString sStartKeySize;
+ sal_Int32 nStartKeyAlgID = 0;
+ *pStartKeyAlg >>= nStartKeyAlgID;
+ if ( nStartKeyAlgID == xml::crypto::DigestID::SHA256 )
+ {
+ sStartKeyAlg = sSHA256_URL_ODF12; // TODO use SHA256_URL
+ aBuffer.append( sal_Int32(32) );
+ sStartKeySize = aBuffer.makeStringAndClear();
+ }
+ else if ( nStartKeyAlgID == xml::crypto::DigestID::SHA1 )
+ {
+ sStartKeyAlg = sSHA1_Name;
+ aBuffer.append( sal_Int32(20) );
+ sStartKeySize = aBuffer.makeStringAndClear();
+ }
+ else
+ throw uno::RuntimeException( THROW_WHERE "Unexpected start key algorithm is provided!" );
+
+ pNewAttrList->AddAttribute ( ATTRIBUTE_START_KEY_GENERATION_NAME, ATTRIBUTE_CDATA, sStartKeyAlg );
+ pNewAttrList->AddAttribute ( ATTRIBUTE_KEY_SIZE, ATTRIBUTE_CDATA, sStartKeySize );
+
+ xHandler->ignorableWhitespace ( sWhiteSpace );
+ xHandler->startElement( ELEMENT_START_KEY_GENERATION , pNewAttrList);
+ xHandler->ignorableWhitespace ( sWhiteSpace );
+ xHandler->endElement( ELEMENT_START_KEY_GENERATION );
+ }
+
+ // ==== Key Derivation
+ pNewAttrList = new ::comphelper::AttributeList;
+
+ if (pKeyInfoProperty)
+ {
+ pNewAttrList->AddAttribute(ATTRIBUTE_KEY_DERIVATION_NAME,
+ ATTRIBUTE_CDATA,
+ sPGP_Name);
+ // no start-key-generation needed, our session key has
+ // max size already
+ bStoreStartKeyGeneration = false;
+ }
+ else
+ {
+ pNewAttrList->AddAttribute(ATTRIBUTE_KEY_DERIVATION_NAME,
+ ATTRIBUTE_CDATA,
+ sPBKDF2_Name);
+
+ if (bStoreStartKeyGeneration)
+ {
+ aBuffer.append(nDerivedKeySize);
+ pNewAttrList->AddAttribute(ATTRIBUTE_KEY_SIZE, ATTRIBUTE_CDATA, aBuffer.makeStringAndClear());
+ }
+
+ sal_Int32 nCount = 0;
+ *pIterationCount >>= nCount;
+ aBuffer.append(nCount);
+ pNewAttrList->AddAttribute(ATTRIBUTE_ITERATION_COUNT, ATTRIBUTE_CDATA, aBuffer.makeStringAndClear());
+
+ *pSalt >>= aSequence;
+ ::comphelper::Base64::encode(aBuffer, aSequence);
+ pNewAttrList->AddAttribute(ATTRIBUTE_SALT, ATTRIBUTE_CDATA, aBuffer.makeStringAndClear());
+ }
+
+ xHandler->ignorableWhitespace(sWhiteSpace);
+ xHandler->startElement(ELEMENT_KEY_DERIVATION, pNewAttrList);
+ xHandler->ignorableWhitespace(sWhiteSpace);
+ xHandler->endElement(ELEMENT_KEY_DERIVATION);
+
+ xHandler->ignorableWhitespace ( sWhiteSpace );
+ xHandler->endElement( ELEMENT_ENCRYPTION_DATA );
+ }
+ xHandler->ignorableWhitespace ( sWhiteSpace );
+ xHandler->endElement( ELEMENT_FILE_ENTRY );
+ }
+ xHandler->ignorableWhitespace ( sWhiteSpace );
+ xHandler->endElement( ELEMENT_MANIFEST );
+ xHandler->endDocument();
+}
+
+/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
diff --git a/package/source/manifest/ManifestExport.hxx b/package/source/manifest/ManifestExport.hxx
new file mode 100644
index 000000000..0148ea62c
--- /dev/null
+++ b/package/source/manifest/ManifestExport.hxx
@@ -0,0 +1,38 @@
+/* -*- 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 .
+ */
+
+#ifndef INCLUDED_PACKAGE_SOURCE_MANIFEST_MANIFESTEXPORT_HXX
+#define INCLUDED_PACKAGE_SOURCE_MANIFEST_MANIFESTEXPORT_HXX
+
+#include <com/sun/star/uno/Sequence.h>
+#include <com/sun/star/uno/Reference.h>
+
+namespace com::sun::star {
+ namespace beans { struct PropertyValue;}
+ namespace xml::sax { class XDocumentHandler; }
+}
+class ManifestExport
+{
+public:
+ ManifestExport(css::uno::Reference < css::xml::sax::XDocumentHandler > const & xHandler, const css::uno::Sequence < css::uno::Sequence < css::beans::PropertyValue > > &rManList );
+};
+
+#endif
+
+/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
diff --git a/package/source/manifest/ManifestImport.cxx b/package/source/manifest/ManifestImport.cxx
new file mode 100644
index 000000000..d2b3177e3
--- /dev/null
+++ b/package/source/manifest/ManifestImport.cxx
@@ -0,0 +1,550 @@
+/* -*- 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 "ManifestImport.hxx"
+#include "ManifestDefines.hxx"
+#include <PackageConstants.hxx>
+#include <osl/diagnose.h>
+#include <com/sun/star/xml/sax/XAttributeList.hpp>
+#include <com/sun/star/xml/crypto/DigestID.hpp>
+#include <com/sun/star/xml/crypto/CipherID.hpp>
+#include <com/sun/star/beans/PropertyValue.hpp>
+#include <comphelper/base64.hxx>
+#include <comphelper/sequence.hxx>
+
+using namespace com::sun::star::uno;
+using namespace com::sun::star::beans;
+using namespace com::sun::star;
+
+constexpr OUStringLiteral gsFullPathProperty ( u"FullPath" );
+constexpr OUStringLiteral gsMediaTypeProperty ( u"MediaType" );
+constexpr OUStringLiteral gsVersionProperty ( u"Version" );
+constexpr OUStringLiteral gsIterationCountProperty ( u"IterationCount" );
+constexpr OUStringLiteral gsDerivedKeySizeProperty ( u"DerivedKeySize" );
+constexpr OUStringLiteral gsSaltProperty ( u"Salt" );
+constexpr OUStringLiteral gsInitialisationVectorProperty ( u"InitialisationVector" );
+constexpr OUStringLiteral gsSizeProperty ( u"Size" );
+constexpr OUStringLiteral gsDigestProperty ( u"Digest" );
+constexpr OUStringLiteral gsEncryptionAlgProperty ( u"EncryptionAlgorithm" );
+constexpr OUStringLiteral gsStartKeyAlgProperty ( u"StartKeyAlgorithm" );
+constexpr OUStringLiteral gsDigestAlgProperty ( u"DigestAlgorithm" );
+
+ManifestImport::ManifestImport( std::vector < Sequence < PropertyValue > > & rNewManVector )
+ : bIgnoreEncryptData ( false )
+ , bPgpEncryption ( false )
+ , nDerivedKeySize( 0 )
+ , rManVector ( rNewManVector )
+{
+ aStack.reserve( 10 );
+}
+
+ManifestImport::~ManifestImport()
+{
+}
+
+void SAL_CALL ManifestImport::startDocument( )
+{
+}
+
+void SAL_CALL ManifestImport::endDocument( )
+{
+}
+
+void ManifestImport::doFileEntry(StringHashMap &rConvertedAttribs)
+{
+ aSequence.resize(PKG_SIZE_ENCR_MNFST);
+
+ aSequence[PKG_MNFST_FULLPATH].Name = gsFullPathProperty;
+ aSequence[PKG_MNFST_FULLPATH].Value <<= rConvertedAttribs[ATTRIBUTE_FULL_PATH];
+ aSequence[PKG_MNFST_MEDIATYPE].Name = gsMediaTypeProperty;
+ aSequence[PKG_MNFST_MEDIATYPE].Value <<= rConvertedAttribs[ATTRIBUTE_MEDIA_TYPE];
+
+ OUString sVersion = rConvertedAttribs[ATTRIBUTE_VERSION];
+ if ( sVersion.getLength() ) {
+ aSequence[PKG_MNFST_VERSION].Name = gsVersionProperty;
+ aSequence[PKG_MNFST_VERSION].Value <<= sVersion;
+ }
+
+ OUString sSize = rConvertedAttribs[ATTRIBUTE_SIZE];
+ if ( sSize.getLength() ) {
+ sal_Int64 nSize = sSize.toInt64();
+ aSequence[PKG_MNFST_UCOMPSIZE].Name = gsSizeProperty;
+ aSequence[PKG_MNFST_UCOMPSIZE].Value <<= nSize;
+ }
+}
+
+void ManifestImport::doEncryptedKey(StringHashMap &)
+{
+ aKeyInfoSequence.clear();
+ aKeyInfoSequence.resize(3);
+}
+
+void ManifestImport::doEncryptionMethod(StringHashMap &rConvertedAttribs,
+ const OUString& rAlgoAttrName)
+{
+ OUString aString = rConvertedAttribs[rAlgoAttrName];
+ if ( aKeyInfoSequence.size() != 3
+ || aString != "http://www.w3.org/2001/04/xmlenc#rsa-oaep-mgf1p" )
+ {
+ bIgnoreEncryptData = true;
+ }
+}
+
+void ManifestImport::doEncryptedCipherValue()
+{
+ if ( aKeyInfoSequence.size() == 3 )
+ {
+ aKeyInfoSequence[2].Name = "CipherValue";
+ uno::Sequence < sal_Int8 > aDecodeBuffer;
+ ::comphelper::Base64::decode(aDecodeBuffer, aCurrentCharacters);
+ aKeyInfoSequence[2].Value <<= aDecodeBuffer;
+ aCurrentCharacters.setLength(0); // consumed
+ }
+ else
+ bIgnoreEncryptData = true;
+}
+
+void ManifestImport::doEncryptedKeyId()
+{
+ if ( aKeyInfoSequence.size() == 3 )
+ {
+ aKeyInfoSequence[0].Name = "KeyId";
+ uno::Sequence < sal_Int8 > aDecodeBuffer;
+ ::comphelper::Base64::decode(aDecodeBuffer, aCurrentCharacters);
+ aKeyInfoSequence[0].Value <<= aDecodeBuffer;
+ aCurrentCharacters.setLength(0); // consumed
+ }
+ else
+ bIgnoreEncryptData = true;
+}
+
+void ManifestImport::doEncryptedKeyPacket()
+{
+ if ( aKeyInfoSequence.size() == 3 )
+ {
+ aKeyInfoSequence[1].Name = "KeyPacket";
+ uno::Sequence < sal_Int8 > aDecodeBuffer;
+ ::comphelper::Base64::decode(aDecodeBuffer, aCurrentCharacters);
+ aKeyInfoSequence[1].Value <<= aDecodeBuffer;
+ aCurrentCharacters.setLength(0); // consumed
+ }
+ else
+ bIgnoreEncryptData = true;
+}
+
+void ManifestImport::doEncryptionData(StringHashMap &rConvertedAttribs)
+{
+ // If this element exists, then this stream is encrypted and we need
+ // to import the initialisation vector, salt and iteration count used
+ nDerivedKeySize = 0;
+ OUString aString = rConvertedAttribs[ATTRIBUTE_CHECKSUM_TYPE];
+ if ( bIgnoreEncryptData )
+ return;
+
+ if ( aString == SHA1_1K_NAME || aString == SHA1_1K_URL ) {
+ aSequence[PKG_MNFST_DIGESTALG].Name = gsDigestAlgProperty;
+ aSequence[PKG_MNFST_DIGESTALG].Value <<= xml::crypto::DigestID::SHA1_1K;
+ } else if ( aString == SHA256_1K_URL ) {
+ aSequence[PKG_MNFST_DIGESTALG].Name = gsDigestAlgProperty;
+ aSequence[PKG_MNFST_DIGESTALG].Value <<= xml::crypto::DigestID::SHA256_1K;
+ } else
+ bIgnoreEncryptData = true;
+
+ if ( !bIgnoreEncryptData ) {
+ aString = rConvertedAttribs[ATTRIBUTE_CHECKSUM];
+ uno::Sequence < sal_Int8 > aDecodeBuffer;
+ ::comphelper::Base64::decode(aDecodeBuffer, aString);
+ aSequence[PKG_MNFST_DIGEST].Name = gsDigestProperty;
+ aSequence[PKG_MNFST_DIGEST].Value <<= aDecodeBuffer;
+ }
+}
+
+void ManifestImport::doAlgorithm(StringHashMap &rConvertedAttribs)
+{
+ if ( bIgnoreEncryptData )
+ return;
+
+ OUString aString = rConvertedAttribs[ATTRIBUTE_ALGORITHM_NAME];
+ if ( aString == BLOWFISH_NAME || aString == BLOWFISH_URL ) {
+ aSequence[PKG_MNFST_ENCALG].Name = gsEncryptionAlgProperty;
+ aSequence[PKG_MNFST_ENCALG].Value <<= xml::crypto::CipherID::BLOWFISH_CFB_8;
+ } else if ( aString == AES256_URL ) {
+ aSequence[PKG_MNFST_ENCALG].Name = gsEncryptionAlgProperty;
+ aSequence[PKG_MNFST_ENCALG].Value <<= xml::crypto::CipherID::AES_CBC_W3C_PADDING;
+ OSL_ENSURE( !nDerivedKeySize || nDerivedKeySize == 32, "Unexpected derived key length!" );
+ nDerivedKeySize = 32;
+ } else if ( aString == AES192_URL ) {
+ aSequence[PKG_MNFST_ENCALG].Name = gsEncryptionAlgProperty;
+ aSequence[PKG_MNFST_ENCALG].Value <<= xml::crypto::CipherID::AES_CBC_W3C_PADDING;
+ OSL_ENSURE( !nDerivedKeySize || nDerivedKeySize == 24, "Unexpected derived key length!" );
+ nDerivedKeySize = 24;
+ } else if ( aString == AES128_URL ) {
+ aSequence[PKG_MNFST_ENCALG].Name = gsEncryptionAlgProperty;
+ aSequence[PKG_MNFST_ENCALG].Value <<= xml::crypto::CipherID::AES_CBC_W3C_PADDING;
+ OSL_ENSURE( !nDerivedKeySize || nDerivedKeySize == 16, "Unexpected derived key length!" );
+ nDerivedKeySize = 16;
+ } else
+ bIgnoreEncryptData = true;
+
+ if ( !bIgnoreEncryptData ) {
+ aString = rConvertedAttribs[ATTRIBUTE_INITIALISATION_VECTOR];
+ uno::Sequence < sal_Int8 > aDecodeBuffer;
+ ::comphelper::Base64::decode(aDecodeBuffer, aString);
+ aSequence[PKG_MNFST_INIVECTOR].Name = gsInitialisationVectorProperty;
+ aSequence[PKG_MNFST_INIVECTOR].Value <<= aDecodeBuffer;
+ }
+}
+
+void ManifestImport::doKeyDerivation(StringHashMap &rConvertedAttribs)
+{
+ if ( bIgnoreEncryptData )
+ return;
+
+ OUString aString = rConvertedAttribs[ATTRIBUTE_KEY_DERIVATION_NAME];
+ if ( aString == PBKDF2_NAME || aString == PBKDF2_URL ) {
+ aString = rConvertedAttribs[ATTRIBUTE_SALT];
+ uno::Sequence < sal_Int8 > aDecodeBuffer;
+ ::comphelper::Base64::decode(aDecodeBuffer, aString);
+ aSequence[PKG_MNFST_SALT].Name = gsSaltProperty;
+ aSequence[PKG_MNFST_SALT].Value <<= aDecodeBuffer;
+
+ aString = rConvertedAttribs[ATTRIBUTE_ITERATION_COUNT];
+ aSequence[PKG_MNFST_ITERATION].Name = gsIterationCountProperty;
+ aSequence[PKG_MNFST_ITERATION].Value <<= aString.toInt32();
+
+ aString = rConvertedAttribs[ATTRIBUTE_KEY_SIZE];
+ if ( aString.getLength() ) {
+ sal_Int32 nKey = aString.toInt32();
+ OSL_ENSURE( !nDerivedKeySize || nKey == nDerivedKeySize , "Provided derived key length differs from the expected one!" );
+ nDerivedKeySize = nKey;
+ } else if ( !nDerivedKeySize )
+ nDerivedKeySize = 16;
+ else if ( nDerivedKeySize != 16 )
+ OSL_ENSURE( false, "Default derived key length differs from the expected one!" );
+
+ aSequence[PKG_MNFST_DERKEYSIZE].Name = gsDerivedKeySizeProperty;
+ aSequence[PKG_MNFST_DERKEYSIZE].Value <<= nDerivedKeySize;
+ } else if ( bPgpEncryption ) {
+ if ( aString != "PGP" )
+ bIgnoreEncryptData = true;
+ } else
+ bIgnoreEncryptData = true;
+}
+
+void ManifestImport::doStartKeyAlg(StringHashMap &rConvertedAttribs)
+{
+ OUString aString = rConvertedAttribs[ATTRIBUTE_START_KEY_GENERATION_NAME];
+ if (aString == SHA256_URL || aString == SHA256_URL_ODF12) {
+ aSequence[PKG_MNFST_STARTALG].Name = gsStartKeyAlgProperty;
+ aSequence[PKG_MNFST_STARTALG].Value <<= xml::crypto::DigestID::SHA256;
+ } else if ( aString == SHA1_NAME || aString == SHA1_URL ) {
+ aSequence[PKG_MNFST_STARTALG].Name = gsStartKeyAlgProperty;
+ aSequence[PKG_MNFST_STARTALG].Value <<= xml::crypto::DigestID::SHA1;
+ } else
+ bIgnoreEncryptData = true;
+}
+
+void SAL_CALL ManifestImport::startElement( const OUString& aName, const uno::Reference< xml::sax::XAttributeList >& xAttribs )
+{
+ StringHashMap aConvertedAttribs;
+ OUString aConvertedName = PushNameAndNamespaces( aName, xAttribs, aConvertedAttribs );
+
+ size_t nLevel = aStack.size();
+
+ assert(nLevel >= 1);
+
+ switch (nLevel) {
+ case 1: {
+ if (aConvertedName != ELEMENT_MANIFEST) //manifest:manifest
+ aStack.back().m_bValid = false;
+ break;
+ }
+ case 2: {
+ if (aConvertedName == ELEMENT_FILE_ENTRY) //manifest:file-entry
+ doFileEntry(aConvertedAttribs);
+ else if (aConvertedName == ELEMENT_MANIFEST_KEYINFO) //loext:keyinfo
+ ;
+ else if (aConvertedName == ELEMENT_ENCRYPTEDKEY13) //manifest:encrypted-key
+ doEncryptedKey(aConvertedAttribs);
+ else
+ aStack.back().m_bValid = false;
+ break;
+ }
+ case 3: {
+ ManifestStack::reverse_iterator aIter = aStack.rbegin();
+ ++aIter;
+
+ if (!aIter->m_bValid)
+ aStack.back().m_bValid = false;
+ else if (aConvertedName == ELEMENT_ENCRYPTION_DATA) //manifest:encryption-data
+ doEncryptionData(aConvertedAttribs);
+ else if (aConvertedName == ELEMENT_ENCRYPTEDKEY) //loext:encrypted-key
+ doEncryptedKey(aConvertedAttribs);
+ else if (aConvertedName == ELEMENT_ENCRYPTIONMETHOD13) //manifest:encryption-method
+ doEncryptionMethod(aConvertedAttribs, ATTRIBUTE_ALGORITHM13);
+ else if (aConvertedName == ELEMENT_MANIFEST13_KEYINFO) //manifest:keyinfo
+ ;
+ else if (aConvertedName == ELEMENT_CIPHERDATA13) //manifest:CipherData
+ ;
+ else
+ aStack.back().m_bValid = false;
+ break;
+ }
+ case 4: {
+ ManifestStack::reverse_iterator aIter = aStack.rbegin();
+ ++aIter;
+
+ if (!aIter->m_bValid)
+ aStack.back().m_bValid = false;
+ else if (aConvertedName == ELEMENT_ALGORITHM) //manifest:algorithm,
+ doAlgorithm(aConvertedAttribs);
+ else if (aConvertedName == ELEMENT_KEY_DERIVATION) //manifest:key-derivation,
+ doKeyDerivation(aConvertedAttribs);
+ else if (aConvertedName == ELEMENT_START_KEY_GENERATION) //manifest:start-key-generation
+ doStartKeyAlg(aConvertedAttribs);
+ else if (aConvertedName == ELEMENT_ENCRYPTIONMETHOD) //loext:encryption-method
+ doEncryptionMethod(aConvertedAttribs, ATTRIBUTE_ALGORITHM);
+ else if (aConvertedName == ELEMENT_ENCRYPTED_KEYINFO) //loext:KeyInfo
+ ;
+ else if (aConvertedName == ELEMENT_CIPHERDATA) //loext:CipherData
+ ;
+ else if (aConvertedName == ELEMENT_PGPDATA13) //manifest:PGPData
+ ;
+ else if (aConvertedName == ELEMENT_CIPHERVALUE13) //manifest:CipherValue
+ // ciphervalue action happens on endElement
+ aCurrentCharacters = "";
+ else
+ aStack.back().m_bValid = false;
+ break;
+ }
+ case 5: {
+ ManifestStack::reverse_iterator aIter = aStack.rbegin();
+ ++aIter;
+
+ if (!aIter->m_bValid)
+ aStack.back().m_bValid = false;
+ else if (aConvertedName == ELEMENT_PGPDATA) //loext:PGPData
+ ;
+ else if (aConvertedName == ELEMENT_CIPHERVALUE) //loext:CipherValue
+ // ciphervalue action happens on endElement
+ aCurrentCharacters = "";
+ else if (aConvertedName == ELEMENT_PGPKEYID13) //manifest:PGPKeyID
+ // ciphervalue action happens on endElement
+ aCurrentCharacters = "";
+ else if (aConvertedName == ELEMENT_PGPKEYPACKET13) //manifest:PGPKeyPacket
+ // ciphervalue action happens on endElement
+ aCurrentCharacters = "";
+ else
+ aStack.back().m_bValid = false;
+ break;
+ }
+ case 6: {
+ ManifestStack::reverse_iterator aIter = aStack.rbegin();
+ ++aIter;
+
+ if (!aIter->m_bValid)
+ aStack.back().m_bValid = false;
+ else if (aConvertedName == ELEMENT_PGPKEYID) //loext:PGPKeyID
+ // ciphervalue action happens on endElement
+ aCurrentCharacters = "";
+ else if (aConvertedName == ELEMENT_PGPKEYPACKET) //loext:PGPKeyPacket
+ // ciphervalue action happens on endElement
+ aCurrentCharacters = "";
+ else
+ aStack.back().m_bValid = false;
+ break;
+ }
+ default:
+ aStack.back().m_bValid = false;
+ break;
+ }
+}
+
+namespace
+{
+bool isEmpty(const css::beans::PropertyValue &rProp)
+{
+ return rProp.Name.isEmpty();
+}
+}
+
+void SAL_CALL ManifestImport::endElement( const OUString& aName )
+{
+ size_t nLevel = aStack.size();
+
+ assert(nLevel >= 1);
+
+ OUString aConvertedName = ConvertName( aName );
+ if ( aStack.empty() || aStack.rbegin()->m_aConvertedName != aConvertedName )
+ return;
+
+ if ( aConvertedName == ELEMENT_FILE_ENTRY && aStack.back().m_bValid ) {
+ // root folder gets KeyInfo entry if any, for PGP encryption
+ if (!bIgnoreEncryptData && !aKeys.empty() && aSequence[PKG_MNFST_FULLPATH].Value.get<OUString>() == "/" )
+ {
+ aSequence[PKG_SIZE_NOENCR_MNFST].Name = "KeyInfo";
+ aSequence[PKG_SIZE_NOENCR_MNFST].Value <<= comphelper::containerToSequence(aKeys);
+ }
+ aSequence.erase(std::remove_if(aSequence.begin(), aSequence.end(),
+ isEmpty), aSequence.end());
+
+ bIgnoreEncryptData = false;
+ rManVector.push_back ( comphelper::containerToSequence(aSequence) );
+
+ aSequence.clear();
+ }
+ else if ( (aConvertedName == ELEMENT_ENCRYPTEDKEY
+ || aConvertedName == ELEMENT_ENCRYPTEDKEY13)
+ && aStack.back().m_bValid ) {
+ if ( !bIgnoreEncryptData )
+ {
+ aKeys.push_back( comphelper::containerToSequence(aKeyInfoSequence) );
+ bPgpEncryption = true;
+ }
+ aKeyInfoSequence.clear();
+ }
+
+ // end element handling for elements with cdata
+ switch (nLevel) {
+ case 4: {
+ if (aConvertedName == ELEMENT_CIPHERVALUE13) //manifest:CipherValue
+ doEncryptedCipherValue();
+ else
+ aStack.back().m_bValid = false;
+ break;
+ }
+ case 5: {
+ if (aConvertedName == ELEMENT_CIPHERVALUE) //loext:CipherValue
+ doEncryptedCipherValue();
+ else if (aConvertedName == ELEMENT_PGPKEYID13) //manifest:PGPKeyID
+ doEncryptedKeyId();
+ else if (aConvertedName == ELEMENT_PGPKEYPACKET13) //manifest:PGPKeyPacket
+ doEncryptedKeyPacket();
+ else
+ aStack.back().m_bValid = false;
+ break;
+ }
+ case 6: {
+ if (aConvertedName == ELEMENT_PGPKEYID) //loext:PGPKeyID
+ doEncryptedKeyId();
+ else if (aConvertedName == ELEMENT_PGPKEYPACKET) //loext:PGPKeyPacket
+ doEncryptedKeyPacket();
+ else
+ aStack.back().m_bValid = false;
+ break;
+ }
+ }
+
+ aStack.pop_back();
+}
+
+void SAL_CALL ManifestImport::characters( const OUString& aChars )
+{
+ aCurrentCharacters.append(aChars);
+}
+
+void SAL_CALL ManifestImport::ignorableWhitespace( const OUString& /*aWhitespaces*/ )
+{
+}
+
+void SAL_CALL ManifestImport::processingInstruction( const OUString& /*aTarget*/, const OUString& /*aData*/ )
+{
+}
+
+void SAL_CALL ManifestImport::setDocumentLocator( const uno::Reference< xml::sax::XLocator >& /*xLocator*/ )
+{
+}
+
+OUString ManifestImport::PushNameAndNamespaces( const OUString& aName, const uno::Reference< xml::sax::XAttributeList >& xAttribs, StringHashMap& o_aConvertedAttribs )
+{
+ StringHashMap aNamespaces;
+ ::std::vector< ::std::pair< OUString, OUString > > aAttribsStrs;
+
+ if ( xAttribs.is() ) {
+ sal_Int16 nAttrCount = xAttribs.is() ? xAttribs->getLength() : 0;
+ aAttribsStrs.reserve( nAttrCount );
+
+ for( sal_Int16 nInd = 0; nInd < nAttrCount; nInd++ ) {
+ OUString aAttrName = xAttribs->getNameByIndex( nInd );
+ OUString aAttrValue = xAttribs->getValueByIndex( nInd );
+ if ( aAttrName.getLength() >= 5
+ && aAttrName.startsWith("xmlns")
+ && ( aAttrName.getLength() == 5 || aAttrName[5] == ':' ) ) {
+ // this is a namespace declaration
+ OUString aNsName( ( aAttrName.getLength() == 5 ) ? OUString() : aAttrName.copy( 6 ) );
+ aNamespaces[aNsName] = aAttrValue;
+ } else {
+ // this is no namespace declaration
+ aAttribsStrs.emplace_back( aAttrName, aAttrValue );
+ }
+ }
+ }
+
+ OUString aConvertedName = ConvertNameWithNamespace( aName, aNamespaces );
+ if ( !aConvertedName.getLength() )
+ aConvertedName = ConvertName( aName );
+
+ aStack.emplace_back( aConvertedName, std::move(aNamespaces) );
+
+ for (const std::pair<OUString,OUString> & rAttribsStr : aAttribsStrs) {
+ // convert the attribute names on filling
+ o_aConvertedAttribs[ConvertName( rAttribsStr.first )] = rAttribsStr.second;
+ }
+
+ return aConvertedName;
+}
+
+OUString ManifestImport::ConvertNameWithNamespace( const OUString& aName, const StringHashMap& aNamespaces )
+{
+ OUString aNsAlias;
+ OUString aPureName = aName;
+
+ sal_Int32 nInd = aName.indexOf( ':' );
+ if ( nInd != -1 && nInd < aName.getLength() ) {
+ aNsAlias = aName.copy( 0, nInd );
+ aPureName = aName.copy( nInd + 1 );
+ }
+
+ OUString aResult;
+
+ StringHashMap::const_iterator aIter = aNamespaces.find( aNsAlias );
+ if ( aIter != aNamespaces.end()
+ && ( aIter->second == MANIFEST_NAMESPACE || aIter->second == MANIFEST_OASIS_NAMESPACE ) ) {
+ // no check for manifest.xml consistency currently since the old versions have supported inconsistent documents as well
+ aResult = MANIFEST_NSPREFIX + aPureName;
+ }
+
+ return aResult;
+}
+
+OUString ManifestImport::ConvertName( const OUString& aName )
+{
+ OUString aConvertedName;
+ for ( ManifestStack::reverse_iterator aIter = aStack.rbegin(); !aConvertedName.getLength() && aIter != aStack.rend(); ++aIter ) {
+ if ( !aIter->m_aNamespaces.empty() )
+ aConvertedName = ConvertNameWithNamespace( aName, aIter->m_aNamespaces );
+ }
+
+ if ( !aConvertedName.getLength() )
+ aConvertedName = aName;
+
+ return aConvertedName;
+}
+
+/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
diff --git a/package/source/manifest/ManifestImport.hxx b/package/source/manifest/ManifestImport.hxx
new file mode 100644
index 000000000..024014639
--- /dev/null
+++ b/package/source/manifest/ManifestImport.hxx
@@ -0,0 +1,102 @@
+/* -*- 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 .
+ */
+
+#ifndef INCLUDED_PACKAGE_SOURCE_MANIFEST_MANIFESTIMPORT_HXX
+#define INCLUDED_PACKAGE_SOURCE_MANIFEST_MANIFESTIMPORT_HXX
+
+#include <cppuhelper/implbase.hxx>
+#include <com/sun/star/xml/sax/XDocumentHandler.hpp>
+#include <com/sun/star/beans/NamedValue.hpp>
+#include <unordered_map>
+#include <vector>
+#include <rtl/ustrbuf.hxx>
+
+namespace com::sun::star {
+ namespace xml::sax { class XAttributeList; }
+ namespace beans { struct PropertyValue; }
+}
+
+typedef std::unordered_map< OUString, OUString > StringHashMap;
+
+struct ManifestScopeEntry
+{
+ OUString m_aConvertedName;
+ StringHashMap m_aNamespaces;
+ bool m_bValid;
+
+ ManifestScopeEntry( const OUString& aConvertedName, StringHashMap&& aNamespaces )
+ : m_aConvertedName( aConvertedName )
+ , m_aNamespaces( std::move(aNamespaces) )
+ , m_bValid( true )
+ {}
+};
+
+typedef ::std::vector< ManifestScopeEntry > ManifestStack;
+
+class ManifestImport final : public cppu::WeakImplHelper < css::xml::sax::XDocumentHandler >
+{
+ std::vector< css::beans::NamedValue > aKeyInfoSequence;
+ std::vector< css::uno::Sequence< css::beans::NamedValue > > aKeys;
+ std::vector< css::beans::PropertyValue > aSequence;
+ OUStringBuffer aCurrentCharacters{64};
+ ManifestStack aStack;
+ bool bIgnoreEncryptData;
+ bool bPgpEncryption;
+ sal_Int32 nDerivedKeySize;
+ ::std::vector < css::uno::Sequence < css::beans::PropertyValue > > & rManVector;
+
+
+ OUString PushNameAndNamespaces( const OUString& aName,
+ const css::uno::Reference< css::xml::sax::XAttributeList >& xAttribs,
+ StringHashMap& o_aConvertedAttribs );
+ static OUString ConvertNameWithNamespace( const OUString& aName, const StringHashMap& aNamespaces );
+ OUString ConvertName( const OUString& aName );
+
+public:
+ ManifestImport( std::vector < css::uno::Sequence < css::beans::PropertyValue > > & rNewVector );
+ virtual ~ManifestImport() override;
+ virtual void SAL_CALL startDocument( ) override;
+ virtual void SAL_CALL endDocument( ) override;
+ virtual void SAL_CALL startElement( const OUString& aName, const css::uno::Reference< css::xml::sax::XAttributeList >& xAttribs ) override;
+ virtual void SAL_CALL endElement( const OUString& aName ) override;
+ virtual void SAL_CALL characters( const OUString& aChars ) override;
+ virtual void SAL_CALL ignorableWhitespace( const OUString& aWhitespaces ) override;
+ virtual void SAL_CALL processingInstruction( const OUString& aTarget, const OUString& aData ) override;
+ virtual void SAL_CALL setDocumentLocator( const css::uno::Reference< css::xml::sax::XLocator >& xLocator ) override;
+
+private:
+ /// @throws css::uno::RuntimeException
+ void doFileEntry(StringHashMap &rConvertedAttribs);
+ /// @throws css::uno::RuntimeException
+ void doEncryptionData(StringHashMap &rConvertedAttribs);
+ /// @throws css::uno::RuntimeException
+ void doAlgorithm(StringHashMap &rConvertedAttribs);
+ /// @throws css::uno::RuntimeException
+ void doKeyDerivation(StringHashMap &rConvertedAttribs);
+ /// @throws css::uno::RuntimeException
+ void doStartKeyAlg(StringHashMap &rConvertedAttribs);
+ void doEncryptedKey(StringHashMap &);
+ void doEncryptionMethod(StringHashMap &, const OUString &);
+ void doEncryptedCipherValue();
+ void doEncryptedKeyId();
+ void doEncryptedKeyPacket();
+};
+#endif
+
+/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
diff --git a/package/source/manifest/ManifestReader.cxx b/package/source/manifest/ManifestReader.cxx
new file mode 100644
index 000000000..6464681f2
--- /dev/null
+++ b/package/source/manifest/ManifestReader.cxx
@@ -0,0 +1,105 @@
+/* -*- 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 "ManifestReader.hxx"
+#include "ManifestImport.hxx"
+#include <tools/diagnose_ex.h>
+#include <comphelper/sequence.hxx>
+#include <cppuhelper/factory.hxx>
+#include <cppuhelper/supportsservice.hxx>
+#include <com/sun/star/io/IOException.hpp>
+#include <com/sun/star/xml/sax/XDocumentHandler.hpp>
+#include <com/sun/star/xml/sax/SAXParseException.hpp>
+#include <com/sun/star/xml/sax/Parser.hpp>
+#include <vector>
+
+using namespace ::std;
+using namespace ::com::sun::star::uno;
+using namespace ::com::sun::star::beans;
+using namespace ::com::sun::star::io;
+using namespace ::com::sun::star::lang;
+using namespace ::com::sun::star::registry;
+using namespace ::com::sun::star::packages;
+using namespace ::com::sun::star::xml::sax;
+
+ManifestReader::ManifestReader( const Reference < XComponentContext > & xContext )
+: m_xContext ( xContext )
+{
+}
+ManifestReader::~ManifestReader()
+{
+}
+Sequence< Sequence< PropertyValue > > SAL_CALL ManifestReader::readManifestSequence( const Reference< XInputStream >& rStream )
+{
+ Sequence < Sequence < PropertyValue > > aManifestSequence;
+ Reference < XParser > xParser = Parser::create(m_xContext);
+ try
+ {
+ vector < Sequence < PropertyValue > > aManVector;
+ Reference < XDocumentHandler > xFilter = new ManifestImport( aManVector );
+ InputSource aParserInput;
+ aParserInput.aInputStream = rStream;
+ aParserInput.sSystemId = "META-INF/manifest.xml";
+ xParser->setDocumentHandler ( xFilter );
+ xParser->parseStream( aParserInput );
+ aManifestSequence = comphelper::containerToSequence(aManVector);
+ }
+ catch (const SAXParseException&)
+ {
+ TOOLS_WARN_EXCEPTION("package", "ignoring");
+ }
+ catch (const SAXException&)
+ {
+ TOOLS_WARN_EXCEPTION("package", "ignoring");
+ }
+ catch (const IOException&)
+ {
+ TOOLS_WARN_EXCEPTION("package", "ignoring");
+ }
+ xParser->setDocumentHandler ( Reference < XDocumentHandler > () );
+ return aManifestSequence;
+}
+// Component functions
+
+
+OUString ManifestReader::getImplementationName()
+{
+ return "com.sun.star.packages.manifest.comp.ManifestReader";
+}
+
+sal_Bool SAL_CALL ManifestReader::supportsService(OUString const & rServiceName)
+{
+ return cppu::supportsService(this, rServiceName );
+}
+
+Sequence < OUString > ManifestReader::getSupportedServiceNames()
+{
+ return { "com.sun.star.packages.manifest.ManifestReader" };
+}
+
+
+extern "C" SAL_DLLPUBLIC_EXPORT css::uno::XInterface*
+package_ManifestReader_get_implementation(
+ css::uno::XComponentContext* context , css::uno::Sequence<css::uno::Any> const&)
+{
+ return cppu::acquire(new ManifestReader(context));
+}
+
+
+/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
diff --git a/package/source/manifest/ManifestReader.hxx b/package/source/manifest/ManifestReader.hxx
new file mode 100644
index 000000000..f85644162
--- /dev/null
+++ b/package/source/manifest/ManifestReader.hxx
@@ -0,0 +1,54 @@
+/* -*- 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 .
+ */
+
+#ifndef INCLUDED_PACKAGE_SOURCE_MANIFEST_MANIFESTREADER_HXX
+#define INCLUDED_PACKAGE_SOURCE_MANIFEST_MANIFESTREADER_HXX
+
+#include <cppuhelper/implbase.hxx>
+#include <com/sun/star/packages/manifest/XManifestReader.hpp>
+#include <com/sun/star/lang/XServiceInfo.hpp>
+
+namespace com::sun::star {
+ namespace lang { class XSingleServiceFactory; }
+ namespace uno { class XComponentContext; }
+}
+
+class ManifestReader: public ::cppu::WeakImplHelper
+<
+ css::packages::manifest::XManifestReader,
+ css::lang::XServiceInfo
+>
+{
+private:
+ css::uno::Reference< css::uno::XComponentContext > m_xContext;
+public:
+ ManifestReader( const css::uno::Reference< css::uno::XComponentContext > & xContext );
+ virtual ~ManifestReader() override;
+
+ // XManifestReader
+ virtual css::uno::Sequence< css::uno::Sequence< css::beans::PropertyValue > > SAL_CALL readManifestSequence( const css::uno::Reference< css::io::XInputStream >& rStream ) override;
+
+ // XServiceInfo
+ virtual OUString SAL_CALL getImplementationName( ) override;
+ virtual sal_Bool SAL_CALL supportsService( const OUString& ServiceName ) override;
+ virtual css::uno::Sequence< OUString > SAL_CALL getSupportedServiceNames( ) override;
+};
+#endif
+
+/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
diff --git a/package/source/manifest/ManifestWriter.cxx b/package/source/manifest/ManifestWriter.cxx
new file mode 100644
index 000000000..5515cc26d
--- /dev/null
+++ b/package/source/manifest/ManifestWriter.cxx
@@ -0,0 +1,92 @@
+/* -*- 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 "ManifestWriter.hxx"
+#include "ManifestExport.hxx"
+#include <cppuhelper/exc_hlp.hxx>
+#include <cppuhelper/factory.hxx>
+#include <cppuhelper/supportsservice.hxx>
+#include <com/sun/star/xml/sax/Writer.hpp>
+#include <com/sun/star/lang/WrappedTargetRuntimeException.hpp>
+#include <com/sun/star/xml/sax/SAXException.hpp>
+
+#include <sal/log.hxx>
+
+using namespace ::com::sun::star;
+using namespace ::com::sun::star::uno;
+using namespace ::com::sun::star::beans;
+using namespace ::com::sun::star::io;
+using namespace ::com::sun::star::lang;
+using namespace ::com::sun::star::registry;
+using namespace ::com::sun::star::packages;
+using namespace ::com::sun::star::xml::sax;
+
+#if OSL_DEBUG_LEVEL > 0
+#define THROW_WHERE SAL_WHERE
+#else
+#define THROW_WHERE ""
+#endif
+
+ManifestWriter::ManifestWriter( const Reference < XComponentContext > & xContext )
+: m_xContext ( xContext )
+{
+}
+ManifestWriter::~ManifestWriter()
+{
+}
+
+// XManifestWriter methods
+void SAL_CALL ManifestWriter::writeManifestSequence( const Reference< XOutputStream >& rStream, const Sequence< Sequence< PropertyValue > >& rSequence )
+{
+ Reference < XWriter > xSource = Writer::create( m_xContext );
+ xSource->setOutputStream ( rStream );
+ try {
+ ManifestExport( xSource, rSequence);
+ }
+ catch( SAXException& )
+ {
+ css::uno::Any anyEx = cppu::getCaughtException();
+ throw css::lang::WrappedTargetRuntimeException( THROW_WHERE,
+ nullptr, anyEx );
+ }
+}
+
+OUString ManifestWriter::getImplementationName()
+{
+ return "com.sun.star.packages.manifest.comp.ManifestWriter";
+}
+
+sal_Bool SAL_CALL ManifestWriter::supportsService(OUString const & rServiceName)
+{
+ return cppu::supportsService(this, rServiceName);
+}
+Sequence < OUString > ManifestWriter::getSupportedServiceNames()
+{
+ return { "com.sun.star.packages.manifest.ManifestWriter" };
+}
+
+
+extern "C" SAL_DLLPUBLIC_EXPORT css::uno::XInterface*
+package_ManifestWriter_get_implementation(
+ css::uno::XComponentContext* context , css::uno::Sequence<css::uno::Any> const&)
+{
+ return cppu::acquire(new ManifestWriter(context));
+}
+
+/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
diff --git a/package/source/manifest/ManifestWriter.hxx b/package/source/manifest/ManifestWriter.hxx
new file mode 100644
index 000000000..ca08bb0e4
--- /dev/null
+++ b/package/source/manifest/ManifestWriter.hxx
@@ -0,0 +1,54 @@
+/* -*- 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 .
+ */
+
+#ifndef INCLUDED_PACKAGE_SOURCE_MANIFEST_MANIFESTWRITER_HXX
+#define INCLUDED_PACKAGE_SOURCE_MANIFEST_MANIFESTWRITER_HXX
+
+#include <cppuhelper/implbase.hxx>
+#include <com/sun/star/packages/manifest/XManifestWriter.hpp>
+#include <com/sun/star/lang/XServiceInfo.hpp>
+
+namespace com::sun::star {
+ namespace lang { class XSingleServiceFactory; }
+ namespace uno { class XComponentContext; }
+}
+
+class ManifestWriter: public ::cppu::WeakImplHelper
+<
+ css::packages::manifest::XManifestWriter,
+ css::lang::XServiceInfo
+>
+{
+private:
+ css::uno::Reference< css::uno::XComponentContext > m_xContext;
+public:
+ ManifestWriter( const css::uno::Reference< css::uno::XComponentContext > & xContext );
+ virtual ~ManifestWriter() override;
+
+ // XManifestWriter
+ virtual void SAL_CALL writeManifestSequence( const css::uno::Reference< css::io::XOutputStream >& rStream, const css::uno::Sequence< css::uno::Sequence< css::beans::PropertyValue > >& rSequence ) override;
+
+ // XServiceInfo
+ virtual OUString SAL_CALL getImplementationName( ) override;
+ virtual sal_Bool SAL_CALL supportsService( const OUString& ServiceName ) override;
+ virtual css::uno::Sequence< OUString > SAL_CALL getSupportedServiceNames( ) override;
+};
+#endif
+
+/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
diff --git a/package/source/xstor/disposelistener.cxx b/package/source/xstor/disposelistener.cxx
new file mode 100644
index 000000000..b7ee40957
--- /dev/null
+++ b/package/source/xstor/disposelistener.cxx
@@ -0,0 +1,46 @@
+/* -*- 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 "disposelistener.hxx"
+#include "xstorage.hxx"
+
+using namespace ::com::sun::star;
+
+OChildDispListener_Impl::OChildDispListener_Impl( OStorage& aStorage )
+: m_pStorage( &aStorage )
+{}
+
+OChildDispListener_Impl::~OChildDispListener_Impl()
+{}
+
+void OChildDispListener_Impl::OwnerIsDisposed()
+{
+ std::scoped_lock aGuard( m_aMutex );
+ m_pStorage = nullptr;
+}
+
+void SAL_CALL OChildDispListener_Impl::disposing( const lang::EventObject& Source )
+{
+ std::scoped_lock aGuard( m_aMutex );
+ // ObjectIsDisposed must not contain any locking!
+ if ( m_pStorage && Source.Source.is() )
+ m_pStorage->ChildIsDisposed( Source.Source );
+}
+
+/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
diff --git a/package/source/xstor/disposelistener.hxx b/package/source/xstor/disposelistener.hxx
new file mode 100644
index 000000000..b635b58ce
--- /dev/null
+++ b/package/source/xstor/disposelistener.hxx
@@ -0,0 +1,44 @@
+/* -*- 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 .
+ */
+
+#ifndef INCLUDED_PACKAGE_SOURCE_XSTOR_DISPOSELISTENER_HXX
+#define INCLUDED_PACKAGE_SOURCE_XSTOR_DISPOSELISTENER_HXX
+
+#include <com/sun/star/lang/XEventListener.hpp>
+#include <cppuhelper/implbase.hxx>
+#include <mutex>
+
+class OStorage;
+class OChildDispListener_Impl : public ::cppu::WeakImplHelper<css::lang::XEventListener>
+{
+ std::mutex m_aMutex;
+ OStorage* m_pStorage;
+
+public:
+ explicit OChildDispListener_Impl(OStorage& aStorage);
+ virtual ~OChildDispListener_Impl() override;
+
+ void OwnerIsDisposed();
+
+ virtual void SAL_CALL disposing(const css::lang::EventObject& Source) override;
+};
+
+#endif
+
+/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
diff --git a/package/source/xstor/ocompinstream.cxx b/package/source/xstor/ocompinstream.cxx
new file mode 100644
index 000000000..14bfd3cab
--- /dev/null
+++ b/package/source/xstor/ocompinstream.cxx
@@ -0,0 +1,602 @@
+/* -*- 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 "ocompinstream.hxx"
+#include <com/sun/star/embed/StorageFormats.hpp>
+#include <com/sun/star/io/IOException.hpp>
+#include <com/sun/star/lang/DisposedException.hpp>
+#include <comphelper/sequence.hxx>
+#include <cppuhelper/queryinterface.hxx>
+#include <osl/diagnose.h>
+#include <sal/log.hxx>
+
+#include "owriteablestream.hxx"
+
+using namespace ::com::sun::star;
+
+OInputCompStream::OInputCompStream( OWriteStream_Impl& aImpl,
+ uno::Reference < io::XInputStream > const & xStream,
+ const uno::Sequence< beans::PropertyValue >& aProps,
+ sal_Int32 nStorageType )
+: m_pImpl( &aImpl )
+, m_xMutex( m_pImpl->m_xMutex )
+, m_xStream( xStream )
+, m_aProperties( aProps )
+, m_bDisposed( false )
+, m_nStorageType( nStorageType )
+{
+ OSL_ENSURE( m_pImpl->m_xMutex.is(), "No mutex is provided!" );
+ if ( !m_pImpl->m_xMutex.is() )
+ throw uno::RuntimeException(); // just a disaster
+
+ assert(m_xStream.is());
+}
+
+OInputCompStream::OInputCompStream( uno::Reference < io::XInputStream > const & xStream,
+ const uno::Sequence< beans::PropertyValue >& aProps,
+ sal_Int32 nStorageType )
+: m_pImpl( nullptr )
+, m_xMutex( new comphelper::RefCountedMutex )
+, m_xStream( xStream )
+, m_aProperties( aProps )
+, m_bDisposed( false )
+, m_nStorageType( nStorageType )
+{
+ assert(m_xStream.is());
+}
+
+OInputCompStream::~OInputCompStream()
+{
+ ::osl::MutexGuard aGuard( m_xMutex->GetMutex() );
+
+ if ( !m_bDisposed )
+ {
+ osl_atomic_increment(&m_refCount);
+ dispose();
+ }
+}
+
+uno::Any SAL_CALL OInputCompStream::queryInterface( const uno::Type& rType )
+{
+ // common interfaces
+ uno::Any aReturn = ::cppu::queryInterface
+ ( rType
+ , static_cast<io::XInputStream*> ( this )
+ , static_cast<io::XStream*> ( this )
+ , static_cast<lang::XComponent*> ( this )
+ , static_cast<beans::XPropertySet*> ( this )
+ , static_cast<embed::XExtendedStorageStream*> ( this ) );
+
+ if ( aReturn.hasValue() )
+ return aReturn ;
+
+ if ( m_nStorageType == embed::StorageFormats::OFOPXML )
+ {
+ aReturn = ::cppu::queryInterface
+ ( rType
+ , static_cast<embed::XRelationshipAccess*> ( this ) );
+
+ if ( aReturn.hasValue() )
+ return aReturn ;
+ }
+
+ return OWeakObject::queryInterface( rType );
+}
+
+sal_Int32 SAL_CALL OInputCompStream::readBytes( uno::Sequence< sal_Int8 >& aData, sal_Int32 nBytesToRead )
+{
+ ::osl::MutexGuard aGuard( m_xMutex->GetMutex() );
+ if ( m_bDisposed )
+ {
+ SAL_INFO("package.xstor", "Disposed!");
+ throw lang::DisposedException();
+ }
+
+ return m_xStream->readBytes( aData, nBytesToRead );
+}
+
+sal_Int32 SAL_CALL OInputCompStream::readSomeBytes( uno::Sequence< sal_Int8 >& aData, sal_Int32 nMaxBytesToRead )
+{
+ ::osl::MutexGuard aGuard( m_xMutex->GetMutex() );
+ if ( m_bDisposed )
+ {
+ SAL_INFO("package.xstor", "Disposed!");
+ throw lang::DisposedException();
+ }
+
+ return m_xStream->readSomeBytes( aData, nMaxBytesToRead );
+
+}
+
+void SAL_CALL OInputCompStream::skipBytes( sal_Int32 nBytesToSkip )
+{
+ ::osl::MutexGuard aGuard( m_xMutex->GetMutex() );
+ if ( m_bDisposed )
+ {
+ SAL_INFO("package.xstor", "Disposed!");
+ throw lang::DisposedException();
+ }
+
+ m_xStream->skipBytes( nBytesToSkip );
+
+}
+
+sal_Int32 SAL_CALL OInputCompStream::available( )
+{
+ ::osl::MutexGuard aGuard( m_xMutex->GetMutex() );
+ if ( m_bDisposed )
+ {
+ SAL_INFO("package.xstor", "Disposed!");
+ throw lang::DisposedException();
+ }
+
+ return m_xStream->available();
+
+}
+
+void SAL_CALL OInputCompStream::closeInput( )
+{
+ dispose();
+}
+
+uno::Reference< io::XInputStream > SAL_CALL OInputCompStream::getInputStream()
+{
+ ::osl::MutexGuard aGuard( m_xMutex->GetMutex() );
+ if ( m_bDisposed )
+ {
+ SAL_INFO("package.xstor", "Disposed!");
+ throw lang::DisposedException();
+ }
+
+ return this;
+}
+
+uno::Reference< io::XOutputStream > SAL_CALL OInputCompStream::getOutputStream()
+{
+ ::osl::MutexGuard aGuard( m_xMutex->GetMutex() );
+ if ( m_bDisposed )
+ {
+ SAL_INFO("package.xstor", "Disposed!");
+ throw lang::DisposedException();
+ }
+
+ return uno::Reference< io::XOutputStream >();
+}
+
+void OInputCompStream::InternalDispose()
+{
+ // can be called only by OWriteStream_Impl
+ ::osl::MutexGuard aGuard( m_xMutex->GetMutex() );
+ if ( m_bDisposed )
+ {
+ SAL_INFO("package.xstor", "Disposed!");
+ throw lang::DisposedException();
+ }
+
+ // the source object is also a kind of locker for the current object
+ // since the listeners could dispose the object while being notified
+ lang::EventObject aSource( static_cast< ::cppu::OWeakObject*>( this ) );
+
+ if ( m_pInterfaceContainer )
+ m_pInterfaceContainer->disposeAndClear( aSource );
+
+ try
+ {
+ m_xStream->closeInput();
+ }
+ catch( uno::Exception& )
+ {}
+
+ m_pImpl = nullptr;
+ m_bDisposed = true;
+}
+
+void SAL_CALL OInputCompStream::dispose( )
+{
+ ::osl::MutexGuard aGuard( m_xMutex->GetMutex() );
+ if ( m_bDisposed )
+ {
+ SAL_INFO("package.xstor", "Disposed!");
+ throw lang::DisposedException();
+ }
+
+ if ( m_pInterfaceContainer )
+ {
+ lang::EventObject aSource( static_cast< ::cppu::OWeakObject*>( this ) );
+ m_pInterfaceContainer->disposeAndClear( aSource );
+ }
+
+ m_xStream->closeInput();
+
+ if ( m_pImpl )
+ {
+ m_pImpl->InputStreamDisposed( this );
+ m_pImpl = nullptr;
+ }
+
+ m_bDisposed = true;
+}
+
+void SAL_CALL OInputCompStream::addEventListener( const uno::Reference< lang::XEventListener >& xListener )
+{
+ ::osl::MutexGuard aGuard( m_xMutex->GetMutex() );
+ if ( m_bDisposed )
+ {
+ SAL_INFO("package.xstor", "Disposed!");
+ throw lang::DisposedException();
+ }
+
+ if ( !m_pInterfaceContainer )
+ m_pInterfaceContainer.reset( new ::comphelper::OInterfaceContainerHelper3<css::lang::XEventListener>( m_xMutex->GetMutex() ) );
+
+ m_pInterfaceContainer->addInterface( xListener );
+}
+
+void SAL_CALL OInputCompStream::removeEventListener( const uno::Reference< lang::XEventListener >& xListener )
+{
+ ::osl::MutexGuard aGuard( m_xMutex->GetMutex() );
+ if ( m_bDisposed )
+ {
+ SAL_INFO("package.xstor", "Disposed!");
+ throw lang::DisposedException();
+ }
+
+ if ( m_pInterfaceContainer )
+ m_pInterfaceContainer->removeInterface( xListener );
+}
+
+sal_Bool SAL_CALL OInputCompStream::hasByID( const OUString& sID )
+{
+ ::osl::MutexGuard aGuard( m_xMutex->GetMutex() );
+
+ if ( m_bDisposed )
+ {
+ SAL_INFO("package.xstor", "Disposed!");
+ throw lang::DisposedException();
+ }
+
+ if ( m_nStorageType != embed::StorageFormats::OFOPXML )
+ throw uno::RuntimeException();
+
+ try
+ {
+ getRelationshipByID( sID );
+ return true;
+ }
+ catch( container::NoSuchElementException& )
+ {}
+
+ return false;
+}
+
+namespace
+{
+
+const beans::StringPair* lcl_findPairByName(const uno::Sequence<beans::StringPair>& rSeq, const OUString& rName)
+{
+ return std::find_if(rSeq.begin(), rSeq.end(),
+ [&rName](const beans::StringPair& rPair) { return rPair.First == rName; });
+}
+
+}
+
+OUString SAL_CALL OInputCompStream::getTargetByID( const OUString& sID )
+{
+ ::osl::MutexGuard aGuard( m_xMutex->GetMutex() );
+
+ if ( m_bDisposed )
+ {
+ SAL_INFO("package.xstor", "Disposed!");
+ throw lang::DisposedException();
+ }
+
+ if ( m_nStorageType != embed::StorageFormats::OFOPXML )
+ throw uno::RuntimeException();
+
+ const uno::Sequence< beans::StringPair > aSeq = getRelationshipByID( sID );
+ auto pRel = lcl_findPairByName(aSeq, "Target");
+ if (pRel != aSeq.end())
+ return pRel->Second;
+
+ return OUString();
+}
+
+OUString SAL_CALL OInputCompStream::getTypeByID( const OUString& sID )
+{
+ ::osl::MutexGuard aGuard( m_xMutex->GetMutex() );
+
+ if ( m_bDisposed )
+ {
+ SAL_INFO("package.xstor", "Disposed!");
+ throw lang::DisposedException();
+ }
+
+ if ( m_nStorageType != embed::StorageFormats::OFOPXML )
+ throw uno::RuntimeException();
+
+ const uno::Sequence< beans::StringPair > aSeq = getRelationshipByID( sID );
+ auto pRel = lcl_findPairByName(aSeq, "Type");
+ if (pRel != aSeq.end())
+ return pRel->Second;
+
+ return OUString();
+}
+
+uno::Sequence< beans::StringPair > SAL_CALL OInputCompStream::getRelationshipByID( const OUString& sID )
+{
+ ::osl::MutexGuard aGuard( m_xMutex->GetMutex() );
+
+ if ( m_bDisposed )
+ {
+ SAL_INFO("package.xstor", "Disposed!");
+ throw lang::DisposedException();
+ }
+
+ if ( m_nStorageType != embed::StorageFormats::OFOPXML )
+ throw uno::RuntimeException();
+
+ // TODO/LATER: in future the unification of the ID could be checked
+ const uno::Sequence< uno::Sequence< beans::StringPair > > aSeq = getAllRelationships();
+ const beans::StringPair aIDRel("Id", sID);
+ auto pRel = std::find_if(aSeq.begin(), aSeq.end(),
+ [&aIDRel](const uno::Sequence<beans::StringPair>& rRel){
+ return std::find(rRel.begin(), rRel.end(), aIDRel) != rRel.end(); });
+ if (pRel != aSeq.end())
+ return *pRel;
+
+ throw container::NoSuchElementException();
+}
+
+uno::Sequence< uno::Sequence< beans::StringPair > > SAL_CALL OInputCompStream::getRelationshipsByType( const OUString& sType )
+{
+ ::osl::MutexGuard aGuard( m_xMutex->GetMutex() );
+
+ if ( m_bDisposed )
+ {
+ SAL_INFO("package.xstor", "Disposed!");
+ throw lang::DisposedException();
+ }
+
+ if ( m_nStorageType != embed::StorageFormats::OFOPXML )
+ throw uno::RuntimeException();
+
+ // TODO/LATER: in future the unification of the ID could be checked
+ const uno::Sequence< uno::Sequence< beans::StringPair > > aSeq = getAllRelationships();
+ const beans::StringPair aTypeRel("Type", sType);
+ std::vector< uno::Sequence<beans::StringPair> > aResult;
+ aResult.reserve(aSeq.getLength());
+
+ std::copy_if(aSeq.begin(), aSeq.end(), std::back_inserter(aResult),
+ [&aTypeRel](const uno::Sequence<beans::StringPair>& rRel) {
+ return std::find(rRel.begin(), rRel.end(), aTypeRel) != rRel.end(); });
+
+ return comphelper::containerToSequence(aResult);
+}
+
+uno::Sequence< uno::Sequence< beans::StringPair > > SAL_CALL OInputCompStream::getAllRelationships()
+{
+ ::osl::MutexGuard aGuard( m_xMutex->GetMutex() );
+
+ if ( m_bDisposed )
+ {
+ SAL_INFO("package.xstor", "Disposed!");
+ throw lang::DisposedException();
+ }
+
+ if ( m_nStorageType != embed::StorageFormats::OFOPXML )
+ throw uno::RuntimeException();
+
+ // TODO/LATER: in future the information could be taken directly from m_pImpl when possible
+ auto pProp = std::find_if(std::cbegin(m_aProperties), std::cend(m_aProperties),
+ [](const beans::PropertyValue& rProp) { return rProp.Name == "RelationsInfo"; });
+ if (pProp != std::cend(m_aProperties))
+ {
+ uno::Sequence< uno::Sequence< beans::StringPair > > aResult;
+ if (pProp->Value >>= aResult)
+ return aResult;
+ }
+
+ throw io::IOException("relations info could not be read"); // the relations info could not be read
+}
+
+void SAL_CALL OInputCompStream::insertRelationshipByID( const OUString& /*sID*/, const uno::Sequence< beans::StringPair >& /*aEntry*/, sal_Bool /*bReplace*/ )
+{
+ ::osl::MutexGuard aGuard( m_xMutex->GetMutex() );
+
+ if ( m_bDisposed )
+ {
+ SAL_INFO("package.xstor", "Disposed!");
+ throw lang::DisposedException();
+ }
+
+ if ( m_nStorageType != embed::StorageFormats::OFOPXML )
+ throw uno::RuntimeException();
+
+ throw io::IOException(); // TODO: Access denied
+}
+
+void SAL_CALL OInputCompStream::removeRelationshipByID( const OUString& /*sID*/ )
+{
+ ::osl::MutexGuard aGuard( m_xMutex->GetMutex() );
+
+ if ( m_bDisposed )
+ {
+ SAL_INFO("package.xstor", "Disposed!");
+ throw lang::DisposedException();
+ }
+
+ if ( m_nStorageType != embed::StorageFormats::OFOPXML )
+ throw uno::RuntimeException();
+
+ throw io::IOException(); // TODO: Access denied
+}
+
+void SAL_CALL OInputCompStream::insertRelationships( const uno::Sequence< uno::Sequence< beans::StringPair > >& /*aEntries*/, sal_Bool /*bReplace*/ )
+{
+ ::osl::MutexGuard aGuard( m_xMutex->GetMutex() );
+
+ if ( m_bDisposed )
+ {
+ SAL_INFO("package.xstor", "Disposed!");
+ throw lang::DisposedException();
+ }
+
+ if ( m_nStorageType != embed::StorageFormats::OFOPXML )
+ throw uno::RuntimeException();
+
+ throw io::IOException(); // TODO: Access denied
+}
+
+void SAL_CALL OInputCompStream::clearRelationships()
+{
+ ::osl::MutexGuard aGuard( m_xMutex->GetMutex() );
+
+ if ( m_bDisposed )
+ {
+ SAL_INFO("package.xstor", "Disposed!");
+ throw lang::DisposedException();
+ }
+
+ if ( m_nStorageType != embed::StorageFormats::OFOPXML )
+ throw uno::RuntimeException();
+
+ throw io::IOException(); // TODO: Access denied
+}
+
+uno::Reference< beans::XPropertySetInfo > SAL_CALL OInputCompStream::getPropertySetInfo()
+{
+ ::osl::MutexGuard aGuard( m_xMutex->GetMutex() );
+
+ if ( m_bDisposed )
+ {
+ SAL_INFO("package.xstor", "Disposed!");
+ throw lang::DisposedException();
+ }
+
+ //TODO:
+ return uno::Reference< beans::XPropertySetInfo >();
+}
+
+void SAL_CALL OInputCompStream::setPropertyValue( const OUString& aPropertyName, const uno::Any& /*aValue*/ )
+{
+ ::osl::MutexGuard aGuard( m_xMutex->GetMutex() );
+
+ if ( m_bDisposed )
+ {
+ SAL_INFO("package.xstor", "Disposed!");
+ throw lang::DisposedException();
+ }
+
+ // all the provided properties are accessible
+ if (std::any_of(std::cbegin(m_aProperties), std::cend(m_aProperties),
+ [&aPropertyName](const beans::PropertyValue& rProp) { return rProp.Name == aPropertyName; }))
+ throw beans::PropertyVetoException(); // TODO
+
+ throw beans::UnknownPropertyException(aPropertyName); // TODO
+}
+
+uno::Any SAL_CALL OInputCompStream::getPropertyValue( const OUString& aProp )
+{
+ ::osl::MutexGuard aGuard( m_xMutex->GetMutex() );
+
+ if ( m_bDisposed )
+ {
+ SAL_INFO("package.xstor", "Disposed!");
+ throw lang::DisposedException();
+ }
+
+ OUString aPropertyName;
+ if ( aProp == "IsEncrypted" )
+ aPropertyName = "Encrypted";
+ else
+ aPropertyName = aProp;
+
+ if ( aPropertyName == "RelationsInfo" )
+ throw beans::UnknownPropertyException(aPropertyName); // TODO
+
+ // all the provided properties are accessible
+ auto pProp = std::find_if(std::cbegin(m_aProperties), std::cend(m_aProperties),
+ [&aPropertyName](const beans::PropertyValue& rProp) { return rProp.Name == aPropertyName; });
+ if (pProp != std::cend(m_aProperties))
+ return pProp->Value;
+
+ throw beans::UnknownPropertyException(aPropertyName); // TODO
+}
+
+void SAL_CALL OInputCompStream::addPropertyChangeListener(
+ const OUString& /*aPropertyName*/,
+ const uno::Reference< beans::XPropertyChangeListener >& /*xListener*/ )
+{
+ ::osl::MutexGuard aGuard( m_xMutex->GetMutex() );
+
+ if ( m_bDisposed )
+ {
+ SAL_INFO("package.xstor", "Disposed!");
+ throw lang::DisposedException();
+ }
+
+ //TODO:
+}
+
+void SAL_CALL OInputCompStream::removePropertyChangeListener(
+ const OUString& /*aPropertyName*/,
+ const uno::Reference< beans::XPropertyChangeListener >& /*aListener*/ )
+{
+ ::osl::MutexGuard aGuard( m_xMutex->GetMutex() );
+
+ if ( m_bDisposed )
+ {
+ SAL_INFO("package.xstor", "Disposed!");
+ throw lang::DisposedException();
+ }
+
+ //TODO:
+}
+
+void SAL_CALL OInputCompStream::addVetoableChangeListener(
+ const OUString& /*PropertyName*/,
+ const uno::Reference< beans::XVetoableChangeListener >& /*aListener*/ )
+{
+ ::osl::MutexGuard aGuard( m_xMutex->GetMutex() );
+
+ if ( m_bDisposed )
+ {
+ SAL_INFO("package.xstor", "Disposed!");
+ throw lang::DisposedException();
+ }
+
+ //TODO:
+}
+
+void SAL_CALL OInputCompStream::removeVetoableChangeListener(
+ const OUString& /*PropertyName*/,
+ const uno::Reference< beans::XVetoableChangeListener >& /*aListener*/ )
+{
+ ::osl::MutexGuard aGuard( m_xMutex->GetMutex() );
+
+ if ( m_bDisposed )
+ {
+ SAL_INFO("package.xstor", "Disposed!");
+ throw lang::DisposedException();
+ }
+
+ //TODO:
+}
+
+/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
diff --git a/package/source/xstor/ocompinstream.hxx b/package/source/xstor/ocompinstream.hxx
new file mode 100644
index 000000000..4001cf118
--- /dev/null
+++ b/package/source/xstor/ocompinstream.hxx
@@ -0,0 +1,109 @@
+/* -*- 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 .
+ */
+
+#ifndef INCLUDED_PACKAGE_SOURCE_XSTOR_OCOMPINSTREAM_HXX
+#define INCLUDED_PACKAGE_SOURCE_XSTOR_OCOMPINSTREAM_HXX
+
+#include <com/sun/star/io/XInputStream.hpp>
+#include <com/sun/star/beans/XPropertySet.hpp>
+#include <com/sun/star/beans/PropertyValue.hpp>
+#include <com/sun/star/embed/XExtendedStorageStream.hpp>
+#include <com/sun/star/embed/XRelationshipAccess.hpp>
+#include <cppuhelper/implbase.hxx>
+#include <comphelper/interfacecontainer3.hxx>
+#include <comphelper/refcountedmutex.hxx>
+#include <rtl/ref.hxx>
+#include <memory>
+
+
+struct OWriteStream_Impl;
+
+class OInputCompStream : public cppu::WeakImplHelper < css::io::XInputStream
+ ,css::embed::XExtendedStorageStream
+ ,css::embed::XRelationshipAccess
+ ,css::beans::XPropertySet >
+{
+protected:
+ OWriteStream_Impl* m_pImpl;
+ rtl::Reference<comphelper::RefCountedMutex> m_xMutex;
+ css::uno::Reference < css::io::XInputStream > m_xStream;
+ std::unique_ptr<::comphelper::OInterfaceContainerHelper3<css::lang::XEventListener>> m_pInterfaceContainer;
+ css::uno::Sequence < css::beans::PropertyValue > m_aProperties;
+ bool m_bDisposed;
+ sal_Int32 m_nStorageType;
+
+public:
+ OInputCompStream( OWriteStream_Impl& pImpl,
+ css::uno::Reference< css::io::XInputStream > const & xStream,
+ const css::uno::Sequence< css::beans::PropertyValue >& aProps,
+ sal_Int32 nStorageType );
+
+ OInputCompStream( css::uno::Reference< css::io::XInputStream > const & xStream,
+ const css::uno::Sequence< css::beans::PropertyValue >& aProps,
+ sal_Int32 nStorageType );
+
+ virtual ~OInputCompStream() override;
+
+ void InternalDispose();
+
+ // XInterface
+ virtual css::uno::Any SAL_CALL queryInterface( const css::uno::Type& rType ) override;
+
+ // XInputStream
+ virtual sal_Int32 SAL_CALL readBytes( css::uno::Sequence< sal_Int8 >& aData, sal_Int32 nBytesToRead ) override;
+ virtual sal_Int32 SAL_CALL readSomeBytes( css::uno::Sequence< sal_Int8 >& aData, sal_Int32 nMaxBytesToRead ) override;
+ virtual void SAL_CALL skipBytes( sal_Int32 nBytesToSkip ) override;
+ virtual sal_Int32 SAL_CALL available( ) override;
+ virtual void SAL_CALL closeInput( ) override;
+
+ //XStream
+ virtual css::uno::Reference< css::io::XInputStream > SAL_CALL getInputStream( ) override;
+ virtual css::uno::Reference< css::io::XOutputStream > SAL_CALL getOutputStream( ) override;
+
+ //XComponent
+ virtual void SAL_CALL dispose( ) override;
+ virtual void SAL_CALL addEventListener( const css::uno::Reference< css::lang::XEventListener >& xListener ) override;
+ virtual void SAL_CALL removeEventListener( const css::uno::Reference< css::lang::XEventListener >& aListener ) override;
+
+ //XRelationshipAccess
+ virtual sal_Bool SAL_CALL hasByID( const OUString& sID ) override;
+ virtual OUString SAL_CALL getTargetByID( const OUString& sID ) override;
+ virtual OUString SAL_CALL getTypeByID( const OUString& sID ) override;
+ virtual css::uno::Sequence< css::beans::StringPair > SAL_CALL getRelationshipByID( const OUString& sID ) override;
+ virtual css::uno::Sequence< css::uno::Sequence< css::beans::StringPair > > SAL_CALL getRelationshipsByType( const OUString& sType ) override;
+ virtual css::uno::Sequence< css::uno::Sequence< css::beans::StringPair > > SAL_CALL getAllRelationships( ) override;
+ virtual void SAL_CALL insertRelationshipByID( const OUString& sID, const css::uno::Sequence< css::beans::StringPair >& aEntry, sal_Bool bReplace ) override;
+ virtual void SAL_CALL removeRelationshipByID( const OUString& sID ) override;
+ virtual void SAL_CALL insertRelationships( const css::uno::Sequence< css::uno::Sequence< css::beans::StringPair > >& aEntries, sal_Bool bReplace ) override;
+ virtual void SAL_CALL clearRelationships( ) override;
+
+ //XPropertySet
+ virtual css::uno::Reference< css::beans::XPropertySetInfo > SAL_CALL getPropertySetInfo() override;
+ virtual void SAL_CALL setPropertyValue( const OUString& aPropertyName, const css::uno::Any& aValue ) override;
+ virtual css::uno::Any SAL_CALL getPropertyValue( const OUString& PropertyName ) override;
+ virtual void SAL_CALL addPropertyChangeListener( const OUString& aPropertyName, const css::uno::Reference< css::beans::XPropertyChangeListener >& xListener ) override;
+ virtual void SAL_CALL removePropertyChangeListener( const OUString& aPropertyName, const css::uno::Reference< css::beans::XPropertyChangeListener >& aListener ) override;
+ virtual void SAL_CALL addVetoableChangeListener( const OUString& PropertyName, const css::uno::Reference< css::beans::XVetoableChangeListener >& aListener ) override;
+ virtual void SAL_CALL removeVetoableChangeListener( const OUString& PropertyName, const css::uno::Reference< css::beans::XVetoableChangeListener >& aListener ) override;
+
+};
+
+#endif
+
+/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
diff --git a/package/source/xstor/ohierarchyholder.cxx b/package/source/xstor/ohierarchyholder.cxx
new file mode 100644
index 000000000..209136bcd
--- /dev/null
+++ b/package/source/xstor/ohierarchyholder.cxx
@@ -0,0 +1,327 @@
+/* -*- 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 <sal/config.h>
+
+#include <com/sun/star/io/IOException.hpp>
+#include <com/sun/star/uno/Reference.hxx>
+#include <com/sun/star/embed/ElementModes.hpp>
+#include <com/sun/star/embed/XHierarchicalStorageAccess2.hpp>
+#include <com/sun/star/embed/XTransactedObject.hpp>
+#include <com/sun/star/embed/XTransactionBroadcaster.hpp>
+#include <com/sun/star/lang/IllegalArgumentException.hpp>
+#include <com/sun/star/lang/WrappedTargetRuntimeException.hpp>
+#include <cppuhelper/exc_hlp.hxx>
+#include <o3tl/string_view.hxx>
+
+#include "ohierarchyholder.hxx"
+
+using namespace ::com::sun::star;
+
+// OHierarchyHolder_Impl
+
+uno::Reference< embed::XExtendedStorageStream > OHierarchyHolder_Impl::GetStreamHierarchically( sal_Int32 nStorageMode, std::vector<OUString>& aListPath, sal_Int32 nStreamMode, const ::comphelper::SequenceAsHashMap& aEncryptionData )
+{
+ uno::Reference< embed::XStorage > xOwnStor( m_xWeakOwnStorage.get(), uno::UNO_QUERY_THROW );
+
+ if ( !( nStorageMode & embed::ElementModes::WRITE ) && ( nStreamMode & embed::ElementModes::WRITE ) )
+ throw io::IOException("invalid storage/stream mode combo");
+
+ uno::Reference< embed::XExtendedStorageStream > xResult =
+ m_xChild->GetStreamHierarchically( nStorageMode, aListPath, nStreamMode, aEncryptionData );
+ if ( !xResult.is() )
+ throw uno::RuntimeException();
+
+ return xResult;
+}
+
+void OHierarchyHolder_Impl::RemoveStreamHierarchically( std::vector<OUString>& aListPath )
+{
+ uno::Reference< embed::XStorage > xOwnStor( m_xWeakOwnStorage.get(), uno::UNO_QUERY_THROW );
+
+ m_xChild->RemoveStreamHierarchically( aListPath );
+}
+
+// static
+std::vector<OUString> OHierarchyHolder_Impl::GetListPathFromString( std::u16string_view aPath )
+{
+ std::vector<OUString> aResult;
+ sal_Int32 nIndex = 0;
+ do
+ {
+ OUString aName( o3tl::getToken(aPath, 0, '/', nIndex ) );
+ if ( aName.isEmpty() )
+ throw lang::IllegalArgumentException();
+
+ aResult.push_back( aName );
+ }
+ while ( nIndex >= 0 );
+
+ return aResult;
+}
+
+// OHierarchyElement_Impl
+
+uno::Reference< embed::XExtendedStorageStream > OHierarchyElement_Impl::GetStreamHierarchically( sal_Int32 nStorageMode, std::vector<OUString>& aListPath, sal_Int32 nStreamMode, const ::comphelper::SequenceAsHashMap& aEncryptionData )
+{
+ ::osl::MutexGuard aGuard( m_aMutex );
+
+ if ( !( nStorageMode & embed::ElementModes::WRITE ) && ( nStreamMode & embed::ElementModes::WRITE ) )
+ throw io::IOException("invalid storage/stream mode combo");
+
+ if ( aListPath.empty() )
+ throw uno::RuntimeException();
+
+ OUString aNextName = *(aListPath.begin());
+ aListPath.erase( aListPath.begin() );
+
+ uno::Reference< embed::XExtendedStorageStream > xResult;
+
+ uno::Reference< embed::XStorage > xOwnStor = m_xOwnStorage.is() ? m_xOwnStorage
+ : uno::Reference< embed::XStorage >( m_xWeakOwnStorage.get(), uno::UNO_QUERY_THROW );
+
+ if ( aListPath.empty() )
+ {
+ if ( aEncryptionData.empty() )
+ {
+ uno::Reference< embed::XHierarchicalStorageAccess > xHStorage( xOwnStor, uno::UNO_QUERY_THROW );
+ xResult = xHStorage->openStreamElementByHierarchicalName( aNextName, nStreamMode );
+ }
+ else
+ {
+ uno::Reference< embed::XHierarchicalStorageAccess2 > xHStorage( xOwnStor, uno::UNO_QUERY_THROW );
+ xResult = xHStorage->openEncryptedStreamByHierarchicalName( aNextName, nStreamMode, aEncryptionData.getAsConstNamedValueList() );
+ }
+
+ uno::Reference< embed::XTransactedObject > xTransact( xResult, uno::UNO_QUERY );
+ if ( xTransact.is() )
+ {
+ // the existence of the transacted object means that the stream is opened for writing also
+ // so the whole chain must be committed
+ uno::Reference< embed::XTransactionBroadcaster > xTrBroadcast( xTransact, uno::UNO_QUERY_THROW );
+ xTrBroadcast->addTransactionListener( static_cast< embed::XTransactionListener* >( this ) );
+ }
+ else
+ {
+ uno::Reference< lang::XComponent > xStreamComp( xResult, uno::UNO_QUERY_THROW );
+ xStreamComp->addEventListener( static_cast< lang::XEventListener* >( this ) );
+ }
+
+ m_aOpenStreams.emplace_back( xResult );
+ }
+ else
+ {
+ bool bNewElement = false;
+ ::rtl::Reference< OHierarchyElement_Impl > aElement;
+ OHierarchyElementList_Impl::iterator aIter = m_aChildren.find( aNextName );
+ if ( aIter != m_aChildren.end() )
+ aElement = aIter->second;
+
+ if ( !aElement.is() )
+ {
+ bNewElement = true;
+ uno::Reference< embed::XStorage > xChildStorage = xOwnStor->openStorageElement( aNextName, nStorageMode );
+ if ( !xChildStorage.is() )
+ throw uno::RuntimeException();
+
+ aElement = new OHierarchyElement_Impl( xChildStorage );
+ }
+
+ xResult = aElement->GetStreamHierarchically( nStorageMode, aListPath, nStreamMode, aEncryptionData );
+ if ( !xResult.is() )
+ throw uno::RuntimeException();
+
+ if ( bNewElement )
+ {
+ m_aChildren[aNextName] = aElement;
+ aElement->SetParent( this );
+ }
+ }
+
+ // the subelement was opened successfully, remember the storage to let it be locked
+ m_xOwnStorage = xOwnStor;
+
+ return xResult;
+}
+
+void OHierarchyElement_Impl::RemoveStreamHierarchically( std::vector<OUString>& aListPath )
+{
+ ::osl::MutexGuard aGuard( m_aMutex );
+
+ if ( aListPath.empty() )
+ throw uno::RuntimeException();
+
+ OUString aNextName = *(aListPath.begin());
+ aListPath.erase( aListPath.begin() );
+
+ uno::Reference< embed::XStorage > xOwnStor = m_xOwnStorage.is() ? m_xOwnStorage
+ : uno::Reference< embed::XStorage >( m_xWeakOwnStorage.get(), uno::UNO_QUERY_THROW );
+
+ if ( aListPath.empty() )
+ {
+ xOwnStor->removeElement( aNextName );
+ }
+ else
+ {
+ ::rtl::Reference< OHierarchyElement_Impl > aElement;
+ OHierarchyElementList_Impl::iterator aIter = m_aChildren.find( aNextName );
+ if ( aIter != m_aChildren.end() )
+ aElement = aIter->second;
+
+ if ( !aElement.is() )
+ {
+ uno::Reference< embed::XStorage > xChildStorage = xOwnStor->openStorageElement( aNextName,
+ embed::ElementModes::READWRITE );
+ if ( !xChildStorage.is() )
+ throw uno::RuntimeException();
+
+ aElement = new OHierarchyElement_Impl( xChildStorage );
+ }
+
+ aElement->RemoveStreamHierarchically( aListPath );
+ }
+
+ uno::Reference< embed::XTransactedObject > xTransact( xOwnStor, uno::UNO_QUERY );
+ if ( xTransact.is() )
+ xTransact->commit();
+
+ TestForClosing();
+}
+
+void OHierarchyElement_Impl::Commit()
+{
+ ::rtl::Reference< OHierarchyElement_Impl > xKeepAlive( this );
+ ::rtl::Reference< OHierarchyElement_Impl > aParent;
+ uno::Reference< embed::XStorage > xOwnStor;
+
+ {
+ ::osl::MutexGuard aGuard( m_aMutex );
+ aParent = m_rParent;
+ xOwnStor = m_xOwnStorage;
+ }
+
+ if ( xOwnStor.is() )
+ {
+ uno::Reference< embed::XTransactedObject > xTransact( xOwnStor, uno::UNO_QUERY_THROW );
+ xTransact->commit();
+ if ( aParent.is() )
+ aParent->Commit();
+ }
+}
+
+void OHierarchyElement_Impl::TestForClosing()
+{
+ ::rtl::Reference< OHierarchyElement_Impl > xKeepAlive( this );
+ {
+ ::osl::MutexGuard aGuard( m_aMutex );
+
+ if ( m_aOpenStreams.empty() && m_aChildren.empty() )
+ {
+ if ( m_rParent.is() )
+ {
+ // only the root storage should not be disposed, other storages can be disposed
+ if ( m_xOwnStorage.is() )
+ {
+ try
+ {
+ m_xOwnStorage->dispose();
+ }
+ catch( uno::Exception& )
+ {}
+ }
+
+ m_rParent->RemoveElement( this );
+ }
+
+ m_xOwnStorage.clear();
+ }
+ }
+}
+
+void SAL_CALL OHierarchyElement_Impl::disposing( const lang::EventObject& Source )
+{
+ try
+ {
+ {
+ osl::MutexGuard aGuard(m_aMutex);
+ uno::Reference< embed::XExtendedStorageStream > xStream(Source.Source, uno::UNO_QUERY);
+
+ m_aOpenStreams.erase(std::remove_if(m_aOpenStreams.begin(), m_aOpenStreams.end(),
+ [&xStream](const OWeakStorRefVector_Impl::value_type& rxStorage) {
+ return !rxStorage.get().is() || rxStorage.get() == xStream; }),
+ m_aOpenStreams.end());
+ }
+
+ TestForClosing();
+ }
+ catch( uno::Exception& ex )
+ {
+ css::uno::Any anyEx = cppu::getCaughtException();
+ throw lang::WrappedTargetRuntimeException( ex.Message,
+ nullptr, anyEx ); // no exception must happen here, usually an exception means disaster
+ }
+}
+
+void OHierarchyElement_Impl::RemoveElement( const ::rtl::Reference< OHierarchyElement_Impl >& aRef )
+{
+ {
+ ::osl::MutexGuard aGuard( m_aMutex );
+ OHierarchyElementList_Impl::iterator aIter = m_aChildren.begin();
+ while (aIter != m_aChildren.end())
+ {
+ if (aIter->second == aRef )
+ aIter = m_aChildren.erase(aIter);
+ else
+ ++aIter;
+ }
+ }
+
+ TestForClosing();
+}
+
+// XTransactionListener
+void SAL_CALL OHierarchyElement_Impl::preCommit( const css::lang::EventObject& /*aEvent*/ )
+{
+}
+
+void SAL_CALL OHierarchyElement_Impl::commited( const css::lang::EventObject& /*aEvent*/ )
+{
+ try
+ {
+ Commit();
+ }
+ catch( const uno::Exception& )
+ {
+ css::uno::Any anyEx = cppu::getCaughtException();
+ throw lang::WrappedTargetRuntimeException(
+ "Can not commit storage sequence!",
+ uno::Reference< uno::XInterface >(),
+ anyEx );
+ }
+}
+
+void SAL_CALL OHierarchyElement_Impl::preRevert( const css::lang::EventObject& /*aEvent*/ )
+{
+}
+
+void SAL_CALL OHierarchyElement_Impl::reverted( const css::lang::EventObject& /*aEvent*/ )
+{
+}
+
+/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
diff --git a/package/source/xstor/ohierarchyholder.hxx b/package/source/xstor/ohierarchyholder.hxx
new file mode 100644
index 000000000..6f32b3f40
--- /dev/null
+++ b/package/source/xstor/ohierarchyholder.hxx
@@ -0,0 +1,115 @@
+/* -*- 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 .
+ */
+
+#ifndef INCLUDED_PACKAGE_SOURCE_XSTOR_OHIERARCHYHOLDER_HXX
+#define INCLUDED_PACKAGE_SOURCE_XSTOR_OHIERARCHYHOLDER_HXX
+
+#include <com/sun/star/embed/XStorage.hpp>
+#include <com/sun/star/embed/XTransactionListener.hpp>
+#include <com/sun/star/embed/XExtendedStorageStream.hpp>
+#include <cppuhelper/implbase.hxx>
+#include <cppuhelper/weakref.hxx>
+
+#include <comphelper/sequenceashashmap.hxx>
+
+#include <rtl/ref.hxx>
+
+#include <unordered_map>
+#include <vector>
+
+class OHierarchyElement_Impl;
+
+typedef std::unordered_map< OUString,
+ ::rtl::Reference< OHierarchyElement_Impl > > OHierarchyElementList_Impl;
+
+typedef ::std::vector< css::uno::WeakReference< css::embed::XExtendedStorageStream > >
+ OWeakStorRefVector_Impl;
+
+class OHierarchyElement_Impl : public cppu::WeakImplHelper< css::embed::XTransactionListener >
+{
+ ::osl::Mutex m_aMutex;
+
+ ::rtl::Reference< OHierarchyElement_Impl > m_rParent;
+ css::uno::Reference< css::embed::XStorage > m_xOwnStorage;
+ css::uno::WeakReference< css::embed::XStorage > m_xWeakOwnStorage;
+
+ OHierarchyElementList_Impl m_aChildren;
+
+ OWeakStorRefVector_Impl m_aOpenStreams;
+
+public:
+ explicit OHierarchyElement_Impl( const css::uno::Reference< css::embed::XStorage >& xStorage )
+ : m_xOwnStorage( xStorage )
+ {}
+
+ explicit OHierarchyElement_Impl( const css::uno::WeakReference< css::embed::XStorage >& xWeakStorage )
+ : m_xWeakOwnStorage( xWeakStorage )
+ {}
+
+ void Commit();
+
+ void SetParent( const ::rtl::Reference< OHierarchyElement_Impl >& rParent ) { m_rParent = rParent; }
+
+ void TestForClosing();
+
+ void RemoveElement( const ::rtl::Reference< OHierarchyElement_Impl >& aRef );
+
+ css::uno::Reference< css::embed::XExtendedStorageStream >
+ GetStreamHierarchically( sal_Int32 nStorageMode,
+ std::vector<OUString>& aPath,
+ sal_Int32 nStreamMode,
+ const ::comphelper::SequenceAsHashMap& aEncryptionData );
+
+ void RemoveStreamHierarchically( std::vector<OUString>& aListPath );
+
+ // XEventListener
+ virtual void SAL_CALL disposing( const css::lang::EventObject& Source ) override;
+
+ // XTransactionListener
+ virtual void SAL_CALL preCommit( const css::lang::EventObject& aEvent ) override;
+ virtual void SAL_CALL commited( const css::lang::EventObject& aEvent ) override;
+ virtual void SAL_CALL preRevert( const css::lang::EventObject& aEvent ) override;
+ virtual void SAL_CALL reverted( const css::lang::EventObject& aEvent ) override;
+
+};
+
+class OHierarchyHolder_Impl : public ::cppu::OWeakObject
+{
+ css::uno::WeakReference< css::embed::XStorage > m_xWeakOwnStorage;
+ ::rtl::Reference< OHierarchyElement_Impl > m_xChild;
+public:
+ explicit OHierarchyHolder_Impl( const css::uno::Reference< css::embed::XStorage >& xOwnStorage )
+ : m_xWeakOwnStorage( xOwnStorage )
+ , m_xChild( new OHierarchyElement_Impl( css::uno::WeakReference< css::embed::XStorage >( xOwnStorage ) ) )
+ {}
+
+ static std::vector<OUString> GetListPathFromString( std::u16string_view aPath );
+
+ css::uno::Reference< css::embed::XExtendedStorageStream >
+ GetStreamHierarchically( sal_Int32 nStorageMode,
+ std::vector<OUString>& aListPath,
+ sal_Int32 nStreamMode,
+ const ::comphelper::SequenceAsHashMap& aEncryptionData = ::comphelper::SequenceAsHashMap() );
+
+ void RemoveStreamHierarchically( std::vector<OUString>& aListPath );
+};
+
+#endif // _OHIERARCHYHOLDER
+
+/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
diff --git a/package/source/xstor/oseekinstream.cxx b/package/source/xstor/oseekinstream.cxx
new file mode 100644
index 000000000..f5e3d644d
--- /dev/null
+++ b/package/source/xstor/oseekinstream.cxx
@@ -0,0 +1,144 @@
+/* -*- 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 <com/sun/star/lang/DisposedException.hpp>
+#include <cppuhelper/typeprovider.hxx>
+#include <cppuhelper/queryinterface.hxx>
+#include <osl/diagnose.h>
+#include <sal/log.hxx>
+
+#include "oseekinstream.hxx"
+#include "owriteablestream.hxx"
+
+using namespace ::com::sun::star;
+
+OInputSeekStream::OInputSeekStream( OWriteStream_Impl& pImpl,
+ uno::Reference < io::XInputStream > const & xStream,
+ const uno::Sequence< beans::PropertyValue >& aProps,
+ sal_Int32 nStorageType )
+: OInputCompStream( pImpl, xStream, aProps, nStorageType )
+{
+ m_xSeekable.set( m_xStream, uno::UNO_QUERY );
+ OSL_ENSURE( m_xSeekable.is(), "No seeking support!" );
+}
+
+OInputSeekStream::OInputSeekStream( uno::Reference < io::XInputStream > const & xStream,
+ const uno::Sequence< beans::PropertyValue >& aProps,
+ sal_Int32 nStorageType )
+: OInputCompStream( xStream, aProps, nStorageType )
+{
+ m_xSeekable.set( m_xStream, uno::UNO_QUERY );
+ OSL_ENSURE( m_xSeekable.is(), "No seeking support!" );
+}
+
+OInputSeekStream::~OInputSeekStream()
+{
+}
+
+uno::Sequence< uno::Type > SAL_CALL OInputSeekStream::getTypes()
+{
+ static cppu::OTypeCollection aTypeCollection(cppu::UnoType<io::XSeekable>::get(),
+ OInputCompStream::getTypes());
+
+ return aTypeCollection.getTypes();
+}
+
+uno::Any SAL_CALL OInputSeekStream::queryInterface( const uno::Type& rType )
+{
+ // Attention:
+ // Don't use mutex or guard in this method!!! Is a method of XInterface.
+
+ uno::Any aReturn( ::cppu::queryInterface( rType,
+ static_cast< io::XSeekable* >( this ) ) );
+
+ if ( aReturn.hasValue() )
+ {
+ return aReturn ;
+ }
+
+ return OInputCompStream::queryInterface( rType ) ;
+}
+
+void SAL_CALL OInputSeekStream::acquire()
+ noexcept
+{
+ OInputCompStream::acquire();
+}
+
+void SAL_CALL OInputSeekStream::release()
+ noexcept
+{
+ OInputCompStream::release();
+}
+
+void SAL_CALL OInputSeekStream::seek( sal_Int64 location )
+{
+ ::osl::MutexGuard aGuard( m_xMutex->GetMutex() );
+ if ( m_bDisposed )
+ {
+ SAL_INFO("package.xstor", "Disposed!");
+ throw lang::DisposedException();
+ }
+
+ if ( !m_xSeekable.is() )
+ {
+ SAL_INFO("package.xstor", "No seekable!");
+ throw uno::RuntimeException();
+ }
+
+ m_xSeekable->seek( location );
+}
+
+sal_Int64 SAL_CALL OInputSeekStream::getPosition()
+{
+ ::osl::MutexGuard aGuard( m_xMutex->GetMutex() );
+ if ( m_bDisposed )
+ {
+ SAL_INFO("package.xstor", "Disposed!");
+ throw lang::DisposedException();
+ }
+
+ if ( !m_xSeekable.is() )
+ {
+ SAL_INFO("package.xstor", "No seekable!");
+ throw uno::RuntimeException();
+ }
+
+ return m_xSeekable->getPosition();
+}
+
+sal_Int64 SAL_CALL OInputSeekStream::getLength()
+{
+ ::osl::MutexGuard aGuard( m_xMutex->GetMutex() );
+ if ( m_bDisposed )
+ {
+ SAL_INFO("package.xstor", "Disposed!");
+ throw lang::DisposedException();
+ }
+
+ if ( !m_xSeekable.is() )
+ {
+ SAL_INFO("package.xstor", "No seekable!");
+ throw uno::RuntimeException();
+ }
+
+ return m_xSeekable->getLength();
+}
+
+/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
diff --git a/package/source/xstor/oseekinstream.hxx b/package/source/xstor/oseekinstream.hxx
new file mode 100644
index 000000000..a77289e9a
--- /dev/null
+++ b/package/source/xstor/oseekinstream.hxx
@@ -0,0 +1,60 @@
+/* -*- 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 .
+ */
+
+#ifndef INCLUDED_PACKAGE_SOURCE_XSTOR_OSEEKINSTREAM_HXX
+#define INCLUDED_PACKAGE_SOURCE_XSTOR_OSEEKINSTREAM_HXX
+
+#include <com/sun/star/io/XSeekable.hpp>
+
+#include "ocompinstream.hxx"
+
+class OInputSeekStream final : public OInputCompStream
+ , public css::io::XSeekable
+{
+ css::uno::Reference < css::io::XSeekable > m_xSeekable;
+
+public:
+ OInputSeekStream( OWriteStream_Impl& pImpl,
+ css::uno::Reference < css::io::XInputStream > const & xStream,
+ const css::uno::Sequence< css::beans::PropertyValue >& aProps,
+ sal_Int32 nStorageType );
+
+ OInputSeekStream( css::uno::Reference < css::io::XInputStream > const & xStream,
+ const css::uno::Sequence< css::beans::PropertyValue >& aProps,
+ sal_Int32 nStorageType );
+
+ virtual ~OInputSeekStream() override;
+
+ virtual css::uno::Sequence< css::uno::Type > SAL_CALL getTypes() override;
+
+ // XInterface
+ virtual css::uno::Any SAL_CALL queryInterface( const css::uno::Type& rType ) override;
+ virtual void SAL_CALL acquire() noexcept override;
+ virtual void SAL_CALL release() noexcept override;
+
+ //XSeekable
+ virtual void SAL_CALL seek( sal_Int64 location ) override;
+ virtual sal_Int64 SAL_CALL getPosition() override;
+ virtual sal_Int64 SAL_CALL getLength() override;
+
+};
+
+#endif
+
+/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
diff --git a/package/source/xstor/owriteablestream.cxx b/package/source/xstor/owriteablestream.cxx
new file mode 100644
index 000000000..c9d012a61
--- /dev/null
+++ b/package/source/xstor/owriteablestream.cxx
@@ -0,0 +1,3276 @@
+/* -*- 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 <memory>
+#include <sal/config.h>
+#include <sal/log.hxx>
+
+#include <com/sun/star/packages/NoEncryptionException.hpp>
+#include <com/sun/star/packages/WrongPasswordException.hpp>
+#include <com/sun/star/uno/XComponentContext.hpp>
+#include <com/sun/star/ucb/SimpleFileAccess.hpp>
+#include <com/sun/star/lang/DisposedException.hpp>
+#include <com/sun/star/lang/XUnoTunnel.hpp>
+#include <com/sun/star/lang/XTypeProvider.hpp>
+#include <com/sun/star/io/NotConnectedException.hpp>
+#include <com/sun/star/io/TempFile.hpp>
+#include <com/sun/star/io/XInputStream.hpp>
+#include <com/sun/star/io/IOException.hpp>
+#include <com/sun/star/embed/ElementModes.hpp>
+#include <com/sun/star/embed/StorageFormats.hpp>
+#include <com/sun/star/embed/StorageWrappedTargetException.hpp>
+#include <com/sun/star/lang/WrappedTargetRuntimeException.hpp>
+#include <cppuhelper/typeprovider.hxx>
+#include <cppuhelper/queryinterface.hxx>
+#include <cppuhelper/exc_hlp.hxx>
+#include <osl/diagnose.h>
+
+#include <comphelper/processfactory.hxx>
+#include <comphelper/servicehelper.hxx>
+#include <comphelper/storagehelper.hxx>
+#include <comphelper/ofopxmlhelper.hxx>
+#include <comphelper/multicontainer2.hxx>
+#include <comphelper/refcountedmutex.hxx>
+#include <comphelper/sequence.hxx>
+
+#include <tools/diagnose_ex.h>
+
+#include <PackageConstants.hxx>
+
+#include "selfterminatefilestream.hxx"
+#include "owriteablestream.hxx"
+#include "oseekinstream.hxx"
+#include "xstorage.hxx"
+
+// since the copying uses 32000 blocks usually, it makes sense to have a smaller size
+#define MAX_STORCACHE_SIZE 30000
+
+using namespace ::com::sun::star;
+
+struct WSInternalData_Impl
+{
+ rtl::Reference<comphelper::RefCountedMutex> m_xSharedMutex;
+ ::std::unique_ptr< ::cppu::OTypeCollection> m_pTypeCollection;
+ comphelper::OMultiTypeInterfaceContainerHelper2 m_aListenersContainer; // list of listeners
+ sal_Int32 m_nStorageType;
+
+ // the mutex reference MUST NOT be empty
+ WSInternalData_Impl( const rtl::Reference<comphelper::RefCountedMutex>& rMutexRef, sal_Int32 nStorageType )
+ : m_xSharedMutex( rMutexRef )
+ , m_aListenersContainer( rMutexRef->GetMutex() )
+ , m_nStorageType( nStorageType )
+ {}
+};
+
+namespace package
+{
+
+bool PackageEncryptionDataLessOrEqual( const ::comphelper::SequenceAsHashMap& aHash1, const ::comphelper::SequenceAsHashMap& aHash2 )
+{
+ // tdf#93389: aHash2 may contain more than in aHash1, if it contains also data for other package
+ // formats (as in case of autorecovery)
+ bool bResult = !aHash1.empty() && aHash1.size() <= aHash2.size();
+ for ( ::comphelper::SequenceAsHashMap::const_iterator aIter = aHash1.begin();
+ bResult && aIter != aHash1.end();
+ ++aIter )
+ {
+ uno::Sequence< sal_Int8 > aKey1;
+ bResult = ( ( aIter->second >>= aKey1 ) && aKey1.hasElements() );
+ if ( bResult )
+ {
+ const uno::Sequence< sal_Int8 > aKey2 = aHash2.getUnpackedValueOrDefault( aIter->first.maString, uno::Sequence< sal_Int8 >() );
+ bResult = aKey1.getLength() == aKey2.getLength()
+ && std::equal(std::cbegin(aKey1), std::cend(aKey1), aKey2.begin(), aKey2.end());
+ }
+ }
+
+ return bResult;
+}
+
+} // namespace package
+
+namespace
+{
+
+void SetEncryptionKeyProperty_Impl( const uno::Reference< beans::XPropertySet >& xPropertySet,
+ const uno::Sequence< beans::NamedValue >& aKey )
+{
+ SAL_WARN_IF( !xPropertySet.is(), "package.xstor", "No property set is provided!" );
+ if ( !xPropertySet.is() )
+ throw uno::RuntimeException();
+
+ try {
+ xPropertySet->setPropertyValue( STORAGE_ENCRYPTION_KEYS_PROPERTY, uno::Any( aKey ) );
+ }
+ catch ( const uno::Exception& ex )
+ {
+ TOOLS_WARN_EXCEPTION( "package.xstor", "Can't write encryption related properties");
+ throw io::IOException(ex.Message); // TODO
+ }
+}
+
+uno::Any GetEncryptionKeyProperty_Impl( const uno::Reference< beans::XPropertySet >& xPropertySet )
+{
+ SAL_WARN_IF( !xPropertySet.is(), "package.xstor", "No property set is provided!" );
+ if ( !xPropertySet.is() )
+ throw uno::RuntimeException();
+
+ try {
+ return xPropertySet->getPropertyValue(STORAGE_ENCRYPTION_KEYS_PROPERTY);
+ }
+ catch ( const uno::Exception& ex )
+ {
+ TOOLS_WARN_EXCEPTION( "package.xstor", "Can't get encryption related properties");
+ throw io::IOException(ex.Message); // TODO
+ }
+}
+
+bool SequencesEqual( const uno::Sequence< sal_Int8 >& aSequence1, const uno::Sequence< sal_Int8 >& aSequence2 )
+{
+ return aSequence1.getLength() == aSequence2.getLength()
+ && std::equal(aSequence1.begin(), aSequence1.end(), aSequence2.begin(), aSequence2.end());
+}
+
+bool SequencesEqual( const uno::Sequence< beans::NamedValue >& aSequence1, const uno::Sequence< beans::NamedValue >& aSequence2 )
+{
+ if ( aSequence1.getLength() != aSequence2.getLength() )
+ return false;
+
+ for ( const auto& rProp1 : aSequence1 )
+ {
+ bool bHasMember = false;
+ uno::Sequence< sal_Int8 > aMember1;
+ sal_Int32 nMember1 = 0;
+ if ( rProp1.Value >>= aMember1 )
+ {
+ for ( const auto& rProp2 : aSequence2 )
+ {
+ if ( rProp1.Name == rProp2.Name )
+ {
+ bHasMember = true;
+
+ uno::Sequence< sal_Int8 > aMember2;
+ if ( !( rProp2.Value >>= aMember2 ) || !SequencesEqual( aMember1, aMember2 ) )
+ return false;
+ }
+ }
+ }
+ else if ( rProp1.Value >>= nMember1 )
+ {
+ for ( const auto& rProp2 : aSequence2 )
+ {
+ if ( rProp1.Name == rProp2.Name )
+ {
+ bHasMember = true;
+
+ sal_Int32 nMember2 = 0;
+ if ( !( rProp2.Value >>= nMember2 ) || nMember1 != nMember2 )
+ return false;
+ }
+ }
+ }
+ else
+ return false;
+
+ if ( !bHasMember )
+ return false;
+ }
+
+ return true;
+}
+
+bool KillFile( const OUString& aURL, const uno::Reference< uno::XComponentContext >& xContext )
+{
+ if ( !xContext.is() )
+ return false;
+
+ bool bRet = false;
+
+ try
+ {
+ uno::Reference < ucb::XSimpleFileAccess3 > xAccess( ucb::SimpleFileAccess::create( xContext ) );
+
+ xAccess->kill( aURL );
+ bRet = true;
+ }
+ catch( const uno::Exception& )
+ {
+ TOOLS_INFO_EXCEPTION("package.xstor", "Quiet exception");
+ }
+
+ return bRet;
+}
+
+OUString GetNewTempFileURL( const uno::Reference< uno::XComponentContext >& rContext )
+{
+ OUString aTempURL;
+
+ uno::Reference < io::XTempFile > xTempFile(
+ io::TempFile::create(rContext),
+ uno::UNO_SET_THROW );
+
+ try {
+ xTempFile->setRemoveFile( false );
+ aTempURL = xTempFile->getUri();
+ }
+ catch ( const uno::Exception& )
+ {
+ TOOLS_INFO_EXCEPTION("package.xstor", "Quiet exception");
+ }
+
+ if ( aTempURL.isEmpty() )
+ throw uno::RuntimeException("Cannot create tempfile.");
+
+ return aTempURL;
+}
+
+uno::Reference< io::XStream > CreateMemoryStream( const uno::Reference< uno::XComponentContext >& rContext )
+{
+ static constexpr OUStringLiteral sName(u"com.sun.star.comp.MemoryStream");
+ return uno::Reference< io::XStream >(
+ rContext->getServiceManager()->createInstanceWithContext(sName, rContext),
+ uno::UNO_QUERY_THROW);
+}
+
+const beans::StringPair* lcl_findPairByName(const uno::Sequence<beans::StringPair>& rSeq, const OUString& rName)
+{
+ return std::find_if(rSeq.begin(), rSeq.end(),
+ [&rName](const beans::StringPair& rPair) { return rPair.First == rName; });
+}
+
+} // anonymous namespace
+
+OWriteStream_Impl::OWriteStream_Impl( OStorage_Impl* pParent,
+ const uno::Reference< packages::XDataSinkEncrSupport >& xPackageStream,
+ const uno::Reference< lang::XSingleServiceFactory >& xPackage,
+ const uno::Reference< uno::XComponentContext >& rContext,
+ bool bForceEncrypted,
+ sal_Int32 nStorageType,
+ bool bDefaultCompress,
+ const uno::Reference< io::XInputStream >& xRelInfoStream )
+: m_xMutex( new comphelper::RefCountedMutex )
+, m_pAntiImpl( nullptr )
+, m_bHasDataToFlush( false )
+, m_bFlushed( false )
+, m_xPackageStream( xPackageStream )
+, m_xContext( rContext )
+, m_pParent( pParent )
+, m_bForceEncrypted( bForceEncrypted )
+, m_bUseCommonEncryption( !bForceEncrypted && nStorageType == embed::StorageFormats::PACKAGE )
+, m_bHasCachedEncryptionData( false )
+, m_bCompressedSetExplicit( !bDefaultCompress )
+, m_xPackage( xPackage )
+, m_bHasInsertedStreamOptimization( false )
+, m_nStorageType( nStorageType )
+, m_xOrigRelInfoStream( xRelInfoStream )
+, m_bOrigRelInfoBroken( false )
+, m_nRelInfoStatus( RELINFO_NO_INIT )
+, m_nRelId( 1 )
+{
+ SAL_WARN_IF( !xPackageStream.is(), "package.xstor", "No package stream is provided!" );
+ SAL_WARN_IF( !xPackage.is(), "package.xstor", "No package component is provided!" );
+ SAL_WARN_IF( !m_xContext.is(), "package.xstor", "No package stream is provided!" );
+ OSL_ENSURE( pParent, "No parent storage is provided!" );
+ OSL_ENSURE( m_nStorageType == embed::StorageFormats::OFOPXML || !m_xOrigRelInfoStream.is(), "The Relations info makes sense only for OFOPXML format!" );
+}
+
+OWriteStream_Impl::~OWriteStream_Impl()
+{
+ DisposeWrappers();
+
+ if ( !m_aTempURL.isEmpty() )
+ {
+ KillFile( m_aTempURL, comphelper::getProcessComponentContext() );
+ m_aTempURL.clear();
+ }
+
+ CleanCacheStream();
+}
+
+void OWriteStream_Impl::CleanCacheStream()
+{
+ if ( !m_xCacheStream.is() )
+ return;
+
+ try
+ {
+ uno::Reference< io::XInputStream > xInputCache = m_xCacheStream->getInputStream();
+ if ( xInputCache.is() )
+ xInputCache->closeInput();
+ }
+ catch( const uno::Exception& )
+ {}
+
+ try
+ {
+ uno::Reference< io::XOutputStream > xOutputCache = m_xCacheStream->getOutputStream();
+ if ( xOutputCache.is() )
+ xOutputCache->closeOutput();
+ }
+ catch( const uno::Exception& )
+ {}
+
+ m_xCacheStream.clear();
+ m_xCacheSeek.clear();
+}
+
+void OWriteStream_Impl::InsertIntoPackageFolder( const OUString& aName,
+ const uno::Reference< container::XNameContainer >& xParentPackageFolder )
+{
+ ::osl::MutexGuard aGuard( m_xMutex->GetMutex() );
+
+ SAL_WARN_IF( !m_bFlushed, "package.xstor", "This method must not be called for nonflushed streams!" );
+ if ( m_bFlushed )
+ {
+ SAL_WARN_IF( !m_xPackageStream.is(), "package.xstor", "An inserted stream is incomplete!" );
+ uno::Reference< lang::XUnoTunnel > xTunnel( m_xPackageStream, uno::UNO_QUERY_THROW );
+ xParentPackageFolder->insertByName( aName, uno::Any( xTunnel ) );
+
+ m_bFlushed = false;
+ m_bHasInsertedStreamOptimization = false;
+ }
+}
+bool OWriteStream_Impl::IsEncrypted()
+{
+ if ( m_nStorageType != embed::StorageFormats::PACKAGE )
+ return false;
+
+ if ( m_bForceEncrypted || m_bHasCachedEncryptionData )
+ return true;
+
+ if ( !m_aTempURL.isEmpty() || m_xCacheStream.is() )
+ return false;
+
+ GetStreamProperties();
+
+ // the following value can not be cached since it can change after root commit
+ bool bWasEncr = false;
+ uno::Reference< beans::XPropertySet > xPropSet( m_xPackageStream, uno::UNO_QUERY );
+ if ( xPropSet.is() )
+ {
+ uno::Any aValue = xPropSet->getPropertyValue("WasEncrypted");
+ if ( !( aValue >>= bWasEncr ) )
+ {
+ SAL_WARN( "package.xstor", "The property WasEncrypted has wrong type!" );
+ }
+ }
+
+ bool bToBeEncr = false;
+ for ( const auto& rProp : std::as_const(m_aProps) )
+ {
+ if ( rProp.Name == "Encrypted" )
+ {
+ if ( !( rProp.Value >>= bToBeEncr ) )
+ {
+ SAL_WARN( "package.xstor", "The property has wrong type!" );
+ }
+ }
+ }
+
+ // since a new key set to the package stream it should not be removed except the case when
+ // the stream becomes nonencrypted
+ uno::Sequence< beans::NamedValue > aKey;
+ if ( bToBeEncr )
+ GetEncryptionKeyProperty_Impl( xPropSet ) >>= aKey;
+
+ // If the properties must be investigated the stream is either
+ // was never changed or was changed, the parent was committed
+ // and the stream was closed.
+ // That means that if it is intended to use common storage key
+ // it is already has no encryption but is marked to be stored
+ // encrypted and the key is empty.
+ if ( !bWasEncr && bToBeEncr && !aKey.hasElements() )
+ {
+ // the stream is intended to use common storage password
+ m_bUseCommonEncryption = true;
+ return false;
+ }
+ else
+ return bToBeEncr;
+}
+
+void OWriteStream_Impl::SetDecrypted()
+{
+ SAL_WARN_IF( m_nStorageType != embed::StorageFormats::PACKAGE, "package.xstor", "The encryption is supported only for package storages!" );
+ if ( m_nStorageType != embed::StorageFormats::PACKAGE )
+ throw uno::RuntimeException();
+
+ GetStreamProperties();
+
+ // let the stream be modified
+ FillTempGetFileName();
+ m_bHasDataToFlush = true;
+
+ // remove encryption
+ m_bForceEncrypted = false;
+ m_bHasCachedEncryptionData = false;
+ m_aEncryptionData.clear();
+
+ for ( auto& rProp : asNonConstRange(m_aProps) )
+ {
+ if ( rProp.Name == "Encrypted" )
+ rProp.Value <<= false;
+ }
+}
+
+void OWriteStream_Impl::SetEncrypted( const ::comphelper::SequenceAsHashMap& aEncryptionData )
+{
+ SAL_WARN_IF( m_nStorageType != embed::StorageFormats::PACKAGE, "package.xstor", "The encryption is supported only for package storages!" );
+ if ( m_nStorageType != embed::StorageFormats::PACKAGE )
+ throw uno::RuntimeException();
+
+ if ( aEncryptionData.empty() )
+ throw uno::RuntimeException();
+
+ GetStreamProperties();
+
+ // let the stream be modified
+ FillTempGetFileName();
+ m_bHasDataToFlush = true;
+
+ // introduce encryption info
+ for ( auto& rProp : asNonConstRange(m_aProps) )
+ {
+ if ( rProp.Name == "Encrypted" )
+ rProp.Value <<= true;
+ }
+
+ m_bUseCommonEncryption = false; // very important to set it to false
+
+ m_bHasCachedEncryptionData = true;
+ m_aEncryptionData = aEncryptionData;
+}
+
+void OWriteStream_Impl::DisposeWrappers()
+{
+ ::osl::MutexGuard aGuard( m_xMutex->GetMutex() );
+ if ( m_pAntiImpl )
+ {
+ try {
+ m_pAntiImpl->dispose();
+ }
+ catch ( const uno::RuntimeException& )
+ {
+ TOOLS_INFO_EXCEPTION("package.xstor", "Quiet exception");
+ }
+
+ m_pAntiImpl = nullptr;
+ }
+ m_pParent = nullptr;
+
+ if ( m_aInputStreamsVector.empty() )
+ return;
+
+ for ( auto& pStream : m_aInputStreamsVector )
+ {
+ if ( pStream )
+ {
+ pStream->InternalDispose();
+ pStream = nullptr;
+ }
+ }
+
+ m_aInputStreamsVector.clear();
+}
+
+OUString const & OWriteStream_Impl::GetFilledTempFileIfNo( const uno::Reference< io::XInputStream >& xStream )
+{
+ if ( !m_aTempURL.getLength() )
+ {
+ OUString aTempURL = GetNewTempFileURL( m_xContext );
+
+ try {
+ if ( !aTempURL.isEmpty() && xStream.is() )
+ {
+ uno::Reference < ucb::XSimpleFileAccess3 > xTempAccess( ucb::SimpleFileAccess::create( ::comphelper::getProcessComponentContext() ) );
+
+ uno::Reference< io::XOutputStream > xTempOutStream = xTempAccess->openFileWrite( aTempURL );
+ if ( !xTempOutStream.is() )
+ throw io::IOException("no temp stream"); // TODO:
+ // the current position of the original stream should be still OK, copy further
+ ::comphelper::OStorageHelper::CopyInputToOutput( xStream, xTempOutStream );
+ xTempOutStream->closeOutput();
+ xTempOutStream.clear();
+ }
+ }
+ catch( const packages::WrongPasswordException& )
+ {
+ TOOLS_INFO_EXCEPTION("package.xstor", "Rethrow");
+ KillFile( aTempURL, comphelper::getProcessComponentContext() );
+ throw;
+ }
+ catch( const uno::Exception& )
+ {
+ TOOLS_INFO_EXCEPTION("package.xstor", "Rethrow");
+ KillFile( aTempURL, comphelper::getProcessComponentContext() );
+ throw;
+ }
+
+ if ( !aTempURL.isEmpty() )
+ CleanCacheStream();
+
+ m_aTempURL = aTempURL;
+ }
+
+ return m_aTempURL;
+}
+
+OUString const & OWriteStream_Impl::FillTempGetFileName()
+{
+ // should try to create cache first, if the amount of contents is too big, the temp file should be taken
+ if ( !m_xCacheStream.is() && m_aTempURL.isEmpty() )
+ {
+ uno::Reference< io::XInputStream > xOrigStream = m_xPackageStream->getDataStream();
+ if ( !xOrigStream.is() )
+ {
+ // in case of new inserted package stream it is possible that input stream still was not set
+ uno::Reference< io::XStream > xCacheStream = CreateMemoryStream( m_xContext );
+ SAL_WARN_IF( !xCacheStream.is(), "package.xstor", "If the stream can not be created an exception must be thrown!" );
+ m_xCacheSeek.set( xCacheStream, uno::UNO_QUERY_THROW );
+ m_xCacheStream = xCacheStream;
+ }
+ else
+ {
+ sal_Int32 nRead = 0;
+ uno::Sequence< sal_Int8 > aData( MAX_STORCACHE_SIZE + 1 );
+ nRead = xOrigStream->readBytes( aData, MAX_STORCACHE_SIZE + 1 );
+ if ( aData.getLength() > nRead )
+ aData.realloc( nRead );
+
+ if ( nRead <= MAX_STORCACHE_SIZE )
+ {
+ uno::Reference< io::XStream > xCacheStream = CreateMemoryStream( m_xContext );
+ SAL_WARN_IF( !xCacheStream.is(), "package.xstor", "If the stream can not be created an exception must be thrown!" );
+
+ if ( nRead )
+ {
+ uno::Reference< io::XOutputStream > xOutStream( xCacheStream->getOutputStream(), uno::UNO_SET_THROW );
+ xOutStream->writeBytes( aData );
+ }
+ m_xCacheSeek.set( xCacheStream, uno::UNO_QUERY_THROW );
+ m_xCacheStream = xCacheStream;
+ m_xCacheSeek->seek( 0 );
+ }
+ else if ( m_aTempURL.isEmpty() )
+ {
+ m_aTempURL = GetNewTempFileURL( m_xContext );
+
+ try {
+ if ( !m_aTempURL.isEmpty() )
+ {
+ uno::Reference < ucb::XSimpleFileAccess3 > xTempAccess( ucb::SimpleFileAccess::create( ::comphelper::getProcessComponentContext() ) );
+
+ uno::Reference< io::XOutputStream > xTempOutStream = xTempAccess->openFileWrite( m_aTempURL );
+ if ( !xTempOutStream.is() )
+ throw io::IOException("no temp stream"); // TODO:
+
+ // copy stream contents to the file
+ xTempOutStream->writeBytes( aData );
+
+ // the current position of the original stream should be still OK, copy further
+ ::comphelper::OStorageHelper::CopyInputToOutput( xOrigStream, xTempOutStream );
+ xTempOutStream->closeOutput();
+ xTempOutStream.clear();
+ }
+ }
+ catch( const packages::WrongPasswordException& )
+ {
+ KillFile( m_aTempURL, comphelper::getProcessComponentContext() );
+ m_aTempURL.clear();
+
+ throw;
+ }
+ catch( const uno::Exception& )
+ {
+ KillFile( m_aTempURL, comphelper::getProcessComponentContext() );
+ m_aTempURL.clear();
+ }
+ }
+ }
+ }
+
+ return m_aTempURL;
+}
+
+uno::Reference< io::XStream > OWriteStream_Impl::GetTempFileAsStream()
+{
+ uno::Reference< io::XStream > xTempStream;
+
+ if ( !m_xCacheStream.is() )
+ {
+ if ( m_aTempURL.isEmpty() )
+ m_aTempURL = FillTempGetFileName();
+
+ if ( !m_aTempURL.isEmpty() )
+ {
+ // the temporary file is not used if the cache is used
+ uno::Reference < ucb::XSimpleFileAccess3 > xTempAccess( ucb::SimpleFileAccess::create( ::comphelper::getProcessComponentContext() ) );
+
+ try
+ {
+ xTempStream = xTempAccess->openFileReadWrite( m_aTempURL );
+ }
+ catch( const uno::Exception& )
+ {
+ TOOLS_INFO_EXCEPTION("package.xstor", "Quiet exception");
+ }
+ }
+ }
+
+ if ( m_xCacheStream.is() )
+ xTempStream = m_xCacheStream;
+
+ // the method must always return a stream
+ // in case the stream can not be open
+ // an exception should be thrown
+ if ( !xTempStream.is() )
+ throw io::IOException("no temp stream"); //TODO:
+
+ return xTempStream;
+}
+
+uno::Reference< io::XInputStream > OWriteStream_Impl::GetTempFileAsInputStream()
+{
+ uno::Reference< io::XInputStream > xInputStream;
+
+ if ( !m_xCacheStream.is() )
+ {
+ if ( m_aTempURL.isEmpty() )
+ m_aTempURL = FillTempGetFileName();
+
+ if ( !m_aTempURL.isEmpty() )
+ {
+ // the temporary file is not used if the cache is used
+ uno::Reference < ucb::XSimpleFileAccess3 > xTempAccess( ucb::SimpleFileAccess::create( ::comphelper::getProcessComponentContext() ) );
+
+ try
+ {
+ xInputStream = xTempAccess->openFileRead( m_aTempURL );
+ }
+ catch( const uno::Exception& )
+ {
+ TOOLS_INFO_EXCEPTION("package.xstor", "Quiet exception");
+ }
+ }
+ }
+
+ if ( m_xCacheStream.is() )
+ xInputStream = m_xCacheStream->getInputStream();
+
+ // the method must always return a stream
+ // in case the stream can not be open
+ // an exception should be thrown
+ if ( !xInputStream.is() )
+ throw io::IOException(); // TODO:
+
+ return xInputStream;
+}
+
+void OWriteStream_Impl::InsertStreamDirectly( const uno::Reference< io::XInputStream >& xInStream,
+ const uno::Sequence< beans::PropertyValue >& aProps )
+{
+ ::osl::MutexGuard aGuard( m_xMutex->GetMutex() ) ;
+
+ // this call can be made only during parent storage commit
+ // the parent storage is responsible for the correct handling
+ // of deleted and renamed contents
+
+ SAL_WARN_IF( !m_xPackageStream.is(), "package.xstor", "No package stream is set!" );
+
+ if ( m_bHasDataToFlush )
+ throw io::IOException("m_bHasDataToFlush==true");
+
+ OSL_ENSURE( m_aTempURL.isEmpty() && !m_xCacheStream.is(), "The temporary must not exist!" );
+
+ // use new file as current persistent representation
+ // the new file will be removed after it's stream is closed
+ m_xPackageStream->setDataStream( xInStream );
+
+ // copy properties to the package stream
+ uno::Reference< beans::XPropertySet > xPropertySet( m_xPackageStream, uno::UNO_QUERY_THROW );
+
+ // The storage-package communication has a problem
+ // the storage caches properties, thus if the package changes one of them itself
+ // the storage does not know about it
+
+ // Depending from MediaType value the package can change the compressed property itself
+ // Thus if Compressed property is provided it must be set as the latest one
+ bool bCompressedIsSet = false;
+ bool bCompressed = false;
+ OUString aComprPropName( "Compressed" );
+ OUString aMedTypePropName( "MediaType" );
+ for ( const auto& rProp : aProps )
+ {
+ if ( rProp.Name == aComprPropName )
+ {
+ bCompressedIsSet = true;
+ rProp.Value >>= bCompressed;
+ }
+ else if ( ( m_nStorageType == embed::StorageFormats::OFOPXML || m_nStorageType == embed::StorageFormats::PACKAGE )
+ && rProp.Name == aMedTypePropName )
+ {
+ xPropertySet->setPropertyValue( rProp.Name, rProp.Value );
+ }
+ else if ( m_nStorageType == embed::StorageFormats::PACKAGE && rProp.Name == "UseCommonStoragePasswordEncryption" )
+ rProp.Value >>= m_bUseCommonEncryption;
+ else
+ throw lang::IllegalArgumentException();
+
+ // if there are cached properties update them
+ if ( rProp.Name == aMedTypePropName || rProp.Name == aComprPropName )
+ for ( auto& rMemProp : asNonConstRange(m_aProps) )
+ {
+ if ( rProp.Name == rMemProp.Name )
+ rMemProp.Value = rProp.Value;
+ }
+ }
+
+ if ( bCompressedIsSet )
+ {
+ xPropertySet->setPropertyValue( aComprPropName, uno::Any( bCompressed ) );
+ m_bCompressedSetExplicit = true;
+ }
+
+ if ( m_bUseCommonEncryption )
+ {
+ if ( m_nStorageType != embed::StorageFormats::PACKAGE )
+ throw uno::RuntimeException();
+
+ // set to be encrypted but do not use encryption key
+ xPropertySet->setPropertyValue( STORAGE_ENCRYPTION_KEYS_PROPERTY,
+ uno::Any( uno::Sequence< beans::NamedValue >() ) );
+ xPropertySet->setPropertyValue( "Encrypted", uno::Any( true ) );
+ }
+
+ // the stream should be free soon, after package is stored
+ m_bHasDataToFlush = false;
+ m_bFlushed = true; // will allow to use transaction on stream level if will need it
+ m_bHasInsertedStreamOptimization = true;
+}
+
+void OWriteStream_Impl::Commit()
+{
+ ::osl::MutexGuard aGuard( m_xMutex->GetMutex() ) ;
+
+ SAL_WARN_IF( !m_xPackageStream.is(), "package.xstor", "No package stream is set!" );
+
+ if ( !m_bHasDataToFlush )
+ return;
+
+ uno::Reference< packages::XDataSinkEncrSupport > xNewPackageStream;
+ uno::Sequence< uno::Any > aSeq{ uno::Any(false) };
+
+ if ( m_xCacheStream.is() )
+ {
+ if ( m_pAntiImpl )
+ m_pAntiImpl->DeInit();
+
+ uno::Reference< io::XInputStream > xInStream( m_xCacheStream->getInputStream(), uno::UNO_SET_THROW );
+
+ xNewPackageStream.set( m_xPackage->createInstanceWithArguments( aSeq ), uno::UNO_QUERY_THROW );
+
+ xNewPackageStream->setDataStream( xInStream );
+
+ m_xCacheStream.clear();
+ m_xCacheSeek.clear();
+
+ }
+ else if ( !m_aTempURL.isEmpty() )
+ {
+ if ( m_pAntiImpl )
+ m_pAntiImpl->DeInit();
+
+ uno::Reference< io::XInputStream > xInStream;
+ try
+ {
+ xInStream = new OSelfTerminateFileStream(m_xContext, m_aTempURL);
+ }
+ catch( const uno::Exception& )
+ {
+ }
+
+ if ( !xInStream.is() )
+ throw io::IOException();
+
+ xNewPackageStream.set( m_xPackage->createInstanceWithArguments( aSeq ), uno::UNO_QUERY_THROW );
+
+ // TODO/NEW: Let the temporary file be removed after commit
+ xNewPackageStream->setDataStream( xInStream );
+ m_aTempURL.clear();
+ }
+ else // if ( m_bHasInsertedStreamOptimization )
+ {
+ // if the optimization is used the stream can be accessed directly
+ xNewPackageStream = m_xPackageStream;
+ }
+
+ // copy properties to the package stream
+ uno::Reference< beans::XPropertySet > xPropertySet( xNewPackageStream, uno::UNO_QUERY_THROW );
+
+ for ( auto& rProp : asNonConstRange(m_aProps) )
+ {
+ if ( rProp.Name == "Size" )
+ {
+ if ( m_pAntiImpl && !m_bHasInsertedStreamOptimization && m_pAntiImpl->m_xSeekable.is() )
+ {
+ rProp.Value <<= m_pAntiImpl->m_xSeekable->getLength();
+ xPropertySet->setPropertyValue( rProp.Name, rProp.Value );
+ }
+ }
+ else
+ xPropertySet->setPropertyValue( rProp.Name, rProp.Value );
+ }
+
+ if ( m_bUseCommonEncryption )
+ {
+ if ( m_nStorageType != embed::StorageFormats::PACKAGE )
+ throw uno::RuntimeException();
+
+ // set to be encrypted but do not use encryption key
+ xPropertySet->setPropertyValue( STORAGE_ENCRYPTION_KEYS_PROPERTY,
+ uno::Any( uno::Sequence< beans::NamedValue >() ) );
+ xPropertySet->setPropertyValue( "Encrypted",
+ uno::Any( true ) );
+ }
+ else if ( m_bHasCachedEncryptionData )
+ {
+ if ( m_nStorageType != embed::StorageFormats::PACKAGE )
+ throw uno::RuntimeException();
+
+ xPropertySet->setPropertyValue( STORAGE_ENCRYPTION_KEYS_PROPERTY,
+ uno::Any( m_aEncryptionData.getAsConstNamedValueList() ) );
+ }
+
+ // the stream should be free soon, after package is stored
+ m_xPackageStream = xNewPackageStream;
+ m_bHasDataToFlush = false;
+ m_bFlushed = true; // will allow to use transaction on stream level if will need it
+}
+
+void OWriteStream_Impl::Revert()
+{
+ // can be called only from parent storage
+ // means complete reload of the stream
+
+ ::osl::MutexGuard aGuard( m_xMutex->GetMutex() ) ;
+
+ if ( !m_bHasDataToFlush )
+ return; // nothing to do
+
+ OSL_ENSURE( !m_aTempURL.isEmpty() || m_xCacheStream.is(), "The temporary must exist!" );
+
+ if ( m_xCacheStream.is() )
+ {
+ m_xCacheStream.clear();
+ m_xCacheSeek.clear();
+ }
+
+ if ( !m_aTempURL.isEmpty() )
+ {
+ KillFile( m_aTempURL, comphelper::getProcessComponentContext() );
+ m_aTempURL.clear();
+ }
+
+ m_aProps.realloc( 0 );
+
+ m_bHasDataToFlush = false;
+
+ m_bUseCommonEncryption = true;
+ m_bHasCachedEncryptionData = false;
+ m_aEncryptionData.clear();
+
+ if ( m_nStorageType != embed::StorageFormats::OFOPXML )
+ return;
+
+ // currently the relations storage is changed only on commit
+ m_xNewRelInfoStream.clear();
+ m_aNewRelInfo = uno::Sequence< uno::Sequence< beans::StringPair > >();
+ if ( m_xOrigRelInfoStream.is() )
+ {
+ // the original stream is still here, that means that it was not parsed
+ m_aOrigRelInfo = uno::Sequence< uno::Sequence< beans::StringPair > >();
+ m_nRelInfoStatus = RELINFO_NO_INIT;
+ }
+ else
+ {
+ // the original stream was already parsed
+ if ( !m_bOrigRelInfoBroken )
+ m_nRelInfoStatus = RELINFO_READ;
+ else
+ m_nRelInfoStatus = RELINFO_BROKEN;
+ }
+}
+
+uno::Sequence< beans::PropertyValue > const & OWriteStream_Impl::GetStreamProperties()
+{
+ if ( !m_aProps.hasElements() )
+ m_aProps = ReadPackageStreamProperties();
+
+ return m_aProps;
+}
+
+uno::Sequence< beans::PropertyValue > OWriteStream_Impl::InsertOwnProps(
+ const uno::Sequence< beans::PropertyValue >& aProps,
+ bool bUseCommonEncryption )
+{
+ uno::Sequence< beans::PropertyValue > aResult( aProps );
+ beans::PropertyValue aPropVal;
+
+ if ( m_nStorageType == embed::StorageFormats::PACKAGE )
+ {
+ aPropVal.Name = "UseCommonStoragePasswordEncryption";
+ aPropVal.Value <<= bUseCommonEncryption;
+ }
+ else if ( m_nStorageType == embed::StorageFormats::OFOPXML )
+ {
+ ReadRelInfoIfNecessary();
+
+ aPropVal.Name = "RelationsInfo";
+ if ( m_nRelInfoStatus == RELINFO_READ )
+ aPropVal.Value <<= m_aOrigRelInfo;
+ else if ( m_nRelInfoStatus == RELINFO_CHANGED_STREAM_READ || m_nRelInfoStatus == RELINFO_CHANGED )
+ aPropVal.Value <<= m_aNewRelInfo;
+ else // m_nRelInfoStatus == RELINFO_CHANGED_BROKEN || m_nRelInfoStatus == RELINFO_BROKEN
+ throw io::IOException( "Wrong relinfo stream!" );
+ }
+ if (!aPropVal.Name.isEmpty())
+ {
+ sal_Int32 i = 0;
+ for (auto p = aResult.getConstArray(); i < aResult.getLength(); ++i)
+ if (p[i].Name == aPropVal.Name)
+ break;
+ if (i == aResult.getLength())
+ aResult.realloc(i + 1);
+ aResult.getArray()[i] = aPropVal;
+ }
+
+ return aResult;
+}
+
+bool OWriteStream_Impl::IsTransacted()
+{
+ ::osl::MutexGuard aGuard( m_xMutex->GetMutex() ) ;
+ return ( m_pAntiImpl && m_pAntiImpl->m_bTransacted );
+}
+
+void OWriteStream_Impl::ReadRelInfoIfNecessary()
+{
+ if ( m_nStorageType != embed::StorageFormats::OFOPXML )
+ return;
+
+ if ( m_nRelInfoStatus == RELINFO_NO_INIT )
+ {
+ try
+ {
+ // Init from original stream
+ if ( m_xOrigRelInfoStream.is() )
+ m_aOrigRelInfo = ::comphelper::OFOPXMLHelper::ReadRelationsInfoSequence(
+ m_xOrigRelInfoStream,
+ u"_rels/*.rels",
+ m_xContext );
+
+ // in case of success the stream must be thrown away, that means that the OrigRelInfo is initialized
+ // the reason for this is that the original stream might not be seekable ( at the same time the new
+ // provided stream must be seekable ), so it must be read only once
+ m_xOrigRelInfoStream.clear();
+ m_nRelInfoStatus = RELINFO_READ;
+ }
+ catch( const uno::Exception& )
+ {
+ TOOLS_INFO_EXCEPTION("package.xstor", "Quiet exception");
+
+ m_nRelInfoStatus = RELINFO_BROKEN;
+ m_bOrigRelInfoBroken = true;
+ }
+ }
+ else if ( m_nRelInfoStatus == RELINFO_CHANGED_STREAM )
+ {
+ // Init from the new stream
+ try
+ {
+ if ( m_xNewRelInfoStream.is() )
+ m_aNewRelInfo = ::comphelper::OFOPXMLHelper::ReadRelationsInfoSequence(
+ m_xNewRelInfoStream,
+ u"_rels/*.rels",
+ m_xContext );
+
+ m_nRelInfoStatus = RELINFO_CHANGED_STREAM_READ;
+ }
+ catch( const uno::Exception& )
+ {
+ m_nRelInfoStatus = RELINFO_CHANGED_BROKEN;
+ }
+ }
+}
+
+uno::Sequence< beans::PropertyValue > OWriteStream_Impl::ReadPackageStreamProperties()
+{
+ sal_Int32 nPropNum = 0;
+ if ( m_nStorageType == embed::StorageFormats::ZIP )
+ nPropNum = 2;
+ else if ( m_nStorageType == embed::StorageFormats::OFOPXML )
+ nPropNum = 3;
+ else if ( m_nStorageType == embed::StorageFormats::PACKAGE )
+ nPropNum = 4;
+ assert(nPropNum >= 2);
+ uno::Sequence< beans::PropertyValue > aResult( nPropNum );
+ auto aResultRange = asNonConstRange(aResult);
+
+ // The "Compressed" property must be set after "MediaType" property,
+ // since the setting of the last one can change the value of the first one
+ static constexpr OUStringLiteral sMediaType = u"MediaType";
+ static constexpr OUStringLiteral sCompressed = u"Compressed";
+ static constexpr OUStringLiteral sSize = u"Size";
+ static constexpr OUStringLiteral sEncrypted = u"Encrypted";
+ if ( m_nStorageType == embed::StorageFormats::OFOPXML || m_nStorageType == embed::StorageFormats::PACKAGE )
+ {
+ aResultRange[0].Name = sMediaType;
+ aResultRange[1].Name = sCompressed;
+ aResultRange[2].Name = sSize;
+
+ if ( m_nStorageType == embed::StorageFormats::PACKAGE )
+ aResultRange[3].Name = sEncrypted;
+ }
+ else
+ {
+ aResultRange[0].Name = sCompressed;
+ aResultRange[1].Name = sSize;
+ }
+
+ // TODO: may be also raw stream should be marked
+
+ uno::Reference< beans::XPropertySet > xPropSet( m_xPackageStream, uno::UNO_QUERY_THROW );
+ for ( auto& rProp : aResultRange )
+ {
+ try {
+ rProp.Value = xPropSet->getPropertyValue( rProp.Name );
+ }
+ catch( const uno::Exception& )
+ {
+ TOOLS_WARN_EXCEPTION( "package.xstor", "A property can't be retrieved" );
+ }
+ }
+
+ return aResult;
+}
+
+void OWriteStream_Impl::CopyInternallyTo_Impl( const uno::Reference< io::XStream >& xDestStream,
+ const ::comphelper::SequenceAsHashMap& aEncryptionData )
+{
+ ::osl::MutexGuard aGuard( m_xMutex->GetMutex() ) ;
+
+ SAL_WARN_IF( m_bUseCommonEncryption, "package.xstor", "The stream can not be encrypted!" );
+
+ if ( m_nStorageType != embed::StorageFormats::PACKAGE )
+ throw packages::NoEncryptionException();
+
+ if ( m_pAntiImpl )
+ {
+ m_pAntiImpl->CopyToStreamInternally_Impl( xDestStream );
+ }
+ else
+ {
+ uno::Reference< io::XStream > xOwnStream = GetStream( embed::ElementModes::READ, aEncryptionData, false );
+ if ( !xOwnStream.is() )
+ throw io::IOException(); // TODO
+
+ OStorage_Impl::completeStorageStreamCopy_Impl( xOwnStream, xDestStream, m_nStorageType, GetAllRelationshipsIfAny() );
+ }
+
+ uno::Reference< embed::XEncryptionProtectedSource2 > xEncr( xDestStream, uno::UNO_QUERY );
+ if ( xEncr.is() )
+ xEncr->setEncryptionData( aEncryptionData.getAsConstNamedValueList() );
+}
+
+uno::Sequence< uno::Sequence< beans::StringPair > > OWriteStream_Impl::GetAllRelationshipsIfAny()
+{
+ if ( m_nStorageType != embed::StorageFormats::OFOPXML )
+ return uno::Sequence< uno::Sequence< beans::StringPair > >();
+
+ ReadRelInfoIfNecessary();
+
+ if ( m_nRelInfoStatus == RELINFO_READ )
+ return m_aOrigRelInfo;
+ else if ( m_nRelInfoStatus == RELINFO_CHANGED_STREAM_READ || m_nRelInfoStatus == RELINFO_CHANGED )
+ return m_aNewRelInfo;
+ else // m_nRelInfoStatus == RELINFO_CHANGED_BROKEN || m_nRelInfoStatus == RELINFO_BROKEN
+ throw io::IOException( "Wrong relinfo stream!" );
+}
+
+void OWriteStream_Impl::CopyInternallyTo_Impl( const uno::Reference< io::XStream >& xDestStream )
+{
+ ::osl::MutexGuard aGuard( m_xMutex->GetMutex() ) ;
+
+ if ( m_pAntiImpl )
+ {
+ m_pAntiImpl->CopyToStreamInternally_Impl( xDestStream );
+ }
+ else
+ {
+ uno::Reference< io::XStream > xOwnStream = GetStream( embed::ElementModes::READ, false );
+ if ( !xOwnStream.is() )
+ throw io::IOException(); // TODO
+
+ OStorage_Impl::completeStorageStreamCopy_Impl( xOwnStream, xDestStream, m_nStorageType, GetAllRelationshipsIfAny() );
+ }
+}
+
+uno::Reference< io::XStream > OWriteStream_Impl::GetStream( sal_Int32 nStreamMode, const ::comphelper::SequenceAsHashMap& aEncryptionData, bool bHierarchyAccess )
+{
+ ::osl::MutexGuard aGuard( m_xMutex->GetMutex() ) ;
+
+ SAL_WARN_IF( !m_xPackageStream.is(), "package.xstor", "No package stream is set!" );
+
+ if ( m_pAntiImpl )
+ throw io::IOException(); // TODO:
+
+ if ( !IsEncrypted() )
+ throw packages::NoEncryptionException();
+
+ uno::Reference< io::XStream > xResultStream;
+
+ uno::Reference< beans::XPropertySet > xPropertySet( m_xPackageStream, uno::UNO_QUERY_THROW );
+
+ if ( m_bHasCachedEncryptionData )
+ {
+ if ( !::package::PackageEncryptionDataLessOrEqual( m_aEncryptionData, aEncryptionData ) )
+ throw packages::WrongPasswordException();
+
+ // the correct key must be set already
+ xResultStream = GetStream_Impl( nStreamMode, bHierarchyAccess );
+ }
+ else
+ {
+ SetEncryptionKeyProperty_Impl( xPropertySet, aEncryptionData.getAsConstNamedValueList() );
+
+ try {
+ xResultStream = GetStream_Impl( nStreamMode, bHierarchyAccess );
+
+ m_bUseCommonEncryption = false; // very important to set it to false
+ m_bHasCachedEncryptionData = true;
+ m_aEncryptionData = aEncryptionData;
+ }
+ catch( const packages::WrongPasswordException& )
+ {
+ TOOLS_INFO_EXCEPTION("package.xstor", "Rethrow");
+ SetEncryptionKeyProperty_Impl( xPropertySet, uno::Sequence< beans::NamedValue >() );
+ throw;
+ }
+ catch ( const uno::Exception& ex )
+ {
+ TOOLS_WARN_EXCEPTION( "package.xstor", "Can't write encryption related properties");
+ SetEncryptionKeyProperty_Impl( xPropertySet, uno::Sequence< beans::NamedValue >() );
+ throw io::IOException(ex.Message); // TODO:
+ }
+ }
+
+ SAL_WARN_IF( !xResultStream.is(), "package.xstor", "In case stream can not be retrieved an exception must be thrown!" );
+
+ return xResultStream;
+}
+
+uno::Reference< io::XStream > OWriteStream_Impl::GetStream( sal_Int32 nStreamMode, bool bHierarchyAccess )
+{
+ ::osl::MutexGuard aGuard( m_xMutex->GetMutex() ) ;
+
+ SAL_WARN_IF( !m_xPackageStream.is(), "package.xstor", "No package stream is set!" );
+
+ if ( m_pAntiImpl )
+ throw io::IOException(); // TODO:
+
+ uno::Reference< io::XStream > xResultStream;
+
+ if ( IsEncrypted() )
+ {
+ ::comphelper::SequenceAsHashMap aGlobalEncryptionData;
+ try
+ {
+ aGlobalEncryptionData = GetCommonRootEncryptionData();
+ }
+ catch( const packages::NoEncryptionException& )
+ {
+ TOOLS_INFO_EXCEPTION("package.xstor", "Rethrow");
+ throw packages::WrongPasswordException();
+ }
+
+ xResultStream = GetStream( nStreamMode, aGlobalEncryptionData, bHierarchyAccess );
+ }
+ else
+ xResultStream = GetStream_Impl( nStreamMode, bHierarchyAccess );
+
+ return xResultStream;
+}
+
+uno::Reference< io::XStream > OWriteStream_Impl::GetStream_Impl( sal_Int32 nStreamMode, bool bHierarchyAccess )
+{
+ // private method, no mutex is used
+ GetStreamProperties();
+
+ // TODO/LATER: this info might be read later, on demand in future
+ ReadRelInfoIfNecessary();
+
+ if ( ( nStreamMode & embed::ElementModes::READWRITE ) == embed::ElementModes::READ )
+ {
+ uno::Reference< io::XInputStream > xInStream;
+ if ( m_xCacheStream.is() || !m_aTempURL.isEmpty() )
+ xInStream = GetTempFileAsInputStream(); //TODO:
+ else
+ xInStream = m_xPackageStream->getDataStream();
+
+ // The stream does not exist in the storage
+ if ( !xInStream.is() )
+ throw io::IOException();
+
+ rtl::Reference<OInputCompStream> pStream = new OInputCompStream( *this, xInStream, InsertOwnProps( m_aProps, m_bUseCommonEncryption ), m_nStorageType );
+ m_aInputStreamsVector.push_back( pStream.get() );
+ return pStream;
+ }
+ else if ( ( nStreamMode & embed::ElementModes::READWRITE ) == embed::ElementModes::SEEKABLEREAD )
+ {
+ if ( !m_xCacheStream.is() && m_aTempURL.isEmpty() && !( m_xPackageStream->getDataStream().is() ) )
+ {
+ // The stream does not exist in the storage
+ throw io::IOException();
+ }
+
+ uno::Reference< io::XInputStream > xInStream = GetTempFileAsInputStream(); //TODO:
+
+ if ( !xInStream.is() )
+ throw io::IOException();
+
+ rtl::Reference<OInputSeekStream> pStream = new OInputSeekStream( *this, xInStream, InsertOwnProps( m_aProps, m_bUseCommonEncryption ), m_nStorageType );
+ m_aInputStreamsVector.push_back( pStream.get() );
+ return pStream;
+ }
+ else if ( ( nStreamMode & embed::ElementModes::WRITE ) == embed::ElementModes::WRITE )
+ {
+ if ( !m_aInputStreamsVector.empty() )
+ throw io::IOException(); // TODO:
+
+ uno::Reference< io::XStream > xStream;
+ if ( ( nStreamMode & embed::ElementModes::TRUNCATE ) == embed::ElementModes::TRUNCATE )
+ {
+ if ( !m_aTempURL.isEmpty() )
+ {
+ KillFile( m_aTempURL, comphelper::getProcessComponentContext() );
+ m_aTempURL.clear();
+ }
+ if ( m_xCacheStream.is() )
+ CleanCacheStream();
+
+ m_bHasDataToFlush = true;
+
+ // this call is triggered by the parent and it will recognize the change of the state
+ if ( m_pParent )
+ m_pParent->m_bIsModified = true;
+
+ xStream = CreateMemoryStream( m_xContext );
+ m_xCacheSeek.set( xStream, uno::UNO_QUERY_THROW );
+ m_xCacheStream = xStream;
+ }
+ else if ( !m_bHasInsertedStreamOptimization )
+ {
+ if ( m_aTempURL.isEmpty() && !m_xCacheStream.is() && !( m_xPackageStream->getDataStream().is() ) )
+ {
+ // The stream does not exist in the storage
+ m_bHasDataToFlush = true;
+
+ // this call is triggered by the parent and it will recognize the change of the state
+ if ( m_pParent )
+ m_pParent->m_bIsModified = true;
+ xStream = GetTempFileAsStream();
+ }
+
+ // if the stream exists the temporary file is created on demand
+ // xStream = GetTempFileAsStream();
+ }
+
+ rtl::Reference<OWriteStream> tmp;
+ if ( !xStream.is() )
+ tmp = new OWriteStream( this, bHierarchyAccess );
+ else
+ tmp = new OWriteStream( this, xStream, bHierarchyAccess );
+
+ m_pAntiImpl = tmp.get();
+ return tmp;
+ }
+
+ throw lang::IllegalArgumentException(); // TODO
+}
+
+uno::Reference< io::XInputStream > OWriteStream_Impl::GetPlainRawInStream()
+{
+ ::osl::MutexGuard aGuard( m_xMutex->GetMutex() ) ;
+
+ SAL_WARN_IF( !m_xPackageStream.is(), "package.xstor", "No package stream is set!" );
+
+ // this method is used only internally, this stream object should not go outside of this implementation
+ // if ( m_pAntiImpl )
+ // throw io::IOException(); // TODO:
+
+ return m_xPackageStream->getPlainRawStream();
+}
+
+uno::Reference< io::XInputStream > OWriteStream_Impl::GetRawInStream()
+{
+ ::osl::MutexGuard aGuard( m_xMutex->GetMutex() ) ;
+
+ SAL_WARN_IF( !m_xPackageStream.is(), "package.xstor", "No package stream is set!" );
+
+ if ( m_pAntiImpl )
+ throw io::IOException(); // TODO:
+
+ SAL_WARN_IF( !IsEncrypted(), "package.xstor", "Impossible to get raw representation for nonencrypted stream!" );
+ if ( !IsEncrypted() )
+ throw packages::NoEncryptionException();
+
+ return m_xPackageStream->getRawStream();
+}
+
+::comphelper::SequenceAsHashMap OWriteStream_Impl::GetCommonRootEncryptionData()
+{
+ ::osl::MutexGuard aGuard( m_xMutex->GetMutex() ) ;
+
+ if ( m_nStorageType != embed::StorageFormats::PACKAGE || !m_pParent )
+ throw packages::NoEncryptionException();
+
+ return m_pParent->GetCommonRootEncryptionData();
+}
+
+void OWriteStream_Impl::InputStreamDisposed( OInputCompStream* pStream )
+{
+ ::osl::MutexGuard aGuard( m_xMutex->GetMutex() );
+ m_aInputStreamsVector.erase(std::remove(m_aInputStreamsVector.begin(), m_aInputStreamsVector.end(), pStream ));
+}
+
+void OWriteStream_Impl::CreateReadonlyCopyBasedOnData( const uno::Reference< io::XInputStream >& xDataToCopy, const uno::Sequence< beans::PropertyValue >& aProps, uno::Reference< io::XStream >& xTargetStream )
+{
+ uno::Reference < io::XStream > xTempFile;
+ if ( !xTargetStream.is() )
+ xTempFile = io::TempFile::create(m_xContext);
+ else
+ xTempFile = xTargetStream;
+
+ uno::Reference < io::XSeekable > xTempSeek( xTempFile, uno::UNO_QUERY_THROW );
+
+ uno::Reference < io::XOutputStream > xTempOut = xTempFile->getOutputStream();
+ if ( !xTempOut.is() )
+ throw uno::RuntimeException();
+
+ if ( xDataToCopy.is() )
+ ::comphelper::OStorageHelper::CopyInputToOutput( xDataToCopy, xTempOut );
+
+ xTempOut->closeOutput();
+ xTempSeek->seek( 0 );
+
+ uno::Reference< io::XInputStream > xInStream = xTempFile->getInputStream();
+ if ( !xInStream.is() )
+ throw io::IOException();
+
+ // TODO: remember last state of m_bUseCommonEncryption
+ if ( !xTargetStream.is() )
+ xTargetStream.set(
+ static_cast< ::cppu::OWeakObject* >(
+ new OInputSeekStream( xInStream, InsertOwnProps( aProps, m_bUseCommonEncryption ), m_nStorageType ) ),
+ uno::UNO_QUERY_THROW );
+}
+
+void OWriteStream_Impl::GetCopyOfLastCommit( uno::Reference< io::XStream >& xTargetStream )
+{
+ ::osl::MutexGuard aGuard( m_xMutex->GetMutex() );
+
+ SAL_WARN_IF( !m_xPackageStream.is(), "package.xstor", "The source stream for copying is incomplete!" );
+ if ( !m_xPackageStream.is() )
+ throw uno::RuntimeException();
+
+ uno::Reference< io::XInputStream > xDataToCopy;
+ if ( IsEncrypted() )
+ {
+ // an encrypted stream must contain input stream
+ ::comphelper::SequenceAsHashMap aGlobalEncryptionData;
+ try
+ {
+ aGlobalEncryptionData = GetCommonRootEncryptionData();
+ }
+ catch( const packages::NoEncryptionException& )
+ {
+ TOOLS_INFO_EXCEPTION("package.xstor", "No Element");
+ throw packages::WrongPasswordException();
+ }
+
+ GetCopyOfLastCommit( xTargetStream, aGlobalEncryptionData );
+ }
+ else
+ {
+ xDataToCopy = m_xPackageStream->getDataStream();
+
+ // in case of new inserted package stream it is possible that input stream still was not set
+ GetStreamProperties();
+
+ CreateReadonlyCopyBasedOnData( xDataToCopy, m_aProps, xTargetStream );
+ }
+}
+
+void OWriteStream_Impl::GetCopyOfLastCommit( uno::Reference< io::XStream >& xTargetStream, const ::comphelper::SequenceAsHashMap& aEncryptionData )
+{
+ ::osl::MutexGuard aGuard( m_xMutex->GetMutex() );
+
+ SAL_WARN_IF( !m_xPackageStream.is(), "package.xstor", "The source stream for copying is incomplete!" );
+ if ( !m_xPackageStream.is() )
+ throw uno::RuntimeException();
+
+ if ( !IsEncrypted() )
+ throw packages::NoEncryptionException();
+
+ uno::Reference< io::XInputStream > xDataToCopy;
+
+ if ( m_bHasCachedEncryptionData )
+ {
+ // TODO: introduce last committed cashed password information and use it here
+ // that means "use common pass" also should be remembered on flash
+ uno::Sequence< beans::NamedValue > aKey = aEncryptionData.getAsConstNamedValueList();
+
+ uno::Reference< beans::XPropertySet > xProps( m_xPackageStream, uno::UNO_QUERY_THROW );
+
+ bool bEncr = false;
+ xProps->getPropertyValue( "Encrypted" ) >>= bEncr;
+ if ( !bEncr )
+ throw packages::NoEncryptionException();
+
+ uno::Sequence< beans::NamedValue > aPackKey;
+ xProps->getPropertyValue( STORAGE_ENCRYPTION_KEYS_PROPERTY ) >>= aPackKey;
+ if ( !SequencesEqual( aKey, aPackKey ) )
+ throw packages::WrongPasswordException();
+
+ // the correct key must be set already
+ xDataToCopy = m_xPackageStream->getDataStream();
+ }
+ else
+ {
+ uno::Reference< beans::XPropertySet > xPropertySet( m_xPackageStream, uno::UNO_QUERY );
+ SetEncryptionKeyProperty_Impl( xPropertySet, aEncryptionData.getAsConstNamedValueList() );
+
+ try {
+ xDataToCopy = m_xPackageStream->getDataStream();
+
+ if ( !xDataToCopy.is() )
+ {
+ SAL_WARN( "package.xstor", "Encrypted ZipStream must already have input stream inside!" );
+ SetEncryptionKeyProperty_Impl( xPropertySet, uno::Sequence< beans::NamedValue >() );
+ }
+ }
+ catch( const uno::Exception& )
+ {
+ TOOLS_WARN_EXCEPTION( "package.xstor", "Can't open encrypted stream");
+ SetEncryptionKeyProperty_Impl( xPropertySet, uno::Sequence< beans::NamedValue >() );
+ throw;
+ }
+
+ SetEncryptionKeyProperty_Impl( xPropertySet, uno::Sequence< beans::NamedValue >() );
+ }
+
+ // in case of new inserted package stream it is possible that input stream still was not set
+ GetStreamProperties();
+
+ CreateReadonlyCopyBasedOnData( xDataToCopy, m_aProps, xTargetStream );
+}
+
+void OWriteStream_Impl::CommitStreamRelInfo( const uno::Reference< embed::XStorage >& xRelStorage, std::u16string_view aOrigStreamName, std::u16string_view aNewStreamName )
+{
+ // at this point of time the old stream must be already cleaned
+ OSL_ENSURE( m_nStorageType == embed::StorageFormats::OFOPXML, "The method should be used only with OFOPXML format!" );
+
+ if ( m_nStorageType != embed::StorageFormats::OFOPXML )
+ return;
+
+ OSL_ENSURE( !aOrigStreamName.empty() && !aNewStreamName.empty() && xRelStorage.is(),
+ "Wrong relation persistence information is provided!" );
+
+ if ( !xRelStorage.is() || aOrigStreamName.empty() || aNewStreamName.empty() )
+ throw uno::RuntimeException();
+
+ if ( m_nRelInfoStatus == RELINFO_BROKEN || m_nRelInfoStatus == RELINFO_CHANGED_BROKEN )
+ throw io::IOException(); // TODO:
+
+ OUString aOrigRelStreamName = OUString::Concat(aOrigStreamName) + ".rels";
+ OUString aNewRelStreamName = OUString::Concat(aNewStreamName) + ".rels";
+
+ bool bRenamed = aOrigRelStreamName != aNewRelStreamName;
+ if ( m_nRelInfoStatus == RELINFO_CHANGED
+ || m_nRelInfoStatus == RELINFO_CHANGED_STREAM_READ
+ || m_nRelInfoStatus == RELINFO_CHANGED_STREAM )
+ {
+ if ( bRenamed && xRelStorage->hasByName( aOrigRelStreamName ) )
+ xRelStorage->removeElement( aOrigRelStreamName );
+
+ if ( m_nRelInfoStatus == RELINFO_CHANGED )
+ {
+ if ( m_aNewRelInfo.hasElements() )
+ {
+ uno::Reference< io::XStream > xRelsStream =
+ xRelStorage->openStreamElement( aNewRelStreamName,
+ embed::ElementModes::TRUNCATE | embed::ElementModes::READWRITE );
+
+ uno::Reference< io::XOutputStream > xOutStream = xRelsStream->getOutputStream();
+ if ( !xOutStream.is() )
+ throw uno::RuntimeException();
+
+ ::comphelper::OFOPXMLHelper::WriteRelationsInfoSequence( xOutStream, m_aNewRelInfo, m_xContext );
+
+ // set the mediatype
+ uno::Reference< beans::XPropertySet > xPropSet( xRelsStream, uno::UNO_QUERY_THROW );
+ xPropSet->setPropertyValue(
+ "MediaType",
+ uno::Any( OUString("application/vnd.openxmlformats-package.relationships+xml" ) ) );
+
+ m_nRelInfoStatus = RELINFO_READ;
+ }
+ }
+ else if ( m_nRelInfoStatus == RELINFO_CHANGED_STREAM_READ
+ || m_nRelInfoStatus == RELINFO_CHANGED_STREAM )
+ {
+ uno::Reference< io::XStream > xRelsStream =
+ xRelStorage->openStreamElement( aNewRelStreamName,
+ embed::ElementModes::TRUNCATE | embed::ElementModes::READWRITE );
+
+ uno::Reference< io::XOutputStream > xOutputStream = xRelsStream->getOutputStream();
+ if ( !xOutputStream.is() )
+ throw uno::RuntimeException();
+
+ uno::Reference< io::XSeekable > xSeek( m_xNewRelInfoStream, uno::UNO_QUERY_THROW );
+ xSeek->seek( 0 );
+ ::comphelper::OStorageHelper::CopyInputToOutput( m_xNewRelInfoStream, xOutputStream );
+ xSeek->seek( 0 );
+
+ // set the mediatype
+ uno::Reference< beans::XPropertySet > xPropSet( xRelsStream, uno::UNO_QUERY_THROW );
+ xPropSet->setPropertyValue("MediaType",
+ uno::Any( OUString("application/vnd.openxmlformats-package.relationships+xml" ) ) );
+
+ if ( m_nRelInfoStatus == RELINFO_CHANGED_STREAM )
+ m_nRelInfoStatus = RELINFO_NO_INIT;
+ else
+ {
+ // the information is already parsed and the stream is stored, no need in temporary stream any more
+ m_xNewRelInfoStream.clear();
+ m_nRelInfoStatus = RELINFO_READ;
+ }
+ }
+
+ // the original stream makes no sense after this step
+ m_xOrigRelInfoStream = m_xNewRelInfoStream;
+ m_aOrigRelInfo = m_aNewRelInfo;
+ m_bOrigRelInfoBroken = false;
+ m_aNewRelInfo = uno::Sequence< uno::Sequence< beans::StringPair > >();
+ m_xNewRelInfoStream.clear();
+ }
+ else
+ {
+ // the stream is not changed but it might be renamed
+ if ( bRenamed && xRelStorage->hasByName( aOrigRelStreamName ) )
+ xRelStorage->renameElement( aOrigRelStreamName, aNewRelStreamName );
+ }
+}
+
+// OWriteStream implementation
+
+OWriteStream::OWriteStream( OWriteStream_Impl* pImpl, bool bTransacted )
+: m_pImpl( pImpl )
+, m_bInStreamDisconnected( false )
+, m_bInitOnDemand( true )
+, m_nInitPosition( 0 )
+, m_bTransacted( bTransacted )
+{
+ OSL_ENSURE( pImpl, "No base implementation!" );
+ OSL_ENSURE( m_pImpl->m_xMutex.is(), "No mutex!" );
+
+ if ( !m_pImpl || !m_pImpl->m_xMutex.is() )
+ throw uno::RuntimeException(); // just a disaster
+
+ m_pData.reset(new WSInternalData_Impl(pImpl->m_xMutex, m_pImpl->m_nStorageType));
+}
+
+OWriteStream::OWriteStream( OWriteStream_Impl* pImpl, uno::Reference< io::XStream > const & xStream, bool bTransacted )
+: m_pImpl( pImpl )
+, m_bInStreamDisconnected( false )
+, m_bInitOnDemand( false )
+, m_nInitPosition( 0 )
+, m_bTransacted( bTransacted )
+{
+ OSL_ENSURE( pImpl && xStream.is(), "No base implementation!" );
+ OSL_ENSURE( m_pImpl->m_xMutex.is(), "No mutex!" );
+
+ if ( !m_pImpl || !m_pImpl->m_xMutex.is() )
+ throw uno::RuntimeException(); // just a disaster
+
+ m_pData.reset(new WSInternalData_Impl(pImpl->m_xMutex, m_pImpl->m_nStorageType));
+
+ if ( xStream.is() )
+ {
+ m_xInStream = xStream->getInputStream();
+ m_xOutStream = xStream->getOutputStream();
+ m_xSeekable.set( xStream, uno::UNO_QUERY );
+ OSL_ENSURE( m_xInStream.is() && m_xOutStream.is() && m_xSeekable.is(), "Stream implementation is incomplete!" );
+ }
+}
+
+OWriteStream::~OWriteStream()
+{
+ ::osl::MutexGuard aGuard( m_pData->m_xSharedMutex->GetMutex() );
+ if ( m_pImpl )
+ {
+ osl_atomic_increment(&m_refCount);
+ try {
+ dispose();
+ }
+ catch( const uno::RuntimeException& )
+ {
+ TOOLS_INFO_EXCEPTION("package.xstor", "Quiet exception");
+ }
+ }
+}
+
+void OWriteStream::DeInit()
+{
+ if ( !m_pImpl )
+ return; // do nothing
+
+ if ( m_xSeekable.is() )
+ m_nInitPosition = m_xSeekable->getPosition();
+
+ m_xInStream.clear();
+ m_xOutStream.clear();
+ m_xSeekable.clear();
+ m_bInitOnDemand = true;
+}
+
+void OWriteStream::CheckInitOnDemand()
+{
+ if ( !m_pImpl )
+ {
+ SAL_INFO("package.xstor", "Disposed!");
+ throw lang::DisposedException();
+ }
+
+ if ( !m_bInitOnDemand )
+ return;
+
+ SAL_INFO( "package.xstor", "package (mv76033) OWriteStream::CheckInitOnDemand, initializing" );
+ uno::Reference< io::XStream > xStream = m_pImpl->GetTempFileAsStream();
+ if ( xStream.is() )
+ {
+ m_xInStream.set( xStream->getInputStream(), uno::UNO_SET_THROW );
+ m_xOutStream.set( xStream->getOutputStream(), uno::UNO_SET_THROW );
+ m_xSeekable.set( xStream, uno::UNO_QUERY_THROW );
+ m_xSeekable->seek( m_nInitPosition );
+
+ m_nInitPosition = 0;
+ m_bInitOnDemand = false;
+ }
+}
+
+void OWriteStream::CopyToStreamInternally_Impl( const uno::Reference< io::XStream >& xDest )
+{
+ ::osl::MutexGuard aGuard( m_pData->m_xSharedMutex->GetMutex() );
+
+ CheckInitOnDemand();
+
+ if ( !m_xInStream.is() )
+ throw uno::RuntimeException();
+
+ if ( !m_xSeekable.is() )
+ throw uno::RuntimeException();
+
+ uno::Reference< beans::XPropertySet > xDestProps( xDest, uno::UNO_QUERY_THROW );
+
+ uno::Reference< io::XOutputStream > xDestOutStream = xDest->getOutputStream();
+ if ( !xDestOutStream.is() )
+ throw io::IOException(); // TODO
+
+ sal_Int64 nCurPos = m_xSeekable->getPosition();
+ m_xSeekable->seek( 0 );
+
+ uno::Exception eThrown;
+ bool bThrown = false;
+ try {
+ ::comphelper::OStorageHelper::CopyInputToOutput( m_xInStream, xDestOutStream );
+ }
+ catch ( const uno::Exception& e )
+ {
+ eThrown = e;
+ bThrown = true;
+ }
+
+ // position-related section below is critical
+ // if it fails the stream will become invalid
+ try {
+ m_xSeekable->seek( nCurPos );
+ }
+ catch ( const uno::Exception& )
+ {
+ // TODO: set the stream in invalid state or dispose
+ TOOLS_WARN_EXCEPTION( "package.xstor", "The stream become invalid during copying" );
+ throw uno::RuntimeException();
+ }
+
+ if ( bThrown )
+ throw eThrown;
+
+ // now the properties can be copied
+ // the order of the properties setting is not important for StorageStream API
+ OUString aPropName ("Compressed");
+ xDestProps->setPropertyValue( aPropName, getPropertyValue( aPropName ) );
+ if ( m_pData->m_nStorageType == embed::StorageFormats::PACKAGE || m_pData->m_nStorageType == embed::StorageFormats::OFOPXML )
+ {
+ aPropName = "MediaType";
+ xDestProps->setPropertyValue( aPropName, getPropertyValue( aPropName ) );
+
+ if ( m_pData->m_nStorageType == embed::StorageFormats::PACKAGE )
+ {
+ aPropName = "UseCommonStoragePasswordEncryption";
+ xDestProps->setPropertyValue( aPropName, getPropertyValue( aPropName ) );
+ }
+ }
+}
+
+void OWriteStream::ModifyParentUnlockMutex_Impl(osl::ClearableMutexGuard& aGuard)
+{
+ if ( m_pImpl->m_pParent )
+ {
+ if ( m_pImpl->m_pParent->HasModifiedListener() )
+ {
+ uno::Reference< util::XModifiable > xParentModif( static_cast<util::XModifiable*>(m_pImpl->m_pParent->m_pAntiImpl) );
+ aGuard.clear();
+ xParentModif->setModified( true );
+ }
+ else
+ m_pImpl->m_pParent->m_bIsModified = true;
+ }
+}
+
+uno::Any SAL_CALL OWriteStream::queryInterface( const uno::Type& rType )
+{
+ // common interfaces
+ uno::Any aReturn = ::cppu::queryInterface
+ ( rType
+ , static_cast<lang::XTypeProvider*> ( this )
+ , static_cast<io::XInputStream*> ( this )
+ , static_cast<io::XOutputStream*> ( this )
+ , static_cast<io::XStream*> ( this )
+ , static_cast<embed::XExtendedStorageStream*> ( this )
+ , static_cast<io::XSeekable*> ( this )
+ , static_cast<io::XTruncate*> ( this )
+ , static_cast<lang::XComponent*> ( this )
+ , static_cast<beans::XPropertySet*> ( this )
+ , static_cast<lang::XUnoTunnel*> ( this ) );
+
+ if ( aReturn.hasValue() )
+ return aReturn ;
+
+ if ( m_pData->m_nStorageType == embed::StorageFormats::PACKAGE )
+ {
+ aReturn = ::cppu::queryInterface
+ ( rType
+ , static_cast<embed::XEncryptionProtectedSource2*> ( this )
+ , static_cast<embed::XEncryptionProtectedSource*> ( this ) );
+ }
+ else if ( m_pData->m_nStorageType == embed::StorageFormats::OFOPXML )
+ {
+ aReturn = ::cppu::queryInterface
+ ( rType
+ , static_cast<embed::XRelationshipAccess*> ( this ) );
+ }
+
+ if ( aReturn.hasValue() )
+ return aReturn ;
+
+ if ( m_bTransacted )
+ {
+ aReturn = ::cppu::queryInterface
+ ( rType
+ , static_cast<embed::XTransactedObject*> ( this )
+ , static_cast<embed::XTransactionBroadcaster*> ( this ) );
+
+ if ( aReturn.hasValue() )
+ return aReturn ;
+ }
+
+ return OWeakObject::queryInterface( rType );
+}
+
+void SAL_CALL OWriteStream::acquire() noexcept
+{
+ OWeakObject::acquire();
+}
+
+void SAL_CALL OWriteStream::release() noexcept
+{
+ OWeakObject::release();
+}
+
+uno::Sequence< uno::Type > SAL_CALL OWriteStream::getTypes()
+{
+ if (! m_pData->m_pTypeCollection)
+ {
+ ::osl::MutexGuard aGuard( m_pData->m_xSharedMutex->GetMutex() );
+
+ if (! m_pData->m_pTypeCollection)
+ {
+ if ( m_bTransacted )
+ {
+ if ( m_pData->m_nStorageType == embed::StorageFormats::PACKAGE )
+ {
+ ::cppu::OTypeCollection aTmpCollection
+ ( cppu::UnoType<lang::XTypeProvider>::get()
+ , cppu::UnoType<io::XInputStream>::get()
+ , cppu::UnoType<io::XOutputStream>::get()
+ , cppu::UnoType<io::XStream>::get()
+ , cppu::UnoType<io::XSeekable>::get()
+ , cppu::UnoType<io::XTruncate>::get()
+ , cppu::UnoType<lang::XComponent>::get()
+ , cppu::UnoType<embed::XEncryptionProtectedSource2>::get()
+ , cppu::UnoType<embed::XEncryptionProtectedSource>::get()
+ , cppu::UnoType<embed::XExtendedStorageStream>::get()
+ , cppu::UnoType<embed::XTransactedObject>::get()
+ , cppu::UnoType<embed::XTransactionBroadcaster>::get());
+
+ m_pData->m_pTypeCollection.reset(new ::cppu::OTypeCollection
+ ( cppu::UnoType<beans::XPropertySet>::get()
+ , aTmpCollection.getTypes()));
+ }
+ else if ( m_pData->m_nStorageType == embed::StorageFormats::OFOPXML )
+ {
+ m_pData->m_pTypeCollection.reset(new ::cppu::OTypeCollection
+ ( cppu::UnoType<lang::XTypeProvider>::get()
+ , cppu::UnoType<io::XInputStream>::get()
+ , cppu::UnoType<io::XOutputStream>::get()
+ , cppu::UnoType<io::XStream>::get()
+ , cppu::UnoType<io::XSeekable>::get()
+ , cppu::UnoType<io::XTruncate>::get()
+ , cppu::UnoType<lang::XComponent>::get()
+ , cppu::UnoType<embed::XRelationshipAccess>::get()
+ , cppu::UnoType<embed::XExtendedStorageStream>::get()
+ , cppu::UnoType<embed::XTransactedObject>::get()
+ , cppu::UnoType<embed::XTransactionBroadcaster>::get()
+ , cppu::UnoType<beans::XPropertySet>::get()));
+ }
+ else // if ( m_pData->m_nStorageType == embed::StorageFormats::ZIP )
+ {
+ m_pData->m_pTypeCollection.reset(new ::cppu::OTypeCollection
+ ( cppu::UnoType<lang::XTypeProvider>::get()
+ , cppu::UnoType<io::XInputStream>::get()
+ , cppu::UnoType<io::XOutputStream>::get()
+ , cppu::UnoType<io::XStream>::get()
+ , cppu::UnoType<io::XSeekable>::get()
+ , cppu::UnoType<io::XTruncate>::get()
+ , cppu::UnoType<lang::XComponent>::get()
+ , cppu::UnoType<embed::XExtendedStorageStream>::get()
+ , cppu::UnoType<embed::XTransactedObject>::get()
+ , cppu::UnoType<embed::XTransactionBroadcaster>::get()
+ , cppu::UnoType<beans::XPropertySet>::get()));
+ }
+ }
+ else
+ {
+ if ( m_pData->m_nStorageType == embed::StorageFormats::PACKAGE )
+ {
+ m_pData->m_pTypeCollection.reset(new ::cppu::OTypeCollection
+ ( cppu::UnoType<lang::XTypeProvider>::get()
+ , cppu::UnoType<io::XInputStream>::get()
+ , cppu::UnoType<io::XOutputStream>::get()
+ , cppu::UnoType<io::XStream>::get()
+ , cppu::UnoType<io::XSeekable>::get()
+ , cppu::UnoType<io::XTruncate>::get()
+ , cppu::UnoType<lang::XComponent>::get()
+ , cppu::UnoType<embed::XEncryptionProtectedSource2>::get()
+ , cppu::UnoType<embed::XEncryptionProtectedSource>::get()
+ , cppu::UnoType<beans::XPropertySet>::get()));
+ }
+ else if ( m_pData->m_nStorageType == embed::StorageFormats::OFOPXML )
+ {
+ m_pData->m_pTypeCollection.reset(new ::cppu::OTypeCollection
+ ( cppu::UnoType<lang::XTypeProvider>::get()
+ , cppu::UnoType<io::XInputStream>::get()
+ , cppu::UnoType<io::XOutputStream>::get()
+ , cppu::UnoType<io::XStream>::get()
+ , cppu::UnoType<io::XSeekable>::get()
+ , cppu::UnoType<io::XTruncate>::get()
+ , cppu::UnoType<lang::XComponent>::get()
+ , cppu::UnoType<embed::XRelationshipAccess>::get()
+ , cppu::UnoType<beans::XPropertySet>::get()));
+ }
+ else // if ( m_pData->m_nStorageType == embed::StorageFormats::ZIP )
+ {
+ m_pData->m_pTypeCollection.reset(new ::cppu::OTypeCollection
+ ( cppu::UnoType<lang::XTypeProvider>::get()
+ , cppu::UnoType<io::XInputStream>::get()
+ , cppu::UnoType<io::XOutputStream>::get()
+ , cppu::UnoType<io::XStream>::get()
+ , cppu::UnoType<io::XSeekable>::get()
+ , cppu::UnoType<io::XTruncate>::get()
+ , cppu::UnoType<lang::XComponent>::get()
+ , cppu::UnoType<beans::XPropertySet>::get()));
+ }
+ }
+ }
+ }
+
+ return m_pData->m_pTypeCollection->getTypes() ;
+}
+
+uno::Sequence< sal_Int8 > SAL_CALL OWriteStream::getImplementationId()
+{
+ static const comphelper::UnoIdInit lcl_ImplId;
+ return lcl_ImplId.getSeq();
+}
+
+sal_Int32 SAL_CALL OWriteStream::readBytes( uno::Sequence< sal_Int8 >& aData, sal_Int32 nBytesToRead )
+{
+ ::osl::MutexGuard aGuard( m_pData->m_xSharedMutex->GetMutex() );
+
+ CheckInitOnDemand();
+
+ if ( !m_pImpl )
+ {
+ SAL_INFO("package.xstor", "Disposed!");
+ throw lang::DisposedException();
+ }
+
+ if ( !m_xInStream.is() )
+ throw io::NotConnectedException();
+
+ return m_xInStream->readBytes( aData, nBytesToRead );
+}
+
+sal_Int32 SAL_CALL OWriteStream::readSomeBytes( uno::Sequence< sal_Int8 >& aData, sal_Int32 nMaxBytesToRead )
+{
+ ::osl::MutexGuard aGuard( m_pData->m_xSharedMutex->GetMutex() );
+
+ CheckInitOnDemand();
+
+ if ( !m_pImpl )
+ {
+ SAL_INFO("package.xstor", "Disposed!");
+ throw lang::DisposedException();
+ }
+
+ if ( !m_xInStream.is() )
+ throw io::NotConnectedException();
+
+ return m_xInStream->readSomeBytes( aData, nMaxBytesToRead );
+}
+
+void SAL_CALL OWriteStream::skipBytes( sal_Int32 nBytesToSkip )
+{
+ ::osl::MutexGuard aGuard( m_pData->m_xSharedMutex->GetMutex() );
+
+ CheckInitOnDemand();
+
+ if ( !m_pImpl )
+ {
+ SAL_INFO("package.xstor", "Disposed!");
+ throw lang::DisposedException();
+ }
+
+ if ( !m_xInStream.is() )
+ throw io::NotConnectedException();
+
+ m_xInStream->skipBytes( nBytesToSkip );
+}
+
+sal_Int32 SAL_CALL OWriteStream::available( )
+{
+ ::osl::MutexGuard aGuard( m_pData->m_xSharedMutex->GetMutex() );
+
+ CheckInitOnDemand();
+
+ if ( !m_pImpl )
+ {
+ SAL_INFO("package.xstor", "Disposed!");
+ throw lang::DisposedException();
+ }
+
+ if ( !m_xInStream.is() )
+ throw io::NotConnectedException();
+
+ return m_xInStream->available();
+
+}
+
+void SAL_CALL OWriteStream::closeInput( )
+{
+ ::osl::MutexGuard aGuard( m_pData->m_xSharedMutex->GetMutex() );
+
+ if ( !m_pImpl )
+ {
+ SAL_INFO("package.xstor", "Disposed!");
+ throw lang::DisposedException();
+ }
+
+ if ( !m_bInitOnDemand && ( m_bInStreamDisconnected || !m_xInStream.is() ) )
+ throw io::NotConnectedException();
+
+ // the input part of the stream stays open for internal purposes (to allow reading during copying)
+ // since it can not be reopened until output part is closed, it will be closed with output part.
+ m_bInStreamDisconnected = true;
+ // m_xInStream->closeInput();
+ // m_xInStream.clear();
+
+ if ( !m_xOutStream.is() )
+ dispose();
+}
+
+uno::Reference< io::XInputStream > SAL_CALL OWriteStream::getInputStream()
+{
+ ::osl::MutexGuard aGuard( m_pData->m_xSharedMutex->GetMutex() );
+
+ if ( !m_pImpl )
+ {
+ SAL_INFO("package.xstor", "Disposed!");
+ throw lang::DisposedException();
+ }
+
+ if ( !m_bInitOnDemand && ( m_bInStreamDisconnected || !m_xInStream.is() ) )
+ return uno::Reference< io::XInputStream >();
+
+ return this;
+}
+
+uno::Reference< io::XOutputStream > SAL_CALL OWriteStream::getOutputStream()
+{
+ ::osl::MutexGuard aGuard( m_pData->m_xSharedMutex->GetMutex() );
+
+ try
+ {
+ CheckInitOnDemand();
+ }
+ catch( const io::IOException& r )
+ {
+ throw lang::WrappedTargetRuntimeException("OWriteStream::getOutputStream: Could not create backing temp file",
+ static_cast < OWeakObject * > ( this ), css::uno::Any ( r ) );
+ }
+
+ if ( !m_pImpl )
+ {
+ SAL_INFO("package.xstor", "Disposed!");
+ throw lang::DisposedException();
+ }
+
+ if ( !m_xOutStream.is() )
+ return uno::Reference< io::XOutputStream >();
+
+ return this;
+}
+
+void SAL_CALL OWriteStream::writeBytes( const uno::Sequence< sal_Int8 >& aData )
+{
+ osl::ClearableMutexGuard aGuard(m_pData->m_xSharedMutex->GetMutex());
+
+ // the write method makes initialization itself, since it depends from the aData length
+ // NO CheckInitOnDemand()!
+
+ if ( !m_pImpl )
+ {
+ SAL_INFO("package.xstor", "Disposed!");
+ throw lang::DisposedException();
+ }
+
+ if ( !m_bInitOnDemand )
+ {
+ if ( !m_xOutStream.is() || !m_xSeekable.is())
+ throw io::NotConnectedException();
+
+ if ( m_pImpl->m_xCacheStream.is() )
+ {
+ // check whether the cache should be turned off
+ sal_Int64 nPos = m_xSeekable->getPosition();
+ if ( nPos + aData.getLength() > MAX_STORCACHE_SIZE )
+ {
+ // disconnect the cache and copy the data to the temporary file
+ m_xSeekable->seek( 0 );
+
+ // it is enough to copy the cached stream, the cache should already contain everything
+ if ( !m_pImpl->GetFilledTempFileIfNo( m_xInStream ).isEmpty() )
+ {
+ DeInit();
+ // the last position is known and it is differs from the current stream position
+ m_nInitPosition = nPos;
+ }
+ }
+ }
+ }
+
+ if ( m_bInitOnDemand )
+ {
+ SAL_INFO( "package.xstor", "package (mv76033) OWriteStream::CheckInitOnDemand, initializing" );
+ uno::Reference< io::XStream > xStream = m_pImpl->GetTempFileAsStream();
+ if ( xStream.is() )
+ {
+ m_xInStream.set( xStream->getInputStream(), uno::UNO_SET_THROW );
+ m_xOutStream.set( xStream->getOutputStream(), uno::UNO_SET_THROW );
+ m_xSeekable.set( xStream, uno::UNO_QUERY_THROW );
+ m_xSeekable->seek( m_nInitPosition );
+
+ m_nInitPosition = 0;
+ m_bInitOnDemand = false;
+ }
+ }
+
+ if ( !m_xOutStream.is() )
+ throw io::NotConnectedException();
+
+ m_xOutStream->writeBytes( aData );
+ m_pImpl->m_bHasDataToFlush = true;
+
+ ModifyParentUnlockMutex_Impl( aGuard );
+}
+
+sal_Int32 OWriteStream::writeSomeBytes( const sal_Int8* pData, sal_Int32 nBytesToWrite )
+{
+ osl::ClearableMutexGuard aGuard(m_pData->m_xSharedMutex->GetMutex());
+
+ // the write method makes initialization itself, since it depends from the aData length
+ // NO CheckInitOnDemand()!
+
+ if ( !m_pImpl )
+ {
+ SAL_INFO("package.xstor", "Disposed!");
+ throw lang::DisposedException();
+ }
+
+ if ( !m_bInitOnDemand )
+ {
+ if ( !m_xOutStream.is() || !m_xSeekable.is())
+ throw io::NotConnectedException();
+
+ if ( m_pImpl->m_xCacheStream.is() )
+ {
+ // check whether the cache should be turned off
+ sal_Int64 nPos = m_xSeekable->getPosition();
+ if ( nPos + nBytesToWrite > MAX_STORCACHE_SIZE )
+ {
+ // disconnect the cache and copy the data to the temporary file
+ m_xSeekable->seek( 0 );
+
+ // it is enough to copy the cached stream, the cache should already contain everything
+ if ( !m_pImpl->GetFilledTempFileIfNo( m_xInStream ).isEmpty() )
+ {
+ DeInit();
+ // the last position is known and it is differs from the current stream position
+ m_nInitPosition = nPos;
+ }
+ }
+ }
+ }
+
+ if ( m_bInitOnDemand )
+ {
+ SAL_INFO( "package.xstor", "package (mv76033) OWriteStream::CheckInitOnDemand, initializing" );
+ uno::Reference< io::XStream > xStream = m_pImpl->GetTempFileAsStream();
+ if ( xStream.is() )
+ {
+ m_xInStream.set( xStream->getInputStream(), uno::UNO_SET_THROW );
+ m_xOutStream.set( xStream->getOutputStream(), uno::UNO_SET_THROW );
+ m_xSeekable.set( xStream, uno::UNO_QUERY_THROW );
+ m_xSeekable->seek( m_nInitPosition );
+
+ m_nInitPosition = 0;
+ m_bInitOnDemand = false;
+ }
+ }
+
+ if ( !m_xOutStream.is() )
+ throw io::NotConnectedException();
+
+ uno::Reference< css::lang::XUnoTunnel > xOutputTunnel( m_xOutStream, uno::UNO_QUERY );
+ comphelper::ByteWriter* pByteWriter = nullptr;
+ if (xOutputTunnel)
+ pByteWriter = reinterpret_cast< comphelper::ByteWriter* >( xOutputTunnel->getSomething( comphelper::ByteWriter::getUnoTunnelId() ) );
+ if (pByteWriter)
+ nBytesToWrite = pByteWriter->writeSomeBytes(pData, nBytesToWrite);
+ else
+ {
+ uno::Sequence<sal_Int8> aData(pData, nBytesToWrite);
+ m_xOutStream->writeBytes( aData );
+ }
+ m_pImpl->m_bHasDataToFlush = true;
+
+ ModifyParentUnlockMutex_Impl( aGuard );
+
+ return nBytesToWrite;
+}
+
+sal_Int64 SAL_CALL OWriteStream::getSomething( const css::uno::Sequence< sal_Int8 >& rIdentifier )
+{
+ if (rIdentifier == comphelper::ByteWriter::getUnoTunnelId())
+ return reinterpret_cast<sal_Int64>(static_cast<comphelper::ByteWriter*>(this));
+ return 0;
+}
+
+void SAL_CALL OWriteStream::flush()
+{
+ // In case stream is flushed its current version becomes visible
+ // to the parent storage. Usually parent storage flushes the stream
+ // during own commit but a user can explicitly flush the stream
+ // so the changes will be available through cloning functionality.
+
+ ::osl::MutexGuard aGuard( m_pData->m_xSharedMutex->GetMutex() );
+
+ if ( !m_pImpl )
+ {
+ SAL_INFO("package.xstor", "Disposed!");
+ throw lang::DisposedException();
+ }
+
+ if ( !m_bInitOnDemand )
+ {
+ if ( !m_xOutStream.is() )
+ throw io::NotConnectedException();
+
+ m_xOutStream->flush();
+ m_pImpl->Commit();
+ }
+}
+
+void OWriteStream::CloseOutput_Impl()
+{
+ // all the checks must be done in calling method
+
+ m_xOutStream->closeOutput();
+ m_xOutStream.clear();
+
+ if ( m_bInitOnDemand )
+ return;
+
+ // after the stream is disposed it can be committed
+ // so transport correct size property
+ if ( !m_xSeekable.is() )
+ throw uno::RuntimeException();
+
+ for ( auto& rProp : asNonConstRange(m_pImpl->m_aProps) )
+ {
+ if ( rProp.Name == "Size" )
+ rProp.Value <<= m_xSeekable->getLength();
+ }
+}
+
+void SAL_CALL OWriteStream::closeOutput()
+{
+ ::osl::MutexGuard aGuard( m_pData->m_xSharedMutex->GetMutex() );
+
+ CheckInitOnDemand();
+
+ if ( !m_pImpl )
+ {
+ SAL_INFO("package.xstor", "Disposed!");
+ throw lang::DisposedException();
+ }
+
+ if ( !m_xOutStream.is() )
+ throw io::NotConnectedException();
+
+ CloseOutput_Impl();
+
+ if ( m_bInStreamDisconnected || !m_xInStream.is() )
+ dispose();
+}
+
+void SAL_CALL OWriteStream::seek( sal_Int64 location )
+{
+ ::osl::MutexGuard aGuard( m_pData->m_xSharedMutex->GetMutex() );
+
+ CheckInitOnDemand();
+
+ if ( !m_pImpl )
+ {
+ SAL_INFO("package.xstor", "Disposed!");
+ throw lang::DisposedException();
+ }
+
+ if ( !m_xSeekable.is() )
+ throw uno::RuntimeException();
+
+ m_xSeekable->seek( location );
+}
+
+sal_Int64 SAL_CALL OWriteStream::getPosition()
+{
+ ::osl::MutexGuard aGuard( m_pData->m_xSharedMutex->GetMutex() );
+
+ CheckInitOnDemand();
+
+ if ( !m_pImpl )
+ {
+ SAL_INFO("package.xstor", "Disposed!");
+ throw lang::DisposedException();
+ }
+
+ if ( !m_xSeekable.is() )
+ throw uno::RuntimeException();
+
+ return m_xSeekable->getPosition();
+}
+
+sal_Int64 SAL_CALL OWriteStream::getLength()
+{
+ ::osl::MutexGuard aGuard( m_pData->m_xSharedMutex->GetMutex() );
+
+ CheckInitOnDemand();
+
+ if ( !m_pImpl )
+ {
+ SAL_INFO("package.xstor", "Disposed!");
+ throw lang::DisposedException();
+ }
+
+ if ( !m_xSeekable.is() )
+ throw uno::RuntimeException();
+
+ return m_xSeekable->getLength();
+}
+
+void SAL_CALL OWriteStream::truncate()
+{
+ osl::ClearableMutexGuard aGuard(m_pData->m_xSharedMutex->GetMutex());
+
+ CheckInitOnDemand();
+
+ if ( !m_pImpl )
+ {
+ SAL_INFO("package.xstor", "Disposed!");
+ throw lang::DisposedException();
+ }
+
+ if ( !m_xOutStream.is() )
+ throw uno::RuntimeException();
+
+ uno::Reference< io::XTruncate > xTruncate( m_xOutStream, uno::UNO_QUERY_THROW );
+ xTruncate->truncate();
+
+ m_pImpl->m_bHasDataToFlush = true;
+
+ ModifyParentUnlockMutex_Impl( aGuard );
+}
+
+void SAL_CALL OWriteStream::dispose()
+{
+ // should be an internal method since it can be called only from parent storage
+ {
+ ::osl::MutexGuard aGuard( m_pData->m_xSharedMutex->GetMutex() );
+
+ if ( !m_pImpl )
+ {
+ SAL_INFO("package.xstor", "Disposed!");
+ throw lang::DisposedException();
+ }
+
+ if ( m_xOutStream.is() )
+ CloseOutput_Impl();
+
+ if ( m_xInStream.is() )
+ {
+ m_xInStream->closeInput();
+ m_xInStream.clear();
+ }
+
+ m_xSeekable.clear();
+
+ m_pImpl->m_pAntiImpl = nullptr;
+
+ if ( !m_bInitOnDemand )
+ {
+ try
+ {
+ if ( !m_bTransacted )
+ {
+ m_pImpl->Commit();
+ }
+ else
+ {
+ // throw away all the changes
+ m_pImpl->Revert();
+ }
+ }
+ catch( const uno::Exception& )
+ {
+ uno::Any aCaught( ::cppu::getCaughtException() );
+ SAL_INFO("package.xstor", "Rethrow: " << exceptionToString(aCaught));
+ throw lang::WrappedTargetRuntimeException("Can not commit/revert the storage!",
+ static_cast< OWeakObject* >( this ),
+ aCaught );
+ }
+ }
+
+ m_pImpl = nullptr;
+ }
+
+ // the listener might try to get rid of parent storage, and the storage would delete this object;
+ // for now the listener is just notified at the end of the method to workaround the problem
+ // in future a more elegant way should be found
+
+ lang::EventObject aSource( static_cast< ::cppu::OWeakObject* >(this) );
+ m_pData->m_aListenersContainer.disposeAndClear( aSource );
+}
+
+void SAL_CALL OWriteStream::addEventListener(
+ const uno::Reference< lang::XEventListener >& xListener )
+{
+ ::osl::MutexGuard aGuard( m_pData->m_xSharedMutex->GetMutex() );
+
+ if ( !m_pImpl )
+ {
+ SAL_INFO("package.xstor", "Disposed!");
+ throw lang::DisposedException();
+ }
+
+ m_pData->m_aListenersContainer.addInterface( cppu::UnoType<lang::XEventListener>::get(),
+ xListener );
+}
+
+void SAL_CALL OWriteStream::removeEventListener(
+ const uno::Reference< lang::XEventListener >& xListener )
+{
+ ::osl::MutexGuard aGuard( m_pData->m_xSharedMutex->GetMutex() );
+
+ if ( !m_pImpl )
+ {
+ SAL_INFO("package.xstor", "Disposed!");
+ throw lang::DisposedException();
+ }
+
+ m_pData->m_aListenersContainer.removeInterface( cppu::UnoType<lang::XEventListener>::get(),
+ xListener );
+}
+
+void SAL_CALL OWriteStream::setEncryptionPassword( const OUString& aPass )
+{
+ osl::ClearableMutexGuard aGuard(m_pData->m_xSharedMutex->GetMutex());
+
+ CheckInitOnDemand();
+
+ if ( !m_pImpl )
+ {
+ SAL_INFO("package.xstor", "Disposed!");
+ throw lang::DisposedException();
+ }
+
+ OSL_ENSURE( m_pImpl->m_xPackageStream.is(), "No package stream is set!" );
+
+ m_pImpl->SetEncrypted( ::comphelper::OStorageHelper::CreatePackageEncryptionData( aPass ) );
+
+ ModifyParentUnlockMutex_Impl( aGuard );
+}
+
+void SAL_CALL OWriteStream::removeEncryption()
+{
+ osl::ClearableMutexGuard aGuard(m_pData->m_xSharedMutex->GetMutex());
+
+ CheckInitOnDemand();
+
+ if ( !m_pImpl )
+ {
+ SAL_INFO("package.xstor", "Disposed!");
+ throw lang::DisposedException();
+ }
+
+ OSL_ENSURE( m_pImpl->m_xPackageStream.is(), "No package stream is set!" );
+
+ m_pImpl->SetDecrypted();
+
+ ModifyParentUnlockMutex_Impl( aGuard );
+}
+
+void SAL_CALL OWriteStream::setEncryptionData( const uno::Sequence< beans::NamedValue >& aEncryptionData )
+{
+ osl::ClearableMutexGuard aGuard(m_pData->m_xSharedMutex->GetMutex());
+
+ CheckInitOnDemand();
+
+ if ( !m_pImpl )
+ {
+ SAL_INFO("package.xstor", "Disposed!");
+ throw lang::DisposedException();
+ }
+
+ OSL_ENSURE( m_pImpl->m_xPackageStream.is(), "No package stream is set!" );
+
+ m_pImpl->SetEncrypted( aEncryptionData );
+
+ ModifyParentUnlockMutex_Impl( aGuard );
+}
+
+sal_Bool SAL_CALL OWriteStream::hasEncryptionData()
+{
+ osl::ClearableMutexGuard aGuard(m_pData->m_xSharedMutex->GetMutex());
+
+ if (!m_pImpl)
+ return false;
+
+ bool bRet = false;
+
+ try
+ {
+ bRet = m_pImpl->IsEncrypted();
+
+ if (!bRet && m_pImpl->m_bUseCommonEncryption && m_pImpl->m_pParent)
+ bRet = m_pImpl->m_pParent->m_bHasCommonEncryptionData;
+ }
+ catch( const uno::RuntimeException& )
+ {
+ TOOLS_INFO_EXCEPTION("package.xstor", "Rethrow");
+ throw;
+ }
+ catch( const uno::Exception& )
+ {
+ uno::Any aCaught( ::cppu::getCaughtException() );
+ SAL_INFO("package.xstor", "Rethrow: " << exceptionToString(aCaught));
+ throw lang::WrappedTargetRuntimeException( "Problems on hasEncryptionData!",
+ static_cast< ::cppu::OWeakObject* >( this ),
+ aCaught );
+ }
+
+ return bRet;
+}
+
+sal_Bool SAL_CALL OWriteStream::hasByID( const OUString& sID )
+{
+ ::osl::MutexGuard aGuard( m_pData->m_xSharedMutex->GetMutex() );
+
+ if ( !m_pImpl )
+ {
+ SAL_INFO("package.xstor", "Disposed!");
+ throw lang::DisposedException();
+ }
+
+ if ( m_pData->m_nStorageType != embed::StorageFormats::OFOPXML )
+ throw uno::RuntimeException();
+
+ try
+ {
+ getRelationshipByID( sID );
+ return true;
+ }
+ catch( const container::NoSuchElementException& )
+ {
+ TOOLS_INFO_EXCEPTION("package.xstor", "No Element");
+ }
+
+ return false;
+}
+
+OUString SAL_CALL OWriteStream::getTargetByID( const OUString& sID )
+{
+ ::osl::MutexGuard aGuard( m_pData->m_xSharedMutex->GetMutex() );
+
+ if ( !m_pImpl )
+ {
+ SAL_INFO("package.xstor", "Disposed!");
+ throw lang::DisposedException();
+ }
+
+ if ( m_pData->m_nStorageType != embed::StorageFormats::OFOPXML )
+ throw uno::RuntimeException();
+
+ const uno::Sequence< beans::StringPair > aSeq = getRelationshipByID( sID );
+ auto pRel = lcl_findPairByName(aSeq, "Target");
+ if (pRel != aSeq.end())
+ return pRel->Second;
+
+ return OUString();
+}
+
+OUString SAL_CALL OWriteStream::getTypeByID( const OUString& sID )
+{
+ ::osl::MutexGuard aGuard( m_pData->m_xSharedMutex->GetMutex() );
+
+ if ( !m_pImpl )
+ {
+ SAL_INFO("package.xstor", "Disposed!");
+ throw lang::DisposedException();
+ }
+
+ if ( m_pData->m_nStorageType != embed::StorageFormats::OFOPXML )
+ throw uno::RuntimeException();
+
+ const uno::Sequence< beans::StringPair > aSeq = getRelationshipByID( sID );
+ auto pRel = lcl_findPairByName(aSeq, "Type");
+ if (pRel != aSeq.end())
+ return pRel->Second;
+
+ return OUString();
+}
+
+uno::Sequence< beans::StringPair > SAL_CALL OWriteStream::getRelationshipByID( const OUString& sID )
+{
+ ::osl::MutexGuard aGuard( m_pData->m_xSharedMutex->GetMutex() );
+
+ if ( !m_pImpl )
+ {
+ SAL_INFO("package.xstor", "Disposed!");
+ throw lang::DisposedException();
+ }
+
+ if ( m_pData->m_nStorageType != embed::StorageFormats::OFOPXML )
+ throw uno::RuntimeException();
+
+ // TODO/LATER: in future the unification of the ID could be checked
+ const uno::Sequence< uno::Sequence< beans::StringPair > > aSeq = getAllRelationships();
+ const beans::StringPair aIDRel("Id", sID);
+ auto pRel = std::find_if(aSeq.begin(), aSeq.end(),
+ [&aIDRel](const uno::Sequence<beans::StringPair>& rRel) {
+ return std::find(rRel.begin(), rRel.end(), aIDRel) != rRel.end(); });
+ if (pRel != aSeq.end())
+ return *pRel;
+
+ throw container::NoSuchElementException();
+}
+
+uno::Sequence< uno::Sequence< beans::StringPair > > SAL_CALL OWriteStream::getRelationshipsByType( const OUString& sType )
+{
+ ::osl::MutexGuard aGuard( m_pData->m_xSharedMutex->GetMutex() );
+
+ if ( !m_pImpl )
+ {
+ SAL_INFO("package.xstor", "Disposed!");
+ throw lang::DisposedException();
+ }
+
+ if ( m_pData->m_nStorageType != embed::StorageFormats::OFOPXML )
+ throw uno::RuntimeException();
+
+ // TODO/LATER: in future the unification of the ID could be checked
+ const uno::Sequence< uno::Sequence< beans::StringPair > > aSeq = getAllRelationships();
+ const beans::StringPair aTypeRel("Type", sType);
+ std::vector< uno::Sequence<beans::StringPair> > aResult;
+ aResult.reserve(aSeq.getLength());
+
+ std::copy_if(aSeq.begin(), aSeq.end(), std::back_inserter(aResult),
+ [&aTypeRel](const uno::Sequence<beans::StringPair>& rRel) {
+ return std::find(rRel.begin(), rRel.end(), aTypeRel) != rRel.end(); });
+
+ return comphelper::containerToSequence(aResult);
+}
+
+uno::Sequence< uno::Sequence< beans::StringPair > > SAL_CALL OWriteStream::getAllRelationships()
+{
+ ::osl::MutexGuard aGuard( m_pData->m_xSharedMutex->GetMutex() );
+
+ if ( !m_pImpl )
+ {
+ SAL_INFO("package.xstor", "Disposed!");
+ throw lang::DisposedException();
+ }
+
+ if ( m_pData->m_nStorageType != embed::StorageFormats::OFOPXML )
+ throw uno::RuntimeException();
+
+ return m_pImpl->GetAllRelationshipsIfAny();
+}
+
+void SAL_CALL OWriteStream::insertRelationshipByID( const OUString& sID, const uno::Sequence< beans::StringPair >& aEntry, sal_Bool bReplace )
+{
+ ::osl::MutexGuard aGuard( m_pData->m_xSharedMutex->GetMutex() );
+
+ if ( !m_pImpl )
+ {
+ SAL_INFO("package.xstor", "Disposed!");
+ throw lang::DisposedException();
+ }
+
+ if ( m_pData->m_nStorageType != embed::StorageFormats::OFOPXML )
+ throw uno::RuntimeException();
+
+ const beans::StringPair aIDRel("Id", sID);
+
+ uno::Sequence<beans::StringPair>* pPair = nullptr;
+
+ // TODO/LATER: in future the unification of the ID could be checked
+ uno::Sequence< uno::Sequence< beans::StringPair > > aSeq = getAllRelationships();
+ for ( sal_Int32 nInd = 0; nInd < aSeq.getLength(); nInd++ )
+ {
+ const auto& rRel = aSeq[nInd];
+ if (std::find(rRel.begin(), rRel.end(), aIDRel) != rRel.end())
+ pPair = &aSeq.getArray()[nInd];
+ }
+
+ if ( pPair && !bReplace )
+ throw container::ElementExistException(); // TODO
+
+ if ( !pPair )
+ {
+ sal_Int32 nIDInd = aSeq.getLength();
+ aSeq.realloc( nIDInd + 1 );
+ pPair = &aSeq.getArray()[nIDInd];
+ }
+
+ std::vector<beans::StringPair> aResult;
+ aResult.reserve(aEntry.getLength() + 1);
+
+ aResult.push_back(aIDRel);
+ std::copy_if(aEntry.begin(), aEntry.end(), std::back_inserter(aResult),
+ [](const beans::StringPair& rRel) { return rRel.First != "Id"; });
+
+ *pPair = comphelper::containerToSequence(aResult);
+
+ m_pImpl->m_aNewRelInfo = aSeq;
+ m_pImpl->m_xNewRelInfoStream.clear();
+ m_pImpl->m_nRelInfoStatus = RELINFO_CHANGED;
+}
+
+void SAL_CALL OWriteStream::removeRelationshipByID( const OUString& sID )
+{
+ ::osl::MutexGuard aGuard( m_pData->m_xSharedMutex->GetMutex() );
+
+ if ( !m_pImpl )
+ {
+ SAL_INFO("package.xstor", "Disposed!");
+ throw lang::DisposedException();
+ }
+
+ if ( m_pData->m_nStorageType != embed::StorageFormats::OFOPXML )
+ throw uno::RuntimeException();
+
+ uno::Sequence< uno::Sequence< beans::StringPair > > aSeq = getAllRelationships();
+ const beans::StringPair aIDRel("Id", sID);
+ auto pRel = std::find_if(std::cbegin(aSeq), std::cend(aSeq),
+ [&aIDRel](const uno::Sequence< beans::StringPair >& rRel) {
+ return std::find(rRel.begin(), rRel.end(), aIDRel) != rRel.end(); });
+ if (pRel != std::cend(aSeq))
+ {
+ auto nInd = static_cast<sal_Int32>(std::distance(std::cbegin(aSeq), pRel));
+ comphelper::removeElementAt(aSeq, nInd);
+
+ m_pImpl->m_aNewRelInfo = aSeq;
+ m_pImpl->m_xNewRelInfoStream.clear();
+ m_pImpl->m_nRelInfoStatus = RELINFO_CHANGED;
+
+ // TODO/LATER: in future the unification of the ID could be checked
+ return;
+ }
+
+ throw container::NoSuchElementException();
+}
+
+void SAL_CALL OWriteStream::insertRelationships( const uno::Sequence< uno::Sequence< beans::StringPair > >& aEntries, sal_Bool bReplace )
+{
+ ::osl::MutexGuard aGuard( m_pData->m_xSharedMutex->GetMutex() );
+
+ if ( !m_pImpl )
+ {
+ SAL_INFO("package.xstor", "Disposed!");
+ throw lang::DisposedException();
+ }
+
+ if ( m_pData->m_nStorageType != embed::StorageFormats::OFOPXML )
+ throw uno::RuntimeException();
+
+ OUString aIDTag( "Id" );
+ const uno::Sequence< uno::Sequence< beans::StringPair > > aSeq = getAllRelationships();
+ std::vector< uno::Sequence<beans::StringPair> > aResultVec;
+ aResultVec.reserve(aSeq.getLength() + aEntries.getLength());
+
+ std::copy_if(aSeq.begin(), aSeq.end(), std::back_inserter(aResultVec),
+ [&aIDTag, &aEntries, bReplace](const uno::Sequence<beans::StringPair>& rTargetRel) {
+ auto pTargetPair = lcl_findPairByName(rTargetRel, aIDTag);
+ if (pTargetPair == rTargetRel.end())
+ return false;
+
+ bool bIsSourceSame = std::any_of(aEntries.begin(), aEntries.end(),
+ [&pTargetPair](const uno::Sequence<beans::StringPair>& rSourceEntry) {
+ return std::find(rSourceEntry.begin(), rSourceEntry.end(), *pTargetPair) != rSourceEntry.end(); });
+
+ if ( bIsSourceSame && !bReplace )
+ throw container::ElementExistException();
+
+ // if no such element in the provided sequence
+ return !bIsSourceSame;
+ });
+
+ std::transform(aEntries.begin(), aEntries.end(), std::back_inserter(aResultVec),
+ [&aIDTag](const uno::Sequence<beans::StringPair>& rEntry) -> uno::Sequence<beans::StringPair> {
+ auto pPair = lcl_findPairByName(rEntry, aIDTag);
+ if (pPair == rEntry.end())
+ throw io::IOException(); // TODO: illegal relation ( no ID )
+
+ auto aResult = comphelper::sequenceToContainer<std::vector<beans::StringPair>>(rEntry);
+ auto nIDInd = std::distance(rEntry.begin(), pPair);
+ std::rotate(aResult.begin(), std::next(aResult.begin(), nIDInd), std::next(aResult.begin(), nIDInd + 1));
+
+ return comphelper::containerToSequence(aResult);
+ });
+
+ m_pImpl->m_aNewRelInfo = comphelper::containerToSequence(aResultVec);
+ m_pImpl->m_xNewRelInfoStream.clear();
+ m_pImpl->m_nRelInfoStatus = RELINFO_CHANGED;
+}
+
+void SAL_CALL OWriteStream::clearRelationships()
+{
+ ::osl::MutexGuard aGuard( m_pData->m_xSharedMutex->GetMutex() );
+
+ if ( !m_pImpl )
+ {
+ SAL_INFO("package.xstor", "Disposed!");
+ throw lang::DisposedException();
+ }
+
+ if ( m_pData->m_nStorageType != embed::StorageFormats::OFOPXML )
+ throw uno::RuntimeException();
+
+ m_pImpl->m_aNewRelInfo.realloc( 0 );
+ m_pImpl->m_xNewRelInfoStream.clear();
+ m_pImpl->m_nRelInfoStatus = RELINFO_CHANGED;
+}
+
+uno::Reference< beans::XPropertySetInfo > SAL_CALL OWriteStream::getPropertySetInfo()
+{
+ ::osl::MutexGuard aGuard( m_pData->m_xSharedMutex->GetMutex() );
+
+ //TODO:
+ return uno::Reference< beans::XPropertySetInfo >();
+}
+
+void SAL_CALL OWriteStream::setPropertyValue( const OUString& aPropertyName, const uno::Any& aValue )
+{
+ osl::ClearableMutexGuard aGuard(m_pData->m_xSharedMutex->GetMutex());
+
+ if ( !m_pImpl )
+ {
+ SAL_INFO("package.xstor", "Disposed!");
+ throw lang::DisposedException();
+ }
+
+ m_pImpl->GetStreamProperties();
+ static constexpr OUStringLiteral aCompressedString( u"Compressed" );
+ static constexpr OUStringLiteral aMediaTypeString( u"MediaType" );
+ if ( m_pData->m_nStorageType == embed::StorageFormats::PACKAGE && aPropertyName == aMediaTypeString )
+ {
+ // if the "Compressed" property is not set explicitly, the MediaType can change the default value
+ bool bCompressedValueFromType = true;
+ OUString aType;
+ aValue >>= aType;
+
+ if ( !m_pImpl->m_bCompressedSetExplicit )
+ {
+ if ( aType == "image/jpeg" || aType == "image/png" || aType == "image/gif" )
+ bCompressedValueFromType = false;
+ }
+
+ for ( auto& rProp : asNonConstRange(m_pImpl->m_aProps) )
+ {
+ if ( aPropertyName == rProp.Name )
+ rProp.Value = aValue;
+ else if ( !m_pImpl->m_bCompressedSetExplicit && aCompressedString == rProp.Name )
+ rProp.Value <<= bCompressedValueFromType;
+ }
+ }
+ else if ( aPropertyName == aCompressedString )
+ {
+ // if the "Compressed" property is not set explicitly, the MediaType can change the default value
+ m_pImpl->m_bCompressedSetExplicit = true;
+ for ( auto& rProp : asNonConstRange(m_pImpl->m_aProps) )
+ {
+ if ( aPropertyName == rProp.Name )
+ rProp.Value = aValue;
+ }
+ }
+ else if ( m_pData->m_nStorageType == embed::StorageFormats::PACKAGE
+ && aPropertyName == "UseCommonStoragePasswordEncryption" )
+ {
+ bool bUseCommonEncryption = false;
+ if ( !(aValue >>= bUseCommonEncryption) )
+ throw lang::IllegalArgumentException(); //TODO
+
+ if ( m_bInitOnDemand && m_pImpl->m_bHasInsertedStreamOptimization )
+ {
+ // the data stream is provided to the packagestream directly
+ m_pImpl->m_bUseCommonEncryption = bUseCommonEncryption;
+ }
+ else if ( bUseCommonEncryption )
+ {
+ if ( !m_pImpl->m_bUseCommonEncryption )
+ {
+ m_pImpl->SetDecrypted();
+ m_pImpl->m_bUseCommonEncryption = true;
+ }
+ }
+ else
+ m_pImpl->m_bUseCommonEncryption = false;
+ }
+ else if ( m_pData->m_nStorageType == embed::StorageFormats::OFOPXML && aPropertyName == aMediaTypeString )
+ {
+ for ( auto& rProp : asNonConstRange(m_pImpl->m_aProps) )
+ {
+ if ( aPropertyName == rProp.Name )
+ rProp.Value = aValue;
+ }
+ }
+ else if ( m_pData->m_nStorageType == embed::StorageFormats::OFOPXML && aPropertyName == "RelationsInfoStream" )
+ {
+ uno::Reference< io::XInputStream > xInRelStream;
+ if ( !( aValue >>= xInRelStream ) || !xInRelStream.is() )
+ throw lang::IllegalArgumentException(); // TODO
+
+ uno::Reference< io::XSeekable > xSeek( xInRelStream, uno::UNO_QUERY );
+ if ( !xSeek.is() )
+ {
+ // currently this is an internal property that is used for optimization
+ // and the stream must support XSeekable interface
+ // TODO/LATER: in future it can be changed if property is used from outside
+ throw lang::IllegalArgumentException(); // TODO
+ }
+
+ m_pImpl->m_xNewRelInfoStream = xInRelStream;
+ m_pImpl->m_aNewRelInfo = uno::Sequence< uno::Sequence< beans::StringPair > >();
+ m_pImpl->m_nRelInfoStatus = RELINFO_CHANGED_STREAM;
+ }
+ else if ( m_pData->m_nStorageType == embed::StorageFormats::OFOPXML && aPropertyName == "RelationsInfo" )
+ {
+ if ( !(aValue >>= m_pImpl->m_aNewRelInfo) )
+ throw lang::IllegalArgumentException(); // TODO
+ }
+ else if ( aPropertyName == "Size" )
+ throw beans::PropertyVetoException(); // TODO
+ else if ( m_pData->m_nStorageType == embed::StorageFormats::PACKAGE
+ && ( aPropertyName == "IsEncrypted" || aPropertyName == "Encrypted" ) )
+ throw beans::PropertyVetoException(); // TODO
+ else if ( aPropertyName == "RelId" )
+ {
+ aValue >>= m_pImpl->m_nRelId;
+ }
+ else
+ throw beans::UnknownPropertyException(aPropertyName); // TODO
+
+ m_pImpl->m_bHasDataToFlush = true;
+ ModifyParentUnlockMutex_Impl( aGuard );
+}
+
+uno::Any SAL_CALL OWriteStream::getPropertyValue( const OUString& aProp )
+{
+ ::osl::MutexGuard aGuard( m_pData->m_xSharedMutex->GetMutex() );
+
+ if ( !m_pImpl )
+ {
+ SAL_INFO("package.xstor", "Disposed!");
+ throw lang::DisposedException();
+ }
+
+ if ( aProp == "RelId" )
+ {
+ return uno::Any( m_pImpl->GetNewRelId() );
+ }
+
+ OUString aPropertyName;
+ if ( aProp == "IsEncrypted" )
+ aPropertyName = "Encrypted";
+ else
+ aPropertyName = aProp;
+
+ if ( ( ( m_pData->m_nStorageType == embed::StorageFormats::PACKAGE || m_pData->m_nStorageType == embed::StorageFormats::OFOPXML )
+ && aPropertyName == "MediaType" )
+ || ( m_pData->m_nStorageType == embed::StorageFormats::PACKAGE && aPropertyName == "Encrypted" )
+ || aPropertyName == "Compressed" )
+ {
+ m_pImpl->GetStreamProperties();
+
+ auto pProp = std::find_if(std::cbegin(m_pImpl->m_aProps), std::cend(m_pImpl->m_aProps),
+ [&aPropertyName](const css::beans::PropertyValue& rProp){ return aPropertyName == rProp.Name; });
+ if (pProp != std::cend(m_pImpl->m_aProps))
+ return pProp->Value;
+ }
+ else if ( m_pData->m_nStorageType == embed::StorageFormats::PACKAGE
+ && aPropertyName == "UseCommonStoragePasswordEncryption" )
+ return uno::Any( m_pImpl->m_bUseCommonEncryption );
+ else if ( aPropertyName == "Size" )
+ {
+ bool bThrow = false;
+ try
+ {
+ CheckInitOnDemand();
+ }
+ catch (const io::IOException&)
+ {
+ bThrow = true;
+ }
+ if (bThrow || !m_xSeekable.is())
+ throw uno::RuntimeException();
+
+ return uno::Any( m_xSeekable->getLength() );
+ }
+
+ throw beans::UnknownPropertyException(aPropertyName); // TODO
+}
+
+void SAL_CALL OWriteStream::addPropertyChangeListener(
+ const OUString& /*aPropertyName*/,
+ const uno::Reference< beans::XPropertyChangeListener >& /*xListener*/ )
+{
+ ::osl::MutexGuard aGuard( m_pData->m_xSharedMutex->GetMutex() );
+
+ if ( !m_pImpl )
+ {
+ SAL_INFO("package.xstor", "Disposed!");
+ throw lang::DisposedException();
+ }
+
+ //TODO:
+}
+
+void SAL_CALL OWriteStream::removePropertyChangeListener(
+ const OUString& /*aPropertyName*/,
+ const uno::Reference< beans::XPropertyChangeListener >& /*aListener*/ )
+{
+ ::osl::MutexGuard aGuard( m_pData->m_xSharedMutex->GetMutex() );
+
+ if ( !m_pImpl )
+ {
+ SAL_INFO("package.xstor", "Disposed!");
+ throw lang::DisposedException();
+ }
+
+ //TODO:
+}
+
+void SAL_CALL OWriteStream::addVetoableChangeListener(
+ const OUString& /*PropertyName*/,
+ const uno::Reference< beans::XVetoableChangeListener >& /*aListener*/ )
+{
+ ::osl::MutexGuard aGuard( m_pData->m_xSharedMutex->GetMutex() );
+
+ if ( !m_pImpl )
+ {
+ SAL_INFO("package.xstor", "Disposed!");
+ throw lang::DisposedException();
+ }
+
+ //TODO:
+}
+
+void SAL_CALL OWriteStream::removeVetoableChangeListener(
+ const OUString& /*PropertyName*/,
+ const uno::Reference< beans::XVetoableChangeListener >& /*aListener*/ )
+{
+ ::osl::MutexGuard aGuard( m_pData->m_xSharedMutex->GetMutex() );
+
+ if ( !m_pImpl )
+ {
+ SAL_INFO("package.xstor", "Disposed!");
+ throw lang::DisposedException();
+ }
+
+ //TODO:
+}
+
+// XTransactedObject
+
+void OWriteStream::BroadcastTransaction( sal_Int8 nMessage )
+/*
+ 1 - preCommit
+ 2 - committed
+ 3 - preRevert
+ 4 - reverted
+*/
+{
+ // no need to lock mutex here for the checking of m_pImpl, and m_pData is alive until the object is destructed
+ if ( !m_pImpl )
+ {
+ SAL_INFO("package.xstor", "Disposed!");
+ throw lang::DisposedException();
+ }
+
+ lang::EventObject aSource( static_cast< ::cppu::OWeakObject* >(this) );
+
+ comphelper::OInterfaceContainerHelper2* pContainer =
+ m_pData->m_aListenersContainer.getContainer(
+ cppu::UnoType<embed::XTransactionListener>::get());
+ if ( !pContainer )
+ return;
+
+ comphelper::OInterfaceIteratorHelper2 pIterator( *pContainer );
+ while ( pIterator.hasMoreElements( ) )
+ {
+ OSL_ENSURE( nMessage >= 1 && nMessage <= 4, "Wrong internal notification code is used!" );
+
+ switch( nMessage )
+ {
+ case STOR_MESS_PRECOMMIT:
+ static_cast<embed::XTransactionListener*>( pIterator.next( ) )->preCommit( aSource );
+ break;
+ case STOR_MESS_COMMITTED:
+ static_cast<embed::XTransactionListener*>( pIterator.next( ) )->commited( aSource );
+ break;
+ case STOR_MESS_PREREVERT:
+ static_cast<embed::XTransactionListener*>( pIterator.next( ) )->preRevert( aSource );
+ break;
+ case STOR_MESS_REVERTED:
+ static_cast< embed::XTransactionListener*>( pIterator.next( ) )->reverted( aSource );
+ break;
+ }
+ }
+}
+void SAL_CALL OWriteStream::commit()
+{
+ SAL_INFO( "package.xstor", "package (mv76033) OWriteStream::commit" );
+
+ if ( !m_pImpl )
+ {
+ SAL_INFO("package.xstor", "Disposed!");
+ throw lang::DisposedException();
+ }
+
+ if ( !m_bTransacted )
+ throw uno::RuntimeException();
+
+ try {
+ BroadcastTransaction( STOR_MESS_PRECOMMIT );
+
+ osl::ClearableMutexGuard aGuard(m_pData->m_xSharedMutex->GetMutex());
+
+ if ( !m_pImpl )
+ {
+ SAL_INFO("package.xstor", "Disposed!");
+ throw lang::DisposedException();
+ }
+
+ m_pImpl->Commit();
+
+ // when the storage is committed the parent is modified
+ ModifyParentUnlockMutex_Impl( aGuard );
+ }
+ catch( const io::IOException& )
+ {
+ TOOLS_INFO_EXCEPTION("package.xstor", "Rethrow");
+ throw;
+ }
+ catch( const embed::StorageWrappedTargetException& )
+ {
+ TOOLS_INFO_EXCEPTION("package.xstor", "Rethrow");
+ throw;
+ }
+ catch( const uno::RuntimeException& )
+ {
+ TOOLS_INFO_EXCEPTION("package.xstor", "Rethrow");
+ throw;
+ }
+ catch( const uno::Exception& )
+ {
+ uno::Any aCaught( ::cppu::getCaughtException() );
+ SAL_INFO("package.xstor", "Rethrow: " << exceptionToString(aCaught));
+ throw embed::StorageWrappedTargetException( "Problems on commit!",
+ static_cast< ::cppu::OWeakObject* >( this ),
+ aCaught );
+ }
+
+ BroadcastTransaction( STOR_MESS_COMMITTED );
+}
+
+void SAL_CALL OWriteStream::revert()
+{
+ SAL_INFO( "package.xstor", "package (mv76033) OWriteStream::revert" );
+
+ // the method removes all the changes done after last commit
+
+ if ( !m_pImpl )
+ {
+ SAL_INFO("package.xstor", "Disposed!");
+ throw lang::DisposedException();
+ }
+
+ if ( !m_bTransacted )
+ throw uno::RuntimeException();
+
+ BroadcastTransaction( STOR_MESS_PREREVERT );
+
+ {
+ osl::MutexGuard aGuard(m_pData->m_xSharedMutex->GetMutex());
+
+ if (!m_pImpl)
+ {
+ SAL_INFO("package.xstor", "Disposed!");
+ throw lang::DisposedException();
+ }
+
+ try {
+ m_pImpl->Revert();
+ }
+ catch (const io::IOException&)
+ {
+ TOOLS_INFO_EXCEPTION("package.xstor", "Rethrow");
+ throw;
+ }
+ catch (const embed::StorageWrappedTargetException&)
+ {
+ TOOLS_INFO_EXCEPTION("package.xstor", "Rethrow");
+ throw;
+ }
+ catch (const uno::RuntimeException&)
+ {
+ TOOLS_INFO_EXCEPTION("package.xstor", "Rethrow");
+ throw;
+ }
+ catch (const uno::Exception&)
+ {
+ uno::Any aCaught(::cppu::getCaughtException());
+ SAL_INFO("package.xstor", "Rethrow: " << exceptionToString(aCaught));
+ throw embed::StorageWrappedTargetException("Problems on revert!",
+ static_cast<::cppu::OWeakObject*>(this),
+ aCaught);
+ }
+ }
+
+ BroadcastTransaction( STOR_MESS_REVERTED );
+}
+
+// XTransactionBroadcaster
+
+void SAL_CALL OWriteStream::addTransactionListener( const uno::Reference< embed::XTransactionListener >& aListener )
+{
+ ::osl::MutexGuard aGuard( m_pData->m_xSharedMutex->GetMutex() );
+
+ if ( !m_pImpl )
+ {
+ SAL_INFO("package.xstor", "Disposed!");
+ throw lang::DisposedException();
+ }
+
+ if ( !m_bTransacted )
+ throw uno::RuntimeException();
+
+ m_pData->m_aListenersContainer.addInterface( cppu::UnoType<embed::XTransactionListener>::get(),
+ aListener );
+}
+
+void SAL_CALL OWriteStream::removeTransactionListener( const uno::Reference< embed::XTransactionListener >& aListener )
+{
+ ::osl::MutexGuard aGuard( m_pData->m_xSharedMutex->GetMutex() );
+
+ if ( !m_pImpl )
+ {
+ SAL_INFO("package.xstor", "Disposed!");
+ throw lang::DisposedException();
+ }
+
+ if ( !m_bTransacted )
+ throw uno::RuntimeException();
+
+ m_pData->m_aListenersContainer.removeInterface( cppu::UnoType<embed::XTransactionListener>::get(),
+ aListener );
+}
+
+/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
diff --git a/package/source/xstor/owriteablestream.hxx b/package/source/xstor/owriteablestream.hxx
new file mode 100644
index 000000000..6c2b657e3
--- /dev/null
+++ b/package/source/xstor/owriteablestream.hxx
@@ -0,0 +1,359 @@
+/* -*- 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 .
+ */
+
+#ifndef INCLUDED_PACKAGE_SOURCE_XSTOR_OWRITEABLESTREAM_HXX
+#define INCLUDED_PACKAGE_SOURCE_XSTOR_OWRITEABLESTREAM_HXX
+
+#include <com/sun/star/io/XInputStream.hpp>
+#include <com/sun/star/io/XOutputStream.hpp>
+#include <com/sun/star/io/XStream.hpp>
+#include <com/sun/star/io/XSeekable.hpp>
+#include <com/sun/star/io/XTruncate.hpp>
+#include <com/sun/star/packages/XDataSinkEncrSupport.hpp>
+#include <com/sun/star/lang/XEventListener.hpp>
+#include <com/sun/star/lang/XSingleServiceFactory.hpp>
+#include <com/sun/star/lang/XUnoTunnel.hpp>
+#include <com/sun/star/embed/XEncryptionProtectedSource2.hpp>
+#include <com/sun/star/embed/XStorage.hpp>
+#include <com/sun/star/embed/XRelationshipAccess.hpp>
+#include <com/sun/star/embed/XExtendedStorageStream.hpp>
+#include <com/sun/star/embed/XTransactedObject.hpp>
+#include <com/sun/star/embed/XTransactionBroadcaster.hpp>
+#include <com/sun/star/container/XNameContainer.hpp>
+#include <com/sun/star/beans/StringPair.hpp>
+
+#include <cppuhelper/weak.hxx>
+
+#include <comphelper/bytereader.hxx>
+#include <comphelper/refcountedmutex.hxx>
+#include <comphelper/sequenceashashmap.hxx>
+
+#include <vector>
+#include <memory>
+#include <string_view>
+
+#include "ocompinstream.hxx"
+
+namespace com::sun::star::uno {
+ class XComponentContext;
+}
+
+namespace package {
+ // all data in aHash1 is contained in aHash2
+ bool PackageEncryptionDataLessOrEqual( const ::comphelper::SequenceAsHashMap& aHash1, const ::comphelper::SequenceAsHashMap& aHash2 );
+}
+
+struct WSInternalData_Impl;
+
+struct OStorage_Impl;
+class OWriteStream;
+
+struct OWriteStream_Impl
+{
+ rtl::Reference<comphelper::RefCountedMutex> m_xMutex;
+
+ friend struct OStorage_Impl;
+ friend class OWriteStream;
+ friend class OInputCompStream;
+
+ OWriteStream* m_pAntiImpl;
+ OUString m_aTempURL;
+
+ css::uno::Reference< css::io::XStream > m_xCacheStream;
+ css::uno::Reference< css::io::XSeekable > m_xCacheSeek;
+
+ std::vector< OInputCompStream* > m_aInputStreamsVector;
+
+ bool m_bHasDataToFlush; // only modified elements will be sent to the original content
+ bool m_bFlushed; // sending the streams is coordinated by the root storage of the package
+
+ css::uno::Reference< css::packages::XDataSinkEncrSupport > m_xPackageStream;
+
+ css::uno::Reference< css::uno::XComponentContext > m_xContext;
+
+ OStorage_Impl* m_pParent;
+
+ css::uno::Sequence< css::beans::PropertyValue > m_aProps;
+
+ bool m_bForceEncrypted;
+
+ bool m_bUseCommonEncryption;
+ bool m_bHasCachedEncryptionData;
+ ::comphelper::SequenceAsHashMap m_aEncryptionData;
+
+ bool m_bCompressedSetExplicit;
+
+ css::uno::Reference< css::lang::XSingleServiceFactory > m_xPackage;
+
+ bool m_bHasInsertedStreamOptimization;
+
+ sal_Int32 m_nStorageType;
+
+ // Relations info related data, stored in *.rels file in OFOPXML format
+ css::uno::Reference< css::io::XInputStream > m_xOrigRelInfoStream;
+ css::uno::Sequence< css::uno::Sequence< css::beans::StringPair > > m_aOrigRelInfo;
+ bool m_bOrigRelInfoBroken;
+
+ css::uno::Sequence< css::uno::Sequence< css::beans::StringPair > > m_aNewRelInfo;
+ css::uno::Reference< css::io::XInputStream > m_xNewRelInfoStream;
+ sal_Int16 m_nRelInfoStatus;
+ sal_Int32 m_nRelId;
+
+private:
+ OUString const & GetFilledTempFileIfNo( const css::uno::Reference< css::io::XInputStream >& xStream );
+ OUString const & FillTempGetFileName();
+ css::uno::Reference< css::io::XStream > GetTempFileAsStream();
+ css::uno::Reference< css::io::XInputStream > GetTempFileAsInputStream();
+
+ css::uno::Reference< css::io::XStream > GetStream_Impl( sal_Int32 nStreamMode,
+ bool bHierarchyAccess );
+
+ /// @throws css::packages::NoEncryptionException
+ ::comphelper::SequenceAsHashMap GetCommonRootEncryptionData();
+
+ css::uno::Sequence< css::beans::PropertyValue > ReadPackageStreamProperties();
+ css::uno::Sequence< css::beans::PropertyValue > InsertOwnProps(
+ const css::uno::Sequence< css::beans::PropertyValue >& aProps,
+ bool bUseCommonEncryption );
+
+public:
+ OWriteStream_Impl(
+ OStorage_Impl* pParent,
+ const css::uno::Reference< css::packages::XDataSinkEncrSupport >& xPackageStream,
+ const css::uno::Reference< css::lang::XSingleServiceFactory >& xPackage,
+ const css::uno::Reference< css::uno::XComponentContext >& xContext,
+ bool bForceEncrypted,
+ sal_Int32 nStorageType,
+ bool bDefaultCompress,
+ const css::uno::Reference< css::io::XInputStream >& xRelInfoStream =
+ css::uno::Reference< css::io::XInputStream >() );
+
+ ~OWriteStream_Impl();
+
+ void CleanCacheStream();
+
+ bool UsesCommonEncryption_Impl() const { return m_bUseCommonEncryption; }
+ bool HasTempFile_Impl() const { return ( m_aTempURL.getLength() != 0 ); }
+ bool IsTransacted();
+
+ bool HasWriteOwner_Impl() const { return ( m_pAntiImpl != nullptr ); }
+
+ void InsertIntoPackageFolder(
+ const OUString& aName,
+ const css::uno::Reference< css::container::XNameContainer >& xParentPackageFolder );
+
+ void SetToBeCommited() { m_bFlushed = true; }
+
+ bool HasCachedEncryptionData() const { return m_bHasCachedEncryptionData; }
+ ::comphelper::SequenceAsHashMap& GetCachedEncryptionData() { return m_aEncryptionData; }
+
+ bool IsModified() const { return m_bHasDataToFlush || m_bFlushed; }
+
+ bool IsEncrypted();
+ void SetDecrypted();
+ void SetEncrypted( const ::comphelper::SequenceAsHashMap& aEncryptionData );
+
+ void DisposeWrappers();
+
+ void InsertStreamDirectly(
+ const css::uno::Reference< css::io::XInputStream >& xInStream,
+ const css::uno::Sequence< css::beans::PropertyValue >& aProps );
+
+ void Commit();
+ void Revert();
+
+ css::uno::Sequence< css::beans::PropertyValue > const & GetStreamProperties();
+
+ css::uno::Sequence< css::uno::Sequence< css::beans::StringPair > > GetAllRelationshipsIfAny();
+
+ void CopyInternallyTo_Impl( const css::uno::Reference< css::io::XStream >& xDestStream,
+ const ::comphelper::SequenceAsHashMap& aEncryptionData );
+ void CopyInternallyTo_Impl( const css::uno::Reference< css::io::XStream >& xDestStream );
+
+ css::uno::Reference< css::io::XStream > GetStream(
+ sal_Int32 nStreamMode,
+ const ::comphelper::SequenceAsHashMap& aEncryptionData,
+ bool bHierarchyAccess );
+
+ css::uno::Reference< css::io::XStream > GetStream(
+ sal_Int32 nStreamMode,
+ bool bHierarchyAccess );
+
+ css::uno::Reference< css::io::XInputStream > GetRawInStream();
+ css::uno::Reference< css::io::XInputStream > GetPlainRawInStream();
+
+ void InputStreamDisposed( OInputCompStream* pStream );
+
+ void CreateReadonlyCopyBasedOnData(
+ const css::uno::Reference< css::io::XInputStream >& xDataToCopy,
+ const css::uno::Sequence< css::beans::PropertyValue >& aProps,
+ css::uno::Reference< css::io::XStream >& xTargetStream );
+
+ void GetCopyOfLastCommit( css::uno::Reference< css::io::XStream >& xTargetStream );
+ void GetCopyOfLastCommit(
+ css::uno::Reference< css::io::XStream >& xTargetStream,
+ const ::comphelper::SequenceAsHashMap& aEncryptionData );
+
+ void CommitStreamRelInfo(
+ const css::uno::Reference< css::embed::XStorage >& xRelStorage,
+ std::u16string_view aOrigStreamName,
+ std::u16string_view aNewStreamName );
+
+ void ReadRelInfoIfNecessary();
+
+ sal_Int32 GetNewRelId() { return m_nRelId ++; }
+};
+
+class OWriteStream : public css::lang::XTypeProvider
+ , public css::io::XInputStream
+ , public css::io::XOutputStream
+ , public css::embed::XExtendedStorageStream
+ , public css::io::XSeekable
+ , public css::io::XTruncate
+ , public css::embed::XEncryptionProtectedSource2
+ , public css::embed::XRelationshipAccess
+ , public css::embed::XTransactedObject
+ , public css::embed::XTransactionBroadcaster
+ , public css::beans::XPropertySet
+ , public css::lang::XUnoTunnel
+ , public ::cppu::OWeakObject
+ , public comphelper::ByteWriter
+{
+ friend struct OWriteStream_Impl;
+
+protected:
+ css::uno::Reference < css::io::XInputStream > m_xInStream;
+ css::uno::Reference < css::io::XOutputStream > m_xOutStream;
+ css::uno::Reference < css::io::XSeekable > m_xSeekable;
+
+ OWriteStream_Impl* m_pImpl;
+ std::unique_ptr<WSInternalData_Impl> m_pData;
+
+ bool m_bInStreamDisconnected;
+ bool m_bInitOnDemand;
+ sal_Int64 m_nInitPosition;
+
+ bool m_bTransacted;
+
+ OWriteStream( OWriteStream_Impl* pImpl, bool bTransacted );
+ OWriteStream( OWriteStream_Impl* pImpl, css::uno::Reference< css::io::XStream > const & xStream, bool bTransacted );
+
+ void CloseOutput_Impl();
+
+ void CopyToStreamInternally_Impl( const css::uno::Reference< css::io::XStream >& xStream );
+
+ void ModifyParentUnlockMutex_Impl(osl::ClearableMutexGuard& aGuard);
+
+ void BroadcastTransaction( sal_Int8 nMessage );
+
+public:
+
+ virtual ~OWriteStream() override;
+
+ void CheckInitOnDemand();
+ void DeInit();
+
+ // XInterface
+ virtual css::uno::Any SAL_CALL queryInterface( const css::uno::Type& rType ) override;
+ virtual void SAL_CALL acquire() noexcept override;
+ virtual void SAL_CALL release() noexcept override;
+
+ // XTypeProvider
+ virtual css::uno::Sequence< css::uno::Type > SAL_CALL getTypes() override;
+ virtual css::uno::Sequence< sal_Int8 > SAL_CALL getImplementationId() override;
+
+ // XInputStream
+ virtual sal_Int32 SAL_CALL readBytes( css::uno::Sequence< sal_Int8 >& aData, sal_Int32 nBytesToRead ) override;
+ virtual sal_Int32 SAL_CALL readSomeBytes( css::uno::Sequence< sal_Int8 >& aData, sal_Int32 nMaxBytesToRead ) override;
+ virtual void SAL_CALL skipBytes( sal_Int32 nBytesToSkip ) override;
+ virtual sal_Int32 SAL_CALL available( ) override;
+ virtual void SAL_CALL closeInput( ) override;
+
+ // XOutputStream
+ virtual void SAL_CALL writeBytes( const css::uno::Sequence< sal_Int8 >& aData ) override;
+ virtual void SAL_CALL flush( ) override;
+ virtual void SAL_CALL closeOutput( ) override;
+
+ //XSeekable
+ virtual void SAL_CALL seek( sal_Int64 location ) override;
+ virtual sal_Int64 SAL_CALL getPosition() override;
+ virtual sal_Int64 SAL_CALL getLength() override;
+
+ //XStream
+ virtual css::uno::Reference< css::io::XInputStream > SAL_CALL getInputStream( ) override;
+ virtual css::uno::Reference< css::io::XOutputStream > SAL_CALL getOutputStream( ) override;
+
+ // XTruncate
+ virtual void SAL_CALL truncate() override;
+
+ //XComponent
+ virtual void SAL_CALL dispose() override;
+ virtual void SAL_CALL addEventListener( const css::uno::Reference< css::lang::XEventListener >& xListener ) override;
+ virtual void SAL_CALL removeEventListener( const css::uno::Reference< css::lang::XEventListener >& aListener ) override;
+
+ //XEncryptionProtectedSource
+ virtual void SAL_CALL setEncryptionPassword( const OUString& aPass ) override;
+ virtual void SAL_CALL removeEncryption() override;
+
+ //XEncryptionProtectedSource2
+ virtual void SAL_CALL setEncryptionData( const css::uno::Sequence< css::beans::NamedValue >& aEncryptionData ) override;
+ virtual sal_Bool SAL_CALL hasEncryptionData() override;
+
+ //XRelationshipAccess
+ virtual sal_Bool SAL_CALL hasByID( const OUString& sID ) override;
+ virtual OUString SAL_CALL getTargetByID( const OUString& sID ) override;
+ virtual OUString SAL_CALL getTypeByID( const OUString& sID ) override;
+ virtual css::uno::Sequence< css::beans::StringPair > SAL_CALL getRelationshipByID( const OUString& sID ) override;
+ virtual css::uno::Sequence< css::uno::Sequence< css::beans::StringPair > > SAL_CALL getRelationshipsByType( const OUString& sType ) override;
+ virtual css::uno::Sequence< css::uno::Sequence< css::beans::StringPair > > SAL_CALL getAllRelationships( ) override;
+ virtual void SAL_CALL insertRelationshipByID( const OUString& sID, const css::uno::Sequence< css::beans::StringPair >& aEntry, sal_Bool bReplace ) override;
+ virtual void SAL_CALL removeRelationshipByID( const OUString& sID ) override;
+ virtual void SAL_CALL insertRelationships( const css::uno::Sequence< css::uno::Sequence< css::beans::StringPair > >& aEntries, sal_Bool bReplace ) override;
+ virtual void SAL_CALL clearRelationships( ) override;
+
+ //XPropertySet
+ virtual css::uno::Reference< css::beans::XPropertySetInfo > SAL_CALL getPropertySetInfo() override;
+ virtual void SAL_CALL setPropertyValue( const OUString& aPropertyName, const css::uno::Any& aValue ) override;
+ virtual css::uno::Any SAL_CALL getPropertyValue( const OUString& PropertyName ) override;
+ virtual void SAL_CALL addPropertyChangeListener( const OUString& aPropertyName, const css::uno::Reference< css::beans::XPropertyChangeListener >& xListener ) override;
+ virtual void SAL_CALL removePropertyChangeListener( const OUString& aPropertyName, const css::uno::Reference< css::beans::XPropertyChangeListener >& aListener ) override;
+ virtual void SAL_CALL addVetoableChangeListener( const OUString& PropertyName, const css::uno::Reference< css::beans::XVetoableChangeListener >& aListener ) override;
+ virtual void SAL_CALL removeVetoableChangeListener( const OUString& PropertyName, const css::uno::Reference< css::beans::XVetoableChangeListener >& aListener ) override;
+
+ // XTransactedObject
+ virtual void SAL_CALL commit() override;
+ virtual void SAL_CALL revert() override;
+
+ // XTransactionBroadcaster
+ virtual void SAL_CALL addTransactionListener(
+ const css::uno::Reference< css::embed::XTransactionListener >& aListener ) override;
+ virtual void SAL_CALL removeTransactionListener(
+ const css::uno::Reference< css::embed::XTransactionListener >& aListener ) override;
+
+ // XUnoTunnel
+ virtual sal_Int64 SAL_CALL getSomething( const css::uno::Sequence< sal_Int8 >& aIdentifier ) override;
+
+ // comphelper::ByteWriter
+ virtual sal_Int32 writeSomeBytes(const sal_Int8* aData, sal_Int32 nBytesToWrite) override;
+
+};
+
+#endif
+
+/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
diff --git a/package/source/xstor/selfterminatefilestream.cxx b/package/source/xstor/selfterminatefilestream.cxx
new file mode 100644
index 000000000..9ee3673ff
--- /dev/null
+++ b/package/source/xstor/selfterminatefilestream.cxx
@@ -0,0 +1,105 @@
+/* -*- 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 <com/sun/star/ucb/SimpleFileAccess.hpp>
+
+#include "selfterminatefilestream.hxx"
+#include <comphelper/processfactory.hxx>
+
+using namespace ::com::sun::star;
+
+OSelfTerminateFileStream::OSelfTerminateFileStream( const uno::Reference< uno::XComponentContext >& xContext, const OUString& aURL )
+: m_aURL( aURL )
+{
+ uno::Reference< uno::XComponentContext > xOwnContext = xContext;
+ if ( !xOwnContext.is() )
+ xOwnContext.set( ::comphelper::getProcessComponentContext(), uno::UNO_SET_THROW );
+
+ // IMPORTANT: The implementation is based on idea that m_xFileAccess, m_xInputStream and m_xSeekable are always set
+ // otherwise an exception is thrown in constructor
+
+ m_xFileAccess.set( ucb::SimpleFileAccess::create(xOwnContext) );
+
+ m_xInputStream.set( m_xFileAccess->openFileRead( aURL ), uno::UNO_SET_THROW );
+ m_xSeekable.set( m_xInputStream, uno::UNO_QUERY_THROW );
+}
+
+OSelfTerminateFileStream::~OSelfTerminateFileStream()
+{
+ CloseStreamDeleteFile();
+}
+
+void OSelfTerminateFileStream::CloseStreamDeleteFile()
+{
+ try
+ {
+ m_xInputStream->closeInput();
+ }
+ catch( uno::Exception& )
+ {}
+
+ try
+ {
+ m_xFileAccess->kill( m_aURL );
+ }
+ catch( uno::Exception& )
+ {}
+}
+
+sal_Int32 SAL_CALL OSelfTerminateFileStream::readBytes( uno::Sequence< sal_Int8 >& aData, sal_Int32 nBytesToRead )
+{
+ return m_xInputStream->readBytes( aData, nBytesToRead );
+}
+
+sal_Int32 SAL_CALL OSelfTerminateFileStream::readSomeBytes( uno::Sequence< sal_Int8 >& aData, sal_Int32 nMaxBytesToRead )
+{
+ return m_xInputStream->readSomeBytes( aData, nMaxBytesToRead );
+}
+
+void SAL_CALL OSelfTerminateFileStream::skipBytes( sal_Int32 nBytesToSkip )
+{
+ return m_xInputStream->skipBytes( nBytesToSkip );
+}
+
+sal_Int32 SAL_CALL OSelfTerminateFileStream::available( )
+{
+ return m_xInputStream->available();
+}
+
+void SAL_CALL OSelfTerminateFileStream::closeInput( )
+{
+ CloseStreamDeleteFile();
+}
+
+void SAL_CALL OSelfTerminateFileStream::seek( sal_Int64 location )
+{
+ m_xSeekable->seek( location );
+}
+
+sal_Int64 SAL_CALL OSelfTerminateFileStream::getPosition()
+{
+ return m_xSeekable->getPosition();
+}
+
+sal_Int64 SAL_CALL OSelfTerminateFileStream::getLength()
+{
+ return m_xSeekable->getLength();
+}
+
+/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
diff --git a/package/source/xstor/selfterminatefilestream.hxx b/package/source/xstor/selfterminatefilestream.hxx
new file mode 100644
index 000000000..14bf3a049
--- /dev/null
+++ b/package/source/xstor/selfterminatefilestream.hxx
@@ -0,0 +1,64 @@
+/* -*- 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 .
+ */
+
+#ifndef INCLUDED_PACKAGE_SOURCE_XSTOR_SELFTERMINATEFILESTREAM_HXX
+#define INCLUDED_PACKAGE_SOURCE_XSTOR_SELFTERMINATEFILESTREAM_HXX
+
+#include <com/sun/star/io/XInputStream.hpp>
+#include <com/sun/star/io/XSeekable.hpp>
+#include <com/sun/star/ucb/XSimpleFileAccess3.hpp>
+#include <com/sun/star/uno/XComponentContext.hpp>
+#include <cppuhelper/implbase.hxx>
+
+struct OWriteStream_Impl;
+
+class OSelfTerminateFileStream final : public cppu::WeakImplHelper< css::io::XInputStream,
+ css::io::XSeekable >
+{
+ css::uno::Reference< css::ucb::XSimpleFileAccess3 > m_xFileAccess;
+
+ OUString m_aURL;
+
+ css::uno::Reference< css::io::XInputStream > m_xInputStream;
+ css::uno::Reference< css::io::XSeekable > m_xSeekable;
+
+public:
+ OSelfTerminateFileStream( const css::uno::Reference< css::uno::XComponentContext >& xContext, const OUString& aURL );
+
+ virtual ~OSelfTerminateFileStream() override;
+
+ void CloseStreamDeleteFile();
+
+ // XInputStream
+ virtual sal_Int32 SAL_CALL readBytes( css::uno::Sequence< sal_Int8 >& aData, sal_Int32 nBytesToRead ) override;
+ virtual sal_Int32 SAL_CALL readSomeBytes( css::uno::Sequence< sal_Int8 >& aData, sal_Int32 nMaxBytesToRead ) override;
+ virtual void SAL_CALL skipBytes( sal_Int32 nBytesToSkip ) override;
+ virtual sal_Int32 SAL_CALL available() override;
+ virtual void SAL_CALL closeInput() override;
+
+ //XSeekable
+ virtual void SAL_CALL seek( sal_Int64 location ) override;
+ virtual sal_Int64 SAL_CALL getPosition() override;
+ virtual sal_Int64 SAL_CALL getLength() override;
+
+};
+
+#endif
+
+/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
diff --git a/package/source/xstor/switchpersistencestream.cxx b/package/source/xstor/switchpersistencestream.cxx
new file mode 100644
index 000000000..ff9828a72
--- /dev/null
+++ b/package/source/xstor/switchpersistencestream.cxx
@@ -0,0 +1,409 @@
+/* -*- 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 <osl/diagnose.h>
+#include <com/sun/star/io/IOException.hpp>
+#include <com/sun/star/io/NotConnectedException.hpp>
+#include <com/sun/star/io/TempFile.hpp>
+#include <comphelper/storagehelper.hxx>
+#include "switchpersistencestream.hxx"
+
+using namespace ::com::sun::star;
+
+struct SPStreamData_Impl
+{
+ bool m_bInStreamBased;
+
+ // the streams below are not visible from outside so there is no need to remember position
+
+ // original stream related members
+ uno::Reference< io::XTruncate > m_xOrigTruncate;
+ uno::Reference< io::XSeekable > m_xOrigSeekable;
+ uno::Reference< io::XInputStream > m_xOrigInStream;
+ uno::Reference< io::XOutputStream > m_xOrigOutStream;
+
+ bool m_bInOpen;
+ bool m_bOutOpen;
+
+ SPStreamData_Impl(
+ bool bInStreamBased,
+ const uno::Reference< io::XTruncate >& xOrigTruncate,
+ const uno::Reference< io::XSeekable >& xOrigSeekable,
+ const uno::Reference< io::XInputStream >& xOrigInStream,
+ const uno::Reference< io::XOutputStream >& xOrigOutStream,
+ bool bInOpen,
+ bool bOutOpen )
+ : m_bInStreamBased( bInStreamBased )
+ , m_xOrigTruncate( xOrigTruncate )
+ , m_xOrigSeekable( xOrigSeekable )
+ , m_xOrigInStream( xOrigInStream )
+ , m_xOrigOutStream( xOrigOutStream )
+ , m_bInOpen( bInOpen )
+ , m_bOutOpen( bOutOpen )
+ {
+ }
+};
+
+SwitchablePersistenceStream::SwitchablePersistenceStream(
+ const uno::Reference< uno::XComponentContext >& xContext,
+ const uno::Reference< io::XStream >& xStream )
+: m_xContext( xContext )
+{
+ SwitchPersistenceTo( xStream );
+}
+
+SwitchablePersistenceStream::SwitchablePersistenceStream(
+ const uno::Reference< uno::XComponentContext >& xContext,
+ const uno::Reference< io::XInputStream >& xInputStream )
+: m_xContext( xContext )
+{
+ SwitchPersistenceTo( xInputStream );
+}
+
+SwitchablePersistenceStream::~SwitchablePersistenceStream()
+{
+ CloseAll_Impl();
+}
+
+void SwitchablePersistenceStream::SwitchPersistenceTo( const uno::Reference< io::XStream >& xStream )
+{
+ uno::Reference< io::XTruncate > xNewTruncate( xStream, uno::UNO_QUERY_THROW );
+ uno::Reference< io::XSeekable > xNewSeekable( xStream, uno::UNO_QUERY_THROW );
+ uno::Reference< io::XInputStream > xNewInStream = xStream->getInputStream();
+ uno::Reference< io::XOutputStream > xNewOutStream = xStream->getOutputStream();
+ if ( !xNewInStream.is() || !xNewOutStream.is() )
+ throw uno::RuntimeException();
+
+ sal_Int64 nPos = 0;
+ bool bInOpen = false;
+ bool bOutOpen = false;
+
+ if ( m_pStreamData && m_pStreamData->m_xOrigSeekable.is() )
+ {
+ // check that the length is the same
+ if ( m_pStreamData->m_xOrigSeekable->getLength() != xNewSeekable->getLength() )
+ throw uno::RuntimeException();
+
+ // get the current position
+ nPos = m_pStreamData->m_xOrigSeekable->getPosition();
+ bInOpen = m_pStreamData->m_bInOpen;
+ bOutOpen = m_pStreamData->m_bOutOpen;
+ }
+
+ xNewSeekable->seek( nPos );
+
+ CloseAll_Impl();
+
+ m_pStreamData.reset( new SPStreamData_Impl( false,
+ xNewTruncate, xNewSeekable, xNewInStream, xNewOutStream,
+ bInOpen, bOutOpen ) );
+}
+
+void SwitchablePersistenceStream::SwitchPersistenceTo( const uno::Reference< io::XInputStream >& xInputStream )
+{
+ uno::Reference< io::XTruncate > xNewTruncate;
+ uno::Reference< io::XSeekable > xNewSeekable( xInputStream, uno::UNO_QUERY_THROW );
+ uno::Reference< io::XOutputStream > xNewOutStream;
+ if ( !xInputStream.is() )
+ throw uno::RuntimeException();
+
+ sal_Int64 nPos = 0;
+ bool bInOpen = false;
+ bool bOutOpen = false;
+
+ if ( m_pStreamData && m_pStreamData->m_xOrigSeekable.is() )
+ {
+ // check that the length is the same
+ if ( m_pStreamData->m_xOrigSeekable->getLength() != xNewSeekable->getLength() )
+ throw uno::RuntimeException();
+
+ // get the current position
+ nPos = m_pStreamData->m_xOrigSeekable->getPosition();
+ bInOpen = m_pStreamData->m_bInOpen;
+ bOutOpen = m_pStreamData->m_bOutOpen;
+ }
+
+ xNewSeekable->seek( nPos );
+
+ CloseAll_Impl();
+
+ m_pStreamData.reset( new SPStreamData_Impl( true,
+ xNewTruncate, xNewSeekable, xInputStream, xNewOutStream,
+ bInOpen, bOutOpen ) );
+
+}
+
+void SwitchablePersistenceStream::CopyAndSwitchPersistenceTo( const uno::Reference< io::XStream >& xStream )
+{
+ uno::Reference< io::XStream > xTargetStream = xStream;
+ uno::Reference< io::XSeekable > xTargetSeek;
+
+ if ( !xTargetStream.is() )
+ {
+ xTargetStream.set( io::TempFile::create(m_xContext), uno::UNO_QUERY_THROW );
+ xTargetSeek.set( xTargetStream, uno::UNO_QUERY_THROW );
+ }
+ else
+ {
+ // the provided stream must be empty
+ xTargetSeek.set( xTargetStream, uno::UNO_QUERY_THROW );
+ if ( xTargetSeek->getLength() )
+ throw io::IOException("provided stream not empty");
+ }
+
+ uno::Reference< io::XTruncate > xTargetTruncate( xTargetStream, uno::UNO_QUERY_THROW );
+ uno::Reference< io::XInputStream > xTargetInStream = xTargetStream->getInputStream();
+ uno::Reference< io::XOutputStream > xTargetOutStream = xTargetStream->getOutputStream();
+ if ( !xTargetInStream.is() || !xTargetOutStream.is() )
+ throw uno::RuntimeException();
+
+ if ( !m_pStreamData->m_xOrigInStream.is() || !m_pStreamData->m_xOrigSeekable.is() )
+ throw uno::RuntimeException();
+
+ sal_Int64 nPos = m_pStreamData->m_xOrigSeekable->getPosition();
+ m_pStreamData->m_xOrigSeekable->seek( 0 );
+ ::comphelper::OStorageHelper::CopyInputToOutput( m_pStreamData->m_xOrigInStream, xTargetOutStream );
+ xTargetOutStream->flush();
+ xTargetSeek->seek( nPos );
+
+ bool bInOpen = m_pStreamData->m_bInOpen;
+ bool bOutOpen = m_pStreamData->m_bOutOpen;
+
+ CloseAll_Impl();
+
+ m_pStreamData.reset( new SPStreamData_Impl( false,
+ xTargetTruncate, xTargetSeek, xTargetInStream, xTargetOutStream,
+ bInOpen, bOutOpen ) );
+}
+
+void SwitchablePersistenceStream::CloseAll_Impl()
+{
+ m_pStreamData.reset();
+}
+
+// css::io::XStream
+uno::Reference< io::XInputStream > SAL_CALL SwitchablePersistenceStream::getInputStream( )
+{
+ std::scoped_lock aGuard( m_aMutex );
+
+ if ( m_pStreamData )
+ m_pStreamData->m_bInOpen = true;
+ return static_cast< io::XInputStream* >( this );
+}
+
+uno::Reference< io::XOutputStream > SAL_CALL SwitchablePersistenceStream::getOutputStream( )
+{
+ std::scoped_lock aGuard( m_aMutex );
+
+ if ( m_pStreamData )
+ m_pStreamData->m_bOutOpen = true;
+ return static_cast< io::XOutputStream* >( this );
+}
+
+// css::io::XInputStream
+::sal_Int32 SAL_CALL SwitchablePersistenceStream::readBytes( uno::Sequence< ::sal_Int8 >& aData, ::sal_Int32 nBytesToRead )
+{
+ std::scoped_lock aGuard( m_aMutex );
+
+ if ( !m_pStreamData )
+ throw io::NotConnectedException();
+
+ // the original stream data should be provided
+ if ( !m_pStreamData->m_xOrigInStream.is() )
+ throw uno::RuntimeException();
+
+ return m_pStreamData->m_xOrigInStream->readBytes( aData, nBytesToRead );
+}
+
+::sal_Int32 SAL_CALL SwitchablePersistenceStream::readSomeBytes( uno::Sequence< ::sal_Int8 >& aData, ::sal_Int32 nMaxBytesToRead )
+{
+ std::scoped_lock aGuard( m_aMutex );
+
+ if ( !m_pStreamData )
+ throw io::NotConnectedException();
+
+ // the original stream data should be provided
+ if ( !m_pStreamData->m_xOrigInStream.is() )
+ throw uno::RuntimeException();
+
+ return m_pStreamData->m_xOrigInStream->readBytes( aData, nMaxBytesToRead );
+}
+
+void SAL_CALL SwitchablePersistenceStream::skipBytes( ::sal_Int32 nBytesToSkip )
+{
+ std::scoped_lock aGuard( m_aMutex );
+
+ if ( !m_pStreamData )
+ throw io::NotConnectedException();
+
+ // the original stream data should be provided
+ if ( !m_pStreamData->m_xOrigInStream.is() )
+ throw uno::RuntimeException();
+
+ m_pStreamData->m_xOrigInStream->skipBytes( nBytesToSkip );
+}
+
+::sal_Int32 SAL_CALL SwitchablePersistenceStream::available( )
+{
+ std::scoped_lock aGuard( m_aMutex );
+
+ if ( !m_pStreamData )
+ throw io::NotConnectedException();
+
+ // the original stream data should be provided
+ if ( !m_pStreamData->m_xOrigInStream.is() )
+ throw uno::RuntimeException();
+
+ return m_pStreamData->m_xOrigInStream->available();
+}
+
+void SAL_CALL SwitchablePersistenceStream::closeInput()
+{
+ std::scoped_lock aGuard( m_aMutex );
+
+ if ( !m_pStreamData )
+ throw io::NotConnectedException();
+
+ m_pStreamData->m_bInOpen = false;
+ if ( !m_pStreamData->m_bOutOpen )
+ CloseAll_Impl();
+}
+
+// css::io::XOutputStream
+void SAL_CALL SwitchablePersistenceStream::writeBytes( const uno::Sequence< ::sal_Int8 >& aData )
+{
+ std::scoped_lock aGuard( m_aMutex );
+
+ if ( !m_pStreamData )
+ throw io::NotConnectedException();
+
+ if ( m_pStreamData->m_bInStreamBased )
+ throw io::IOException();
+
+ // the original stream data should be provided
+ if ( !m_pStreamData->m_xOrigOutStream.is() )
+ throw uno::RuntimeException();
+
+ m_pStreamData->m_xOrigOutStream->writeBytes( aData );
+}
+
+void SAL_CALL SwitchablePersistenceStream::flush( )
+{
+ std::scoped_lock aGuard( m_aMutex );
+
+ if ( !m_pStreamData || m_pStreamData->m_bInStreamBased )
+ {
+ OSL_FAIL( "flush() is not acceptable!" );
+ return;
+ // in future throw exception, for now some code might call flush() on closed stream
+ // since file ucp implementation allows it
+ // throw io::NotConnectedException();
+ }
+
+ // the original stream data should be provided
+ if ( !m_pStreamData->m_xOrigOutStream.is() )
+ throw uno::RuntimeException();
+
+ m_pStreamData->m_xOrigOutStream->flush();
+}
+
+void SAL_CALL SwitchablePersistenceStream::closeOutput( )
+{
+ std::scoped_lock aGuard( m_aMutex );
+
+ if ( !m_pStreamData )
+ throw io::NotConnectedException();
+
+ m_pStreamData->m_bOutOpen = false;
+ if ( !m_pStreamData->m_bInOpen )
+ CloseAll_Impl();
+}
+
+// css::io::XTruncate
+void SAL_CALL SwitchablePersistenceStream::truncate( )
+{
+ std::scoped_lock aGuard( m_aMutex );
+
+ if ( !m_pStreamData )
+ throw io::NotConnectedException();
+
+ if ( m_pStreamData->m_bInStreamBased )
+ throw io::IOException();
+
+ // the original stream data should be provided
+ if ( !m_pStreamData->m_xOrigTruncate.is() )
+ throw uno::RuntimeException();
+
+ m_pStreamData->m_xOrigTruncate->truncate();
+}
+
+// css::io::XSeekable
+void SAL_CALL SwitchablePersistenceStream::seek( ::sal_Int64 location )
+{
+ std::scoped_lock aGuard( m_aMutex );
+
+ if ( !m_pStreamData )
+ throw io::NotConnectedException();
+
+ // the original stream data should be provided
+ if ( !m_pStreamData->m_xOrigSeekable.is() )
+ throw uno::RuntimeException();
+
+ m_pStreamData->m_xOrigSeekable->seek( location );
+}
+
+::sal_Int64 SAL_CALL SwitchablePersistenceStream::getPosition( )
+{
+ std::scoped_lock aGuard( m_aMutex );
+
+ if ( !m_pStreamData )
+ throw io::NotConnectedException();
+
+ // the original stream data should be provided
+ if ( !m_pStreamData->m_xOrigSeekable.is() )
+ throw uno::RuntimeException();
+
+ return m_pStreamData->m_xOrigSeekable->getPosition();
+}
+
+::sal_Int64 SAL_CALL SwitchablePersistenceStream::getLength( )
+{
+ std::scoped_lock aGuard( m_aMutex );
+
+ if ( !m_pStreamData )
+ throw io::NotConnectedException();
+
+ // the original stream data should be provided
+ if ( !m_pStreamData->m_xOrigSeekable.is() )
+ throw uno::RuntimeException();
+
+ return m_pStreamData->m_xOrigSeekable->getLength();
+}
+
+void SAL_CALL SwitchablePersistenceStream::waitForCompletion()
+{
+ if ( !m_pStreamData )
+ throw io::NotConnectedException();
+
+ uno::Reference< io::XAsyncOutputMonitor > asyncOutputMonitor( m_pStreamData->m_xOrigOutStream, uno::UNO_QUERY );
+ if ( asyncOutputMonitor.is() )
+ asyncOutputMonitor->waitForCompletion();
+}
+
+/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
diff --git a/package/source/xstor/switchpersistencestream.hxx b/package/source/xstor/switchpersistencestream.hxx
new file mode 100644
index 000000000..f1e9ddcee
--- /dev/null
+++ b/package/source/xstor/switchpersistencestream.hxx
@@ -0,0 +1,107 @@
+/* -*- 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 .
+ */
+#ifndef INCLUDED_PACKAGE_SOURCE_XSTOR_SWITCHPERSISTENCESTREAM_HXX
+#define INCLUDED_PACKAGE_SOURCE_XSTOR_SWITCHPERSISTENCESTREAM_HXX
+
+#include <com/sun/star/uno/Sequence.hxx>
+#include <com/sun/star/uno/Reference.hxx>
+#include <com/sun/star/uno/XComponentContext.hpp>
+#include <com/sun/star/io/XInputStream.hpp>
+#include <com/sun/star/io/XOutputStream.hpp>
+#include <com/sun/star/io/XSeekable.hpp>
+#include <com/sun/star/io/XTruncate.hpp>
+#include <com/sun/star/io/XStream.hpp>
+#include <com/sun/star/io/XAsyncOutputMonitor.hpp>
+#include <mutex>
+#include <cppuhelper/implbase.hxx>
+
+// SwitchablePersistenceStream
+
+// Allows to switch the stream persistence on the fly. The target
+// stream ( if not filled by the implementation ) MUST have the same
+// size as the original one!
+
+struct SPStreamData_Impl;
+class SwitchablePersistenceStream
+ : public ::cppu::WeakImplHelper <
+ css::io::XStream,
+ css::io::XInputStream,
+ css::io::XOutputStream,
+ css::io::XTruncate,
+ css::io::XSeekable,
+ css::io::XAsyncOutputMonitor >
+{
+ std::mutex m_aMutex;
+
+ const css::uno::Reference< css::uno::XComponentContext > m_xContext;
+
+ std::unique_ptr<SPStreamData_Impl> m_pStreamData;
+
+ void CloseAll_Impl();
+
+public:
+
+ SwitchablePersistenceStream(
+ const css::uno::Reference< css::uno::XComponentContext >& xContext,
+ const css::uno::Reference< css::io::XStream >& xStream );
+
+ SwitchablePersistenceStream(
+ const css::uno::Reference< css::uno::XComponentContext >& xContext,
+ const css::uno::Reference< css::io::XInputStream >& xInStream );
+
+ virtual ~SwitchablePersistenceStream() override;
+
+ void SwitchPersistenceTo( const css::uno::Reference< css::io::XStream >& xStream );
+
+ void SwitchPersistenceTo( const css::uno::Reference< css::io::XInputStream >& xInputStream );
+
+ void CopyAndSwitchPersistenceTo( const css::uno::Reference< css::io::XStream >& xStream );
+
+// css::io::XStream
+ virtual css::uno::Reference< css::io::XInputStream > SAL_CALL getInputStream( ) override;
+ virtual css::uno::Reference< css::io::XOutputStream > SAL_CALL getOutputStream( ) override;
+
+// css::io::XInputStream
+ virtual ::sal_Int32 SAL_CALL readBytes( css::uno::Sequence< ::sal_Int8 >& aData, ::sal_Int32 nBytesToRead ) override;
+ virtual ::sal_Int32 SAL_CALL readSomeBytes( css::uno::Sequence< ::sal_Int8 >& aData, ::sal_Int32 nMaxBytesToRead ) override;
+ virtual void SAL_CALL skipBytes( ::sal_Int32 nBytesToSkip ) override;
+ virtual ::sal_Int32 SAL_CALL available( ) override;
+ virtual void SAL_CALL closeInput( ) override;
+
+// css::io::XOutputStream
+ virtual void SAL_CALL writeBytes( const css::uno::Sequence< ::sal_Int8 >& aData ) override;
+ virtual void SAL_CALL flush( ) override;
+ virtual void SAL_CALL closeOutput( ) override;
+
+// css::io::XTruncate
+ virtual void SAL_CALL truncate( ) override;
+
+// css::io::XSeekable
+ virtual void SAL_CALL seek( ::sal_Int64 location ) override;
+ virtual ::sal_Int64 SAL_CALL getPosition( ) override;
+ virtual ::sal_Int64 SAL_CALL getLength( ) override;
+
+// css::io::XAsyncOutputMonitor
+ virtual void SAL_CALL waitForCompletion( ) override;
+
+};
+
+#endif // INCLUDED_PACKAGE_SOURCE_XSTOR_SWITCHPERSISTENCESTREAM_HXX
+
+/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
diff --git a/package/source/xstor/xfactory.cxx b/package/source/xstor/xfactory.cxx
new file mode 100644
index 000000000..38c8d4df2
--- /dev/null
+++ b/package/source/xstor/xfactory.cxx
@@ -0,0 +1,293 @@
+/* -*- 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 <sal/config.h>
+#include <sal/log.hxx>
+
+#include <com/sun/star/ucb/SimpleFileAccess.hpp>
+#include <com/sun/star/embed/ElementModes.hpp>
+#include <com/sun/star/embed/StorageFormats.hpp>
+#include <com/sun/star/beans/PropertyValue.hpp>
+#include <com/sun/star/io/IOException.hpp>
+#include <com/sun/star/io/TempFile.hpp>
+#include <com/sun/star/io/XSeekable.hpp>
+
+#include <comphelper/propertyvalue.hxx>
+#include <comphelper/storagehelper.hxx>
+#include <cppuhelper/supportsservice.hxx>
+#include <cppuhelper/weak.hxx>
+#include <osl/diagnose.h>
+
+#include "xfactory.hxx"
+#include "xstorage.hxx"
+
+using namespace ::com::sun::star;
+
+#if OSL_DEBUG_LEVEL > 0
+#define THROW_WHERE SAL_WHERE
+#else
+#define THROW_WHERE ""
+#endif
+
+static bool CheckPackageSignature_Impl( const uno::Reference< io::XInputStream >& xInputStream,
+ const uno::Reference< io::XSeekable >& xSeekable )
+{
+ if ( !xInputStream.is() || !xSeekable.is() )
+ throw uno::RuntimeException();
+
+ if ( xSeekable->getLength() )
+ {
+ uno::Sequence< sal_Int8 > aData( 4 );
+ xSeekable->seek( 0 );
+ sal_Int32 nRead = xInputStream->readBytes( aData, 4 );
+ xSeekable->seek( 0 );
+
+ // TODO/LATER: should the disk spanned files be supported?
+ // 0x50, 0x4b, 0x07, 0x08
+ return ( nRead == 4 && aData[0] == 0x50 && aData[1] == 0x4b && aData[2] == 0x03 && aData[3] == 0x04 );
+ }
+ else
+ return true; // allow to create a storage based on empty stream
+}
+
+
+
+uno::Reference< uno::XInterface > SAL_CALL OStorageFactory::createInstance()
+{
+ // TODO: reimplement TempStream service to support XStream interface
+ uno::Reference < io::XStream > xTempStream(
+ io::TempFile::create(m_xContext),
+ uno::UNO_QUERY_THROW );
+
+ return static_cast<OWeakObject*>(new OStorage(xTempStream, embed::ElementModes::READWRITE,
+ uno::Sequence<beans::PropertyValue>(), m_xContext,
+ embed::StorageFormats::PACKAGE));
+}
+
+uno::Reference< uno::XInterface > SAL_CALL OStorageFactory::createInstanceWithArguments(
+ const uno::Sequence< uno::Any >& aArguments )
+{
+ // The request for storage can be done with up to three arguments
+
+ // The first argument specifies a source for the storage
+ // it can be URL, XStream, XInputStream.
+ // The second value is a mode the storage should be open in.
+ // And the third value is a media descriptor.
+
+ sal_Int32 nArgNum = aArguments.getLength();
+ OSL_ENSURE( nArgNum < 4, "Wrong parameter number" );
+
+ if ( !nArgNum )
+ return createInstance();
+
+ // first try to retrieve storage open mode if any
+ // by default the storage will be open in readonly mode
+ sal_Int32 nStorageMode = embed::ElementModes::READ;
+ if ( nArgNum >= 2 )
+ {
+ if( !( aArguments[1] >>= nStorageMode ) )
+ {
+ OSL_FAIL( "Wrong second argument!" );
+ throw lang::IllegalArgumentException(); // TODO:
+ }
+ // it's always possible to read written storage in this implementation
+ nStorageMode |= embed::ElementModes::READ;
+ }
+
+ if ( ( nStorageMode & embed::ElementModes::TRUNCATE ) == embed::ElementModes::TRUNCATE
+ && ( nStorageMode & embed::ElementModes::WRITE ) != embed::ElementModes::WRITE )
+ throw lang::IllegalArgumentException(); // TODO:
+
+ // retrieve storage source stream
+ OUString aURL;
+ uno::Reference< io::XStream > xStream;
+ uno::Reference< io::XInputStream > xInputStream;
+
+ if ( aArguments[0] >>= aURL )
+ {
+ if ( aURL.isEmpty() )
+ {
+ OSL_FAIL( "Empty URL is provided!" );
+ throw lang::IllegalArgumentException(); // TODO:
+ }
+
+ if ( aURL.startsWithIgnoreAsciiCase("vnd.sun.star.pkg:") )
+ {
+ OSL_FAIL( "Packages URL's are not valid for storages!" ); // ???
+ throw lang::IllegalArgumentException(); // TODO:
+ }
+
+ uno::Reference < ucb::XSimpleFileAccess3 > xTempAccess(
+ ucb::SimpleFileAccess::create(
+ m_xContext ) );
+
+ if ( nStorageMode & embed::ElementModes::WRITE )
+ xStream = xTempAccess->openFileReadWrite( aURL );
+ else
+ xInputStream = xTempAccess->openFileRead( aURL );
+ }
+ else if ( !( aArguments[0] >>= xStream ) && !( aArguments[0] >>= xInputStream ) )
+ {
+ OSL_FAIL( "Wrong first argument!" );
+ throw uno::Exception("wrong first arg", nullptr); // TODO: Illegal argument
+ }
+
+ // retrieve mediadescriptor and set storage properties
+ uno::Sequence< beans::PropertyValue > aDescr;
+ uno::Sequence< beans::PropertyValue > aPropsToSet;
+
+ sal_Int32 nStorageType = embed::StorageFormats::PACKAGE;
+
+ if ( nArgNum >= 3 )
+ {
+ if( aArguments[2] >>= aDescr )
+ {
+ if ( !aURL.isEmpty() )
+ {
+ aPropsToSet = { comphelper::makePropertyValue("URL", aURL) };
+ }
+
+ sal_Int32 nNumArgs = 1;
+ for ( const auto& rProp : std::as_const(aDescr) )
+ {
+ if ( rProp.Name == "InteractionHandler"
+ || rProp.Name == "Password"
+ || rProp.Name == "RepairPackage"
+ || rProp.Name == "StatusIndicator" )
+ {
+ aPropsToSet.realloc( ++nNumArgs );
+ auto pPropsToSet = aPropsToSet.getArray();
+ pPropsToSet[nNumArgs-1].Name = rProp.Name;
+ pPropsToSet[nNumArgs-1].Value = rProp.Value;
+ }
+ else if ( rProp.Name == "StorageFormat" )
+ {
+ OUString aFormatName;
+ sal_Int32 nFormatID = 0;
+ if ( rProp.Value >>= aFormatName )
+ {
+ if ( aFormatName == PACKAGE_STORAGE_FORMAT_STRING )
+ nStorageType = embed::StorageFormats::PACKAGE;
+ else if ( aFormatName == ZIP_STORAGE_FORMAT_STRING )
+ nStorageType = embed::StorageFormats::ZIP;
+ else if ( aFormatName == OFOPXML_STORAGE_FORMAT_STRING )
+ nStorageType = embed::StorageFormats::OFOPXML;
+ else
+ throw lang::IllegalArgumentException( THROW_WHERE, uno::Reference< uno::XInterface >(), 1 );
+ }
+ else if ( rProp.Value >>= nFormatID )
+ {
+ if ( nFormatID != embed::StorageFormats::PACKAGE
+ && nFormatID != embed::StorageFormats::ZIP
+ && nFormatID != embed::StorageFormats::OFOPXML )
+ throw lang::IllegalArgumentException( THROW_WHERE, uno::Reference< uno::XInterface >(), 1 );
+
+ nStorageType = nFormatID;
+ }
+ else
+ throw lang::IllegalArgumentException( THROW_WHERE, uno::Reference< uno::XInterface >(), 1 );
+ }
+ else if (rProp.Name == "NoFileSync")
+ {
+ // Forward NoFileSync to the storage.
+ aPropsToSet.realloc(++nNumArgs);
+ auto pPropsToSet = aPropsToSet.getArray();
+ pPropsToSet[nNumArgs - 1].Name = rProp.Name;
+ pPropsToSet[nNumArgs - 1].Value = rProp.Value;
+ }
+ else
+ OSL_FAIL( "Unacceptable property, will be ignored!" );
+ }
+ }
+ else
+ {
+ OSL_FAIL( "Wrong third argument!" );
+ throw uno::Exception("wrong 3rd arg", nullptr); // TODO: Illegal argument
+ }
+
+ }
+
+ // create storage based on source
+ if ( xInputStream.is() )
+ {
+ // if xInputStream is set the storage should be open from it
+ if ( nStorageMode & embed::ElementModes::WRITE )
+ throw uno::Exception("storagemode==write", nullptr); // TODO: access denied
+
+ uno::Reference< io::XSeekable > xSeekable( xInputStream, uno::UNO_QUERY );
+ if ( !xSeekable.is() )
+ {
+ // TODO: wrap stream to let it be seekable
+ OSL_FAIL( "Nonseekable streams are not supported for now!" );
+ }
+
+ if ( !CheckPackageSignature_Impl( xInputStream, xSeekable ) )
+ throw io::IOException("package signature check failed, probably not a package file", nullptr); // TODO: this is not a package file
+
+ return static_cast<OWeakObject*>(
+ new OStorage(xInputStream, nStorageMode, aPropsToSet, m_xContext, nStorageType));
+ }
+ else if ( xStream.is() )
+ {
+ if ( ( ( nStorageMode & embed::ElementModes::WRITE ) && !xStream->getOutputStream().is() )
+ || !xStream->getInputStream().is() )
+ throw uno::Exception("access denied", nullptr); // TODO: access denied
+
+ uno::Reference< io::XSeekable > xSeekable( xStream, uno::UNO_QUERY );
+ if ( !xSeekable.is() )
+ {
+ // TODO: wrap stream to let it be seekable
+ OSL_FAIL( "Nonseekable streams are not supported for now!" );
+ }
+
+ if ( !CheckPackageSignature_Impl( xStream->getInputStream(), xSeekable ) )
+ throw io::IOException(); // TODO: this is not a package file
+
+ return static_cast<OWeakObject*>(
+ new OStorage(xStream, nStorageMode, aPropsToSet, m_xContext, nStorageType));
+ }
+
+ throw uno::Exception("no input stream or regular stream", nullptr); // general error during creation
+}
+
+OUString SAL_CALL OStorageFactory::getImplementationName()
+{
+ return "com.sun.star.comp.embed.StorageFactory";
+}
+
+sal_Bool SAL_CALL OStorageFactory::supportsService( const OUString& ServiceName )
+{
+ return cppu::supportsService(this, ServiceName);
+}
+
+uno::Sequence< OUString > SAL_CALL OStorageFactory::getSupportedServiceNames()
+{
+ return { "com.sun.star.embed.StorageFactory",
+ "com.sun.star.comp.embed.StorageFactory" };
+}
+
+
+extern "C" SAL_DLLPUBLIC_EXPORT css::uno::XInterface*
+package_OStorageFactory_get_implementation(
+ css::uno::XComponentContext* context, css::uno::Sequence<css::uno::Any> const&)
+{
+ return cppu::acquire(new OStorageFactory(context));
+}
+
+/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
diff --git a/package/source/xstor/xfactory.hxx b/package/source/xstor/xfactory.hxx
new file mode 100644
index 000000000..366911849
--- /dev/null
+++ b/package/source/xstor/xfactory.hxx
@@ -0,0 +1,55 @@
+/* -*- 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 .
+ */
+
+#ifndef INCLUDED_PACKAGE_SOURCE_XSTOR_XFACTORY_HXX
+#define INCLUDED_PACKAGE_SOURCE_XSTOR_XFACTORY_HXX
+
+#include <com/sun/star/lang/XSingleServiceFactory.hpp>
+#include <com/sun/star/lang/XServiceInfo.hpp>
+#include <com/sun/star/uno/XComponentContext.hpp>
+
+#include <cppuhelper/implbase.hxx>
+#include <osl/diagnose.h>
+
+class OStorageFactory : public ::cppu::WeakImplHelper< css::lang::XSingleServiceFactory,
+ css::lang::XServiceInfo >
+{
+ css::uno::Reference< css::uno::XComponentContext > m_xContext;
+
+public:
+ explicit OStorageFactory( const css::uno::Reference< css::uno::XComponentContext >& xContext )
+ : m_xContext( xContext )
+ {
+ OSL_ENSURE( xContext.is(), "No service manager is provided!" );
+ }
+
+ // XSingleServiceFactory
+ virtual css::uno::Reference< css::uno::XInterface > SAL_CALL createInstance() override;
+ virtual css::uno::Reference< css::uno::XInterface > SAL_CALL createInstanceWithArguments( const css::uno::Sequence< css::uno::Any >& aArguments ) override;
+
+ // XServiceInfo
+ virtual OUString SAL_CALL getImplementationName() override;
+ virtual sal_Bool SAL_CALL supportsService( const OUString& ServiceName ) override;
+ virtual css::uno::Sequence< OUString > SAL_CALL getSupportedServiceNames() override;
+
+};
+
+#endif
+
+/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
diff --git a/package/source/xstor/xstor.component b/package/source/xstor/xstor.component
new file mode 100644
index 000000000..ff6de82b6
--- /dev/null
+++ b/package/source/xstor/xstor.component
@@ -0,0 +1,27 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+ * 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 .
+ -->
+
+<component loader="com.sun.star.loader.SharedLibrary" environment="@CPPU_ENV@"
+ xmlns="http://openoffice.org/2010/uno-components">
+ <implementation name="com.sun.star.comp.embed.StorageFactory"
+ constructor="package_OStorageFactory_get_implementation" single-instance="true">
+ <service name="com.sun.star.comp.embed.StorageFactory"/>
+ <service name="com.sun.star.embed.StorageFactory"/>
+ </implementation>
+</component>
diff --git a/package/source/xstor/xstorage.cxx b/package/source/xstor/xstorage.cxx
new file mode 100644
index 000000000..bdcd699a7
--- /dev/null
+++ b/package/source/xstor/xstorage.cxx
@@ -0,0 +1,5503 @@
+/* -*- 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 <memory>
+#include <sal/config.h>
+#include <sal/log.hxx>
+
+#include <cassert>
+#include <string_view>
+
+#include <com/sun/star/beans/PropertyValue.hpp>
+#include <com/sun/star/embed/ElementModes.hpp>
+#include <com/sun/star/embed/InvalidStorageException.hpp>
+#include <com/sun/star/embed/UseBackupException.hpp>
+#include <com/sun/star/embed/StorageFormats.hpp>
+#include <com/sun/star/embed/StorageWrappedTargetException.hpp>
+#include <com/sun/star/packages/NoEncryptionException.hpp>
+#include <com/sun/star/packages/NoRawFormatException.hpp>
+#include <com/sun/star/packages/WrongPasswordException.hpp>
+#include <com/sun/star/io/TempFile.hpp>
+#include <com/sun/star/ucb/SimpleFileAccess.hpp>
+#include <com/sun/star/container/XHierarchicalNameAccess.hpp>
+#include <com/sun/star/container/XEnumerationAccess.hpp>
+#include <com/sun/star/container/XNamed.hpp>
+#include <com/sun/star/util/XChangesBatch.hpp>
+
+#include <com/sun/star/lang/XUnoTunnel.hpp>
+#include <com/sun/star/lang/XComponent.hpp>
+#include <com/sun/star/lang/DisposedException.hpp>
+#include <com/sun/star/lang/WrappedTargetRuntimeException.hpp>
+#include <com/sun/star/beans/NamedValue.hpp>
+
+#include <PackageConstants.hxx>
+
+#include <comphelper/sequence.hxx>
+#include <cppuhelper/queryinterface.hxx>
+#include <cppuhelper/exc_hlp.hxx>
+
+#include <comphelper/servicehelper.hxx>
+#include <comphelper/storagehelper.hxx>
+#include <comphelper/ofopxmlhelper.hxx>
+#include <tools/diagnose_ex.h>
+
+#include "xstorage.hxx"
+#include "owriteablestream.hxx"
+#include "switchpersistencestream.hxx"
+
+using namespace ::com::sun::star;
+
+#if OSL_DEBUG_LEVEL > 0
+#define THROW_WHERE SAL_WHERE
+#else
+#define THROW_WHERE ""
+#endif
+
+// static
+void OStorage_Impl::completeStorageStreamCopy_Impl(
+ const uno::Reference< io::XStream >& xSource,
+ const uno::Reference< io::XStream >& xDest,
+ sal_Int32 nStorageType,
+ const uno::Sequence< uno::Sequence< beans::StringPair > >& aRelInfo )
+{
+ uno::Reference< beans::XPropertySet > xSourceProps( xSource, uno::UNO_QUERY_THROW );
+ uno::Reference< beans::XPropertySet > xDestProps( xDest, uno::UNO_QUERY_THROW );
+
+ uno::Reference< io::XOutputStream > xDestOutStream = xDest->getOutputStream();
+ if ( !xDestOutStream.is() )
+ throw io::IOException( THROW_WHERE );
+
+ uno::Reference< io::XInputStream > xSourceInStream = xSource->getInputStream();
+ if ( !xSourceInStream.is() )
+ throw io::IOException( THROW_WHERE );
+
+ // TODO: headers of encrypted streams should be copied also
+ ::comphelper::OStorageHelper::CopyInputToOutput( xSourceInStream, xDestOutStream );
+
+ uno::Sequence<OUString> aPropNames { "Compressed", "MediaType",
+ "UseCommonStoragePasswordEncryption" };
+
+ if ( nStorageType == embed::StorageFormats::OFOPXML )
+ {
+ // TODO/LATER: in future it might make sense to provide the stream if there is one
+ uno::Reference< embed::XRelationshipAccess > xRelAccess( xDest, uno::UNO_QUERY_THROW );
+ xRelAccess->clearRelationships();
+ xRelAccess->insertRelationships( aRelInfo, false );
+
+ aPropNames.realloc( 2 );
+ }
+ else if ( nStorageType != embed::StorageFormats::PACKAGE )
+ {
+ aPropNames.realloc( 1 );
+ }
+
+ for ( const auto& rPropName : std::as_const(aPropNames) )
+ xDestProps->setPropertyValue( rPropName, xSourceProps->getPropertyValue( rPropName ) );
+}
+
+static uno::Reference< io::XInputStream > GetSeekableTempCopy( const uno::Reference< io::XInputStream >& xInStream,
+ const uno::Reference< uno::XComponentContext >& xContext )
+{
+ uno::Reference < io::XTempFile > xTempFile = io::TempFile::create(xContext);
+ uno::Reference < io::XOutputStream > xTempOut = xTempFile->getOutputStream();
+ uno::Reference < io::XInputStream > xTempIn = xTempFile->getInputStream();
+
+ if ( !xTempOut.is() || !xTempIn.is() )
+ throw io::IOException( THROW_WHERE );
+
+ ::comphelper::OStorageHelper::CopyInputToOutput( xInStream, xTempOut );
+ xTempOut->closeOutput();
+
+ return xTempIn;
+}
+
+SotElement_Impl::SotElement_Impl(const OUString& rName, bool bStor, bool bNew)
+ : m_aOriginalName(rName)
+ , m_bIsRemoved(false)
+ , m_bIsInserted(bNew)
+ , m_bIsStorage(bStor)
+{
+}
+
+// most of properties are holt by the storage but are not used
+OStorage_Impl::OStorage_Impl( uno::Reference< io::XInputStream > const & xInputStream,
+ sal_Int32 nMode,
+ const uno::Sequence< beans::PropertyValue >& xProperties,
+ uno::Reference< uno::XComponentContext > const & xContext,
+ sal_Int32 nStorageType )
+: m_xMutex( new comphelper::RefCountedMutex )
+, m_pAntiImpl( nullptr )
+, m_nStorageMode( nMode & ~embed::ElementModes::SEEKABLE )
+, m_bIsModified( ( nMode & ( embed::ElementModes::WRITE | embed::ElementModes::TRUNCATE ) ) == ( embed::ElementModes::WRITE | embed::ElementModes::TRUNCATE ) )
+, m_bBroadcastModified( false )
+, m_bCommited( false )
+, m_bIsRoot( true )
+, m_bListCreated( false )
+, m_nModifiedListenerCount( 0 )
+, m_xContext( xContext )
+, m_xProperties( xProperties )
+, m_bHasCommonEncryptionData( false )
+, m_pParent( nullptr )
+, m_bControlMediaType( false )
+, m_bMTFallbackUsed( false )
+, m_bControlVersion( false )
+, m_nStorageType( nStorageType )
+, m_pRelStorElement( nullptr )
+, m_nRelInfoStatus( RELINFO_NO_INIT )
+{
+ // all the checks done below by assertion statements must be done by factory
+ SAL_WARN_IF( !xInputStream.is(), "package.xstor", "No input stream is provided!" );
+ assert(xContext.is());
+
+ m_pSwitchStream = new SwitchablePersistenceStream(xContext, xInputStream);
+ m_xInputStream = m_pSwitchStream->getInputStream();
+
+ if ( m_nStorageMode & embed::ElementModes::WRITE )
+ {
+ // check that the stream allows to write
+ SAL_WARN( "package.xstor", "No stream for writing is provided!" );
+ }
+}
+
+// most of properties are holt by the storage but are not used
+OStorage_Impl::OStorage_Impl( uno::Reference< io::XStream > const & xStream,
+ sal_Int32 nMode,
+ const uno::Sequence< beans::PropertyValue >& xProperties,
+ uno::Reference< uno::XComponentContext > const & xContext,
+ sal_Int32 nStorageType )
+: m_xMutex( new comphelper::RefCountedMutex )
+, m_pAntiImpl( nullptr )
+, m_nStorageMode( nMode & ~embed::ElementModes::SEEKABLE )
+, m_bIsModified( ( nMode & ( embed::ElementModes::WRITE | embed::ElementModes::TRUNCATE ) ) == ( embed::ElementModes::WRITE | embed::ElementModes::TRUNCATE ) )
+, m_bBroadcastModified( false )
+, m_bCommited( false )
+, m_bIsRoot( true )
+, m_bListCreated( false )
+, m_nModifiedListenerCount( 0 )
+, m_xContext( xContext )
+, m_xProperties( xProperties )
+, m_bHasCommonEncryptionData( false )
+, m_pParent( nullptr )
+, m_bControlMediaType( false )
+, m_bMTFallbackUsed( false )
+, m_bControlVersion( false )
+, m_nStorageType( nStorageType )
+, m_pRelStorElement( nullptr )
+, m_nRelInfoStatus( RELINFO_NO_INIT )
+{
+ // all the checks done below by assertion statements must be done by factory
+ SAL_WARN_IF( !xStream.is(), "package.xstor", "No stream is provided!" );
+ assert(xContext.is());
+
+ if ( m_nStorageMode & embed::ElementModes::WRITE )
+ {
+ m_pSwitchStream = new SwitchablePersistenceStream(xContext, xStream);
+ m_xStream = static_cast< io::XStream* >( m_pSwitchStream.get() );
+ }
+ else
+ {
+ m_pSwitchStream = new SwitchablePersistenceStream(xContext, xStream->getInputStream());
+ m_xInputStream = m_pSwitchStream->getInputStream();
+ }
+}
+
+OStorage_Impl::OStorage_Impl( OStorage_Impl* pParent,
+ sal_Int32 nMode,
+ uno::Reference< container::XNameContainer > const & xPackageFolder,
+ uno::Reference< lang::XSingleServiceFactory > const & xPackage,
+ uno::Reference< uno::XComponentContext > const & xContext,
+ sal_Int32 nStorageType )
+: m_xMutex( new comphelper::RefCountedMutex )
+, m_pAntiImpl( nullptr )
+, m_nStorageMode( nMode & ~embed::ElementModes::SEEKABLE )
+, m_bIsModified( ( nMode & ( embed::ElementModes::WRITE | embed::ElementModes::TRUNCATE ) ) == ( embed::ElementModes::WRITE | embed::ElementModes::TRUNCATE ) )
+, m_bBroadcastModified( false )
+, m_bCommited( false )
+, m_bIsRoot( false )
+, m_bListCreated( false )
+, m_nModifiedListenerCount( 0 )
+, m_xPackageFolder( xPackageFolder )
+, m_xPackage( xPackage )
+, m_xContext( xContext )
+, m_bHasCommonEncryptionData( false )
+, m_pParent( pParent ) // can be empty in case of temporary readonly substorages and relation storage
+, m_bControlMediaType( false )
+, m_bMTFallbackUsed( false )
+, m_bControlVersion( false )
+, m_nStorageType( nStorageType )
+, m_pRelStorElement( nullptr )
+, m_nRelInfoStatus( RELINFO_NO_INIT )
+{
+ SAL_WARN_IF( !xPackageFolder.is(), "package.xstor", "No package folder!" );
+ assert(xContext.is());
+}
+
+OStorage_Impl::~OStorage_Impl()
+{
+ {
+ ::osl::MutexGuard aGuard( m_xMutex->GetMutex() );
+ if ( m_pAntiImpl ) // root storage wrapper must set this member to NULL before destruction of object
+ {
+ SAL_WARN_IF( m_bIsRoot, "package.xstor", "The root storage wrapper must be disposed already" );
+
+ try {
+ m_pAntiImpl->InternalDispose( false );
+ }
+ catch ( const uno::Exception& )
+ {
+ TOOLS_INFO_EXCEPTION("package.xstor", "Quiet exception");
+ }
+ m_pAntiImpl = nullptr;
+ }
+ else if ( !m_aReadOnlyWrapVector.empty() )
+ {
+ for ( auto& rStorage : m_aReadOnlyWrapVector )
+ {
+ uno::Reference< embed::XStorage > xTmp = rStorage.m_xWeakRef;
+ if ( xTmp.is() )
+ try {
+ rStorage.m_pPointer->InternalDispose( false );
+ } catch( const uno::Exception& )
+ {
+ TOOLS_INFO_EXCEPTION("package.xstor", "Quiet exception");
+ }
+ }
+
+ m_aReadOnlyWrapVector.clear();
+ }
+
+ m_pParent = nullptr;
+ }
+
+ for (const auto & pair : m_aChildrenMap)
+ for (auto pElement : pair.second)
+ delete pElement;
+ m_aChildrenMap.clear();
+
+ std::for_each(m_aDeletedVector.begin(), m_aDeletedVector.end(), std::default_delete<SotElement_Impl>());
+ m_aDeletedVector.clear();
+
+ if ( m_nStorageType == embed::StorageFormats::OFOPXML && m_pRelStorElement )
+ {
+ delete m_pRelStorElement;
+ m_pRelStorElement = nullptr;
+ }
+
+ m_xPackageFolder.clear();
+ m_xPackage.clear();
+
+ OUString aPropertyName = "URL";
+ for ( const auto& rProp : std::as_const(m_xProperties) )
+ {
+ if ( rProp.Name == aPropertyName )
+ {
+ // the storage is URL based so all the streams are opened by factory and should be closed
+ try
+ {
+ if ( m_xInputStream.is() )
+ {
+ m_xInputStream->closeInput();
+ m_xInputStream.clear();
+ }
+
+ if ( m_xStream.is() )
+ {
+ uno::Reference< io::XInputStream > xInStr = m_xStream->getInputStream();
+ if ( xInStr.is() )
+ xInStr->closeInput();
+
+ uno::Reference< io::XOutputStream > xOutStr = m_xStream->getOutputStream();
+ if ( xOutStr.is() )
+ xOutStr->closeOutput();
+
+ m_xStream.clear();
+ }
+ }
+ catch (const uno::Exception&)
+ {
+ TOOLS_INFO_EXCEPTION("package.xstor", "Quiet exception");
+ }
+ }
+ }
+}
+
+void OStorage_Impl::SetReadOnlyWrap( OStorage& aStorage )
+{
+ // Weak reference is used inside the holder so the refcount must not be zero at this point
+ OSL_ENSURE( aStorage.GetRefCount_Impl(), "There must be a reference alive to use this method!" );
+ m_aReadOnlyWrapVector.emplace_back( &aStorage );
+}
+
+void OStorage_Impl::RemoveReadOnlyWrap( const OStorage& aStorage )
+{
+ for ( StorageHoldersType::iterator pStorageIter = m_aReadOnlyWrapVector.begin();
+ pStorageIter != m_aReadOnlyWrapVector.end();)
+ {
+ uno::Reference< embed::XStorage > xTmp = pStorageIter->m_xWeakRef;
+ if ( !xTmp.is() || pStorageIter->m_pPointer == &aStorage )
+ {
+ try {
+ pStorageIter->m_pPointer->InternalDispose( false );
+ } catch( const uno::Exception& )
+ {
+ TOOLS_INFO_EXCEPTION("package.xstor", "Quiet exception");
+ }
+
+ pStorageIter = m_aReadOnlyWrapVector.erase(pStorageIter);
+ }
+ else
+ ++pStorageIter;
+ }
+}
+
+void OStorage_Impl::OpenOwnPackage()
+{
+ SAL_WARN_IF( !m_bIsRoot, "package.xstor", "Opening of the package has no sense!" );
+
+ ::osl::MutexGuard aGuard( m_xMutex->GetMutex() );
+
+ if ( !m_xPackageFolder.is() )
+ {
+ if ( !m_xPackage.is() )
+ {
+ uno::Sequence< uno::Any > aArguments( 2 );
+ auto pArguments = aArguments.getArray();
+ if ( m_nStorageMode & embed::ElementModes::WRITE )
+ pArguments[ 0 ] <<= m_xStream;
+ else
+ {
+ SAL_WARN_IF( !m_xInputStream.is(), "package.xstor", "Input stream must be set for readonly access!" );
+ pArguments[ 0 ] <<= m_xInputStream;
+ // TODO: if input stream is not seekable or XSeekable interface is supported
+ // on XStream object a wrapper must be used
+ }
+
+ // do not allow elements to remove themself from the old container in case of insertion to another container
+ pArguments[ 1 ] <<= beans::NamedValue( "AllowRemoveOnInsert",
+ uno::Any( false ) );
+
+ sal_Int32 nArgNum = 2;
+ for ( const auto& rProp : std::as_const(m_xProperties) )
+ {
+ if ( rProp.Name == "RepairPackage"
+ || rProp.Name == "ProgressHandler"
+ || rProp.Name == "NoFileSync" )
+ {
+ // Forward these to the package.
+ beans::NamedValue aNamedValue( rProp.Name, rProp.Value );
+ aArguments.realloc( ++nArgNum );
+ pArguments = aArguments.getArray();
+ pArguments[nArgNum-1] <<= aNamedValue;
+ }
+ else if ( rProp.Name == "Password" )
+ {
+ // TODO: implement password setting for documents
+ // the password entry must be removed after setting
+ }
+ }
+
+ if ( m_nStorageType == embed::StorageFormats::ZIP )
+ {
+ // let the package support only plain zip format
+ beans::NamedValue aNamedValue;
+ aNamedValue.Name = "StorageFormat";
+ aNamedValue.Value <<= OUString( "ZipFormat" );
+ aArguments.realloc( ++nArgNum );
+ pArguments = aArguments.getArray();
+ pArguments[nArgNum-1] <<= aNamedValue;
+ }
+ else if ( m_nStorageType == embed::StorageFormats::OFOPXML )
+ {
+ // let the package support OFOPXML media type handling
+ beans::NamedValue aNamedValue;
+ aNamedValue.Name = "StorageFormat";
+ aNamedValue.Value <<= OUString( "OFOPXMLFormat" );
+ aArguments.realloc( ++nArgNum );
+ pArguments = aArguments.getArray();
+ pArguments[nArgNum-1] <<= aNamedValue;
+ }
+
+ m_xPackage.set( m_xContext->getServiceManager()->createInstanceWithArgumentsAndContext(
+ "com.sun.star.packages.comp.ZipPackage", aArguments, m_xContext),
+ uno::UNO_QUERY );
+ }
+
+ uno::Reference< container::XHierarchicalNameAccess > xHNameAccess( m_xPackage, uno::UNO_QUERY );
+ SAL_WARN_IF( !xHNameAccess.is(), "package.xstor", "The package could not be created!" );
+
+ if ( xHNameAccess.is() )
+ {
+ uno::Any aFolder = xHNameAccess->getByHierarchicalName("/");
+ aFolder >>= m_xPackageFolder;
+ }
+ }
+
+ SAL_WARN_IF( !m_xPackageFolder.is(), "package.xstor", "The package root folder can not be opened!" );
+ if ( !m_xPackageFolder.is() )
+ throw embed::InvalidStorageException( THROW_WHERE );
+}
+
+bool OStorage_Impl::HasChildren()
+{
+ ::osl::MutexGuard aGuard( m_xMutex->GetMutex() );
+
+ ReadContents();
+ return !m_aChildrenMap.empty();
+}
+
+void OStorage_Impl::GetStorageProperties()
+{
+ if ( m_nStorageType != embed::StorageFormats::PACKAGE )
+ return;
+
+ uno::Reference< beans::XPropertySet > xProps( m_xPackageFolder, uno::UNO_QUERY_THROW );
+
+ if ( !m_bControlMediaType )
+ {
+ uno::Reference< beans::XPropertySet > xPackageProps( m_xPackage, uno::UNO_QUERY_THROW );
+ xPackageProps->getPropertyValue( MEDIATYPE_FALLBACK_USED_PROPERTY ) >>= m_bMTFallbackUsed;
+
+ static constexpr OUStringLiteral sMediaType(u"MediaType");
+ xProps->getPropertyValue( sMediaType ) >>= m_aMediaType;
+ m_bControlMediaType = true;
+ }
+
+ if ( !m_bControlVersion )
+ {
+ xProps->getPropertyValue( "Version" ) >>= m_aVersion;
+ m_bControlVersion = true;
+ }
+
+ // the properties of OFOPXML will be handled directly
+}
+
+void OStorage_Impl::ReadRelInfoIfNecessary()
+{
+ if ( m_nStorageType != embed::StorageFormats::OFOPXML )
+ return;
+
+ if ( m_nRelInfoStatus == RELINFO_NO_INIT )
+ {
+ // Init from original stream
+ uno::Reference< io::XInputStream > xRelInfoStream
+ = GetRelInfoStreamForName( std::u16string_view() );
+ try
+ {
+ if ( xRelInfoStream.is() )
+ m_aRelInfo = ::comphelper::OFOPXMLHelper::ReadRelationsInfoSequence(
+ xRelInfoStream,
+ u"_rels/.rels",
+ m_xContext );
+ m_nRelInfoStatus = RELINFO_READ;
+ }
+ catch (css::uno::Exception &)
+ {
+ TOOLS_INFO_EXCEPTION("package.xstor", "");
+ }
+ }
+ else if ( m_nRelInfoStatus == RELINFO_CHANGED_STREAM )
+ {
+ // Init from the new stream
+ try
+ {
+ if ( m_xNewRelInfoStream.is() )
+ m_aRelInfo = ::comphelper::OFOPXMLHelper::ReadRelationsInfoSequence(
+ m_xNewRelInfoStream,
+ u"_rels/.rels",
+ m_xContext );
+
+ m_nRelInfoStatus = RELINFO_CHANGED_STREAM_READ;
+ }
+ catch( const uno::Exception& )
+ {
+ m_nRelInfoStatus = RELINFO_CHANGED_BROKEN;
+ }
+ }
+}
+
+void OStorage_Impl::ReadContents()
+{
+ ::osl::MutexGuard aGuard( m_xMutex->GetMutex() );
+
+ if ( m_bListCreated )
+ return;
+
+ if ( m_bIsRoot )
+ OpenOwnPackage();
+
+ uno::Reference< container::XEnumerationAccess > xEnumAccess( m_xPackageFolder, uno::UNO_QUERY_THROW );
+ uno::Reference< container::XEnumeration > xEnum = xEnumAccess->createEnumeration();
+ if ( !xEnum.is() )
+ throw uno::RuntimeException( THROW_WHERE );
+
+ m_bListCreated = true;
+
+ while( xEnum->hasMoreElements() )
+ {
+ try {
+ uno::Reference< container::XNamed > xNamed;
+ xEnum->nextElement() >>= xNamed;
+
+ if ( !xNamed.is() )
+ {
+ SAL_WARN( "package.xstor", "XNamed is not supported!" );
+ throw uno::RuntimeException( THROW_WHERE );
+ }
+
+ OUString aName = xNamed->getName();
+ SAL_WARN_IF( aName.isEmpty(), "package.xstor", "Empty name!" );
+
+ uno::Reference< container::XNameContainer > xNameContainer( xNamed, uno::UNO_QUERY );
+
+ std::unique_ptr<SotElement_Impl> xNewElement(new SotElement_Impl(aName, xNameContainer.is(), false));
+ if ( m_nStorageType == embed::StorageFormats::OFOPXML && aName == "_rels" )
+ {
+ if (!xNewElement->m_bIsStorage)
+ throw io::IOException( THROW_WHERE ); // TODO: Unexpected format
+
+ m_pRelStorElement = xNewElement.release();
+ CreateRelStorage();
+ }
+ else
+ {
+ if ( ( m_nStorageMode & embed::ElementModes::TRUNCATE ) == embed::ElementModes::TRUNCATE )
+ {
+ // if a storage is truncated all of it elements are marked as deleted
+ xNewElement->m_bIsRemoved = true;
+ }
+
+ m_aChildrenMap[aName].push_back(xNewElement.release());
+ }
+ }
+ catch( const container::NoSuchElementException& )
+ {
+ TOOLS_WARN_EXCEPTION( "package.xstor", "hasMoreElements() implementation has problems!");
+ break;
+ }
+ }
+ if ( ( m_nStorageMode & embed::ElementModes::TRUNCATE ) == embed::ElementModes::TRUNCATE )
+ {
+ // if a storage is truncated the relations information should be cleaned
+ m_xNewRelInfoStream.clear();
+ m_aRelInfo = uno::Sequence< uno::Sequence< beans::StringPair > >();
+ m_nRelInfoStatus = RELINFO_CHANGED;
+ }
+
+ // cache changeable folder properties
+ GetStorageProperties();
+}
+
+void OStorage_Impl::CopyToStorage( const uno::Reference< embed::XStorage >& xDest, bool bDirect )
+{
+ ::osl::MutexGuard aGuard( m_xMutex->GetMutex() );
+
+ uno::Reference< beans::XPropertySet > xPropSet( xDest, uno::UNO_QUERY );
+ if ( !xPropSet.is() )
+ throw lang::IllegalArgumentException( THROW_WHERE, uno::Reference< uno::XInterface >(), 1 );
+
+ sal_Int32 nDestMode = embed::ElementModes::READ;
+ xPropSet->getPropertyValue( "OpenMode" ) >>= nDestMode;
+
+ if ( !( nDestMode & embed::ElementModes::WRITE ) )
+ throw io::IOException( THROW_WHERE ); // TODO: access_denied
+
+ ReadContents();
+
+ if ( !m_xPackageFolder.is() )
+ throw embed::InvalidStorageException( THROW_WHERE );
+
+ for ( const auto& pair : m_aChildrenMap )
+ for (auto pElement : pair.second)
+ {
+ if ( !pElement->m_bIsRemoved )
+ CopyStorageElement( pElement, xDest, /*aName*/pair.first, bDirect );
+ }
+
+ // move storage properties to the destination one ( means changeable properties )
+ if ( m_nStorageType == embed::StorageFormats::PACKAGE )
+ {
+ xPropSet->setPropertyValue( "MediaType", uno::Any( m_aMediaType ) );
+ xPropSet->setPropertyValue( "Version", uno::Any( m_aVersion ) );
+ }
+
+ if ( m_nStorageType == embed::StorageFormats::PACKAGE )
+ {
+ // if this is a root storage, the common key from current one should be moved there
+ bool bIsRoot = false;
+ if ( ( xPropSet->getPropertyValue( "IsRoot" ) >>= bIsRoot ) && bIsRoot )
+ {
+ try
+ {
+ uno::Reference< embed::XEncryptionProtectedStorage > xEncr( xDest, uno::UNO_QUERY );
+ if ( xEncr.is() )
+ {
+ xEncr->setEncryptionData( GetCommonRootEncryptionData().getAsConstNamedValueList() );
+
+ uno::Sequence< beans::NamedValue > aAlgorithms;
+ uno::Reference< beans::XPropertySet > xPackPropSet( m_xPackage, uno::UNO_QUERY_THROW );
+ xPackPropSet->getPropertyValue( ENCRYPTION_ALGORITHMS_PROPERTY )
+ >>= aAlgorithms;
+ xEncr->setEncryptionAlgorithms( aAlgorithms );
+ }
+ }
+ catch( const packages::NoEncryptionException& )
+ {
+ TOOLS_INFO_EXCEPTION("package.xstor", "No Encryption");
+ }
+ }
+ }
+ else if ( m_nStorageType == embed::StorageFormats::OFOPXML )
+ {
+
+ // TODO/LATER: currently the optimization is not active
+ // uno::Reference< io::XInputStream > xRelInfoStream = GetRelInfoStreamForName( OUString() ); // own stream
+ // if ( xRelInfoStream.is() )
+ // {
+ // // Relations info stream is a writeonly property, introduced only to optimize copying
+ // // Should be used carefully since no check for stream consistency is done, and the stream must not stay locked
+
+ // OUString aRelInfoString = "RelationsInfoStream";
+ // xPropSet->setPropertyValue( aRelInfoString, uno::makeAny( GetSeekableTempCopy( xRelInfoStream, m_xFactory ) ) );
+ // }
+
+ uno::Reference< embed::XRelationshipAccess > xRels( xDest, uno::UNO_QUERY );
+ if ( !xRels.is() )
+ throw lang::IllegalArgumentException( THROW_WHERE, uno::Reference< uno::XInterface >(), 1 );
+
+ xRels->insertRelationships( GetAllRelationshipsIfAny(), false );
+ }
+
+ // if possible the destination storage should be committed after successful copying
+ uno::Reference< embed::XTransactedObject > xObjToCommit( xDest, uno::UNO_QUERY );
+ if ( xObjToCommit.is() )
+ xObjToCommit->commit();
+}
+
+void OStorage_Impl::CopyStorageElement( SotElement_Impl* pElement,
+ const uno::Reference< embed::XStorage >& xDest,
+ const OUString& aName,
+ bool bDirect )
+{
+ SAL_WARN_IF( !xDest.is(), "package.xstor", "No destination storage!" );
+ SAL_WARN_IF( aName.isEmpty(), "package.xstor", "Empty element name!" );
+
+ ::osl::MutexGuard aGuard( m_xMutex->GetMutex() );
+
+ uno::Reference< container::XNameAccess > xDestAccess( xDest, uno::UNO_QUERY_THROW );
+ if ( xDestAccess->hasByName( aName )
+ && !( pElement->m_bIsStorage && xDest->isStorageElement( aName ) ) )
+ xDest->removeElement( aName );
+
+ if ( pElement->m_bIsStorage )
+ {
+ uno::Reference< embed::XStorage > xSubDest =
+ xDest->openStorageElement( aName,
+ embed::ElementModes::WRITE );
+
+ SAL_WARN_IF( !xSubDest.is(), "package.xstor", "No destination substorage!" );
+
+ if (!pElement->m_xStorage)
+ {
+ OpenSubStorage( pElement, embed::ElementModes::READ );
+ if (!pElement->m_xStorage)
+ throw io::IOException( THROW_WHERE );
+ }
+
+ pElement->m_xStorage->CopyToStorage(xSubDest, bDirect);
+ }
+ else
+ {
+ if (!pElement->m_xStream)
+ {
+ OpenSubStream( pElement );
+ if (!pElement->m_xStream)
+ throw io::IOException( THROW_WHERE );
+ }
+
+ if (!pElement->m_xStream->IsEncrypted())
+ {
+ if ( bDirect )
+ {
+ // fill in the properties for the stream
+ uno::Sequence< beans::PropertyValue > aStrProps(0);
+ const uno::Sequence< beans::PropertyValue > aSrcPkgProps = pElement->m_xStream->GetStreamProperties();
+ sal_Int32 nNum = 0;
+ for ( const auto& rSrcPkgProp : aSrcPkgProps )
+ {
+ if ( rSrcPkgProp.Name == "MediaType" || rSrcPkgProp.Name == "Compressed" )
+ {
+ aStrProps.realloc( ++nNum );
+ auto pStrProps = aStrProps.getArray();
+ pStrProps[nNum-1].Name = rSrcPkgProp.Name;
+ pStrProps[nNum-1].Value = rSrcPkgProp.Value;
+ }
+ }
+
+ if ( m_nStorageType == embed::StorageFormats::PACKAGE )
+ {
+ aStrProps.realloc( ++nNum );
+ auto pStrProps = aStrProps.getArray();
+ pStrProps[nNum-1].Name = "UseCommonStoragePasswordEncryption";
+ pStrProps[nNum-1].Value <<= pElement->m_xStream->UsesCommonEncryption_Impl();
+ }
+ else if ( m_nStorageType == embed::StorageFormats::OFOPXML )
+ {
+ // TODO/LATER: currently the optimization is not active
+ // uno::Reference< io::XInputStream > xInStream = GetRelInfoStreamForName( OUString() ); // own rels stream
+ // if ( xInStream.is() )
+ // {
+ // aStrProps.realloc( ++nNum );
+ // aStrProps[nNum-1].Name = "RelationsInfoStream";
+ // aStrProps[nNum-1].Value <<= GetSeekableTempCopy( xInStream, m_xFactory );
+ // }
+
+ uno::Reference< embed::XRelationshipAccess > xRels( xDest, uno::UNO_QUERY );
+ if ( !xRels.is() )
+ throw lang::IllegalArgumentException( THROW_WHERE, uno::Reference< uno::XInterface >(), 0 );
+
+ xRels->insertRelationships( GetAllRelationshipsIfAny(), false );
+ }
+
+ uno::Reference< embed::XOptimizedStorage > xOptDest( xDest, uno::UNO_QUERY_THROW );
+ uno::Reference < io::XInputStream > xInputToInsert;
+
+ if (pElement->m_xStream->HasTempFile_Impl() || !pElement->m_xStream->m_xPackageStream.is())
+ {
+ SAL_WARN_IF(!pElement->m_xStream->m_xPackageStream.is(), "package.xstor", "No package stream!");
+
+ // if the stream is modified - the temporary file must be used for insertion
+ xInputToInsert = pElement->m_xStream->GetTempFileAsInputStream();
+ }
+ else
+ {
+ // for now get just nonseekable access to the stream
+ // TODO/LATER: the raw stream can be used
+
+ xInputToInsert = pElement->m_xStream->m_xPackageStream->getDataStream();
+ }
+
+ if ( !xInputToInsert.is() )
+ throw io::IOException( THROW_WHERE );
+
+ xOptDest->insertStreamElementDirect( aName, xInputToInsert, aStrProps );
+ }
+ else
+ {
+ uno::Reference< io::XStream > xSubStr =
+ xDest->openStreamElement( aName,
+ embed::ElementModes::READWRITE | embed::ElementModes::TRUNCATE );
+ SAL_WARN_IF( !xSubStr.is(), "package.xstor", "No destination substream!" );
+
+ pElement->m_xStream->CopyInternallyTo_Impl(xSubStr);
+ }
+ }
+ else if ( m_nStorageType != embed::StorageFormats::PACKAGE )
+ {
+ SAL_WARN( "package.xstor", "Encryption is only supported in package storage!" );
+ throw io::IOException( THROW_WHERE );
+ }
+ else if ( pElement->m_xStream->HasCachedEncryptionData()
+ && ( pElement->m_xStream->IsModified() || pElement->m_xStream->HasWriteOwner_Impl() ) )
+ {
+ ::comphelper::SequenceAsHashMap aCommonEncryptionData;
+ bool bHasCommonEncryptionData = false;
+ try
+ {
+ aCommonEncryptionData = GetCommonRootEncryptionData();
+ bHasCommonEncryptionData = true;
+ }
+ catch( const packages::NoEncryptionException& )
+ {
+ TOOLS_INFO_EXCEPTION("package.xstor", "No Encryption");
+ }
+
+ if (bHasCommonEncryptionData && ::package::PackageEncryptionDataLessOrEqual(pElement->m_xStream->GetCachedEncryptionData(), aCommonEncryptionData))
+ {
+ // If the stream can be opened with the common storage password
+ // it must be stored with the common storage password as well
+ uno::Reference< io::XStream > xDestStream =
+ xDest->openStreamElement( aName,
+ embed::ElementModes::READWRITE | embed::ElementModes::TRUNCATE );
+
+ pElement->m_xStream->CopyInternallyTo_Impl( xDestStream );
+
+ uno::Reference< beans::XPropertySet > xProps( xDestStream, uno::UNO_QUERY_THROW );
+ xProps->setPropertyValue(
+ "UseCommonStoragePasswordEncryption",
+ uno::Any( true ) );
+ }
+ else
+ {
+ // the stream is already opened for writing or was changed
+ uno::Reference< embed::XStorage2 > xDest2( xDest, uno::UNO_QUERY_THROW );
+ uno::Reference< io::XStream > xSubStr =
+ xDest2->openEncryptedStream( aName,
+ embed::ElementModes::READWRITE | embed::ElementModes::TRUNCATE,
+ pElement->m_xStream->GetCachedEncryptionData().getAsConstNamedValueList() );
+ SAL_WARN_IF( !xSubStr.is(), "package.xstor", "No destination substream!" );
+
+ pElement->m_xStream->CopyInternallyTo_Impl(xSubStr, pElement->m_xStream->GetCachedEncryptionData());
+ }
+ }
+ else
+ {
+ // the stream is not opened at all, so it can be just opened for reading
+ try
+ {
+ // If the stream can be opened with the common storage password
+ // it must be stored with the common storage password as well
+
+ uno::Reference< io::XStream > xOwnStream = pElement->m_xStream->GetStream(embed::ElementModes::READ,
+ false);
+ uno::Reference< io::XStream > xDestStream =
+ xDest->openStreamElement( aName,
+ embed::ElementModes::READWRITE | embed::ElementModes::TRUNCATE );
+ SAL_WARN_IF( !xDestStream.is(), "package.xstor", "No destination substream!" );
+ completeStorageStreamCopy_Impl( xOwnStream, xDestStream, m_nStorageType, GetAllRelationshipsIfAny() );
+
+ uno::Reference< beans::XPropertySet > xProps( xDestStream, uno::UNO_QUERY_THROW );
+ xProps->setPropertyValue(
+ "UseCommonStoragePasswordEncryption",
+ uno::Any( true ) );
+ }
+ catch( const packages::WrongPasswordException& )
+ {
+ TOOLS_INFO_EXCEPTION("package.xstor", "Handled exception");
+
+ // If the common storage password does not allow to open the stream
+ // it could be copied in raw way, the problem is that the StartKey should be the same
+ // in the ODF1.2 package, so an invalid package could be produced if the stream
+ // is copied from ODF1.1 package, where it is allowed to have different StartKeys
+ uno::Reference< embed::XStorageRawAccess > xRawDest( xDest, uno::UNO_QUERY_THROW );
+ uno::Reference< io::XInputStream > xRawInStream = pElement->m_xStream->GetRawInStream();
+ xRawDest->insertRawEncrStreamElement( aName, xRawInStream );
+ }
+ }
+ }
+}
+
+uno::Sequence< uno::Sequence< beans::StringPair > > OStorage_Impl::GetAllRelationshipsIfAny()
+{
+ if ( m_nStorageType != embed::StorageFormats::OFOPXML )
+ return uno::Sequence< uno::Sequence< beans::StringPair > >();
+
+ ReadRelInfoIfNecessary();
+
+ if ( m_nRelInfoStatus != RELINFO_READ
+ && m_nRelInfoStatus != RELINFO_CHANGED_STREAM_READ
+ && m_nRelInfoStatus != RELINFO_CHANGED )
+ throw io::IOException( THROW_WHERE "Wrong relinfo stream!" );
+ // m_nRelInfoStatus == RELINFO_CHANGED_BROKEN || m_nRelInfoStatus == RELINFO_BROKEN
+ return m_aRelInfo;
+}
+
+void OStorage_Impl::CopyLastCommitTo( const uno::Reference< embed::XStorage >& xNewStor )
+{
+ ::osl::MutexGuard aGuard( m_xMutex->GetMutex() );
+
+ SAL_WARN_IF( !m_xPackageFolder.is(), "package.xstor", "A committed storage is incomplete!" );
+ if ( !m_xPackageFolder.is() )
+ throw uno::RuntimeException( THROW_WHERE );
+
+ OStorage_Impl aTempRepresent( nullptr,
+ embed::ElementModes::READ,
+ m_xPackageFolder,
+ m_xPackage,
+ m_xContext,
+ m_nStorageType);
+
+ // TODO/LATER: could use direct copying
+ aTempRepresent.CopyToStorage( xNewStor, false );
+}
+
+void OStorage_Impl::InsertIntoPackageFolder( const OUString& aName,
+ const uno::Reference< container::XNameContainer >& xParentPackageFolder )
+{
+ ::osl::MutexGuard aGuard( m_xMutex->GetMutex() );
+
+ SAL_WARN_IF( !m_xPackageFolder.is(), "package.xstor", "An inserted storage is incomplete!" );
+ uno::Reference< lang::XUnoTunnel > xTunnel( m_xPackageFolder, uno::UNO_QUERY_THROW );
+ xParentPackageFolder->insertByName( aName, uno::Any( xTunnel ) );
+
+ m_bCommited = false;
+}
+
+void OStorage_Impl::Commit()
+{
+ ::osl::MutexGuard aGuard( m_xMutex->GetMutex() );
+
+ if ( !m_bIsModified )
+ return;
+
+ // in case of a new empty storage it is possible that the contents are still not read
+ // ( the storage of course has no contents, but the initialization is postponed till the first use,
+ // thus if a new storage was created and committed immediately it must be initialized here )
+ ReadContents();
+
+ // if storage is committed it should have a valid Package representation
+ SAL_WARN_IF( !m_xPackageFolder.is(), "package.xstor", "The package representation should exist!" );
+ if ( !m_xPackageFolder.is() )
+ throw embed::InvalidStorageException( THROW_WHERE );
+
+ OSL_ENSURE( m_nStorageMode & embed::ElementModes::WRITE,
+ "Commit of readonly storage, should be detected before!" );
+
+ uno::Reference< container::XNameContainer > xNewPackageFolder;
+
+ // here the storage will switch to the temporary package folder
+ // if the storage was already committed and the parent was not committed after that
+ // the switch should not be done since the package folder in use is a temporary one;
+ // it can be detected by m_bCommited flag ( root storage doesn't need temporary representation )
+ if ( !m_bCommited && !m_bIsRoot )
+ {
+ uno::Sequence< uno::Any > aSeq{ uno::Any(true) };
+ xNewPackageFolder.set( m_xPackage->createInstanceWithArguments( aSeq ),
+ uno::UNO_QUERY );
+ }
+ else
+ xNewPackageFolder = m_xPackageFolder;
+
+ // remove replaced removed elements
+ for ( auto& pDeleted : m_aDeletedVector )
+ {
+
+ if ( m_nStorageType == embed::StorageFormats::OFOPXML && !pDeleted->m_bIsStorage )
+ RemoveStreamRelInfo( pDeleted->m_aOriginalName );
+
+ // the removed elements are not in new temporary storage
+ if ( m_bCommited || m_bIsRoot )
+ xNewPackageFolder->removeByName( pDeleted->m_aOriginalName );
+ delete pDeleted;
+ pDeleted = nullptr;
+ }
+ m_aDeletedVector.clear();
+
+ // remove removed elements
+ for (auto mapIt = m_aChildrenMap.begin(); mapIt != m_aChildrenMap.end(); )
+ {
+ for (auto it = mapIt->second.begin(); it != mapIt->second.end(); )
+ {
+ // renamed and inserted elements must be really inserted to package later
+ // since they can conflict with removed elements
+ auto & pElement = *it;
+ if ( pElement->m_bIsRemoved )
+ {
+ if ( m_nStorageType == embed::StorageFormats::OFOPXML && !pElement->m_bIsStorage )
+ RemoveStreamRelInfo( pElement->m_aOriginalName );
+
+ // the removed elements are not in new temporary storage
+ if ( m_bCommited || m_bIsRoot )
+ xNewPackageFolder->removeByName( pElement->m_aOriginalName );
+
+ delete pElement;
+ it = mapIt->second.erase(it);
+ }
+ else
+ ++it;
+ }
+ if (mapIt->second.empty())
+ mapIt = m_aChildrenMap.erase(mapIt);
+ else
+ ++mapIt;
+ }
+
+
+ // there should be no more deleted elements
+ for ( const auto& pair : m_aChildrenMap )
+ for (auto pElement : pair.second)
+ {
+ // if it is a 'duplicate commit' inserted elements must be really inserted to package later
+ // since they can conflict with renamed elements
+ if ( !pElement->m_bIsInserted )
+ {
+ // for now stream is opened in direct mode that means that in case
+ // storage is committed all the streams from it are committed in current state.
+ // following two steps are separated to allow easily implement transacted mode
+ // for streams if we need it in future.
+ // Only hierarchical access uses transacted streams currently
+ if ( !pElement->m_bIsStorage && pElement->m_xStream
+ && !pElement->m_xStream->IsTransacted() )
+ pElement->m_xStream->Commit();
+
+ // if the storage was not open, there is no need to commit it ???
+ // the storage should be checked that it is committed
+ if (pElement->m_bIsStorage && pElement->m_xStorage && pElement->m_xStorage->m_bCommited)
+ {
+ // it's temporary PackageFolder should be inserted instead of current one
+ // also the new copy of PackageFolder should be used by the children storages
+
+ // the renamed elements are not in new temporary storage
+ if ( m_bCommited || m_bIsRoot )
+ xNewPackageFolder->removeByName( pElement->m_aOriginalName );
+
+ pElement->m_xStorage->InsertIntoPackageFolder(/*aName*/pair.first, xNewPackageFolder);
+ }
+ else if (!pElement->m_bIsStorage && pElement->m_xStream && pElement->m_xStream->m_bFlushed)
+ {
+ if ( m_nStorageType == embed::StorageFormats::OFOPXML )
+ CommitStreamRelInfo( /*aName*/pair.first, pElement );
+
+ // the renamed elements are not in new temporary storage
+ if ( m_bCommited || m_bIsRoot )
+ xNewPackageFolder->removeByName( pElement->m_aOriginalName );
+
+ pElement->m_xStream->InsertIntoPackageFolder(/*aName*/pair.first, xNewPackageFolder);
+ }
+ else if ( !m_bCommited && !m_bIsRoot )
+ {
+ // the element must be just copied to the new temporary package folder
+ // the connection with the original package should not be lost just because
+ // the element is still referred by the folder in the original hierarchy
+ uno::Any aPackageElement = m_xPackageFolder->getByName( pElement->m_aOriginalName );
+ xNewPackageFolder->insertByName( /*aName*/pair.first, aPackageElement );
+ }
+ else if ( pair.first != pElement->m_aOriginalName )
+ {
+ // this is the case when xNewPackageFolder refers to m_xPackageFolder
+ // in case the name was changed and it is not a changed storage - rename the element
+ uno::Any aPackageElement = xNewPackageFolder->getByName( pElement->m_aOriginalName );
+ xNewPackageFolder->removeByName( pElement->m_aOriginalName );
+ xNewPackageFolder->insertByName( /*aName*/pair.first, aPackageElement );
+
+ if ( m_nStorageType == embed::StorageFormats::OFOPXML && !pElement->m_bIsStorage )
+ {
+ if (!pElement->m_xStream)
+ {
+ OpenSubStream( pElement );
+ if (!pElement->m_xStream)
+ throw uno::RuntimeException( THROW_WHERE );
+ }
+
+ CommitStreamRelInfo( /*aName*/pair.first, pElement );
+ }
+ }
+
+ pElement->m_aOriginalName = pair.first;
+ }
+ }
+
+ for ( const auto& pair : m_aChildrenMap )
+ for (auto pElement : pair.second)
+ {
+ // now inserted elements can be inserted to the package
+ if ( pElement->m_bIsInserted )
+ {
+ pElement->m_aOriginalName = pair.first;
+
+ if ( pElement->m_bIsStorage )
+ {
+ OSL_ENSURE(pElement->m_xStorage, "An inserted storage is incomplete!");
+ if (!pElement->m_xStorage)
+ throw uno::RuntimeException( THROW_WHERE );
+
+ if (pElement->m_xStorage->m_bCommited)
+ {
+ pElement->m_xStorage->InsertIntoPackageFolder(/*aName*/pair.first, xNewPackageFolder);
+
+ pElement->m_bIsInserted = false;
+ }
+ }
+ else
+ {
+ OSL_ENSURE(pElement->m_xStream, "An inserted stream is incomplete!");
+ if (!pElement->m_xStream)
+ throw uno::RuntimeException( THROW_WHERE );
+
+ if (!pElement->m_xStream->IsTransacted())
+ pElement->m_xStream->Commit();
+
+ if (pElement->m_xStream->m_bFlushed)
+ {
+ if ( m_nStorageType == embed::StorageFormats::OFOPXML )
+ CommitStreamRelInfo( /*aName*/pair.first, pElement );
+
+ pElement->m_xStream->InsertIntoPackageFolder( /*aName*/pair.first, xNewPackageFolder );
+
+ pElement->m_bIsInserted = false;
+ }
+ }
+ }
+ }
+
+ if ( m_nStorageType == embed::StorageFormats::PACKAGE )
+ {
+ // move properties to the destination package folder
+ uno::Reference< beans::XPropertySet > xProps( xNewPackageFolder, uno::UNO_QUERY_THROW );
+ xProps->setPropertyValue( "MediaType", uno::Any( m_aMediaType ) );
+ xProps->setPropertyValue( "Version", uno::Any( m_aVersion ) );
+ }
+
+ if ( m_nStorageType == embed::StorageFormats::OFOPXML )
+ CommitRelInfo( xNewPackageFolder ); // store own relations and commit complete relations storage
+
+ if ( m_bIsRoot )
+ {
+ uno::Reference< util::XChangesBatch > xChangesBatch( m_xPackage, uno::UNO_QUERY_THROW );
+ try
+ {
+ xChangesBatch->commitChanges();
+ }
+ catch( const lang::WrappedTargetException& r )
+ {
+ css::uno::Any ex( cppu::getCaughtException() );
+ // the wrapped UseBackupException means that the target medium can be corrupted
+ embed::UseBackupException aException;
+ if ( r.TargetException >>= aException )
+ {
+ m_xStream.clear();
+ m_xInputStream.clear();
+ throw aException;
+ }
+
+ SAL_INFO("package.xstor", "Rethrow: " << exceptionToString(ex));
+ throw;
+ }
+ }
+ else if ( !m_bCommited )
+ {
+ m_xPackageFolder = xNewPackageFolder;
+ m_bCommited = true;
+ }
+
+ // after commit the mediatype treated as the correct one
+ m_bMTFallbackUsed = false;
+}
+
+void OStorage_Impl::Revert()
+{
+ ::osl::MutexGuard aGuard( m_xMutex->GetMutex() );
+
+ if ( !( m_nStorageMode & embed::ElementModes::WRITE ) )
+ return; // nothing to do
+
+ // all the children must be removed
+ // they will be created later on demand
+
+ // rebuild the map - cannot do it in-place, because we're changing some of the key values
+ std::unordered_map<OUString, std::vector<SotElement_Impl*>> oldMap;
+ std::swap(oldMap, m_aChildrenMap);
+
+ for (const auto & rPair : oldMap)
+ for (auto pElement : rPair.second)
+ {
+ if ( pElement->m_bIsInserted )
+ delete pElement;
+ else
+ {
+ ClearElement( pElement );
+
+ pElement->m_bIsRemoved = false;
+
+ m_aChildrenMap[pElement->m_aOriginalName].push_back(pElement);
+ }
+ }
+
+ // return replaced removed elements
+ for ( auto& pDeleted : m_aDeletedVector )
+ {
+ m_aChildrenMap[pDeleted->m_aOriginalName].push_back(pDeleted);
+
+ ClearElement( pDeleted );
+
+ pDeleted->m_bIsRemoved = false;
+ }
+ m_aDeletedVector.clear();
+
+ m_bControlMediaType = false;
+ m_bControlVersion = false;
+
+ GetStorageProperties();
+
+ if ( m_nStorageType == embed::StorageFormats::OFOPXML )
+ {
+ // currently the relations storage is changed only on commit
+ m_xNewRelInfoStream.clear();
+ m_aRelInfo = uno::Sequence< uno::Sequence< beans::StringPair > >();
+ m_nRelInfoStatus = RELINFO_NO_INIT;
+ }
+}
+
+::comphelper::SequenceAsHashMap OStorage_Impl::GetCommonRootEncryptionData()
+{
+ ::osl::MutexGuard aGuard( m_xMutex->GetMutex() ) ;
+
+ if ( m_nStorageType != embed::StorageFormats::PACKAGE )
+ throw packages::NoEncryptionException( THROW_WHERE );
+
+ if ( m_bIsRoot )
+ {
+ if ( !m_bHasCommonEncryptionData )
+ throw packages::NoEncryptionException( THROW_WHERE );
+
+ return m_aCommonEncryptionData;
+ }
+ else
+ {
+ if ( !m_pParent )
+ throw packages::NoEncryptionException( THROW_WHERE );
+
+ return m_pParent->GetCommonRootEncryptionData();
+ }
+}
+
+SotElement_Impl* OStorage_Impl::FindElement( const OUString& rName )
+{
+ ::osl::MutexGuard aGuard( m_xMutex->GetMutex() );
+
+ SAL_WARN_IF( rName.isEmpty(), "package.xstor", "Name is empty!" );
+
+ ReadContents();
+
+ auto mapIt = m_aChildrenMap.find(rName);
+ if (mapIt == m_aChildrenMap.end())
+ return nullptr;
+ for (auto pElement : mapIt->second)
+ if (!pElement->m_bIsRemoved)
+ return pElement;
+
+ return nullptr;
+}
+
+SotElement_Impl* OStorage_Impl::InsertStream( const OUString& aName, bool bEncr )
+{
+ SAL_WARN_IF( !m_xPackage.is(), "package.xstor", "Not possible to refer to package as to factory!" );
+ if ( !m_xPackage.is() )
+ throw embed::InvalidStorageException( THROW_WHERE);
+
+ uno::Sequence< uno::Any > aSeq{ uno::Any(false) };
+ uno::Reference< lang::XUnoTunnel > xNewElement( m_xPackage->createInstanceWithArguments( aSeq ),
+ uno::UNO_QUERY );
+
+ SAL_WARN_IF( !xNewElement.is(), "package.xstor", "Not possible to create a new stream!" );
+ if ( !xNewElement.is() )
+ throw io::IOException( THROW_WHERE );
+
+ uno::Reference< packages::XDataSinkEncrSupport > xPackageSubStream( xNewElement, uno::UNO_QUERY_THROW );
+
+ OSL_ENSURE( m_nStorageType == embed::StorageFormats::PACKAGE || !bEncr, "Only package storage supports encryption!" );
+ if ( m_nStorageType != embed::StorageFormats::PACKAGE && bEncr )
+ throw packages::NoEncryptionException( THROW_WHERE );
+
+ // the mode is not needed for storage stream internal implementation
+ SotElement_Impl* pNewElement = InsertElement( aName, false );
+ pNewElement->m_xStream.reset(new OWriteStream_Impl(this, xPackageSubStream, m_xPackage, m_xContext, bEncr, m_nStorageType, true));
+
+ m_aChildrenMap[aName].push_back( pNewElement );
+ m_bIsModified = true;
+ m_bBroadcastModified = true;
+
+ return pNewElement;
+}
+
+void OStorage_Impl::InsertRawStream( const OUString& aName, const uno::Reference< io::XInputStream >& xInStream )
+{
+ // insert of raw stream means insert and commit
+ SAL_WARN_IF( !m_xPackage.is(), "package.xstor", "Not possible to refer to package as to factory!" );
+ if ( !m_xPackage.is() )
+ throw embed::InvalidStorageException( THROW_WHERE );
+
+ if ( m_nStorageType != embed::StorageFormats::PACKAGE )
+ throw packages::NoEncryptionException( THROW_WHERE );
+
+ uno::Reference< io::XSeekable > xSeek( xInStream, uno::UNO_QUERY );
+ uno::Reference< io::XInputStream > xInStrToInsert = xSeek.is() ? xInStream :
+ GetSeekableTempCopy( xInStream, m_xContext );
+
+ uno::Sequence< uno::Any > aSeq{ uno::Any(false) };
+ uno::Reference< lang::XUnoTunnel > xNewElement( m_xPackage->createInstanceWithArguments( aSeq ),
+ uno::UNO_QUERY );
+
+ SAL_WARN_IF( !xNewElement.is(), "package.xstor", "Not possible to create a new stream!" );
+ if ( !xNewElement.is() )
+ throw io::IOException( THROW_WHERE );
+
+ uno::Reference< packages::XDataSinkEncrSupport > xPackageSubStream( xNewElement, uno::UNO_QUERY_THROW );
+ xPackageSubStream->setRawStream( xInStrToInsert );
+
+ // the mode is not needed for storage stream internal implementation
+ SotElement_Impl* pNewElement = InsertElement( aName, false );
+ pNewElement->m_xStream.reset(new OWriteStream_Impl(this, xPackageSubStream, m_xPackage, m_xContext, true, m_nStorageType, false));
+ // the stream is inserted and must be treated as a committed one
+ pNewElement->m_xStream->SetToBeCommited();
+
+ m_aChildrenMap[aName].push_back( pNewElement );
+ m_bIsModified = true;
+ m_bBroadcastModified = true;
+}
+
+std::unique_ptr<OStorage_Impl> OStorage_Impl::CreateNewStorageImpl( sal_Int32 nStorageMode )
+{
+ SAL_WARN_IF( !m_xPackage.is(), "package.xstor", "Not possible to refer to package as to factory!" );
+ if ( !m_xPackage.is() )
+ throw embed::InvalidStorageException( THROW_WHERE );
+
+ uno::Sequence< uno::Any > aSeq{ uno::Any(true) };
+ uno::Reference< lang::XUnoTunnel > xNewElement( m_xPackage->createInstanceWithArguments( aSeq ),
+ uno::UNO_QUERY );
+
+ SAL_WARN_IF( !xNewElement.is(), "package.xstor", "Not possible to create a new storage!" );
+ if ( !xNewElement.is() )
+ throw io::IOException( THROW_WHERE );
+
+ uno::Reference< container::XNameContainer > xPackageSubFolder( xNewElement, uno::UNO_QUERY_THROW );
+ std::unique_ptr<OStorage_Impl> pResult(
+ new OStorage_Impl( this, nStorageMode, xPackageSubFolder, m_xPackage, m_xContext, m_nStorageType ));
+ pResult->m_bIsModified = true;
+
+ return pResult;
+}
+
+SotElement_Impl* OStorage_Impl::InsertStorage( const OUString& aName, sal_Int32 nStorageMode )
+{
+ SotElement_Impl* pNewElement = InsertElement( aName, true );
+
+ pNewElement->m_xStorage = CreateNewStorageImpl(nStorageMode);
+
+ m_aChildrenMap[aName].push_back( pNewElement );
+
+ return pNewElement;
+}
+
+SotElement_Impl* OStorage_Impl::InsertElement( const OUString& aName, bool bIsStorage )
+{
+ assert( FindElement(aName) == nullptr && "Should not try to insert existing element");
+
+ ::osl::MutexGuard aGuard( m_xMutex->GetMutex() );
+
+ SotElement_Impl* pDeletedElm = nullptr;
+
+ auto it = m_aChildrenMap.find(aName);
+ if (it != m_aChildrenMap.end())
+ for (auto pElement : it->second)
+ {
+ SAL_WARN_IF( !pElement->m_bIsRemoved, "package.xstor", "Try to insert an element instead of existing one!" );
+ if ( pElement->m_bIsRemoved )
+ {
+ SAL_WARN_IF( pElement->m_bIsInserted, "package.xstor", "Inserted elements must be deleted immediately!" );
+ pDeletedElm = pElement;
+ }
+ }
+
+ if ( pDeletedElm )
+ {
+ if ( pDeletedElm->m_bIsStorage )
+ OpenSubStorage( pDeletedElm, embed::ElementModes::READWRITE );
+ else
+ OpenSubStream( pDeletedElm );
+
+ auto & rVec = m_aChildrenMap[aName];
+ rVec.erase(std::remove(rVec.begin(), rVec.end(), pDeletedElm), rVec.end());
+ if (rVec.empty())
+ m_aChildrenMap.erase(aName);
+ m_aDeletedVector.push_back( pDeletedElm );
+ }
+
+ // create new element
+ return new SotElement_Impl( aName, bIsStorage, true );
+}
+
+void OStorage_Impl::OpenSubStorage( SotElement_Impl* pElement, sal_Int32 nStorageMode )
+{
+ SAL_WARN_IF( !pElement, "package.xstor", "pElement is not set!" );
+ SAL_WARN_IF( !pElement->m_bIsStorage, "package.xstor", "Storage flag is not set!" );
+
+ ::osl::MutexGuard aGuard( m_xMutex->GetMutex() );
+
+ if (!pElement->m_xStorage)
+ {
+ SAL_WARN_IF( pElement->m_bIsInserted, "package.xstor", "Inserted element must be created already!" );
+
+ uno::Reference< lang::XUnoTunnel > xTunnel;
+ m_xPackageFolder->getByName( pElement->m_aOriginalName ) >>= xTunnel;
+ if ( !xTunnel.is() )
+ throw container::NoSuchElementException( THROW_WHERE );
+
+ uno::Reference< container::XNameContainer > xPackageSubFolder( xTunnel, uno::UNO_QUERY_THROW );
+ pElement->m_xStorage.reset(new OStorage_Impl(this, nStorageMode, xPackageSubFolder, m_xPackage, m_xContext, m_nStorageType));
+ }
+}
+
+void OStorage_Impl::OpenSubStream( SotElement_Impl* pElement )
+{
+ SAL_WARN_IF( !pElement, "package.xstor", "pElement is not set!" );
+ SAL_WARN_IF( pElement->m_bIsStorage, "package.xstor", "Storage flag is set!" );
+
+ ::osl::MutexGuard aGuard( m_xMutex->GetMutex() );
+
+ if (pElement->m_xStream)
+ return;
+
+ SAL_WARN_IF( pElement->m_bIsInserted, "package.xstor", "Inserted element must be created already!" );
+
+ uno::Reference< lang::XUnoTunnel > xTunnel;
+ m_xPackageFolder->getByName( pElement->m_aOriginalName ) >>= xTunnel;
+ if ( !xTunnel.is() )
+ throw container::NoSuchElementException( THROW_WHERE );
+
+ uno::Reference< packages::XDataSinkEncrSupport > xPackageSubStream( xTunnel, uno::UNO_QUERY_THROW );
+
+ // the stream can never be inserted here, because inserted stream element holds the stream till commit or destruction
+ pElement->m_xStream.reset(new OWriteStream_Impl(this, xPackageSubStream, m_xPackage, m_xContext, false, m_nStorageType, false, GetRelInfoStreamForName(pElement->m_aOriginalName)));
+}
+
+uno::Sequence< OUString > OStorage_Impl::GetElementNames()
+{
+ ::osl::MutexGuard aGuard( m_xMutex->GetMutex() );
+
+ ReadContents();
+
+ sal_Int32 nCnt = 0;
+ for ( const auto& pair : m_aChildrenMap )
+ for (auto pElement : pair.second)
+ {
+ if ( !pElement->m_bIsRemoved )
+ nCnt++;
+ }
+
+ uno::Sequence<OUString> aElementNames(nCnt);
+ OUString* pArray = aElementNames.getArray();
+ for ( const auto& pair : m_aChildrenMap )
+ for (auto pElement : pair.second)
+ {
+ if ( !pElement->m_bIsRemoved )
+ *pArray++ = pair.first;
+ }
+
+ return aElementNames;
+}
+
+void OStorage_Impl::RemoveElement( OUString const & rName, SotElement_Impl* pElement )
+{
+ assert(pElement);
+
+ if ( (pElement->m_xStorage && ( pElement->m_xStorage->m_pAntiImpl || !pElement->m_xStorage->m_aReadOnlyWrapVector.empty() ))
+ || (pElement->m_xStream && ( pElement->m_xStream->m_pAntiImpl || !pElement->m_xStream->m_aInputStreamsVector.empty() )) )
+ throw io::IOException( THROW_WHERE ); // TODO: Access denied
+
+ auto mapIt = m_aChildrenMap.find(rName);
+ for (auto it = mapIt->second.begin(); it != mapIt->second.end(); ++it)
+ if (pElement == *it)
+ {
+ if ( pElement->m_bIsInserted )
+ {
+ delete pElement;
+ mapIt->second.erase(std::remove(mapIt->second.begin(), mapIt->second.end(), pElement), mapIt->second.end());
+ if (mapIt->second.empty())
+ m_aChildrenMap.erase(mapIt);
+ }
+ else
+ {
+ pElement->m_bIsRemoved = true;
+ ClearElement( pElement );
+ }
+ return;
+ }
+ assert(false && "not found");
+
+ // TODO/OFOPXML: the rel stream should be removed as well
+}
+
+void OStorage_Impl::ClearElement( SotElement_Impl* pElement )
+{
+ pElement->m_xStorage.reset();
+ pElement->m_xStream.reset();
+}
+
+void OStorage_Impl::CloneStreamElement( const OUString& aStreamName,
+ bool bEncryptionDataProvided,
+ const ::comphelper::SequenceAsHashMap& aEncryptionData,
+ uno::Reference< io::XStream >& xTargetStream )
+{
+ SotElement_Impl *pElement = FindElement( aStreamName );
+ if ( !pElement )
+ {
+ // element does not exist, throw exception
+ throw io::IOException( THROW_WHERE ); // TODO: access_denied
+ }
+ else if ( pElement->m_bIsStorage )
+ throw io::IOException( THROW_WHERE );
+
+ if (!pElement->m_xStream)
+ OpenSubStream( pElement );
+
+ if (!pElement->m_xStream || !pElement->m_xStream->m_xPackageStream.is())
+ throw io::IOException( THROW_WHERE ); // TODO: general_error
+
+ // the existence of m_pAntiImpl of the child is not interesting,
+ // the copy will be created internally
+
+ // usual copying is not applicable here, only last flushed version of the
+ // child stream should be used for copying. Probably the children m_xPackageStream
+ // can be used as a base of a new stream, that would be copied to result
+ // storage. The only problem is that some package streams can be accessed from outside
+ // at the same time (now solved by wrappers that remember own position).
+
+ if (bEncryptionDataProvided)
+ pElement->m_xStream->GetCopyOfLastCommit(xTargetStream, aEncryptionData);
+ else
+ pElement->m_xStream->GetCopyOfLastCommit(xTargetStream);
+}
+
+void OStorage_Impl::RemoveStreamRelInfo( std::u16string_view aOriginalName )
+{
+ // this method should be used only in OStorage_Impl::Commit() method
+ // the aOriginalName can be empty, in this case the storage relation info should be removed
+
+ if ( m_nStorageType == embed::StorageFormats::OFOPXML && m_xRelStorage.is() )
+ {
+ OUString aRelStreamName = OUString::Concat(aOriginalName) + ".rels";
+
+ if ( m_xRelStorage->hasByName( aRelStreamName ) )
+ m_xRelStorage->removeElement( aRelStreamName );
+ }
+}
+
+void OStorage_Impl::CreateRelStorage()
+{
+ if ( m_nStorageType != embed::StorageFormats::OFOPXML )
+ return;
+
+ if ( m_xRelStorage.is() )
+ return;
+
+ if ( !m_pRelStorElement )
+ {
+ m_pRelStorElement = new SotElement_Impl( "_rels", true, true );
+ m_pRelStorElement->m_xStorage = CreateNewStorageImpl(embed::ElementModes::WRITE);
+ if (m_pRelStorElement->m_xStorage)
+ m_pRelStorElement->m_xStorage->m_pParent = nullptr; // the relation storage is completely controlled by parent
+ }
+
+ if (!m_pRelStorElement->m_xStorage)
+ OpenSubStorage( m_pRelStorElement, embed::ElementModes::WRITE );
+
+ if (!m_pRelStorElement->m_xStorage)
+ throw uno::RuntimeException( THROW_WHERE );
+
+ m_xRelStorage = new OStorage(m_pRelStorElement->m_xStorage.get(), false);
+}
+
+void OStorage_Impl::CommitStreamRelInfo( std::u16string_view rName, SotElement_Impl const * pStreamElement )
+{
+ // this method should be used only in OStorage_Impl::Commit() method
+
+ // the stream element must be provided
+ if ( !pStreamElement )
+ throw uno::RuntimeException( THROW_WHERE );
+
+ if (m_nStorageType == embed::StorageFormats::OFOPXML && pStreamElement->m_xStream)
+ {
+ SAL_WARN_IF( rName.empty(), "package.xstor", "The name must not be empty!" );
+
+ if ( !m_xRelStorage.is() )
+ {
+ // Create new rels storage, this is commit scenario so it must be possible
+ CreateRelStorage();
+ }
+
+ pStreamElement->m_xStream->CommitStreamRelInfo(m_xRelStorage, pStreamElement->m_aOriginalName, rName);
+ }
+}
+
+uno::Reference< io::XInputStream > OStorage_Impl::GetRelInfoStreamForName(
+ std::u16string_view aName )
+{
+ if ( m_nStorageType == embed::StorageFormats::OFOPXML )
+ {
+ ReadContents();
+ if ( m_xRelStorage.is() )
+ {
+ OUString aRelStreamName = OUString::Concat(aName) + ".rels";
+ if ( m_xRelStorage->hasByName( aRelStreamName ) )
+ {
+ uno::Reference< io::XStream > xStream = m_xRelStorage->openStreamElement( aRelStreamName, embed::ElementModes::READ );
+ if ( xStream.is() )
+ return xStream->getInputStream();
+ }
+ }
+ }
+
+ return uno::Reference< io::XInputStream >();
+}
+
+void OStorage_Impl::CommitRelInfo( const uno::Reference< container::XNameContainer >& xNewPackageFolder )
+{
+ // this method should be used only in OStorage_Impl::Commit() method
+ OUString aRelsStorName("_rels");
+
+ if ( !xNewPackageFolder.is() )
+ throw uno::RuntimeException( THROW_WHERE );
+
+ if ( m_nStorageType != embed::StorageFormats::OFOPXML )
+ return;
+
+ if ( m_nRelInfoStatus == RELINFO_BROKEN || m_nRelInfoStatus == RELINFO_CHANGED_BROKEN )
+ throw io::IOException( THROW_WHERE );
+
+ if (m_nRelInfoStatus == RELINFO_CHANGED)
+ {
+ if (m_aRelInfo.hasElements())
+ {
+ CreateRelStorage();
+
+ uno::Reference<io::XStream> xRelsStream = m_xRelStorage->openStreamElement(
+ ".rels", embed::ElementModes::TRUNCATE | embed::ElementModes::READWRITE);
+
+ uno::Reference<io::XOutputStream> xOutStream = xRelsStream->getOutputStream();
+ if (!xOutStream.is())
+ throw uno::RuntimeException(THROW_WHERE);
+
+ ::comphelper::OFOPXMLHelper::WriteRelationsInfoSequence(xOutStream, m_aRelInfo,
+ m_xContext);
+
+ // set the mediatype
+ uno::Reference<beans::XPropertySet> xPropSet(xRelsStream, uno::UNO_QUERY_THROW);
+ xPropSet->setPropertyValue(
+ "MediaType", uno::Any(OUString(
+ "application/vnd.openxmlformats-package.relationships+xml")));
+
+ m_nRelInfoStatus = RELINFO_READ;
+ }
+ else if (m_xRelStorage.is())
+ RemoveStreamRelInfo(std::u16string_view()); // remove own rel info
+ }
+ else if (m_nRelInfoStatus == RELINFO_CHANGED_STREAM_READ
+ || m_nRelInfoStatus == RELINFO_CHANGED_STREAM)
+ {
+ CreateRelStorage();
+
+ uno::Reference<io::XStream> xRelsStream = m_xRelStorage->openStreamElement(
+ ".rels", embed::ElementModes::TRUNCATE | embed::ElementModes::READWRITE);
+
+ uno::Reference<io::XOutputStream> xOutputStream = xRelsStream->getOutputStream();
+ if (!xOutputStream.is())
+ throw uno::RuntimeException(THROW_WHERE);
+
+ uno::Reference<io::XSeekable> xSeek(m_xNewRelInfoStream, uno::UNO_QUERY_THROW);
+ xSeek->seek(0);
+ ::comphelper::OStorageHelper::CopyInputToOutput(m_xNewRelInfoStream, xOutputStream);
+
+ // set the mediatype
+ uno::Reference<beans::XPropertySet> xPropSet(xRelsStream, uno::UNO_QUERY_THROW);
+ xPropSet->setPropertyValue(
+ "MediaType",
+ uno::Any(OUString("application/vnd.openxmlformats-package.relationships+xml")));
+
+ m_xNewRelInfoStream.clear();
+ if (m_nRelInfoStatus == RELINFO_CHANGED_STREAM)
+ {
+ m_aRelInfo = uno::Sequence<uno::Sequence<beans::StringPair>>();
+ m_nRelInfoStatus = RELINFO_NO_INIT;
+ }
+ else
+ m_nRelInfoStatus = RELINFO_READ;
+ }
+
+ if ( !m_xRelStorage.is() )
+ return;
+
+ if ( m_xRelStorage->hasElements() )
+ {
+ uno::Reference< embed::XTransactedObject > xTrans( m_xRelStorage, uno::UNO_QUERY_THROW );
+ xTrans->commit();
+ }
+
+ if ( xNewPackageFolder.is() && xNewPackageFolder->hasByName( aRelsStorName ) )
+ xNewPackageFolder->removeByName( aRelsStorName );
+
+ if ( !m_xRelStorage->hasElements() )
+ {
+ // the empty relations storage should not be created
+ delete m_pRelStorElement;
+ m_pRelStorElement = nullptr;
+ m_xRelStorage.clear();
+ }
+ else if ( m_pRelStorElement && m_pRelStorElement->m_xStorage && xNewPackageFolder.is() )
+ m_pRelStorElement->m_xStorage->InsertIntoPackageFolder( aRelsStorName, xNewPackageFolder );
+}
+
+// OStorage implementation
+
+OStorage::OStorage( uno::Reference< io::XInputStream > const & xInputStream,
+ sal_Int32 nMode,
+ const uno::Sequence< beans::PropertyValue >& xProperties,
+ uno::Reference< uno::XComponentContext > const & xContext,
+ sal_Int32 nStorageType )
+: m_pImpl( new OStorage_Impl( xInputStream, nMode, xProperties, xContext, nStorageType ) )
+, m_xSharedMutex( m_pImpl->m_xMutex )
+, m_aListenersContainer( m_pImpl->m_xMutex->GetMutex() )
+, m_bReadOnlyWrap( false )
+{
+ m_pImpl->m_pAntiImpl = this;
+}
+
+OStorage::OStorage( uno::Reference< io::XStream > const & xStream,
+ sal_Int32 nMode,
+ const uno::Sequence< beans::PropertyValue >& xProperties,
+ uno::Reference< uno::XComponentContext > const & xContext,
+ sal_Int32 nStorageType )
+: m_pImpl( new OStorage_Impl( xStream, nMode, xProperties, xContext, nStorageType ) )
+, m_xSharedMutex( m_pImpl->m_xMutex )
+, m_aListenersContainer( m_pImpl->m_xMutex->GetMutex() )
+, m_bReadOnlyWrap( false )
+{
+ m_pImpl->m_pAntiImpl = this;
+}
+
+OStorage::OStorage( OStorage_Impl* pImpl, bool bReadOnlyWrap )
+: m_pImpl( pImpl )
+, m_xSharedMutex( m_pImpl->m_xMutex )
+, m_aListenersContainer( m_pImpl->m_xMutex->GetMutex() )
+, m_bReadOnlyWrap( bReadOnlyWrap )
+{
+ // this call can be done only from OStorage_Impl implementation to create child storage
+ assert( m_pImpl && m_pImpl->m_xMutex.is() && "The provided pointer & mutex MUST NOT be empty!" );
+
+ OSL_ENSURE( ( m_pImpl->m_nStorageMode & embed::ElementModes::WRITE ) == embed::ElementModes::WRITE ||
+ m_bReadOnlyWrap,
+ "The wrapper can not allow writing in case implementation does not!" );
+
+ if ( !bReadOnlyWrap )
+ m_pImpl->m_pAntiImpl = this;
+}
+
+OStorage::~OStorage()
+{
+ ::osl::MutexGuard aGuard( m_xSharedMutex->GetMutex() );
+ if ( m_pImpl )
+ {
+ osl_atomic_increment(&m_refCount); // to call dispose
+ try {
+ dispose();
+ }
+ catch( const uno::RuntimeException& )
+ {
+ TOOLS_INFO_EXCEPTION("package.xstor", "Handled exception");
+ }
+ }
+}
+
+void OStorage::InternalDispose( bool bNotifyImpl )
+{
+ if ( !m_pImpl )
+ {
+ SAL_INFO("package.xstor", THROW_WHERE "Disposed!");
+ throw lang::DisposedException( THROW_WHERE );
+ }
+
+ // the source object is also a kind of locker for the current object
+ // since the listeners could dispose the object while being notified
+ lang::EventObject aSource( static_cast< ::cppu::OWeakObject* >(this) );
+ m_aListenersContainer.disposeAndClear( aSource );
+
+ if ( !m_pImpl )
+ {
+ SAL_INFO("package.xstor", THROW_WHERE "Disposed!");
+ throw lang::DisposedException( THROW_WHERE );
+ }
+
+ m_pImpl->m_nModifiedListenerCount = 0;
+
+ if ( m_bReadOnlyWrap )
+ {
+ OSL_ENSURE( m_aOpenSubComponentsVector.empty() || m_pSubElDispListener,
+ "If any subelements are open the listener must exist!" );
+
+ if (m_pSubElDispListener)
+ {
+ m_pSubElDispListener->OwnerIsDisposed();
+
+ // iterate through m_pData->m_aOpenSubComponentsVector
+ // deregister m_pData->m_pSubElDispListener and dispose all of them
+ if ( !m_aOpenSubComponentsVector.empty() )
+ {
+ for ( const auto& pComp : m_aOpenSubComponentsVector )
+ {
+ uno::Reference< lang::XComponent > xTmp = pComp;
+ if ( xTmp.is() )
+ {
+ xTmp->removeEventListener( uno::Reference< lang::XEventListener >(
+ static_cast< lang::XEventListener* >( m_pSubElDispListener.get())));
+
+ try {
+ xTmp->dispose();
+ } catch( const uno::Exception& )
+ {
+ TOOLS_INFO_EXCEPTION("package.xstor", "Quiet exception");
+ }
+ }
+ }
+
+ m_aOpenSubComponentsVector.clear();
+ }
+ }
+
+ if ( bNotifyImpl )
+ m_pImpl->RemoveReadOnlyWrap( *this );
+ }
+ else
+ {
+ m_pImpl->m_pAntiImpl = nullptr;
+
+ if ( bNotifyImpl )
+ {
+ if ( m_pImpl->m_bIsRoot )
+ delete m_pImpl;
+ else
+ {
+ // the non-committed changes for the storage must be removed
+ m_pImpl->Revert();
+ }
+ }
+ }
+
+ m_pImpl = nullptr;
+}
+
+void OStorage::ChildIsDisposed( const uno::Reference< uno::XInterface >& xChild )
+{
+ // this method can only be called by child disposing listener
+
+ // this method must not contain any locking
+ // the locking is done in the listener
+
+ auto& rVec = m_aOpenSubComponentsVector;
+ rVec.erase(std::remove_if(rVec.begin(), rVec.end(),
+ [&xChild](const uno::Reference<lang::XComponent>& xTmp) {
+ return !xTmp.is() || xTmp == xChild;
+ }),
+ rVec.end());
+}
+
+void OStorage::BroadcastModifiedIfNecessary()
+{
+ // no need to lock mutex here for the checking of m_pImpl, and m_pData is alive until the object is destructed
+ if ( !m_pImpl )
+ {
+ SAL_INFO("package.xstor", THROW_WHERE "Disposed!");
+ throw lang::DisposedException( THROW_WHERE );
+ }
+
+ if ( !m_pImpl->m_bBroadcastModified )
+ return;
+
+ m_pImpl->m_bBroadcastModified = false;
+
+ SAL_WARN_IF( m_bReadOnlyWrap, "package.xstor", "The storage can not be modified at all!" );
+
+ lang::EventObject aSource( static_cast< ::cppu::OWeakObject* >(this) );
+
+ comphelper::OInterfaceContainerHelper2* pContainer =
+ m_aListenersContainer.getContainer(
+ cppu::UnoType<util::XModifyListener>::get());
+ if ( pContainer )
+ {
+ comphelper::OInterfaceIteratorHelper2 pIterator( *pContainer );
+ while ( pIterator.hasMoreElements( ) )
+ {
+ static_cast<util::XModifyListener*>( pIterator.next( ) )->modified( aSource );
+ }
+ }
+}
+
+void OStorage::BroadcastTransaction( sal_Int8 nMessage )
+/*
+ 1 - preCommit
+ 2 - committed
+ 3 - preRevert
+ 4 - reverted
+*/
+{
+ // no need to lock mutex here for the checking of m_pImpl, and m_pData is alive until the object is destructed
+ if ( !m_pImpl )
+ {
+ SAL_INFO("package.xstor", THROW_WHERE "Disposed!");
+ throw lang::DisposedException( THROW_WHERE );
+ }
+
+ SAL_WARN_IF( m_bReadOnlyWrap, "package.xstor", "The storage can not be modified at all!" );
+
+ lang::EventObject aSource( static_cast< ::cppu::OWeakObject* >(this) );
+
+ comphelper::OInterfaceContainerHelper2* pContainer =
+ m_aListenersContainer.getContainer(
+ cppu::UnoType<embed::XTransactionListener>::get());
+ if ( !pContainer )
+ return;
+
+ comphelper::OInterfaceIteratorHelper2 pIterator( *pContainer );
+ while ( pIterator.hasMoreElements( ) )
+ {
+ OSL_ENSURE( nMessage >= 1 && nMessage <= 4, "Wrong internal notification code is used!" );
+
+ switch( nMessage )
+ {
+ case STOR_MESS_PRECOMMIT:
+ static_cast<embed::XTransactionListener*>( pIterator.next( ) )->preCommit( aSource );
+ break;
+ case STOR_MESS_COMMITTED:
+ static_cast<embed::XTransactionListener*>( pIterator.next( ) )->commited( aSource );
+ break;
+ case STOR_MESS_PREREVERT:
+ static_cast<embed::XTransactionListener*>( pIterator.next( ) )->preRevert( aSource );
+ break;
+ case STOR_MESS_REVERTED:
+ static_cast<embed::XTransactionListener*>( pIterator.next( ) )->reverted( aSource );
+ break;
+ }
+ }
+}
+
+SotElement_Impl* OStorage::OpenStreamElement_Impl( const OUString& aStreamName, sal_Int32 nOpenMode, bool bEncr )
+{
+ ::osl::MutexGuard aGuard( m_xSharedMutex->GetMutex() );
+
+ OSL_ENSURE( !m_bReadOnlyWrap || ( nOpenMode & embed::ElementModes::WRITE ) != embed::ElementModes::WRITE,
+ "An element can not be opened for writing in readonly storage!" );
+
+ SotElement_Impl *pElement = m_pImpl->FindElement( aStreamName );
+ if ( !pElement )
+ {
+ // element does not exist, check if creation is allowed
+ if ( !( m_pImpl->m_nStorageMode & embed::ElementModes::WRITE )
+ || (( nOpenMode & embed::ElementModes::WRITE ) != embed::ElementModes::WRITE )
+ || ( nOpenMode & embed::ElementModes::NOCREATE ) == embed::ElementModes::NOCREATE )
+ {
+ throw io::IOException("Element does not exist and cannot be "
+ "created: \"" + aStreamName + "\""); // TODO: access_denied
+ }
+
+ // create a new StreamElement and insert it into the list
+ pElement = m_pImpl->InsertStream( aStreamName, bEncr );
+ }
+ else if ( pElement->m_bIsStorage )
+ {
+ throw io::IOException( THROW_WHERE );
+ }
+
+ SAL_WARN_IF( !pElement, "package.xstor", "In case element can not be created an exception must be thrown!" );
+
+ if (!pElement->m_xStream)
+ m_pImpl->OpenSubStream( pElement );
+
+ if (!pElement->m_xStream)
+ throw io::IOException( THROW_WHERE );
+
+ return pElement;
+}
+
+void OStorage::MakeLinkToSubComponent_Impl( const uno::Reference< lang::XComponent >& xComponent )
+{
+ if ( !xComponent.is() )
+ throw uno::RuntimeException( THROW_WHERE );
+
+ if (!m_pSubElDispListener)
+ {
+ m_pSubElDispListener = new OChildDispListener_Impl( *this );
+ }
+
+ xComponent->addEventListener( m_pSubElDispListener );
+
+ m_aOpenSubComponentsVector.emplace_back(xComponent );
+}
+
+// XInterface
+
+uno::Any SAL_CALL OStorage::queryInterface( const uno::Type& rType )
+{
+ // common interfaces
+ uno::Any aReturn = ::cppu::queryInterface
+ ( rType
+ , static_cast<lang::XTypeProvider*> ( this )
+ , static_cast<embed::XStorage*> ( this )
+ , static_cast<embed::XStorage2*> ( this )
+ , static_cast<embed::XTransactedObject*> ( this )
+ , static_cast<embed::XTransactionBroadcaster*> ( this )
+ , static_cast<util::XModifiable*> ( this )
+ , static_cast<container::XNameAccess*> ( this )
+ , static_cast<container::XElementAccess*> ( this )
+ , static_cast<lang::XComponent*> ( this )
+ , static_cast<beans::XPropertySet*> ( this )
+ , static_cast<embed::XOptimizedStorage*> ( this ) );
+
+ if ( aReturn.hasValue() )
+ return aReturn ;
+
+ aReturn = ::cppu::queryInterface
+ ( rType
+ , static_cast<embed::XHierarchicalStorageAccess*> ( this )
+ , static_cast<embed::XHierarchicalStorageAccess2*> ( this ) );
+
+ if ( aReturn.hasValue() )
+ return aReturn ;
+
+ if ( m_pImpl->m_nStorageType == embed::StorageFormats::PACKAGE )
+ {
+ if ( m_pImpl->m_bIsRoot )
+ {
+ aReturn = ::cppu::queryInterface
+ ( rType
+ , static_cast<embed::XStorageRawAccess*> ( this )
+ , static_cast<embed::XEncryptionProtectedSource*> ( this )
+ , static_cast<embed::XEncryptionProtectedSource2*> ( this )
+ , static_cast<embed::XEncryptionProtectedStorage*> ( this ) );
+ }
+ else
+ {
+ aReturn = ::cppu::queryInterface
+ ( rType
+ , static_cast<embed::XStorageRawAccess*> ( this ) );
+ }
+ }
+ else if ( m_pImpl->m_nStorageType == embed::StorageFormats::OFOPXML )
+ {
+ aReturn = ::cppu::queryInterface
+ ( rType
+ , static_cast<embed::XRelationshipAccess*> ( this ) );
+ }
+
+ if ( aReturn.hasValue() )
+ return aReturn ;
+
+ return OWeakObject::queryInterface( rType );
+}
+
+void SAL_CALL OStorage::acquire() noexcept
+{
+ OWeakObject::acquire();
+}
+
+void SAL_CALL OStorage::release() noexcept
+{
+ OWeakObject::release();
+}
+
+// XTypeProvider
+uno::Sequence< uno::Type > SAL_CALL OStorage::getTypes()
+{
+ if (! m_pTypeCollection)
+ {
+ ::osl::MutexGuard aGuard( m_xSharedMutex->GetMutex() );
+
+ if (! m_pTypeCollection)
+ {
+ if ( m_pImpl->m_nStorageType == embed::StorageFormats::PACKAGE )
+ {
+ if ( m_pImpl->m_bIsRoot )
+ {
+ m_pTypeCollection.reset(new ::cppu::OTypeCollection
+ ( cppu::UnoType<lang::XTypeProvider>::get()
+ , cppu::UnoType<embed::XStorage>::get()
+ , cppu::UnoType<embed::XStorage2>::get()
+ , cppu::UnoType<embed::XStorageRawAccess>::get()
+ , cppu::UnoType<embed::XTransactedObject>::get()
+ , cppu::UnoType<embed::XTransactionBroadcaster>::get()
+ , cppu::UnoType<util::XModifiable>::get()
+ , cppu::UnoType<embed::XEncryptionProtectedStorage>::get()
+ , cppu::UnoType<embed::XEncryptionProtectedSource2>::get()
+ , cppu::UnoType<embed::XEncryptionProtectedSource>::get()
+ , cppu::UnoType<beans::XPropertySet>::get()));
+ }
+ else
+ {
+ m_pTypeCollection.reset(new ::cppu::OTypeCollection
+ ( cppu::UnoType<lang::XTypeProvider>::get()
+ , cppu::UnoType<embed::XStorage>::get()
+ , cppu::UnoType<embed::XStorage2>::get()
+ , cppu::UnoType<embed::XStorageRawAccess>::get()
+ , cppu::UnoType<embed::XTransactedObject>::get()
+ , cppu::UnoType<embed::XTransactionBroadcaster>::get()
+ , cppu::UnoType<util::XModifiable>::get()
+ , cppu::UnoType<beans::XPropertySet>::get()));
+ }
+ }
+ else if ( m_pImpl->m_nStorageType == embed::StorageFormats::OFOPXML )
+ {
+ m_pTypeCollection.reset(new ::cppu::OTypeCollection
+ ( cppu::UnoType<lang::XTypeProvider>::get()
+ , cppu::UnoType<embed::XStorage>::get()
+ , cppu::UnoType<embed::XTransactedObject>::get()
+ , cppu::UnoType<embed::XTransactionBroadcaster>::get()
+ , cppu::UnoType<util::XModifiable>::get()
+ , cppu::UnoType<embed::XRelationshipAccess>::get()
+ , cppu::UnoType<beans::XPropertySet>::get()));
+ }
+ else
+ {
+ m_pTypeCollection.reset(new ::cppu::OTypeCollection
+ ( cppu::UnoType<lang::XTypeProvider>::get()
+ , cppu::UnoType<embed::XStorage>::get()
+ , cppu::UnoType<embed::XTransactedObject>::get()
+ , cppu::UnoType<embed::XTransactionBroadcaster>::get()
+ , cppu::UnoType<util::XModifiable>::get()
+ , cppu::UnoType<beans::XPropertySet>::get()));
+ }
+ }
+ }
+
+ return m_pTypeCollection->getTypes() ;
+}
+
+uno::Sequence< sal_Int8 > SAL_CALL OStorage::getImplementationId()
+{
+ static const comphelper::UnoIdInit lcl_ImplId;
+ return lcl_ImplId.getSeq();
+}
+
+// XStorage
+void SAL_CALL OStorage::copyToStorage( const uno::Reference< embed::XStorage >& xDest )
+{
+ ::osl::MutexGuard aGuard( m_xSharedMutex->GetMutex() );
+
+ if ( !m_pImpl )
+ {
+ SAL_INFO("package.xstor", THROW_WHERE "Disposed!");
+ throw lang::DisposedException( THROW_WHERE );
+ }
+
+ if ( !xDest.is() || xDest == uno::Reference< uno::XInterface >( static_cast< OWeakObject*> ( this ), uno::UNO_QUERY ) )
+ throw lang::IllegalArgumentException( THROW_WHERE, uno::Reference< uno::XInterface >(), 1 );
+
+ try {
+ m_pImpl->CopyToStorage( xDest, false );
+ }
+ catch( const embed::InvalidStorageException& )
+ {
+ TOOLS_INFO_EXCEPTION("package.xstor", "Rethrow");
+ throw;
+ }
+ catch( const lang::IllegalArgumentException& )
+ {
+ TOOLS_INFO_EXCEPTION("package.xstor", "Rethrow");
+ throw;
+ }
+ catch( const embed::StorageWrappedTargetException& )
+ {
+ TOOLS_INFO_EXCEPTION("package.xstor", "Rethrow");
+ throw;
+ }
+ catch( const io::IOException& )
+ {
+ TOOLS_INFO_EXCEPTION("package.xstor", "Rethrow");
+ throw;
+ }
+ catch( const uno::RuntimeException& )
+ {
+ TOOLS_INFO_EXCEPTION("package.xstor", "Rethrow");
+ throw;
+ }
+ catch( const uno::Exception& )
+ {
+ uno::Any aCaught( ::cppu::getCaughtException() );
+ SAL_INFO("package.xstor", "Rethrow: " << exceptionToString(aCaught));
+
+ throw embed::StorageWrappedTargetException( THROW_WHERE "Can't copy storage!",
+ uno::Reference< io::XInputStream >(),
+ aCaught );
+ }
+}
+
+uno::Reference< io::XStream > SAL_CALL OStorage::openStreamElement(
+ const OUString& aStreamName, sal_Int32 nOpenMode )
+{
+ osl::ClearableMutexGuard aGuard(m_xSharedMutex->GetMutex());
+
+ if ( !m_pImpl )
+ {
+ SAL_INFO("package.xstor", THROW_WHERE "Disposed!");
+ throw lang::DisposedException( THROW_WHERE );
+ }
+
+ if ( aStreamName.isEmpty() || !::comphelper::OStorageHelper::IsValidZipEntryFileName( aStreamName, false ) )
+ throw lang::IllegalArgumentException( THROW_WHERE "Unexpected entry name syntax.", uno::Reference< uno::XInterface >(), 1 );
+
+ if ( m_pImpl->m_nStorageType == embed::StorageFormats::OFOPXML && aStreamName == "_rels" )
+ throw lang::IllegalArgumentException( THROW_WHERE, uno::Reference< uno::XInterface >(), 1 ); // unacceptable element name
+
+ if ( ( nOpenMode & embed::ElementModes::WRITE ) && m_bReadOnlyWrap )
+ throw io::IOException( THROW_WHERE ); // TODO: access denied
+
+ uno::Reference< io::XStream > xResult;
+ try
+ {
+ SotElement_Impl *pElement = OpenStreamElement_Impl( aStreamName, nOpenMode, false );
+ OSL_ENSURE(pElement && pElement->m_xStream, "In case element can not be created an exception must be thrown!");
+
+ xResult = pElement->m_xStream->GetStream(nOpenMode, false);
+ SAL_WARN_IF( !xResult.is(), "package.xstor", "The method must throw exception instead of removing empty result!" );
+
+ if ( m_bReadOnlyWrap )
+ {
+ // before the storage disposes the stream it must deregister itself as listener
+ uno::Reference< lang::XComponent > xStreamComponent( xResult, uno::UNO_QUERY_THROW );
+ MakeLinkToSubComponent_Impl( xStreamComponent );
+ }
+ }
+ catch( const embed::InvalidStorageException& )
+ {
+ TOOLS_INFO_EXCEPTION("package.xstor", "Rethrow");
+ throw;
+ }
+ catch( const lang::IllegalArgumentException& )
+ {
+ TOOLS_INFO_EXCEPTION("package.xstor", "Rethrow");
+ throw;
+ }
+ catch( const packages::WrongPasswordException& )
+ {
+ TOOLS_INFO_EXCEPTION("package.xstor", "Rethrow");
+ throw;
+ }
+ catch( const embed::StorageWrappedTargetException& )
+ {
+ TOOLS_INFO_EXCEPTION("package.xstor", "Rethrow");
+ throw;
+ }
+ catch( const io::IOException& )
+ {
+ TOOLS_INFO_EXCEPTION("package.xstor", "Rethrow");
+ throw;
+ }
+ catch( const uno::RuntimeException& )
+ {
+ TOOLS_INFO_EXCEPTION("package.xstor", "Rethrow");
+ throw;
+ }
+ catch( const uno::Exception& )
+ {
+ uno::Any aCaught( ::cppu::getCaughtException() );
+ SAL_INFO("package.xstor", "Rethrow: " << exceptionToString(aCaught));
+
+ throw embed::StorageWrappedTargetException(THROW_WHERE "Can't open stream element!",
+ uno::Reference< io::XInputStream >(),
+ aCaught );
+ }
+
+ aGuard.clear();
+
+ BroadcastModifiedIfNecessary();
+
+ return xResult;
+}
+
+uno::Reference< io::XStream > SAL_CALL OStorage::openEncryptedStreamElement(
+ const OUString& aStreamName, sal_Int32 nOpenMode, const OUString& aPass )
+{
+ return openEncryptedStream( aStreamName, nOpenMode, ::comphelper::OStorageHelper::CreatePackageEncryptionData( aPass ) );
+}
+
+uno::Reference< embed::XStorage > SAL_CALL OStorage::openStorageElement(
+ const OUString& aStorName, sal_Int32 nStorageMode )
+{
+ ::osl::MutexGuard aGuard( m_xSharedMutex->GetMutex() );
+
+ if ( !m_pImpl )
+ {
+ SAL_INFO("package.xstor", THROW_WHERE "Disposed!");
+ throw lang::DisposedException( THROW_WHERE );
+ }
+
+ if ( aStorName.isEmpty() || !::comphelper::OStorageHelper::IsValidZipEntryFileName( aStorName, false ) )
+ throw lang::IllegalArgumentException( THROW_WHERE "Unexpected entry name syntax.", uno::Reference< uno::XInterface >(), 1 );
+
+ if ( m_pImpl->m_nStorageType == embed::StorageFormats::OFOPXML && aStorName == "_rels" )
+ throw lang::IllegalArgumentException( THROW_WHERE, uno::Reference< uno::XInterface >(), 1 ); // unacceptable storage name
+
+ if ( ( nStorageMode & embed::ElementModes::WRITE ) && m_bReadOnlyWrap )
+ throw io::IOException( THROW_WHERE ); // TODO: access denied
+
+ if ( ( nStorageMode & embed::ElementModes::TRUNCATE )
+ && !( nStorageMode & embed::ElementModes::WRITE ) )
+ throw io::IOException( THROW_WHERE ); // TODO: access denied
+
+ // it's always possible to read written storage in this implementation
+ nStorageMode |= embed::ElementModes::READ;
+
+ uno::Reference< embed::XStorage > xResult;
+ try
+ {
+ SotElement_Impl *pElement = m_pImpl->FindElement( aStorName );
+ if ( !pElement )
+ {
+ // element does not exist, check if creation is allowed
+ if ( !( m_pImpl->m_nStorageMode & embed::ElementModes::WRITE )
+ || (( nStorageMode & embed::ElementModes::WRITE ) != embed::ElementModes::WRITE )
+ || ( nStorageMode & embed::ElementModes::NOCREATE ) == embed::ElementModes::NOCREATE )
+ throw io::IOException( THROW_WHERE ); // TODO: access_denied
+
+ // create a new StorageElement and insert it into the list
+ pElement = m_pImpl->InsertStorage( aStorName, nStorageMode );
+ }
+ else if ( !pElement->m_bIsStorage )
+ {
+ throw io::IOException( THROW_WHERE );
+ }
+ else if (pElement->m_xStorage)
+ {
+ // storage has already been opened; it may be opened another time, if it the mode allows to do so
+ if (pElement->m_xStorage->m_pAntiImpl)
+ {
+ throw io::IOException( THROW_WHERE ); // TODO: access_denied
+ }
+ else if ( !pElement->m_xStorage->m_aReadOnlyWrapVector.empty()
+ && ( nStorageMode & embed::ElementModes::WRITE ) )
+ {
+ throw io::IOException( THROW_WHERE ); // TODO: access_denied
+ }
+ else
+ {
+ // in case parent storage allows writing the readonly mode of the child storage is
+ // virtual, that means that it is just enough to change the flag to let it be writable
+ // and since there is no AntiImpl nobody should be notified about it
+ pElement->m_xStorage->m_nStorageMode = nStorageMode | embed::ElementModes::READ;
+
+ if ( nStorageMode & embed::ElementModes::TRUNCATE )
+ {
+ for (const auto & rPair : pElement->m_xStorage->m_aChildrenMap)
+ for (auto pElementToDel : rPair.second)
+ m_pImpl->RemoveElement( /*aName*/rPair.first, pElementToDel );
+ }
+ }
+ }
+
+ if (!pElement->m_xStorage)
+ m_pImpl->OpenSubStorage(pElement, nStorageMode);
+
+ if (!pElement->m_xStorage)
+ throw io::IOException( THROW_WHERE ); // TODO: general_error
+
+ bool bReadOnlyWrap = ( ( nStorageMode & embed::ElementModes::WRITE ) != embed::ElementModes::WRITE );
+ rtl::Reference<OStorage> pResultStorage = new OStorage(pElement->m_xStorage.get(), bReadOnlyWrap);
+ xResult = pResultStorage;
+
+ if ( bReadOnlyWrap )
+ {
+ // Before this call is done the object must be refcounted already
+ pElement->m_xStorage->SetReadOnlyWrap(*pResultStorage);
+
+ // before the storage disposes the stream it must deregister itself as listener
+ uno::Reference< lang::XComponent > xStorageComponent( xResult, uno::UNO_QUERY_THROW );
+ MakeLinkToSubComponent_Impl( xStorageComponent );
+ }
+ }
+ catch( const embed::InvalidStorageException& )
+ {
+ TOOLS_INFO_EXCEPTION("package.xstor", "Rethrow");
+ throw;
+ }
+ catch( const lang::IllegalArgumentException& )
+ {
+ TOOLS_INFO_EXCEPTION("package.xstor", "Rethrow");
+ throw;
+ }
+ catch( const embed::StorageWrappedTargetException& )
+ {
+ TOOLS_INFO_EXCEPTION("package.xstor", "Rethrow");
+ throw;
+ }
+ catch( const io::IOException& )
+ {
+ TOOLS_INFO_EXCEPTION("package.xstor", "Rethrow");
+ throw;
+ }
+ catch( const uno::RuntimeException& )
+ {
+ TOOLS_INFO_EXCEPTION("package.xstor", "Rethrow");
+ throw;
+ }
+ catch( const uno::Exception& )
+ {
+ uno::Any aCaught( ::cppu::getCaughtException() );
+ SAL_INFO("package.xstor", "Rethrow: " << exceptionToString(aCaught));
+
+ throw embed::StorageWrappedTargetException( THROW_WHERE "Can't open storage!",
+ uno::Reference< io::XInputStream >(),
+ aCaught );
+ }
+
+ return xResult;
+}
+
+uno::Reference< io::XStream > SAL_CALL OStorage::cloneStreamElement( const OUString& aStreamName )
+{
+ ::osl::MutexGuard aGuard( m_xSharedMutex->GetMutex() );
+
+ if ( !m_pImpl )
+ {
+ SAL_INFO("package.xstor", THROW_WHERE "Disposed!");
+ throw lang::DisposedException( THROW_WHERE );
+ }
+
+ if ( aStreamName.isEmpty() || !::comphelper::OStorageHelper::IsValidZipEntryFileName( aStreamName, false ) )
+ throw lang::IllegalArgumentException( THROW_WHERE "Unexpected entry name syntax.", uno::Reference< uno::XInterface >(), 1 );
+
+ if ( m_pImpl->m_nStorageType == embed::StorageFormats::OFOPXML && aStreamName == "_rels" )
+ throw lang::IllegalArgumentException( THROW_WHERE, uno::Reference< uno::XInterface >(), 1 ); // unacceptable storage name
+
+ try
+ {
+ uno::Reference< io::XStream > xResult;
+ m_pImpl->CloneStreamElement( aStreamName, false, ::comphelper::SequenceAsHashMap(), xResult );
+ if ( !xResult.is() )
+ throw uno::RuntimeException( THROW_WHERE );
+ return xResult;
+ }
+ catch( const embed::InvalidStorageException& )
+ {
+ TOOLS_INFO_EXCEPTION("package.xstor", "Rethrow");
+ throw;
+ }
+ catch( const lang::IllegalArgumentException& )
+ {
+ TOOLS_INFO_EXCEPTION("package.xstor", "Rethrow");
+ throw;
+ }
+ catch( const packages::WrongPasswordException& )
+ {
+ TOOLS_INFO_EXCEPTION("package.xstor", "Rethrow");
+ throw;
+ }
+ catch( const io::IOException& )
+ {
+ TOOLS_INFO_EXCEPTION("package.xstor", "Rethrow");
+ throw;
+ }
+ catch( const embed::StorageWrappedTargetException& )
+ {
+ TOOLS_INFO_EXCEPTION("package.xstor", "Rethrow");
+ throw;
+ }
+ catch( const uno::RuntimeException& )
+ {
+ TOOLS_INFO_EXCEPTION("package.xstor", "Rethrow");
+ throw;
+ }
+ catch( const uno::Exception& )
+ {
+ uno::Any aCaught( ::cppu::getCaughtException() );
+ SAL_INFO("package.xstor", "Rethrow: " << exceptionToString(aCaught));
+
+ throw embed::StorageWrappedTargetException( THROW_WHERE "Can't clone stream!",
+ uno::Reference< io::XInputStream >(),
+ aCaught );
+ }
+}
+
+uno::Reference< io::XStream > SAL_CALL OStorage::cloneEncryptedStreamElement(
+ const OUString& aStreamName,
+ const OUString& aPass )
+{
+ return cloneEncryptedStream( aStreamName, ::comphelper::OStorageHelper::CreatePackageEncryptionData( aPass ) );
+}
+
+void SAL_CALL OStorage::copyLastCommitTo(
+ const uno::Reference< embed::XStorage >& xTargetStorage )
+{
+ ::osl::MutexGuard aGuard( m_xSharedMutex->GetMutex() );
+
+ if ( !m_pImpl )
+ {
+ SAL_INFO("package.xstor", THROW_WHERE "Disposed!");
+ throw lang::DisposedException( THROW_WHERE );
+ }
+
+ try
+ {
+ m_pImpl->CopyLastCommitTo( xTargetStorage );
+ }
+ catch( const embed::InvalidStorageException& )
+ {
+ TOOLS_INFO_EXCEPTION("package.xstor", "Rethrow");
+ throw;
+ }
+ catch( const lang::IllegalArgumentException& )
+ {
+ TOOLS_INFO_EXCEPTION("package.xstor", "Rethrow");
+ throw;
+ }
+ catch( const embed::StorageWrappedTargetException& )
+ {
+ TOOLS_INFO_EXCEPTION("package.xstor", "Rethrow");
+ throw;
+ }
+ catch( const io::IOException& )
+ {
+ TOOLS_INFO_EXCEPTION("package.xstor", "Rethrow");
+ throw;
+ }
+ catch( const uno::RuntimeException& )
+ {
+ TOOLS_INFO_EXCEPTION("package.xstor", "Rethrow");
+ throw;
+ }
+ catch( const uno::Exception& )
+ {
+ uno::Any aCaught( ::cppu::getCaughtException() );
+ SAL_INFO("package.xstor", "Rethrow: " << exceptionToString(aCaught));
+
+ throw embed::StorageWrappedTargetException( THROW_WHERE "Can't copy last commit version!",
+ uno::Reference< io::XInputStream >(),
+ aCaught );
+ }
+
+}
+
+void SAL_CALL OStorage::copyStorageElementLastCommitTo(
+ const OUString& aStorName,
+ const uno::Reference< embed::XStorage >& xTargetStorage )
+{
+ ::osl::MutexGuard aGuard( m_xSharedMutex->GetMutex() );
+
+ if ( !m_pImpl )
+ {
+ SAL_INFO("package.xstor", THROW_WHERE "Disposed!");
+ throw lang::DisposedException( THROW_WHERE );
+ }
+
+ if ( aStorName.isEmpty() || !::comphelper::OStorageHelper::IsValidZipEntryFileName( aStorName, false ) )
+ throw lang::IllegalArgumentException( THROW_WHERE "Unexpected entry name syntax.", uno::Reference< uno::XInterface >(), 1 );
+
+ if ( m_pImpl->m_nStorageType == embed::StorageFormats::OFOPXML && aStorName == "_rels" )
+ throw lang::IllegalArgumentException( THROW_WHERE, uno::Reference< uno::XInterface >(), 1 ); // unacceptable storage name
+
+ try
+ {
+ SotElement_Impl *pElement = m_pImpl->FindElement( aStorName );
+ if ( !pElement )
+ {
+ // element does not exist, throw exception
+ throw io::IOException( THROW_WHERE ); // TODO: access_denied
+ }
+ else if ( !pElement->m_bIsStorage )
+ {
+ throw io::IOException( THROW_WHERE );
+ }
+
+ if (!pElement->m_xStorage)
+ m_pImpl->OpenSubStorage( pElement, embed::ElementModes::READ );
+
+ if (!pElement->m_xStorage)
+ throw io::IOException( THROW_WHERE ); // TODO: general_error
+
+ // the existence of m_pAntiImpl of the child is not interesting,
+ // the copy will be created internally
+
+ pElement->m_xStorage->CopyLastCommitTo(xTargetStorage);
+ }
+ catch( const embed::InvalidStorageException& )
+ {
+ TOOLS_INFO_EXCEPTION("package.xstor", "Rethrow");
+ throw;
+ }
+ catch( const lang::IllegalArgumentException& )
+ {
+ TOOLS_INFO_EXCEPTION("package.xstor", "Rethrow");
+ throw;
+ }
+ catch( const io::IOException& )
+ {
+ TOOLS_INFO_EXCEPTION("package.xstor", "Rethrow");
+ throw;
+ }
+ catch( const embed::StorageWrappedTargetException& )
+ {
+ TOOLS_INFO_EXCEPTION("package.xstor", "Rethrow");
+ throw;
+ }
+ catch( const uno::RuntimeException& )
+ {
+ TOOLS_INFO_EXCEPTION("package.xstor", "Rethrow");
+ throw;
+ }
+ catch( const uno::Exception& )
+ {
+ uno::Any aCaught( ::cppu::getCaughtException() );
+ SAL_INFO("package.xstor", "Rethrow: " << exceptionToString(aCaught));
+
+ throw embed::StorageWrappedTargetException( THROW_WHERE "Can't copy last commit element version!",
+ uno::Reference< io::XInputStream >(),
+ aCaught );
+ }
+}
+
+sal_Bool SAL_CALL OStorage::isStreamElement( const OUString& aElementName )
+{
+ ::osl::MutexGuard aGuard( m_xSharedMutex->GetMutex() );
+
+ if ( !m_pImpl )
+ {
+ SAL_INFO("package.xstor", THROW_WHERE "Disposed!");
+ throw lang::DisposedException( THROW_WHERE );
+ }
+
+ if ( aElementName.isEmpty() || !::comphelper::OStorageHelper::IsValidZipEntryFileName( aElementName, false ) )
+ throw lang::IllegalArgumentException( THROW_WHERE "Unexpected entry name syntax.", uno::Reference< uno::XInterface >(), 1 );
+
+ if ( m_pImpl->m_nStorageType == embed::StorageFormats::OFOPXML && aElementName == "_rels" )
+ throw lang::IllegalArgumentException( THROW_WHERE, uno::Reference< uno::XInterface >(), 1 ); // unacceptable name
+
+ SotElement_Impl* pElement = nullptr;
+
+ try
+ {
+ pElement = m_pImpl->FindElement( aElementName );
+ }
+ catch( const embed::InvalidStorageException& )
+ {
+ TOOLS_INFO_EXCEPTION("package.xstor", "Rethrow");
+ throw;
+ }
+ catch( const lang::IllegalArgumentException& )
+ {
+ TOOLS_INFO_EXCEPTION("package.xstor", "Rethrow");
+ throw;
+ }
+ catch( const container::NoSuchElementException& )
+ {
+ TOOLS_INFO_EXCEPTION("package.xstor", "Rethrow");
+ throw;
+ }
+ catch( const uno::RuntimeException& )
+ {
+ TOOLS_INFO_EXCEPTION("package.xstor", "Rethrow");
+ throw;
+ }
+ catch( const uno::Exception& )
+ {
+ uno::Any aCaught( ::cppu::getCaughtException() );
+ SAL_INFO("package.xstor", "Rethrow: " << exceptionToString(aCaught));
+
+ throw lang::WrappedTargetRuntimeException( THROW_WHERE "Can't detect whether it is a stream!",
+ uno::Reference< io::XInputStream >(),
+ aCaught );
+ }
+
+ if ( !pElement )
+ throw container::NoSuchElementException( THROW_WHERE ); //???
+
+ return !pElement->m_bIsStorage;
+}
+
+sal_Bool SAL_CALL OStorage::isStorageElement( const OUString& aElementName )
+{
+ ::osl::MutexGuard aGuard( m_xSharedMutex->GetMutex() );
+
+ if ( !m_pImpl )
+ {
+ SAL_INFO("package.xstor", THROW_WHERE "Disposed!");
+ throw lang::DisposedException( THROW_WHERE );
+ }
+
+ if ( aElementName.isEmpty() || !::comphelper::OStorageHelper::IsValidZipEntryFileName( aElementName, false ) )
+ throw lang::IllegalArgumentException( THROW_WHERE "Unexpected entry name syntax.", uno::Reference< uno::XInterface >(), 1 );
+
+ if ( m_pImpl->m_nStorageType == embed::StorageFormats::OFOPXML && aElementName == "_rels" )
+ throw lang::IllegalArgumentException( THROW_WHERE, uno::Reference< uno::XInterface >(), 1 );
+
+ SotElement_Impl* pElement = nullptr;
+
+ try
+ {
+ pElement = m_pImpl->FindElement( aElementName );
+ }
+ catch( const embed::InvalidStorageException& )
+ {
+ TOOLS_INFO_EXCEPTION("package.xstor", "Rethrow");
+ throw;
+ }
+ catch( const lang::IllegalArgumentException& )
+ {
+ TOOLS_INFO_EXCEPTION("package.xstor", "Rethrow");
+ throw;
+ }
+ catch( const container::NoSuchElementException& )
+ {
+ TOOLS_INFO_EXCEPTION("package.xstor", "Rethrow");
+ throw;
+ }
+ catch( const uno::RuntimeException& )
+ {
+ TOOLS_INFO_EXCEPTION("package.xstor", "Rethrow");
+ throw;
+ }
+ catch( const uno::Exception& )
+ {
+ uno::Any aCaught( ::cppu::getCaughtException() );
+ SAL_INFO("package.xstor", "Rethrow: " << exceptionToString(aCaught));
+
+ throw lang::WrappedTargetRuntimeException( THROW_WHERE "can't detect whether it is a storage",
+ uno::Reference< io::XInputStream >(),
+ aCaught );
+ }
+
+ if ( !pElement )
+ throw container::NoSuchElementException( THROW_WHERE ); //???
+
+ return pElement->m_bIsStorage;
+}
+
+void SAL_CALL OStorage::removeElement( const OUString& aElementName )
+{
+ {
+ osl::MutexGuard aGuard(m_xSharedMutex->GetMutex());
+
+ if (!m_pImpl)
+ {
+ SAL_INFO("package.xstor", THROW_WHERE "Disposed!");
+ throw lang::DisposedException(THROW_WHERE);
+ }
+
+ if (aElementName.isEmpty()
+ || !::comphelper::OStorageHelper::IsValidZipEntryFileName(aElementName, false))
+ throw lang::IllegalArgumentException(THROW_WHERE "Unexpected entry name syntax.",
+ uno::Reference<uno::XInterface>(), 1);
+
+ if (m_pImpl->m_nStorageType == embed::StorageFormats::OFOPXML && aElementName == "_rels")
+ throw lang::IllegalArgumentException(THROW_WHERE, uno::Reference<uno::XInterface>(),
+ 1); // TODO: unacceptable name
+
+ if (!(m_pImpl->m_nStorageMode & embed::ElementModes::WRITE))
+ throw io::IOException(THROW_WHERE); // TODO: access denied
+
+ try
+ {
+ auto pElement = m_pImpl->FindElement(aElementName);
+ if ( !pElement )
+ throw container::NoSuchElementException(THROW_WHERE); //???
+
+ m_pImpl->RemoveElement(aElementName, pElement);
+
+ m_pImpl->m_bIsModified = true;
+ m_pImpl->m_bBroadcastModified = true;
+ }
+ catch (const embed::InvalidStorageException&)
+ {
+ TOOLS_INFO_EXCEPTION("package.xstor", "Rethrow");
+ throw;
+ }
+ catch (const lang::IllegalArgumentException&)
+ {
+ TOOLS_INFO_EXCEPTION("package.xstor", "Rethrow");
+ throw;
+ }
+ catch (const container::NoSuchElementException&)
+ {
+ TOOLS_INFO_EXCEPTION("package.xstor", "Rethrow");
+ throw;
+ }
+ catch (const io::IOException&)
+ {
+ TOOLS_INFO_EXCEPTION("package.xstor", "Rethrow");
+ throw;
+ }
+ catch (const embed::StorageWrappedTargetException&)
+ {
+ TOOLS_INFO_EXCEPTION("package.xstor", "Rethrow");
+ throw;
+ }
+ catch (const uno::RuntimeException&)
+ {
+ TOOLS_INFO_EXCEPTION("package.xstor", "Rethrow");
+ throw;
+ }
+ catch (const uno::Exception&)
+ {
+ uno::Any aCaught(::cppu::getCaughtException());
+ SAL_INFO("package.xstor", "Rethrow: " << exceptionToString(aCaught));
+
+ throw embed::StorageWrappedTargetException(THROW_WHERE "Can't remove element!",
+ uno::Reference<io::XInputStream>(), aCaught);
+ }
+ }
+
+ BroadcastModifiedIfNecessary();
+}
+
+void SAL_CALL OStorage::renameElement( const OUString& aElementName, const OUString& aNewName )
+{
+ {
+ osl::MutexGuard aGuard(m_xSharedMutex->GetMutex());
+
+ if (!m_pImpl)
+ {
+ SAL_INFO("package.xstor", THROW_WHERE "Disposed!");
+ throw lang::DisposedException(THROW_WHERE);
+ }
+
+ if (aElementName.isEmpty()
+ || !::comphelper::OStorageHelper::IsValidZipEntryFileName(aElementName, false)
+ || aNewName.isEmpty()
+ || !::comphelper::OStorageHelper::IsValidZipEntryFileName(aNewName, false))
+ throw lang::IllegalArgumentException(THROW_WHERE "Unexpected entry name syntax.",
+ uno::Reference<uno::XInterface>(), 1);
+
+ if (m_pImpl->m_nStorageType == embed::StorageFormats::OFOPXML
+ && (aElementName == "_rels" || aNewName == "_rels"))
+ throw lang::IllegalArgumentException(THROW_WHERE, uno::Reference<uno::XInterface>(),
+ 0); // TODO: unacceptable element name
+
+ if (!(m_pImpl->m_nStorageMode & embed::ElementModes::WRITE))
+ throw io::IOException(THROW_WHERE); // TODO: access denied
+
+ try
+ {
+ SotElement_Impl* pRefElement = m_pImpl->FindElement(aNewName);
+ if (pRefElement)
+ throw container::ElementExistException(THROW_WHERE); //???
+
+ auto pElement = m_pImpl->FindElement( aElementName );
+ if ( !pElement )
+ throw container::NoSuchElementException(THROW_WHERE); //???
+
+ auto mapIt = m_pImpl->m_aChildrenMap.find(aElementName);
+ auto rVec = mapIt->second;
+ for (auto it = rVec.begin(); it != rVec.end(); ++it)
+ if (pElement == *it)
+ {
+ rVec.erase(std::remove(rVec.begin(), rVec.end(), pElement), rVec.end());
+ if (rVec.empty())
+ m_pImpl->m_aChildrenMap.erase(mapIt);
+ break;
+ }
+ m_pImpl->m_aChildrenMap[aNewName].push_back(pElement);
+ m_pImpl->m_bIsModified = true;
+ m_pImpl->m_bBroadcastModified = true;
+ }
+ catch (const embed::InvalidStorageException&)
+ {
+ TOOLS_INFO_EXCEPTION("package.xstor", "Rethrow");
+ throw;
+ }
+ catch (const lang::IllegalArgumentException&)
+ {
+ TOOLS_INFO_EXCEPTION("package.xstor", "Rethrow");
+ throw;
+ }
+ catch (const container::NoSuchElementException&)
+ {
+ TOOLS_INFO_EXCEPTION("package.xstor", "Rethrow");
+ throw;
+ }
+ catch (const container::ElementExistException&)
+ {
+ TOOLS_INFO_EXCEPTION("package.xstor", "Rethrow");
+ throw;
+ }
+ catch (const io::IOException&)
+ {
+ TOOLS_INFO_EXCEPTION("package.xstor", "Rethrow");
+ throw;
+ }
+ catch (const embed::StorageWrappedTargetException&)
+ {
+ TOOLS_INFO_EXCEPTION("package.xstor", "Rethrow");
+ throw;
+ }
+ catch (const uno::RuntimeException&)
+ {
+ TOOLS_INFO_EXCEPTION("package.xstor", "Rethrow");
+ throw;
+ }
+ catch (const uno::Exception&)
+ {
+ uno::Any aCaught(::cppu::getCaughtException());
+ SAL_INFO("package.xstor", "Rethrow: " << exceptionToString(aCaught));
+
+ throw embed::StorageWrappedTargetException(THROW_WHERE "Can't rename element!",
+ uno::Reference<io::XInputStream>(), aCaught);
+ }
+ }
+
+ BroadcastModifiedIfNecessary();
+}
+
+void SAL_CALL OStorage::copyElementTo( const OUString& aElementName,
+ const uno::Reference< embed::XStorage >& xDest,
+ const OUString& aNewName )
+{
+ ::osl::MutexGuard aGuard( m_xSharedMutex->GetMutex() );
+
+ if ( !m_pImpl )
+ {
+ SAL_INFO("package.xstor", THROW_WHERE "Disposed!");
+ throw lang::DisposedException( THROW_WHERE );
+ }
+
+ if ( aElementName.isEmpty() || !::comphelper::OStorageHelper::IsValidZipEntryFileName( aElementName, false )
+ || aNewName.isEmpty() || !::comphelper::OStorageHelper::IsValidZipEntryFileName( aNewName, false ) )
+ throw lang::IllegalArgumentException( THROW_WHERE "Unexpected entry name syntax.", uno::Reference< uno::XInterface >(), 1 );
+
+ if ( !xDest.is() )
+ // || xDest == uno::Reference< uno::XInterface >( static_cast< OWeakObject* >( this ), uno::UNO_QUERY ) )
+ throw lang::IllegalArgumentException( THROW_WHERE, uno::Reference< uno::XInterface >(), 2 );
+
+ if ( m_pImpl->m_nStorageType == embed::StorageFormats::OFOPXML && ( aElementName == "_rels" || aNewName == "_rels" ) )
+ throw lang::IllegalArgumentException( THROW_WHERE, uno::Reference< uno::XInterface >(), 0 ); // unacceptable element name
+
+ try
+ {
+ SotElement_Impl* pElement = m_pImpl->FindElement( aElementName );
+ if ( !pElement )
+ throw container::NoSuchElementException( THROW_WHERE );
+
+ uno::Reference< XNameAccess > xNameAccess( xDest, uno::UNO_QUERY_THROW );
+ if ( xNameAccess->hasByName( aNewName ) )
+ throw container::ElementExistException( THROW_WHERE );
+
+ m_pImpl->CopyStorageElement( pElement, xDest, aNewName, false );
+ }
+ catch( const embed::InvalidStorageException& )
+ {
+ TOOLS_INFO_EXCEPTION("package.xstor", "Rethrow");
+ throw;
+ }
+ catch( const lang::IllegalArgumentException& )
+ {
+ TOOLS_INFO_EXCEPTION("package.xstor", "Rethrow");
+ throw;
+ }
+ catch( const container::NoSuchElementException& )
+ {
+ TOOLS_INFO_EXCEPTION("package.xstor", "Rethrow");
+ throw;
+ }
+ catch( const container::ElementExistException& )
+ {
+ TOOLS_INFO_EXCEPTION("package.xstor", "Rethrow");
+ throw;
+ }
+ catch( const embed::StorageWrappedTargetException& )
+ {
+ TOOLS_INFO_EXCEPTION("package.xstor", "Rethrow");
+ throw;
+ }
+ catch( const io::IOException& )
+ {
+ TOOLS_INFO_EXCEPTION("package.xstor", "Rethrow");
+ throw;
+ }
+ catch( const uno::RuntimeException& )
+ {
+ TOOLS_INFO_EXCEPTION("package.xstor", "Rethrow");
+ throw;
+ }
+ catch( const uno::Exception& )
+ {
+ uno::Any aCaught( ::cppu::getCaughtException() );
+ SAL_INFO("package.xstor", "Rethrow: " << exceptionToString(aCaught));
+
+ throw embed::StorageWrappedTargetException( THROW_WHERE "Can't copy element!",
+ uno::Reference< io::XInputStream >(),
+ aCaught );
+ }
+}
+
+void SAL_CALL OStorage::moveElementTo( const OUString& aElementName,
+ const uno::Reference< embed::XStorage >& xDest,
+ const OUString& aNewName )
+{
+ {
+ osl::MutexGuard aGuard(m_xSharedMutex->GetMutex());
+
+ if (!m_pImpl)
+ {
+ SAL_INFO("package.xstor", THROW_WHERE "Disposed!");
+ throw lang::DisposedException(THROW_WHERE);
+ }
+
+ if (aElementName.isEmpty()
+ || !::comphelper::OStorageHelper::IsValidZipEntryFileName(aElementName, false)
+ || aNewName.isEmpty()
+ || !::comphelper::OStorageHelper::IsValidZipEntryFileName(aNewName, false))
+ throw lang::IllegalArgumentException(THROW_WHERE "Unexpected entry name syntax.",
+ uno::Reference<uno::XInterface>(), 1);
+
+ if (!xDest.is()
+ || xDest
+ == uno::Reference<uno::XInterface>(static_cast<OWeakObject*>(this),
+ uno::UNO_QUERY))
+ throw lang::IllegalArgumentException(THROW_WHERE, uno::Reference<uno::XInterface>(), 2);
+
+ if (m_pImpl->m_nStorageType == embed::StorageFormats::OFOPXML
+ && (aElementName == "_rels" || aNewName == "_rels"))
+ throw lang::IllegalArgumentException(THROW_WHERE, uno::Reference<uno::XInterface>(),
+ 0); // unacceptable element name
+
+ if (!(m_pImpl->m_nStorageMode & embed::ElementModes::WRITE))
+ throw io::IOException(THROW_WHERE); // TODO: access denied
+
+ try
+ {
+ auto pElement = m_pImpl->FindElement( aElementName );
+ if ( !pElement )
+ throw container::NoSuchElementException(THROW_WHERE); //???
+
+ uno::Reference<XNameAccess> xNameAccess(xDest, uno::UNO_QUERY_THROW);
+ if (xNameAccess->hasByName(aNewName))
+ throw container::ElementExistException(THROW_WHERE);
+
+ m_pImpl->CopyStorageElement(pElement, xDest, aNewName, false);
+
+ m_pImpl->RemoveElement(aElementName, pElement);
+
+ m_pImpl->m_bIsModified = true;
+ m_pImpl->m_bBroadcastModified = true;
+ }
+ catch (const embed::InvalidStorageException&)
+ {
+ TOOLS_INFO_EXCEPTION("package.xstor", "Rethrow");
+ throw;
+ }
+ catch (const lang::IllegalArgumentException&)
+ {
+ TOOLS_INFO_EXCEPTION("package.xstor", "Rethrow");
+ throw;
+ }
+ catch (const container::NoSuchElementException&)
+ {
+ TOOLS_INFO_EXCEPTION("package.xstor", "Rethrow");
+ throw;
+ }
+ catch (const container::ElementExistException&)
+ {
+ TOOLS_INFO_EXCEPTION("package.xstor", "Rethrow");
+ throw;
+ }
+ catch (const embed::StorageWrappedTargetException&)
+ {
+ TOOLS_INFO_EXCEPTION("package.xstor", "Rethrow");
+ throw;
+ }
+ catch (const io::IOException&)
+ {
+ TOOLS_INFO_EXCEPTION("package.xstor", "Rethrow");
+ throw;
+ }
+ catch (const uno::RuntimeException&)
+ {
+ TOOLS_INFO_EXCEPTION("package.xstor", "Rethrow");
+ throw;
+ }
+ catch (const uno::Exception&)
+ {
+ uno::Any aCaught(::cppu::getCaughtException());
+ SAL_INFO("package.xstor", "Rethrow: " << exceptionToString(aCaught));
+
+ throw embed::StorageWrappedTargetException(THROW_WHERE "Can't move element!",
+ uno::Reference<io::XInputStream>(), aCaught);
+ }
+ }
+
+ BroadcastModifiedIfNecessary();
+}
+
+// XStorage2
+uno::Reference< io::XStream > SAL_CALL OStorage::openEncryptedStream(
+ const OUString& aStreamName, sal_Int32 nOpenMode, const uno::Sequence< beans::NamedValue >& aEncryptionData )
+{
+ osl::ClearableMutexGuard aGuard( m_xSharedMutex->GetMutex() );
+
+ if ( !m_pImpl )
+ {
+ SAL_INFO("package.xstor", THROW_WHERE "Disposed!");
+ throw lang::DisposedException( THROW_WHERE );
+ }
+
+ if ( ( nOpenMode & embed::ElementModes::WRITE ) && m_bReadOnlyWrap )
+ throw io::IOException( THROW_WHERE ); // TODO: access denied
+
+ if ( !aEncryptionData.hasElements() )
+ throw lang::IllegalArgumentException( THROW_WHERE, uno::Reference< uno::XInterface >(), 3 );
+
+ uno::Reference< io::XStream > xResult;
+ try
+ {
+ SotElement_Impl *pElement = OpenStreamElement_Impl( aStreamName, nOpenMode, true );
+ OSL_ENSURE(pElement && pElement->m_xStream, "In case element can not be created an exception must be thrown!");
+
+ xResult = pElement->m_xStream->GetStream(nOpenMode, aEncryptionData, false);
+ SAL_WARN_IF( !xResult.is(), "package.xstor", "The method must throw exception instead of removing empty result!" );
+
+ if ( m_bReadOnlyWrap )
+ {
+ // before the storage disposes the stream it must deregister itself as listener
+ uno::Reference< lang::XComponent > xStreamComponent( xResult, uno::UNO_QUERY_THROW );
+ MakeLinkToSubComponent_Impl( xStreamComponent );
+ }
+ }
+ catch( const embed::InvalidStorageException& )
+ {
+ TOOLS_INFO_EXCEPTION("package.xstor", "Rethrow");
+ throw;
+ }
+ catch( const lang::IllegalArgumentException& )
+ {
+ TOOLS_INFO_EXCEPTION("package.xstor", "Rethrow");
+ throw;
+ }
+ catch( const packages::NoEncryptionException& )
+ {
+ TOOLS_INFO_EXCEPTION("package.xstor", "Rethrow");
+ throw;
+ }
+ catch( const packages::WrongPasswordException& )
+ {
+ TOOLS_INFO_EXCEPTION("package.xstor", "Rethrow");
+ throw;
+ }
+ catch( const embed::StorageWrappedTargetException& )
+ {
+ TOOLS_INFO_EXCEPTION("package.xstor", "Rethrow");
+ throw;
+ }
+ catch( const io::IOException& )
+ {
+ TOOLS_INFO_EXCEPTION("package.xstor", "Rethrow");
+ throw;
+ }
+ catch( const uno::RuntimeException& )
+ {
+ TOOLS_INFO_EXCEPTION("package.xstor", "Rethrow");
+ throw;
+ }
+ catch( const uno::Exception& )
+ {
+ uno::Any aCaught( ::cppu::getCaughtException() );
+ SAL_INFO("package.xstor", "Rethrow: " << exceptionToString(aCaught));
+
+ throw embed::StorageWrappedTargetException( THROW_WHERE "Can't open encrypted stream!",
+ uno::Reference< io::XInputStream >(),
+ aCaught );
+ }
+
+ aGuard.clear();
+
+ BroadcastModifiedIfNecessary();
+
+ return xResult;
+}
+
+uno::Reference< io::XStream > SAL_CALL OStorage::cloneEncryptedStream(
+ const OUString& aStreamName,
+ const uno::Sequence< beans::NamedValue >& aEncryptionData )
+{
+ ::osl::MutexGuard aGuard( m_xSharedMutex->GetMutex() );
+
+ if ( !m_pImpl )
+ {
+ SAL_INFO("package.xstor", THROW_WHERE "Disposed!");
+ throw lang::DisposedException( THROW_WHERE );
+ }
+
+ if ( !aEncryptionData.hasElements() )
+ throw lang::IllegalArgumentException( THROW_WHERE, uno::Reference< uno::XInterface >(), 2 );
+
+ try
+ {
+ uno::Reference< io::XStream > xResult;
+ m_pImpl->CloneStreamElement( aStreamName, true, aEncryptionData, xResult );
+ if ( !xResult.is() )
+ throw uno::RuntimeException( THROW_WHERE );
+ return xResult;
+ }
+ catch( const embed::InvalidStorageException& )
+ {
+ TOOLS_INFO_EXCEPTION("package.xstor", "Rethrow");
+ throw;
+ }
+ catch( const lang::IllegalArgumentException& )
+ {
+ TOOLS_INFO_EXCEPTION("package.xstor", "Rethrow");
+ throw;
+ }
+ catch( const packages::NoEncryptionException& )
+ {
+ TOOLS_INFO_EXCEPTION("package.xstor", "Rethrow");
+ throw;
+ }
+ catch( const packages::WrongPasswordException& )
+ {
+ TOOLS_INFO_EXCEPTION("package.xstor", "Rethrow");
+ throw;
+ }
+ catch( const io::IOException& )
+ {
+ TOOLS_INFO_EXCEPTION("package.xstor", "Rethrow");
+ throw;
+ }
+ catch( const embed::StorageWrappedTargetException& )
+ {
+ TOOLS_INFO_EXCEPTION("package.xstor", "Rethrow");
+ throw;
+ }
+ catch( const uno::RuntimeException& )
+ {
+ TOOLS_INFO_EXCEPTION("package.xstor", "Rethrow");
+ throw;
+ }
+ catch( const uno::Exception& )
+ {
+ uno::Any aCaught( ::cppu::getCaughtException() );
+ SAL_INFO("package.xstor", "Rethrow: " << exceptionToString(aCaught));
+
+ throw embed::StorageWrappedTargetException( THROW_WHERE "Can't clone encrypted stream!",
+ uno::Reference< io::XInputStream >(),
+ aCaught );
+ }
+}
+
+// XStorageRawAccess
+uno::Reference< io::XInputStream > SAL_CALL OStorage::getPlainRawStreamElement(
+ const OUString& sStreamName )
+{
+ ::osl::MutexGuard aGuard( m_xSharedMutex->GetMutex() );
+
+ if ( !m_pImpl )
+ {
+ SAL_INFO("package.xstor", THROW_WHERE "Disposed!");
+ throw lang::DisposedException( THROW_WHERE );
+ }
+
+ if ( m_pImpl->m_nStorageType == embed::StorageFormats::OFOPXML )
+ throw uno::RuntimeException( THROW_WHERE ); // the interface is not supported and must not be accessible
+
+ if ( sStreamName.isEmpty() || !::comphelper::OStorageHelper::IsValidZipEntryFileName( sStreamName, false ) )
+ throw lang::IllegalArgumentException( THROW_WHERE "Unexpected entry name syntax.", uno::Reference< uno::XInterface >(), 1 );
+
+ uno::Reference < io::XInputStream > xTempIn;
+ try
+ {
+ SotElement_Impl* pElement = m_pImpl->FindElement( sStreamName );
+ if ( !pElement )
+ throw container::NoSuchElementException( THROW_WHERE );
+
+ if (!pElement->m_xStream)
+ {
+ m_pImpl->OpenSubStream( pElement );
+ if (!pElement->m_xStream)
+ throw io::IOException( THROW_WHERE );
+ }
+
+ uno::Reference<io::XInputStream> xRawInStream = pElement->m_xStream->GetPlainRawInStream();
+ if ( !xRawInStream.is() )
+ throw io::IOException( THROW_WHERE );
+
+ uno::Reference < io::XTempFile > xTempFile = io::TempFile::create( m_pImpl->m_xContext );
+ uno::Reference < io::XOutputStream > xTempOut = xTempFile->getOutputStream();
+ xTempIn = xTempFile->getInputStream();
+ uno::Reference < io::XSeekable > xSeek( xTempOut, uno::UNO_QUERY );
+
+ if ( !xTempOut.is() || !xTempIn.is() || !xSeek.is() )
+ throw io::IOException( THROW_WHERE );
+
+ // Copy temporary file to a new one
+ ::comphelper::OStorageHelper::CopyInputToOutput( xRawInStream, xTempOut );
+ xTempOut->closeOutput();
+ xSeek->seek( 0 );
+ }
+ catch( const embed::InvalidStorageException& )
+ {
+ TOOLS_INFO_EXCEPTION("package.xstor", "Rethrow");
+ throw;
+ }
+ catch( const lang::IllegalArgumentException& )
+ {
+ TOOLS_INFO_EXCEPTION("package.xstor", "Rethrow");
+ throw;
+ }
+ catch( const container::NoSuchElementException& )
+ {
+ TOOLS_INFO_EXCEPTION("package.xstor", "Rethrow");
+ throw;
+ }
+ catch( const embed::StorageWrappedTargetException& )
+ {
+ TOOLS_INFO_EXCEPTION("package.xstor", "Rethrow");
+ throw;
+ }
+ catch( const io::IOException& )
+ {
+ TOOLS_INFO_EXCEPTION("package.xstor", "Rethrow");
+ throw;
+ }
+ catch( const uno::RuntimeException& )
+ {
+ TOOLS_INFO_EXCEPTION("package.xstor", "Rethrow");
+ throw;
+ }
+ catch( const uno::Exception& )
+ {
+ uno::Any aCaught( ::cppu::getCaughtException() );
+ SAL_INFO("package.xstor", "Rethrow: " << exceptionToString(aCaught));
+
+ throw embed::StorageWrappedTargetException( THROW_WHERE "Can't get plain raw stream!",
+ uno::Reference< io::XInputStream >(),
+ aCaught );
+ }
+
+ return xTempIn;
+}
+
+uno::Reference< io::XInputStream > SAL_CALL OStorage::getRawEncrStreamElement(
+ const OUString& sStreamName )
+{
+ ::osl::MutexGuard aGuard( m_xSharedMutex->GetMutex() );
+
+ if ( !m_pImpl )
+ {
+ SAL_INFO("package.xstor", THROW_WHERE "Disposed!");
+ throw lang::DisposedException( THROW_WHERE );
+ }
+
+ if ( m_pImpl->m_nStorageType != embed::StorageFormats::PACKAGE )
+ throw packages::NoEncryptionException( THROW_WHERE );
+
+ if ( sStreamName.isEmpty() || !::comphelper::OStorageHelper::IsValidZipEntryFileName( sStreamName, false ) )
+ throw lang::IllegalArgumentException( THROW_WHERE "Unexpected entry name syntax.", uno::Reference< uno::XInterface >(), 1 );
+
+ uno::Reference < io::XInputStream > xTempIn;
+ try
+ {
+ SotElement_Impl* pElement = m_pImpl->FindElement( sStreamName );
+ if ( !pElement )
+ throw container::NoSuchElementException( THROW_WHERE );
+
+ if (!pElement->m_xStream)
+ {
+ m_pImpl->OpenSubStream( pElement );
+ if (!pElement->m_xStream)
+ throw io::IOException( THROW_WHERE );
+ }
+
+ if (!pElement->m_xStream->IsEncrypted())
+ throw packages::NoEncryptionException( THROW_WHERE );
+
+ uno::Reference< io::XInputStream > xRawInStream = pElement->m_xStream->GetRawInStream();
+ if ( !xRawInStream.is() )
+ throw io::IOException( THROW_WHERE );
+
+ uno::Reference < io::XTempFile > xTempFile = io::TempFile::create(m_pImpl->m_xContext);
+ uno::Reference < io::XOutputStream > xTempOut = xTempFile->getOutputStream();
+ xTempIn = xTempFile->getInputStream();
+ uno::Reference < io::XSeekable > xSeek( xTempOut, uno::UNO_QUERY );
+
+ if ( !xTempOut.is() || !xTempIn.is() || !xSeek.is() )
+ throw io::IOException( THROW_WHERE );
+
+ // Copy temporary file to a new one
+ ::comphelper::OStorageHelper::CopyInputToOutput( xRawInStream, xTempOut );
+ xTempOut->closeOutput();
+ xSeek->seek( 0 );
+
+ }
+ catch( const embed::InvalidStorageException& )
+ {
+ TOOLS_INFO_EXCEPTION("package.xstor", "Rethrow");
+ throw;
+ }
+ catch( const lang::IllegalArgumentException& )
+ {
+ TOOLS_INFO_EXCEPTION("package.xstor", "Rethrow");
+ throw;
+ }
+ catch( const packages::NoEncryptionException& )
+ {
+ TOOLS_INFO_EXCEPTION("package.xstor", "Rethrow");
+ throw;
+ }
+ catch( const container::NoSuchElementException& )
+ {
+ TOOLS_INFO_EXCEPTION("package.xstor", "Rethrow");
+ throw;
+ }
+ catch( const embed::StorageWrappedTargetException& )
+ {
+ TOOLS_INFO_EXCEPTION("package.xstor", "Rethrow");
+ throw;
+ }
+ catch( const io::IOException& )
+ {
+ TOOLS_INFO_EXCEPTION("package.xstor", "Rethrow");
+ throw;
+ }
+ catch( const uno::RuntimeException& )
+ {
+ TOOLS_INFO_EXCEPTION("package.xstor", "Rethrow");
+ throw;
+ }
+ catch( const uno::Exception& )
+ {
+ uno::Any aCaught( ::cppu::getCaughtException() );
+ SAL_INFO("package.xstor", "Rethrow: " << exceptionToString(aCaught));
+
+ throw embed::StorageWrappedTargetException( THROW_WHERE "Can't get raw stream!",
+ uno::Reference< io::XInputStream >(),
+ aCaught );
+ }
+
+ return xTempIn;
+}
+
+void SAL_CALL OStorage::insertRawEncrStreamElement( const OUString& aStreamName,
+ const uno::Reference< io::XInputStream >& xInStream )
+{
+ ::osl::MutexGuard aGuard( m_xSharedMutex->GetMutex() );
+
+ if ( !m_pImpl )
+ {
+ SAL_INFO("package.xstor", THROW_WHERE "Disposed!");
+ throw lang::DisposedException( THROW_WHERE );
+ }
+
+ if ( m_pImpl->m_nStorageType != embed::StorageFormats::PACKAGE )
+ throw embed::InvalidStorageException( THROW_WHERE );
+
+ if ( aStreamName.isEmpty() || !::comphelper::OStorageHelper::IsValidZipEntryFileName( aStreamName, false ) )
+ throw lang::IllegalArgumentException( THROW_WHERE "Unexpected entry name syntax.", uno::Reference< uno::XInterface >(), 1 );
+
+ if ( !xInStream.is() )
+ throw lang::IllegalArgumentException( THROW_WHERE, uno::Reference< uno::XInterface >(), 2 );
+
+ if ( !( m_pImpl->m_nStorageMode & embed::ElementModes::WRITE ) )
+ throw io::IOException( THROW_WHERE ); // TODO: access denied
+
+ try
+ {
+ SotElement_Impl* pElement = m_pImpl->FindElement( aStreamName );
+ if ( pElement )
+ throw container::ElementExistException( THROW_WHERE );
+
+ m_pImpl->InsertRawStream( aStreamName, xInStream );
+ }
+ catch( const embed::InvalidStorageException& )
+ {
+ TOOLS_INFO_EXCEPTION("package.xstor", "Rethrow:");
+ throw;
+ }
+ catch( const lang::IllegalArgumentException& )
+ {
+ TOOLS_INFO_EXCEPTION("package.xstor", "Rethrow:");
+ throw;
+ }
+ catch( const packages::NoRawFormatException& )
+ {
+ TOOLS_INFO_EXCEPTION("package.xstor", "Rethrow:");
+ throw;
+ }
+ catch( const container::ElementExistException& )
+ {
+ TOOLS_INFO_EXCEPTION("package.xstor", "Rethrow:");
+ throw;
+ }
+ catch( const embed::StorageWrappedTargetException& )
+ {
+ TOOLS_INFO_EXCEPTION("package.xstor", "Rethrow:");
+ throw;
+ }
+ catch( const io::IOException& )
+ {
+ TOOLS_INFO_EXCEPTION("package.xstor", "Rethrow:");
+ throw;
+ }
+ catch( const uno::RuntimeException& )
+ {
+ TOOLS_INFO_EXCEPTION("package.xstor", "Rethrow:");
+ throw;
+ }
+ catch( const uno::Exception& )
+ {
+ uno::Any aCaught( ::cppu::getCaughtException() );
+ SAL_INFO("package.xstor", "Rethrow: " << exceptionToString(aCaught));
+
+ throw embed::StorageWrappedTargetException( THROW_WHERE "Can't insert raw stream!",
+ uno::Reference< io::XInputStream >(),
+ aCaught );
+ }
+}
+
+// XTransactedObject
+void SAL_CALL OStorage::commit()
+{
+ uno::Reference< util::XModifiable > xParentModif;
+
+ try {
+ BroadcastTransaction( STOR_MESS_PRECOMMIT );
+
+ ::osl::MutexGuard aGuard( m_xSharedMutex->GetMutex() );
+
+ if ( !m_pImpl )
+ {
+ SAL_INFO("package.xstor", THROW_WHERE "Disposed!");
+ throw lang::DisposedException( THROW_WHERE );
+ }
+
+ if ( m_bReadOnlyWrap )
+ throw io::IOException( THROW_WHERE ); // TODO: access_denied
+
+ m_pImpl->Commit(); // the root storage initiates the storing to source
+
+ // when the storage is committed the parent is modified
+ if ( m_pImpl->m_pParent && m_pImpl->m_pParent->m_pAntiImpl )
+ xParentModif = static_cast<util::XModifiable*>(m_pImpl->m_pParent->m_pAntiImpl);
+ }
+ catch( const io::IOException& )
+ {
+ TOOLS_INFO_EXCEPTION("package.xstor", "Rethrow:");
+ throw;
+ }
+ catch( const embed::StorageWrappedTargetException& )
+ {
+ TOOLS_INFO_EXCEPTION("package.xstor", "Rethrow:");
+ throw;
+ }
+ catch( const uno::RuntimeException& )
+ {
+ TOOLS_INFO_EXCEPTION("package.xstor", "Rethrow:");
+ throw;
+ }
+ catch( const uno::Exception& )
+ {
+ uno::Any aCaught( ::cppu::getCaughtException() );
+ SAL_INFO("package.xstor", "Rethrow: " << exceptionToString(aCaught));
+
+ throw embed::StorageWrappedTargetException( THROW_WHERE "Problems on commit!",
+ static_cast< ::cppu::OWeakObject* >( this ),
+ aCaught );
+ }
+
+ setModified( false );
+ if ( xParentModif.is() )
+ xParentModif->setModified( true );
+
+ BroadcastTransaction( STOR_MESS_COMMITTED );
+}
+
+void SAL_CALL OStorage::revert()
+{
+ // the method removes all the changes done after last commit
+
+ BroadcastTransaction( STOR_MESS_PREREVERT );
+
+ {
+ osl::MutexGuard aGuard(m_xSharedMutex->GetMutex());
+
+ if (!m_pImpl)
+ {
+ SAL_INFO("package.xstor", THROW_WHERE "Disposed!");
+ throw lang::DisposedException(THROW_WHERE);
+ }
+
+ for (const auto & rPair : m_pImpl->m_aChildrenMap)
+ for (auto pElement : rPair.second)
+ {
+ bool bThrow = (pElement->m_xStorage
+ && (pElement->m_xStorage->m_pAntiImpl
+ || !pElement->m_xStorage->m_aReadOnlyWrapVector.empty()))
+ || (pElement->m_xStream
+ && (pElement->m_xStream->m_pAntiImpl
+ || !pElement->m_xStream->m_aInputStreamsVector.empty()));
+ if (bThrow)
+ throw io::IOException(THROW_WHERE); // TODO: access denied
+ }
+
+ if (m_bReadOnlyWrap || !m_pImpl->m_bListCreated)
+ return; // nothing to do
+
+ try
+ {
+ m_pImpl->Revert();
+ m_pImpl->m_bIsModified = false;
+ m_pImpl->m_bBroadcastModified = true;
+ }
+ catch (const io::IOException&)
+ {
+ TOOLS_INFO_EXCEPTION("package.xstor", "Rethrow:");
+ throw;
+ }
+ catch (const embed::StorageWrappedTargetException&)
+ {
+ TOOLS_INFO_EXCEPTION("package.xstor", "Rethrow:");
+ throw;
+ }
+ catch (const uno::RuntimeException&)
+ {
+ TOOLS_INFO_EXCEPTION("package.xstor", "Rethrow:");
+ throw;
+ }
+ catch (const uno::Exception&)
+ {
+ uno::Any aCaught(::cppu::getCaughtException());
+ SAL_INFO("package.xstor", "Rethrow: " << exceptionToString(aCaught));
+
+ throw embed::StorageWrappedTargetException(THROW_WHERE "Problems on revert!",
+ static_cast<::cppu::OWeakObject*>(this),
+ aCaught);
+ }
+ }
+
+ setModified( false );
+ BroadcastTransaction( STOR_MESS_REVERTED );
+}
+
+// XTransactionBroadcaster
+void SAL_CALL OStorage::addTransactionListener( const uno::Reference< embed::XTransactionListener >& aListener )
+{
+ ::osl::MutexGuard aGuard( m_xSharedMutex->GetMutex() );
+
+ if ( !m_pImpl )
+ {
+ SAL_INFO("package.xstor", THROW_WHERE "Disposed!");
+ throw lang::DisposedException( THROW_WHERE );
+ }
+
+ m_aListenersContainer.addInterface( cppu::UnoType<embed::XTransactionListener>::get(),
+ aListener );
+}
+
+void SAL_CALL OStorage::removeTransactionListener( const uno::Reference< embed::XTransactionListener >& aListener )
+{
+ ::osl::MutexGuard aGuard( m_xSharedMutex->GetMutex() );
+
+ if ( !m_pImpl )
+ {
+ SAL_INFO("package.xstor", THROW_WHERE "Disposed!");
+ throw lang::DisposedException( THROW_WHERE );
+ }
+
+ m_aListenersContainer.removeInterface( cppu::UnoType<embed::XTransactionListener>::get(),
+ aListener );
+}
+
+// XModifiable
+// TODO: if there will be no demand on this interface it will be removed from implementation,
+// I do not want to remove it now since it is still possible that it will be inserted
+// to the service back.
+
+sal_Bool SAL_CALL OStorage::isModified()
+{
+ ::osl::MutexGuard aGuard( m_xSharedMutex->GetMutex() );
+
+ if ( !m_pImpl )
+ {
+ SAL_INFO("package.xstor", THROW_WHERE "Disposed!");
+ throw lang::DisposedException( THROW_WHERE );
+ }
+
+ return m_pImpl->m_bIsModified;
+}
+
+void SAL_CALL OStorage::setModified( sal_Bool bModified )
+{
+ {
+ osl::MutexGuard aGuard(m_xSharedMutex->GetMutex());
+
+ if (!m_pImpl)
+ {
+ SAL_INFO("package.xstor", THROW_WHERE "Disposed!");
+ throw lang::DisposedException(THROW_WHERE);
+ }
+
+ if (m_bReadOnlyWrap)
+ throw beans::PropertyVetoException(THROW_WHERE); // TODO: access denied
+
+ if (m_pImpl->m_bIsModified != bool(bModified))
+ m_pImpl->m_bIsModified = bModified;
+ }
+
+ if ( bModified )
+ {
+ m_pImpl->m_bBroadcastModified = true;
+ BroadcastModifiedIfNecessary();
+ }
+}
+
+void SAL_CALL OStorage::addModifyListener(
+ const uno::Reference< util::XModifyListener >& aListener )
+{
+ ::osl::MutexGuard aGuard( m_xSharedMutex->GetMutex() );
+
+ if ( !m_pImpl )
+ {
+ SAL_INFO("package.xstor", THROW_WHERE "Disposed!");
+ throw lang::DisposedException( THROW_WHERE );
+ }
+
+ osl_atomic_increment( &m_pImpl->m_nModifiedListenerCount );
+ m_aListenersContainer.addInterface(
+ cppu::UnoType<util::XModifyListener>::get(), aListener );
+}
+
+void SAL_CALL OStorage::removeModifyListener(
+ const uno::Reference< util::XModifyListener >& aListener )
+{
+ ::osl::MutexGuard aGuard( m_xSharedMutex->GetMutex() );
+
+ if ( !m_pImpl )
+ {
+ SAL_INFO("package.xstor", THROW_WHERE "Disposed!");
+ throw lang::DisposedException( THROW_WHERE );
+ }
+
+ osl_atomic_decrement( &m_pImpl->m_nModifiedListenerCount );
+ m_aListenersContainer.removeInterface(
+ cppu::UnoType<util::XModifyListener>::get(), aListener );
+}
+
+// XNameAccess
+
+uno::Any SAL_CALL OStorage::getByName( const OUString& aName )
+{
+ ::osl::MutexGuard aGuard( m_xSharedMutex->GetMutex() );
+
+ if ( !m_pImpl )
+ {
+ SAL_INFO("package.xstor", THROW_WHERE "Disposed!");
+ throw lang::DisposedException( THROW_WHERE );
+ }
+
+ if ( aName.isEmpty() || !::comphelper::OStorageHelper::IsValidZipEntryFileName( aName, false ) )
+ throw lang::IllegalArgumentException( THROW_WHERE "Unexpected entry name syntax.", uno::Reference< uno::XInterface >(), 1 );
+
+ if ( m_pImpl->m_nStorageType == embed::StorageFormats::OFOPXML && aName == "_rels" )
+ throw lang::IllegalArgumentException( THROW_WHERE, uno::Reference< uno::XInterface >(), 1 ); // unacceptable element name
+
+ uno::Any aResult;
+ try
+ {
+ SotElement_Impl* pElement = m_pImpl->FindElement( aName );
+ if ( !pElement )
+ throw container::NoSuchElementException( THROW_WHERE );
+
+ if ( pElement->m_bIsStorage )
+ aResult <<= openStorageElement( aName, embed::ElementModes::READ );
+ else
+ aResult <<= openStreamElement( aName, embed::ElementModes::READ );
+ }
+ catch( const container::NoSuchElementException& )
+ {
+ TOOLS_INFO_EXCEPTION("package.xstor", "Rethrow:");
+ throw;
+ }
+ catch( const lang::WrappedTargetException& )
+ {
+ TOOLS_INFO_EXCEPTION("package.xstor", "Rethrow:");
+ throw;
+ }
+ catch( const uno::RuntimeException& )
+ {
+ TOOLS_INFO_EXCEPTION("package.xstor", "Rethrow:");
+ throw;
+ }
+ catch( const uno::Exception& )
+ {
+ uno::Any aCaught( ::cppu::getCaughtException() );
+ SAL_INFO("package.xstor", "Rethrow: " << exceptionToString(aCaught));
+
+ throw lang::WrappedTargetException( THROW_WHERE "Can not open storage!",
+ static_cast< OWeakObject* >( this ),
+ aCaught );
+ }
+
+ return aResult;
+}
+
+uno::Sequence< OUString > SAL_CALL OStorage::getElementNames()
+{
+ ::osl::MutexGuard aGuard( m_xSharedMutex->GetMutex() );
+
+ if ( !m_pImpl )
+ {
+ SAL_INFO("package.xstor", THROW_WHERE "Disposed!");
+ throw lang::DisposedException( THROW_WHERE );
+ }
+
+ try
+ {
+ return m_pImpl->GetElementNames();
+ }
+ catch( const uno::RuntimeException& )
+ {
+ TOOLS_INFO_EXCEPTION("package.xstor", "Rethrow:");
+ throw;
+ }
+ catch ( const uno::Exception& )
+ {
+ uno::Any aCaught( ::cppu::getCaughtException() );
+ SAL_INFO("package.xstor", "Rethrow: " << exceptionToString(aCaught));
+
+ throw lang::WrappedTargetRuntimeException( THROW_WHERE "Can not open storage!",
+ static_cast< OWeakObject* >( this ),
+ aCaught );
+ }
+}
+
+sal_Bool SAL_CALL OStorage::hasByName( const OUString& aName )
+{
+ ::osl::MutexGuard aGuard( m_xSharedMutex->GetMutex() );
+
+ if ( !m_pImpl )
+ {
+ SAL_INFO("package.xstor", THROW_WHERE "Disposed!");
+ throw lang::DisposedException( THROW_WHERE );
+ }
+
+ if ( aName.isEmpty() )
+ return false;
+
+ if ( m_pImpl->m_nStorageType == embed::StorageFormats::OFOPXML && aName == "_rels" )
+ return false;
+
+ SotElement_Impl* pElement = nullptr;
+ try
+ {
+ pElement = m_pImpl->FindElement( aName );
+ }
+ catch( const uno::RuntimeException& )
+ {
+ TOOLS_INFO_EXCEPTION("package.xstor", "Rethrow:");
+ throw;
+ }
+ catch ( const uno::Exception& )
+ {
+ uno::Any aCaught( ::cppu::getCaughtException() );
+ SAL_INFO("package.xstor", "Rethrow: " << exceptionToString(aCaught));
+
+ throw lang::WrappedTargetRuntimeException( THROW_WHERE "Can not open storage!",
+ static_cast< OWeakObject* >( this ),
+ aCaught );
+ }
+
+ return ( pElement != nullptr );
+}
+
+uno::Type SAL_CALL OStorage::getElementType()
+{
+ ::osl::MutexGuard aGuard( m_xSharedMutex->GetMutex() );
+
+ if ( !m_pImpl )
+ {
+ SAL_INFO("package.xstor", THROW_WHERE "Disposed!");
+ throw lang::DisposedException( THROW_WHERE );
+ }
+
+ // it is a multitype container
+ return uno::Type();
+}
+
+sal_Bool SAL_CALL OStorage::hasElements()
+{
+ ::osl::MutexGuard aGuard( m_xSharedMutex->GetMutex() );
+
+ if ( !m_pImpl )
+ {
+ SAL_INFO("package.xstor", THROW_WHERE "Disposed!");
+ throw lang::DisposedException( THROW_WHERE );
+ }
+
+ try
+ {
+ return m_pImpl->HasChildren();
+ }
+ catch( const uno::RuntimeException& )
+ {
+ TOOLS_INFO_EXCEPTION("package.xstor", "Rethrow:");
+ throw;
+ }
+ catch( const uno::Exception& )
+ {
+ uno::Any aCaught( ::cppu::getCaughtException() );
+ SAL_INFO("package.xstor", "Rethrow: " << exceptionToString(aCaught));
+
+ throw lang::WrappedTargetRuntimeException( THROW_WHERE "Can not open storage!",
+ static_cast< OWeakObject* >( this ),
+ aCaught );
+ }
+}
+
+// XComponent
+void SAL_CALL OStorage::dispose()
+{
+ ::osl::MutexGuard aGuard( m_xSharedMutex->GetMutex() );
+
+ if ( !m_pImpl )
+ {
+ SAL_INFO("package.xstor", THROW_WHERE "Disposed!");
+ throw lang::DisposedException( THROW_WHERE );
+ }
+
+ try
+ {
+ InternalDispose( true );
+ }
+ catch( const uno::RuntimeException& )
+ {
+ TOOLS_INFO_EXCEPTION("package.xstor", "Rethrow:");
+ throw;
+ }
+ catch( const uno::Exception& )
+ {
+ uno::Any aCaught( ::cppu::getCaughtException() );
+ SAL_INFO("package.xstor", "Rethrow: " << exceptionToString(aCaught));
+
+ throw lang::WrappedTargetRuntimeException( THROW_WHERE "Can not open storage!",
+ static_cast< OWeakObject* >( this ),
+ aCaught );
+ }
+}
+
+void SAL_CALL OStorage::addEventListener(
+ const uno::Reference< lang::XEventListener >& xListener )
+{
+ ::osl::MutexGuard aGuard( m_xSharedMutex->GetMutex() );
+
+ if ( !m_pImpl )
+ {
+ SAL_INFO("package.xstor", THROW_WHERE "Disposed!");
+ throw lang::DisposedException( THROW_WHERE );
+ }
+
+ m_aListenersContainer.addInterface(
+ cppu::UnoType<lang::XEventListener>::get(), xListener );
+}
+
+void SAL_CALL OStorage::removeEventListener(
+ const uno::Reference< lang::XEventListener >& xListener )
+{
+ ::osl::MutexGuard aGuard( m_xSharedMutex->GetMutex() );
+
+ if ( !m_pImpl )
+ {
+ SAL_INFO("package.xstor", THROW_WHERE "Disposed!");
+ throw lang::DisposedException( THROW_WHERE );
+ }
+
+ m_aListenersContainer.removeInterface(
+ cppu::UnoType<lang::XEventListener>::get(), xListener );
+}
+
+// XEncryptionProtectedSource
+
+void SAL_CALL OStorage::setEncryptionPassword( const OUString& aPass )
+{
+ setEncryptionData( ::comphelper::OStorageHelper::CreatePackageEncryptionData( aPass ) );
+}
+
+void SAL_CALL OStorage::removeEncryption()
+{
+ ::osl::MutexGuard aGuard( m_xSharedMutex->GetMutex() );
+
+ if ( !m_pImpl )
+ {
+ SAL_INFO("package.xstor", THROW_WHERE "Disposed!");
+ throw lang::DisposedException( THROW_WHERE );
+ }
+
+ if ( m_pImpl->m_nStorageType != embed::StorageFormats::PACKAGE )
+ throw uno::RuntimeException( THROW_WHERE ); // the interface must be visible only for package storage
+
+ SAL_WARN_IF( !m_pImpl->m_bIsRoot, "package.xstor", "removeEncryption() method is not available for nonroot storages!" );
+ if ( !m_pImpl->m_bIsRoot )
+ return;
+
+ try {
+ m_pImpl->ReadContents();
+ }
+ catch ( const uno::RuntimeException& )
+ {
+ TOOLS_INFO_EXCEPTION("package.xstor", "Rethrow:");
+ throw;
+ }
+ catch ( const uno::Exception& )
+ {
+ uno::Any aCaught( ::cppu::getCaughtException() );
+ SAL_INFO("package.xstor", "Rethrow: " << exceptionToString(aCaught));
+
+ throw lang::WrappedTargetRuntimeException( THROW_WHERE "Can not open package!",
+ static_cast< OWeakObject* >( this ),
+ aCaught );
+ }
+
+ // TODO: check if the password is valid
+ // update all streams that was encrypted with old password
+
+ uno::Reference< beans::XPropertySet > xPackPropSet( m_pImpl->m_xPackage, uno::UNO_QUERY_THROW );
+ try
+ {
+ xPackPropSet->setPropertyValue( STORAGE_ENCRYPTION_KEYS_PROPERTY,
+ uno::Any( uno::Sequence< beans::NamedValue >() ) );
+
+ m_pImpl->m_bHasCommonEncryptionData = false;
+ m_pImpl->m_aCommonEncryptionData.clear();
+ }
+ catch( const uno::RuntimeException& )
+ {
+ TOOLS_WARN_EXCEPTION( "package.xstor", "The call must not fail, it is pretty simple!" );
+ throw;
+ }
+ catch( const uno::Exception& )
+ {
+ TOOLS_WARN_EXCEPTION( "package.xstor", "The call must not fail, it is pretty simple!" );
+ throw io::IOException( THROW_WHERE );
+ }
+}
+
+// XEncryptionProtectedSource2
+
+void SAL_CALL OStorage::setEncryptionData( const uno::Sequence< beans::NamedValue >& aEncryptionData )
+{
+ ::osl::MutexGuard aGuard( m_xSharedMutex->GetMutex() );
+
+ if ( !m_pImpl )
+ {
+ SAL_INFO("package.xstor", THROW_WHERE "Disposed!");
+ throw lang::DisposedException( THROW_WHERE );
+ }
+
+ if ( m_pImpl->m_nStorageType != embed::StorageFormats::PACKAGE )
+ throw uno::RuntimeException( THROW_WHERE ); // the interface must be visible only for package storage
+
+ if ( !aEncryptionData.hasElements() )
+ throw uno::RuntimeException( THROW_WHERE "Unexpected empty encryption data!" );
+
+ SAL_WARN_IF( !m_pImpl->m_bIsRoot, "package.xstor", "setEncryptionData() method is not available for nonroot storages!" );
+ if ( !m_pImpl->m_bIsRoot )
+ return;
+
+ try {
+ m_pImpl->ReadContents();
+ }
+ catch ( const uno::RuntimeException& )
+ {
+ TOOLS_INFO_EXCEPTION("package.xstor", "Rethrow:");
+ throw;
+ }
+ catch ( const uno::Exception& )
+ {
+ uno::Any aCaught( ::cppu::getCaughtException() );
+ SAL_INFO("package.xstor", "Rethrow: " << exceptionToString(aCaught));
+
+ throw lang::WrappedTargetRuntimeException( THROW_WHERE "Can not open package!",
+ static_cast< OWeakObject* >( this ),
+ aCaught );
+ }
+
+ uno::Reference< beans::XPropertySet > xPackPropSet( m_pImpl->m_xPackage, uno::UNO_QUERY_THROW );
+ try
+ {
+ ::comphelper::SequenceAsHashMap aEncryptionMap( aEncryptionData );
+ xPackPropSet->setPropertyValue( STORAGE_ENCRYPTION_KEYS_PROPERTY,
+ uno::Any( aEncryptionMap.getAsConstNamedValueList() ) );
+
+ m_pImpl->m_bHasCommonEncryptionData = true;
+ m_pImpl->m_aCommonEncryptionData = aEncryptionMap;
+ }
+ catch( const uno::Exception& )
+ {
+ TOOLS_INFO_EXCEPTION("package.xstor", "Rethrow:" );
+
+ throw io::IOException( THROW_WHERE );
+ }
+}
+
+sal_Bool SAL_CALL OStorage::hasEncryptionData()
+{
+ ::osl::MutexGuard aGuard( m_xSharedMutex->GetMutex() );
+
+ return m_pImpl && m_pImpl->m_bHasCommonEncryptionData;
+}
+
+// XEncryptionProtectedStorage
+
+void SAL_CALL OStorage::setEncryptionAlgorithms( const uno::Sequence< beans::NamedValue >& aAlgorithms )
+{
+ ::osl::MutexGuard aGuard( m_xSharedMutex->GetMutex() );
+
+ if ( !m_pImpl )
+ {
+ SAL_INFO("package.xstor", THROW_WHERE "Disposed!");
+ throw lang::DisposedException( THROW_WHERE );
+ }
+
+ if ( m_pImpl->m_nStorageType != embed::StorageFormats::PACKAGE )
+ throw uno::RuntimeException( THROW_WHERE ); // the interface must be visible only for package storage
+
+ if ( !aAlgorithms.hasElements() )
+ throw uno::RuntimeException( THROW_WHERE "Unexpected empty encryption algorithms list!" );
+
+ SAL_WARN_IF( !m_pImpl->m_bIsRoot, "package.xstor", "setEncryptionAlgorithms() method is not available for nonroot storages!" );
+ if ( !m_pImpl->m_bIsRoot )
+ return;
+
+ try {
+ m_pImpl->ReadContents();
+ }
+ catch ( const uno::RuntimeException& )
+ {
+ TOOLS_INFO_EXCEPTION("package.xstor", "Rethrow:");
+ throw;
+ }
+ catch ( const uno::Exception& )
+ {
+ uno::Any aCaught( ::cppu::getCaughtException() );
+ SAL_INFO("package.xstor", "Rethrow: " << exceptionToString(aCaught));
+
+ throw lang::WrappedTargetRuntimeException( THROW_WHERE "Can not open package!",
+ static_cast< OWeakObject* >( this ),
+ aCaught );
+ }
+
+ uno::Reference< beans::XPropertySet > xPackPropSet( m_pImpl->m_xPackage, uno::UNO_QUERY_THROW );
+ try
+ {
+ xPackPropSet->setPropertyValue( ENCRYPTION_ALGORITHMS_PROPERTY,
+ uno::Any( aAlgorithms ) );
+ }
+ catch ( const uno::RuntimeException& )
+ {
+ TOOLS_INFO_EXCEPTION("package.xstor", "Rethrow:");
+ throw;
+ }
+ catch( const uno::Exception& )
+ {
+ uno::Any aCaught( ::cppu::getCaughtException() );
+ SAL_INFO("package.xstor", "Rethrow: " << exceptionToString(aCaught));
+
+ throw lang::WrappedTargetRuntimeException( THROW_WHERE "Can not open package!",
+ static_cast< OWeakObject* >( this ),
+ aCaught );
+ }
+}
+
+void SAL_CALL OStorage::setGpgProperties( const uno::Sequence< uno::Sequence< beans::NamedValue > >& aProps )
+{
+ ::osl::MutexGuard aGuard( m_xSharedMutex->GetMutex() );
+
+ if ( !m_pImpl )
+ {
+ SAL_INFO("package.xstor", THROW_WHERE "Disposed!");
+ throw lang::DisposedException( THROW_WHERE );
+ }
+
+ if ( m_pImpl->m_nStorageType != embed::StorageFormats::PACKAGE )
+ throw uno::RuntimeException( THROW_WHERE ); // the interface must be visible only for package storage
+
+ if ( !aProps.hasElements() )
+ throw uno::RuntimeException( THROW_WHERE "Unexpected empty encryption algorithms list!" );
+
+ SAL_WARN_IF( !m_pImpl->m_bIsRoot, "package.xstor", "setGpgProperties() method is not available for nonroot storages!" );
+ if ( !m_pImpl->m_bIsRoot )
+ return;
+
+ try {
+ m_pImpl->ReadContents();
+ }
+ catch ( const uno::RuntimeException& aRuntimeException )
+ {
+ SAL_INFO("package.xstor", "Rethrow: " << aRuntimeException.Message);
+ throw;
+ }
+ catch ( const uno::Exception& )
+ {
+ uno::Any aCaught( ::cppu::getCaughtException() );
+ SAL_INFO("package.xstor", "Rethrow: " << exceptionToString(aCaught));
+
+ throw lang::WrappedTargetRuntimeException( THROW_WHERE "Can not open package!",
+ static_cast< OWeakObject* >( this ),
+ aCaught );
+ }
+
+ uno::Reference< beans::XPropertySet > xPackPropSet( m_pImpl->m_xPackage, uno::UNO_QUERY_THROW );
+ try
+ {
+ xPackPropSet->setPropertyValue( ENCRYPTION_GPG_PROPERTIES,
+ uno::Any( aProps ) );
+ }
+ catch ( const uno::RuntimeException& aRuntimeException )
+ {
+ SAL_INFO("package.xstor", "Rethrow: " << aRuntimeException.Message);
+ throw;
+ }
+ catch( const uno::Exception& )
+ {
+ uno::Any aCaught( ::cppu::getCaughtException() );
+ SAL_INFO("package.xstor", "Rethrow: " << exceptionToString(aCaught));
+
+ throw lang::WrappedTargetRuntimeException( THROW_WHERE "Can not open package!",
+ static_cast< OWeakObject* >( this ),
+ aCaught );
+ }
+}
+
+uno::Sequence< beans::NamedValue > SAL_CALL OStorage::getEncryptionAlgorithms()
+{
+ ::osl::MutexGuard aGuard( m_xSharedMutex->GetMutex() );
+
+ if ( !m_pImpl )
+ {
+ SAL_INFO("package.xstor", THROW_WHERE "Disposed!");
+ throw lang::DisposedException( THROW_WHERE );
+ }
+
+ if ( m_pImpl->m_nStorageType != embed::StorageFormats::PACKAGE )
+ throw uno::RuntimeException( THROW_WHERE ); // the interface must be visible only for package storage
+
+ uno::Sequence< beans::NamedValue > aResult;
+ SAL_WARN_IF( !m_pImpl->m_bIsRoot, "package.xstor", "getEncryptionAlgorithms() method is not available for nonroot storages!" );
+ if ( m_pImpl->m_bIsRoot )
+ {
+ try {
+ m_pImpl->ReadContents();
+ }
+ catch ( const uno::RuntimeException& )
+ {
+ TOOLS_INFO_EXCEPTION("package.xstor", "Rethrow:");
+ throw;
+ }
+ catch ( const uno::Exception& )
+ {
+ uno::Any aCaught( ::cppu::getCaughtException() );
+ SAL_INFO("package.xstor", "Rethrow: " << exceptionToString(aCaught));
+
+ throw lang::WrappedTargetRuntimeException( THROW_WHERE "Can not open package!",
+ static_cast< OWeakObject* >( this ),
+ aCaught );
+ }
+
+ uno::Reference< beans::XPropertySet > xPackPropSet( m_pImpl->m_xPackage, uno::UNO_QUERY_THROW );
+ try
+ {
+ xPackPropSet->getPropertyValue( ENCRYPTION_ALGORITHMS_PROPERTY ) >>= aResult;
+ }
+ catch ( const uno::RuntimeException& )
+ {
+ TOOLS_INFO_EXCEPTION("package.xstor", "Rethrow:");
+ throw;
+ }
+ catch( const uno::Exception& )
+ {
+ uno::Any aCaught( ::cppu::getCaughtException() );
+ SAL_INFO("package.xstor", "Rethrow: " << exceptionToString(aCaught));
+
+ throw lang::WrappedTargetRuntimeException( THROW_WHERE "Can not open package!",
+ static_cast< OWeakObject* >( this ),
+ aCaught );
+ }
+ }
+
+ return aResult;
+}
+
+// XPropertySet
+
+uno::Reference< beans::XPropertySetInfo > SAL_CALL OStorage::getPropertySetInfo()
+{
+ ::osl::MutexGuard aGuard( m_xSharedMutex->GetMutex() );
+
+ if ( !m_pImpl )
+ {
+ SAL_INFO("package.xstor", THROW_WHERE "Disposed!");
+ throw lang::DisposedException( THROW_WHERE );
+ }
+
+ //TODO:
+ return uno::Reference< beans::XPropertySetInfo >();
+}
+
+void SAL_CALL OStorage::setPropertyValue( const OUString& aPropertyName, const uno::Any& aValue )
+{
+ ::osl::MutexGuard aGuard( m_xSharedMutex->GetMutex() );
+
+ if ( !m_pImpl )
+ {
+ SAL_INFO("package.xstor", THROW_WHERE "Disposed!");
+ throw lang::DisposedException( THROW_WHERE );
+ }
+
+ //TODO: think about interaction handler
+
+ // WORKAROUND:
+ // The old document might have no version in the manifest.xml, so we have to allow to set the version
+ // even for readonly storages, so that the version from content.xml can be used.
+ if ( m_bReadOnlyWrap && aPropertyName != "Version" )
+ throw uno::RuntimeException( THROW_WHERE ); // TODO: Access denied
+
+ if ( m_pImpl->m_nStorageType == embed::StorageFormats::ZIP )
+ throw beans::UnknownPropertyException( aPropertyName );
+ else if ( m_pImpl->m_nStorageType == embed::StorageFormats::PACKAGE )
+ {
+ if ( aPropertyName == "MediaType" )
+ {
+ aValue >>= m_pImpl->m_aMediaType;
+ m_pImpl->m_bControlMediaType = true;
+
+ m_pImpl->m_bBroadcastModified = true;
+ m_pImpl->m_bIsModified = true;
+ }
+ else if ( aPropertyName == "Version" )
+ {
+ aValue >>= m_pImpl->m_aVersion;
+ m_pImpl->m_bControlVersion = true;
+
+ // this property can be set even for readonly storage
+ if ( !m_bReadOnlyWrap )
+ {
+ m_pImpl->m_bBroadcastModified = true;
+ m_pImpl->m_bIsModified = true;
+ }
+ }
+ else if ( ( m_pImpl->m_bIsRoot && ( aPropertyName == HAS_ENCRYPTED_ENTRIES_PROPERTY
+ || aPropertyName == HAS_NONENCRYPTED_ENTRIES_PROPERTY
+ || aPropertyName == IS_INCONSISTENT_PROPERTY
+ || aPropertyName == "URL"
+ || aPropertyName == "RepairPackage"
+ || aPropertyName == ENCRYPTION_GPG_PROPERTIES) )
+ || aPropertyName == "IsRoot"
+ || aPropertyName == MEDIATYPE_FALLBACK_USED_PROPERTY )
+ throw beans::PropertyVetoException( THROW_WHERE );
+ else
+ throw beans::UnknownPropertyException( aPropertyName );
+ }
+ else if ( m_pImpl->m_nStorageType == embed::StorageFormats::OFOPXML )
+ {
+ if ( aPropertyName == "RelationsInfoStream" )
+ {
+ uno::Reference< io::XInputStream > xInRelStream;
+ if ( !( aValue >>= xInRelStream ) || !xInRelStream.is() )
+ throw lang::IllegalArgumentException( THROW_WHERE, uno::Reference< uno::XInterface >(), 0 );
+
+ uno::Reference< io::XSeekable > xSeek( xInRelStream, uno::UNO_QUERY );
+ if ( !xSeek.is() )
+ {
+ // currently this is an internal property that is used for optimization
+ // and the stream must support XSeekable interface
+ // TODO/LATER: in future it can be changed if property is used from outside
+ throw lang::IllegalArgumentException( THROW_WHERE, uno::Reference< uno::XInterface >(), 0 );
+ }
+
+ m_pImpl->m_xNewRelInfoStream = xInRelStream;
+ m_pImpl->m_aRelInfo = uno::Sequence< uno::Sequence< beans::StringPair > >();
+ m_pImpl->m_nRelInfoStatus = RELINFO_CHANGED_STREAM;
+ m_pImpl->m_bBroadcastModified = true;
+ m_pImpl->m_bIsModified = true;
+ }
+ else if ( aPropertyName == "RelationsInfo" )
+ {
+ if ( !(aValue >>= m_pImpl->m_aRelInfo) )
+ throw lang::IllegalArgumentException( THROW_WHERE, uno::Reference< uno::XInterface >(), 0 );
+
+ m_pImpl->m_xNewRelInfoStream.clear();
+ m_pImpl->m_nRelInfoStatus = RELINFO_CHANGED;
+ m_pImpl->m_bBroadcastModified = true;
+ m_pImpl->m_bIsModified = true;
+ }
+ else if ( ( m_pImpl->m_bIsRoot && ( aPropertyName == "URL" || aPropertyName == "RepairPackage") )
+ || aPropertyName == "IsRoot" )
+ throw beans::PropertyVetoException( THROW_WHERE );
+ else
+ throw beans::UnknownPropertyException( aPropertyName );
+ }
+ else
+ throw beans::UnknownPropertyException( aPropertyName );
+
+ BroadcastModifiedIfNecessary();
+}
+
+uno::Any SAL_CALL OStorage::getPropertyValue( const OUString& aPropertyName )
+{
+ ::osl::MutexGuard aGuard( m_xSharedMutex->GetMutex() );
+
+ if ( !m_pImpl )
+ {
+ SAL_INFO("package.xstor", THROW_WHERE "Disposed!");
+ throw lang::DisposedException( THROW_WHERE );
+ }
+
+ if ( m_pImpl->m_nStorageType == embed::StorageFormats::PACKAGE
+ && ( aPropertyName == "MediaType" || aPropertyName == MEDIATYPE_FALLBACK_USED_PROPERTY || aPropertyName == "Version" ) )
+ {
+ try
+ {
+ m_pImpl->ReadContents();
+ }
+ catch ( const uno::RuntimeException& )
+ {
+ TOOLS_INFO_EXCEPTION("package.xstor", "Rethrow:");
+ throw;
+ }
+ catch ( const uno::Exception& )
+ {
+ uno::Any aCaught( ::cppu::getCaughtException() );
+ SAL_INFO("package.xstor", "Rethrow: " << exceptionToString(aCaught));
+
+ throw lang::WrappedTargetException(
+ "Can't read contents!",
+ static_cast< OWeakObject* >( this ),
+ aCaught );
+ }
+
+ if ( aPropertyName == "MediaType" )
+ return uno::Any( m_pImpl->m_aMediaType );
+ else if ( aPropertyName == "Version" )
+ return uno::Any( m_pImpl->m_aVersion );
+ else
+ return uno::Any( m_pImpl->m_bMTFallbackUsed );
+ }
+ else if ( aPropertyName == "IsRoot" )
+ {
+ return uno::Any( m_pImpl->m_bIsRoot );
+ }
+ else if ( aPropertyName == "OpenMode" )
+ {
+ return uno::Any( m_pImpl->m_nStorageMode );
+ }
+ else if ( m_pImpl->m_bIsRoot )
+ {
+ if ( aPropertyName == "URL"
+ || aPropertyName == "RepairPackage" )
+ {
+ auto pProp = std::find_if(std::cbegin(m_pImpl->m_xProperties), std::cend(m_pImpl->m_xProperties),
+ [&aPropertyName](const css::beans::PropertyValue& rProp) { return rProp.Name == aPropertyName; });
+ if (pProp != std::cend(m_pImpl->m_xProperties))
+ return pProp->Value;
+
+ if ( aPropertyName == "URL" )
+ return uno::Any( OUString() );
+
+ return uno::Any( false ); // RepairPackage
+ }
+ else if ( m_pImpl->m_nStorageType == embed::StorageFormats::PACKAGE
+ && ( aPropertyName == HAS_ENCRYPTED_ENTRIES_PROPERTY
+ || aPropertyName == HAS_NONENCRYPTED_ENTRIES_PROPERTY
+ || aPropertyName == ENCRYPTION_GPG_PROPERTIES
+ || aPropertyName == IS_INCONSISTENT_PROPERTY ) )
+ {
+ try {
+ m_pImpl->ReadContents();
+ uno::Reference< beans::XPropertySet > xPackPropSet( m_pImpl->m_xPackage, uno::UNO_QUERY_THROW );
+ return xPackPropSet->getPropertyValue( aPropertyName );
+ }
+ catch ( const uno::RuntimeException& )
+ {
+ TOOLS_INFO_EXCEPTION("package.xstor", "Rethrow:");
+ throw;
+ }
+ catch ( const uno::Exception& )
+ {
+ uno::Any aCaught( ::cppu::getCaughtException() );
+ SAL_INFO("package.xstor", "Rethrow: " << exceptionToString(aCaught));
+
+ throw lang::WrappedTargetException( THROW_WHERE "Can not open package!",
+ static_cast< OWeakObject* >( this ),
+ aCaught );
+ }
+ }
+ }
+
+ throw beans::UnknownPropertyException(aPropertyName);
+}
+
+void SAL_CALL OStorage::addPropertyChangeListener(
+ const OUString& /*aPropertyName*/,
+ const uno::Reference< beans::XPropertyChangeListener >& /*xListener*/ )
+{
+ ::osl::MutexGuard aGuard( m_xSharedMutex->GetMutex() );
+
+ if ( !m_pImpl )
+ {
+ SAL_INFO("package.xstor", THROW_WHERE "Disposed!");
+ throw lang::DisposedException( THROW_WHERE );
+ }
+
+ //TODO:
+}
+
+void SAL_CALL OStorage::removePropertyChangeListener(
+ const OUString& /*aPropertyName*/,
+ const uno::Reference< beans::XPropertyChangeListener >& /*aListener*/ )
+{
+ ::osl::MutexGuard aGuard( m_xSharedMutex->GetMutex() );
+
+ if ( !m_pImpl )
+ {
+ SAL_INFO("package.xstor", THROW_WHERE "Disposed!");
+ throw lang::DisposedException( THROW_WHERE );
+ }
+
+ //TODO:
+}
+
+void SAL_CALL OStorage::addVetoableChangeListener(
+ const OUString& /*PropertyName*/,
+ const uno::Reference< beans::XVetoableChangeListener >& /*aListener*/ )
+{
+ ::osl::MutexGuard aGuard( m_xSharedMutex->GetMutex() );
+
+ if ( !m_pImpl )
+ {
+ SAL_INFO("package.xstor", THROW_WHERE "Disposed!");
+ throw lang::DisposedException( THROW_WHERE );
+ }
+
+ //TODO:
+}
+
+void SAL_CALL OStorage::removeVetoableChangeListener(
+ const OUString& /*PropertyName*/,
+ const uno::Reference< beans::XVetoableChangeListener >& /*aListener*/ )
+{
+ ::osl::MutexGuard aGuard( m_xSharedMutex->GetMutex() );
+
+ if ( !m_pImpl )
+ {
+ SAL_INFO("package.xstor", THROW_WHERE "Disposed!");
+ throw lang::DisposedException( THROW_WHERE );
+ }
+
+ //TODO:
+}
+
+// XRelationshipAccess
+
+// TODO/LATER: the storage and stream implementations of this interface are very similar, they could use a helper class
+
+sal_Bool SAL_CALL OStorage::hasByID( const OUString& sID )
+{
+ ::osl::MutexGuard aGuard( m_xSharedMutex->GetMutex() );
+
+ if ( !m_pImpl )
+ {
+ SAL_INFO("package.xstor", THROW_WHERE "Disposed!");
+ throw lang::DisposedException( THROW_WHERE );
+ }
+
+ if ( m_pImpl->m_nStorageType != embed::StorageFormats::OFOPXML )
+ throw uno::RuntimeException( THROW_WHERE );
+
+ try
+ {
+ getRelationshipByID( sID );
+ return true;
+ }
+ catch( const container::NoSuchElementException& )
+ {
+ TOOLS_INFO_EXCEPTION("package.xstor", "Rethrow:");
+ }
+
+ return false;
+}
+
+namespace
+{
+
+const beans::StringPair* lcl_findPairByName(const uno::Sequence<beans::StringPair>& rSeq, const OUString& rName)
+{
+ return std::find_if(rSeq.begin(), rSeq.end(), [&rName](const beans::StringPair& rPair) { return rPair.First == rName; });
+}
+
+}
+
+OUString SAL_CALL OStorage::getTargetByID( const OUString& sID )
+{
+ ::osl::MutexGuard aGuard( m_xSharedMutex->GetMutex() );
+
+ if ( !m_pImpl )
+ {
+ SAL_INFO("package.xstor", THROW_WHERE "Disposed!");
+ throw lang::DisposedException( THROW_WHERE );
+ }
+
+ if ( m_pImpl->m_nStorageType != embed::StorageFormats::OFOPXML )
+ throw uno::RuntimeException( THROW_WHERE );
+
+ const uno::Sequence< beans::StringPair > aSeq = getRelationshipByID( sID );
+ auto pRel = lcl_findPairByName(aSeq, "Target");
+ if (pRel != aSeq.end())
+ return pRel->Second;
+
+ return OUString();
+}
+
+OUString SAL_CALL OStorage::getTypeByID( const OUString& sID )
+{
+ ::osl::MutexGuard aGuard( m_xSharedMutex->GetMutex() );
+
+ if ( !m_pImpl )
+ {
+ SAL_INFO("package.xstor", THROW_WHERE "Disposed!");
+ throw lang::DisposedException( THROW_WHERE );
+ }
+
+ if ( m_pImpl->m_nStorageType != embed::StorageFormats::OFOPXML )
+ throw uno::RuntimeException( THROW_WHERE );
+
+ const uno::Sequence< beans::StringPair > aSeq = getRelationshipByID( sID );
+ auto pRel = lcl_findPairByName(aSeq, "Type");
+ if (pRel != aSeq.end())
+ return pRel->Second;
+
+ return OUString();
+}
+
+uno::Sequence< beans::StringPair > SAL_CALL OStorage::getRelationshipByID( const OUString& sID )
+{
+ ::osl::MutexGuard aGuard( m_xSharedMutex->GetMutex() );
+
+ if ( !m_pImpl )
+ {
+ SAL_INFO("package.xstor", THROW_WHERE "Disposed!");
+ throw lang::DisposedException( THROW_WHERE );
+ }
+
+ if ( m_pImpl->m_nStorageType != embed::StorageFormats::OFOPXML )
+ throw uno::RuntimeException( THROW_WHERE );
+
+ // TODO/LATER: in future the unification of the ID could be checked
+ const uno::Sequence< uno::Sequence< beans::StringPair > > aSeq = getAllRelationships();
+ const beans::StringPair aIDRel("Id", sID);
+
+ auto pRel = std::find_if(aSeq.begin(), aSeq.end(),
+ [&aIDRel](const uno::Sequence<beans::StringPair>& rRel) {
+ return std::find(rRel.begin(), rRel.end(), aIDRel) != rRel.end(); });
+ if (pRel != aSeq.end())
+ return *pRel;
+
+ throw container::NoSuchElementException( THROW_WHERE );
+}
+
+uno::Sequence< uno::Sequence< beans::StringPair > > SAL_CALL OStorage::getRelationshipsByType( const OUString& sType )
+{
+ ::osl::MutexGuard aGuard( m_xSharedMutex->GetMutex() );
+
+ if ( !m_pImpl )
+ {
+ SAL_INFO("package.xstor", THROW_WHERE "Disposed!");
+ throw lang::DisposedException( THROW_WHERE );
+ }
+
+ if ( m_pImpl->m_nStorageType != embed::StorageFormats::OFOPXML )
+ throw uno::RuntimeException( THROW_WHERE );
+
+ // TODO/LATER: in future the unification of the ID could be checked
+ const uno::Sequence< uno::Sequence< beans::StringPair > > aSeq = getAllRelationships();
+ std::vector< uno::Sequence< beans::StringPair > > aResult;
+ aResult.reserve(aSeq.getLength());
+
+ std::copy_if(aSeq.begin(), aSeq.end(), std::back_inserter(aResult),
+ [&sType](const uno::Sequence<beans::StringPair>& rRel) {
+ auto pRel = lcl_findPairByName(rRel, "Type");
+ return pRel != rRel.end()
+ // the type is usually a URL, so the check should be case insensitive
+ && pRel->Second.equalsIgnoreAsciiCase( sType );
+ });
+
+ return comphelper::containerToSequence(aResult);
+}
+
+uno::Sequence< uno::Sequence< beans::StringPair > > SAL_CALL OStorage::getAllRelationships()
+{
+ ::osl::MutexGuard aGuard( m_xSharedMutex->GetMutex() );
+
+ if ( !m_pImpl )
+ {
+ SAL_INFO("package.xstor", THROW_WHERE "Disposed!");
+ throw lang::DisposedException( THROW_WHERE );
+ }
+
+ if ( m_pImpl->m_nStorageType != embed::StorageFormats::OFOPXML )
+ throw uno::RuntimeException( THROW_WHERE );
+
+ uno::Sequence< uno::Sequence< beans::StringPair > > aRet;
+ try
+ {
+ aRet = m_pImpl->GetAllRelationshipsIfAny();
+ }
+ catch (const io::IOException&)
+ {
+ throw;
+ }
+ catch (const uno::RuntimeException&)
+ {
+ throw;
+ }
+ catch (const uno::Exception &)
+ {
+ uno::Any aCaught( ::cppu::getCaughtException() );
+ throw lang::WrappedTargetRuntimeException(THROW_WHERE "Can't getAllRelationships!",
+ uno::Reference< uno::XInterface >(),
+ aCaught);
+ }
+
+ return aRet;
+}
+
+void SAL_CALL OStorage::insertRelationshipByID( const OUString& sID, const uno::Sequence< beans::StringPair >& aEntry, sal_Bool bReplace )
+{
+ ::osl::MutexGuard aGuard( m_xSharedMutex->GetMutex() );
+
+ if ( !m_pImpl )
+ {
+ SAL_INFO("package.xstor", THROW_WHERE "Disposed!");
+ throw lang::DisposedException( THROW_WHERE );
+ }
+
+ if ( m_pImpl->m_nStorageType != embed::StorageFormats::OFOPXML )
+ throw uno::RuntimeException( THROW_WHERE );
+
+ const beans::StringPair aIDRel("Id", sID);
+
+ uno::Sequence<beans::StringPair>* pResult = nullptr;
+
+ // TODO/LATER: in future the unification of the ID could be checked
+ uno::Sequence< uno::Sequence< beans::StringPair > > aSeq = getAllRelationships();
+ for ( sal_Int32 nInd = 0; nInd < aSeq.getLength(); nInd++ )
+ {
+ const auto& rRel = aSeq[nInd];
+ if (std::find(rRel.begin(), rRel.end(), aIDRel) != rRel.end())
+ pResult = &aSeq.getArray()[nInd];
+ }
+
+ if ( pResult && !bReplace )
+ throw container::ElementExistException( THROW_WHERE );
+
+ if ( !pResult )
+ {
+ const sal_Int32 nIDInd = aSeq.getLength();
+ aSeq.realloc( nIDInd + 1 );
+ pResult = &aSeq.getArray()[nIDInd];
+ }
+
+ std::vector<beans::StringPair> aResult;
+ aResult.reserve(aEntry.getLength() + 1);
+
+ aResult.push_back(aIDRel);
+ std::copy_if(aEntry.begin(), aEntry.end(), std::back_inserter(aResult),
+ [](const beans::StringPair& rPair) { return rPair.First != "Id"; });
+
+ *pResult = comphelper::containerToSequence(aResult);
+
+ m_pImpl->m_aRelInfo = aSeq;
+ m_pImpl->m_xNewRelInfoStream.clear();
+ m_pImpl->m_nRelInfoStatus = RELINFO_CHANGED;
+}
+
+void SAL_CALL OStorage::removeRelationshipByID( const OUString& sID )
+{
+ ::osl::MutexGuard aGuard( m_xSharedMutex->GetMutex() );
+
+ if ( !m_pImpl )
+ {
+ SAL_INFO("package.xstor", THROW_WHERE "Disposed!");
+ throw lang::DisposedException( THROW_WHERE );
+ }
+
+ if ( m_pImpl->m_nStorageType != embed::StorageFormats::OFOPXML )
+ throw uno::RuntimeException( THROW_WHERE );
+
+ uno::Sequence< uno::Sequence< beans::StringPair > > aSeq = getAllRelationships();
+ const beans::StringPair aIDRel("Id", sID);
+ auto pRel = std::find_if(std::cbegin(aSeq), std::cend(aSeq),
+ [&aIDRel](const uno::Sequence< beans::StringPair >& rRel) {
+ return std::find(rRel.begin(), rRel.end(), aIDRel) != rRel.end(); });
+ if (pRel != std::cend(aSeq))
+ {
+ auto nInd = static_cast<sal_Int32>(std::distance(std::cbegin(aSeq), pRel));
+ comphelper::removeElementAt(aSeq, nInd);
+
+ m_pImpl->m_aRelInfo = aSeq;
+ m_pImpl->m_xNewRelInfoStream.clear();
+ m_pImpl->m_nRelInfoStatus = RELINFO_CHANGED;
+
+ // TODO/LATER: in future the unification of the ID could be checked
+ return;
+ }
+
+ throw container::NoSuchElementException( THROW_WHERE );
+}
+
+void SAL_CALL OStorage::insertRelationships( const uno::Sequence< uno::Sequence< beans::StringPair > >& aEntries, sal_Bool bReplace )
+{
+ ::osl::MutexGuard aGuard( m_xSharedMutex->GetMutex() );
+
+ if ( !m_pImpl )
+ {
+ SAL_INFO("package.xstor", THROW_WHERE "Disposed!");
+ throw lang::DisposedException( THROW_WHERE );
+ }
+
+ if ( m_pImpl->m_nStorageType != embed::StorageFormats::OFOPXML )
+ throw uno::RuntimeException( THROW_WHERE );
+
+ OUString aIDTag( "Id" );
+ const uno::Sequence< uno::Sequence< beans::StringPair > > aSeq = getAllRelationships();
+ std::vector< uno::Sequence<beans::StringPair> > aResultVec;
+ aResultVec.reserve(aSeq.getLength() + aEntries.getLength());
+
+ std::copy_if(aSeq.begin(), aSeq.end(), std::back_inserter(aResultVec),
+ [&aIDTag, &aEntries, bReplace](const uno::Sequence<beans::StringPair>& rTargetRel) {
+ auto pTargetPair = lcl_findPairByName(rTargetRel, aIDTag);
+ if (pTargetPair == rTargetRel.end())
+ return false;
+
+ bool bIsSourceSame = std::any_of(aEntries.begin(), aEntries.end(),
+ [&pTargetPair](const uno::Sequence<beans::StringPair>& rSourceEntry) {
+ return std::find(rSourceEntry.begin(), rSourceEntry.end(), *pTargetPair) != rSourceEntry.end(); });
+
+ if ( bIsSourceSame && !bReplace )
+ throw container::ElementExistException( THROW_WHERE );
+
+ // if no such element in the provided sequence
+ return !bIsSourceSame;
+ });
+
+ std::transform(aEntries.begin(), aEntries.end(), std::back_inserter(aResultVec),
+ [&aIDTag](const uno::Sequence<beans::StringPair>& rEntry) -> uno::Sequence<beans::StringPair> {
+ auto pPair = lcl_findPairByName(rEntry, aIDTag);
+ if (pPair == rEntry.end())
+ throw io::IOException( THROW_WHERE ); // TODO: illegal relation ( no ID )
+
+ auto aResult = comphelper::sequenceToContainer<std::vector<beans::StringPair>>(rEntry);
+ auto nIDInd = std::distance(rEntry.begin(), pPair);
+ std::rotate(aResult.begin(), std::next(aResult.begin(), nIDInd), std::next(aResult.begin(), nIDInd + 1));
+
+ return comphelper::containerToSequence(aResult);
+ });
+
+ m_pImpl->m_aRelInfo = comphelper::containerToSequence(aResultVec);
+ m_pImpl->m_xNewRelInfoStream.clear();
+ m_pImpl->m_nRelInfoStatus = RELINFO_CHANGED;
+}
+
+void SAL_CALL OStorage::clearRelationships()
+{
+ ::osl::MutexGuard aGuard( m_xSharedMutex->GetMutex() );
+
+ if ( !m_pImpl )
+ {
+ SAL_INFO("package.xstor", THROW_WHERE "Disposed!");
+ throw lang::DisposedException( THROW_WHERE );
+ }
+
+ if ( m_pImpl->m_nStorageType != embed::StorageFormats::OFOPXML )
+ throw uno::RuntimeException( THROW_WHERE );
+
+ m_pImpl->m_aRelInfo.realloc( 0 );
+ m_pImpl->m_xNewRelInfoStream.clear();
+ m_pImpl->m_nRelInfoStatus = RELINFO_CHANGED;
+}
+
+// XOptimizedStorage
+void SAL_CALL OStorage::insertRawNonEncrStreamElementDirect(
+ const OUString& /*sStreamName*/,
+ const uno::Reference< io::XInputStream >& /*xInStream*/ )
+{
+ // not implemented currently because there is still no demand
+ // might need to be implemented if direct copying of compressed streams is used
+ throw io::IOException( THROW_WHERE );
+}
+
+void SAL_CALL OStorage::insertStreamElementDirect(
+ const OUString& aStreamName,
+ const uno::Reference< io::XInputStream >& xInStream,
+ const uno::Sequence< beans::PropertyValue >& aProps )
+{
+ ::osl::MutexGuard aGuard( m_xSharedMutex->GetMutex() );
+
+ if ( !m_pImpl )
+ {
+ SAL_INFO("package.xstor", THROW_WHERE "Disposed!");
+ throw lang::DisposedException( THROW_WHERE );
+ }
+
+ if ( aStreamName.isEmpty() || !::comphelper::OStorageHelper::IsValidZipEntryFileName( aStreamName, false ) )
+ throw lang::IllegalArgumentException( THROW_WHERE "Unexpected entry name syntax.", uno::Reference< uno::XInterface >(), 1 );
+
+ if ( m_pImpl->m_nStorageType == embed::StorageFormats::OFOPXML && aStreamName == "_rels" )
+ throw lang::IllegalArgumentException( THROW_WHERE, uno::Reference< uno::XInterface >(), 1 ); // unacceptable storage name
+
+ if ( m_bReadOnlyWrap )
+ throw io::IOException( THROW_WHERE ); // TODO: access denied
+
+ try
+ {
+ SotElement_Impl* pElement = m_pImpl->FindElement( aStreamName );
+
+ if ( pElement )
+ throw container::ElementExistException( THROW_WHERE );
+
+ pElement = OpenStreamElement_Impl( aStreamName, embed::ElementModes::READWRITE, false );
+ OSL_ENSURE(pElement && pElement->m_xStream, "In case element can not be created an exception must be thrown!");
+
+ pElement->m_xStream->InsertStreamDirectly(xInStream, aProps);
+ }
+ catch( const embed::InvalidStorageException& )
+ {
+ TOOLS_INFO_EXCEPTION("package.xstor", "Rethrow:");
+ throw;
+ }
+ catch( const lang::IllegalArgumentException& )
+ {
+ TOOLS_INFO_EXCEPTION("package.xstor", "Rethrow:");
+ throw;
+ }
+ catch( const container::ElementExistException& )
+ {
+ TOOLS_INFO_EXCEPTION("package.xstor", "Rethrow:");
+ throw;
+ }
+ catch( const embed::StorageWrappedTargetException& )
+ {
+ TOOLS_INFO_EXCEPTION("package.xstor", "Rethrow:");
+ throw;
+ }
+ catch( const io::IOException& )
+ {
+ TOOLS_INFO_EXCEPTION("package.xstor", "Rethrow:");
+ throw;
+ }
+ catch( const uno::RuntimeException& )
+ {
+ TOOLS_INFO_EXCEPTION("package.xstor", "Rethrow:");
+ throw;
+ }
+ catch( const uno::Exception& )
+ {
+ uno::Any aCaught( ::cppu::getCaughtException() );
+ SAL_INFO("package.xstor", "Rethrow: " << exceptionToString(aCaught));
+
+ throw embed::StorageWrappedTargetException( THROW_WHERE "Can't insert stream directly!",
+ uno::Reference< io::XInputStream >(),
+ aCaught );
+ }
+}
+
+void SAL_CALL OStorage::copyElementDirectlyTo(
+ const OUString& aElementName,
+ const uno::Reference< embed::XOptimizedStorage >& xDest,
+ const OUString& aNewName )
+{
+ ::osl::MutexGuard aGuard( m_xSharedMutex->GetMutex() );
+
+ if ( !m_pImpl )
+ {
+ SAL_INFO("package.xstor", THROW_WHERE "Disposed!");
+ throw lang::DisposedException( THROW_WHERE );
+ }
+
+ if ( aElementName.isEmpty() || !::comphelper::OStorageHelper::IsValidZipEntryFileName( aElementName, false )
+ || aNewName.isEmpty() || !::comphelper::OStorageHelper::IsValidZipEntryFileName( aNewName, false ) )
+ throw lang::IllegalArgumentException( THROW_WHERE "Unexpected entry name syntax.", uno::Reference< uno::XInterface >(), 1 );
+
+ if ( !xDest.is() || xDest == uno::Reference< uno::XInterface >( static_cast< OWeakObject* >( this ), uno::UNO_QUERY ) )
+ throw lang::IllegalArgumentException( THROW_WHERE, uno::Reference< uno::XInterface >(), 2 );
+
+ if ( m_pImpl->m_nStorageType == embed::StorageFormats::OFOPXML && ( aElementName == "_rels" || aNewName == "_rels" ) )
+ throw lang::IllegalArgumentException( THROW_WHERE, uno::Reference< uno::XInterface >(), 0 ); // unacceptable name
+
+ try
+ {
+ SotElement_Impl* pElement = m_pImpl->FindElement( aElementName );
+ if ( !pElement )
+ throw container::NoSuchElementException( THROW_WHERE );
+
+ uno::Reference< XNameAccess > xNameAccess( xDest, uno::UNO_QUERY_THROW );
+ if ( xNameAccess->hasByName( aNewName ) )
+ throw container::ElementExistException( THROW_WHERE );
+
+ // let the element be copied directly
+ uno::Reference< embed::XStorage > xStorDest( xDest, uno::UNO_QUERY_THROW );
+ m_pImpl->CopyStorageElement( pElement, xStorDest, aNewName, true );
+ }
+ catch( const embed::InvalidStorageException& )
+ {
+ TOOLS_INFO_EXCEPTION("package.xstor", "Rethrow:");
+ throw;
+ }
+ catch( const lang::IllegalArgumentException& )
+ {
+ TOOLS_INFO_EXCEPTION("package.xstor", "Rethrow:");
+ throw;
+ }
+ catch( const container::NoSuchElementException& )
+ {
+ TOOLS_INFO_EXCEPTION("package.xstor", "Rethrow:");
+ throw;
+ }
+ catch( const container::ElementExistException& )
+ {
+ TOOLS_INFO_EXCEPTION("package.xstor", "Rethrow:");
+ throw;
+ }
+ catch( const embed::StorageWrappedTargetException& )
+ {
+ TOOLS_INFO_EXCEPTION("package.xstor", "Rethrow:");
+ throw;
+ }
+ catch( const io::IOException& )
+ {
+ TOOLS_INFO_EXCEPTION("package.xstor", "Rethrow:");
+ throw;
+ }
+ catch( const uno::RuntimeException& )
+ {
+ TOOLS_INFO_EXCEPTION("package.xstor", "Rethrow:");
+ throw;
+ }
+ catch( const uno::Exception& )
+ {
+ uno::Any aCaught( ::cppu::getCaughtException() );
+ SAL_INFO("package.xstor", "Rethrow: " << exceptionToString(aCaught));
+
+ throw embed::StorageWrappedTargetException( THROW_WHERE "Can't copy element directly!",
+ uno::Reference< io::XInputStream >(),
+ aCaught );
+ }
+}
+
+void SAL_CALL OStorage::writeAndAttachToStream( const uno::Reference< io::XStream >& xStream )
+{
+ ::osl::MutexGuard aGuard( m_xSharedMutex->GetMutex() );
+
+ if ( !m_pImpl )
+ {
+ SAL_INFO("package.xstor", THROW_WHERE "Disposed!");
+ throw lang::DisposedException( THROW_WHERE );
+ }
+
+ if ( !m_pImpl->m_bIsRoot )
+ throw lang::IllegalArgumentException( THROW_WHERE, uno::Reference< uno::XInterface >(), 0 );
+
+ if ( !m_pImpl->m_pSwitchStream )
+ throw uno::RuntimeException( THROW_WHERE );
+
+ try
+ {
+ m_pImpl->m_pSwitchStream->CopyAndSwitchPersistenceTo( xStream );
+ }
+ catch( const embed::InvalidStorageException& )
+ {
+ TOOLS_INFO_EXCEPTION("package.xstor", "Rethrow:");
+ throw;
+ }
+ catch( const lang::IllegalArgumentException& )
+ {
+ TOOLS_INFO_EXCEPTION("package.xstor", "Rethrow:");
+ throw;
+ }
+ catch( const embed::StorageWrappedTargetException& )
+ {
+ TOOLS_INFO_EXCEPTION("package.xstor", "Rethrow:");
+ throw;
+ }
+ catch( const io::IOException& )
+ {
+ TOOLS_INFO_EXCEPTION("package.xstor", "Rethrow:" );
+ throw;
+ }
+ catch( const uno::RuntimeException& )
+ {
+ TOOLS_INFO_EXCEPTION("package.xstor", "Rethrow:");
+ throw;
+ }
+ catch( const uno::Exception& )
+ {
+ uno::Any aCaught( ::cppu::getCaughtException() );
+ SAL_INFO("package.xstor", "Rethrow: " << exceptionToString(aCaught));
+
+ throw embed::StorageWrappedTargetException( THROW_WHERE "Can't write and attach to stream!",
+ uno::Reference< io::XInputStream >(),
+ aCaught );
+ }
+
+}
+
+void SAL_CALL OStorage::attachToURL( const OUString& sURL,
+ sal_Bool bReadOnly )
+{
+ ::osl::MutexGuard aGuard( m_xSharedMutex->GetMutex() );
+
+ if ( !m_pImpl )
+ {
+ SAL_INFO("package.xstor", THROW_WHERE "Disposed!");
+ throw lang::DisposedException( THROW_WHERE );
+ }
+
+ if ( !m_pImpl->m_bIsRoot )
+ throw lang::IllegalArgumentException( THROW_WHERE, uno::Reference< uno::XInterface >(), 0 );
+
+ if ( !m_pImpl->m_pSwitchStream )
+ throw uno::RuntimeException( THROW_WHERE );
+
+ uno::Reference < ucb::XSimpleFileAccess3 > xAccess(
+ ucb::SimpleFileAccess::create( m_pImpl->m_xContext ) );
+
+ try
+ {
+ if ( bReadOnly )
+ {
+ uno::Reference< io::XInputStream > xInputStream = xAccess->openFileRead( sURL );
+ m_pImpl->m_pSwitchStream->SwitchPersistenceTo( xInputStream );
+ }
+ else
+ {
+ uno::Reference< io::XStream > xStream = xAccess->openFileReadWrite( sURL );
+ m_pImpl->m_pSwitchStream->SwitchPersistenceTo( xStream );
+ }
+ }
+ catch( const embed::InvalidStorageException& )
+ {
+ TOOLS_INFO_EXCEPTION("package.xstor", "Rethrow:");
+ throw;
+ }
+ catch( const lang::IllegalArgumentException& )
+ {
+ TOOLS_INFO_EXCEPTION("package.xstor", "Rethrow:");
+ throw;
+ }
+ catch( const embed::StorageWrappedTargetException& )
+ {
+ TOOLS_INFO_EXCEPTION("package.xstor", "Rethrow:");
+ throw;
+ }
+ catch( const io::IOException& )
+ {
+ TOOLS_INFO_EXCEPTION("package.xstor", "Rethrow:");
+ throw;
+ }
+ catch( const uno::RuntimeException& )
+ {
+ TOOLS_INFO_EXCEPTION("package.xstor", "Rethrow:");
+ throw;
+ }
+ catch( const uno::Exception& )
+ {
+ uno::Any aCaught( ::cppu::getCaughtException() );
+ SAL_INFO("package.xstor", "Rethrow: " << exceptionToString(aCaught));
+
+ throw embed::StorageWrappedTargetException( THROW_WHERE "Can't attach to URL!",
+ uno::Reference< io::XInputStream >(),
+ aCaught );
+ }
+}
+
+uno::Any SAL_CALL OStorage::getElementPropertyValue( const OUString& aElementName, const OUString& aPropertyName )
+{
+ ::osl::MutexGuard aGuard( m_xSharedMutex->GetMutex() );
+
+ if ( !m_pImpl )
+ {
+ SAL_INFO("package.xstor", THROW_WHERE "Disposed!");
+ throw lang::DisposedException( THROW_WHERE );
+ }
+
+ if ( aElementName.isEmpty() || !::comphelper::OStorageHelper::IsValidZipEntryFileName( aElementName, false ) )
+ throw lang::IllegalArgumentException( THROW_WHERE "Unexpected entry name syntax.", uno::Reference< uno::XInterface >(), 1 );
+
+ if ( m_pImpl->m_nStorageType == embed::StorageFormats::OFOPXML && aElementName == "_rels" )
+ throw lang::IllegalArgumentException( THROW_WHERE, uno::Reference< uno::XInterface >(), 1 ); // TODO: unacceptable name
+
+ try
+ {
+ SotElement_Impl *pElement = m_pImpl->FindElement( aElementName );
+ if ( !pElement )
+ throw container::NoSuchElementException( THROW_WHERE );
+
+ // TODO/LATER: Currently it is only implemented for MediaType property of substorages, might be changed in future
+ if ( !pElement->m_bIsStorage || m_pImpl->m_nStorageType != embed::StorageFormats::PACKAGE || aPropertyName != "MediaType" )
+ throw beans::PropertyVetoException( THROW_WHERE );
+
+ if (!pElement->m_xStorage)
+ m_pImpl->OpenSubStorage( pElement, embed::ElementModes::READ );
+
+ if (!pElement->m_xStorage)
+ throw io::IOException( THROW_WHERE ); // TODO: general_error
+
+ pElement->m_xStorage->ReadContents();
+ return uno::Any(pElement->m_xStorage->m_aMediaType);
+ }
+ catch( const embed::InvalidStorageException& )
+ {
+ TOOLS_INFO_EXCEPTION("package.xstor", "Rethrow:");
+ throw;
+ }
+ catch( const lang::IllegalArgumentException& )
+ {
+ TOOLS_INFO_EXCEPTION("package.xstor", "Rethrow:");
+ throw;
+ }
+ catch( const container::NoSuchElementException& )
+ {
+ TOOLS_INFO_EXCEPTION("package.xstor", "Rethrow:");
+ throw;
+ }
+ catch( const beans::UnknownPropertyException& )
+ {
+ TOOLS_INFO_EXCEPTION("package.xstor", "Rethrow:");
+ throw;
+ }
+ catch( const beans::PropertyVetoException& )
+ {
+ TOOLS_INFO_EXCEPTION("package.xstor", "Rethrow:");
+ throw;
+ }
+ catch( const embed::StorageWrappedTargetException& )
+ {
+ TOOLS_INFO_EXCEPTION("package.xstor", "Rethrow:");
+ throw;
+ }
+ catch( const io::IOException& )
+ {
+ TOOLS_INFO_EXCEPTION("package.xstor", "Rethrow:");
+ throw;
+ }
+ catch( const uno::RuntimeException& )
+ {
+ TOOLS_INFO_EXCEPTION("package.xstor", "Rethrow:");
+ throw;
+ }
+ catch( const uno::Exception& )
+ {
+ uno::Any aCaught( ::cppu::getCaughtException() );
+ SAL_INFO("package.xstor", "Rethrow: " << exceptionToString(aCaught));
+
+ throw embed::StorageWrappedTargetException( THROW_WHERE "Can't get element property!",
+ uno::Reference< io::XInputStream >(),
+ aCaught );
+ }
+}
+
+void SAL_CALL OStorage::copyStreamElementData( const OUString& aStreamName, const uno::Reference< io::XStream >& xTargetStream )
+{
+ ::osl::MutexGuard aGuard( m_xSharedMutex->GetMutex() );
+
+ if ( !m_pImpl )
+ {
+ SAL_INFO("package.xstor", THROW_WHERE "Disposed!");
+ throw lang::DisposedException( THROW_WHERE );
+ }
+
+ if ( aStreamName.isEmpty() || !::comphelper::OStorageHelper::IsValidZipEntryFileName( aStreamName, false ) )
+ throw lang::IllegalArgumentException( THROW_WHERE "Unexpected entry name syntax.", uno::Reference< uno::XInterface >(), 1 );
+
+ if ( m_pImpl->m_nStorageType == embed::StorageFormats::OFOPXML && aStreamName == "_rels" )
+ throw lang::IllegalArgumentException( THROW_WHERE, uno::Reference< uno::XInterface >(), 1 ); // unacceptable name
+
+ if ( !xTargetStream.is() )
+ throw lang::IllegalArgumentException( THROW_WHERE, uno::Reference< uno::XInterface >(), 2 );
+
+ try
+ {
+ uno::Reference< io::XStream > xNonconstRef = xTargetStream;
+ m_pImpl->CloneStreamElement( aStreamName, false, ::comphelper::SequenceAsHashMap(), xNonconstRef );
+
+ SAL_WARN_IF( xNonconstRef != xTargetStream, "package.xstor", "The provided stream reference seems not be filled in correctly!" );
+ if ( xNonconstRef != xTargetStream )
+ throw uno::RuntimeException( THROW_WHERE ); // if the stream reference is set it must not be changed!
+ }
+ catch( const embed::InvalidStorageException& )
+ {
+ TOOLS_INFO_EXCEPTION("package.xstor", "Rethrow:");
+ throw;
+ }
+ catch( const lang::IllegalArgumentException& )
+ {
+ TOOLS_INFO_EXCEPTION("package.xstor", "Rethrow:");
+ throw;
+ }
+ catch( const packages::WrongPasswordException& )
+ {
+ TOOLS_INFO_EXCEPTION("package.xstor", "Rethrow:");
+ throw;
+ }
+ catch( const io::IOException& )
+ {
+ TOOLS_INFO_EXCEPTION("package.xstor", "Rethrow:");
+ throw;
+ }
+ catch( const embed::StorageWrappedTargetException& )
+ {
+ TOOLS_INFO_EXCEPTION("package.xstor", "Rethrow:");
+ throw;
+ }
+ catch( const uno::RuntimeException& )
+ {
+ TOOLS_INFO_EXCEPTION("package.xstor", "Rethrow:");
+ throw;
+ }
+ catch( const uno::Exception& )
+ {
+ uno::Any aCaught( ::cppu::getCaughtException() );
+ SAL_INFO("package.xstor", "Rethrow: " << exceptionToString(aCaught));
+
+ throw embed::StorageWrappedTargetException( THROW_WHERE "Can't copy stream data!",
+ uno::Reference< io::XInputStream >(),
+ aCaught );
+ }
+
+}
+
+// XHierarchicalStorageAccess
+uno::Reference< embed::XExtendedStorageStream > SAL_CALL OStorage::openStreamElementByHierarchicalName( const OUString& aStreamPath, ::sal_Int32 nOpenMode )
+{
+ ::osl::MutexGuard aGuard( m_xSharedMutex->GetMutex() );
+
+ if ( !m_pImpl )
+ {
+ SAL_INFO("package.xstor", THROW_WHERE "Disposed!");
+ throw lang::DisposedException( THROW_WHERE );
+ }
+
+ if ( aStreamPath.isEmpty() || !::comphelper::OStorageHelper::IsValidZipEntryFileName( aStreamPath, true ) )
+ throw lang::IllegalArgumentException( THROW_WHERE "Unexpected entry name syntax.", uno::Reference< uno::XInterface >(), 1 );
+
+ if ( !( m_pImpl->m_nStorageMode & embed::ElementModes::WRITE )
+ && ( nOpenMode & embed::ElementModes::WRITE ) )
+ throw io::IOException( THROW_WHERE ); // Access denied
+
+ std::vector<OUString> aListPath = OHierarchyHolder_Impl::GetListPathFromString( aStreamPath );
+ OSL_ENSURE( aListPath.size(), "The result list must not be empty!" );
+
+ uno::Reference< embed::XExtendedStorageStream > xResult;
+ if ( aListPath.size() == 1 )
+ {
+ try
+ {
+ // that must be a direct request for a stream
+ // the transacted version of the stream should be opened
+
+ SotElement_Impl *pElement = OpenStreamElement_Impl( aStreamPath, nOpenMode, false );
+ assert(pElement && pElement->m_xStream && "In case element can not be created an exception must be thrown!");
+
+ xResult.set(pElement->m_xStream->GetStream(nOpenMode, true),
+ uno::UNO_QUERY_THROW);
+ }
+ catch ( const container::NoSuchElementException & )
+ {
+ throw io::IOException( THROW_WHERE ); // file not found
+ }
+ }
+ else
+ {
+ // there are still storages in between
+ if ( !m_rHierarchyHolder.is() )
+ m_rHierarchyHolder = new OHierarchyHolder_Impl(
+ uno::Reference< embed::XStorage >( static_cast< embed::XStorage* >( this ) ) );
+
+ xResult = m_rHierarchyHolder->GetStreamHierarchically(
+ ( m_pImpl->m_nStorageMode & embed::ElementModes::READWRITE ),
+ aListPath,
+ nOpenMode );
+ }
+
+ if ( !xResult.is() )
+ throw uno::RuntimeException( THROW_WHERE );
+
+ return xResult;
+}
+
+uno::Reference< embed::XExtendedStorageStream > SAL_CALL OStorage::openEncryptedStreamElementByHierarchicalName( const OUString& aStreamPath, ::sal_Int32 nOpenMode, const OUString& sPassword )
+{
+ return openEncryptedStreamByHierarchicalName( aStreamPath, nOpenMode, ::comphelper::OStorageHelper::CreatePackageEncryptionData( sPassword ) );
+}
+
+void SAL_CALL OStorage::removeStreamElementByHierarchicalName( const OUString& aStreamPath )
+{
+ ::osl::MutexGuard aGuard( m_xSharedMutex->GetMutex() );
+
+ if ( !m_pImpl )
+ {
+ SAL_INFO("package.xstor", THROW_WHERE "Disposed!");
+ throw lang::DisposedException( THROW_WHERE );
+ }
+
+ if ( aStreamPath.isEmpty() || !::comphelper::OStorageHelper::IsValidZipEntryFileName( aStreamPath, true ) )
+ throw lang::IllegalArgumentException( THROW_WHERE "Unexpected entry name syntax.", uno::Reference< uno::XInterface >(), 1 );
+
+ if ( !( m_pImpl->m_nStorageMode & embed::ElementModes::WRITE ) )
+ throw io::IOException( THROW_WHERE ); // Access denied
+
+ std::vector<OUString> aListPath = OHierarchyHolder_Impl::GetListPathFromString( aStreamPath );
+ OSL_ENSURE( aListPath.size(), "The result list must not be empty!" );
+
+ if ( !m_rHierarchyHolder.is() )
+ m_rHierarchyHolder = new OHierarchyHolder_Impl(
+ uno::Reference< embed::XStorage >( static_cast< embed::XStorage* >( this ) ) );
+
+ m_rHierarchyHolder->RemoveStreamHierarchically( aListPath );
+}
+
+// XHierarchicalStorageAccess2
+uno::Reference< embed::XExtendedStorageStream > SAL_CALL OStorage::openEncryptedStreamByHierarchicalName( const OUString& aStreamPath, ::sal_Int32 nOpenMode, const uno::Sequence< beans::NamedValue >& aEncryptionData )
+{
+ ::osl::MutexGuard aGuard( m_xSharedMutex->GetMutex() );
+
+ if ( !m_pImpl )
+ {
+ SAL_INFO("package.xstor", THROW_WHERE "Disposed!");
+ throw lang::DisposedException( THROW_WHERE );
+ }
+
+ if ( m_pImpl->m_nStorageType != embed::StorageFormats::PACKAGE )
+ throw packages::NoEncryptionException( THROW_WHERE );
+
+ if ( aStreamPath.isEmpty() || !::comphelper::OStorageHelper::IsValidZipEntryFileName( aStreamPath, true ) )
+ throw lang::IllegalArgumentException( THROW_WHERE "Unexpected entry name syntax.", uno::Reference< uno::XInterface >(), 1 );
+
+ if ( !aEncryptionData.hasElements() )
+ throw lang::IllegalArgumentException( THROW_WHERE, uno::Reference< uno::XInterface >(), 3 );
+
+ if ( !( m_pImpl->m_nStorageMode & embed::ElementModes::WRITE )
+ && ( nOpenMode & embed::ElementModes::WRITE ) )
+ throw io::IOException( THROW_WHERE ); // Access denied
+
+ std::vector<OUString> aListPath = OHierarchyHolder_Impl::GetListPathFromString( aStreamPath );
+ OSL_ENSURE( aListPath.size(), "The result list must not be empty!" );
+
+ uno::Reference< embed::XExtendedStorageStream > xResult;
+ if ( aListPath.size() == 1 )
+ {
+ // that must be a direct request for a stream
+ // the transacted version of the stream should be opened
+
+ SotElement_Impl *pElement = OpenStreamElement_Impl( aStreamPath, nOpenMode, true );
+ OSL_ENSURE(pElement && pElement->m_xStream, "In case element can not be created an exception must be thrown!");
+
+ xResult.set(pElement->m_xStream->GetStream(nOpenMode, aEncryptionData, true),
+ uno::UNO_QUERY_THROW);
+ }
+ else
+ {
+ // there are still storages in between
+ if ( !m_rHierarchyHolder.is() )
+ m_rHierarchyHolder = new OHierarchyHolder_Impl(
+ uno::Reference< embed::XStorage >( static_cast< embed::XStorage* >( this ) ) );
+
+ xResult = m_rHierarchyHolder->GetStreamHierarchically(
+ ( m_pImpl->m_nStorageMode & embed::ElementModes::READWRITE ),
+ aListPath,
+ nOpenMode,
+ aEncryptionData );
+ }
+
+ if ( !xResult.is() )
+ throw uno::RuntimeException( THROW_WHERE );
+
+ return xResult;
+}
+
+/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
diff --git a/package/source/xstor/xstorage.hxx b/package/source/xstor/xstorage.hxx
new file mode 100644
index 000000000..35a80e717
--- /dev/null
+++ b/package/source/xstor/xstorage.hxx
@@ -0,0 +1,538 @@
+/* -*- 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 .
+ */
+
+#ifndef INCLUDED_PACKAGE_SOURCE_XSTOR_XSTORAGE_HXX
+#define INCLUDED_PACKAGE_SOURCE_XSTOR_XSTORAGE_HXX
+
+#include <com/sun/star/uno/Sequence.hxx>
+#include <com/sun/star/embed/XStorage2.hpp>
+#include <com/sun/star/embed/XOptimizedStorage.hpp>
+#include <com/sun/star/embed/XHierarchicalStorageAccess2.hpp>
+#include <com/sun/star/embed/XStorageRawAccess.hpp>
+#include <com/sun/star/embed/XTransactedObject.hpp>
+#include <com/sun/star/embed/XTransactionBroadcaster.hpp>
+#include <com/sun/star/embed/XEncryptionProtectedStorage.hpp>
+#include <com/sun/star/embed/XRelationshipAccess.hpp>
+#include <com/sun/star/util/XModifiable.hpp>
+#include <com/sun/star/container/XNameContainer.hpp>
+#include <com/sun/star/beans/XPropertySet.hpp>
+#include <com/sun/star/beans/PropertyValue.hpp>
+#include <com/sun/star/beans/StringPair.hpp>
+#include <com/sun/star/io/XStream.hpp>
+#include <com/sun/star/lang/XSingleServiceFactory.hpp>
+#include <com/sun/star/lang/XTypeProvider.hpp>
+#include <com/sun/star/lang/XComponent.hpp>
+
+#include <cppuhelper/typeprovider.hxx>
+#include <cppuhelper/weak.hxx>
+#include <cppuhelper/weakref.hxx>
+#include <comphelper/multicontainer2.hxx>
+#include <comphelper/refcountedmutex.hxx>
+#include <comphelper/sequenceashashmap.hxx>
+#include <o3tl/deleter.hxx>
+#include <rtl/ref.hxx>
+
+#include "ohierarchyholder.hxx"
+#include "disposelistener.hxx"
+
+#include <vector>
+#include <memory>
+#include <string_view>
+
+namespace com::sun::star::uno {
+ class XComponentContext;
+}
+
+#define RELINFO_NO_INIT 1
+#define RELINFO_READ 2
+#define RELINFO_CHANGED 3
+#define RELINFO_CHANGED_STREAM 4
+#define RELINFO_CHANGED_STREAM_READ 5
+#define RELINFO_BROKEN 6
+#define RELINFO_CHANGED_BROKEN 7
+
+#define STOR_MESS_PRECOMMIT 1
+#define STOR_MESS_COMMITTED 2
+#define STOR_MESS_PREREVERT 3
+#define STOR_MESS_REVERTED 4
+
+// a common implementation for an entry
+
+struct OStorage_Impl;
+struct OWriteStream_Impl;
+
+struct SotElement_Impl
+{
+ OUString m_aOriginalName;
+ bool m_bIsRemoved;
+ bool m_bIsInserted;
+ bool m_bIsStorage;
+
+ std::unique_ptr<OStorage_Impl> m_xStorage;
+ std::unique_ptr<OWriteStream_Impl, o3tl::default_delete<OWriteStream_Impl>> m_xStream;
+
+public:
+ SotElement_Impl(const OUString& rName, bool bStor, bool bNew);
+};
+
+// Main storage implementation
+
+class OStorage;
+
+struct StorageHolder_Impl
+{
+ OStorage* m_pPointer;
+ css::uno::WeakReference< css::embed::XStorage > m_xWeakRef;
+
+ explicit inline StorageHolder_Impl( OStorage* pStorage );
+};
+
+class SwitchablePersistenceStream;
+struct OStorage_Impl
+{
+ typedef std::vector<StorageHolder_Impl> StorageHoldersType;
+
+ rtl::Reference<comphelper::RefCountedMutex> m_xMutex;
+
+ OStorage* m_pAntiImpl; // only valid if external references exists
+ StorageHoldersType m_aReadOnlyWrapVector; // only valid if readonly external reference exists
+
+ sal_Int32 m_nStorageMode; // open mode ( read/write/trunc/nocreate )
+ bool m_bIsModified; // only modified elements will be sent to the original content
+ bool m_bBroadcastModified; // will be set if notification is required
+
+ bool m_bCommited; // sending the streams is coordinated by the root storage of the package
+
+ bool m_bIsRoot; // marks this storage as root storages that manages all commits and reverts
+ bool m_bListCreated;
+
+ /// Count of registered modification listeners
+ oslInterlockedCount m_nModifiedListenerCount;
+ bool HasModifiedListener() const
+ {
+ return m_nModifiedListenerCount > 0 && m_pAntiImpl != nullptr;
+ }
+
+ std::unordered_map<OUString, std::vector<SotElement_Impl*>> m_aChildrenMap;
+ std::vector< SotElement_Impl* > m_aDeletedVector;
+
+ css::uno::Reference< css::container::XNameContainer > m_xPackageFolder;
+
+ css::uno::Reference< css::lang::XSingleServiceFactory > m_xPackage;
+ css::uno::Reference< css::uno::XComponentContext > m_xContext;
+
+ // valid only for root storage
+ css::uno::Reference< css::io::XInputStream > m_xInputStream; // ??? may be stored in properties
+ css::uno::Reference< css::io::XStream > m_xStream; // ??? may be stored in properties
+ css::uno::Sequence< css::beans::PropertyValue > m_xProperties;
+ bool m_bHasCommonEncryptionData;
+ ::comphelper::SequenceAsHashMap m_aCommonEncryptionData;
+
+ // must be empty in case of root storage
+ OStorage_Impl* m_pParent;
+
+ bool m_bControlMediaType;
+ OUString m_aMediaType;
+ bool m_bMTFallbackUsed;
+
+ bool m_bControlVersion;
+ OUString m_aVersion;
+
+ rtl::Reference<SwitchablePersistenceStream> m_pSwitchStream;
+
+ sal_Int32 m_nStorageType; // the mode in which the storage is used
+
+ // the _rels substorage that is handled in a special way in embed::StorageFormats::OFOPXML
+ SotElement_Impl* m_pRelStorElement;
+ css::uno::Reference< css::embed::XStorage > m_xRelStorage;
+ css::uno::Sequence< css::uno::Sequence< css::beans::StringPair > > m_aRelInfo;
+ css::uno::Reference< css::io::XInputStream > m_xNewRelInfoStream;
+ sal_Int16 m_nRelInfoStatus;
+
+ // Constructors
+ OStorage_Impl( css::uno::Reference< css::io::XInputStream > const & xInputStream,
+ sal_Int32 nMode,
+ const css::uno::Sequence< css::beans::PropertyValue >& xProperties,
+ css::uno::Reference< css::uno::XComponentContext > const & xContext,
+ sal_Int32 nStorageType );
+
+ OStorage_Impl( css::uno::Reference< css::io::XStream > const & xStream,
+ sal_Int32 nMode,
+ const css::uno::Sequence< css::beans::PropertyValue >& xProperties,
+ css::uno::Reference< css::uno::XComponentContext > const & xContext,
+ sal_Int32 nStorageType );
+
+ // constructor for a substorage
+ OStorage_Impl( OStorage_Impl* pParent,
+ sal_Int32 nMode,
+ css::uno::Reference< css::container::XNameContainer > const & xPackageFolder,
+ css::uno::Reference< css::lang::XSingleServiceFactory > const & xPackage,
+ css::uno::Reference< css::uno::XComponentContext > const & xContext,
+ sal_Int32 nStorageType );
+
+ ~OStorage_Impl();
+
+ void SetReadOnlyWrap( OStorage& aStorage );
+ void RemoveReadOnlyWrap( const OStorage& aStorage );
+
+ void OpenOwnPackage();
+ void ReadContents();
+ void ReadRelInfoIfNecessary();
+
+ bool HasChildren();
+ void GetStorageProperties();
+
+ css::uno::Sequence< css::uno::Sequence< css::beans::StringPair > > GetAllRelationshipsIfAny();
+ void CopyLastCommitTo( const css::uno::Reference< css::embed::XStorage >& xNewStor );
+
+ void InsertIntoPackageFolder(
+ const OUString& aName,
+ const css::uno::Reference< css::container::XNameContainer >& xParentPackageFolder );
+
+ void Commit();
+ void Revert();
+
+ /// @throws css::packages::NoEncryptionException
+ ::comphelper::SequenceAsHashMap GetCommonRootEncryptionData();
+
+ void CopyToStorage( const css::uno::Reference< css::embed::XStorage >& xDest,
+ bool bDirect );
+ void CopyStorageElement( SotElement_Impl* pElement,
+ const css::uno::Reference< css::embed::XStorage >& xDest,
+ const OUString& aName,
+ bool bDirect );
+
+ SotElement_Impl* FindElement( const OUString& rName );
+
+ SotElement_Impl* InsertStream( const OUString& aName, bool bEncr );
+ void InsertRawStream( const OUString& aName, const css::uno::Reference< css::io::XInputStream >& xInStream );
+
+ std::unique_ptr<OStorage_Impl> CreateNewStorageImpl( sal_Int32 nStorageMode );
+ SotElement_Impl* InsertStorage( const OUString& aName, sal_Int32 nStorageMode );
+ SotElement_Impl* InsertElement( const OUString& aName, bool bIsStorage );
+
+ void OpenSubStorage( SotElement_Impl* pElement, sal_Int32 nStorageMode );
+ void OpenSubStream( SotElement_Impl* pElement );
+
+ css::uno::Sequence< OUString > GetElementNames();
+
+ void RemoveElement( OUString const & rName, SotElement_Impl* pElement );
+ static void ClearElement( SotElement_Impl* pElement );
+
+ /// @throws css::embed::InvalidStorageException
+ /// @throws css::lang::IllegalArgumentException
+ /// @throws css::packages::WrongPasswordException
+ /// @throws css::packages::NoEncryptionException
+ /// @throws css::container::NoSuchElementException
+ /// @throws css::io::IOException
+ /// @throws css::embed::StorageWrappedTargetException
+ /// @throws css::uno::RuntimeException
+ void CloneStreamElement(
+ const OUString& aStreamName,
+ bool bPassProvided,
+ const ::comphelper::SequenceAsHashMap& aEncryptionData,
+ css::uno::Reference< css::io::XStream >& xTargetStream );
+
+ void RemoveStreamRelInfo( std::u16string_view aOriginalName );
+ void CreateRelStorage();
+ void CommitStreamRelInfo( std::u16string_view rName, SotElement_Impl const * pStreamElement );
+ css::uno::Reference< css::io::XInputStream > GetRelInfoStreamForName(
+ std::u16string_view aName );
+ void CommitRelInfo( const css::uno::Reference< css::container::XNameContainer >& xNewPackageFolder );
+
+ static void completeStorageStreamCopy_Impl(
+ const css::uno::Reference< css::io::XStream >& xSource,
+ const css::uno::Reference< css::io::XStream >& xDest,
+ sal_Int32 nStorageType,
+ const css::uno::Sequence< css::uno::Sequence< css::beans::StringPair > >& aRelInfo );
+
+};
+
+class OStorage final : public css::lang::XTypeProvider
+ , public css::embed::XStorage2
+ , public css::embed::XStorageRawAccess
+ , public css::embed::XTransactedObject
+ , public css::embed::XTransactionBroadcaster
+ , public css::util::XModifiable
+ , public css::embed::XEncryptionProtectedStorage
+ , public css::beans::XPropertySet
+ , public css::embed::XOptimizedStorage
+ , public css::embed::XRelationshipAccess
+ , public css::embed::XHierarchicalStorageAccess2
+ , public ::cppu::OWeakObject
+{
+ OStorage_Impl* m_pImpl;
+ rtl::Reference<comphelper::RefCountedMutex> m_xSharedMutex;
+ comphelper::OMultiTypeInterfaceContainerHelper2 m_aListenersContainer; // list of listeners
+ ::std::unique_ptr< ::cppu::OTypeCollection> m_pTypeCollection;
+ bool m_bReadOnlyWrap;
+ ::rtl::Reference<OChildDispListener_Impl> m_pSubElDispListener;
+ ::std::vector< css::uno::WeakReference< css::lang::XComponent > > m_aOpenSubComponentsVector;
+ ::rtl::Reference< OHierarchyHolder_Impl > m_rHierarchyHolder;
+
+ SotElement_Impl* OpenStreamElement_Impl( const OUString& aStreamName, sal_Int32 nOpenMode, bool bEncr );
+
+ void BroadcastModifiedIfNecessary();
+
+ void BroadcastTransaction( sal_Int8 nMessage );
+
+ void MakeLinkToSubComponent_Impl(
+ const css::uno::Reference< css::lang::XComponent >& xComponent );
+
+public:
+
+ OStorage( css::uno::Reference< css::io::XInputStream > const & xInputStream,
+ sal_Int32 nMode,
+ const css::uno::Sequence< css::beans::PropertyValue >& xProperties,
+ css::uno::Reference< css::uno::XComponentContext > const & xContext,
+ sal_Int32 nStorageType );
+
+ OStorage( css::uno::Reference< css::io::XStream > const & xStream,
+ sal_Int32 nMode,
+ const css::uno::Sequence< css::beans::PropertyValue >& xProperties,
+ css::uno::Reference< css::uno::XComponentContext > const & xContext,
+ sal_Int32 nStorageType );
+
+ OStorage( OStorage_Impl* pImpl, bool bReadOnlyWrap );
+
+ virtual ~OStorage() override;
+
+ void InternalDispose( bool bNotifyImpl );
+
+ void ChildIsDisposed( const css::uno::Reference< css::uno::XInterface >& xChild );
+
+ sal_Int32 GetRefCount_Impl() const { return m_refCount; }
+
+ // XInterface
+
+ virtual css::uno::Any SAL_CALL queryInterface( const css::uno::Type& rType ) override;
+
+ virtual void SAL_CALL acquire() noexcept override;
+
+ virtual void SAL_CALL release() noexcept override;
+
+ // XTypeProvider
+
+ virtual css::uno::Sequence< css::uno::Type > SAL_CALL getTypes() override;
+
+ virtual css::uno::Sequence< sal_Int8 > SAL_CALL getImplementationId() override;
+
+ // XStorage
+
+ virtual void SAL_CALL copyToStorage( const css::uno::Reference< css::embed::XStorage >& xDest ) override;
+
+ virtual css::uno::Reference< css::io::XStream > SAL_CALL openStreamElement(
+ const OUString& aStreamName, sal_Int32 nOpenMode ) override;
+
+ virtual css::uno::Reference< css::io::XStream > SAL_CALL openEncryptedStreamElement(
+ const OUString& aStreamName, sal_Int32 nOpenMode, const OUString& aPass ) override;
+
+ virtual css::uno::Reference< css::embed::XStorage > SAL_CALL openStorageElement(
+ const OUString& aStorName, sal_Int32 nStorageMode ) override;
+
+ virtual css::uno::Reference< css::io::XStream > SAL_CALL cloneStreamElement(
+ const OUString& aStreamName ) override;
+
+ virtual css::uno::Reference< css::io::XStream > SAL_CALL cloneEncryptedStreamElement(
+ const OUString& aStreamName, const OUString& aPass ) override;
+
+ virtual void SAL_CALL copyLastCommitTo(
+ const css::uno::Reference< css::embed::XStorage >& xTargetStorage ) override;
+
+ virtual void SAL_CALL copyStorageElementLastCommitTo(
+ const OUString& aStorName,
+ const css::uno::Reference< css::embed::XStorage >& xTargetStorage ) override;
+
+ virtual sal_Bool SAL_CALL isStreamElement( const OUString& aElementName ) override;
+
+ virtual sal_Bool SAL_CALL isStorageElement( const OUString& aElementName ) override;
+
+ virtual void SAL_CALL removeElement( const OUString& aElementName ) override;
+
+ virtual void SAL_CALL renameElement( const OUString& rEleName, const OUString& rNewName ) override;
+
+ virtual void SAL_CALL copyElementTo( const OUString& aElementName,
+ const css::uno::Reference< css::embed::XStorage >& xDest,
+ const OUString& aNewName ) override;
+
+ virtual void SAL_CALL moveElementTo( const OUString& aElementName,
+ const css::uno::Reference< css::embed::XStorage >& xDest,
+ const OUString& rNewName ) override;
+
+ // XStorage2
+
+ virtual css::uno::Reference< css::io::XStream > SAL_CALL openEncryptedStream( const OUString& sStreamName, ::sal_Int32 nOpenMode, const css::uno::Sequence< css::beans::NamedValue >& aEncryptionData ) override;
+
+ virtual css::uno::Reference< css::io::XStream > SAL_CALL cloneEncryptedStream( const OUString& sStreamName, const css::uno::Sequence< css::beans::NamedValue >& aEncryptionData ) override;
+
+ // XStorageRawAccess
+
+ virtual css::uno::Reference< css::io::XInputStream > SAL_CALL getPlainRawStreamElement(
+ const OUString& sStreamName ) override;
+
+ virtual css::uno::Reference< css::io::XInputStream > SAL_CALL getRawEncrStreamElement(
+ const OUString& sStreamName ) override;
+
+ virtual void SAL_CALL insertRawEncrStreamElement( const OUString& aStreamName,
+ const css::uno::Reference< css::io::XInputStream >& xInStream ) override;
+
+ // XTransactedObject
+ virtual void SAL_CALL commit() override;
+
+ virtual void SAL_CALL revert() override;
+
+ // XTransactionBroadcaster
+ virtual void SAL_CALL addTransactionListener(
+ const css::uno::Reference< css::embed::XTransactionListener >& aListener ) override;
+
+ virtual void SAL_CALL removeTransactionListener(
+ const css::uno::Reference< css::embed::XTransactionListener >& aListener ) override;
+
+ // XModifiable
+
+ virtual sal_Bool SAL_CALL isModified() override;
+
+ virtual void SAL_CALL setModified( sal_Bool bModified ) override;
+
+ virtual void SAL_CALL addModifyListener(
+ const css::uno::Reference< css::util::XModifyListener >& aListener ) override;
+
+ virtual void SAL_CALL removeModifyListener(
+ const css::uno::Reference< css::util::XModifyListener >& aListener ) override;
+
+ // XNameAccess
+
+ virtual css::uno::Any SAL_CALL getByName( const OUString& aName ) override;
+
+ virtual css::uno::Sequence< OUString > SAL_CALL getElementNames() override;
+
+ virtual sal_Bool SAL_CALL hasByName( const OUString& aName ) override;
+
+ virtual css::uno::Type SAL_CALL getElementType() override;
+
+ virtual sal_Bool SAL_CALL hasElements() override;
+
+ // XComponent
+
+ virtual void SAL_CALL dispose() override;
+
+ virtual void SAL_CALL addEventListener(
+ const css::uno::Reference< css::lang::XEventListener >& xListener ) override;
+
+ virtual void SAL_CALL removeEventListener(
+ const css::uno::Reference< css::lang::XEventListener >& xListener ) override;
+
+ // XEncryptionProtectedSource
+
+ virtual void SAL_CALL setEncryptionPassword( const OUString& aPass ) override;
+
+ virtual void SAL_CALL removeEncryption() override;
+
+ // XEncryptionProtectedSource2
+
+ virtual void SAL_CALL setEncryptionData(
+ const css::uno::Sequence< css::beans::NamedValue >& aEncryptionData ) override;
+
+ virtual sal_Bool SAL_CALL hasEncryptionData() override;
+
+ // XEncryptionProtectedStorage
+
+ virtual void SAL_CALL setEncryptionAlgorithms( const css::uno::Sequence< css::beans::NamedValue >& aAlgorithms ) override;
+ virtual void SAL_CALL setGpgProperties( const css::uno::Sequence< css::uno::Sequence< css::beans::NamedValue > >& aCryptProps ) override;
+
+ virtual css::uno::Sequence< css::beans::NamedValue > SAL_CALL getEncryptionAlgorithms() override;
+
+ // XPropertySet
+
+ virtual css::uno::Reference< css::beans::XPropertySetInfo > SAL_CALL getPropertySetInfo() override;
+
+ virtual void SAL_CALL setPropertyValue( const OUString& aPropertyName, const css::uno::Any& aValue ) override;
+
+ virtual css::uno::Any SAL_CALL getPropertyValue( const OUString& PropertyName ) override;
+
+ virtual void SAL_CALL addPropertyChangeListener(
+ const OUString& aPropertyName,
+ const css::uno::Reference< css::beans::XPropertyChangeListener >& xListener ) override;
+
+ virtual void SAL_CALL removePropertyChangeListener(
+ const OUString& aPropertyName,
+ const css::uno::Reference< css::beans::XPropertyChangeListener >& aListener ) override;
+
+ virtual void SAL_CALL addVetoableChangeListener(
+ const OUString& PropertyName,
+ const css::uno::Reference< css::beans::XVetoableChangeListener >& aListener ) override;
+
+ virtual void SAL_CALL removeVetoableChangeListener( const OUString& PropertyName, const css::uno::Reference< css::beans::XVetoableChangeListener >& aListener ) override;
+
+ // XOptimizedStorage
+ virtual void SAL_CALL insertRawNonEncrStreamElementDirect( const OUString& sStreamName, const css::uno::Reference< css::io::XInputStream >& xInStream ) override;
+
+ virtual void SAL_CALL insertStreamElementDirect( const OUString& sStreamName, const css::uno::Reference< css::io::XInputStream >& xInStream, const css::uno::Sequence< css::beans::PropertyValue >& aProps ) override;
+
+ virtual void SAL_CALL copyElementDirectlyTo( const OUString& sSourceName, const css::uno::Reference< css::embed::XOptimizedStorage >& xTargetStorage, const OUString& sTargetName ) override;
+
+ virtual void SAL_CALL writeAndAttachToStream( const css::uno::Reference< css::io::XStream >& xStream ) override;
+
+ virtual void SAL_CALL attachToURL( const OUString& sURL, sal_Bool bReadOnly ) override;
+
+ virtual css::uno::Any SAL_CALL getElementPropertyValue( const OUString& sElementName, const OUString& sPropertyName ) override;
+
+ virtual void SAL_CALL copyStreamElementData( const OUString& sStreamName, const css::uno::Reference< css::io::XStream >& xTargetStream ) override;
+
+ // XRelationshipAccess
+ virtual sal_Bool SAL_CALL hasByID( const OUString& sID ) override;
+
+ virtual OUString SAL_CALL getTargetByID( const OUString& sID ) override;
+
+ virtual OUString SAL_CALL getTypeByID( const OUString& sID ) override;
+
+ virtual css::uno::Sequence< css::beans::StringPair > SAL_CALL getRelationshipByID( const OUString& sID ) override;
+
+ virtual css::uno::Sequence< css::uno::Sequence< css::beans::StringPair > > SAL_CALL getRelationshipsByType( const OUString& sType ) override;
+
+ virtual css::uno::Sequence< css::uno::Sequence< css::beans::StringPair > > SAL_CALL getAllRelationships( ) override;
+
+ virtual void SAL_CALL insertRelationshipByID( const OUString& sID, const css::uno::Sequence< css::beans::StringPair >& aEntry, sal_Bool bReplace ) override;
+
+ virtual void SAL_CALL removeRelationshipByID( const OUString& sID ) override;
+
+ virtual void SAL_CALL insertRelationships( const css::uno::Sequence< css::uno::Sequence< css::beans::StringPair > >& aEntries, sal_Bool bReplace ) override;
+
+ virtual void SAL_CALL clearRelationships( ) override;
+
+ // XHierarchicalStorageAccess
+ virtual css::uno::Reference< css::embed::XExtendedStorageStream > SAL_CALL openStreamElementByHierarchicalName( const OUString& sStreamPath, ::sal_Int32 nOpenMode ) override;
+
+ virtual css::uno::Reference< css::embed::XExtendedStorageStream > SAL_CALL openEncryptedStreamElementByHierarchicalName( const OUString& sStreamName, ::sal_Int32 nOpenMode, const OUString& sPassword ) override;
+
+ virtual void SAL_CALL removeStreamElementByHierarchicalName( const OUString& sElementPath ) override;
+
+ // XHierarchicalStorageAccess2
+ virtual css::uno::Reference< css::embed::XExtendedStorageStream > SAL_CALL openEncryptedStreamByHierarchicalName( const OUString& sStreamName, ::sal_Int32 nOpenMode, const css::uno::Sequence< css::beans::NamedValue >& aEncryptionData ) override;
+};
+
+StorageHolder_Impl::StorageHolder_Impl( OStorage* pStorage )
+: m_pPointer( pStorage )
+, m_xWeakRef( css::uno::Reference< css::embed::XStorage >( pStorage ) )
+{
+}
+
+#endif
+
+/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
diff --git a/package/source/zipapi/ByteChucker.cxx b/package/source/zipapi/ByteChucker.cxx
new file mode 100644
index 000000000..6c5994aa6
--- /dev/null
+++ b/package/source/zipapi/ByteChucker.cxx
@@ -0,0 +1,51 @@
+/* -*- 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 <ByteChucker.hxx>
+#include <com/sun/star/io/XSeekable.hpp>
+#include <com/sun/star/io/XOutputStream.hpp>
+
+using namespace ::com::sun::star::io;
+using namespace ::com::sun::star::uno;
+
+ByteChucker::ByteChucker(Reference<XOutputStream> const & xOstream)
+: xStream(xOstream)
+, xSeek (xOstream, UNO_QUERY )
+, a2Sequence ( 2 )
+, a4Sequence ( 4 )
+, p2Sequence ( a2Sequence.getArray() )
+, p4Sequence ( a4Sequence.getArray() )
+{
+}
+
+ByteChucker::~ByteChucker()
+{
+}
+
+void ByteChucker::WriteBytes( const Sequence< sal_Int8 >& aData )
+{
+ xStream->writeBytes(aData);
+}
+
+sal_Int64 ByteChucker::GetPosition( )
+{
+ return xSeek->getPosition();
+}
+
+/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
diff --git a/package/source/zipapi/ByteGrabber.cxx b/package/source/zipapi/ByteGrabber.cxx
new file mode 100644
index 000000000..b58a7087f
--- /dev/null
+++ b/package/source/zipapi/ByteGrabber.cxx
@@ -0,0 +1,125 @@
+/* -*- 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 <ByteGrabber.hxx>
+#include <sal/log.hxx>
+#include <com/sun/star/io/IOException.hpp>
+#include <com/sun/star/io/XSeekable.hpp>
+#include <com/sun/star/io/XInputStream.hpp>
+#include <com/sun/star/lang/IllegalArgumentException.hpp>
+
+using namespace ::com::sun::star;
+
+#if OSL_DEBUG_LEVEL > 0
+#define THROW_WHERE SAL_WHERE
+#else
+#define THROW_WHERE ""
+#endif
+
+/** ByteGrabber implements the >> operators on an XOutputStream. This is
+ * potentially quite slow and may need to be optimised
+ */
+
+ByteGrabber::ByteGrabber(uno::Reference < io::XInputStream > const & xIstream)
+: xStream(xIstream)
+, xSeek (xIstream, uno::UNO_QUERY )
+, aSequence ( 4 )
+{
+ pSequence = aSequence.getArray();
+}
+
+ByteGrabber::~ByteGrabber()
+{
+}
+
+void ByteGrabber::setInputStream (const uno::Reference < io::XInputStream >& xNewStream)
+{
+ std::scoped_lock aGuard( m_aMutex );
+ xStream = xNewStream;
+ xSeek.set(xNewStream, uno::UNO_QUERY);
+}
+
+// XInputStream chained
+sal_Int32 ByteGrabber::readBytes( uno::Sequence< sal_Int8 >& aData,
+ sal_Int32 nBytesToRead )
+{
+ std::scoped_lock aGuard( m_aMutex );
+ return xStream->readBytes(aData, nBytesToRead );
+}
+
+// XSeekable chained...
+void ByteGrabber::seek( sal_Int64 location )
+{
+ std::scoped_lock aGuard( m_aMutex );
+ if (!xSeek.is() )
+ throw io::IOException(THROW_WHERE );
+
+ sal_Int64 nLen = xSeek->getLength();
+ if ( location < 0 || location > nLen )
+ throw lang::IllegalArgumentException(THROW_WHERE, uno::Reference< uno::XInterface >(), 1 );
+ xSeek->seek( location );
+}
+
+sal_Int64 ByteGrabber::getPosition( )
+{
+ std::scoped_lock aGuard( m_aMutex );
+ if (!xSeek.is() )
+ throw io::IOException(THROW_WHERE );
+
+ return xSeek->getPosition();
+}
+
+sal_Int64 ByteGrabber::getLength( )
+{
+ std::scoped_lock aGuard( m_aMutex );
+ if (!xSeek.is() )
+ throw io::IOException(THROW_WHERE );
+
+ return xSeek->getLength();
+}
+
+sal_uInt16 ByteGrabber::ReadUInt16()
+{
+ std::scoped_lock aGuard( m_aMutex );
+
+ if (xStream->readBytes(aSequence, 2) != 2)
+ return 0;
+
+ pSequence = aSequence.getConstArray();
+ return static_cast <sal_uInt16>
+ ( (pSequence[0] & 0xFF)
+ | (pSequence[1] & 0xFF) << 8);
+}
+
+sal_uInt32 ByteGrabber::ReadUInt32()
+{
+ std::scoped_lock aGuard( m_aMutex );
+
+ if (xStream->readBytes(aSequence, 4) != 4)
+ return 0;
+
+ pSequence = aSequence.getConstArray();
+ return static_cast < sal_uInt32 >
+ ( (pSequence[0] & 0xFF)
+ | ( pSequence[1] & 0xFF ) << 8
+ | ( pSequence[2] & 0xFF ) << 16
+ | ( pSequence[3] & 0xFF ) << 24 );
+}
+
+/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
diff --git a/package/source/zipapi/CRC32.cxx b/package/source/zipapi/CRC32.cxx
new file mode 100644
index 000000000..bd0682248
--- /dev/null
+++ b/package/source/zipapi/CRC32.cxx
@@ -0,0 +1,72 @@
+/* -*- 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 <CRC32.hxx>
+#include <PackageConstants.hxx>
+#include <rtl/crc.h>
+#include <com/sun/star/io/XInputStream.hpp>
+
+using namespace com::sun::star::uno;
+using namespace com::sun::star::io;
+
+/** A class to compute the CRC32 value of a data stream
+ */
+
+CRC32::CRC32()
+: nCRC(0)
+{
+}
+void CRC32::reset()
+{
+ nCRC=0;
+}
+sal_Int32 CRC32::getValue() const
+{
+ return nCRC;
+}
+/** Update CRC32 with specified sequence of bytes
+ */
+void CRC32::updateSegment(const Sequence< sal_Int8 > &b, sal_Int32 len)
+{
+ nCRC = rtl_crc32(nCRC, b.getConstArray(), len );
+}
+/** Update CRC32 with specified sequence of bytes
+ */
+void CRC32::update(const Sequence< sal_Int8 > &b)
+{
+ nCRC = rtl_crc32(nCRC, b.getConstArray(),b.getLength());
+}
+
+sal_Int64 CRC32::updateStream( Reference < XInputStream > const & xStream )
+{
+ sal_Int32 nLength;
+ sal_Int64 nTotal = 0;
+ Sequence < sal_Int8 > aSeq ( n_ConstBufferSize );
+ do
+ {
+ nLength = xStream->readBytes ( aSeq, n_ConstBufferSize );
+ updateSegment ( aSeq, nLength );
+ nTotal += nLength;
+ }
+ while ( nLength == n_ConstBufferSize );
+
+ return nTotal;
+}
+
+/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
diff --git a/package/source/zipapi/Deflater.cxx b/package/source/zipapi/Deflater.cxx
new file mode 100644
index 000000000..5c0fd7012
--- /dev/null
+++ b/package/source/zipapi/Deflater.cxx
@@ -0,0 +1,148 @@
+/* -*- 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 <package/Deflater.hxx>
+#include <zlib.h>
+#include <com/sun/star/packages/zip/ZipConstants.hpp>
+#include <osl/diagnose.h>
+#include <string.h>
+
+using namespace com::sun::star::packages::zip::ZipConstants;
+using namespace com::sun::star;
+using namespace ZipUtils;
+
+/** Provides general purpose compression using the ZLIB compression
+ * library.
+ */
+
+Deflater::~Deflater()
+{
+ end();
+}
+void Deflater::init (sal_Int32 nLevelArg, bool bNowrap)
+{
+ pStream.reset(new z_stream);
+ /* Memset it to 0...sets zalloc/zfree/opaque to NULL */
+ memset (pStream.get(), 0, sizeof(*pStream));
+
+ switch (deflateInit2(pStream.get(), nLevelArg, Z_DEFLATED, bNowrap? -MAX_WBITS : MAX_WBITS,
+ DEF_MEM_LEVEL, DEFAULT_STRATEGY))
+ {
+ case Z_OK:
+ break;
+ case Z_MEM_ERROR:
+ pStream.reset();
+ break;
+ case Z_STREAM_ERROR:
+ pStream.reset();
+ break;
+ default:
+ break;
+ }
+}
+
+Deflater::Deflater(sal_Int32 nSetLevel, bool bNowrap)
+: bFinish(false)
+, bFinished(false)
+, nOffset(0)
+, nLength(0)
+{
+ init(nSetLevel, bNowrap);
+}
+
+sal_Int32 Deflater::doDeflateBytes (uno::Sequence < sal_Int8 > &rBuffer, sal_Int32 nNewOffset, sal_Int32 nNewLength)
+{
+ sal_Int32 nResult;
+ pStream->next_in = reinterpret_cast<const unsigned char*>( sInBuffer.getConstArray() + nOffset );
+ pStream->next_out = reinterpret_cast<unsigned char*>(rBuffer.getArray())+nNewOffset;
+ pStream->avail_in = nLength;
+ pStream->avail_out = nNewLength;
+
+#if !defined Z_PREFIX
+ nResult = deflate(pStream.get(), bFinish ? Z_FINISH : Z_NO_FLUSH);
+#else
+ nResult = z_deflate(pStream.get(), bFinish ? Z_FINISH : Z_NO_FLUSH);
+#endif
+ switch (nResult)
+ {
+ case Z_STREAM_END:
+ bFinished = true;
+ [[fallthrough]];
+ case Z_OK:
+ nOffset += nLength - pStream->avail_in;
+ nLength = pStream->avail_in;
+ return nNewLength - pStream->avail_out;
+ default:
+ return 0;
+ }
+}
+
+void Deflater::setInputSegment( const uno::Sequence< sal_Int8 >& rBuffer )
+{
+ sInBuffer = rBuffer;
+ nOffset = 0;
+ nLength = rBuffer.getLength();
+}
+
+bool Deflater::needsInput() const
+{
+ return nLength <=0;
+}
+void Deflater::finish( )
+{
+ bFinish = true;
+}
+sal_Int32 Deflater::doDeflateSegment( uno::Sequence< sal_Int8 >& rBuffer, sal_Int32 nNewLength )
+{
+ OSL_ASSERT( !(nNewLength < 0 || nNewLength > rBuffer.getLength()));
+ return doDeflateBytes(rBuffer, /*nNewOffset*/0, nNewLength);
+}
+sal_Int64 Deflater::getTotalIn() const
+{
+ return pStream->total_in; // FIXME64: zlib doesn't look 64bit clean here
+}
+sal_Int64 Deflater::getTotalOut() const
+{
+ return pStream->total_out; // FIXME64: zlib doesn't look 64bit clean here
+}
+void Deflater::reset( )
+{
+#if !defined Z_PREFIX
+ deflateReset(pStream.get());
+#else
+ z_deflateReset(pStream.get());
+#endif
+ bFinish = false;
+ bFinished = false;
+ nOffset = nLength = 0;
+}
+void Deflater::end( )
+{
+ if (pStream)
+ {
+#if !defined Z_PREFIX
+ deflateEnd(pStream.get());
+#else
+ z_deflateEnd(pStream.get());
+#endif
+ pStream.reset();
+ }
+}
+
+/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
diff --git a/package/source/zipapi/Inflater.cxx b/package/source/zipapi/Inflater.cxx
new file mode 100644
index 000000000..d03fed8c0
--- /dev/null
+++ b/package/source/zipapi/Inflater.cxx
@@ -0,0 +1,137 @@
+/* -*- 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 <package/Inflater.hxx>
+#include <zlib.h>
+#include <string.h>
+
+using namespace com::sun::star::uno;
+using namespace ZipUtils;
+
+/** Provides general purpose decompression using the ZLIB library */
+
+Inflater::Inflater(bool bNoWrap)
+: bFinished(false),
+ bNeedDict(false),
+ nOffset(0),
+ nLength(0),
+ nLastInflateError(0)
+{
+ pStream.reset(new z_stream);
+ /* memset to 0 to set zalloc/opaque etc */
+ memset (pStream.get(), 0, sizeof(*pStream));
+ sal_Int32 nRes;
+ nRes = inflateInit2(pStream.get(), bNoWrap ? -MAX_WBITS : MAX_WBITS);
+ switch (nRes)
+ {
+ case Z_OK:
+ break;
+ case Z_MEM_ERROR:
+ pStream.reset();
+ break;
+ case Z_STREAM_ERROR:
+ pStream.reset();
+ break;
+ default:
+ break;
+ }
+}
+
+Inflater::~Inflater()
+{
+ end();
+}
+
+void Inflater::setInput( const Sequence< sal_Int8 >& rBuffer )
+{
+ sInBuffer = rBuffer;
+ nOffset = 0;
+ nLength = rBuffer.getLength();
+}
+
+
+sal_Int32 Inflater::doInflateSegment( Sequence< sal_Int8 >& rBuffer, sal_Int32 nNewOffset, sal_Int32 nNewLength )
+{
+ if (nNewOffset < 0 || nNewLength < 0 || nNewOffset + nNewLength > rBuffer.getLength())
+ {
+ // do error handling
+ }
+ return doInflateBytes(rBuffer, nNewOffset, nNewLength);
+}
+
+void Inflater::end( )
+{
+ if (pStream)
+ {
+#if !defined Z_PREFIX
+ inflateEnd(pStream.get());
+#else
+ z_inflateEnd(pStream.get());
+#endif
+ pStream.reset();
+ }
+}
+
+sal_Int32 Inflater::doInflateBytes (Sequence < sal_Int8 > &rBuffer, sal_Int32 nNewOffset, sal_Int32 nNewLength)
+{
+ if ( !pStream )
+ {
+ nLastInflateError = Z_STREAM_ERROR;
+ return 0;
+ }
+
+ nLastInflateError = 0;
+
+ pStream->next_in = reinterpret_cast<const unsigned char*>( sInBuffer.getConstArray() + nOffset );
+ pStream->avail_in = nLength;
+ pStream->next_out = reinterpret_cast < unsigned char* > ( rBuffer.getArray() + nNewOffset );
+ pStream->avail_out = nNewLength;
+
+#if !defined Z_PREFIX
+ sal_Int32 nResult = ::inflate(pStream.get(), Z_PARTIAL_FLUSH);
+#else
+ sal_Int32 nResult = ::z_inflate(pStream.get(), Z_PARTIAL_FLUSH);
+#endif
+
+ switch (nResult)
+ {
+ case Z_STREAM_END:
+ bFinished = true;
+ [[fallthrough]];
+ case Z_OK:
+ nOffset += nLength - pStream->avail_in;
+ nLength = pStream->avail_in;
+ return nNewLength - pStream->avail_out;
+
+ case Z_NEED_DICT:
+ bNeedDict = true;
+ nOffset += nLength - pStream->avail_in;
+ nLength = pStream->avail_in;
+ return 0;
+
+ default:
+ // it is no error, if there is no input or no output
+ if ( nLength && nNewLength )
+ nLastInflateError = nResult;
+ }
+
+ return 0;
+}
+
+/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
diff --git a/package/source/zipapi/MemoryByteGrabber.hxx b/package/source/zipapi/MemoryByteGrabber.hxx
new file mode 100644
index 000000000..8dcf7f067
--- /dev/null
+++ b/package/source/zipapi/MemoryByteGrabber.hxx
@@ -0,0 +1,88 @@
+/* -*- 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 .
+ */
+#ifndef INCLUDED_PACKAGE_SOURCE_ZIPAPI_MEMORYBYTEGRABBER_HXX
+#define INCLUDED_PACKAGE_SOURCE_ZIPAPI_MEMORYBYTEGRABBER_HXX
+
+#include <com/sun/star/uno/Sequence.h>
+
+class MemoryByteGrabber final
+{
+ const sal_Int8 *mpBuffer;
+ sal_Int32 mnCurrent, mnEnd;
+public:
+ MemoryByteGrabber ( const css::uno::Sequence < sal_Int8 > & rBuffer )
+ : mpBuffer ( rBuffer.getConstArray() )
+ , mnCurrent ( 0 )
+ , mnEnd ( rBuffer.getLength() )
+ {
+ }
+ MemoryByteGrabber(css::uno::Sequence<sal_Int8> &&) = delete;
+
+ const sal_Int8 * getCurrentPos () const { return mpBuffer + mnCurrent; }
+
+ sal_Int32 remainingSize() const { return mnEnd - mnCurrent; }
+
+ // XInputStream chained
+
+ /// @throws css::io::NotConnectedException
+ /// @throws css::io::BufferSizeExceededException
+ /// @throws css::io::IOException
+ /// @throws css::uno::RuntimeException
+ void skipBytes( sal_Int32 nBytesToSkip )
+ {
+ mnCurrent += nBytesToSkip;
+ }
+
+ // XSeekable chained...
+ sal_Int16 ReadInt16()
+ {
+ if (mnCurrent + 2 > mnEnd )
+ return 0;
+ sal_Int16 nInt16 = mpBuffer[mnCurrent++] & 0xFF;
+ nInt16 |= ( mpBuffer[mnCurrent++] & 0xFF ) << 8;
+ return nInt16;
+ }
+ sal_Int32 ReadInt32()
+ {
+ if (mnCurrent + 4 > mnEnd )
+ return 0;
+
+ sal_Int32 nInt32 = mpBuffer[mnCurrent++] & 0xFF;
+ nInt32 |= ( mpBuffer[mnCurrent++] & 0xFF ) << 8;
+ nInt32 |= ( mpBuffer[mnCurrent++] & 0xFF ) << 16;
+ nInt32 |= ( mpBuffer[mnCurrent++] & 0xFF ) << 24;
+ return nInt32;
+ }
+
+ sal_uInt32 ReadUInt32()
+ {
+ if (mnCurrent + 4 > mnEnd )
+ return 0;
+
+ sal_uInt32 nInt32 = mpBuffer [mnCurrent++] & 0xFF;
+ nInt32 |= ( mpBuffer [mnCurrent++] & 0xFF ) << 8;
+ nInt32 |= ( mpBuffer [mnCurrent++] & 0xFF ) << 16;
+ nInt32 |= ( mpBuffer [mnCurrent++] & 0xFF ) << 24;
+ return nInt32;
+ }
+};
+
+#endif
+
+/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
diff --git a/package/source/zipapi/ThreadedDeflater.cxx b/package/source/zipapi/ThreadedDeflater.cxx
new file mode 100644
index 000000000..f574105ad
--- /dev/null
+++ b/package/source/zipapi/ThreadedDeflater.cxx
@@ -0,0 +1,220 @@
+/* -*- 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 <ThreadedDeflater.hxx>
+#include <zlib.h>
+#include <com/sun/star/packages/zip/ZipConstants.hpp>
+#include <sal/log.hxx>
+
+using namespace com::sun::star::packages::zip::ZipConstants;
+using namespace com::sun::star;
+
+namespace ZipUtils
+{
+const sal_Int64 MaxBlockSize = 128 * 1024;
+
+// Parallel ZLIB compression using threads. The class internally splits the data into
+// blocks and spawns ThreadPool tasks to process them independently. This is achieved
+// in a similar way how pigz works, see comments from Mark Adler at
+// https://stackoverflow.com/questions/30294766/how-to-use-multiple-threads-for-zlib-compression
+// and
+// https://stackoverflow.com/questions/30794053/how-to-use-multiple-threads-for-zlib-compression-same-input-source
+
+// Everything here should be either read-only, or writing to distinct data, or atomic.
+
+class ThreadedDeflater::Task : public comphelper::ThreadTask
+{
+ z_stream stream;
+ ThreadedDeflater* deflater;
+ int sequence;
+ int blockSize;
+ bool firstTask : 1;
+ bool lastTask : 1;
+
+public:
+ Task(ThreadedDeflater* deflater_, int sequence_, int blockSize_, bool firstTask_,
+ bool lastTask_)
+ : comphelper::ThreadTask(deflater_->threadTaskTag)
+ , stream()
+ , deflater(deflater_)
+ , sequence(sequence_)
+ , blockSize(blockSize_)
+ , firstTask(firstTask_)
+ , lastTask(lastTask_)
+ {
+ }
+
+private:
+ virtual void doWork() override;
+};
+
+ThreadedDeflater::ThreadedDeflater(sal_Int32 nSetLevel)
+ : threadTaskTag(comphelper::ThreadPool::createThreadTaskTag())
+ , totalIn(0)
+ , totalOut(0)
+ , zlibLevel(nSetLevel)
+{
+}
+
+ThreadedDeflater::~ThreadedDeflater() COVERITY_NOEXCEPT_FALSE { clear(); }
+
+void ThreadedDeflater::deflateWrite(
+ const css::uno::Reference<css::io::XInputStream>& xInStream,
+ std::function<void(const css::uno::Sequence<sal_Int8>&, sal_Int32)> aProcessInputFunc,
+ std::function<void(const css::uno::Sequence<sal_Int8>&, sal_Int32)> aProcessOutputFunc)
+{
+ sal_Int64 nThreadCount = comphelper::ThreadPool::getSharedOptimalPool().getWorkerCount();
+ sal_Int64 batchSize = MaxBlockSize * nThreadCount;
+ inBuffer.realloc(batchSize);
+ prevDataBlock.realloc(MaxBlockSize);
+ outBuffers.resize(nThreadCount);
+ maProcessOutputFunc = aProcessOutputFunc;
+ bool firstTask = true;
+
+ while (xInStream->available() > 0)
+ {
+ sal_Int64 inputBytes = xInStream->readBytes(inBuffer, batchSize);
+ aProcessInputFunc(inBuffer, inputBytes);
+ totalIn += inputBytes;
+ int sequence = 0;
+ bool lastBatch = xInStream->available() <= 0;
+ sal_Int64 bytesPending = inputBytes;
+ while (bytesPending > 0)
+ {
+ sal_Int64 taskSize = std::min(MaxBlockSize, bytesPending);
+ bytesPending -= taskSize;
+ bool lastTask = lastBatch && !bytesPending;
+ comphelper::ThreadPool::getSharedOptimalPool().pushTask(
+ std::make_unique<Task>(this, sequence++, taskSize, firstTask, lastTask));
+
+ if (firstTask)
+ firstTask = false;
+ }
+
+ assert(bytesPending == 0);
+
+ comphelper::ThreadPool::getSharedOptimalPool().waitUntilDone(threadTaskTag);
+
+ if (!lastBatch)
+ {
+ assert(inputBytes == batchSize);
+ std::copy_n(std::cbegin(inBuffer) + (batchSize - MaxBlockSize), MaxBlockSize,
+ prevDataBlock.getArray());
+ }
+
+ processDeflatedBuffers();
+ }
+}
+
+void ThreadedDeflater::processDeflatedBuffers()
+{
+ sal_Int64 batchOutputSize = 0;
+ for (const auto& buffer : outBuffers)
+ batchOutputSize += buffer.size();
+
+ css::uno::Sequence<sal_Int8> outBuffer(batchOutputSize);
+
+ auto pos = outBuffer.getArray();
+ for (auto& buffer : outBuffers)
+ {
+ pos = std::copy(buffer.begin(), buffer.end(), pos);
+ buffer.clear();
+ }
+
+ maProcessOutputFunc(outBuffer, batchOutputSize);
+ totalOut += batchOutputSize;
+}
+
+void ThreadedDeflater::clear()
+{
+ inBuffer = uno::Sequence<sal_Int8>();
+ outBuffers.clear();
+}
+
+#if defined Z_PREFIX
+#define deflateInit2 z_deflateInit2
+#define deflateBound z_deflateBound
+#define deflateSetDictionary z_deflateSetDictionary
+#define deflate z_deflate
+#define deflateEnd z_deflateEnd
+#endif
+
+void ThreadedDeflater::Task::doWork()
+{
+ stream.zalloc = nullptr;
+ stream.zfree = nullptr;
+ stream.opaque = nullptr;
+ // -MAX_WBITS means 32k window size and raw stream
+ if (deflateInit2(&stream, deflater->zlibLevel, Z_DEFLATED, -MAX_WBITS, DEF_MEM_LEVEL,
+ Z_DEFAULT_STRATEGY)
+ != Z_OK)
+ {
+ SAL_WARN("package.threadeddeflate", "deflateInit2() failed");
+ abort();
+ }
+ // Find out size for our output buffer to be large enough for deflate() needing to be called just once.
+ sal_Int64 outputMaxSize = deflateBound(&stream, blockSize);
+ // add extra size for Z_SYNC_FLUSH
+ outputMaxSize += 20;
+ deflater->outBuffers[sequence].resize(outputMaxSize);
+ sal_Int64 myInBufferStart = sequence * MaxBlockSize;
+ // zlib doesn't handle const properly
+ unsigned char* inBufferPtr = reinterpret_cast<unsigned char*>(
+ const_cast<signed char*>(deflater->inBuffer.getConstArray()));
+ if (!firstTask)
+ {
+ // the window size is 32k, so set last 32k of previous data as the dictionary
+ assert(MAX_WBITS == 15);
+ assert(MaxBlockSize >= 32768);
+ if (sequence > 0)
+ {
+ deflateSetDictionary(&stream, inBufferPtr + myInBufferStart - 32768, 32768);
+ }
+ else
+ {
+ unsigned char* prevBufferPtr = reinterpret_cast<unsigned char*>(
+ const_cast<signed char*>(deflater->prevDataBlock.getConstArray()));
+ deflateSetDictionary(&stream, prevBufferPtr + MaxBlockSize - 32768, 32768);
+ }
+ }
+ stream.next_in = inBufferPtr + myInBufferStart;
+ stream.avail_in = blockSize;
+ stream.next_out = reinterpret_cast<unsigned char*>(deflater->outBuffers[sequence].data());
+ stream.avail_out = outputMaxSize;
+
+ // The trick is in using Z_SYNC_FLUSH instead of Z_NO_FLUSH. It will align the data at a byte boundary,
+ // and since we use a raw stream, the data blocks then can be simply concatenated.
+ int res = deflate(&stream, lastTask ? Z_FINISH : Z_SYNC_FLUSH);
+ assert(stream.avail_in == 0); // Check that everything has been deflated.
+ if (lastTask ? res == Z_STREAM_END : res == Z_OK)
+ { // ok
+ sal_Int64 outSize = outputMaxSize - stream.avail_out;
+ deflater->outBuffers[sequence].resize(outSize);
+ }
+ else
+ {
+ SAL_WARN("package.threadeddeflate", "deflate() failed");
+ abort();
+ }
+ deflateEnd(&stream);
+}
+
+} // namespace
+
+/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
diff --git a/package/source/zipapi/XBufferedThreadedStream.cxx b/package/source/zipapi/XBufferedThreadedStream.cxx
new file mode 100644
index 000000000..d3bf995d9
--- /dev/null
+++ b/package/source/zipapi/XBufferedThreadedStream.cxx
@@ -0,0 +1,189 @@
+/* -*- 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/.
+ */
+
+#include "XBufferedThreadedStream.hxx"
+
+using namespace css::uno;
+
+namespace {
+
+class UnzippingThread: public salhelper::Thread
+{
+ XBufferedThreadedStream &mxStream;
+public:
+ explicit UnzippingThread(XBufferedThreadedStream &xStream): Thread("Unzipping"), mxStream(xStream) {}
+private:
+ virtual void execute() override
+ {
+ try
+ {
+ mxStream.produce();
+ }
+ catch (...)
+ {
+ mxStream.saveException(std::current_exception());
+ }
+
+ mxStream.setTerminateThread();
+ }
+};
+
+}
+
+XBufferedThreadedStream::XBufferedThreadedStream(
+ const Reference<XInputStream>& xSrcStream,
+ sal_Int64 nStreamSize)
+: mxSrcStream( xSrcStream )
+, mnPos(0)
+, mnStreamSize( nStreamSize )
+, mnOffset( 0 )
+, mxUnzippingThread( new UnzippingThread(*this) )
+, mbTerminateThread( false )
+{
+ mxUnzippingThread->launch();
+}
+
+XBufferedThreadedStream::~XBufferedThreadedStream()
+{
+ setTerminateThread();
+ mxUnzippingThread->join();
+}
+
+/**
+ * Reads from UnbufferedStream in a separate thread and stores the buffer blocks
+ * in maPendingBuffers queue for further use.
+ */
+void XBufferedThreadedStream::produce()
+{
+ Buffer pProducedBuffer;
+ sal_Int64 nTotalBytesRead(0);
+ std::unique_lock<std::mutex> aGuard( maBufferProtector );
+ do
+ {
+ if( !maUsedBuffers.empty() )
+ {
+ pProducedBuffer = maUsedBuffers.front();
+ maUsedBuffers.pop();
+ }
+
+ aGuard.unlock();
+ nTotalBytesRead += mxSrcStream->readBytes( pProducedBuffer, nBufferSize );
+
+ aGuard.lock();
+ maPendingBuffers.push( pProducedBuffer );
+ maBufferConsumeResume.notify_one();
+
+ if (!mbTerminateThread)
+ maBufferProduceResume.wait( aGuard, [&]{return canProduce(); } );
+
+ } while( !mbTerminateThread && nTotalBytesRead < mnStreamSize );
+}
+
+/**
+ * Fetches next available block from maPendingBuffers for use in Reading thread.
+ */
+const Buffer& XBufferedThreadedStream::getNextBlock()
+{
+ std::unique_lock<std::mutex> aGuard( maBufferProtector );
+ const sal_Int32 nBufSize = maInUseBuffer.getLength();
+ if( nBufSize <= 0 || mnOffset >= nBufSize )
+ {
+ if( mnOffset >= nBufSize )
+ maUsedBuffers.push( maInUseBuffer );
+
+ maBufferConsumeResume.wait( aGuard, [&]{return canConsume(); } );
+
+ if( maPendingBuffers.empty() )
+ {
+ maInUseBuffer = Buffer();
+ if (maSavedException)
+ std::rethrow_exception(maSavedException);
+ }
+ else
+ {
+ maInUseBuffer = maPendingBuffers.front();
+ maPendingBuffers.pop();
+ mnOffset = 0;
+
+ if( maPendingBuffers.size() <= nBufferLowWater )
+ maBufferProduceResume.notify_one();
+ }
+ }
+
+ return maInUseBuffer;
+}
+
+void XBufferedThreadedStream::setTerminateThread()
+{
+ std::scoped_lock<std::mutex> aGuard( maBufferProtector );
+ mbTerminateThread = true;
+ maBufferProduceResume.notify_one();
+ maBufferConsumeResume.notify_one();
+}
+
+sal_Int32 SAL_CALL XBufferedThreadedStream::readBytes( Sequence< sal_Int8 >& rData, sal_Int32 nBytesToRead )
+{
+ if( !hasBytes() )
+ return 0;
+
+ const sal_Int32 nAvailableSize = static_cast< sal_Int32 > ( std::min< sal_Int64 >( nBytesToRead, remainingSize() ) );
+ rData.realloc( nAvailableSize );
+ auto pData = rData.getArray();
+ sal_Int32 i = 0, nPendingBytes = nAvailableSize;
+
+ while( nPendingBytes )
+ {
+ const Buffer &pBuffer = getNextBlock();
+ if( !pBuffer.hasElements() )
+ {
+ rData.realloc( nAvailableSize - nPendingBytes );
+ return nAvailableSize - nPendingBytes;
+ }
+ const sal_Int32 limit = std::min<sal_Int32>( nPendingBytes, pBuffer.getLength() - mnOffset );
+
+ memcpy( &pData[i], &pBuffer[mnOffset], limit );
+
+ nPendingBytes -= limit;
+ mnOffset += limit;
+ mnPos += limit;
+ i += limit;
+ }
+
+ return nAvailableSize;
+}
+
+sal_Int32 SAL_CALL XBufferedThreadedStream::readSomeBytes( Sequence< sal_Int8 >& aData, sal_Int32 nMaxBytesToRead )
+{
+ return readBytes( aData, nMaxBytesToRead );
+}
+void SAL_CALL XBufferedThreadedStream::skipBytes( sal_Int32 nBytesToSkip )
+{
+ if( nBytesToSkip )
+ {
+ Sequence < sal_Int8 > aSequence( nBytesToSkip );
+ readBytes( aSequence, nBytesToSkip );
+ }
+}
+
+sal_Int32 SAL_CALL XBufferedThreadedStream::available()
+{
+ if( !hasBytes() )
+ return 0;
+
+ return static_cast< sal_Int32 > ( std::min< sal_Int64 >( SAL_MAX_INT32, remainingSize() ) );
+}
+
+void SAL_CALL XBufferedThreadedStream::closeInput()
+{
+ setTerminateThread();
+ mxUnzippingThread->join();
+ mxSrcStream->closeInput();
+}
+
+/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
diff --git a/package/source/zipapi/XBufferedThreadedStream.hxx b/package/source/zipapi/XBufferedThreadedStream.hxx
new file mode 100644
index 000000000..ad5d3b0ce
--- /dev/null
+++ b/package/source/zipapi/XBufferedThreadedStream.hxx
@@ -0,0 +1,83 @@
+/* -*- 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/.
+ */
+
+#ifndef INCLUDED_PACKAGE_SOURCE_ZIPAPI_XBUFFEREDTHREADEDSTREAM_HXX
+#define INCLUDED_PACKAGE_SOURCE_ZIPAPI_XBUFFEREDTHREADEDSTREAM_HXX
+
+#include <com/sun/star/io/XInputStream.hpp>
+
+#include <cppuhelper/implbase.hxx>
+#include <rtl/ref.hxx>
+#include <salhelper/thread.hxx>
+
+#include <queue>
+#include <mutex>
+#include <condition_variable>
+
+typedef css::uno::Sequence< sal_Int8 > Buffer;
+
+class XBufferedThreadedStream : public cppu::WeakImplHelper< css::io::XInputStream >
+{
+private:
+ const css::uno::Reference<XInputStream> mxSrcStream;
+ sal_Int64 mnPos; /// position in stream
+ sal_Int64 mnStreamSize; /// available size of stream
+
+ Buffer maInUseBuffer; /// Buffer block in use
+ int mnOffset; /// position in maInUseBuffer
+ std::queue < Buffer > maPendingBuffers; /// Buffers that are available for use
+ std::queue < Buffer > maUsedBuffers;
+
+ rtl::Reference< salhelper::Thread > mxUnzippingThread;
+ std::mutex maBufferProtector; /// mutex protecting Buffer queues.
+ std::condition_variable maBufferConsumeResume;
+ std::condition_variable maBufferProduceResume;
+ bool mbTerminateThread; /// indicates the failure of one of the threads
+
+ std::exception_ptr maSavedException; /// exception caught during unzipping is saved to be thrown during reading
+
+ static const size_t nBufferLowWater = 2;
+ static const size_t nBufferHighWater = 4;
+ static const size_t nBufferSize = 32 * 1024;
+
+ const Buffer& getNextBlock();
+ sal_Int64 remainingSize() const { return mnStreamSize - mnPos; }
+ bool hasBytes() const { return mnPos < mnStreamSize; }
+
+ bool canProduce() const
+ {
+ return( mbTerminateThread || maPendingBuffers.size() < nBufferHighWater );
+ }
+
+ bool canConsume() const
+ {
+ return( mbTerminateThread || !maPendingBuffers.empty() );
+ }
+
+public:
+ XBufferedThreadedStream(
+ const css::uno::Reference<XInputStream>& xSrcStream,
+ sal_Int64 nStreamSize /* cf. sal_Int32 available(); */ );
+
+ virtual ~XBufferedThreadedStream() override;
+
+ void produce();
+ void setTerminateThread();
+ void saveException(const std::exception_ptr& exception) { maSavedException = exception; }
+
+ // XInputStream
+ virtual sal_Int32 SAL_CALL readBytes( css::uno::Sequence< sal_Int8 >& aData, sal_Int32 nBytesToRead ) override;
+ virtual sal_Int32 SAL_CALL readSomeBytes( css::uno::Sequence< sal_Int8 >& aData, sal_Int32 nMaxBytesToRead ) override;
+ virtual void SAL_CALL skipBytes( sal_Int32 nBytesToSkip ) override;
+ virtual sal_Int32 SAL_CALL available( ) override;
+ virtual void SAL_CALL closeInput( ) override;
+};
+#endif
+
+/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
diff --git a/package/source/zipapi/XUnbufferedStream.cxx b/package/source/zipapi/XUnbufferedStream.cxx
new file mode 100644
index 000000000..56f864a2d
--- /dev/null
+++ b/package/source/zipapi/XUnbufferedStream.cxx
@@ -0,0 +1,323 @@
+/* -*- 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 <com/sun/star/packages/zip/ZipConstants.hpp>
+#include <com/sun/star/packages/zip/ZipIOException.hpp>
+#include <com/sun/star/xml/crypto/CipherID.hpp>
+
+#include "XUnbufferedStream.hxx"
+#include <EncryptionData.hxx>
+#include <ZipFile.hxx>
+#include <EncryptedDataHeader.hxx>
+#include <algorithm>
+#include <string.h>
+
+#include <osl/diagnose.h>
+#include <osl/mutex.hxx>
+#include <tools/diagnose_ex.h>
+
+using namespace ::com::sun::star;
+using namespace com::sun::star::packages::zip::ZipConstants;
+using namespace com::sun::star::io;
+using namespace com::sun::star::uno;
+using com::sun::star::packages::zip::ZipIOException;
+
+XUnbufferedStream::XUnbufferedStream(
+ const uno::Reference< uno::XComponentContext >& xContext,
+ const rtl::Reference< comphelper::RefCountedMutex >& aMutexHolder,
+ ZipEntry const & rEntry,
+ Reference < XInputStream > const & xNewZipStream,
+ const ::rtl::Reference< EncryptionData >& rData,
+ sal_Int8 nStreamMode,
+ bool bIsEncrypted,
+ const OUString& aMediaType,
+ bool bRecoveryMode )
+: maMutexHolder( aMutexHolder )
+, mxZipStream ( xNewZipStream )
+, mxZipSeek ( xNewZipStream, UNO_QUERY )
+, maEntry ( rEntry )
+, mnBlockSize( 1 )
+, maInflater ( true )
+, mbRawStream ( nStreamMode == UNBUFF_STREAM_RAW || nStreamMode == UNBUFF_STREAM_WRAPPEDRAW )
+, mbWrappedRaw ( nStreamMode == UNBUFF_STREAM_WRAPPEDRAW )
+, mnHeaderToRead ( 0 )
+, mnZipCurrent ( 0 )
+, mnZipEnd ( 0 )
+, mnZipSize ( 0 )
+, mnMyCurrent ( 0 )
+, mbCheckCRC(!bRecoveryMode)
+{
+ mnZipCurrent = maEntry.nOffset;
+ if ( mbRawStream )
+ {
+ mnZipSize = maEntry.nMethod == DEFLATED ? maEntry.nCompressedSize : maEntry.nSize;
+ mnZipEnd = maEntry.nOffset + mnZipSize;
+ }
+ else
+ {
+ mnZipSize = maEntry.nSize;
+ mnZipEnd = maEntry.nMethod == DEFLATED ? maEntry.nOffset + maEntry.nCompressedSize : maEntry.nOffset + maEntry.nSize;
+ }
+
+ if (mnZipSize < 0)
+ throw ZipIOException("The stream seems to be broken!");
+
+ bool bHaveEncryptData = rData.is() && rData->m_aInitVector.hasElements() &&
+ ((rData->m_aSalt.hasElements() && rData->m_nIterationCount != 0)
+ ||
+ rData->m_aKey.hasElements());
+ bool bMustDecrypt = nStreamMode == UNBUFF_STREAM_DATA && bHaveEncryptData && bIsEncrypted;
+
+ if ( bMustDecrypt )
+ {
+ m_xCipherContext = ZipFile::StaticGetCipher( xContext, rData, false );
+ mnBlockSize = ( rData->m_nEncAlg == xml::crypto::CipherID::AES_CBC_W3C_PADDING ? 16 : 1 );
+ }
+
+ if ( !(bHaveEncryptData && mbWrappedRaw && bIsEncrypted) )
+ return;
+
+ // if we have the data needed to decrypt it, but didn't want it decrypted (or
+ // we couldn't decrypt it due to wrong password), then we prepend this
+ // data to the stream
+
+ // Make a buffer big enough to hold both the header and the data itself
+ maHeader.realloc ( n_ConstHeaderSize +
+ rData->m_aInitVector.getLength() +
+ rData->m_aSalt.getLength() +
+ rData->m_aDigest.getLength() +
+ aMediaType.getLength() * sizeof( sal_Unicode ) );
+ sal_Int8 * pHeader = maHeader.getArray();
+ ZipFile::StaticFillHeader( rData, rEntry.nSize, aMediaType, pHeader );
+ mnHeaderToRead = static_cast < sal_Int16 > ( maHeader.getLength() );
+ mnZipSize += mnHeaderToRead;
+}
+
+// allows to read package raw stream
+XUnbufferedStream::XUnbufferedStream(
+ const rtl::Reference< comphelper::RefCountedMutex >& aMutexHolder,
+ const Reference < XInputStream >& xRawStream,
+ const ::rtl::Reference< EncryptionData >& rData )
+: maMutexHolder( aMutexHolder )
+, mxZipStream ( xRawStream )
+, mxZipSeek ( xRawStream, UNO_QUERY )
+, mnBlockSize( 1 )
+, maInflater ( true )
+, mbRawStream ( false )
+, mbWrappedRaw ( false )
+, mnHeaderToRead ( 0 )
+, mnZipCurrent ( 0 )
+, mnZipEnd ( 0 )
+, mnZipSize ( 0 )
+, mnMyCurrent ( 0 )
+, mbCheckCRC( false )
+{
+ // for this scenario maEntry is not set !!!
+ OSL_ENSURE( mxZipSeek.is(), "The stream must be seekable!" );
+
+ // skip raw header, it must be already parsed to rData
+ mnZipCurrent = n_ConstHeaderSize + rData->m_aInitVector.getLength() +
+ rData->m_aSalt.getLength() + rData->m_aDigest.getLength();
+
+ try {
+ if ( mxZipSeek.is() )
+ mnZipSize = mxZipSeek->getLength();
+ } catch( const Exception& )
+ {
+ // in case of problem the size will stay set to 0
+ TOOLS_WARN_EXCEPTION("package", "ignoring");
+ }
+
+ mnZipEnd = mnZipCurrent + mnZipSize;
+
+ // the raw data will not be decrypted, no need for the cipher
+ // m_xCipherContext = ZipFile::StaticGetCipher( xContext, rData, false );
+}
+
+XUnbufferedStream::~XUnbufferedStream()
+{
+}
+
+sal_Int32 SAL_CALL XUnbufferedStream::readBytes( Sequence< sal_Int8 >& aData, sal_Int32 nBytesToRead )
+{
+ ::osl::MutexGuard aGuard( maMutexHolder->GetMutex() );
+
+ sal_Int32 nRequestedBytes = nBytesToRead;
+ OSL_ENSURE( !mnHeaderToRead || mbWrappedRaw, "Only encrypted raw stream can be provided with header!" );
+ if ( mnMyCurrent + nRequestedBytes > mnZipSize + maHeader.getLength() )
+ nRequestedBytes = static_cast < sal_Int32 > ( mnZipSize + maHeader.getLength() - mnMyCurrent );
+
+ sal_Int32 nTotal = 0;
+ aData.realloc ( nRequestedBytes );
+ if ( nRequestedBytes )
+ {
+ sal_Int32 nRead = 0;
+ sal_Int32 nLastRead = 0;
+ if ( mbRawStream )
+ {
+ sal_Int64 nDiff = mnZipEnd - mnZipCurrent;
+
+ if ( mbWrappedRaw && mnHeaderToRead )
+ {
+ sal_Int16 nHeadRead = static_cast< sal_Int16 >(( nRequestedBytes > mnHeaderToRead ?
+ mnHeaderToRead : nRequestedBytes ));
+ memcpy ( aData.getArray(), maHeader.getConstArray() + maHeader.getLength() - mnHeaderToRead, nHeadRead );
+ mnHeaderToRead = mnHeaderToRead - nHeadRead;
+
+ if ( nHeadRead < nRequestedBytes )
+ {
+ sal_Int32 nToRead = nRequestedBytes - nHeadRead;
+ nToRead = ( nDiff < nToRead ) ? sal::static_int_cast< sal_Int32 >( nDiff ) : nToRead;
+
+ Sequence< sal_Int8 > aPureData( nToRead );
+ mxZipSeek->seek ( mnZipCurrent );
+ nRead = mxZipStream->readBytes ( aPureData, nToRead );
+ mnZipCurrent += nRead;
+
+ aPureData.realloc( nRead );
+ if ( mbCheckCRC )
+ maCRC.update( aPureData );
+
+ aData.realloc( nHeadRead + nRead );
+
+ const sal_Int8* pPureBuffer = aPureData.getConstArray();
+ sal_Int8* pBuffer = aData.getArray();
+ for ( sal_Int32 nInd = 0; nInd < nRead; nInd++ )
+ pBuffer[ nHeadRead + nInd ] = pPureBuffer[ nInd ];
+ }
+
+ nRead += nHeadRead;
+ }
+ else
+ {
+ mxZipSeek->seek ( mnZipCurrent );
+
+ nRead = mxZipStream->readBytes (
+ aData,
+ std::min<sal_Int64>(nDiff, nRequestedBytes) );
+
+ mnZipCurrent += nRead;
+
+ aData.realloc( nRead );
+ if ( mbWrappedRaw && mbCheckCRC )
+ maCRC.update( aData );
+ }
+ }
+ else
+ {
+ for (;;)
+ {
+ nLastRead = maInflater.doInflateSegment( aData, nRead, aData.getLength() - nRead );
+ if ( 0 != nLastRead && ( nRead + nLastRead == nRequestedBytes || mnZipCurrent >= mnZipEnd ) )
+ break;
+ nRead += nLastRead;
+ if ( nRead > nRequestedBytes )
+ throw RuntimeException(
+ "Should not be possible to read more than requested!" );
+
+ if ( maInflater.finished() || maInflater.getLastInflateError() )
+ throw ZipIOException("The stream seems to be broken!" );
+
+ if ( maInflater.needsDictionary() )
+ throw ZipIOException("Dictionaries are not supported!" );
+
+ sal_Int32 nDiff = static_cast< sal_Int32 >( mnZipEnd - mnZipCurrent );
+ if ( nDiff <= 0 )
+ {
+ throw ZipIOException("The stream seems to be broken!" );
+ }
+
+ mxZipSeek->seek ( mnZipCurrent );
+
+ sal_Int32 nToRead = std::max( nRequestedBytes, static_cast< sal_Int32 >( 8192 ) );
+ if ( mnBlockSize > 1 )
+ nToRead = nToRead + mnBlockSize - nToRead % mnBlockSize;
+ nToRead = std::min( nDiff, nToRead );
+
+ sal_Int32 nZipRead = mxZipStream->readBytes( maCompBuffer, nToRead );
+ if ( nZipRead < nToRead )
+ throw ZipIOException("No expected data!" );
+
+ mnZipCurrent += nZipRead;
+ // maCompBuffer now has the data, check if we need to decrypt
+ // before passing to the Inflater
+ if ( m_xCipherContext.is() )
+ {
+ if ( mbCheckCRC )
+ maCRC.update( maCompBuffer );
+
+ maCompBuffer = m_xCipherContext->convertWithCipherContext( maCompBuffer );
+ if ( mnZipCurrent == mnZipEnd )
+ {
+ uno::Sequence< sal_Int8 > aSuffix = m_xCipherContext->finalizeCipherContextAndDispose();
+ if ( aSuffix.hasElements() )
+ {
+ sal_Int32 nOldLen = maCompBuffer.getLength();
+ maCompBuffer.realloc( nOldLen + aSuffix.getLength() );
+ memcpy( maCompBuffer.getArray() + nOldLen, aSuffix.getConstArray(), aSuffix.getLength() );
+ }
+ }
+ }
+ maInflater.setInput ( maCompBuffer );
+
+ }
+ }
+
+ mnMyCurrent += nRead + nLastRead;
+ nTotal = nRead + nLastRead;
+ if ( nTotal < nRequestedBytes)
+ aData.realloc ( nTotal );
+
+ if ( mbCheckCRC && ( !mbRawStream || mbWrappedRaw ) )
+ {
+ if ( !m_xCipherContext.is() && !mbWrappedRaw )
+ maCRC.update( aData );
+
+ if ( mnZipSize + maHeader.getLength() == mnMyCurrent && maCRC.getValue() != maEntry.nCrc )
+ throw ZipIOException("The stream seems to be broken!" );
+ }
+ }
+
+ return nTotal;
+}
+
+sal_Int32 SAL_CALL XUnbufferedStream::readSomeBytes( Sequence< sal_Int8 >& aData, sal_Int32 nMaxBytesToRead )
+{
+ return readBytes ( aData, nMaxBytesToRead );
+}
+void SAL_CALL XUnbufferedStream::skipBytes( sal_Int32 nBytesToSkip )
+{
+ if ( nBytesToSkip )
+ {
+ Sequence < sal_Int8 > aSequence ( nBytesToSkip );
+ readBytes ( aSequence, nBytesToSkip );
+ }
+}
+
+sal_Int32 SAL_CALL XUnbufferedStream::available( )
+{
+ //available size must include the prepended header in case of wrapped raw stream
+ return static_cast< sal_Int32 > ( std::min< sal_Int64 >( SAL_MAX_INT32, (mnZipSize + mnHeaderToRead - mnMyCurrent) ) );
+}
+
+void SAL_CALL XUnbufferedStream::closeInput( )
+{
+}
+
+/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
diff --git a/package/source/zipapi/XUnbufferedStream.hxx b/package/source/zipapi/XUnbufferedStream.hxx
new file mode 100644
index 000000000..277f356ee
--- /dev/null
+++ b/package/source/zipapi/XUnbufferedStream.hxx
@@ -0,0 +1,93 @@
+/* -*- 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 .
+ */
+#ifndef INCLUDED_PACKAGE_SOURCE_ZIPAPI_XUNBUFFEREDSTREAM_HXX
+#define INCLUDED_PACKAGE_SOURCE_ZIPAPI_XUNBUFFEREDSTREAM_HXX
+
+#include <com/sun/star/io/XSeekable.hpp>
+#include <com/sun/star/io/XInputStream.hpp>
+#include <com/sun/star/xml/crypto/XCipherContext.hpp>
+
+#include <comphelper/refcountedmutex.hxx>
+#include <cppuhelper/implbase.hxx>
+#include <rtl/ref.hxx>
+#include <package/Inflater.hxx>
+#include <ZipEntry.hxx>
+#include <CRC32.hxx>
+
+namespace com::sun::star::uno {
+ class XComponentContext;
+}
+
+#define UNBUFF_STREAM_DATA 0
+#define UNBUFF_STREAM_RAW 1
+#define UNBUFF_STREAM_WRAPPEDRAW 2
+
+class EncryptionData;
+class XUnbufferedStream final : public cppu::WeakImplHelper
+<
+ css::io::XInputStream
+>
+{
+ rtl::Reference<comphelper::RefCountedMutex> maMutexHolder;
+
+ css::uno::Reference < css::io::XInputStream > mxZipStream;
+ css::uno::Reference < css::io::XSeekable > mxZipSeek;
+ css::uno::Sequence < sal_Int8 > maCompBuffer, maHeader;
+ ZipEntry maEntry;
+ sal_Int32 mnBlockSize;
+ css::uno::Reference< css::xml::crypto::XCipherContext > m_xCipherContext;
+ ZipUtils::Inflater maInflater;
+ bool mbRawStream, mbWrappedRaw;
+ sal_Int16 mnHeaderToRead;
+ sal_Int64 mnZipCurrent, mnZipEnd, mnZipSize, mnMyCurrent;
+ CRC32 maCRC;
+ bool mbCheckCRC;
+
+public:
+ XUnbufferedStream(
+ const css::uno::Reference< css::uno::XComponentContext >& xContext,
+ const rtl::Reference<comphelper::RefCountedMutex>& aMutexHolder,
+ ZipEntry const & rEntry,
+ css::uno::Reference < css::io::XInputStream > const & xNewZipStream,
+ const ::rtl::Reference< EncryptionData >& rData,
+ sal_Int8 nStreamMode,
+ bool bIsEncrypted,
+ const OUString& aMediaType,
+ bool bRecoveryMode );
+
+ // allows to read package raw stream
+ XUnbufferedStream(
+ const rtl::Reference<comphelper::RefCountedMutex>& aMutexHolder,
+ const css::uno::Reference < css::io::XInputStream >& xRawStream,
+ const ::rtl::Reference< EncryptionData >& rData );
+
+ sal_Int64 getSize() const { return mnZipSize; }
+
+ virtual ~XUnbufferedStream() override;
+
+ // XInputStream
+ virtual sal_Int32 SAL_CALL readBytes( css::uno::Sequence< sal_Int8 >& aData, sal_Int32 nBytesToRead ) override;
+ virtual sal_Int32 SAL_CALL readSomeBytes( css::uno::Sequence< sal_Int8 >& aData, sal_Int32 nMaxBytesToRead ) override;
+ virtual void SAL_CALL skipBytes( sal_Int32 nBytesToSkip ) override;
+ virtual sal_Int32 SAL_CALL available( ) override;
+ virtual void SAL_CALL closeInput( ) override;
+};
+#endif
+
+/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
diff --git a/package/source/zipapi/ZipEnumeration.cxx b/package/source/zipapi/ZipEnumeration.cxx
new file mode 100644
index 000000000..0c036882f
--- /dev/null
+++ b/package/source/zipapi/ZipEnumeration.cxx
@@ -0,0 +1,39 @@
+/* -*- 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 <ZipEnumeration.hxx>
+
+/** Provides an Enumeration over the contents of a Zip file */
+
+ZipEnumeration::ZipEnumeration(EntryHash& rNewEntryHash)
+ : rEntryHash(rNewEntryHash)
+ , aIterator(rEntryHash.begin())
+{
+}
+bool ZipEnumeration::hasMoreElements() { return (aIterator != rEntryHash.end()); }
+
+const ZipEntry* ZipEnumeration::nextElement()
+{
+ if (aIterator != rEntryHash.end())
+ return &((*aIterator++).second);
+ else
+ return nullptr;
+}
+
+/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
diff --git a/package/source/zipapi/ZipFile.cxx b/package/source/zipapi/ZipFile.cxx
new file mode 100644
index 000000000..79dc5bb68
--- /dev/null
+++ b/package/source/zipapi/ZipFile.cxx
@@ -0,0 +1,1263 @@
+/* -*- 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 <com/sun/star/io/BufferSizeExceededException.hpp>
+#include <com/sun/star/io/NotConnectedException.hpp>
+#include <com/sun/star/lang/IllegalArgumentException.hpp>
+#include <com/sun/star/lang/XUnoTunnel.hpp>
+#include <com/sun/star/packages/NoEncryptionException.hpp>
+#include <com/sun/star/packages/WrongPasswordException.hpp>
+#include <com/sun/star/packages/zip/ZipConstants.hpp>
+#include <com/sun/star/packages/zip/ZipException.hpp>
+#include <com/sun/star/packages/zip/ZipIOException.hpp>
+#include <com/sun/star/xml/crypto/XCipherContext.hpp>
+#include <com/sun/star/xml/crypto/XDigestContext.hpp>
+#include <com/sun/star/xml/crypto/CipherID.hpp>
+#include <com/sun/star/xml/crypto/DigestID.hpp>
+#include <com/sun/star/xml/crypto/NSSInitializer.hpp>
+
+#include <comphelper/bytereader.hxx>
+#include <comphelper/storagehelper.hxx>
+#include <comphelper/processfactory.hxx>
+#include <rtl/digest.h>
+#include <sal/log.hxx>
+#include <o3tl/safeint.hxx>
+#include <osl/diagnose.h>
+
+#include <algorithm>
+#include <iterator>
+#include <vector>
+
+#include "blowfishcontext.hxx"
+#include "sha1context.hxx"
+#include <ZipFile.hxx>
+#include <ZipEnumeration.hxx>
+#include "XUnbufferedStream.hxx"
+#include "XBufferedThreadedStream.hxx"
+#include <PackageConstants.hxx>
+#include <EncryptedDataHeader.hxx>
+#include <EncryptionData.hxx>
+#include "MemoryByteGrabber.hxx"
+
+#include <CRC32.hxx>
+
+using namespace com::sun::star;
+using namespace com::sun::star::io;
+using namespace com::sun::star::uno;
+using namespace com::sun::star::lang;
+using namespace com::sun::star::packages;
+using namespace com::sun::star::packages::zip;
+using namespace com::sun::star::packages::zip::ZipConstants;
+
+using ZipUtils::Inflater;
+
+#if OSL_DEBUG_LEVEL > 0
+#define THROW_WHERE SAL_WHERE
+#else
+#define THROW_WHERE ""
+#endif
+
+/** This class is used to read entries from a zip file
+ */
+ZipFile::ZipFile( const rtl::Reference<comphelper::RefCountedMutex>& aMutexHolder,
+ uno::Reference < XInputStream > const &xInput,
+ const uno::Reference < XComponentContext > & rxContext,
+ bool bInitialise )
+: m_aMutexHolder( aMutexHolder )
+, aGrabber( xInput )
+, aInflater( true )
+, xStream(xInput)
+, m_xContext ( rxContext )
+, bRecoveryMode( false )
+{
+ if (bInitialise && readCEN() == -1 )
+ {
+ aEntries.clear();
+ throw ZipException( "stream data looks to be broken" );
+ }
+}
+
+ZipFile::ZipFile( const rtl::Reference< comphelper::RefCountedMutex >& aMutexHolder,
+ uno::Reference < XInputStream > const &xInput,
+ const uno::Reference < XComponentContext > & rxContext,
+ bool bInitialise, bool bForceRecovery)
+: m_aMutexHolder( aMutexHolder )
+, aGrabber( xInput )
+, aInflater( true )
+, xStream(xInput)
+, m_xContext ( rxContext )
+, bRecoveryMode( bForceRecovery )
+{
+ if (bInitialise)
+ {
+ if ( bForceRecovery )
+ {
+ recover();
+ }
+ else if ( readCEN() == -1 )
+ {
+ aEntries.clear();
+ throw ZipException("stream data looks to be broken" );
+ }
+ }
+}
+
+ZipFile::~ZipFile()
+{
+ aEntries.clear();
+}
+
+void ZipFile::setInputStream ( const uno::Reference < XInputStream >& xNewStream )
+{
+ ::osl::MutexGuard aGuard( m_aMutexHolder->GetMutex() );
+
+ xStream = xNewStream;
+ aGrabber.setInputStream ( xStream );
+}
+
+uno::Reference< xml::crypto::XDigestContext > ZipFile::StaticGetDigestContextForChecksum( const uno::Reference< uno::XComponentContext >& xArgContext, const ::rtl::Reference< EncryptionData >& xEncryptionData )
+{
+ uno::Reference< xml::crypto::XDigestContext > xDigestContext;
+ if ( xEncryptionData->m_nCheckAlg == xml::crypto::DigestID::SHA256_1K )
+ {
+ uno::Reference< uno::XComponentContext > xContext = xArgContext;
+ if ( !xContext.is() )
+ xContext = comphelper::getProcessComponentContext();
+
+ uno::Reference< xml::crypto::XNSSInitializer > xDigestContextSupplier = xml::crypto::NSSInitializer::create( xContext );
+
+ xDigestContext.set( xDigestContextSupplier->getDigestContext( xEncryptionData->m_nCheckAlg, uno::Sequence< beans::NamedValue >() ), uno::UNO_SET_THROW );
+ }
+ else if ( xEncryptionData->m_nCheckAlg == xml::crypto::DigestID::SHA1_1K )
+ {
+ if (xEncryptionData->m_bTryWrongSHA1)
+ {
+ xDigestContext.set(StarOfficeSHA1DigestContext::Create(), uno::UNO_SET_THROW);
+ }
+ else
+ {
+ xDigestContext.set(CorrectSHA1DigestContext::Create(), uno::UNO_SET_THROW);
+ }
+ }
+
+ return xDigestContext;
+}
+
+uno::Reference< xml::crypto::XCipherContext > ZipFile::StaticGetCipher( const uno::Reference< uno::XComponentContext >& xArgContext, const ::rtl::Reference< EncryptionData >& xEncryptionData, bool bEncrypt )
+{
+ uno::Reference< xml::crypto::XCipherContext > xResult;
+
+ if (xEncryptionData->m_nDerivedKeySize < 0)
+ {
+ throw ZipIOException("Invalid derived key length!" );
+ }
+
+ uno::Sequence< sal_Int8 > aDerivedKey( xEncryptionData->m_nDerivedKeySize );
+ if ( !xEncryptionData->m_nIterationCount &&
+ xEncryptionData->m_nDerivedKeySize == xEncryptionData->m_aKey.getLength() )
+ {
+ // gpg4libre: no need to derive key, m_aKey is already
+ // usable as symmetric session key
+ aDerivedKey = xEncryptionData->m_aKey;
+ }
+ else if ( rtl_Digest_E_None != rtl_digest_PBKDF2( reinterpret_cast< sal_uInt8* >( aDerivedKey.getArray() ),
+ aDerivedKey.getLength(),
+ reinterpret_cast< const sal_uInt8 * > (xEncryptionData->m_aKey.getConstArray() ),
+ xEncryptionData->m_aKey.getLength(),
+ reinterpret_cast< const sal_uInt8 * > ( xEncryptionData->m_aSalt.getConstArray() ),
+ xEncryptionData->m_aSalt.getLength(),
+ xEncryptionData->m_nIterationCount ) )
+ {
+ throw ZipIOException("Can not create derived key!" );
+ }
+
+ if ( xEncryptionData->m_nEncAlg == xml::crypto::CipherID::AES_CBC_W3C_PADDING )
+ {
+ uno::Reference< uno::XComponentContext > xContext = xArgContext;
+ if ( !xContext.is() )
+ xContext = comphelper::getProcessComponentContext();
+
+ uno::Reference< xml::crypto::XNSSInitializer > xCipherContextSupplier = xml::crypto::NSSInitializer::create( xContext );
+
+ xResult = xCipherContextSupplier->getCipherContext( xEncryptionData->m_nEncAlg, aDerivedKey, xEncryptionData->m_aInitVector, bEncrypt, uno::Sequence< beans::NamedValue >() );
+ }
+ else if ( xEncryptionData->m_nEncAlg == xml::crypto::CipherID::BLOWFISH_CFB_8 )
+ {
+ xResult = BlowfishCFB8CipherContext::Create( aDerivedKey, xEncryptionData->m_aInitVector, bEncrypt );
+ }
+ else
+ {
+ throw ZipIOException("Unknown cipher algorithm is requested!" );
+ }
+
+ return xResult;
+}
+
+void ZipFile::StaticFillHeader( const ::rtl::Reference< EncryptionData >& rData,
+ sal_Int64 nSize,
+ const OUString& aMediaType,
+ sal_Int8 * & pHeader )
+{
+ // I think it's safe to restrict vector and salt length to 2 bytes !
+ sal_Int16 nIVLength = static_cast < sal_Int16 > ( rData->m_aInitVector.getLength() );
+ sal_Int16 nSaltLength = static_cast < sal_Int16 > ( rData->m_aSalt.getLength() );
+ sal_Int16 nDigestLength = static_cast < sal_Int16 > ( rData->m_aDigest.getLength() );
+ sal_Int16 nMediaTypeLength = static_cast < sal_Int16 > ( aMediaType.getLength() * sizeof( sal_Unicode ) );
+
+ // First the header
+ *(pHeader++) = ( n_ConstHeader >> 0 ) & 0xFF;
+ *(pHeader++) = ( n_ConstHeader >> 8 ) & 0xFF;
+ *(pHeader++) = ( n_ConstHeader >> 16 ) & 0xFF;
+ *(pHeader++) = ( n_ConstHeader >> 24 ) & 0xFF;
+
+ // Then the version
+ *(pHeader++) = ( n_ConstCurrentVersion >> 0 ) & 0xFF;
+ *(pHeader++) = ( n_ConstCurrentVersion >> 8 ) & 0xFF;
+
+ // Then the iteration Count
+ sal_Int32 nIterationCount = rData->m_nIterationCount;
+ *(pHeader++) = static_cast< sal_Int8 >(( nIterationCount >> 0 ) & 0xFF);
+ *(pHeader++) = static_cast< sal_Int8 >(( nIterationCount >> 8 ) & 0xFF);
+ *(pHeader++) = static_cast< sal_Int8 >(( nIterationCount >> 16 ) & 0xFF);
+ *(pHeader++) = static_cast< sal_Int8 >(( nIterationCount >> 24 ) & 0xFF);
+
+ // FIXME64: need to handle larger sizes
+ // Then the size:
+ *(pHeader++) = static_cast< sal_Int8 >(( nSize >> 0 ) & 0xFF);
+ *(pHeader++) = static_cast< sal_Int8 >(( nSize >> 8 ) & 0xFF);
+ *(pHeader++) = static_cast< sal_Int8 >(( nSize >> 16 ) & 0xFF);
+ *(pHeader++) = static_cast< sal_Int8 >(( nSize >> 24 ) & 0xFF);
+
+ // Then the encryption algorithm
+ sal_Int32 nEncAlgID = rData->m_nEncAlg;
+ *(pHeader++) = static_cast< sal_Int8 >(( nEncAlgID >> 0 ) & 0xFF);
+ *(pHeader++) = static_cast< sal_Int8 >(( nEncAlgID >> 8 ) & 0xFF);
+ *(pHeader++) = static_cast< sal_Int8 >(( nEncAlgID >> 16 ) & 0xFF);
+ *(pHeader++) = static_cast< sal_Int8 >(( nEncAlgID >> 24 ) & 0xFF);
+
+ // Then the checksum algorithm
+ sal_Int32 nChecksumAlgID = rData->m_nCheckAlg;
+ *(pHeader++) = static_cast< sal_Int8 >(( nChecksumAlgID >> 0 ) & 0xFF);
+ *(pHeader++) = static_cast< sal_Int8 >(( nChecksumAlgID >> 8 ) & 0xFF);
+ *(pHeader++) = static_cast< sal_Int8 >(( nChecksumAlgID >> 16 ) & 0xFF);
+ *(pHeader++) = static_cast< sal_Int8 >(( nChecksumAlgID >> 24 ) & 0xFF);
+
+ // Then the derived key size
+ sal_Int32 nDerivedKeySize = rData->m_nDerivedKeySize;
+ *(pHeader++) = static_cast< sal_Int8 >(( nDerivedKeySize >> 0 ) & 0xFF);
+ *(pHeader++) = static_cast< sal_Int8 >(( nDerivedKeySize >> 8 ) & 0xFF);
+ *(pHeader++) = static_cast< sal_Int8 >(( nDerivedKeySize >> 16 ) & 0xFF);
+ *(pHeader++) = static_cast< sal_Int8 >(( nDerivedKeySize >> 24 ) & 0xFF);
+
+ // Then the start key generation algorithm
+ sal_Int32 nKeyAlgID = rData->m_nStartKeyGenID;
+ *(pHeader++) = static_cast< sal_Int8 >(( nKeyAlgID >> 0 ) & 0xFF);
+ *(pHeader++) = static_cast< sal_Int8 >(( nKeyAlgID >> 8 ) & 0xFF);
+ *(pHeader++) = static_cast< sal_Int8 >(( nKeyAlgID >> 16 ) & 0xFF);
+ *(pHeader++) = static_cast< sal_Int8 >(( nKeyAlgID >> 24 ) & 0xFF);
+
+ // Then the salt length
+ *(pHeader++) = static_cast< sal_Int8 >(( nSaltLength >> 0 ) & 0xFF);
+ *(pHeader++) = static_cast< sal_Int8 >(( nSaltLength >> 8 ) & 0xFF);
+
+ // Then the IV length
+ *(pHeader++) = static_cast< sal_Int8 >(( nIVLength >> 0 ) & 0xFF);
+ *(pHeader++) = static_cast< sal_Int8 >(( nIVLength >> 8 ) & 0xFF);
+
+ // Then the digest length
+ *(pHeader++) = static_cast< sal_Int8 >(( nDigestLength >> 0 ) & 0xFF);
+ *(pHeader++) = static_cast< sal_Int8 >(( nDigestLength >> 8 ) & 0xFF);
+
+ // Then the mediatype length
+ *(pHeader++) = static_cast< sal_Int8 >(( nMediaTypeLength >> 0 ) & 0xFF);
+ *(pHeader++) = static_cast< sal_Int8 >(( nMediaTypeLength >> 8 ) & 0xFF);
+
+ // Then the salt content
+ memcpy ( pHeader, rData->m_aSalt.getConstArray(), nSaltLength );
+ pHeader += nSaltLength;
+
+ // Then the IV content
+ memcpy ( pHeader, rData->m_aInitVector.getConstArray(), nIVLength );
+ pHeader += nIVLength;
+
+ // Then the digest content
+ memcpy ( pHeader, rData->m_aDigest.getConstArray(), nDigestLength );
+ pHeader += nDigestLength;
+
+ // Then the mediatype itself
+ memcpy ( pHeader, aMediaType.getStr(), nMediaTypeLength );
+ pHeader += nMediaTypeLength;
+}
+
+bool ZipFile::StaticFillData ( ::rtl::Reference< BaseEncryptionData > const & rData,
+ sal_Int32 &rEncAlg,
+ sal_Int32 &rChecksumAlg,
+ sal_Int32 &rDerivedKeySize,
+ sal_Int32 &rStartKeyGenID,
+ sal_Int32 &rSize,
+ OUString& aMediaType,
+ const uno::Reference< XInputStream >& rStream )
+{
+ bool bOk = false;
+ const sal_Int32 nHeaderSize = n_ConstHeaderSize - 4;
+ Sequence < sal_Int8 > aBuffer ( nHeaderSize );
+ if ( nHeaderSize == rStream->readBytes ( aBuffer, nHeaderSize ) )
+ {
+ sal_Int16 nPos = 0;
+ sal_Int8 *pBuffer = aBuffer.getArray();
+ sal_Int16 nVersion = pBuffer[nPos++] & 0xFF;
+ nVersion |= ( pBuffer[nPos++] & 0xFF ) << 8;
+ if ( nVersion == n_ConstCurrentVersion )
+ {
+ sal_Int32 nCount = pBuffer[nPos++] & 0xFF;
+ nCount |= ( pBuffer[nPos++] & 0xFF ) << 8;
+ nCount |= ( pBuffer[nPos++] & 0xFF ) << 16;
+ nCount |= ( pBuffer[nPos++] & 0xFF ) << 24;
+ rData->m_nIterationCount = nCount;
+
+ rSize = pBuffer[nPos++] & 0xFF;
+ rSize |= ( pBuffer[nPos++] & 0xFF ) << 8;
+ rSize |= ( pBuffer[nPos++] & 0xFF ) << 16;
+ rSize |= ( pBuffer[nPos++] & 0xFF ) << 24;
+
+ rEncAlg = pBuffer[nPos++] & 0xFF;
+ rEncAlg |= ( pBuffer[nPos++] & 0xFF ) << 8;
+ rEncAlg |= ( pBuffer[nPos++] & 0xFF ) << 16;
+ rEncAlg |= ( pBuffer[nPos++] & 0xFF ) << 24;
+
+ rChecksumAlg = pBuffer[nPos++] & 0xFF;
+ rChecksumAlg |= ( pBuffer[nPos++] & 0xFF ) << 8;
+ rChecksumAlg |= ( pBuffer[nPos++] & 0xFF ) << 16;
+ rChecksumAlg |= ( pBuffer[nPos++] & 0xFF ) << 24;
+
+ rDerivedKeySize = pBuffer[nPos++] & 0xFF;
+ rDerivedKeySize |= ( pBuffer[nPos++] & 0xFF ) << 8;
+ rDerivedKeySize |= ( pBuffer[nPos++] & 0xFF ) << 16;
+ rDerivedKeySize |= ( pBuffer[nPos++] & 0xFF ) << 24;
+
+ rStartKeyGenID = pBuffer[nPos++] & 0xFF;
+ rStartKeyGenID |= ( pBuffer[nPos++] & 0xFF ) << 8;
+ rStartKeyGenID |= ( pBuffer[nPos++] & 0xFF ) << 16;
+ rStartKeyGenID |= ( pBuffer[nPos++] & 0xFF ) << 24;
+
+ sal_Int16 nSaltLength = pBuffer[nPos++] & 0xFF;
+ nSaltLength |= ( pBuffer[nPos++] & 0xFF ) << 8;
+ sal_Int16 nIVLength = ( pBuffer[nPos++] & 0xFF );
+ nIVLength |= ( pBuffer[nPos++] & 0xFF ) << 8;
+ sal_Int16 nDigestLength = pBuffer[nPos++] & 0xFF;
+ nDigestLength |= ( pBuffer[nPos++] & 0xFF ) << 8;
+
+ sal_Int16 nMediaTypeLength = pBuffer[nPos++] & 0xFF;
+ nMediaTypeLength |= ( pBuffer[nPos++] & 0xFF ) << 8;
+
+ if ( nSaltLength == rStream->readBytes ( aBuffer, nSaltLength ) )
+ {
+ rData->m_aSalt.realloc ( nSaltLength );
+ memcpy ( rData->m_aSalt.getArray(), aBuffer.getConstArray(), nSaltLength );
+ if ( nIVLength == rStream->readBytes ( aBuffer, nIVLength ) )
+ {
+ rData->m_aInitVector.realloc ( nIVLength );
+ memcpy ( rData->m_aInitVector.getArray(), aBuffer.getConstArray(), nIVLength );
+ if ( nDigestLength == rStream->readBytes ( aBuffer, nDigestLength ) )
+ {
+ rData->m_aDigest.realloc ( nDigestLength );
+ memcpy ( rData->m_aDigest.getArray(), aBuffer.getConstArray(), nDigestLength );
+
+ if ( nMediaTypeLength == rStream->readBytes ( aBuffer, nMediaTypeLength ) )
+ {
+ aMediaType = OUString( reinterpret_cast<sal_Unicode const *>(aBuffer.getConstArray()),
+ nMediaTypeLength / sizeof( sal_Unicode ) );
+ bOk = true;
+ }
+ }
+ }
+ }
+ }
+ }
+ return bOk;
+}
+
+uno::Reference< XInputStream > ZipFile::StaticGetDataFromRawStream( const rtl::Reference< comphelper::RefCountedMutex >& aMutexHolder,
+ const uno::Reference< uno::XComponentContext >& rxContext,
+ const uno::Reference< XInputStream >& xStream,
+ const ::rtl::Reference< EncryptionData > &rData )
+{
+ if ( !rData.is() )
+ throw ZipIOException("Encrypted stream without encryption data!" );
+
+ if ( !rData->m_aKey.hasElements() )
+ throw packages::WrongPasswordException(THROW_WHERE );
+
+ uno::Reference< XSeekable > xSeek( xStream, UNO_QUERY );
+ if ( !xSeek.is() )
+ throw ZipIOException("The stream must be seekable!" );
+
+ // if we have a digest, then this file is an encrypted one and we should
+ // check if we can decrypt it or not
+ OSL_ENSURE( rData->m_aDigest.hasElements(), "Can't detect password correctness without digest!" );
+ if ( rData->m_aDigest.hasElements() )
+ {
+ sal_Int32 nSize = sal::static_int_cast< sal_Int32 >( xSeek->getLength() );
+ if ( nSize > n_ConstDigestLength + 32 )
+ nSize = n_ConstDigestLength + 32;
+
+ // skip header
+ xSeek->seek( n_ConstHeaderSize + rData->m_aInitVector.getLength() +
+ rData->m_aSalt.getLength() + rData->m_aDigest.getLength() );
+
+ // Only want to read enough to verify the digest
+ Sequence < sal_Int8 > aReadBuffer ( nSize );
+
+ xStream->readBytes( aReadBuffer, nSize );
+
+ if ( !StaticHasValidPassword( rxContext, aReadBuffer, rData ) )
+ throw packages::WrongPasswordException(THROW_WHERE );
+ }
+
+ return new XUnbufferedStream( aMutexHolder, xStream, rData );
+}
+
+#if 0
+// for debugging purposes
+void CheckSequence( const uno::Sequence< sal_Int8 >& aSequence )
+{
+ if ( aSequence.getLength() )
+ {
+ sal_Int32* pPointer = *( (sal_Int32**)&aSequence );
+ sal_Int32 nSize = *( pPointer + 1 );
+ sal_Int32 nMemSize = *( pPointer - 2 );
+ sal_Int32 nUsedMemSize = ( nSize + 4 * sizeof( sal_Int32 ) );
+ OSL_ENSURE( nSize == aSequence.getLength() && nUsedMemSize + 7 - ( nUsedMemSize - 1 ) % 8 == nMemSize, "Broken Sequence!" );
+ }
+}
+#endif
+
+bool ZipFile::StaticHasValidPassword( const uno::Reference< uno::XComponentContext >& rxContext, const Sequence< sal_Int8 > &aReadBuffer, const ::rtl::Reference< EncryptionData > &rData )
+{
+ if ( !rData.is() || !rData->m_aKey.hasElements() )
+ return false;
+
+ bool bRet = false;
+
+ uno::Reference< xml::crypto::XCipherContext > xCipher( StaticGetCipher( rxContext, rData, false ), uno::UNO_SET_THROW );
+
+ uno::Sequence< sal_Int8 > aDecryptBuffer;
+ uno::Sequence< sal_Int8 > aDecryptBuffer2;
+ try
+ {
+ aDecryptBuffer = xCipher->convertWithCipherContext( aReadBuffer );
+ aDecryptBuffer2 = xCipher->finalizeCipherContextAndDispose();
+ }
+ catch( uno::Exception& )
+ {
+ // decryption with padding will throw the exception in finalizing if the buffer represent only part of the stream
+ // it is no problem, actually this is why we read 32 additional bytes ( two of maximal possible encryption blocks )
+ }
+
+ if ( aDecryptBuffer2.hasElements() )
+ {
+ sal_Int32 nOldLen = aDecryptBuffer.getLength();
+ aDecryptBuffer.realloc( nOldLen + aDecryptBuffer2.getLength() );
+ memcpy( aDecryptBuffer.getArray() + nOldLen, aDecryptBuffer2.getConstArray(), aDecryptBuffer2.getLength() );
+ }
+
+ if ( aDecryptBuffer.getLength() > n_ConstDigestLength )
+ aDecryptBuffer.realloc( n_ConstDigestLength );
+
+ uno::Sequence< sal_Int8 > aDigestSeq;
+ uno::Reference< xml::crypto::XDigestContext > xDigestContext( StaticGetDigestContextForChecksum( rxContext, rData ), uno::UNO_SET_THROW );
+
+ xDigestContext->updateDigest( aDecryptBuffer );
+ aDigestSeq = xDigestContext->finalizeDigestAndDispose();
+
+ // If we don't have a digest, then we have to assume that the password is correct
+ if ( rData->m_aDigest.hasElements() &&
+ ( aDigestSeq.getLength() != rData->m_aDigest.getLength() ||
+ 0 != memcmp ( aDigestSeq.getConstArray(),
+ rData->m_aDigest.getConstArray(),
+ aDigestSeq.getLength() ) ) )
+ {
+ // We should probably tell the user that the password they entered was wrong
+ }
+ else
+ bRet = true;
+
+ return bRet;
+}
+
+bool ZipFile::hasValidPassword ( ZipEntry const & rEntry, const ::rtl::Reference< EncryptionData >& rData )
+{
+ ::osl::MutexGuard aGuard( m_aMutexHolder->GetMutex() );
+
+ bool bRet = false;
+ if ( rData.is() && rData->m_aKey.hasElements() )
+ {
+ css::uno::Reference < css::io::XSeekable > xSeek(xStream, UNO_QUERY_THROW);
+ xSeek->seek( rEntry.nOffset );
+ sal_Int64 nSize = rEntry.nMethod == DEFLATED ? rEntry.nCompressedSize : rEntry.nSize;
+
+ // Only want to read enough to verify the digest
+ if ( nSize > n_ConstDigestDecrypt )
+ nSize = n_ConstDigestDecrypt;
+
+ Sequence < sal_Int8 > aReadBuffer ( nSize );
+
+ xStream->readBytes( aReadBuffer, nSize );
+
+ bRet = StaticHasValidPassword( m_xContext, aReadBuffer, rData );
+ }
+
+ return bRet;
+}
+
+namespace {
+
+class XBufferedStream : public cppu::WeakImplHelper<css::io::XInputStream, css::io::XSeekable>
+{
+ std::vector<sal_Int8> maBytes;
+ size_t mnPos;
+
+ size_t remainingSize() const
+ {
+ return maBytes.size() - mnPos;
+ }
+
+ bool hasBytes() const
+ {
+ return mnPos < maBytes.size();
+ }
+
+public:
+ XBufferedStream( const uno::Reference<XInputStream>& xSrcStream ) : mnPos(0)
+ {
+ sal_Int32 nRemaining = xSrcStream->available();
+ uno::Reference< css::lang::XUnoTunnel > xInputTunnel( xSrcStream, uno::UNO_QUERY );
+ comphelper::ByteReader* pByteReader = nullptr;
+ if (xInputTunnel)
+ pByteReader = reinterpret_cast< comphelper::ByteReader* >( xInputTunnel->getSomething( comphelper::ByteReader::getUnoTunnelId() ) );
+
+ if (pByteReader)
+ {
+ maBytes.resize(nRemaining);
+
+ sal_Int8* pData = maBytes.data();
+ while (nRemaining > 0)
+ {
+ sal_Int32 nRead = pByteReader->readSomeBytes(pData, nRemaining);
+ nRemaining -= nRead;
+ pData += nRead;
+ }
+ }
+ else
+ {
+ const sal_Int32 nBufSize = 8192;
+
+ sal_Int32 nRead = 0;
+ maBytes.reserve(nRemaining);
+ uno::Sequence<sal_Int8> aBuf(nBufSize);
+
+ auto readAndCopy = [&]( sal_Int32 nReadSize ) -> sal_Int32
+ {
+ sal_Int32 nBytes = xSrcStream->readBytes(aBuf, nReadSize);
+ const sal_Int8* p = aBuf.getConstArray();
+ const sal_Int8* pEnd = p + nBytes;
+ maBytes.insert( maBytes.end(), p, pEnd );
+ return nBytes;
+ };
+
+ while (nRemaining > nBufSize)
+ {
+ const auto nBytes = readAndCopy(nBufSize);
+ if (!nBytes)
+ break;
+ nRead += nBytes;
+ nRemaining -= nBytes;
+ }
+
+ if (nRemaining)
+ nRead += readAndCopy(nRemaining);
+ maBytes.resize(nRead);
+ }
+ }
+
+ virtual sal_Int32 SAL_CALL readBytes( uno::Sequence<sal_Int8>& rData, sal_Int32 nBytesToRead ) override
+ {
+ if (!hasBytes())
+ return 0;
+
+ sal_Int32 nReadSize = std::min<sal_Int32>(nBytesToRead, remainingSize());
+ rData.realloc(nReadSize);
+ auto pData = rData.getArray();
+ std::vector<sal_Int8>::const_iterator it = maBytes.cbegin();
+ std::advance(it, mnPos);
+ for (sal_Int32 i = 0; i < nReadSize; ++i, ++it)
+ pData[i] = *it;
+
+ mnPos += nReadSize;
+
+ return nReadSize;
+ }
+
+ virtual sal_Int32 SAL_CALL readSomeBytes( ::css::uno::Sequence<sal_Int8>& rData, sal_Int32 nMaxBytesToRead ) override
+ {
+ return readBytes(rData, nMaxBytesToRead);
+ }
+
+ virtual void SAL_CALL skipBytes( sal_Int32 nBytesToSkip ) override
+ {
+ if (!hasBytes())
+ return;
+
+ mnPos += nBytesToSkip;
+ }
+
+ virtual sal_Int32 SAL_CALL available() override
+ {
+ if (!hasBytes())
+ return 0;
+
+ return remainingSize();
+ }
+
+ virtual void SAL_CALL closeInput() override
+ {
+ }
+ // XSeekable
+ virtual void SAL_CALL seek( sal_Int64 location ) override
+ {
+ if ( location < 0 || o3tl::make_unsigned(location) > maBytes.size() )
+ throw IllegalArgumentException(THROW_WHERE, uno::Reference< uno::XInterface >(), 1 );
+ mnPos = location;
+ }
+ virtual sal_Int64 SAL_CALL getPosition() override
+ {
+ return mnPos;
+ }
+ virtual sal_Int64 SAL_CALL getLength() override
+ {
+ return maBytes.size();
+ }
+};
+
+}
+
+uno::Reference< XInputStream > ZipFile::createStreamForZipEntry(
+ const rtl::Reference< comphelper::RefCountedMutex >& aMutexHolder,
+ ZipEntry const & rEntry,
+ const ::rtl::Reference< EncryptionData > &rData,
+ sal_Int8 nStreamMode,
+ bool bIsEncrypted,
+ const bool bUseBufferedStream,
+ const OUString& aMediaType )
+{
+ ::osl::MutexGuard aGuard( m_aMutexHolder->GetMutex() );
+
+ rtl::Reference< XUnbufferedStream > xSrcStream = new XUnbufferedStream(
+ m_xContext, aMutexHolder, rEntry, xStream, rData, nStreamMode, bIsEncrypted, aMediaType, bRecoveryMode);
+
+ if (!bUseBufferedStream)
+ return xSrcStream;
+
+ uno::Reference<io::XInputStream> xBufStream;
+#ifndef EMSCRIPTEN
+ static const sal_Int32 nThreadingThreshold = 10000;
+
+ if( xSrcStream->available() > nThreadingThreshold )
+ xBufStream = new XBufferedThreadedStream(xSrcStream, xSrcStream->getSize());
+ else
+#endif
+ xBufStream = new XBufferedStream(xSrcStream);
+
+ return xBufStream;
+}
+
+ZipEnumeration ZipFile::entries()
+{
+ return aEntries;
+}
+
+uno::Reference< XInputStream > ZipFile::getInputStream( ZipEntry& rEntry,
+ const ::rtl::Reference< EncryptionData > &rData,
+ bool bIsEncrypted,
+ const rtl::Reference<comphelper::RefCountedMutex>& aMutexHolder )
+{
+ ::osl::MutexGuard aGuard( m_aMutexHolder->GetMutex() );
+
+ if ( rEntry.nOffset <= 0 )
+ readLOC( rEntry );
+
+ // We want to return a rawStream if we either don't have a key or if the
+ // key is wrong
+
+ bool bNeedRawStream = rEntry.nMethod == STORED;
+
+ // if we have a digest, then this file is an encrypted one and we should
+ // check if we can decrypt it or not
+ if ( bIsEncrypted && rData.is() && rData->m_aDigest.hasElements() )
+ bNeedRawStream = !hasValidPassword ( rEntry, rData );
+
+ return createStreamForZipEntry ( aMutexHolder,
+ rEntry,
+ rData,
+ bNeedRawStream ? UNBUFF_STREAM_RAW : UNBUFF_STREAM_DATA,
+ bIsEncrypted );
+}
+
+uno::Reference< XInputStream > ZipFile::getDataStream( ZipEntry& rEntry,
+ const ::rtl::Reference< EncryptionData > &rData,
+ bool bIsEncrypted,
+ const rtl::Reference<comphelper::RefCountedMutex>& aMutexHolder )
+{
+ ::osl::MutexGuard aGuard( m_aMutexHolder->GetMutex() );
+
+ if ( rEntry.nOffset <= 0 )
+ readLOC( rEntry );
+
+ // An exception must be thrown in case stream is encrypted and
+ // there is no key or the key is wrong
+ bool bNeedRawStream = false;
+ if ( bIsEncrypted )
+ {
+ // in case no digest is provided there is no way
+ // to detect password correctness
+ if ( !rData.is() )
+ throw ZipException("Encrypted stream without encryption data!" );
+
+ // if we have a digest, then this file is an encrypted one and we should
+ // check if we can decrypt it or not
+ OSL_ENSURE( rData->m_aDigest.hasElements(), "Can't detect password correctness without digest!" );
+ if ( rData->m_aDigest.hasElements() && !hasValidPassword ( rEntry, rData ) )
+ throw packages::WrongPasswordException(THROW_WHERE );
+ }
+ else
+ bNeedRawStream = ( rEntry.nMethod == STORED );
+
+ return createStreamForZipEntry ( aMutexHolder,
+ rEntry,
+ rData,
+ bNeedRawStream ? UNBUFF_STREAM_RAW : UNBUFF_STREAM_DATA,
+ bIsEncrypted );
+}
+
+uno::Reference< XInputStream > ZipFile::getRawData( ZipEntry& rEntry,
+ const ::rtl::Reference< EncryptionData >& rData,
+ bool bIsEncrypted,
+ const rtl::Reference<comphelper::RefCountedMutex>& aMutexHolder,
+ const bool bUseBufferedStream )
+{
+ ::osl::MutexGuard aGuard( m_aMutexHolder->GetMutex() );
+
+ if ( rEntry.nOffset <= 0 )
+ readLOC( rEntry );
+
+ return createStreamForZipEntry ( aMutexHolder, rEntry, rData, UNBUFF_STREAM_RAW, bIsEncrypted, bUseBufferedStream );
+}
+
+uno::Reference< XInputStream > ZipFile::getWrappedRawStream(
+ ZipEntry& rEntry,
+ const ::rtl::Reference< EncryptionData >& rData,
+ const OUString& aMediaType,
+ const rtl::Reference<comphelper::RefCountedMutex>& aMutexHolder )
+{
+ ::osl::MutexGuard aGuard( m_aMutexHolder->GetMutex() );
+
+ if ( !rData.is() )
+ throw packages::NoEncryptionException(THROW_WHERE );
+
+ if ( rEntry.nOffset <= 0 )
+ readLOC( rEntry );
+
+ return createStreamForZipEntry ( aMutexHolder, rEntry, rData, UNBUFF_STREAM_WRAPPEDRAW, true, true, aMediaType );
+}
+
+void ZipFile::readLOC( ZipEntry &rEntry )
+{
+ ::osl::MutexGuard aGuard( m_aMutexHolder->GetMutex() );
+
+ sal_Int64 nPos = -rEntry.nOffset;
+
+ aGrabber.seek(nPos);
+ sal_Int32 nTestSig = aGrabber.ReadInt32();
+ if (nTestSig != LOCSIG)
+ throw ZipIOException("Invalid LOC header (bad signature)" );
+
+ // Ignore all (duplicated) information from the local file header.
+ // various programs produced "broken" zip files; even LO at some point.
+ // Just verify the path and calculate the data offset and otherwise
+ // rely on the central directory info.
+
+ aGrabber.ReadInt16(); //version
+ aGrabber.ReadInt16(); //flag
+ aGrabber.ReadInt16(); //how
+ aGrabber.ReadInt32(); //time
+ aGrabber.ReadInt32(); //crc
+ aGrabber.ReadInt32(); //compressed size
+ aGrabber.ReadInt32(); //size
+ sal_Int16 nPathLen = aGrabber.ReadInt16();
+ sal_Int16 nExtraLen = aGrabber.ReadInt16();
+ rEntry.nOffset = aGrabber.getPosition() + nPathLen + nExtraLen;
+
+ // FIXME64: need to read 64bit LOC
+
+ bool bBroken = false;
+
+ try
+ {
+ sal_Int16 nPathLenToRead = nPathLen;
+ const sal_Int64 nBytesAvailable = aGrabber.getLength() - aGrabber.getPosition();
+ if (nPathLenToRead > nBytesAvailable)
+ nPathLenToRead = nBytesAvailable;
+ else if (nPathLenToRead < 0)
+ nPathLenToRead = 0;
+
+ // read always in UTF8, some tools seem not to set UTF8 bit
+ uno::Sequence<sal_Int8> aNameBuffer(nPathLenToRead);
+ sal_Int32 nRead = aGrabber.readBytes(aNameBuffer, nPathLenToRead);
+ if (nRead < aNameBuffer.getLength())
+ aNameBuffer.realloc(nRead);
+
+ OUString sLOCPath( reinterpret_cast<const char *>(aNameBuffer.getConstArray()),
+ aNameBuffer.getLength(),
+ RTL_TEXTENCODING_UTF8 );
+
+ if ( rEntry.nPathLen == -1 ) // the file was created
+ {
+ rEntry.nPathLen = nPathLen;
+ rEntry.sPath = sLOCPath;
+ }
+
+ bBroken = rEntry.nPathLen != nPathLen
+ || rEntry.sPath != sLOCPath;
+ }
+ catch(...)
+ {
+ bBroken = true;
+ }
+
+ if ( bBroken && !bRecoveryMode )
+ throw ZipIOException("The stream seems to be broken!" );
+}
+
+sal_Int32 ZipFile::findEND()
+{
+ // this method is called in constructor only, no need for mutex
+ sal_Int32 nPos, nEnd;
+ Sequence < sal_Int8 > aBuffer;
+ try
+ {
+ sal_Int32 nLength = static_cast <sal_Int32 > (aGrabber.getLength());
+ if (nLength < ENDHDR)
+ return -1;
+ nPos = nLength - ENDHDR - ZIP_MAXNAMELEN;
+ nEnd = nPos >= 0 ? nPos : 0 ;
+
+ aGrabber.seek( nEnd );
+
+ auto nSize = nLength - nEnd;
+ if (nSize != aGrabber.readBytes(aBuffer, nSize))
+ throw ZipException("Zip END signature not found!" );
+
+ const sal_Int8 *pBuffer = aBuffer.getConstArray();
+
+ nPos = nSize - ENDHDR;
+ while ( nPos >= 0 )
+ {
+ if (pBuffer[nPos] == 'P' && pBuffer[nPos+1] == 'K' && pBuffer[nPos+2] == 5 && pBuffer[nPos+3] == 6 )
+ return nPos + nEnd;
+ nPos--;
+ }
+ }
+ catch ( IllegalArgumentException& )
+ {
+ throw ZipException("Zip END signature not found!" );
+ }
+ catch ( NotConnectedException& )
+ {
+ throw ZipException("Zip END signature not found!" );
+ }
+ catch ( BufferSizeExceededException& )
+ {
+ throw ZipException("Zip END signature not found!" );
+ }
+ throw ZipException("Zip END signature not found!" );
+}
+
+sal_Int32 ZipFile::readCEN()
+{
+ // this method is called in constructor only, no need for mutex
+ sal_Int32 nCenPos = -1, nLocPos;
+ sal_uInt16 nCount;
+
+ try
+ {
+ sal_Int32 nEndPos = findEND();
+ if (nEndPos == -1)
+ return -1;
+ aGrabber.seek(nEndPos + ENDTOT);
+ sal_uInt16 nTotal = aGrabber.ReadUInt16();
+ sal_Int32 nCenLen = aGrabber.ReadInt32();
+ sal_Int32 nCenOff = aGrabber.ReadInt32();
+
+ if ( nTotal * CENHDR > nCenLen )
+ throw ZipException("invalid END header (bad entry count)" );
+
+ if ( nTotal > ZIP_MAXENTRIES )
+ throw ZipException("too many entries in ZIP File" );
+
+ if ( nCenLen < 0 || nCenLen > nEndPos )
+ throw ZipException("Invalid END header (bad central directory size)" );
+
+ nCenPos = nEndPos - nCenLen;
+
+ if ( nCenOff < 0 || nCenOff > nCenPos )
+ throw ZipException("Invalid END header (bad central directory size)" );
+
+ nLocPos = nCenPos - nCenOff;
+ aGrabber.seek( nCenPos );
+ Sequence < sal_Int8 > aCENBuffer ( nCenLen );
+ sal_Int64 nRead = aGrabber.readBytes ( aCENBuffer, nCenLen );
+ if ( static_cast < sal_Int64 > ( nCenLen ) != nRead )
+ throw ZipException ("Error reading CEN into memory buffer!" );
+
+ MemoryByteGrabber aMemGrabber(aCENBuffer);
+
+ ZipEntry aEntry;
+ sal_Int16 nCommentLen;
+
+ aEntries.reserve(nTotal);
+ for (nCount = 0 ; nCount < nTotal; nCount++)
+ {
+ sal_Int32 nTestSig = aMemGrabber.ReadInt32();
+ if ( nTestSig != CENSIG )
+ throw ZipException("Invalid CEN header (bad signature)" );
+
+ aMemGrabber.skipBytes ( 2 );
+ aEntry.nVersion = aMemGrabber.ReadInt16();
+ aEntry.nFlag = aMemGrabber.ReadInt16();
+
+ if ( ( aEntry.nFlag & 1 ) == 1 )
+ throw ZipException("Invalid CEN header (encrypted entry)" );
+
+ aEntry.nMethod = aMemGrabber.ReadInt16();
+
+ if ( aEntry.nMethod != STORED && aEntry.nMethod != DEFLATED)
+ throw ZipException("Invalid CEN header (bad compression method)" );
+
+ aEntry.nTime = aMemGrabber.ReadInt32();
+ aEntry.nCrc = aMemGrabber.ReadInt32();
+
+ sal_uInt32 nCompressedSize = aMemGrabber.ReadUInt32();
+ sal_uInt32 nSize = aMemGrabber.ReadUInt32();
+ aEntry.nPathLen = aMemGrabber.ReadInt16();
+ aEntry.nExtraLen = aMemGrabber.ReadInt16();
+ nCommentLen = aMemGrabber.ReadInt16();
+ aMemGrabber.skipBytes ( 8 );
+ sal_uInt32 nOffset = aMemGrabber.ReadUInt32();
+
+ // FIXME64: need to read the 64bit header instead
+ if ( nSize == 0xffffffff ||
+ nOffset == 0xffffffff ||
+ nCompressedSize == 0xffffffff ) {
+ throw ZipException("PK64 zip file entry" );
+ }
+ aEntry.nCompressedSize = nCompressedSize;
+ aEntry.nSize = nSize;
+ aEntry.nOffset = nOffset;
+
+ aEntry.nOffset += nLocPos;
+ aEntry.nOffset *= -1;
+
+ if ( aEntry.nPathLen < 0 )
+ throw ZipException("unexpected name length" );
+
+ if ( nCommentLen < 0 )
+ throw ZipException("unexpected comment length" );
+
+ if ( aEntry.nExtraLen < 0 )
+ throw ZipException("unexpected extra header info length" );
+
+ if (aEntry.nPathLen > aMemGrabber.remainingSize())
+ throw ZipException("name too long");
+
+ // read always in UTF8, some tools seem not to set UTF8 bit
+ aEntry.sPath = OUString( reinterpret_cast<char const *>(aMemGrabber.getCurrentPos()),
+ aEntry.nPathLen,
+ RTL_TEXTENCODING_UTF8 );
+
+ if ( !::comphelper::OStorageHelper::IsValidZipEntryFileName( aEntry.sPath, true ) )
+ throw ZipException("Zip entry has an invalid name." );
+
+ aMemGrabber.skipBytes( aEntry.nPathLen + aEntry.nExtraLen + nCommentLen );
+ aEntries[aEntry.sPath] = aEntry;
+ }
+
+ if (nCount != nTotal)
+ throw ZipException("Count != Total" );
+ }
+ catch ( IllegalArgumentException & )
+ {
+ // seek can throw this...
+ nCenPos = -1; // make sure we return -1 to indicate an error
+ }
+ return nCenPos;
+}
+
+void ZipFile::recover()
+{
+ ::osl::MutexGuard aGuard( m_aMutexHolder->GetMutex() );
+
+ sal_Int64 nLength;
+ Sequence < sal_Int8 > aBuffer;
+
+ try
+ {
+ nLength = aGrabber.getLength();
+ if (nLength < ENDHDR)
+ return;
+
+ aGrabber.seek( 0 );
+
+ const sal_Int64 nToRead = 32000;
+ for( sal_Int64 nGenPos = 0; aGrabber.readBytes( aBuffer, nToRead ) && aBuffer.getLength() > 16; )
+ {
+ const sal_Int8 *pBuffer = aBuffer.getConstArray();
+ sal_Int32 nBufSize = aBuffer.getLength();
+
+ sal_Int64 nPos = 0;
+ // the buffer should contain at least one header,
+ // or if it is end of the file, at least the postheader with sizes and hash
+ while( nPos < nBufSize - 30
+ || ( nBufSize < nToRead && nPos < nBufSize - 16 ) )
+
+ {
+ if ( nPos < nBufSize - 30 && pBuffer[nPos] == 'P' && pBuffer[nPos+1] == 'K' && pBuffer[nPos+2] == 3 && pBuffer[nPos+3] == 4 )
+ {
+ ZipEntry aEntry;
+ Sequence<sal_Int8> aTmpBuffer(&(pBuffer[nPos+4]), 26);
+ MemoryByteGrabber aMemGrabber(aTmpBuffer);
+
+ aEntry.nVersion = aMemGrabber.ReadInt16();
+ aEntry.nFlag = aMemGrabber.ReadInt16();
+
+ if ( ( aEntry.nFlag & 1 ) != 1 )
+ {
+ aEntry.nMethod = aMemGrabber.ReadInt16();
+
+ if ( aEntry.nMethod == STORED || aEntry.nMethod == DEFLATED )
+ {
+ aEntry.nTime = aMemGrabber.ReadInt32();
+ aEntry.nCrc = aMemGrabber.ReadInt32();
+ sal_uInt32 nCompressedSize = aMemGrabber.ReadUInt32();
+ sal_uInt32 nSize = aMemGrabber.ReadUInt32();
+ aEntry.nPathLen = aMemGrabber.ReadInt16();
+ aEntry.nExtraLen = aMemGrabber.ReadInt16();
+
+ // FIXME64: need to read the 64bit header instead
+ if ( nSize == 0xffffffff ||
+ nCompressedSize == 0xffffffff ) {
+ throw ZipException("PK64 zip file entry" );
+ }
+ aEntry.nCompressedSize = nCompressedSize;
+ aEntry.nSize = nSize;
+
+ sal_Int32 nDescrLength =
+ ( aEntry.nMethod == DEFLATED && ( aEntry.nFlag & 8 ) ) ? 16 : 0;
+
+ sal_Int64 nDataSize = ( aEntry.nMethod == DEFLATED ) ? aEntry.nCompressedSize : aEntry.nSize;
+ sal_Int64 nBlockLength = nDataSize + aEntry.nPathLen + aEntry.nExtraLen + 30 + nDescrLength;
+ if ( aEntry.nPathLen >= 0 && aEntry.nExtraLen >= 0
+ && ( nGenPos + nPos + nBlockLength ) <= nLength )
+ {
+ // read always in UTF8, some tools seem not to set UTF8 bit
+ if( nPos + 30 + aEntry.nPathLen <= nBufSize )
+ aEntry.sPath = OUString ( reinterpret_cast<char const *>(&pBuffer[nPos + 30]),
+ aEntry.nPathLen,
+ RTL_TEXTENCODING_UTF8 );
+ else
+ {
+ Sequence < sal_Int8 > aFileName;
+ aGrabber.seek( nGenPos + nPos + 30 );
+ aGrabber.readBytes( aFileName, aEntry.nPathLen );
+ aEntry.sPath = OUString ( reinterpret_cast<const char *>(aFileName.getConstArray()),
+ aFileName.getLength(),
+ RTL_TEXTENCODING_UTF8 );
+ aEntry.nPathLen = static_cast< sal_Int16 >(aFileName.getLength());
+ }
+
+ aEntry.nOffset = nGenPos + nPos + 30 + aEntry.nPathLen + aEntry.nExtraLen;
+
+ if ( ( aEntry.nSize || aEntry.nCompressedSize ) && !checkSizeAndCRC( aEntry ) )
+ {
+ aEntry.nCrc = 0;
+ aEntry.nCompressedSize = 0;
+ aEntry.nSize = 0;
+ }
+
+ aEntries.emplace( aEntry.sPath, aEntry );
+ }
+ }
+ }
+
+ nPos += 4;
+ }
+ else if (pBuffer[nPos] == 'P' && pBuffer[nPos+1] == 'K' && pBuffer[nPos+2] == 7 && pBuffer[nPos+3] == 8 )
+ {
+ sal_Int64 nCompressedSize, nSize;
+ Sequence<sal_Int8> aTmpBuffer(&(pBuffer[nPos+4]), 12);
+ MemoryByteGrabber aMemGrabber(aTmpBuffer);
+ sal_Int32 nCRC32 = aMemGrabber.ReadInt32();
+ sal_uInt32 nCompressedSize32 = aMemGrabber.ReadUInt32();
+ sal_uInt32 nSize32 = aMemGrabber.ReadUInt32();
+
+ // FIXME64: work to be done here ...
+ nCompressedSize = nCompressedSize32;
+ nSize = nSize32;
+
+ for( auto& rEntry : aEntries )
+ {
+ // this is a broken package, accept this block not only for DEFLATED streams
+ if( rEntry.second.nFlag & 8 )
+ {
+ sal_Int64 nStreamOffset = nGenPos + nPos - nCompressedSize;
+ if ( nStreamOffset == rEntry.second.nOffset && nCompressedSize > rEntry.second.nCompressedSize )
+ {
+ // only DEFLATED blocks need to be checked
+ bool bAcceptBlock = ( rEntry.second.nMethod == STORED && nCompressedSize == nSize );
+
+ if ( !bAcceptBlock )
+ {
+ sal_Int64 nRealSize = 0;
+ sal_Int32 nRealCRC = 0;
+ getSizeAndCRC( nStreamOffset, nCompressedSize, &nRealSize, &nRealCRC );
+ bAcceptBlock = ( nRealSize == nSize && nRealCRC == nCRC32 );
+ }
+
+ if ( bAcceptBlock )
+ {
+ rEntry.second.nCrc = nCRC32;
+ rEntry.second.nCompressedSize = nCompressedSize;
+ rEntry.second.nSize = nSize;
+ }
+ }
+#if 0
+// for now ignore clearly broken streams
+ else if( !rEntry.second.nCompressedSize )
+ {
+ rEntry.second.nCrc = nCRC32;
+ sal_Int32 nRealStreamSize = nGenPos + nPos - rEntry.second.nOffset;
+ rEntry.second.nCompressedSize = nRealStreamSize;
+ rEntry.second.nSize = nSize;
+ }
+#endif
+ }
+ }
+
+ nPos += 4;
+ }
+ else
+ nPos++;
+ }
+
+ nGenPos += nPos;
+ aGrabber.seek( nGenPos );
+ }
+ }
+ catch ( IllegalArgumentException& )
+ {
+ throw ZipException("Zip END signature not found!" );
+ }
+ catch ( NotConnectedException& )
+ {
+ throw ZipException("Zip END signature not found!" );
+ }
+ catch ( BufferSizeExceededException& )
+ {
+ throw ZipException("Zip END signature not found!" );
+ }
+}
+
+bool ZipFile::checkSizeAndCRC( const ZipEntry& aEntry )
+{
+ ::osl::MutexGuard aGuard( m_aMutexHolder->GetMutex() );
+
+ sal_Int32 nCRC = 0;
+ sal_Int64 nSize = 0;
+
+ if( aEntry.nMethod == STORED )
+ return ( getCRC( aEntry.nOffset, aEntry.nSize ) == aEntry.nCrc );
+
+ getSizeAndCRC( aEntry.nOffset, aEntry.nCompressedSize, &nSize, &nCRC );
+ return ( aEntry.nSize == nSize && aEntry.nCrc == nCRC );
+}
+
+sal_Int32 ZipFile::getCRC( sal_Int64 nOffset, sal_Int64 nSize )
+{
+ ::osl::MutexGuard aGuard( m_aMutexHolder->GetMutex() );
+
+ Sequence < sal_Int8 > aBuffer;
+ CRC32 aCRC;
+ sal_Int64 nBlockSize = ::std::min(nSize, static_cast< sal_Int64 >(32000));
+
+ aGrabber.seek( nOffset );
+ for (sal_Int64 ind = 0;
+ aGrabber.readBytes( aBuffer, nBlockSize ) && ind * nBlockSize < nSize;
+ ++ind)
+ {
+ sal_Int64 nLen = ::std::min(nBlockSize, nSize - ind * nBlockSize);
+ aCRC.updateSegment(aBuffer, static_cast<sal_Int32>(nLen));
+ }
+
+ return aCRC.getValue();
+}
+
+void ZipFile::getSizeAndCRC( sal_Int64 nOffset, sal_Int64 nCompressedSize, sal_Int64 *nSize, sal_Int32 *nCRC )
+{
+ ::osl::MutexGuard aGuard( m_aMutexHolder->GetMutex() );
+
+ Sequence < sal_Int8 > aBuffer;
+ CRC32 aCRC;
+ sal_Int64 nRealSize = 0;
+ Inflater aInflaterLocal( true );
+ sal_Int32 nBlockSize = static_cast< sal_Int32 > (::std::min( nCompressedSize, static_cast< sal_Int64 >( 32000 ) ) );
+
+ aGrabber.seek( nOffset );
+ for ( sal_Int64 ind = 0;
+ !aInflaterLocal.finished() && aGrabber.readBytes( aBuffer, nBlockSize ) && ind * nBlockSize < nCompressedSize;
+ ind++ )
+ {
+ Sequence < sal_Int8 > aData( nBlockSize );
+ sal_Int32 nLastInflated = 0;
+ sal_Int64 nInBlock = 0;
+
+ aInflaterLocal.setInput( aBuffer );
+ do
+ {
+ nLastInflated = aInflaterLocal.doInflateSegment( aData, 0, nBlockSize );
+ aCRC.updateSegment( aData, nLastInflated );
+ nInBlock += nLastInflated;
+ } while( !aInflater.finished() && nLastInflated );
+
+ nRealSize += nInBlock;
+ }
+
+ *nSize = nRealSize;
+ *nCRC = aCRC.getValue();
+}
+
+/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
diff --git a/package/source/zipapi/ZipOutputEntry.cxx b/package/source/zipapi/ZipOutputEntry.cxx
new file mode 100644
index 000000000..897ea6212
--- /dev/null
+++ b/package/source/zipapi/ZipOutputEntry.cxx
@@ -0,0 +1,400 @@
+/* -*- 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 <ZipOutputEntry.hxx>
+
+#include <com/sun/star/io/TempFile.hpp>
+#include <com/sun/star/packages/zip/ZipConstants.hpp>
+
+#include <osl/diagnose.h>
+
+#include <PackageConstants.hxx>
+#include <ThreadedDeflater.hxx>
+#include <ZipEntry.hxx>
+#include <ZipFile.hxx>
+#include <ZipPackageStream.hxx>
+
+#include <algorithm>
+
+using namespace com::sun::star;
+using namespace com::sun::star::io;
+using namespace com::sun::star::uno;
+using namespace com::sun::star::packages::zip::ZipConstants;
+
+/** This class is used to deflate Zip entries
+ */
+ZipOutputEntryBase::ZipOutputEntryBase(
+ const css::uno::Reference< css::io::XOutputStream >& rxOutput,
+ const uno::Reference< uno::XComponentContext >& rxContext,
+ ZipEntry& rEntry,
+ ZipPackageStream* pStream,
+ bool bEncrypt,
+ bool checkStream)
+: m_xContext(rxContext)
+, m_xOutStream(rxOutput)
+, m_pCurrentEntry(&rEntry)
+, m_nDigested(0)
+, m_pCurrentStream(pStream)
+, m_bEncryptCurrentEntry(bEncrypt)
+{
+ assert(m_pCurrentEntry->nMethod == DEFLATED && "Use ZipPackageStream::rawWrite() for STORED entries");
+ (void)checkStream;
+ assert(!checkStream || m_xOutStream.is());
+ if (m_bEncryptCurrentEntry)
+ {
+ m_xCipherContext = ZipFile::StaticGetCipher( m_xContext, pStream->GetEncryptionData(), true );
+ m_xDigestContext = ZipFile::StaticGetDigestContextForChecksum( m_xContext, pStream->GetEncryptionData() );
+ }
+}
+
+void ZipOutputEntryBase::closeEntry()
+{
+ finishDeflater();
+
+ if ((m_pCurrentEntry->nFlag & 8) == 0)
+ {
+ if (m_pCurrentEntry->nSize != getDeflaterTotalIn())
+ {
+ OSL_FAIL("Invalid entry size");
+ }
+ if (m_pCurrentEntry->nCompressedSize != getDeflaterTotalOut())
+ {
+ // Different compression strategies make the merit of this
+ // test somewhat dubious
+ m_pCurrentEntry->nCompressedSize = getDeflaterTotalOut();
+ }
+ if (m_pCurrentEntry->nCrc != m_aCRC.getValue())
+ {
+ OSL_FAIL("Invalid entry CRC-32");
+ }
+ }
+ else
+ {
+ if ( !m_bEncryptCurrentEntry )
+ {
+ m_pCurrentEntry->nSize = getDeflaterTotalIn();
+ m_pCurrentEntry->nCompressedSize = getDeflaterTotalOut();
+ }
+ m_pCurrentEntry->nCrc = m_aCRC.getValue();
+ }
+ deflaterReset();
+ m_aCRC.reset();
+
+ if (!m_bEncryptCurrentEntry)
+ return;
+
+ m_xCipherContext.clear();
+
+ uno::Sequence< sal_Int8 > aDigestSeq;
+ if ( m_xDigestContext.is() )
+ {
+ aDigestSeq = m_xDigestContext->finalizeDigestAndDispose();
+ m_xDigestContext.clear();
+ }
+
+ if ( m_pCurrentStream )
+ m_pCurrentStream->setDigest( aDigestSeq );
+}
+
+void ZipOutputEntryBase::processDeflated( const uno::Sequence< sal_Int8 >& deflateBuffer, sal_Int32 nLength )
+{
+ if ( nLength > 0 )
+ {
+ uno::Sequence< sal_Int8 > aTmpBuffer( deflateBuffer.getConstArray(), nLength );
+ if ( m_bEncryptCurrentEntry && m_xDigestContext.is() && m_xCipherContext.is() )
+ {
+ // Need to update our digest before encryption...
+ sal_Int32 nDiff = n_ConstDigestLength - m_nDigested;
+ if ( nDiff )
+ {
+ sal_Int32 nEat = ::std::min( nLength, nDiff );
+ uno::Sequence< sal_Int8 > aTmpSeq( aTmpBuffer.getConstArray(), nEat );
+ m_xDigestContext->updateDigest( aTmpSeq );
+ m_nDigested = m_nDigested + static_cast< sal_Int16 >( nEat );
+ }
+
+ // FIXME64: uno::Sequence not 64bit safe.
+ uno::Sequence< sal_Int8 > aEncryptionBuffer = m_xCipherContext->convertWithCipherContext( aTmpBuffer );
+
+ m_xOutStream->writeBytes( aEncryptionBuffer );
+
+ // the sizes as well as checksum for encrypted streams is calculated here
+ m_pCurrentEntry->nCompressedSize += aEncryptionBuffer.getLength();
+ m_pCurrentEntry->nSize = m_pCurrentEntry->nCompressedSize;
+ m_aCRC.update( aEncryptionBuffer );
+ }
+ else
+ {
+ m_xOutStream->writeBytes ( aTmpBuffer );
+ }
+ }
+
+ if ( !(isDeflaterFinished() && m_bEncryptCurrentEntry && m_xDigestContext.is() && m_xCipherContext.is()) )
+ return;
+
+ // FIXME64: sequence not 64bit safe.
+ uno::Sequence< sal_Int8 > aEncryptionBuffer = m_xCipherContext->finalizeCipherContextAndDispose();
+ if ( aEncryptionBuffer.hasElements() )
+ {
+ m_xOutStream->writeBytes( aEncryptionBuffer );
+
+ // the sizes as well as checksum for encrypted streams are calculated here
+ m_pCurrentEntry->nCompressedSize += aEncryptionBuffer.getLength();
+ m_pCurrentEntry->nSize = m_pCurrentEntry->nCompressedSize;
+ m_aCRC.update( aEncryptionBuffer );
+ }
+}
+
+void ZipOutputEntryBase::processInput( const uno::Sequence< sal_Int8 >& rBuffer )
+{
+ if (!m_bEncryptCurrentEntry)
+ m_aCRC.updateSegment(rBuffer, rBuffer.getLength());
+}
+
+ZipOutputEntry::ZipOutputEntry(
+ const css::uno::Reference< css::io::XOutputStream >& rxOutput,
+ const uno::Reference< uno::XComponentContext >& rxContext,
+ ZipEntry& rEntry,
+ ZipPackageStream* pStream,
+ bool bEncrypt,
+ bool checkStream)
+: ZipOutputEntryBase(rxOutput, rxContext, rEntry, pStream, bEncrypt, checkStream)
+, m_aDeflateBuffer(n_ConstBufferSize)
+, m_aDeflater(DEFAULT_COMPRESSION, true)
+{
+}
+
+ZipOutputEntry::ZipOutputEntry(
+ const css::uno::Reference< css::io::XOutputStream >& rxOutput,
+ const uno::Reference< uno::XComponentContext >& rxContext,
+ ZipEntry& rEntry,
+ ZipPackageStream* pStream,
+ bool bEncrypt)
+: ZipOutputEntry( rxOutput, rxContext, rEntry, pStream, bEncrypt, true)
+{
+}
+
+void ZipOutputEntry::write( const Sequence< sal_Int8 >& rBuffer )
+{
+ if (!m_aDeflater.finished())
+ {
+ m_aDeflater.setInputSegment(rBuffer);
+ while (!m_aDeflater.needsInput())
+ doDeflate();
+ processInput(rBuffer);
+ }
+}
+
+void ZipOutputEntry::doDeflate()
+{
+ sal_Int32 nLength = m_aDeflater.doDeflateSegment(m_aDeflateBuffer, m_aDeflateBuffer.getLength());
+ processDeflated( m_aDeflateBuffer, nLength );
+}
+
+void ZipOutputEntry::finishDeflater()
+{
+ m_aDeflater.finish();
+ while (!m_aDeflater.finished())
+ doDeflate();
+}
+
+sal_Int64 ZipOutputEntry::getDeflaterTotalIn() const
+{
+ return m_aDeflater.getTotalIn();
+}
+
+sal_Int64 ZipOutputEntry::getDeflaterTotalOut() const
+{
+ return m_aDeflater.getTotalOut();
+}
+
+void ZipOutputEntry::deflaterReset()
+{
+ m_aDeflater.reset();
+}
+
+bool ZipOutputEntry::isDeflaterFinished() const
+{
+ return m_aDeflater.finished();
+}
+
+
+ZipOutputEntryInThread::ZipOutputEntryInThread(
+ const uno::Reference< uno::XComponentContext >& rxContext,
+ ZipEntry& rEntry,
+ ZipPackageStream* pStream,
+ bool bEncrypt)
+: ZipOutputEntry( uno::Reference< css::io::XOutputStream >(), rxContext, rEntry, pStream, bEncrypt, false )
+, m_bFinished(false)
+{
+}
+
+void ZipOutputEntryInThread::createBufferFile()
+{
+ assert(!m_xOutStream && !m_xTempFile &&
+ "should only be called in the threaded mode where there is no existing stream yet");
+ m_xTempFile.set(
+ io::TempFile::create(m_xContext),
+ uno::UNO_SET_THROW );
+ m_xOutStream = m_xTempFile->getOutputStream();
+}
+
+void ZipOutputEntryInThread::closeBufferFile()
+{
+ m_xOutStream->closeOutput();
+ m_xOutStream.clear();
+}
+
+void ZipOutputEntryInThread::deleteBufferFile()
+{
+ assert(!m_xOutStream.is() && m_xTempFile);
+ m_xTempFile.clear();
+}
+
+uno::Reference< io::XInputStream > ZipOutputEntryInThread::getData() const
+{
+ return m_xTempFile->getInputStream();
+}
+
+class ZipOutputEntryInThread::Task : public comphelper::ThreadTask
+{
+ ZipOutputEntryInThread *mpEntry;
+ uno::Reference< io::XInputStream > mxInStream;
+
+public:
+ Task( const std::shared_ptr<comphelper::ThreadTaskTag>& pTag, ZipOutputEntryInThread *pEntry,
+ const uno::Reference< io::XInputStream >& xInStream )
+ : comphelper::ThreadTask(pTag)
+ , mpEntry(pEntry)
+ , mxInStream(xInStream)
+ {}
+
+private:
+ virtual void doWork() override
+ {
+ try
+ {
+ mpEntry->createBufferFile();
+ mpEntry->writeStream(mxInStream);
+ mxInStream.clear();
+ mpEntry->closeBufferFile();
+ mpEntry->setFinished();
+ }
+ catch (...)
+ {
+ mpEntry->setParallelDeflateException(std::current_exception());
+ try
+ {
+ if (mpEntry->m_xOutStream.is())
+ mpEntry->closeBufferFile();
+ if (mpEntry->m_xTempFile)
+ mpEntry->deleteBufferFile();
+ }
+ catch (uno::Exception const&)
+ {
+ }
+ mpEntry->setFinished();
+ }
+ }
+};
+
+std::unique_ptr<comphelper::ThreadTask> ZipOutputEntryInThread::createTask(
+ const std::shared_ptr<comphelper::ThreadTaskTag>& pTag,
+ const uno::Reference< io::XInputStream >& xInStream )
+{
+ return std::make_unique<Task>(pTag, this, xInStream);
+}
+
+void ZipOutputEntry::writeStream(const uno::Reference< io::XInputStream >& xInStream)
+{
+ sal_Int32 nLength = 0;
+ uno::Sequence< sal_Int8 > aSeq(n_ConstBufferSize);
+ do
+ {
+ nLength = xInStream->readBytes(aSeq, n_ConstBufferSize);
+ if (nLength != n_ConstBufferSize)
+ aSeq.realloc(nLength);
+
+ write(aSeq);
+ }
+ while (nLength == n_ConstBufferSize);
+ closeEntry();
+}
+
+
+ZipOutputEntryParallel::ZipOutputEntryParallel(
+ const css::uno::Reference< css::io::XOutputStream >& rxOutput,
+ const uno::Reference< uno::XComponentContext >& rxContext,
+ ZipEntry& rEntry,
+ ZipPackageStream* pStream,
+ bool bEncrypt)
+: ZipOutputEntryBase(rxOutput, rxContext, rEntry, pStream, bEncrypt, true)
+, totalIn(0)
+, totalOut(0)
+, finished(false)
+{
+}
+
+void ZipOutputEntryParallel::writeStream(const uno::Reference< io::XInputStream >& xInStream)
+{
+ ZipUtils::ThreadedDeflater deflater( DEFAULT_COMPRESSION );
+ deflater.deflateWrite(xInStream,
+ [this](const uno::Sequence< sal_Int8 >& rBuffer, sal_Int32 nLen) {
+ if (!m_bEncryptCurrentEntry)
+ m_aCRC.updateSegment(rBuffer, nLen);
+ },
+ [this](const uno::Sequence< sal_Int8 >& rBuffer, sal_Int32 nLen) {
+ processDeflated(rBuffer, nLen);
+ }
+ );
+ finished = true;
+ processDeflated( uno::Sequence< sal_Int8 >(), 0 ); // finish encrypting, etc.
+ totalIn = deflater.getTotalIn();
+ totalOut = deflater.getTotalOut();
+ closeEntry();
+}
+
+void ZipOutputEntryParallel::finishDeflater()
+{
+ // ThreadedDeflater is called synchronously in one call, so nothing to do here.
+}
+
+sal_Int64 ZipOutputEntryParallel::getDeflaterTotalIn() const
+{
+ return totalIn;
+}
+
+sal_Int64 ZipOutputEntryParallel::getDeflaterTotalOut() const
+{
+ return totalOut;
+}
+
+void ZipOutputEntryParallel::deflaterReset()
+{
+ totalIn = 0;
+ totalOut = 0;
+ finished = false;
+}
+
+bool ZipOutputEntryParallel::isDeflaterFinished() const
+{
+ return finished;
+}
+
+/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
diff --git a/package/source/zipapi/ZipOutputStream.cxx b/package/source/zipapi/ZipOutputStream.cxx
new file mode 100644
index 000000000..33321627b
--- /dev/null
+++ b/package/source/zipapi/ZipOutputStream.cxx
@@ -0,0 +1,365 @@
+/* -*- 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 <ZipOutputStream.hxx>
+
+#include <com/sun/star/packages/zip/ZipConstants.hpp>
+#include <com/sun/star/io/IOException.hpp>
+#include <com/sun/star/io/XInputStream.hpp>
+#include <comphelper/storagehelper.hxx>
+
+#include <osl/time.h>
+#include <osl/thread.hxx>
+
+#include <PackageConstants.hxx>
+#include <ZipEntry.hxx>
+#include <ZipOutputEntry.hxx>
+#include <ZipPackageStream.hxx>
+
+using namespace com::sun::star;
+using namespace com::sun::star::io;
+using namespace com::sun::star::uno;
+using namespace com::sun::star::packages::zip::ZipConstants;
+
+/** This class is used to write Zip files
+ */
+ZipOutputStream::ZipOutputStream( const uno::Reference < io::XOutputStream > &xOStream )
+: m_xStream(xOStream)
+, mpThreadTaskTag( comphelper::ThreadPool::createThreadTaskTag() )
+, m_aChucker(xOStream)
+, m_pCurrentEntry(nullptr)
+{
+}
+
+ZipOutputStream::~ZipOutputStream()
+{
+}
+
+void ZipOutputStream::setEntry( ZipEntry *pEntry )
+{
+ if (pEntry->nTime == -1)
+ pEntry->nTime = getCurrentDosTime();
+ if (pEntry->nMethod == -1)
+ pEntry->nMethod = DEFLATED;
+ pEntry->nVersion = 20;
+ pEntry->nFlag = 1 << 11;
+ if (pEntry->nSize == -1 || pEntry->nCompressedSize == -1 ||
+ pEntry->nCrc == -1)
+ {
+ pEntry->nSize = pEntry->nCompressedSize = 0;
+ pEntry->nFlag |= 8;
+ }
+}
+
+void ZipOutputStream::addDeflatingThreadTask( ZipOutputEntryInThread *pEntry, std::unique_ptr<comphelper::ThreadTask> pTask )
+{
+ comphelper::ThreadPool::getSharedOptimalPool().pushTask(std::move(pTask));
+ m_aEntries.push_back(pEntry);
+}
+
+void ZipOutputStream::rawWrite( const Sequence< sal_Int8 >& rBuffer )
+{
+ m_aChucker.WriteBytes( rBuffer );
+}
+
+void ZipOutputStream::rawCloseEntry( bool bEncrypt )
+{
+ assert(m_pCurrentEntry && "Forgot to call writeLOC()?");
+ if ( m_pCurrentEntry->nMethod == DEFLATED && ( m_pCurrentEntry->nFlag & 8 ) )
+ writeEXT(*m_pCurrentEntry);
+
+ if (bEncrypt)
+ m_pCurrentEntry->nMethod = STORED;
+
+ m_pCurrentEntry = nullptr;
+}
+
+void ZipOutputStream::consumeScheduledThreadTaskEntry(std::unique_ptr<ZipOutputEntryInThread> pCandidate)
+{
+ //Any exceptions thrown in the threads were caught and stored for now
+ const std::exception_ptr& rCaughtException(pCandidate->getParallelDeflateException());
+ if (rCaughtException)
+ {
+ m_aDeflateException = rCaughtException; // store it for later throwing
+ // the exception handler in DeflateThreadTask should have cleaned temp file
+ return;
+ }
+
+ writeLOC(pCandidate->getZipEntry(), pCandidate->isEncrypt());
+
+ sal_Int32 nRead;
+ uno::Sequence< sal_Int8 > aSequence(n_ConstBufferSize);
+ uno::Reference< io::XInputStream > xInput = pCandidate->getData();
+ do
+ {
+ nRead = xInput->readBytes(aSequence, n_ConstBufferSize);
+ if (nRead < n_ConstBufferSize)
+ aSequence.realloc(nRead);
+
+ rawWrite(aSequence);
+ }
+ while (nRead == n_ConstBufferSize);
+ xInput.clear();
+
+ rawCloseEntry(pCandidate->isEncrypt());
+
+ pCandidate->getZipPackageStream()->successfullyWritten(pCandidate->getZipEntry());
+ pCandidate->deleteBufferFile();
+}
+
+void ZipOutputStream::consumeFinishedScheduledThreadTaskEntries()
+{
+ std::vector< ZipOutputEntryInThread* > aNonFinishedEntries;
+
+ for(ZipOutputEntryInThread* pEntry : m_aEntries)
+ {
+ if(pEntry->isFinished())
+ {
+ consumeScheduledThreadTaskEntry(std::unique_ptr<ZipOutputEntryInThread>(pEntry));
+ }
+ else
+ {
+ aNonFinishedEntries.push_back(pEntry);
+ }
+ }
+
+ // always reset to non-consumed entries
+ m_aEntries = aNonFinishedEntries;
+}
+
+void ZipOutputStream::reduceScheduledThreadTasksToGivenNumberOrLess(std::size_t nThreadTasks)
+{
+ while(m_aEntries.size() > nThreadTasks)
+ {
+ consumeFinishedScheduledThreadTaskEntries();
+
+ if(m_aEntries.size() > nThreadTasks)
+ {
+ osl::Thread::wait(std::chrono::microseconds(100));
+ }
+ }
+}
+
+void ZipOutputStream::finish()
+{
+ assert(!m_aZipList.empty() && "Zip file must have at least one entry!");
+
+ // Wait for all thread tasks to finish & write
+ comphelper::ThreadPool::getSharedOptimalPool().waitUntilDone(mpThreadTaskTag);
+
+ // consume all processed entries
+ while(!m_aEntries.empty())
+ {
+ ZipOutputEntryInThread* pCandidate = m_aEntries.back();
+ m_aEntries.pop_back();
+ consumeScheduledThreadTaskEntry(std::unique_ptr<ZipOutputEntryInThread>(pCandidate));
+ }
+
+ sal_Int32 nOffset= static_cast < sal_Int32 > (m_aChucker.GetPosition());
+ for (ZipEntry* p : m_aZipList)
+ {
+ writeCEN( *p );
+ delete p;
+ }
+ writeEND( nOffset, static_cast < sal_Int32 > (m_aChucker.GetPosition()) - nOffset);
+ m_xStream->flush();
+ m_aZipList.clear();
+
+ if (m_aDeflateException)
+ { // throw once all thread tasks are finished and m_aEntries can be released
+ std::rethrow_exception(m_aDeflateException);
+ }
+}
+
+const css::uno::Reference< css::io::XOutputStream >& ZipOutputStream::getStream() const
+{
+ return m_xStream;
+}
+
+void ZipOutputStream::writeEND(sal_uInt32 nOffset, sal_uInt32 nLength)
+{
+ m_aChucker.WriteInt32( ENDSIG );
+ m_aChucker.WriteInt16( 0 );
+ m_aChucker.WriteInt16( 0 );
+ m_aChucker.WriteInt16( m_aZipList.size() );
+ m_aChucker.WriteInt16( m_aZipList.size() );
+ m_aChucker.WriteUInt32( nLength );
+ m_aChucker.WriteUInt32( nOffset );
+ m_aChucker.WriteInt16( 0 );
+}
+
+static sal_uInt32 getTruncated( sal_Int64 nNum, bool *pIsTruncated )
+{
+ if( nNum >= 0xffffffff )
+ {
+ *pIsTruncated = true;
+ return 0xffffffff;
+ }
+ else
+ return static_cast< sal_uInt32 >( nNum );
+}
+
+void ZipOutputStream::writeCEN( const ZipEntry &rEntry )
+{
+ if ( !::comphelper::OStorageHelper::IsValidZipEntryFileName( rEntry.sPath, true ) )
+ throw IOException("Unexpected character is used in file name." );
+
+ OString sUTF8Name = OUStringToOString( rEntry.sPath, RTL_TEXTENCODING_UTF8 );
+ sal_Int16 nNameLength = static_cast < sal_Int16 > ( sUTF8Name.getLength() );
+
+ m_aChucker.WriteInt32( CENSIG );
+ m_aChucker.WriteInt16( rEntry.nVersion );
+ m_aChucker.WriteInt16( rEntry.nVersion );
+ m_aChucker.WriteInt16( rEntry.nFlag );
+ m_aChucker.WriteInt16( rEntry.nMethod );
+ bool bWrite64Header = false;
+
+ m_aChucker.WriteUInt32( rEntry.nTime );
+ m_aChucker.WriteUInt32( rEntry.nCrc );
+ m_aChucker.WriteUInt32( getTruncated( rEntry.nCompressedSize, &bWrite64Header ) );
+ m_aChucker.WriteUInt32( getTruncated( rEntry.nSize, &bWrite64Header ) );
+ m_aChucker.WriteInt16( nNameLength );
+ m_aChucker.WriteInt16( 0 );
+ m_aChucker.WriteInt16( 0 );
+ m_aChucker.WriteInt16( 0 );
+ m_aChucker.WriteInt16( 0 );
+ m_aChucker.WriteInt32( 0 );
+ m_aChucker.WriteUInt32( getTruncated( rEntry.nOffset, &bWrite64Header ) );
+
+ if( bWrite64Header )
+ {
+ // FIXME64: need to append a ZIP64 header instead of throwing
+ // We're about to silently lose people's data - which they are
+ // unlikely to appreciate so fail instead:
+ throw IOException( "File contains streams that are too large." );
+ }
+
+ Sequence < sal_Int8 > aSequence( reinterpret_cast<sal_Int8 const *>(sUTF8Name.getStr()), sUTF8Name.getLength() );
+ m_aChucker.WriteBytes( aSequence );
+}
+
+void ZipOutputStream::writeEXT( const ZipEntry &rEntry )
+{
+ bool bWrite64Header = false;
+
+ m_aChucker.WriteInt32( EXTSIG );
+ m_aChucker.WriteUInt32( rEntry.nCrc );
+ m_aChucker.WriteUInt32( getTruncated( rEntry.nCompressedSize, &bWrite64Header ) );
+ m_aChucker.WriteUInt32( getTruncated( rEntry.nSize, &bWrite64Header ) );
+
+ if( bWrite64Header )
+ {
+ // FIXME64: need to append a ZIP64 header instead of throwing
+ // We're about to silently lose people's data - which they are
+ // unlikely to appreciate so fail instead:
+ throw IOException( "File contains streams that are too large." );
+ }
+}
+
+void ZipOutputStream::writeLOC( ZipEntry *pEntry, bool bEncrypt )
+{
+ assert(!m_pCurrentEntry && "Forgot to close an entry with rawCloseEntry()?");
+ m_pCurrentEntry = pEntry;
+ m_aZipList.push_back( m_pCurrentEntry );
+ const ZipEntry &rEntry = *m_pCurrentEntry;
+
+ if ( !::comphelper::OStorageHelper::IsValidZipEntryFileName( rEntry.sPath, true ) )
+ throw IOException("Unexpected character is used in file name." );
+
+ OString sUTF8Name = OUStringToOString( rEntry.sPath, RTL_TEXTENCODING_UTF8 );
+ sal_Int16 nNameLength = static_cast < sal_Int16 > ( sUTF8Name.getLength() );
+
+ m_aChucker.WriteInt32( LOCSIG );
+ m_aChucker.WriteInt16( rEntry.nVersion );
+
+ m_aChucker.WriteInt16( rEntry.nFlag );
+ // If it's an encrypted entry, we pretend its stored plain text
+ if (bEncrypt)
+ m_aChucker.WriteInt16( STORED );
+ else
+ m_aChucker.WriteInt16( rEntry.nMethod );
+
+ bool bWrite64Header = false;
+
+ m_aChucker.WriteUInt32( rEntry.nTime );
+ if ((rEntry.nFlag & 8) == 8 )
+ {
+ m_aChucker.WriteInt32( 0 );
+ m_aChucker.WriteInt32( 0 );
+ m_aChucker.WriteInt32( 0 );
+ }
+ else
+ {
+ m_aChucker.WriteUInt32( rEntry.nCrc );
+ m_aChucker.WriteUInt32( getTruncated( rEntry.nCompressedSize, &bWrite64Header ) );
+ m_aChucker.WriteUInt32( getTruncated( rEntry.nSize, &bWrite64Header ) );
+ }
+ m_aChucker.WriteInt16( nNameLength );
+ m_aChucker.WriteInt16( 0 );
+
+ if( bWrite64Header )
+ {
+ // FIXME64: need to append a ZIP64 header instead of throwing
+ // We're about to silently lose people's data - which they are
+ // unlikely to appreciate so fail instead:
+ throw IOException( "File contains streams that are too large." );
+ }
+
+ Sequence < sal_Int8 > aSequence( reinterpret_cast<sal_Int8 const *>(sUTF8Name.getStr()), sUTF8Name.getLength() );
+ m_aChucker.WriteBytes( aSequence );
+
+ m_pCurrentEntry->nOffset = m_aChucker.GetPosition() - (LOCHDR + nNameLength);
+}
+
+sal_uInt32 ZipOutputStream::getCurrentDosTime()
+{
+ oslDateTime aDateTime;
+ TimeValue aTimeValue;
+ osl_getSystemTime ( &aTimeValue );
+ osl_getDateTimeFromTimeValue( &aTimeValue, &aDateTime);
+
+ // at year 2108, there is an overflow
+ // -> some decision needs to be made
+ // how to handle the ZIP file format (just overflow?)
+
+ // if the current system time is before 1980,
+ // then the time traveller will have to make a decision
+ // how to handle the ZIP file format before it is invented
+ // (just underflow?)
+
+ assert(aDateTime.Year > 1980 && aDateTime.Year < 2108);
+
+ sal_uInt32 nYear = static_cast <sal_uInt32> (aDateTime.Year);
+
+ if (nYear>=1980)
+ nYear-=1980;
+ else if (nYear>=80)
+ {
+ nYear-=80;
+ }
+ sal_uInt32 nResult = static_cast < sal_uInt32>( ( ( ( aDateTime.Day) +
+ ( 32 * (aDateTime.Month)) +
+ ( 512 * nYear ) ) << 16) |
+ ( ( aDateTime.Seconds/2) +
+ ( 32 * aDateTime.Minutes) +
+ ( 2048 * static_cast <sal_uInt32 > (aDateTime.Hours) ) ) );
+ return nResult;
+}
+
+/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
diff --git a/package/source/zipapi/blowfishcontext.cxx b/package/source/zipapi/blowfishcontext.cxx
new file mode 100644
index 000000000..1b5ed4a14
--- /dev/null
+++ b/package/source/zipapi/blowfishcontext.cxx
@@ -0,0 +1,109 @@
+/* -*- 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 <sal/config.h>
+
+#include <com/sun/star/lang/DisposedException.hpp>
+#include <rtl/cipher.h>
+#include <rtl/ref.hxx>
+
+#include "blowfishcontext.hxx"
+
+using namespace ::com::sun::star;
+
+// static
+uno::Reference< xml::crypto::XCipherContext > BlowfishCFB8CipherContext::Create( const uno::Sequence< sal_Int8 >& aDerivedKey, const uno::Sequence< sal_Int8 >& aInitVector, bool bEncrypt )
+{
+ ::rtl::Reference< BlowfishCFB8CipherContext > xResult = new BlowfishCFB8CipherContext();
+ xResult->m_pCipher = rtl_cipher_create( rtl_Cipher_AlgorithmBF, rtl_Cipher_ModeStream );
+ if ( !xResult->m_pCipher )
+ throw uno::RuntimeException("Can not create cipher!" );
+
+ if ( rtl_Cipher_E_None != rtl_cipher_init(
+ xResult->m_pCipher,
+ bEncrypt ? rtl_Cipher_DirectionEncode : rtl_Cipher_DirectionDecode,
+ reinterpret_cast< const sal_uInt8* >( aDerivedKey.getConstArray() ),
+ aDerivedKey.getLength(),
+ reinterpret_cast< const sal_uInt8* >( aInitVector.getConstArray() ),
+ aInitVector.getLength() ) )
+ {
+ throw uno::RuntimeException("Can not initialize cipher!" );
+ }
+
+ xResult->m_bEncrypt = bEncrypt;
+
+ return xResult;
+}
+
+BlowfishCFB8CipherContext::~BlowfishCFB8CipherContext()
+{
+ if ( m_pCipher )
+ {
+ rtl_cipher_destroy ( m_pCipher );
+ m_pCipher = nullptr;
+ }
+}
+
+uno::Sequence< sal_Int8 > SAL_CALL BlowfishCFB8CipherContext::convertWithCipherContext( const uno::Sequence< ::sal_Int8 >& aData )
+{
+ std::scoped_lock aGuard( m_aMutex );
+ if ( !m_pCipher )
+ throw lang::DisposedException();
+
+ uno::Sequence< sal_Int8 > aResult( aData.getLength() );
+ rtlCipherError nError = rtl_Cipher_E_None;
+
+ if ( m_bEncrypt )
+ {
+ nError = rtl_cipher_encode( m_pCipher,
+ aData.getConstArray(),
+ aData.getLength(),
+ reinterpret_cast< sal_uInt8* >( aResult.getArray() ),
+ aResult.getLength() );
+ }
+ else
+ {
+ nError = rtl_cipher_decode( m_pCipher,
+ aData.getConstArray(),
+ aData.getLength(),
+ reinterpret_cast< sal_uInt8* >( aResult.getArray() ),
+ aResult.getLength() );
+ }
+
+ if ( rtl_Cipher_E_None != nError )
+ {
+ throw uno::RuntimeException("Can not decrypt/encrypt with cipher!" );
+ }
+
+ return aResult;
+}
+
+uno::Sequence< ::sal_Int8 > SAL_CALL BlowfishCFB8CipherContext::finalizeCipherContextAndDispose()
+{
+ std::scoped_lock aGuard( m_aMutex );
+ if ( !m_pCipher )
+ throw lang::DisposedException();
+
+ rtl_cipher_destroy ( m_pCipher );
+ m_pCipher = nullptr;
+
+ return uno::Sequence< sal_Int8 >();
+}
+
+/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
diff --git a/package/source/zipapi/blowfishcontext.hxx b/package/source/zipapi/blowfishcontext.hxx
new file mode 100644
index 000000000..c0b603c15
--- /dev/null
+++ b/package/source/zipapi/blowfishcontext.hxx
@@ -0,0 +1,51 @@
+/* -*- 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 .
+ */
+#ifndef INCLUDED_PACKAGE_SOURCE_ZIPAPI_BLOWFISHCONTEXT_HXX
+#define INCLUDED_PACKAGE_SOURCE_ZIPAPI_BLOWFISHCONTEXT_HXX
+
+#include <com/sun/star/xml/crypto/XCipherContext.hpp>
+
+#include <cppuhelper/implbase.hxx>
+#include <mutex>
+
+class BlowfishCFB8CipherContext : public cppu::WeakImplHelper< css::xml::crypto::XCipherContext >
+{
+ std::mutex m_aMutex;
+ void* m_pCipher;
+ bool m_bEncrypt;
+
+ BlowfishCFB8CipherContext()
+ : m_pCipher( nullptr )
+ , m_bEncrypt( false )
+ {}
+
+public:
+
+ virtual ~BlowfishCFB8CipherContext() override;
+
+ static css::uno::Reference< css::xml::crypto::XCipherContext >
+ Create( const css::uno::Sequence< sal_Int8 >& aDerivedKey, const css::uno::Sequence< sal_Int8 >& aInitVector, bool bEncrypt );
+
+ virtual css::uno::Sequence< ::sal_Int8 > SAL_CALL convertWithCipherContext( const css::uno::Sequence< ::sal_Int8 >& aData ) override;
+ virtual css::uno::Sequence< ::sal_Int8 > SAL_CALL finalizeCipherContextAndDispose( ) override;
+};
+
+#endif // INCLUDED_PACKAGE_SOURCE_ZIPAPI_BLOWFISHCONTEXT_HXX
+
+/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
diff --git a/package/source/zipapi/sha1context.cxx b/package/source/zipapi/sha1context.cxx
new file mode 100644
index 000000000..4b6cbd2d3
--- /dev/null
+++ b/package/source/zipapi/sha1context.cxx
@@ -0,0 +1,119 @@
+/* -*- 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 <sal/config.h>
+
+#include <com/sun/star/lang/DisposedException.hpp>
+#include <rtl/digest.h>
+#include <rtl/ref.hxx>
+
+#include "sha1context.hxx"
+
+using namespace ::com::sun::star;
+
+// static
+uno::Reference<xml::crypto::XDigestContext> StarOfficeSHA1DigestContext::Create()
+{
+ ::rtl::Reference<StarOfficeSHA1DigestContext> xResult = new StarOfficeSHA1DigestContext();
+ xResult->m_pDigest = rtl_digest_createSHA1();
+ if ( !xResult->m_pDigest )
+ throw uno::RuntimeException("Can not create cipher!" );
+
+ return xResult;
+}
+
+StarOfficeSHA1DigestContext::~StarOfficeSHA1DigestContext()
+{
+ if ( m_pDigest )
+ {
+ rtl_digest_destroySHA1( m_pDigest );
+ m_pDigest = nullptr;
+ }
+}
+
+void SAL_CALL StarOfficeSHA1DigestContext::updateDigest(const uno::Sequence<::sal_Int8>& aData)
+{
+ std::scoped_lock aGuard( m_aMutex );
+ if ( !m_pDigest )
+ throw lang::DisposedException();
+
+ if ( rtl_Digest_E_None != rtl_digest_updateSHA1( m_pDigest, aData.getConstArray(), aData.getLength() ) )
+ {
+ rtl_digest_destroySHA1( m_pDigest );
+ m_pDigest = nullptr;
+
+ throw uno::RuntimeException();
+ }
+}
+
+uno::Sequence<::sal_Int8> SAL_CALL StarOfficeSHA1DigestContext::finalizeDigestAndDispose()
+{
+ std::scoped_lock aGuard( m_aMutex );
+ if ( !m_pDigest )
+ throw lang::DisposedException();
+
+ uno::Sequence< sal_Int8 > aResult( RTL_DIGEST_LENGTH_SHA1 );
+ if ( rtl_Digest_E_None != rtl_digest_getSHA1( m_pDigest, reinterpret_cast< sal_uInt8* >( aResult.getArray() ), aResult.getLength() ) )
+ {
+ rtl_digest_destroySHA1( m_pDigest );
+ m_pDigest = nullptr;
+
+ throw uno::RuntimeException();
+ }
+
+ rtl_digest_destroySHA1( m_pDigest );
+ m_pDigest = nullptr;
+
+ return aResult;
+}
+
+uno::Reference<xml::crypto::XDigestContext> CorrectSHA1DigestContext::Create()
+{
+ return new CorrectSHA1DigestContext();
+}
+
+CorrectSHA1DigestContext::CorrectSHA1DigestContext()
+{
+}
+
+CorrectSHA1DigestContext::~CorrectSHA1DigestContext()
+{
+}
+
+void SAL_CALL CorrectSHA1DigestContext::updateDigest(const uno::Sequence<::sal_Int8>& rData)
+{
+ std::scoped_lock aGuard(m_Mutex);
+ if (m_bDisposed)
+ throw lang::DisposedException();
+
+ m_Hash.update(reinterpret_cast<unsigned char const*>(rData.getConstArray()), rData.getLength());
+}
+
+uno::Sequence<::sal_Int8> SAL_CALL CorrectSHA1DigestContext::finalizeDigestAndDispose()
+{
+ std::scoped_lock aGuard(m_Mutex);
+ if (m_bDisposed)
+ throw lang::DisposedException();
+
+ m_bDisposed = true;
+ std::vector<unsigned char> const sha1(m_Hash.finalize());
+ return uno::Sequence<sal_Int8>(reinterpret_cast<sal_Int8 const*>(sha1.data()), sha1.size());
+}
+
+/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
diff --git a/package/source/zipapi/sha1context.hxx b/package/source/zipapi/sha1context.hxx
new file mode 100644
index 000000000..6cc09da01
--- /dev/null
+++ b/package/source/zipapi/sha1context.hxx
@@ -0,0 +1,71 @@
+/* -*- 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 .
+ */
+#ifndef INCLUDED_PACKAGE_SOURCE_ZIPAPI_SHA1CONTEXT_HXX
+#define INCLUDED_PACKAGE_SOURCE_ZIPAPI_SHA1CONTEXT_HXX
+
+#include <com/sun/star/xml/crypto/XDigestContext.hpp>
+
+#include <comphelper/hash.hxx>
+#include <cppuhelper/implbase.hxx>
+#include <mutex>
+
+class StarOfficeSHA1DigestContext
+ : public cppu::WeakImplHelper<css::xml::crypto::XDigestContext>
+{
+ std::mutex m_aMutex;
+ void* m_pDigest;
+
+ StarOfficeSHA1DigestContext()
+ : m_pDigest( nullptr )
+ {}
+
+public:
+
+ virtual ~StarOfficeSHA1DigestContext() override;
+
+ static css::uno::Reference< css::xml::crypto::XDigestContext > Create();
+
+ virtual void SAL_CALL updateDigest( const css::uno::Sequence< ::sal_Int8 >& aData ) override;
+ virtual css::uno::Sequence< ::sal_Int8 > SAL_CALL finalizeDigestAndDispose() override;
+
+};
+
+class CorrectSHA1DigestContext
+ : public cppu::WeakImplHelper<css::xml::crypto::XDigestContext>
+{
+ std::mutex m_Mutex;
+ ::comphelper::Hash m_Hash{::comphelper::HashType::SHA1};
+ bool m_bDisposed{false};
+
+ CorrectSHA1DigestContext();
+
+public:
+
+ virtual ~CorrectSHA1DigestContext() override;
+
+ static css::uno::Reference<css::xml::crypto::XDigestContext> Create();
+
+ virtual void SAL_CALL updateDigest(const css::uno::Sequence<::sal_Int8>& rData) override;
+ virtual css::uno::Sequence<::sal_Int8> SAL_CALL finalizeDigestAndDispose() override;
+
+};
+
+#endif
+
+/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
diff --git a/package/source/zippackage/ZipPackage.cxx b/package/source/zippackage/ZipPackage.cxx
new file mode 100644
index 000000000..9270bb705
--- /dev/null
+++ b/package/source/zippackage/ZipPackage.cxx
@@ -0,0 +1,1837 @@
+/* -*- 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 <ZipPackage.hxx>
+#include "ZipPackageSink.hxx"
+#include <ZipEnumeration.hxx>
+#include <ZipPackageStream.hxx>
+#include <ZipPackageFolder.hxx>
+#include <ZipOutputEntry.hxx>
+#include <ZipOutputStream.hxx>
+#include <ZipPackageBuffer.hxx>
+#include <ZipFile.hxx>
+#include <PackageConstants.hxx>
+#include <com/sun/star/beans/PropertyValue.hpp>
+#include <com/sun/star/packages/zip/ZipConstants.hpp>
+#include <com/sun/star/packages/zip/ZipException.hpp>
+#include <com/sun/star/packages/zip/ZipIOException.hpp>
+#include <com/sun/star/packages/manifest/ManifestReader.hpp>
+#include <com/sun/star/packages/manifest/ManifestWriter.hpp>
+#include <com/sun/star/io/TempFile.hpp>
+#include <com/sun/star/io/XStream.hpp>
+#include <com/sun/star/io/XInputStream.hpp>
+#include <com/sun/star/io/XOutputStream.hpp>
+#include <com/sun/star/io/XTruncate.hpp>
+#include <com/sun/star/io/XSeekable.hpp>
+#include <com/sun/star/lang/WrappedTargetRuntimeException.hpp>
+#include <com/sun/star/container/XNameContainer.hpp>
+#include <comphelper/fileurl.hxx>
+#include <ucbhelper/content.hxx>
+#include <cppuhelper/exc_hlp.hxx>
+#include <com/sun/star/ucb/ContentCreationException.hpp>
+#include <com/sun/star/ucb/TransferInfo.hpp>
+#include <com/sun/star/ucb/NameClash.hpp>
+#include <com/sun/star/ucb/OpenCommandArgument2.hpp>
+#include <com/sun/star/ucb/OpenMode.hpp>
+#include <com/sun/star/ucb/SimpleFileAccess.hpp>
+#include <com/sun/star/io/XActiveDataStreamer.hpp>
+#include <com/sun/star/embed/UseBackupException.hpp>
+#include <com/sun/star/embed/StorageFormats.hpp>
+#include <com/sun/star/beans/NamedValue.hpp>
+#include <com/sun/star/xml/crypto/DigestID.hpp>
+#include <cppuhelper/implbase.hxx>
+#include <rtl/uri.hxx>
+#include <rtl/random.h>
+#include <o3tl/string_view.hxx>
+#include <osl/diagnose.h>
+#include <sal/log.hxx>
+#include <com/sun/star/io/XAsyncOutputMonitor.hpp>
+
+#include <string_view>
+
+#include <comphelper/seekableinput.hxx>
+#include <comphelper/storagehelper.hxx>
+#include <comphelper/ofopxmlhelper.hxx>
+#include <comphelper/documentconstants.hxx>
+#include <comphelper/sequenceashashmap.hxx>
+#include <cppuhelper/supportsservice.hxx>
+#include <comphelper/sequence.hxx>
+#include <comphelper/servicehelper.hxx>
+
+using namespace osl;
+using namespace cppu;
+using namespace ucbhelper;
+using namespace com::sun::star;
+using namespace com::sun::star::io;
+using namespace com::sun::star::uno;
+using namespace com::sun::star::ucb;
+using namespace com::sun::star::util;
+using namespace com::sun::star::lang;
+using namespace com::sun::star::task;
+using namespace com::sun::star::beans;
+using namespace com::sun::star::packages;
+using namespace com::sun::star::container;
+using namespace com::sun::star::packages::zip;
+using namespace com::sun::star::packages::manifest;
+using namespace com::sun::star::packages::zip::ZipConstants;
+
+#if OSL_DEBUG_LEVEL > 0
+#define THROW_WHERE SAL_WHERE
+#else
+#define THROW_WHERE ""
+#endif
+
+namespace {
+
+class ActiveDataStreamer : public ::cppu::WeakImplHelper< XActiveDataStreamer >
+{
+ uno::Reference< XStream > mStream;
+public:
+
+ virtual uno::Reference< XStream > SAL_CALL getStream() override
+ { return mStream; }
+
+ virtual void SAL_CALL setStream( const uno::Reference< XStream >& stream ) override
+ { mStream = stream; }
+};
+
+class DummyInputStream : public ::cppu::WeakImplHelper< XInputStream >
+{
+ virtual sal_Int32 SAL_CALL readBytes( uno::Sequence< sal_Int8 >&, sal_Int32 ) override
+ { return 0; }
+
+ virtual sal_Int32 SAL_CALL readSomeBytes( uno::Sequence< sal_Int8 >&, sal_Int32 ) override
+ { return 0; }
+
+ virtual void SAL_CALL skipBytes( sal_Int32 ) override
+ {}
+
+ virtual sal_Int32 SAL_CALL available() override
+ { return 0; }
+
+ virtual void SAL_CALL closeInput() override
+ {}
+};
+
+}
+
+ZipPackage::ZipPackage ( const uno::Reference < XComponentContext > &xContext )
+: m_aMutexHolder( new comphelper::RefCountedMutex )
+, m_nStartKeyGenerationID( xml::crypto::DigestID::SHA1 )
+, m_nChecksumDigestID( xml::crypto::DigestID::SHA1_1K )
+, m_nCommonEncryptionID( xml::crypto::CipherID::BLOWFISH_CFB_8 )
+, m_bHasEncryptedEntries ( false )
+, m_bHasNonEncryptedEntries ( false )
+, m_bInconsistent ( false )
+, m_bForceRecovery ( false )
+, m_bMediaTypeFallbackUsed ( false )
+, m_nFormat( embed::StorageFormats::PACKAGE ) // package is the default format
+, m_bAllowRemoveOnInsert( true )
+, m_eMode ( e_IMode_None )
+, m_xContext( xContext )
+{
+ m_xRootFolder = new ZipPackageFolder( m_xContext, m_nFormat, m_bAllowRemoveOnInsert );
+}
+
+ZipPackage::~ZipPackage()
+{
+}
+
+bool ZipPackage::isLocalFile() const
+{
+ return comphelper::isFileUrl(m_aURL);
+}
+
+void ZipPackage::parseManifest()
+{
+ if ( m_nFormat != embed::StorageFormats::PACKAGE )
+ return;
+
+ bool bManifestParsed = false;
+ static const OUStringLiteral sMeta (u"META-INF");
+ if ( m_xRootFolder->hasByName( sMeta ) )
+ {
+ try {
+ static const OUStringLiteral sManifest (u"manifest.xml");
+ uno::Reference< XUnoTunnel > xTunnel;
+ Any aAny = m_xRootFolder->getByName( sMeta );
+ aAny >>= xTunnel;
+ uno::Reference< XNameContainer > xMetaInfFolder( xTunnel, UNO_QUERY );
+ if ( xMetaInfFolder.is() && xMetaInfFolder->hasByName( sManifest ) )
+ {
+ aAny = xMetaInfFolder->getByName( sManifest );
+ aAny >>= xTunnel;
+ uno::Reference < XActiveDataSink > xSink ( xTunnel, UNO_QUERY );
+ if ( xSink.is() )
+ {
+ uno::Reference < XManifestReader > xReader = ManifestReader::create( m_xContext );
+
+ static const OUStringLiteral sPropFullPath (u"FullPath");
+ static const OUStringLiteral sPropVersion (u"Version");
+ static const OUStringLiteral sPropMediaType (u"MediaType");
+ static const OUStringLiteral sPropInitialisationVector (u"InitialisationVector");
+ static const OUStringLiteral sPropSalt (u"Salt");
+ static const OUStringLiteral sPropIterationCount (u"IterationCount");
+ static const OUStringLiteral sPropSize (u"Size");
+ static const OUStringLiteral sPropDigest (u"Digest");
+ static const OUStringLiteral sPropDerivedKeySize (u"DerivedKeySize");
+ static const OUStringLiteral sPropDigestAlgorithm (u"DigestAlgorithm");
+ static const OUStringLiteral sPropEncryptionAlgorithm (u"EncryptionAlgorithm");
+ static const OUStringLiteral sPropStartKeyAlgorithm (u"StartKeyAlgorithm");
+ static const OUStringLiteral sKeyInfo (u"KeyInfo");
+
+ const uno::Sequence < uno::Sequence < PropertyValue > > aManifestSequence = xReader->readManifestSequence ( xSink->getInputStream() );
+ const Any *pKeyInfo = nullptr;
+
+ for ( const uno::Sequence<PropertyValue>& rSequence : aManifestSequence )
+ {
+ OUString sPath, sMediaType, sVersion;
+ const Any *pSalt = nullptr, *pVector = nullptr, *pCount = nullptr, *pSize = nullptr, *pDigest = nullptr, *pDigestAlg = nullptr, *pEncryptionAlg = nullptr, *pStartKeyAlg = nullptr, *pDerivedKeySize = nullptr;
+ for ( const PropertyValue& rValue : rSequence )
+ {
+ if ( rValue.Name == sPropFullPath )
+ rValue.Value >>= sPath;
+ else if ( rValue.Name == sPropVersion )
+ rValue.Value >>= sVersion;
+ else if ( rValue.Name == sPropMediaType )
+ rValue.Value >>= sMediaType;
+ else if ( rValue.Name == sPropSalt )
+ pSalt = &( rValue.Value );
+ else if ( rValue.Name == sPropInitialisationVector )
+ pVector = &( rValue.Value );
+ else if ( rValue.Name == sPropIterationCount )
+ pCount = &( rValue.Value );
+ else if ( rValue.Name == sPropSize )
+ pSize = &( rValue.Value );
+ else if ( rValue.Name == sPropDigest )
+ pDigest = &( rValue.Value );
+ else if ( rValue.Name == sPropDigestAlgorithm )
+ pDigestAlg = &( rValue.Value );
+ else if ( rValue.Name == sPropEncryptionAlgorithm )
+ pEncryptionAlg = &( rValue.Value );
+ else if ( rValue.Name == sPropStartKeyAlgorithm )
+ pStartKeyAlg = &( rValue.Value );
+ else if ( rValue.Name == sPropDerivedKeySize )
+ pDerivedKeySize = &( rValue.Value );
+ else if ( rValue.Name == sKeyInfo )
+ pKeyInfo = &( rValue.Value );
+ }
+
+ if ( !sPath.isEmpty() && hasByHierarchicalName ( sPath ) )
+ {
+ aAny = getByHierarchicalName( sPath );
+ uno::Reference < XUnoTunnel > xUnoTunnel;
+ aAny >>= xUnoTunnel;
+ if (auto pFolder = comphelper::getFromUnoTunnel<ZipPackageFolder>(xUnoTunnel))
+ {
+ pFolder->SetMediaType ( sMediaType );
+ pFolder->SetVersion ( sVersion );
+ }
+ else if (auto pStream = comphelper::getFromUnoTunnel<ZipPackageStream>(xUnoTunnel))
+ {
+ pStream->SetMediaType ( sMediaType );
+ pStream->SetFromManifest( true );
+
+ if ( pKeyInfo && pVector && pSize && pDigest && pDigestAlg && pEncryptionAlg )
+ {
+ uno::Sequence < sal_Int8 > aSequence;
+ sal_Int64 nSize = 0;
+ sal_Int32 nDigestAlg = 0, nEncryptionAlg = 0;
+
+ pStream->SetToBeEncrypted ( true );
+
+ *pVector >>= aSequence;
+ pStream->setInitialisationVector ( aSequence );
+
+ *pSize >>= nSize;
+ pStream->setSize ( nSize );
+
+ *pDigest >>= aSequence;
+ pStream->setDigest ( aSequence );
+
+ *pDigestAlg >>= nDigestAlg;
+ pStream->SetImportedChecksumAlgorithm( nDigestAlg );
+
+ *pEncryptionAlg >>= nEncryptionAlg;
+ pStream->SetImportedEncryptionAlgorithm( nEncryptionAlg );
+
+ *pKeyInfo >>= m_aGpgProps;
+
+ pStream->SetToBeCompressed ( true );
+ pStream->SetToBeEncrypted ( true );
+ pStream->SetIsEncrypted ( true );
+ pStream->setIterationCount(0);
+
+ // clamp to default SHA256 start key magic value,
+ // c.f. ZipPackageStream::GetEncryptionKey()
+ // trying to get key value from properties
+ const sal_Int32 nStartKeyAlg = xml::crypto::DigestID::SHA256;
+ pStream->SetImportedStartKeyAlgorithm( nStartKeyAlg );
+
+ if ( !m_bHasEncryptedEntries && pStream->getName() == "content.xml" )
+ {
+ m_bHasEncryptedEntries = true;
+ m_nChecksumDigestID = nDigestAlg;
+ m_nCommonEncryptionID = nEncryptionAlg;
+ m_nStartKeyGenerationID = nStartKeyAlg;
+ }
+ }
+ else if ( pSalt && pVector && pCount && pSize && pDigest && pDigestAlg && pEncryptionAlg )
+ {
+ uno::Sequence < sal_Int8 > aSequence;
+ sal_Int64 nSize = 0;
+ sal_Int32 nCount = 0, nDigestAlg = 0, nEncryptionAlg = 0;
+ sal_Int32 nDerivedKeySize = 16, nStartKeyAlg = xml::crypto::DigestID::SHA1;
+
+ pStream->SetToBeEncrypted ( true );
+
+ *pSalt >>= aSequence;
+ pStream->setSalt ( aSequence );
+
+ *pVector >>= aSequence;
+ pStream->setInitialisationVector ( aSequence );
+
+ *pCount >>= nCount;
+ pStream->setIterationCount ( nCount );
+
+ *pSize >>= nSize;
+ pStream->setSize ( nSize );
+
+ *pDigest >>= aSequence;
+ pStream->setDigest ( aSequence );
+
+ *pDigestAlg >>= nDigestAlg;
+ pStream->SetImportedChecksumAlgorithm( nDigestAlg );
+
+ *pEncryptionAlg >>= nEncryptionAlg;
+ pStream->SetImportedEncryptionAlgorithm( nEncryptionAlg );
+
+ if ( pDerivedKeySize )
+ *pDerivedKeySize >>= nDerivedKeySize;
+ pStream->SetImportedDerivedKeySize( nDerivedKeySize );
+
+ if ( pStartKeyAlg )
+ *pStartKeyAlg >>= nStartKeyAlg;
+ pStream->SetImportedStartKeyAlgorithm( nStartKeyAlg );
+
+ pStream->SetToBeCompressed ( true );
+ pStream->SetToBeEncrypted ( true );
+ pStream->SetIsEncrypted ( true );
+ if ( !m_bHasEncryptedEntries && pStream->getName() == "content.xml" )
+ {
+ m_bHasEncryptedEntries = true;
+ m_nStartKeyGenerationID = nStartKeyAlg;
+ m_nChecksumDigestID = nDigestAlg;
+ m_nCommonEncryptionID = nEncryptionAlg;
+ }
+ }
+ else
+ m_bHasNonEncryptedEntries = true;
+ }
+ else
+ throw ZipIOException(THROW_WHERE "Wrong content");
+ }
+ }
+
+ bManifestParsed = true;
+ }
+
+ // now hide the manifest.xml file from user
+ xMetaInfFolder->removeByName( sManifest );
+ }
+ }
+ catch( Exception& )
+ {
+ if ( !m_bForceRecovery )
+ throw;
+ }
+ }
+
+ if ( !bManifestParsed && !m_bForceRecovery )
+ throw ZipIOException(
+ THROW_WHERE "Could not parse manifest.xml" );
+
+ static const OUStringLiteral sMimetype (u"mimetype");
+ if ( m_xRootFolder->hasByName( sMimetype ) )
+ {
+ // get mediatype from the "mimetype" stream
+ OUString aPackageMediatype;
+ uno::Reference< lang::XUnoTunnel > xMimeTypeTunnel;
+ m_xRootFolder->getByName( sMimetype ) >>= xMimeTypeTunnel;
+ uno::Reference < io::XActiveDataSink > xMimeSink( xMimeTypeTunnel, UNO_QUERY );
+ if ( xMimeSink.is() )
+ {
+ uno::Reference< io::XInputStream > xMimeInStream = xMimeSink->getInputStream();
+ if ( xMimeInStream.is() )
+ {
+ // Mediatypes longer than 1024 symbols should not appear here
+ uno::Sequence< sal_Int8 > aData( 1024 );
+ sal_Int32 nRead = xMimeInStream->readBytes( aData, 1024 );
+ if ( nRead > aData.getLength() )
+ nRead = aData.getLength();
+
+ if ( nRead )
+ aPackageMediatype = OUString( reinterpret_cast<char const *>(aData.getConstArray()), nRead, RTL_TEXTENCODING_ASCII_US );
+ }
+ }
+
+ if ( !bManifestParsed )
+ {
+ // the manifest.xml could not be successfully parsed, this is an inconsistent package
+ if ( aPackageMediatype.startsWith("application/vnd.") )
+ {
+ // accept only types that look similar to own mediatypes
+ m_xRootFolder->SetMediaType( aPackageMediatype );
+ m_bMediaTypeFallbackUsed = true;
+ }
+ }
+ else if ( !m_bForceRecovery )
+ {
+ // the mimetype stream should contain the information from manifest.xml
+ if ( m_xRootFolder->GetMediaType() != aPackageMediatype )
+ throw ZipIOException(
+ THROW_WHERE
+ "mimetype conflicts with manifest.xml, \""
+ + m_xRootFolder->GetMediaType() + "\" vs. \""
+ + aPackageMediatype + "\"" );
+ }
+
+ m_xRootFolder->removeByName( sMimetype );
+ }
+
+ m_bInconsistent = m_xRootFolder->LookForUnexpectedODF12Streams( std::u16string_view() );
+
+ bool bODF12AndNewer = ( m_xRootFolder->GetVersion().compareTo( ODFVER_012_TEXT ) >= 0 );
+ if ( !m_bForceRecovery && bODF12AndNewer )
+ {
+ if ( m_bInconsistent )
+ {
+ // this is an ODF1.2 document that contains streams not referred in the manifest.xml;
+ // in case of ODF1.2 documents without version in manifest.xml the property IsInconsistent
+ // should be checked later
+ throw ZipIOException(
+ THROW_WHERE "there are streams not referred in manifest.xml" );
+ }
+ // all the streams should be encrypted with the same StartKey in ODF1.2
+ // TODO/LATER: in future the exception should be thrown
+ // throw ZipIOException( THROW_WHERE "More than one Start Key Generation algorithm is specified!" );
+ }
+
+ // in case it is a correct ODF1.2 document, the version must be set
+ // and the META-INF folder is reserved for package format
+ if ( bODF12AndNewer )
+ m_xRootFolder->removeByName( sMeta );
+}
+
+void ZipPackage::parseContentType()
+{
+ if ( m_nFormat != embed::StorageFormats::OFOPXML )
+ return;
+
+ try {
+ static const OUStringLiteral aContentTypes(u"[Content_Types].xml");
+ // the content type must exist in OFOPXML format!
+ if ( !m_xRootFolder->hasByName( aContentTypes ) )
+ throw io::IOException(THROW_WHERE "Wrong format!" );
+
+ uno::Reference< lang::XUnoTunnel > xTunnel;
+ uno::Any aAny = m_xRootFolder->getByName( aContentTypes );
+ aAny >>= xTunnel;
+ uno::Reference < io::XActiveDataSink > xSink( xTunnel, UNO_QUERY );
+ if ( xSink.is() )
+ {
+ uno::Reference< io::XInputStream > xInStream = xSink->getInputStream();
+ if ( xInStream.is() )
+ {
+ // here aContentTypeInfo[0] - Defaults, and aContentTypeInfo[1] - Overrides
+ const uno::Sequence< uno::Sequence< beans::StringPair > > aContentTypeInfo =
+ ::comphelper::OFOPXMLHelper::ReadContentTypeSequence( xInStream, m_xContext );
+
+ if ( aContentTypeInfo.getLength() != 2 )
+ throw io::IOException(THROW_WHERE );
+
+ // set the implicit types first
+ for ( const auto& rPair : aContentTypeInfo[0] )
+ m_xRootFolder->setChildStreamsTypeByExtension( rPair );
+
+ // now set the explicit types
+ for ( const auto& rPair : aContentTypeInfo[1] )
+ {
+ OUString aPath;
+ if ( rPair.First.toChar() == '/' )
+ aPath = rPair.First.copy( 1 );
+ else
+ aPath = rPair.First;
+
+ if ( !aPath.isEmpty() && hasByHierarchicalName( aPath ) )
+ {
+ uno::Any aIterAny = getByHierarchicalName( aPath );
+ uno::Reference < lang::XUnoTunnel > xIterTunnel;
+ aIterAny >>= xIterTunnel;
+ if (auto pStream = comphelper::getFromUnoTunnel<ZipPackageStream>(xIterTunnel))
+ {
+ // this is a package stream, in OFOPXML format only streams can have mediatype
+ pStream->SetMediaType( rPair.Second );
+ }
+ }
+ }
+ }
+ }
+
+ m_xRootFolder->removeByName( aContentTypes );
+ }
+ catch( uno::Exception& )
+ {
+ if ( !m_bForceRecovery )
+ throw;
+ }
+}
+
+void ZipPackage::getZipFileContents()
+{
+ ZipEnumeration aEnum = m_pZipFile->entries();
+ OUString sTemp, sDirName;
+ sal_Int32 nOldIndex, nStreamIndex;
+ FolderHash::iterator aIter;
+
+ while (aEnum.hasMoreElements())
+ {
+ nOldIndex = 0;
+ ZipPackageFolder* pCurrent = m_xRootFolder.get();
+ const ZipEntry & rEntry = *aEnum.nextElement();
+ OUString rName = rEntry.sPath;
+
+ if ( m_bForceRecovery )
+ {
+ // the PKZIP Application note version 6.2 does not allows to use '\' as separator
+ // unfortunately it is used by some implementations, so we have to support it in recovery mode
+ rName = rName.replace( '\\', '/' );
+ }
+
+ nStreamIndex = rName.lastIndexOf ( '/' );
+ if ( nStreamIndex != -1 )
+ {
+ sDirName = rName.copy ( 0, nStreamIndex );
+ aIter = m_aRecent.find ( sDirName );
+ if ( aIter != m_aRecent.end() )
+ pCurrent = ( *aIter ).second;
+ }
+
+ if ( pCurrent == m_xRootFolder.get() )
+ {
+ sal_Int32 nIndex;
+ while ( ( nIndex = rName.indexOf( '/', nOldIndex ) ) != -1 )
+ {
+ sTemp = rName.copy ( nOldIndex, nIndex - nOldIndex );
+ if ( nIndex == nOldIndex )
+ break;
+ if ( !pCurrent->hasByName( sTemp ) )
+ {
+ rtl::Reference<ZipPackageFolder> pPkgFolder = new ZipPackageFolder(m_xContext, m_nFormat, m_bAllowRemoveOnInsert);
+ pPkgFolder->setName( sTemp );
+ pPkgFolder->doSetParent( pCurrent );
+ pCurrent = pPkgFolder.get();
+ }
+ else
+ {
+ ZipContentInfo& rInfo = pCurrent->doGetByName(sTemp);
+ if (!rInfo.bFolder)
+ throw css::packages::zip::ZipIOException("Bad Zip File, stream as folder");
+ pCurrent = rInfo.pFolder;
+ }
+ nOldIndex = nIndex+1;
+ }
+ if ( nStreamIndex != -1 && !sDirName.isEmpty() )
+ m_aRecent [ sDirName ] = pCurrent;
+ }
+ if ( rName.getLength() -1 != nStreamIndex )
+ {
+ nStreamIndex++;
+ sTemp = rName.copy( nStreamIndex );
+
+ if (!pCurrent->hasByName(sTemp))
+ {
+ rtl::Reference<ZipPackageStream> pPkgStream = new ZipPackageStream(*this, m_xContext, m_nFormat, m_bAllowRemoveOnInsert);
+ pPkgStream->SetPackageMember(true);
+ pPkgStream->setZipEntryOnLoading(rEntry);
+ pPkgStream->setName(sTemp);
+ pPkgStream->doSetParent(pCurrent);
+ }
+ }
+ }
+
+ if ( m_nFormat == embed::StorageFormats::PACKAGE )
+ parseManifest();
+ else if ( m_nFormat == embed::StorageFormats::OFOPXML )
+ parseContentType();
+}
+
+void SAL_CALL ZipPackage::initialize( const uno::Sequence< Any >& aArguments )
+{
+ beans::NamedValue aNamedValue;
+
+ if ( !aArguments.hasElements() )
+ return;
+
+ bool bHaveZipFile = true;
+
+ for( const auto& rArgument : aArguments )
+ {
+ OUString aParamUrl;
+ if ( rArgument >>= aParamUrl )
+ {
+ m_eMode = e_IMode_URL;
+ try
+ {
+ sal_Int32 nParam = aParamUrl.indexOf( '?' );
+ if ( nParam >= 0 )
+ {
+ m_aURL = aParamUrl.copy( 0, nParam );
+ std::u16string_view aParam = aParamUrl.subView( nParam + 1 );
+
+ sal_Int32 nIndex = 0;
+ do
+ {
+ std::u16string_view aCommand = o3tl::getToken(aParam, 0, '&', nIndex );
+ if ( aCommand == u"repairpackage" )
+ {
+ m_bForceRecovery = true;
+ break;
+ }
+ else if ( aCommand == u"purezip" )
+ {
+ m_nFormat = embed::StorageFormats::ZIP;
+ m_xRootFolder->setPackageFormat_Impl( m_nFormat );
+ break;
+ }
+ else if ( aCommand == u"ofopxml" )
+ {
+ m_nFormat = embed::StorageFormats::OFOPXML;
+ m_xRootFolder->setPackageFormat_Impl( m_nFormat );
+ break;
+ }
+ }
+ while ( nIndex >= 0 );
+ }
+ else
+ m_aURL = aParamUrl;
+
+ Content aContent(
+ m_aURL, uno::Reference< XCommandEnvironment >(),
+ m_xContext );
+ Any aAny = aContent.getPropertyValue("Size");
+ sal_uInt64 aSize = 0;
+ // kind of optimization: treat empty files as nonexistent files
+ // and write to such files directly. Note that "Size" property is optional.
+ bool bHasSizeProperty = aAny >>= aSize;
+ if( !bHasSizeProperty || aSize )
+ {
+ uno::Reference < XActiveDataSink > xSink = new ZipPackageSink;
+ if ( aContent.openStream ( xSink ) )
+ m_xContentStream = xSink->getInputStream();
+ }
+ else
+ bHaveZipFile = false;
+ }
+ catch ( css::uno::Exception& )
+ {
+ // Exception derived from uno::Exception thrown. This probably
+ // means the file doesn't exist...we'll create it at
+ // commitChanges time
+ bHaveZipFile = false;
+ }
+ }
+ else if ( rArgument >>= m_xStream )
+ {
+ // a writable stream can implement both XStream & XInputStream
+ m_eMode = e_IMode_XStream;
+ m_xContentStream = m_xStream->getInputStream();
+ }
+ else if ( rArgument >>= m_xContentStream )
+ {
+ m_eMode = e_IMode_XInputStream;
+ }
+ else if ( rArgument >>= aNamedValue )
+ {
+ if ( aNamedValue.Name == "RepairPackage" )
+ aNamedValue.Value >>= m_bForceRecovery;
+ else if ( aNamedValue.Name == "PackageFormat" )
+ {
+ // setting this argument to true means Package format
+ // setting it to false means plain Zip format
+
+ bool bPackFormat = true;
+ aNamedValue.Value >>= bPackFormat;
+ if ( !bPackFormat )
+ m_nFormat = embed::StorageFormats::ZIP;
+
+ m_xRootFolder->setPackageFormat_Impl( m_nFormat );
+ }
+ else if ( aNamedValue.Name == "StorageFormat" )
+ {
+ OUString aFormatName;
+ sal_Int32 nFormatID = 0;
+ if ( aNamedValue.Value >>= aFormatName )
+ {
+ if ( aFormatName == PACKAGE_STORAGE_FORMAT_STRING )
+ m_nFormat = embed::StorageFormats::PACKAGE;
+ else if ( aFormatName == ZIP_STORAGE_FORMAT_STRING )
+ m_nFormat = embed::StorageFormats::ZIP;
+ else if ( aFormatName == OFOPXML_STORAGE_FORMAT_STRING )
+ m_nFormat = embed::StorageFormats::OFOPXML;
+ else
+ throw lang::IllegalArgumentException(THROW_WHERE, uno::Reference< uno::XInterface >(), 1 );
+ }
+ else if ( aNamedValue.Value >>= nFormatID )
+ {
+ if (nFormatID != embed::StorageFormats::PACKAGE
+ && nFormatID != embed::StorageFormats::ZIP
+ && nFormatID != embed::StorageFormats::OFOPXML)
+ throw lang::IllegalArgumentException(THROW_WHERE, uno::Reference< uno::XInterface >(), 1 );
+
+ m_nFormat = nFormatID;
+ }
+ else
+ throw lang::IllegalArgumentException(THROW_WHERE, uno::Reference< uno::XInterface >(), 1 );
+
+ m_xRootFolder->setPackageFormat_Impl( m_nFormat );
+ }
+ else if ( aNamedValue.Name == "AllowRemoveOnInsert" )
+ {
+ aNamedValue.Value >>= m_bAllowRemoveOnInsert;
+ m_xRootFolder->setRemoveOnInsertMode_Impl( m_bAllowRemoveOnInsert );
+ }
+ else if (aNamedValue.Name == "NoFileSync")
+ aNamedValue.Value >>= m_bDisableFileSync;
+
+ // for now the progress handler is not used, probably it will never be
+ // if ( aNamedValue.Name == "ProgressHandler" )
+ }
+ else
+ {
+ // The URL is not acceptable
+ throw css::uno::Exception (THROW_WHERE "Bad arguments.",
+ static_cast < ::cppu::OWeakObject * > ( this ) );
+ }
+ }
+
+ try
+ {
+ if ( m_xContentStream.is() )
+ {
+ // the stream must be seekable, if it is not it will be wrapped
+ m_xContentStream = ::comphelper::OSeekableInputWrapper::CheckSeekableCanWrap( m_xContentStream, m_xContext );
+ m_xContentSeek.set( m_xContentStream, UNO_QUERY_THROW );
+ if ( !m_xContentSeek->getLength() )
+ bHaveZipFile = false;
+ }
+ else
+ bHaveZipFile = false;
+ }
+ catch ( css::uno::Exception& )
+ {
+ // Exception derived from uno::Exception thrown. This probably
+ // means the file doesn't exist...we'll create it at
+ // commitChanges time
+ bHaveZipFile = false;
+ }
+ if ( !bHaveZipFile )
+ return;
+
+ bool bBadZipFile = false;
+ OUString message;
+ try
+ {
+ m_pZipFile.emplace(m_aMutexHolder, m_xContentStream, m_xContext, true, m_bForceRecovery);
+ getZipFileContents();
+ }
+ catch ( IOException & e )
+ {
+ bBadZipFile = true;
+ message = "IOException: " + e.Message;
+ }
+ catch ( ZipException & e )
+ {
+ bBadZipFile = true;
+ message = "ZipException: " + e.Message;
+ }
+ catch ( Exception & )
+ {
+ m_pZipFile.reset();
+ throw;
+ }
+
+ if ( bBadZipFile )
+ {
+ // clean up the memory, and tell the UCB about the error
+ m_pZipFile.reset();
+
+ throw css::packages::zip::ZipIOException (
+ THROW_WHERE "Bad Zip File, " + message,
+ static_cast < ::cppu::OWeakObject * > ( this ) );
+ }
+}
+
+Any SAL_CALL ZipPackage::getByHierarchicalName( const OUString& aName )
+{
+ OUString sTemp, sDirName;
+ sal_Int32 nOldIndex, nStreamIndex;
+ FolderHash::iterator aIter;
+
+ sal_Int32 nIndex = aName.getLength();
+
+ if (aName == "/")
+ // root directory.
+ return Any ( uno::Reference < XUnoTunnel > ( m_xRootFolder ) );
+
+ nStreamIndex = aName.lastIndexOf ( '/' );
+ bool bFolder = nStreamIndex == nIndex-1; // last character is '/'.
+
+ if ( nStreamIndex != -1 )
+ {
+ // The name contains '/'.
+ sDirName = aName.copy ( 0, nStreamIndex );
+ aIter = m_aRecent.find ( sDirName );
+ if ( aIter != m_aRecent.end() )
+ {
+ // There is a cached entry for this name.
+
+ ZipPackageFolder* pFolder = aIter->second;
+
+ if ( bFolder )
+ {
+ // Determine the directory name.
+ sal_Int32 nDirIndex = aName.lastIndexOf ( '/', nStreamIndex );
+ sTemp = aName.copy ( nDirIndex == -1 ? 0 : nDirIndex+1, nStreamIndex-nDirIndex-1 );
+
+ if (pFolder && sTemp == pFolder->getName())
+ return Any(uno::Reference<XUnoTunnel>(pFolder));
+ }
+ else
+ {
+ // Determine the file name.
+ sTemp = aName.copy ( nStreamIndex + 1 );
+
+ if (pFolder && pFolder->hasByName(sTemp))
+ return pFolder->getByName(sTemp);
+ }
+
+ m_aRecent.erase( aIter );
+ }
+ }
+ else if ( m_xRootFolder->hasByName ( aName ) )
+ // top-level element.
+ return m_xRootFolder->getByName ( aName );
+
+ // Not in the cache. Search normally.
+
+ nOldIndex = 0;
+ ZipPackageFolder * pCurrent = m_xRootFolder.get();
+ ZipPackageFolder * pPrevious = nullptr;
+
+ // Find the right directory for the given path.
+
+ while ( ( nIndex = aName.indexOf( '/', nOldIndex )) != -1 )
+ {
+ sTemp = aName.copy ( nOldIndex, nIndex - nOldIndex );
+ if ( nIndex == nOldIndex )
+ break;
+ if ( !pCurrent->hasByName( sTemp ) )
+ throw NoSuchElementException(THROW_WHERE );
+
+ pPrevious = pCurrent;
+ ZipContentInfo& rInfo = pCurrent->doGetByName(sTemp);
+ if (!rInfo.bFolder)
+ throw css::packages::zip::ZipIOException("Bad Zip File, stream as folder");
+ pCurrent = rInfo.pFolder;
+ nOldIndex = nIndex+1;
+ }
+
+ if ( bFolder )
+ {
+ if ( nStreamIndex != -1 )
+ m_aRecent[sDirName] = pPrevious; // cache it.
+ return Any ( uno::Reference < XUnoTunnel > ( pCurrent ) );
+ }
+
+ sTemp = aName.copy( nOldIndex );
+
+ if ( pCurrent->hasByName ( sTemp ) )
+ {
+ if ( nStreamIndex != -1 )
+ m_aRecent[sDirName] = pCurrent; // cache it.
+ return pCurrent->getByName( sTemp );
+ }
+
+ throw NoSuchElementException(THROW_WHERE);
+}
+
+sal_Bool SAL_CALL ZipPackage::hasByHierarchicalName( const OUString& aName )
+{
+ OUString sTemp;
+ sal_Int32 nOldIndex;
+ FolderHash::iterator aIter;
+
+ sal_Int32 nIndex = aName.getLength();
+
+ if (aName == "/")
+ // root directory
+ return true;
+
+ try
+ {
+ OUString sDirName;
+ sal_Int32 nStreamIndex;
+ nStreamIndex = aName.lastIndexOf ( '/' );
+ bool bFolder = nStreamIndex == nIndex-1;
+ if ( nStreamIndex != -1 )
+ {
+ sDirName = aName.copy ( 0, nStreamIndex );
+ aIter = m_aRecent.find ( sDirName );
+ if ( aIter != m_aRecent.end() )
+ {
+ if ( bFolder )
+ {
+ sal_Int32 nDirIndex = aName.lastIndexOf ( '/', nStreamIndex );
+ sTemp = aName.copy ( nDirIndex == -1 ? 0 : nDirIndex+1, nStreamIndex-nDirIndex-1 );
+ if ( sTemp == ( *aIter ).second->getName() )
+ return true;
+ else
+ m_aRecent.erase ( aIter );
+ }
+ else
+ {
+ sTemp = aName.copy ( nStreamIndex + 1 );
+ if ( ( *aIter ).second->hasByName( sTemp ) )
+ return true;
+ else
+ m_aRecent.erase( aIter );
+ }
+ }
+ }
+ else
+ {
+ if ( m_xRootFolder->hasByName ( aName ) )
+ return true;
+ }
+ ZipPackageFolder * pCurrent = m_xRootFolder.get();
+ ZipPackageFolder * pPrevious = nullptr;
+ nOldIndex = 0;
+ while ( ( nIndex = aName.indexOf( '/', nOldIndex )) != -1 )
+ {
+ sTemp = aName.copy ( nOldIndex, nIndex - nOldIndex );
+ if ( nIndex == nOldIndex )
+ break;
+ if ( pCurrent->hasByName( sTemp ) )
+ {
+ pPrevious = pCurrent;
+ ZipContentInfo& rInfo = pCurrent->doGetByName(sTemp);
+ if (!rInfo.bFolder)
+ throw css::packages::zip::ZipIOException("Bad Zip File, stream as folder");
+ pCurrent = rInfo.pFolder;
+ }
+ else
+ return false;
+ nOldIndex = nIndex+1;
+ }
+ if ( bFolder )
+ {
+ m_aRecent[sDirName] = pPrevious;
+ return true;
+ }
+ else
+ {
+ sTemp = aName.copy( nOldIndex );
+
+ if ( pCurrent->hasByName( sTemp ) )
+ {
+ m_aRecent[sDirName] = pCurrent;
+ return true;
+ }
+ }
+ }
+ catch (const uno::RuntimeException &)
+ {
+ throw;
+ }
+ catch (const uno::Exception&)
+ {
+ uno::Any e(::cppu::getCaughtException());
+ throw lang::WrappedTargetRuntimeException("ZipPackage::hasByHierarchicalName", nullptr, e);
+ }
+ return false;
+}
+
+uno::Reference< XInterface > SAL_CALL ZipPackage::createInstance()
+{
+ uno::Reference < XInterface > xRef = *( new ZipPackageStream( *this, m_xContext, m_nFormat, m_bAllowRemoveOnInsert ) );
+ return xRef;
+}
+
+uno::Reference< XInterface > SAL_CALL ZipPackage::createInstanceWithArguments( const uno::Sequence< Any >& aArguments )
+{
+ bool bArg = false;
+ uno::Reference < XInterface > xRef;
+ if ( aArguments.hasElements() )
+ aArguments[0] >>= bArg;
+ if ( bArg )
+ xRef = *new ZipPackageFolder( m_xContext, m_nFormat, m_bAllowRemoveOnInsert );
+ else
+ xRef = *new ZipPackageStream( *this, m_xContext, m_nFormat, m_bAllowRemoveOnInsert );
+
+ return xRef;
+}
+
+void ZipPackage::WriteMimetypeMagicFile( ZipOutputStream& aZipOut )
+{
+ static const OUStringLiteral sMime (u"mimetype");
+ if ( m_xRootFolder->hasByName( sMime ) )
+ m_xRootFolder->removeByName( sMime );
+
+ ZipEntry * pEntry = new ZipEntry;
+ sal_Int32 nBufferLength = m_xRootFolder->GetMediaType().getLength();
+ OString sMediaType = OUStringToOString( m_xRootFolder->GetMediaType(), RTL_TEXTENCODING_ASCII_US );
+ const uno::Sequence< sal_Int8 > aType( reinterpret_cast<sal_Int8 const *>(sMediaType.getStr()),
+ nBufferLength );
+
+ pEntry->sPath = sMime;
+ pEntry->nMethod = STORED;
+ pEntry->nSize = pEntry->nCompressedSize = nBufferLength;
+ pEntry->nTime = ZipOutputStream::getCurrentDosTime();
+
+ CRC32 aCRC32;
+ aCRC32.update( aType );
+ pEntry->nCrc = aCRC32.getValue();
+
+ try
+ {
+ ZipOutputStream::setEntry(pEntry);
+ aZipOut.writeLOC(pEntry);
+ aZipOut.rawWrite(aType);
+ aZipOut.rawCloseEntry();
+ }
+ catch ( const css::io::IOException & )
+ {
+ css::uno::Any anyEx = cppu::getCaughtException();
+ throw WrappedTargetException(
+ THROW_WHERE "Error adding mimetype to the ZipOutputStream!",
+ static_cast < OWeakObject * > ( this ),
+ anyEx );
+ }
+}
+
+void ZipPackage::WriteManifest( ZipOutputStream& aZipOut, const std::vector< uno::Sequence < PropertyValue > >& aManList )
+{
+ // Write the manifest
+ uno::Reference < XManifestWriter > xWriter = ManifestWriter::create( m_xContext );
+ ZipEntry * pEntry = new ZipEntry;
+ rtl::Reference<ZipPackageBuffer> pBuffer = new ZipPackageBuffer;
+
+ pEntry->sPath = "META-INF/manifest.xml";
+ pEntry->nMethod = DEFLATED;
+ pEntry->nCrc = -1;
+ pEntry->nSize = pEntry->nCompressedSize = -1;
+ pEntry->nTime = ZipOutputStream::getCurrentDosTime();
+
+ xWriter->writeManifestSequence ( pBuffer, comphelper::containerToSequence(aManList) );
+
+ sal_Int32 nBufferLength = static_cast < sal_Int32 > ( pBuffer->getPosition() );
+ pBuffer->realloc( nBufferLength );
+
+ // the manifest.xml is never encrypted - so pass an empty reference
+ ZipOutputStream::setEntry(pEntry);
+ aZipOut.writeLOC(pEntry);
+ ZipOutputEntry aZipEntry(aZipOut.getStream(), m_xContext, *pEntry, nullptr, /*bEncrypt*/false);
+ aZipEntry.write(pBuffer->getSequence());
+ aZipEntry.closeEntry();
+ aZipOut.rawCloseEntry();
+}
+
+void ZipPackage::WriteContentTypes( ZipOutputStream& aZipOut, const std::vector< uno::Sequence < PropertyValue > >& aManList )
+{
+ ZipEntry* pEntry = new ZipEntry;
+ rtl::Reference<ZipPackageBuffer> pBuffer = new ZipPackageBuffer;
+
+ pEntry->sPath = "[Content_Types].xml";
+ pEntry->nMethod = DEFLATED;
+ pEntry->nCrc = -1;
+ pEntry->nSize = pEntry->nCompressedSize = -1;
+ pEntry->nTime = ZipOutputStream::getCurrentDosTime();
+
+ // Add default entries, the count must be updated manually when appending.
+ // Add at least the standard default entries.
+ uno::Sequence< beans::StringPair > aDefaultsSequence
+ {
+ { "xml", "application/xml" },
+ { "rels", "application/vnd.openxmlformats-package.relationships+xml" },
+ { "png", "image/png" },
+ { "jpeg", "image/jpeg" }
+ };
+
+ uno::Sequence< beans::StringPair > aOverridesSequence(aManList.size());
+ auto aOverridesSequenceRange = asNonConstRange(aOverridesSequence);
+ sal_Int32 nOverSeqLength = 0;
+ for (const auto& rMan : aManList)
+ {
+ OUString aType;
+ OSL_ENSURE( rMan[PKG_MNFST_MEDIATYPE].Name == "MediaType" && rMan[PKG_MNFST_FULLPATH].Name == "FullPath",
+ "The mediatype sequence format is wrong!" );
+ rMan[PKG_MNFST_MEDIATYPE].Value >>= aType;
+ if ( !aType.isEmpty() )
+ {
+ OUString aPath;
+ // only nonempty type makes sense here
+ rMan[PKG_MNFST_FULLPATH].Value >>= aPath;
+ //FIXME: For now we have no way of differentiating defaults from others.
+ aOverridesSequenceRange[nOverSeqLength].First = "/" + aPath;
+ aOverridesSequenceRange[nOverSeqLength].Second = aType;
+ ++nOverSeqLength;
+ }
+ }
+ aOverridesSequence.realloc(nOverSeqLength);
+
+ ::comphelper::OFOPXMLHelper::WriteContentSequence(
+ pBuffer, aDefaultsSequence, aOverridesSequence, m_xContext );
+
+ sal_Int32 nBufferLength = static_cast < sal_Int32 > ( pBuffer->getPosition() );
+ pBuffer->realloc( nBufferLength );
+
+ // there is no encryption in this format currently
+ ZipOutputStream::setEntry(pEntry);
+ aZipOut.writeLOC(pEntry);
+ ZipOutputEntry aZipEntry(aZipOut.getStream(), m_xContext, *pEntry, nullptr, /*bEncrypt*/false);
+ aZipEntry.write(pBuffer->getSequence());
+ aZipEntry.closeEntry();
+ aZipOut.rawCloseEntry();
+}
+
+void ZipPackage::ConnectTo( const uno::Reference< io::XInputStream >& xInStream )
+{
+ m_xContentSeek.set( xInStream, uno::UNO_QUERY_THROW );
+ m_xContentStream = xInStream;
+
+ // seek back to the beginning of the temp file so we can read segments from it
+ m_xContentSeek->seek( 0 );
+ if ( m_pZipFile )
+ m_pZipFile->setInputStream( m_xContentStream );
+ else
+ m_pZipFile.emplace(m_aMutexHolder, m_xContentStream, m_xContext, false);
+}
+
+namespace
+{
+ class RandomPool
+ {
+ private:
+ rtlRandomPool m_aRandomPool;
+ public:
+ RandomPool() : m_aRandomPool(rtl_random_createPool ())
+ {
+ }
+ rtlRandomPool get()
+ {
+ return m_aRandomPool;
+ }
+ ~RandomPool()
+ {
+ // Clean up random pool memory
+ rtl_random_destroyPool(m_aRandomPool);
+ }
+ };
+}
+
+uno::Reference< io::XInputStream > ZipPackage::writeTempFile()
+{
+ // In case the target local file does not exist or empty
+ // write directly to it otherwise create a temporary file to write to.
+ // If a temporary file is created it is returned back by the method.
+ // If the data written directly, xComponentStream will be switched here
+
+ bool bUseTemp = true;
+ uno::Reference < io::XInputStream > xResult;
+ uno::Reference < io::XInputStream > xTempIn;
+
+ uno::Reference < io::XOutputStream > xTempOut;
+ uno::Reference< io::XActiveDataStreamer > xSink;
+
+ if ( m_eMode == e_IMode_URL && !m_pZipFile && isLocalFile() )
+ {
+ xSink = openOriginalForOutput();
+ if( xSink.is() )
+ {
+ uno::Reference< io::XStream > xStr = xSink->getStream();
+ if( xStr.is() )
+ {
+ xTempOut = xStr->getOutputStream();
+ if( xTempOut.is() )
+ bUseTemp = false;
+ }
+ }
+ }
+ else if ( m_eMode == e_IMode_XStream && !m_pZipFile )
+ {
+ // write directly to an empty stream
+ xTempOut = m_xStream->getOutputStream();
+ if( xTempOut.is() )
+ bUseTemp = false;
+ }
+
+ if( bUseTemp )
+ {
+ // create temporary file
+ uno::Reference < io::XTempFile > xTempFile( io::TempFile::create(m_xContext) );
+ xTempOut.set( xTempFile->getOutputStream(), UNO_SET_THROW );
+ xTempIn.set( xTempFile->getInputStream(), UNO_SET_THROW );
+ }
+
+ // Hand it to the ZipOutputStream:
+ ZipOutputStream aZipOut( xTempOut );
+ try
+ {
+ if ( m_nFormat == embed::StorageFormats::PACKAGE )
+ {
+ // Remove the old manifest.xml file as the
+ // manifest will be re-generated and the
+ // META-INF directory implicitly created if does not exist
+ static constexpr OUStringLiteral sMeta (u"META-INF");
+
+ if ( m_xRootFolder->hasByName( sMeta ) )
+ {
+ static const OUStringLiteral sManifest (u"manifest.xml");
+
+ uno::Reference< XUnoTunnel > xTunnel;
+ Any aAny = m_xRootFolder->getByName( sMeta );
+ aAny >>= xTunnel;
+ uno::Reference< XNameContainer > xMetaInfFolder( xTunnel, UNO_QUERY );
+ if ( xMetaInfFolder.is() && xMetaInfFolder->hasByName( sManifest ) )
+ xMetaInfFolder->removeByName( sManifest );
+ }
+
+ // Write a magic file with mimetype
+ WriteMimetypeMagicFile( aZipOut );
+ }
+ else if ( m_nFormat == embed::StorageFormats::OFOPXML )
+ {
+ // Remove the old [Content_Types].xml file as the
+ // file will be re-generated
+
+ static constexpr OUStringLiteral aContentTypes(u"[Content_Types].xml");
+
+ if ( m_xRootFolder->hasByName( aContentTypes ) )
+ m_xRootFolder->removeByName( aContentTypes );
+ }
+
+ // Create a vector to store data for the manifest.xml file
+ std::vector < uno::Sequence < PropertyValue > > aManList;
+
+ static constexpr OUStringLiteral sMediaType(u"MediaType");
+ static constexpr OUStringLiteral sVersion(u"Version");
+ static constexpr OUStringLiteral sFullPath(u"FullPath");
+ const bool bIsGpgEncrypt = m_aGpgProps.hasElements();
+
+ if ( m_nFormat == embed::StorageFormats::PACKAGE )
+ {
+ uno::Sequence < PropertyValue > aPropSeq(
+ bIsGpgEncrypt ? PKG_SIZE_NOENCR_MNFST+1 : PKG_SIZE_NOENCR_MNFST );
+ auto pPropSeq = aPropSeq.getArray();
+ pPropSeq [PKG_MNFST_MEDIATYPE].Name = sMediaType;
+ pPropSeq [PKG_MNFST_MEDIATYPE].Value <<= m_xRootFolder->GetMediaType();
+ pPropSeq [PKG_MNFST_VERSION].Name = sVersion;
+ pPropSeq [PKG_MNFST_VERSION].Value <<= m_xRootFolder->GetVersion();
+ pPropSeq [PKG_MNFST_FULLPATH].Name = sFullPath;
+ pPropSeq [PKG_MNFST_FULLPATH].Value <<= OUString("/");
+
+ if( bIsGpgEncrypt )
+ {
+ pPropSeq[PKG_SIZE_NOENCR_MNFST].Name = "KeyInfo";
+ pPropSeq[PKG_SIZE_NOENCR_MNFST].Value <<= m_aGpgProps;
+ }
+ aManList.push_back( aPropSeq );
+ }
+
+ {
+ // This will be used to generate random salt and initialisation vectors
+ // for encrypted streams
+ RandomPool aRandomPool;
+
+ sal_Int32 const nPBKDF2IterationCount = 100000;
+
+ // call saveContents ( it will recursively save sub-directories
+ m_xRootFolder->saveContents("", aManList, aZipOut, GetEncryptionKey(), bIsGpgEncrypt ? 0 : nPBKDF2IterationCount, aRandomPool.get());
+ }
+
+ if( m_nFormat == embed::StorageFormats::PACKAGE )
+ {
+ WriteManifest( aZipOut, aManList );
+ }
+ else if( m_nFormat == embed::StorageFormats::OFOPXML )
+ {
+ WriteContentTypes( aZipOut, aManList );
+ }
+
+ aZipOut.finish();
+
+ if( bUseTemp )
+ xResult = xTempIn;
+
+ // Update our References to point to the new temp file
+ if( !bUseTemp )
+ {
+ // the case when the original contents were written directly
+ xTempOut->flush();
+
+ // in case the stream is based on a file it will implement the following interface
+ // the call should be used to be sure that the contents are written to the file system
+ uno::Reference< io::XAsyncOutputMonitor > asyncOutputMonitor( xTempOut, uno::UNO_QUERY );
+ if (asyncOutputMonitor.is() && !m_bDisableFileSync)
+ asyncOutputMonitor->waitForCompletion();
+
+ // no need to postpone switching to the new stream since the target was written directly
+ uno::Reference< io::XInputStream > xNewStream;
+ if ( m_eMode == e_IMode_URL )
+ xNewStream = xSink->getStream()->getInputStream();
+ else if ( m_eMode == e_IMode_XStream && m_xStream.is() )
+ xNewStream = m_xStream->getInputStream();
+
+ if ( xNewStream.is() )
+ ConnectTo( xNewStream );
+ }
+ }
+ catch ( uno::Exception& )
+ {
+ if( bUseTemp )
+ {
+ // no information loss appears, thus no special handling is required
+ uno::Any aCaught( ::cppu::getCaughtException() );
+
+ // it is allowed to throw WrappedTargetException
+ WrappedTargetException aException;
+ if ( aCaught >>= aException )
+ throw aException;
+
+ throw WrappedTargetException(
+ THROW_WHERE "Problem writing the original content!",
+ static_cast < OWeakObject * > ( this ),
+ aCaught );
+ }
+ else
+ {
+ // the document is written directly, although it was empty it is important to notify that the writing has failed
+ // TODO/LATER: let the package be able to recover in this situation
+ OUString aErrTxt(THROW_WHERE "This package is unusable!");
+ embed::UseBackupException aException( aErrTxt, uno::Reference< uno::XInterface >(), OUString() );
+ throw WrappedTargetException( aErrTxt,
+ static_cast < OWeakObject * > ( this ),
+ Any ( aException ) );
+ }
+ }
+
+ return xResult;
+}
+
+uno::Reference< XActiveDataStreamer > ZipPackage::openOriginalForOutput()
+{
+ // open and truncate the original file
+ Content aOriginalContent(
+ m_aURL, uno::Reference< XCommandEnvironment >(),
+ m_xContext );
+ uno::Reference< XActiveDataStreamer > xSink = new ActiveDataStreamer;
+
+ if ( m_eMode == e_IMode_URL )
+ {
+ try
+ {
+ bool bTruncSuccess = false;
+
+ try
+ {
+ Exception aDetect;
+ Any aAny = aOriginalContent.setPropertyValue("Size", Any( sal_Int64(0) ) );
+ if( !( aAny >>= aDetect ) )
+ bTruncSuccess = true;
+ }
+ catch( Exception& )
+ {
+ }
+
+ if( !bTruncSuccess )
+ {
+ // the file is not accessible
+ // just try to write an empty stream to it
+
+ uno::Reference< XInputStream > xTempIn = new DummyInputStream; //uno::Reference< XInputStream >( xTempOut, UNO_QUERY );
+ aOriginalContent.writeStream( xTempIn , true );
+ }
+
+ OpenCommandArgument2 aArg;
+ aArg.Mode = OpenMode::DOCUMENT;
+ aArg.Priority = 0; // unused
+ aArg.Sink = xSink;
+ aArg.Properties = uno::Sequence< Property >( 0 ); // unused
+
+ aOriginalContent.executeCommand("open", Any( aArg ) );
+ }
+ catch( Exception& )
+ {
+ // seems to be nonlocal file
+ // temporary file mechanics should be used
+ }
+ }
+
+ return xSink;
+}
+
+void SAL_CALL ZipPackage::commitChanges()
+{
+ // lock the component for the time of committing
+ ::osl::MutexGuard aGuard( m_aMutexHolder->GetMutex() );
+
+ if ( m_eMode == e_IMode_XInputStream )
+ {
+ IOException aException;
+ throw WrappedTargetException(THROW_WHERE "This package is read only!",
+ static_cast < OWeakObject * > ( this ), Any ( aException ) );
+ }
+ // first the writeTempFile is called, if it returns a stream the stream should be written to the target
+ // if no stream was returned, the file was written directly, nothing should be done
+ uno::Reference< io::XInputStream > xTempInStream;
+ try
+ {
+ xTempInStream = writeTempFile();
+ }
+ catch (const ucb::ContentCreationException&)
+ {
+ css::uno::Any anyEx = cppu::getCaughtException();
+ throw WrappedTargetException(THROW_WHERE "Temporary file should be creatable!",
+ static_cast < OWeakObject * > ( this ), anyEx );
+ }
+ if ( xTempInStream.is() )
+ {
+ uno::Reference< io::XSeekable > xTempSeek( xTempInStream, uno::UNO_QUERY_THROW );
+
+ try
+ {
+ xTempSeek->seek( 0 );
+ }
+ catch( const uno::Exception& )
+ {
+ css::uno::Any anyEx = cppu::getCaughtException();
+ throw WrappedTargetException(THROW_WHERE "Temporary file should be seekable!",
+ static_cast < OWeakObject * > ( this ), anyEx );
+ }
+
+ try
+ {
+ // connect to the temporary stream
+ ConnectTo( xTempInStream );
+ }
+ catch( const io::IOException& )
+ {
+ css::uno::Any anyEx = cppu::getCaughtException();
+ throw WrappedTargetException(THROW_WHERE "Temporary file should be connectable!",
+ static_cast < OWeakObject * > ( this ), anyEx );
+ }
+
+ if ( m_eMode == e_IMode_XStream )
+ {
+ // First truncate our output stream
+ uno::Reference < XOutputStream > xOutputStream;
+
+ // preparation for copy step
+ try
+ {
+ xOutputStream = m_xStream->getOutputStream();
+
+ // Make sure we avoid a situation where the current position is
+ // not zero, but the underlying file is truncated in the
+ // meantime.
+ uno::Reference<io::XSeekable> xSeekable(xOutputStream, uno::UNO_QUERY);
+ if (xSeekable.is())
+ xSeekable->seek(0);
+
+ uno::Reference < XTruncate > xTruncate ( xOutputStream, UNO_QUERY_THROW );
+
+ // after successful truncation the original file contents are already lost
+ xTruncate->truncate();
+ }
+ catch( const uno::Exception& )
+ {
+ css::uno::Any anyEx = cppu::getCaughtException();
+ throw WrappedTargetException(THROW_WHERE "This package is read only!",
+ static_cast < OWeakObject * > ( this ), anyEx );
+ }
+
+ try
+ {
+ // then copy the contents of the tempfile to our output stream
+ ::comphelper::OStorageHelper::CopyInputToOutput( xTempInStream, xOutputStream );
+ xOutputStream->flush();
+ uno::Reference< io::XAsyncOutputMonitor > asyncOutputMonitor(
+ xOutputStream, uno::UNO_QUERY );
+ if ( asyncOutputMonitor.is() ) {
+ asyncOutputMonitor->waitForCompletion();
+ }
+ }
+ catch( uno::Exception& )
+ {
+ // if anything goes wrong in this block the target file becomes corrupted
+ // so an exception should be thrown as a notification about it
+ // and the package must disconnect from the stream
+ DisconnectFromTargetAndThrowException_Impl( xTempInStream );
+ }
+ }
+ else if ( m_eMode == e_IMode_URL )
+ {
+ uno::Reference< XOutputStream > aOrigFileStream;
+ bool bCanBeCorrupted = false;
+
+ if( isLocalFile() )
+ {
+ // write directly in case of local file
+ uno::Reference< css::ucb::XSimpleFileAccess3 > xSimpleAccess(
+ SimpleFileAccess::create( m_xContext ) );
+ OSL_ENSURE( xSimpleAccess.is(), "Can't instantiate SimpleFileAccess service!" );
+ uno::Reference< io::XTruncate > xOrigTruncate;
+ if ( xSimpleAccess.is() )
+ {
+ try
+ {
+ aOrigFileStream = xSimpleAccess->openFileWrite( m_aURL );
+ xOrigTruncate.set( aOrigFileStream, uno::UNO_QUERY_THROW );
+ // after successful truncation the file is already corrupted
+ xOrigTruncate->truncate();
+ }
+ catch( uno::Exception& )
+ {}
+ }
+
+ if( xOrigTruncate.is() )
+ {
+ try
+ {
+ ::comphelper::OStorageHelper::CopyInputToOutput( xTempInStream, aOrigFileStream );
+ aOrigFileStream->closeOutput();
+ }
+ catch( uno::Exception& )
+ {
+ try {
+ aOrigFileStream->closeOutput();
+ } catch ( uno::Exception& ) {}
+
+ aOrigFileStream.clear();
+ // the original file can already be corrupted
+ bCanBeCorrupted = true;
+ }
+ }
+ }
+
+ if( !aOrigFileStream.is() )
+ {
+ try
+ {
+ uno::Reference < XPropertySet > xPropSet ( xTempInStream, UNO_QUERY_THROW );
+
+ OUString sTargetFolder = m_aURL.copy ( 0, m_aURL.lastIndexOf ( u'/' ) );
+ Content aContent(
+ sTargetFolder, uno::Reference< XCommandEnvironment >(),
+ m_xContext );
+
+ OUString sTempURL;
+ Any aAny = xPropSet->getPropertyValue ("Uri");
+ aAny >>= sTempURL;
+
+ TransferInfo aInfo;
+ aInfo.NameClash = NameClash::OVERWRITE;
+ aInfo.MoveData = false;
+ aInfo.SourceURL = sTempURL;
+ aInfo.NewTitle = rtl::Uri::decode ( m_aURL.copy ( 1 + m_aURL.lastIndexOf ( u'/' ) ),
+ rtl_UriDecodeWithCharset,
+ RTL_TEXTENCODING_UTF8 );
+ // if the file is still not corrupted, it can become after the next step
+ aContent.executeCommand ("transfer", Any(aInfo) );
+ }
+ catch ( const css::uno::Exception& )
+ {
+ if ( bCanBeCorrupted )
+ DisconnectFromTargetAndThrowException_Impl( xTempInStream );
+
+ css::uno::Any anyEx = cppu::getCaughtException();
+ throw WrappedTargetException(
+ THROW_WHERE "This package may be read only!",
+ static_cast < OWeakObject * > ( this ),
+ anyEx );
+ }
+ }
+ }
+ }
+
+ // after successful storing it can be set to false
+ m_bMediaTypeFallbackUsed = false;
+}
+
+void ZipPackage::DisconnectFromTargetAndThrowException_Impl( const uno::Reference< io::XInputStream >& xTempStream )
+{
+ m_xStream.set( xTempStream, uno::UNO_QUERY );
+ if ( m_xStream.is() )
+ m_eMode = e_IMode_XStream;
+ else
+ m_eMode = e_IMode_XInputStream;
+
+ OUString aTempURL;
+ try {
+ uno::Reference< beans::XPropertySet > xTempFile( xTempStream, uno::UNO_QUERY_THROW );
+ uno::Any aUrl = xTempFile->getPropertyValue("Uri");
+ aUrl >>= aTempURL;
+ xTempFile->setPropertyValue("RemoveFile",
+ uno::Any( false ) );
+ }
+ catch ( uno::Exception& )
+ {
+ OSL_FAIL( "These calls are pretty simple, they should not fail!" );
+ }
+
+ OUString aErrTxt(THROW_WHERE "This package is read only!");
+ embed::UseBackupException aException( aErrTxt, uno::Reference< uno::XInterface >(), aTempURL );
+ throw WrappedTargetException( aErrTxt,
+ static_cast < OWeakObject * > ( this ),
+ Any ( aException ) );
+}
+
+uno::Sequence< sal_Int8 > ZipPackage::GetEncryptionKey()
+{
+ uno::Sequence< sal_Int8 > aResult;
+
+ if ( m_aStorageEncryptionKeys.hasElements() )
+ {
+ OUString aNameToFind;
+ if ( m_nStartKeyGenerationID == xml::crypto::DigestID::SHA256 )
+ aNameToFind = PACKAGE_ENCRYPTIONDATA_SHA256UTF8;
+ else if ( m_nStartKeyGenerationID == xml::crypto::DigestID::SHA1 )
+ aNameToFind = PACKAGE_ENCRYPTIONDATA_SHA1CORRECT;
+ else
+ throw uno::RuntimeException(THROW_WHERE "No expected key is provided!" );
+
+ for ( const auto& rKey : std::as_const(m_aStorageEncryptionKeys) )
+ if ( rKey.Name == aNameToFind )
+ rKey.Value >>= aResult;
+ }
+ else
+ aResult = m_aEncryptionKey;
+
+ return aResult;
+}
+
+sal_Bool SAL_CALL ZipPackage::hasPendingChanges()
+{
+ return false;
+}
+Sequence< ElementChange > SAL_CALL ZipPackage::getPendingChanges()
+{
+ return uno::Sequence < ElementChange > ();
+}
+
+
+OUString ZipPackage::getImplementationName()
+{
+ return "com.sun.star.packages.comp.ZipPackage";
+}
+
+Sequence< OUString > ZipPackage::getSupportedServiceNames()
+{
+ return { "com.sun.star.packages.Package" };
+}
+
+sal_Bool SAL_CALL ZipPackage::supportsService( OUString const & rServiceName )
+{
+ return cppu::supportsService(this, rServiceName);
+}
+
+const Sequence< sal_Int8 > & ZipPackage::getUnoTunnelId()
+{
+ static const comphelper::UnoIdInit implId;
+ return implId.getSeq();
+}
+
+sal_Int64 SAL_CALL ZipPackage::getSomething( const uno::Sequence< sal_Int8 >& aIdentifier )
+{
+ return comphelper::getSomethingImpl(aIdentifier, this);
+}
+
+uno::Reference< XPropertySetInfo > SAL_CALL ZipPackage::getPropertySetInfo()
+{
+ return uno::Reference < XPropertySetInfo > ();
+}
+
+void SAL_CALL ZipPackage::setPropertyValue( const OUString& aPropertyName, const Any& aValue )
+{
+ if ( m_nFormat != embed::StorageFormats::PACKAGE )
+ throw UnknownPropertyException(aPropertyName);
+
+ if (aPropertyName == HAS_ENCRYPTED_ENTRIES_PROPERTY
+ ||aPropertyName == HAS_NONENCRYPTED_ENTRIES_PROPERTY
+ ||aPropertyName == IS_INCONSISTENT_PROPERTY
+ ||aPropertyName == MEDIATYPE_FALLBACK_USED_PROPERTY)
+ throw PropertyVetoException(THROW_WHERE );
+ else if ( aPropertyName == ENCRYPTION_KEY_PROPERTY )
+ {
+ if ( !( aValue >>= m_aEncryptionKey ) )
+ throw IllegalArgumentException(THROW_WHERE, uno::Reference< uno::XInterface >(), 2 );
+
+ m_aStorageEncryptionKeys.realloc( 0 );
+ }
+ else if ( aPropertyName == STORAGE_ENCRYPTION_KEYS_PROPERTY )
+ {
+ // this property is only necessary to support raw passwords in storage API;
+ // because of this support the storage has to operate with more than one key dependent on storage generation algorithm;
+ // when this support is removed, the storage will get only one key from outside
+ if ( !( aValue >>= m_aStorageEncryptionKeys ) )
+ throw IllegalArgumentException(THROW_WHERE, uno::Reference< uno::XInterface >(), 2 );
+
+ m_aEncryptionKey.realloc( 0 );
+ }
+ else if ( aPropertyName == ENCRYPTION_ALGORITHMS_PROPERTY )
+ {
+ uno::Sequence< beans::NamedValue > aAlgorithms;
+ if ( m_pZipFile || !( aValue >>= aAlgorithms ) || !aAlgorithms.hasElements() )
+ {
+ // the algorithms can not be changed if the file has a persistence based on the algorithms ( m_pZipFile )
+ throw IllegalArgumentException(THROW_WHERE "unexpected algorithms list is provided.", uno::Reference< uno::XInterface >(), 2 );
+ }
+
+ for ( const auto& rAlgorithm : std::as_const(aAlgorithms) )
+ {
+ if ( rAlgorithm.Name == "StartKeyGenerationAlgorithm" )
+ {
+ sal_Int32 nID = 0;
+ if ( !( rAlgorithm.Value >>= nID )
+ || ( nID != xml::crypto::DigestID::SHA256 && nID != xml::crypto::DigestID::SHA1 ) )
+ throw IllegalArgumentException(THROW_WHERE "Unexpected start key generation algorithm is provided!", uno::Reference< uno::XInterface >(), 2 );
+
+ m_nStartKeyGenerationID = nID;
+ }
+ else if ( rAlgorithm.Name == "EncryptionAlgorithm" )
+ {
+ sal_Int32 nID = 0;
+ if ( !( rAlgorithm.Value >>= nID )
+ || ( nID != xml::crypto::CipherID::AES_CBC_W3C_PADDING && nID != xml::crypto::CipherID::BLOWFISH_CFB_8 ) )
+ throw IllegalArgumentException(THROW_WHERE "Unexpected start key generation algorithm is provided!", uno::Reference< uno::XInterface >(), 2 );
+
+ m_nCommonEncryptionID = nID;
+ }
+ else if ( rAlgorithm.Name == "ChecksumAlgorithm" )
+ {
+ sal_Int32 nID = 0;
+ if ( !( rAlgorithm.Value >>= nID )
+ || ( nID != xml::crypto::DigestID::SHA1_1K && nID != xml::crypto::DigestID::SHA256_1K ) )
+ throw IllegalArgumentException(THROW_WHERE "Unexpected start key generation algorithm is provided!", uno::Reference< uno::XInterface >(), 2 );
+
+ m_nChecksumDigestID = nID;
+ }
+ else
+ {
+ OSL_ENSURE( false, "Unexpected encryption algorithm is provided!" );
+ throw IllegalArgumentException(THROW_WHERE "unexpected algorithms list is provided.", uno::Reference< uno::XInterface >(), 2 );
+ }
+ }
+ }
+ else if ( aPropertyName == ENCRYPTION_GPG_PROPERTIES )
+ {
+ uno::Sequence< uno::Sequence< beans::NamedValue > > aGpgProps;
+ if ( !( aValue >>= aGpgProps ) || !aGpgProps.hasElements() )
+ {
+ throw IllegalArgumentException(THROW_WHERE "unexpected Gpg properties are provided.", uno::Reference< uno::XInterface >(), 2 );
+ }
+
+ m_aGpgProps = aGpgProps;
+
+ // override algorithm defaults (which are some legacy ODF
+ // defaults) with reasonable values
+ m_nStartKeyGenerationID = 0; // this is unused for PGP
+ m_nCommonEncryptionID = xml::crypto::CipherID::AES_CBC_W3C_PADDING;
+ m_nChecksumDigestID = xml::crypto::DigestID::SHA512_1K;
+ }
+ else
+ throw UnknownPropertyException(aPropertyName);
+}
+
+Any SAL_CALL ZipPackage::getPropertyValue( const OUString& PropertyName )
+{
+ // TODO/LATER: Activate the check when zip-ucp is ready
+ // if ( m_nFormat != embed::StorageFormats::PACKAGE )
+ // throw UnknownPropertyException(THROW_WHERE );
+
+ if ( PropertyName == ENCRYPTION_KEY_PROPERTY )
+ {
+ return Any(m_aEncryptionKey);
+ }
+ else if ( PropertyName == ENCRYPTION_ALGORITHMS_PROPERTY )
+ {
+ ::comphelper::SequenceAsHashMap aAlgorithms;
+ aAlgorithms["StartKeyGenerationAlgorithm"] <<= m_nStartKeyGenerationID;
+ aAlgorithms["EncryptionAlgorithm"] <<= m_nCommonEncryptionID;
+ aAlgorithms["ChecksumAlgorithm"] <<= m_nChecksumDigestID;
+ return Any(aAlgorithms.getAsConstNamedValueList());
+ }
+ if ( PropertyName == STORAGE_ENCRYPTION_KEYS_PROPERTY )
+ {
+ return Any(m_aStorageEncryptionKeys);
+ }
+ else if ( PropertyName == HAS_ENCRYPTED_ENTRIES_PROPERTY )
+ {
+ return Any(m_bHasEncryptedEntries);
+ }
+ else if ( PropertyName == ENCRYPTION_GPG_PROPERTIES )
+ {
+ return Any(m_aGpgProps);
+ }
+ else if ( PropertyName == HAS_NONENCRYPTED_ENTRIES_PROPERTY )
+ {
+ return Any(m_bHasNonEncryptedEntries);
+ }
+ else if ( PropertyName == IS_INCONSISTENT_PROPERTY )
+ {
+ return Any(m_bInconsistent);
+ }
+ else if ( PropertyName == MEDIATYPE_FALLBACK_USED_PROPERTY )
+ {
+ return Any(m_bMediaTypeFallbackUsed);
+ }
+ throw UnknownPropertyException(PropertyName);
+}
+void SAL_CALL ZipPackage::addPropertyChangeListener( const OUString& /*aPropertyName*/, const uno::Reference< XPropertyChangeListener >& /*xListener*/ )
+{
+}
+void SAL_CALL ZipPackage::removePropertyChangeListener( const OUString& /*aPropertyName*/, const uno::Reference< XPropertyChangeListener >& /*aListener*/ )
+{
+}
+void SAL_CALL ZipPackage::addVetoableChangeListener( const OUString& /*PropertyName*/, const uno::Reference< XVetoableChangeListener >& /*aListener*/ )
+{
+}
+void SAL_CALL ZipPackage::removeVetoableChangeListener( const OUString& /*PropertyName*/, const uno::Reference< XVetoableChangeListener >& /*aListener*/ )
+{
+}
+
+extern "C" SAL_DLLPUBLIC_EXPORT css::uno::XInterface*
+package_ZipPackage_get_implementation(
+ css::uno::XComponentContext* context , css::uno::Sequence<css::uno::Any> const&)
+{
+ return cppu::acquire(new ZipPackage(context));
+}
+
+/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
diff --git a/package/source/zippackage/ZipPackageBuffer.cxx b/package/source/zippackage/ZipPackageBuffer.cxx
new file mode 100644
index 000000000..810daa737
--- /dev/null
+++ b/package/source/zippackage/ZipPackageBuffer.cxx
@@ -0,0 +1,128 @@
+/* -*- 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 <ZipPackageBuffer.hxx>
+#include <PackageConstants.hxx>
+#include <string.h>
+#include <sal/log.hxx>
+
+#include <com/sun/star/io/BufferSizeExceededException.hpp>
+#include <com/sun/star/lang/IllegalArgumentException.hpp>
+
+using namespace ::com::sun::star;
+using namespace com::sun::star::uno;
+using namespace com::sun::star::io;
+using com::sun::star::lang::IllegalArgumentException;
+
+#if OSL_DEBUG_LEVEL > 0
+#define THROW_WHERE SAL_WHERE
+#else
+#define THROW_WHERE ""
+#endif
+
+ZipPackageBuffer::ZipPackageBuffer()
+: m_nBufferSize (n_ConstBufferSize)
+, m_nEnd(0)
+, m_nCurrent(0)
+, m_bMustInitBuffer ( true )
+{
+}
+ZipPackageBuffer::~ZipPackageBuffer()
+{
+}
+
+sal_Int32 SAL_CALL ZipPackageBuffer::readBytes( Sequence< sal_Int8 >& aData, sal_Int32 nBytesToRead )
+{
+ if (nBytesToRead < 0)
+ throw BufferSizeExceededException(THROW_WHERE, *this );
+
+ if (nBytesToRead + m_nCurrent > m_nEnd)
+ nBytesToRead = static_cast < sal_Int32 > (m_nEnd - m_nCurrent);
+
+ aData.realloc ( nBytesToRead );
+ memcpy(aData.getArray(), m_aBuffer.getConstArray() + m_nCurrent, nBytesToRead);
+ m_nCurrent +=nBytesToRead;
+ return nBytesToRead;
+}
+
+sal_Int32 SAL_CALL ZipPackageBuffer::readSomeBytes( Sequence< sal_Int8 >& aData, sal_Int32 nMaxBytesToRead )
+{
+ return readBytes(aData, nMaxBytesToRead);
+}
+void SAL_CALL ZipPackageBuffer::skipBytes( sal_Int32 nBytesToSkip )
+{
+ if (nBytesToSkip < 0)
+ throw BufferSizeExceededException(THROW_WHERE, *this );
+
+ if (nBytesToSkip + m_nCurrent > m_nEnd)
+ nBytesToSkip = static_cast < sal_Int32 > (m_nEnd - m_nCurrent);
+
+ m_nCurrent+=nBytesToSkip;
+}
+sal_Int32 SAL_CALL ZipPackageBuffer::available( )
+{
+ return std::min<sal_Int64>(SAL_MAX_INT32, m_nEnd - m_nCurrent);
+}
+void SAL_CALL ZipPackageBuffer::closeInput( )
+{
+}
+void SAL_CALL ZipPackageBuffer::writeBytes( const Sequence< sal_Int8 >& aData )
+{
+ sal_Int64 nDataLen = aData.getLength(), nCombined = m_nEnd + nDataLen;
+
+ if ( nCombined > m_nBufferSize)
+ {
+ do
+ m_nBufferSize *=2;
+ while (nCombined > m_nBufferSize);
+ m_aBuffer.realloc(static_cast < sal_Int32 > (m_nBufferSize));
+ m_bMustInitBuffer = false;
+ }
+ else if (m_bMustInitBuffer)
+ {
+ m_aBuffer.realloc ( static_cast < sal_Int32 > ( m_nBufferSize ) );
+ m_bMustInitBuffer = false;
+ }
+ memcpy( m_aBuffer.getArray() + m_nCurrent, aData.getConstArray(), static_cast < sal_Int32 > (nDataLen));
+ m_nCurrent+=nDataLen;
+ if (m_nCurrent>m_nEnd)
+ m_nEnd = m_nCurrent;
+}
+void SAL_CALL ZipPackageBuffer::flush( )
+{
+}
+void SAL_CALL ZipPackageBuffer::closeOutput( )
+{
+}
+void SAL_CALL ZipPackageBuffer::seek( sal_Int64 location )
+{
+ if ( location > m_nEnd || location < 0 )
+ throw IllegalArgumentException(THROW_WHERE, uno::Reference< uno::XInterface >(), 1 );
+ m_nCurrent = location;
+}
+sal_Int64 SAL_CALL ZipPackageBuffer::getPosition( )
+{
+ return m_nCurrent;
+}
+sal_Int64 SAL_CALL ZipPackageBuffer::getLength( )
+{
+ return m_nEnd;
+}
+
+/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
diff --git a/package/source/zippackage/ZipPackageEntry.cxx b/package/source/zippackage/ZipPackageEntry.cxx
new file mode 100644
index 000000000..df18f0874
--- /dev/null
+++ b/package/source/zippackage/ZipPackageEntry.cxx
@@ -0,0 +1,125 @@
+/* -*- 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 <ZipPackageEntry.hxx>
+#include <com/sun/star/lang/NoSupportException.hpp>
+#include <com/sun/star/packages/zip/ZipConstants.hpp>
+#include <osl/diagnose.h>
+#include <sal/log.hxx>
+
+#include <ZipPackageFolder.hxx>
+
+#include <comphelper/servicehelper.hxx>
+#include <comphelper/storagehelper.hxx>
+
+using namespace com::sun::star;
+using namespace com::sun::star::uno;
+using namespace com::sun::star::lang;
+using namespace com::sun::star::container;
+using namespace com::sun::star::packages::zip;
+using namespace com::sun::star::packages::zip::ZipConstants;
+
+#if OSL_DEBUG_LEVEL > 0
+#define THROW_WHERE SAL_WHERE
+#else
+#define THROW_WHERE ""
+#endif
+
+ZipPackageEntry::ZipPackageEntry()
+: mbIsFolder( false )
+, mbAllowRemoveOnInsert(false)
+, mpParent ( nullptr )
+, m_nFormat(0)
+{
+}
+
+ZipPackageEntry::~ZipPackageEntry()
+{
+ // When the entry is destroyed it must be already disconnected from the parent
+ OSL_ENSURE( !mpParent, "The parent must be disconnected already! Memory corruption is possible!" );
+}
+
+// XChild
+OUString SAL_CALL ZipPackageEntry::getName( )
+{
+ return msName;
+}
+void SAL_CALL ZipPackageEntry::setName( const OUString& aName )
+{
+ if ( mpParent && !msName.isEmpty() && mpParent->hasByName ( msName ) )
+ mpParent->removeByName ( msName );
+
+ // unfortunately no other exception than RuntimeException can be thrown here
+ // usually the package is used through storage implementation, the problem should be detected there
+ if ( !::comphelper::OStorageHelper::IsValidZipEntryFileName( aName, true ) )
+ throw RuntimeException(THROW_WHERE "Unexpected character is used in file name." );
+
+ msName = aName;
+
+ if ( mpParent )
+ mpParent->doInsertByName ( this, false );
+}
+uno::Reference< XInterface > SAL_CALL ZipPackageEntry::getParent( )
+{
+ // return uno::Reference< XInterface >( xParent, UNO_QUERY );
+ return uno::Reference< XInterface >( static_cast< ::cppu::OWeakObject* >( mpParent ), UNO_QUERY );
+}
+
+void ZipPackageEntry::doSetParent ( ZipPackageFolder * pNewParent )
+{
+ // xParent = mpParent = pNewParent;
+ mpParent = pNewParent;
+ if ( !msName.isEmpty() && !pNewParent->hasByName ( msName ) )
+ pNewParent->doInsertByName ( this, false );
+}
+
+void SAL_CALL ZipPackageEntry::setParent( const uno::Reference< XInterface >& xNewParent )
+{
+ if ( !xNewParent.is() )
+ throw NoSupportException(THROW_WHERE );
+ ZipPackageFolder* pNewParent = comphelper::getFromUnoTunnel<ZipPackageFolder>(xNewParent);
+ if (!pNewParent)
+ throw NoSupportException(THROW_WHERE );
+
+ if ( pNewParent != mpParent )
+ {
+ if ( mpParent && !msName.isEmpty() && mpParent->hasByName ( msName ) && mbAllowRemoveOnInsert )
+ mpParent->removeByName( msName );
+ doSetParent ( pNewParent );
+ }
+}
+ //XPropertySet
+uno::Reference< beans::XPropertySetInfo > SAL_CALL ZipPackageEntry::getPropertySetInfo( )
+{
+ return uno::Reference < beans::XPropertySetInfo > ();
+}
+void SAL_CALL ZipPackageEntry::addPropertyChangeListener( const OUString& /*aPropertyName*/, const uno::Reference< beans::XPropertyChangeListener >& /*xListener*/ )
+{
+}
+void SAL_CALL ZipPackageEntry::removePropertyChangeListener( const OUString& /*aPropertyName*/, const uno::Reference< beans::XPropertyChangeListener >& /*aListener*/ )
+{
+}
+void SAL_CALL ZipPackageEntry::addVetoableChangeListener( const OUString& /*PropertyName*/, const uno::Reference< beans::XVetoableChangeListener >& /*aListener*/ )
+{
+}
+void SAL_CALL ZipPackageEntry::removeVetoableChangeListener( const OUString& /*PropertyName*/, const uno::Reference< beans::XVetoableChangeListener >& /*aListener*/ )
+{
+}
+
+/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
diff --git a/package/source/zippackage/ZipPackageFolder.cxx b/package/source/zippackage/ZipPackageFolder.cxx
new file mode 100644
index 000000000..7e7168805
--- /dev/null
+++ b/package/source/zippackage/ZipPackageFolder.cxx
@@ -0,0 +1,424 @@
+/* -*- 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 <ZipPackageFolder.hxx>
+#include <ZipOutputStream.hxx>
+#include <ZipPackageStream.hxx>
+#include <PackageConstants.hxx>
+#include "ZipPackageFolderEnumeration.hxx"
+#include <com/sun/star/io/IOException.hpp>
+#include <com/sun/star/packages/zip/ZipConstants.hpp>
+#include <com/sun/star/packages/zip/ZipException.hpp>
+#include <com/sun/star/embed/StorageFormats.hpp>
+#include <comphelper/sequence.hxx>
+#include <comphelper/servicehelper.hxx>
+#include <cppuhelper/supportsservice.hxx>
+#include <sal/log.hxx>
+#include <com/sun/star/beans/PropertyValue.hpp>
+
+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
+
+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( std::u16string_view aPath )
+{
+ bool bHasUnexpected = false;
+
+ for (const auto& [rShortName, rInfo] : maContents)
+ {
+ if ( rInfo.bFolder )
+ {
+ if ( aPath == u"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 == u"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.empty() || rShortName != "mimetype" )
+ {
+ // if it is not "mimetype" from the root it is not a part of the package
+ bHasUnexpected = true;
+ }
+ }
+ }
+
+ if (bHasUnexpected)
+ break;
+ }
+
+ return bHasUnexpected;
+}
+
+void ZipPackageFolder::setChildStreamsTypeByExtension( const beans::StringPair& aPair )
+{
+ OUString aExt;
+ if ( aPair.First.toChar() == '.' )
+ aExt = aPair.First;
+ else
+ aExt = "." + aPair.First;
+
+ for (const auto& [rShortName, rInfo] : maContents)
+ {
+ 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 );
+ }
+ }
+}
+
+const css::uno::Sequence < sal_Int8 > & ZipPackageFolder::getUnoTunnelId()
+{
+ static const comphelper::UnoIdInit lcl_CachedImplId;
+ return lcl_CachedImplId.getSeq();
+}
+
+ // 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 );
+
+ ZipPackageEntry* pEntry = comphelper::getFromUnoTunnel<ZipPackageFolder>(xRef);
+ if (!pEntry)
+ pEntry = comphelper::getFromUnoTunnel<ZipPackageStream>(xRef);
+ if (!pEntry)
+ 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::Any ( doGetByName ( aName ).xTunnel );
+}
+uno::Sequence< OUString > SAL_CALL ZipPackageFolder::getElementNames( )
+{
+ return comphelper::mapKeysToSequence(maContents);
+}
+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)
+{
+ uno::Sequence < PropertyValue > aPropSet (PKG_SIZE_NOENCR_MNFST);
+ OUString sTempName = rPath + "/";
+
+ if ( !GetMediaType().isEmpty() )
+ {
+ auto pPropSet = aPropSet.getArray();
+ pPropSet[PKG_MNFST_MEDIATYPE].Name = "MediaType";
+ pPropSet[PKG_MNFST_MEDIATYPE].Value <<= GetMediaType();
+ pPropSet[PKG_MNFST_VERSION].Name = "Version";
+ pPropSet[PKG_MNFST_VERSION].Value <<= GetVersion();
+ pPropSet[PKG_MNFST_FULLPATH].Name = "FullPath";
+ pPropSet[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.hasElements() && ( 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
+{
+ 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& )
+ {
+ throw uno::RuntimeException( THROW_WHERE );
+ }
+ catch ( IOException& )
+ {
+ throw uno::RuntimeException( THROW_WHERE );
+ }
+ }
+
+ 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;
+ if( !aIter->second.pStream->saveChild(
+ rPath + aIter->first, rManList, rZipOut, rEncryptionKey, nPBKDF2IterationCount, rRandomPool ))
+ {
+ throw uno::RuntimeException( THROW_WHERE );
+ }
+ }
+ }
+
+ for (const auto& [rShortName, rInfo] : maContents)
+ {
+ if ( !bMimeTypeStreamStored || rShortName != aMimeTypeStreamName )
+ {
+ if (rInfo.bFolder)
+ {
+ if( !rInfo.pFolder->saveChild(
+ rPath + rShortName, rManList, rZipOut, rEncryptionKey, nPBKDF2IterationCount, rRandomPool ))
+ {
+ throw uno::RuntimeException( THROW_WHERE );
+ }
+ }
+ else
+ {
+ if( !rInfo.pStream->saveChild(
+ rPath + rShortName, rManList, rZipOut, rEncryptionKey, nPBKDF2IterationCount, rRandomPool ))
+ {
+ throw uno::RuntimeException( THROW_WHERE );
+ }
+ }
+ }
+ }
+}
+
+sal_Int64 SAL_CALL ZipPackageFolder::getSomething( const uno::Sequence< sal_Int8 >& aIdentifier )
+{
+ return comphelper::getSomethingImpl(aIdentifier, this);
+}
+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(aPropertyName);
+}
+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::Any ( msMediaType );
+ }
+ else if ( PropertyName == "Version" )
+ return uno::Any( m_sVersion );
+ else if ( PropertyName == "Size" )
+ return uno::Any ( aEntry.nSize );
+ else
+ throw UnknownPropertyException(PropertyName);
+}
+
+void ZipPackageFolder::doInsertByName ( ZipPackageEntry *pEntry, bool bSetParent )
+{
+ if ( pEntry->IsFolder() )
+ maContents.emplace(pEntry->getName(), ZipContentInfo(static_cast<ZipPackageFolder*>(pEntry)));
+ else
+ maContents.emplace(pEntry->getName(), ZipContentInfo(static_cast<ZipPackageStream*>(pEntry)));
+ if ( bSetParent )
+ pEntry->setParent ( *this );
+}
+
+OUString ZipPackageFolder::getImplementationName()
+{
+ return "ZipPackageFolder";
+}
+
+uno::Sequence< OUString > ZipPackageFolder::getSupportedServiceNames()
+{
+ return { "com.sun.star.packages.PackageFolder" };
+}
+
+sal_Bool SAL_CALL ZipPackageFolder::supportsService( OUString const & rServiceName )
+{
+ return cppu::supportsService(this, rServiceName);
+}
+
+
+ZipContentInfo::ZipContentInfo ( ZipPackageStream * pNewStream )
+: xTunnel ( pNewStream )
+, bFolder ( false )
+, pStream ( pNewStream )
+{
+}
+
+ZipContentInfo::ZipContentInfo ( ZipPackageFolder * pNewFolder )
+: xTunnel ( pNewFolder )
+, bFolder ( true )
+, pFolder ( pNewFolder )
+{
+}
+
+ZipContentInfo::ZipContentInfo( const ZipContentInfo& ) = default;
+ZipContentInfo::ZipContentInfo( ZipContentInfo&& ) = default;
+ZipContentInfo& ZipContentInfo::operator=( const ZipContentInfo& ) = default;
+ZipContentInfo& ZipContentInfo::operator=( ZipContentInfo&& ) = default;
+
+ZipContentInfo::~ZipContentInfo()
+{
+ if ( bFolder )
+ pFolder->clearParent();
+ else
+ pStream->clearParent();
+}
+
+/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
diff --git a/package/source/zippackage/ZipPackageFolderEnumeration.cxx b/package/source/zippackage/ZipPackageFolderEnumeration.cxx
new file mode 100644
index 000000000..7b08e1890
--- /dev/null
+++ b/package/source/zippackage/ZipPackageFolderEnumeration.cxx
@@ -0,0 +1,70 @@
+/* -*- 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 "ZipPackageFolderEnumeration.hxx"
+#include <cppuhelper/supportsservice.hxx>
+#include <sal/log.hxx>
+
+using namespace com::sun::star;
+
+#if OSL_DEBUG_LEVEL > 0
+#define THROW_WHERE SAL_WHERE
+#else
+#define THROW_WHERE ""
+#endif
+
+ZipPackageFolderEnumeration::ZipPackageFolderEnumeration(ContentHash& rInput)
+ : rContents(rInput)
+ , aIterator(rContents.begin())
+{
+}
+
+ZipPackageFolderEnumeration::~ZipPackageFolderEnumeration() {}
+
+sal_Bool SAL_CALL ZipPackageFolderEnumeration::hasMoreElements()
+{
+ return (aIterator != rContents.end());
+}
+uno::Any SAL_CALL ZipPackageFolderEnumeration::nextElement()
+{
+ uno::Any aAny;
+ if (aIterator == rContents.end())
+ throw container::NoSuchElementException(THROW_WHERE);
+ aAny <<= (*aIterator).second.xTunnel;
+ ++aIterator;
+ return aAny;
+}
+
+OUString ZipPackageFolderEnumeration::getImplementationName()
+{
+ return "ZipPackageFolderEnumeration";
+}
+
+uno::Sequence<OUString> ZipPackageFolderEnumeration::getSupportedServiceNames()
+{
+ uno::Sequence<OUString> aNames{ "com.sun.star.packages.PackageFolderEnumeration" };
+ return aNames;
+}
+
+sal_Bool SAL_CALL ZipPackageFolderEnumeration::supportsService(OUString const& rServiceName)
+{
+ return cppu::supportsService(this, rServiceName);
+}
+
+/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
diff --git a/package/source/zippackage/ZipPackageFolderEnumeration.hxx b/package/source/zippackage/ZipPackageFolderEnumeration.hxx
new file mode 100644
index 000000000..f3b805b2a
--- /dev/null
+++ b/package/source/zippackage/ZipPackageFolderEnumeration.hxx
@@ -0,0 +1,49 @@
+/* -*- 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 .
+ */
+#ifndef INCLUDED_PACKAGE_SOURCE_ZIPPACKAGE_ZIPPACKAGEFOLDERENUMERATION_HXX
+#define INCLUDED_PACKAGE_SOURCE_ZIPPACKAGE_ZIPPACKAGEFOLDERENUMERATION_HXX
+
+#include <cppuhelper/implbase.hxx>
+#include <com/sun/star/container/XEnumeration.hpp>
+#include <com/sun/star/lang/XServiceInfo.hpp>
+#include <ZipPackageFolder.hxx>
+
+class ZipPackageFolderEnumeration final
+ : public cppu::WeakImplHelper<css::container::XEnumeration, css::lang::XServiceInfo>
+{
+ ContentHash& rContents;
+ ContentHash::const_iterator aIterator;
+
+public:
+ //ZipPackageFolderEnumeration (unordered_map < OUString, css::uno::Reference < css::container::XNamed >, hashFunc, eqFunc > &rInput);
+ ZipPackageFolderEnumeration(ContentHash& rInput);
+ virtual ~ZipPackageFolderEnumeration() override;
+
+ // XEnumeration
+ virtual sal_Bool SAL_CALL hasMoreElements() override;
+ virtual css::uno::Any SAL_CALL nextElement() override;
+
+ // XServiceInfo
+ virtual OUString SAL_CALL getImplementationName() override;
+ virtual sal_Bool SAL_CALL supportsService(const OUString& ServiceName) override;
+ virtual css::uno::Sequence<OUString> SAL_CALL getSupportedServiceNames() override;
+};
+#endif
+
+/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
diff --git a/package/source/zippackage/ZipPackageSink.cxx b/package/source/zippackage/ZipPackageSink.cxx
new file mode 100644
index 000000000..103af9d6e
--- /dev/null
+++ b/package/source/zippackage/ZipPackageSink.cxx
@@ -0,0 +1,37 @@
+/* -*- 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 "ZipPackageSink.hxx"
+
+ZipPackageSink::ZipPackageSink()
+ : xStream(css::uno::Reference<css::io::XInputStream>(nullptr))
+{
+}
+ZipPackageSink::~ZipPackageSink() {}
+void SAL_CALL
+ZipPackageSink::setInputStream(const css::uno::Reference<css::io::XInputStream>& aStream)
+{
+ xStream = aStream;
+}
+css::uno::Reference<css::io::XInputStream> SAL_CALL ZipPackageSink::getInputStream()
+{
+ return xStream;
+}
+
+/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
diff --git a/package/source/zippackage/ZipPackageSink.hxx b/package/source/zippackage/ZipPackageSink.hxx
new file mode 100644
index 000000000..9bc406c89
--- /dev/null
+++ b/package/source/zippackage/ZipPackageSink.hxx
@@ -0,0 +1,38 @@
+/* -*- 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 .
+ */
+#ifndef INCLUDED_PACKAGE_SOURCE_ZIPPACKAGE_ZIPPACKAGESINK_HXX
+#define INCLUDED_PACKAGE_SOURCE_ZIPPACKAGE_ZIPPACKAGESINK_HXX
+
+#include <com/sun/star/io/XActiveDataSink.hpp>
+#include <cppuhelper/implbase.hxx>
+
+class ZipPackageSink final : public ::cppu::WeakImplHelper<css::io::XActiveDataSink>
+{
+ css::uno::Reference<css::io::XInputStream> xStream;
+
+public:
+ ZipPackageSink();
+ virtual ~ZipPackageSink() override;
+ virtual void SAL_CALL
+ setInputStream(const css::uno::Reference<css::io::XInputStream>& aStream) override;
+ virtual css::uno::Reference<css::io::XInputStream> SAL_CALL getInputStream() override;
+};
+#endif
+
+/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
diff --git a/package/source/zippackage/ZipPackageStream.cxx b/package/source/zippackage/ZipPackageStream.cxx
new file mode 100644
index 000000000..b63bf24ea
--- /dev/null
+++ b/package/source/zippackage/ZipPackageStream.cxx
@@ -0,0 +1,1315 @@
+/* -*- 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 <ZipPackageStream.hxx>
+
+#include <com/sun/star/beans/PropertyValue.hpp>
+#include <com/sun/star/container/XNameContainer.hpp>
+#include <com/sun/star/packages/NoRawFormatException.hpp>
+#include <com/sun/star/packages/zip/ZipConstants.hpp>
+#include <com/sun/star/embed/StorageFormats.hpp>
+#include <com/sun/star/packages/zip/ZipIOException.hpp>
+#include <com/sun/star/packages/NoEncryptionException.hpp>
+#include <com/sun/star/packages/zip/ZipException.hpp>
+#include <com/sun/star/packages/WrongPasswordException.hpp>
+#include <com/sun/star/io/TempFile.hpp>
+#include <com/sun/star/io/XInputStream.hpp>
+#include <com/sun/star/io/XOutputStream.hpp>
+#include <com/sun/star/io/XStream.hpp>
+#include <com/sun/star/io/XSeekable.hpp>
+#include <com/sun/star/xml/crypto/DigestID.hpp>
+#include <com/sun/star/xml/crypto/CipherID.hpp>
+
+#include <CRC32.hxx>
+#include <ZipOutputEntry.hxx>
+#include <ZipOutputStream.hxx>
+#include <ZipPackage.hxx>
+#include <ZipFile.hxx>
+#include <EncryptedDataHeader.hxx>
+#include <osl/diagnose.h>
+#include "wrapstreamforshare.hxx"
+
+#include <comphelper/seekableinput.hxx>
+#include <comphelper/servicehelper.hxx>
+#include <comphelper/storagehelper.hxx>
+#include <cppuhelper/supportsservice.hxx>
+
+#include <rtl/random.h>
+#include <sal/log.hxx>
+#include <tools/diagnose_ex.h>
+
+#include <PackageConstants.hxx>
+
+#include <algorithm>
+#include <cstddef>
+
+using namespace com::sun::star::packages::zip::ZipConstants;
+using namespace com::sun::star::packages::zip;
+using namespace com::sun::star::uno;
+using namespace com::sun::star::lang;
+using namespace com::sun::star;
+using namespace cppu;
+
+#if OSL_DEBUG_LEVEL > 0
+#define THROW_WHERE SAL_WHERE
+#else
+#define THROW_WHERE ""
+#endif
+
+const css::uno::Sequence < sal_Int8 > & ZipPackageStream::getUnoTunnelId()
+{
+ static const comphelper::UnoIdInit lcl_CachedImplId;
+ return lcl_CachedImplId.getSeq();
+}
+
+ZipPackageStream::ZipPackageStream ( ZipPackage & rNewPackage,
+ const uno::Reference< XComponentContext >& xContext,
+ sal_Int32 nFormat,
+ bool bAllowRemoveOnInsert )
+: m_rZipPackage( rNewPackage )
+, m_bToBeCompressed ( true )
+, m_bToBeEncrypted ( false )
+, m_bHaveOwnKey ( false )
+, m_bIsEncrypted ( false )
+, m_nImportedStartKeyAlgorithm( 0 )
+, m_nImportedEncryptionAlgorithm( 0 )
+, m_nImportedChecksumAlgorithm( 0 )
+, m_nImportedDerivedKeySize( 0 )
+, m_nStreamMode( PACKAGE_STREAM_NOTSET )
+, m_nMagicalHackPos( 0 )
+, m_nMagicalHackSize( 0 )
+, m_nOwnStreamOrigSize( 0 )
+, m_bHasSeekable( false )
+, m_bCompressedIsSetFromOutside( false )
+, m_bFromManifest( false )
+, m_bUseWinEncoding( false )
+, m_bRawStream( false )
+{
+ m_xContext = xContext;
+ m_nFormat = nFormat;
+ mbAllowRemoveOnInsert = bAllowRemoveOnInsert;
+ SetFolder ( false );
+ aEntry.nVersion = -1;
+ aEntry.nFlag = 0;
+ aEntry.nMethod = -1;
+ aEntry.nTime = -1;
+ aEntry.nCrc = -1;
+ aEntry.nCompressedSize = -1;
+ aEntry.nSize = -1;
+ aEntry.nOffset = -1;
+ aEntry.nPathLen = -1;
+ aEntry.nExtraLen = -1;
+}
+
+ZipPackageStream::~ZipPackageStream()
+{
+}
+
+void ZipPackageStream::setZipEntryOnLoading( const ZipEntry &rInEntry )
+{
+ aEntry.nVersion = rInEntry.nVersion;
+ aEntry.nFlag = rInEntry.nFlag;
+ aEntry.nMethod = rInEntry.nMethod;
+ aEntry.nTime = rInEntry.nTime;
+ aEntry.nCrc = rInEntry.nCrc;
+ aEntry.nCompressedSize = rInEntry.nCompressedSize;
+ aEntry.nSize = rInEntry.nSize;
+ aEntry.nOffset = rInEntry.nOffset;
+ aEntry.sPath = rInEntry.sPath;
+ aEntry.nPathLen = rInEntry.nPathLen;
+ aEntry.nExtraLen = rInEntry.nExtraLen;
+
+ if ( aEntry.nMethod == STORED )
+ m_bToBeCompressed = false;
+}
+
+uno::Reference< io::XInputStream > const & ZipPackageStream::GetOwnSeekStream()
+{
+ if ( !m_bHasSeekable && m_xStream.is() )
+ {
+ // The package component requires that every stream either be FROM a package or it must support XSeekable!
+ // The only exception is a nonseekable stream that is provided only for storing, if such a stream
+ // is accessed before commit it MUST be wrapped.
+ // Wrap the stream in case it is not seekable
+ m_xStream = ::comphelper::OSeekableInputWrapper::CheckSeekableCanWrap( m_xStream, m_xContext );
+ uno::Reference< io::XSeekable > xSeek( m_xStream, UNO_QUERY_THROW );
+
+ m_bHasSeekable = true;
+ }
+
+ return m_xStream;
+}
+
+uno::Reference< io::XInputStream > ZipPackageStream::GetRawEncrStreamNoHeaderCopy()
+{
+ if ( m_nStreamMode != PACKAGE_STREAM_RAW || !GetOwnSeekStream().is() )
+ throw io::IOException(THROW_WHERE );
+
+ if ( m_xBaseEncryptionData.is() )
+ throw ZipIOException(THROW_WHERE "Encrypted stream without encryption data!" );
+
+ uno::Reference< io::XSeekable > xSeek( GetOwnSeekStream(), UNO_QUERY );
+ if ( !xSeek.is() )
+ throw ZipIOException(THROW_WHERE "The stream must be seekable!" );
+
+ // skip header
+ xSeek->seek( n_ConstHeaderSize + m_xBaseEncryptionData->m_aInitVector.getLength() +
+ m_xBaseEncryptionData->m_aSalt.getLength() + m_xBaseEncryptionData->m_aDigest.getLength() );
+
+ // create temporary stream
+ uno::Reference < io::XTempFile > xTempFile = io::TempFile::create(m_xContext);
+ uno::Reference < io::XOutputStream > xTempOut = xTempFile->getOutputStream();
+ uno::Reference < io::XInputStream > xTempIn = xTempFile->getInputStream();
+ uno::Reference < io::XSeekable > xTempSeek( xTempOut, UNO_QUERY_THROW );
+
+ // copy the raw stream to the temporary file starting from the current position
+ ::comphelper::OStorageHelper::CopyInputToOutput( GetOwnSeekStream(), xTempOut );
+ xTempOut->closeOutput();
+ xTempSeek->seek( 0 );
+
+ return xTempIn;
+}
+
+sal_Int32 ZipPackageStream::GetEncryptionAlgorithm() const
+{
+ return m_nImportedEncryptionAlgorithm ? m_nImportedEncryptionAlgorithm : m_rZipPackage.GetEncAlgID();
+}
+
+sal_Int32 ZipPackageStream::GetBlockSize() const
+{
+ return GetEncryptionAlgorithm() == css::xml::crypto::CipherID::AES_CBC_W3C_PADDING ? 16 : 8;
+}
+
+::rtl::Reference<EncryptionData> ZipPackageStream::GetEncryptionData(Bugs const bugs)
+{
+ ::rtl::Reference< EncryptionData > xResult;
+ if ( m_xBaseEncryptionData.is() )
+ xResult = new EncryptionData(
+ *m_xBaseEncryptionData,
+ GetEncryptionKey(bugs),
+ GetEncryptionAlgorithm(),
+ m_nImportedChecksumAlgorithm ? m_nImportedChecksumAlgorithm : m_rZipPackage.GetChecksumAlgID(),
+ m_nImportedDerivedKeySize ? m_nImportedDerivedKeySize : m_rZipPackage.GetDefaultDerivedKeySize(),
+ GetStartKeyGenID(),
+ bugs != Bugs::None);
+
+ return xResult;
+}
+
+uno::Sequence<sal_Int8> ZipPackageStream::GetEncryptionKey(Bugs const bugs)
+{
+ uno::Sequence< sal_Int8 > aResult;
+ sal_Int32 nKeyGenID = GetStartKeyGenID();
+ bool const bUseWinEncoding = (bugs == Bugs::WinEncodingWrongSHA1 || m_bUseWinEncoding);
+
+ if ( m_bHaveOwnKey && m_aStorageEncryptionKeys.hasElements() )
+ {
+ OUString aNameToFind;
+ if ( nKeyGenID == xml::crypto::DigestID::SHA256 )
+ aNameToFind = PACKAGE_ENCRYPTIONDATA_SHA256UTF8;
+ else if ( nKeyGenID == xml::crypto::DigestID::SHA1 )
+ {
+ aNameToFind = bUseWinEncoding
+ ? OUString(PACKAGE_ENCRYPTIONDATA_SHA1MS1252)
+ : (bugs == Bugs::WrongSHA1)
+ ? OUString(PACKAGE_ENCRYPTIONDATA_SHA1UTF8)
+ : OUString(PACKAGE_ENCRYPTIONDATA_SHA1CORRECT);
+ }
+ else
+ throw uno::RuntimeException(THROW_WHERE "No expected key is provided!" );
+
+ for ( const auto& rKey : std::as_const(m_aStorageEncryptionKeys) )
+ if ( rKey.Name == aNameToFind )
+ rKey.Value >>= aResult;
+
+ // empty keys are not allowed here
+ // so it is not important whether there is no key, or the key is empty, it is an error
+ if ( !aResult.hasElements() )
+ throw uno::RuntimeException(THROW_WHERE "No expected key is provided!" );
+ }
+ else
+ aResult = m_aEncryptionKey;
+
+ if ( !aResult.hasElements() || !m_bHaveOwnKey )
+ aResult = m_rZipPackage.GetEncryptionKey();
+
+ return aResult;
+}
+
+sal_Int32 ZipPackageStream::GetStartKeyGenID() const
+{
+ // generally should all the streams use the same Start Key
+ // but if raw copy without password takes place, we should preserve the imported algorithm
+ return m_nImportedStartKeyAlgorithm ? m_nImportedStartKeyAlgorithm : m_rZipPackage.GetStartKeyGenID();
+}
+
+uno::Reference< io::XInputStream > ZipPackageStream::TryToGetRawFromDataStream( bool bAddHeaderForEncr )
+{
+ if ( m_nStreamMode != PACKAGE_STREAM_DATA || !GetOwnSeekStream().is() || ( bAddHeaderForEncr && !m_bToBeEncrypted ) )
+ throw packages::NoEncryptionException(THROW_WHERE );
+
+ Sequence< sal_Int8 > aKey;
+
+ if ( m_bToBeEncrypted )
+ {
+ aKey = GetEncryptionKey();
+ if ( !aKey.hasElements() )
+ throw packages::NoEncryptionException(THROW_WHERE );
+ }
+
+ try
+ {
+ // create temporary file
+ uno::Reference < io::XStream > xTempStream(
+ io::TempFile::create(m_xContext),
+ uno::UNO_QUERY_THROW );
+
+ // create a package based on it
+ rtl::Reference<ZipPackage> pPackage = new ZipPackage( m_xContext );
+
+ Sequence< Any > aArgs{ Any(xTempStream) };
+ pPackage->initialize( aArgs );
+
+ // create a new package stream
+ uno::Reference< XDataSinkEncrSupport > xNewPackStream( pPackage->createInstance(), UNO_QUERY_THROW );
+ xNewPackStream->setDataStream(
+ new WrapStreamForShare(GetOwnSeekStream(), m_rZipPackage.GetSharedMutexRef()));
+
+ uno::Reference< XPropertySet > xNewPSProps( xNewPackStream, UNO_QUERY_THROW );
+
+ // copy all the properties of this stream to the new stream
+ xNewPSProps->setPropertyValue("MediaType", Any( msMediaType ) );
+ xNewPSProps->setPropertyValue("Compressed", Any( m_bToBeCompressed ) );
+ if ( m_bToBeEncrypted )
+ {
+ xNewPSProps->setPropertyValue(ENCRYPTION_KEY_PROPERTY, Any( aKey ) );
+ xNewPSProps->setPropertyValue("Encrypted", Any( true ) );
+ }
+
+ // insert a new stream in the package
+ uno::Reference< XUnoTunnel > xTunnel;
+ Any aRoot = pPackage->getByHierarchicalName("/");
+ aRoot >>= xTunnel;
+ uno::Reference< container::XNameContainer > xRootNameContainer( xTunnel, UNO_QUERY_THROW );
+
+ uno::Reference< XUnoTunnel > xNPSTunnel( xNewPackStream, UNO_QUERY );
+ xRootNameContainer->insertByName("dummy", Any( xNPSTunnel ) );
+
+ // commit the temporary package
+ pPackage->commitChanges();
+
+ // get raw stream from the temporary package
+ uno::Reference< io::XInputStream > xInRaw;
+ if ( bAddHeaderForEncr )
+ xInRaw = xNewPackStream->getRawStream();
+ else
+ xInRaw = xNewPackStream->getPlainRawStream();
+
+ // create another temporary file
+ uno::Reference < io::XOutputStream > xTempOut(
+ io::TempFile::create(m_xContext),
+ uno::UNO_QUERY_THROW );
+ uno::Reference < io::XInputStream > xTempIn( xTempOut, UNO_QUERY_THROW );
+ uno::Reference < io::XSeekable > xTempSeek( xTempOut, UNO_QUERY_THROW );
+
+ // copy the raw stream to the temporary file
+ ::comphelper::OStorageHelper::CopyInputToOutput( xInRaw, xTempOut );
+ xTempOut->closeOutput();
+ xTempSeek->seek( 0 );
+
+ // close raw stream, package stream and folder
+ xInRaw.clear();
+ xNewPSProps.clear();
+ xNPSTunnel.clear();
+ xNewPackStream.clear();
+ xTunnel.clear();
+ xRootNameContainer.clear();
+
+ // return the stream representing the first temporary file
+ return xTempIn;
+ }
+ catch ( RuntimeException& )
+ {
+ throw;
+ }
+ catch ( Exception& )
+ {
+ }
+
+ throw io::IOException(THROW_WHERE );
+}
+
+bool ZipPackageStream::ParsePackageRawStream()
+{
+ OSL_ENSURE( GetOwnSeekStream().is(), "A stream must be provided!" );
+
+ if ( !GetOwnSeekStream().is() )
+ return false;
+
+ bool bOk = false;
+
+ ::rtl::Reference< BaseEncryptionData > xTempEncrData;
+ Sequence < sal_Int8 > aHeader ( 4 );
+
+ try
+ {
+ if ( GetOwnSeekStream()->readBytes ( aHeader, 4 ) == 4 )
+ {
+ const sal_Int8 *pHeader = aHeader.getConstArray();
+ sal_uInt32 nHeader = ( pHeader [0] & 0xFF ) |
+ ( pHeader [1] & 0xFF ) << 8 |
+ ( pHeader [2] & 0xFF ) << 16 |
+ ( pHeader [3] & 0xFF ) << 24;
+ if ( nHeader == n_ConstHeader )
+ {
+ // this is one of our god-awful, but extremely devious hacks, everyone cheer
+ xTempEncrData = new BaseEncryptionData;
+
+ OUString aMediaType;
+ sal_Int32 nEncAlgorithm = 0;
+ sal_Int32 nChecksumAlgorithm = 0;
+ sal_Int32 nDerivedKeySize = 0;
+ sal_Int32 nStartKeyGenID = 0;
+ sal_Int32 nMagHackSize = 0;
+ if ( ZipFile::StaticFillData( xTempEncrData, nEncAlgorithm, nChecksumAlgorithm, nDerivedKeySize, nStartKeyGenID, nMagHackSize, aMediaType, GetOwnSeekStream() ) )
+ {
+ // We'll want to skip the data we've just read, so calculate how much we just read
+ // and remember it
+ m_nMagicalHackPos = n_ConstHeaderSize + xTempEncrData->m_aSalt.getLength()
+ + xTempEncrData->m_aInitVector.getLength()
+ + xTempEncrData->m_aDigest.getLength()
+ + aMediaType.getLength() * sizeof( sal_Unicode );
+ m_nImportedEncryptionAlgorithm = nEncAlgorithm;
+ m_nImportedChecksumAlgorithm = nChecksumAlgorithm;
+ m_nImportedDerivedKeySize = nDerivedKeySize;
+ m_nImportedStartKeyAlgorithm = nStartKeyGenID;
+ m_nMagicalHackSize = nMagHackSize;
+ msMediaType = aMediaType;
+
+ bOk = true;
+ }
+ }
+ }
+ }
+ catch( Exception& )
+ {
+ }
+
+ if ( !bOk )
+ {
+ // the provided stream is not a raw stream
+ return false;
+ }
+
+ m_xBaseEncryptionData = xTempEncrData;
+ SetIsEncrypted ( true );
+ // it's already compressed and encrypted
+ m_bToBeEncrypted = m_bToBeCompressed = false;
+
+ return true;
+}
+
+static void ImplSetStoredData( ZipEntry & rEntry, uno::Reference< io::XInputStream> const & rStream )
+{
+ // It's very annoying that we have to do this, but lots of zip packages
+ // don't allow data descriptors for STORED streams, meaning we have to
+ // know the size and CRC32 of uncompressed streams before we actually
+ // write them !
+ CRC32 aCRC32;
+ rEntry.nMethod = STORED;
+ rEntry.nCompressedSize = rEntry.nSize = aCRC32.updateStream ( rStream );
+ rEntry.nCrc = aCRC32.getValue();
+}
+
+bool ZipPackageStream::saveChild(
+ const OUString &rPath,
+ std::vector < uno::Sequence < beans::PropertyValue > > &rManList,
+ ZipOutputStream & rZipOut,
+ const uno::Sequence < sal_Int8 >& rEncryptionKey,
+ sal_Int32 nPBKDF2IterationCount,
+ const rtlRandomPool &rRandomPool)
+{
+ bool bSuccess = true;
+
+ static const OUStringLiteral sDigestProperty (u"Digest");
+ static const OUStringLiteral sEncryptionAlgProperty (u"EncryptionAlgorithm");
+ static const OUStringLiteral sStartKeyAlgProperty (u"StartKeyAlgorithm");
+ static const OUStringLiteral sDigestAlgProperty (u"DigestAlgorithm");
+ static const OUStringLiteral sDerivedKeySizeProperty (u"DerivedKeySize");
+
+ uno::Sequence < beans::PropertyValue > aPropSet (PKG_SIZE_NOENCR_MNFST);
+
+ // In case the entry we are reading is also the entry we are writing, we will
+ // store the ZipEntry data in pTempEntry
+
+ // if pTempEntry is necessary, it will be released and passed to the ZipOutputStream
+ // and be deleted in the ZipOutputStream destructor
+ std::unique_ptr < ZipEntry > pAutoTempEntry ( new ZipEntry(aEntry) );
+ ZipEntry* pTempEntry = pAutoTempEntry.get();
+
+ pTempEntry->sPath = rPath;
+ pTempEntry->nPathLen = static_cast<sal_Int16>( OUStringToOString( pTempEntry->sPath, RTL_TEXTENCODING_UTF8 ).getLength() );
+
+ const bool bToBeEncrypted = m_bToBeEncrypted && (rEncryptionKey.hasElements() || m_bHaveOwnKey);
+ const bool bToBeCompressed = bToBeEncrypted || m_bToBeCompressed;
+
+ auto pPropSet = aPropSet.getArray();
+ pPropSet[PKG_MNFST_MEDIATYPE].Name = "MediaType";
+ pPropSet[PKG_MNFST_MEDIATYPE].Value <<= GetMediaType( );
+ pPropSet[PKG_MNFST_VERSION].Name = "Version";
+ pPropSet[PKG_MNFST_VERSION].Value <<= OUString(); // no version is stored for streams currently
+ pPropSet[PKG_MNFST_FULLPATH].Name = "FullPath";
+ pPropSet[PKG_MNFST_FULLPATH].Value <<= pTempEntry->sPath;
+
+ OSL_ENSURE( m_nStreamMode != PACKAGE_STREAM_NOTSET, "Unacceptable ZipPackageStream mode!" );
+
+ m_bRawStream = false;
+ if ( m_nStreamMode == PACKAGE_STREAM_DETECT )
+ m_bRawStream = ParsePackageRawStream();
+ else if ( m_nStreamMode == PACKAGE_STREAM_RAW )
+ m_bRawStream = true;
+
+ bool bBackgroundThreadDeflate = false;
+ bool bTransportOwnEncrStreamAsRaw = false;
+ // During the storing the original size of the stream can be changed
+ // TODO/LATER: get rid of this hack
+ m_nOwnStreamOrigSize = m_bRawStream ? m_nMagicalHackSize : aEntry.nSize;
+
+ bool bUseNonSeekableAccess = false;
+ uno::Reference < io::XInputStream > xStream;
+ if ( !IsPackageMember() && !m_bRawStream && !bToBeEncrypted && bToBeCompressed )
+ {
+ // the stream is not a package member, not a raw stream,
+ // it should not be encrypted and it should be compressed,
+ // in this case nonseekable access can be used
+
+ xStream = m_xStream;
+ uno::Reference < io::XSeekable > xSeek ( xStream, uno::UNO_QUERY );
+
+ bUseNonSeekableAccess = ( xStream.is() && !xSeek.is() );
+ }
+
+ if ( !bUseNonSeekableAccess )
+ {
+ xStream = getRawData();
+
+ if ( !xStream.is() )
+ {
+ OSL_FAIL( "ZipPackageStream didn't have a stream associated with it, skipping!" );
+ bSuccess = false;
+ return bSuccess;
+ }
+
+ uno::Reference < io::XSeekable > xSeek ( xStream, uno::UNO_QUERY );
+ try
+ {
+ if ( xSeek.is() )
+ {
+ // If the stream is a raw one, then we should be positioned
+ // at the beginning of the actual data
+ if ( !bToBeCompressed || m_bRawStream )
+ {
+ // The raw stream can neither be encrypted nor connected
+ OSL_ENSURE( !m_bRawStream || !(bToBeCompressed || bToBeEncrypted), "The stream is already encrypted!" );
+ xSeek->seek ( m_bRawStream ? m_nMagicalHackPos : 0 );
+ ImplSetStoredData ( *pTempEntry, xStream );
+
+ // TODO/LATER: Get rid of hacks related to switching of Flag Method and Size properties!
+ }
+ else if ( bToBeEncrypted )
+ {
+ // this is the correct original size
+ pTempEntry->nSize = xSeek->getLength();
+ m_nOwnStreamOrigSize = pTempEntry->nSize;
+ }
+
+ xSeek->seek ( 0 );
+ }
+ else
+ {
+ // Okay, we don't have an xSeekable stream. This is possibly bad.
+ // check if it's one of our own streams, if it is then we know that
+ // each time we ask for it we'll get a new stream that will be
+ // at position zero...otherwise, assert and skip this stream...
+ if ( IsPackageMember() )
+ {
+ // if the password has been changed then the stream should not be package member any more
+ if ( m_bIsEncrypted && m_bToBeEncrypted )
+ {
+ // Should be handled close to the raw stream handling
+ bTransportOwnEncrStreamAsRaw = true;
+ pTempEntry->nMethod = STORED;
+
+ // TODO/LATER: get rid of this situation
+ // this size should be different from the one that will be stored in manifest.xml
+ // it is used in storing algorithms and after storing the correct size will be set
+ pTempEntry->nSize = pTempEntry->nCompressedSize;
+ }
+ }
+ else
+ {
+ bSuccess = false;
+ return bSuccess;
+ }
+ }
+ }
+ catch ( uno::Exception& )
+ {
+ bSuccess = false;
+ return bSuccess;
+ }
+
+ if ( bToBeEncrypted || m_bRawStream || bTransportOwnEncrStreamAsRaw )
+ {
+ if ( bToBeEncrypted && !bTransportOwnEncrStreamAsRaw )
+ {
+ uno::Sequence < sal_Int8 > aSalt( 16 ), aVector( GetBlockSize() );
+ rtl_random_getBytes ( rRandomPool, aSalt.getArray(), 16 );
+ rtl_random_getBytes ( rRandomPool, aVector.getArray(), aVector.getLength() );
+ if ( !m_bHaveOwnKey )
+ {
+ m_aEncryptionKey = rEncryptionKey;
+ m_aStorageEncryptionKeys.realloc( 0 );
+ }
+
+ setInitialisationVector ( aVector );
+ setSalt ( aSalt );
+ setIterationCount(nPBKDF2IterationCount);
+ }
+
+ // last property is digest, which is inserted later if we didn't have
+ // a magic header
+ aPropSet.realloc(PKG_SIZE_ENCR_MNFST);
+ pPropSet = aPropSet.getArray();
+ pPropSet[PKG_MNFST_INIVECTOR].Name = "InitialisationVector";
+ pPropSet[PKG_MNFST_INIVECTOR].Value <<= m_xBaseEncryptionData->m_aInitVector;
+ pPropSet[PKG_MNFST_SALT].Name = "Salt";
+ pPropSet[PKG_MNFST_SALT].Value <<= m_xBaseEncryptionData->m_aSalt;
+ pPropSet[PKG_MNFST_ITERATION].Name = "IterationCount";
+ pPropSet[PKG_MNFST_ITERATION].Value <<= m_xBaseEncryptionData->m_nIterationCount;
+
+ // Need to store the uncompressed size in the manifest
+ OSL_ENSURE( m_nOwnStreamOrigSize >= 0, "The stream size was not correctly initialized!" );
+ pPropSet[PKG_MNFST_UCOMPSIZE].Name = "Size";
+ pPropSet[PKG_MNFST_UCOMPSIZE].Value <<= m_nOwnStreamOrigSize;
+
+ if ( m_bRawStream || bTransportOwnEncrStreamAsRaw )
+ {
+ ::rtl::Reference< EncryptionData > xEncData = GetEncryptionData();
+ if ( !xEncData.is() )
+ throw uno::RuntimeException();
+
+ pPropSet[PKG_MNFST_DIGEST].Name = sDigestProperty;
+ pPropSet[PKG_MNFST_DIGEST].Value <<= m_xBaseEncryptionData->m_aDigest;
+ pPropSet[PKG_MNFST_ENCALG].Name = sEncryptionAlgProperty;
+ pPropSet[PKG_MNFST_ENCALG].Value <<= xEncData->m_nEncAlg;
+ pPropSet[PKG_MNFST_STARTALG].Name = sStartKeyAlgProperty;
+ pPropSet[PKG_MNFST_STARTALG].Value <<= xEncData->m_nStartKeyGenID;
+ pPropSet[PKG_MNFST_DIGESTALG].Name = sDigestAlgProperty;
+ pPropSet[PKG_MNFST_DIGESTALG].Value <<= xEncData->m_nCheckAlg;
+ pPropSet[PKG_MNFST_DERKEYSIZE].Name = sDerivedKeySizeProperty;
+ pPropSet[PKG_MNFST_DERKEYSIZE].Value <<= xEncData->m_nDerivedKeySize;
+ }
+ }
+ }
+
+ // If the entry is already stored in the zip file in the format we
+ // want for this write...copy it raw
+ if ( !bUseNonSeekableAccess
+ && ( m_bRawStream || bTransportOwnEncrStreamAsRaw
+ || ( IsPackageMember() && !bToBeEncrypted
+ && ( ( aEntry.nMethod == DEFLATED && bToBeCompressed )
+ || ( aEntry.nMethod == STORED && !bToBeCompressed ) ) ) ) )
+ {
+ // If it's a PackageMember, then it's an unbuffered stream and we need
+ // to get a new version of it as we can't seek backwards.
+ if ( IsPackageMember() )
+ {
+ xStream = getRawData();
+ if ( !xStream.is() )
+ {
+ // Make sure that we actually _got_ a new one !
+ bSuccess = false;
+ return bSuccess;
+ }
+ }
+
+ try
+ {
+ if ( m_bRawStream )
+ xStream->skipBytes( m_nMagicalHackPos );
+
+ ZipOutputStream::setEntry(pTempEntry);
+ rZipOut.writeLOC(pTempEntry);
+ // the entry is provided to the ZipOutputStream that will delete it
+ pAutoTempEntry.release();
+
+ uno::Sequence < sal_Int8 > aSeq ( n_ConstBufferSize );
+ sal_Int32 nLength;
+
+ do
+ {
+ nLength = xStream->readBytes( aSeq, n_ConstBufferSize );
+ if (nLength != n_ConstBufferSize)
+ aSeq.realloc(nLength);
+
+ rZipOut.rawWrite(aSeq);
+ }
+ while ( nLength == n_ConstBufferSize );
+
+ rZipOut.rawCloseEntry();
+ }
+ catch ( ZipException& )
+ {
+ bSuccess = false;
+ }
+ catch ( io::IOException& )
+ {
+ bSuccess = false;
+ }
+ }
+ else
+ {
+ // This stream is definitely not a raw stream
+
+ // If nonseekable access is used the stream should be at the beginning and
+ // is useless after the storing. Thus if the storing fails the package should
+ // be thrown away ( as actually it is done currently )!
+ // To allow to reuse the package after the error, the optimization must be removed!
+
+ // If it's a PackageMember, then our previous reference held a 'raw' stream
+ // so we need to re-get it, unencrypted, uncompressed and positioned at the
+ // beginning of the stream
+ if ( IsPackageMember() )
+ {
+ xStream = getInputStream();
+ if ( !xStream.is() )
+ {
+ // Make sure that we actually _got_ a new one !
+ bSuccess = false;
+ return bSuccess;
+ }
+ }
+
+ if ( bToBeCompressed )
+ {
+ pTempEntry->nMethod = DEFLATED;
+ pTempEntry->nCrc = -1;
+ pTempEntry->nCompressedSize = pTempEntry->nSize = -1;
+ }
+
+ uno::Reference< io::XSeekable > xSeek(xStream, uno::UNO_QUERY);
+ // It's not worth to deflate jpegs to save ~1% in a slow process
+ // Unfortunately, does not work for streams protected by password
+ if (xSeek.is() && msMediaType.endsWith("/jpeg") && !m_bToBeEncrypted && !m_bToBeCompressed)
+ {
+ ImplSetStoredData(*pTempEntry, xStream);
+ xSeek->seek(0);
+ }
+
+ try
+ {
+ ZipOutputStream::setEntry(pTempEntry);
+ // the entry is provided to the ZipOutputStream that will delete it
+ pAutoTempEntry.release();
+
+ if (pTempEntry->nMethod == STORED)
+ {
+ sal_Int32 nLength;
+ uno::Sequence< sal_Int8 > aSeq(n_ConstBufferSize);
+ rZipOut.writeLOC(pTempEntry, bToBeEncrypted);
+ do
+ {
+ nLength = xStream->readBytes(aSeq, n_ConstBufferSize);
+ if (nLength != n_ConstBufferSize)
+ aSeq.realloc(nLength);
+
+ rZipOut.rawWrite(aSeq);
+ }
+ while ( nLength == n_ConstBufferSize );
+ rZipOut.rawCloseEntry(bToBeEncrypted);
+ }
+ else
+ {
+ // tdf#89236 Encrypting in a background thread does not work
+ bBackgroundThreadDeflate = !bToBeEncrypted;
+ // Do not deflate small streams using threads. XSeekable's getLength()
+ // gives the full size, XInputStream's available() may not be
+ // the full size, but it appears that at this point it usually is.
+ sal_Int64 estimatedSize = xSeek.is() ? xSeek->getLength() : xStream->available();
+
+ if (estimatedSize > 1000000)
+ {
+ // Use ThreadDeflater which will split the stream into blocks and compress
+ // them in threads, but not in background (i.e. writeStream() will block).
+ // This is suitable for large data.
+ bBackgroundThreadDeflate = false;
+ rZipOut.writeLOC(pTempEntry, bToBeEncrypted);
+ ZipOutputEntryParallel aZipEntry(rZipOut.getStream(), m_xContext, *pTempEntry, this, bToBeEncrypted);
+ aZipEntry.writeStream(xStream);
+ rZipOut.rawCloseEntry(bToBeEncrypted);
+ }
+ else if (bBackgroundThreadDeflate && estimatedSize > 100000)
+ {
+ // tdf#93553 limit to a useful amount of pending tasks. Having way too many
+ // tasks pending may use a lot of memory. Take number of available
+ // cores and allow 4-times the amount for having the queue well filled. The
+ // 2nd parameter is the time to wait between cleanups in 10th of a second.
+ // Both values may be added to the configuration settings if needed.
+ static std::size_t nAllowedTasks(comphelper::ThreadPool::getPreferredConcurrency() * 4); //TODO: overflow
+ rZipOut.reduceScheduledThreadTasksToGivenNumberOrLess(nAllowedTasks);
+
+ // Start a new thread task deflating this zip entry
+ ZipOutputEntryInThread *pZipEntry = new ZipOutputEntryInThread(
+ m_xContext, *pTempEntry, this, bToBeEncrypted);
+ rZipOut.addDeflatingThreadTask( pZipEntry,
+ pZipEntry->createTask( rZipOut.getThreadTaskTag(), xStream) );
+ }
+ else
+ {
+ bBackgroundThreadDeflate = false;
+ rZipOut.writeLOC(pTempEntry, bToBeEncrypted);
+ ZipOutputEntry aZipEntry(rZipOut.getStream(), m_xContext, *pTempEntry, this, bToBeEncrypted);
+ aZipEntry.writeStream(xStream);
+ rZipOut.rawCloseEntry(bToBeEncrypted);
+ }
+ }
+ }
+ catch ( ZipException& )
+ {
+ bSuccess = false;
+ }
+ catch ( io::IOException& )
+ {
+ bSuccess = false;
+ }
+
+ if ( bToBeEncrypted )
+ {
+ ::rtl::Reference< EncryptionData > xEncData = GetEncryptionData();
+ if ( !xEncData.is() )
+ throw uno::RuntimeException();
+
+ pPropSet[PKG_MNFST_DIGEST].Name = sDigestProperty;
+ pPropSet[PKG_MNFST_DIGEST].Value <<= m_xBaseEncryptionData->m_aDigest;
+ pPropSet[PKG_MNFST_ENCALG].Name = sEncryptionAlgProperty;
+ pPropSet[PKG_MNFST_ENCALG].Value <<= xEncData->m_nEncAlg;
+ pPropSet[PKG_MNFST_STARTALG].Name = sStartKeyAlgProperty;
+ pPropSet[PKG_MNFST_STARTALG].Value <<= xEncData->m_nStartKeyGenID;
+ pPropSet[PKG_MNFST_DIGESTALG].Name = sDigestAlgProperty;
+ pPropSet[PKG_MNFST_DIGESTALG].Value <<= xEncData->m_nCheckAlg;
+ pPropSet[PKG_MNFST_DERKEYSIZE].Name = sDerivedKeySizeProperty;
+ pPropSet[PKG_MNFST_DERKEYSIZE].Value <<= xEncData->m_nDerivedKeySize;
+
+ SetIsEncrypted ( true );
+ }
+ }
+
+ if (bSuccess && !bBackgroundThreadDeflate)
+ successfullyWritten(pTempEntry);
+
+ if ( aPropSet.hasElements()
+ && ( m_nFormat == embed::StorageFormats::PACKAGE || m_nFormat == embed::StorageFormats::OFOPXML ) )
+ rManList.push_back( aPropSet );
+
+ return bSuccess;
+}
+
+void ZipPackageStream::successfullyWritten( ZipEntry const *pEntry )
+{
+ if ( !IsPackageMember() )
+ {
+ if ( m_xStream.is() )
+ {
+ m_xStream->closeInput();
+ m_xStream.clear();
+ m_bHasSeekable = false;
+ }
+ SetPackageMember ( true );
+ }
+
+ if ( m_bRawStream )
+ {
+ // the raw stream was integrated and now behaves
+ // as usual encrypted stream
+ SetToBeEncrypted( true );
+ }
+
+ // Then copy it back afterwards...
+ aEntry = *pEntry;
+
+ // TODO/LATER: get rid of this hack ( the encrypted stream size property is changed during saving )
+ if ( m_bIsEncrypted )
+ setSize( m_nOwnStreamOrigSize );
+
+ aEntry.nOffset *= -1;
+}
+
+void ZipPackageStream::SetPackageMember( bool bNewValue )
+{
+ if ( bNewValue )
+ {
+ m_nStreamMode = PACKAGE_STREAM_PACKAGEMEMBER;
+ m_nMagicalHackPos = 0;
+ m_nMagicalHackSize = 0;
+ }
+ else if ( m_nStreamMode == PACKAGE_STREAM_PACKAGEMEMBER )
+ m_nStreamMode = PACKAGE_STREAM_NOTSET; // must be reset
+}
+
+// XActiveDataSink
+void SAL_CALL ZipPackageStream::setInputStream( const uno::Reference< io::XInputStream >& aStream )
+{
+ // if seekable access is required the wrapping will be done on demand
+ m_xStream = aStream;
+ m_nImportedEncryptionAlgorithm = 0;
+ m_bHasSeekable = false;
+ SetPackageMember ( false );
+ aEntry.nTime = -1;
+ m_nStreamMode = PACKAGE_STREAM_DETECT;
+}
+
+uno::Reference< io::XInputStream > ZipPackageStream::getRawData()
+{
+ try
+ {
+ if ( IsPackageMember() )
+ {
+ return m_rZipPackage.getZipFile().getRawData( aEntry, GetEncryptionData(), m_bIsEncrypted, m_rZipPackage.GetSharedMutexRef(), false/*bUseBufferedStream*/ );
+ }
+ else if ( GetOwnSeekStream().is() )
+ {
+ return new WrapStreamForShare( GetOwnSeekStream(), m_rZipPackage.GetSharedMutexRef() );
+ }
+ else
+ return uno::Reference < io::XInputStream > ();
+ }
+ catch ( ZipException & )//rException )
+ {
+ TOOLS_WARN_EXCEPTION( "package", "" );
+ return uno::Reference < io::XInputStream > ();
+ }
+ catch ( Exception & )
+ {
+ TOOLS_WARN_EXCEPTION( "package", "Exception is thrown during stream wrapping!" );
+ return uno::Reference < io::XInputStream > ();
+ }
+}
+
+uno::Reference< io::XInputStream > SAL_CALL ZipPackageStream::getInputStream()
+{
+ try
+ {
+ if ( IsPackageMember() )
+ {
+ return m_rZipPackage.getZipFile().getInputStream( aEntry, GetEncryptionData(), m_bIsEncrypted, m_rZipPackage.GetSharedMutexRef() );
+ }
+ else if ( GetOwnSeekStream().is() )
+ {
+ return new WrapStreamForShare( GetOwnSeekStream(), m_rZipPackage.GetSharedMutexRef() );
+ }
+ else
+ return uno::Reference < io::XInputStream > ();
+ }
+ catch ( ZipException & )//rException )
+ {
+ TOOLS_WARN_EXCEPTION( "package", "" );
+ return uno::Reference < io::XInputStream > ();
+ }
+ catch ( const Exception & )
+ {
+ TOOLS_WARN_EXCEPTION( "package", "Exception is thrown during stream wrapping!");
+ return uno::Reference < io::XInputStream > ();
+ }
+}
+
+// XDataSinkEncrSupport
+uno::Reference< io::XInputStream > SAL_CALL ZipPackageStream::getDataStream()
+{
+ // There is no stream attached to this object
+ if ( m_nStreamMode == PACKAGE_STREAM_NOTSET )
+ return uno::Reference< io::XInputStream >();
+
+ // this method can not be used together with old approach
+ if ( m_nStreamMode == PACKAGE_STREAM_DETECT )
+ throw packages::zip::ZipIOException(THROW_WHERE );
+
+ if ( IsPackageMember() )
+ {
+ uno::Reference< io::XInputStream > xResult;
+ try
+ {
+ xResult = m_rZipPackage.getZipFile().getDataStream( aEntry, GetEncryptionData(Bugs::None), m_bIsEncrypted, m_rZipPackage.GetSharedMutexRef() );
+ }
+ catch( const packages::WrongPasswordException& )
+ {
+ if ( m_rZipPackage.GetStartKeyGenID() == xml::crypto::DigestID::SHA1 )
+ {
+ SAL_WARN("package", "ZipPackageStream::getDataStream(): SHA1 mismatch, trying fallbacks...");
+ try
+ { // tdf#114939 try with legacy StarOffice SHA1 bug
+ xResult = m_rZipPackage.getZipFile().getDataStream( aEntry, GetEncryptionData(Bugs::WrongSHA1), m_bIsEncrypted, m_rZipPackage.GetSharedMutexRef() );
+ return xResult;
+ }
+ catch (const packages::WrongPasswordException&)
+ {
+ /* ignore and try next... */
+ }
+
+ try
+ {
+ // rhbz#1013844 / fdo#47482 workaround for the encrypted
+ // OpenOffice.org 1.0 documents generated by Libreoffice <=
+ // 3.6 with the new encryption format and using SHA256, but
+ // missing a specified startkey of SHA256
+
+ // force SHA256 and see if that works
+ m_nImportedStartKeyAlgorithm = xml::crypto::DigestID::SHA256;
+ xResult = m_rZipPackage.getZipFile().getDataStream( aEntry, GetEncryptionData(), m_bIsEncrypted, m_rZipPackage.GetSharedMutexRef() );
+ return xResult;
+ }
+ catch (const packages::WrongPasswordException&)
+ {
+ // if that didn't work, restore to SHA1 and trundle through the *other* earlier
+ // bug fix
+ m_nImportedStartKeyAlgorithm = xml::crypto::DigestID::SHA1;
+ }
+
+ // workaround for the encrypted documents generated with the old OOo1.x bug.
+ if ( !m_bUseWinEncoding )
+ {
+ xResult = m_rZipPackage.getZipFile().getDataStream( aEntry, GetEncryptionData(Bugs::WinEncodingWrongSHA1), m_bIsEncrypted, m_rZipPackage.GetSharedMutexRef() );
+ m_bUseWinEncoding = true;
+ }
+ else
+ throw;
+ }
+ else
+ throw;
+ }
+ return xResult;
+ }
+ else if ( m_nStreamMode == PACKAGE_STREAM_RAW )
+ return ZipFile::StaticGetDataFromRawStream( m_rZipPackage.GetSharedMutexRef(), m_xContext, GetOwnSeekStream(), GetEncryptionData() );
+ else if ( GetOwnSeekStream().is() )
+ {
+ return new WrapStreamForShare( GetOwnSeekStream(), m_rZipPackage.GetSharedMutexRef() );
+ }
+ else
+ return uno::Reference< io::XInputStream >();
+}
+
+uno::Reference< io::XInputStream > SAL_CALL ZipPackageStream::getRawStream()
+{
+ // There is no stream attached to this object
+ if ( m_nStreamMode == PACKAGE_STREAM_NOTSET )
+ return uno::Reference< io::XInputStream >();
+
+ // this method can not be used together with old approach
+ if ( m_nStreamMode == PACKAGE_STREAM_DETECT )
+ throw packages::zip::ZipIOException(THROW_WHERE );
+
+ if ( IsPackageMember() )
+ {
+ if ( !m_bIsEncrypted || !GetEncryptionData().is() )
+ throw packages::NoEncryptionException(THROW_WHERE );
+
+ return m_rZipPackage.getZipFile().getWrappedRawStream( aEntry, GetEncryptionData(), msMediaType, m_rZipPackage.GetSharedMutexRef() );
+ }
+ else if ( GetOwnSeekStream().is() )
+ {
+ if ( m_nStreamMode == PACKAGE_STREAM_RAW )
+ {
+ return new WrapStreamForShare( GetOwnSeekStream(), m_rZipPackage.GetSharedMutexRef() );
+ }
+ else if ( m_nStreamMode == PACKAGE_STREAM_DATA && m_bToBeEncrypted )
+ return TryToGetRawFromDataStream( true );
+ }
+
+ throw packages::NoEncryptionException(THROW_WHERE );
+}
+
+void SAL_CALL ZipPackageStream::setDataStream( const uno::Reference< io::XInputStream >& aStream )
+{
+ setInputStream( aStream );
+ m_nStreamMode = PACKAGE_STREAM_DATA;
+}
+
+void SAL_CALL ZipPackageStream::setRawStream( const uno::Reference< io::XInputStream >& aStream )
+{
+ // wrap the stream in case it is not seekable
+ uno::Reference< io::XInputStream > xNewStream = ::comphelper::OSeekableInputWrapper::CheckSeekableCanWrap( aStream, m_xContext );
+ uno::Reference< io::XSeekable > xSeek( xNewStream, UNO_QUERY_THROW );
+ xSeek->seek( 0 );
+ uno::Reference< io::XInputStream > xOldStream = m_xStream;
+ m_xStream = xNewStream;
+ if ( !ParsePackageRawStream() )
+ {
+ m_xStream = xOldStream;
+ throw packages::NoRawFormatException(THROW_WHERE );
+ }
+
+ // the raw stream MUST have seekable access
+ m_bHasSeekable = true;
+
+ SetPackageMember ( false );
+ aEntry.nTime = -1;
+ m_nStreamMode = PACKAGE_STREAM_RAW;
+}
+
+uno::Reference< io::XInputStream > SAL_CALL ZipPackageStream::getPlainRawStream()
+{
+ // There is no stream attached to this object
+ if ( m_nStreamMode == PACKAGE_STREAM_NOTSET )
+ return uno::Reference< io::XInputStream >();
+
+ // this method can not be used together with old approach
+ if ( m_nStreamMode == PACKAGE_STREAM_DETECT )
+ throw packages::zip::ZipIOException(THROW_WHERE );
+
+ if ( IsPackageMember() )
+ {
+ return m_rZipPackage.getZipFile().getRawData( aEntry, GetEncryptionData(), m_bIsEncrypted, m_rZipPackage.GetSharedMutexRef() );
+ }
+ else if ( GetOwnSeekStream().is() )
+ {
+ if ( m_nStreamMode == PACKAGE_STREAM_RAW )
+ {
+ // the header should not be returned here
+ return GetRawEncrStreamNoHeaderCopy();
+ }
+ else if ( m_nStreamMode == PACKAGE_STREAM_DATA )
+ return TryToGetRawFromDataStream( false );
+ }
+
+ return uno::Reference< io::XInputStream >();
+}
+
+// XUnoTunnel
+
+sal_Int64 SAL_CALL ZipPackageStream::getSomething( const Sequence< sal_Int8 >& aIdentifier )
+{
+ return comphelper::getSomethingImpl(aIdentifier, this);
+}
+
+// XPropertySet
+void SAL_CALL ZipPackageStream::setPropertyValue( const OUString& aPropertyName, const Any& aValue )
+{
+ if ( aPropertyName == "MediaType" )
+ {
+ if ( m_rZipPackage.getFormat() != embed::StorageFormats::PACKAGE && m_rZipPackage.getFormat() != embed::StorageFormats::OFOPXML )
+ throw beans::PropertyVetoException(THROW_WHERE );
+
+ if ( !(aValue >>= msMediaType) )
+ throw IllegalArgumentException(THROW_WHERE "MediaType must be a string!",
+ uno::Reference< XInterface >(),
+ 2 );
+
+ if ( !msMediaType.isEmpty() )
+ {
+ if ( msMediaType.indexOf ( "text" ) != -1
+ || msMediaType == "application/vnd.sun.star.oleobject" )
+ m_bToBeCompressed = true;
+ else if ( !m_bCompressedIsSetFromOutside )
+ m_bToBeCompressed = false;
+ }
+ }
+ else if ( aPropertyName == "Size" )
+ {
+ if ( !( aValue >>= aEntry.nSize ) )
+ throw IllegalArgumentException(THROW_WHERE "Wrong type for Size property!",
+ uno::Reference< XInterface >(),
+ 2 );
+ }
+ else if ( aPropertyName == "Encrypted" )
+ {
+ if ( m_rZipPackage.getFormat() != embed::StorageFormats::PACKAGE )
+ throw beans::PropertyVetoException(THROW_WHERE );
+
+ bool bEnc = false;
+ if ( !(aValue >>= bEnc) )
+ throw IllegalArgumentException(THROW_WHERE "Wrong type for Encrypted property!",
+ uno::Reference< XInterface >(),
+ 2 );
+
+ // In case of new raw stream, the stream must not be encrypted on storing
+ if ( bEnc && m_nStreamMode == PACKAGE_STREAM_RAW )
+ throw IllegalArgumentException(THROW_WHERE "Raw stream can not be encrypted on storing",
+ uno::Reference< XInterface >(),
+ 2 );
+
+ m_bToBeEncrypted = bEnc;
+ if ( m_bToBeEncrypted && !m_xBaseEncryptionData.is() )
+ m_xBaseEncryptionData = new BaseEncryptionData;
+
+ }
+ else if ( aPropertyName == ENCRYPTION_KEY_PROPERTY )
+ {
+ if ( m_rZipPackage.getFormat() != embed::StorageFormats::PACKAGE )
+ throw beans::PropertyVetoException(THROW_WHERE );
+
+ uno::Sequence< sal_Int8 > aNewKey;
+
+ if ( !( aValue >>= aNewKey ) )
+ {
+ OUString sTempString;
+ if ( !(aValue >>= sTempString) )
+ throw IllegalArgumentException(THROW_WHERE "Wrong type for EncryptionKey property!",
+ uno::Reference< XInterface >(),
+ 2 );
+
+ sal_Int32 nPathLength = sTempString.getLength();
+ Sequence < sal_Int8 > aSequence ( nPathLength );
+ sal_Int8 *pArray = aSequence.getArray();
+ const sal_Unicode *pChar = sTempString.getStr();
+ for ( sal_Int32 i = 0; i < nPathLength; i++ )
+ pArray[i] = static_cast < sal_Int8 > ( pChar[i] );
+ aNewKey = aSequence;
+ }
+
+ if ( aNewKey.hasElements() )
+ {
+ if ( !m_xBaseEncryptionData.is() )
+ m_xBaseEncryptionData = new BaseEncryptionData;
+
+ m_aEncryptionKey = aNewKey;
+ // In case of new raw stream, the stream must not be encrypted on storing
+ m_bHaveOwnKey = true;
+ if ( m_nStreamMode != PACKAGE_STREAM_RAW )
+ m_bToBeEncrypted = true;
+ }
+ else
+ {
+ m_bHaveOwnKey = false;
+ m_aEncryptionKey.realloc( 0 );
+ }
+
+ m_aStorageEncryptionKeys.realloc( 0 );
+ }
+ else if ( aPropertyName == STORAGE_ENCRYPTION_KEYS_PROPERTY )
+ {
+ if ( m_rZipPackage.getFormat() != embed::StorageFormats::PACKAGE )
+ throw beans::PropertyVetoException(THROW_WHERE );
+
+ uno::Sequence< beans::NamedValue > aKeys;
+ if ( !( aValue >>= aKeys ) )
+ {
+ throw IllegalArgumentException(THROW_WHERE "Wrong type for StorageEncryptionKeys property!",
+ uno::Reference< XInterface >(),
+ 2 );
+ }
+
+ if ( aKeys.hasElements() )
+ {
+ if ( !m_xBaseEncryptionData.is() )
+ m_xBaseEncryptionData = new BaseEncryptionData;
+
+ m_aStorageEncryptionKeys = aKeys;
+
+ // In case of new raw stream, the stream must not be encrypted on storing
+ m_bHaveOwnKey = true;
+ if ( m_nStreamMode != PACKAGE_STREAM_RAW )
+ m_bToBeEncrypted = true;
+ }
+ else
+ {
+ m_bHaveOwnKey = false;
+ m_aStorageEncryptionKeys.realloc( 0 );
+ }
+
+ m_aEncryptionKey.realloc( 0 );
+ }
+ else if ( aPropertyName == "Compressed" )
+ {
+ bool bCompr = false;
+
+ if ( !(aValue >>= bCompr) )
+ throw IllegalArgumentException(THROW_WHERE "Wrong type for Compressed property!",
+ uno::Reference< XInterface >(),
+ 2 );
+
+ // In case of new raw stream, the stream must not be encrypted on storing
+ if ( bCompr && m_nStreamMode == PACKAGE_STREAM_RAW )
+ throw IllegalArgumentException(THROW_WHERE "Raw stream can not be encrypted on storing",
+ uno::Reference< XInterface >(),
+ 2 );
+
+ m_bToBeCompressed = bCompr;
+ m_bCompressedIsSetFromOutside = true;
+ }
+ else
+ throw beans::UnknownPropertyException(aPropertyName);
+}
+
+Any SAL_CALL ZipPackageStream::getPropertyValue( const OUString& PropertyName )
+{
+ if ( PropertyName == "MediaType" )
+ {
+ return Any(msMediaType);
+ }
+ else if ( PropertyName == "Size" )
+ {
+ return Any(aEntry.nSize);
+ }
+ else if ( PropertyName == "Encrypted" )
+ {
+ return Any((m_nStreamMode == PACKAGE_STREAM_RAW) || m_bToBeEncrypted);
+ }
+ else if ( PropertyName == "WasEncrypted" )
+ {
+ return Any(m_bIsEncrypted);
+ }
+ else if ( PropertyName == "Compressed" )
+ {
+ return Any(m_bToBeCompressed);
+ }
+ else if ( PropertyName == ENCRYPTION_KEY_PROPERTY )
+ {
+ return Any(m_aEncryptionKey);
+ }
+ else if ( PropertyName == STORAGE_ENCRYPTION_KEYS_PROPERTY )
+ {
+ return Any(m_aStorageEncryptionKeys);
+ }
+ else
+ throw beans::UnknownPropertyException(PropertyName);
+}
+
+void ZipPackageStream::setSize ( const sal_Int64 nNewSize )
+{
+ if ( aEntry.nCompressedSize != nNewSize )
+ aEntry.nMethod = DEFLATED;
+ aEntry.nSize = nNewSize;
+}
+OUString ZipPackageStream::getImplementationName()
+{
+ return "ZipPackageStream";
+}
+
+Sequence< OUString > ZipPackageStream::getSupportedServiceNames()
+{
+ return { "com.sun.star.packages.PackageStream" };
+}
+
+sal_Bool SAL_CALL ZipPackageStream::supportsService( OUString const & rServiceName )
+{
+ return cppu::supportsService(this, rServiceName);
+}
+
+/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
diff --git a/package/source/zippackage/wrapstreamforshare.cxx b/package/source/zippackage/wrapstreamforshare.cxx
new file mode 100644
index 000000000..e5a475665
--- /dev/null
+++ b/package/source/zippackage/wrapstreamforshare.cxx
@@ -0,0 +1,151 @@
+/* -*- 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 <sal/config.h>
+#include <sal/log.hxx>
+
+#include <com/sun/star/io/IOException.hpp>
+#include <osl/diagnose.h>
+
+#include "wrapstreamforshare.hxx"
+
+using namespace ::com::sun::star;
+
+#if OSL_DEBUG_LEVEL > 0
+#define THROW_WHERE SAL_WHERE
+#else
+#define THROW_WHERE ""
+#endif
+
+WrapStreamForShare::WrapStreamForShare( const uno::Reference< io::XInputStream >& xInStream,
+ const rtl::Reference< comphelper::RefCountedMutex >& rMutexRef )
+: m_xMutex( rMutexRef )
+, m_xInStream( xInStream )
+, m_nCurPos( 0 )
+{
+ if ( !m_xMutex.is() || !m_xInStream.is() )
+ {
+ OSL_FAIL( "Wrong initialization of wrapping stream!" );
+ throw uno::RuntimeException(THROW_WHERE );
+ }
+ m_xSeekable.set( m_xInStream, uno::UNO_QUERY_THROW );
+}
+
+WrapStreamForShare::~WrapStreamForShare()
+{
+}
+
+// XInputStream
+sal_Int32 SAL_CALL WrapStreamForShare::readBytes( uno::Sequence< sal_Int8 >& aData, sal_Int32 nBytesToRead )
+{
+ if ( !m_xInStream.is() )
+ throw io::IOException(THROW_WHERE );
+
+ m_xSeekable->seek( m_nCurPos );
+
+ sal_Int32 nRead = m_xInStream->readBytes( aData, nBytesToRead );
+ m_nCurPos += nRead;
+
+ return nRead;
+}
+
+sal_Int32 SAL_CALL WrapStreamForShare::readSomeBytes( uno::Sequence< sal_Int8 >& aData, sal_Int32 nMaxBytesToRead )
+{
+ if ( !m_xInStream.is() )
+ throw io::IOException(THROW_WHERE );
+
+ m_xSeekable->seek( m_nCurPos );
+
+ sal_Int32 nRead = m_xInStream->readSomeBytes( aData, nMaxBytesToRead );
+ m_nCurPos += nRead;
+
+ return nRead;
+}
+
+void SAL_CALL WrapStreamForShare::skipBytes( sal_Int32 nBytesToSkip )
+{
+ ::osl::MutexGuard aGuard( m_xMutex->GetMutex() );
+
+ if ( !m_xInStream.is() )
+ throw io::IOException(THROW_WHERE );
+
+ m_xSeekable->seek( m_nCurPos );
+
+ m_xInStream->skipBytes( nBytesToSkip );
+ m_nCurPos = m_xSeekable->getPosition();
+}
+
+sal_Int32 SAL_CALL WrapStreamForShare::available()
+{
+ ::osl::MutexGuard aGuard( m_xMutex->GetMutex() );
+
+ if ( !m_xInStream.is() )
+ throw io::IOException(THROW_WHERE );
+
+ return m_xInStream->available();
+}
+
+void SAL_CALL WrapStreamForShare::closeInput()
+{
+ ::osl::MutexGuard aGuard( m_xMutex->GetMutex() );
+
+ if ( !m_xInStream.is() )
+ throw io::IOException(THROW_WHERE );
+
+ // the package is the owner so it will close the stream
+ // m_xInStream->closeInput();
+ m_xInStream.clear();
+ m_xSeekable.clear();
+}
+
+// XSeekable
+void SAL_CALL WrapStreamForShare::seek( sal_Int64 location )
+{
+ ::osl::MutexGuard aGuard( m_xMutex->GetMutex() );
+
+ if ( !m_xInStream.is() )
+ throw io::IOException(THROW_WHERE );
+
+ // let stream implementation do all the checking
+ m_xSeekable->seek( location );
+
+ m_nCurPos = m_xSeekable->getPosition();
+}
+
+sal_Int64 SAL_CALL WrapStreamForShare::getPosition()
+{
+ ::osl::MutexGuard aGuard( m_xMutex->GetMutex() );
+
+ if ( !m_xInStream.is() )
+ throw io::IOException(THROW_WHERE );
+
+ return m_nCurPos;
+}
+
+sal_Int64 SAL_CALL WrapStreamForShare::getLength()
+{
+ ::osl::MutexGuard aGuard( m_xMutex->GetMutex() );
+
+ if ( !m_xInStream.is() )
+ throw io::IOException(THROW_WHERE );
+
+ return m_xSeekable->getLength();
+}
+
+/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
diff --git a/package/source/zippackage/wrapstreamforshare.hxx b/package/source/zippackage/wrapstreamforshare.hxx
new file mode 100644
index 000000000..238483b76
--- /dev/null
+++ b/package/source/zippackage/wrapstreamforshare.hxx
@@ -0,0 +1,59 @@
+/* -*- 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 .
+ */
+
+#ifndef INCLUDED_PACKAGE_SOURCE_ZIPPACKAGE_WRAPSTREAMFORSHARE_HXX
+#define INCLUDED_PACKAGE_SOURCE_ZIPPACKAGE_WRAPSTREAMFORSHARE_HXX
+
+#include <com/sun/star/io/XInputStream.hpp>
+#include <com/sun/star/io/XSeekable.hpp>
+#include <comphelper/refcountedmutex.hxx>
+#include <cppuhelper/implbase.hxx>
+#include <rtl/ref.hxx>
+
+class WrapStreamForShare final : public cppu::WeakImplHelper < css::io::XInputStream
+ , css::io::XSeekable >
+{
+ rtl::Reference< comphelper::RefCountedMutex > m_xMutex;
+ css::uno::Reference < css::io::XInputStream > m_xInStream;
+ css::uno::Reference < css::io::XSeekable > m_xSeekable;
+
+ sal_Int64 m_nCurPos;
+
+public:
+ WrapStreamForShare( const css::uno::Reference< css::io::XInputStream >& xInStream,
+ const rtl::Reference< comphelper::RefCountedMutex >& rMutexRef );
+ virtual ~WrapStreamForShare() override;
+
+ // XInputStream
+ virtual sal_Int32 SAL_CALL readBytes( css::uno::Sequence< sal_Int8 >& aData, sal_Int32 nBytesToRead ) override;
+ virtual sal_Int32 SAL_CALL readSomeBytes( css::uno::Sequence< sal_Int8 >& aData, sal_Int32 nMaxBytesToRead ) override;
+ virtual void SAL_CALL skipBytes( sal_Int32 nBytesToSkip ) override;
+ virtual sal_Int32 SAL_CALL available( ) override;
+ virtual void SAL_CALL closeInput( ) override;
+
+ //XSeekable
+ virtual void SAL_CALL seek( sal_Int64 location ) override;
+ virtual sal_Int64 SAL_CALL getPosition() override;
+ virtual sal_Int64 SAL_CALL getLength() override;
+
+};
+
+#endif
+
+/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
diff --git a/package/source/zippackage/zipfileaccess.cxx b/package/source/zippackage/zipfileaccess.cxx
new file mode 100644
index 000000000..d9b17fd80
--- /dev/null
+++ b/package/source/zippackage/zipfileaccess.cxx
@@ -0,0 +1,479 @@
+/* -*- 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 <com/sun/star/lang/DisposedException.hpp>
+#include <com/sun/star/lang/IllegalArgumentException.hpp>
+#include <com/sun/star/ucb/XCommandEnvironment.hpp>
+#include <com/sun/star/io/NotConnectedException.hpp>
+#include <com/sun/star/io/XActiveDataSink.hpp>
+#include <com/sun/star/io/XStream.hpp>
+#include <com/sun/star/io/XSeekable.hpp>
+#include <com/sun/star/beans/NamedValue.hpp>
+#include <comphelper/processfactory.hxx>
+#include <cppuhelper/exc_hlp.hxx>
+#include <cppuhelper/supportsservice.hxx>
+#include <zipfileaccess.hxx>
+#include "ZipPackageSink.hxx"
+#include <EncryptionData.hxx>
+
+#include <ucbhelper/content.hxx>
+#include <rtl/ref.hxx>
+#include <sal/log.hxx>
+#include <osl/diagnose.h>
+
+using namespace ::com::sun::star;
+
+#if OSL_DEBUG_LEVEL > 0
+#define THROW_WHERE SAL_WHERE
+#else
+#define THROW_WHERE ""
+#endif
+
+OZipFileAccess::OZipFileAccess( const uno::Reference< uno::XComponentContext >& rxContext )
+: m_aMutexHolder( new comphelper::RefCountedMutex )
+, m_xContext( rxContext )
+, m_bDisposed( false )
+, m_bOwnContent( false )
+{
+ if ( !rxContext.is() )
+ throw uno::RuntimeException(THROW_WHERE );
+}
+
+OZipFileAccess::~OZipFileAccess()
+{
+ ::osl::MutexGuard aGuard( m_aMutexHolder->GetMutex() );
+ if ( !m_bDisposed )
+ {
+ try {
+ // dispose will use refcounting so the further destruction must be avoided
+ osl_atomic_increment(&m_refCount);
+ dispose();
+ } catch( uno::Exception& )
+ {}
+ }
+}
+
+uno::Sequence< OUString > OZipFileAccess::GetPatternsFromString_Impl( const OUString& aString )
+{
+ if ( aString.isEmpty() )
+ return uno::Sequence< OUString >();
+
+ uno::Sequence< OUString > aPattern( 1 );
+ auto pPattern = aPattern.getArray();
+ sal_Int32 nInd = 0;
+
+ const sal_Unicode* pString = aString.getStr();
+ while( *pString )
+ {
+ if ( *pString == '\\' )
+ {
+ pString++;
+
+ if ( *pString == '\\' )
+ {
+ pPattern[nInd] += "\\";
+ pString++;
+ }
+ else if ( *pString == '*' )
+ {
+ pPattern[nInd] += "*";
+ pString++;
+ }
+ else
+ {
+ OSL_FAIL( "The backslash is not guarded!" );
+ pPattern[nInd] += "\\";
+ }
+ }
+ else if ( *pString == '*' )
+ {
+ aPattern.realloc( ( ++nInd ) + 1 );
+ pPattern = aPattern.getArray();
+ pString++;
+ }
+ else
+ {
+ pPattern[nInd] += OUStringChar( *pString );
+ pString++;
+ }
+ }
+
+ return aPattern;
+}
+
+bool OZipFileAccess::StringGoodForPattern_Impl( const OUString& aString,
+ const uno::Sequence< OUString >& aPattern )
+{
+ sal_Int32 nInd = aPattern.getLength() - 1;
+ if ( nInd < 0 )
+ return false;
+
+ if ( nInd == 0 )
+ {
+ if ( aPattern[0].isEmpty() )
+ return true;
+
+ return aString == aPattern[0];
+ }
+
+ sal_Int32 nBeginInd = aPattern[0].getLength();
+ sal_Int32 nEndInd = aString.getLength() - aPattern[nInd].getLength();
+ if ( nEndInd < nBeginInd
+ || ( nEndInd != aString.getLength() && aString.subView( nEndInd ) != aPattern[nInd] )
+ || ( nBeginInd != 0 && aString.subView( 0, nBeginInd ) != aPattern[0] ) )
+ return false;
+
+ for ( sal_Int32 nCurInd = aPattern.getLength() - 2; nCurInd > 0; nCurInd-- )
+ {
+ if ( aPattern[nCurInd].isEmpty() )
+ continue;
+
+ if ( nEndInd == nBeginInd )
+ return false;
+
+ // check that search does not use nEndInd position
+ sal_Int32 nLastInd = aString.lastIndexOf( aPattern[nCurInd], nEndInd - 1 );
+
+ if ( nLastInd == -1 )
+ return false;
+
+ if ( nLastInd < nBeginInd )
+ return false;
+
+ nEndInd = nLastInd;
+ }
+
+ return true;
+}
+
+// XInitialization
+void SAL_CALL OZipFileAccess::initialize( const uno::Sequence< uno::Any >& aArguments )
+{
+ ::osl::MutexGuard aGuard( m_aMutexHolder->GetMutex() );
+
+ if ( m_bDisposed )
+ throw lang::DisposedException(THROW_WHERE );
+
+ if ( m_pZipFile )
+ throw uno::RuntimeException(THROW_WHERE ); // initialization is allowed only one time
+
+ if ( !aArguments.hasElements() )
+ throw lang::IllegalArgumentException(THROW_WHERE, uno::Reference< uno::XInterface >(), 1 );
+
+ OSL_ENSURE( aArguments.getLength() == 1, "Too many arguments are provided, only the first one will be used!" );
+
+ OUString aParamURL;
+ uno::Reference< io::XStream > xStream;
+ uno::Reference< io::XSeekable > xSeekable;
+ uno::Sequence<beans::NamedValue> aArgs;
+
+ auto openInputStream = [&]()
+ {
+ ::ucbhelper::Content aContent(
+ aParamURL,
+ uno::Reference< css::ucb::XCommandEnvironment >(),
+ m_xContext );
+ uno::Reference < io::XActiveDataSink > xSink = new ZipPackageSink;
+ if ( aContent.openStream ( xSink ) )
+ {
+ m_xContentStream = xSink->getInputStream();
+ m_bOwnContent = true;
+ xSeekable.set( m_xContentStream, uno::UNO_QUERY );
+ }
+ };
+
+ if ( aArguments[0] >>= aParamURL )
+ {
+ openInputStream();
+ }
+ else if ( aArguments[0] >>= xStream )
+ {
+ // a writable stream can implement both XStream & XInputStream
+ m_xContentStream = xStream->getInputStream();
+ xSeekable.set( xStream, uno::UNO_QUERY );
+ }
+ else if ( aArguments[0] >>= m_xContentStream )
+ {
+ xSeekable.set( m_xContentStream, uno::UNO_QUERY );
+ }
+ else if (aArguments[0] >>= aArgs)
+ {
+ for (const beans::NamedValue& rArg : std::as_const(aArgs))
+ {
+ if (rArg.Name == "URL")
+ rArg.Value >>= aParamURL;
+ }
+
+ if (aParamURL.isEmpty())
+ throw lang::IllegalArgumentException(
+ THROW_WHERE"required argument 'URL' is not given or invalid.",
+ uno::Reference<uno::XInterface>(), 1);
+
+ openInputStream();
+ }
+ else
+ throw lang::IllegalArgumentException(THROW_WHERE, uno::Reference< uno::XInterface >(), 1 );
+
+ if ( !m_xContentStream.is() )
+ throw io::IOException(THROW_WHERE );
+
+ if ( !xSeekable.is() )
+ {
+ // TODO: after fwkbugfix02 is integrated a helper class can be used to make the stream seekable
+ throw io::IOException(THROW_WHERE );
+ }
+
+ // TODO: in case xSeekable is implemented on separated XStream implementation a wrapper is required
+ m_pZipFile.emplace(
+ m_aMutexHolder,
+ m_xContentStream,
+ m_xContext,
+ true );
+}
+
+// XNameAccess
+uno::Any SAL_CALL OZipFileAccess::getByName( const OUString& aName )
+{
+ ::osl::MutexGuard aGuard( m_aMutexHolder->GetMutex() );
+
+ if ( m_bDisposed )
+ throw lang::DisposedException(THROW_WHERE );
+
+ if ( !m_pZipFile )
+ throw uno::RuntimeException(THROW_WHERE);
+
+ EntryHash::iterator aIter = m_pZipFile->GetEntryHash().find( aName );
+ if ( aIter == m_pZipFile->GetEntryHash().end() )
+ throw container::NoSuchElementException(THROW_WHERE );
+
+ uno::Reference< io::XInputStream > xEntryStream;
+ try
+ {
+ xEntryStream = m_pZipFile->getDataStream((*aIter).second,
+ ::rtl::Reference< EncryptionData >(),
+ false,
+ m_aMutexHolder);
+ }
+ catch (const container::NoSuchElementException&)
+ {
+ throw;
+ }
+ catch (const lang::WrappedTargetException&)
+ {
+ throw;
+ }
+ catch (const uno::RuntimeException&)
+ {
+ throw;
+ }
+ catch (const uno::Exception&)
+ {
+ css::uno::Any anyEx = cppu::getCaughtException();
+ throw lang::WrappedTargetException( "This package is unusable!",
+ static_cast < OWeakObject * > ( this ), anyEx);
+ }
+
+ if ( !xEntryStream.is() )
+ throw uno::RuntimeException(THROW_WHERE );
+
+ return uno::Any ( xEntryStream );
+}
+
+uno::Sequence< OUString > SAL_CALL OZipFileAccess::getElementNames()
+{
+ ::osl::MutexGuard aGuard( m_aMutexHolder->GetMutex() );
+
+ if ( m_bDisposed )
+ throw lang::DisposedException(THROW_WHERE );
+
+ if ( !m_pZipFile )
+ throw uno::RuntimeException(THROW_WHERE);
+
+ uno::Sequence< OUString > aNames( m_pZipFile->GetEntryHash().size() );
+ auto pNames = aNames.getArray();
+ sal_Int32 nLen = 0;
+
+ for ( const auto& rEntry : m_pZipFile->GetEntryHash() )
+ {
+ if ( aNames.getLength() < ++nLen )
+ {
+ OSL_FAIL( "The size must be the same!" );
+ aNames.realloc( nLen );
+ pNames = aNames.getArray();
+ }
+
+ pNames[nLen-1] = rEntry.second.sPath;
+ }
+
+ if ( aNames.getLength() != nLen )
+ {
+ OSL_FAIL( "The size must be the same!" );
+ aNames.realloc( nLen );
+ }
+
+ return aNames;
+}
+
+sal_Bool SAL_CALL OZipFileAccess::hasByName( const OUString& aName )
+{
+ ::osl::MutexGuard aGuard( m_aMutexHolder->GetMutex() );
+
+ if ( m_bDisposed )
+ throw lang::DisposedException(THROW_WHERE );
+
+ if ( !m_pZipFile )
+ throw uno::RuntimeException(THROW_WHERE);
+
+ EntryHash::iterator aIter = m_pZipFile->GetEntryHash().find( aName );
+
+ return ( aIter != m_pZipFile->GetEntryHash().end() );
+}
+
+uno::Type SAL_CALL OZipFileAccess::getElementType()
+{
+ ::osl::MutexGuard aGuard( m_aMutexHolder->GetMutex() );
+
+ if ( m_bDisposed )
+ throw lang::DisposedException(THROW_WHERE );
+
+ if ( !m_pZipFile )
+ throw uno::RuntimeException(THROW_WHERE);
+
+ return cppu::UnoType<io::XInputStream>::get();
+}
+
+sal_Bool SAL_CALL OZipFileAccess::hasElements()
+{
+ ::osl::MutexGuard aGuard( m_aMutexHolder->GetMutex() );
+
+ if ( m_bDisposed )
+ throw lang::DisposedException(THROW_WHERE );
+
+ if ( !m_pZipFile )
+ throw uno::RuntimeException(THROW_WHERE);
+
+ return ( !m_pZipFile->GetEntryHash().empty() );
+}
+
+// XZipFileAccess
+uno::Reference< io::XInputStream > SAL_CALL OZipFileAccess::getStreamByPattern( const OUString& aPatternString )
+{
+ ::osl::MutexGuard aGuard( m_aMutexHolder->GetMutex() );
+
+ if ( m_bDisposed )
+ throw lang::DisposedException(THROW_WHERE );
+
+ if ( !m_pZipFile )
+ throw io::NotConnectedException(THROW_WHERE );
+
+ // Code to compare strings by patterns
+ uno::Sequence< OUString > aPattern = GetPatternsFromString_Impl( aPatternString );
+
+ auto aIter = std::find_if(m_pZipFile->GetEntryHash().begin(), m_pZipFile->GetEntryHash().end(),
+ [&aPattern](const EntryHash::value_type& rEntry) { return StringGoodForPattern_Impl(rEntry.second.sPath, aPattern); });
+ if (aIter != m_pZipFile->GetEntryHash().end())
+ {
+ uno::Reference< io::XInputStream > xEntryStream( m_pZipFile->getDataStream( (*aIter).second,
+ ::rtl::Reference< EncryptionData >(),
+ false,
+ m_aMutexHolder ) );
+
+ if ( !xEntryStream.is() )
+ throw uno::RuntimeException(THROW_WHERE );
+ return xEntryStream;
+ }
+
+ throw container::NoSuchElementException(THROW_WHERE );
+}
+
+// XComponent
+void SAL_CALL OZipFileAccess::dispose()
+{
+ ::osl::MutexGuard aGuard( m_aMutexHolder->GetMutex() );
+
+ if ( m_bDisposed )
+ throw lang::DisposedException(THROW_WHERE );
+
+ if ( m_pListenersContainer )
+ {
+ lang::EventObject aSource( static_cast< ::cppu::OWeakObject* >(this) );
+ m_pListenersContainer->disposeAndClear( aSource );
+ m_pListenersContainer.reset();
+ }
+
+ m_pZipFile.reset();
+
+ if ( m_xContentStream.is() && m_bOwnContent )
+ try {
+ m_xContentStream->closeInput();
+ } catch( uno::Exception& )
+ {}
+
+ m_bDisposed = true;
+}
+
+void SAL_CALL OZipFileAccess::addEventListener( const uno::Reference< lang::XEventListener >& xListener )
+{
+ ::osl::MutexGuard aGuard( m_aMutexHolder->GetMutex() );
+
+ if ( m_bDisposed )
+ throw lang::DisposedException(THROW_WHERE );
+
+ if ( !m_pListenersContainer )
+ m_pListenersContainer.reset( new ::comphelper::OInterfaceContainerHelper3<css::lang::XEventListener>( m_aMutexHolder->GetMutex() ) );
+ m_pListenersContainer->addInterface( xListener );
+}
+
+void SAL_CALL OZipFileAccess::removeEventListener( const uno::Reference< lang::XEventListener >& xListener )
+{
+ ::osl::MutexGuard aGuard( m_aMutexHolder->GetMutex() );
+
+ if ( m_bDisposed )
+ throw lang::DisposedException(THROW_WHERE );
+
+ if ( m_pListenersContainer )
+ m_pListenersContainer->removeInterface( xListener );
+}
+
+OUString SAL_CALL OZipFileAccess::getImplementationName()
+{
+ return "com.sun.star.comp.package.zip.ZipFileAccess";
+}
+
+sal_Bool SAL_CALL OZipFileAccess::supportsService( const OUString& ServiceName )
+{
+ return cppu::supportsService(this, ServiceName);
+}
+
+uno::Sequence< OUString > SAL_CALL OZipFileAccess::getSupportedServiceNames()
+{
+ return { "com.sun.star.packages.zip.ZipFileAccess",
+ "com.sun.star.comp.packages.zip.ZipFileAccess" };
+}
+
+
+extern "C" SAL_DLLPUBLIC_EXPORT css::uno::XInterface*
+package_OZipFileAccess_get_implementation(
+ css::uno::XComponentContext* context , css::uno::Sequence<css::uno::Any> const&)
+{
+ return cppu::acquire(new OZipFileAccess(context));
+}
+
+
+/* vim:set shiftwidth=4 softtabstop=4 expandtab: */