1/*
2 * Copyright (C) 2010 Google 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 are
6 * met:
7 *
8 *     * Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 *     * Redistributions in binary form must reproduce the above
11 * copyright notice, this list of conditions and the following disclaimer
12 * in the documentation and/or other materials provided with the
13 * distribution.
14 *     * Neither the name of Google Inc. nor the names of its
15 * contributors may be used to endorse or promote products derived from
16 * this software without specific prior written permission.
17 *
18 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29 *
30 */
31
32#include "config.h"
33#include "core/loader/PingLoader.h"
34
35#include "core/FetchInitiatorTypeNames.h"
36#include "core/dom/Document.h"
37#include "core/fetch/FetchContext.h"
38#include "core/frame/LocalFrame.h"
39#include "core/inspector/InspectorInstrumentation.h"
40#include "core/inspector/InspectorTraceEvents.h"
41#include "core/loader/FrameLoader.h"
42#include "core/loader/FrameLoaderClient.h"
43#include "core/loader/UniqueIdentifier.h"
44#include "core/page/Page.h"
45#include "platform/exported/WrappedResourceRequest.h"
46#include "platform/network/ResourceError.h"
47#include "platform/network/ResourceRequest.h"
48#include "platform/network/ResourceResponse.h"
49#include "platform/weborigin/SecurityOrigin.h"
50#include "platform/weborigin/SecurityPolicy.h"
51#include "public/platform/Platform.h"
52#include "public/platform/WebURLLoader.h"
53#include "public/platform/WebURLResponse.h"
54#include "wtf/OwnPtr.h"
55
56namespace WebCore {
57
58void PingLoader::loadImage(LocalFrame* frame, const KURL& url)
59{
60    if (!frame->document()->securityOrigin()->canDisplay(url)) {
61        FrameLoader::reportLocalLoadFailed(frame, url.string());
62        return;
63    }
64
65    ResourceRequest request(url);
66    request.setTargetType(ResourceRequest::TargetIsPing);
67    request.setHTTPHeaderField("Cache-Control", "max-age=0");
68    frame->loader().fetchContext().addAdditionalRequestHeaders(frame->document(), request, FetchSubresource);
69    frame->loader().fetchContext().setFirstPartyForCookies(request);
70
71    FetchInitiatorInfo initiatorInfo;
72    initiatorInfo.name = FetchInitiatorTypeNames::ping;
73    PingLoader::start(frame, request, initiatorInfo);
74}
75
76// http://www.whatwg.org/specs/web-apps/current-work/multipage/links.html#hyperlink-auditing
77void PingLoader::sendLinkAuditPing(LocalFrame* frame, const KURL& pingURL, const KURL& destinationURL)
78{
79    ResourceRequest request(pingURL);
80    request.setTargetType(ResourceRequest::TargetIsPing);
81    request.setHTTPMethod("POST");
82    request.setHTTPContentType("text/ping");
83    request.setHTTPBody(FormData::create("PING"));
84    request.setHTTPHeaderField("Cache-Control", "max-age=0");
85    frame->loader().fetchContext().addAdditionalRequestHeaders(frame->document(), request, FetchSubresource);
86    frame->loader().fetchContext().setFirstPartyForCookies(request);
87
88    RefPtr<SecurityOrigin> pingOrigin = SecurityOrigin::create(pingURL);
89    // addAdditionalRequestHeaders() will have added a referrer for same origin requests,
90    // but the spec omits the referrer for same origin.
91    if (frame->document()->securityOrigin()->isSameSchemeHostPort(pingOrigin.get()))
92        request.clearHTTPReferrer();
93
94    request.setHTTPHeaderField("Ping-To", AtomicString(destinationURL.string()));
95
96    // Ping-From follows the same rules as the default referrer beahavior for subresource requests.
97    // FIXME: Should Ping-From obey ReferrerPolicy?
98    if (!SecurityPolicy::shouldHideReferrer(pingURL, frame->document()->url().string()))
99        request.setHTTPHeaderField("Ping-From", AtomicString(frame->document()->url().string()));
100
101    FetchInitiatorInfo initiatorInfo;
102    initiatorInfo.name = FetchInitiatorTypeNames::ping;
103    PingLoader::start(frame, request, initiatorInfo);
104}
105
106void PingLoader::sendViolationReport(LocalFrame* frame, const KURL& reportURL, PassRefPtr<FormData> report, ViolationReportType type)
107{
108    ResourceRequest request(reportURL);
109    request.setTargetType(ResourceRequest::TargetIsSubresource);
110    request.setHTTPMethod("POST");
111    request.setHTTPContentType(type == ContentSecurityPolicyViolationReport ? "application/csp-report" : "application/json");
112    request.setHTTPBody(report);
113    frame->loader().fetchContext().addAdditionalRequestHeaders(frame->document(), request, FetchSubresource);
114    frame->loader().fetchContext().setFirstPartyForCookies(request);
115
116    FetchInitiatorInfo initiatorInfo;
117    initiatorInfo.name = FetchInitiatorTypeNames::violationreport;
118    PingLoader::start(frame, request, initiatorInfo, SecurityOrigin::create(reportURL)->isSameSchemeHostPort(frame->document()->securityOrigin()) ? AllowStoredCredentials : DoNotAllowStoredCredentials);
119}
120
121void PingLoader::start(LocalFrame* frame, ResourceRequest& request, const FetchInitiatorInfo& initiatorInfo, StoredCredentials credentialsAllowed)
122{
123    OwnPtr<PingLoader> pingLoader = adoptPtr(new PingLoader(frame, request, initiatorInfo, credentialsAllowed));
124
125    // Leak the ping loader, since it will kill itself as soon as it receives a response.
126    PingLoader* leakedPingLoader ALLOW_UNUSED = pingLoader.leakPtr();
127}
128
129PingLoader::PingLoader(LocalFrame* frame, ResourceRequest& request, const FetchInitiatorInfo& initiatorInfo, StoredCredentials credentialsAllowed)
130    : PageLifecycleObserver(frame->page())
131    , m_timeout(this, &PingLoader::timeout)
132    , m_url(request.url())
133    , m_identifier(createUniqueIdentifier())
134{
135    frame->loader().client()->didDispatchPingLoader(request.url());
136
137    m_loader = adoptPtr(blink::Platform::current()->createURLLoader());
138    ASSERT(m_loader);
139    blink::WrappedResourceRequest wrappedRequest(request);
140    wrappedRequest.setAllowStoredCredentials(credentialsAllowed == AllowStoredCredentials);
141    m_loader->loadAsynchronously(wrappedRequest, this);
142
143    TRACE_EVENT_INSTANT1(TRACE_DISABLED_BY_DEFAULT("devtools.timeline"), "ResourceSendRequest", "data", InspectorSendRequestEvent::data(m_identifier, frame, request));
144    TRACE_EVENT_INSTANT1(TRACE_DISABLED_BY_DEFAULT("devtools.timeline.stack"), "CallStack", "stack", InspectorCallStackEvent::currentCallStack());
145    // FIXME(361045): remove InspectorInstrumentation calls once DevTools Timeline migrates to tracing.
146    InspectorInstrumentation::willSendRequest(frame, m_identifier, frame->loader().documentLoader(), request, ResourceResponse(), initiatorInfo);
147
148    // If the server never responds, FrameLoader won't be able to cancel this load and
149    // we'll sit here waiting forever. Set a very generous timeout, just in case.
150    m_timeout.startOneShot(60000, FROM_HERE);
151}
152
153PingLoader::~PingLoader()
154{
155    if (m_loader)
156        m_loader->cancel();
157}
158
159void PingLoader::didReceiveResponse(blink::WebURLLoader*, const blink::WebURLResponse&)
160{
161    if (Page* page = this->page()) {
162        TRACE_EVENT_INSTANT1(TRACE_DISABLED_BY_DEFAULT("devtools.timeline"), "ResourceFinish", "data", InspectorResourceFinishEvent::data(m_identifier, 0, true));
163        // FIXME(361045): remove InspectorInstrumentation calls once DevTools Timeline migrates to tracing.
164        InspectorInstrumentation::didFailLoading(page->deprecatedLocalMainFrame(), m_identifier, ResourceError::cancelledError(m_url));
165    }
166    delete this;
167}
168
169void PingLoader::didReceiveData(blink::WebURLLoader*, const char*, int, int)
170{
171    if (Page* page = this->page()) {
172        TRACE_EVENT_INSTANT1(TRACE_DISABLED_BY_DEFAULT("devtools.timeline"), "ResourceFinish", "data", InspectorResourceFinishEvent::data(m_identifier, 0, true));
173        // FIXME(361045): remove InspectorInstrumentation calls once DevTools Timeline migrates to tracing.
174        InspectorInstrumentation::didFailLoading(page->deprecatedLocalMainFrame(), m_identifier, ResourceError::cancelledError(m_url));
175    }
176    delete this;
177}
178
179void PingLoader::didFinishLoading(blink::WebURLLoader*, double, int64_t)
180{
181    if (Page* page = this->page()) {
182        TRACE_EVENT_INSTANT1(TRACE_DISABLED_BY_DEFAULT("devtools.timeline"), "ResourceFinish", "data", InspectorResourceFinishEvent::data(m_identifier, 0, true));
183        // FIXME(361045): remove InspectorInstrumentation calls once DevTools Timeline migrates to tracing.
184        InspectorInstrumentation::didFailLoading(page->deprecatedLocalMainFrame(), m_identifier, ResourceError::cancelledError(m_url));
185    }
186    delete this;
187}
188
189void PingLoader::didFail(blink::WebURLLoader*, const blink::WebURLError& resourceError)
190{
191    if (Page* page = this->page()) {
192        TRACE_EVENT_INSTANT1(TRACE_DISABLED_BY_DEFAULT("devtools.timeline"), "ResourceFinish", "data", InspectorResourceFinishEvent::data(m_identifier, 0, true));
193        // FIXME(361045): remove InspectorInstrumentation calls once DevTools Timeline migrates to tracing.
194        InspectorInstrumentation::didFailLoading(page->deprecatedLocalMainFrame(), m_identifier, ResourceError(resourceError));
195    }
196    delete this;
197}
198
199void PingLoader::timeout(Timer<PingLoader>*)
200{
201    if (Page* page = this->page()) {
202        TRACE_EVENT_INSTANT1(TRACE_DISABLED_BY_DEFAULT("devtools.timeline"), "ResourceFinish", "data", InspectorResourceFinishEvent::data(m_identifier, 0, true));
203        // FIXME(361045): remove InspectorInstrumentation calls once DevTools Timeline migrates to tracing.
204        InspectorInstrumentation::didFailLoading(page->deprecatedLocalMainFrame(), m_identifier, ResourceError::cancelledError(m_url));
205    }
206    delete this;
207}
208
209}
210