summaryrefslogtreecommitdiffstats
path: root/third_party/WebKit/Source/core/fetch/Resource.cpp
blob: a311e3f2bc0c214dec20f2802340b62ba17c1db3 (plain)
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
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
/*
    Copyright (C) 1998 Lars Knoll (knoll@mpi-hd.mpg.de)
    Copyright (C) 2001 Dirk Mueller (mueller@kde.org)
    Copyright (C) 2002 Waldo Bastian (bastian@kde.org)
    Copyright (C) 2006 Samuel Weinig (sam.weinig@gmail.com)
    Copyright (C) 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011 Apple Inc. All rights reserved.

    This library is free software; you can redistribute it and/or
    modify it under the terms of the GNU Library General Public
    License as published by the Free Software Foundation; either
    version 2 of the License, or (at your option) any later version.

    This library is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
    Library General Public License for more details.

    You should have received a copy of the GNU Library General Public License
    along with this library; see the file COPYING.LIB.  If not, write to
    the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
    Boston, MA 02110-1301, USA.
*/

#include "core/fetch/Resource.h"

#include "core/fetch/CachedMetadata.h"
#include "core/fetch/CrossOriginAccessControl.h"
#include "core/fetch/FetchInitiatorTypeNames.h"
#include "core/fetch/MemoryCache.h"
#include "core/fetch/ResourceClient.h"
#include "core/fetch/ResourceClientOrObserverWalker.h"
#include "core/fetch/ResourceFetcher.h"
#include "core/fetch/ResourceLoader.h"
#include "core/inspector/InspectorInstrumentation.h"
#include "core/inspector/InstanceCounters.h"
#include "platform/Logging.h"
#include "platform/SharedBuffer.h"
#include "platform/TraceEvent.h"
#include "platform/network/HTTPParsers.h"
#include "platform/weborigin/KURL.h"
#include "public/platform/Platform.h"
#include "public/platform/WebProcessMemoryDump.h"
#include "public/platform/WebScheduler.h"
#include "wtf/CurrentTime.h"
#include "wtf/MathExtras.h"
#include "wtf/StdLibExtras.h"
#include "wtf/Vector.h"
#include "wtf/WeakPtr.h"
#include "wtf/text/CString.h"
#include <algorithm>

