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 "NetworkCacheData.h"
28
29#include <fcntl.h>
30#include <wtf/CryptographicallyRandomNumber.h>
31#include <wtf/FileSystem.h>
32
33#if !OS(WINDOWS)
34#include <sys/mman.h>
35#include <sys/stat.h>
36#include <unistd.h>
37#endif
38
39namespace WebKit {
40namespace NetworkCache {
41
42#if !OS(WINDOWS)
43Data Data::mapToFile(const String& path) const
44{
45 int fd = open(FileSystem::fileSystemRepresentation(path).data(), O_CREAT | O_EXCL | O_RDWR , S_IRUSR | S_IWUSR);
46 if (fd < 0)
47 return { };
48
49 if (ftruncate(fd, m_size) < 0) {
50 close(fd);
51 return { };
52 }
53
54 void* map = mmap(nullptr, m_size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
55 if (map == MAP_FAILED) {
56 close(fd);
57 return { };
58 }
59
60 uint8_t* mapData = static_cast<uint8_t*>(map);
61 apply([&mapData](const uint8_t* bytes, size_t bytesSize) {
62 memcpy(mapData, bytes, bytesSize);
63 mapData += bytesSize;
64 return true;
65 });
66
67 // Drop the write permission.
68 mprotect(map, m_size, PROT_READ);
69
70 // Flush (asynchronously) to file, turning this into clean memory.
71 msync(map, m_size, MS_ASYNC);
72
73 return Data::adoptMap(map, m_size, fd);
74}
75#else
76Data Data::mapToFile(const String& path) const
77{
78 auto file = FileSystem::openFile(path, FileSystem::FileOpenMode::Write);
79 if (!FileSystem::isHandleValid(file))
80 return { };
81 if (FileSystem::writeToFile(file, reinterpret_cast<const char*>(data()), size()) < 0)
82 return { };
83 return Data(Vector<uint8_t>(m_buffer));
84}
85#endif
86
87#if !OS(WINDOWS)
88Data mapFile(const char* path)
89{
90 int fd = open(path, O_RDONLY, 0);
91 if (fd < 0)
92 return { };
93 struct stat stat;
94 if (fstat(fd, &stat) < 0) {
95 close(fd);
96 return { };
97 }
98 size_t size = stat.st_size;
99 if (!size) {
100 close(fd);
101 return Data::empty();
102 }
103
104 return adoptAndMapFile(fd, 0, size);
105}
106#endif
107
108Data mapFile(const String& path)
109{
110#if !OS(WINDOWS)
111 return mapFile(FileSystem::fileSystemRepresentation(path).data());
112#else
113 auto file = FileSystem::openFile(path, FileSystem::FileOpenMode::Read);
114 if (!FileSystem::isHandleValid(file))
115 return { };
116 long long size;
117 if (!FileSystem::getFileSize(file, size))
118 return { };
119 return adoptAndMapFile(file, 0, size);
120#endif
121}
122
123#if !OS(WINDOWS)
124Data adoptAndMapFile(int fd, size_t offset, size_t size)
125{
126 if (!size) {
127 close(fd);
128 return Data::empty();
129 }
130
131 void* map = mmap(nullptr, size, PROT_READ, MAP_PRIVATE, fd, offset);
132 if (map == MAP_FAILED) {
133 close(fd);
134 return { };
135 }
136
137 return Data::adoptMap(map, size, fd);
138}
139#else
140Data adoptAndMapFile(FileSystem::PlatformFileHandle file, size_t offset, size_t size)
141{
142 return Data(file, offset, size);
143}
144#endif
145
146SHA1::Digest computeSHA1(const Data& data, const Salt& salt)
147{
148 SHA1 sha1;
149 sha1.addBytes(salt.data(), salt.size());
150 data.apply([&sha1](const uint8_t* data, size_t size) {
151 sha1.addBytes(data, size);
152 return true;
153 });
154
155 SHA1::Digest digest;
156 sha1.computeHash(digest);
157 return digest;
158}
159
160bool bytesEqual(const Data& a, const Data& b)
161{
162 if (a.isNull() || b.isNull())
163 return false;
164 if (a.size() != b.size())
165 return false;
166 return !memcmp(a.data(), b.data(), a.size());
167}
168
169static Salt makeSalt()
170{
171 Salt salt;
172 static_assert(salt.size() == 8, "Salt size");
173 *reinterpret_cast<uint32_t*>(&salt[0]) = cryptographicallyRandomNumber();
174 *reinterpret_cast<uint32_t*>(&salt[4]) = cryptographicallyRandomNumber();
175 return salt;
176}
177
178Optional<Salt> readOrMakeSalt(const String& path)
179{
180#if !OS(WINDOWS)
181 auto cpath = FileSystem::fileSystemRepresentation(path);
182 auto fd = open(cpath.data(), O_RDONLY, 0);
183 Salt salt;
184 auto bytesRead = read(fd, salt.data(), salt.size());
185 close(fd);
186 if (bytesRead != static_cast<ssize_t>(salt.size())) {
187 salt = makeSalt();
188
189 unlink(cpath.data());
190 fd = open(cpath.data(), O_WRONLY | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR);
191 bool success = write(fd, salt.data(), salt.size()) == static_cast<ssize_t>(salt.size());
192 close(fd);
193 if (!success)
194 return { };
195 }
196 return salt;
197#else
198 auto file = FileSystem::openFile(path, FileSystem::FileOpenMode::Read);
199 Salt salt;
200 auto bytesRead = FileSystem::readFromFile(file, reinterpret_cast<char*>(salt.data()), salt.size());
201 FileSystem::closeFile(file);
202 if (bytesRead != salt.size()) {
203 salt = makeSalt();
204
205 FileSystem::deleteFile(path);
206 file = FileSystem::openFile(path, FileSystem::FileOpenMode::Write);
207 bool success = FileSystem::writeToFile(file, reinterpret_cast<char*>(salt.data()), salt.size()) == salt.size();
208 FileSystem::closeFile(file);
209 if (!success)
210 return { };
211 }
212 return salt;
213#endif
214}
215
216} // namespace NetworkCache
217} // namespace WebKit
218