[iOS] We should not take a background assertion for the UIProcess when app is MobileMail
[WebKit-https.git] / Source / WebKit2 / UIProcess / Network / NetworkProcessProxy.cpp
1 /*
2  * Copyright (C) 2012-2016 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 "NetworkProcessProxy.h"
28
29 #include "AuthenticationChallengeProxy.h"
30 #include "DatabaseProcessMessages.h"
31 #include "DownloadProxyMessages.h"
32 #include "LegacyCustomProtocolManagerProxyMessages.h"
33 #include "Logging.h"
34 #include "NetworkProcessCreationParameters.h"
35 #include "NetworkProcessMessages.h"
36 #include "SandboxExtension.h"
37 #include "WebProcessMessages.h"
38 #include "WebProcessPool.h"
39 #include "WebsiteData.h"
40
41 #if ENABLE(SEC_ITEM_SHIM)
42 #include "SecItemShimProxy.h"
43 #endif
44
45 #if PLATFORM(IOS)
46 #include <wtf/spi/darwin/XPCSPI.h>
47 #endif
48
49 #define MESSAGE_CHECK(assertion) MESSAGE_CHECK_BASE(assertion, connection())
50
51 using namespace WebCore;
52
53 namespace WebKit {
54
55 static uint64_t generateCallbackID()
56 {
57     static uint64_t callbackID;
58
59     return ++callbackID;
60 }
61
62 Ref<NetworkProcessProxy> NetworkProcessProxy::create(WebProcessPool& processPool)
63 {
64     return adoptRef(*new NetworkProcessProxy(processPool));
65 }
66
67 NetworkProcessProxy::NetworkProcessProxy(WebProcessPool& processPool)
68     : ChildProcessProxy(processPool.alwaysRunsAtBackgroundPriority())
69     , m_processPool(processPool)
70     , m_numPendingConnectionRequests(0)
71     , m_customProtocolManagerProxy(this, processPool)
72     , m_throttler(*this, processPool.shouldTakeUIBackgroundAssertion())
73 {
74     connect();
75 }
76
77 NetworkProcessProxy::~NetworkProcessProxy()
78 {
79     ASSERT(m_pendingFetchWebsiteDataCallbacks.isEmpty());
80     ASSERT(m_pendingDeleteWebsiteDataCallbacks.isEmpty());
81     ASSERT(m_pendingDeleteWebsiteDataForOriginsCallbacks.isEmpty());
82 }
83
84 void NetworkProcessProxy::getLaunchOptions(ProcessLauncher::LaunchOptions& launchOptions)
85 {
86     launchOptions.processType = ProcessLauncher::ProcessType::Network;
87     ChildProcessProxy::getLaunchOptions(launchOptions);
88 }
89
90 void NetworkProcessProxy::connectionWillOpen(IPC::Connection& connection)
91 {
92 #if ENABLE(SEC_ITEM_SHIM)
93     SecItemShimProxy::singleton().initializeConnection(connection);
94 #else
95     UNUSED_PARAM(connection);
96 #endif
97 }
98
99 void NetworkProcessProxy::processWillShutDown(IPC::Connection& connection)
100 {
101     ASSERT_UNUSED(connection, this->connection() == &connection);
102 }
103
104 void NetworkProcessProxy::getNetworkProcessConnection(Ref<Messages::WebProcessProxy::GetNetworkProcessConnection::DelayedReply>&& reply)
105 {
106     m_pendingConnectionReplies.append(WTFMove(reply));
107
108     if (state() == State::Launching) {
109         m_numPendingConnectionRequests++;
110         return;
111     }
112
113     connection()->send(Messages::NetworkProcess::CreateNetworkConnectionToWebProcess(), 0, IPC::SendOption::DispatchMessageEvenWhenWaitingForSyncReply);
114 }
115
116 DownloadProxy* NetworkProcessProxy::createDownloadProxy(const ResourceRequest& resourceRequest)
117 {
118     if (!m_downloadProxyMap)
119         m_downloadProxyMap = std::make_unique<DownloadProxyMap>(this);
120
121     return m_downloadProxyMap->createDownloadProxy(m_processPool, resourceRequest);
122 }
123
124 void NetworkProcessProxy::fetchWebsiteData(SessionID sessionID, OptionSet<WebsiteDataType> dataTypes, OptionSet<WebsiteDataFetchOption> fetchOptions, std::function<void (WebsiteData)> completionHandler)
125 {
126     ASSERT(canSendMessage());
127
128     uint64_t callbackID = generateCallbackID();
129     auto token = throttler().backgroundActivityToken();
130     RELEASE_LOG_IF(sessionID.isAlwaysOnLoggingAllowed(), ProcessSuspension, "%p - NetworkProcessProxy is taking a background assertion because the Network process is fetching Website data", this);
131
132     m_pendingFetchWebsiteDataCallbacks.add(callbackID, [this, token, completionHandler, sessionID](WebsiteData websiteData) {
133         completionHandler(WTFMove(websiteData));
134         RELEASE_LOG_IF(sessionID.isAlwaysOnLoggingAllowed(), ProcessSuspension, "%p - NetworkProcessProxy is releasing a background assertion because the Network process is done fetching Website data", this);
135     });
136
137     send(Messages::NetworkProcess::FetchWebsiteData(sessionID, dataTypes, fetchOptions, callbackID), 0);
138 }
139
140 void NetworkProcessProxy::deleteWebsiteData(WebCore::SessionID sessionID, OptionSet<WebsiteDataType> dataTypes, std::chrono::system_clock::time_point modifiedSince,  std::function<void ()> completionHandler)
141 {
142     auto callbackID = generateCallbackID();
143     auto token = throttler().backgroundActivityToken();
144     RELEASE_LOG_IF(sessionID.isAlwaysOnLoggingAllowed(), ProcessSuspension, "%p - NetworkProcessProxy is taking a background assertion because the Network process is deleting Website data", this);
145
146     m_pendingDeleteWebsiteDataCallbacks.add(callbackID, [this, token, completionHandler, sessionID] {
147         completionHandler();
148         RELEASE_LOG_IF(sessionID.isAlwaysOnLoggingAllowed(), ProcessSuspension, "%p - NetworkProcessProxy is releasing a background assertion because the Network process is done deleting Website data", this);
149     });
150     send(Messages::NetworkProcess::DeleteWebsiteData(sessionID, dataTypes, modifiedSince, callbackID), 0);
151 }
152
153 void NetworkProcessProxy::deleteWebsiteDataForOrigins(SessionID sessionID, OptionSet<WebsiteDataType> dataTypes, const Vector<WebCore::SecurityOriginData>& origins, const Vector<String>& cookieHostNames, std::function<void()> completionHandler)
154 {
155     ASSERT(canSendMessage());
156
157     uint64_t callbackID = generateCallbackID();
158     auto token = throttler().backgroundActivityToken();
159     RELEASE_LOG_IF(sessionID.isAlwaysOnLoggingAllowed(), ProcessSuspension, "%p - NetworkProcessProxy is taking a background assertion because the Network process is deleting Website data for several origins", this);
160
161     m_pendingDeleteWebsiteDataForOriginsCallbacks.add(callbackID, [this, token, completionHandler, sessionID] {
162         completionHandler();
163         RELEASE_LOG_IF(sessionID.isAlwaysOnLoggingAllowed(), ProcessSuspension, "%p - NetworkProcessProxy is releasing a background assertion because the Network process is done deleting Website data for several origins", this);
164     });
165
166     send(Messages::NetworkProcess::DeleteWebsiteDataForOrigins(sessionID, dataTypes, origins, cookieHostNames, callbackID), 0);
167 }
168
169 void NetworkProcessProxy::networkProcessCrashedOrFailedToLaunch()
170 {
171     // The network process must have crashed or exited, send any pending sync replies we might have.
172     while (!m_pendingConnectionReplies.isEmpty()) {
173         Ref<Messages::WebProcessProxy::GetNetworkProcessConnection::DelayedReply> reply = m_pendingConnectionReplies.takeFirst();
174
175 #if USE(UNIX_DOMAIN_SOCKETS)
176         reply->send(IPC::Attachment());
177 #elif OS(DARWIN)
178         reply->send(IPC::Attachment(0, MACH_MSG_TYPE_MOVE_SEND));
179 #else
180         notImplemented();
181 #endif
182     }
183
184     for (const auto& callback : m_pendingFetchWebsiteDataCallbacks.values())
185         callback(WebsiteData());
186     m_pendingFetchWebsiteDataCallbacks.clear();
187
188     for (const auto& callback : m_pendingDeleteWebsiteDataCallbacks.values())
189         callback();
190     m_pendingDeleteWebsiteDataCallbacks.clear();
191
192     for (const auto& callback : m_pendingDeleteWebsiteDataForOriginsCallbacks.values())
193         callback();
194     m_pendingDeleteWebsiteDataForOriginsCallbacks.clear();
195
196     // Tell the network process manager to forget about this network process proxy. This may cause us to be deleted.
197     m_processPool.networkProcessCrashed(this);
198 }
199
200 void NetworkProcessProxy::didReceiveMessage(IPC::Connection& connection, IPC::Decoder& decoder)
201 {
202     if (dispatchMessage(connection, decoder))
203         return;
204
205     if (m_processPool.dispatchMessage(connection, decoder))
206         return;
207
208     didReceiveNetworkProcessProxyMessage(connection, decoder);
209 }
210
211 void NetworkProcessProxy::didReceiveSyncMessage(IPC::Connection& connection, IPC::Decoder& decoder, std::unique_ptr<IPC::Encoder>& replyEncoder)
212 {
213     if (dispatchSyncMessage(connection, decoder, replyEncoder))
214         return;
215
216     ASSERT_NOT_REACHED();
217 }
218
219 void NetworkProcessProxy::didClose(IPC::Connection&)
220 {
221     if (m_downloadProxyMap)
222         m_downloadProxyMap->processDidClose();
223     m_customProtocolManagerProxy.processDidClose();
224
225     m_tokenForHoldingLockedFiles = nullptr;
226
227     // This may cause us to be deleted.
228     networkProcessCrashedOrFailedToLaunch();
229 }
230
231 void NetworkProcessProxy::didReceiveInvalidMessage(IPC::Connection&, IPC::StringReference, IPC::StringReference)
232 {
233 }
234
235 void NetworkProcessProxy::didCreateNetworkConnectionToWebProcess(const IPC::Attachment& connectionIdentifier)
236 {
237     ASSERT(!m_pendingConnectionReplies.isEmpty());
238
239     // Grab the first pending connection reply.
240     RefPtr<Messages::WebProcessProxy::GetNetworkProcessConnection::DelayedReply> reply = m_pendingConnectionReplies.takeFirst();
241
242 #if USE(UNIX_DOMAIN_SOCKETS)
243     reply->send(connectionIdentifier);
244 #elif OS(DARWIN)
245     reply->send(IPC::Attachment(connectionIdentifier.port(), MACH_MSG_TYPE_MOVE_SEND));
246 #else
247     notImplemented();
248 #endif
249 }
250
251 void NetworkProcessProxy::didReceiveAuthenticationChallenge(uint64_t pageID, uint64_t frameID, const WebCore::AuthenticationChallenge& coreChallenge, uint64_t challengeID)
252 {
253     WebPageProxy* page = WebProcessProxy::webPage(pageID);
254     MESSAGE_CHECK(page);
255
256     auto authenticationChallenge = AuthenticationChallengeProxy::create(coreChallenge, challengeID, connection());
257     page->didReceiveAuthenticationChallengeProxy(frameID, WTFMove(authenticationChallenge));
258 }
259
260 void NetworkProcessProxy::didFetchWebsiteData(uint64_t callbackID, const WebsiteData& websiteData)
261 {
262     auto callback = m_pendingFetchWebsiteDataCallbacks.take(callbackID);
263     callback(websiteData);
264 }
265
266 void NetworkProcessProxy::didDeleteWebsiteData(uint64_t callbackID)
267 {
268     auto callback = m_pendingDeleteWebsiteDataCallbacks.take(callbackID);
269     callback();
270 }
271
272 void NetworkProcessProxy::didDeleteWebsiteDataForOrigins(uint64_t callbackID)
273 {
274     auto callback = m_pendingDeleteWebsiteDataForOriginsCallbacks.take(callbackID);
275     callback();
276 }
277
278 void NetworkProcessProxy::grantSandboxExtensionsToDatabaseProcessForBlobs(uint64_t requestID, const Vector<String>& paths)
279 {
280 #if ENABLE(DATABASE_PROCESS)
281 #if ENABLE(SANDBOX_EXTENSIONS)
282     SandboxExtension::HandleArray extensions;
283     extensions.allocate(paths.size());
284     for (size_t i = 0; i < paths.size(); ++i) {
285         // ReadWrite is required for creating hard links as well as deleting the temporary file, which the DatabaseProcess will do.
286         SandboxExtension::createHandle(paths[i], SandboxExtension::ReadWrite, extensions[i]);
287     }
288
289     m_processPool.sendToDatabaseProcessRelaunchingIfNecessary(Messages::DatabaseProcess::GrantSandboxExtensionsForBlobs(paths, extensions));
290 #endif
291     connection()->send(Messages::NetworkProcess::DidGrantSandboxExtensionsToDatabaseProcessForBlobs(requestID), 0);
292 #endif
293 }
294
295 #if HAVE(CFNETWORK_STORAGE_PARTITIONING)
296 void NetworkProcessProxy::shouldPartitionCookiesForTopPrivatelyOwnedDomains(const Vector<String>& domainsToRemove, const Vector<String>& domainsToAdd, bool clearFirst)
297 {
298     connection()->send(Messages::NetworkProcess::ShouldPartitionCookiesForTopPrivatelyOwnedDomains(domainsToRemove, domainsToAdd, clearFirst), 0);
299 }
300 #endif
301
302 void NetworkProcessProxy::didFinishLaunching(ProcessLauncher* launcher, IPC::Connection::Identifier connectionIdentifier)
303 {
304     ChildProcessProxy::didFinishLaunching(launcher, connectionIdentifier);
305
306     if (IPC::Connection::identifierIsNull(connectionIdentifier)) {
307         networkProcessCrashedOrFailedToLaunch();
308         return;
309     }
310
311     for (unsigned i = 0; i < m_numPendingConnectionRequests; ++i)
312         connection()->send(Messages::NetworkProcess::CreateNetworkConnectionToWebProcess(), 0);
313     
314     m_numPendingConnectionRequests = 0;
315
316 #if PLATFORM(COCOA)
317     if (m_processPool.processSuppressionEnabled())
318         setProcessSuppressionEnabled(true);
319 #endif
320     
321 #if PLATFORM(IOS)
322     if (xpc_connection_t connection = this->connection()->xpcConnection())
323         m_throttler.didConnectToProcess(xpc_connection_get_pid(connection));
324 #endif
325 }
326
327 void NetworkProcessProxy::logDiagnosticMessage(uint64_t pageID, const String& message, const String& description, WebCore::ShouldSample shouldSample)
328 {
329     WebPageProxy* page = WebProcessProxy::webPage(pageID);
330     // FIXME: We do this null-check because by the time the decision to log is made, the page may be gone. We should refactor to avoid this,
331     // but for now we simply drop the message in the rare case this happens.
332     if (!page)
333         return;
334
335     page->logDiagnosticMessage(message, description, shouldSample);
336 }
337
338 void NetworkProcessProxy::logDiagnosticMessageWithResult(uint64_t pageID, const String& message, const String& description, uint32_t result, WebCore::ShouldSample shouldSample)
339 {
340     WebPageProxy* page = WebProcessProxy::webPage(pageID);
341     // FIXME: We do this null-check because by the time the decision to log is made, the page may be gone. We should refactor to avoid this,
342     // but for now we simply drop the message in the rare case this happens.
343     if (!page)
344         return;
345
346     page->logDiagnosticMessageWithResult(message, description, result, shouldSample);
347 }
348
349 void NetworkProcessProxy::logDiagnosticMessageWithValue(uint64_t pageID, const String& message, const String& description, double value, unsigned significantFigures, WebCore::ShouldSample shouldSample)
350 {
351     WebPageProxy* page = WebProcessProxy::webPage(pageID);
352     // FIXME: We do this null-check because by the time the decision to log is made, the page may be gone. We should refactor to avoid this,
353     // but for now we simply drop the message in the rare case this happens.
354     if (!page)
355         return;
356
357     page->logDiagnosticMessageWithValue(message, description, value, significantFigures, shouldSample);
358 }
359
360 #if USE(PROTECTION_SPACE_AUTH_CALLBACK)
361 void NetworkProcessProxy::canAuthenticateAgainstProtectionSpace(uint64_t loaderID, uint64_t pageID, uint64_t frameID, const WebCore::ProtectionSpace& protectionSpace)
362 {
363     WebPageProxy* page = WebProcessProxy::webPage(pageID);
364     if (!page)
365         return;
366     
367     page->canAuthenticateAgainstProtectionSpace(loaderID, frameID, protectionSpace);
368 }
369 #endif
370
371 void NetworkProcessProxy::sendProcessWillSuspendImminently()
372 {
373     if (!canSendMessage())
374         return;
375
376     bool handled = false;
377     sendSync(Messages::NetworkProcess::ProcessWillSuspendImminently(), Messages::NetworkProcess::ProcessWillSuspendImminently::Reply(handled), 0, 1_s);
378 }
379     
380 void NetworkProcessProxy::sendPrepareToSuspend()
381 {
382     if (canSendMessage())
383         send(Messages::NetworkProcess::PrepareToSuspend(), 0);
384 }
385
386 void NetworkProcessProxy::sendCancelPrepareToSuspend()
387 {
388     if (canSendMessage())
389         send(Messages::NetworkProcess::CancelPrepareToSuspend(), 0);
390 }
391
392 void NetworkProcessProxy::sendProcessDidResume()
393 {
394     if (canSendMessage())
395         send(Messages::NetworkProcess::ProcessDidResume(), 0);
396 }
397
398 void NetworkProcessProxy::processReadyToSuspend()
399 {
400     m_throttler.processReadyToSuspend();
401 }
402
403 void NetworkProcessProxy::didSetAssertionState(AssertionState)
404 {
405 }
406     
407 void NetworkProcessProxy::setIsHoldingLockedFiles(bool isHoldingLockedFiles)
408 {
409     if (!isHoldingLockedFiles) {
410         RELEASE_LOG(ProcessSuspension, "UIProcess is releasing a background assertion because the Network process is no longer holding locked files");
411         m_tokenForHoldingLockedFiles = nullptr;
412         return;
413     }
414     if (!m_tokenForHoldingLockedFiles) {
415         RELEASE_LOG(ProcessSuspension, "UIProcess is taking a background assertion because the Network process is holding locked files");
416         m_tokenForHoldingLockedFiles = m_throttler.backgroundActivityToken();
417     }
418 }
419
420 } // namespace WebKit