merge the formfield patch from ooo-build
[ooovba.git] / package / source / zipapi / XUnbufferedStream.cxx
blob0328837d0f5099c43b155f601b537251a4f5c430
1 /*************************************************************************
3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4 *
5 * Copyright 2008 by Sun Microsystems, Inc.
7 * OpenOffice.org - a multi-platform office productivity suite
9 * $RCSfile: XUnbufferedStream.cxx,v $
10 * $Revision: 1.14 $
12 * This file is part of OpenOffice.org.
14 * OpenOffice.org is free software: you can redistribute it and/or modify
15 * it under the terms of the GNU Lesser General Public License version 3
16 * only, as published by the Free Software Foundation.
18 * OpenOffice.org is distributed in the hope that it will be useful,
19 * but WITHOUT ANY WARRANTY; without even the implied warranty of
20 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 * GNU Lesser General Public License version 3 for more details
22 * (a copy is included in the LICENSE file that accompanied this code).
24 * You should have received a copy of the GNU Lesser General Public License
25 * version 3 along with OpenOffice.org. If not, see
26 * <http://www.openoffice.org/license.html>
27 * for a copy of the LGPLv3 License.
29 ************************************************************************/
31 // MARKER(update_precomp.py): autogen include statement, do not remove
32 #include "precompiled_package.hxx"
33 #include <XUnbufferedStream.hxx>
34 #include <EncryptionData.hxx>
35 #include <com/sun/star/packages/zip/ZipConstants.hpp>
36 #include <com/sun/star/packages/zip/ZipIOException.hpp>
37 #include <PackageConstants.hxx>
38 #include <rtl/cipher.h>
39 #include <ZipFile.hxx>
40 #include <EncryptedDataHeader.hxx>
41 #include <algorithm>
42 #include <string.h>
44 #include <osl/mutex.hxx>
46 #if 0
47 // for debugging purposes here
48 #include <com/sun/star/ucb/XSimpleFileAccess.hpp>
49 #include <comphelper/processfactory.hxx>
50 using namespace ::com::sun::star;
51 #endif
53 using namespace com::sun::star::packages::zip::ZipConstants;
54 using namespace com::sun::star::io;
55 using namespace com::sun::star::uno;
56 using com::sun::star::lang::IllegalArgumentException;
57 using com::sun::star::packages::zip::ZipIOException;
58 using ::rtl::OUString;
60 XUnbufferedStream::XUnbufferedStream( SotMutexHolderRef aMutexHolder,
61 ZipEntry & rEntry,
62 Reference < XInputStream > xNewZipStream,
63 const vos::ORef < EncryptionData > &rData,
64 sal_Int8 nStreamMode,
65 sal_Bool bIsEncrypted,
66 const ::rtl::OUString& aMediaType,
67 sal_Bool bRecoveryMode )
68 : maMutexHolder( aMutexHolder.Is() ? aMutexHolder : SotMutexHolderRef( new SotMutexHolder ) )
69 , mxZipStream ( xNewZipStream )
70 , mxZipSeek ( xNewZipStream, UNO_QUERY )
71 , maEntry ( rEntry )
72 , mxData ( rData )
73 , maCipher ( NULL )
74 , maInflater ( sal_True )
75 , mbRawStream ( nStreamMode == UNBUFF_STREAM_RAW || nStreamMode == UNBUFF_STREAM_WRAPPEDRAW )
76 , mbWrappedRaw ( nStreamMode == UNBUFF_STREAM_WRAPPEDRAW )
77 , mbFinished ( sal_False )
78 , mnHeaderToRead ( 0 )
79 , mnZipCurrent ( 0 )
80 , mnZipEnd ( 0 )
81 , mnZipSize ( 0 )
82 , mnMyCurrent ( 0 )
83 , mbCheckCRC( !bRecoveryMode )
85 mnZipCurrent = maEntry.nOffset;
86 if ( mbRawStream )
88 mnZipSize = maEntry.nMethod == DEFLATED ? maEntry.nCompressedSize : maEntry.nSize;
89 mnZipEnd = maEntry.nOffset + mnZipSize;
91 else
93 mnZipSize = maEntry.nSize;
94 mnZipEnd = maEntry.nMethod == DEFLATED ? maEntry.nOffset + maEntry.nCompressedSize : maEntry.nOffset + maEntry.nSize;
96 sal_Bool bHaveEncryptData = ( !rData.isEmpty() && rData->aSalt.getLength() && rData->aInitVector.getLength() && rData->nIterationCount != 0 ) ? sal_True : sal_False;
97 sal_Bool bMustDecrypt = ( nStreamMode == UNBUFF_STREAM_DATA && bHaveEncryptData && bIsEncrypted ) ? sal_True : sal_False;
99 if ( bMustDecrypt )
100 ZipFile::StaticGetCipher ( rData, maCipher, sal_True );
101 if ( bHaveEncryptData && mbWrappedRaw && bIsEncrypted )
103 // if we have the data needed to decrypt it, but didn't want it decrypted (or
104 // we couldn't decrypt it due to wrong password), then we prepend this
105 // data to the stream
107 // Make a buffer big enough to hold both the header and the data itself
108 maHeader.realloc ( n_ConstHeaderSize +
109 rData->aInitVector.getLength() +
110 rData->aSalt.getLength() +
111 rData->aDigest.getLength() +
112 aMediaType.getLength() * sizeof( sal_Unicode ) );
113 sal_Int8 * pHeader = maHeader.getArray();
114 ZipFile::StaticFillHeader ( rData, rEntry.nSize, aMediaType, pHeader );
115 mnHeaderToRead = static_cast < sal_Int16 > ( maHeader.getLength() );
119 // allows to read package raw stream
120 XUnbufferedStream::XUnbufferedStream( const Reference < XInputStream >& xRawStream,
121 const vos::ORef < EncryptionData > &rData )
122 : maMutexHolder( new SotMutexHolder )
123 , mxZipStream ( xRawStream )
124 , mxZipSeek ( xRawStream, UNO_QUERY )
125 , mxData ( rData )
126 , maCipher ( NULL )
127 , maInflater ( sal_True )
128 , mbRawStream ( sal_False )
129 , mbWrappedRaw ( sal_False )
130 , mbFinished ( sal_False )
131 , mnHeaderToRead ( 0 )
132 , mnZipCurrent ( 0 )
133 , mnZipEnd ( 0 )
134 , mnZipSize ( 0 )
135 , mnMyCurrent ( 0 )
136 , mbCheckCRC( sal_False )
138 // for this scenario maEntry is not set !!!
139 OSL_ENSURE( mxZipSeek.is(), "The stream must be seekable!\n" );
141 // skip raw header, it must be already parsed to rData
142 mnZipCurrent = n_ConstHeaderSize + rData->aInitVector.getLength() +
143 rData->aSalt.getLength() + rData->aDigest.getLength();
145 try {
146 if ( mxZipSeek.is() )
147 mnZipSize = mxZipSeek->getLength();
148 } catch( Exception& )
150 // in case of problem the size will stay set to 0
153 mnZipEnd = mnZipCurrent + mnZipSize;
155 ZipFile::StaticGetCipher ( rData, maCipher, sal_True );
158 XUnbufferedStream::~XUnbufferedStream()
160 if ( maCipher )
161 rtl_cipher_destroy ( maCipher );
164 sal_Int32 SAL_CALL XUnbufferedStream::readBytes( Sequence< sal_Int8 >& aData, sal_Int32 nBytesToRead )
165 throw( NotConnectedException, BufferSizeExceededException, IOException, RuntimeException)
167 ::osl::MutexGuard aGuard( maMutexHolder->GetMutex() );
169 sal_Int32 nRequestedBytes = nBytesToRead;
170 OSL_ENSURE( !mnHeaderToRead || mbWrappedRaw, "Only encrypted raw stream can be provided with header!" );
171 if ( mnMyCurrent + nRequestedBytes > mnZipSize + maHeader.getLength() )
172 nRequestedBytes = static_cast < sal_Int32 > ( mnZipSize + maHeader.getLength() - mnMyCurrent );
174 sal_Int32 nRead = 0, nLastRead = 0, nTotal = 0;
175 aData.realloc ( nRequestedBytes );
176 if ( nRequestedBytes )
178 if ( mbRawStream )
180 sal_Int64 nDiff = mnZipEnd - mnZipCurrent;
182 if ( mbWrappedRaw && mnHeaderToRead )
184 sal_Int16 nHeadRead = static_cast< sal_Int16 >(( nRequestedBytes > mnHeaderToRead ?
185 mnHeaderToRead : nRequestedBytes ));
186 memcpy ( aData.getArray(), maHeader.getConstArray() + maHeader.getLength() - mnHeaderToRead, nHeadRead );
187 mnHeaderToRead = mnHeaderToRead - nHeadRead;
189 if ( nHeadRead < nRequestedBytes )
191 sal_Int32 nToRead = nRequestedBytes - nHeadRead;
192 nToRead = ( nDiff < nToRead ) ? sal::static_int_cast< sal_Int32 >( nDiff ) : nToRead;
194 Sequence< sal_Int8 > aPureData( nToRead );
195 mxZipSeek->seek ( mnZipCurrent );
196 nRead = mxZipStream->readBytes ( aPureData, nToRead );
197 mnZipCurrent += nRead;
199 aPureData.realloc( nRead );
200 if ( mbCheckCRC )
201 maCRC.update( aPureData );
203 aData.realloc( nHeadRead + nRead );
205 sal_Int8* pPureBuffer = aPureData.getArray();
206 sal_Int8* pBuffer = aData.getArray();
207 for ( sal_Int32 nInd = 0; nInd < nRead; nInd++ )
208 pBuffer[ nHeadRead + nInd ] = pPureBuffer[ nInd ];
211 nRead += nHeadRead;
213 else
215 mxZipSeek->seek ( mnZipCurrent );
217 nRead = mxZipStream->readBytes (
218 aData,
219 static_cast < sal_Int32 > ( nDiff < nRequestedBytes ? nDiff : nRequestedBytes ) );
221 mnZipCurrent += nRead;
223 aData.realloc( nRead );
224 if ( mbWrappedRaw && mbCheckCRC )
225 maCRC.update( aData );
228 else
230 while ( 0 == ( nLastRead = maInflater.doInflateSegment( aData, nRead, aData.getLength() - nRead ) ) ||
231 ( nRead + nLastRead != nRequestedBytes && mnZipCurrent < mnZipEnd ) )
233 nRead += nLastRead;
235 if ( nRead > nRequestedBytes )
236 throw RuntimeException(
237 OUString( RTL_CONSTASCII_USTRINGPARAM( "Should not be possible to read more then requested!" ) ),
238 Reference< XInterface >() );
240 if ( maInflater.finished() || maInflater.getLastInflateError() )
241 throw ZipIOException( OUString( RTL_CONSTASCII_USTRINGPARAM( "The stream seems to be broken!" ) ),
242 Reference< XInterface >() );
244 if ( maInflater.needsDictionary() )
245 throw ZipIOException( OUString( RTL_CONSTASCII_USTRINGPARAM( "Dictionaries are not supported!" ) ),
246 Reference< XInterface >() );
248 sal_Int32 nDiff = static_cast < sal_Int32 > ( mnZipEnd - mnZipCurrent );
249 if ( nDiff > 0 )
251 mxZipSeek->seek ( mnZipCurrent );
252 sal_Int32 nToRead = std::min ( nDiff, std::max ( nRequestedBytes, static_cast< sal_Int32 >( 8192 ) ) );
253 sal_Int32 nZipRead = mxZipStream->readBytes ( maCompBuffer, nToRead );
254 if ( nZipRead < nToRead )
255 throw ZipIOException( OUString( RTL_CONSTASCII_USTRINGPARAM( "No expected data!" ) ),
256 Reference< XInterface >() );
258 mnZipCurrent += nZipRead;
259 // maCompBuffer now has the data, check if we need to decrypt
260 // before passing to the Inflater
261 if ( maCipher )
263 if ( mbCheckCRC )
264 maCRC.update( maCompBuffer );
266 Sequence < sal_Int8 > aCryptBuffer ( nZipRead );
267 rtlCipherError aResult =
268 rtl_cipher_decode ( maCipher,
269 maCompBuffer.getConstArray(),
270 nZipRead,
271 reinterpret_cast < sal_uInt8 * > (aCryptBuffer.getArray()),
272 nZipRead);
273 if( aResult != rtl_Cipher_E_None ) {
274 OSL_ASSERT (aResult == rtl_Cipher_E_None);
276 maCompBuffer = aCryptBuffer; // Now it holds the decrypted data
279 maInflater.setInput ( maCompBuffer );
281 else
283 throw ZipIOException( OUString( RTL_CONSTASCII_USTRINGPARAM( "The stream seems to be broken!" ) ),
284 Reference< XInterface >() );
289 mnMyCurrent += nRead + nLastRead;
290 nTotal = nRead + nLastRead;
291 if ( nTotal < nRequestedBytes)
292 aData.realloc ( nTotal );
294 if ( mbCheckCRC && ( !mbRawStream || mbWrappedRaw ) )
296 if ( !maCipher && !mbWrappedRaw )
297 maCRC.update( aData );
299 #if 0
300 // for debugging purposes here
301 if ( mbWrappedRaw )
303 if ( 0 )
305 uno::Reference< lang::XMultiServiceFactory > xFactory = comphelper::getProcessServiceFactory();
306 uno::Reference< ucb::XSimpleFileAccess > xAccess( xFactory->createInstance( ::rtl::OUString::createFromAscii( "com.sun.star.ucb.SimpleFileAccess" ) ), uno::UNO_QUERY );
307 uno::Reference< io::XOutputStream > xOut = xAccess->openFileWrite( ::rtl::OUString::createFromAscii( "file:///d:/777/Encrypted/picture" ) );
308 xOut->writeBytes( aData );
309 xOut->closeOutput();
312 #endif
314 if ( mnZipSize + maHeader.getLength() == mnMyCurrent && maCRC.getValue() != maEntry.nCrc )
315 throw ZipIOException( OUString( RTL_CONSTASCII_USTRINGPARAM( "The stream seems to be broken!" ) ),
316 Reference< XInterface >() );
320 return nTotal;
323 sal_Int32 SAL_CALL XUnbufferedStream::readSomeBytes( Sequence< sal_Int8 >& aData, sal_Int32 nMaxBytesToRead )
324 throw( NotConnectedException, BufferSizeExceededException, IOException, RuntimeException)
326 return readBytes ( aData, nMaxBytesToRead );
328 void SAL_CALL XUnbufferedStream::skipBytes( sal_Int32 nBytesToSkip )
329 throw( NotConnectedException, BufferSizeExceededException, IOException, RuntimeException)
331 if ( nBytesToSkip )
333 Sequence < sal_Int8 > aSequence ( nBytesToSkip );
334 readBytes ( aSequence, nBytesToSkip );
338 sal_Int32 SAL_CALL XUnbufferedStream::available( )
339 throw( NotConnectedException, IOException, RuntimeException)
341 return static_cast < sal_Int32 > ( mnZipSize - mnMyCurrent );
344 void SAL_CALL XUnbufferedStream::closeInput( )
345 throw( NotConnectedException, IOException, RuntimeException)
349 void SAL_CALL XUnbufferedStream::seek( sal_Int64 location )
350 throw( IllegalArgumentException, IOException, RuntimeException)
353 sal_Int64 SAL_CALL XUnbufferedStream::getPosition( )
354 throw(IOException, RuntimeException)
356 return mnMyCurrent;
358 sal_Int64 SAL_CALL XUnbufferedStream::getLength( )
359 throw(IOException, RuntimeException)
361 return mnZipSize;