faa4f04d18320dc7dfa329e99244e8835725e4b5
[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(WTFMove(buffer))
48 {
49     ASSERT(m_key.type() == "resource");
50 }
51
52 Entry::Entry(const Key& key, const WebCore::ResourceResponse& response, const WebCore::ResourceRequest& redirectRequest, const Vector<std::pair<String, String>>& varyingRequestHeaders)
53     : m_key(key)
54     , m_timeStamp(std::chrono::system_clock::now())
55     , m_response(response)
56     , m_varyingRequestHeaders(varyingRequestHeaders)
57     , m_redirectRequest(WebCore::ResourceRequest::adopt(redirectRequest.copyData())) // Don't include the underlying platform request object.
58 {
59     ASSERT(m_key.type() == "resource");
60     // Redirect body is not needed even if exists.
61     m_redirectRequest->setHTTPBody(nullptr);
62 }
63
64 Entry::Entry(const Entry& other)
65     : m_key(other.m_key)
66     , m_timeStamp(other.m_timeStamp)
67     , m_response(other.m_response)
68     , m_varyingRequestHeaders(other.m_varyingRequestHeaders)
69     , m_buffer(other.m_buffer)
70     , m_sourceStorageRecord(other.m_sourceStorageRecord)
71 {
72 }
73
74 Entry::Entry(const Storage::Record& storageEntry)
75     : m_key(storageEntry.key)
76     , m_timeStamp(storageEntry.timeStamp)
77     , m_sourceStorageRecord(storageEntry)
78 {
79     ASSERT(m_key.type() == "resource");
80 }
81
82 Storage::Record Entry::encodeAsStorageRecord() const
83 {
84     Encoder encoder;
85     encoder << m_response;
86
87     bool hasVaryingRequestHeaders = !m_varyingRequestHeaders.isEmpty();
88     encoder << hasVaryingRequestHeaders;
89     if (hasVaryingRequestHeaders)
90         encoder << m_varyingRequestHeaders;
91
92     bool isRedirect = !!m_redirectRequest;
93     encoder << isRedirect;
94     if (isRedirect)
95         m_redirectRequest->encodeWithoutPlatformData(encoder);
96
97     encoder.encodeChecksum();
98
99     Data header(encoder.buffer(), encoder.bufferSize());
100     Data body;
101     if (m_buffer)
102         body = { reinterpret_cast<const uint8_t*>(m_buffer->data()), m_buffer->size() };
103
104     return { m_key, m_timeStamp, header, body };
105 }
106
107 std::unique_ptr<Entry> Entry::decodeStorageRecord(const Storage::Record& storageEntry)
108 {
109     auto entry = std::make_unique<Entry>(storageEntry);
110
111     Decoder decoder(storageEntry.header.data(), storageEntry.header.size());
112     if (!decoder.decode(entry->m_response))
113         return nullptr;
114     entry->m_response.setSource(WebCore::ResourceResponse::Source::DiskCache);
115
116     bool hasVaryingRequestHeaders;
117     if (!decoder.decode(hasVaryingRequestHeaders))
118         return nullptr;
119
120     if (hasVaryingRequestHeaders) {
121         if (!decoder.decode(entry->m_varyingRequestHeaders))
122             return nullptr;
123     }
124
125     bool isRedirect;
126     if (!decoder.decode(isRedirect))
127         return nullptr;
128
129     if (isRedirect) {
130         entry->m_redirectRequest = std::make_unique<WebCore::ResourceRequest>();
131         if (!entry->m_redirectRequest->decodeWithoutPlatformData(decoder))
132             return nullptr;
133     }
134
135     if (!decoder.verifyChecksum()) {
136         LOG(NetworkCache, "(NetworkProcess) checksum verification failure\n");
137         return nullptr;
138     }
139
140     return entry;
141 }
142
143 #if ENABLE(SHAREABLE_RESOURCE)
144 void Entry::initializeShareableResourceHandleFromStorageRecord() const
145 {
146     RefPtr<SharedMemory> sharedMemory = m_sourceStorageRecord.body.tryCreateSharedMemory();
147     if (!sharedMemory)
148         return;
149
150     RefPtr<ShareableResource> shareableResource = ShareableResource::create(sharedMemory.release(), 0, m_sourceStorageRecord.body.size());
151     ASSERT(shareableResource);
152     shareableResource->createHandle(m_shareableResourceHandle);
153 }
154 #endif
155
156 void Entry::initializeBufferFromStorageRecord() const
157 {
158 #if ENABLE(SHAREABLE_RESOURCE)
159     if (!shareableResourceHandle().isNull()) {
160         m_buffer = m_shareableResourceHandle.tryWrapInSharedBuffer();
161         if (m_buffer)
162             return;
163     }
164 #endif
165     m_buffer = WebCore::SharedBuffer::create(m_sourceStorageRecord.body.data(), m_sourceStorageRecord.body.size());
166 }
167
168 WebCore::SharedBuffer* Entry::buffer() const
169 {
170     if (!m_buffer)
171         initializeBufferFromStorageRecord();
172
173     return m_buffer.get();
174 }
175
176 #if ENABLE(SHAREABLE_RESOURCE)
177 ShareableResource::Handle& Entry::shareableResourceHandle() const
178 {
179     if (m_shareableResourceHandle.isNull())
180         initializeShareableResourceHandleFromStorageRecord();
181
182     return m_shareableResourceHandle;
183 }
184 #endif
185
186 bool Entry::needsValidation() const
187 {
188     return m_response.source() == WebCore::ResourceResponse::Source::DiskCacheAfterValidation;
189 }
190
191 void Entry::setNeedsValidation()
192 {
193     ASSERT(m_response.source() == WebCore::ResourceResponse::Source::DiskCache);
194     m_response.setSource(WebCore::ResourceResponse::Source::DiskCacheAfterValidation);
195 }
196
197 void Entry::asJSON(StringBuilder& json, const Storage::RecordInfo& info) const
198 {
199     json.appendLiteral("{\n");
200     json.appendLiteral("\"hash\": ");
201     json.appendQuotedJSONString(m_key.hashAsString());
202     json.appendLiteral(",\n");
203     json.appendLiteral("\"bodySize\": ");
204     json.appendNumber(info.bodySize);
205     json.appendLiteral(",\n");
206     json.appendLiteral("\"worth\": ");
207     json.appendNumber(info.worth);
208     json.appendLiteral(",\n");
209     json.appendLiteral("\"partition\": ");
210     json.appendQuotedJSONString(m_key.partition());
211     json.appendLiteral(",\n");
212     json.appendLiteral("\"timestamp\": ");
213     json.appendNumber(std::chrono::duration_cast<std::chrono::milliseconds>(m_timeStamp.time_since_epoch()).count());
214     json.appendLiteral(",\n");
215     json.appendLiteral("\"URL\": ");
216     json.appendQuotedJSONString(m_response.url().string());
217     json.appendLiteral(",\n");
218     json.appendLiteral("\"bodyHash\": ");
219     json.appendQuotedJSONString(info.bodyHash);
220     json.appendLiteral(",\n");
221     json.appendLiteral("\"bodyShareCount\": ");
222     json.appendNumber(info.bodyShareCount);
223     json.appendLiteral(",\n");
224     json.appendLiteral("\"headers\": {\n");
225     bool firstHeader = true;
226     for (auto& header : m_response.httpHeaderFields()) {
227         if (!firstHeader)
228             json.appendLiteral(",\n");
229         firstHeader = false;
230         json.appendLiteral("    ");
231         json.appendQuotedJSONString(header.key);
232         json.appendLiteral(": ");
233         json.appendQuotedJSONString(header.value);
234     }
235     json.appendLiteral("\n}\n");
236     json.appendLiteral("}");
237 }
238
239 }
240 }
241
242 #endif