WebCore:
[WebKit-https.git] / WebCore / loader / WorkerThreadableLoader.cpp
1 /*
2  * Copyright (C) 2009 Google 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 are
6  * met:
7  *
8  *     * Redistributions of source code must retain the above copyright
9  * notice, this list of conditions and the following disclaimer.
10  *     * Redistributions in binary form must reproduce the above
11  * copyright notice, this list of conditions and the following disclaimer
12  * in the documentation and/or other materials provided with the
13  * distribution.
14  *     * Neither the name of Google Inc. nor the names of its
15  * contributors may be used to endorse or promote products derived from
16  * this software without specific prior written permission.
17  *
18  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21  * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22  * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29  */
30
31 #include "config.h"
32
33 #if ENABLE(WORKERS)
34
35 #include "WorkerThreadableLoader.h"
36
37 #include "GenericWorkerTask.h"
38 #include "ResourceError.h"
39 #include "ResourceRequest.h"
40 #include "ResourceResponse.h"
41 #include "ThreadableLoader.h"
42 #include "WorkerContext.h"
43 #include "WorkerLoaderProxy.h"
44 #include "WorkerThread.h"
45 #include <memory>
46 #include <wtf/OwnPtr.h>
47 #include <wtf/Threading.h>
48 #include <wtf/Vector.h>
49
50 using namespace std;
51
52 namespace WebCore {
53
54 static const char loadResourceSynchronouslyMode[] = "loadResourceSynchronouslyMode";
55
56 WorkerThreadableLoader::WorkerThreadableLoader(WorkerContext* workerContext, ThreadableLoaderClient* client, const String& taskMode, const ResourceRequest& request, LoadCallbacks callbacksSetting,
57                                                ContentSniff contentSniff, StoredCredentials storedCredentials, RedirectOriginCheck redirectOriginCheck)
58     : m_workerContext(workerContext)
59     , m_workerClientWrapper(ThreadableLoaderClientWrapper::create(client))
60     , m_bridge(*(new MainThreadBridge(m_workerClientWrapper, m_workerContext->thread()->workerLoaderProxy(), taskMode, request, callbacksSetting, contentSniff, storedCredentials, redirectOriginCheck)))
61 {
62 }
63
64 WorkerThreadableLoader::~WorkerThreadableLoader()
65 {
66     m_bridge.destroy();
67 }
68
69 void WorkerThreadableLoader::loadResourceSynchronously(WorkerContext* workerContext, const ResourceRequest& request, ThreadableLoaderClient& client, StoredCredentials storedCredentials, RedirectOriginCheck redirectOriginCheck)
70 {
71     WorkerRunLoop& runLoop = workerContext->thread()->runLoop();
72
73     // Create a unique mode just for this synchronous resource load.
74     String mode = loadResourceSynchronouslyMode;
75     mode.append(String::number(runLoop.createUniqueId()));
76
77     ContentSniff contentSniff = request.url().isLocalFile() ? SniffContent : DoNotSniffContent;
78     RefPtr<WorkerThreadableLoader> loader = WorkerThreadableLoader::create(workerContext, &client, mode, request, DoNotSendLoadCallbacks, contentSniff, storedCredentials, redirectOriginCheck);
79
80     MessageQueueWaitResult result = MessageQueueMessageReceived;
81     while (!loader->done() && result != MessageQueueTerminated)
82         result = runLoop.runInMode(workerContext, mode);
83
84     if (!loader->done() && result == MessageQueueTerminated)
85         loader->cancel();
86 }
87
88 void WorkerThreadableLoader::cancel()
89 {
90     m_bridge.cancel();
91 }
92
93 WorkerThreadableLoader::MainThreadBridge::MainThreadBridge(PassRefPtr<ThreadableLoaderClientWrapper> workerClientWrapper, WorkerLoaderProxy& loaderProxy, const String& taskMode,
94                                                            const ResourceRequest& request, LoadCallbacks callbacksSetting, ContentSniff contentSniff, StoredCredentials storedCredentials,
95                                                            RedirectOriginCheck redirectOriginCheck)
96     : m_workerClientWrapper(workerClientWrapper)
97     , m_loaderProxy(loaderProxy)
98     , m_taskMode(taskMode.copy())
99 {
100     ASSERT(m_workerClientWrapper.get());
101     m_loaderProxy.postTaskToLoader(createCallbackTask(&MainThreadBridge::mainThreadCreateLoader, this, request, callbacksSetting, contentSniff, storedCredentials, redirectOriginCheck));
102 }
103
104 WorkerThreadableLoader::MainThreadBridge::~MainThreadBridge()
105 {
106 }
107
108 void WorkerThreadableLoader::MainThreadBridge::mainThreadCreateLoader(ScriptExecutionContext* context, MainThreadBridge* thisPtr, auto_ptr<CrossThreadResourceRequestData> requestData, LoadCallbacks callbacksSetting, ContentSniff contentSniff, StoredCredentials storedCredentials, RedirectOriginCheck redirectOriginCheck)
109 {
110     ASSERT(isMainThread());
111     ASSERT(context->isDocument());
112
113     // FIXME: the created loader has no knowledge of the origin of the worker doing the load request.
114     // Basically every setting done in SubresourceLoader::create (including the contents of addExtraFieldsToRequest)
115     // needs to be examined for how it should take into account a different originator.
116     OwnPtr<ResourceRequest> request(ResourceRequest::adopt(requestData));
117     // FIXME: If the a site requests a local resource, then this will return a non-zero value but the sync path
118     // will return a 0 value.  Either this should return 0 or the other code path should do a callback with
119     // a failure.
120     thisPtr->m_mainThreadLoader = ThreadableLoader::create(context, thisPtr, *request, callbacksSetting, contentSniff, storedCredentials, redirectOriginCheck);
121     ASSERT(thisPtr->m_mainThreadLoader);
122 }
123
124 void WorkerThreadableLoader::MainThreadBridge::mainThreadDestroy(ScriptExecutionContext* context, MainThreadBridge* thisPtr)
125 {
126     ASSERT(isMainThread());
127     ASSERT_UNUSED(context, context->isDocument());
128     delete thisPtr;
129 }
130
131 void WorkerThreadableLoader::MainThreadBridge::destroy()
132 {
133     // Ensure that no more client callbacks are done in the worker context's thread.
134     clearClientWrapper();
135
136     // "delete this" and m_mainThreadLoader::deref() on the worker object's thread.
137     m_loaderProxy.postTaskToLoader(createCallbackTask(&MainThreadBridge::mainThreadDestroy, this));
138 }
139
140 void WorkerThreadableLoader::MainThreadBridge::mainThreadCancel(ScriptExecutionContext* context, MainThreadBridge* thisPtr)
141 {
142     ASSERT(isMainThread());
143     ASSERT_UNUSED(context, context->isDocument());
144
145     if (!thisPtr->m_mainThreadLoader)
146         return;
147     thisPtr->m_mainThreadLoader->cancel();
148     thisPtr->m_mainThreadLoader = 0;
149 }
150
151 void WorkerThreadableLoader::MainThreadBridge::cancel()
152 {
153     m_loaderProxy.postTaskToLoader(createCallbackTask(&MainThreadBridge::mainThreadCancel, this));
154     ThreadableLoaderClientWrapper* clientWrapper = static_cast<ThreadableLoaderClientWrapper*>(m_workerClientWrapper.get());
155     if (!clientWrapper->done()) {
156         // If the client hasn't reached a termination state, then transition it by sending a cancellation error.
157         // Note: no more client callbacks will be done after this method -- the clearClientWrapper() call ensures that.
158         ResourceError error(String(), 0, String(), String());
159         error.setIsCancellation(true);
160         clientWrapper->didFail(error);
161     }
162     clearClientWrapper();
163 }
164
165 void WorkerThreadableLoader::MainThreadBridge::clearClientWrapper()
166 {
167     static_cast<ThreadableLoaderClientWrapper*>(m_workerClientWrapper.get())->clearClient();
168 }
169
170 static void workerContextDidSendData(ScriptExecutionContext* context, RefPtr<ThreadableLoaderClientWrapper> workerClientWrapper, unsigned long long bytesSent, unsigned long long totalBytesToBeSent)
171 {
172     ASSERT_UNUSED(context, context->isWorkerContext());
173     workerClientWrapper->didSendData(bytesSent, totalBytesToBeSent);
174 }
175
176 void WorkerThreadableLoader::MainThreadBridge::didSendData(unsigned long long bytesSent, unsigned long long totalBytesToBeSent)
177 {
178     m_loaderProxy.postTaskForModeToWorkerContext(createCallbackTask(&workerContextDidSendData, m_workerClientWrapper, bytesSent, totalBytesToBeSent), m_taskMode);
179 }
180
181 static void workerContextDidReceiveResponse(ScriptExecutionContext* context, RefPtr<ThreadableLoaderClientWrapper> workerClientWrapper, auto_ptr<CrossThreadResourceResponseData> responseData)
182 {
183     ASSERT_UNUSED(context, context->isWorkerContext());
184     OwnPtr<ResourceResponse> response(ResourceResponse::adopt(responseData));
185     workerClientWrapper->didReceiveResponse(*response);
186 }
187
188 void WorkerThreadableLoader::MainThreadBridge::didReceiveResponse(const ResourceResponse& response)
189 {
190     m_loaderProxy.postTaskForModeToWorkerContext(createCallbackTask(&workerContextDidReceiveResponse, m_workerClientWrapper, response), m_taskMode);
191 }
192
193 static void workerContextDidReceiveData(ScriptExecutionContext* context, RefPtr<ThreadableLoaderClientWrapper> workerClientWrapper, auto_ptr<Vector<char> > vectorData)
194 {
195     ASSERT_UNUSED(context, context->isWorkerContext());
196     workerClientWrapper->didReceiveData(vectorData->data(), vectorData->size());
197 }
198
199 void WorkerThreadableLoader::MainThreadBridge::didReceiveData(const char* data, int lengthReceived)
200 {
201     auto_ptr<Vector<char> > vector(new Vector<char>(lengthReceived)); // needs to be an auto_ptr for usage with createCallbackTask.
202     memcpy(vector->data(), data, lengthReceived);
203     m_loaderProxy.postTaskForModeToWorkerContext(createCallbackTask(&workerContextDidReceiveData, m_workerClientWrapper, vector), m_taskMode);
204 }
205
206 static void workerContextDidFinishLoading(ScriptExecutionContext* context, RefPtr<ThreadableLoaderClientWrapper> workerClientWrapper, unsigned long identifier)
207 {
208     ASSERT_UNUSED(context, context->isWorkerContext());
209     workerClientWrapper->didFinishLoading(identifier);
210 }
211
212 void WorkerThreadableLoader::MainThreadBridge::didFinishLoading(unsigned long identifier)
213 {
214     m_loaderProxy.postTaskForModeToWorkerContext(createCallbackTask(&workerContextDidFinishLoading, m_workerClientWrapper, identifier), m_taskMode);
215 }
216
217 static void workerContextDidFail(ScriptExecutionContext* context, RefPtr<ThreadableLoaderClientWrapper> workerClientWrapper, const ResourceError& error)
218 {
219     ASSERT_UNUSED(context, context->isWorkerContext());
220     workerClientWrapper->didFail(error);
221 }
222
223 void WorkerThreadableLoader::MainThreadBridge::didFail(const ResourceError& error)
224 {
225     m_loaderProxy.postTaskForModeToWorkerContext(createCallbackTask(&workerContextDidFail, m_workerClientWrapper, error), m_taskMode);
226 }
227
228 static void workerContextDidFailRedirectCheck(ScriptExecutionContext* context, RefPtr<ThreadableLoaderClientWrapper> workerClientWrapper)
229 {
230     ASSERT_UNUSED(context, context->isWorkerContext());
231     workerClientWrapper->didFailRedirectCheck();
232 }
233
234 void WorkerThreadableLoader::MainThreadBridge::didFailRedirectCheck()
235 {
236     m_loaderProxy.postTaskForModeToWorkerContext(createCallbackTask(&workerContextDidFailRedirectCheck, m_workerClientWrapper), m_taskMode);
237 }
238
239 static void workerContextDidReceiveAuthenticationCancellation(ScriptExecutionContext* context, RefPtr<ThreadableLoaderClientWrapper> workerClientWrapper, auto_ptr<CrossThreadResourceResponseData> responseData)
240 {
241     ASSERT_UNUSED(context, context->isWorkerContext());
242     OwnPtr<ResourceResponse> response(ResourceResponse::adopt(responseData));
243     workerClientWrapper->didReceiveAuthenticationCancellation(*response);
244 }
245
246 void WorkerThreadableLoader::MainThreadBridge::didReceiveAuthenticationCancellation(const ResourceResponse& response)
247 {
248     m_loaderProxy.postTaskForModeToWorkerContext(createCallbackTask(&workerContextDidReceiveAuthenticationCancellation, m_workerClientWrapper, response), m_taskMode);
249 }
250
251 } // namespace WebCore
252
253 #endif // ENABLE(WORKERS)