namespace blink {

// These response headers are not copied from a revalidated response to the
// cached response headers. For compatibility, this list is based on Chromium's
// net/http/http_response_headers.cc.
const char* const headersToIgnoreAfterRevalidation[] = {
    "allow",
    "connection",
    "etag",
    "expires",
    "keep-alive",
    "last-modified"
    "proxy-authenticate",
    "proxy-connection",
    "trailer",
    "transfer-encoding",
    "upgrade",
    "www-authenticate",
    "x-frame-options",
    "x-xss-protection",
};

// Some header prefixes mean "Don't copy this header from a 304 response.".
// Rather than listing all the relevant headers, we can consolidate them into
// this list, also grabbed from Chromium's net/http/http_response_headers.cc.
const char* const headerPrefixesToIgnoreAfterRevalidation[] = {
    "content-",
    "x-content-",
    "x-webkit-"
};

static inline bool shouldUpdateHeaderAfterRevalidation(const AtomicString& header)
{
    for (size_t i = 0; i < WTF_ARRAY_LENGTH(headersToIgnoreAfterRevalidation); i++) {
        if (equalIgnoringCase(header, headersToIgnoreAfterRevalidation[i]))
            return false;
    }
    for (size_t i = 0; i < WTF_ARRAY_LENGTH(headerPrefixesToIgnoreAfterRevalidation); i++) {
        if (header.startsWith(headerPrefixesToIgnoreAfterRevalidation[i], TextCaseInsensitive))
            return false;
    }
    return true;
}

class Resource::CacheHandler : public CachedMetadataHandler {
public:
    static PassOwnPtrWillBeRawPtr<CacheHandler> create(Resource* resource)
    {
        return adoptPtrWillBeNoop(new CacheHandler(resource));
    }
    ~CacheHandler() override { }
    DECLARE_VIRTUAL_TRACE();
    void setCachedMetadata(unsigned, const char*, size_t, CacheType) override;
    void clearCachedMetadata(CacheType) override;
    CachedMetadata* cachedMetadata(unsigned) const override;
    String encoding() const override;

private:
    explicit CacheHandler(Resource*);
    RawPtrWillBeMember<Resource> m_resource;
};

Resource::CacheHandler::CacheHandler(Resource* resource)
    : m_resource(resource)
{
}

DEFINE_TRACE(Resource::CacheHandler)
{
#if ENABLE(OILPAN)
    visitor->trace(m_resource);
#endif
    CachedMetadataHandler::trace(visitor);
}

void Resource::CacheHandler::setCachedMetadata(unsigned dataTypeID, const char* data, size_t size, CacheType type)
{
    m_resource->setCachedMetadata(dataTypeID, data, size, type);
}

void Resource::CacheHandler::clearCachedMetadata(CacheType type)
{
    m_resource->clearCachedMetadata(type);
}

CachedMetadata* Resource::CacheHandler::cachedMetadata(unsigned dataTypeID) const
{
    return m_resource->cachedMetadata(dataTypeID);
}

String Resource::CacheHandler::encoding() const
{
    return m_resource->encoding();
}

Resource::Resource(const ResourceRequest& request, Type type, const ResourceLoaderOptions& options)
    : m_resourceRequest(request)
    , m_options(options)
    , m_responseTimestamp(currentTime())
    , m_cancelTimer(this, &Resource::cancelTimerFired)
#if !ENABLE(OILPAN)
    , m_weakPtrFactory(this)
#endif
    , m_loadFinishTime(0)
    , m_identifier(0)
    , m_encodedSize(0)
    , m_decodedSize(0)
    , m_preloadCount(0)
    , m_cacheIdentifier(MemoryCache::defaultCacheIdentifier())
    , m_preloadResult(PreloadNotReferenced)
    , m_type(type)
    , m_status(NotStarted)
    , m_needsSynchronousCacheHit(false)
    , m_linkPreload(false)
{
    ASSERT(m_type == unsigned(type)); // m_type is a bitfield, so this tests careless updates of the enum.
    InstanceCounters::incrementCounter(InstanceCounters::ResourceCounter);

    // Currently we support the metadata caching only for HTTP family.
    if (m_resourceRequest.url().protocolIsInHTTPFamily())
        m_cacheHandler = CacheHandler::create(this);

    if (!m_resourceRequest.url().hasFragmentIdentifier())
        return;
    KURL urlForCache = MemoryCache::removeFragmentIdentifierIfNeeded(m_resourceRequest.url());
    if (urlForCache.hasFragmentIdentifier())
        return;
    m_fragmentIdentifierForRequest = m_resourceRequest.url().fragmentIdentifier();
    m_resourceRequest.setURL(urlForCache);
}

Resource::~Resource()
{
    InstanceCounters::decrementCounter(InstanceCounters::ResourceCounter);
}

void Resource::removedFromMemoryCache()
{
    InspectorInstrumentation::removedResourceFromMemoryCache(this);
}

DEFINE_TRACE(Resource)
{
    visitor->trace(m_loader);
#if ENABLE(OILPAN)
    visitor->trace(m_cacheHandler);
#endif
}

void Resource::load(ResourceFetcher* fetcher)
{
    RELEASE_ASSERT(!m_loader);
    m_status = Pending;

    ResourceRequest& request(m_revalidatingRequest.isNull() ? m_resourceRequest : m_revalidatingRequest);
    if (!accept().isEmpty())
        request.setHTTPAccept(accept());
    request.setAllowStoredCredentials(m_options.allowCredentials == AllowStoredCredentials);

    // FIXME: It's unfortunate that the cache layer and below get to know anything about fragment identifiers.
    // We should look into removing the expectation of that knowledge from the platform network stacks.
    KURL urlWithoutFragment = request.url();
    if (!m_fragmentIdentifierForRequest.isNull()) {
        KURL url = request.url();
        url.setFragmentIdentifier(m_fragmentIdentifierForRequest);
        request.setURL(url);
        m_fragmentIdentifierForRequest = String();
    }

    m_loader = ResourceLoader::create(fetcher, this);
    m_loader->start(request);
    // If the request reference is null (i.e., a synchronous revalidation will
    // null the request), don't make the request non-null by setting the url.
    if (!request.isNull())
        request.setURL(urlWithoutFragment);
}

void Resource::checkNotify()
{
    if (isLoading())
        return;

    ResourceClientWalker<ResourceClient> w(m_clients);
    while (ResourceClient* c = w.next())
        c->notifyFinished(this);
}

void Resource::appendData(const char* data, size_t length)
{
    TRACE_EVENT0("blink", "Resource::appendData");
    ASSERT(m_revalidatingRequest.isNull());
    ASSERT(!errorOccurred());
    if (m_options.dataBufferingPolicy == DoNotBufferData)
        return;
    if (m_data)
        m_data->append(data, length);
    else
        m_data = SharedBuffer::createPurgeable(data, length);
    setEncodedSize(m_data->size());
}

void Resource::setResourceBuffer(PassRefPtr<SharedBuffer> resourceBuffer)
{
    ASSERT(m_revalidatingRequest.isNull());
    ASSERT(!errorOccurred());
    ASSERT(m_options.dataBufferingPolicy == BufferData);
    m_data = resourceBuffer;
    setEncodedSize(m_data->size());
}

void Resource::setDataBufferingPolicy(DataBufferingPolicy dataBufferingPolicy)
{
    m_options.dataBufferingPolicy = dataBufferingPolicy;
    m_data.clear();
    setEncodedSize(0);
}

void Resource::markClientsFinished()
{
    while (!m_clients.isEmpty()) {
        HashCountedSet<ResourceClient*>::iterator it = m_clients.begin();
        for (int i = it->value; i; i--) {
            m_finishedClients.add(it->key);
            m_clients.remove(it);
        }
    }
}

void Resource::error(Resource::Status status)
{
    if (!m_revalidatingRequest.isNull())
        m_revalidatingRequest = ResourceRequest();

    if (!m_error.isNull() && (m_error.isCancellation() || !isPreloaded()))
        memoryCache()->remove(this);

    setStatus(status);
    ASSERT(errorOccurred());
    m_data.clear();
    checkNotify();
    markClientsFinished();
}

void Resource::finish()
{
    ASSERT(m_revalidatingRequest.isNull());
    if (!errorOccurred())
        m_status = Cached;
    checkNotify();
    markClientsFinished();
}

AtomicString Resource::httpContentType() const
{
    return extractMIMETypeFromMediaType(m_response.httpHeaderField(HTTPNames::Content_Type).lower());
}

bool Resource::passesAccessControlCheck(SecurityOrigin* securityOrigin) const
{
    String ignoredErrorDescription;
    return passesAccessControlCheck(securityOrigin, ignoredErrorDescription);
}

bool Resource::passesAccessControlCheck(SecurityOrigin* securityOrigin, String& errorDescription) const
{
    return blink::passesAccessControlCheck(m_response, lastResourceRequest().allowStoredCredentials() ? AllowStoredCredentials : DoNotAllowStoredCredentials, securityOrigin, errorDescription, lastResourceRequest().requestContext());
}

bool Resource::isEligibleForIntegrityCheck(SecurityOrigin* securityOrigin) const
{
    String ignoredErrorDescription;
    return securityOrigin->canRequest(resourceRequest().url()) || passesAccessControlCheck(securityOrigin, ignoredErrorDescription);
}

static double currentAge(const ResourceResponse& response, double responseTimestamp)
{
    // RFC2616 13.2.3
    // No compensation for latency as that is not terribly important in practice
    double dateValue = response.date();
    double apparentAge = std::isfinite(dateValue) ? std::max(0., responseTimestamp - dateValue) : 0;
    double ageValue = response.age();
    double correctedReceivedAge = std::isfinite(ageValue) ? std::max(apparentAge, ageValue) : apparentAge;
    double residentTime = currentTime() - responseTimestamp;
    return correctedReceivedAge + residentTime;
}

double Resource::currentAge() const
{
    return blink::currentAge(m_response, m_responseTimestamp);
}

static double freshnessLifetime(ResourceResponse& response, double responseTimestamp)
{
#if !OS(ANDROID)
    // On desktop, local files should be reloaded in case they change.
    if (response.url().isLocalFile())
        return 0;
#endif

    // Cache other non-http / non-filesystem resources liberally.
    if (!response.url().protocolIsInHTTPFamily()
        && !response.url().protocolIs("filesystem"))
        return std::numeric_limits<double>::max();

    // RFC2616 13.2.4
    double maxAgeValue = response.cacheControlMaxAge();
    if (std::isfinite(maxAgeValue))
        return maxAgeValue;
    double expiresValue = response.expires();
    double dateValue = response.date();
    double creationTime = std::isfinite(dateValue) ? dateValue : responseTimestamp;
    if (std::isfinite(expiresValue))
        return expiresValue - creationTime;
    double lastModifiedValue = response.lastModified();
    if (std::isfinite(lastModifiedValue))
        return (creationTime - lastModifiedValue) * 0.1;
    // If no cache headers are present, the specification leaves the decision to the UA. Other browsers seem to opt for 0.
    return 0;
}

double Resource::freshnessLifetime()
{
    return blink::freshnessLifetime(m_response, m_responseTimestamp);
}

double Resource::stalenessLifetime()
{
    return m_response.cacheControlStaleWhileRevalidate();
}

static bool canUseResponse(ResourceResponse& response, double responseTimestamp)
{
    if (response.isNull())
        return false;

    // FIXME: Why isn't must-revalidate considered a reason we can't use the response?
    if (response.cacheControlContainsNoCache() || response.cacheControlContainsNoStore())
        return false;

    if (response.httpStatusCode() == 303)  {
        // Must not be cached.
        return false;
    }

    if (response.httpStatusCode() == 302 || response.httpStatusCode() == 307) {
        // Default to not cacheable unless explicitly allowed.
        bool hasMaxAge = std::isfinite(response.cacheControlMaxAge());
        bool hasExpires = std::isfinite(response.expires());
        // TODO: consider catching Cache-Control "private" and "public" here.
        if (!hasMaxAge && !hasExpires)
            return false;
    }

    return currentAge(response, responseTimestamp) <= freshnessLifetime(response, responseTimestamp);
}

const ResourceRequest& Resource::lastResourceRequest() const
{
    if (!m_redirectChain.size())
        return m_resourceRequest;
    return m_redirectChain.last().m_request;
}

void Resource::willFollowRedirect(ResourceRequest& newRequest, const ResourceResponse& redirectResponse)
{
    newRequest.setAllowStoredCredentials(m_options.allowCredentials == AllowStoredCredentials);
    m_redirectChain.append(RedirectPair(newRequest, redirectResponse));
}

bool Resource::unlock()
{
    if (!m_data)
        return false;

    if (!m_data->isLocked())
        return true;

    if (!memoryCache()->contains(this) || hasClientsOrObservers() || !m_revalidatingRequest.isNull() || !m_loadFinishTime || !isSafeToUnlock())
        return false;

    m_data->unlock();
    return true;
}

void Resource::responseReceived(const ResourceResponse& response, PassOwnPtr<WebDataConsumerHandle>)
{
    m_responseTimestamp = currentTime();

    if (!m_revalidatingRequest.isNull()) {
        if (response.httpStatusCode() == 304) {
            revalidationSucceeded(response);
            return;
        }
        revalidationFailed();
    }
    setResponse(response);
    String encoding = response.textEncodingName();
    if (!encoding.isNull())
        setEncoding(encoding);
}

void Resource::setSerializedCachedMetadata(const char* data, size_t size)
{
    // We only expect to receive cached metadata from the platform once.
    // If this triggers, it indicates an efficiency problem which is most
    // likely unexpected in code designed to improve performance.
    ASSERT(!m_cachedMetadata);
    ASSERT(m_revalidatingRequest.isNull());

    m_cachedMetadata = CachedMetadata::deserialize(data, size);
}

CachedMetadataHandler* Resource::cacheHandler()
{
    return m_cacheHandler.get();
}

void Resource::setCachedMetadata(unsigned dataTypeID, const char* data, size_t size, CachedMetadataHandler::CacheType cacheType)
{
    // Currently, only one type of cached metadata per resource is supported.
    // If the need arises for multiple types of metadata per resource this could
    // be enhanced to store types of metadata in a map.
    ASSERT(!m_cachedMetadata);

    m_cachedMetadata = CachedMetadata::create(dataTypeID, data, size);

    // We don't support sending the metadata to the platform when the response
    // was fetched via a ServiceWorker to prevent an attacker's Service Worker
    // from poisoning the metadata cache.
    // FIXME: Support sending the metadata even if the response was fetched via
    // a ServiceWorker. https://crbug.com/448706
    if (cacheType == CachedMetadataHandler::SendToPlatform && !m_response.wasFetchedViaServiceWorker()) {
        const Vector<char>& serializedData = m_cachedMetadata->serialize();
        Platform::current()->cacheMetadata(m_response.url(), m_response.responseTime(), serializedData.data(), serializedData.size());
    }
}

void Resource::clearCachedMetadata(CachedMetadataHandler::CacheType cacheType)
{
    m_cachedMetadata.clear();

    if (cacheType == CachedMetadataHandler::SendToPlatform)
        Platform::current()->cacheMetadata(m_response.url(), m_response.responseTime(), 0, 0);
}

WeakPtrWillBeRawPtr<Resource> Resource::asWeakPtr()
{
#if ENABLE(OILPAN)
    return this;
#else
    return m_weakPtrFactory.createWeakPtr();
#endif
}

String Resource::reasonNotDeletable() const
{
    StringBuilder builder;
    if (hasClientsOrObservers()) {
        builder.append("hasClients(");
        builder.appendNumber(m_clients.size());
        if (!m_clientsAwaitingCallback.isEmpty()) {
            builder.append(", AwaitingCallback=");
            builder.appendNumber(m_clientsAwaitingCallback.size());
        }
        if (!m_finishedClients.isEmpty()) {
            builder.append(", Finished=");
            builder.appendNumber(m_finishedClients.size());
        }
        builder.append(")");
    }
    if (m_loader) {
        if (!builder.isEmpty())
            builder.append(' ');
        builder.append("m_loader");
    }
    if (m_preloadCount) {
        if (!builder.isEmpty())
            builder.append(' ');
        builder.append("m_preloadCount(");
        builder.appendNumber(m_preloadCount);
        builder.append(")");
    }
    if (memoryCache()->contains(this)) {
        if (!builder.isEmpty())
            builder.append(' ');
        builder.append("in_memory_cache");
    }
    return builder.toString();
}

CachedMetadata* Resource::cachedMetadata(unsigned dataTypeID) const
{
    if (!m_cachedMetadata || m_cachedMetadata->dataTypeID() != dataTypeID)
        return nullptr;
    return m_cachedMetadata.get();
}

void Resource::clearLoader()
{
    m_loader = nullptr;
}

void Resource::didAddClient(ResourceClient* c)
{
    if (isLoaded()) {
        c->notifyFinished(this);
        if (m_clients.contains(c)) {
            m_finishedClients.add(c);
            m_clients.remove(c);
        }
    }
}

static bool shouldSendCachedDataSynchronouslyForType(Resource::Type type)
{
    // Some resources types default to return data synchronously.
    // For most of these, it's because there are layout tests that
    // expect data to return synchronously in case of cache hit. In
    // the case of fonts, there was a performance regression.
    // FIXME: Get to the point where we don't need to special-case sync/async
    // behavior for different resource types.
    if (type == Resource::Image)
        return true;
    if (type == Resource::CSSStyleSheet)
        return true;
    if (type == Resource::Script)
        return true;
    if (type == Resource::Font)
        return true;
    return false;
}

void Resource::willAddClientOrObserver()
{
    ASSERT(!isPurgeable());
    if (m_preloadResult == PreloadNotReferenced) {
        if (isLoaded())
            m_preloadResult = PreloadReferencedWhileComplete;
        else if (isLoading())
            m_preloadResult = PreloadReferencedWhileLoading;
        else
            m_preloadResult = PreloadReferenced;
    }
    if (!hasClientsOrObservers())
        memoryCache()->makeLive(this);
}

void Resource::addClient(ResourceClient* client)
{
    willAddClientOrObserver();

    if (!m_revalidatingRequest.isNull()) {
        m_clients.add(client);
        return;
    }

    // If we have existing data to send to the new client and the resource type supprts it, send it asynchronously.
    if (!m_response.isNull() && !shouldSendCachedDataSynchronouslyForType(getType()) && !m_needsSynchronousCacheHit) {
        m_clientsAwaitingCallback.add(client);
        ResourceCallback::callbackHandler()->schedule(this);
        return;
    }

    m_clients.add(client);
    didAddClient(client);
    return;
}

void Resource::removeClient(ResourceClient* client)
{
    ASSERT(hasClient(client));
    if (m_finishedClients.contains(client))
        m_finishedClients.remove(client);
    else if (m_clientsAwaitingCallback.contains(client))
        m_clientsAwaitingCallback.remove(client);
    else
        m_clients.remove(client);

    if (m_clientsAwaitingCallback.isEmpty())
        ResourceCallback::callbackHandler()->cancel(this);

    didRemoveClientOrObserver();
    // This object may be dead here.
}

void Resource::didRemoveClientOrObserver()
{
    if (!hasClientsOrObservers()) {
        RefPtrWillBeRawPtr<Resource> protect(this);
        memoryCache()->makeDead(this);
        allClientsAndObserversRemoved();

        // RFC2616 14.9.2:
        // "no-store: ... MUST make a best-effort attempt to remove the information from volatile storage as promptly as possible"
        // "... History buffers MAY store such responses as part of their normal operation."
        // We allow non-secure content to be reused in history, but we do not allow secure content to be reused.
        if (hasCacheControlNoStoreHeader() && url().protocolIs("https")) {
            memoryCache()->remove(this);
            memoryCache()->prune();
        } else {
            memoryCache()->prune(this);
        }
    }
    // This object may be dead here.
}

void Resource::allClientsAndObserversRemoved()
{
    if (!m_loader)
        return;
    if (m_type == MainResource || m_type == Raw || !memoryCache()->contains(this))
        cancelTimerFired(&m_cancelTimer);
    else if (!m_cancelTimer.isActive())
        m_cancelTimer.startOneShot(0, BLINK_FROM_HERE);

    unlock();
}

void Resource::cancelTimerFired(Timer<Resource>* timer)
{
    ASSERT_UNUSED(timer, timer == &m_cancelTimer);
    if (hasClientsOrObservers() || !m_loader)
        return;
    RefPtrWillBeRawPtr<Resource> protect(this);
    m_loader->cancelIfNotFinishing();
    memoryCache()->remove(this);
}

void Resource::setDecodedSize(size_t decodedSize)
{
    if (decodedSize == m_decodedSize)
        return;
    size_t oldSize = size();
    m_decodedSize = decodedSize;
    memoryCache()->update(this, oldSize, size());
    memoryCache()->updateDecodedResource(this, UpdateForPropertyChange);
}

void Resource::setEncodedSize(size_t encodedSize)
{
    if (encodedSize == m_encodedSize)
        return;
    size_t oldSize = size();
    m_encodedSize = encodedSize;
    memoryCache()->update(this, oldSize, size());
}

void Resource::didAccessDecodedData()
{
    memoryCache()->updateDecodedResource(this, UpdateForAccess);
    memoryCache()->prune();
}

void Resource::finishPendingClients()
{
    // We're going to notify clients one by one. It is simple if the client does nothing.
    // However there are a couple other things that can happen.
    //
    // 1. Clients can be added during the loop. Make sure they are not processed.
    // 2. Clients can be removed during the loop. Make sure they are always available to be
    //    removed. Also don't call removed clients or add them back.

    // Handle case (1) by saving a list of clients to notify. A separate list also ensure
    // a client is either in m_clients or m_clientsAwaitingCallback.
    Vector<ResourceClient*> clientsToNotify;
    copyToVector(m_clientsAwaitingCallback, clientsToNotify);

    for (const auto& client : clientsToNotify) {
        // Handle case (2) to skip removed clients.
        if (!m_clientsAwaitingCallback.remove(client))
            continue;
        m_clients.add(client);
        didAddClient(client);
    }

    // It is still possible for the above loop to finish a new client synchronously.
    // If there's no client waiting we should deschedule.
    bool scheduled = ResourceCallback::callbackHandler()->isScheduled(this);
    if (scheduled && m_clientsAwaitingCallback.isEmpty())
        ResourceCallback::callbackHandler()->cancel(this);

    // Prevent the case when there are clients waiting but no callback scheduled.
    ASSERT(m_clientsAwaitingCallback.isEmpty() || scheduled);
}

void Resource::prune()
{
    destroyDecodedDataIfPossible();
    unlock();
}

void Resource::onMemoryDump(WebMemoryDumpLevelOfDetail levelOfDetail, WebProcessMemoryDump* memoryDump) const
{
    static const size_t kMaxURLReportLength = 128;
    static const int kMaxResourceClientToShowInMemoryInfra = 10;

    const String dumpName = getMemoryDumpName();
    WebMemoryAllocatorDump* dump = memoryDump->createMemoryAllocatorDump(dumpName);
    dump->addScalar("encoded_size", "bytes", m_encodedSize);
    if (m_data && m_data->isLocked())
        dump->addScalar("live_size", "bytes", m_encodedSize);
    else
        dump->addScalar("dead_size", "bytes", m_encodedSize);

    if (m_data) {
        dump->addScalar("purgeable_size", "bytes", isPurgeable() ? encodedSize() + overheadSize() : 0);
        m_data->onMemoryDump(dumpName, memoryDump);
    }

    if (levelOfDetail == WebMemoryDumpLevelOfDetail::Detailed) {
        String urlToReport = url().getString();
        if (urlToReport.length() > kMaxURLReportLength) {
            urlToReport.truncate(kMaxURLReportLength);
            urlToReport = urlToReport + "...";
        }
        dump->addString("url", "", urlToReport);

        dump->addString("reason_not_deletable", "", reasonNotDeletable());

        Vector<String> clientNames;
        ResourceClientWalker<ResourceClient> walker(m_clients);
        while (ResourceClient* client = walker.next())
            clientNames.append(client->debugName());
        ResourceClientWalker<ResourceClient> walker2(m_clientsAwaitingCallback);
        while (ResourceClient* client = walker2.next())
            clientNames.append("(awaiting) " + client->debugName());
        ResourceClientWalker<ResourceClient> walker3(m_finishedClients);
        while (ResourceClient* client = walker3.next())
            clientNames.append("(finished) " + client->debugName());
        std::sort(clientNames.begin(), clientNames.end(), WTF::codePointCompareLessThan);

        StringBuilder builder;
        for (size_t i = 0; i < clientNames.size() && i < kMaxResourceClientToShowInMemoryInfra; ++i) {
            if (i > 0)
                builder.append(" / ");
            builder.append(clientNames[i]);
        }
        if (clientNames.size() > kMaxResourceClientToShowInMemoryInfra) {
            builder.append(" / and ");
            builder.appendNumber(clientNames.size() - kMaxResourceClientToShowInMemoryInfra);
            builder.append(" more");
        }
        dump->addString("ResourceClient", "", builder.toString());
    }

    const String overheadName = dumpName + "/metadata";
    WebMemoryAllocatorDump* overheadDump = memoryDump->createMemoryAllocatorDump(overheadName);
    overheadDump->addScalar("size", "bytes", overheadSize());
    memoryDump->addSuballocation(overheadDump->guid(), String(WTF::Partitions::kAllocatedObjectPoolName));
}

String Resource::getMemoryDumpName() const
{
    return String::format("web_cache/%s_resources/%ld", resourceTypeToString(getType(), options().initiatorInfo), m_identifier);
}

void Resource::revalidationSucceeded(const ResourceResponse& validatingResponse)
{
    m_response.setResourceLoadTiming(validatingResponse.resourceLoadTiming());

    // RFC2616 10.3.5
    // Update cached headers from the 304 response
    const HTTPHeaderMap& newHeaders = validatingResponse.httpHeaderFields();
    for (const auto& header : newHeaders) {
        // Entity headers should not be sent by servers when generating a 304
        // response; misconfigured servers send them anyway. We shouldn't allow
        // such headers to update the original request. We'll base this on the
        // list defined by RFC2616 7.1, with a few additions for extension headers
        // we care about.
        if (!shouldUpdateHeaderAfterRevalidation(header.key))
            continue;
        m_response.setHTTPHeaderField(header.key, header.value);
    }

    m_resourceRequest = m_revalidatingRequest;
    m_revalidatingRequest = ResourceRequest();
}

void Resource::revalidationFailed()
{
    m_resourceRequest = m_revalidatingRequest;
    m_revalidatingRequest = ResourceRequest();
    m_redirectChain.clear();
    m_data.clear();
    m_cachedMetadata.clear();
    destroyDecodedDataForFailedRevalidation();
}

bool Resource::canReuseRedirectChain()
{
    for (auto& redirect : m_redirectChain) {
        if (!canUseResponse(redirect.m_redirectResponse, m_responseTimestamp))
            return false;
        if (redirect.m_request.cacheControlContainsNoCache() || redirect.m_request.cacheControlContainsNoStore())
            return false;
    }
    return true;
}

bool Resource::hasCacheControlNoStoreHeader()
{
    return m_response.cacheControlContainsNoStore() || m_resourceRequest.cacheControlContainsNoStore();
}

bool Resource::hasVaryHeader() const
{
    return !m_response.httpHeaderField(HTTPNames::Vary).isNull();
}

bool Resource::mustRevalidateDueToCacheHeaders()
{
    return !canUseResponse(m_response, m_responseTimestamp) || m_resourceRequest.cacheControlContainsNoCache() || m_resourceRequest.cacheControlContainsNoStore();
}

bool Resource::canUseCacheValidator()
{
    if (isLoading() || errorOccurred())
        return false;

    if (hasCacheControlNoStoreHeader())
        return false;
    return m_response.hasCacheValidatorFields() || m_resourceRequest.hasCacheValidatorFields();
}

bool Resource::isPurgeable() const
{
    return m_data && !m_data->isLocked();
}

bool Resource::lock()
{
    if (!m_data)
        return true;
    if (m_data->isLocked())
        return true;

    ASSERT(!hasClientsOrObservers());

    // If locking fails, our buffer has been purged. There's no point
    // in leaving a purged resource in MemoryCache.
    if (!m_data->lock()) {
        m_data.clear();
        setEncodedSize(0);
        memoryCache()->remove(this);
        return false;
    }
    return true;
}

size_t Resource::overheadSize() const
{
    static const int kAverageClientsHashMapSize = 384;
    return sizeof(Resource) + m_response.memoryUsage() + kAverageClientsHashMapSize + m_resourceRequest.url().getString().length() * 2;
}

void Resource::didChangePriority(ResourceLoadPriority loadPriority, int intraPriorityValue)
{
    m_resourceRequest.setPriority(loadPriority, intraPriorityValue);
    if (m_loader)
        m_loader->didChangePriority(loadPriority, intraPriorityValue);
}

Resource::ResourceCallback* Resource::ResourceCallback::callbackHandler()
{
    // Oilpan + LSan: as the callbackHandler() singleton is used by Resource
    // and ResourcePtr finalizers, it cannot be released upon shutdown in
    // preparation for leak detection.
    //
    // Keep it out of LSan's reach instead.
    LEAK_SANITIZER_DISABLED_SCOPE;
    DEFINE_STATIC_LOCAL(OwnPtrWillBePersistent<ResourceCallback>, callbackHandler, (adoptPtrWillBeNoop(new ResourceCallback)));
    return callbackHandler.get();
}

DEFINE_TRACE(Resource::ResourceCallback)
{
#if ENABLE(OILPAN)
    visitor->trace(m_resourcesWithPendingClients);
#endif
}

Resource::ResourceCallback::ResourceCallback()
    : m_callbackTaskFactory(CancellableTaskFactory::create(this, &ResourceCallback::runTask))
{
}

void Resource::ResourceCallback::schedule(Resource* resource)
{
    if (!m_callbackTaskFactory->isPending())
        Platform::current()->currentThread()->scheduler()->loadingTaskRunner()->postTask(BLINK_FROM_HERE, m_callbackTaskFactory->cancelAndCreate());
    m_resourcesWithPendingClients.add(resource);
}

void Resource::ResourceCallback::cancel(Resource* resource)
{
    m_resourcesWithPendingClients.remove(resource);
    if (m_callbackTaskFactory->isPending() && m_resourcesWithPendingClients.isEmpty())
        m_callbackTaskFactory->cancel();
}

bool Resource::ResourceCallback::isScheduled(Resource* resource) const
{
    return m_resourcesWithPendingClients.contains(resource);
}

void Resource::ResourceCallback::runTask()
{
    WillBeHeapVector<RefPtrWillBeMember<Resource>> resources;
    for (const RefPtrWillBeMember<Resource>& resource : m_resourcesWithPendingClients)
        resources.append(resource.get());
    m_resourcesWithPendingClients.clear();

    for (const auto& resource : resources)
        resource->finishPendingClients();
}

static const char* initatorTypeNameToString(const AtomicString& initiatorTypeName)
{
    if (initiatorTypeName == FetchInitiatorTypeNames::css)
        return "CSS resource";
    if (initiatorTypeName == FetchInitiatorTypeNames::document)
        return "Document";
    if (initiatorTypeName == FetchInitiatorTypeNames::icon)
        return "Icon";
    if (initiatorTypeName == FetchInitiatorTypeNames::internal)
        return "Internal resource";
    if (initiatorTypeName == FetchInitiatorTypeNames::link)
        return "Link element resource";
    if (initiatorTypeName == FetchInitiatorTypeNames::processinginstruction)
        return "Processing instruction";
    if (initiatorTypeName == FetchInitiatorTypeNames::texttrack)
        return "Text track";
    if (initiatorTypeName == FetchInitiatorTypeNames::xml)
        return "XML resource";
    if (initiatorTypeName == FetchInitiatorTypeNames::xmlhttprequest)
        return "XMLHttpRequest";

    return "Resource";
}

const char* Resource::resourceTypeToString(Type type, const FetchInitiatorInfo& initiatorInfo)
{
    switch (type) {
    case Resource::MainResource:
        return "Main resource";
    case Resource::Image:
        return "Image";
    case Resource::CSSStyleSheet:
        return "CSS stylesheet";
    case Resource::Script:
        return "Script";
    case Resource::Font:
        return "Font";
    case Resource::Raw:
        return initatorTypeNameToString(initiatorInfo.name);
    case Resource::SVGDocument:
        return "SVG document";
    case Resource::XSLStyleSheet:
        return "XSL stylesheet";
    case Resource::LinkPrefetch:
        return "Link prefetch resource";
    case Resource::LinkPreload:
        return "Link preload resource";
    case Resource::TextTrack:
        return "Text track";
    case Resource::ImportResource:
        return "Imported resource";
    case Resource::Media:
        return "Media";
    case Resource::Manifest:
        return "Manifest";
    }
    ASSERT_NOT_REACHED();
    return initatorTypeNameToString(initiatorInfo.name);
}

bool Resource::shouldBlockLoadEvent() const
{
    return !m_linkPreload && isLoadEventBlockingResourceType();
}

bool Resource::isLoadEventBlockingResourceType() const
{
    switch (m_type) {
    case Resource::MainResource:
    case Resource::Image:
    case Resource::CSSStyleSheet:
    case Resource::Script:
    case Resource::Font:
    case Resource::SVGDocument:
    case Resource::XSLStyleSheet:
    case Resource::ImportResource:
        return true;
    case Resource::Raw:
    case Resource::LinkPrefetch:
    case Resource::LinkPreload:
    case Resource::TextTrack:
    case Resource::Media:
    case Resource::Manifest:
        return false;
    }
    ASSERT_NOT_REACHED();
    return false;
}

// Do not modify existing strings below because they are used as UMA names.
// https://crbug.com/579496
const char* Resource::resourceTypeName(Resource::Type type)
{
    switch (type) {
    case Resource::MainResource:
        return "MainResource";
    case Resource::Image:
        return "Image";
    case Resource::CSSStyleSheet:
        return "CSSStyleSheet";
    case Resource::Script:
        return "Script";
    case Resource::Font:
        return "Font";
    case Resource::Raw:
        return "Raw";
    case Resource::SVGDocument:
        return "SVGDocument";
    case Resource::XSLStyleSheet:
        return "XSLStyleSheet";
    case Resource::LinkPrefetch:
        return "LinkPrefetch";
    case Resource::LinkPreload:
        return "LinkPreload";
    case Resource::TextTrack:
        return "TextTrack";
    case Resource::ImportResource:
        return "ImportResource";
    case Resource::Media:
        return "Media";
    case Resource::Manifest:
        return "Manifest";
    }
    ASSERT_NOT_REACHED();
    return "Unknown";
}

} // namespace blink