Downloads in WK2 on Windows should write resume data to bundle
[WebKit-https.git] / Source / WebKit / win / WebDownloadCFNet.cpp
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 <wtf/platform.h>
41 #include <wtf/text/CString.h>
42
43 #include <io.h>
44 #include <sys/stat.h>
45 #include <sys/types.h>
46
47 #pragma warning(push, 0)
48 #include <WebCore/AuthenticationCF.h>
49 #include <WebCore/BString.h>
50 #include <WebCore/CredentialStorage.h>
51 #include <WebCore/DownloadBundle.h>
52 #include <WebCore/LoaderRunLoopCF.h>
53 #include <WebCore/ResourceError.h>
54 #include <WebCore/ResourceHandle.h>
55 #include <WebCore/ResourceRequest.h>
56 #include <WebCore/ResourceResponse.h>
57 #include <wtf/CurrentTime.h>
58 #pragma warning(pop)
59
60 using namespace WebCore;
61
62 // CFURLDownload Callbacks ----------------------------------------------------------------
63 static void didStartCallback(CFURLDownloadRef download, const void *clientInfo);
64 static CFURLRequestRef willSendRequestCallback(CFURLDownloadRef download, CFURLRequestRef request, CFURLResponseRef redirectionResponse, const void *clientInfo);
65 static void didReceiveAuthenticationChallengeCallback(CFURLDownloadRef download, CFURLAuthChallengeRef challenge, const void *clientInfo);
66 static void didReceiveResponseCallback(CFURLDownloadRef download, CFURLResponseRef response, const void *clientInfo);
67 static void willResumeWithResponseCallback(CFURLDownloadRef download, CFURLResponseRef response, UInt64 startingByte, const void *clientInfo);
68 static void didReceiveDataCallback(CFURLDownloadRef download, CFIndex length, const void *clientInfo);
69 static Boolean shouldDecodeDataOfMIMETypeCallback(CFURLDownloadRef download, CFStringRef encodingType, const void *clientInfo);
70 static void decideDestinationWithSuggestedObjectNameCallback(CFURLDownloadRef download, CFStringRef objectName, const void *clientInfo);
71 static void didCreateDestinationCallback(CFURLDownloadRef download, CFURLRef path, const void *clientInfo);
72 static void didFinishCallback(CFURLDownloadRef download, const void *clientInfo);
73 static void didFailCallback(CFURLDownloadRef download, CFErrorRef error, const void *clientInfo);
74
75 void WebDownload::init(ResourceHandle* handle, const ResourceRequest& request, const ResourceResponse& response, IWebDownloadDelegate* delegate)
76 {
77     m_delegate = delegate ? delegate : DefaultDownloadDelegate::sharedInstance();
78     CFURLConnectionRef connection = handle->connection();
79     if (!connection) {
80         LOG_ERROR("WebDownload::WebDownload(ResourceHandle*,...) called with an inactive ResourceHandle");    
81         return;
82     }
83
84     CFURLDownloadClient client = {0, this, 0, 0, 0, didStartCallback, willSendRequestCallback, didReceiveAuthenticationChallengeCallback, 
85         didReceiveResponseCallback, willResumeWithResponseCallback, didReceiveDataCallback, shouldDecodeDataOfMIMETypeCallback,
86         decideDestinationWithSuggestedObjectNameCallback, didCreateDestinationCallback, didFinishCallback, didFailCallback};
87
88     m_request.adoptRef(WebMutableURLRequest::createInstance(request));
89     m_download.adoptCF(CFURLDownloadCreateAndStartWithLoadingConnection(0, connection, request.cfURLRequest(), response.cfURLResponse(), &client));
90
91     // It is possible for CFURLDownloadCreateAndStartWithLoadingConnection() to fail if the passed in CFURLConnection is not in a "downloadable state"
92     // However, we should never hit that case
93     if (!m_download) {
94         ASSERT_NOT_REACHED();
95         LOG_ERROR("WebDownload - Failed to create WebDownload from existing connection (%s)", request.url().string().utf8().data());
96     } else
97         LOG(Download, "WebDownload - Created WebDownload %p from existing connection (%s)", this, request.url().string().utf8().data());
98
99     // The CFURLDownload either starts successfully and retains the CFURLConnection, 
100     // or it fails to creating and we have a now-useless connection with a dangling ref. 
101     // Either way, we need to release the connection to balance out ref counts
102     handle->releaseConnectionForDownload();
103     CFRelease(connection);
104 }
105
106 void WebDownload::init(const KURL& url, IWebDownloadDelegate* delegate)
107 {
108     m_delegate = delegate ? delegate : DefaultDownloadDelegate::sharedInstance();
109     LOG_ERROR("Delegate is %p", m_delegate.get());
110
111     ResourceRequest request(url);
112     CFURLRequestRef cfRequest = request.cfURLRequest();
113
114     CFURLDownloadClient client = {0, this, 0, 0, 0, didStartCallback, willSendRequestCallback, didReceiveAuthenticationChallengeCallback, 
115                                   didReceiveResponseCallback, willResumeWithResponseCallback, didReceiveDataCallback, shouldDecodeDataOfMIMETypeCallback, 
116                                   decideDestinationWithSuggestedObjectNameCallback, didCreateDestinationCallback, didFinishCallback, didFailCallback};
117     m_request.adoptRef(WebMutableURLRequest::createInstance(request));
118     m_download.adoptCF(CFURLDownloadCreate(0, cfRequest, &client));
119
120     CFURLDownloadScheduleWithCurrentMessageQueue(m_download.get());
121     CFURLDownloadScheduleDownloadWithRunLoop(m_download.get(), loaderRunLoop(), kCFRunLoopDefaultMode);
122
123     LOG(Download, "WebDownload - Initialized download of url %s in WebDownload %p", url.string().utf8().data(), this);
124 }
125
126 // IWebDownload -------------------------------------------------------------------
127
128 HRESULT STDMETHODCALLTYPE WebDownload::initWithRequest(
129         /* [in] */ IWebURLRequest* request, 
130         /* [in] */ IWebDownloadDelegate* delegate)
131 {
132     COMPtr<WebMutableURLRequest> webRequest;
133     if (!request || FAILED(request->QueryInterface(&webRequest))) {
134         LOG(Download, "WebDownload - initWithRequest failed - not a WebMutableURLRequest");    
135         return E_FAIL;
136     }
137
138     if (!delegate)
139         return E_FAIL;
140     m_delegate = delegate;
141     LOG(Download, "Delegate is %p", m_delegate.get());
142
143     RetainPtr<CFURLRequestRef> cfRequest = webRequest->resourceRequest().cfURLRequest();
144
145     CFURLDownloadClient client = {0, this, 0, 0, 0, didStartCallback, willSendRequestCallback, didReceiveAuthenticationChallengeCallback, 
146                                   didReceiveResponseCallback, willResumeWithResponseCallback, didReceiveDataCallback, shouldDecodeDataOfMIMETypeCallback, 
147                                   decideDestinationWithSuggestedObjectNameCallback, didCreateDestinationCallback, didFinishCallback, didFailCallback};
148     m_request.adoptRef(WebMutableURLRequest::createInstance(webRequest.get()));
149     m_download.adoptCF(CFURLDownloadCreate(0, cfRequest.get(), &client));
150
151     // If for some reason the download failed to create, 
152     // we have particular cleanup to do
153     if (!m_download) {
154         m_request = 0;    
155         return E_FAIL;
156     }
157
158     CFURLDownloadScheduleWithCurrentMessageQueue(m_download.get());
159     CFURLDownloadScheduleDownloadWithRunLoop(m_download.get(), loaderRunLoop(), kCFRunLoopDefaultMode);
160
161     LOG(Download, "WebDownload - initWithRequest complete, started download of url %s", webRequest->resourceRequest().url().string().utf8().data());
162     return S_OK;
163 }
164
165 HRESULT STDMETHODCALLTYPE WebDownload::initToResumeWithBundle(
166         /* [in] */ BSTR bundlePath, 
167         /* [in] */ IWebDownloadDelegate* delegate)
168 {
169     LOG(Download, "Attempting resume of download bundle %s", String(bundlePath, SysStringLen(bundlePath)).ascii().data());
170
171     RetainPtr<CFDataRef> resumeData(AdoptCF, DownloadBundle::extractResumeData(String(bundlePath, SysStringLen(bundlePath))));
172
173     if (!resumeData)
174         return E_FAIL;
175
176     if (!delegate)
177         return E_FAIL;
178     m_delegate = delegate;
179     LOG(Download, "Delegate is %p", m_delegate.get());
180
181     CFURLDownloadClient client = {0, this, 0, 0, 0, didStartCallback, willSendRequestCallback, didReceiveAuthenticationChallengeCallback, 
182                                   didReceiveResponseCallback, willResumeWithResponseCallback, didReceiveDataCallback, shouldDecodeDataOfMIMETypeCallback, 
183                                   decideDestinationWithSuggestedObjectNameCallback, didCreateDestinationCallback, didFinishCallback, didFailCallback};
184     
185     RetainPtr<CFURLRef> pathURL(AdoptCF, MarshallingHelpers::PathStringToFileCFURLRef(String(bundlePath, SysStringLen(bundlePath))));
186     ASSERT(pathURL);
187
188     m_download.adoptCF(CFURLDownloadCreateWithResumeData(0, resumeData.get(), pathURL.get(), &client));
189
190     if (!m_download) {
191         LOG(Download, "Failed to create CFURLDownloadRef for resume");    
192         return E_FAIL;
193     }
194     
195     m_bundlePath = String(bundlePath, SysStringLen(bundlePath));
196     // Attempt to remove the ".download" extension from the bundle for the final file destination
197     // Failing that, we clear m_destination and will ask the delegate later once the download starts
198     if (m_bundlePath.endsWith(DownloadBundle::fileExtension(), false)) {
199         m_destination = m_bundlePath.threadsafeCopy();
200         m_destination.truncate(m_destination.length() - DownloadBundle::fileExtension().length());
201     } else
202         m_destination = String();
203     
204     CFURLDownloadScheduleWithCurrentMessageQueue(m_download.get());
205     CFURLDownloadScheduleDownloadWithRunLoop(m_download.get(), loaderRunLoop(), kCFRunLoopDefaultMode);
206
207     LOG(Download, "WebDownload - initWithRequest complete, resumed download of bundle %s", String(bundlePath, SysStringLen(bundlePath)).ascii().data());
208     return S_OK;
209 }
210
211 HRESULT STDMETHODCALLTYPE WebDownload::start()
212 {
213     LOG(Download, "WebDownload - Starting download (%p)", this);
214     if (!m_download)
215         return E_FAIL;
216
217     CFURLDownloadStart(m_download.get());
218     // FIXME: 4950477 - CFURLDownload neglects to make the didStart() client call upon starting the download.
219     // This is a somewhat critical call, so we'll fake it for now!
220     didStart();
221
222     return S_OK;
223 }
224
225 HRESULT STDMETHODCALLTYPE WebDownload::cancel()
226 {
227     LOG(Download, "WebDownload - Cancelling download (%p)", this);
228     if (!m_download)
229         return E_FAIL;
230
231     CFURLDownloadCancel(m_download.get());
232     m_download = 0;
233     return S_OK;
234 }
235
236 HRESULT STDMETHODCALLTYPE WebDownload::cancelForResume()
237 {
238     LOG(Download, "WebDownload - Cancelling download (%p), writing resume information to file if possible", this);
239     ASSERT(m_download);
240     if (!m_download)
241         return E_FAIL;
242
243     HRESULT hr = S_OK;
244     RetainPtr<CFDataRef> resumeData;
245     if (m_destination.isEmpty()) {
246         CFURLDownloadCancel(m_download.get());
247         goto exit;
248     }
249
250     CFURLDownloadSetDeletesUponFailure(m_download.get(), false);
251     CFURLDownloadCancel(m_download.get());
252
253     resumeData.adoptCF(CFURLDownloadCopyResumeData(m_download.get()));
254     if (!resumeData) {
255         LOG(Download, "WebDownload - Unable to create resume data for download (%p)", this);
256         goto exit;
257     }
258
259     DownloadBundle::appendResumeData(resumeData.get(), m_bundlePath);
260
261 exit:
262     m_download = 0;
263     return hr;
264 }
265
266 HRESULT STDMETHODCALLTYPE WebDownload::deletesFileUponFailure(
267         /* [out, retval] */ BOOL* result)
268 {
269     if (!m_download)
270         return E_FAIL;
271     *result = CFURLDownloadDeletesUponFailure(m_download.get());
272     return S_OK;
273 }
274
275 HRESULT STDMETHODCALLTYPE WebDownload::setDeletesFileUponFailure(
276         /* [in] */ BOOL deletesFileUponFailure)
277 {
278     if (!m_download)
279         return E_FAIL;
280     CFURLDownloadSetDeletesUponFailure(m_download.get(), !!deletesFileUponFailure);
281     return S_OK;
282 }
283
284 HRESULT STDMETHODCALLTYPE WebDownload::setDestination(
285         /* [in] */ BSTR path, 
286         /* [in] */ BOOL allowOverwrite)
287 {
288     if (!m_download)
289         return E_FAIL;
290
291     m_destination = String(path, SysStringLen(path));
292     m_bundlePath = m_destination + DownloadBundle::fileExtension();
293
294     CFURLRef pathURL = MarshallingHelpers::PathStringToFileCFURLRef(m_bundlePath);
295     CFURLDownloadSetDestination(m_download.get(), pathURL, !!allowOverwrite);
296     CFRelease(pathURL);
297
298     LOG(Download, "WebDownload - Set destination to %s", m_bundlePath.ascii().data());
299
300     return S_OK;
301 }
302
303 // IWebURLAuthenticationChallengeSender -------------------------------------------------------------------
304
305 HRESULT STDMETHODCALLTYPE WebDownload::cancelAuthenticationChallenge(
306         /* [in] */ IWebURLAuthenticationChallenge*)
307 {
308     if (m_download) {
309         CFURLDownloadCancel(m_download.get());
310         m_download = 0;
311     }
312
313     // FIXME: Do we need a URL or description for this error code?
314     ResourceError error(String(WebURLErrorDomain), WebURLErrorUserCancelledAuthentication, "", "");
315     COMPtr<WebError> webError(AdoptCOM, WebError::createInstance(error));
316     m_delegate->didFailWithError(this, webError.get());
317
318     return S_OK;
319 }
320
321 HRESULT STDMETHODCALLTYPE WebDownload::continueWithoutCredentialForAuthenticationChallenge(
322         /* [in] */ IWebURLAuthenticationChallenge* challenge)
323 {
324     COMPtr<WebURLAuthenticationChallenge> webChallenge(Query, challenge);
325     if (!webChallenge)
326         return E_NOINTERFACE;
327
328     if (m_download)
329         CFURLDownloadUseCredential(m_download.get(), 0, webChallenge->authenticationChallenge().cfURLAuthChallengeRef());
330     return S_OK;
331 }
332
333 HRESULT STDMETHODCALLTYPE WebDownload::useCredential(
334         /* [in] */ IWebURLCredential* credential, 
335         /* [in] */ IWebURLAuthenticationChallenge* challenge)
336 {
337     COMPtr<WebURLAuthenticationChallenge> webChallenge(Query, challenge);
338     if (!webChallenge)
339         return E_NOINTERFACE;
340
341     COMPtr<WebURLCredential> webCredential(Query, credential);
342     if (!webCredential)
343         return E_NOINTERFACE;
344
345     RetainPtr<CFURLCredentialRef> cfCredential(AdoptCF, createCF(webCredential->credential()));
346
347     if (m_download)
348         CFURLDownloadUseCredential(m_download.get(), cfCredential.get(), webChallenge->authenticationChallenge().cfURLAuthChallengeRef());
349     return S_OK;
350 }
351
352 // CFURLDownload Callbacks -------------------------------------------------------------------
353 void WebDownload::didStart()
354 {
355 #ifndef NDEBUG
356     m_startTime = m_dataTime = currentTime();
357     m_received = 0;
358     LOG(Download, "DOWNLOAD - Started %p at %.3f seconds", this, m_startTime);
359 #endif
360     if (FAILED(m_delegate->didBegin(this)))
361         LOG_ERROR("DownloadDelegate->didBegin failed");
362 }
363
364 CFURLRequestRef WebDownload::willSendRequest(CFURLRequestRef request, CFURLResponseRef response)
365 {
366     COMPtr<WebMutableURLRequest> webRequest(AdoptCOM, WebMutableURLRequest::createInstance(ResourceRequest(request)));
367     COMPtr<WebURLResponse> webResponse(AdoptCOM, WebURLResponse::createInstance(ResourceResponse(response)));
368     COMPtr<IWebMutableURLRequest> finalRequest;
369
370     if (FAILED(m_delegate->willSendRequest(this, webRequest.get(), webResponse.get(), &finalRequest)))
371         LOG_ERROR("DownloadDelegate->willSendRequest failed");
372     
373     if (!finalRequest)
374         return 0;
375
376     COMPtr<WebMutableURLRequest> finalWebRequest(AdoptCOM, WebMutableURLRequest::createInstance(finalRequest.get()));
377     m_request = finalWebRequest.get();
378     CFURLRequestRef result = finalWebRequest->resourceRequest().cfURLRequest();
379     CFRetain(result);
380     return result;
381 }
382
383 void WebDownload::didReceiveAuthenticationChallenge(CFURLAuthChallengeRef challenge)
384 {
385     // Try previously stored credential first.
386     if (!CFURLAuthChallengeGetPreviousFailureCount(challenge)) {
387         Credential credential = CredentialStorage::get(core(CFURLAuthChallengeGetProtectionSpace(challenge)));
388         if (!credential.isEmpty()) {
389             RetainPtr<CFURLCredentialRef> cfCredential(AdoptCF, createCF(credential));
390             CFURLDownloadUseCredential(m_download.get(), cfCredential.get(), challenge);
391             return;
392         }
393     }
394
395     COMPtr<IWebURLAuthenticationChallenge> webChallenge(AdoptCOM,
396         WebURLAuthenticationChallenge::createInstance(AuthenticationChallenge(challenge, 0), this));
397
398     if (SUCCEEDED(m_delegate->didReceiveAuthenticationChallenge(this, webChallenge.get())))
399         return;
400
401     cancelAuthenticationChallenge(webChallenge.get());
402 }
403
404 void WebDownload::didReceiveResponse(CFURLResponseRef response)
405 {
406     COMPtr<WebURLResponse> webResponse(AdoptCOM, WebURLResponse::createInstance(ResourceResponse(response)));
407     if (FAILED(m_delegate->didReceiveResponse(this, webResponse.get())))
408         LOG_ERROR("DownloadDelegate->didReceiveResponse failed");
409 }
410
411 void WebDownload::willResumeWithResponse(CFURLResponseRef response, UInt64 fromByte)
412 {
413     COMPtr<WebURLResponse> webResponse(AdoptCOM, WebURLResponse::createInstance(ResourceResponse(response)));
414     if (FAILED(m_delegate->willResumeWithResponse(this, webResponse.get(), fromByte)))
415         LOG_ERROR("DownloadDelegate->willResumeWithResponse failed");
416 }
417
418 void WebDownload::didReceiveData(CFIndex length)
419 {
420 #ifndef NDEBUG
421     m_received += length;
422     double current = currentTime();
423     if (current - m_dataTime > 2.0)
424         LOG(Download, "DOWNLOAD - %p hanged for %.3f seconds - Received %i bytes for a total of %i", this, current - m_dataTime, length, m_received);
425     m_dataTime = current;
426 #endif
427     if (FAILED(m_delegate->didReceiveDataOfLength(this, length)))
428         LOG_ERROR("DownloadDelegate->didReceiveData failed");
429 }
430
431 bool WebDownload::shouldDecodeDataOfMIMEType(CFStringRef mimeType)
432 {
433     BOOL result;
434     if (FAILED(m_delegate->shouldDecodeSourceDataOfMIMEType(this, BString(mimeType), &result))) {
435         LOG_ERROR("DownloadDelegate->shouldDecodeSourceDataOfMIMEType failed");
436         return false;
437     }
438     return !!result;
439 }
440
441 void WebDownload::decideDestinationWithSuggestedObjectName(CFStringRef name)
442 {    
443     if (FAILED(m_delegate->decideDestinationWithSuggestedFilename(this, BString(name))))
444         LOG_ERROR("DownloadDelegate->decideDestinationWithSuggestedObjectName failed");
445 }
446
447 void WebDownload::didCreateDestination(CFURLRef destination)
448 {
449     // The concept of the ".download bundle" is internal to the WebDownload, so therefore
450     // we try to mask the delegate from its existence as much as possible by telling it the final
451     // destination was created, when in reality the bundle was created
452
453     String createdDestination = MarshallingHelpers::FileCFURLRefToPathString(destination);
454
455     // At this point in receiving CFURLDownload callbacks, we should definitely have the bundle path stored locally
456     // and it should match with the file that CFURLDownload created
457     ASSERT(createdDestination == m_bundlePath);
458     // And we should also always have the final-destination stored
459     ASSERT(!m_destination.isEmpty());
460
461     BString path(m_destination);
462     if (FAILED(m_delegate->didCreateDestination(this, path)))
463         LOG_ERROR("DownloadDelegate->didCreateDestination failed");
464 }
465
466 void WebDownload::didFinish()
467 {
468 #ifndef NDEBUG
469     LOG(Download, "DOWNLOAD - Finished %p after %i bytes and %.3f seconds", this, m_received, currentTime() - m_startTime);
470 #endif
471
472     ASSERT(!m_bundlePath.isEmpty() && !m_destination.isEmpty());
473     LOG(Download, "WebDownload - Moving file from bundle %s to destination %s", m_bundlePath.ascii().data(), m_destination.ascii().data());
474
475     // We try to rename the bundle to the final file name.  If that fails, we give the delegate one more chance to chose
476     // the final file name, then we just leave it
477     if (!MoveFileEx(m_bundlePath.charactersWithNullTermination(), m_destination.charactersWithNullTermination(), 0)) {
478         LOG_ERROR("Failed to move bundle %s to %s on completion\nError - %i", m_bundlePath.ascii().data(), m_destination.ascii().data(), GetLastError());
479         
480         bool reportBundlePathAsFinalPath = true;
481
482         BString destinationBSTR(m_destination.characters(), m_destination.length());
483         if (FAILED(m_delegate->decideDestinationWithSuggestedFilename(this, destinationBSTR)))
484             LOG_ERROR("delegate->decideDestinationWithSuggestedFilename() failed");
485
486         // The call to m_delegate->decideDestinationWithSuggestedFilename() should have changed our destination, so we'll try the move
487         // one last time.
488         if (!m_destination.isEmpty())
489             if (MoveFileEx(m_bundlePath.charactersWithNullTermination(), m_destination.charactersWithNullTermination(), 0))
490                 reportBundlePathAsFinalPath = false;
491
492         // 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
493         if (reportBundlePathAsFinalPath) {
494             BString bundleBSTR(m_bundlePath);
495             m_delegate->didCreateDestination(this, bundleBSTR);
496         } else {
497             BString finalDestinationBSTR = BString(m_destination);
498             m_delegate->didCreateDestination(this, finalDestinationBSTR);
499         }
500     }
501
502     // It's extremely likely the call to delegate->didFinish() will deref this, so lets not let that cause our destruction just yet
503     COMPtr<WebDownload> protect = this;
504     if (FAILED(m_delegate->didFinish(this)))
505         LOG_ERROR("DownloadDelegate->didFinish failed");
506
507     m_download = 0;
508 }
509
510 void WebDownload::didFail(CFErrorRef error)
511 {
512     COMPtr<WebError> webError(AdoptCOM, WebError::createInstance(ResourceError(error)));
513     if (FAILED(m_delegate->didFailWithError(this, webError.get())))
514         LOG_ERROR("DownloadDelegate->didFailWithError failed");
515 }
516
517 // CFURLDownload Callbacks ----------------------------------------------------------------
518 void didStartCallback(CFURLDownloadRef, const void *clientInfo)
519 { ((WebDownload*)clientInfo)->didStart(); }
520
521 CFURLRequestRef willSendRequestCallback(CFURLDownloadRef, CFURLRequestRef request, CFURLResponseRef redirectionResponse, const void *clientInfo)
522 { return ((WebDownload*)clientInfo)->willSendRequest(request, redirectionResponse); }
523
524 void didReceiveAuthenticationChallengeCallback(CFURLDownloadRef, CFURLAuthChallengeRef challenge, const void *clientInfo)
525 { ((WebDownload*)clientInfo)->didReceiveAuthenticationChallenge(challenge); }
526
527 void didReceiveResponseCallback(CFURLDownloadRef, CFURLResponseRef response, const void *clientInfo)
528 { ((WebDownload*)clientInfo)->didReceiveResponse(response); }
529
530 void willResumeWithResponseCallback(CFURLDownloadRef, CFURLResponseRef response, UInt64 startingByte, const void *clientInfo)
531 { ((WebDownload*)clientInfo)->willResumeWithResponse(response, startingByte); }
532
533 void didReceiveDataCallback(CFURLDownloadRef, CFIndex length, const void *clientInfo)
534 { ((WebDownload*)clientInfo)->didReceiveData(length); }
535
536 Boolean shouldDecodeDataOfMIMETypeCallback(CFURLDownloadRef, CFStringRef encodingType, const void *clientInfo)
537 { return ((WebDownload*)clientInfo)->shouldDecodeDataOfMIMEType(encodingType); }
538
539 void decideDestinationWithSuggestedObjectNameCallback(CFURLDownloadRef, CFStringRef objectName, const void *clientInfo)
540 { ((WebDownload*)clientInfo)->decideDestinationWithSuggestedObjectName(objectName); }
541
542 void didCreateDestinationCallback(CFURLDownloadRef, CFURLRef path, const void *clientInfo)
543 { ((WebDownload*)clientInfo)->didCreateDestination(path); }
544
545 void didFinishCallback(CFURLDownloadRef, const void *clientInfo)
546 { ((WebDownload*)clientInfo)->didFinish(); }
547
548 void didFailCallback(CFURLDownloadRef, CFErrorRef error, const void *clientInfo)
549 { ((WebDownload*)clientInfo)->didFail(error); }