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 The depth limit protects the stack, but it does not limit the time. In a
84 corrupt mime.cache, the child offset of a matchlet can point back to the
85 list that contains it. For example, take a list of 2 matchlets where the
86 children of each one are that same list. Each path still stops at
87 MaxRecursionDepth, but there are 2^depth paths, and a file of a few
88 hundred bytes is enough to describe them.
89
90 So one findByMagic() or checkMagicRules() call also has a budget: the
91 number of input data bytes it may scan, summed over all matchlets it
92 checks. Each checked matchlet costs 1 + min(rangeLength, data.size())
93 bytes: the input bytes it may compare, plus 1 so that no matchlet is free.
94 When the budget is used up, the lookup stops and reports no match.
95
96 Checking every matchlet in the shared-mime-info database costs about 76k
97 bytes, so this limit is far above what a valid mime.cache needs.
98 */
99static constexpr qint64 MagicMatchBudget = 1 << 21;
100
101/*
102 A corrupt mime.cache can hold any number of globs that need a regular
103 expression, and each compiled expression takes memory for as long as the
104 file is loaded.
105 */
107
108/*
109 A list of fixed-size records in the mime.cache file, whose bounds have been
110 checked once: for any index below count, the whole record at
111 recordOffset(index) is inside the file, so walking the list needs no further
112 checking - read the fields with CacheFile::recordUint32(). An empty list
113 means either a mime.cache is empty or corrupted.
114
115 Anything reached by following an offset stored inside a record is still
116 untrusted and has to be checked where it is used.
117 */
118class QMimeBinaryProvider::RecordList
119{
120public:
121 // The lists whose offsets live in the first 40 bytes of the file are read
122 // by these two functions, once, when the cache file is loaded.
123 bool load(const CacheFile *cacheFile, quint64 posListOffset, quint32 stride);
124 bool loadIndirect(const CacheFile *cacheFile, quint64 posListOffset,
125 quint64 firstRecordPos, quint32 stride);
126
127 quint32 count() const { return m_count; } // N_ALIASES/N_ENTRIES/N_PARENTS/etc => CARD32 type
128 quint32 stride() const { return m_stride; }
129 quint64 firstRecord() const { return m_firstRecord; }
130 quint64 recordOffset(quint32 index) const
131 {
132 Q_ASSERT(index < m_count);
133 return m_firstRecord + quint64(index) * m_stride;
134 }
135
136private:
137 // The state is private, and setRecords() is the only thing that writes it,
138 // so a RecordList that is not empty has been bounds-checked.
139 bool setRecords(const CacheFile *cacheFile, quint64 firstRecord,
140 quint32 count, quint32 stride);
141
142 quint64 m_firstRecord = 0;
143 quint32 m_stride = 0;
144 quint32 m_count = 0;
145};
146
147struct QMimeBinaryProvider::CacheFile
148{
149 CacheFile(const QString &fileName);
151
152 bool isValid() const { return m_valid; }
153 inline std::optional<quint16> getUint16(quint64 offset) const
154 {
155 if (offset > m_fileSize || m_fileSize - offset < sizeof(quint16))
156 return std::nullopt;
157 return qFromBigEndian<quint16>(m_data + offset);
158 }
159 inline std::optional<quint32> getUint32(quint64 offset, quint64 extra = 0) const
160 {
161 if (offset > m_fileSize || extra > m_fileSize - offset)
162 return std::nullopt;
163 const quint64 pos = offset + extra;
164 if (m_fileSize - pos < sizeof(quint32))
165 return std::nullopt;
166 return qFromBigEndian<quint32>(m_data + pos);
167 }
168 inline QLatin1StringView getLatin1String(quint64 offset) const
169 {
170 if (offset >= m_fileSize)
171 return QLatin1StringView();
172 const char *str = reinterpret_cast<const char *>(m_data + offset);
173 const void *end = std::memchr(str, '\0', m_fileSize - offset);
174 if (!end)
175 return QLatin1StringView();
176 return QLatin1StringView(str, static_cast<const char *>(end));
177 }
178 inline const char *getData(quint64 offset, quint64 length) const
179 {
180 if (offset > m_fileSize || length > m_fileSize - offset)
181 return nullptr;
182 return reinterpret_cast<const char *>(m_data + offset);
183 }
184 // Check base + headerSize + index * stride can not overflow.
185 std::optional<quint64> safeRecordOffset(quint64 base, quint64 headerSize,
186 quint32 index, quint32 stride) const
187 {
188 if (base > m_fileSize || headerSize > m_fileSize - base)
189 return std::nullopt;
190 const quint64 avail = m_fileSize - base - headerSize;
191 // A zero stride would make every index alias the same record: corrupt cache.
192 if (!stride || index >= avail / stride)
193 return std::nullopt;
194 return base + headerSize + quint64(index) * stride;
195 }
196 // A quint32 field of a record of a bounds-checked RecordList. load() has
197 // verified that every record below list.count() lies inside the mapping.
198 inline quint32 recordUint32(const RecordList &list, quint32 index, quint32 fieldOffset) const
199 {
200 // note: fieldOffset is in range: { 0, 4, 8, 12 }
201 const quint64 pos = list.recordOffset(index) + fieldOffset;
202 return qFromBigEndian<quint32>(m_data + pos);
203 }
204 bool load();
205 bool reload();
206 bool matchRegularExpressionGlob(quint32 globOffset, QLatin1StringView pattern,
207 const QString &fileName);
208
210 uchar *m_data = nullptr;
213 bool m_valid = false;
214
215 // The lists whose offsets are stored in the first 40 bytes of the file,
216 // bounds-checked once by load() so that lookups don't have to.
225
226#if QT_CONFIG(regularexpression)
228#endif
229};
230
231// Leaves the list empty if the records don't all fit.
232bool QMimeBinaryProvider::RecordList::setRecords(const CacheFile *cacheFile, quint64 firstRecord,
233 quint32 count, quint32 stride)
234{
235 if (!stride || (firstRecord > cacheFile->m_fileSize)) // corrupt cache
236 return false;
237 if (count > (cacheFile->m_fileSize - firstRecord) / stride)
238 return false; // corrupt cache, or more records than can possibly fit
239 m_firstRecord = firstRecord;
240 m_stride = stride;
241 m_count = count;
242 return true;
243}
244
245// Reads the list header pointed to by the offset at posListOffset: the number
246// of records sits at +0 and the records themselves follow at +4.
247bool QMimeBinaryProvider::RecordList::load(const CacheFile *cacheFile, quint64 posListOffset,
248 quint32 stride)
249{
250 const std::optional<quint32> listOffset = cacheFile->getUint32(posListOffset);
251 if (!listOffset)
252 return false; // corrupt cache
253 const std::optional<quint32> n = cacheFile->getUint32(*listOffset);
254 if (!n)
255 return false; // corrupt cache
256 return setRecords(cacheFile, quint64(*listOffset) + 4, *n, stride);
257}
258
259bool QMimeBinaryProvider::RecordList::loadIndirect(const CacheFile *cacheFile,
260 quint64 posListOffset, quint64 firstRecordPos,
261 quint32 stride)
262{
263 const std::optional<quint32> listOffset = cacheFile->getUint32(posListOffset);
264 if (!listOffset)
265 return false; // corrupt cache
266 const std::optional<quint32> n = cacheFile->getUint32(*listOffset);
267 const std::optional<quint32> first = cacheFile->getUint32(*listOffset + firstRecordPos);
268 if (!n || !first)
269 return false; // corrupt cache
270 return setRecords(cacheFile, *first, *n, stride);
271}
272
273static inline void appendIfNew(QStringList &list, const QString &str)
274{
275 if (!list.contains(str))
276 list.push_back(str);
277}
278
279QMimeProviderBase::QMimeProviderBase(QMimeDatabasePrivate *db, const QString &directory)
280 : m_db(db), m_directory(directory)
281{
282}
283
288
293
294bool QMimeProviderBase::isMimeTypeGlobsExcluded(const QString &name) const
295{
296 if (m_overrideProvider) {
297 if (m_overrideProvider->hasGlobDeleteAll(name))
298 return true;
299 return m_overrideProvider->isMimeTypeGlobsExcluded(name);
300 }
301 return false;
302}
303
304QMimeBinaryProvider::QMimeBinaryProvider(QMimeDatabasePrivate *db, const QString &directory)
305 : QMimeProviderBase(db, directory), m_mimetypeListLoaded(false)
306{
308}
309
310QMimeBinaryProvider::CacheFile::CacheFile(const QString &fileName)
312{
313 load();
314}
315
316QMimeBinaryProvider::CacheFile::~CacheFile()
317{
318}
319
320bool QMimeBinaryProvider::CacheFile::load()
321{
322 if (!m_file.open(QIODevice::ReadOnly))
323 return false;
324 const qint64 fileSize = m_file.size();
325 m_fileSize = fileSize > 0 ? fileSize : 0;
326 m_data = m_file.map(0, m_fileSize);
327 if (m_data && m_fileSize >= 4) {
328 const quint16 major = *getUint16(0);
329 const quint16 minor = *getUint16(2);
330 m_valid = (major == 1 && minor >= 1 && minor <= 2)
331 && m_aliases.load(this, PosAliasListOffset, AliasRecordSize)
332 && m_parents.load(this, PosParentListOffset, ParentRecordSize)
333 && m_literals.load(this, PosLiteralListOffset, GlobRecordSize)
334 && m_globs.load(this, PosGlobListOffset, GlobRecordSize)
335 && m_icons.load(this, PosIconsListOffset, IconRecordSize)
336 && m_genericIcons.load(this, PosGenericIconsListOffset, IconRecordSize)
337 && m_suffixTreeRoots.loadIndirect(this, PosReverseSuffixTreeOffset,
338 PosFirstRootOffset, SuffixNodeSize)
339 && m_magicMatches.loadIndirect(this, PosMagicListOffset, PosFirstMatchOffset,
340 MagicMatchSize);
341 }
342 m_mtime = QFileInfo(m_file).lastModified(QTimeZone::UTC);
343 return m_valid;
344}
345
346bool QMimeBinaryProvider::CacheFile::reload()
347{
348 m_valid = false;
349 if (m_file.isOpen()) {
350 m_file.close();
351 }
352 m_data = nullptr;
353 m_fileSize = 0;
354 m_aliases = RecordList();
355 m_parents = RecordList();
356 m_literals = RecordList();
357 m_globs = RecordList();
358 m_suffixTreeRoots = RecordList();
359 m_magicMatches = RecordList();
360 m_icons = RecordList();
361 m_genericIcons = RecordList();
362#if QT_CONFIG(regularexpression)
363 m_regularExpressionsByGlobOffset.clear();
364#endif
365 return load();
366}
367
368bool QMimeBinaryProvider::CacheFile::matchRegularExpressionGlob(quint32 globOffset,
369 QLatin1StringView pattern,
370 const QString &fileName)
371{
372#if QT_CONFIG(regularexpression)
373 const auto cached = m_regularExpressionsByGlobOffset.constFind(globOffset);
374 if (cached != m_regularExpressionsByGlobOffset.cend())
375 return cached->match(fileName).hasMatch();
376 const QRegularExpression regExp = QRegularExpression::fromWildcard(QString(pattern));
377 if (m_regularExpressionsByGlobOffset.size() < MaxCachedGlobRegularExpressions)
378 m_regularExpressionsByGlobOffset.insert(globOffset, regExp);
379 return regExp.match(fileName).hasMatch();
380#else
381 Q_UNUSED(globOffset);
382 Q_UNUSED(pattern);
383 Q_UNUSED(fileName);
384 return false;
385#endif
386}
387
388QMimeBinaryProvider::~QMimeBinaryProvider() = default;
389
390bool QMimeBinaryProvider::isValid()
391{
392 return m_cacheFile != nullptr;
393}
394
395bool QMimeBinaryProvider::isInternalDatabase() const
396{
397 return false;
398}
399
400bool QMimeBinaryProvider::checkCacheChanged()
401{
402 QFileInfo fileInfo(m_cacheFile->m_file);
403 if (fileInfo.lastModified(QTimeZone::UTC) > m_cacheFile->m_mtime) {
404 // Deletion can't happen by just running update-mime-database.
405 // But the user could use rm -rf :-)
406 m_cacheFile->reload(); // will mark itself as invalid on failure
407 return true;
408 }
409 return false;
410}
411
412void QMimeBinaryProvider::ensureLoaded()
413{
414 if (!m_cacheFile) {
415 const QString cacheFileName = m_directory + "/mime.cache"_L1;
416 m_cacheFile = std::make_unique<CacheFile>(cacheFileName);
417 m_mimetypeListLoaded = false;
418 m_mimetypeExtra.clear();
419 } else {
420 if (checkCacheChanged()) {
421 m_mimetypeListLoaded = false;
422 m_mimetypeExtra.clear();
423 } else {
424 return; // nothing to do
425 }
426 }
427 if (!m_cacheFile->isValid()) // verify existence and version
428 m_cacheFile.reset();
429}
430
431bool QMimeBinaryProvider::knowsMimeType(const QString &name)
432{
433 if (!m_mimetypeListLoaded)
434 loadMimeTypeList();
435 return m_mimetypeNames.contains(name);
436}
437
438void QMimeBinaryProvider::addFileNameMatches(const QString &fileName, QMimeGlobMatchResult &result)
439{
440 if (fileName.isEmpty())
441 return;
442 Q_ASSERT(m_cacheFile);
443 // Check literals (e.g. "Makefile")
444 quint32 numMatches = matchGlobList(result, m_cacheFile.get(), m_cacheFile->m_literals,
445 GlobListType::Literals, fileName);
446 // Check the very common *.txt cases with the suffix tree
447 if (numMatches == 0) {
448 const QString lowerFileName = fileName.toLower();
449 const RecordList &roots = m_cacheFile->m_suffixTreeRoots;
450 if (matchSuffixTree(result, m_cacheFile.get(), roots.count(), roots.firstRecord(),
451 lowerFileName, lowerFileName.size() - 1, false)) {
452 ++numMatches;
453 } else if (matchSuffixTree(result, m_cacheFile.get(), roots.count(), roots.firstRecord(),
454 fileName, fileName.size() - 1, true)) {
455 ++numMatches;
456 }
457 }
458 // Check complex globs (e.g. "callgrind.out[0-9]*" or "README*")
459 if (numMatches == 0)
460 matchGlobList(result, m_cacheFile.get(), m_cacheFile->m_globs, GlobListType::Globs,
461 fileName);
462}
463
464quint32 QMimeBinaryProvider::matchGlobList(QMimeGlobMatchResult &result, CacheFile *cacheFile,
465 const RecordList &globs, GlobListType listType,
466 const QString &fileName)
467{
468 quint32 numMatches = 0;
469 //qDebug() << "Loading" << globs.count() << "globs from" << cacheFile->m_file.fileName();
470 for (quint32 i = 0; i < globs.count(); ++i) {
471 const quint32 globOffset = cacheFile->recordUint32(globs, i, 0);
472 const quint32 mimeTypeOffset = cacheFile->recordUint32(globs, i, 4);
473 const quint32 flagsAndWeight = cacheFile->recordUint32(globs, i, 8);
474 const quint32 weight = flagsAndWeight & 0xff;
475 const bool caseSensitive = flagsAndWeight & 0x100;
476 const Qt::CaseSensitivity qtCaseSensitive = caseSensitive ? Qt::CaseSensitive : Qt::CaseInsensitive;
477 const QLatin1StringView patternL1 = cacheFile->getLatin1String(globOffset);
478 const QLatin1StringView mimeTypeL1 = cacheFile->getLatin1String(mimeTypeOffset);
479 if (patternL1.isNull() || mimeTypeL1.isNull()) // corrupt cache: skip this record
480 continue;
481
482 bool matches;
483 if (listType == GlobListType::Literals) {
484 matches = fileName.compare(patternL1, qtCaseSensitive) == 0;
485 } else {
486 const auto patternType = QMimeGlobPattern::detectPatternType(patternL1);
487 matches = patternType == QMimeGlobPattern::OtherPattern
488 ? cacheFile->matchRegularExpressionGlob(globOffset, patternL1, fileName)
489 : QMimeGlobPattern::matchWithoutRegularExpression(patternType, patternL1,
490 fileName, qtCaseSensitive);
491 }
492 if (!matches)
493 continue;
494
495 const QString mimeType = mimeTypeL1;
496 if (isMimeTypeGlobsExcluded(mimeType))
497 continue;
498
499 result.addMatch(mimeType, weight, patternL1);
500 ++numMatches;
501 }
502 return numMatches;
503}
504
505bool QMimeBinaryProvider::matchSuffixTree(QMimeGlobMatchResult &result,
506 QMimeBinaryProvider::CacheFile *cacheFile, quint32 numEntries,
507 quint64 firstOffset, const QString &fileName,
508 qsizetype charPos, bool caseSensitiveCheck)
509{
510 QChar fileChar = fileName[charPos];
511 if (fileChar.isNull())
512 return false;
513 if (numEntries == 0)
514 return false;
515 quint32 min = 0;
516 quint32 max = numEntries - 1;
517 while (min <= max) {
518 const quint32 mid = (min + max) / 2;
519 const std::optional<quint64> off = cacheFile->safeRecordOffset(firstOffset, 0, mid, SuffixNodeSize);
520 if (!off) // corrupt cache
521 break;
522 const std::optional<quint32> chValue = cacheFile->getUint32(*off);
523 if (!chValue) // corrupt cache
524 break;
525 const QChar ch = char16_t(*chValue);
526 if (ch < fileChar) {
527 min = mid + 1;
528 } else if (ch > fileChar) {
529 if (!mid)
530 break;
531 max = mid - 1;
532 } else {
533 --charPos;
534 const std::optional<quint32> numChildrenOpt = cacheFile->getUint32(*off, 4);
535 const std::optional<quint32> childrenOffsetOpt = cacheFile->getUint32(*off, 8);
536 if (!numChildrenOpt || !childrenOffsetOpt) // corrupt cache
537 return false;
538 const quint32 numChildren = *numChildrenOpt;
539 const quint32 childrenOffset = *childrenOffsetOpt;
540 bool success = false;
541 if (charPos >= 0)
542 success = matchSuffixTree(result, cacheFile, numChildren, childrenOffset, fileName, charPos, caseSensitiveCheck);
543 if (!success) {
544 for (quint32 i = 0; i < numChildren; ++i) {
545 const std::optional<quint64> childOff =
546 cacheFile->safeRecordOffset(childrenOffset, 0, i, SuffixNodeSize);
547 if (!childOff) // corrupt cache, or numChildren bigger than can possibly fit
548 break;
549 const std::optional<quint32> mchOpt = cacheFile->getUint32(*childOff);
550 if (!mchOpt) // corrupt cache: no later record can be inside the file either
551 break;
552 if (*mchOpt != 0) // not a leaf entry: end of the leaf list
553 break;
554 const std::optional<quint32> mimeTypeOffset = cacheFile->getUint32(*childOff, 4);
555 const std::optional<quint32> flagsAndWeight = cacheFile->getUint32(*childOff, 8);
556 if (!mimeTypeOffset || !flagsAndWeight) // corrupt cache: nor is any later one
557 break;
558 const QLatin1StringView mimeType = cacheFile->getLatin1String(*mimeTypeOffset);
559 if (mimeType.isNull()) // corrupt cache: skip this record
560 continue;
561 if (isMimeTypeGlobsExcluded(mimeType))
562 continue;
563 const quint32 weight = *flagsAndWeight & 0xff;
564 const bool caseSensitive = *flagsAndWeight & 0x100;
565 if (caseSensitiveCheck || !caseSensitive) {
566 result.addMatch(mimeType, weight,
567 u'*' + QStringView{ fileName }.mid(charPos + 1),
568 fileName.size() - charPos - 2);
569 success = true;
570 }
571 }
572 }
573 return success;
574 }
575 }
576 return false;
577}
578
579bool QMimeBinaryProvider::matchMagicRule(QMimeBinaryProvider::CacheFile *cacheFile,
580 quint32 numMatchlets, quint64 firstOffset,
581 const QByteArray &data, int depth, qint64 &budget)
582{
583 // The child offsets come straight from the cache file, so a corrupt (or
584 // hostile) mime.cache can describe a cyclic or unreasonably deep matchlet
585 // tree. Stop following it instead of exhausting the stack.
586 if (depth <= 0)
587 return false;
588
589 const char *dataPtr = data.constData();
590 const qsizetype dataSize = data.size();
591 for (quint32 matchlet = 0; matchlet < numMatchlets; ++matchlet) {
592 const std::optional<quint64> off = cacheFile->safeRecordOffset(firstOffset, 0, matchlet, MagicMatchletSize);
593 if (!off) // corrupt cache, or numMatchlets bigger than can possibly fit
594 break;
595 const std::optional<quint32> rangeStartOpt = cacheFile->getUint32(*off);
596 const std::optional<quint32> rangeLengthOpt = cacheFile->getUint32(*off, 4);
597 //const auto wordSize = cacheFile->getUint32(*off, 8);
598 const std::optional<quint32> valueLengthOpt = cacheFile->getUint32(*off, 12);
599 const std::optional<quint32> valueOffsetOpt = cacheFile->getUint32(*off, 16);
600 const std::optional<quint32> maskOffsetOpt = cacheFile->getUint32(*off, 20);
601 if (!rangeStartOpt || !rangeLengthOpt || !valueLengthOpt || !valueOffsetOpt
602 || !maskOffsetOpt) // corrupt cache: no later matchlet can be inside the file either
603 break;
604 const quint32 rangeStart = *rangeStartOpt;
605 const quint32 rangeLength = *rangeLengthOpt;
606 const quint32 valueLength = *valueLengthOpt;
607 const quint32 valueOffset = *valueOffsetOpt;
608 const quint32 maskOffset = *maskOffsetOpt;
609 budget -= 1 + qMin(quint64(rangeLength), quint64(dataSize));
610 if (budget < 0) // corrupt cache: give up on this record
611 return false;
612 const char *value = cacheFile->getData(valueOffset, valueLength);
613 const char *mask = maskOffset ? cacheFile->getData(maskOffset, valueLength) : nullptr;
614 if (!value || (maskOffset && !mask)) // corrupt cache
615 continue;
616
617 if (!QMimeMagicRule::matchSubstring(dataPtr, dataSize, rangeStart, rangeLength, valueLength, value, mask))
618 continue;
619
620 const std::optional<quint32> numChildrenOpt = cacheFile->getUint32(*off, 24);
621 const std::optional<quint32> firstChildOffsetOpt = cacheFile->getUint32(*off, 28);
622 if (!numChildrenOpt || !firstChildOffsetOpt) // corrupt cache: nor is any later matchlet
623 break;
624 const quint32 numChildren = *numChildrenOpt;
625 const quint32 firstChildOffset = *firstChildOffsetOpt;
626 if (numChildren == 0) // No submatch? Then we are done.
627 return true;
628 // Check that one of the submatches matches too
629 if (matchMagicRule(cacheFile, numChildren, firstChildOffset, data, depth - 1, budget))
630 return true;
631 }
632 return false;
633}
634
635bool QMimeBinaryProvider::magicRecordMatches(quint32 index, const QByteArray &data,
636 qint64 &budget) const
637{
638 const RecordList &matches = m_cacheFile->m_magicMatches;
639 const quint32 numMatchlets = m_cacheFile->recordUint32(matches, index, 8);
640 const quint32 firstMatchletOffset = m_cacheFile->recordUint32(matches, index, 12);
641 return matchMagicRule(m_cacheFile.get(), numMatchlets, firstMatchletOffset, data,
642 QMimeMagicRule::MaxRecursionDepth, budget);
643}
644
645void QMimeBinaryProvider::findByMagic(const QByteArray &data, QMimeMagicResult &result)
646{
647 const RecordList &matches = m_cacheFile->m_magicMatches;
648 qint64 budget = MagicMatchBudget;
649 for (quint32 i = 0; i < matches.count() && budget >= 0; ++i) {
650 if (magicRecordMatches(i, data, budget)) {
651 const int accuracy = static_cast<int>(m_cacheFile->recordUint32(matches, i, 0));
652 if (accuracy > result.accuracy) {
653 const quint32 mimeTypeOffset = m_cacheFile->recordUint32(matches, i, 4);
654 const QLatin1StringView candidate = m_cacheFile->getLatin1String(mimeTypeOffset);
655 if (candidate.isNull()) // corrupt cache: skip this record
656 continue;
657 result.accuracy = accuracy;
658 result.candidate = candidate;
659 // Return the first match, mime.cache is sorted
660 return;
661 }
662 }
663 }
664}
665
667QMimeBinaryProvider::checkMagicRules(const QString &mime, const QByteArray &data) const
668{
670 const RecordList &matches = m_cacheFile->m_magicMatches;
671 qint64 budget = MagicMatchBudget;
672 for (quint32 i = 0; i < matches.count() && budget >= 0; ++i) {
673 const quint32 mimeTypeOffset = m_cacheFile->recordUint32(matches, i, 4);
674 if (m_cacheFile->getLatin1String(mimeTypeOffset) != mime)
675 continue;
676 result.hasRules = true;
677 if (magicRecordMatches(i, data, budget)) {
678 result.matched = true;
679 break;
680 }
681 }
682 return result;
683}
684
685void QMimeBinaryProvider::addParents(const QString &mime, QStringList &result)
686{
687 const RecordList &parentList = m_cacheFile->m_parents;
688 const quint32 count = parentList.count();
689 if (!count)
690 return;
691 quint32 begin = 0;
692 quint32 end = count - 1;
693 while (begin <= end) {
694 const quint32 medium = (begin + end) / 2;
695 const quint32 mimeOffset = m_cacheFile->recordUint32(parentList, medium, 0);
696 const QLatin1StringView aMime = m_cacheFile->getLatin1String(mimeOffset);
697 if (aMime.isNull()) // corrupt cache: the search cannot continue
698 break;
699 const int cmp = aMime.compare(mime);
700 if (cmp < 0) {
701 begin = medium + 1;
702 } else if (cmp > 0) {
703 if (!medium)
704 break;
705 end = medium - 1;
706 } else {
707 // The parent list is reached by following an offset stored in the
708 // record, so it has to be bounds-checked here.
709 const quint32 parentsOffset = m_cacheFile->recordUint32(parentList, medium, 4);
710 const std::optional<quint32> numParentsOpt = m_cacheFile->getUint32(parentsOffset);
711 if (!numParentsOpt) // corrupt cache
712 break;
713 const quint32 numParents = *numParentsOpt;
714 for (quint32 i = 0; i < numParents; ++i) {
715 const std::optional<quint64> parentOff =
716 m_cacheFile->safeRecordOffset(parentsOffset, 4, i, 4);
717 if (!parentOff) // past end of file: no later index can be inside it
718 break;
719 const std::optional<quint32> parentOffsetOpt = m_cacheFile->getUint32(*parentOff);
720 if (!parentOffsetOpt) // corrupt cache: no later index can be inside the file either
721 break;
722 const QLatin1StringView parentL1 = m_cacheFile->getLatin1String(*parentOffsetOpt);
723 if (parentL1.isNull()) // corrupt cache: skip this record
724 break;
725 appendIfNew(result, QString(parentL1));
726 }
727 break;
728 }
729 }
730}
731
732QString QMimeBinaryProvider::resolveAlias(const QString &name)
733{
734 const RecordList &aliases = m_cacheFile->m_aliases;
735 quint32 begin = 0;
736 const quint32 count = aliases.count();
737 if (!count)
738 return QString();
739 quint32 end = count - 1;
740 while (begin <= end) {
741 const quint32 medium = (begin + end) / 2;
742 const quint32 aliasOffset = m_cacheFile->recordUint32(aliases, medium, 0);
743 const QLatin1StringView alias = m_cacheFile->getLatin1String(aliasOffset);
744 if (alias.isNull()) // corrupt cache: the search cannot continue
745 break;
746 const int cmp = alias.compare(name);
747 if (cmp < 0) {
748 begin = medium + 1;
749 } else if (cmp > 0) {
750 if (!medium)
751 break;
752 end = medium - 1;
753 } else {
754 const quint32 mimeOffset = m_cacheFile->recordUint32(aliases, medium, 4);
755 // if corrupt cache, returns QLatin1StringView(), which converts to a null QString
756 return m_cacheFile->getLatin1String(mimeOffset);
757 }
758 }
759 return QString();
760}
761
762void QMimeBinaryProvider::addAliases(const QString &name, QStringList &result)
763{
764 const RecordList &aliases = m_cacheFile->m_aliases;
765 for (quint32 pos = 0; pos < aliases.count(); ++pos) {
766 const quint32 mimeOffset = m_cacheFile->recordUint32(aliases, pos, 4);
767 const QLatin1StringView mimeType = m_cacheFile->getLatin1String(mimeOffset);
768 if (mimeType.isNull()) // corrupt cache: skip this record
769 continue;
770
771 if (name == QLatin1StringView(mimeType)) {
772 const quint32 aliasOffset = m_cacheFile->recordUint32(aliases, pos, 0);
773 const QLatin1StringView aliasL1 = m_cacheFile->getLatin1String(aliasOffset);
774 if (aliasL1.isNull()) // corrupt cache: skip this record
775 continue;
776 appendIfNew(result, QString(aliasL1));
777 }
778 }
779}
780
781void QMimeBinaryProvider::loadMimeTypeList()
782{
783 if (!m_mimetypeListLoaded) {
784 m_mimetypeListLoaded = true;
785 m_mimetypeNames.clear();
786 // Unfortunately mime.cache doesn't have a full list of all mimetypes.
787 // So we have to parse the plain-text files called "types".
788 QFile file(m_directory + QStringView(u"/types"));
789 if (file.open(QIODevice::ReadOnly)) {
790 QByteArray line;
791 while (file.readLineInto(&line)) {
792 auto lineView = QByteArrayView(line);
793 if (lineView.endsWith('\n'))
794 lineView.chop(1);
795 m_mimetypeNames.insert(QString::fromLatin1(lineView));
796 }
797 }
798 }
799}
800
801void QMimeBinaryProvider::addAllMimeTypes(QList<QMimeType> &result)
802{
803 loadMimeTypeList();
804 if (result.isEmpty()) {
805 result.reserve(m_mimetypeNames.size());
806 for (const QString &name : std::as_const(m_mimetypeNames))
807 result.append(QMimeType(QMimeTypePrivate(name)));
808 } else {
809 for (const QString &name : std::as_const(m_mimetypeNames))
810 if (std::find_if(result.constBegin(), result.constEnd(), [name](const QMimeType &mime) -> bool { return mime.name() == name; })
811 == result.constEnd())
812 result.append(QMimeType(QMimeTypePrivate(name)));
813 }
814}
815
816QMimeTypePrivate::LocaleHash QMimeBinaryProvider::localeComments(const QString &name)
817{
818 MimeTypeExtraMap::const_iterator it = loadMimeTypeExtra(name);
819 if (it != m_mimetypeExtra.cend())
820 return it->second.localeComments;
821 return {};
822}
823
824bool QMimeBinaryProvider::hasGlobDeleteAll(const QString &name)
825{
826 MimeTypeExtraMap::const_iterator it = loadMimeTypeExtra(name);
827 if (it != m_mimetypeExtra.cend())
828 return it->second.hasGlobDeleteAll;
829 return {};
830}
831
832QStringList QMimeBinaryProvider::globPatterns(const QString &name)
833{
834 MimeTypeExtraMap::const_iterator it = loadMimeTypeExtra(name);
835 if (it != m_mimetypeExtra.cend())
836 return it->second.globPatterns;
837 return {};
838}
839
840QMimeBinaryProvider::MimeTypeExtraMap::const_iterator
841QMimeBinaryProvider::loadMimeTypeExtra(const QString &mimeName)
842{
843#if QT_CONFIG(xmlstreamreader)
844 auto [it, insertionOccurred] = m_mimetypeExtra.try_emplace(mimeName);
845 if (insertionOccurred) {
846 // load comment and globPatterns
847
848 // shared-mime-info since 1.3 lowercases the xml files
849 QFile qfile;
850 const QString mimeFile = m_directory + u'/' + mimeName.toLower() + ".xml"_L1;
851 qfile.setFileName(mimeFile);
852 if (!qfile.open(QFile::ReadOnly)) {
853 const QString fallbackMimeFile = m_directory + u'/' + mimeName + ".xml"_L1; // pre-1.3
854 qfile.setFileName(fallbackMimeFile);
855 if (!qfile.open(QFile::ReadOnly))
856 return it;
857 }
858
859 MimeTypeExtra &extra = it->second;
860 QString mainPattern;
861
862 QXmlStreamReader xml(&qfile);
863 if (xml.readNextStartElement()) {
864 if (xml.name() != "mime-type"_L1) {
865 return m_mimetypeExtra.cend();
866 }
867 const auto name = xml.attributes().value("type"_L1);
868 if (name.isEmpty())
869 return m_mimetypeExtra.cend();
870 if (name.compare(mimeName, Qt::CaseInsensitive))
871 qWarning() << "Got name" << name << "in file" << mimeFile << "expected" << mimeName;
872
873 while (xml.readNextStartElement()) {
874 const auto tag = xml.name();
875 if (tag == "comment"_L1) {
876 QString lang = xml.attributes().value("xml:lang"_L1).toString();
877 const QString text = xml.readElementText();
878 if (lang.isEmpty()) {
879 lang = "default"_L1; // no locale attribute provided, treat it as default.
880 } else {
881 // normalize BCP 47 to internal underscore-splitted language tags
882 lang.replace(u'-', u'_');
883 }
884 extra.localeComments.insert(lang, text);
885 continue; // we called readElementText, so we're at the EndElement already.
886 } else if (tag == "glob-deleteall"_L1) { // as written out by shared-mime-info >= 0.70
887 extra.hasGlobDeleteAll = true;
888 } else if (tag == "glob"_L1) { // as written out by shared-mime-info >= 0.70
889 const QString pattern = xml.attributes().value("pattern"_L1).toString();
890 if (mainPattern.isEmpty() && pattern.startsWith(u'*')) {
891 mainPattern = pattern;
892 }
893 appendIfNew(extra.globPatterns, pattern);
894 }
895 xml.skipCurrentElement();
896 }
897 Q_ASSERT(xml.name() == "mime-type"_L1);
898 }
899
900 // Let's assume that shared-mime-info is at least version 0.70
901 // Otherwise we would need 1) a version check, and 2) code for parsing patterns from the globs file.
902 if (!mainPattern.isEmpty() &&
903 (extra.globPatterns.isEmpty() || extra.globPatterns.constFirst() != mainPattern)) {
904 // ensure it's first in the list of patterns
905 extra.globPatterns.removeAll(mainPattern);
906 extra.globPatterns.prepend(mainPattern);
907 }
908 }
909 return it;
910#else
911 Q_UNUSED(mimeName);
912 qWarning("Cannot load mime type since QXmlStreamReader is not available.");
913 return m_mimetypeExtra.cend();
914#endif // feature xmlstreamreader
915}
916
917// Binary search in the icons or generic-icons list
918QLatin1StringView QMimeBinaryProvider::iconForMime(CacheFile *cacheFile, const RecordList &icons,
919 QStringView inputMime)
920{
921 quint32 begin = 0;
922 const quint32 count = icons.count();
923 if (!count)
924 return QLatin1StringView();
925 quint32 end = count - 1;
926 while (begin <= end) {
927 const quint32 medium = (begin + end) / 2;
928 const quint32 mimeOffset = cacheFile->recordUint32(icons, medium, 0);
929 const QLatin1StringView mime = cacheFile->getLatin1String(mimeOffset);
930 if (mime.isNull()) // corrupt cache: the search cannot continue
931 break;
932 const int cmp = mime.compare(inputMime);
933 if (cmp < 0) {
934 begin = medium + 1;
935 } else if (cmp > 0) {
936 if (!medium)
937 break;
938 end = medium - 1;
939 } else {
940 const quint32 iconOffset = cacheFile->recordUint32(icons, medium, 4);
941 // if corrupt cache, returns QLatin1StringView()
942 return cacheFile->getLatin1String(iconOffset);
943 }
944 }
945 return QLatin1StringView();
946}
947
948QString QMimeBinaryProvider::icon(const QString &name)
949{
950 return iconForMime(m_cacheFile.get(), m_cacheFile->m_icons, name);
951}
952
953QString QMimeBinaryProvider::genericIcon(const QString &name)
954{
955 return iconForMime(m_cacheFile.get(), m_cacheFile->m_genericIcons, name);
956}
957
958////
959
960#if QT_CONFIG(mimetype_database)
961static QString internalMimeFileName()
962{
963 return QStringLiteral("<internal MIME data>");
964}
965
966QMimeXMLProvider::QMimeXMLProvider(QMimeDatabasePrivate *db, InternalDatabaseEnum)
967 : QMimeProviderBase(db, internalMimeFileName())
968{
969 static_assert(sizeof(mimetype_database), "Bundled MIME database is empty");
970 static_assert(sizeof(mimetype_database) <= MimeTypeDatabaseOriginalSize,
971 "Compressed MIME database is larger than the original size");
972 static_assert(MimeTypeDatabaseOriginalSize <= 16*1024*1024,
973 "Bundled MIME database is too big");
974 const char *data = reinterpret_cast<const char *>(mimetype_database);
975 qsizetype size = MimeTypeDatabaseOriginalSize;
976
977#ifdef MIME_DATABASE_IS_ZSTD
978 // uncompress with libzstd
979 std::unique_ptr<char []> uncompressed(new char[size]);
980 size = ZSTD_decompress(uncompressed.get(), size, mimetype_database, sizeof(mimetype_database));
981 Q_ASSERT(!ZSTD_isError(size));
982 data = uncompressed.get();
983#elif defined(MIME_DATABASE_IS_GZIP)
984 std::unique_ptr<char []> uncompressed(new char[size]);
985 z_stream zs = {};
986 zs.next_in = const_cast<Bytef *>(mimetype_database);
987 zs.avail_in = sizeof(mimetype_database);
988 zs.next_out = reinterpret_cast<Bytef *>(uncompressed.get());
989 zs.avail_out = size;
990
991 int res = inflateInit2(&zs, MAX_WBITS | 32);
992 Q_ASSERT(res == Z_OK);
993 res = inflate(&zs, Z_FINISH);
994 Q_ASSERT(res == Z_STREAM_END);
995 res = inflateEnd(&zs);
996 Q_ASSERT(res == Z_OK);
997
998 data = uncompressed.get();
999 size = zs.total_out;
1000#endif
1001
1002 load(data, size);
1003 sortMagicMatchers();
1004}
1005#else // !QT_CONFIG(mimetype_database)
1006// never called in release mode, but some debug builds may need
1007// this to be defined.
1009 : QMimeProviderBase(db, QString())
1010{
1011 Q_UNREACHABLE();
1012}
1013#endif // QT_CONFIG(mimetype_database)
1014
1015QMimeXMLProvider::QMimeXMLProvider(QMimeDatabasePrivate *db, const QString &directory)
1016 : QMimeProviderBase(db, directory)
1017{
1019}
1020
1021QMimeXMLProvider::~QMimeXMLProvider()
1022{
1023}
1024
1025bool QMimeXMLProvider::isValid()
1026{
1027 // If you change this method, adjust the logic in QMimeDatabasePrivate::loadProviders,
1028 // which assumes isValid==false is only possible in QMimeBinaryProvider.
1029 return true;
1030}
1031
1032bool QMimeXMLProvider::isInternalDatabase() const
1033{
1034#if QT_CONFIG(mimetype_database)
1035 return m_directory == internalMimeFileName();
1036#else
1037 return false;
1038#endif
1039}
1040
1041bool QMimeXMLProvider::knowsMimeType(const QString &name)
1042{
1043 return m_nameMimeTypeMap.contains(name);
1044}
1045
1046void QMimeXMLProvider::addFileNameMatches(const QString &fileName, QMimeGlobMatchResult &result)
1047{
1048 auto filterFunc = [this](const QString &name) { return !isMimeTypeGlobsExcluded(name); };
1049 m_mimeTypeGlobs.matchingGlobs(fileName, result, filterFunc);
1050}
1051
1052void QMimeXMLProvider::findByMagic(const QByteArray &data, QMimeMagicResult &result)
1053{
1054 const QMimeMagicData magicData(data);
1055 for (const QMimeMagicRuleMatcher &matcher : std::as_const(m_magicMatchers)) {
1056 if (matcher.matches(magicData)) {
1057 const int priority = matcher.priority();
1058 if (priority > result.accuracy) {
1059 result.accuracy = priority;
1060 result.candidate = matcher.mimetype();
1061 }
1062 }
1063 }
1064}
1065
1067QMimeXMLProvider::checkMagicRules(const QString &mime, const QByteArray &data) const
1068{
1069 QMimeMagicCheckResult result;
1070 const QMimeMagicData magicData(data);
1071 for (const QMimeMagicRuleMatcher &matcher : m_magicMatchers) {
1072 if (matcher.mimetype() != mime)
1073 continue;
1074 result.hasRules = true;
1075 if (matcher.matches(magicData)) {
1076 result.matched = true;
1077 break;
1078 }
1079 }
1080 return result;
1081}
1082
1083void QMimeXMLProvider::ensureLoaded()
1084{
1085 QStringList allFiles;
1086 const QString packageDir = m_directory + QStringView(u"/packages");
1087 for (const auto &entry : QDirListing(packageDir, QDirListing::IteratorFlag::FilesOnly
1088 | QDirListing::IteratorFlag::ResolveSymlinks))
1089 allFiles.emplace_back(packageDir + u'/' + entry.fileName());
1090
1091 if (m_allFiles == allFiles)
1092 return;
1093 m_allFiles = allFiles;
1094
1095 m_nameMimeTypeMap.clear();
1096 m_aliases.clear();
1097 m_parents.clear();
1098 m_mimeTypeGlobs.clear();
1099 m_magicMatchers.clear();
1100
1101 //qDebug() << "Loading" << m_allFiles;
1102
1103 for (const QString &file : std::as_const(allFiles))
1104 load(file);
1105 sortMagicMatchers();
1106}
1107
1108// Same order as in mime.cache: highest priority first, then by mimetype name,
1109// so that both providers pick the same mimetype when several rules match.
1110void QMimeXMLProvider::sortMagicMatchers()
1111{
1112 std::stable_sort(m_magicMatchers.begin(), m_magicMatchers.end(),
1113 [](const QMimeMagicRuleMatcher &a, const QMimeMagicRuleMatcher &b) {
1114 if (a.priority() != b.priority())
1115 return a.priority() > b.priority();
1116 return a.mimetype() < b.mimetype();
1117 });
1118}
1119
1120QMimeTypePrivate::LocaleHash QMimeXMLProvider::localeComments(const QString &name)
1121{
1122 return m_nameMimeTypeMap.value(name).localeComments;
1123}
1124
1125bool QMimeXMLProvider::hasGlobDeleteAll(const QString &name)
1126{
1127 return m_nameMimeTypeMap.value(name).hasGlobDeleteAll;
1128}
1129
1130QStringList QMimeXMLProvider::globPatterns(const QString &name)
1131{
1132 return m_nameMimeTypeMap.value(name).globPatterns;
1133}
1134
1135QString QMimeXMLProvider::icon(const QString &name)
1136{
1137 return m_nameMimeTypeMap.value(name).iconName;
1138}
1139
1140QString QMimeXMLProvider::genericIcon(const QString &name)
1141{
1142 return m_nameMimeTypeMap.value(name).genericIconName;
1143}
1144
1145void QMimeXMLProvider::load(const QString &fileName)
1146{
1147 QString errorMessage;
1148 if (!load(fileName, &errorMessage))
1149 qWarning("QMimeDatabase: Error loading %ls\n%ls", qUtf16Printable(fileName), qUtf16Printable(errorMessage));
1150}
1151
1152bool QMimeXMLProvider::load(const QString &fileName, QString *errorMessage)
1153{
1154 QFile file(fileName);
1155 if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
1156 if (errorMessage)
1157 *errorMessage = "Cannot open "_L1 + fileName + ": "_L1 + file.errorString();
1158 return false;
1159 }
1160
1161 if (errorMessage)
1162 errorMessage->clear();
1163
1165 return parser.parse(&file, fileName, errorMessage);
1166}
1167
1168#if QT_CONFIG(mimetype_database)
1169void QMimeXMLProvider::load(const char *data, qsizetype len)
1170{
1171 QBuffer buffer;
1172 buffer.setData(QByteArray::fromRawData(data, len));
1173 buffer.open(QIODevice::ReadOnly);
1174 QString errorMessage;
1175 QMimeTypeParser parser(*this, QMimeMagicRule::RegexRules::Allowed);
1176 if (!parser.parse(&buffer, internalMimeFileName(), &errorMessage))
1177 qWarning("QMimeDatabase: Error loading internal MIME data\n%s", qPrintable(errorMessage));
1178}
1179#endif
1180
1181void QMimeXMLProvider::addGlobPattern(const QMimeGlobPattern &glob)
1182{
1183 m_mimeTypeGlobs.addGlob(glob);
1184}
1185
1186void QMimeXMLProvider::addMimeType(const QMimeTypeXMLData &mt)
1187{
1188 m_nameMimeTypeMap.insert(mt.name, mt);
1189}
1190
1191void QMimeXMLProvider::addParents(const QString &mime, QStringList &result)
1192{
1193 const QStringList parents = m_parents.value(mime);
1194 for (const QString &parent : parents) {
1195 if (!result.contains(parent))
1196 result.append(parent);
1197 }
1198}
1199
1200void QMimeXMLProvider::addParent(const QString &child, const QString &parent)
1201{
1202 m_parents[child].append(parent);
1203}
1204
1205void QMimeXMLProvider::addAliases(const QString &name, QStringList &result)
1206{
1207 // Iterate through the whole hash. This method is rarely used.
1208 for (const auto &[alias, mimeName] : std::as_const(m_aliases).asKeyValueRange()) {
1209 if (mimeName == name)
1210 appendIfNew(result, alias);
1211 }
1212}
1213
1214QString QMimeXMLProvider::resolveAlias(const QString &name)
1215{
1216 return m_aliases.value(name);
1217}
1218
1219void QMimeXMLProvider::addAlias(const QString &alias, const QString &name)
1220{
1221 m_aliases.insert(alias, name);
1222}
1223
1224void QMimeXMLProvider::addAllMimeTypes(QList<QMimeType> &result)
1225{
1226 if (result.isEmpty()) { // fast path
1227 for (auto it = m_nameMimeTypeMap.constBegin(), end = m_nameMimeTypeMap.constEnd();
1228 it != end; ++it) {
1229 result.append(QMimeType(QMimeTypePrivate(it.value().name)));
1230 }
1231 } else {
1232 for (auto it = m_nameMimeTypeMap.constBegin(), end = m_nameMimeTypeMap.constEnd() ; it != end ; ++it) {
1233 const QString newMime = it.key();
1234 if (std::find_if(result.constBegin(), result.constEnd(), [newMime](const QMimeType &mime) -> bool { return mime.name() == newMime; })
1235 == result.constEnd())
1236 result.append(QMimeType(QMimeTypePrivate(it.value().name)));
1237 }
1238 }
1239}
1240
1241void QMimeXMLProvider::addMagicMatcher(const QMimeMagicRuleMatcher &matcher)
1242{
1243 m_magicMatchers.append(matcher);
1244}
1245
1246QT_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
QMimeMagicCheckResult checkMagicRules(const QString &mime, const QByteArray &data) const 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, QMimeMagicRule::RegexRules regexRules)
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)
QMimeMagicCheckResult checkMagicRules(const QString &mime, const QByteArray &data) const override
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
static constexpr qsizetype MaxCachedGlobRegularExpressions
@ 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)
static constexpr qint64 MagicMatchBudget
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
bool matchRegularExpressionGlob(quint32 globOffset, QLatin1StringView pattern, const QString &fileName)
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