Gtk-WARNING gtktreestore.c:1047: Invalid column number 1 added to iter
[LibreOffice.git] / package / source / zipapi / XUnbufferedStream.cxx
blob192958412d9390e1fb11c6e6800a27c1a658243d
1 /* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
2 /*
3 * This file is part of the LibreOffice project.
5 * This Source Code Form is subject to the terms of the Mozilla Public
6 * License, v. 2.0. If a copy of the MPL was not distributed with this
7 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
9 * This file incorporates work covered by the following license notice:
11 * Licensed to the Apache Software Foundation (ASF) under one or more
12 * contributor license agreements. See the NOTICE file distributed
13 * with this work for additional information regarding copyright
14 * ownership. The ASF licenses this file to you under the Apache
15 * License, Version 2.0 (the "License"); you may not use this file
16 * except in compliance with the License. You may obtain a copy of
17 * the License at http://www.apache.org/licenses/LICENSE-2.0 .
20 #include <com/sun/star/packages/zip/ZipConstants.hpp>
21 #include <com/sun/star/packages/zip/ZipIOException.hpp>
22 #include <com/sun/star/xml/crypto/CipherID.hpp>
24 #include "XUnbufferedStream.hxx"
25 #include <EncryptionData.hxx>
26 #include <ZipFile.hxx>
27 #include <EncryptedDataHeader.hxx>
28 #include <algorithm>
29 #include <string.h>
31 #include <o3tl/safeint.hxx>
32 #include <osl/diagnose.h>
33 #include <osl/mutex.hxx>
34 #include <utility>
35 #include <comphelper/diagnose_ex.hxx>
37 using namespace ::com::sun::star;
38 using namespace com::sun::star::packages::zip::ZipConstants;
39 using namespace com::sun::star::io;
40 using namespace com::sun::star::uno;
41 using com::sun::star::packages::zip::ZipIOException;
43 XUnbufferedStream::XUnbufferedStream(
44 const uno::Reference< uno::XComponentContext >& xContext,
45 rtl::Reference< comphelper::RefCountedMutex > aMutexHolder,
46 ZipEntry const & rEntry,
47 Reference < XInputStream > const & xNewZipStream,
48 const ::rtl::Reference< EncryptionData >& rData,
49 sal_Int8 nStreamMode,
50 ::std::optional<sal_Int64> const oDecryptedSize,
51 const OUString& aMediaType,
52 bool bRecoveryMode )
53 : maMutexHolder(std::move( aMutexHolder ))
54 , mxZipStream ( xNewZipStream )
55 , mxZipSeek ( xNewZipStream, UNO_QUERY )
56 , maEntry ( rEntry )
57 , mnBlockSize( 1 )
58 , maInflater ( true )
59 , mbRawStream ( nStreamMode == UNBUFF_STREAM_RAW || nStreamMode == UNBUFF_STREAM_WRAPPEDRAW )
60 , mbWrappedRaw ( nStreamMode == UNBUFF_STREAM_WRAPPEDRAW )
61 , mnHeaderToRead ( 0 )
62 , mnZipCurrent ( 0 )
63 , mnZipEnd ( 0 )
64 , mnZipSize ( 0 )
65 , mnMyCurrent ( 0 )
66 , mbCheckCRC(!bRecoveryMode)
68 mnZipCurrent = maEntry.nOffset;
69 sal_Int64 nSize; // data size in the zip file
70 assert(maEntry.nMethod != STORED || maEntry.nCompressedSize == maEntry.nSize);
71 if ( mbRawStream )
73 mnZipSize = maEntry.nCompressedSize;
74 nSize = mnZipSize;
76 else
78 mnZipSize = oDecryptedSize ? *oDecryptedSize : maEntry.nSize;
79 nSize = maEntry.nCompressedSize;
82 if (mnZipSize < 0)
83 throw ZipIOException(u"The stream seems to be broken!"_ustr);
85 if (o3tl::checked_add(maEntry.nOffset, nSize, mnZipEnd))
86 throw ZipIOException(u"Integer-overflow"_ustr);
88 bool bHaveEncryptData = rData.is() && rData->m_aInitVector.hasElements() &&
89 ((rData->m_aSalt.hasElements() && (rData->m_oPBKDFIterationCount || rData->m_oArgon2Args))
91 rData->m_aKey.hasElements());
92 bool bMustDecrypt = nStreamMode == UNBUFF_STREAM_DATA && bHaveEncryptData && oDecryptedSize;
94 if ( bMustDecrypt )
96 m_xCipherContext = ZipFile::StaticGetCipher( xContext, rData, false );
97 // this is only relevant when padding is used
98 mnBlockSize = ( rData->m_nEncAlg == xml::crypto::CipherID::AES_CBC_W3C_PADDING ? 16 : 1 );
101 if (!(bHaveEncryptData && mbWrappedRaw && oDecryptedSize))
102 return;
104 // if we have the data needed to decrypt it, but didn't want it decrypted (or
105 // we couldn't decrypt it due to wrong password), then we prepend this
106 // data to the stream
108 // Make a buffer big enough to hold both the header and the data itself
109 maHeader.realloc ( n_ConstHeaderSize +
110 rData->m_aInitVector.getLength() +
111 rData->m_aSalt.getLength() +
112 rData->m_aDigest.getLength() +
113 aMediaType.getLength() * sizeof( sal_Unicode ) );
114 sal_Int8 * pHeader = maHeader.getArray();
115 ZipFile::StaticFillHeader(rData, *oDecryptedSize, aMediaType, pHeader);
116 mnHeaderToRead = static_cast < sal_Int16 > ( maHeader.getLength() );
117 mnZipSize += mnHeaderToRead;
120 // allows to read package raw stream
121 XUnbufferedStream::XUnbufferedStream(
122 rtl::Reference< comphelper::RefCountedMutex > aMutexHolder,
123 const Reference < XInputStream >& xRawStream,
124 const ::rtl::Reference< EncryptionData >& rData )
125 : maMutexHolder(std::move( aMutexHolder ))
126 , mxZipStream ( xRawStream )
127 , mxZipSeek ( xRawStream, UNO_QUERY )
128 , mnBlockSize( 1 )
129 , maInflater ( true )
130 , mbRawStream ( false )
131 , mbWrappedRaw ( false )
132 , mnHeaderToRead ( 0 )
133 , mnZipCurrent ( 0 )
134 , mnZipEnd ( 0 )
135 , mnZipSize ( 0 )
136 , mnMyCurrent ( 0 )
137 , mbCheckCRC( false )
139 // for this scenario maEntry is not set !!!
140 OSL_ENSURE( mxZipSeek.is(), "The stream must be seekable!" );
142 // skip raw header, it must be already parsed to rData
143 mnZipCurrent = n_ConstHeaderSize + rData->m_aInitVector.getLength() +
144 rData->m_aSalt.getLength() + rData->m_aDigest.getLength();
146 try {
147 if ( mxZipSeek.is() )
148 mnZipSize = mxZipSeek->getLength();
149 } catch( const Exception& )
151 // in case of problem the size will stay set to 0
152 TOOLS_WARN_EXCEPTION("package", "ignoring");
155 mnZipEnd = mnZipCurrent + mnZipSize;
157 // the raw data will not be decrypted, no need for the cipher
158 // m_xCipherContext = ZipFile::StaticGetCipher( xContext, rData, false );
161 XUnbufferedStream::~XUnbufferedStream()
165 sal_Int32 SAL_CALL XUnbufferedStream::readBytes( Sequence< sal_Int8 >& aData, sal_Int32 nBytesToRead )
167 ::osl::MutexGuard aGuard( maMutexHolder->GetMutex() );
169 sal_Int32 nRequestedBytes = nBytesToRead;
170 OSL_ENSURE( !mnHeaderToRead || mbWrappedRaw, "Only encrypted raw stream can be provided with header!" );
171 if ( mnMyCurrent + nRequestedBytes > mnZipSize + maHeader.getLength() )
172 nRequestedBytes = static_cast < sal_Int32 > ( mnZipSize + maHeader.getLength() - mnMyCurrent );
174 sal_Int32 nTotal = 0;
175 aData.realloc ( nRequestedBytes );
176 if ( nRequestedBytes )
178 sal_Int32 nRead = 0;
179 sal_Int32 nLastRead = 0;
180 if ( mbRawStream )
182 sal_Int64 nDiff = mnZipEnd - mnZipCurrent;
184 if ( mbWrappedRaw && mnHeaderToRead )
186 sal_Int16 nHeadRead = static_cast< sal_Int16 >(( nRequestedBytes > mnHeaderToRead ?
187 mnHeaderToRead : nRequestedBytes ));
188 memcpy ( aData.getArray(), maHeader.getConstArray() + maHeader.getLength() - mnHeaderToRead, nHeadRead );
189 mnHeaderToRead = mnHeaderToRead - nHeadRead;
191 if ( nHeadRead < nRequestedBytes )
193 sal_Int32 nToRead = nRequestedBytes - nHeadRead;
194 nToRead = ( nDiff < nToRead ) ? sal::static_int_cast< sal_Int32 >( nDiff ) : nToRead;
196 Sequence< sal_Int8 > aPureData( nToRead );
197 mxZipSeek->seek ( mnZipCurrent );
198 nRead = mxZipStream->readBytes ( aPureData, nToRead );
199 mnZipCurrent += nRead;
201 aPureData.realloc( nRead );
202 if ( mbCheckCRC )
203 maCRC.update( aPureData );
205 aData.realloc( nHeadRead + nRead );
207 const sal_Int8* pPureBuffer = aPureData.getConstArray();
208 sal_Int8* pBuffer = aData.getArray();
209 for ( sal_Int32 nInd = 0; nInd < nRead; nInd++ )
210 pBuffer[ nHeadRead + nInd ] = pPureBuffer[ nInd ];
213 nRead += nHeadRead;
215 else
217 mxZipSeek->seek ( mnZipCurrent );
219 nRead = mxZipStream->readBytes (
220 aData,
221 std::min<sal_Int64>(nDiff, nRequestedBytes) );
223 mnZipCurrent += nRead;
225 aData.realloc( nRead );
226 if ( mbWrappedRaw && mbCheckCRC )
227 maCRC.update( aData );
230 else
232 for (;;)
234 nLastRead = maInflater.doInflateSegment( aData, nRead, aData.getLength() - nRead );
235 if ( 0 != nLastRead && ( nRead + nLastRead == nRequestedBytes || mnZipCurrent >= mnZipEnd ) )
236 break;
237 nRead += nLastRead;
238 if ( nRead > nRequestedBytes )
239 throw RuntimeException(
240 u"Should not be possible to read more than requested!"_ustr );
242 if ( maInflater.finished() || maInflater.getLastInflateError() )
243 throw ZipIOException(u"The stream seems to be broken!"_ustr );
245 if ( maInflater.needsDictionary() )
246 throw ZipIOException(u"Dictionaries are not supported!"_ustr );
248 sal_Int32 nDiff = static_cast< sal_Int32 >( mnZipEnd - mnZipCurrent );
249 if ( nDiff <= 0 )
251 throw ZipIOException(u"The stream seems to be broken!"_ustr );
254 mxZipSeek->seek ( mnZipCurrent );
256 sal_Int32 nToRead = std::max( nRequestedBytes, static_cast< sal_Int32 >( 8192 ) );
257 if ( mnBlockSize > 1 )
258 nToRead = nToRead + mnBlockSize - nToRead % mnBlockSize;
259 nToRead = std::min( nDiff, nToRead );
261 sal_Int32 nZipRead = mxZipStream->readBytes( maCompBuffer, nToRead );
262 if ( nZipRead < nToRead )
263 throw ZipIOException(u"No expected data!"_ustr );
265 mnZipCurrent += nZipRead;
266 // maCompBuffer now has the data, check if we need to decrypt
267 // before passing to the Inflater
268 if ( m_xCipherContext.is() )
270 if ( mbCheckCRC )
271 maCRC.update( maCompBuffer );
273 maCompBuffer = m_xCipherContext->convertWithCipherContext( maCompBuffer );
274 if ( mnZipCurrent == mnZipEnd )
276 // this should throw if AEAD is in use and the tag fails to validate
277 uno::Sequence< sal_Int8 > aSuffix = m_xCipherContext->finalizeCipherContextAndDispose();
278 if ( aSuffix.hasElements() )
280 sal_Int32 nOldLen = maCompBuffer.getLength();
281 maCompBuffer.realloc( nOldLen + aSuffix.getLength() );
282 memcpy( maCompBuffer.getArray() + nOldLen, aSuffix.getConstArray(), aSuffix.getLength() );
286 maInflater.setInput ( maCompBuffer );
291 mnMyCurrent += nRead + nLastRead;
292 nTotal = nRead + nLastRead;
293 if ( nTotal < nRequestedBytes)
294 aData.realloc ( nTotal );
296 if ( mbCheckCRC && ( !mbRawStream || mbWrappedRaw ) )
298 if ( !m_xCipherContext.is() && !mbWrappedRaw )
299 maCRC.update( aData );
301 if ( mnZipSize + maHeader.getLength() == mnMyCurrent && maCRC.getValue() != maEntry.nCrc )
302 throw ZipIOException(u"The stream seems to be broken!"_ustr );
306 return nTotal;
309 sal_Int32 SAL_CALL XUnbufferedStream::readSomeBytes( Sequence< sal_Int8 >& aData, sal_Int32 nMaxBytesToRead )
311 return readBytes ( aData, nMaxBytesToRead );
313 void SAL_CALL XUnbufferedStream::skipBytes( sal_Int32 nBytesToSkip )
315 if ( nBytesToSkip )
317 Sequence < sal_Int8 > aSequence ( nBytesToSkip );
318 readBytes ( aSequence, nBytesToSkip );
322 sal_Int32 SAL_CALL XUnbufferedStream::available( )
324 //available size must include the prepended header in case of wrapped raw stream
325 return static_cast< sal_Int32 > ( std::min< sal_Int64 >( SAL_MAX_INT32, (mnZipSize + mnHeaderToRead - mnMyCurrent) ) );
328 void SAL_CALL XUnbufferedStream::closeInput( )
332 /* vim:set shiftwidth=4 softtabstop=4 expandtab: */