Debian Codegraph @

src/ResourceProvider.cpp

raw symbols SCIP
1 /*
2 * Open Chinese Convert
3 *
4 * Copyright 2010-2026 Carbo Kuo and contributors
5 *
6 * Licensed under the Apache License, Version 2.0 (the "License");
7 * you may not use this file except in compliance with the License.
8 * You may obtain a copy of the License at
9 *
10 * http://www.apache.org/licenses/LICENSE-2.0
11 *
12 * Unless required by applicable law or agreed to in writing, software
13 * distributed under the License is distributed on an "AS IS" BASIS,
14 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 * See the License for the specific language governing permissions and
16 * limitations under the License.
17 */
18
19 #include "ResourceProvider.hpp"
20
21 #include <cstdint>
22 #include <fstream>
23 #include <unordered_map>
24 #include <sstream>
25 #include <sys/stat.h>
26
27 #if defined(_WIN32) || defined(_WIN64)
28 #include <windows.h>
29 #include "WinUtil.hpp"
30 #else
31 #include <fcntl.h>
32 #include <sys/mman.h>
33 #include <unistd.h>
34 #endif
35
36 #include "Exception.hpp"
37
38 namespace opencc {
39 namespace {
40
41 bool IsSeparator(char ch) { return ch == '/' || ch == '\\'; }
42
43 uint16_t ReadLe16(const unsigned char* data) {
44 return static_cast<uint16_t>(data[0]) |
45 (static_cast<uint16_t>(data[1]) << 8);
46 }
47
48 uint32_t ReadLe32(const unsigned char* data) {
49 return static_cast<uint32_t>(data[0]) |
50 (static_cast<uint32_t>(data[1]) << 8) |
51 (static_cast<uint32_t>(data[2]) << 16) |
52 (static_cast<uint32_t>(data[3]) << 24);
53 }
54
55 bool IsAbsolutePath(const std::string& path) {
56 if (path.empty()) {
57 return false;
58 }
59 if (IsSeparator(path[0])) {
60 return true;
61 }
62 #if defined(_WIN32) || defined(_WIN64)
63 return path.size() >= 3 && path[1] == ':' && IsSeparator(path[2]);
64 #else
65 return false;
66 #endif
67 }
68
69 bool IsRegularFileUtf8(const std::string& path) {
70 #if defined(_WIN32) || defined(_WIN64)
71 const DWORD attributes =
72 GetFileAttributesW(internal::WideFromUtf8(path).c_str());
73 return attributes != INVALID_FILE_ATTRIBUTES &&
74 (attributes & FILE_ATTRIBUTE_DIRECTORY) == 0;
75 #else
76 struct stat info;
77 if (stat(path.c_str(), &info) != 0) {
78 return false;
79 }
80 return (info.st_mode & S_IFMT) == S_IFREG;
81 #endif
82 }
83
84 std::string JoinPath(const std::string& root, const std::string& resource) {
85 if (root.empty()) {
86 return resource;
87 }
88 if (IsSeparator(root.back())) {
89 return root + resource;
90 }
91 return root + "/" + resource;
92 }
93
94 std::string NormalizeResourceName(std::string_view resourceName) {
95 std::string normalized(resourceName);
96 for (char& ch : normalized) {
97 if (ch == '\\') {
98 ch = '/';
99 }
100 }
101 while (!normalized.empty() && normalized.front() == '/') {
102 normalized.erase(normalized.begin());
103 }
104 return normalized;
105 }
106
107 bool IsSafeZipResourceName(const std::string& name) {
108 if (name.empty() || IsAbsolutePath(name)) {
109 return false;
110 }
111 size_t start = 0;
112 for (;;) {
113 const size_t pos = name.find('/', start);
114 const std::string part = name.substr(start, pos - start);
115 if (part.empty() || part == "." || part == "..") {
116 return false;
117 }
118 if (pos == std::string::npos) {
119 return true;
120 }
121 start = pos + 1;
122 }
123 }
124
125 std::string BaseName(const std::string& path) {
126 const size_t pos = path.find_last_of('/');
127 if (pos == std::string::npos) {
128 return path;
129 }
130 return path.substr(pos + 1);
131 }
132
133 bool GetFileFreshnessCacheKey(const std::string& path, std::string* cacheKey) {
134 #if defined(_WIN32) || defined(_WIN64)
135 WIN32_FILE_ATTRIBUTE_DATA fileInfo;
136 const std::wstring widePath = internal::WideFromUtf8(path);
137 if (widePath.empty() ||
138 !GetFileAttributesExW(widePath.c_str(), GetFileExInfoStandard,
139 &fileInfo)) {
140 return false;
141 }
142 #else
143 struct stat statBuf;
144 if (stat(path.c_str(), &statBuf) != 0) {
145 return false;
146 }
147 #endif
148 *cacheKey = path;
149 cacheKey->push_back('\n');
150 #if defined(_WIN32) || defined(_WIN64)
151 cacheKey->append(
152 std::to_string(static_cast<unsigned long long>(
153 fileInfo.ftLastWriteTime.dwHighDateTime)));
154 cacheKey->push_back('.');
155 cacheKey->append(
156 std::to_string(static_cast<unsigned long long>(
157 fileInfo.ftLastWriteTime.dwLowDateTime)));
158 cacheKey->push_back('\n');
159 cacheKey->append(
160 std::to_string(static_cast<unsigned long long>(fileInfo.nFileSizeHigh)));
161 cacheKey->push_back('.');
162 cacheKey->append(
163 std::to_string(static_cast<unsigned long long>(fileInfo.nFileSizeLow)));
164 #else
165 cacheKey->append(std::to_string(static_cast<long long>(statBuf.st_mtime)));
166 cacheKey->push_back('.');
167 #if defined(__APPLE__) && defined(__MACH__)
168 cacheKey->append(
169 std::to_string(static_cast<long long>(statBuf.st_mtimespec.tv_nsec)));
170 #elif defined(st_mtime_nsec)
171 cacheKey->append(
172 std::to_string(static_cast<long long>(statBuf.st_mtime_nsec)));
173 #else
174 cacheKey->append(
175 std::to_string(static_cast<long long>(statBuf.st_mtim.tv_nsec)));
176 #endif
177 cacheKey->push_back('\n');
178 cacheKey->append(std::to_string(static_cast<long long>(statBuf.st_size)));
179 #endif
180 return true;
181 }
182
183 #if defined(_WIN32) || defined(_WIN64)
184 std::vector<unsigned char> ReadBinaryFile(const std::string& path) {
185 FILE* file = _wfopen(internal::WideFromUtf8(path).c_str(), L"rb");
186 if (file == nullptr) {
187 throw FileNotFound(path);
188 }
189 if (fseek(file, 0, SEEK_END) != 0) {
190 fclose(file);
191 throw FileNotFound(path);
192 }
193 const long fileSize = ftell(file);
194 if (fileSize < 0) {
195 fclose(file);
196 throw FileNotFound(path);
197 }
198 if (fseek(file, 0, SEEK_SET) != 0) {
199 fclose(file);
200 throw FileNotFound(path);
201 }
202 std::vector<unsigned char> data(static_cast<size_t>(fileSize));
203 if (!data.empty() &&
204 fread(data.data(), 1, data.size(), file) != data.size()) {
205 fclose(file);
206 throw FileNotFound(path);
207 }
208 fclose(file);
209 return data;
210 }
211 #endif
212
213 struct ZipEntry {
214 uint16_t method;
215 uint32_t compressedSize;
216 uint32_t uncompressedSize;
217 uint32_t dataOffset;
218 };
219
220 class MappedZipArchive {
221 public:
222 explicit MappedZipArchive(const std::string& path) : fileName(path) {
223 if (!GetFileFreshnessCacheKey(path, &cacheKey)) {
224 throw FileNotFound(path);
225 }
226 #if defined(_WIN32) || defined(_WIN64)
227 buffer = ReadBinaryFile(path);
228 data = buffer.empty() ? nullptr : buffer.data();
229 size = buffer.size();
230 #else
231 fd = open(path.c_str(), O_RDONLY);
232 if (fd < 0) {
233 throw FileNotFound(path);
234 }
235 struct stat info;
236 if (fstat(fd, &info) != 0 || info.st_size < 0) {
237 close(fd);
238 fd = -1;
239 throw FileNotFound(path);
240 }
241 size = static_cast<size_t>(info.st_size);
242 if (size == 0) {
243 close(fd);
244 fd = -1;
245 data = nullptr;
246 return;
247 }
248 void* mapped = mmap(nullptr, size, PROT_READ, MAP_PRIVATE, fd, 0);
249 if (mapped == MAP_FAILED) {
250 close(fd);
251 fd = -1;
252 throw FileNotFound(path);
253 }
254 data = static_cast<const unsigned char*>(mapped);
255 #endif
256 }
257
258 MappedZipArchive(const MappedZipArchive&) = delete;
259 MappedZipArchive& operator=(const MappedZipArchive&) = delete;
260
261 ~MappedZipArchive() {
262 #if !defined(_WIN32) && !defined(_WIN64)
263 if (data != nullptr) {
264 munmap(const_cast<unsigned char*>(data), size);
265 }
266 if (fd >= 0) {
267 close(fd);
268 }
269 #endif
270 }
271
272 const std::string fileName;
273 std::string cacheKey;
274 const unsigned char* data = nullptr;
275 size_t size = 0;
276
277 private:
278 #if defined(_WIN32) || defined(_WIN64)
279 std::vector<unsigned char> buffer;
280 #else
281 int fd = -1;
282 #endif
283 };
284
285 } // namespace
286
287 struct ZipResourceProvider::Internal {
288 explicit Internal(const std::string& zipFileName_)
289 : archive(std::make_shared<MappedZipArchive>(zipFileName_)) {
290 Index();
291 }
292
293 void Index();
294
295 std::shared_ptr<MappedZipArchive> archive;
296 std::unordered_map<std::string, ZipEntry> entries;
297 };
298
299 void ZipResourceProvider::Internal::Index() {
300 const unsigned char* data = archive->data;
301 const size_t size = archive->size;
302 if (size < 22) {
303 throw InvalidFormat("Invalid zip archive: " + archive->fileName);
304 }
305
306 const size_t maxCommentSize = 65535;
307 const size_t searchStart =
308 size > maxCommentSize + 22 ? size - maxCommentSize - 22 : 0;
309 size_t eocdOffset = std::string::npos;
310 for (size_t pos = size - 22;; pos--) {
311 if (data[pos] == 0x50 && data[pos + 1] == 0x4b && data[pos + 2] == 0x05 &&
312 data[pos + 3] == 0x06) {
313 eocdOffset = pos;
314 break;
315 }
316 if (pos == searchStart) {
317 break;
318 }
319 }
320 if (eocdOffset == std::string::npos) {
321 throw InvalidFormat("Invalid zip archive: " + archive->fileName);
322 }
323
324 const uint16_t entryCount = ReadLe16(&data[eocdOffset + 10]);
325 const uint32_t centralDirectorySize = ReadLe32(&data[eocdOffset + 12]);
326 const uint32_t centralDirectoryOffset = ReadLe32(&data[eocdOffset + 16]);
327 if (centralDirectoryOffset > size ||
328 centralDirectorySize > size - centralDirectoryOffset) {
329 throw InvalidFormat("Invalid zip central directory: " + archive->fileName);
330 }
331
332 size_t pos = centralDirectoryOffset;
333 for (uint16_t i = 0; i < entryCount; i++) {
334 if (pos + 46 > size || ReadLe32(&data[pos]) != 0x02014b50) {
335 throw InvalidFormat("Invalid zip central directory: " + archive->fileName);
336 }
337 const uint16_t method = ReadLe16(&data[pos + 10]);
338 const uint32_t compressedSize = ReadLe32(&data[pos + 20]);
339 const uint32_t uncompressedSize = ReadLe32(&data[pos + 24]);
340 const uint16_t fileNameLength = ReadLe16(&data[pos + 28]);
341 const uint16_t extraLength = ReadLe16(&data[pos + 30]);
342 const uint16_t commentLength = ReadLe16(&data[pos + 32]);
343 const uint32_t localHeaderOffset = ReadLe32(&data[pos + 42]);
344 const size_t next = pos + 46 + fileNameLength + extraLength + commentLength;
345 if (next > size) {
346 throw InvalidFormat("Invalid zip central directory: " + archive->fileName);
347 }
348 const std::string name(
349 reinterpret_cast<const char*>(&data[pos + 46]), fileNameLength);
350 const std::string normalized = NormalizeResourceName(name);
351 if (!IsAbsolutePath(name) && !normalized.empty() &&
352 normalized.back() != '/' && IsSafeZipResourceName(normalized)) {
353 if (localHeaderOffset + 30 > size ||
354 ReadLe32(&data[localHeaderOffset]) != 0x04034b50) {
355 throw InvalidFormat("Invalid zip local header: " + archive->fileName);
356 }
357 const uint16_t localNameLength = ReadLe16(&data[localHeaderOffset + 26]);
358 const uint16_t localExtraLength = ReadLe16(&data[localHeaderOffset + 28]);
359 const size_t dataOffset =
360 localHeaderOffset + 30 + localNameLength + localExtraLength;
361 if (dataOffset > size || compressedSize > size - dataOffset) {
362 throw InvalidFormat("Invalid zip entry data: " + archive->fileName);
363 }
364 entries[normalized] = ZipEntry{
365 method, compressedSize, uncompressedSize,
366 static_cast<uint32_t>(dataOffset)};
367 }
368 pos = next;
369 }
370 }
371
372 ResourceProvider::Resource::Resource(std::string name_, const char* data_,
373 size_t size_,
374 std::shared_ptr<const void> owner_,
375 std::string cacheKey_)
376 : name(std::move(name_)), data(data_), size(size_),
377 owner(std::move(owner_)), cacheKey(std::move(cacheKey_)) {}
378
379 std::shared_ptr<const ResourceProvider::Resource>
380 ResourceProvider::GetResource(std::string_view resourceName) const {
381 const std::string path = Resolve(resourceName);
382 std::shared_ptr<std::string> content(new std::string);
383 #if defined(_WIN32) || defined(_WIN64)
384 const std::vector<unsigned char> data = ReadBinaryFile(path);
385 content->assign(reinterpret_cast<const char*>(data.data()), data.size());
386 #else
387 std::ifstream input(path, std::ios::binary);
388 if (!input) {
389 throw FileNotFound(path);
390 }
391 content->assign(std::istreambuf_iterator<char>(input),
392 std::istreambuf_iterator<char>());
393 if (input.bad()) {
394 throw FileNotFound(path);
395 }
396 #endif
397
398 std::string cacheKey;
399 if (!GetFileFreshnessCacheKey(path, &cacheKey)) {
400 throw FileNotFound(path);
401 }
402 return std::make_shared<Resource>(path, content->data(), content->size(),
403 content, cacheKey);
404 }
405
406 FilesystemResourceProvider::FilesystemResourceProvider(
407 std::vector<std::string> searchPaths_)
408 : searchPaths(std::move(searchPaths_)) {}
409
410 std::string
411 FilesystemResourceProvider::Resolve(std::string_view resourceName) const {
412 const std::string resourcePath(resourceName);
413 if (resourcePath.empty()) {
414 throw FileNotFound(resourcePath);
415 }
416
417 if (IsAbsolutePath(resourcePath)) {
418 if (IsRegularFileUtf8(resourcePath)) {
419 return resourcePath;
420 }
421 throw FileNotFound(resourcePath);
422 }
423
424 std::ostringstream searched;
425 for (size_t i = 0; i < searchPaths.size(); i++) {
426 const std::string& root = searchPaths[i];
427 if (i != 0) {
428 searched << ", ";
429 }
430 searched << root;
431
432 const std::string candidate = JoinPath(root, resourcePath);
433 if (IsRegularFileUtf8(candidate)) {
434 return candidate;
435 }
436 }
437
438 throw FileNotFound(resourcePath + " (searched: " + searched.str() + ")");
439 }
440
441 ZipResourceProvider::ZipResourceProvider(std::string zipFileName)
442 : internal(new Internal(zipFileName)) {}
443
444 ZipResourceProvider::~ZipResourceProvider() = default;
445
446 std::string ZipResourceProvider::Resolve(std::string_view resourceName) const {
447 throw FileNotFound(std::string(resourceName));
448 }
449
450 std::shared_ptr<const ResourceProvider::Resource>
451 ZipResourceProvider::GetResource(std::string_view resourceName) const {
452 if (IsAbsolutePath(std::string(resourceName))) {
453 throw FileNotFound(std::string(resourceName));
454 }
455
456 const std::string normalized = NormalizeResourceName(resourceName);
457 if (!IsSafeZipResourceName(normalized)) {
458 throw FileNotFound(std::string(resourceName));
459 }
460
461 auto entry = internal->entries.find(normalized);
462 if (entry == internal->entries.end()) {
463 const std::string baseName = BaseName(normalized);
464 if (baseName != normalized) {
465 entry = internal->entries.find(baseName);
466 }
467 }
468 if (entry == internal->entries.end()) {
469 throw FileNotFound(normalized);
470 }
471 if (entry->second.method != 0) {
472 throw InvalidFormat("Unsupported zip compression method for " + entry->first);
473 }
474 if (entry->second.compressedSize != entry->second.uncompressedSize) {
475 throw InvalidFormat("Invalid stored zip entry size for " + entry->first);
476 }
477
478 const char* data = reinterpret_cast<const char*>(
479 internal->archive->data + entry->second.dataOffset);
480 std::string cacheKey = internal->archive->cacheKey;
481 cacheKey.push_back('\n');
482 cacheKey.append(entry->first);
483 cacheKey.push_back('\n');
484 cacheKey.append(std::to_string(entry->second.uncompressedSize));
485 return std::make_shared<ResourceProvider::Resource>(
486 entry->first, data, entry->second.uncompressedSize, internal->archive,
487 cacheKey);
488 }
489
490 } // namespace opencc