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