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
qstorageinfo_linux.cpp
Go to the documentation of this file.
1// Copyright (C) 2021 The Qt Company Ltd.
2// Copyright (C) 2014 Ivan Komissarov <ABBAPOH@gmail.com>
3// Copyright (C) 2016 Intel Corporation.
4// Copyright (C) 2023 Ahmad Samir <a.samirh78@gmail.com>
5// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
6// Qt-Security score:significant reason:default
7
9
10#include <private/qcore_unix_p.h>
11#include <private/qlocale_tools_p.h>
12#include <private/qtools_p.h>
13
14#include <QtCore/qdirlisting.h>
15#include <QtCore/qsystemdetection.h>
16
17#include <q20memory.h>
18
19#include <sys/ioctl.h>
20#include <sys/stat.h>
21#include <sys/statfs.h>
22#include <sys/syscall.h>
23
24#include <linux/types.h>
25#include <linux/mount.h>
26
27// so we don't have to #include <linux/fs.h>, which is known to cause conflicts
28#ifndef FSLABEL_MAX
29# define FSLABEL_MAX 256
30#endif
31#ifndef FS_IOC_GETFSLABEL
32# define FS_IOC_GETFSLABEL _IOR(0x94, 49, char[FSLABEL_MAX])
33#endif
34
36# define STATX_MNT_ID_UNIQUE 0x4000U
37#endif
38
39// or <linux/statfs.h>
40#ifndef ST_RDONLY
41# define ST_RDONLY 0x0001 /* mount read-only */
42#endif
43
44#if defined(Q_OS_ANDROID)
45// statx() is disabled on Android because quite a few systems
46// come with sandboxes that kill applications that make system calls outside a
47// whitelist and several Android vendors can't be bothered to update the list.
48# undef STATX_BASIC_STATS
49// Likewise for listmount() and statmount() (disabling statx() and listmount()
50// disables statmount()).
51# undef LSMT_ROOT
52
53#include <private/qjnihelpers_p.h>
54#endif
55
56QT_BEGIN_NAMESPACE
57
58// So we don't depend on linux/mount.h defining the version we need (we need at
59// least 6.13, with sb_source).
60namespace QtPrivate {
61struct statmount {
62 __u32 size; /* Total size, including strings */
63 __u32 mnt_opts; /* [str] Options (comma separated, escaped) */
64 __u64 mask; /* What results were written */
65 __u32 sb_dev_major; /* Device ID */
67 __u64 sb_magic; /* ..._SUPER_MAGIC */
68 __u32 sb_flags; /* SB_{RDONLY,SYNCHRONOUS,DIRSYNC,LAZYTIME} */
69 __u32 fs_type; /* [str] Filesystem type */
70 __u64 mnt_id; /* Unique ID of mount */
71 __u64 mnt_parent_id; /* Unique ID of parent (for root == mnt_id) */
72 __u32 mnt_id_old; /* Reused IDs used in proc/.../mountinfo */
74 __u64 mnt_attr; /* MOUNT_ATTR_... */
75 __u64 mnt_propagation; /* MS_{SHARED,SLAVE,PRIVATE,UNBINDABLE} */
76 __u64 mnt_peer_group; /* ID of shared peer group */
77 __u64 mnt_master; /* Mount receives propagation from this ID */
78 __u64 propagate_from; /* Propagation from in current namespace */
79 __u32 mnt_root; /* [str] Root of mount relative to root of fs */
80 __u32 mnt_point; /* [str] Mountpoint relative to current root */
81 __u64 mnt_ns_id; /* ID of the mount namespace */
82 __u32 fs_subtype; /* [str] Subtype of fs_type (if any) */
83 __u32 sb_source; /* [str] Source string of the mount */
84 __u32 opt_num; /* Number of fs options */
85 __u32 opt_array; /* [str] Array of nul terminated fs options */
86 __u32 opt_sec_num; /* Number of security options */
87 __u32 opt_sec_array; /* [str] Array of nul terminated security options */
88 __u64 __spare2[46];
89 char str[]; /* Variable size part containing strings */
90};
91} // namespace QtPrivate
92
93using namespace Qt::StringLiterals;
94
95static const char MountInfoPath[] = "/proc/self/mountinfo";
96
97static std::optional<dev_t> deviceNumber(QByteArrayView devno)
98{
99 // major:minor
100 auto it = devno.cbegin();
101 auto r = qstrntoll(it, devno.size(), 10);
102 if (!r.ok())
103 return std::nullopt;
104 int rdevmajor = int(r.result);
105 it += r.used;
106
107 if (*it != ':')
108 return std::nullopt;
109
110 r = qstrntoll(++it, devno.size() - r.used + 1, 10);
111 if (!r.ok())
112 return std::nullopt;
113
114 return makedev(rdevmajor, r.result);
115}
116
117// Helper function to parse paths that the kernel inserts escape sequences
118// for.
119static QByteArray parseMangledPath(QByteArrayView path)
120{
121 // The kernel escapes with octal the following characters:
122 // space ' ', tab '\t', backslash '\\', and newline '\n'
123 // See:
124 // https://codebrowser.dev/linux/linux/fs/proc_namespace.c.html#show_mountinfo
125 // https://codebrowser.dev/linux/linux/fs/seq_file.c.html#mangle_path
126
127 QByteArray ret(path.size(), '\0');
128 char *dst = ret.data();
129 const char *src = path.data();
130 const char *srcEnd = path.data() + path.size();
131 while (src != srcEnd) {
132 switch (*src) {
133 case ' ': // Shouldn't happen
134 return {};
135
136 case '\\': {
137 // It always uses exactly three octal characters.
138 ++src;
139 char c = (*src++ - '0') << 6;
140 c |= (*src++ - '0') << 3;
141 c |= (*src++ - '0');
142 *dst++ = c;
143 break;
144 }
145
146 default:
147 *dst++ = *src++;
148 break;
149 }
150 }
151 // If "path" contains any of the characters this method is demangling,
152 // "ret" would be oversized with extra '\0' characters at the end.
153 ret.resize(dst - ret.data());
154 return ret;
155}
156
157// Indexes into the "fields" std::array in parseMountInfo()
158static constexpr short MountId = 0;
159// static constexpr short ParentId = 1;
160static constexpr short DevNo = 2;
161static constexpr short FsRoot = 3;
162static constexpr short MountPoint = 4;
163static constexpr short MountOptions = 5;
164// static constexpr short OptionalFields = 6;
165// static constexpr short Separator = 7;
166static constexpr short FsType = 8;
167static constexpr short MountSource = 9;
168static constexpr short SuperOptions = 10;
169static constexpr short FieldCount = 11;
170
171// Splits a line from /proc/self/mountinfo into fields; fields are separated
172// by a single space.
173static void tokenizeLine(std::array<QByteArrayView, FieldCount> &fields, QByteArrayView line)
174{
175 size_t fieldIndex = 0;
176 qsizetype from = 0;
177 const char *begin = line.data();
178 const qsizetype len = line.size();
179 qsizetype spaceIndex = -1;
180 while ((spaceIndex = line.indexOf(' ', from)) != -1 && fieldIndex < FieldCount) {
181 fields[fieldIndex] = QByteArrayView{begin + from, begin + spaceIndex};
182 from = spaceIndex;
183
184 // Skip "OptionalFields" and Separator fields
185 if (fieldIndex == MountOptions) {
186 static constexpr char separatorField[] = " - ";
187 const qsizetype sepIndex = line.indexOf(separatorField, from);
188 if (sepIndex == -1) {
189 qCWarning(lcStorageInfo,
190 "Malformed line (missing '-' separator field) while parsing '%s':\n%s",
191 MountInfoPath, line.constData());
192 fields.fill({});
193 return;
194 }
195
196 from = sepIndex + strlen(separatorField);
197 // Continue parsing at FsType field
198 fieldIndex = FsType;
199 continue;
200 }
201
202 if (from + 1 < len)
203 ++from; // Skip the space at spaceIndex
204
205 ++fieldIndex;
206 }
207
208 // Currently we don't use the last field, so just check the index
209 if (fieldIndex != SuperOptions) {
210 qCInfo(lcStorageInfo,
211 "Expected %d fields while parsing line from '%s', but found %zu instead:\n%.*s",
212 FieldCount, MountInfoPath, fieldIndex, int(line.size()), line.data());
213 fields.fill({});
214 }
215}
216
217std::vector<MountInfo> doParseMountInfo(const QByteArray &mountinfo, FilterMountInfo filter)
218{
219 // https://www.kernel.org/doc/Documentation/filesystems/proc.txt:
220 // 36 35 98:0 /mnt1 /mnt2 rw,noatime master:1 - ext3 /dev/root rw,errors=continue
221 // (1)(2)(3) (4) (5) (6) (7) (8) (9) (10) (11)
222
223 auto it = mountinfo.cbegin();
224 const auto end = mountinfo.cend();
225 auto nextLine = [&it, &end]() -> QByteArrayView {
226 auto nIt = std::find(it, end, '\n');
227 if (nIt != end) {
228 QByteArrayView ba(it, nIt);
229 it = ++nIt; // Advance
230 return ba;
231 }
232 return {};
233 };
234
235 std::vector<MountInfo> infos;
236 std::array<QByteArrayView, FieldCount> fields;
237 QByteArrayView line;
238
239 auto checkField = [&line](QByteArrayView field) {
240 if (field.isEmpty()) {
241 qDebug("Failed to parse line from %s:\n%.*s", MountInfoPath, int(line.size()),
242 line.data());
243 return false;
244 }
245 return true;
246 };
247
248 // mountinfo has a stable format, no empty lines
249 while (!(line = nextLine()).isEmpty()) {
250 fields.fill({});
251 tokenizeLine(fields, line);
252
253 MountInfo info;
254 if (auto r = qstrntoll(fields[MountId].data(), fields[MountId].size(), 10); r.ok()) {
255 info.mntid = r.result;
256 } else {
257 checkField({});
258 continue;
259 }
260
261 QByteArray mountP = parseMangledPath(fields[MountPoint]);
262 if (!checkField(mountP))
263 continue;
264 info.mountPoint = QFile::decodeName(mountP);
265
266 if (!checkField(fields[FsType]))
267 continue;
268 info.fsType = fields[FsType].toByteArray();
269
270 if (filter == FilterMountInfo::Filtered
271 && !QStorageInfoPrivate::shouldIncludeFs(info.mountPoint, info.fsType))
272 continue;
273
274 std::optional<dev_t> devno = deviceNumber(fields[DevNo]);
275 if (!devno) {
276 checkField({});
277 continue;
278 }
279 info.stDev = *devno;
280
281 QByteArrayView fsRootView = fields[FsRoot];
282 if (!checkField(fsRootView))
283 continue;
284
285 // If the filesystem root is "/" -- it's not a *sub*-volume/bind-mount,
286 // in that case we leave info.fsRoot empty
287 if (fsRootView != "/") {
288 info.fsRoot = parseMangledPath(fsRootView);
289 if (!checkField(info.fsRoot))
290 continue;
291 }
292
293 info.device = parseMangledPath(fields[MountSource]);
294 if (!checkField(info.device))
295 continue;
296
297 infos.push_back(std::move(info));
298 }
299 return infos;
300}
301
302namespace {
303struct AutoFileDescriptor
304{
305 int fd = -1;
306 explicit AutoFileDescriptor() = default;
307 AutoFileDescriptor(const QString &path, int mode = QT_OPEN_RDONLY)
308 : fd(qt_safe_open(QFile::encodeName(path), mode))
309 {}
310 ~AutoFileDescriptor() { if (fd >= 0) qt_safe_close(fd); }
311 operator int() const noexcept { return fd; }
312};
313
314struct QStorageLabelRetriever
315{
316 struct Entry {
317 QString label;
318 quint64 deviceId;
319 };
320 QList<Entry> labelMap;
321 bool populated = false;
322 QString operator()(const QStorageInfoPrivate &d, int fd, quint64 devid);
323
324private:
325 static QList<Entry> allLabels();
326};
327}
328Q_DECLARE_TYPEINFO(QStorageLabelRetriever::Entry, Q_RELOCATABLE_TYPE);
329
330// udev encodes the labels with ID_LABEL_FS_ENC which is done with
331// blkid_encode_string(). Within this function some 1-byte utf-8
332// characters not considered safe (e.g. '\' or ' ') are encoded as hex
333static QString decodeFsEncString(QString decoded)
334{
335 using namespace QtMiscUtils;
336 const qsizetype start = decoded.indexOf(u'\\');
337 if (start < 0)
338 return decoded;
339
340 // decode in-place
341 auto ptr = reinterpret_cast<char16_t *>(decoded.begin());
342 qsizetype in = start;
343 qsizetype out = start;
344 qsizetype size = decoded.size();
345
346 while (in < size) {
347 Q_ASSERT(ptr[in] == u'\\');
348 if (size - in >= 4 && ptr[in + 1] == u'x') { // we need four characters: \xAB
349 int c = fromHex(ptr[in + 2]) << 4;
350 c |= fromHex(ptr[in + 3]);
351 if (Q_UNLIKELY(c < 0))
352 c = QChar::ReplacementCharacter; // bad hex sequence
353 ptr[out++] = c;
354 in += 4;
355 }
356
357 for ( ; in < size; ++in) {
358 char16_t c = ptr[in];
359 if (c == u'\\')
360 break;
361 ptr[out++] = c;
362 }
363 }
364 decoded.resize(out);
365 return decoded;
366}
367
368static inline dev_t deviceIdForPath(const QString &device)
369{
370 QT_STATBUF st;
371 if (QT_STAT(QFile::encodeName(device), &st) < 0)
372 return 0;
373 return st.st_dev;
374}
375
376static inline quint64 mountIdForPath(int fd, unsigned mountIdType = 0)
377{
378 if (fd < 0)
379 return 0;
380#if defined(STATX_BASIC_STATS) && defined(STATX_MNT_ID)
381 // STATX_MNT_ID was added in kernel v5.8
382 struct statx st;
383 if (mountIdType == 0)
384 mountIdType = STATX_MNT_ID;
385 int r = statx(fd, "", AT_EMPTY_PATH | AT_NO_AUTOMOUNT, mountIdType, &st);
386 if (r == 0 && (st.stx_mask & mountIdType))
387 return st.stx_mnt_id;
388#else
389 Q_UNUSED(mountIdType);
390#endif
391 return 0;
392}
393
394static inline quint64 retrieveDeviceId(const QByteArray &device, quint64 deviceId = 0)
395{
396 // major = 0 implies an anonymous block device, so we need to stat() the
397 // actual device to get its dev_t. This is required for btrfs (and possibly
398 // others), which always uses them for all the subvolumes (including the
399 // root):
400 // https://codebrowser.dev/linux/linux/fs/btrfs/disk-io.c.html#btrfs_init_fs_root
401 // https://codebrowser.dev/linux/linux/fs/super.c.html#get_anon_bdev
402 // For everything else, we trust the parameter.
403 if (major(deviceId) != 0)
404 return deviceId;
405
406 // don't even try to stat() a relative path or "/"
407 if (device.size() < 2 || !device.startsWith('/'))
408 return 0;
409
410 QT_STATBUF st;
411 if (QT_STAT(device, &st) < 0)
412 return 0;
413 if (!S_ISBLK(st.st_mode))
414 return 0;
415 return st.st_rdev;
416}
417
419{
420 static const char pathDiskByLabel[] = "/dev/disk/by-label";
421 static constexpr auto LabelFileFilter = QDirListing::IteratorFlag::IncludeHidden;
422 return QDirListing(QLatin1StringView(pathDiskByLabel), LabelFileFilter);
423}
424
425auto QStorageLabelRetriever::allLabels() -> QList<Entry>
426{
427 QList<Entry> result;
428
429 for (const auto &dirEntry : devicesByLabel()) {
430 quint64 deviceId = retrieveDeviceId(QFile::encodeName(dirEntry.filePath()));
431 if (!deviceId)
432 continue;
433 result.emplaceBack(Entry{ decodeFsEncString(dirEntry.fileName()), deviceId });
434 }
435 return result;
436}
437
439{
440 // FS_IOC_GETFSLABEL was introduced in v4.18; previously it was btrfs-specific.
441 if (fd < 0)
442 return std::nullopt;
443
444 // Note: it doesn't append the null terminator (despite what the man page
445 // says) and the return code on success (0) does not indicate the length.
446 char label[FSLABEL_MAX] = {};
447 int r = ioctl(fd, FS_IOC_GETFSLABEL, &label);
448 if (r < 0)
449 return std::nullopt;
450 return QString::fromUtf8(label);
451}
452
453static inline QString retrieveLabel(const QStorageInfoPrivate &d, int fd, quint64 deviceId)
454{
455 if (auto label = retrieveLabelViaIoctl(fd))
456 return *label;
457
458 deviceId = retrieveDeviceId(d.device, deviceId);
459 if (!deviceId)
460 return QString();
461
462 for (const auto &dirEntry : devicesByLabel()) {
463 if (retrieveDeviceId(QFile::encodeName(dirEntry.filePath())) == deviceId)
464 return decodeFsEncString(dirEntry.fileName());
465 }
466 return QString();
467}
468
469QString QStorageLabelRetriever::operator()(const QStorageInfoPrivate &d, int fd, quint64 devid)
470{
471 if (d.fileSystemType == "tmpfs")
472 return QString();
473
474 if (auto label = retrieveLabelViaIoctl(fd))
475 return *label;
476
477 devid = retrieveDeviceId(d.device, devid);
478 if (!devid)
479 return QString();
480
481 if (!populated) {
482 labelMap = allLabels();
483 populated = true;
484 }
485 for (auto &[deviceLabel, deviceId] : std::as_const(labelMap)) {
486 if (devid == deviceId)
487 return deviceLabel;
488 }
489 return QString();
490}
491
492void QStorageInfoPrivate::retrieveVolumeInfo()
493{
494 struct statfs64 statfs_buf;
495 int result;
496 QT_EINTR_LOOP(result, statfs64(QFile::encodeName(rootPath).constData(), &statfs_buf));
497 valid = ready = (result == 0);
498 if (valid) {
499 bytesTotal = statfs_buf.f_blocks * statfs_buf.f_frsize;
500 bytesFree = statfs_buf.f_bfree * statfs_buf.f_frsize;
501 bytesAvailable = statfs_buf.f_bavail * statfs_buf.f_frsize;
502 blockSize = int(statfs_buf.f_bsize);
503 readOnly = (statfs_buf.f_flags & ST_RDONLY) != 0;
504 }
505}
506
507static auto
508doStatMount(QStorageInfoPrivate *d, const AutoFileDescriptor &fd, quint64 mountid,
509 QStorageLabelRetriever &labelRetriever)
510{
511 enum TriStateResult : qint8 {
512 NotSupported = -1,
513 Skip = 0,
514 Add = 1,
515 };
516
517#ifdef __NR_statmount
518 using QtPrivate::statmount;
519 constexpr int NumStringsInRequest = 4; // mnt_point, sb_type, sb_source, mnt_root
520 // the parameters we'll request
521 static constexpr quint64 StatMountRequestParams = 0x23b;
522 // the minimum set of parameters we need
523 static constexpr quint64 StatMountMinParams = StatMountRequestParams;
524# ifdef STATMOUNT_SB_SOURCE // added in 6.13
525 // confirm our numeric value above is correct
526 constexpr quint64 SymbolicStatMountParams = STATMOUNT_SB_BASIC | STATMOUNT_MNT_BASIC
527 | STATMOUNT_MNT_POINT | STATMOUNT_MNT_ROOT | STATMOUNT_FS_TYPE
528 | STATMOUNT_SB_SOURCE;
529 static_assert(SymbolicStatMountParams == StatMountRequestParams);
530# endif
531
532 QVarLengthArray<char, 1024> smbuf(1024);
533 auto sm = new (smbuf.data()) struct statmount;
534 struct mnt_id_req req = {};
535 req.size = sizeof(req);
536 req.mnt_id = mountid;
537 req.param = StatMountRequestParams;
538
539 int r = syscall(__NR_statmount, &req, sm, smbuf.size(), 0);
540 if (r < 0 && errno == EOVERFLOW) {
541 // try with heap
542 smbuf.resize(sizeof(struct statmount) + NumStringsInRequest * PATH_MAX);
543 sm = new (smbuf.data()) struct statmount;
544 r = syscall(__NR_statmount, &req, sm, smbuf.size(), 0);
545 }
546 if (r == 0 && (sm->mask & StatMountMinParams) == StatMountMinParams) {
547 d->rootPath = QFile::decodeName(sm->str + sm->mnt_point);
548 d->fileSystemType.assign(sm->str + sm->fs_type);
549 if (!QStorageInfoPrivate::shouldIncludeFs(d->rootPath, d->fileSystemType))
550 return Skip;
551
552 d->device = QByteArray(sm->str + sm->sb_source);
553 if (QByteArrayView subv(sm->str + sm->mnt_root); subv != "/")
554 d->subvolume.assign(subv);
555 else
556 d->subvolume.clear();
557
558 quint64 devid = makedev(sm->sb_dev_major, sm->sb_dev_minor);
559 if (fd.fd >= 0)
560 d->name = labelRetriever(*d, fd, devid); // already open
561 else
562 d->name = labelRetriever(*d, AutoFileDescriptor(d->rootPath), devid);
563 return Add;
564 }
565#else
566 Q_UNUSED(d);
567 Q_UNUSED(fd);
568 Q_UNUSED(mountid);
569 Q_UNUSED(labelRetriever);
570#endif // !__NR_statmount
571 return NotSupported;
572}
573
574static bool doStatMount(QStorageInfoPrivate *d, const AutoFileDescriptor &fd)
575{
576 quint64 mountId = mountIdForPath(fd, STATX_MNT_ID_UNIQUE);
577 if (!mountId)
578 return false;
579
580 QStorageLabelRetriever retriever;
581 return doStatMount(d, fd, mountId, retriever) > 0;
582}
583
584QList<QStorageInfo> QStorageInfoPrivate::listMounts()
585{
586 QList<QStorageInfo> volumes;
587
588#if defined(__NR_listmount) && defined(LSMT_ROOT)
589 QStorageLabelRetriever labelRetriever;
590 Q_DECL_UNINITIALIZED
591 quint64 mounts[128];
592
593 struct mnt_id_req req = {};
594 req.size = sizeof(req);
595 req.mnt_id = LSMT_ROOT;
596 int r = syscall(__NR_listmount, &req, mounts, std::size(mounts), 0);
597 if (r < 0)
598 return volumes;
599
600 std::unique_ptr<QStorageInfoPrivate> d;
601 while (r > 0) {
602 for (quint64 mntid : QSpan(mounts, r)) {
603 if (!d)
604 d = std::make_unique<QStorageInfoPrivate>();
605 auto shouldAdd = doStatMount(d.get(), AutoFileDescriptor(), mntid, labelRetriever);
606 if (shouldAdd < 0) {
607 r = -1;
608 break; // API failure
609 }
610 if (!shouldAdd)
611 continue;
612 d->retrieveVolumeInfo();
613 if (!d->ready)
614 continue; // mount point inaccessible
615 volumes.emplace_back(QStorageInfo(*d.release()));
616 }
617 if (r < q20::ssize(mounts))
618 break; // done or failure
619
620 // ask for more
621 req.param = mounts[r - 1];
622 r = syscall(__NR_listmount, &req, mounts, std::size(mounts), 0);
623 }
624 if (r < 0)
625 volumes.clear(); // we've failed
626#endif // __NR_listmount
627
628 return volumes;
629}
630
632{
633 QFile file(u"/proc/self/mountinfo"_s);
634 if (!file.open(QIODevice::ReadOnly | QIODevice::Text))
635 return {};
636
637 QByteArray mountinfo = file.readAll();
638 file.close();
639
640 return doParseMountInfo(mountinfo, filter);
641}
642
643void QStorageInfoPrivate::doStat()
644{
645#ifdef Q_OS_ANDROID
646 if (QtAndroidPrivate::isUncompressedNativeLibs()) {
647 // We need to pass the actual file path on the file system to statfs64
648 QString possibleApk = QtAndroidPrivate::resolveApkPath(rootPath);
649 if (!possibleApk.isEmpty())
650 rootPath = possibleApk;
651 }
652#endif
653
654 retrieveVolumeInfo();
655 if (!ready)
656 return;
657
658 AutoFileDescriptor fd(rootPath);
659 if (doStatMount(this, fd))
660 return;
661
662 QFileInfo fileInfo(rootPath);
663 if (QString canonicalPath = fileInfo.canonicalFilePath(); !canonicalPath.isEmpty()) {
664 rootPath = std::move(canonicalPath);
665 } else {
666 // The volume is ready but canonization process failed (for example, a
667 // mount point we're allowed to statfs() but not open(), as can happen
668 // under SELinux on Android). The absolute path will have to do.
669 rootPath = fileInfo.absoluteFilePath();
670 }
671
672 std::vector<MountInfo> infos = parseMountInfo();
673 if (infos.empty()) {
674 rootPath = u'/';
675 return;
676 }
677
678 MountInfo *best = nullptr;
679 if (quint64 mntid = mountIdForPath(fd)) {
680 // We have the mount ID for this path, so find the matching line.
681 auto it = std::find_if(infos.begin(), infos.end(),
682 [mntid](const MountInfo &info) { return info.mntid == mntid; });
683 if (it != infos.end())
684 best = q20::to_address(it);
685 } else {
686 // We have failed to get the mount ID for this path, usually because
687 // the path cannot be open()ed by this user (e.g., /root), so we fall
688 // back to a string search.
689 // We iterate over the /proc/self/mountinfo list backwards because then any
690 // matching isParentOf must be the actual mount point because it's the most
691 // recent mount on that path. Linux does allow mounting over non-empty
692 // directories, such as in:
693 // # mount | tail -2
694 // tmpfs on /tmp/foo/bar type tmpfs (rw,relatime,inode64)
695 // tmpfs on /tmp/foo type tmpfs (rw,relatime,inode64)
696 //
697 // We try to match the device ID in case there's a mount --move.
698 // We can't *rely* on it because some filesystems like btrfs will assign
699 // device IDs to subvolumes that aren't listed in /proc/self/mountinfo.
700
701 const QString oldRootPath = std::exchange(rootPath, QString());
702 const dev_t rootPathDevId = deviceIdForPath(oldRootPath);
703 for (auto it = infos.rbegin(); it != infos.rend(); ++it) {
704 if (!isParentOf(it->mountPoint, oldRootPath))
705 continue;
706 if (rootPathDevId == it->stDev) {
707 // device ID matches; this is definitely the best option
708 best = q20::to_address(it);
709 break;
710 }
711 if (!best) {
712 // if we can't find a device ID match, this parent path is probably
713 // the correct one
714 best = q20::to_address(it);
715 }
716 }
717 }
718 if (best) {
719 auto stDev = best->stDev;
720 setFromMountInfo(std::move(*best));
721 name = retrieveLabel(*this, fd, stDev);
722 }
723}
724
725QList<QStorageInfo> QStorageInfoPrivate::mountedVolumes()
726{
727 QList<QStorageInfo> volumes = listMounts();
728 if (!volumes.isEmpty())
729 return volumes;
730
731 std::vector<MountInfo> infos = parseMountInfo(FilterMountInfo::Filtered);
732 if (infos.empty()) {
733 volumes.append(root());
734 return volumes;
735 }
736
737 QStorageLabelRetriever labelForDevice;
738 volumes.reserve(infos.size());
739 for (auto it = infos.begin(); it != infos.end(); ++it) {
740 MountInfo &info = *it;
741 AutoFileDescriptor fd(info.mountPoint);
742
743 // find out if the path as we see it matches this line from mountinfo
744 quint64 mntid = mountIdForPath(fd);
745 if (mntid == 0) {
746 // statx failed, so scan the later lines to see if any is a parent
747 // to this
748 auto isParent = [&info](const MountInfo &maybeParent) {
749 return isParentOf(maybeParent.mountPoint, info.mountPoint);
750 };
751 if (std::find_if(it + 1, infos.end(), isParent) != infos.end())
752 continue;
753 } else if (mntid != info.mntid) {
754 continue;
755 }
756
757 const auto infoStDev = info.stDev;
758 QStorageInfoPrivate d(std::move(info));
759 d.retrieveVolumeInfo();
760 if (d.bytesTotal <= 0 && d.rootPath != u'/')
761 continue;
762 d.name = labelForDevice(d, fd, infoStDev);
763 volumes.emplace_back(QStorageInfo(*new QStorageInfoPrivate(std::move(d))));
764 }
765 return volumes;
766}
767
768QT_END_NAMESPACE
static QString retrieveLabel(const QStorageInfoPrivate &d, int fd, quint64 deviceId)
static constexpr short MountId
static quint64 retrieveDeviceId(const QByteArray &device, quint64 deviceId=0)
static auto doStatMount(QStorageInfoPrivate *d, const AutoFileDescriptor &fd, quint64 mountid, QStorageLabelRetriever &labelRetriever)
static const char MountInfoPath[]
static constexpr short MountPoint
static constexpr short MountSource
static constexpr short FieldCount
static constexpr short MountOptions
std::vector< MountInfo > doParseMountInfo(const QByteArray &mountinfo, FilterMountInfo filter)
static constexpr short FsType
static std::optional< dev_t > deviceNumber(QByteArrayView devno)
static std::optional< QString > retrieveLabelViaIoctl(int fd)
#define FS_IOC_GETFSLABEL
static constexpr short DevNo
Q_DECLARE_TYPEINFO(QStorageLabelRetriever::Entry, Q_RELOCATABLE_TYPE)
static bool doStatMount(QStorageInfoPrivate *d, const AutoFileDescriptor &fd)
#define ST_RDONLY
static quint64 mountIdForPath(int fd, unsigned mountIdType=0)
static QByteArray parseMangledPath(QByteArrayView path)
static constexpr short SuperOptions
static QDirListing devicesByLabel()
static constexpr short FsRoot
static std::vector< MountInfo > parseMountInfo(FilterMountInfo filter=FilterMountInfo::All)
static QString decodeFsEncString(QString decoded)
static void tokenizeLine(std::array< QByteArrayView, FieldCount > &fields, QByteArrayView line)
static dev_t deviceIdForPath(const QString &device)
#define FSLABEL_MAX
#define STATX_MNT_ID_UNIQUE