1 /* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
2 /* nsJARInputStream.cpp
4 * ***** BEGIN LICENSE BLOCK *****
5 * Version: MPL 1.1/GPL 2.0/LGPL 2.1
7 * The contents of this file are subject to the Mozilla Public License Version
8 * 1.1 (the "License"); you may not use this file except in compliance with
9 * the License. You may obtain a copy of the License at
10 * http://www.mozilla.org/MPL/
12 * Software distributed under the License is distributed on an "AS IS" basis,
13 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
14 * for the specific language governing rights and limitations under the
17 * The Original Code is Netscape Communicator source code.
19 * The Initial Developer of the Original Code is
20 * Netscape Communications Corporation.
21 * Portions created by the Initial Developer are Copyright (C) 1999
22 * the Initial Developer. All Rights Reserved.
25 * Mitch Stoltz <mstoltz@netscape.com>
27 * Alternatively, the contents of this file may be used under the terms of
28 * either the GNU General Public License Version 2 or later (the "GPL"), or
29 * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
30 * in which case the provisions of the GPL or the LGPL are applicable instead
31 * of those above. If you wish to allow use of your version of this file only
32 * under the terms of either the GPL or the LGPL, and not to allow others to
33 * use your version of this file under the terms of the MPL, indicate your
34 * decision by deleting the provisions above and replace them with the notice
35 * and other provisions required by the GPL or the LGPL. If you do not delete
36 * the provisions above, a recipient may use your version of this file under
37 * the terms of any one of the MPL, the GPL or the LGPL.
39 * ***** END LICENSE BLOCK ***** */
41 #include "nsJARInputStream.h"
42 #include "zipstruct.h" // defines ZIP compression codes
43 #include "nsZipArchive.h"
45 #include "nsNetUtil.h"
49 /*---------------------------------------------
50 * nsISupports implementation
51 *--------------------------------------------*/
53 NS_IMPL_THREADSAFE_ISUPPORTS1(nsJARInputStream
, nsIInputStream
)
55 /*----------------------------------------------------------
56 * nsJARInputStream implementation
57 *--------------------------------------------------------*/
60 nsJARInputStream::InitFile(nsZipArchive
* aZip
, nsZipItem
*item
, PRFileDesc
*fd
)
64 // Keep the file handle, even on failure
67 NS_ENSURE_ARG_POINTER(aZip
);
68 NS_ENSURE_ARG_POINTER(item
);
69 NS_ENSURE_ARG_POINTER(fd
);
71 // Mark it as closed, in case something fails in initialisation
74 // Keep the important bits of nsZipItem only
77 //-- prepare for the compression type
78 switch (item
->compression
) {
83 mInflate
= (InflateStruct
*) PR_Malloc(sizeof(InflateStruct
));
84 NS_ENSURE_TRUE(mInflate
, NS_ERROR_OUT_OF_MEMORY
);
86 rv
= gZlibInit(&(mInflate
->mZs
));
87 NS_ENSURE_SUCCESS(rv
, NS_ERROR_OUT_OF_MEMORY
);
89 mInflate
->mOutSize
= item
->realsize
;
90 mInflate
->mInCrc
= item
->crc32
;
91 mInflate
->mOutCrc
= crc32(0L, Z_NULL
, 0);
95 return NS_ERROR_NOT_IMPLEMENTED
;
98 //-- Set filepointer to start of item
99 rv
= aZip
->SeekToItem(item
, mFd
);
100 NS_ENSURE_SUCCESS(rv
, NS_ERROR_FILE_CORRUPTED
);
109 nsJARInputStream::InitDirectory(nsZipArchive
* aZip
,
110 const nsACString
& aJarDirSpec
,
113 NS_ENSURE_ARG_POINTER(aZip
);
114 NS_ENSURE_ARG_POINTER(aDir
);
116 // Mark it as closed, in case something fails in initialisation
118 mDirectory
= PR_TRUE
;
120 // Keep the zipReader for getting the actual zipItems
124 // We can get aDir's contents as strings via FindEntries
125 // with the following pattern (see nsIZipReader.findEntries docs)
126 // assuming dirName is properly escaped:
128 // dirName + "?*~" + dirName + "?*/?*"
129 nsDependentCString
dirName(aDir
);
130 mNameLen
= dirName
.Length();
132 // iterate through dirName and copy it to escDirName, escaping chars
133 // which are special at the "top" level of the regexp so FindEntries
135 nsCAutoString escDirName
;
136 const char* curr
= dirName
.BeginReading();
137 const char* end
= dirName
.EndReading();
138 while (curr
!= end
) {
150 escDirName
.Append('\\');
153 escDirName
.Append(*curr
);
157 nsCAutoString pattern
= escDirName
+ NS_LITERAL_CSTRING("?*~") +
158 escDirName
+ NS_LITERAL_CSTRING("?*/?*");
159 rv
= aZip
->FindInit(pattern
.get(), &find
);
160 if (NS_FAILED(rv
)) return rv
;
163 while ((rv
= find
->FindNext( &name
)) == NS_OK
) {
164 // No need to copy string, just share the one from nsZipArchive
165 mArray
.AppendCString(nsDependentCString(name
));
169 if (rv
!= NS_ERROR_FILE_TARGET_DOES_NOT_EXIST
&& NS_FAILED(rv
)) {
170 return NS_ERROR_FAILURE
; // no error translation
176 mBuffer
.AssignLiteral("300: ");
177 mBuffer
.Append(aJarDirSpec
);
178 mBuffer
.AppendLiteral("\n200: filename content-length last-modified file-type\n");
188 nsJARInputStream::Available(PRUint32
*_retval
)
191 return NS_BASE_STREAM_CLOSED
;
194 *_retval
= mBuffer
.Length();
196 *_retval
= mInflate
->mOutSize
- mInflate
->mZs
.total_out
;
198 *_retval
= mInSize
- mCurPos
;
203 nsJARInputStream::Read(char* aBuffer
, PRUint32 aCount
, PRUint32
*aBytesRead
)
205 NS_ENSURE_ARG_POINTER(aBuffer
);
206 NS_ENSURE_ARG_POINTER(aBytesRead
);
215 rv
= ReadDirectory(aBuffer
, aCount
, aBytesRead
);
218 rv
= ContinueInflate(aBuffer
, aCount
, aBytesRead
);
220 PRInt32 bytesRead
= 0;
221 aCount
= PR_MIN(aCount
, mInSize
- mCurPos
);
223 bytesRead
= PR_Read(mFd
, aBuffer
, aCount
);
225 return NS_ERROR_FILE_CORRUPTED
;
226 mCurPos
+= bytesRead
;
227 if (bytesRead
!= aCount
) {
228 // file is truncated or was lying about size, we're done
231 return NS_ERROR_FILE_CORRUPTED
;
234 *aBytesRead
= bytesRead
;
237 // be aggressive about closing!
238 // note that sometimes, we will close mFd before we've finished
239 // deflating - this is because zlib buffers the input
240 // So, don't free the ReadBuf/InflateStruct yet.
241 if (mCurPos
>= mInSize
&& mFd
) {
250 nsJARInputStream::ReadSegments(nsWriteSegmentFun writer
, void * closure
, PRUint32 count
, PRUint32
*_retval
)
252 // don't have a buffer to read from, so this better not be called!
253 NS_NOTREACHED("Consumers should be using Read()!");
254 return NS_ERROR_NOT_IMPLEMENTED
;
258 nsJARInputStream::IsNonBlocking(PRBool
*aNonBlocking
)
260 *aNonBlocking
= PR_FALSE
;
265 nsJARInputStream::Close()
277 nsJARInputStream::ContinueInflate(char* aBuffer
, PRUint32 aCount
,
278 PRUint32
* aBytesRead
)
280 // No need to check the args, ::Read did that, but assert them at least
281 NS_ASSERTION(mInflate
,"inflate data structure missing");
282 NS_ASSERTION(aBuffer
,"aBuffer parameter must not be null");
283 NS_ASSERTION(aBytesRead
,"aBytesRead parameter must not be null");
285 // Keep old total_out count
286 const PRUint32 oldTotalOut
= mInflate
->mZs
.total_out
;
288 // make sure we aren't reading too much
289 mInflate
->mZs
.avail_out
= (mInflate
->mOutSize
-oldTotalOut
> aCount
) ? aCount
: mInflate
->mOutSize
-oldTotalOut
;
290 mInflate
->mZs
.next_out
= (unsigned char*)aBuffer
;
294 while (mInflate
->mZs
.avail_out
> 0 && zerr
== Z_OK
) {
296 if (mInflate
->mZs
.avail_in
== 0 && mCurPos
< mInSize
) {
297 // time to fill the buffer!
298 PRUint32 bytesToRead
= PR_MIN(mInSize
- mCurPos
, ZIP_BUFLEN
);
300 NS_ASSERTION(mFd
, "File handle missing");
301 PRInt32 bytesRead
= PR_Read(mFd
, mInflate
->mReadBuf
, bytesToRead
);
306 mCurPos
+= bytesRead
;
308 // now set the state for 'inflate'
309 mInflate
->mZs
.next_in
= mInflate
->mReadBuf
;
310 mInflate
->mZs
.avail_in
= bytesRead
;
314 zerr
= inflate(&(mInflate
->mZs
), Z_SYNC_FLUSH
);
317 if ((zerr
!= Z_OK
) && (zerr
!= Z_STREAM_END
))
318 return NS_ERROR_FILE_CORRUPTED
;
320 *aBytesRead
= (mInflate
->mZs
.total_out
- oldTotalOut
);
322 // Calculate the CRC on the output
323 mInflate
->mOutCrc
= crc32(mInflate
->mOutCrc
, (unsigned char*)aBuffer
, *aBytesRead
);
325 // be aggressive about ending the inflation
326 // for some reason we don't always get Z_STREAM_END
327 if (zerr
== Z_STREAM_END
|| mInflate
->mZs
.total_out
== mInflate
->mOutSize
) {
328 inflateEnd(&(mInflate
->mZs
));
330 // stop returning valid data as soon as we know we have a bad CRC
331 if (mInflate
->mOutCrc
!= mInflate
->mInCrc
) {
332 // asserting because while this rarely happens, you definitely
333 // want to catch it in debug builds!
335 return NS_ERROR_FILE_CORRUPTED
;
343 nsJARInputStream::ReadDirectory(char* aBuffer
, PRUint32 aCount
, PRUint32
*aBytesRead
)
345 // No need to check the args, ::Read did that, but assert them at least
346 NS_ASSERTION(aBuffer
,"aBuffer parameter must not be null");
347 NS_ASSERTION(aBytesRead
,"aBytesRead parameter must not be null");
349 // If the buffer contains data, copy what's there up to the desired amount
350 PRUint32 numRead
= CopyDataToBuffer(aBuffer
, aCount
);
353 // empty the buffer and start writing directory entry lines to it
356 const PRUint32 arrayLen
= mArray
.Count();
358 for ( ;aCount
> mBuffer
.Length(); mArrPos
++) {
359 // have we consumed all the directory contents?
360 if (arrayLen
<= mArrPos
)
363 const char * entryName
= mArray
[mArrPos
]->get();
364 PRUint32 entryNameLen
= mArray
[mArrPos
]->Length();
365 nsZipItem
* ze
= mZip
->GetItem(entryName
);
366 NS_ENSURE_TRUE(ze
, NS_ERROR_FILE_TARGET_DOES_NOT_EXIST
);
368 // Last Modified Time
370 PR_ExplodeTime(GetModTime(ze
->date
, ze
->time
), PR_GMTParameters
, &tm
);
371 char itemLastModTime
[65];
372 PR_FormatTimeUSEnglish(itemLastModTime
,
373 sizeof(itemLastModTime
),
374 " %a,%%20%d%%20%b%%20%Y%%20%H:%M:%S%%20GMT ",
377 // write a 201: line to the buffer for this item
378 // 200: filename content-length last-modified file-type
379 mBuffer
.AppendLiteral("201: ");
381 // Names must be escaped and relative, so use the pre-calculated length
382 // of the directory name as the offset into the string
383 // NS_EscapeURL adds the escaped URL to the give string buffer
384 NS_EscapeURL(entryName
+ mNameLen
,
385 entryNameLen
- mNameLen
,
386 esc_Minimal
| esc_AlwaysCopy
,
390 mBuffer
.AppendInt(ze
->realsize
, 10);
391 mBuffer
.Append(itemLastModTime
); // starts/ends with ' '
393 mBuffer
.AppendLiteral("DIRECTORY\n");
395 mBuffer
.AppendLiteral("FILE\n");
398 // Copy up to the desired amount of data to buffer
399 numRead
+= CopyDataToBuffer(aBuffer
, aCount
);
402 *aBytesRead
= numRead
;
407 nsJARInputStream::CopyDataToBuffer(char* &aBuffer
, PRUint32
&aCount
)
409 const PRUint32 writeLength
= PR_MIN(aCount
, mBuffer
.Length() - mCurPos
);
411 if (writeLength
> 0) {
412 memcpy(aBuffer
, mBuffer
.get() + mCurPos
, writeLength
);
413 mCurPos
+= writeLength
;
414 aCount
-= writeLength
;
415 aBuffer
+= writeLength
;
418 // return number of bytes copied to the buffer so the
419 // Read method can return the number of bytes copied