navigator.onLine does not work inside service workers
[WebKit-https.git] / Source / WebCore / workers / service / context / ServiceWorkerThreadProxy.cpp
1 /*
2  * Copyright (C) 2017 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 "ServiceWorkerThreadProxy.h"
28
29 #if ENABLE(SERVICE_WORKER)
30
31 #include "CacheStorageProvider.h"
32 #include "FrameLoader.h"
33 #include "MainFrame.h"
34 #include "Settings.h"
35 #include <pal/SessionID.h>
36 #include <wtf/MainThread.h>
37 #include <wtf/RunLoop.h>
38
39 namespace WebCore {
40
41 URL static inline topOriginURL(const SecurityOrigin& origin)
42 {
43     URL url;
44     url.setProtocol(origin.protocol());
45     url.setHost(origin.host());
46     if (origin.port())
47         url.setPort(*origin.port());
48     return url;
49 }
50
51 static inline UniqueRef<Page> createPageForServiceWorker(PageConfiguration&& configuration, const ServiceWorkerContextData& data, SecurityOrigin::StorageBlockingPolicy storageBlockingPolicy)
52 {
53     auto page = makeUniqueRef<Page>(WTFMove(configuration));
54     auto& mainFrame = page->mainFrame();
55     mainFrame.loader().initForSynthesizedDocument({ });
56     auto document = Document::createNonRenderedPlaceholder(&mainFrame, data.scriptURL);
57     document->createDOMWindow();
58
59     document->mutableSettings().setStorageBlockingPolicy(storageBlockingPolicy);
60     document->storageBlockingStateDidChange();
61
62     auto origin = data.registration.key.topOrigin().securityOrigin();
63     origin->setStorageBlockingPolicy(storageBlockingPolicy);
64
65     document->setFirstPartyForCookies(topOriginURL(origin));
66     document->setDomainForCachePartition(origin->domainForCachePartition());
67     mainFrame.setDocument(WTFMove(document));
68     return page;
69 }
70
71 static inline IDBClient::IDBConnectionProxy* idbConnectionProxy(Document& document)
72 {
73 #if ENABLE(INDEXED_DATABASE)
74     return document.idbConnectionProxy();
75 #else
76     return nullptr;
77 #endif
78 }
79
80 static HashSet<ServiceWorkerThreadProxy*>& allServiceWorkerThreadProxies()
81 {
82     static NeverDestroyed<HashSet<ServiceWorkerThreadProxy*>> set;
83     return set;
84 }
85
86 ServiceWorkerThreadProxy::ServiceWorkerThreadProxy(PageConfiguration&& pageConfiguration, const ServiceWorkerContextData& data, PAL::SessionID sessionID, String&& userAgent, CacheStorageProvider& cacheStorageProvider, SecurityOrigin::StorageBlockingPolicy storageBlockingPolicy)
87     : m_page(createPageForServiceWorker(WTFMove(pageConfiguration), data, storageBlockingPolicy))
88     , m_document(*m_page->mainFrame().document())
89     , m_serviceWorkerThread(ServiceWorkerThread::create(data, sessionID, WTFMove(userAgent), *this, *this, idbConnectionProxy(m_document), m_document->socketProvider()))
90     , m_cacheStorageProvider(cacheStorageProvider)
91     , m_sessionID(sessionID)
92     , m_inspectorProxy(*this)
93 {
94     static bool addedListener;
95     if (!addedListener) {
96         NetworkStateNotifier::singleton().addListener(&networkStateChanged);
97         addedListener = true;
98     }
99
100     ASSERT(!allServiceWorkerThreadProxies().contains(this));
101     allServiceWorkerThreadProxies().add(this);
102
103 #if ENABLE(REMOTE_INSPECTOR)
104     m_remoteDebuggable = std::make_unique<ServiceWorkerDebuggable>(*this, data);
105     m_remoteDebuggable->setRemoteDebuggingAllowed(true);
106     m_remoteDebuggable->init();
107 #endif
108 }
109
110 ServiceWorkerThreadProxy::~ServiceWorkerThreadProxy()
111 {
112     ASSERT(allServiceWorkerThreadProxies().contains(this));
113     allServiceWorkerThreadProxies().remove(this);
114 }
115
116 bool ServiceWorkerThreadProxy::postTaskForModeToWorkerGlobalScope(ScriptExecutionContext::Task&& task, const String& mode)
117 {
118     if (m_isTerminatingOrTerminated)
119         return false;
120
121     m_serviceWorkerThread->runLoop().postTaskForMode(WTFMove(task), mode);
122     return true;
123 }
124
125 void ServiceWorkerThreadProxy::postTaskToLoader(ScriptExecutionContext::Task&& task)
126 {
127     callOnMainThread([task = WTFMove(task), this, protectedThis = makeRef(*this)] () mutable {
128         task.performTask(m_document.get());
129     });
130 }
131
132 void ServiceWorkerThreadProxy::postMessageToDebugger(const String& message)
133 {
134     RunLoop::main().dispatch([this, protectedThis = makeRef(*this), message = message.isolatedCopy()] {
135         // FIXME: Handle terminated case.
136         m_inspectorProxy.sendMessageFromWorkerToFrontend(message);
137     });
138 }
139
140 void ServiceWorkerThreadProxy::setResourceCachingDisabled(bool disabled)
141 {
142     postTaskToLoader([this, protectedThis = makeRef(*this), disabled] (ScriptExecutionContext&) {
143         ASSERT(isMainThread());
144         m_page->setResourceCachingDisabled(disabled);
145     });   
146 }
147
148 Ref<CacheStorageConnection> ServiceWorkerThreadProxy::createCacheStorageConnection()
149 {
150     ASSERT(isMainThread());
151     if (!m_cacheStorageConnection)
152         m_cacheStorageConnection = m_cacheStorageProvider.createCacheStorageConnection(m_sessionID);
153     return *m_cacheStorageConnection;
154 }
155
156 std::unique_ptr<FetchLoader> ServiceWorkerThreadProxy::createBlobLoader(FetchLoaderClient& client, const URL& blobURL)
157 {
158     auto loader = std::make_unique<FetchLoader>(client, nullptr);
159     loader->startLoadingBlobURL(m_document, blobURL);
160     if (!loader->isStarted())
161         return nullptr;
162     return loader;
163 }
164
165 void ServiceWorkerThreadProxy::networkStateChanged(bool isOnLine)
166 {
167     for (auto* proxy : allServiceWorkerThreadProxies())
168         proxy->notifyNetworkStateChange(isOnLine);
169 }
170
171 void ServiceWorkerThreadProxy::notifyNetworkStateChange(bool isOnline)
172 {
173     if (m_isTerminatingOrTerminated)
174         return;
175
176     postTaskForModeToWorkerGlobalScope([isOnline] (ScriptExecutionContext& context) {
177         auto& globalScope = downcast<WorkerGlobalScope>(context);
178         globalScope.setIsOnline(isOnline);
179         globalScope.dispatchEvent(Event::create(isOnline ? eventNames().onlineEvent : eventNames().offlineEvent, false, false));
180     }, WorkerRunLoop::defaultMode());
181 }
182
183 } // namespace WebCore
184
185 #endif // ENABLE(SERVICE_WORKER)