ServiceWorkerContainer is leaking due to a ref cycle
[WebKit-https.git] / Source / WebCore / workers / WorkerScriptLoader.cpp
1 /*
2  * Copyright (C) 2009-2017 Apple Inc. All Rights Reserved.
3  * Copyright (C) 2009, 2011 Google Inc. All Rights Reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  *
14  * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
15  * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
16  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
17  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL APPLE INC. OR
18  * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
19  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
20  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
21  * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
22  * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
23  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
24  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 
25  */
26
27 #include "config.h"
28 #include "WorkerScriptLoader.h"
29
30 #include "ContentSecurityPolicy.h"
31 #include "FetchIdioms.h"
32 #include "MIMETypeRegistry.h"
33 #include "ResourceResponse.h"
34 #include "ScriptExecutionContext.h"
35 #include "ServiceWorker.h"
36 #include "ServiceWorkerGlobalScope.h"
37 #include "TextResourceDecoder.h"
38 #include "WorkerGlobalScope.h"
39 #include "WorkerScriptLoaderClient.h"
40 #include "WorkerThreadableLoader.h"
41 #include <wtf/Ref.h>
42
43 namespace WebCore {
44
45 WorkerScriptLoader::WorkerScriptLoader() = default;
46
47 WorkerScriptLoader::~WorkerScriptLoader() = default;
48
49 Optional<Exception> WorkerScriptLoader::loadSynchronously(ScriptExecutionContext* scriptExecutionContext, const URL& url, FetchOptions::Mode mode, FetchOptions::Cache cachePolicy, ContentSecurityPolicyEnforcement contentSecurityPolicyEnforcement, const String& initiatorIdentifier)
50 {
51     ASSERT(scriptExecutionContext);
52     auto& workerGlobalScope = downcast<WorkerGlobalScope>(*scriptExecutionContext);
53
54     m_url = url;
55     m_destination = FetchOptions::Destination::Script;
56
57 #if ENABLE(SERVICE_WORKER)
58     bool isServiceWorkerGlobalScope = is<ServiceWorkerGlobalScope>(workerGlobalScope);
59
60     if (isServiceWorkerGlobalScope) {
61         if (auto* scriptResource = downcast<ServiceWorkerGlobalScope>(workerGlobalScope).scriptResource(url)) {
62             m_script.append(scriptResource->script);
63             m_responseURL = URL { URL { }, scriptResource->responseURL };
64             m_responseMIMEType = scriptResource->mimeType;
65             return WTF::nullopt;
66         }
67     }
68 #endif
69
70     std::unique_ptr<ResourceRequest> request(createResourceRequest(initiatorIdentifier));
71     if (!request)
72         return WTF::nullopt;
73
74     ASSERT_WITH_SECURITY_IMPLICATION(is<WorkerGlobalScope>(scriptExecutionContext));
75
76     // Only used for importScripts that prescribes NoCors mode.
77     ASSERT(mode == FetchOptions::Mode::NoCors);
78     request->setRequester(ResourceRequest::Requester::ImportScripts);
79
80     ThreadableLoaderOptions options;
81     options.credentials = FetchOptions::Credentials::Include;
82     options.mode = mode;
83     options.cache = cachePolicy;
84     options.sendLoadCallbacks = SendCallbackPolicy::SendCallbacks;
85     options.contentSecurityPolicyEnforcement = contentSecurityPolicyEnforcement;
86     options.destination = m_destination;
87 #if ENABLE(SERVICE_WORKER)
88     options.serviceWorkersMode = isServiceWorkerGlobalScope ? ServiceWorkersMode::None : ServiceWorkersMode::All;
89     if (auto* activeServiceWorker = workerGlobalScope.activeServiceWorker())
90         options.serviceWorkerRegistrationIdentifier = activeServiceWorker->registrationIdentifier();
91 #endif
92     WorkerThreadableLoader::loadResourceSynchronously(workerGlobalScope, WTFMove(*request), *this, options);
93
94     // If the fetching attempt failed, throw a NetworkError exception and abort all these steps.
95     if (failed())
96         return Exception { NetworkError, error().localizedDescription() };
97
98 #if ENABLE(SERVICE_WORKER)
99     if (isServiceWorkerGlobalScope) {
100         if (!MIMETypeRegistry::isSupportedJavaScriptMIMEType(responseMIMEType()))
101             return Exception { NetworkError, "mime type is not a supported JavaScript mime type"_s };
102
103         downcast<ServiceWorkerGlobalScope>(workerGlobalScope).setScriptResource(url, ServiceWorkerContextData::ImportedScript { script(), m_responseURL, m_responseMIMEType });
104     }
105 #endif
106     return WTF::nullopt;
107 }
108
109 void WorkerScriptLoader::loadAsynchronously(ScriptExecutionContext& scriptExecutionContext, ResourceRequest&& scriptRequest, FetchOptions&& fetchOptions, ContentSecurityPolicyEnforcement contentSecurityPolicyEnforcement, ServiceWorkersMode serviceWorkerMode, WorkerScriptLoaderClient& client)
110 {
111     m_client = &client;
112     m_url = scriptRequest.url();
113     m_destination = fetchOptions.destination;
114
115     ASSERT(scriptRequest.httpMethod() == "GET");
116
117     auto request = std::make_unique<ResourceRequest>(WTFMove(scriptRequest));
118     if (!request)
119         return;
120
121     // Only used for loading worker scripts in classic mode.
122     // FIXME: We should add an option to set credential mode.
123     ASSERT(fetchOptions.mode == FetchOptions::Mode::SameOrigin);
124
125     ThreadableLoaderOptions options { WTFMove(fetchOptions) };
126     options.credentials = FetchOptions::Credentials::SameOrigin;
127     options.sendLoadCallbacks = SendCallbackPolicy::SendCallbacks;
128     options.contentSecurityPolicyEnforcement = contentSecurityPolicyEnforcement;
129     // A service worker job can be executed from a worker context or a document context.
130     options.serviceWorkersMode = serviceWorkerMode;
131 #if ENABLE(SERVICE_WORKER)
132     if (auto* activeServiceWorker = scriptExecutionContext.activeServiceWorker())
133         options.serviceWorkerRegistrationIdentifier = activeServiceWorker->registrationIdentifier();
134 #endif
135
136     // During create, callbacks may happen which remove the last reference to this object.
137     Ref<WorkerScriptLoader> protectedThis(*this);
138     m_threadableLoader = ThreadableLoader::create(scriptExecutionContext, *this, WTFMove(*request), options);
139 }
140
141 const URL& WorkerScriptLoader::responseURL() const
142 {
143     ASSERT(!failed());
144     return m_responseURL;
145 }
146
147 std::unique_ptr<ResourceRequest> WorkerScriptLoader::createResourceRequest(const String& initiatorIdentifier)
148 {
149     auto request = std::make_unique<ResourceRequest>(m_url);
150     request->setHTTPMethod("GET"_s);
151     request->setInitiatorIdentifier(initiatorIdentifier);
152     return request;
153 }
154
155 void WorkerScriptLoader::didReceiveResponse(unsigned long identifier, const ResourceResponse& response)
156 {
157     if (response.httpStatusCode() / 100 != 2 && response.httpStatusCode()) {
158         m_failed = true;
159         return;
160     }
161
162     if (!isScriptAllowedByNosniff(response)) {
163         String message = makeString("Refused to execute ", response.url().stringCenterEllipsizedToLength(), " as script because \"X-Content-Type: nosniff\" was given and its Content-Type is not a script MIME type.");
164         m_error = ResourceError { errorDomainWebKitInternal, 0, url(), message, ResourceError::Type::General };
165         m_failed = true;
166         return;
167     }
168
169     if (shouldBlockResponseDueToMIMEType(response, m_destination)) {
170         String message = makeString("Refused to execute ", response.url().stringCenterEllipsizedToLength(), " as script because ", response.mimeType(), " is not a script MIME type.");
171         m_error = ResourceError { errorDomainWebKitInternal, 0, response.url(), message, ResourceError::Type::General };
172         m_failed = true;
173         return;
174     }
175
176     m_responseURL = response.url();
177     m_responseMIMEType = response.mimeType();
178     m_responseEncoding = response.textEncodingName();
179     m_contentSecurityPolicy = ContentSecurityPolicyResponseHeaders { response };
180     m_referrerPolicy = response.httpHeaderField(HTTPHeaderName::ReferrerPolicy);
181     if (m_client)
182         m_client->didReceiveResponse(identifier, response);
183 }
184
185 void WorkerScriptLoader::didReceiveData(const char* data, int len)
186 {
187     if (m_failed)
188         return;
189
190     if (!m_decoder) {
191         if (!m_responseEncoding.isEmpty())
192             m_decoder = TextResourceDecoder::create("text/javascript"_s, m_responseEncoding);
193         else
194             m_decoder = TextResourceDecoder::create("text/javascript"_s, "UTF-8");
195     }
196
197     if (!len)
198         return;
199     
200     if (len == -1)
201         len = strlen(data);
202     
203     m_script.append(m_decoder->decode(data, len));
204 }
205
206 void WorkerScriptLoader::didFinishLoading(unsigned long identifier)
207 {
208     if (m_failed) {
209         notifyError();
210         return;
211     }
212
213     if (m_decoder)
214         m_script.append(m_decoder->flush());
215
216     m_identifier = identifier;
217     notifyFinished();
218 }
219
220 void WorkerScriptLoader::didFail(const ResourceError& error)
221 {
222     m_error = error;
223     notifyError();
224 }
225
226 void WorkerScriptLoader::notifyError()
227 {
228     m_failed = true;
229     if (m_error.isNull())
230         m_error = ResourceError { errorDomainWebKitInternal, 0, url(), "Failed to load script", ResourceError::Type::General };
231     notifyFinished();
232 }
233
234 String WorkerScriptLoader::script()
235 {
236     return m_script.toString();
237 }
238
239 void WorkerScriptLoader::notifyFinished()
240 {
241     m_threadableLoader = nullptr;
242     if (!m_client || m_finishing)
243         return;
244
245     m_finishing = true;
246     m_client->notifyFinished();
247 }
248
249 void WorkerScriptLoader::cancel()
250 {
251     if (!m_threadableLoader)
252         return;
253
254     m_client = nullptr;
255     m_threadableLoader->cancel();
256     m_threadableLoader = nullptr;
257 }
258
259 } // namespace WebCore