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 rMemGrabber >> n8; // Version
659 rMemGrabber.skipBytes( 4 ); // skip NameCRC32
660 s = rtl::OUString::intern ( (sal_Char *) rMemGrabber.getCurrentPos(),
661 nDataSize - 5,
662 RTL_TEXTENCODING_UTF8 );
663 if ( n8 != 1 )
664 throw ZipException( OUString( RTL_CONSTASCII_USTRINGPARAM ( "Invalid ZIP unicode path extra field version" ) ), uno::Reference < XInterface > () );
665 if ( s != rEntry.sPath )
666 throw ZipException( OUString( RTL_CONSTASCII_USTRINGPARAM ( "Invalid ZIP unicode path extra field" ) ), uno::Reference < XInterface > () );
667 rMemGrabber.skipBytes( nDataSize - 5 );
668 break;
669 default: // We are not interested in this field
670 rMemGrabber.skipBytes( nDataSize );
671 }
672 nReadBytes += nDataSize;
673 }
674 }
675
readLOC(ZipEntry & rEntry)676 sal_Bool ZipFile::readLOC( ZipEntry &rEntry )
677 {
678 ::osl::MutexGuard aGuard( m_aMutex );
679
680 sal_Int32 nTestSig, nTime, nCRC, nSize, nCompressedSize;
681 sal_Int16 nVersion, nFlag, nHow, nPathLen;
682 sal_Int32 nPos = rEntry.nFileHeaderOffset;
683
684 aGrabber.seek(nPos);
685 aGrabber >> nTestSig;
686
687 if (nTestSig != LOCSIG)
688 throw ZipIOException( OUString( RTL_CONSTASCII_USTRINGPARAM ( "Invalid LOC header (bad signature") ), uno::Reference < XInterface > () );
689 aGrabber >> nVersion;
690 aGrabber >> nFlag;
691 aGrabber >> nHow;
692 aGrabber >> nTime;
693 aGrabber >> nCRC;
694 aGrabber >> nCompressedSize;
695 aGrabber >> nSize;
696 aGrabber >> nPathLen;
697 aGrabber >> rEntry.nLOCExtraLen;
698 rEntry.nFileDataOffset = static_cast < sal_Int32 > (aGrabber.getPosition()) + nPathLen + rEntry.nLOCExtraLen;
699
700 // read always in UTF8, some tools seem not to set UTF8 bit
701 uno::Sequence < sal_Int8 > aNameBuffer( nPathLen );
702 sal_Int32 nRead = aGrabber.readBytes( aNameBuffer, nPathLen );
703 if ( nRead < aNameBuffer.getLength() )
704 aNameBuffer.realloc( nRead );
705
706 ::rtl::OUString sLOCPath = rtl::OUString::intern( (sal_Char *) aNameBuffer.getArray(),
707 aNameBuffer.getLength(),
708 RTL_TEXTENCODING_UTF8 );
709
710 if ( rEntry.nPathLen == -1 ) // the file was created
711 {
712 rEntry.nPathLen = nPathLen;
713 rEntry.sPath = sLOCPath;
714 }
715
716 // the method can be reset for internal use so it is not checked
717 sal_Bool bBroken = rEntry.nVersion != nVersion
718 || rEntry.nFlag != nFlag
719 || rEntry.nMethod != nHow
720 || rEntry.nTime != nTime
721 || rEntry.nPathLen != nPathLen
722 || !rEntry.sPath.equals( sLOCPath );
723
724 if ( bBroken && !bRecoveryMode )
725 throw ZipIOException( OUString( RTL_CONSTASCII_USTRINGPARAM( "The stream seems to be broken!" ) ),
726 uno::Reference< XInterface >() );
727
728 Sequence < sal_Int8 > aExtraFields ( rEntry.nLOCExtraLen );
729 nRead = aGrabber.readBytes( aExtraFields, rEntry.nLOCExtraLen );
730 if ( nRead != rEntry.nLOCExtraLen )
731 throw ZipException ( OUString ( RTL_CONSTASCII_USTRINGPARAM ( "Error reading LOC extra fields into memory buffer!") ), uno::Reference < XInterface > () );
732 MemoryByteGrabber aMemGrabber ( aExtraFields );
733 readExtraFields( aMemGrabber, rEntry.nLOCExtraLen, rEntry );
734
735 // Check for a data descriptor
736 rEntry.bHasDataDescriptor = rEntry.nFlag & ( 1 << 3 );
737 if ( rEntry.bHasDataDescriptor ) {
738 // some fields of the local file header must be zero
739 if ( ( nCRC | nCompressedSize | nSize ) != 0 )
740 throw ZipException ( OUString ( RTL_CONSTASCII_USTRINGPARAM ( "Data descriptor mismatch!") ), uno::Reference < XInterface > () );
741 }
742 sal_Int32 n32;
743 aGrabber.seek( rEntry.nFileDataOffset + rEntry.nCompressedSize );
744 aGrabber >> n32;
745 if ( n32 == EXTSIG ) { // Signature detected
746 rEntry.bHasDataDescriptor = sal_True;
747 aGrabber >> n32;
748 }
749 if ( rEntry.bHasDataDescriptor ) {
750 if ( n32 != rEntry.nCrc )
751 throw ZipException ( OUString ( RTL_CONSTASCII_USTRINGPARAM ( "Data descriptor CRC mismatch!") ), uno::Reference < XInterface > () );
752 aGrabber >> n32;
753 if ( n32 != rEntry.nCompressedSize )
754 throw ZipException ( OUString ( RTL_CONSTASCII_USTRINGPARAM ( "Data descriptor compressed size mismatch!") ), uno::Reference < XInterface > () );
755 aGrabber >> n32;
756 if ( n32 != rEntry.nSize )
757 throw ZipException ( OUString ( RTL_CONSTASCII_USTRINGPARAM ( "Data descriptor uncompressed size mismatch!") ), uno::Reference < XInterface > () );
758 }
759 return sal_True;
760 }
761
findEND()762 sal_Int32 ZipFile::findEND( )
763 {
764 // this method is called in constructor only, no need for mutex
765 sal_Int32 nLength, nPos, nEnd;
766 Sequence < sal_Int8 > aBuffer;
767 try
768 {
769 nLength = static_cast <sal_Int32 > (aGrabber.getLength());
770 if (nLength == 0 || nLength < ENDHDR)
771 return -1;
772 nPos = nLength - ENDHDR - ZIP_MAXNAMELEN;
773 nEnd = nPos >= 0 ? nPos : 0 ;
774
775 aGrabber.seek( nEnd );
776 aGrabber.readBytes ( aBuffer, nLength - nEnd );
777
778 const sal_Int8 *pBuffer = aBuffer.getConstArray();
779
780 nPos = nLength - nEnd - ENDHDR;
781 while ( nPos >= 0 )
782 {
783 if (pBuffer[nPos] == 'P' && pBuffer[nPos+1] == 'K' && pBuffer[nPos+2] == 5 && pBuffer[nPos+3] == 6 )
784 return nPos + nEnd;
785 nPos--;
786 }
787 }
788 catch ( IllegalArgumentException& )
789 {
790 throw ZipException( OUString( RTL_CONSTASCII_USTRINGPARAM ( "Zip END signature not found!") ), uno::Reference < XInterface > () );
791 }
792 catch ( NotConnectedException& )
793 {
794 throw ZipException( OUString( RTL_CONSTASCII_USTRINGPARAM ( "Zip END signature not found!") ), uno::Reference < XInterface > () );
795 }
796 catch ( BufferSizeExceededException& )
797 {
798 throw ZipException( OUString( RTL_CONSTASCII_USTRINGPARAM ( "Zip END signature not found!") ), uno::Reference < XInterface > () );
799 }
800 throw ZipException( OUString( RTL_CONSTASCII_USTRINGPARAM ( "Zip END signature not found!") ), uno::Reference < XInterface > () );
801 }
802
entriesContainPath(const EntryHash & rEntries,const OUString & sPath)803 static sal_Bool entriesContainPath( const EntryHash &rEntries,
804 const OUString &sPath )
805 {
806 for ( EntryHash::const_iterator aIt = rEntries.begin();
807 aIt != rEntries.end(); ++aIt)
808 {
809 if ( aIt->first.equalsIgnoreAsciiCase( sPath ) )
810 return sal_True;
811 }
812 return sal_False;
813 }
814
readCEN()815 sal_Int32 ZipFile::readCEN()
816 {
817 // this method is called in constructor only, no need for mutex
818 sal_Int32 nCenLen, nCenPos = -1, nCenOff, nEndPos, nLocPos;
819 sal_uInt16 nCount, nTotal;
820
821 try
822 {
823 nEndPos = findEND();
824 if (nEndPos == -1)
825 return -1;
826 /*
827 Ignored fields:
828 - number of this disk
829 - number of the disk with the start of the central directory
830 - total number of entries in the central directory on this disk
831 */
832 aGrabber.seek(nEndPos + ENDTOT);
833 // total number of entries in the central directory
834 aGrabber >> nTotal;
835 // size of the central directory
836 aGrabber >> nCenLen;
837 // offset of start of central directory
838 aGrabber >> nCenOff;
839
840 if ( nTotal * CENHDR > nCenLen )
841 throw ZipException(OUString( RTL_CONSTASCII_USTRINGPARAM ( "invalid END header (bad entry count)") ), uno::Reference < XInterface > () );
842
843 if ( nTotal > ZIP_MAXENTRIES )
844 throw ZipException(OUString( RTL_CONSTASCII_USTRINGPARAM ( "too many entries in ZIP File") ), uno::Reference < XInterface > () );
845
846 if ( nCenLen < 0 || nCenLen > nEndPos )
847 throw ZipException(OUString( RTL_CONSTASCII_USTRINGPARAM ( "Invalid END header (bad central directory size)") ), uno::Reference < XInterface > () );
848
849 nCenPos = nEndPos - nCenLen;
850
851 if ( nCenOff < 0 || nCenOff > nCenPos )
852 throw ZipException(OUString( RTL_CONSTASCII_USTRINGPARAM ( "Invalid END header (bad central directory size)") ), uno::Reference < XInterface > () );
853
854 // Read the central directory headers
855 nLocPos = nCenPos - nCenOff;
856 aGrabber.seek( nCenPos );
857 Sequence < sal_Int8 > aCENBuffer ( nCenLen );
858 sal_Int64 nRead = aGrabber.readBytes ( aCENBuffer, nCenLen );
859 if ( static_cast < sal_Int64 > ( nCenLen ) != nRead )
860 throw ZipException ( OUString ( RTL_CONSTASCII_USTRINGPARAM ( "Error reading CEN into memory buffer!") ), uno::Reference < XInterface > () );
861
862 MemoryByteGrabber aMemGrabber ( aCENBuffer );
863
864 ZipEntry aEntry;
865 sal_Int32 nTestSig;
866 sal_Int16 nCommentLen;
867 rtl::OUString sFirstFilePath;
868
869 for (nCount = 0 ; nCount < nTotal; nCount++)
870 {
871 aMemGrabber >> nTestSig;
872 if ( nTestSig != CENSIG )
873 throw ZipException(OUString( RTL_CONSTASCII_USTRINGPARAM ( "Invalid CEN header (bad signature)") ), uno::Reference < XInterface > () );
874
875 aMemGrabber.skipBytes ( 2 ); // skip: versione made by
876 aMemGrabber >> aEntry.nVersion; // version needed to extract
877 aMemGrabber >> aEntry.nFlag; // general purpose bit flag
878 if ( ( aEntry.nFlag & 1 ) == 1 )
879 throw ZipException(OUString( RTL_CONSTASCII_USTRINGPARAM ( "Invalid CEN header (encrypted entry)") ), uno::Reference < XInterface > () );
880
881 aMemGrabber >> aEntry.nMethod; // compression method
882
883 if ( aEntry.nMethod != STORED && aEntry.nMethod != DEFLATED)
884 throw ZipException(OUString( RTL_CONSTASCII_USTRINGPARAM ( "Invalid CEN header (bad compression method)") ), uno::Reference < XInterface > () );
885
886 aMemGrabber >> aEntry.nTime; // last mod file date & time
887 aMemGrabber >> aEntry.nCrc; // crc-32
888 aMemGrabber >> aEntry.nCompressedSize; // compressed size
889 aMemGrabber >> aEntry.nSize; // uncompressed size
890 if ( aEntry.nMethod == STORED && ( aEntry.nCompressedSize != aEntry.nSize ) )
891 throw ZipException(OUString( RTL_CONSTASCII_USTRINGPARAM ( "Size mismatch of STORED entry") ), uno::Reference < XInterface > () );
892 aMemGrabber >> aEntry.nPathLen; // file name length
893 aMemGrabber >> aEntry.nCENExtraLen; // extra field length
894 aMemGrabber >> nCommentLen; // file comment length
895 // skip: disk number start, internal & external file attributes
896 aMemGrabber.skipBytes ( 8 );
897 aMemGrabber >> aEntry.nFileHeaderOffset; // relative offset of local header
898
899 aEntry.nFileHeaderOffset += nLocPos;
900
901 if ( aEntry.nPathLen < 0 )
902 throw ZipException( OUString( RTL_CONSTASCII_USTRINGPARAM ( "unexpected name length" ) ), uno::Reference < XInterface > () );
903
904 if ( nCommentLen < 0 )
905 throw ZipException( OUString( RTL_CONSTASCII_USTRINGPARAM ( "unexpected comment length" ) ), uno::Reference < XInterface > () );
906
907 if ( aEntry.nCENExtraLen < 0 )
908 throw ZipException( OUString( RTL_CONSTASCII_USTRINGPARAM ( "unexpected extra header info length") ), uno::Reference < XInterface > () );
909
910 // read file name always in UTF8, some tools seem not to set UTF8 bit
911 aEntry.sPath = rtl::OUString::intern ( (sal_Char *) aMemGrabber.getCurrentPos(),
912 aEntry.nPathLen,
913 RTL_TEXTENCODING_UTF8 );
914
915 if ( !::comphelper::OStorageHelper::IsValidZipEntryFileName( aEntry.sPath, sal_True ) )
916 throw ZipException( OUString( RTL_CONSTASCII_USTRINGPARAM ( "Zip entry has an invalid name.") ), uno::Reference < XInterface > () );
917 // Simplify path removing leading "./"
918 while ( aEntry.sPath.compareToAscii( "./", 2 ) == 0 )
919 aEntry.sPath = aEntry.sPath.copy( 2 );
920
921 // skip: file name (already processed)
922 aMemGrabber.skipBytes( aEntry.nPathLen );
923 readExtraFields( aMemGrabber, aEntry.nCENExtraLen, aEntry );
924 // Search for Zip64 data among the comments.
925 // The Zip64 EOCDL takes 20 bytes; the ZIP64 EOCDR takes > 56 bytes
926 const sal_Int8* pCommentStart = aMemGrabber.getCurrentPos();
927 for ( const sal_Int8* pCommentEnd = pCommentStart + nCommentLen;
928 pCommentEnd >= ( pCommentStart + 76 );
929 --pCommentEnd) {
930 const sal_Int8 * p = ( pCommentEnd - 20 );
931 sal_Int32 n32;
932 if (p[0] == 0x50)
933 // Detect EOCDL signature 0x07064b50
934 if ( ( p[0] == 0x50 ) &&
935 ( p[1] == 0x4b ) &&
936 ( p[2] == 0x06 ) &&
937 ( p[3] == 0x07 ) ) {
938 // the relative offset of the zip64 end of central directory record starts at offset 8...
939 n32 = p[8] | ( p[9] << 8 ) | ( p[10] << 16 ) |
940 ( p[11] << 24 );
941 // ...and it must be a 32-bit number represented with 64 bits
942 if ( ( p[12] | p[13] | p[14] | p[15] ) == 0 ) {
943 n32 -= nCenPos + aMemGrabber.getPosition();
944 // Detect EOCDR signature 0x06064b50
945 if ( ( n32 > 0 ) &&
946 ( pCommentStart[n32] == 0x50 ) &&
947 ( pCommentStart[n32 + 1] == 0x4b ) &&
948 ( pCommentStart[n32 + 2] == 0x06 ) &&
949 ( pCommentStart[n32 + 3] == 0x06 ) ) {
950 throw ZipException ( OUString ( RTL_CONSTASCII_USTRINGPARAM ( "Zip64 data found inside comments section") ), uno::Reference < XInterface > () );
951 }
952 }
953 }
954 }
955 aMemGrabber.skipBytes( nCommentLen );
956 if ( entriesContainPath( aEntries, aEntry.sPath ) )
957 throw ZipException( OUString( RTL_CONSTASCII_USTRINGPARAM ( "Duplicated zip entry") ), uno::Reference < XInterface > () );
958 readLOC( aEntry );
959 if ( aEntry.nFileHeaderOffset == 0 )
960 sFirstFilePath = aEntry.sPath;
961 aEntries[aEntry.sPath] = aEntry;
962 }
963
964 if (nCount != nTotal)
965 throw ZipException(OUString( RTL_CONSTASCII_USTRINGPARAM ( "Count != Total") ), uno::Reference < XInterface > () );
966
967 if ( sFirstFilePath.getLength() == 0 )
968 throw ZipException(OUString( RTL_CONSTASCII_USTRINGPARAM ( "File contains junk before compressed data" ) ), uno::Reference < XInterface > () );
969
970 // Verify the proper sequence of fields
971 sal_Int32 nPos, nPos2;
972 EntryHash::const_iterator aIt = aEntries.find( sFirstFilePath );
973 nCount = 0;
974 nPos = 0;
975 do {
976 if ( aIt == aEntries.end() ) throw ZipException(OUString( RTL_CONSTASCII_USTRINGPARAM ( "Internal error" ) ), uno::Reference < XInterface > () );
977 // Local file header
978 nPos += 30 + aIt->first.getLength() + aIt->second.nLOCExtraLen;
979 if ( nPos != aIt->second.nFileDataOffset )
980 throw ZipException(OUString( RTL_CONSTASCII_USTRINGPARAM ( "ZIP file contains a hole between local descriptor and file data" ) ), uno::Reference < XInterface > () );
981 // File data
982 nPos += aIt->second.nCompressedSize;
983 if ( aIt->second.nFlag & ( 1 << 3 ) ) {
984 // Data descriptor...
985 nPos += 16; // ...with signature
986 nPos2 = nPos - 4; // ...without signature
987 } else nPos2 = nPos;
988 ++nCount;
989 if ( nCount == nTotal ) {
990 break;
991 }
992 // Find next entry, starting at either nPos or nPos2
993 for ( aIt = aEntries.begin(); aIt != aEntries.end(); ++aIt )
994 if (( aIt->second.nFileHeaderOffset == nPos ) ||
995 ( aIt->second.nFileHeaderOffset == nPos2 ))
996 break;
997 if ( aIt == aEntries.end() )
998 throw ZipException(OUString( RTL_CONSTASCII_USTRINGPARAM ( "ZIP file contains holes among files" ) ), uno::Reference < XInterface > () );
999 nPos = aIt->second.nFileHeaderOffset;
1000 } while ( 1 );
1001 // After all files, we should have arrived at the central directory header
1002 if ( nPos != nCenPos )
1003 throw ZipException(OUString( RTL_CONSTASCII_USTRINGPARAM ( "ZIP file contains a hole before the central directory" ) ), uno::Reference < XInterface > () );
1004 }
1005 catch ( IllegalArgumentException & )
1006 {
1007 // seek can throw this...
1008 nCenPos = -1; // make sure we return -1 to indicate an error
1009 }
1010 return nCenPos;
1011 }
1012
recover()1013 sal_Int32 ZipFile::recover()
1014 {
1015 ::osl::MutexGuard aGuard( m_aMutex );
1016
1017 sal_Int32 nLength;
1018 Sequence < sal_Int8 > aBuffer;
1019 Sequence < sal_Int32 > aHeaderOffsets;
1020
1021 try
1022 {
1023 nLength = static_cast <sal_Int32 > (aGrabber.getLength());
1024 if (nLength == 0 || nLength < ENDHDR)
1025 return -1;
1026
1027 aGrabber.seek( 0 );
1028
1029 const sal_Int32 nToRead = 32000;
1030 for( sal_Int32 nGenPos = 0; aGrabber.readBytes( aBuffer, nToRead ) && aBuffer.getLength() > 16; )
1031 {
1032 const sal_Int8 *pBuffer = aBuffer.getConstArray();
1033 sal_Int32 nBufSize = aBuffer.getLength();
1034
1035 sal_Int32 nPos = 0;
1036 // the buffer should contain at least one header,
1037 // or if it is end of the file, at least the postheader with sizes and hash
1038 while( nPos < nBufSize - 30
1039 || ( aBuffer.getLength() < nToRead && nPos < nBufSize - 16 ) )
1040
1041 {
1042 if ( nPos < nBufSize - 30 && pBuffer[nPos] == 'P' && pBuffer[nPos+1] == 'K' && pBuffer[nPos+2] == 3 && pBuffer[nPos+3] == 4 )
1043 {
1044 // Local file header
1045 ZipEntry aEntry;
1046 MemoryByteGrabber aMemGrabber ( Sequence< sal_Int8 >( ((sal_Int8*)(&(pBuffer[nPos+4]))), 26 ) );
1047
1048 aMemGrabber >> aEntry.nVersion;
1049 aMemGrabber >> aEntry.nFlag;
1050 if ( ( aEntry.nFlag & 1 ) != 1 ) // Must not be encrypted
1051 {
1052 aMemGrabber >> aEntry.nMethod;
1053
1054 if ( aEntry.nMethod == STORED || aEntry.nMethod == DEFLATED )
1055 {
1056 aMemGrabber >> aEntry.nTime;
1057 aMemGrabber >> aEntry.nCrc;
1058 aMemGrabber >> aEntry.nCompressedSize;
1059 aMemGrabber >> aEntry.nSize;
1060 aMemGrabber >> aEntry.nPathLen;
1061 aMemGrabber >> aEntry.nLOCExtraLen;
1062
1063 sal_Int32 nDescrLength =
1064 ( aEntry.nMethod == DEFLATED && ( aEntry.nFlag & 8 ) ) ?
1065 16 : 0;
1066
1067
1068 // This is a quick fix for OOo1.1RC
1069 // For OOo2.0 the whole package must be switched to unsigned values
1070 if ( aEntry.nCompressedSize < 0 ) aEntry.nCompressedSize = 0x7FFFFFFF;
1071 if ( aEntry.nSize < 0 ) aEntry.nSize = 0x7FFFFFFF;
1072 if ( aEntry.nPathLen < 0 ) aEntry.nPathLen = 0x7FFF;
1073 if ( aEntry.nLOCExtraLen < 0 ) aEntry.nLOCExtraLen = 0x7FFF;
1074 // End of quick fix
1075
1076 sal_Int32 nDataSize = ( aEntry.nMethod == DEFLATED ) ? aEntry.nCompressedSize : aEntry.nSize;
1077 sal_Int32 nBlockLength = nDataSize + aEntry.nPathLen + aEntry.nLOCExtraLen + 30 + nDescrLength;
1078 if ( aEntry.nPathLen >= 0 && aEntry.nLOCExtraLen >= 0
1079 && ( nGenPos + nPos + nBlockLength ) <= nLength )
1080 {
1081 // read always in UTF8, some tools seem not to set UTF8 bit
1082 if( nPos + 30 + aEntry.nPathLen <= nBufSize )
1083 aEntry.sPath = OUString ( (sal_Char *) &pBuffer[nPos + 30],
1084 aEntry.nPathLen,
1085 RTL_TEXTENCODING_UTF8 );
1086 else
1087 {
1088 Sequence < sal_Int8 > aFileName;
1089 aGrabber.seek( nGenPos + nPos + 30 );
1090 aGrabber.readBytes( aFileName, aEntry.nPathLen );
1091 aEntry.sPath = OUString ( (sal_Char *) aFileName.getArray(),
1092 aFileName.getLength(),
1093 RTL_TEXTENCODING_UTF8 );
1094 aEntry.nPathLen = static_cast< sal_Int16 >(aFileName.getLength());
1095 }
1096
1097 aEntry.nFileDataOffset = nGenPos + nPos + 30 + aEntry.nPathLen + aEntry.nLOCExtraLen;
1098
1099 if ( ( aEntry.nSize || aEntry.nCompressedSize ) && !checkSizeAndCRC( aEntry ) )
1100 {
1101 aEntry.nCrc = 0;
1102 aEntry.nCompressedSize = 0;
1103 aEntry.nSize = 0;
1104 }
1105
1106 if ( aEntries.find( aEntry.sPath ) == aEntries.end() )
1107 aEntries[aEntry.sPath] = aEntry;
1108 }
1109 }
1110 }
1111
1112 nPos += 4;
1113 }
1114 else if (pBuffer[nPos] == 'P' && pBuffer[nPos+1] == 'K' && pBuffer[nPos+2] == 7 && pBuffer[nPos+3] == 8 )
1115 { // This is a data descriptor
1116 sal_Int32 nCompressedSize, nSize, nCRC32;
1117 MemoryByteGrabber aMemGrabber ( Sequence< sal_Int8 >( ((sal_Int8*)(&(pBuffer[nPos+4]))), 12 ) );
1118 aMemGrabber >> nCRC32;
1119 aMemGrabber >> nCompressedSize;
1120 aMemGrabber >> nSize;
1121
1122 for( EntryHash::iterator aIter = aEntries.begin(); aIter != aEntries.end(); aIter++ )
1123 {
1124 ZipEntry aTmp = (*aIter).second;
1125
1126 // this is a broken package, accept this block not only for DEFLATED streams
1127 if( (*aIter).second.nFlag & 8 )
1128 {
1129 sal_Int32 nStreamOffset = nGenPos + nPos - nCompressedSize;
1130 if ( nStreamOffset == (*aIter).second.nFileDataOffset && nCompressedSize > (*aIter).second.nCompressedSize )
1131 {
1132 // only DEFLATED blocks need to be checked
1133 sal_Bool bAcceptBlock = ( (*aIter).second.nMethod == STORED && nCompressedSize == nSize );
1134
1135 if ( !bAcceptBlock )
1136 {
1137 sal_Int32 nRealSize = 0, nRealCRC = 0;
1138 getSizeAndCRC( nStreamOffset, nCompressedSize, &nRealSize, &nRealCRC );
1139 bAcceptBlock = ( nRealSize == nSize && nRealCRC == nCRC32 );
1140 }
1141
1142 if ( bAcceptBlock )
1143 {
1144 (*aIter).second.nCrc = nCRC32;
1145 (*aIter).second.nCompressedSize = nCompressedSize;
1146 (*aIter).second.nSize = nSize;
1147 }
1148 }
1149 #if 0
1150 // for now ignore clearly broken streams
1151 else if( !(*aIter).second.nCompressedSize )
1152 {
1153 (*aIter).second.nCrc = nCRC32;
1154 sal_Int32 nRealStreamSize = nGenPos + nPos - (*aIter).second.nFileDataOffset;
1155 (*aIter).second.nCompressedSize = nGenPos + nPos - (*aIter).second.nFileDataOffset;
1156 (*aIter).second.nSize = nSize;
1157 }
1158 #endif
1159 }
1160 }
1161
1162 nPos += 4;
1163 }
1164 else
1165 nPos++;
1166 }
1167
1168 nGenPos += nPos;
1169 aGrabber.seek( nGenPos );
1170 }
1171
1172 return 0;
1173 }
1174 catch ( IllegalArgumentException& )
1175 {
1176 throw ZipException( OUString( RTL_CONSTASCII_USTRINGPARAM ( "Zip END signature not found!") ), uno::Reference < XInterface > () );
1177 }
1178 catch ( NotConnectedException& )
1179 {
1180 throw ZipException( OUString( RTL_CONSTASCII_USTRINGPARAM ( "Zip END signature not found!") ), uno::Reference < XInterface > () );
1181 }
1182 catch ( BufferSizeExceededException& )
1183 {
1184 throw ZipException( OUString( RTL_CONSTASCII_USTRINGPARAM ( "Zip END signature not found!") ), uno::Reference < XInterface > () );
1185 }
1186 }
1187
checkSizeAndCRC(const ZipEntry & aEntry)1188 sal_Bool ZipFile::checkSizeAndCRC( const ZipEntry& aEntry )
1189 {
1190 ::osl::MutexGuard aGuard( m_aMutex );
1191
1192 sal_Int32 nSize = 0, nCRC = 0;
1193
1194 if( aEntry.nMethod == STORED )
1195 return ( getCRC( aEntry.nFileDataOffset, aEntry.nSize ) == aEntry.nCrc );
1196
1197 getSizeAndCRC( aEntry.nFileDataOffset, aEntry.nCompressedSize, &nSize, &nCRC );
1198 return ( aEntry.nSize == nSize && aEntry.nCrc == nCRC );
1199 }
1200
getCRC(sal_Int32 nFileDataOffset,sal_Int32 nSize)1201 sal_Int32 ZipFile::getCRC( sal_Int32 nFileDataOffset, sal_Int32 nSize )
1202 {
1203 ::osl::MutexGuard aGuard( m_aMutex );
1204
1205 Sequence < sal_Int8 > aBuffer;
1206 CRC32 aCRC;
1207 sal_Int32 nBlockSize = ::std::min( nSize, static_cast< sal_Int32 >( 32000 ) );
1208
1209 aGrabber.seek( nFileDataOffset );
1210 for ( int ind = 0;
1211 aGrabber.readBytes( aBuffer, nBlockSize ) && ind * nBlockSize < nSize;
1212 ind++ )
1213 {
1214 aCRC.updateSegment( aBuffer, 0, ::std::min( nBlockSize, nSize - ind * nBlockSize ) );
1215 }
1216
1217 return aCRC.getValue();
1218 }
1219
getSizeAndCRC(sal_Int32 nFileDataOffset,sal_Int32 nCompressedSize,sal_Int32 * nSize,sal_Int32 * nCRC)1220 void ZipFile::getSizeAndCRC( sal_Int32 nFileDataOffset, sal_Int32 nCompressedSize, sal_Int32 *nSize, sal_Int32 *nCRC )
1221 {
1222 ::osl::MutexGuard aGuard( m_aMutex );
1223
1224 Sequence < sal_Int8 > aBuffer;
1225 CRC32 aCRC;
1226 sal_Int32 nRealSize = 0;
1227 Inflater aInflaterLocal( sal_True );
1228 sal_Int32 nBlockSize = ::std::min( nCompressedSize, static_cast< sal_Int32 >( 32000 ) );
1229
1230 aGrabber.seek( nFileDataOffset );
1231 for ( int ind = 0;
1232 !aInflaterLocal.finished() && aGrabber.readBytes( aBuffer, nBlockSize ) && ind * nBlockSize < nCompressedSize;
1233 ind++ )
1234 {
1235 Sequence < sal_Int8 > aData( nBlockSize );
1236 sal_Int32 nLastInflated = 0;
1237 sal_Int32 nInBlock = 0;
1238
1239 aInflaterLocal.setInput( aBuffer );
1240 do
1241 {
1242 nLastInflated = aInflaterLocal.doInflateSegment( aData, 0, nBlockSize );
1243 aCRC.updateSegment( aData, 0, nLastInflated );
1244 nInBlock += nLastInflated;
1245 } while( !aInflater.finished() && nLastInflated );
1246
1247 nRealSize += nInBlock;
1248 }
1249
1250 *nSize = nRealSize;
1251 *nCRC = aCRC.getValue();
1252 }
1253