83ab3599f27ace5ad69651b4a70d4a9fb7f42fd0
[WebKit-https.git] / Source / WebCore / loader / PingLoader.cpp
1 /*
2  * Copyright (C) 2010 Google Inc. All rights reserved.
3  * Copyright (C) 2015 Roopesh Chander (roop@roopc.net)
4  * Copyright (C) 2015-2017 Apple Inc. All rights reserved.
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions are
8  * met:
9  *
10  *     * Redistributions of source code must retain the above copyright
11  * notice, this list of conditions and the following disclaimer.
12  *     * Redistributions in binary form must reproduce the above
13  * copyright notice, this list of conditions and the following disclaimer
14  * in the documentation and/or other materials provided with the
15  * distribution.
16  *     * Neither the name of Google Inc. nor the names of its
17  * contributors may be used to endorse or promote products derived from
18  * this software without specific prior written permission.
19  *
20  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
21  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
22  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
23  * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
24  * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
25  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
26  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
27  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
28  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
29  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
30  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
31  *
32  */
33
34 #include "config.h"
35 #include "PingLoader.h"
36
37 #include "ContentRuleListResults.h"
38 #include "ContentSecurityPolicy.h"
39 #include "Document.h"
40 #include "Frame.h"
41 #include "FrameLoader.h"
42 #include "FrameLoaderClient.h"
43 #include "InspectorInstrumentation.h"
44 #include "LoaderStrategy.h"
45 #include "NetworkLoadMetrics.h"
46 #include "Page.h"
47 #include "PlatformStrategies.h"
48 #include "ProgressTracker.h"
49 #include "ResourceError.h"
50 #include "ResourceHandle.h"
51 #include "ResourceLoadInfo.h"
52 #include "ResourceRequest.h"
53 #include "ResourceResponse.h"
54 #include "SecurityOrigin.h"
55 #include "SecurityPolicy.h"
56 #include "UserContentController.h"
57 #include <wtf/text/CString.h>
58
59 namespace WebCore {
60
61 #if ENABLE(CONTENT_EXTENSIONS)
62
63 // Returns true if we should block the load.
64 static bool processContentRuleListsForLoad(const Frame& frame, ResourceRequest& request, ContentExtensions::ResourceType resourceType)
65 {
66     auto* documentLoader = frame.loader().documentLoader();
67     if (!documentLoader)
68         return false;
69     auto* page = frame.page();
70     if (!page)
71         return false;
72     auto results = page->userContentProvider().processContentRuleListsForLoad(request.url(), resourceType, *documentLoader);
73     bool result = results.summary.blockedLoad;
74     ContentExtensions::applyResultsToRequest(WTFMove(results), page, request);
75     return result;
76 }
77
78 #endif
79
80 void PingLoader::loadImage(Frame& frame, const URL& url)
81 {
82     ASSERT(frame.document());
83     auto& document = *frame.document();
84
85     if (!document.securityOrigin().canDisplay(url)) {
86         FrameLoader::reportLocalLoadFailed(&frame, url);
87         return;
88     }
89
90     ResourceRequest request(url);
91 #if ENABLE(CONTENT_EXTENSIONS)
92     if (processContentRuleListsForLoad(frame, request, ContentExtensions::ResourceType::Image))
93         return;
94 #endif
95
96     document.contentSecurityPolicy()->upgradeInsecureRequestIfNeeded(request, ContentSecurityPolicy::InsecureRequestType::Load);
97
98     request.setHTTPHeaderField(HTTPHeaderName::CacheControl, "max-age=0");
99
100     HTTPHeaderMap originalRequestHeader = request.httpHeaderFields();
101
102     String referrer = SecurityPolicy::generateReferrerHeader(document.referrerPolicy(), request.url(), frame.loader().outgoingReferrer());
103     if (!referrer.isEmpty())
104         request.setHTTPReferrer(referrer);
105     frame.loader().addExtraFieldsToSubresourceRequest(request);
106
107     startPingLoad(frame, request, WTFMove(originalRequestHeader), ShouldFollowRedirects::Yes, ContentSecurityPolicyImposition::DoPolicyCheck);
108 }
109
110 // http://www.whatwg.org/specs/web-apps/current-work/multipage/links.html#hyperlink-auditing
111 void PingLoader::sendPing(Frame& frame, const URL& pingURL, const URL& destinationURL)
112 {
113     ASSERT(frame.document());
114
115     if (!pingURL.protocolIsInHTTPFamily())
116         return;
117
118     ResourceRequest request(pingURL);
119 #if ENABLE(CONTENT_EXTENSIONS)
120     if (processContentRuleListsForLoad(frame, request, ContentExtensions::ResourceType::Raw))
121         return;
122 #endif
123
124     auto& document = *frame.document();
125     document.contentSecurityPolicy()->upgradeInsecureRequestIfNeeded(request, ContentSecurityPolicy::InsecureRequestType::Load);
126
127     request.setHTTPMethod("POST");
128     request.setHTTPContentType("text/ping");
129     request.setHTTPBody(FormData::create("PING"));
130     request.setHTTPHeaderField(HTTPHeaderName::CacheControl, "max-age=0");
131
132     HTTPHeaderMap originalRequestHeader = request.httpHeaderFields();
133
134     frame.loader().addExtraFieldsToSubresourceRequest(request);
135
136     auto& sourceOrigin = document.securityOrigin();
137     FrameLoader::addHTTPOriginIfNeeded(request, sourceOrigin.toString());
138     request.setHTTPHeaderField(HTTPHeaderName::PingTo, destinationURL);
139     if (!SecurityPolicy::shouldHideReferrer(pingURL, frame.loader().outgoingReferrer())) {
140         request.setHTTPHeaderField(HTTPHeaderName::PingFrom, document.url());
141         if (!sourceOrigin.isSameSchemeHostPort(SecurityOrigin::create(pingURL).get())) {
142             String referrer = SecurityPolicy::generateReferrerHeader(document.referrerPolicy(), pingURL, frame.loader().outgoingReferrer());
143             if (!referrer.isEmpty())
144                 request.setHTTPReferrer(referrer);
145         }
146     }
147
148     startPingLoad(frame, request, WTFMove(originalRequestHeader), ShouldFollowRedirects::Yes, ContentSecurityPolicyImposition::DoPolicyCheck);
149 }
150
151 void PingLoader::sendViolationReport(Frame& frame, const URL& reportURL, Ref<FormData>&& report, ViolationReportType reportType)
152 {
153     ASSERT(frame.document());
154
155     ResourceRequest request(reportURL);
156 #if ENABLE(CONTENT_EXTENSIONS)
157     if (processContentRuleListsForLoad(frame, request, ContentExtensions::ResourceType::Raw))
158         return;
159 #endif
160
161     auto& document = *frame.document();
162     document.contentSecurityPolicy()->upgradeInsecureRequestIfNeeded(request, ContentSecurityPolicy::InsecureRequestType::Load);
163
164     request.setHTTPMethod("POST"_s);
165     request.setHTTPBody(WTFMove(report));
166     switch (reportType) {
167     case ViolationReportType::ContentSecurityPolicy:
168         request.setHTTPContentType("application/csp-report"_s);
169         break;
170     case ViolationReportType::XSSAuditor:
171         request.setHTTPContentType("application/json"_s);
172         break;
173     }
174
175     bool removeCookies = true;
176     if (document.securityOrigin().isSameSchemeHostPort(SecurityOrigin::create(reportURL).get()))
177         removeCookies = false;
178     if (removeCookies)
179         request.setAllowCookies(false);
180
181     HTTPHeaderMap originalRequestHeader = request.httpHeaderFields();
182
183     frame.loader().addExtraFieldsToSubresourceRequest(request);
184
185     String referrer = SecurityPolicy::generateReferrerHeader(document.referrerPolicy(), reportURL, frame.loader().outgoingReferrer());
186     if (!referrer.isEmpty())
187         request.setHTTPReferrer(referrer);
188
189     startPingLoad(frame, request, WTFMove(originalRequestHeader), ShouldFollowRedirects::No, ContentSecurityPolicyImposition::SkipPolicyCheck);
190 }
191
192 void PingLoader::startPingLoad(Frame& frame, ResourceRequest& request, HTTPHeaderMap&& originalRequestHeaders, ShouldFollowRedirects shouldFollowRedirects, ContentSecurityPolicyImposition policyCheck)
193 {
194     unsigned long identifier = frame.page()->progress().createUniqueIdentifier();
195     // FIXME: Why activeDocumentLoader? I would have expected documentLoader().
196     // It seems like the PingLoader should be associated with the current
197     // Document in the Frame, but the activeDocumentLoader will be associated
198     // with the provisional DocumentLoader if there is a provisional
199     // DocumentLoader.
200     bool shouldUseCredentialStorage = frame.loader().client().shouldUseCredentialStorage(frame.loader().activeDocumentLoader(), identifier);
201     FetchOptions options;
202     options.credentials = shouldUseCredentialStorage ? FetchOptions::Credentials::Include : FetchOptions::Credentials::Omit;
203     options.redirect = shouldFollowRedirects == ShouldFollowRedirects::Yes ? FetchOptions::Redirect::Follow : FetchOptions::Redirect::Error;
204
205     // FIXME: Move ping loads to normal subresource loading to get normal inspector request instrumentation hooks.
206     InspectorInstrumentation::willSendRequestOfType(&frame, identifier, frame.loader().activeDocumentLoader(), request, InspectorInstrumentation::LoadType::Ping);
207
208     platformStrategies()->loaderStrategy()->startPingLoad(frame, request, WTFMove(originalRequestHeaders), options, policyCheck, [protectedFrame = makeRef(frame), identifier] (const ResourceError& error, const ResourceResponse& response) {
209         if (!response.isNull())
210             InspectorInstrumentation::didReceiveResourceResponse(protectedFrame, identifier, protectedFrame->loader().activeDocumentLoader(), response, nullptr);
211         if (error.isNull()) {
212             NetworkLoadMetrics emptyMetrics;
213             InspectorInstrumentation::didFinishLoading(protectedFrame.ptr(), protectedFrame->loader().activeDocumentLoader(), identifier, emptyMetrics, nullptr);
214         } else
215             InspectorInstrumentation::didFailLoading(protectedFrame.ptr(), protectedFrame->loader().activeDocumentLoader(), identifier, error);
216     });
217 }
218
219 }