b=450088 backing out (new reftest failed)
[wine-gecko.git] / modules / libjar / nsJARInputStream.cpp
blob029ae23def3437b7628970f3b9a2f6d14f2c7e38
1 /* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
2 /* nsJARInputStream.cpp
3 *
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
15 * License.
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.
24 * Contributor(s):
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"
46 #include "nsEscape.h"
47 #include "nsIFile.h"
49 /*---------------------------------------------
50 * nsISupports implementation
51 *--------------------------------------------*/
53 NS_IMPL_THREADSAFE_ISUPPORTS1(nsJARInputStream, nsIInputStream)
55 /*----------------------------------------------------------
56 * nsJARInputStream implementation
57 *--------------------------------------------------------*/
59 nsresult
60 nsJARInputStream::InitFile(nsZipArchive* aZip, nsZipItem *item, PRFileDesc *fd)
62 nsresult rv;
64 // Keep the file handle, even on failure
65 mFd = fd;
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
72 mClosed = PR_TRUE;
74 // Keep the important bits of nsZipItem only
75 mInSize = item->size;
77 //-- prepare for the compression type
78 switch (item->compression) {
79 case STORED:
80 break;
82 case DEFLATED:
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);
92 break;
94 default:
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);
102 // Open for reading
103 mClosed = PR_FALSE;
104 mCurPos = 0;
105 return NS_OK;
108 nsresult
109 nsJARInputStream::InitDirectory(nsZipArchive* aZip,
110 const nsACString& aJarDirSpec,
111 const char* aDir)
113 NS_ENSURE_ARG_POINTER(aZip);
114 NS_ENSURE_ARG_POINTER(aDir);
116 // Mark it as closed, in case something fails in initialisation
117 mClosed = PR_TRUE;
118 mDirectory = PR_TRUE;
120 // Keep the zipReader for getting the actual zipItems
121 mZip = aZip;
122 nsZipFind *find;
123 nsresult rv;
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
134 // works correctly
135 nsCAutoString escDirName;
136 const char* curr = dirName.BeginReading();
137 const char* end = dirName.EndReading();
138 while (curr != end) {
139 switch (*curr) {
140 case '*':
141 case '?':
142 case '$':
143 case '[':
144 case ']':
145 case '^':
146 case '~':
147 case '(':
148 case ')':
149 case '\\':
150 escDirName.Append('\\');
151 // fall through
152 default:
153 escDirName.Append(*curr);
155 ++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;
162 const char *name;
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));
167 delete find;
169 if (rv != NS_ERROR_FILE_TARGET_DOES_NOT_EXIST && NS_FAILED(rv)) {
170 return NS_ERROR_FAILURE; // no error translation
173 // Sort it
174 mArray.Sort();
176 mBuffer.AssignLiteral("300: ");
177 mBuffer.Append(aJarDirSpec);
178 mBuffer.AppendLiteral("\n200: filename content-length last-modified file-type\n");
180 // Open for reading
181 mClosed = PR_FALSE;
182 mCurPos = 0;
183 mArrPos = 0;
184 return NS_OK;
187 NS_IMETHODIMP
188 nsJARInputStream::Available(PRUint32 *_retval)
190 if (mClosed)
191 return NS_BASE_STREAM_CLOSED;
193 if (mDirectory)
194 *_retval = mBuffer.Length();
195 else if (mInflate)
196 *_retval = mInflate->mOutSize - mInflate->mZs.total_out;
197 else
198 *_retval = mInSize - mCurPos;
199 return NS_OK;
202 NS_IMETHODIMP
203 nsJARInputStream::Read(char* aBuffer, PRUint32 aCount, PRUint32 *aBytesRead)
205 NS_ENSURE_ARG_POINTER(aBuffer);
206 NS_ENSURE_ARG_POINTER(aBytesRead);
208 *aBytesRead = 0;
210 nsresult rv = NS_OK;
211 if (mClosed)
212 return rv;
214 if (mDirectory) {
215 rv = ReadDirectory(aBuffer, aCount, aBytesRead);
216 } else {
217 if (mInflate) {
218 rv = ContinueInflate(aBuffer, aCount, aBytesRead);
219 } else {
220 PRInt32 bytesRead = 0;
221 aCount = PR_MIN(aCount, mInSize - mCurPos);
222 if (aCount) {
223 bytesRead = PR_Read(mFd, aBuffer, aCount);
224 if (bytesRead < 0)
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
229 PR_Close(mFd);
230 mFd = nsnull;
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) {
242 PR_Close(mFd);
243 mFd = nsnull;
246 return rv;
249 NS_IMETHODIMP
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;
257 NS_IMETHODIMP
258 nsJARInputStream::IsNonBlocking(PRBool *aNonBlocking)
260 *aNonBlocking = PR_FALSE;
261 return NS_OK;
264 NS_IMETHODIMP
265 nsJARInputStream::Close()
267 PR_FREEIF(mInflate);
268 if (mFd) {
269 PR_Close(mFd);
270 mFd = nsnull;
272 mClosed = PR_TRUE;
273 return NS_OK;
276 nsresult
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;
292 int zerr = Z_OK;
293 //-- inflate loop
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);
302 if (bytesRead < 0) {
303 zerr = Z_ERRNO;
304 break;
306 mCurPos += bytesRead;
308 // now set the state for 'inflate'
309 mInflate->mZs.next_in = mInflate->mReadBuf;
310 mInflate->mZs.avail_in = bytesRead;
313 // now inflate
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!
334 NS_NOTREACHED(0);
335 return NS_ERROR_FILE_CORRUPTED;
339 return NS_OK;
342 nsresult
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);
352 if (aCount > 0) {
353 // empty the buffer and start writing directory entry lines to it
354 mBuffer.Truncate();
355 mCurPos = 0;
356 const PRUint32 arrayLen = mArray.Count();
358 for ( ;aCount > mBuffer.Length(); mArrPos++) {
359 // have we consumed all the directory contents?
360 if (arrayLen <= mArrPos)
361 break;
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
369 PRExplodedTime tm;
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 ",
375 &tm);
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,
387 mBuffer);
389 mBuffer.Append(' ');
390 mBuffer.AppendInt(ze->realsize, 10);
391 mBuffer.Append(itemLastModTime); // starts/ends with ' '
392 if (ze->isDirectory)
393 mBuffer.AppendLiteral("DIRECTORY\n");
394 else
395 mBuffer.AppendLiteral("FILE\n");
398 // Copy up to the desired amount of data to buffer
399 numRead += CopyDataToBuffer(aBuffer, aCount);
402 *aBytesRead = numRead;
403 return NS_OK;
406 PRUint32
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
420 return writeLength;