xref: /trunk/main/package/source/package/zipapi/ZipFile.cxx (revision 57cd559d060c509755c8b0f6cac469b512911542)
1 /**************************************************************
2  *
3  * Licensed to the Apache Software Foundation (ASF) under one
4  * or more contributor license agreements.  See the NOTICE file
5  * distributed with this work for additional information
6  * regarding copyright ownership.  The ASF licenses this file
7  * to you under the Apache License, Version 2.0 (the
8  * "License"); you may not use this file except in compliance
9  * with the License.  You may obtain a copy of the License at
10  *
11  *   http://www.apache.org/licenses/LICENSE-2.0
12  *
13  * Unless required by applicable law or agreed to in writing,
14  * software distributed under the License is distributed on an
15  * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
16  * KIND, either express or implied.  See the License for the
17  * specific language governing permissions and limitations
18  * under the License.
19  *
20  *************************************************************/
21 
22 
23 
24 // MARKER(update_precomp.py): autogen include statement, do not remove
25 #include "precompiled_package.hxx"
26 
27 #include <com/sun/star/lang/XMultiServiceFactory.hpp>
28 #include <com/sun/star/ucb/XProgressHandler.hpp>
29 #include <com/sun/star/packages/zip/ZipConstants.hpp>
30 #include <com/sun/star/xml/crypto/XCipherContext.hpp>
31 #include <com/sun/star/xml/crypto/XDigestContext.hpp>
32 #include <com/sun/star/xml/crypto/XCipherContextSupplier.hpp>
33 #include <com/sun/star/xml/crypto/XDigestContextSupplier.hpp>
34 #include <com/sun/star/xml/crypto/CipherID.hpp>
35 #include <com/sun/star/xml/crypto/DigestID.hpp>
36 
37 #include <comphelper/storagehelper.hxx>
38 #include <comphelper/processfactory.hxx>
39 #include <rtl/digest.h>
40 
41 #include <vector>
42 
43 #include "blowfishcontext.hxx"
44 #include "sha1context.hxx"
45 #include <ZipFile.hxx>
46 #include <ZipEnumeration.hxx>
47 #include <XUnbufferedStream.hxx>
48 #include <PackageConstants.hxx>
49 #include <EncryptedDataHeader.hxx>
50 #include <EncryptionData.hxx>
51 #include <MemoryByteGrabber.hxx>
52 
53 #include <CRC32.hxx>
54 
55 #define AES_CBC_BLOCK_SIZE 16
56 
57 using namespace vos;
58 using namespace rtl;
59 using namespace com::sun::star;
60 using namespace com::sun::star::io;
61 using namespace com::sun::star::uno;
62 using namespace com::sun::star::ucb;
63 using namespace com::sun::star::lang;
64 using namespace com::sun::star::packages;
65 using namespace com::sun::star::packages::zip;
66 using namespace com::sun::star::packages::zip::ZipConstants;
67 
68 
69 /** This class is used to read entries from a zip file
70  */
ZipFile(uno::Reference<XInputStream> & xInput,const uno::Reference<XMultiServiceFactory> & xNewFactory,sal_Bool bInitialise)71 ZipFile::ZipFile( uno::Reference < XInputStream > &xInput, const uno::Reference < XMultiServiceFactory > &xNewFactory, sal_Bool bInitialise )
72 : aGrabber(xInput)
73 , aInflater (sal_True)
74 , xStream(xInput)
75 , xSeek(xInput, UNO_QUERY)
76 , m_xFactory ( xNewFactory )
77 , bRecoveryMode( sal_False )
78 {
79     if (bInitialise)
80     {
81         if ( readCEN() == -1 )
82         {
83             aEntries.clear();
84             throw ZipException( OUString( RTL_CONSTASCII_USTRINGPARAM ( "stream data looks to be broken" ) ), uno::Reference < XInterface > () );
85         }
86     }
87 }
88 
89 
90 
ZipFile(uno::Reference<XInputStream> & xInput,const uno::Reference<XMultiServiceFactory> & xNewFactory,sal_Bool bInitialise,sal_Bool bForceRecovery,uno::Reference<XProgressHandler> xProgress)91 ZipFile::ZipFile( uno::Reference < XInputStream > &xInput, const uno::Reference < XMultiServiceFactory > &xNewFactory, sal_Bool bInitialise, sal_Bool bForceRecovery, uno::Reference < XProgressHandler > xProgress )
92 : aGrabber(xInput)
93 , aInflater (sal_True)
94 , xStream(xInput)
95 , xSeek(xInput, UNO_QUERY)
96 , m_xFactory ( xNewFactory )
97 , xProgressHandler( xProgress )
98 , bRecoveryMode( bForceRecovery )
99 {
100     if (bInitialise)
101     {
102         if ( bForceRecovery )
103         {
104             recover();
105         }
106         else if ( readCEN() == -1 )
107         {
108             aEntries.clear();
109             throw ZipException( OUString( RTL_CONSTASCII_USTRINGPARAM ( "stream data looks to be broken" ) ), uno::Reference < XInterface > () );
110         }
111     }
112 }
113 
~ZipFile()114 ZipFile::~ZipFile()
115 {
116     aEntries.clear();
117 }
118 
setInputStream(uno::Reference<XInputStream> xNewStream)119 void ZipFile::setInputStream ( uno::Reference < XInputStream > xNewStream )
120 {
121     ::osl::MutexGuard aGuard( m_aMutex );
122 
123     xStream = xNewStream;
124     xSeek = uno::Reference < XSeekable > ( xStream, UNO_QUERY );
125     aGrabber.setInputStream ( xStream );
126 }
127 
StaticGetDigestContextForChecksum(const uno::Reference<lang::XMultiServiceFactory> & xArgFactory,const::rtl::Reference<EncryptionData> & xEncryptionData)128 uno::Reference< xml::crypto::XDigestContext > ZipFile::StaticGetDigestContextForChecksum( const uno::Reference< lang::XMultiServiceFactory >& xArgFactory, const ::rtl::Reference< EncryptionData >& xEncryptionData )
129 {
130     uno::Reference< xml::crypto::XDigestContext > xDigestContext;
131     if ( xEncryptionData->m_nCheckAlg == xml::crypto::DigestID::SHA256_1K )
132     {
133         uno::Reference< lang::XMultiServiceFactory > xFactory = xArgFactory;
134         if ( !xFactory.is() )
135             xFactory.set( comphelper::getProcessServiceFactory(), uno::UNO_SET_THROW );
136 
137         uno::Reference< xml::crypto::XDigestContextSupplier > xDigestContextSupplier(
138             xFactory->createInstance( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.xml.crypto.NSSInitializer" ) ) ),
139             uno::UNO_QUERY_THROW );
140 
141         xDigestContext.set( xDigestContextSupplier->getDigestContext( xEncryptionData->m_nCheckAlg, uno::Sequence< beans::NamedValue >() ), uno::UNO_SET_THROW );
142     }
143     else if ( xEncryptionData->m_nCheckAlg == xml::crypto::DigestID::SHA1_1K )
144         xDigestContext.set( SHA1DigestContext::Create(), uno::UNO_SET_THROW );
145 
146     return xDigestContext;
147 }
148 
StaticGetCipher(const uno::Reference<lang::XMultiServiceFactory> & xArgFactory,const::rtl::Reference<EncryptionData> & xEncryptionData,bool bEncrypt)149 uno::Reference< xml::crypto::XCipherContext > ZipFile::StaticGetCipher( const uno::Reference< lang::XMultiServiceFactory >& xArgFactory, const ::rtl::Reference< EncryptionData >& xEncryptionData, bool bEncrypt )
150 {
151     uno::Reference< xml::crypto::XCipherContext > xResult;
152 
153     try
154     {
155         uno::Sequence< sal_Int8 > aDerivedKey( xEncryptionData->m_nDerivedKeySize );
156         if ( rtl_Digest_E_None != rtl_digest_PBKDF2( reinterpret_cast< sal_uInt8* >( aDerivedKey.getArray() ),
157                             aDerivedKey.getLength(),
158                             reinterpret_cast< const sal_uInt8 * > (xEncryptionData->m_aKey.getConstArray() ),
159                             xEncryptionData->m_aKey.getLength(),
160                             reinterpret_cast< const sal_uInt8 * > ( xEncryptionData->m_aSalt.getConstArray() ),
161                             xEncryptionData->m_aSalt.getLength(),
162                             xEncryptionData->m_nIterationCount ) )
163         {
164             throw ZipIOException( ::rtl::OUString::createFromAscii( "Can not create derived key!\n" ),
165                                   uno::Reference< XInterface >() );
166         }
167 
168         if ( xEncryptionData->m_nEncAlg == xml::crypto::CipherID::AES_CBC_W3C_PADDING )
169         {
170             uno::Reference< lang::XMultiServiceFactory > xFactory = xArgFactory;
171             if ( !xFactory.is() )
172                 xFactory.set( comphelper::getProcessServiceFactory(), uno::UNO_SET_THROW );
173 
174             uno::Reference< xml::crypto::XCipherContextSupplier > xCipherContextSupplier(
175                 xFactory->createInstance( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.xml.crypto.NSSInitializer" ) ) ),
176                 uno::UNO_QUERY_THROW );
177 
178             xResult = xCipherContextSupplier->getCipherContext( xEncryptionData->m_nEncAlg, aDerivedKey, xEncryptionData->m_aInitVector, bEncrypt, uno::Sequence< beans::NamedValue >() );
179         }
180         else if ( xEncryptionData->m_nEncAlg == xml::crypto::CipherID::BLOWFISH_CFB_8 )
181         {
182             xResult = BlowfishCFB8CipherContext::Create( aDerivedKey, xEncryptionData->m_aInitVector, bEncrypt );
183         }
184         else
185         {
186             throw ZipIOException( ::rtl::OUString::createFromAscii( "Unknown cipher algorithm is requested!\n" ),
187                                   uno::Reference< XInterface >() );
188         }
189     }
190     catch( uno::Exception& )
191     {
192         OSL_ENSURE( sal_False, "Can not create cipher context!" );
193     }
194 
195     return xResult;
196 }
197 
StaticFillHeader(const::rtl::Reference<EncryptionData> & rData,sal_Int32 nSize,const::rtl::OUString & aMediaType,sal_Int8 * & pHeader)198 void ZipFile::StaticFillHeader( const ::rtl::Reference< EncryptionData >& rData,
199                                 sal_Int32 nSize,
200                                 const ::rtl::OUString& aMediaType,
201                                 sal_Int8 * & pHeader )
202 {
203     // I think it's safe to restrict vector and salt length to 2 bytes !
204     sal_Int16 nIVLength = static_cast < sal_Int16 > ( rData->m_aInitVector.getLength() );
205     sal_Int16 nSaltLength = static_cast < sal_Int16 > ( rData->m_aSalt.getLength() );
206     sal_Int16 nDigestLength = static_cast < sal_Int16 > ( rData->m_aDigest.getLength() );
207     sal_Int16 nMediaTypeLength = static_cast < sal_Int16 > ( aMediaType.getLength() * sizeof( sal_Unicode ) );
208 
209     // First the header
210     *(pHeader++) = ( n_ConstHeader >> 0 ) & 0xFF;
211     *(pHeader++) = ( n_ConstHeader >> 8 ) & 0xFF;
212     *(pHeader++) = ( n_ConstHeader >> 16 ) & 0xFF;
213     *(pHeader++) = ( n_ConstHeader >> 24 ) & 0xFF;
214 
215     // Then the version
216     *(pHeader++) = ( n_ConstCurrentVersion >> 0 ) & 0xFF;
217     *(pHeader++) = ( n_ConstCurrentVersion >> 8 ) & 0xFF;
218 
219     // Then the iteration Count
220     sal_Int32 nIterationCount = rData->m_nIterationCount;
221     *(pHeader++) = static_cast< sal_Int8 >(( nIterationCount >> 0 ) & 0xFF);
222     *(pHeader++) = static_cast< sal_Int8 >(( nIterationCount >> 8 ) & 0xFF);
223     *(pHeader++) = static_cast< sal_Int8 >(( nIterationCount >> 16 ) & 0xFF);
224     *(pHeader++) = static_cast< sal_Int8 >(( nIterationCount >> 24 ) & 0xFF);
225 
226     // Then the size
227     *(pHeader++) = static_cast< sal_Int8 >(( nSize >> 0 ) & 0xFF);
228     *(pHeader++) = static_cast< sal_Int8 >(( nSize >> 8 ) & 0xFF);
229     *(pHeader++) = static_cast< sal_Int8 >(( nSize >> 16 ) & 0xFF);
230     *(pHeader++) = static_cast< sal_Int8 >(( nSize >> 24 ) & 0xFF);
231 
232     // Then the encryption algorithm
233     sal_Int32 nEncAlgID = rData->m_nEncAlg;
234     *(pHeader++) = static_cast< sal_Int8 >(( nEncAlgID >> 0 ) & 0xFF);
235     *(pHeader++) = static_cast< sal_Int8 >(( nEncAlgID >> 8 ) & 0xFF);
236     *(pHeader++) = static_cast< sal_Int8 >(( nEncAlgID >> 16 ) & 0xFF);
237     *(pHeader++) = static_cast< sal_Int8 >(( nEncAlgID >> 24 ) & 0xFF);
238 
239     // Then the checksum algorithm
240     sal_Int32 nChecksumAlgID = rData->m_nCheckAlg;
241     *(pHeader++) = static_cast< sal_Int8 >(( nChecksumAlgID >> 0 ) & 0xFF);
242     *(pHeader++) = static_cast< sal_Int8 >(( nChecksumAlgID >> 8 ) & 0xFF);
243     *(pHeader++) = static_cast< sal_Int8 >(( nChecksumAlgID >> 16 ) & 0xFF);
244     *(pHeader++) = static_cast< sal_Int8 >(( nChecksumAlgID >> 24 ) & 0xFF);
245 
246     // Then the derived key size
247     sal_Int32 nDerivedKeySize = rData->m_nDerivedKeySize;
248     *(pHeader++) = static_cast< sal_Int8 >(( nDerivedKeySize >> 0 ) & 0xFF);
249     *(pHeader++) = static_cast< sal_Int8 >(( nDerivedKeySize >> 8 ) & 0xFF);
250     *(pHeader++) = static_cast< sal_Int8 >(( nDerivedKeySize >> 16 ) & 0xFF);
251     *(pHeader++) = static_cast< sal_Int8 >(( nDerivedKeySize >> 24 ) & 0xFF);
252 
253     // Then the start key generation algorithm
254     sal_Int32 nKeyAlgID = rData->m_nStartKeyGenID;
255     *(pHeader++) = static_cast< sal_Int8 >(( nKeyAlgID >> 0 ) & 0xFF);
256     *(pHeader++) = static_cast< sal_Int8 >(( nKeyAlgID >> 8 ) & 0xFF);
257     *(pHeader++) = static_cast< sal_Int8 >(( nKeyAlgID >> 16 ) & 0xFF);
258     *(pHeader++) = static_cast< sal_Int8 >(( nKeyAlgID >> 24 ) & 0xFF);
259 
260     // Then the salt length
261     *(pHeader++) = static_cast< sal_Int8 >(( nSaltLength >> 0 ) & 0xFF);
262     *(pHeader++) = static_cast< sal_Int8 >(( nSaltLength >> 8 ) & 0xFF);
263 
264     // Then the IV length
265     *(pHeader++) = static_cast< sal_Int8 >(( nIVLength >> 0 ) & 0xFF);
266     *(pHeader++) = static_cast< sal_Int8 >(( nIVLength >> 8 ) & 0xFF);
267 
268     // Then the digest length
269     *(pHeader++) = static_cast< sal_Int8 >(( nDigestLength >> 0 ) & 0xFF);
270     *(pHeader++) = static_cast< sal_Int8 >(( nDigestLength >> 8 ) & 0xFF);
271 
272     // Then the mediatype length
273     *(pHeader++) = static_cast< sal_Int8 >(( nMediaTypeLength >> 0 ) & 0xFF);
274     *(pHeader++) = static_cast< sal_Int8 >(( nMediaTypeLength >> 8 ) & 0xFF);
275 
276     // Then the salt content
277     rtl_copyMemory ( pHeader, rData->m_aSalt.getConstArray(), nSaltLength );
278     pHeader += nSaltLength;
279 
280     // Then the IV content
281     rtl_copyMemory ( pHeader, rData->m_aInitVector.getConstArray(), nIVLength );
282     pHeader += nIVLength;
283 
284     // Then the digest content
285     rtl_copyMemory ( pHeader, rData->m_aDigest.getConstArray(), nDigestLength );
286     pHeader += nDigestLength;
287 
288     // Then the mediatype itself
289     rtl_copyMemory ( pHeader, aMediaType.getStr(), nMediaTypeLength );
290     pHeader += nMediaTypeLength;
291 }
292 
StaticFillData(::rtl::Reference<BaseEncryptionData> & rData,sal_Int32 & rEncAlg,sal_Int32 & rChecksumAlg,sal_Int32 & rDerivedKeySize,sal_Int32 & rStartKeyGenID,sal_Int32 & rSize,::rtl::OUString & aMediaType,const uno::Reference<XInputStream> & rStream)293 sal_Bool ZipFile::StaticFillData (  ::rtl::Reference< BaseEncryptionData > & rData,
294                                     sal_Int32 &rEncAlg,
295                                     sal_Int32 &rChecksumAlg,
296                                     sal_Int32 &rDerivedKeySize,
297                                     sal_Int32 &rStartKeyGenID,
298                                     sal_Int32 &rSize,
299                                     ::rtl::OUString& aMediaType,
300                                     const uno::Reference< XInputStream >& rStream )
301 {
302     sal_Bool bOk = sal_False;
303     const sal_Int32 nHeaderSize = n_ConstHeaderSize - 4;
304     Sequence < sal_Int8 > aBuffer ( nHeaderSize );
305     if ( nHeaderSize == rStream->readBytes ( aBuffer, nHeaderSize ) )
306     {
307         sal_Int16 nPos = 0;
308         sal_Int8 *pBuffer = aBuffer.getArray();
309         sal_Int16 nVersion = pBuffer[nPos++] & 0xFF;
310         nVersion |= ( pBuffer[nPos++] & 0xFF ) << 8;
311         if ( nVersion == n_ConstCurrentVersion )
312         {
313             sal_Int32 nCount = pBuffer[nPos++] & 0xFF;
314             nCount |= ( pBuffer[nPos++] & 0xFF ) << 8;
315             nCount |= ( pBuffer[nPos++] & 0xFF ) << 16;
316             nCount |= ( pBuffer[nPos++] & 0xFF ) << 24;
317             rData->m_nIterationCount = nCount;
318 
319             rSize  =   pBuffer[nPos++] & 0xFF;
320             rSize |= ( pBuffer[nPos++] & 0xFF ) << 8;
321             rSize |= ( pBuffer[nPos++] & 0xFF ) << 16;
322             rSize |= ( pBuffer[nPos++] & 0xFF ) << 24;
323 
324             rEncAlg   =   pBuffer[nPos++] & 0xFF;
325             rEncAlg  |= ( pBuffer[nPos++] & 0xFF ) << 8;
326             rEncAlg  |= ( pBuffer[nPos++] & 0xFF ) << 16;
327             rEncAlg  |= ( pBuffer[nPos++] & 0xFF ) << 24;
328 
329             rChecksumAlg   =   pBuffer[nPos++] & 0xFF;
330             rChecksumAlg  |= ( pBuffer[nPos++] & 0xFF ) << 8;
331             rChecksumAlg  |= ( pBuffer[nPos++] & 0xFF ) << 16;
332             rChecksumAlg  |= ( pBuffer[nPos++] & 0xFF ) << 24;
333 
334             rDerivedKeySize   =   pBuffer[nPos++] & 0xFF;
335             rDerivedKeySize  |= ( pBuffer[nPos++] & 0xFF ) << 8;
336             rDerivedKeySize  |= ( pBuffer[nPos++] & 0xFF ) << 16;
337             rDerivedKeySize  |= ( pBuffer[nPos++] & 0xFF ) << 24;
338 
339             rStartKeyGenID   =   pBuffer[nPos++] & 0xFF;
340             rStartKeyGenID  |= ( pBuffer[nPos++] & 0xFF ) << 8;
341             rStartKeyGenID  |= ( pBuffer[nPos++] & 0xFF ) << 16;
342             rStartKeyGenID  |= ( pBuffer[nPos++] & 0xFF ) << 24;
343 
344             sal_Int16 nSaltLength =   pBuffer[nPos++] & 0xFF;
345             nSaltLength          |= ( pBuffer[nPos++] & 0xFF ) << 8;
346             sal_Int16 nIVLength   = ( pBuffer[nPos++] & 0xFF );
347             nIVLength            |= ( pBuffer[nPos++] & 0xFF ) << 8;
348             sal_Int16 nDigestLength = pBuffer[nPos++] & 0xFF;
349             nDigestLength        |= ( pBuffer[nPos++] & 0xFF ) << 8;
350 
351             sal_Int16 nMediaTypeLength = pBuffer[nPos++] & 0xFF;
352             nMediaTypeLength |= ( pBuffer[nPos++] & 0xFF ) << 8;
353 
354             if ( nSaltLength == rStream->readBytes ( aBuffer, nSaltLength ) )
355             {
356                 rData->m_aSalt.realloc ( nSaltLength );
357                 rtl_copyMemory ( rData->m_aSalt.getArray(), aBuffer.getConstArray(), nSaltLength );
358                 if ( nIVLength == rStream->readBytes ( aBuffer, nIVLength ) )
359                 {
360                     rData->m_aInitVector.realloc ( nIVLength );
361                     rtl_copyMemory ( rData->m_aInitVector.getArray(), aBuffer.getConstArray(), nIVLength );
362                     if ( nDigestLength == rStream->readBytes ( aBuffer, nDigestLength ) )
363                     {
364                         rData->m_aDigest.realloc ( nDigestLength );
365                         rtl_copyMemory ( rData->m_aDigest.getArray(), aBuffer.getConstArray(), nDigestLength );
366 
367                         if ( nMediaTypeLength == rStream->readBytes ( aBuffer, nMediaTypeLength ) )
368                         {
369                             aMediaType = ::rtl::OUString( (sal_Unicode*)aBuffer.getConstArray(),
370                                                             nMediaTypeLength / sizeof( sal_Unicode ) );
371                             bOk = sal_True;
372                         }
373                     }
374                 }
375             }
376         }
377     }
378     return bOk;
379 }
380 
StaticGetDataFromRawStream(const uno::Reference<lang::XMultiServiceFactory> & xFactory,const uno::Reference<XInputStream> & xStream,const::rtl::Reference<EncryptionData> & rData)381 uno::Reference< XInputStream > ZipFile::StaticGetDataFromRawStream( const uno::Reference< lang::XMultiServiceFactory >& xFactory,
382                                                                 const uno::Reference< XInputStream >& xStream,
383                                                                 const ::rtl::Reference< EncryptionData > &rData )
384 {
385     if ( !rData.is() )
386         throw ZipIOException( OUString::createFromAscii( "Encrypted stream without encryption data!\n" ),
387                             uno::Reference< XInterface >() );
388 
389     if ( !rData->m_aKey.getLength() )
390         throw packages::WrongPasswordException( ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( OSL_LOG_PREFIX ) ), uno::Reference< uno::XInterface >() );
391 
392     uno::Reference< XSeekable > xSeek( xStream, UNO_QUERY );
393     if ( !xSeek.is() )
394         throw ZipIOException( OUString::createFromAscii( "The stream must be seekable!\n" ),
395                             uno::Reference< XInterface >() );
396 
397 
398     // if we have a digest, then this file is an encrypted one and we should
399     // check if we can decrypt it or not
400     OSL_ENSURE( rData->m_aDigest.getLength(), "Can't detect password correctness without digest!\n" );
401     if ( rData->m_aDigest.getLength() )
402     {
403         sal_Int32 nSize = sal::static_int_cast< sal_Int32 >( xSeek->getLength() );
404         if ( nSize > n_ConstDigestLength + 32 )
405             nSize = n_ConstDigestLength + 32;
406 
407         // skip header
408         xSeek->seek( n_ConstHeaderSize + rData->m_aInitVector.getLength() +
409                                 rData->m_aSalt.getLength() + rData->m_aDigest.getLength() );
410 
411         // Only want to read enough to verify the digest
412         Sequence < sal_Int8 > aReadBuffer ( nSize );
413 
414         xStream->readBytes( aReadBuffer, nSize );
415 
416         if ( !StaticHasValidPassword( xFactory, aReadBuffer, rData ) )
417             throw packages::WrongPasswordException( ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( OSL_LOG_PREFIX ) ), uno::Reference< uno::XInterface >() );
418     }
419 
420     return new XUnbufferedStream( xFactory, xStream, rData );
421 }
422 
423 #if 0
424 // for debugging purposes
425 void CheckSequence( const uno::Sequence< sal_Int8 >& aSequence )
426 {
427     if ( aSequence.getLength() )
428     {
429         sal_Int32* pPointer = *( (sal_Int32**)&aSequence );
430         sal_Int32 nSize = *( pPointer + 1 );
431         sal_Int32 nMemSize = *( pPointer - 2 );
432         sal_Int32 nUsedMemSize = ( nSize + 4 * sizeof( sal_Int32 ) );
433         OSL_ENSURE( nSize == aSequence.getLength() && nUsedMemSize + 7 - ( nUsedMemSize - 1 ) % 8 == nMemSize, "Broken Sequence!" );
434     }
435 }
436 #endif
437 
StaticHasValidPassword(const uno::Reference<lang::XMultiServiceFactory> & xFactory,const Sequence<sal_Int8> & aReadBuffer,const::rtl::Reference<EncryptionData> & rData)438 sal_Bool ZipFile::StaticHasValidPassword( const uno::Reference< lang::XMultiServiceFactory >& xFactory, const Sequence< sal_Int8 > &aReadBuffer, const ::rtl::Reference< EncryptionData > &rData )
439 {
440     if ( !rData.is() || !rData->m_aKey.getLength() )
441         return sal_False;
442 
443     sal_Bool bRet = sal_False;
444 
445     uno::Reference< xml::crypto::XCipherContext > xCipher( StaticGetCipher( xFactory, rData, false ), uno::UNO_SET_THROW );
446 
447     uno::Sequence< sal_Int8 > aDecryptBuffer;
448     uno::Sequence< sal_Int8 > aDecryptBuffer2;
449     try
450     {
451         aDecryptBuffer = xCipher->convertWithCipherContext( aReadBuffer );
452         aDecryptBuffer2 = xCipher->finalizeCipherContextAndDispose();
453     }
454     catch( uno::Exception& )
455     {
456         // decryption with padding will throw the exception in finalizing if the buffer represent only part of the stream
457         // it is no problem, actually this is why we read 32 additional bytes ( two of maximal possible encryption blocks )
458     }
459 
460     if ( aDecryptBuffer2.getLength() )
461     {
462         sal_Int32 nOldLen = aDecryptBuffer.getLength();
463         aDecryptBuffer.realloc( nOldLen + aDecryptBuffer2.getLength() );
464         rtl_copyMemory( aDecryptBuffer.getArray() + nOldLen, aDecryptBuffer2.getArray(), aDecryptBuffer2.getLength() );
465     }
466 
467     if ( aDecryptBuffer.getLength() > n_ConstDigestLength )
468         aDecryptBuffer.realloc( n_ConstDigestLength );
469 
470     uno::Sequence< sal_Int8 > aDigestSeq;
471     uno::Reference< xml::crypto::XDigestContext > xDigestContext( StaticGetDigestContextForChecksum( xFactory, rData ), uno::UNO_SET_THROW );
472 
473     xDigestContext->updateDigest( aDecryptBuffer );
474     aDigestSeq = xDigestContext->finalizeDigestAndDispose();
475 
476     // If we don't have a digest, then we have to assume that the password is correct
477     if (  rData->m_aDigest.getLength() != 0  &&
478           ( aDigestSeq.getLength() != rData->m_aDigest.getLength() ||
479             0 != rtl_compareMemory ( aDigestSeq.getConstArray(),
480                                     rData->m_aDigest.getConstArray(),
481                                     aDigestSeq.getLength() ) ) )
482     {
483         // We should probably tell the user that the password they entered was wrong
484     }
485     else
486         bRet = sal_True;
487 
488     return bRet;
489 }
490 
hasValidPassword(ZipEntry & rEntry,const::rtl::Reference<EncryptionData> & rData)491 sal_Bool ZipFile::hasValidPassword ( ZipEntry & rEntry, const ::rtl::Reference< EncryptionData >& rData )
492 {
493     ::osl::MutexGuard aGuard( m_aMutex );
494 
495     sal_Bool bRet = sal_False;
496     if ( rData.is() && rData->m_aKey.getLength() )
497     {
498         xSeek->seek( rEntry.nFileDataOffset );
499         sal_Int32 nSize = rEntry.nMethod == DEFLATED ? rEntry.nCompressedSize : rEntry.nSize;
500 
501         // Only want to read enough to verify the digest
502         if ( nSize > n_ConstDigestDecrypt )
503             nSize = n_ConstDigestDecrypt;
504 
505         Sequence < sal_Int8 > aReadBuffer ( nSize );
506 
507         xStream->readBytes( aReadBuffer, nSize );
508 
509         bRet = StaticHasValidPassword( m_xFactory, aReadBuffer, rData );
510     }
511 
512     return bRet;
513 }
514 
createUnbufferedStream(SotMutexHolderRef aMutexHolder,ZipEntry & rEntry,const::rtl::Reference<EncryptionData> & rData,sal_Int8 nStreamMode,sal_Bool bIsEncrypted,::rtl::OUString aMediaType)515 uno::Reference< XInputStream > ZipFile::createUnbufferedStream(
516             SotMutexHolderRef aMutexHolder,
517             ZipEntry & rEntry,
518             const ::rtl::Reference< EncryptionData > &rData,
519             sal_Int8 nStreamMode,
520             sal_Bool bIsEncrypted,
521             ::rtl::OUString aMediaType )
522 {
523 
524     // Only encrypted entries can be STORED and have a data descriptor
525     if ( !bIsEncrypted && ( rEntry.nMethod == STORED ) && rEntry.bHasDataDescriptor )
526         throw ZipException( OUString( RTL_CONSTASCII_USTRINGPARAM ( "entry has spurious file descriptor" ) ), uno::Reference < XInterface > () );
527     ::osl::MutexGuard aGuard( m_aMutex );
528 
529     return new XUnbufferedStream ( m_xFactory, aMutexHolder, rEntry, xStream, rData, nStreamMode, bIsEncrypted, aMediaType, bRecoveryMode );
530 }
531 
532 
entries()533 ZipEnumeration * SAL_CALL ZipFile::entries(  )
534 {
535     return new ZipEnumeration ( aEntries );
536 }
537 
getInputStream(ZipEntry & rEntry,const::rtl::Reference<EncryptionData> & rData,sal_Bool bIsEncrypted,SotMutexHolderRef aMutexHolder)538 uno::Reference< XInputStream > SAL_CALL ZipFile::getInputStream( ZipEntry& rEntry,
539         const ::rtl::Reference< EncryptionData > &rData,
540         sal_Bool bIsEncrypted,
541         SotMutexHolderRef aMutexHolder )
542 {
543     ::osl::MutexGuard aGuard( m_aMutex );
544 
545     if ( rEntry.nFileDataOffset <= 0 )
546         readLOC( rEntry );
547 
548     // We want to return a rawStream if we either don't have a key or if the
549     // key is wrong
550 
551     sal_Bool bNeedRawStream = rEntry.nMethod == STORED;
552 
553     // if we have a digest, then this file is an encrypted one and we should
554     // check if we can decrypt it or not
555     if ( bIsEncrypted && rData.is() && rData->m_aDigest.getLength() )
556         bNeedRawStream = !hasValidPassword ( rEntry, rData );
557 
558     return createUnbufferedStream ( aMutexHolder,
559                                     rEntry,
560                                     rData,
561                                     bNeedRawStream ? UNBUFF_STREAM_RAW : UNBUFF_STREAM_DATA,
562                                     bIsEncrypted );
563 }
564 
getDataStream(ZipEntry & rEntry,const::rtl::Reference<EncryptionData> & rData,sal_Bool bIsEncrypted,SotMutexHolderRef aMutexHolder)565 uno::Reference< XInputStream > SAL_CALL ZipFile::getDataStream( ZipEntry& rEntry,
566         const ::rtl::Reference< EncryptionData > &rData,
567         sal_Bool bIsEncrypted,
568         SotMutexHolderRef aMutexHolder )
569 {
570     ::osl::MutexGuard aGuard( m_aMutex );
571 
572     if ( rEntry.nFileDataOffset <= 0 )
573         readLOC( rEntry );
574 
575     // An exception must be thrown in case stream is encrypted and
576     // there is no key or the key is wrong
577     sal_Bool bNeedRawStream = sal_False;
578     if ( bIsEncrypted )
579     {
580         // in case no digest is provided there is no way
581         // to detect password correctness
582         if ( !rData.is() )
583             throw ZipException( OUString::createFromAscii( "Encrypted stream without encryption data!\n" ),
584                                 uno::Reference< XInterface >() );
585 
586         // if we have a digest, then this file is an encrypted one and we should
587         // check if we can decrypt it or not
588         OSL_ENSURE( rData->m_aDigest.getLength(), "Can't detect password correctness without digest!\n" );
589         if ( rData->m_aDigest.getLength() && !hasValidPassword ( rEntry, rData ) )
590                 throw packages::WrongPasswordException( ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( OSL_LOG_PREFIX ) ), uno::Reference< uno::XInterface >() );
591     }
592     else
593         bNeedRawStream = ( rEntry.nMethod == STORED );
594 
595     return createUnbufferedStream ( aMutexHolder,
596                                     rEntry,
597                                     rData,
598                                     bNeedRawStream ? UNBUFF_STREAM_RAW : UNBUFF_STREAM_DATA,
599                                     bIsEncrypted );
600 }
601 
getRawData(ZipEntry & rEntry,const::rtl::Reference<EncryptionData> & rData,sal_Bool bIsEncrypted,SotMutexHolderRef aMutexHolder)602 uno::Reference< XInputStream > SAL_CALL ZipFile::getRawData( ZipEntry& rEntry,
603         const ::rtl::Reference< EncryptionData >& rData,
604         sal_Bool bIsEncrypted,
605         SotMutexHolderRef aMutexHolder )
606 {
607     ::osl::MutexGuard aGuard( m_aMutex );
608 
609     if ( rEntry.nFileDataOffset <= 0 )
610         readLOC( rEntry );
611 
612     return createUnbufferedStream ( aMutexHolder, rEntry, rData, UNBUFF_STREAM_RAW, bIsEncrypted );
613 }
614 
getWrappedRawStream(ZipEntry & rEntry,const::rtl::Reference<EncryptionData> & rData,const::rtl::OUString & aMediaType,SotMutexHolderRef aMutexHolder)615 uno::Reference< XInputStream > SAL_CALL ZipFile::getWrappedRawStream(
616         ZipEntry& rEntry,
617         const ::rtl::Reference< EncryptionData >& rData,
618         const ::rtl::OUString& aMediaType,
619         SotMutexHolderRef aMutexHolder )
620 {
621     ::osl::MutexGuard aGuard( m_aMutex );
622 
623     if ( !rData.is() )
624         throw packages::NoEncryptionException( ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( OSL_LOG_PREFIX ) ), uno::Reference< uno::XInterface >() );
625 
626     if ( rEntry.nFileDataOffset <= 0 )
627         readLOC( rEntry );
628 
629     return createUnbufferedStream ( aMutexHolder, rEntry, rData, UNBUFF_STREAM_WRAPPEDRAW, sal_True, aMediaType );
630 }
631 
632 /** Read extra fields
633  *
634  * @param rGrabber Grabber object for reading data.
635  * @param nLength extra field length
636  * @param rEntry entry data.
637  *
638  * Expects rGrabber to point to the beginning of the extra fields.
639  * Advances it until all fields are read (i.e. after nLength bytes).
640  *
641  * @throw ZipException in case of problems.
642  */
readExtraFields(MemoryByteGrabber & rMemGrabber,sal_Int16 nLength,ZipEntry & rEntry)643 static void readExtraFields( MemoryByteGrabber &rMemGrabber, sal_Int16 nLength, ZipEntry &rEntry )
644 {
645     sal_Int16 nHeaderID, nDataSize;
646     sal_Int16 nReadBytes = 0;
647     sal_Int8 n8;
648     rtl::OUString s;
649     while ( ( nLength - nReadBytes ) >= 4 ) {
650         rMemGrabber >> nHeaderID;
651         rMemGrabber >> nDataSize;
652         nReadBytes += 4;
653         if (( nDataSize > ( nLength - nReadBytes ) ) ||
654             ( nDataSize > rMemGrabber.available() ) )
655             throw ZipException( OUString( RTL_CONSTASCII_USTRINGPARAM ( "Invalid ZIP extra fields" ) ), uno::Reference < XInterface > () );
656         switch ( nHeaderID ) {
657         case 0x7075: // Info-ZIP Unicode Path Extra Field
658             if ( nDataSize < 5 )
659                 throw ZipException( OUString( RTL_CONSTASCII_USTRINGPARAM ( "Invalid size for ZIP unicode path extra field" ) ), uno::Reference < XInterface > () );
660             rMemGrabber >> n8; // Version
661             rMemGrabber.skipBytes( 4 ); // skip NameCRC32
662             s = rtl::OUString::intern ( (sal_Char *) rMemGrabber.getCurrentPos(),
663                                         nDataSize - 5,
664                                         RTL_TEXTENCODING_UTF8 );
665             if ( n8 != 1 )
666                 throw ZipException( OUString( RTL_CONSTASCII_USTRINGPARAM ( "Invalid ZIP unicode path extra field version" ) ), uno::Reference < XInterface > () );
667             if ( s != rEntry.sPath )
668                 throw ZipException( OUString( RTL_CONSTASCII_USTRINGPARAM ( "Invalid ZIP unicode path extra field" ) ), uno::Reference < XInterface > () );
669             rMemGrabber.skipBytes( nDataSize - 5 );
670             break;
671         default:  // We are not interested in this field
672             rMemGrabber.skipBytes( nDataSize );
673         }
674         nReadBytes += nDataSize;
675     }
676 }
677 
readLOC(ZipEntry & rEntry)678 sal_Bool ZipFile::readLOC( ZipEntry &rEntry )
679 {
680     ::osl::MutexGuard aGuard( m_aMutex );
681 
682     sal_Int32 nTestSig, nTime, nCRC, nSize, nCompressedSize;
683     sal_Int16 nVersion, nFlag, nHow, nPathLen;
684     sal_Int32 nPos = rEntry.nFileHeaderOffset;
685 
686     aGrabber.seek(nPos);
687     aGrabber >> nTestSig;
688 
689     if (nTestSig != LOCSIG)
690         throw ZipIOException( OUString( RTL_CONSTASCII_USTRINGPARAM ( "Invalid LOC header (bad signature") ), uno::Reference < XInterface > () );
691     aGrabber >> nVersion;
692     aGrabber >> nFlag;
693     aGrabber >> nHow;
694     aGrabber >> nTime;
695     aGrabber >> nCRC;
696     aGrabber >> nCompressedSize;
697     aGrabber >> nSize;
698     aGrabber >> nPathLen;
699     aGrabber >> rEntry.nLOCExtraLen;
700     rEntry.nFileDataOffset = static_cast < sal_Int32 > (aGrabber.getPosition()) + nPathLen + rEntry.nLOCExtraLen;
701 
702     // read always in UTF8, some tools seem not to set UTF8 bit
703     uno::Sequence < sal_Int8 > aNameBuffer( nPathLen );
704     sal_Int32 nRead = aGrabber.readBytes( aNameBuffer, nPathLen );
705     if ( nRead < aNameBuffer.getLength() )
706             aNameBuffer.realloc( nRead );
707 
708     ::rtl::OUString sLOCPath = rtl::OUString::intern( (sal_Char *) aNameBuffer.getArray(),
709                                                         aNameBuffer.getLength(),
710                                                         RTL_TEXTENCODING_UTF8 );
711 
712     if ( rEntry.nPathLen == -1 ) // the file was created
713     {
714         rEntry.nPathLen = nPathLen;
715         rEntry.sPath = sLOCPath;
716     }
717 
718     // the method can be reset for internal use so it is not checked
719     sal_Bool bBroken = rEntry.nVersion != nVersion
720                     || rEntry.nFlag != nFlag
721                     || rEntry.nMethod != nHow
722                     || rEntry.nTime != nTime
723                     || rEntry.nPathLen != nPathLen
724                     || !rEntry.sPath.equals( sLOCPath );
725 
726     if ( bBroken && !bRecoveryMode )
727         throw ZipIOException( OUString( RTL_CONSTASCII_USTRINGPARAM( "The stream seems to be broken!" ) ),
728                             uno::Reference< XInterface >() );
729 
730     Sequence < sal_Int8 > aExtraFields ( rEntry.nLOCExtraLen );
731     nRead = aGrabber.readBytes( aExtraFields, rEntry.nLOCExtraLen );
732     if ( nRead != rEntry.nLOCExtraLen )
733         throw ZipException ( OUString ( RTL_CONSTASCII_USTRINGPARAM ( "Error reading LOC extra fields into memory buffer!") ), uno::Reference < XInterface > () );
734     MemoryByteGrabber aMemGrabber ( aExtraFields );
735     readExtraFields( aMemGrabber, rEntry.nLOCExtraLen, rEntry );
736 
737     // Check for a data descriptor
738     rEntry.bHasDataDescriptor = rEntry.nFlag & ( 1 << 3 );
739     if ( rEntry.bHasDataDescriptor ) {
740         // some fields of the local file header must be zero
741         if ( ( nCRC | nCompressedSize | nSize ) != 0 )
742             throw ZipException ( OUString ( RTL_CONSTASCII_USTRINGPARAM ( "Data descriptor mismatch!") ), uno::Reference < XInterface > () );
743     }
744     sal_Int32 n32;
745     aGrabber.seek( rEntry.nFileDataOffset + rEntry.nCompressedSize );
746     aGrabber >> n32;
747     if ( n32 == EXTSIG ) { // Signature detected
748         rEntry.bHasDataDescriptor = sal_True;
749         aGrabber >> n32;
750     }
751     if ( rEntry.bHasDataDescriptor ) {
752         if ( n32 != rEntry.nCrc )
753             throw ZipException ( OUString ( RTL_CONSTASCII_USTRINGPARAM ( "Data descriptor CRC mismatch!") ), uno::Reference < XInterface > () );
754         aGrabber >> n32;
755         if ( n32 != rEntry.nCompressedSize )
756             throw ZipException ( OUString ( RTL_CONSTASCII_USTRINGPARAM ( "Data descriptor compressed size mismatch!") ), uno::Reference < XInterface > () );
757         aGrabber >> n32;
758         if ( n32 != rEntry.nSize )
759             throw ZipException ( OUString ( RTL_CONSTASCII_USTRINGPARAM ( "Data descriptor uncompressed size mismatch!") ), uno::Reference < XInterface > () );
760     }
761     return sal_True;
762 }
763 
findEND()764 sal_Int32 ZipFile::findEND( )
765 {
766     // this method is called in constructor only, no need for mutex
767     sal_Int32 nLength, nPos, nEnd;
768     Sequence < sal_Int8 > aBuffer;
769     try
770     {
771         nLength = static_cast <sal_Int32 > (aGrabber.getLength());
772         if (nLength == 0 || nLength < ENDHDR)
773             return -1;
774         nPos = nLength - ENDHDR - ZIP_MAXNAMELEN;
775         nEnd = nPos >= 0 ? nPos : 0 ;
776 
777         aGrabber.seek( nEnd );
778         aGrabber.readBytes ( aBuffer, nLength - nEnd );
779 
780         const sal_Int8 *pBuffer = aBuffer.getConstArray();
781 
782         nPos = nLength - nEnd - ENDHDR;
783         while ( nPos >= 0 )
784         {
785             if (pBuffer[nPos] == 'P' && pBuffer[nPos+1] == 'K' && pBuffer[nPos+2] == 5 && pBuffer[nPos+3] == 6 )
786                 return nPos + nEnd;
787             nPos--;
788         }
789     }
790     catch ( IllegalArgumentException& )
791     {
792         throw ZipException( OUString( RTL_CONSTASCII_USTRINGPARAM ( "Zip END signature not found!") ), uno::Reference < XInterface > () );
793     }
794     catch ( NotConnectedException& )
795     {
796         throw ZipException( OUString( RTL_CONSTASCII_USTRINGPARAM ( "Zip END signature not found!") ), uno::Reference < XInterface > () );
797     }
798     catch ( BufferSizeExceededException& )
799     {
800         throw ZipException( OUString( RTL_CONSTASCII_USTRINGPARAM ( "Zip END signature not found!") ), uno::Reference < XInterface > () );
801     }
802     throw ZipException( OUString( RTL_CONSTASCII_USTRINGPARAM ( "Zip END signature not found!") ), uno::Reference < XInterface > () );
803 }
804 
entriesContainPath(const EntryHash & rEntries,const OUString & sPath)805 static sal_Bool entriesContainPath( const EntryHash &rEntries,
806                                     const OUString &sPath )
807 {
808     for ( EntryHash::const_iterator aIt = rEntries.begin();
809           aIt != rEntries.end(); ++aIt)
810     {
811         if ( aIt->first.equalsIgnoreAsciiCase( sPath ) )
812             return sal_True;
813     }
814     return sal_False;
815 }
816 
readCEN()817 sal_Int32 ZipFile::readCEN()
818 {
819     // this method is called in constructor only, no need for mutex
820     sal_Int32 nCenLen, nCenPos = -1, nCenOff, nEndPos, nLocPos;
821     sal_uInt16 nCount, nTotal;
822 
823     try
824     {
825         nEndPos = findEND();
826         if (nEndPos == -1)
827             return -1;
828         /*
829           Ignored fields:
830            - number of this disk
831            - number of the disk with the start of the central directory
832            - total number of entries in the central directory on this disk
833         */
834         aGrabber.seek(nEndPos + ENDTOT);
835         // total number of entries in the central directory
836         aGrabber >> nTotal;
837         // size of the central directory
838         aGrabber >> nCenLen;
839         // offset of start of central directory
840         aGrabber >> nCenOff;
841 
842         if ( nTotal * CENHDR > nCenLen )
843             throw ZipException(OUString( RTL_CONSTASCII_USTRINGPARAM ( "invalid END header (bad entry count)") ), uno::Reference < XInterface > () );
844 
845         if ( nTotal > ZIP_MAXENTRIES )
846             throw ZipException(OUString( RTL_CONSTASCII_USTRINGPARAM ( "too many entries in ZIP File") ), uno::Reference < XInterface > () );
847 
848         if ( nCenLen < 0 || nCenLen > nEndPos )
849             throw ZipException(OUString( RTL_CONSTASCII_USTRINGPARAM ( "Invalid END header (bad central directory size)") ), uno::Reference < XInterface > () );
850 
851         nCenPos = nEndPos - nCenLen;
852 
853         if ( nCenOff < 0 || nCenOff > nCenPos )
854             throw ZipException(OUString( RTL_CONSTASCII_USTRINGPARAM ( "Invalid END header (bad central directory size)") ), uno::Reference < XInterface > () );
855 
856         // Read the central directory headers
857         nLocPos = nCenPos - nCenOff;
858         aGrabber.seek( nCenPos );
859         Sequence < sal_Int8 > aCENBuffer ( nCenLen );
860         sal_Int64 nRead = aGrabber.readBytes ( aCENBuffer, nCenLen );
861         if ( static_cast < sal_Int64 > ( nCenLen ) != nRead )
862             throw ZipException ( OUString ( RTL_CONSTASCII_USTRINGPARAM ( "Error reading CEN into memory buffer!") ), uno::Reference < XInterface > () );
863 
864         MemoryByteGrabber aMemGrabber ( aCENBuffer );
865 
866         ZipEntry aEntry;
867         sal_Int32 nTestSig;
868         sal_Int16 nCommentLen;
869         rtl::OUString sFirstFilePath;
870 
871         for (nCount = 0 ; nCount < nTotal; nCount++)
872         {
873             aMemGrabber >> nTestSig;
874             if ( nTestSig != CENSIG )
875                 throw ZipException(OUString( RTL_CONSTASCII_USTRINGPARAM ( "Invalid CEN header (bad signature)") ), uno::Reference < XInterface > () );
876 
877             aMemGrabber.skipBytes ( 2 ); // skip: versione made by
878             aMemGrabber >> aEntry.nVersion; // version needed to extract
879             aMemGrabber >> aEntry.nFlag; // general purpose bit flag
880             if ( ( aEntry.nFlag & 1 ) == 1 )
881                 throw ZipException(OUString( RTL_CONSTASCII_USTRINGPARAM ( "Invalid CEN header (encrypted entry)") ), uno::Reference < XInterface > () );
882 
883             aMemGrabber >> aEntry.nMethod; // compression method
884 
885             if ( aEntry.nMethod != STORED && aEntry.nMethod != DEFLATED)
886                 throw ZipException(OUString( RTL_CONSTASCII_USTRINGPARAM ( "Invalid CEN header (bad compression method)") ), uno::Reference < XInterface > () );
887 
888             aMemGrabber >> aEntry.nTime; // last mod file date & time
889             aMemGrabber >> aEntry.nCrc; // crc-32
890             aMemGrabber >> aEntry.nCompressedSize; // compressed size
891             aMemGrabber >> aEntry.nSize; // uncompressed size
892             if ( aEntry.nMethod == STORED && ( aEntry.nCompressedSize != aEntry.nSize ) )
893                 throw ZipException(OUString( RTL_CONSTASCII_USTRINGPARAM ( "Size mismatch of STORED entry") ), uno::Reference < XInterface > () );
894             aMemGrabber >> aEntry.nPathLen; // file name length
895             aMemGrabber >> aEntry.nCENExtraLen; // extra field length
896             aMemGrabber >> nCommentLen; // file comment length
897             // skip: disk number start, internal & external file attributes
898             aMemGrabber.skipBytes ( 8 );
899             aMemGrabber >> aEntry.nFileHeaderOffset; // relative offset of local header
900 
901             aEntry.nFileHeaderOffset += nLocPos;
902 
903             if ( aEntry.nPathLen < 0 )
904                 throw ZipException( OUString( RTL_CONSTASCII_USTRINGPARAM ( "unexpected name length" ) ), uno::Reference < XInterface > () );
905 
906             if ( nCommentLen < 0 )
907                 throw ZipException( OUString( RTL_CONSTASCII_USTRINGPARAM ( "unexpected comment length" ) ), uno::Reference < XInterface > () );
908 
909             if ( aEntry.nCENExtraLen < 0 )
910                 throw ZipException( OUString( RTL_CONSTASCII_USTRINGPARAM ( "unexpected extra header info length") ), uno::Reference < XInterface > () );
911 
912             // read file name always in UTF8, some tools seem not to set UTF8 bit
913             aEntry.sPath = rtl::OUString::intern ( (sal_Char *) aMemGrabber.getCurrentPos(),
914                                                    aEntry.nPathLen,
915                                                    RTL_TEXTENCODING_UTF8 );
916 
917             if ( !::comphelper::OStorageHelper::IsValidZipEntryFileName( aEntry.sPath, sal_True ) )
918                 throw ZipException( OUString( RTL_CONSTASCII_USTRINGPARAM ( "Zip entry has an invalid name.") ), uno::Reference < XInterface > () );
919             // Simplify path removing leading "./"
920             while ( aEntry.sPath.compareToAscii( "./", 2 ) == 0 )
921                 aEntry.sPath = aEntry.sPath.copy( 2 );
922 
923             // skip: file name (already processed)
924             aMemGrabber.skipBytes( aEntry.nPathLen );
925             readExtraFields( aMemGrabber, aEntry.nCENExtraLen, aEntry );
926             // Search for Zip64 data among the comments.
927             // The Zip64 EOCDL takes 20 bytes; the ZIP64 EOCDR takes > 56 bytes
928             const sal_Int8* pCommentStart = aMemGrabber.getCurrentPos();
929             for ( const sal_Int8* pCommentEnd = pCommentStart + nCommentLen;
930                   pCommentEnd >= ( pCommentStart + 76 );
931                   --pCommentEnd) {
932                 const sal_Int8 * p = ( pCommentEnd - 20 );
933                 sal_Int32 n32;
934                 if (p[0] == 0x50)
935                 // Detect EOCDL signature 0x07064b50
936                 if ( ( p[0] == 0x50 ) &&
937                      ( p[1] == 0x4b ) &&
938                      ( p[2] == 0x06 ) &&
939                      ( p[3] == 0x07 ) ) {
940                     // the relative offset of the zip64 end of central directory record starts at offset 8...
941                     n32 = p[8] | ( p[9] << 8 ) | ( p[10] << 16 ) |
942                         ( p[11] << 24 );
943                     // ...and it must be a 32-bit number represented with 64 bits
944                     if ( ( p[12] | p[13] | p[14] | p[15] ) == 0 ) {
945                         n32 -= nCenPos + aMemGrabber.getPosition();
946                         // Detect EOCDR signature 0x06064b50
947                         if ( ( n32 > 0 ) &&
948                              ( pCommentStart[n32] == 0x50 ) &&
949                              ( pCommentStart[n32 + 1] == 0x4b ) &&
950                              ( pCommentStart[n32 + 2] == 0x06 ) &&
951                              ( pCommentStart[n32 + 3] == 0x06 ) ) {
952                                 throw ZipException ( OUString ( RTL_CONSTASCII_USTRINGPARAM ( "Zip64 data found inside comments section") ), uno::Reference < XInterface > () );
953                         }
954                     }
955                 }
956             }
957             aMemGrabber.skipBytes( nCommentLen );
958             if ( entriesContainPath( aEntries, aEntry.sPath ) )
959                 throw ZipException( OUString( RTL_CONSTASCII_USTRINGPARAM ( "Duplicated zip entry") ), uno::Reference < XInterface > () );
960             readLOC( aEntry );
961             if ( aEntry.nFileHeaderOffset == 0 )
962                 sFirstFilePath = aEntry.sPath;
963             aEntries[aEntry.sPath] = aEntry;
964         }
965 
966         if (nCount != nTotal)
967             throw ZipException(OUString( RTL_CONSTASCII_USTRINGPARAM ( "Count != Total") ), uno::Reference < XInterface > () );
968 
969         if ( sFirstFilePath.getLength() == 0 )
970             throw ZipException(OUString( RTL_CONSTASCII_USTRINGPARAM ( "File contains junk before compressed data" ) ), uno::Reference < XInterface > () );
971 
972         // Verify the proper sequence of fields
973         sal_Int32 nPos, nPos2;
974         EntryHash::const_iterator aIt = aEntries.find( sFirstFilePath );
975         nCount = 0;
976         nPos = 0;
977         do {
978             if ( aIt == aEntries.end() ) throw ZipException(OUString( RTL_CONSTASCII_USTRINGPARAM ( "Internal error" ) ), uno::Reference < XInterface > () );
979             // Local file header
980             nPos += 30 + aIt->first.getLength() + aIt->second.nLOCExtraLen;
981             if ( nPos != aIt->second.nFileDataOffset )
982                 throw ZipException(OUString( RTL_CONSTASCII_USTRINGPARAM ( "ZIP file contains a hole between local descriptor and file data" ) ), uno::Reference < XInterface > () );
983             // File data
984             nPos += aIt->second.nCompressedSize;
985             if ( aIt->second.bHasDataDescriptor ) {
986                 // Data descriptor...
987                 nPos += 16;  // ...with signature
988                 nPos2 = nPos - 4; // ...without signature
989             } else nPos2 = nPos;
990             ++nCount;
991             if ( nCount == nTotal ) {
992                 break;
993             }
994             // Find next entry, starting at either nPos or nPos2
995             for ( aIt = aEntries.begin(); aIt != aEntries.end(); ++aIt )
996                 if (( aIt->second.nFileHeaderOffset == nPos ) ||
997                     ( aIt->second.nFileHeaderOffset == nPos2 ))
998                     break;
999             if ( aIt == aEntries.end() )
1000                 throw ZipException(OUString( RTL_CONSTASCII_USTRINGPARAM ( "ZIP file contains holes among files" ) ), uno::Reference < XInterface > () );
1001             nPos = aIt->second.nFileHeaderOffset;
1002         } while ( 1 );
1003         // After all files, we should have arrived at the central directory header
1004         if ( nPos != nCenPos )
1005             throw ZipException(OUString( RTL_CONSTASCII_USTRINGPARAM ( "ZIP file contains a hole before the central directory" ) ), uno::Reference < XInterface > () );
1006     }
1007     catch ( IllegalArgumentException & )
1008     {
1009         // seek can throw this...
1010         nCenPos = -1; // make sure we return -1 to indicate an error
1011     }
1012     return nCenPos;
1013 }
1014 
recover()1015 sal_Int32 ZipFile::recover()
1016 {
1017     ::osl::MutexGuard aGuard( m_aMutex );
1018 
1019     sal_Int32 nLength;
1020     Sequence < sal_Int8 > aBuffer;
1021     Sequence < sal_Int32 > aHeaderOffsets;
1022 
1023     try
1024     {
1025         nLength = static_cast <sal_Int32 > (aGrabber.getLength());
1026         if (nLength == 0 || nLength < ENDHDR)
1027             return -1;
1028 
1029         aGrabber.seek( 0 );
1030 
1031         const sal_Int32 nToRead = 32000;
1032         for( sal_Int32 nGenPos = 0; aGrabber.readBytes( aBuffer, nToRead ) && aBuffer.getLength() > 16; )
1033         {
1034             const sal_Int8 *pBuffer = aBuffer.getConstArray();
1035             sal_Int32 nBufSize = aBuffer.getLength();
1036 
1037             sal_Int32 nPos = 0;
1038             // the buffer should contain at least one header,
1039             // or if it is end of the file, at least the postheader with sizes and hash
1040             while( nPos < nBufSize - 30
1041                 || ( aBuffer.getLength() < nToRead && nPos < nBufSize - 16 ) )
1042 
1043             {
1044                 if ( nPos < nBufSize - 30 && pBuffer[nPos] == 'P' && pBuffer[nPos+1] == 'K' && pBuffer[nPos+2] == 3 && pBuffer[nPos+3] == 4 )
1045                 {
1046                     // Local file header
1047                     ZipEntry aEntry;
1048                     MemoryByteGrabber aMemGrabber ( Sequence< sal_Int8 >( ((sal_Int8*)(&(pBuffer[nPos+4]))), 26 ) );
1049 
1050                     aMemGrabber >> aEntry.nVersion;
1051                     aMemGrabber >> aEntry.nFlag;
1052                     if ( ( aEntry.nFlag & 1 ) != 1 ) // Must not be encrypted
1053                     {
1054                         aMemGrabber >> aEntry.nMethod;
1055 
1056                         if ( aEntry.nMethod == STORED || aEntry.nMethod == DEFLATED )
1057                         {
1058                             aMemGrabber >> aEntry.nTime;
1059                             aMemGrabber >> aEntry.nCrc;
1060                             aMemGrabber >> aEntry.nCompressedSize;
1061                             aMemGrabber >> aEntry.nSize;
1062                             aMemGrabber >> aEntry.nPathLen;
1063                             aMemGrabber >> aEntry.nLOCExtraLen;
1064 
1065                             sal_Int32 nDescrLength =
1066                                 ( aEntry.nMethod == DEFLATED && ( aEntry.nFlag & 8 ) ) ?
1067                                                         16 : 0;
1068 
1069 
1070                             // This is a quick fix for OOo1.1RC
1071                             // For OOo2.0 the whole package must be switched to unsigned values
1072                             if ( aEntry.nCompressedSize < 0 ) aEntry.nCompressedSize = 0x7FFFFFFF;
1073                             if ( aEntry.nSize < 0 ) aEntry.nSize = 0x7FFFFFFF;
1074                             if ( aEntry.nPathLen < 0 ) aEntry.nPathLen = 0x7FFF;
1075                             if ( aEntry.nLOCExtraLen < 0 ) aEntry.nLOCExtraLen = 0x7FFF;
1076                             // End of quick fix
1077 
1078                             sal_Int32 nDataSize = ( aEntry.nMethod == DEFLATED ) ? aEntry.nCompressedSize : aEntry.nSize;
1079                             sal_Int32 nBlockLength = nDataSize + aEntry.nPathLen + aEntry.nLOCExtraLen + 30 + nDescrLength;
1080                             if ( aEntry.nPathLen >= 0 && aEntry.nLOCExtraLen >= 0
1081                                 && ( nGenPos + nPos + nBlockLength ) <= nLength )
1082                             {
1083                                 // read always in UTF8, some tools seem not to set UTF8 bit
1084                                 if( nPos + 30 + aEntry.nPathLen <= nBufSize )
1085                                     aEntry.sPath = OUString ( (sal_Char *) &pBuffer[nPos + 30],
1086                                                                 aEntry.nPathLen,
1087                                                                 RTL_TEXTENCODING_UTF8 );
1088                                 else
1089                                 {
1090                                     Sequence < sal_Int8 > aFileName;
1091                                     aGrabber.seek( nGenPos + nPos + 30 );
1092                                     aGrabber.readBytes( aFileName, aEntry.nPathLen );
1093                                     aEntry.sPath = OUString ( (sal_Char *) aFileName.getArray(),
1094                                                                 aFileName.getLength(),
1095                                                                 RTL_TEXTENCODING_UTF8 );
1096                                     aEntry.nPathLen = static_cast< sal_Int16 >(aFileName.getLength());
1097                                 }
1098 
1099                                 aEntry.nFileDataOffset = nGenPos + nPos + 30 + aEntry.nPathLen + aEntry.nLOCExtraLen;
1100 
1101                                 if ( ( aEntry.nSize || aEntry.nCompressedSize ) && !checkSizeAndCRC( aEntry ) )
1102                                 {
1103                                     aEntry.nCrc = 0;
1104                                     aEntry.nCompressedSize = 0;
1105                                     aEntry.nSize = 0;
1106                                 }
1107 
1108                                 if ( aEntries.find( aEntry.sPath ) == aEntries.end() )
1109                                     aEntries[aEntry.sPath] = aEntry;
1110                             }
1111                         }
1112                     }
1113 
1114                     nPos += 4;
1115                 }
1116                 else if (pBuffer[nPos] == 'P' && pBuffer[nPos+1] == 'K' && pBuffer[nPos+2] == 7 && pBuffer[nPos+3] == 8 )
1117                 { // This is a data descriptor
1118                     sal_Int32 nCompressedSize, nSize, nCRC32;
1119                     MemoryByteGrabber aMemGrabber ( Sequence< sal_Int8 >( ((sal_Int8*)(&(pBuffer[nPos+4]))), 12 ) );
1120                     aMemGrabber >> nCRC32;
1121                     aMemGrabber >> nCompressedSize;
1122                     aMemGrabber >> nSize;
1123 
1124                     for( EntryHash::iterator aIter = aEntries.begin(); aIter != aEntries.end(); aIter++ )
1125                     {
1126                         ZipEntry aTmp = (*aIter).second;
1127 
1128                         // this is a broken package, accept this block not only for DEFLATED streams
1129                         if( (*aIter).second.nFlag & 8 )
1130                         {
1131                             sal_Int32 nStreamOffset = nGenPos + nPos - nCompressedSize;
1132                             if ( nStreamOffset == (*aIter).second.nFileDataOffset && nCompressedSize > (*aIter).second.nCompressedSize )
1133                             {
1134                                 // only DEFLATED blocks need to be checked
1135                                 sal_Bool bAcceptBlock = ( (*aIter).second.nMethod == STORED && nCompressedSize == nSize );
1136 
1137                                 if ( !bAcceptBlock )
1138                                 {
1139                                     sal_Int32 nRealSize = 0, nRealCRC = 0;
1140                                     getSizeAndCRC( nStreamOffset, nCompressedSize, &nRealSize, &nRealCRC );
1141                                     bAcceptBlock = ( nRealSize == nSize && nRealCRC == nCRC32 );
1142                                 }
1143 
1144                                 if ( bAcceptBlock )
1145                                 {
1146                                     (*aIter).second.nCrc = nCRC32;
1147                                     (*aIter).second.nCompressedSize = nCompressedSize;
1148                                     (*aIter).second.nSize = nSize;
1149                                 }
1150                             }
1151 #if 0
1152 // for now ignore clearly broken streams
1153                             else if( !(*aIter).second.nCompressedSize )
1154                             {
1155                                 (*aIter).second.nCrc = nCRC32;
1156                                 sal_Int32 nRealStreamSize = nGenPos + nPos - (*aIter).second.nFileDataOffset;
1157                                 (*aIter).second.nCompressedSize = nGenPos + nPos - (*aIter).second.nFileDataOffset;
1158                                 (*aIter).second.nSize = nSize;
1159                             }
1160 #endif
1161                         }
1162                     }
1163 
1164                     nPos += 4;
1165                 }
1166                 else
1167                     nPos++;
1168             }
1169 
1170             nGenPos += nPos;
1171             aGrabber.seek( nGenPos );
1172         }
1173 
1174         return 0;
1175     }
1176     catch ( IllegalArgumentException& )
1177     {
1178         throw ZipException( OUString( RTL_CONSTASCII_USTRINGPARAM ( "Zip END signature not found!") ), uno::Reference < XInterface > () );
1179     }
1180     catch ( NotConnectedException& )
1181     {
1182         throw ZipException( OUString( RTL_CONSTASCII_USTRINGPARAM ( "Zip END signature not found!") ), uno::Reference < XInterface > () );
1183     }
1184     catch ( BufferSizeExceededException& )
1185     {
1186         throw ZipException( OUString( RTL_CONSTASCII_USTRINGPARAM ( "Zip END signature not found!") ), uno::Reference < XInterface > () );
1187     }
1188 }
1189 
checkSizeAndCRC(const ZipEntry & aEntry)1190 sal_Bool ZipFile::checkSizeAndCRC( const ZipEntry& aEntry )
1191 {
1192     ::osl::MutexGuard aGuard( m_aMutex );
1193 
1194     sal_Int32 nSize = 0, nCRC = 0;
1195 
1196     if( aEntry.nMethod == STORED )
1197         return ( getCRC( aEntry.nFileDataOffset, aEntry.nSize ) == aEntry.nCrc );
1198 
1199     getSizeAndCRC( aEntry.nFileDataOffset, aEntry.nCompressedSize, &nSize, &nCRC );
1200     return ( aEntry.nSize == nSize && aEntry.nCrc == nCRC );
1201 }
1202 
getCRC(sal_Int32 nFileDataOffset,sal_Int32 nSize)1203 sal_Int32 ZipFile::getCRC( sal_Int32 nFileDataOffset, sal_Int32 nSize )
1204 {
1205     ::osl::MutexGuard aGuard( m_aMutex );
1206 
1207     Sequence < sal_Int8 > aBuffer;
1208     CRC32 aCRC;
1209     sal_Int32 nBlockSize = ::std::min( nSize, static_cast< sal_Int32 >( 32000 ) );
1210 
1211     aGrabber.seek( nFileDataOffset );
1212     for ( int ind = 0;
1213           aGrabber.readBytes( aBuffer, nBlockSize ) && ind * nBlockSize < nSize;
1214           ind++ )
1215     {
1216         aCRC.updateSegment( aBuffer, 0, ::std::min( nBlockSize, nSize - ind * nBlockSize ) );
1217     }
1218 
1219     return aCRC.getValue();
1220 }
1221 
getSizeAndCRC(sal_Int32 nFileDataOffset,sal_Int32 nCompressedSize,sal_Int32 * nSize,sal_Int32 * nCRC)1222 void ZipFile::getSizeAndCRC( sal_Int32 nFileDataOffset, sal_Int32 nCompressedSize, sal_Int32 *nSize, sal_Int32 *nCRC )
1223 {
1224     ::osl::MutexGuard aGuard( m_aMutex );
1225 
1226     Sequence < sal_Int8 > aBuffer;
1227     CRC32 aCRC;
1228     sal_Int32 nRealSize = 0;
1229     Inflater aInflaterLocal( sal_True );
1230     sal_Int32 nBlockSize = ::std::min( nCompressedSize, static_cast< sal_Int32 >( 32000 ) );
1231 
1232     aGrabber.seek( nFileDataOffset );
1233     for ( int ind = 0;
1234           !aInflaterLocal.finished() && aGrabber.readBytes( aBuffer, nBlockSize ) && ind * nBlockSize < nCompressedSize;
1235           ind++ )
1236     {
1237         Sequence < sal_Int8 > aData( nBlockSize );
1238         sal_Int32 nLastInflated = 0;
1239         sal_Int32 nInBlock = 0;
1240 
1241         aInflaterLocal.setInput( aBuffer );
1242         do
1243         {
1244             nLastInflated = aInflaterLocal.doInflateSegment( aData, 0, nBlockSize );
1245             aCRC.updateSegment( aData, 0, nLastInflated );
1246             nInBlock += nLastInflated;
1247         } while( !aInflater.finished() && nLastInflated );
1248 
1249         nRealSize += nInBlock;
1250     }
1251 
1252     *nSize = nRealSize;
1253     *nCRC = aCRC.getValue();
1254 }
1255