LCOV - code coverage report
Current view: directory - netwerk/protocol/file - nsFileChannel.cpp (source / functions) Found Hit Coverage
Test: app.info Lines: 162 128 79.0 %
Date: 2012-04-21 Functions: 25 23 92.0 %

       1                 : /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
       2                 : /* vim:set ts=2 sw=2 sts=2 et cin: */
       3                 : /* ***** BEGIN LICENSE BLOCK *****
       4                 :  * Version: MPL 1.1/GPL 2.0/LGPL 2.1
       5                 :  *
       6                 :  * The contents of this file are subject to the Mozilla Public License Version
       7                 :  * 1.1 (the "License"); you may not use this file except in compliance with
       8                 :  * the License. You may obtain a copy of the License at
       9                 :  * http://www.mozilla.org/MPL/
      10                 :  *
      11                 :  * Software distributed under the License is distributed on an "AS IS" basis,
      12                 :  * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
      13                 :  * for the specific language governing rights and limitations under the
      14                 :  * License.
      15                 :  *
      16                 :  * The Original Code is mozilla.org code.
      17                 :  *
      18                 :  * The Initial Developer of the Original Code is
      19                 :  * Netscape Communications Corporation.
      20                 :  * Portions created by the Initial Developer are Copyright (C) 1998
      21                 :  * the Initial Developer. All Rights Reserved.
      22                 :  *
      23                 :  * Contributor(s):
      24                 :  *  Darin Fisher <darin@meer.net>
      25                 :  *
      26                 :  * Alternatively, the contents of this file may be used under the terms of
      27                 :  * either the GNU General Public License Version 2 or later (the "GPL"), or
      28                 :  * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
      29                 :  * in which case the provisions of the GPL or the LGPL are applicable instead
      30                 :  * of those above. If you wish to allow use of your version of this file only
      31                 :  * under the terms of either the GPL or the LGPL, and not to allow others to
      32                 :  * use your version of this file under the terms of the MPL, indicate your
      33                 :  * decision by deleting the provisions above and replace them with the notice
      34                 :  * and other provisions required by the GPL or the LGPL. If you do not delete
      35                 :  * the provisions above, a recipient may use your version of this file under
      36                 :  * the terms of any one of the MPL, the GPL or the LGPL.
      37                 :  *
      38                 :  * ***** END LICENSE BLOCK ***** */
      39                 : 
      40                 : #include "nsIOService.h"
      41                 : #include "nsFileChannel.h"
      42                 : #include "nsBaseContentStream.h"
      43                 : #include "nsDirectoryIndexStream.h"
      44                 : #include "nsThreadUtils.h"
      45                 : #include "nsTransportUtils.h"
      46                 : #include "nsStreamUtils.h"
      47                 : #include "nsURLHelper.h"
      48                 : #include "nsMimeTypes.h"
      49                 : #include "nsNetUtil.h"
      50                 : #include "nsProxyRelease.h"
      51                 : #include "nsAutoPtr.h"
      52                 : #include "nsStandardURL.h"
      53                 : 
      54                 : #include "nsIFileURL.h"
      55                 : #include "nsIMIMEService.h"
      56                 : 
      57                 : //-----------------------------------------------------------------------------
      58                 : 
      59               4 : class nsFileCopyEvent : public nsRunnable {
      60                 : public:
      61               1 :   nsFileCopyEvent(nsIOutputStream *dest, nsIInputStream *source, PRInt64 len)
      62                 :     : mDest(dest)
      63                 :     , mSource(source)
      64                 :     , mLen(len)
      65                 :     , mStatus(NS_OK)
      66               1 :     , mInterruptStatus(NS_OK) {
      67               1 :   }
      68                 : 
      69                 :   // Read the current status of the file copy operation.
      70               1 :   nsresult Status() { return mStatus; }
      71                 :   
      72                 :   // Call this method to perform the file copy synchronously.
      73                 :   void DoCopy();
      74                 : 
      75                 :   // Call this method to perform the file copy on a background thread.  The
      76                 :   // callback is dispatched when the file copy completes.
      77                 :   nsresult Dispatch(nsIRunnable *callback,
      78                 :                     nsITransportEventSink *sink,
      79                 :                     nsIEventTarget *target);
      80                 : 
      81                 :   // Call this method to interrupt a file copy operation that is occuring on
      82                 :   // a background thread.  The status parameter passed to this function must
      83                 :   // be a failure code and is set as the status of this file copy operation.
      84                 :   void Interrupt(nsresult status) {
      85                 :     NS_ASSERTION(NS_FAILED(status), "must be a failure code");
      86                 :     mInterruptStatus = status;
      87                 :   }
      88                 : 
      89               1 :   NS_IMETHOD Run() {
      90               1 :     DoCopy();
      91               1 :     return NS_OK;
      92                 :   }
      93                 : 
      94                 : private:
      95                 :   nsCOMPtr<nsIEventTarget> mCallbackTarget;
      96                 :   nsCOMPtr<nsIRunnable> mCallback;
      97                 :   nsCOMPtr<nsITransportEventSink> mSink;
      98                 :   nsCOMPtr<nsIOutputStream> mDest;
      99                 :   nsCOMPtr<nsIInputStream> mSource;
     100                 :   PRInt64 mLen;
     101                 :   nsresult mStatus;           // modified on i/o thread only
     102                 :   nsresult mInterruptStatus;  // modified on main thread only
     103                 : };
     104                 : 
     105                 : void
     106               1 : nsFileCopyEvent::DoCopy()
     107                 : {
     108                 :   // We'll copy in chunks this large by default.  This size affects how
     109                 :   // frequently we'll check for interrupts.
     110               1 :   const PRInt32 chunk = nsIOService::gDefaultSegmentSize * nsIOService::gDefaultSegmentCount;
     111                 : 
     112               1 :   nsresult rv = NS_OK;
     113                 : 
     114               1 :   PRInt64 len = mLen, progress = 0;
     115               3 :   while (len) {
     116                 :     // If we've been interrupted, then stop copying.
     117               1 :     rv = mInterruptStatus;
     118               1 :     if (NS_FAILED(rv))
     119               0 :       break;
     120                 : 
     121               1 :     PRInt32 num = NS_MIN((PRInt32) len, chunk);
     122                 : 
     123                 :     PRUint32 result;
     124               1 :     rv = mSource->ReadSegments(NS_CopySegmentToStream, mDest, num, &result);
     125               1 :     if (NS_FAILED(rv))
     126               0 :       break;
     127               1 :     if (result != (PRUint32) num) {
     128               0 :       rv = NS_ERROR_FILE_DISK_FULL;  // stopped prematurely (out of disk space)
     129               0 :       break;
     130                 :     }
     131                 : 
     132                 :     // Dispatch progress notification
     133               1 :     if (mSink) {
     134               1 :       progress += num;
     135               1 :       mSink->OnTransportStatus(nsnull, nsITransport::STATUS_WRITING, progress,
     136               1 :                                mLen);
     137                 :     }
     138                 :                                
     139               1 :     len -= num;
     140                 :   }
     141                 : 
     142               1 :   if (NS_FAILED(rv))
     143               0 :     mStatus = rv;
     144                 : 
     145                 :   // Close the output stream before notifying our callback so that others may
     146                 :   // freely "play" with the file.
     147               1 :   mDest->Close();
     148                 : 
     149                 :   // Notify completion
     150               1 :   if (mCallback) {
     151               1 :     mCallbackTarget->Dispatch(mCallback, NS_DISPATCH_NORMAL);
     152                 : 
     153                 :     // Release the callback on the target thread to avoid destroying stuff on
     154                 :     // the wrong thread.
     155               1 :     nsIRunnable *doomed = nsnull;
     156               1 :     mCallback.swap(doomed);
     157               1 :     NS_ProxyRelease(mCallbackTarget, doomed);
     158                 :   }
     159               1 : }
     160                 : 
     161                 : nsresult
     162               1 : nsFileCopyEvent::Dispatch(nsIRunnable *callback,
     163                 :                           nsITransportEventSink *sink,
     164                 :                           nsIEventTarget *target)
     165                 : {
     166                 :   // Use the supplied event target for all asynchronous operations.
     167                 : 
     168               1 :   mCallback = callback;
     169               1 :   mCallbackTarget = target;
     170                 : 
     171                 :   // Build a coalescing proxy for progress events
     172               1 :   nsresult rv = net_NewTransportEventSinkProxy(getter_AddRefs(mSink), sink,
     173               1 :                                                target, true);
     174               1 :   if (NS_FAILED(rv))
     175               0 :     return rv;
     176                 : 
     177                 :   // Dispatch ourselves to I/O thread pool...
     178                 :   nsCOMPtr<nsIEventTarget> pool =
     179               2 :       do_GetService(NS_STREAMTRANSPORTSERVICE_CONTRACTID, &rv);
     180               1 :   if (NS_FAILED(rv))
     181               0 :     return rv;
     182                 : 
     183               1 :   return pool->Dispatch(this, NS_DISPATCH_NORMAL);
     184                 : }
     185                 : 
     186                 : //-----------------------------------------------------------------------------
     187                 : 
     188                 : // This is a dummy input stream that when read, performs the file copy.  The
     189                 : // copy happens on a background thread via mCopyEvent.
     190                 : 
     191               4 : class nsFileUploadContentStream : public nsBaseContentStream {
     192                 : public:
     193                 :   NS_DECL_ISUPPORTS_INHERITED
     194                 : 
     195               1 :   nsFileUploadContentStream(bool nonBlocking,
     196                 :                             nsIOutputStream *dest,
     197                 :                             nsIInputStream *source,
     198                 :                             PRInt64 len,
     199                 :                             nsITransportEventSink *sink)
     200                 :     : nsBaseContentStream(nonBlocking)
     201               1 :     , mCopyEvent(new nsFileCopyEvent(dest, source, len))
     202               3 :     , mSink(sink) {
     203               1 :   }
     204                 : 
     205               1 :   bool IsInitialized() {
     206               1 :     return mCopyEvent != nsnull;
     207                 :   }
     208                 : 
     209                 :   NS_IMETHODIMP ReadSegments(nsWriteSegmentFun fun, void *closure,
     210                 :                              PRUint32 count, PRUint32 *result);
     211                 :   NS_IMETHODIMP AsyncWait(nsIInputStreamCallback *callback, PRUint32 flags,
     212                 :                           PRUint32 count, nsIEventTarget *target);
     213                 : 
     214                 : private:
     215                 :   void OnCopyComplete();
     216                 : 
     217                 :   nsRefPtr<nsFileCopyEvent> mCopyEvent;
     218                 :   nsCOMPtr<nsITransportEventSink> mSink;
     219                 : };
     220                 : 
     221              23 : NS_IMPL_ISUPPORTS_INHERITED0(nsFileUploadContentStream,
     222                 :                              nsBaseContentStream)
     223                 : 
     224                 : NS_IMETHODIMP
     225               0 : nsFileUploadContentStream::ReadSegments(nsWriteSegmentFun fun, void *closure,
     226                 :                                         PRUint32 count, PRUint32 *result)
     227                 : {
     228               0 :   *result = 0;  // nothing is ever actually read from this stream
     229                 : 
     230               0 :   if (IsClosed())
     231               0 :     return NS_OK;
     232                 : 
     233               0 :   if (IsNonBlocking()) {
     234                 :     // Inform the caller that they will have to wait for the copy operation to
     235                 :     // complete asynchronously.  We'll kick of the copy operation once they
     236                 :     // call AsyncWait.
     237               0 :     return NS_BASE_STREAM_WOULD_BLOCK;  
     238                 :   }
     239                 : 
     240                 :   // Perform copy synchronously, and then close out the stream.
     241               0 :   mCopyEvent->DoCopy();
     242               0 :   nsresult status = mCopyEvent->Status();
     243               0 :   CloseWithStatus(NS_FAILED(status) ? status : NS_BASE_STREAM_CLOSED);
     244               0 :   return status;
     245                 : }
     246                 : 
     247                 : NS_IMETHODIMP
     248               1 : nsFileUploadContentStream::AsyncWait(nsIInputStreamCallback *callback,
     249                 :                                      PRUint32 flags, PRUint32 count,
     250                 :                                      nsIEventTarget *target)
     251                 : {
     252               1 :   nsresult rv = nsBaseContentStream::AsyncWait(callback, flags, count, target);
     253               1 :   if (NS_FAILED(rv) || IsClosed())
     254               0 :     return rv;
     255                 : 
     256               1 :   if (IsNonBlocking()) {
     257                 :     nsCOMPtr<nsIRunnable> callback =
     258               2 :       NS_NewRunnableMethod(this, &nsFileUploadContentStream::OnCopyComplete);
     259               1 :     mCopyEvent->Dispatch(callback, mSink, target);
     260                 :   }
     261                 : 
     262               1 :   return NS_OK;
     263                 : }
     264                 : 
     265                 : void
     266               1 : nsFileUploadContentStream::OnCopyComplete()
     267                 : {
     268                 :   // This method is being called to indicate that we are done copying.
     269               1 :   nsresult status = mCopyEvent->Status();
     270                 : 
     271               1 :   CloseWithStatus(NS_FAILED(status) ? status : NS_BASE_STREAM_CLOSED);
     272               1 : }
     273                 : 
     274                 : //-----------------------------------------------------------------------------
     275                 : 
     276                 : nsresult
     277            2899 : nsFileChannel::MakeFileInputStream(nsIFile *file,
     278                 :                                    nsCOMPtr<nsIInputStream> &stream,
     279                 :                                    nsCString &contentType)
     280                 : {
     281                 :   // we accept that this might result in a disk hit to stat the file
     282                 :   bool isDir;
     283            2899 :   nsresult rv = file->IsDirectory(&isDir);
     284            2899 :   if (NS_FAILED(rv)) {
     285                 :     // canonicalize error message
     286              49 :     if (rv == NS_ERROR_FILE_TARGET_DOES_NOT_EXIST)
     287              49 :       rv = NS_ERROR_FILE_NOT_FOUND;
     288              49 :     return rv;
     289                 :   }
     290                 : 
     291            2850 :   if (isDir) {
     292               3 :     rv = nsDirectoryIndexStream::Create(file, getter_AddRefs(stream));
     293               3 :     if (NS_SUCCEEDED(rv) && !HasContentTypeHint())
     294               2 :       contentType.AssignLiteral(APPLICATION_HTTP_INDEX_FORMAT);
     295                 :   } else {
     296            2847 :     rv = NS_NewLocalFileInputStream(getter_AddRefs(stream), file);
     297            2847 :     if (NS_SUCCEEDED(rv) && !HasContentTypeHint()) {
     298                 :       // Use file extension to infer content type
     299             114 :       nsCOMPtr<nsIMIMEService> mime = do_GetService("@mozilla.org/mime;1", &rv);
     300              57 :       if (NS_SUCCEEDED(rv)) {
     301              57 :         mime->GetTypeFromFile(file, contentType);
     302                 :       }
     303                 :     }
     304                 :   }
     305            2850 :   return rv;
     306                 : }
     307                 : 
     308                 : nsresult
     309            2902 : nsFileChannel::OpenContentStream(bool async, nsIInputStream **result,
     310                 :                                  nsIChannel** channel)
     311                 : {
     312                 :   // NOTE: the resulting file is a clone, so it is safe to pass it to the
     313                 :   //       file input stream which will be read on a background thread.
     314            5804 :   nsCOMPtr<nsIFile> file;
     315            2902 :   nsresult rv = GetFile(getter_AddRefs(file));
     316            2902 :   if (NS_FAILED(rv))
     317               0 :     return rv;
     318                 : 
     319            5804 :   nsCOMPtr<nsIFileProtocolHandler> fileHandler;
     320            2902 :   rv = NS_GetFileProtocolHandler(getter_AddRefs(fileHandler));
     321            2902 :   if (NS_FAILED(rv))
     322               0 :     return rv;
     323                 :     
     324            5804 :   nsCOMPtr<nsIURI> newURI;
     325            2902 :   rv = fileHandler->ReadURLFile(file, getter_AddRefs(newURI));
     326            2902 :   if (NS_SUCCEEDED(rv)) {
     327               4 :     nsCOMPtr<nsIChannel> newChannel;
     328               2 :     rv = NS_NewChannel(getter_AddRefs(newChannel), newURI);
     329               2 :     if (NS_FAILED(rv))
     330               0 :       return rv;
     331                 : 
     332               2 :     *result = nsnull;
     333               2 :     newChannel.forget(channel);
     334               2 :     return NS_OK;
     335                 :   }
     336                 : 
     337            5800 :   nsCOMPtr<nsIInputStream> stream;
     338                 : 
     339            2900 :   if (mUploadStream) {
     340                 :     // Pass back a nsFileUploadContentStream instance that knows how to perform
     341                 :     // the file copy when "read" (the resulting stream in this case does not
     342                 :     // actually return any data).
     343                 : 
     344               2 :     nsCOMPtr<nsIOutputStream> fileStream;
     345               1 :     rv = NS_NewLocalFileOutputStream(getter_AddRefs(fileStream), file,
     346                 :                                      PR_WRONLY | PR_CREATE_FILE | PR_TRUNCATE,
     347               1 :                                      PR_IRUSR | PR_IWUSR);
     348               1 :     if (NS_FAILED(rv))
     349               0 :       return rv;
     350                 : 
     351                 :     nsFileUploadContentStream *uploadStream =
     352                 :         new nsFileUploadContentStream(async, fileStream, mUploadStream,
     353               2 :                                       mUploadLength, this);
     354               1 :     if (!uploadStream || !uploadStream->IsInitialized()) {
     355               0 :       delete uploadStream;
     356               0 :       return NS_ERROR_OUT_OF_MEMORY;
     357                 :     }
     358               1 :     stream = uploadStream;
     359                 : 
     360               1 :     SetContentLength64(0);
     361                 : 
     362                 :     // Since there isn't any content to speak of we just set the content-type
     363                 :     // to something other than "unknown" to avoid triggering the content-type
     364                 :     // sniffer code in nsBaseChannel.
     365                 :     // However, don't override explicitly set types.
     366               1 :     if (!HasContentTypeHint())
     367               0 :       SetContentType(NS_LITERAL_CSTRING(APPLICATION_OCTET_STREAM));
     368                 :   } else {
     369            5798 :     nsCAutoString contentType;
     370            2899 :     rv = MakeFileInputStream(file, stream, contentType);
     371            2899 :     if (NS_FAILED(rv))
     372              49 :       return rv;
     373                 : 
     374            2850 :     EnableSynthesizedProgressEvents(true);
     375                 : 
     376                 :     // fixup content length and type
     377            2850 :     if (ContentLength64() < 0) {
     378                 :       PRInt64 size;
     379            2850 :       rv = file->GetFileSize(&size);
     380            2850 :       if (NS_FAILED(rv))
     381               0 :         return rv;
     382            2850 :       SetContentLength64(size);
     383                 :     }
     384            2850 :     if (!contentType.IsEmpty())
     385              54 :       SetContentType(contentType);
     386                 :   }
     387                 : 
     388            2851 :   *result = nsnull;
     389            2851 :   stream.swap(*result);
     390            2851 :   return NS_OK;
     391                 : }
     392                 : 
     393                 : //-----------------------------------------------------------------------------
     394                 : // nsFileChannel::nsISupports
     395                 : 
     396          274156 : NS_IMPL_ISUPPORTS_INHERITED2(nsFileChannel,
     397                 :                              nsBaseChannel,
     398                 :                              nsIUploadChannel,
     399                 :                              nsIFileChannel)
     400                 : 
     401                 : //-----------------------------------------------------------------------------
     402                 : // nsFileChannel::nsIFileChannel
     403                 : 
     404                 : NS_IMETHODIMP
     405            4780 : nsFileChannel::GetFile(nsIFile **file)
     406                 : {
     407            9560 :     nsCOMPtr<nsIFileURL> fileURL = do_QueryInterface(URI());
     408            4780 :     NS_ENSURE_STATE(fileURL);
     409                 : 
     410                 :     // This returns a cloned nsIFile
     411            4780 :     return fileURL->GetFile(file);
     412                 : }
     413                 : 
     414                 : //-----------------------------------------------------------------------------
     415                 : // nsFileChannel::nsIUploadChannel
     416                 : 
     417                 : NS_IMETHODIMP
     418               1 : nsFileChannel::SetUploadStream(nsIInputStream *stream,
     419                 :                                const nsACString &contentType,
     420                 :                                PRInt32 contentLength)
     421                 : {
     422               1 :   NS_ENSURE_TRUE(!IsPending(), NS_ERROR_IN_PROGRESS);
     423                 : 
     424               1 :   if ((mUploadStream = stream)) {
     425               1 :     mUploadLength = contentLength;
     426               1 :     if (mUploadLength < 0) {
     427                 :       // Make sure we know how much data we are uploading.
     428                 :       PRUint32 avail;
     429               0 :       nsresult rv = mUploadStream->Available(&avail);
     430               0 :       if (NS_FAILED(rv))
     431               0 :         return rv;
     432               0 :       mUploadLength = avail;
     433                 :     }
     434                 :   } else {
     435               0 :     mUploadLength = -1;
     436                 :   }
     437               1 :   return NS_OK;
     438                 : }
     439                 : 
     440                 : NS_IMETHODIMP
     441               0 : nsFileChannel::GetUploadStream(nsIInputStream **result)
     442                 : {
     443               0 :     NS_IF_ADDREF(*result = mUploadStream);
     444               0 :     return NS_OK;
     445                 : }

Generated by: LCOV version 1.7