File: RawResource.cpp

package info (click to toggle)
chromium-browser 57.0.2987.98-1~deb8u1
  • links: PTS, VCS
  • area: main
  • in suites: jessie
  • size: 2,637,852 kB
  • ctags: 2,544,394
  • sloc: cpp: 12,815,961; ansic: 3,676,222; python: 1,147,112; asm: 526,608; java: 523,212; xml: 286,794; perl: 92,654; sh: 86,408; objc: 73,271; makefile: 27,698; cs: 18,487; yacc: 13,031; tcl: 12,957; pascal: 4,875; ml: 4,716; lex: 3,904; sql: 3,862; ruby: 1,982; lisp: 1,508; php: 1,368; exp: 404; awk: 325; csh: 117; jsp: 39; sed: 37
file content (364 lines) | stat: -rw-r--r-- 13,835 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
/*
 * Copyright (C) 2011 Google Inc. All Rights Reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS ``AS IS'' AND ANY
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL APPLE INC. OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
 * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include "core/fetch/RawResource.h"

#include "core/fetch/FetchRequest.h"
#include "core/fetch/MemoryCache.h"
#include "core/fetch/ResourceClientWalker.h"
#include "core/fetch/ResourceFetcher.h"
#include "core/fetch/ResourceLoader.h"
#include "platform/HTTPNames.h"
#include <memory>

namespace blink {

RawResource* RawResource::fetchSynchronously(FetchRequest& request,
                                             ResourceFetcher* fetcher) {
  request.makeSynchronous();
  return toRawResource(
      fetcher->requestResource(request, RawResourceFactory(Resource::Raw)));
}

RawResource* RawResource::fetchImport(FetchRequest& request,
                                      ResourceFetcher* fetcher) {
  DCHECK_EQ(request.resourceRequest().frameType(),
            WebURLRequest::FrameTypeNone);
  request.mutableResourceRequest().setRequestContext(
      WebURLRequest::RequestContextImport);
  return toRawResource(fetcher->requestResource(
      request, RawResourceFactory(Resource::ImportResource)));
}

RawResource* RawResource::fetch(FetchRequest& request,
                                ResourceFetcher* fetcher) {
  DCHECK_EQ(request.resourceRequest().frameType(),
            WebURLRequest::FrameTypeNone);
  DCHECK_NE(request.resourceRequest().requestContext(),
            WebURLRequest::RequestContextUnspecified);
  return toRawResource(
      fetcher->requestResource(request, RawResourceFactory(Resource::Raw)));
}

RawResource* RawResource::fetchMainResource(
    FetchRequest& request,
    ResourceFetcher* fetcher,
    const SubstituteData& substituteData) {
  DCHECK_NE(request.resourceRequest().frameType(),
            WebURLRequest::FrameTypeNone);
  DCHECK(request.resourceRequest().requestContext() ==
             WebURLRequest::RequestContextForm ||
         request.resourceRequest().requestContext() ==
             WebURLRequest::RequestContextFrame ||
         request.resourceRequest().requestContext() ==
             WebURLRequest::RequestContextHyperlink ||
         request.resourceRequest().requestContext() ==
             WebURLRequest::RequestContextIframe ||
         request.resourceRequest().requestContext() ==
             WebURLRequest::RequestContextInternal ||
         request.resourceRequest().requestContext() ==
             WebURLRequest::RequestContextLocation);

  return toRawResource(fetcher->requestResource(
      request, RawResourceFactory(Resource::MainResource), substituteData));
}

RawResource* RawResource::fetchMedia(FetchRequest& request,
                                     ResourceFetcher* fetcher) {
  DCHECK_EQ(request.resourceRequest().frameType(),
            WebURLRequest::FrameTypeNone);
  DCHECK(request.resourceRequest().requestContext() ==
             WebURLRequest::RequestContextAudio ||
         request.resourceRequest().requestContext() ==
             WebURLRequest::RequestContextVideo);
  return toRawResource(
      fetcher->requestResource(request, RawResourceFactory(Resource::Media)));
}

RawResource* RawResource::fetchTextTrack(FetchRequest& request,
                                         ResourceFetcher* fetcher) {
  DCHECK_EQ(request.resourceRequest().frameType(),
            WebURLRequest::FrameTypeNone);
  request.mutableResourceRequest().setRequestContext(
      WebURLRequest::RequestContextTrack);
  return toRawResource(fetcher->requestResource(
      request, RawResourceFactory(Resource::TextTrack)));
}

RawResource* RawResource::fetchManifest(FetchRequest& request,
                                        ResourceFetcher* fetcher) {
  DCHECK_EQ(request.resourceRequest().frameType(),
            WebURLRequest::FrameTypeNone);
  DCHECK_EQ(request.resourceRequest().requestContext(),
            WebURLRequest::RequestContextManifest);
  return toRawResource(fetcher->requestResource(
      request, RawResourceFactory(Resource::Manifest)));
}

RawResource::RawResource(const ResourceRequest& resourceRequest,
                         Type type,
                         const ResourceLoaderOptions& options)
    : Resource(resourceRequest, type, options) {}

void RawResource::appendData(const char* data, size_t length) {
  Resource::appendData(data, length);

  ResourceClientWalker<RawResourceClient> w(clients());
  while (RawResourceClient* c = w.next())
    c->dataReceived(this, data, length);
}

void RawResource::didAddClient(ResourceClient* c) {
  // CHECK()/RevalidationStartForbiddenScope are for
  // https://crbug.com/640960#c24.
  CHECK(!isCacheValidator());
  if (!hasClient(c))
    return;
  DCHECK(RawResourceClient::isExpectedType(c));
  RevalidationStartForbiddenScope revalidationStartForbiddenScope(this);
  RawResourceClient* client = static_cast<RawResourceClient*>(c);
  for (const auto& redirect : redirectChain()) {
    ResourceRequest request(redirect.m_request);
    client->redirectReceived(this, request, redirect.m_redirectResponse);
    if (!hasClient(c))
      return;
  }

  if (!response().isNull())
    client->responseReceived(this, response(), nullptr);
  if (!hasClient(c))
    return;
  if (data())
    client->dataReceived(this, data()->data(), data()->size());
  if (!hasClient(c))
    return;
  Resource::didAddClient(client);
}

bool RawResource::willFollowRedirect(const ResourceRequest& newRequest,
                                     const ResourceResponse& redirectResponse) {
  bool follow = Resource::willFollowRedirect(newRequest, redirectResponse);
  // The base class method takes a const reference of a ResourceRequest and
  // returns bool just for allowing RawResource to reject redirect. It must
  // always return true.
  DCHECK(follow);

  DCHECK(!redirectResponse.isNull());
  ResourceClientWalker<RawResourceClient> w(clients());
  while (RawResourceClient* c = w.next()) {
    if (!c->redirectReceived(this, newRequest, redirectResponse))
      follow = false;
  }

  return follow;
}

void RawResource::willNotFollowRedirect() {
  ResourceClientWalker<RawResourceClient> w(clients());
  while (RawResourceClient* c = w.next())
    c->redirectBlocked();
}

void RawResource::responseReceived(
    const ResourceResponse& response,
    std::unique_ptr<WebDataConsumerHandle> handle) {
  bool isSuccessfulRevalidation =
      isCacheValidator() && response.httpStatusCode() == 304;
  Resource::responseReceived(response, nullptr);

  ResourceClientWalker<RawResourceClient> w(clients());
  DCHECK(clients().size() <= 1 || !handle);
  while (RawResourceClient* c = w.next()) {
    // |handle| is cleared when passed, but it's not a problem because |handle|
    // is null when there are two or more clients, as asserted.
    c->responseReceived(this, this->response(), std::move(handle));
  }

  // If we successfully revalidated, we won't get appendData() calls. Forward
  // the data to clients now instead. Note: |m_data| can be null when no data is
  // appended to the original resource.
  if (isSuccessfulRevalidation && data()) {
    ResourceClientWalker<RawResourceClient> w(clients());
    while (RawResourceClient* c = w.next())
      c->dataReceived(this, data()->data(), data()->size());
  }
}

void RawResource::setSerializedCachedMetadata(const char* data, size_t size) {
  Resource::setSerializedCachedMetadata(data, size);
  ResourceClientWalker<RawResourceClient> w(clients());
  while (RawResourceClient* c = w.next())
    c->setSerializedCachedMetadata(this, data, size);
}

void RawResource::didSendData(unsigned long long bytesSent,
                              unsigned long long totalBytesToBeSent) {
  ResourceClientWalker<RawResourceClient> w(clients());
  while (RawResourceClient* c = w.next())
    c->dataSent(this, bytesSent, totalBytesToBeSent);
}

void RawResource::didDownloadData(int dataLength) {
  ResourceClientWalker<RawResourceClient> w(clients());
  while (RawResourceClient* c = w.next())
    c->dataDownloaded(this, dataLength);
}

void RawResource::reportResourceTimingToClients(
    const ResourceTimingInfo& info) {
  ResourceClientWalker<RawResourceClient> w(clients());
  while (RawResourceClient* c = w.next())
    c->didReceiveResourceTiming(this, info);
}

void RawResource::setDefersLoading(bool defers) {
  if (loader())
    loader()->setDefersLoading(defers);
}

static bool shouldIgnoreHeaderForCacheReuse(AtomicString headerName) {
  // FIXME: This list of headers that don't affect cache policy almost certainly
  // isn't complete.
  DEFINE_STATIC_LOCAL(
      HashSet<AtomicString>, headers,
      ({
          "Cache-Control", "If-Modified-Since", "If-None-Match", "Origin",
          "Pragma", "Purpose", "Referer", "User-Agent",
          HTTPNames::X_DevTools_Emulate_Network_Conditions_Client_Id,
      }));
  return headers.contains(headerName);
}

static bool isCacheableHTTPMethod(const AtomicString& method) {
  // Per http://www.w3.org/Protocols/rfc2616/rfc2616-sec13.html#sec13.10,
  // these methods always invalidate the cache entry.
  return method != "POST" && method != "PUT" && method != "DELETE";
}

bool RawResource::canReuse(const ResourceRequest& newRequest) const {
  if (getDataBufferingPolicy() == DoNotBufferData)
    return false;

  if (!isCacheableHTTPMethod(resourceRequest().httpMethod()))
    return false;
  if (resourceRequest().httpMethod() != newRequest.httpMethod())
    return false;

  if (resourceRequest().httpBody() != newRequest.httpBody())
    return false;

  if (resourceRequest().allowStoredCredentials() !=
      newRequest.allowStoredCredentials())
    return false;

  // Ensure most headers match the existing headers before continuing. Note that
  // the list of ignored headers includes some headers explicitly related to
  // caching. A more detailed check of caching policy will be performed later,
  // this is simply a list of headers that we might permit to be different and
  // still reuse the existing Resource.
  const HTTPHeaderMap& newHeaders = newRequest.httpHeaderFields();
  const HTTPHeaderMap& oldHeaders = resourceRequest().httpHeaderFields();

  for (const auto& header : newHeaders) {
    AtomicString headerName = header.key;
    if (!shouldIgnoreHeaderForCacheReuse(headerName) &&
        header.value != oldHeaders.get(headerName))
      return false;
  }

  for (const auto& header : oldHeaders) {
    AtomicString headerName = header.key;
    if (!shouldIgnoreHeaderForCacheReuse(headerName) &&
        header.value != newHeaders.get(headerName))
      return false;
  }

  return true;
}

RawResourceClientStateChecker::RawResourceClientStateChecker()
    : m_state(NotAddedAsClient) {}

RawResourceClientStateChecker::~RawResourceClientStateChecker() {}

NEVER_INLINE void RawResourceClientStateChecker::willAddClient() {
  SECURITY_CHECK(m_state == NotAddedAsClient);
  m_state = Started;
}

NEVER_INLINE void RawResourceClientStateChecker::willRemoveClient() {
  SECURITY_CHECK(m_state != NotAddedAsClient);
  m_state = NotAddedAsClient;
}

NEVER_INLINE void RawResourceClientStateChecker::redirectReceived() {
  SECURITY_CHECK(m_state == Started);
}

NEVER_INLINE void RawResourceClientStateChecker::redirectBlocked() {
  SECURITY_CHECK(m_state == Started);
  m_state = RedirectBlocked;
}

NEVER_INLINE void RawResourceClientStateChecker::dataSent() {
  SECURITY_CHECK(m_state == Started);
}

NEVER_INLINE void RawResourceClientStateChecker::responseReceived() {
  SECURITY_CHECK(m_state == Started);
  m_state = ResponseReceived;
}

NEVER_INLINE void RawResourceClientStateChecker::setSerializedCachedMetadata() {
  SECURITY_CHECK(m_state == ResponseReceived);
  m_state = SetSerializedCachedMetadata;
}

NEVER_INLINE void RawResourceClientStateChecker::dataReceived() {
  SECURITY_CHECK(m_state == ResponseReceived ||
                 m_state == SetSerializedCachedMetadata ||
                 m_state == DataReceived);
  m_state = DataReceived;
}

NEVER_INLINE void RawResourceClientStateChecker::dataDownloaded() {
  SECURITY_CHECK(m_state == ResponseReceived ||
                 m_state == SetSerializedCachedMetadata ||
                 m_state == DataDownloaded);
  m_state = DataDownloaded;
}

NEVER_INLINE void RawResourceClientStateChecker::notifyFinished(
    Resource* resource) {
  SECURITY_CHECK(m_state != NotAddedAsClient);
  SECURITY_CHECK(m_state != NotifyFinished);
  SECURITY_CHECK(resource->errorOccurred() ||
                 (m_state == ResponseReceived ||
                  m_state == SetSerializedCachedMetadata ||
                  m_state == DataReceived || m_state == DataDownloaded));
  m_state = NotifyFinished;
}

}  // namespace blink