7350a5b756df980440d4ffdd678dbacff33baecc
[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 }
50
51 Entry::Entry(const Storage::Record& storageEntry)
52     : m_key(storageEntry.key)
53     , m_timeStamp(storageEntry.timeStamp)
54     , m_sourceStorageRecord(storageEntry)
55 {
56 }
57
58 Storage::Record Entry::encodeAsStorageRecord() const
59 {
60     Encoder encoder;
61     encoder << m_response;
62
63     bool hasVaryingRequestHeaders = !m_varyingRequestHeaders.isEmpty();
64     encoder << hasVaryingRequestHeaders;
65     if (hasVaryingRequestHeaders)
66         encoder << m_varyingRequestHeaders;
67
68     encoder.encodeChecksum();
69
70     Data header(encoder.buffer(), encoder.bufferSize());
71     Data body;
72     if (m_buffer)
73         body = { reinterpret_cast<const uint8_t*>(m_buffer->data()), m_buffer->size() };
74
75     return { m_key, m_timeStamp, header, body };
76 }
77
78 std::unique_ptr<Entry> Entry::decodeStorageRecord(const Storage::Record& storageEntry)
79 {
80     std::unique_ptr<Entry> entry(new Entry(storageEntry));
81
82     Decoder decoder(storageEntry.header.data(), storageEntry.header.size());
83     if (!decoder.decode(entry->m_response))
84         return nullptr;
85     entry->m_response.setSource(WebCore::ResourceResponse::Source::DiskCache);
86
87     bool hasVaryingRequestHeaders;
88     if (!decoder.decode(hasVaryingRequestHeaders))
89         return nullptr;
90
91     if (hasVaryingRequestHeaders) {
92         if (!decoder.decode(entry->m_varyingRequestHeaders))
93             return nullptr;
94     }
95
96     if (!decoder.verifyChecksum()) {
97         LOG(NetworkCache, "(NetworkProcess) checksum verification failure\n");
98         return nullptr;
99     }
100
101     return entry;
102 }
103
104 #if ENABLE(SHAREABLE_RESOURCE)
105 void Entry::initializeShareableResourceHandleFromStorageRecord() const
106 {
107     auto* data = m_sourceStorageRecord.body.data();
108     size_t size = m_sourceStorageRecord.body.size();
109     RefPtr<SharedMemory> sharedMemory = m_sourceStorageRecord.body.isMap() ? SharedMemory::create(const_cast<uint8_t*>(data), size, SharedMemory::Protection::ReadOnly) : nullptr;
110     RefPtr<ShareableResource> shareableResource = sharedMemory ? ShareableResource::create(sharedMemory.release(), 0, size) : nullptr;
111     if (shareableResource)
112         shareableResource->createHandle(m_shareableResourceHandle);
113 }
114 #endif
115
116 void Entry::initializeBufferFromStorageRecord() const
117 {
118 #if ENABLE(SHAREABLE_RESOURCE)
119     if (!shareableResourceHandle().isNull()) {
120         m_buffer = m_shareableResourceHandle.tryWrapInSharedBuffer();
121         if (m_buffer)
122             return;
123     }
124 #endif
125     m_buffer = WebCore::SharedBuffer::create(m_sourceStorageRecord.body.data(), m_sourceStorageRecord.body.size());
126 }
127
128 WebCore::SharedBuffer* Entry::buffer() const
129 {
130     if (!m_buffer)
131         initializeBufferFromStorageRecord();
132
133     return m_buffer.get();
134 }
135
136 #if ENABLE(SHAREABLE_RESOURCE)
137 ShareableResource::Handle& Entry::shareableResourceHandle() const
138 {
139     if (m_shareableResourceHandle.isNull())
140         initializeShareableResourceHandleFromStorageRecord();
141
142     return m_shareableResourceHandle;
143 }
144 #endif
145
146 bool Entry::needsValidation() const
147 {
148     return m_response.source() == WebCore::ResourceResponse::Source::DiskCacheAfterValidation;
149 }
150
151 void Entry::setNeedsValidation()
152 {
153     ASSERT(m_response.source() == WebCore::ResourceResponse::Source::DiskCache);
154     m_response.setSource(WebCore::ResourceResponse::Source::DiskCacheAfterValidation);
155 }
156
157 void Entry::asJSON(StringBuilder& json, const Storage::RecordInfo& info) const
158 {
159     json.appendLiteral("{\n");
160     json.appendLiteral("\"hash\": ");
161     json.appendQuotedJSONString(m_key.hashAsString());
162     json.appendLiteral(",\n");
163     json.appendLiteral("\"bodySize\": ");
164     json.appendNumber(info.bodySize);
165     json.appendLiteral(",\n");
166     json.appendLiteral("\"worth\": ");
167     json.appendNumber(info.worth);
168     json.appendLiteral(",\n");
169     json.appendLiteral("\"partition\": ");
170     json.appendQuotedJSONString(m_key.partition());
171     json.appendLiteral(",\n");
172     json.appendLiteral("\"timestamp\": ");
173     json.appendNumber(std::chrono::duration_cast<std::chrono::milliseconds>(m_timeStamp.time_since_epoch()).count());
174     json.appendLiteral(",\n");
175     json.appendLiteral("\"URL\": ");
176     json.appendQuotedJSONString(m_response.url().string());
177     json.appendLiteral(",\n");
178     json.appendLiteral("\"bodyHash\": ");
179     json.appendQuotedJSONString(info.bodyHash);
180     json.appendLiteral(",\n");
181     json.appendLiteral("\"bodyShareCount\": ");
182     json.appendNumber(info.bodyShareCount);
183     json.appendLiteral(",\n");
184     json.appendLiteral("\"headers\": {\n");
185     bool firstHeader = true;
186     for (auto& header : m_response.httpHeaderFields()) {
187         if (!firstHeader)
188             json.appendLiteral(",\n");
189         firstHeader = false;
190         json.appendLiteral("    ");
191         json.appendQuotedJSONString(header.key);
192         json.appendLiteral(": ");
193         json.appendQuotedJSONString(header.value);
194     }
195     json.appendLiteral("\n}\n");
196     json.appendLiteral("}");
197 }
198
199 }
200 }
201
202 #endif