0c14615579438901a3fafbdf212b9a1e70ea482c
[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 "ResourceResponse.h"
32 #include "ScriptExecutionContext.h"
33 #include "ServiceWorker.h"
34 #include "TextResourceDecoder.h"
35 #include "WorkerGlobalScope.h"
36 #include "WorkerScriptLoaderClient.h"
37 #include "WorkerThreadableLoader.h"
38 #include <wtf/Ref.h>
39
40 namespace WebCore {
41
42 WorkerScriptLoader::WorkerScriptLoader() = default;
43
44 WorkerScriptLoader::~WorkerScriptLoader() = default;
45
46 void WorkerScriptLoader::loadSynchronously(ScriptExecutionContext* scriptExecutionContext, const URL& url, FetchOptions::Mode mode, FetchOptions::Cache cachePolicy, ContentSecurityPolicyEnforcement contentSecurityPolicyEnforcement, const String& initiatorIdentifier)
47 {
48     ASSERT(scriptExecutionContext);
49     auto& workerGlobalScope = downcast<WorkerGlobalScope>(*scriptExecutionContext);
50
51     m_url = url;
52
53     std::unique_ptr<ResourceRequest> request(createResourceRequest(initiatorIdentifier));
54     if (!request)
55         return;
56
57     ASSERT_WITH_SECURITY_IMPLICATION(is<WorkerGlobalScope>(scriptExecutionContext));
58
59     // Only used for importScripts that prescribes NoCors mode.
60     ASSERT(mode == FetchOptions::Mode::NoCors);
61
62     ThreadableLoaderOptions options;
63     options.credentials = FetchOptions::Credentials::Include;
64     options.mode = mode;
65     options.cache = cachePolicy;
66     options.sendLoadCallbacks = SendCallbacks;
67     options.contentSecurityPolicyEnforcement = contentSecurityPolicyEnforcement;
68 #if ENABLE(SERVICE_WORKER)
69     options.serviceWorkersMode = workerGlobalScope.isServiceWorkerGlobalScope() ? ServiceWorkersMode::None : ServiceWorkersMode::All;
70     if (auto* activeServiceWorker = workerGlobalScope.activeServiceWorker())
71         options.serviceWorkerIdentifier = activeServiceWorker->identifier();
72 #endif
73     WorkerThreadableLoader::loadResourceSynchronously(workerGlobalScope, WTFMove(*request), *this, options);
74 }
75
76 void WorkerScriptLoader::loadAsynchronously(ScriptExecutionContext& scriptExecutionContext, ResourceRequest&& scriptRequest, FetchOptions::Mode mode, FetchOptions::Cache cachePolicy, ContentSecurityPolicyEnforcement contentSecurityPolicyEnforcement, WorkerScriptLoaderClient& client)
77 {
78     m_client = &client;
79     m_url = scriptRequest.url();
80
81     ASSERT(scriptRequest.httpMethod() == "GET");
82
83     auto request = std::make_unique<ResourceRequest>(WTFMove(scriptRequest));
84     if (!request)
85         return;
86
87     // Only used for loading worker scripts in classic mode.
88     // FIXME: We should add an option to set credential mode.
89     ASSERT(mode == FetchOptions::Mode::SameOrigin);
90
91     ThreadableLoaderOptions options;
92     options.credentials = FetchOptions::Credentials::SameOrigin;
93     options.mode = mode;
94     options.cache = cachePolicy;
95     options.sendLoadCallbacks = SendCallbacks;
96     options.contentSecurityPolicyEnforcement = contentSecurityPolicyEnforcement;
97 #if ENABLE(SERVICE_WORKER)
98     options.serviceWorkersMode = m_client->isServiceWorkerClient() ? ServiceWorkersMode::None : ServiceWorkersMode::All;
99     if (auto* activeServiceWorker = scriptExecutionContext.activeServiceWorker())
100         options.serviceWorkerIdentifier = activeServiceWorker->identifier();
101 #endif
102     // During create, callbacks may happen which remove the last reference to this object.
103     Ref<WorkerScriptLoader> protectedThis(*this);
104     m_threadableLoader = ThreadableLoader::create(scriptExecutionContext, *this, WTFMove(*request), options);
105 }
106
107 const URL& WorkerScriptLoader::responseURL() const
108 {
109     ASSERT(!failed());
110     return m_responseURL;
111 }
112
113 std::unique_ptr<ResourceRequest> WorkerScriptLoader::createResourceRequest(const String& initiatorIdentifier)
114 {
115     auto request = std::make_unique<ResourceRequest>(m_url);
116     request->setHTTPMethod(ASCIILiteral("GET"));
117     request->setInitiatorIdentifier(initiatorIdentifier);
118     return request;
119 }
120
121 void WorkerScriptLoader::didReceiveResponse(unsigned long identifier, const ResourceResponse& response)
122 {
123     if (response.httpStatusCode() / 100 != 2 && response.httpStatusCode()) {
124         m_failed = true;
125         return;
126     }
127
128     if (!isScriptAllowedByNosniff(response)) {
129         m_failed = true;
130         return;
131     }
132
133     m_responseURL = response.url();
134     m_responseEncoding = response.textEncodingName();
135     if (m_client)
136         m_client->didReceiveResponse(identifier, response);
137 }
138
139 void WorkerScriptLoader::didReceiveData(const char* data, int len)
140 {
141     if (m_failed)
142         return;
143
144     if (!m_decoder) {
145         if (!m_responseEncoding.isEmpty())
146             m_decoder = TextResourceDecoder::create(ASCIILiteral("text/javascript"), m_responseEncoding);
147         else
148             m_decoder = TextResourceDecoder::create(ASCIILiteral("text/javascript"), "UTF-8");
149     }
150
151     if (!len)
152         return;
153     
154     if (len == -1)
155         len = strlen(data);
156     
157     m_script.append(m_decoder->decode(data, len));
158 }
159
160 void WorkerScriptLoader::didFinishLoading(unsigned long identifier)
161 {
162     if (m_failed) {
163         notifyError();
164         return;
165     }
166
167     if (m_decoder)
168         m_script.append(m_decoder->flush());
169
170     m_identifier = identifier;
171     notifyFinished();
172 }
173
174 void WorkerScriptLoader::didFail(const ResourceError& error)
175 {
176     m_error = error;
177     notifyError();
178 }
179
180 void WorkerScriptLoader::notifyError()
181 {
182     m_failed = true;
183     if (m_error.isNull())
184         m_error = ResourceError { errorDomainWebKitInternal, 0, url(), "Failed to load script", ResourceError::Type::General };
185     notifyFinished();
186 }
187
188 String WorkerScriptLoader::script()
189 {
190     return m_script.toString();
191 }
192
193 void WorkerScriptLoader::notifyFinished()
194 {
195     if (!m_client || m_finishing)
196         return;
197
198     m_finishing = true;
199     m_client->notifyFinished();
200 }
201
202 } // namespace WebCore