We should use "error" redirect mode for fetching service worker scripts
[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, FetchOptions::Redirect redirectPolicy, 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.redirect = redirectPolicy;
96     options.sendLoadCallbacks = SendCallbacks;
97     options.contentSecurityPolicyEnforcement = contentSecurityPolicyEnforcement;
98 #if ENABLE(SERVICE_WORKER)
99     options.serviceWorkersMode = m_client->isServiceWorkerClient() ? ServiceWorkersMode::None : ServiceWorkersMode::All;
100     if (auto* activeServiceWorker = scriptExecutionContext.activeServiceWorker())
101         options.serviceWorkerIdentifier = activeServiceWorker->identifier();
102 #endif
103     // During create, callbacks may happen which remove the last reference to this object.
104     Ref<WorkerScriptLoader> protectedThis(*this);
105     m_threadableLoader = ThreadableLoader::create(scriptExecutionContext, *this, WTFMove(*request), options);
106 }
107
108 const URL& WorkerScriptLoader::responseURL() const
109 {
110     ASSERT(!failed());
111     return m_responseURL;
112 }
113
114 std::unique_ptr<ResourceRequest> WorkerScriptLoader::createResourceRequest(const String& initiatorIdentifier)
115 {
116     auto request = std::make_unique<ResourceRequest>(m_url);
117     request->setHTTPMethod(ASCIILiteral("GET"));
118     request->setInitiatorIdentifier(initiatorIdentifier);
119     return request;
120 }
121
122 void WorkerScriptLoader::didReceiveResponse(unsigned long identifier, const ResourceResponse& response)
123 {
124     if (response.httpStatusCode() / 100 != 2 && response.httpStatusCode()) {
125         m_failed = true;
126         return;
127     }
128
129     if (!isScriptAllowedByNosniff(response)) {
130         m_failed = true;
131         return;
132     }
133
134     m_responseURL = response.url();
135     m_responseEncoding = response.textEncodingName();
136     if (m_client)
137         m_client->didReceiveResponse(identifier, response);
138 }
139
140 void WorkerScriptLoader::didReceiveData(const char* data, int len)
141 {
142     if (m_failed)
143         return;
144
145     if (!m_decoder) {
146         if (!m_responseEncoding.isEmpty())
147             m_decoder = TextResourceDecoder::create(ASCIILiteral("text/javascript"), m_responseEncoding);
148         else
149             m_decoder = TextResourceDecoder::create(ASCIILiteral("text/javascript"), "UTF-8");
150     }
151
152     if (!len)
153         return;
154     
155     if (len == -1)
156         len = strlen(data);
157     
158     m_script.append(m_decoder->decode(data, len));
159 }
160
161 void WorkerScriptLoader::didFinishLoading(unsigned long identifier)
162 {
163     if (m_failed) {
164         notifyError();
165         return;
166     }
167
168     if (m_decoder)
169         m_script.append(m_decoder->flush());
170
171     m_identifier = identifier;
172     notifyFinished();
173 }
174
175 void WorkerScriptLoader::didFail(const ResourceError& error)
176 {
177     m_error = error;
178     notifyError();
179 }
180
181 void WorkerScriptLoader::notifyError()
182 {
183     m_failed = true;
184     if (m_error.isNull())
185         m_error = ResourceError { errorDomainWebKitInternal, 0, url(), "Failed to load script", ResourceError::Type::General };
186     notifyFinished();
187 }
188
189 String WorkerScriptLoader::script()
190 {
191     return m_script.toString();
192 }
193
194 void WorkerScriptLoader::notifyFinished()
195 {
196     if (!m_client || m_finishing)
197         return;
198
199     m_finishing = true;
200     m_client->notifyFinished();
201 }
202
203 } // namespace WebCore