1/*
2 * Copyright (C) 2012 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 "WebResourceLoadScheduler.h"
28
29#include "Logging.h"
30#include "NetworkConnectionToWebProcessMessages.h"
31#include "NetworkProcessConnection.h"
32#include "NetworkResourceLoadParameters.h"
33#include "WebCoreArgumentCoders.h"
34#include "WebErrors.h"
35#include "WebFrame.h"
36#include "WebFrameLoaderClient.h"
37#include "WebPage.h"
38#include "WebProcess.h"
39#include "WebResourceLoader.h"
40#include <WebCore/CachedResource.h>
41#include <WebCore/Document.h>
42#include <WebCore/DocumentLoader.h>
43#include <WebCore/Frame.h>
44#include <WebCore/FrameLoader.h>
45#include <WebCore/NetscapePlugInStreamLoader.h>
46#include <WebCore/ReferrerPolicy.h>
47#include <WebCore/ResourceBuffer.h>
48#include <WebCore/ResourceLoader.h>
49#include <WebCore/Settings.h>
50#include <WebCore/SubresourceLoader.h>
51#include <wtf/text/CString.h>
52
53#if ENABLE(NETWORK_PROCESS)
54
55using namespace WebCore;
56
57namespace WebKit {
58
59WebResourceLoadScheduler::WebResourceLoadScheduler()
60    : m_internallyFailedLoadTimer(RunLoop::main(), this, &WebResourceLoadScheduler::internallyFailedLoadTimerFired)
61    , m_suspendPendingRequestsCount(0)
62{
63}
64
65WebResourceLoadScheduler::~WebResourceLoadScheduler()
66{
67}
68
69PassRefPtr<SubresourceLoader> WebResourceLoadScheduler::scheduleSubresourceLoad(Frame* frame, CachedResource* resource, const ResourceRequest& request, ResourceLoadPriority priority, const ResourceLoaderOptions& options)
70{
71    RefPtr<SubresourceLoader> loader = SubresourceLoader::create(frame, resource, request, options);
72    if (loader)
73        scheduleLoad(loader.get(), resource, priority, frame->document()->referrerPolicy() == ReferrerPolicyDefault);
74    return loader.release();
75}
76
77PassRefPtr<NetscapePlugInStreamLoader> WebResourceLoadScheduler::schedulePluginStreamLoad(Frame* frame, NetscapePlugInStreamLoaderClient* client, const ResourceRequest& request)
78{
79    RefPtr<NetscapePlugInStreamLoader> loader = NetscapePlugInStreamLoader::create(frame, client, request);
80    if (loader)
81        scheduleLoad(loader.get(), 0, ResourceLoadPriorityLow, frame->document()->referrerPolicy() == ReferrerPolicyDefault);
82    return loader.release();
83}
84
85void WebResourceLoadScheduler::scheduleLoad(ResourceLoader* resourceLoader, CachedResource* resource, ResourceLoadPriority priority, bool shouldClearReferrerOnHTTPSToHTTPRedirect)
86{
87    ASSERT(resourceLoader);
88    ASSERT(priority != ResourceLoadPriorityUnresolved);
89    priority = ResourceLoadPriorityHighest;
90
91    ResourceLoadIdentifier identifier = resourceLoader->identifier();
92    ASSERT(identifier);
93
94    // If the DocumentLoader schedules this as an archive resource load,
95    // then we should remember the ResourceLoader in our records but not schedule it in the NetworkProcess.
96    if (resourceLoader->documentLoader()->scheduleArchiveLoad(resourceLoader, resourceLoader->request())) {
97        LOG(NetworkScheduling, "(WebProcess) WebResourceLoadScheduler::scheduleLoad, url '%s' will be handled as an archive resource.", resourceLoader->url().string().utf8().data());
98        m_webResourceLoaders.set(identifier, WebResourceLoader::create(resourceLoader));
99        return;
100    }
101
102    LOG(NetworkScheduling, "(WebProcess) WebResourceLoadScheduler::scheduleLoad, url '%s' will be scheduled with the NetworkProcess with priority %i", resourceLoader->url().string().utf8().data(), priority);
103
104    ContentSniffingPolicy contentSniffingPolicy = resourceLoader->shouldSniffContent() ? SniffContent : DoNotSniffContent;
105    StoredCredentials allowStoredCredentials = resourceLoader->shouldUseCredentialStorage() ? AllowStoredCredentials : DoNotAllowStoredCredentials;
106    bool privateBrowsingEnabled = resourceLoader->frameLoader()->frame()->settings()->privateBrowsingEnabled();
107
108    // FIXME: Some entities in WebCore use WebCore's "EmptyFrameLoaderClient" instead of having a proper WebFrameLoaderClient.
109    // EmptyFrameLoaderClient shouldn't exist and everything should be using a WebFrameLoaderClient,
110    // but in the meantime we have to make sure not to mis-cast.
111    WebFrameLoaderClient* webFrameLoaderClient = toWebFrameLoaderClient(resourceLoader->frameLoader()->client());
112    WebFrame* webFrame = webFrameLoaderClient ? webFrameLoaderClient->webFrame() : 0;
113    WebPage* webPage = webFrame ? webFrame->page() : 0;
114
115    NetworkResourceLoadParameters loadParameters;
116    loadParameters.identifier = identifier;
117    loadParameters.webPageID = webPage ? webPage->pageID() : 0;
118    loadParameters.webFrameID = webFrame ? webFrame->frameID() : 0;
119    loadParameters.request = resourceLoader->request();
120    loadParameters.priority = priority;
121    loadParameters.contentSniffingPolicy = contentSniffingPolicy;
122    loadParameters.allowStoredCredentials = allowStoredCredentials;
123    // If there is no WebFrame then this resource cannot be authenticated with the client.
124    loadParameters.clientCredentialPolicy = (webFrame && webPage) ? resourceLoader->clientCredentialPolicy() : DoNotAskClientForAnyCredentials;
125    loadParameters.inPrivateBrowsingMode = privateBrowsingEnabled;
126    loadParameters.shouldClearReferrerOnHTTPSToHTTPRedirect = shouldClearReferrerOnHTTPSToHTTPRedirect;
127    loadParameters.isMainResource = resource && resource->type() == CachedResource::MainResource;
128
129    ASSERT((loadParameters.webPageID && loadParameters.webFrameID) || loadParameters.clientCredentialPolicy == DoNotAskClientForAnyCredentials);
130
131    if (!WebProcess::shared().networkConnection()->connection()->send(Messages::NetworkConnectionToWebProcess::ScheduleResourceLoad(loadParameters), 0)) {
132        // We probably failed to schedule this load with the NetworkProcess because it had crashed.
133        // This load will never succeed so we will schedule it to fail asynchronously.
134        scheduleInternallyFailedLoad(resourceLoader);
135        return;
136    }
137
138    m_webResourceLoaders.set(identifier, WebResourceLoader::create(resourceLoader));
139
140    notifyDidScheduleResourceRequest(resourceLoader);
141}
142
143void WebResourceLoadScheduler::scheduleInternallyFailedLoad(WebCore::ResourceLoader* resourceLoader)
144{
145    m_internallyFailedResourceLoaders.add(resourceLoader);
146    m_internallyFailedLoadTimer.startOneShot(0);
147}
148
149void WebResourceLoadScheduler::internallyFailedLoadTimerFired()
150{
151    Vector<RefPtr<ResourceLoader>> internallyFailedResourceLoaders;
152    copyToVector(m_internallyFailedResourceLoaders, internallyFailedResourceLoaders);
153
154    for (size_t i = 0; i < internallyFailedResourceLoaders.size(); ++i)
155        internallyFailedResourceLoaders[i]->didFail(internalError(internallyFailedResourceLoaders[i]->url()));
156}
157
158void WebResourceLoadScheduler::remove(ResourceLoader* resourceLoader)
159{
160    ASSERT(resourceLoader);
161    LOG(NetworkScheduling, "(WebProcess) WebResourceLoadScheduler::remove, url '%s'", resourceLoader->url().string().utf8().data());
162
163    if (m_internallyFailedResourceLoaders.contains(resourceLoader)) {
164        m_internallyFailedResourceLoaders.remove(resourceLoader);
165        return;
166    }
167
168    ResourceLoadIdentifier identifier = resourceLoader->identifier();
169    if (!identifier) {
170        LOG_ERROR("WebResourceLoadScheduler removing a ResourceLoader that has no identifier.");
171        return;
172    }
173
174    RefPtr<WebResourceLoader> loader = m_webResourceLoaders.take(identifier);
175    // Loader may not be registered if we created it, but haven't scheduled yet (a bundle client can decide to cancel such request via willSendRequest).
176    if (!loader)
177        return;
178
179    WebProcess::shared().networkConnection()->connection()->send(Messages::NetworkConnectionToWebProcess::RemoveLoadIdentifier(identifier), 0);
180
181    // It's possible that this WebResourceLoader might be just about to message back to the NetworkProcess (e.g. ContinueWillSendRequest)
182    // but there's no point in doing so anymore.
183    loader->detachFromCoreLoader();
184}
185
186void WebResourceLoadScheduler::crossOriginRedirectReceived(ResourceLoader*, const KURL&)
187{
188    // We handle cross origin redirects entirely within the NetworkProcess.
189    // We override this call in the WebProcess to make it a no-op.
190}
191
192void WebResourceLoadScheduler::servePendingRequests(ResourceLoadPriority minimumPriority)
193{
194    LOG(NetworkScheduling, "(WebProcess) WebResourceLoadScheduler::servePendingRequests");
195
196    // The NetworkProcess scheduler is good at making sure loads are serviced until there are no more pending requests.
197    // If this WebProcess isn't expecting requests to be served then we can ignore messaging the NetworkProcess right now.
198    if (m_suspendPendingRequestsCount)
199        return;
200
201    WebProcess::shared().networkConnection()->connection()->send(Messages::NetworkConnectionToWebProcess::ServePendingRequests(minimumPriority), 0);
202}
203
204void WebResourceLoadScheduler::suspendPendingRequests()
205{
206    ++m_suspendPendingRequestsCount;
207}
208
209void WebResourceLoadScheduler::resumePendingRequests()
210{
211    ASSERT(m_suspendPendingRequestsCount);
212    --m_suspendPendingRequestsCount;
213}
214
215void WebResourceLoadScheduler::setSerialLoadingEnabled(bool enabled)
216{
217    WebProcess::shared().networkConnection()->connection()->sendSync(Messages::NetworkConnectionToWebProcess::SetSerialLoadingEnabled(enabled), Messages::NetworkConnectionToWebProcess::SetSerialLoadingEnabled::Reply(), 0);
218}
219
220void WebResourceLoadScheduler::networkProcessCrashed()
221{
222    HashMap<unsigned long, RefPtr<WebResourceLoader>>::iterator end = m_webResourceLoaders.end();
223    for (HashMap<unsigned long, RefPtr<WebResourceLoader>>::iterator i = m_webResourceLoaders.begin(); i != end; ++i)
224        scheduleInternallyFailedLoad(i->value.get()->resourceLoader());
225
226    m_webResourceLoaders.clear();
227}
228
229} // namespace WebKit
230
231#endif // ENABLE(NETWORK_PROCESS)
232