Qt
Internal/Contributor docs for the Qt SDK. Note: These are NOT official API docs; those are found at https://doc.qt.io/
Loading...
Searching...
No Matches
qmimeprovider.cpp
Go to the documentation of this file.
1// Copyright (C) 2018 The Qt Company Ltd.
2// Copyright (C) 2018 Klaralvdalens Datakonsult AB, a KDAB Group company, info@kdab.com, author David Faure <david.faure@kdab.com>
3// Copyright (C) 2019 Intel Corporation.
4// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
5// Qt-Security score:critical reason:data-parser
6
8
10#include <qstandardpaths.h>
12
13#include <QXmlStreamReader>
14#include <QBuffer>
15#include <QDir>
16#include <QFile>
17#include <QByteArrayMatcher>
18#include <QDebug>
19#include <QDateTime>
20#include <QtEndian>
21
22#if QT_CONFIG(mimetype_database)
23# if defined(Q_CC_MSVC_ONLY)
24# pragma section(".qtmimedatabase", read, shared)
25__declspec(allocate(".qtmimedatabase")) __declspec(align(4096))
26# elif defined(Q_OS_DARWIN)
27__attribute__((section("__TEXT,.qtmimedatabase"), aligned(4096)))
28# elif (defined(Q_OF_ELF) || defined(Q_OS_WIN)) && defined(Q_CC_GNU)
29__attribute__((section(".qtmimedatabase"), aligned(4096)))
30# endif
31
32# include "qmimeprovider_database.cpp"
33
34# ifdef MIME_DATABASE_IS_ZSTD
35# if !QT_CONFIG(zstd)
36# error "MIME database is zstd but no support compiled in!"
37# endif
38# include <zstd.h>
39# endif
40# ifdef MIME_DATABASE_IS_GZIP
41# ifdef QT_NO_COMPRESS
42# error "MIME database is zlib but no support compiled in!"
43# endif
44# define ZLIB_CONST
45# include <zconf.h>
46# include <zlib.h>
47# endif
48#endif
49
50QT_BEGIN_NAMESPACE
51
52using namespace Qt::StringLiterals;
53// Position of the "list offsets" values, at the beginning of the mime.cache file
54enum {
61 // PosNamespaceListOffset = 28,
64};
65
66// Size of one record of each of the lists, as defined by the mime.cache format
67enum {
75};
76
77enum {
80};
81
82/*
83 A list of fixed-size records in the mime.cache file, whose bounds have been
84 checked once: for any index below count, the whole record at
85 recordOffset(index) is inside the file, so walking the list needs no further
86 checking - read the fields with CacheFile::recordUint32(). An empty list
87 means either a mime.cache is empty or corrupted.
88
89 Anything reached by following an offset stored inside a record is still
90 untrusted and has to be checked where it is used.
91 */
92class QMimeBinaryProvider::RecordList
93{
94public:
95 // The lists whose offsets live in the first 40 bytes of the file are read
96 // by these two functions, once, when the cache file is loaded.
97 bool load(const CacheFile *cacheFile, quint64 posListOffset, quint32 stride);
98 bool loadIndirect(const CacheFile *cacheFile, quint64 posListOffset,
99 quint64 firstRecordPos, quint32 stride);
100
101 quint32 count() const { return m_count; } // N_ALIASES/N_ENTRIES/N_PARENTS/etc => CARD32 type
102 quint32 stride() const { return m_stride; }
103 quint64 firstRecord() const { return m_firstRecord; }
104 quint64 recordOffset(quint32 index) const
105 {
106 Q_ASSERT(index < m_count);
107 return m_firstRecord + quint64(index) * m_stride;
108 }
109
110private:
111 // The state is private, and setRecords() is the only thing that writes it,
112 // so a RecordList that is not empty has been bounds-checked.
113 bool setRecords(const CacheFile *cacheFile, quint64 firstRecord,
114 quint32 count, quint32 stride);
115
116 quint64 m_firstRecord = 0;
117 quint32 m_stride = 0;
118 quint32 m_count = 0;
119};
120
121struct QMimeBinaryProvider::CacheFile
122{
123 CacheFile(const QString &fileName);
125
126 bool isValid() const { return m_valid; }
127 inline std::optional<quint16> getUint16(quint64 offset) const
128 {
129 if (offset > m_fileSize || m_fileSize - offset < sizeof(quint16))
130 return std::nullopt;
131 return qFromBigEndian<quint16>(m_data + offset);
132 }
133 inline std::optional<quint32> getUint32(quint64 offset, quint64 extra = 0) const
134 {
135 if (offset > m_fileSize || extra > m_fileSize - offset)
136 return std::nullopt;
137 const quint64 pos = offset + extra;
138 if (m_fileSize - pos < sizeof(quint32))
139 return std::nullopt;
140 return qFromBigEndian<quint32>(m_data + pos);
141 }
142 inline QLatin1StringView getLatin1String(quint64 offset) const
143 {
144 if (offset >= m_fileSize)
145 return QLatin1StringView();
146 const char *str = reinterpret_cast<const char *>(m_data + offset);
147 const void *end = std::memchr(str, '\0', m_fileSize - offset);
148 if (!end)
149 return QLatin1StringView();
150 return QLatin1StringView(str, static_cast<const char *>(end));
151 }
152 inline const char *getData(quint64 offset, quint64 length) const
153 {
154 if (offset > m_fileSize || length > m_fileSize - offset)
155 return nullptr;
156 return reinterpret_cast<const char *>(m_data + offset);
157 }
158 // Check base + headerSize + index * stride can not overflow.
159 std::optional<quint64> safeRecordOffset(quint64 base, quint64 headerSize,
160 quint32 index, quint32 stride) const
161 {
162 if (base > m_fileSize || headerSize > m_fileSize - base)
163 return std::nullopt;
164 const quint64 avail = m_fileSize - base - headerSize;
165 // A zero stride would make every index alias the same record: corrupt cache.
166 if (!stride || index >= avail / stride)
167 return std::nullopt;
168 return base + headerSize + quint64(index) * stride;
169 }
170 // A quint32 field of a record of a bounds-checked RecordList. load() has
171 // verified that every record below list.count() lies inside the mapping.
172 inline quint32 recordUint32(const RecordList &list, quint32 index, quint32 fieldOffset) const
173 {
174 // note: fieldOffset is in range: { 0, 4, 8, 12 }
175 const quint64 pos = list.recordOffset(index) + fieldOffset;
176 return qFromBigEndian<quint32>(m_data + pos);
177 }
178 bool load();
179 bool reload();
180
182 uchar *m_data = nullptr;
185 bool m_valid = false;
186
187 // The lists whose offsets are stored in the first 40 bytes of the file,
188 // bounds-checked once by load() so that lookups don't have to.
197};
198
199// Leaves the list empty if the records don't all fit.
200bool QMimeBinaryProvider::RecordList::setRecords(const CacheFile *cacheFile, quint64 firstRecord,
201 quint32 count, quint32 stride)
202{
203 if (!stride || (firstRecord > cacheFile->m_fileSize)) // corrupt cache
204 return false;
205 if (count > (cacheFile->m_fileSize - firstRecord) / stride)
206 return false; // corrupt cache, or more records than can possibly fit
207 m_firstRecord = firstRecord;
208 m_stride = stride;
209 m_count = count;
210 return true;
211}
212
213// Reads the list header pointed to by the offset at posListOffset: the number
214// of records sits at +0 and the records themselves follow at +4.
215bool QMimeBinaryProvider::RecordList::load(const CacheFile *cacheFile, quint64 posListOffset,
216 quint32 stride)
217{
218 const std::optional<quint32> listOffset = cacheFile->getUint32(posListOffset);
219 if (!listOffset)
220 return false; // corrupt cache
221 const std::optional<quint32> n = cacheFile->getUint32(*listOffset);
222 if (!n)
223 return false; // corrupt cache
224 return setRecords(cacheFile, quint64(*listOffset) + 4, *n, stride);
225}
226
227bool QMimeBinaryProvider::RecordList::loadIndirect(const CacheFile *cacheFile,
228 quint64 posListOffset, quint64 firstRecordPos,
229 quint32 stride)
230{
231 const std::optional<quint32> listOffset = cacheFile->getUint32(posListOffset);
232 if (!listOffset)
233 return false; // corrupt cache
234 const std::optional<quint32> n = cacheFile->getUint32(*listOffset);
235 const std::optional<quint32> first = cacheFile->getUint32(*listOffset + firstRecordPos);
236 if (!n || !first)
237 return false; // corrupt cache
238 return setRecords(cacheFile, *first, *n, stride);
239}
240
241static inline void appendIfNew(QStringList &list, const QString &str)
242{
243 if (!list.contains(str))
244 list.push_back(str);
245}
246
247QMimeProviderBase::QMimeProviderBase(QMimeDatabasePrivate *db, const QString &directory)
248 : m_db(db), m_directory(directory)
249{
250}
251
256
261
262bool QMimeProviderBase::isMimeTypeGlobsExcluded(const QString &name) const
263{
264 if (m_overrideProvider) {
265 if (m_overrideProvider->hasGlobDeleteAll(name))
266 return true;
267 return m_overrideProvider->isMimeTypeGlobsExcluded(name);
268 }
269 return false;
270}
271
272QMimeBinaryProvider::QMimeBinaryProvider(QMimeDatabasePrivate *db, const QString &directory)
273 : QMimeProviderBase(db, directory), m_mimetypeListLoaded(false)
274{
276}
277
278QMimeBinaryProvider::CacheFile::CacheFile(const QString &fileName)
280{
281 load();
282}
283
284QMimeBinaryProvider::CacheFile::~CacheFile()
285{
286}
287
288bool QMimeBinaryProvider::CacheFile::load()
289{
290 if (!m_file.open(QIODevice::ReadOnly))
291 return false;
292 const qint64 fileSize = m_file.size();
293 m_fileSize = fileSize > 0 ? fileSize : 0;
294 m_data = m_file.map(0, m_fileSize);
295 if (m_data && m_fileSize >= 4) {
296 const quint16 major = *getUint16(0);
297 const quint16 minor = *getUint16(2);
298 m_valid = (major == 1 && minor >= 1 && minor <= 2)
299 && m_aliases.load(this, PosAliasListOffset, AliasRecordSize)
300 && m_parents.load(this, PosParentListOffset, ParentRecordSize)
301 && m_literals.load(this, PosLiteralListOffset, GlobRecordSize)
302 && m_globs.load(this, PosGlobListOffset, GlobRecordSize)
303 && m_icons.load(this, PosIconsListOffset, IconRecordSize)
304 && m_genericIcons.load(this, PosGenericIconsListOffset, IconRecordSize)
305 && m_suffixTreeRoots.loadIndirect(this, PosReverseSuffixTreeOffset,
306 PosFirstRootOffset, SuffixNodeSize)
307 && m_magicMatches.loadIndirect(this, PosMagicListOffset, PosFirstMatchOffset,
308 MagicMatchSize);
309 }
310 m_mtime = QFileInfo(m_file).lastModified(QTimeZone::UTC);
311 return m_valid;
312}
313
314bool QMimeBinaryProvider::CacheFile::reload()
315{
316 m_valid = false;
317 if (m_file.isOpen()) {
318 m_file.close();
319 }
320 m_data = nullptr;
321 m_fileSize = 0;
322 m_aliases = RecordList();
323 m_parents = RecordList();
324 m_literals = RecordList();
325 m_globs = RecordList();
326 m_suffixTreeRoots = RecordList();
327 m_magicMatches = RecordList();
328 m_icons = RecordList();
329 m_genericIcons = RecordList();
330 return load();
331}
332
333QMimeBinaryProvider::~QMimeBinaryProvider() = default;
334
335bool QMimeBinaryProvider::isValid()
336{
337 return m_cacheFile != nullptr;
338}
339
340bool QMimeBinaryProvider::isInternalDatabase() const
341{
342 return false;
343}
344
345bool QMimeBinaryProvider::checkCacheChanged()
346{
347 QFileInfo fileInfo(m_cacheFile->m_file);
348 if (fileInfo.lastModified(QTimeZone::UTC) > m_cacheFile->m_mtime) {
349 // Deletion can't happen by just running update-mime-database.
350 // But the user could use rm -rf :-)
351 m_cacheFile->reload(); // will mark itself as invalid on failure
352 return true;
353 }
354 return false;
355}
356
357void QMimeBinaryProvider::ensureLoaded()
358{
359 if (!m_cacheFile) {
360 const QString cacheFileName = m_directory + "/mime.cache"_L1;
361 m_cacheFile = std::make_unique<CacheFile>(cacheFileName);
362 m_mimetypeListLoaded = false;
363 m_mimetypeExtra.clear();
364 } else {
365 if (checkCacheChanged()) {
366 m_mimetypeListLoaded = false;
367 m_mimetypeExtra.clear();
368 } else {
369 return; // nothing to do
370 }
371 }
372 if (!m_cacheFile->isValid()) // verify existence and version
373 m_cacheFile.reset();
374}
375
376bool QMimeBinaryProvider::knowsMimeType(const QString &name)
377{
378 if (!m_mimetypeListLoaded)
379 loadMimeTypeList();
380 return m_mimetypeNames.contains(name);
381}
382
383void QMimeBinaryProvider::addFileNameMatches(const QString &fileName, QMimeGlobMatchResult &result)
384{
385 if (fileName.isEmpty())
386 return;
387 Q_ASSERT(m_cacheFile);
388 // Check literals (e.g. "Makefile")
389 quint32 numMatches = matchGlobList(result, m_cacheFile.get(), m_cacheFile->m_literals, fileName);
390 // Check the very common *.txt cases with the suffix tree
391 if (numMatches == 0) {
392 const QString lowerFileName = fileName.toLower();
393 const RecordList &roots = m_cacheFile->m_suffixTreeRoots;
394 if (matchSuffixTree(result, m_cacheFile.get(), roots.count(), roots.firstRecord(),
395 lowerFileName, lowerFileName.size() - 1, false)) {
396 ++numMatches;
397 } else if (matchSuffixTree(result, m_cacheFile.get(), roots.count(), roots.firstRecord(),
398 fileName, fileName.size() - 1, true)) {
399 ++numMatches;
400 }
401 }
402 // Check complex globs (e.g. "callgrind.out[0-9]*" or "README*")
403 if (numMatches == 0)
404 matchGlobList(result, m_cacheFile.get(), m_cacheFile->m_globs, fileName);
405}
406
407quint32 QMimeBinaryProvider::matchGlobList(QMimeGlobMatchResult &result, CacheFile *cacheFile,
408 const RecordList &globs, const QString &fileName)
409{
410 quint32 numMatches = 0;
411 //qDebug() << "Loading" << globs.count() << "globs from" << cacheFile->m_file.fileName();
412 for (quint32 i = 0; i < globs.count(); ++i) {
413 const quint32 globOffset = cacheFile->recordUint32(globs, i, 0);
414 const quint32 mimeTypeOffset = cacheFile->recordUint32(globs, i, 4);
415 const quint32 flagsAndWeight = cacheFile->recordUint32(globs, i, 8);
416 const quint32 weight = flagsAndWeight & 0xff;
417 const bool caseSensitive = flagsAndWeight & 0x100;
418 const Qt::CaseSensitivity qtCaseSensitive = caseSensitive ? Qt::CaseSensitive : Qt::CaseInsensitive;
419 const QLatin1StringView patternL1 = cacheFile->getLatin1String(globOffset);
420 const QLatin1StringView mimeType = cacheFile->getLatin1String(mimeTypeOffset);
421 if (patternL1.isNull() || mimeType.isNull()) // corrupt cache: skip this record
422 continue;
423
424 //qDebug() << pattern << mimeType << weight << caseSensitive;
425 if (isMimeTypeGlobsExcluded(mimeType))
426 continue;
427
428 const QString pattern = patternL1;
429 QMimeGlobPattern glob(pattern, QString() /*unused*/, weight, qtCaseSensitive);
430 if (glob.matchFileName(fileName)) {
431 result.addMatch(mimeType, weight, pattern);
432 ++numMatches;
433 }
434 }
435 return numMatches;
436}
437
438bool QMimeBinaryProvider::matchSuffixTree(QMimeGlobMatchResult &result,
439 QMimeBinaryProvider::CacheFile *cacheFile, quint32 numEntries,
440 quint64 firstOffset, const QString &fileName,
441 qsizetype charPos, bool caseSensitiveCheck)
442{
443 QChar fileChar = fileName[charPos];
444 if (fileChar.isNull())
445 return false;
446 if (numEntries == 0)
447 return false;
448 quint32 min = 0;
449 quint32 max = numEntries - 1;
450 while (min <= max) {
451 const quint32 mid = (min + max) / 2;
452 const std::optional<quint64> off = cacheFile->safeRecordOffset(firstOffset, 0, mid, SuffixNodeSize);
453 if (!off) // corrupt cache
454 break;
455 const std::optional<quint32> chValue = cacheFile->getUint32(*off);
456 if (!chValue) // corrupt cache
457 break;
458 const QChar ch = char16_t(*chValue);
459 if (ch < fileChar) {
460 min = mid + 1;
461 } else if (ch > fileChar) {
462 if (!mid)
463 break;
464 max = mid - 1;
465 } else {
466 --charPos;
467 const std::optional<quint32> numChildrenOpt = cacheFile->getUint32(*off, 4);
468 const std::optional<quint32> childrenOffsetOpt = cacheFile->getUint32(*off, 8);
469 if (!numChildrenOpt || !childrenOffsetOpt) // corrupt cache
470 return false;
471 const quint32 numChildren = *numChildrenOpt;
472 const quint32 childrenOffset = *childrenOffsetOpt;
473 bool success = false;
474 if (charPos > 0)
475 success = matchSuffixTree(result, cacheFile, numChildren, childrenOffset, fileName, charPos, caseSensitiveCheck);
476 if (!success) {
477 for (quint32 i = 0; i < numChildren; ++i) {
478 const std::optional<quint64> childOff =
479 cacheFile->safeRecordOffset(childrenOffset, 0, i, SuffixNodeSize);
480 if (!childOff) // corrupt cache, or numChildren bigger than can possibly fit
481 break;
482 const std::optional<quint32> mchOpt = cacheFile->getUint32(*childOff);
483 if (!mchOpt) // corrupt cache: no later record can be inside the file either
484 break;
485 if (*mchOpt != 0) // not a leaf entry: end of the leaf list
486 break;
487 const std::optional<quint32> mimeTypeOffset = cacheFile->getUint32(*childOff, 4);
488 const std::optional<quint32> flagsAndWeight = cacheFile->getUint32(*childOff, 8);
489 if (!mimeTypeOffset || !flagsAndWeight) // corrupt cache: nor is any later one
490 break;
491 const QLatin1StringView mimeType = cacheFile->getLatin1String(*mimeTypeOffset);
492 if (mimeType.isNull()) // corrupt cache: skip this record
493 continue;
494 if (isMimeTypeGlobsExcluded(mimeType))
495 continue;
496 const quint32 weight = *flagsAndWeight & 0xff;
497 const bool caseSensitive = *flagsAndWeight & 0x100;
498 if (caseSensitiveCheck || !caseSensitive) {
499 result.addMatch(mimeType, weight,
500 u'*' + QStringView{ fileName }.mid(charPos + 1),
501 fileName.size() - charPos - 2);
502 success = true;
503 }
504 }
505 }
506 return success;
507 }
508 }
509 return false;
510}
511
512bool QMimeBinaryProvider::matchMagicRule(QMimeBinaryProvider::CacheFile *cacheFile, quint32 numMatchlets, quint64 firstOffset, const QByteArray &data)
513{
514 const char *dataPtr = data.constData();
515 const qsizetype dataSize = data.size();
516 for (quint32 matchlet = 0; matchlet < numMatchlets; ++matchlet) {
517 const std::optional<quint64> off = cacheFile->safeRecordOffset(firstOffset, 0, matchlet, MagicMatchletSize);
518 if (!off) // corrupt cache, or numMatchlets bigger than can possibly fit
519 break;
520 const std::optional<quint32> rangeStartOpt = cacheFile->getUint32(*off);
521 const std::optional<quint32> rangeLengthOpt = cacheFile->getUint32(*off, 4);
522 //const auto wordSize = cacheFile->getUint32(*off, 8);
523 const std::optional<quint32> valueLengthOpt = cacheFile->getUint32(*off, 12);
524 const std::optional<quint32> valueOffsetOpt = cacheFile->getUint32(*off, 16);
525 const std::optional<quint32> maskOffsetOpt = cacheFile->getUint32(*off, 20);
526 if (!rangeStartOpt || !rangeLengthOpt || !valueLengthOpt || !valueOffsetOpt
527 || !maskOffsetOpt) // corrupt cache: no later matchlet can be inside the file either
528 break;
529 const quint32 rangeStart = *rangeStartOpt;
530 const quint32 rangeLength = *rangeLengthOpt;
531 const quint32 valueLength = *valueLengthOpt;
532 const quint32 valueOffset = *valueOffsetOpt;
533 const quint32 maskOffset = *maskOffsetOpt;
534 const char *value = cacheFile->getData(valueOffset, valueLength);
535 const char *mask = maskOffset ? cacheFile->getData(maskOffset, valueLength) : nullptr;
536 if (!value || (maskOffset && !mask)) // corrupt cache
537 continue;
538
539 if (!QMimeMagicRule::matchSubstring(dataPtr, dataSize, rangeStart, rangeLength, valueLength, value, mask))
540 continue;
541
542 const std::optional<quint32> numChildrenOpt = cacheFile->getUint32(*off, 24);
543 const std::optional<quint32> firstChildOffsetOpt = cacheFile->getUint32(*off, 28);
544 if (!numChildrenOpt || !firstChildOffsetOpt) // corrupt cache: nor is any later matchlet
545 break;
546 const quint32 numChildren = *numChildrenOpt;
547 const quint32 firstChildOffset = *firstChildOffsetOpt;
548 if (numChildren == 0) // No submatch? Then we are done.
549 return true;
550 // Check that one of the submatches matches too
551 if (matchMagicRule(cacheFile, numChildren, firstChildOffset, data))
552 return true;
553 }
554 return false;
555}
556
557void QMimeBinaryProvider::findByMagic(const QByteArray &data, QMimeMagicResult &result)
558{
559 const RecordList &matches = m_cacheFile->m_magicMatches;
560 for (quint32 i = 0; i < matches.count(); ++i) {
561 const quint32 numMatchlets = m_cacheFile->recordUint32(matches, i, 8);
562 const quint32 firstMatchletOffset = m_cacheFile->recordUint32(matches, i, 12);
563 if (matchMagicRule(m_cacheFile.get(), numMatchlets, firstMatchletOffset, data)) {
564 const int accuracy = static_cast<int>(m_cacheFile->recordUint32(matches, i, 0));
565 if (accuracy > result.accuracy) {
566 const quint32 mimeTypeOffset = m_cacheFile->recordUint32(matches, i, 4);
567 const QLatin1StringView candidate = m_cacheFile->getLatin1String(mimeTypeOffset);
568 if (candidate.isNull()) // corrupt cache: skip this record
569 continue;
570 result.accuracy = accuracy;
571 result.candidate = candidate;
572 // Return the first match, mime.cache is sorted
573 return;
574 }
575 }
576 }
577}
578
579void QMimeBinaryProvider::addParents(const QString &mime, QStringList &result)
580{
581 const RecordList &parentList = m_cacheFile->m_parents;
582 const quint32 count = parentList.count();
583 if (!count)
584 return;
585 quint32 begin = 0;
586 quint32 end = count - 1;
587 while (begin <= end) {
588 const quint32 medium = (begin + end) / 2;
589 const quint32 mimeOffset = m_cacheFile->recordUint32(parentList, medium, 0);
590 const QLatin1StringView aMime = m_cacheFile->getLatin1String(mimeOffset);
591 if (aMime.isNull()) // corrupt cache: the search cannot continue
592 break;
593 const int cmp = aMime.compare(mime);
594 if (cmp < 0) {
595 begin = medium + 1;
596 } else if (cmp > 0) {
597 if (!medium)
598 break;
599 end = medium - 1;
600 } else {
601 // The parent list is reached by following an offset stored in the
602 // record, so it has to be bounds-checked here.
603 const quint32 parentsOffset = m_cacheFile->recordUint32(parentList, medium, 4);
604 const std::optional<quint32> numParentsOpt = m_cacheFile->getUint32(parentsOffset);
605 if (!numParentsOpt) // corrupt cache
606 break;
607 const quint32 numParents = *numParentsOpt;
608 for (quint32 i = 0; i < numParents; ++i) {
609 const std::optional<quint64> parentOff =
610 m_cacheFile->safeRecordOffset(parentsOffset, 4, i, 4);
611 if (!parentOff) // past end of file: no later index can be inside it
612 break;
613 const std::optional<quint32> parentOffsetOpt = m_cacheFile->getUint32(*parentOff);
614 if (!parentOffsetOpt) // corrupt cache: no later index can be inside the file either
615 break;
616 const QLatin1StringView parentL1 = m_cacheFile->getLatin1String(*parentOffsetOpt);
617 if (parentL1.isNull()) // corrupt cache: skip this record
618 break;
619 appendIfNew(result, QString(parentL1));
620 }
621 break;
622 }
623 }
624}
625
626QString QMimeBinaryProvider::resolveAlias(const QString &name)
627{
628 const RecordList &aliases = m_cacheFile->m_aliases;
629 quint32 begin = 0;
630 const quint32 count = aliases.count();
631 if (!count)
632 return QString();
633 quint32 end = count - 1;
634 while (begin <= end) {
635 const quint32 medium = (begin + end) / 2;
636 const quint32 aliasOffset = m_cacheFile->recordUint32(aliases, medium, 0);
637 const QLatin1StringView alias = m_cacheFile->getLatin1String(aliasOffset);
638 if (alias.isNull()) // corrupt cache: the search cannot continue
639 break;
640 const int cmp = alias.compare(name);
641 if (cmp < 0) {
642 begin = medium + 1;
643 } else if (cmp > 0) {
644 if (!medium)
645 break;
646 end = medium - 1;
647 } else {
648 const quint32 mimeOffset = m_cacheFile->recordUint32(aliases, medium, 4);
649 // if corrupt cache, returns QLatin1StringView(), which converts to a null QString
650 return m_cacheFile->getLatin1String(mimeOffset);
651 }
652 }
653 return QString();
654}
655
656void QMimeBinaryProvider::addAliases(const QString &name, QStringList &result)
657{
658 const RecordList &aliases = m_cacheFile->m_aliases;
659 for (quint32 pos = 0; pos < aliases.count(); ++pos) {
660 const quint32 mimeOffset = m_cacheFile->recordUint32(aliases, pos, 4);
661 const QLatin1StringView mimeType = m_cacheFile->getLatin1String(mimeOffset);
662 if (mimeType.isNull()) // corrupt cache: skip this record
663 continue;
664
665 if (name == QLatin1StringView(mimeType)) {
666 const quint32 aliasOffset = m_cacheFile->recordUint32(aliases, pos, 0);
667 const QLatin1StringView aliasL1 = m_cacheFile->getLatin1String(aliasOffset);
668 if (aliasL1.isNull()) // corrupt cache: skip this record
669 continue;
670 appendIfNew(result, QString(aliasL1));
671 }
672 }
673}
674
675void QMimeBinaryProvider::loadMimeTypeList()
676{
677 if (!m_mimetypeListLoaded) {
678 m_mimetypeListLoaded = true;
679 m_mimetypeNames.clear();
680 // Unfortunately mime.cache doesn't have a full list of all mimetypes.
681 // So we have to parse the plain-text files called "types".
682 QFile file(m_directory + QStringView(u"/types"));
683 if (file.open(QIODevice::ReadOnly)) {
684 QByteArray line;
685 while (file.readLineInto(&line)) {
686 auto lineView = QByteArrayView(line);
687 if (lineView.endsWith('\n'))
688 lineView.chop(1);
689 m_mimetypeNames.insert(QString::fromLatin1(lineView));
690 }
691 }
692 }
693}
694
695void QMimeBinaryProvider::addAllMimeTypes(QList<QMimeType> &result)
696{
697 loadMimeTypeList();
698 if (result.isEmpty()) {
699 result.reserve(m_mimetypeNames.size());
700 for (const QString &name : std::as_const(m_mimetypeNames))
701 result.append(QMimeType(QMimeTypePrivate(name)));
702 } else {
703 for (const QString &name : std::as_const(m_mimetypeNames))
704 if (std::find_if(result.constBegin(), result.constEnd(), [name](const QMimeType &mime) -> bool { return mime.name() == name; })
705 == result.constEnd())
706 result.append(QMimeType(QMimeTypePrivate(name)));
707 }
708}
709
710QMimeTypePrivate::LocaleHash QMimeBinaryProvider::localeComments(const QString &name)
711{
712 MimeTypeExtraMap::const_iterator it = loadMimeTypeExtra(name);
713 if (it != m_mimetypeExtra.cend())
714 return it->second.localeComments;
715 return {};
716}
717
718bool QMimeBinaryProvider::hasGlobDeleteAll(const QString &name)
719{
720 MimeTypeExtraMap::const_iterator it = loadMimeTypeExtra(name);
721 if (it != m_mimetypeExtra.cend())
722 return it->second.hasGlobDeleteAll;
723 return {};
724}
725
726QStringList QMimeBinaryProvider::globPatterns(const QString &name)
727{
728 MimeTypeExtraMap::const_iterator it = loadMimeTypeExtra(name);
729 if (it != m_mimetypeExtra.cend())
730 return it->second.globPatterns;
731 return {};
732}
733
734QMimeBinaryProvider::MimeTypeExtraMap::const_iterator
735QMimeBinaryProvider::loadMimeTypeExtra(const QString &mimeName)
736{
737#if QT_CONFIG(xmlstreamreader)
738 auto [it, insertionOccurred] = m_mimetypeExtra.try_emplace(mimeName);
739 if (insertionOccurred) {
740 // load comment and globPatterns
741
742 // shared-mime-info since 1.3 lowercases the xml files
743 QFile qfile;
744 const QString mimeFile = m_directory + u'/' + mimeName.toLower() + ".xml"_L1;
745 qfile.setFileName(mimeFile);
746 if (!qfile.open(QFile::ReadOnly)) {
747 const QString fallbackMimeFile = m_directory + u'/' + mimeName + ".xml"_L1; // pre-1.3
748 qfile.setFileName(fallbackMimeFile);
749 if (!qfile.open(QFile::ReadOnly))
750 return it;
751 }
752
753 MimeTypeExtra &extra = it->second;
754 QString mainPattern;
755
756 QXmlStreamReader xml(&qfile);
757 if (xml.readNextStartElement()) {
758 if (xml.name() != "mime-type"_L1) {
759 return m_mimetypeExtra.cend();
760 }
761 const auto name = xml.attributes().value("type"_L1);
762 if (name.isEmpty())
763 return m_mimetypeExtra.cend();
764 if (name.compare(mimeName, Qt::CaseInsensitive))
765 qWarning() << "Got name" << name << "in file" << mimeFile << "expected" << mimeName;
766
767 while (xml.readNextStartElement()) {
768 const auto tag = xml.name();
769 if (tag == "comment"_L1) {
770 QString lang = xml.attributes().value("xml:lang"_L1).toString();
771 const QString text = xml.readElementText();
772 if (lang.isEmpty()) {
773 lang = "default"_L1; // no locale attribute provided, treat it as default.
774 }
775 extra.localeComments.insert(lang, text);
776 continue; // we called readElementText, so we're at the EndElement already.
777 } else if (tag == "glob-deleteall"_L1) { // as written out by shared-mime-info >= 0.70
778 extra.hasGlobDeleteAll = true;
779 } else if (tag == "glob"_L1) { // as written out by shared-mime-info >= 0.70
780 const QString pattern = xml.attributes().value("pattern"_L1).toString();
781 if (mainPattern.isEmpty() && pattern.startsWith(u'*')) {
782 mainPattern = pattern;
783 }
784 appendIfNew(extra.globPatterns, pattern);
785 }
786 xml.skipCurrentElement();
787 }
788 Q_ASSERT(xml.name() == "mime-type"_L1);
789 }
790
791 // Let's assume that shared-mime-info is at least version 0.70
792 // Otherwise we would need 1) a version check, and 2) code for parsing patterns from the globs file.
793 if (!mainPattern.isEmpty() &&
794 (extra.globPatterns.isEmpty() || extra.globPatterns.constFirst() != mainPattern)) {
795 // ensure it's first in the list of patterns
796 extra.globPatterns.removeAll(mainPattern);
797 extra.globPatterns.prepend(mainPattern);
798 }
799 }
800 return it;
801#else
802 Q_UNUSED(mimeName);
803 qWarning("Cannot load mime type since QXmlStreamReader is not available.");
804 return m_mimetypeExtra.cend();
805#endif // feature xmlstreamreader
806}
807
808// Binary search in the icons or generic-icons list
809QLatin1StringView QMimeBinaryProvider::iconForMime(CacheFile *cacheFile, const RecordList &icons,
810 QStringView inputMime)
811{
812 quint32 begin = 0;
813 const quint32 count = icons.count();
814 if (!count)
815 return QLatin1StringView();
816 quint32 end = count - 1;
817 while (begin <= end) {
818 const quint32 medium = (begin + end) / 2;
819 const quint32 mimeOffset = cacheFile->recordUint32(icons, medium, 0);
820 const QLatin1StringView mime = cacheFile->getLatin1String(mimeOffset);
821 if (mime.isNull()) // corrupt cache: the search cannot continue
822 break;
823 const int cmp = mime.compare(inputMime);
824 if (cmp < 0) {
825 begin = medium + 1;
826 } else if (cmp > 0) {
827 if (!medium)
828 break;
829 end = medium - 1;
830 } else {
831 const quint32 iconOffset = cacheFile->recordUint32(icons, medium, 4);
832 // if corrupt cache, returns QLatin1StringView()
833 return cacheFile->getLatin1String(iconOffset);
834 }
835 }
836 return QLatin1StringView();
837}
838
839QString QMimeBinaryProvider::icon(const QString &name)
840{
841 return iconForMime(m_cacheFile.get(), m_cacheFile->m_icons, name);
842}
843
844QString QMimeBinaryProvider::genericIcon(const QString &name)
845{
846 return iconForMime(m_cacheFile.get(), m_cacheFile->m_genericIcons, name);
847}
848
849////
850
851#if QT_CONFIG(mimetype_database)
852static QString internalMimeFileName()
853{
854 return QStringLiteral("<internal MIME data>");
855}
856
857QMimeXMLProvider::QMimeXMLProvider(QMimeDatabasePrivate *db, InternalDatabaseEnum)
858 : QMimeProviderBase(db, internalMimeFileName())
859{
860 static_assert(sizeof(mimetype_database), "Bundled MIME database is empty");
861 static_assert(sizeof(mimetype_database) <= MimeTypeDatabaseOriginalSize,
862 "Compressed MIME database is larger than the original size");
863 static_assert(MimeTypeDatabaseOriginalSize <= 16*1024*1024,
864 "Bundled MIME database is too big");
865 const char *data = reinterpret_cast<const char *>(mimetype_database);
866 qsizetype size = MimeTypeDatabaseOriginalSize;
867
868#ifdef MIME_DATABASE_IS_ZSTD
869 // uncompress with libzstd
870 std::unique_ptr<char []> uncompressed(new char[size]);
871 size = ZSTD_decompress(uncompressed.get(), size, mimetype_database, sizeof(mimetype_database));
872 Q_ASSERT(!ZSTD_isError(size));
873 data = uncompressed.get();
874#elif defined(MIME_DATABASE_IS_GZIP)
875 std::unique_ptr<char []> uncompressed(new char[size]);
876 z_stream zs = {};
877 zs.next_in = const_cast<Bytef *>(mimetype_database);
878 zs.avail_in = sizeof(mimetype_database);
879 zs.next_out = reinterpret_cast<Bytef *>(uncompressed.get());
880 zs.avail_out = size;
881
882 int res = inflateInit2(&zs, MAX_WBITS | 32);
883 Q_ASSERT(res == Z_OK);
884 res = inflate(&zs, Z_FINISH);
885 Q_ASSERT(res == Z_STREAM_END);
886 res = inflateEnd(&zs);
887 Q_ASSERT(res == Z_OK);
888
889 data = uncompressed.get();
890 size = zs.total_out;
891#endif
892
893 load(data, size);
894}
895#else // !QT_CONFIG(mimetype_database)
896// never called in release mode, but some debug builds may need
897// this to be defined.
899 : QMimeProviderBase(db, QString())
900{
901 Q_UNREACHABLE();
902}
903#endif // QT_CONFIG(mimetype_database)
904
905QMimeXMLProvider::QMimeXMLProvider(QMimeDatabasePrivate *db, const QString &directory)
906 : QMimeProviderBase(db, directory)
907{
909}
910
911QMimeXMLProvider::~QMimeXMLProvider()
912{
913}
914
915bool QMimeXMLProvider::isValid()
916{
917 // If you change this method, adjust the logic in QMimeDatabasePrivate::loadProviders,
918 // which assumes isValid==false is only possible in QMimeBinaryProvider.
919 return true;
920}
921
922bool QMimeXMLProvider::isInternalDatabase() const
923{
924#if QT_CONFIG(mimetype_database)
925 return m_directory == internalMimeFileName();
926#else
927 return false;
928#endif
929}
930
931bool QMimeXMLProvider::knowsMimeType(const QString &name)
932{
933 return m_nameMimeTypeMap.contains(name);
934}
935
936void QMimeXMLProvider::addFileNameMatches(const QString &fileName, QMimeGlobMatchResult &result)
937{
938 auto filterFunc = [this](const QString &name) { return !isMimeTypeGlobsExcluded(name); };
939 m_mimeTypeGlobs.matchingGlobs(fileName, result, filterFunc);
940}
941
942void QMimeXMLProvider::findByMagic(const QByteArray &data, QMimeMagicResult &result)
943{
944 for (const QMimeMagicRuleMatcher &matcher : std::as_const(m_magicMatchers)) {
945 if (matcher.matches(data)) {
946 const int priority = matcher.priority();
947 if (priority < result.accuracy)
948 continue;
949 if (priority == result.accuracy) {
950 if (m_db->inherits(result.candidate, matcher.mimetype()))
951 continue;
952
953 if (!m_db->inherits(matcher.mimetype(), result.candidate)) {
954 // Two or more magic rules matching, both with the same priority but not
955 // connected with one another should not happen:
956 qWarning("QMimeXMLProvider: MimeType is ambiguous between %ls and %ls",
957 qUtf16Printable(result.candidate),
958 qUtf16Printable(matcher.mimetype()));
959 continue;
960 }
961 }
962
963 result.accuracy = priority;
964 result.candidate = matcher.mimetype();
965 }
966 }
967}
968
969void QMimeXMLProvider::ensureLoaded()
970{
971 QStringList allFiles;
972 const QString packageDir = m_directory + QStringView(u"/packages");
973 for (const auto &entry : QDirListing(packageDir, QDirListing::IteratorFlag::FilesOnly
974 | QDirListing::IteratorFlag::ResolveSymlinks))
975 allFiles.emplace_back(packageDir + u'/' + entry.fileName());
976
977 if (m_allFiles == allFiles)
978 return;
979 m_allFiles = allFiles;
980
981 m_nameMimeTypeMap.clear();
982 m_aliases.clear();
983 m_parents.clear();
984 m_mimeTypeGlobs.clear();
985 m_magicMatchers.clear();
986
987 //qDebug() << "Loading" << m_allFiles;
988
989 for (const QString &file : std::as_const(allFiles))
990 load(file);
991}
992
993QMimeTypePrivate::LocaleHash QMimeXMLProvider::localeComments(const QString &name)
994{
995 return m_nameMimeTypeMap.value(name).localeComments;
996}
997
998bool QMimeXMLProvider::hasGlobDeleteAll(const QString &name)
999{
1000 return m_nameMimeTypeMap.value(name).hasGlobDeleteAll;
1001}
1002
1003QStringList QMimeXMLProvider::globPatterns(const QString &name)
1004{
1005 return m_nameMimeTypeMap.value(name).globPatterns;
1006}
1007
1008QString QMimeXMLProvider::icon(const QString &name)
1009{
1010 return m_nameMimeTypeMap.value(name).iconName;
1011}
1012
1013QString QMimeXMLProvider::genericIcon(const QString &name)
1014{
1015 return m_nameMimeTypeMap.value(name).genericIconName;
1016}
1017
1018void QMimeXMLProvider::load(const QString &fileName)
1019{
1020 QString errorMessage;
1021 if (!load(fileName, &errorMessage))
1022 qWarning("QMimeDatabase: Error loading %ls\n%ls", qUtf16Printable(fileName), qUtf16Printable(errorMessage));
1023}
1024
1025bool QMimeXMLProvider::load(const QString &fileName, QString *errorMessage)
1026{
1027 QFile file(fileName);
1028 if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
1029 if (errorMessage)
1030 *errorMessage = "Cannot open "_L1 + fileName + ": "_L1 + file.errorString();
1031 return false;
1032 }
1033
1034 if (errorMessage)
1035 errorMessage->clear();
1036
1037 QMimeTypeParser parser(*this);
1038 return parser.parse(&file, fileName, errorMessage);
1039}
1040
1041#if QT_CONFIG(mimetype_database)
1042void QMimeXMLProvider::load(const char *data, qsizetype len)
1043{
1044 QBuffer buffer;
1045 buffer.setData(QByteArray::fromRawData(data, len));
1046 buffer.open(QIODevice::ReadOnly);
1047 QString errorMessage;
1048 QMimeTypeParser parser(*this);
1049 if (!parser.parse(&buffer, internalMimeFileName(), &errorMessage))
1050 qWarning("QMimeDatabase: Error loading internal MIME data\n%s", qPrintable(errorMessage));
1051}
1052#endif
1053
1054void QMimeXMLProvider::addGlobPattern(const QMimeGlobPattern &glob)
1055{
1056 m_mimeTypeGlobs.addGlob(glob);
1057}
1058
1059void QMimeXMLProvider::addMimeType(const QMimeTypeXMLData &mt)
1060{
1061 m_nameMimeTypeMap.insert(mt.name, mt);
1062}
1063
1064void QMimeXMLProvider::addParents(const QString &mime, QStringList &result)
1065{
1066 const QStringList parents = m_parents.value(mime);
1067 for (const QString &parent : parents) {
1068 if (!result.contains(parent))
1069 result.append(parent);
1070 }
1071}
1072
1073void QMimeXMLProvider::addParent(const QString &child, const QString &parent)
1074{
1075 m_parents[child].append(parent);
1076}
1077
1078void QMimeXMLProvider::addAliases(const QString &name, QStringList &result)
1079{
1080 // Iterate through the whole hash. This method is rarely used.
1081 for (const auto &[alias, mimeName] : std::as_const(m_aliases).asKeyValueRange()) {
1082 if (mimeName == name)
1083 appendIfNew(result, alias);
1084 }
1085}
1086
1087QString QMimeXMLProvider::resolveAlias(const QString &name)
1088{
1089 return m_aliases.value(name);
1090}
1091
1092void QMimeXMLProvider::addAlias(const QString &alias, const QString &name)
1093{
1094 m_aliases.insert(alias, name);
1095}
1096
1097void QMimeXMLProvider::addAllMimeTypes(QList<QMimeType> &result)
1098{
1099 if (result.isEmpty()) { // fast path
1100 for (auto it = m_nameMimeTypeMap.constBegin(), end = m_nameMimeTypeMap.constEnd();
1101 it != end; ++it) {
1102 result.append(QMimeType(QMimeTypePrivate(it.value().name)));
1103 }
1104 } else {
1105 for (auto it = m_nameMimeTypeMap.constBegin(), end = m_nameMimeTypeMap.constEnd() ; it != end ; ++it) {
1106 const QString newMime = it.key();
1107 if (std::find_if(result.constBegin(), result.constEnd(), [newMime](const QMimeType &mime) -> bool { return mime.name() == newMime; })
1108 == result.constEnd())
1109 result.append(QMimeType(QMimeTypePrivate(it.value().name)));
1110 }
1111 }
1112}
1113
1114void QMimeXMLProvider::addMagicMatcher(const QMimeMagicRuleMatcher &matcher)
1115{
1116 m_magicMatchers.append(matcher);
1117}
1118
1119QT_END_NAMESPACE
void addGlob(const QMimeGlobPattern &glob)
quint64 recordOffset(quint32 index) const
bool loadIndirect(const CacheFile *cacheFile, quint64 posListOffset, quint64 firstRecordPos, quint32 stride)
bool load(const CacheFile *cacheFile, quint64 posListOffset, quint32 stride)
void addFileNameMatches(const QString &fileName, QMimeGlobMatchResult &result) override
QString resolveAlias(const QString &name) override
void findByMagic(const QByteArray &data, QMimeMagicResult &result) override
bool knowsMimeType(const QString &name) override
QString icon(const QString &name) override
bool hasGlobDeleteAll(const QString &name) override
void ensureLoaded() override
bool isValid() override
void addAliases(const QString &name, QStringList &result) override
virtual ~QMimeBinaryProvider()
void addAllMimeTypes(QList< QMimeType > &result) override
void addParents(const QString &mime, QStringList &result) override
QMimeBinaryProvider(QMimeDatabasePrivate *db, const QString &directory)
QStringList globPatterns(const QString &name) override
QString genericIcon(const QString &name) override
bool isInternalDatabase() const override
QMimeTypePrivate::LocaleHash localeComments(const QString &name) override
The QMimeGlobPattern class contains the glob pattern for file names for MIME type matching.
bool isMimeTypeGlobsExcluded(const QString &name) const
QMimeProviderBase * m_overrideProvider
QMimeProviderBase * overrideProvider() const
void setOverrideProvider(QMimeProviderBase *provider)
QMimeDatabasePrivate * m_db
\inmodule QtCore
QMimeTypeParser(QMimeXMLProvider &provider)
void addFileNameMatches(const QString &fileName, QMimeGlobMatchResult &result) override
void addGlobPattern(const QMimeGlobPattern &glob)
void addAliases(const QString &name, QStringList &result) override
void addAlias(const QString &alias, const QString &name)
QMimeTypePrivate::LocaleHash localeComments(const QString &name) override
QStringList globPatterns(const QString &name) override
bool load(const QString &fileName, QString *errorMessage)
QMimeXMLProvider(QMimeDatabasePrivate *db, const QString &directory)
void ensureLoaded() override
bool knowsMimeType(const QString &name) override
bool isValid() override
bool isInternalDatabase() const override
QString resolveAlias(const QString &name) override
void addMimeType(const QMimeTypeXMLData &mt)
void findByMagic(const QByteArray &data, QMimeMagicResult &result) override
QString icon(const QString &name) override
void addParents(const QString &mime, QStringList &result) override
void addAllMimeTypes(QList< QMimeType > &result) override
QMimeXMLProvider(QMimeDatabasePrivate *db, InternalDatabaseEnum)
void addMagicMatcher(const QMimeMagicRuleMatcher &matcher)
bool hasGlobDeleteAll(const QString &name) override
void addParent(const QString &child, const QString &parent)
QString genericIcon(const QString &name) override
@ PosMagicListOffset
@ PosGenericIconsListOffset
@ PosIconsListOffset
@ PosParentListOffset
@ PosLiteralListOffset
@ PosAliasListOffset
@ PosGlobListOffset
@ PosReverseSuffixTreeOffset
@ AliasRecordSize
@ SuffixNodeSize
@ ParentRecordSize
@ IconRecordSize
@ GlobRecordSize
@ MagicMatchletSize
@ MagicMatchSize
@ PosFirstRootOffset
@ PosFirstMatchOffset
static void appendIfNew(QStringList &list, const QString &str)
std::optional< quint32 > getUint32(quint64 offset, quint64 extra=0) const
std::optional< quint16 > getUint16(quint64 offset) const
quint32 recordUint32(const RecordList &list, quint32 index, quint32 fieldOffset) const
QLatin1StringView getLatin1String(quint64 offset) const
CacheFile(const QString &fileName)
std::optional< quint64 > safeRecordOffset(quint64 base, quint64 headerSize, quint32 index, quint32 stride) const
const char * getData(quint64 offset, quint64 length) const