webengine/osswebengine/WebKit/win/WebDownload.cpp
changeset 0 dd21522fd290
equal deleted inserted replaced
-1:000000000000 0:dd21522fd290
       
     1 /*
       
     2  * Copyright (C) 2007 Apple Inc.  All rights reserved.
       
     3  *
       
     4  * Redistribution and use in source and binary forms, with or without
       
     5  * modification, are permitted provided that the following conditions
       
     6  * are met:
       
     7  * 1. Redistributions of source code must retain the above copyright
       
     8  *    notice, this list of conditions and the following disclaimer.
       
     9  * 2. Redistributions in binary form must reproduce the above copyright
       
    10  *    notice, this list of conditions and the following disclaimer in the
       
    11  *    documentation and/or other materials provided with the distribution.
       
    12  *
       
    13  * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
       
    14  * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
       
    15  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
       
    16  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL APPLE COMPUTER, INC. OR
       
    17  * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
       
    18  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
       
    19  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
       
    20  * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
       
    21  * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
       
    22  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
       
    23  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 
       
    24  */
       
    25 
       
    26 #include "config.h"
       
    27 #include "WebKitDLL.h"
       
    28 #include "WebDownload.h"
       
    29 
       
    30 #include "DefaultDownloadDelegate.h"
       
    31 #include "MarshallingHelpers.h"
       
    32 #include "WebError.h"
       
    33 #include "WebKit.h"
       
    34 #include "WebKitLogging.h"
       
    35 #include "WebMutableURLRequest.h"
       
    36 #include "WebURLAuthenticationChallenge.h"
       
    37 #include "WebURLCredential.h"
       
    38 #include "WebURLResponse.h"
       
    39 
       
    40 #include <io.h>
       
    41 #include <sys/stat.h>
       
    42 #include <sys/types.h>
       
    43 
       
    44 #pragma warning(push, 0)
       
    45 #include <WebCore/AuthenticationCF.h>
       
    46 #include <WebCore/BString.h>
       
    47 #include <WebCore/NotImplemented.h>
       
    48 #include <WebCore/ResourceError.h>
       
    49 #include <WebCore/ResourceHandle.h>
       
    50 #include <WebCore/ResourceRequest.h>
       
    51 #include <WebCore/ResourceResponse.h>
       
    52 #include <WebCore/SystemTime.h>
       
    53 #pragma warning(pop)
       
    54 
       
    55 using namespace WebCore;
       
    56 
       
    57 // CFURLDownload Callbacks ----------------------------------------------------------------
       
    58 static void didStartCallback(CFURLDownloadRef download, const void *clientInfo);
       
    59 static CFURLRequestRef willSendRequestCallback(CFURLDownloadRef download, CFURLRequestRef request, CFURLResponseRef redirectionResponse, const void *clientInfo);
       
    60 static void didReceiveAuthenticationChallengeCallback(CFURLDownloadRef download, CFURLAuthChallengeRef challenge, const void *clientInfo);
       
    61 static void didReceiveResponseCallback(CFURLDownloadRef download, CFURLResponseRef response, const void *clientInfo);
       
    62 static void willResumeWithResponseCallback(CFURLDownloadRef download, CFURLResponseRef response, UInt64 startingByte, const void *clientInfo);
       
    63 static void didReceiveDataCallback(CFURLDownloadRef download, CFIndex length, const void *clientInfo);
       
    64 static Boolean shouldDecodeDataOfMIMETypeCallback(CFURLDownloadRef download, CFStringRef encodingType, const void *clientInfo);
       
    65 static void decideDestinationWithSuggestedObjectNameCallback(CFURLDownloadRef download, CFStringRef objectName, const void *clientInfo);
       
    66 static void didCreateDestinationCallback(CFURLDownloadRef download, CFURLRef path, const void *clientInfo);
       
    67 static void didFinishCallback(CFURLDownloadRef download, const void *clientInfo);
       
    68 static void didFailCallback(CFURLDownloadRef download, CFErrorRef error, const void *clientInfo);
       
    69 
       
    70 // Download Bundle file utilities ----------------------------------------------------------------
       
    71 static const String BundleExtension(".download");
       
    72 static UInt32 BundleMagicNumber = 0xDECAF4EA;
       
    73 
       
    74 static CFDataRef extractResumeDataFromBundle(const String& bundlePath);
       
    75 static HRESULT appendResumeDataToBundle(CFDataRef resumeData, const String& bundlePath);
       
    76 
       
    77 // WebDownload ----------------------------------------------------------------
       
    78 
       
    79 WebDownload::WebDownload()
       
    80     : m_refCount(0)
       
    81 {
       
    82     gClassCount++;
       
    83 }
       
    84 
       
    85 void WebDownload::init(ResourceHandle* handle, const ResourceRequest& request, const ResourceResponse& response, IWebDownloadDelegate* delegate)
       
    86 {
       
    87     m_delegate = delegate ? delegate : DefaultDownloadDelegate::sharedInstance();
       
    88     CFURLConnectionRef connection = handle->connection();
       
    89     if (!connection) {
       
    90         LOG_ERROR("WebDownload::WebDownload(ResourceHandle*,...) called with an inactive ResourceHandle");    
       
    91         return;
       
    92     }
       
    93 
       
    94     CFURLDownloadClient client = {0, this, 0, 0, 0, didStartCallback, willSendRequestCallback, didReceiveAuthenticationChallengeCallback, 
       
    95         didReceiveResponseCallback, willResumeWithResponseCallback, didReceiveDataCallback, shouldDecodeDataOfMIMETypeCallback,
       
    96         decideDestinationWithSuggestedObjectNameCallback, didCreateDestinationCallback, didFinishCallback, didFailCallback};
       
    97 
       
    98     m_request.adoptRef(WebMutableURLRequest::createInstance(request));
       
    99     m_download.adoptCF(CFURLDownloadCreateAndStartWithLoadingConnection(0, connection, request.cfURLRequest(), response.cfURLResponse(), &client));
       
   100 
       
   101     // It is possible for CFURLDownloadCreateAndStartWithLoadingConnection() to fail if the passed in CFURLConnection is not in a "downloadable state"
       
   102     // However, we should never hit that case
       
   103     if (!m_download) {
       
   104         ASSERT_NOT_REACHED();
       
   105         LOG_ERROR("WebDownload - Failed to create WebDownload from existing connection (%s)", request.url().url().ascii());
       
   106     } else
       
   107         LOG(Download, "WebDownload - Created WebDownload %p from existing connection (%s)", this, request.url().url().ascii());
       
   108 
       
   109     // The CFURLDownload either starts successfully and retains the CFURLConnection, 
       
   110     // or it fails to creating and we have a now-useless connection with a dangling ref. 
       
   111     // Either way, we need to release the connection to balance out ref counts
       
   112     handle->releaseConnectionForDownload();
       
   113     CFRelease(connection);
       
   114 }
       
   115 
       
   116 void WebDownload::init(const KURL& url, IWebDownloadDelegate* delegate)
       
   117 {
       
   118     m_delegate = delegate ? delegate : DefaultDownloadDelegate::sharedInstance();
       
   119     LOG_ERROR("Delegate is %p", m_delegate.get());
       
   120 
       
   121     ResourceRequest request(url);
       
   122     CFURLRequestRef cfRequest = request.cfURLRequest();
       
   123 
       
   124     CFURLDownloadClient client = {0, this, 0, 0, 0, didStartCallback, willSendRequestCallback, didReceiveAuthenticationChallengeCallback, 
       
   125                                   didReceiveResponseCallback, willResumeWithResponseCallback, didReceiveDataCallback, shouldDecodeDataOfMIMETypeCallback, 
       
   126                                   decideDestinationWithSuggestedObjectNameCallback, didCreateDestinationCallback, didFinishCallback, didFailCallback};
       
   127     m_request.adoptRef(WebMutableURLRequest::createInstance(request));
       
   128     m_download.adoptCF(CFURLDownloadCreate(0, cfRequest, &client));
       
   129 
       
   130     CFURLDownloadScheduleWithCurrentMessageQueue(m_download.get());
       
   131     CFURLDownloadScheduleDownloadWithRunLoop(m_download.get(), ResourceHandle::loaderRunLoop(), kCFRunLoopDefaultMode);
       
   132 
       
   133     LOG(Download, "WebDownload - Initialized download of url %s in WebDownload %p", url.url().ascii(), this);
       
   134 }
       
   135 
       
   136 WebDownload::~WebDownload()
       
   137 {
       
   138     LOG(Download, "WebDownload - Destroying download (%p)", this);
       
   139     cancel();
       
   140     gClassCount--;
       
   141 }
       
   142 
       
   143 WebDownload* WebDownload::createInstance()
       
   144 {
       
   145     WebDownload* instance = new WebDownload();
       
   146     instance->AddRef();
       
   147     return instance;
       
   148 }
       
   149 
       
   150 WebDownload* WebDownload::createInstance(ResourceHandle* handle, const ResourceRequest& request, const ResourceResponse& response, IWebDownloadDelegate* delegate)
       
   151 {
       
   152     WebDownload* instance = new WebDownload();
       
   153     instance->AddRef();
       
   154     instance->init(handle, request, response, delegate);
       
   155     return instance;
       
   156 }
       
   157 
       
   158 WebDownload* WebDownload::createInstance(const KURL& url, IWebDownloadDelegate* delegate)
       
   159 {
       
   160     WebDownload* instance = new WebDownload();
       
   161     instance->AddRef();
       
   162     instance->init(url, delegate);
       
   163     return instance;
       
   164 }
       
   165 
       
   166 // IUnknown -------------------------------------------------------------------
       
   167 
       
   168 HRESULT STDMETHODCALLTYPE WebDownload::QueryInterface(REFIID riid, void** ppvObject)
       
   169 {
       
   170     *ppvObject = 0;
       
   171     if (IsEqualGUID(riid, IID_IUnknown))
       
   172         *ppvObject = static_cast<IWebDownload*>(this);
       
   173     else if (IsEqualGUID(riid, IID_IWebDownload))
       
   174         *ppvObject = static_cast<IWebDownload*>(this);
       
   175     else if (IsEqualGUID(riid, IID_IWebURLAuthenticationChallengeSender))
       
   176         *ppvObject = static_cast<IWebURLAuthenticationChallengeSender*>(this);
       
   177     else if (IsEqualGUID(riid, CLSID_WebDownload))
       
   178         *ppvObject = static_cast<WebDownload*>(this);
       
   179     else
       
   180         return E_NOINTERFACE;
       
   181 
       
   182     AddRef();
       
   183     return S_OK;
       
   184 }
       
   185 
       
   186 ULONG STDMETHODCALLTYPE WebDownload::AddRef(void)
       
   187 {
       
   188     return ++m_refCount;
       
   189 }
       
   190 
       
   191 ULONG STDMETHODCALLTYPE WebDownload::Release(void)
       
   192 {
       
   193     ULONG newRef = --m_refCount;
       
   194     if (!newRef)
       
   195         delete(this);
       
   196 
       
   197     return newRef;
       
   198 }
       
   199 
       
   200 // IWebDownload -------------------------------------------------------------------
       
   201 
       
   202 HRESULT STDMETHODCALLTYPE WebDownload::initWithRequest(
       
   203         /* [in] */ IWebURLRequest* request, 
       
   204         /* [in] */ IWebDownloadDelegate* delegate)
       
   205 {
       
   206     COMPtr<WebMutableURLRequest> webRequest;
       
   207     if (!request || FAILED(request->QueryInterface(CLSID_WebMutableURLRequest, (void**)&webRequest))) {
       
   208         LOG(Download, "WebDownload - initWithRequest failed - not a WebMutableURLRequest");    
       
   209         return E_FAIL;
       
   210     }
       
   211 
       
   212     if (!delegate)
       
   213         return E_FAIL;
       
   214     m_delegate = delegate;
       
   215     LOG(Download, "Delegate is %p", m_delegate.get());
       
   216 
       
   217     RetainPtr<CFURLRequestRef> cfRequest = webRequest->resourceRequest().cfURLRequest();
       
   218 
       
   219     CFURLDownloadClient client = {0, this, 0, 0, 0, didStartCallback, willSendRequestCallback, didReceiveAuthenticationChallengeCallback, 
       
   220                                   didReceiveResponseCallback, willResumeWithResponseCallback, didReceiveDataCallback, shouldDecodeDataOfMIMETypeCallback, 
       
   221                                   decideDestinationWithSuggestedObjectNameCallback, didCreateDestinationCallback, didFinishCallback, didFailCallback};
       
   222     m_request.adoptRef(WebMutableURLRequest::createInstance(webRequest.get()));
       
   223     m_download.adoptCF(CFURLDownloadCreate(0, cfRequest.get(), &client));
       
   224 
       
   225     // If for some reason the download failed to create, 
       
   226     // we have particular cleanup to do
       
   227     if (!m_download) {
       
   228         m_request = 0;    
       
   229         return E_FAIL;
       
   230     }
       
   231 
       
   232     CFURLDownloadScheduleWithCurrentMessageQueue(m_download.get());
       
   233     CFURLDownloadScheduleDownloadWithRunLoop(m_download.get(), ResourceHandle::loaderRunLoop(), kCFRunLoopDefaultMode);
       
   234 
       
   235     LOG(Download, "WebDownload - initWithRequest complete, started download of url %s", webRequest->resourceRequest().url().url().ascii());
       
   236     return S_OK;
       
   237 }
       
   238 
       
   239 HRESULT STDMETHODCALLTYPE WebDownload::initToResumeWithBundle(
       
   240         /* [in] */ BSTR bundlePath, 
       
   241         /* [in] */ IWebDownloadDelegate* delegate)
       
   242 {
       
   243     LOG(Download, "Attempting resume of download bundle %s", String(bundlePath, SysStringLen(bundlePath)).ascii().data());
       
   244 
       
   245     RetainPtr<CFDataRef> resumeData(AdoptCF, extractResumeDataFromBundle(String(bundlePath, SysStringLen(bundlePath))));
       
   246     
       
   247     if (!resumeData)
       
   248         return E_FAIL;
       
   249 
       
   250     if (!delegate)
       
   251         return E_FAIL;
       
   252     m_delegate = delegate;
       
   253     LOG(Download, "Delegate is %p", m_delegate.get());
       
   254 
       
   255     CFURLDownloadClient client = {0, this, 0, 0, 0, didStartCallback, willSendRequestCallback, didReceiveAuthenticationChallengeCallback, 
       
   256                                   didReceiveResponseCallback, willResumeWithResponseCallback, didReceiveDataCallback, shouldDecodeDataOfMIMETypeCallback, 
       
   257                                   decideDestinationWithSuggestedObjectNameCallback, didCreateDestinationCallback, didFinishCallback, didFailCallback};
       
   258     
       
   259     RetainPtr<CFURLRef> pathURL(AdoptCF, MarshallingHelpers::PathStringToFileCFURLRef(String(bundlePath, SysStringLen(bundlePath))));
       
   260     ASSERT(pathURL);
       
   261 
       
   262     m_download.adoptCF(CFURLDownloadCreateWithResumeData(0, resumeData.get(), pathURL.get(), &client));
       
   263 
       
   264     if (!m_download) {
       
   265         LOG(Download, "Failed to create CFURLDownloadRef for resume");    
       
   266         return E_FAIL;
       
   267     }
       
   268     
       
   269     m_bundlePath = String(bundlePath, SysStringLen(bundlePath));
       
   270     // Attempt to remove the ".download" extension from the bundle for the final file destination
       
   271     // Failing that, we clear m_destination and will ask the delegate later once the download starts
       
   272     if (m_bundlePath.endsWith(BundleExtension, false)) {
       
   273         m_destination = m_bundlePath.copy();
       
   274         m_destination.truncate(m_destination.length() - BundleExtension.length());
       
   275     } else
       
   276         m_destination = String();
       
   277     
       
   278     CFURLDownloadScheduleWithCurrentMessageQueue(m_download.get());
       
   279     CFURLDownloadScheduleDownloadWithRunLoop(m_download.get(), ResourceHandle::loaderRunLoop(), kCFRunLoopDefaultMode);
       
   280 
       
   281     LOG(Download, "WebDownload - initWithRequest complete, resumed download of bundle %s", String(bundlePath, SysStringLen(bundlePath)).ascii().data());
       
   282     return S_OK;
       
   283 }
       
   284 
       
   285 HRESULT STDMETHODCALLTYPE WebDownload::canResumeDownloadDecodedWithEncodingMIMEType(
       
   286         /* [in] */ BSTR, 
       
   287         /* [out, retval] */ BOOL*)
       
   288 {
       
   289     notImplemented();
       
   290     return E_FAIL;
       
   291 }
       
   292 
       
   293 HRESULT STDMETHODCALLTYPE WebDownload::start()
       
   294 {
       
   295     LOG(Download, "WebDownload - Starting download (%p)", this);
       
   296     if (!m_download)
       
   297         return E_FAIL;
       
   298 
       
   299     CFURLDownloadStart(m_download.get());
       
   300     // FIXME: 4950477 - CFURLDownload neglects to make the didStart() client call upon starting the download.
       
   301     // This is a somewhat critical call, so we'll fake it for now!
       
   302     didStart();
       
   303 
       
   304     return S_OK;
       
   305 }
       
   306 
       
   307 HRESULT STDMETHODCALLTYPE WebDownload::cancel()
       
   308 {
       
   309     LOG(Download, "WebDownload - Cancelling download (%p)", this);
       
   310     if (!m_download)
       
   311         return E_FAIL;
       
   312 
       
   313     CFURLDownloadCancel(m_download.get());
       
   314     m_download = 0;
       
   315     return S_OK;
       
   316 }
       
   317 
       
   318 HRESULT STDMETHODCALLTYPE WebDownload::cancelForResume()
       
   319 {
       
   320     LOG(Download, "WebDownload - Cancelling download (%p), writing resume information to file if possible", this);
       
   321     ASSERT(m_download);
       
   322     if (!m_download)
       
   323         return E_FAIL;
       
   324 
       
   325     HRESULT hr = S_OK;
       
   326     RetainPtr<CFDataRef> resumeData;
       
   327     if (m_destination.isEmpty())
       
   328         goto exit;
       
   329 
       
   330     CFURLDownloadSetDeletesUponFailure(m_download.get(), false);
       
   331     CFURLDownloadCancel(m_download.get());
       
   332 
       
   333     resumeData = CFURLDownloadCopyResumeData(m_download.get());
       
   334     if (!resumeData) {
       
   335         LOG(Download, "WebDownload - Unable to create resume data for download (%p)", this);
       
   336         goto exit;
       
   337     }
       
   338 
       
   339     appendResumeDataToBundle(resumeData.get(), m_bundlePath);
       
   340    
       
   341 exit:
       
   342     m_download = 0;
       
   343     return hr;
       
   344 }
       
   345 
       
   346 HRESULT STDMETHODCALLTYPE WebDownload::deletesFileUponFailure(
       
   347         /* [out, retval] */ BOOL* result)
       
   348 {
       
   349     if (!m_download)
       
   350         return E_FAIL;
       
   351     *result = CFURLDownloadDeletesUponFailure(m_download.get());
       
   352     return S_OK;
       
   353 }
       
   354 
       
   355 HRESULT STDMETHODCALLTYPE WebDownload::bundlePathForTargetPath(
       
   356         /* [in] */ BSTR targetPath, 
       
   357         /* [out, retval] */ BSTR* bundlePath)
       
   358 {
       
   359     if (!targetPath)
       
   360         return E_INVALIDARG;
       
   361 
       
   362     String bundle(targetPath, SysStringLen(targetPath));
       
   363     if (bundle.isEmpty())
       
   364         return E_INVALIDARG;
       
   365 
       
   366     if (bundle[bundle.length()-1] == '/')
       
   367         bundle.truncate(1);
       
   368 
       
   369     bundle += BundleExtension;
       
   370     *bundlePath = SysAllocStringLen(bundle.characters(), bundle.length());
       
   371     if (!*bundlePath)
       
   372         return E_FAIL;
       
   373     return S_OK;
       
   374 }
       
   375 
       
   376 HRESULT STDMETHODCALLTYPE WebDownload::request(
       
   377         /* [out, retval] */ IWebURLRequest** request)
       
   378 {
       
   379     if (request) {
       
   380         *request = m_request.get();
       
   381         if (*request)
       
   382             (*request)->AddRef();
       
   383     }
       
   384     return S_OK;
       
   385 }
       
   386 
       
   387 HRESULT STDMETHODCALLTYPE WebDownload::setDeletesFileUponFailure(
       
   388         /* [in] */ BOOL deletesFileUponFailure)
       
   389 {
       
   390     if (!m_download)
       
   391         return E_FAIL;
       
   392     CFURLDownloadSetDeletesUponFailure(m_download.get(), !!deletesFileUponFailure);
       
   393     return S_OK;
       
   394 }
       
   395 
       
   396 HRESULT STDMETHODCALLTYPE WebDownload::setDestination(
       
   397         /* [in] */ BSTR path, 
       
   398         /* [in] */ BOOL allowOverwrite)
       
   399 {
       
   400     if (!m_download)
       
   401         return E_FAIL;
       
   402 
       
   403     m_destination = String(path, SysStringLen(path));
       
   404     m_bundlePath = m_destination + BundleExtension;
       
   405 
       
   406     CFURLRef pathURL = MarshallingHelpers::PathStringToFileCFURLRef(m_bundlePath);
       
   407     CFURLDownloadSetDestination(m_download.get(), pathURL, !!allowOverwrite);
       
   408     CFRelease(pathURL);
       
   409 
       
   410     LOG(Download, "WebDownload - Set destination to %s", m_bundlePath.ascii().data());
       
   411 
       
   412     return S_OK;
       
   413 }
       
   414 
       
   415 // IWebURLAuthenticationChallengeSender -------------------------------------------------------------------
       
   416 
       
   417 HRESULT STDMETHODCALLTYPE WebDownload::cancelAuthenticationChallenge(
       
   418         /* [in] */ IWebURLAuthenticationChallenge*)
       
   419 {
       
   420     if (m_download) {
       
   421         CFURLDownloadCancel(m_download.get());
       
   422         m_download = 0;
       
   423     }
       
   424 
       
   425     // FIXME: Do we need a URL or description for this error code?
       
   426     ResourceError error(String(WebURLErrorDomain), WebURLErrorUserCancelledAuthentication, "", "");
       
   427     COMPtr<WebError> webError(AdoptCOM, WebError::createInstance(error));
       
   428     m_delegate->didFailWithError(this, webError.get());
       
   429 
       
   430     return S_OK;
       
   431 }
       
   432 
       
   433 HRESULT STDMETHODCALLTYPE WebDownload::continueWithoutCredentialForAuthenticationChallenge(
       
   434         /* [in] */ IWebURLAuthenticationChallenge* challenge)
       
   435 {
       
   436     COMPtr<WebURLAuthenticationChallenge> webChallenge(Query, challenge);
       
   437     if (!webChallenge)
       
   438         return E_NOINTERFACE;
       
   439 
       
   440     if (m_download)
       
   441         CFURLDownloadUseCredential(m_download.get(), 0, webChallenge->authenticationChallenge().cfURLAuthChallengeRef());
       
   442     return S_OK;
       
   443 }
       
   444 
       
   445 HRESULT STDMETHODCALLTYPE WebDownload::useCredential(
       
   446         /* [in] */ IWebURLCredential* credential, 
       
   447         /* [in] */ IWebURLAuthenticationChallenge* challenge)
       
   448 {
       
   449     COMPtr<WebURLAuthenticationChallenge> webChallenge(Query, challenge);
       
   450     if (!webChallenge)
       
   451         return E_NOINTERFACE;
       
   452 
       
   453     COMPtr<WebURLCredential> webCredential(Query, credential);
       
   454     if (!webCredential)
       
   455         return E_NOINTERFACE;
       
   456 
       
   457     RetainPtr<CFURLCredentialRef> cfCredential(AdoptCF, createCF(webCredential->credential()));
       
   458 
       
   459     if (m_download)
       
   460         CFURLDownloadUseCredential(m_download.get(), cfCredential.get(), webChallenge->authenticationChallenge().cfURLAuthChallengeRef());
       
   461     return S_OK;
       
   462 }
       
   463 
       
   464 // CFURLDownload Callbacks -------------------------------------------------------------------
       
   465 void WebDownload::didStart()
       
   466 {
       
   467 #ifndef NDEBUG
       
   468     m_startTime = m_dataTime = currentTime();
       
   469     m_received = 0;
       
   470     LOG(Download, "DOWNLOAD - Started %p at %.3f seconds", this, m_startTime);
       
   471 #endif
       
   472     if (FAILED(m_delegate->didBegin(this)))
       
   473         LOG_ERROR("DownloadDelegate->didBegin failed");
       
   474 }
       
   475 
       
   476 CFURLRequestRef WebDownload::willSendRequest(CFURLRequestRef request, CFURLResponseRef response)
       
   477 {
       
   478     COMPtr<WebMutableURLRequest> webRequest(AdoptCOM, WebMutableURLRequest::createInstance(ResourceRequest(request)));
       
   479     COMPtr<WebURLResponse> webResponse(AdoptCOM, WebURLResponse::createInstance(ResourceResponse(response)));
       
   480     COMPtr<IWebMutableURLRequest> finalRequest;
       
   481 
       
   482     if (FAILED(m_delegate->willSendRequest(this, webRequest.get(), webResponse.get(), &finalRequest)))
       
   483         LOG_ERROR("DownloadDelegate->willSendRequest failed");
       
   484     
       
   485     if (!finalRequest)
       
   486         return 0;
       
   487 
       
   488     COMPtr<WebMutableURLRequest> finalWebRequest(AdoptCOM, WebMutableURLRequest::createInstance(finalRequest.get()));
       
   489     m_request = finalWebRequest.get();
       
   490     CFURLRequestRef result = finalWebRequest->resourceRequest().cfURLRequest();
       
   491     CFRetain(result);
       
   492     return result;
       
   493 }
       
   494 
       
   495 void WebDownload::didReceiveAuthenticationChallenge(CFURLAuthChallengeRef challenge)
       
   496 {
       
   497     COMPtr<IWebURLAuthenticationChallenge> webChallenge(AdoptCOM,
       
   498         WebURLAuthenticationChallenge::createInstance(AuthenticationChallenge(challenge, 0), this));
       
   499 
       
   500     if (SUCCEEDED(m_delegate->didReceiveAuthenticationChallenge(this, webChallenge.get())))
       
   501         return;
       
   502 
       
   503     cancelAuthenticationChallenge(webChallenge.get());
       
   504 }
       
   505 
       
   506 void WebDownload::didReceiveResponse(CFURLResponseRef response)
       
   507 {
       
   508     COMPtr<WebURLResponse> webResponse(AdoptCOM, WebURLResponse::createInstance(ResourceResponse(response)));
       
   509     if (FAILED(m_delegate->didReceiveResponse(this, webResponse.get())))
       
   510         LOG_ERROR("DownloadDelegate->didReceiveResponse failed");
       
   511 }
       
   512 
       
   513 void WebDownload::willResumeWithResponse(CFURLResponseRef response, UInt64 fromByte)
       
   514 {
       
   515     COMPtr<WebURLResponse> webResponse(AdoptCOM, WebURLResponse::createInstance(ResourceResponse(response)));
       
   516     if (FAILED(m_delegate->willResumeWithResponse(this, webResponse.get(), fromByte)))
       
   517         LOG_ERROR("DownloadDelegate->willResumeWithResponse failed");
       
   518 }
       
   519 
       
   520 void WebDownload::didReceiveData(CFIndex length)
       
   521 {
       
   522 #ifndef NDEBUG
       
   523     m_received += length;
       
   524     double current = currentTime();
       
   525     if (current - m_dataTime > 2.0)
       
   526         LOG(Download, "DOWNLOAD - %p hanged for %.3f seconds - Received %i bytes for a total of %i", this, current - m_dataTime, length, m_received);
       
   527     m_dataTime = current;
       
   528 #endif
       
   529     if (FAILED(m_delegate->didReceiveDataOfLength(this, length)))
       
   530         LOG_ERROR("DownloadDelegate->didReceiveData failed");
       
   531 }
       
   532 
       
   533 bool WebDownload::shouldDecodeDataOfMIMEType(CFStringRef mimeType)
       
   534 {
       
   535     BOOL result;
       
   536     if (FAILED(m_delegate->shouldDecodeSourceDataOfMIMEType(this, BString(mimeType), &result))) {
       
   537         LOG_ERROR("DownloadDelegate->shouldDecodeSourceDataOfMIMEType failed");
       
   538         return false;
       
   539     }
       
   540     return !!result;
       
   541 }
       
   542 
       
   543 void WebDownload::decideDestinationWithSuggestedObjectName(CFStringRef name)
       
   544 {    
       
   545     if (FAILED(m_delegate->decideDestinationWithSuggestedFilename(this, BString(name))))
       
   546         LOG_ERROR("DownloadDelegate->decideDestinationWithSuggestedObjectName failed");
       
   547 }
       
   548 
       
   549 void WebDownload::didCreateDestination(CFURLRef destination)
       
   550 {
       
   551     // The concept of the ".download bundle" is internal to the WebDownload, so therefore
       
   552     // we try to mask the delegate from its existence as much as possible by telling it the final
       
   553     // destination was created, when in reality the bundle was created
       
   554 
       
   555     String createdDestination = MarshallingHelpers::FileCFURLRefToPathString(destination);
       
   556 
       
   557     // At this point in receiving CFURLDownload callbacks, we should definitely have the bundle path stored locally
       
   558     // and it should match with the file that CFURLDownload created
       
   559     ASSERT(createdDestination == m_bundlePath);
       
   560     // And we should also always have the final-destination stored
       
   561     ASSERT(!m_destination.isEmpty());
       
   562 
       
   563     BString path(m_destination);
       
   564     if (FAILED(m_delegate->didCreateDestination(this, path)))
       
   565         LOG_ERROR("DownloadDelegate->didCreateDestination failed");
       
   566 }
       
   567 
       
   568 void WebDownload::didFinish()
       
   569 {
       
   570 #ifndef NDEBUG
       
   571     LOG(Download, "DOWNLOAD - Finished %p after %i bytes and %.3f seconds", this, m_received, currentTime() - m_startTime);
       
   572 #endif
       
   573 
       
   574     ASSERT(!m_bundlePath.isEmpty() && !m_destination.isEmpty());
       
   575     LOG(Download, "WebDownload - Moving file from bundle %s to destination %s", m_bundlePath.ascii().data(), m_destination.ascii().data());
       
   576 
       
   577     // We try to rename the bundle to the final file name.  If that fails, we give the delegate one more chance to chose
       
   578     // the final file name, then we just leave it
       
   579     if (!MoveFileEx(m_bundlePath.charactersWithNullTermination(), m_destination.charactersWithNullTermination(), 0)) {
       
   580         LOG_ERROR("Failed to move bundle %s to %s on completion\nError - %i", m_bundlePath.ascii().data(), m_destination.ascii().data(), GetLastError());
       
   581         
       
   582         bool reportBundlePathAsFinalPath = true;
       
   583 
       
   584         BString destinationBSTR(m_destination.characters(), m_destination.length());
       
   585         if (FAILED(m_delegate->decideDestinationWithSuggestedFilename(this, destinationBSTR)))
       
   586             LOG_ERROR("delegate->decideDestinationWithSuggestedFilename() failed");
       
   587 
       
   588         // The call to m_delegate->decideDestinationWithSuggestedFilename() should have changed our destination, so we'll try the move
       
   589         // one last time.
       
   590         if (!m_destination.isEmpty())
       
   591             if (MoveFileEx(m_bundlePath.charactersWithNullTermination(), m_destination.charactersWithNullTermination(), 0))
       
   592                 reportBundlePathAsFinalPath = false;
       
   593 
       
   594         // We either need to tell the delegate our final filename is the bundle filename, or is the file name they just told us to use
       
   595         if (reportBundlePathAsFinalPath) {
       
   596             BString bundleBSTR(m_bundlePath);
       
   597             m_delegate->didCreateDestination(this, bundleBSTR);
       
   598         } else {
       
   599             BString finalDestinationBSTR = BString(m_destination);
       
   600             m_delegate->didCreateDestination(this, finalDestinationBSTR);
       
   601         }
       
   602     }
       
   603 
       
   604     // It's extremely likely the call to delegate->didFinish() will deref this, so lets not let that cause our destruction just yet
       
   605     COMPtr<WebDownload> protect = this;
       
   606     if (FAILED(m_delegate->didFinish(this)))
       
   607         LOG_ERROR("DownloadDelegate->didFinish failed");
       
   608 
       
   609     m_download = 0;
       
   610 }
       
   611 
       
   612 void WebDownload::didFail(CFErrorRef error)
       
   613 {
       
   614     COMPtr<WebError> webError(AdoptCOM, WebError::createInstance(ResourceError(error)));
       
   615     if (FAILED(m_delegate->didFailWithError(this, webError.get())))
       
   616         LOG_ERROR("DownloadDelegate->didFailWithError failed");
       
   617 }
       
   618 
       
   619 // CFURLDownload Callbacks ----------------------------------------------------------------
       
   620 void didStartCallback(CFURLDownloadRef, const void *clientInfo)
       
   621 { ((WebDownload*)clientInfo)->didStart(); }
       
   622 
       
   623 CFURLRequestRef willSendRequestCallback(CFURLDownloadRef, CFURLRequestRef request, CFURLResponseRef redirectionResponse, const void *clientInfo)
       
   624 { return ((WebDownload*)clientInfo)->willSendRequest(request, redirectionResponse); }
       
   625 
       
   626 void didReceiveAuthenticationChallengeCallback(CFURLDownloadRef, CFURLAuthChallengeRef challenge, const void *clientInfo)
       
   627 { ((WebDownload*)clientInfo)->didReceiveAuthenticationChallenge(challenge); }
       
   628 
       
   629 void didReceiveResponseCallback(CFURLDownloadRef, CFURLResponseRef response, const void *clientInfo)
       
   630 { ((WebDownload*)clientInfo)->didReceiveResponse(response); }
       
   631 
       
   632 void willResumeWithResponseCallback(CFURLDownloadRef, CFURLResponseRef response, UInt64 startingByte, const void *clientInfo)
       
   633 { ((WebDownload*)clientInfo)->willResumeWithResponse(response, startingByte); }
       
   634 
       
   635 void didReceiveDataCallback(CFURLDownloadRef, CFIndex length, const void *clientInfo)
       
   636 { ((WebDownload*)clientInfo)->didReceiveData(length); }
       
   637 
       
   638 Boolean shouldDecodeDataOfMIMETypeCallback(CFURLDownloadRef, CFStringRef encodingType, const void *clientInfo)
       
   639 { return ((WebDownload*)clientInfo)->shouldDecodeDataOfMIMEType(encodingType); }
       
   640 
       
   641 void decideDestinationWithSuggestedObjectNameCallback(CFURLDownloadRef, CFStringRef objectName, const void *clientInfo)
       
   642 { ((WebDownload*)clientInfo)->decideDestinationWithSuggestedObjectName(objectName); }
       
   643 
       
   644 void didCreateDestinationCallback(CFURLDownloadRef, CFURLRef path, const void *clientInfo)
       
   645 { ((WebDownload*)clientInfo)->didCreateDestination(path); }
       
   646 
       
   647 void didFinishCallback(CFURLDownloadRef, const void *clientInfo)
       
   648 { ((WebDownload*)clientInfo)->didFinish(); }
       
   649 
       
   650 void didFailCallback(CFURLDownloadRef, CFErrorRef error, const void *clientInfo)
       
   651 { ((WebDownload*)clientInfo)->didFail(error); }
       
   652 
       
   653 // Download Bundle file utilities ----------------------------------------------------------------
       
   654 
       
   655 static CFDataRef extractResumeDataFromBundle(const String& bundlePath)
       
   656 {
       
   657     if (bundlePath.isEmpty()) {
       
   658         LOG_ERROR("Cannot create resume data from empty download bundle path");
       
   659         return 0;
       
   660     }
       
   661     
       
   662     // Open a handle to the bundle file
       
   663     String nullifiedPath = bundlePath;
       
   664     FILE* bundle = 0;
       
   665     if (_wfopen_s(&bundle, nullifiedPath.charactersWithNullTermination(), TEXT("r+b")) || !bundle) {
       
   666         LOG_ERROR("Failed to open file %s to get resume data", bundlePath.ascii().data());
       
   667         return 0;
       
   668     }
       
   669 
       
   670     CFDataRef result = 0;
       
   671     Vector<UInt8> footerBuffer;
       
   672     
       
   673     // Stat the file to get its size
       
   674     struct _stat64 fileStat;
       
   675     if (_fstat64(_fileno(bundle), &fileStat))
       
   676         goto exit;
       
   677     
       
   678     // Check for the bundle magic number at the end of the file
       
   679     fpos_t footerMagicNumberPosition = fileStat.st_size - 4;
       
   680     ASSERT(footerMagicNumberPosition >= 0);
       
   681     if (footerMagicNumberPosition < 0)
       
   682         goto exit;
       
   683     if (fsetpos(bundle, &footerMagicNumberPosition))
       
   684         goto exit;
       
   685 
       
   686     UInt32 footerMagicNumber = 0;
       
   687     if (fread(&footerMagicNumber, 4, 1, bundle) != 1) {
       
   688         LOG_ERROR("Failed to read footer magic number from the bundle - errno(%i)", errno);  
       
   689         goto exit;
       
   690     }
       
   691 
       
   692     if (footerMagicNumber != BundleMagicNumber) {
       
   693         LOG_ERROR("Footer's magic number does not match 0x%X - errno(%i)", BundleMagicNumber, errno);  
       
   694         goto exit;
       
   695     }
       
   696 
       
   697     // Now we're *reasonably* sure this is a .download bundle we actually wrote. 
       
   698     // Get the length of the resume data
       
   699     fpos_t footerLengthPosition = fileStat.st_size - 8;
       
   700     ASSERT(footerLengthPosition >= 0);
       
   701     if (footerLengthPosition < 0)
       
   702         goto exit;
       
   703 
       
   704     if (fsetpos(bundle, &footerLengthPosition))
       
   705         goto exit;
       
   706 
       
   707     UInt32 footerLength = 0;
       
   708     if (fread(&footerLength, 4, 1, bundle) != 1) {
       
   709         LOG_ERROR("Failed to read ResumeData length from the bundle - errno(%i)", errno);  
       
   710         goto exit;
       
   711     }
       
   712 
       
   713     // Make sure theres enough bytes to read in for the resume data, and perform the read
       
   714     fpos_t footerStartPosition = fileStat.st_size - 8 - footerLength;
       
   715     ASSERT(footerStartPosition >= 0);
       
   716     if (footerStartPosition < 0)
       
   717         goto exit;
       
   718     if (fsetpos(bundle, &footerStartPosition))
       
   719         goto exit;
       
   720 
       
   721     footerBuffer.resize(footerLength);
       
   722     if (fread(footerBuffer.data(), 1, footerLength, bundle) != footerLength) {
       
   723         LOG_ERROR("Failed to read ResumeData from the bundle - errno(%i)", errno);  
       
   724         goto exit;
       
   725     }
       
   726 
       
   727     // CFURLDownload will seek to the appropriate place in the file (before our footer) and start overwriting from there
       
   728     // However, say we were within a few hundred bytes of the end of a download when it was paused -
       
   729     // The additional footer extended the length of the file beyond its final length, and there will be junk data leftover
       
   730     // at the end.  Therefore, now that we've retrieved the footer data, we need to truncate it.
       
   731     if (errno_t resizeError = _chsize_s(_fileno(bundle), footerStartPosition)) {
       
   732         LOG_ERROR("Failed to truncate the resume footer off the end of the file - errno(%i)", resizeError);
       
   733         goto exit;
       
   734     }
       
   735 
       
   736     // Finally, make the resume data.  Now, it is possible by some twist of fate the bundle magic number
       
   737     // was naturally at the end of the file and its not actually a valid bundle.  That, or someone engineered
       
   738     // it that way to try to attack us.  In that cause, this CFData will successfully create but when we 
       
   739     // actually try to start the CFURLDownload using this bogus data, it will fail and we will handle that gracefully
       
   740     result = CFDataCreate(0, footerBuffer.data(), footerLength);
       
   741 exit:
       
   742     fclose(bundle);
       
   743     return result;
       
   744 }
       
   745 
       
   746 static HRESULT appendResumeDataToBundle(CFDataRef resumeData, const String& bundlePath)
       
   747 {
       
   748     if (!resumeData) {
       
   749         LOG_ERROR("Invalid resume data to write to bundle path");
       
   750         return E_FAIL;
       
   751     }
       
   752     if (bundlePath.isEmpty()) {
       
   753         LOG_ERROR("Cannot write resume data to empty download bundle path");
       
   754         return E_FAIL;
       
   755     }
       
   756 
       
   757     String nullifiedPath = bundlePath;
       
   758     FILE* bundle = 0;
       
   759     if (_wfopen_s(&bundle, nullifiedPath.charactersWithNullTermination(), TEXT("ab")) || !bundle) {
       
   760         LOG_ERROR("Failed to open file %s to append resume data", bundlePath.ascii().data());
       
   761         return E_FAIL;
       
   762     }
       
   763 
       
   764     HRESULT hr = E_FAIL;
       
   765 
       
   766     const UInt8* resumeBytes = CFDataGetBytePtr(resumeData);
       
   767     ASSERT(resumeBytes);
       
   768     if (!resumeBytes)
       
   769         goto exit;
       
   770 
       
   771     UInt32 resumeLength = CFDataGetLength(resumeData);
       
   772     ASSERT(resumeLength > 0);
       
   773     if (resumeLength < 1)
       
   774         goto exit;
       
   775 
       
   776     if (fwrite(resumeBytes, 1, resumeLength, bundle) != resumeLength) {
       
   777         LOG_ERROR("Failed to write resume data to the bundle - errno(%i)", errno);
       
   778         goto exit;
       
   779     }
       
   780 
       
   781     if (fwrite(&resumeLength, 4, 1, bundle) != 1) {
       
   782         LOG_ERROR("Failed to write footer length to the bundle - errno(%i)", errno);
       
   783         goto exit;
       
   784     }
       
   785 
       
   786     if (fwrite(&BundleMagicNumber, 4, 1, bundle) != 1) {
       
   787         LOG_ERROR("Failed to write footer magic number to the bundle - errno(%i)", errno);
       
   788         goto exit;
       
   789     }
       
   790     
       
   791     hr = S_OK;
       
   792 exit:
       
   793     fclose(bundle);
       
   794     return hr;
       
   795 }