Add a separate class for networking related storage
[WebKit-https.git] / Source / WebKit2 / WebProcess / Downloads / cfnet / DownloadCFNet.cpp
1 /*
2  * Copyright (C) 2010, 2011 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 INC. AND ITS CONTRIBUTORS ``AS IS''
14  * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
15  * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
16  * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS
17  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
18  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
19  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
20  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
21  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
22  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
23  * THE POSSIBILITY OF SUCH DAMAGE.
24  */
25
26 #include "config.h"
27 #include "Download.h"
28
29 #include "DataReference.h"
30 #include "DownloadAuthenticationClient.h"
31
32 #pragma warning(push, 0)
33 #include <WebCore/AuthenticationCF.h>
34 #include <WebCore/AuthenticationChallenge.h>
35 #include <WebCore/DownloadBundle.h>
36 #include <WebCore/LoaderRunLoopCF.h>
37 #include <WebCore/NotImplemented.h>
38 #include <WebCore/ResourceError.h>
39 #include <WebCore/ResourceHandle.h>
40 #include <WebCore/ResourceResponse.h>
41 #pragma warning(pop)
42
43 using namespace WebCore;
44
45 namespace WebKit {
46
47 // CFURLDownload Callbacks ----------------------------------------------------------------
48 static void didStartCallback(CFURLDownloadRef download, const void* clientInfo);
49 static CFURLRequestRef willSendRequestCallback(CFURLDownloadRef download, CFURLRequestRef request, CFURLResponseRef redirectionResponse, const void* clientInfo);
50 static void didReceiveAuthenticationChallengeCallback(CFURLDownloadRef download, CFURLAuthChallengeRef challenge, const void* clientInfo);
51 static void didReceiveResponseCallback(CFURLDownloadRef download, CFURLResponseRef response, const void* clientInfo);
52 static void willResumeWithResponseCallback(CFURLDownloadRef download, CFURLResponseRef response, UInt64 startingByte, const void* clientInfo);
53 static void didReceiveDataCallback(CFURLDownloadRef download, CFIndex length, const void* clientInfo);
54 static Boolean shouldDecodeDataOfMIMETypeCallback(CFURLDownloadRef download, CFStringRef encodingType, const void* clientInfo);
55 static void decideDestinationWithSuggestedObjectNameCallback(CFURLDownloadRef download, CFStringRef objectName, const void* clientInfo);
56 static void didCreateDestinationCallback(CFURLDownloadRef download, CFURLRef path, const void* clientInfo);
57 static void didFinishCallback(CFURLDownloadRef download, const void* clientInfo);
58 static void didFailCallback(CFURLDownloadRef download, CFErrorRef error, const void* clientInfo);
59
60 void Download::useCredential(const WebCore::AuthenticationChallenge& challenge, const WebCore::Credential& credential)
61 {
62     if (!m_download)
63         return;
64     RetainPtr<CFURLCredentialRef> cfCredential(AdoptCF, createCF(credential));
65     CFURLDownloadUseCredential(m_download.get(), cfCredential.get(), challenge.cfURLAuthChallengeRef());
66 }
67
68 void Download::continueWithoutCredential(const WebCore::AuthenticationChallenge& challenge)
69 {
70     if (!m_download)
71         return;
72     CFURLDownloadUseCredential(m_download.get(), 0, challenge.cfURLAuthChallengeRef());
73 }
74
75 void Download::cancelAuthenticationChallenge(const WebCore::AuthenticationChallenge&)
76 {
77     if (!m_download)
78         return;
79     CFURLDownloadCancel(m_download.get());
80     m_download = 0;
81 }
82
83 DownloadAuthenticationClient* Download::authenticationClient()
84 {
85     if (!m_authenticationClient)
86         m_authenticationClient = DownloadAuthenticationClient::create(this);
87     return m_authenticationClient.get();
88 }
89
90 void Download::start()
91 {
92     ASSERT(!m_download);
93
94     CFURLRequestRef cfRequest = m_request.cfURLRequest();
95
96     CFURLDownloadClient client = {0, this, 0, 0, 0, didStartCallback, willSendRequestCallback, didReceiveAuthenticationChallengeCallback, 
97                                   didReceiveResponseCallback, willResumeWithResponseCallback, didReceiveDataCallback, shouldDecodeDataOfMIMETypeCallback, 
98                                   decideDestinationWithSuggestedObjectNameCallback, didCreateDestinationCallback, didFinishCallback, didFailCallback};
99     m_download.adoptCF(CFURLDownloadCreate(0, cfRequest, &client));
100
101     // FIXME: Allow this to be changed by the client.
102     CFURLDownloadSetDeletesUponFailure(m_download.get(), false);
103
104 #if OS(WINDOWS)
105     CFURLDownloadScheduleWithCurrentMessageQueue(m_download.get());
106 #endif
107     CFURLDownloadScheduleDownloadWithRunLoop(m_download.get(), loaderRunLoop(), kCFRunLoopDefaultMode);
108
109     CFURLDownloadStart(m_download.get());
110 }
111
112 void Download::startWithHandle(ResourceHandle* handle, const ResourceResponse& response)
113 {
114     ASSERT(!m_download);
115
116     CFURLConnectionRef connection = handle->connection();
117     if (!connection)
118         return;
119
120     CFURLDownloadClient client = {0, this, 0, 0, 0, didStartCallback, willSendRequestCallback, didReceiveAuthenticationChallengeCallback, 
121                                   didReceiveResponseCallback, willResumeWithResponseCallback, didReceiveDataCallback, shouldDecodeDataOfMIMETypeCallback,
122                                   decideDestinationWithSuggestedObjectNameCallback, didCreateDestinationCallback, didFinishCallback, didFailCallback};
123
124     m_download.adoptCF(CFURLDownloadCreateAndStartWithLoadingConnection(0, connection, handle->firstRequest().cfURLRequest(), response.cfURLResponse(), &client));
125
126     // It is possible for CFURLDownloadCreateAndStartWithLoadingConnection() to fail if the passed in CFURLConnection is not in a "downloadable state"
127     // However, we should never hit that case
128     if (!m_download)
129         ASSERT_NOT_REACHED();
130
131     // The CFURLDownload either starts successfully and retains the CFURLConnection, 
132     // or it fails to creating and we have a now-useless connection with a dangling ref. 
133     // Either way, we need to release the connection to balance out ref counts
134     handle->releaseConnectionForDownload();
135     CFRelease(connection);
136 }
137
138 void Download::cancel()
139 {
140     ASSERT(m_download);
141     if (!m_download)
142         return;
143
144     CFURLDownloadSetDeletesUponFailure(m_download.get(), false);
145     CFURLDownloadCancel(m_download.get());
146
147     RetainPtr<CFDataRef> resumeData(AdoptCF, CFURLDownloadCopyResumeData(m_download.get()));
148     if (resumeData)
149         DownloadBundle::appendResumeData(resumeData.get(), m_bundlePath);
150
151     didCancel(CoreIPC::DataReference());
152 }
153
154 void Download::platformInvalidate()
155 {
156     m_download = nullptr;
157     if (m_authenticationClient)
158         m_authenticationClient->detach();
159 }
160
161 void Download::didDecideDestination(const String& destination, bool allowOverwrite)
162 {
163     ASSERT(!destination.isEmpty());
164     if (destination.isEmpty())
165         return;
166
167     m_allowOverwrite = allowOverwrite;
168     m_destination = destination;
169     m_bundlePath = destination + DownloadBundle::fileExtension();
170
171     RetainPtr<CFStringRef> bundlePath(AdoptCF, CFStringCreateWithCharactersNoCopy(0, reinterpret_cast<const UniChar*>(m_bundlePath.characters()), m_bundlePath.length(), kCFAllocatorNull));
172     RetainPtr<CFURLRef> bundlePathURL(AdoptCF, CFURLCreateWithFileSystemPath(0, bundlePath.get(), kCFURLWindowsPathStyle, false));
173     CFURLDownloadSetDestination(m_download.get(), bundlePathURL.get(), allowOverwrite);
174 }
175
176 // CFURLDownload Callbacks ----------------------------------------------------------------
177 static Download* downloadFromClientInfo(const void* clientInfo)
178 {
179     return reinterpret_cast<Download*>(const_cast<void*>(clientInfo));
180 }
181
182 void didStartCallback(CFURLDownloadRef, const void* clientInfo)
183
184     downloadFromClientInfo(clientInfo)->didStart(); 
185 }
186
187 CFURLRequestRef willSendRequestCallback(CFURLDownloadRef, CFURLRequestRef request, CFURLResponseRef redirectionResponse, const void* clientInfo)
188
189     // CFNetwork requires us to return a retained request.
190     CFRetain(request);
191     return request;
192 }
193
194 void didReceiveAuthenticationChallengeCallback(CFURLDownloadRef, CFURLAuthChallengeRef challenge, const void* clientInfo)
195 {
196     Download* download = downloadFromClientInfo(clientInfo);
197     download->didReceiveAuthenticationChallenge(AuthenticationChallenge(challenge, download->authenticationClient()));
198 }
199
200 void didReceiveResponseCallback(CFURLDownloadRef, CFURLResponseRef response, const void* clientInfo)
201 {
202     downloadFromClientInfo(clientInfo)->didReceiveResponse(ResourceResponse(response)); 
203 }
204
205 void willResumeWithResponseCallback(CFURLDownloadRef, CFURLResponseRef response, UInt64 startingByte, const void* clientInfo)
206 {
207     // FIXME: implement.
208     notImplemented();
209 }
210
211 void didReceiveDataCallback(CFURLDownloadRef, CFIndex length, const void* clientInfo)
212
213     downloadFromClientInfo(clientInfo)->didReceiveData(length);
214 }
215
216 Boolean shouldDecodeDataOfMIMETypeCallback(CFURLDownloadRef, CFStringRef encodingType, const void* clientInfo)
217
218     return downloadFromClientInfo(clientInfo)->shouldDecodeSourceDataOfMIMEType(encodingType);
219 }
220
221 void decideDestinationWithSuggestedObjectNameCallback(CFURLDownloadRef, CFStringRef objectName, const void* clientInfo)
222
223     Download* download = downloadFromClientInfo(clientInfo);
224     bool allowOverwrite;
225     download->decideDestinationWithSuggestedFilename(objectName, allowOverwrite);
226 }
227
228 void didCreateDestinationCallback(CFURLDownloadRef, CFURLRef, const void* clientInfo)
229 {
230     // The concept of the ".download bundle" is internal to the Download, so we try to hide its
231     // existence by reporting the final destination was created, when in reality the bundle was created.
232
233     Download* download = downloadFromClientInfo(clientInfo);
234     download->didCreateDestination(download->destination());
235 }
236
237 void didFinishCallback(CFURLDownloadRef, const void* clientInfo)
238
239     downloadFromClientInfo(clientInfo)->didFinish();
240 }
241
242 void didFailCallback(CFURLDownloadRef, CFErrorRef error, const void* clientInfo)
243
244     CoreIPC::DataReference dataReference(0, 0);
245     downloadFromClientInfo(clientInfo)->didFail(ResourceError(error), dataReference);
246 }
247
248 void Download::receivedCredential(const AuthenticationChallenge& authenticationChallenge, const Credential& credential)
249 {
250     ASSERT(authenticationChallenge.authenticationClient());
251     authenticationChallenge.authenticationClient()->receivedCredential(authenticationChallenge, credential);
252 }
253
254 void Download::receivedRequestToContinueWithoutCredential(const AuthenticationChallenge& authenticationChallenge)
255 {
256     ASSERT(authenticationChallenge.authenticationClient());
257     authenticationChallenge.authenticationClient()->receivedRequestToContinueWithoutCredential(authenticationChallenge);
258 }
259
260 void Download::receivedCancellation(const AuthenticationChallenge& authenticationChallenge)
261 {
262     ASSERT(authenticationChallenge.authenticationClient());
263     authenticationChallenge.authenticationClient()->receivedCancellation(authenticationChallenge);
264 }
265
266 } // namespace WebKit