Add assertions to NetworkCache::Entry constructor to make sure a key's type is "resource"
[WebKit-https.git] / Source / WebKit2 / NetworkProcess / cache / NetworkCacheEntry.cpp
1 /*
2  * Copyright (C) 2015 Apple 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
6  * are met:
7  * 1. Redistributions of source code must retain the above copyright
8  *    notice, this list of conditions and the following disclaimer.
9  * 2. Redistributions in binary form must reproduce the above copyright
10  *    notice, this list of conditions and the following disclaimer in the
11  *    documentation and/or other materials provided with the distribution.
12  *
13  * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''
14  * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
15  * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
16  * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS
17  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
18  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
19  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
20  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
21  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
22  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
23  * THE POSSIBILITY OF SUCH DAMAGE.
24  */
25
26 #include "config.h"
27 #include "NetworkCache.h"
28
29 #include "Logging.h"
30 #include "NetworkCacheCoders.h"
31 #include "NetworkCacheDecoder.h"
32 #include "NetworkCacheEncoder.h"
33 #include <WebCore/ResourceRequest.h>
34 #include <WebCore/SharedBuffer.h>
35 #include <wtf/text/StringBuilder.h>
36
37 #if ENABLE(NETWORK_CACHE)
38
39 namespace WebKit {
40 namespace NetworkCache {
41
42 Entry::Entry(const Key& key, const WebCore::ResourceResponse& response, RefPtr<WebCore::SharedBuffer>&& buffer, const Vector<std::pair<String, String>>& varyingRequestHeaders)
43     : m_key(key)
44     , m_timeStamp(std::chrono::system_clock::now())
45     , m_response(response)
46     , m_varyingRequestHeaders(varyingRequestHeaders)
47     , m_buffer(WTF::move(buffer))
48 {
49     ASSERT(m_key.type() == "resource");
50 }
51
52 Entry::Entry(const Storage::Record& storageEntry)
53     : m_key(storageEntry.key)
54     , m_timeStamp(storageEntry.timeStamp)
55     , m_sourceStorageRecord(storageEntry)
56 {
57     ASSERT(m_key.type() == "resource");
58 }
59
60 Storage::Record Entry::encodeAsStorageRecord() const
61 {
62     Encoder encoder;
63     encoder << m_response;
64
65     bool hasVaryingRequestHeaders = !m_varyingRequestHeaders.isEmpty();
66     encoder << hasVaryingRequestHeaders;
67     if (hasVaryingRequestHeaders)
68         encoder << m_varyingRequestHeaders;
69
70     encoder.encodeChecksum();
71
72     Data header(encoder.buffer(), encoder.bufferSize());
73     Data body;
74     if (m_buffer)
75         body = { reinterpret_cast<const uint8_t*>(m_buffer->data()), m_buffer->size() };
76
77     return { m_key, m_timeStamp, header, body };
78 }
79
80 std::unique_ptr<Entry> Entry::decodeStorageRecord(const Storage::Record& storageEntry)
81 {
82     std::unique_ptr<Entry> entry(new Entry(storageEntry));
83
84     Decoder decoder(storageEntry.header.data(), storageEntry.header.size());
85     if (!decoder.decode(entry->m_response))
86         return nullptr;
87     entry->m_response.setSource(WebCore::ResourceResponse::Source::DiskCache);
88
89     bool hasVaryingRequestHeaders;
90     if (!decoder.decode(hasVaryingRequestHeaders))
91         return nullptr;
92
93     if (hasVaryingRequestHeaders) {
94         if (!decoder.decode(entry->m_varyingRequestHeaders))
95             return nullptr;
96     }
97
98     if (!decoder.verifyChecksum()) {
99         LOG(NetworkCache, "(NetworkProcess) checksum verification failure\n");
100         return nullptr;
101     }
102
103     return entry;
104 }
105
106 #if ENABLE(SHAREABLE_RESOURCE)
107 void Entry::initializeShareableResourceHandleFromStorageRecord() const
108 {
109     RefPtr<SharedMemory> sharedMemory = m_sourceStorageRecord.body.tryCreateSharedMemory();
110     if (!sharedMemory)
111         return;
112
113     RefPtr<ShareableResource> shareableResource = ShareableResource::create(sharedMemory.release(), 0, m_sourceStorageRecord.body.size());
114     ASSERT(shareableResource);
115     shareableResource->createHandle(m_shareableResourceHandle);
116 }
117 #endif
118
119 void Entry::initializeBufferFromStorageRecord() const
120 {
121 #if ENABLE(SHAREABLE_RESOURCE)
122     if (!shareableResourceHandle().isNull()) {
123         m_buffer = m_shareableResourceHandle.tryWrapInSharedBuffer();
124         if (m_buffer)
125             return;
126     }
127 #endif
128     m_buffer = WebCore::SharedBuffer::create(m_sourceStorageRecord.body.data(), m_sourceStorageRecord.body.size());
129 }
130
131 WebCore::SharedBuffer* Entry::buffer() const
132 {
133     if (!m_buffer)
134         initializeBufferFromStorageRecord();
135
136     return m_buffer.get();
137 }
138
139 #if ENABLE(SHAREABLE_RESOURCE)
140 ShareableResource::Handle& Entry::shareableResourceHandle() const
141 {
142     if (m_shareableResourceHandle.isNull())
143         initializeShareableResourceHandleFromStorageRecord();
144
145     return m_shareableResourceHandle;
146 }
147 #endif
148
149 bool Entry::needsValidation() const
150 {
151     return m_response.source() == WebCore::ResourceResponse::Source::DiskCacheAfterValidation;
152 }
153
154 void Entry::setNeedsValidation()
155 {
156     ASSERT(m_response.source() == WebCore::ResourceResponse::Source::DiskCache);
157     m_response.setSource(WebCore::ResourceResponse::Source::DiskCacheAfterValidation);
158 }
159
160 void Entry::asJSON(StringBuilder& json, const Storage::RecordInfo& info) const
161 {
162     json.appendLiteral("{\n");
163     json.appendLiteral("\"hash\": ");
164     json.appendQuotedJSONString(m_key.hashAsString());
165     json.appendLiteral(",\n");
166     json.appendLiteral("\"bodySize\": ");
167     json.appendNumber(info.bodySize);
168     json.appendLiteral(",\n");
169     json.appendLiteral("\"worth\": ");
170     json.appendNumber(info.worth);
171     json.appendLiteral(",\n");
172     json.appendLiteral("\"partition\": ");
173     json.appendQuotedJSONString(m_key.partition());
174     json.appendLiteral(",\n");
175     json.appendLiteral("\"timestamp\": ");
176     json.appendNumber(std::chrono::duration_cast<std::chrono::milliseconds>(m_timeStamp.time_since_epoch()).count());
177     json.appendLiteral(",\n");
178     json.appendLiteral("\"URL\": ");
179     json.appendQuotedJSONString(m_response.url().string());
180     json.appendLiteral(",\n");
181     json.appendLiteral("\"bodyHash\": ");
182     json.appendQuotedJSONString(info.bodyHash);
183     json.appendLiteral(",\n");
184     json.appendLiteral("\"bodyShareCount\": ");
185     json.appendNumber(info.bodyShareCount);
186     json.appendLiteral(",\n");
187     json.appendLiteral("\"headers\": {\n");
188     bool firstHeader = true;
189     for (auto& header : m_response.httpHeaderFields()) {
190         if (!firstHeader)
191             json.appendLiteral(",\n");
192         firstHeader = false;
193         json.appendLiteral("    ");
194         json.appendQuotedJSONString(header.key);
195         json.appendLiteral(": ");
196         json.appendQuotedJSONString(header.value);
197     }
198     json.appendLiteral("\n}\n");
199     json.appendLiteral("}");
200 }
201
202 }
203 }
204
205 #endif