Phosphor
Qt6 / Wayland library suite for window-management tools
Loading...
Searching...
No Matches
PackPathGuard.h
Go to the documentation of this file.
1// SPDX-FileCopyrightText: 2026 fuddlesworth
2// SPDX-License-Identifier: LGPL-2.1-or-later
3
4#pragma once
5
6#include <QtCore/QDir>
7#include <QtCore/QFileInfo>
8#include <QtCore/QString>
9#include <QtCore/QStringList>
10
11#include <optional>
12
13namespace PhosphorFsLoader {
14
28
61[[nodiscard]] inline std::optional<QString> resolveWithinDirectory(const QString& declaredPath,
62 const QString& directory, AbsolutePathPolicy policy)
63{
64 if (declaredPath.isEmpty() || directory.isEmpty()) {
65 return std::nullopt;
66 }
67
68 const QDir dir(directory);
69 const bool wasAbsolute = QFileInfo(declaredPath).isAbsolute();
70 if (wasAbsolute && policy == AbsolutePathPolicy::Trust) {
71 // Cleaned like every other accepted return, so a trusted override cannot
72 // reach watch keys and path-keyed caches in two spellings of one file.
73 return QDir::cleanPath(declaredPath);
74 }
75 // `absoluteFilePath`, not `filePath`: a RELATIVE @p directory would otherwise
76 // yield a relative result, breaking both the documented return contract and
77 // the cache-dedupe rationale.
78 const QString resolved = wasAbsolute ? declaredPath : dir.absoluteFilePath(declaredPath);
79
80 const QString lexicalRoot = QDir::cleanPath(dir.absolutePath());
81 const QString canonicalRoot = QFileInfo(dir.absolutePath()).canonicalFilePath();
82
83 // Canonicalise as much of the target as EXISTS, then re-append the rest.
84 //
85 // A plain `QFileInfo(resolved).canonicalFilePath()` returns empty for a path
86 // whose leaf does not exist yet, and falling back to a purely lexical
87 // compare there fails OPEN: `pack/link/future.frag`, where `link` is a
88 // symlink out of the pack, is lexically inside and canonically outside, and
89 // the leaf not existing is exactly the live-reload case (the watcher arms on
90 // the path and the file materialises later). So walk up to the deepest
91 // existing ancestor, canonicalise THAT, and rebuild — which resolves every
92 // symlinked intermediate component even when the leaf is absent.
93 //
94 // The climb is PURE STRING WORK via `QFileInfo::absolutePath()`. It must not
95 // use `QDir::cdUp()`: that is `cd("..")`, which FAILS on a parent that does
96 // not exist, so it stops at the first missing component rather than at the
97 // deepest existing ancestor. With two or more missing components below a
98 // symlink (`pack/link/sub/future.frag`) the old loop bailed out to a lexical
99 // path and handed it to a CANONICAL root comparison — the exact domain mixing
100 // this function claims never to do, failing open on a real escape.
101 //
102 // Returns nullopt when NOTHING on the chain exists up to the filesystem root.
103 // That case fails CLOSED rather than degrading to lexical, because a lexical
104 // target compared against a canonical root is unsound in both directions.
105 const auto canonicalise = [](const QString& path) -> std::optional<QString> {
106 QString current = QDir::cleanPath(path);
107 QStringList tail;
108 // Bounded by the component count: each iteration strips exactly one, and
109 // `absolutePath()` of the filesystem root is the root itself, which ends it.
110 for (;;) {
111 const QString canonical = QFileInfo(current).canonicalFilePath();
112 if (!canonical.isEmpty()) {
113 // A canonical path holds no symlink in ANY component. When one
114 // does, Qt did not resolve it: up to 6.11 a self-referential
115 // CYCLE, and any path THROUGH one, came back as its own spelling,
116 // where 6.12 returns empty for it like any other unresolvable
117 // link. Refused here so both agree with the isSymLink() arm
118 // below, which is where 6.12 lands. A cycle can never be opened
119 // (ELOOP), so nothing usable is lost, and the verdict no longer
120 // depends on the Qt the library was built with. The whole chain,
121 // not just the leaf: for `loop/effect.frag` the leaf is not a
122 // link, its parent is. Bounded by the component count.
123 for (QString probe = canonical;;) {
124 const QFileInfo probeInfo(probe);
125 if (probeInfo.isSymLink()) {
126 return std::nullopt;
127 }
128 const QString probeParent = probeInfo.absolutePath();
129 if (probeParent.isEmpty() || probeParent == probe) {
130 break;
131 }
132 probe = probeParent;
133 }
134 if (tail.isEmpty()) {
135 return canonical;
136 }
137 // Cleaned, so a deepest-existing-ancestor of "/" does not produce
138 // a doubled separator.
139 return QDir::cleanPath(canonical + QLatin1Char('/') + tail.join(QLatin1Char('/')));
140 }
141 const QFileInfo info(current);
142 // PRESENT but unresolvable is NOT the same as absent, and conflating
143 // them is an escape of exactly the kind this climb was rewritten to
144 // close. `canonicalFilePath()` returns empty for a DANGLING symlink
145 // just as it does for a missing component, and from Qt 6.12 for a
146 // self-referential CYCLE too (older Qt is caught by the symlink
147 // check on the canonical result above — see
148 // refusesASymlinkCycleOnEveryQt in the tests).
149 // Without this the climb would treat a dangling link as
150 // "not there yet", prepend its name, and
151 // re-append it LEXICALLY onto the canonical root — mixing the two
152 // domains this function promises never to mix. A pack shipping
153 // `link -> /outside` while `/outside` does not exist yet would then be
154 // accepted, and the stored path resolves out of the pack the moment the
155 // target materialises. Nothing re-validates at that point either:
156 // QFileSystemWatcher cannot watch a non-existent path, so the
157 // materialisation fires no rescan.
158 if (info.isSymLink()) {
159 return std::nullopt;
160 }
161 const QString parent = info.absolutePath();
162 const QString name = info.fileName();
163 if (name.isEmpty() || parent.isEmpty() || parent == current) {
164 return std::nullopt;
165 }
166 tail.prepend(name);
167 current = parent;
168 }
169 };
170
171 // Never mix domains: compare canonical against canonical, and only fall back
172 // to lexical-vs-lexical when the ROOT itself cannot be canonicalised.
173 const bool useCanonical = !canonicalRoot.isEmpty();
174 QString target;
175 if (useCanonical) {
176 const auto canonicalTarget = canonicalise(resolved);
177 if (!canonicalTarget) {
178 return std::nullopt;
179 }
180 target = *canonicalTarget;
181 } else {
182 target = QDir::cleanPath(resolved);
183 }
184 const QString root = useCanonical ? canonicalRoot : lexicalRoot;
185
186 // `root + '/'` unless root already ends in one, so a directory of "/" does
187 // not become "//" and refuse everything.
188 const QString prefix = root.endsWith(QLatin1Char('/')) ? root : root + QLatin1Char('/');
189 if (target == root || !target.startsWith(prefix)) {
190 return std::nullopt;
191 }
192 // The CLEANED form, so `./x.frag` and `sub//x.frag` do not reach watch keys,
193 // content signatures and path-keyed caches as distinct strings for one file.
194 return QDir::cleanPath(resolved);
195}
196
197} // namespace PhosphorFsLoader
Definition ContainedFileReader.h:15
AbsolutePathPolicy
What to do with a declared path that is already absolute.
Definition PackPathGuard.h:16
@ Trust
Accept it unchecked.
Definition PackPathGuard.h:26
@ Reject
Do not trust it as-is: the path is still subject to the containment check, so only an absolute path t...
Definition PackPathGuard.h:22
std::optional< QString > resolveWithinDirectory(const QString &declaredPath, const QString &directory, AbsolutePathPolicy policy)
Resolve declaredPath against directory, refusing anything that lands outside it.
Definition PackPathGuard.h:61