File: raw_resource.cc

package info (click to toggle)
chromium 138.0.7204.183-1
  • links: PTS, VCS
  • area: main
  • in suites: trixie
  • size: 6,071,908 kB
  • sloc: cpp: 34,937,088; ansic: 7,176,967; javascript: 4,110,704; python: 1,419,953; asm: 946,768; xml: 739,971; pascal: 187,324; sh: 89,623; perl: 88,663; objc: 79,944; sql: 50,304; cs: 41,786; fortran: 24,137; makefile: 21,806; php: 13,980; tcl: 13,166; yacc: 8,925; ruby: 7,485; awk: 3,720; lisp: 3,096; lex: 1,327; ada: 727; jsp: 228; sed: 36
file content (398 lines) | stat: -rw-r--r-- 15,101 bytes parent folder | download | duplicates (5)
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
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
/*
 * 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 "third_party/blink/renderer/platform/loader/fetch/raw_resource.h"

#include <memory>
#include <variant>

#include "base/compiler_specific.h"
#include "base/containers/span.h"
#include "base/task/single_thread_task_runner.h"
#include "third_party/blink/public/mojom/fetch/fetch_api_request.mojom-blink.h"
#include "third_party/blink/public/mojom/loader/request_context_frame_type.mojom-blink.h"
#include "third_party/blink/public/platform/platform.h"
#include "third_party/blink/renderer/platform/loader/fetch/buffering_bytes_consumer.h"
#include "third_party/blink/renderer/platform/loader/fetch/fetch_parameters.h"
#include "third_party/blink/renderer/platform/loader/fetch/memory_cache.h"
#include "third_party/blink/renderer/platform/loader/fetch/resource_client_walker.h"
#include "third_party/blink/renderer/platform/loader/fetch/resource_fetcher.h"
#include "third_party/blink/renderer/platform/loader/fetch/response_body_loader.h"
#include "third_party/blink/renderer/platform/network/http_names.h"
#include "third_party/blink/renderer/platform/scheduler/public/thread.h"
#include "third_party/blink/renderer/platform/scheduler/public/thread_scheduler.h"
#include "third_party/blink/renderer/platform/wtf/std_lib_extras.h"

namespace blink {

RawResource* RawResource::FetchSynchronously(FetchParameters& params,
                                             ResourceFetcher* fetcher,
                                             RawResourceClient* client) {
  params.MakeSynchronous();
  return ToRawResource(fetcher->RequestResource(
      params, RawResourceFactory(ResourceType::kRaw), client));
}

RawResource* RawResource::Fetch(FetchParameters& params,
                                ResourceFetcher* fetcher,
                                RawResourceClient* client) {
  DCHECK_NE(params.GetResourceRequest().GetRequestContext(),
            mojom::blink::RequestContextType::UNSPECIFIED);
  return ToRawResource(fetcher->RequestResource(
      params, RawResourceFactory(ResourceType::kRaw), client));
}

RawResource* RawResource::FetchMedia(FetchParameters& params,
                                     ResourceFetcher* fetcher,
                                     RawResourceClient* client) {
  auto context = params.GetResourceRequest().GetRequestContext();
  DCHECK(context == mojom::blink::RequestContextType::AUDIO ||
         context == mojom::blink::RequestContextType::VIDEO);
  ResourceType type = (context == mojom::blink::RequestContextType::AUDIO)
                          ? ResourceType::kAudio
                          : ResourceType::kVideo;
  return ToRawResource(
      fetcher->RequestResource(params, RawResourceFactory(type), client));
}

RawResource* RawResource::FetchTextTrack(FetchParameters& params,
                                         ResourceFetcher* fetcher,
                                         RawResourceClient* client) {
  params.SetRequestContext(mojom::blink::RequestContextType::TRACK);
  params.SetRequestDestination(network::mojom::RequestDestination::kTrack);
  return ToRawResource(fetcher->RequestResource(
      params, RawResourceFactory(ResourceType::kTextTrack), client));
}

RawResource* RawResource::FetchManifest(FetchParameters& params,
                                        ResourceFetcher* fetcher,
                                        RawResourceClient* client) {
  DCHECK_EQ(params.GetResourceRequest().GetRequestContext(),
            mojom::blink::RequestContextType::MANIFEST);
  return ToRawResource(fetcher->RequestResource(
      params, RawResourceFactory(ResourceType::kManifest), client));
}

RawResource::RawResource(const ResourceRequest& resource_request,
                         ResourceType type,
                         const ResourceLoaderOptions& options)
    : Resource(resource_request, type, options) {}

void RawResource::AppendData(
    std::variant<SegmentedBuffer, base::span<const char>> data) {
  if (GetResourceRequest().UseStreamOnResponse())
    return;

  Resource::AppendData(std::move(data));
}

class RawResource::PreloadBytesConsumerClient final
    : public GarbageCollected<PreloadBytesConsumerClient>,
      public BytesConsumer::Client {
 public:
  PreloadBytesConsumerClient(BytesConsumer& bytes_consumer,
                             RawResource& resource,
                             RawResourceClient& client)
      : bytes_consumer_(bytes_consumer),
        resource_(resource),
        client_(&client) {}
  void OnStateChange() override {
    auto* client = client_.Get();
    if (!client) {
      return;
    }
    while (resource_->HasClient(client)) {
      base::span<const char> buffer;
      auto result = bytes_consumer_->BeginRead(buffer);
      if (result == BytesConsumer::Result::kShouldWait)
        return;
      if (result == BytesConsumer::Result::kOk) {
        client->DataReceived(resource_, buffer);
        result = bytes_consumer_->EndRead(buffer.size());
      }
      if (result != BytesConsumer::Result::kOk) {
        return;
      }
    }
    client_ = nullptr;
  }

  String DebugName() const override { return "PreloadBytesConsumerClient"; }

  void Trace(Visitor* visitor) const override {
    visitor->Trace(bytes_consumer_);
    visitor->Trace(resource_);
    visitor->Trace(client_);
    BytesConsumer::Client::Trace(visitor);
  }

 private:
  const Member<BytesConsumer> bytes_consumer_;
  const Member<RawResource> resource_;
  WeakMember<RawResourceClient> client_;
};

void RawResource::DidAddClient(ResourceClient* c) {
  auto* bytes_consumer_for_preload = bytes_consumer_for_preload_.Release();

  // CHECK()/RevalidationStartForbiddenScope are for
  // https://crbug.com/640960#c24.
  CHECK(!IsCacheValidator());
  if (!HasClient(c))
    return;
  DCHECK(c->IsRawResourceClient());
  RevalidationStartForbiddenScope revalidation_start_forbidden_scope(this);
  RawResourceClient* client = static_cast<RawResourceClient*>(c);
  for (const auto& redirect : RedirectChain()) {
    client->RedirectReceived(this, ResourceRequest(redirect.request_),
                             redirect.redirect_response_);
    if (!HasClient(c))
      return;
  }

  if (!GetResponse().IsNull()) {
    client->ResponseReceived(this, GetResponse());
  }
  if (!HasClient(c))
    return;

  if (bytes_consumer_for_preload) {
    bytes_consumer_for_preload->StopBuffering();

    if (matched_with_non_streaming_destination_) {
      // In this case, the client needs individual chunks so we need
      // PreloadBytesConsumerClient for the translation.
      auto* preload_bytes_consumer_client =
          MakeGarbageCollected<PreloadBytesConsumerClient>(
              *bytes_consumer_for_preload, *this, *client);
      bytes_consumer_for_preload->SetClient(preload_bytes_consumer_client);
      preload_bytes_consumer_client->OnStateChange();
    } else {
      // In this case, we can simply pass the BytesConsumer to the client.
      client->ResponseBodyReceived(this, *bytes_consumer_for_preload);
    }
  }

  if (!HasClient(c))
    return;

  Resource::DidAddClient(client);
}

bool RawResource::WillFollowRedirect(
    const ResourceRequest& new_request,
    const ResourceResponse& redirect_response) {
  bool follow = Resource::WillFollowRedirect(new_request, redirect_response);
  // 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(!redirect_response.IsNull());
  ResourceClientWalker<RawResourceClient> w(Clients());
  while (RawResourceClient* c = w.Next()) {
    if (!c->RedirectReceived(this, new_request, redirect_response))
      follow = false;
  }

  return follow;
}

void RawResource::WillNotFollowRedirect() {
  ResourceClientWalker<RawResourceClient> w(Clients());
  while (RawResourceClient* c = w.Next())
    c->RedirectBlocked();
}

scoped_refptr<BlobDataHandle> RawResource::DownloadedBlob() const {
  return downloaded_blob_;
}

void RawResource::Trace(Visitor* visitor) const {
  visitor->Trace(bytes_consumer_for_preload_);
  Resource::Trace(visitor);
}

void RawResource::ResponseReceived(const ResourceResponse& response) {
  Resource::ResponseReceived(response);

  ResourceClientWalker<RawResourceClient> w(Clients());
  while (RawResourceClient* c = w.Next()) {
    c->ResponseReceived(this, GetResponse());
  }
}

void RawResource::ResponseBodyReceived(
    ResponseBodyLoaderDrainableInterface& body_loader,
    scoped_refptr<base::SingleThreadTaskRunner> loader_task_runner) {
  DCHECK_LE(Clients().size(), 1u);
  RawResourceClient* client =
      ResourceClientWalker<RawResourceClient>(Clients()).Next();
  if (!client && GetResourceRequest().UseStreamOnResponse()) {
    // For preload, we want to store the body while dispatching
    // onload and onerror events.
    bytes_consumer_for_preload_ =
        BufferingBytesConsumer::Create(&body_loader.DrainAsBytesConsumer());
    return;
  }

  if (matched_with_non_streaming_destination_) {
    DCHECK(GetResourceRequest().UseStreamOnResponse());
    // The loading was initiated as a preload (hence UseStreamOnResponse is
    // set), but this resource has been matched with a request without
    // UseStreamOnResponse set.
    auto& bytes_consumer_for_preload = body_loader.DrainAsBytesConsumer();
    auto* preload_bytes_consumer_client =
        MakeGarbageCollected<PreloadBytesConsumerClient>(
            bytes_consumer_for_preload, *this, *client);
    bytes_consumer_for_preload.SetClient(preload_bytes_consumer_client);
    preload_bytes_consumer_client->OnStateChange();
    return;
  }

  if (!GetResourceRequest().UseStreamOnResponse()) {
    return;
  }

  client->ResponseBodyReceived(this, body_loader.DrainAsBytesConsumer());
}

void RawResource::SetSerializedCachedMetadata(mojo_base::BigBuffer data) {
  // Resource ignores the cached metadata.
  Resource::SetSerializedCachedMetadata(mojo_base::BigBuffer());

  ResourceClientWalker<RawResourceClient> w(Clients());
  // We rely on the fact that RawResource cannot have multiple clients.
  CHECK_LE(Clients().size(), 1u);
  if (RawResourceClient* c = w.Next()) {
    c->CachedMetadataReceived(this, std::move(data));
  }
}

void RawResource::DidSendData(uint64_t bytes_sent,
                              uint64_t total_bytes_to_be_sent) {
  ResourceClientWalker<RawResourceClient> w(Clients());
  while (RawResourceClient* c = w.Next())
    c->DataSent(this, bytes_sent, total_bytes_to_be_sent);
}

void RawResource::DidDownloadData(uint64_t data_length) {
  ResourceClientWalker<RawResourceClient> w(Clients());
  while (RawResourceClient* c = w.Next())
    c->DataDownloaded(this, data_length);
}

void RawResource::DidDownloadToBlob(scoped_refptr<BlobDataHandle> blob) {
  downloaded_blob_ = blob;
  ResourceClientWalker<RawResourceClient> w(Clients());
  while (RawResourceClient* c = w.Next())
    c->DidDownloadToBlob(this, blob);
}

void RawResource::MatchPreload(const FetchParameters& params) {
  Resource::MatchPreload(params);
  matched_with_non_streaming_destination_ =
      !params.GetResourceRequest().UseStreamOnResponse();
}

void RawResourceClient::DidDownloadToBlob(Resource*,
                                          scoped_refptr<BlobDataHandle>) {}

RawResourceClientStateChecker::RawResourceClientStateChecker() = default;

NOINLINE void RawResourceClientStateChecker::WillAddClient() {
  SECURITY_CHECK(state_ == kNotAddedAsClient);
  state_ = kStarted;
}

NOINLINE void RawResourceClientStateChecker::WillRemoveClient() {
  SECURITY_CHECK(state_ != kNotAddedAsClient);
  SECURITY_CHECK(state_ != kDetached);
  state_ = kDetached;
}

NOINLINE void RawResourceClientStateChecker::RedirectReceived() {
  SECURITY_CHECK(state_ == kStarted);
}

NOINLINE void RawResourceClientStateChecker::RedirectBlocked() {
  SECURITY_CHECK(state_ == kStarted);
  state_ = kRedirectBlocked;
}

NOINLINE void RawResourceClientStateChecker::DataSent() {
  SECURITY_CHECK(state_ == kStarted);
}

NOINLINE void RawResourceClientStateChecker::ResponseReceived() {
  // TODO(crbug.com/1431421): remove |state_| dump when the cause is clarified.
  SECURITY_CHECK(state_ == kStarted) << " state_ was " << state_;
  state_ = kResponseReceived;
}

NOINLINE void RawResourceClientStateChecker::SetSerializedCachedMetadata() {
  SECURITY_CHECK(state_ == kStarted || state_ == kResponseReceived ||
                 state_ == kDataReceivedAsBytesConsumer ||
                 state_ == kDataReceived);
}

NOINLINE void RawResourceClientStateChecker::ResponseBodyReceived() {
  SECURITY_CHECK(state_ == kResponseReceived);
  state_ = kDataReceivedAsBytesConsumer;
}

NOINLINE void RawResourceClientStateChecker::DataReceived() {
  SECURITY_CHECK(state_ == kResponseReceived ||
                 state_ == kDataReceived);
  state_ = kDataReceived;
}

NOINLINE void RawResourceClientStateChecker::DataDownloaded() {
  SECURITY_CHECK(state_ == kResponseReceived ||
                 state_ == kDataDownloaded);
  state_ = kDataDownloaded;
}

NOINLINE void RawResourceClientStateChecker::DidDownloadToBlob() {
  SECURITY_CHECK(state_ == kResponseReceived ||
                 state_ == kDataDownloaded);
  state_ = kDidDownloadToBlob;
}

NOINLINE void RawResourceClientStateChecker::NotifyFinished(
    Resource* resource) {
  SECURITY_CHECK(state_ != kNotAddedAsClient);
  SECURITY_CHECK(state_ != kDetached);
  SECURITY_CHECK(state_ != kNotifyFinished);

  SECURITY_CHECK(resource->ErrorOccurred() ||
                 (state_ == kResponseReceived || state_ == kDataReceived ||
                  state_ == kDataDownloaded ||
                  state_ == kDataReceivedAsBytesConsumer ||
                  state_ == kDidDownloadToBlob));
  state_ = kNotifyFinished;
}

}  // namespace blink