Updated December 2, 2026 · every figure below was measured on the host described in Section 1 unless its table marks it as documented, and a table that counts runs says how many it used.
A deploy that has worked for months fails at three in the morning, and the log line is one sentence: OSError: [Errno 40] Too many levels of symbolic links. The path is short, the file exists, and the release directory has the shape the last ten releases had. What changed is rarely a chain someone built on purpose. The two shapes a deploy leaves behind are smaller: a link it wrote through instead of replacing, which becomes a one-hop loop, or a link it failed to replace at all, so the path still reaches the old release. A chain long enough to exhaust the budget is a different shape, and not one a deploy builds by accident: the chain measured in Section 3 is a ladder of forty-one links built side by side in one directory, the shape a generated tree leaves behind. One number ends both, and this page measures them apart.
The kernel’s answer is a budget, not a length. It counts symlink traversals while it resolves one path, and when the count passes its ceiling it stops with errno 40 and the message “Too many levels of symbolic links”. On the host this page measured, 40 traversals resolve and the 41st is refused. Every arm below ran five times.
TL;DR — The ceiling is 40 traversals per resolution, and the 41st is refused. The budget is spent across the whole path, split between directories and charged per traversal rather than per link object. O_NOFOLLOW on a symlink returns the same 40 as an over-long chain, while O_NOFOLLOW|O_DIRECTORY on the same link returns 20. Python’s exists() reports both refusals as absence, and realpath resolves a chain the kernel refuses.
Fix It First: Ten Changes, Matched to What You Saw
The first column is what the failing call or the exit status shows; the second is the cheapest check that separates this cause from the other three; the third is the change that stops it from returning.
| What you saw | First check | Change that ends it |
|---|---|---|
open() returns ELOOP and the path is short | count the traversals with count_links() | flatten the chain: one link to a versioned directory, not a link to a link |
A deploy exited 0 but current still names the old release | readlink current, and look for links inside the old release | replace the link instead of writing through it (ln -sfn), then delete what the earlier deploys left behind |
open(path, O_NOFOLLOW) returns ELOOP for a path you thought was a file | lstat the final component | the final component is a link; remove it or stop asking for O_NOFOLLOW |
open(path, O_NOFOLLOW|O_DIRECTORY) returns ENOTDIR | check what the link points at | the final component is a link: resolve it yourself, or drop O_NOFOLLOW if you meant to follow it |
find -L exits 1 with “File system loop detected” | run find without -L once | drop -L, or prune the looping directory with -prune |
cp -rL refuses with “cyclic symbolic link” | compare with cp -a | copy links as links (-a) and dereference only the paths you chose |
tar -c -h dies with a signal instead of an error | run tar -c without -h | do not hand -h a tree that contains a loop; exclude the path |
os.path.exists() says the file is missing | os.stat() the same path and read the errno | treat ELOOP as an error, not as absence; a health check must not pass on it |
realpath() returns a path that open() refuses | compare the hop count with the budget | count the traversals only to explain it; let the open carry the refusal (O_NOFOLLOW on one name, or openat2 with RESOLVE_BENEATH|RESOLVE_NO_SYMLINKS beneath a pinned descriptor, and a component-by-component openat walk only where the syscall is not answered) and never trust the resolver’s answer as proof |
| A ConfigMap mount fails with ELOOP (documented Kubernetes shape) | the ..data link is the documented shape, not a fault | do not dereference the mount with -L; read the projected files directly |
Why this table starts with a count and not a flag
Every row is one of four causes: a chain over the budget, a final component that is a link, a directory that contains itself, or a magic link. The count is the only check that separates all four, which is why the list opens with it. What ends the failure is in the third column: a flag, or a descriptor held open in the call itself. The two jobs are different, and a count one syscall old decides nothing.
1. The Refusal, and the Four Things It Can Mean
Linux resolves a pathname one component at a time. A symlink in the middle or at the end is not an error: it is a substitution, and the kernel continues with the link’s target. To stop a pair of links that point at each other, the resolver carries a counter, and when the counter runs out the call fails with ELOOP. The counter is what makes the refusal mean four different things, because it is spent by four different situations.
- a chain of links longer than the budget, built link to link until one resolution spends it;
- a single link reached over and over inside one path, such as a directory that contains itself through a link to
.or..; - a final component that is a link, when the caller asked not to follow one with
O_NOFOLLOW; - a magic link, such as the entries under
/proc/self/fd, when the resolution was told not to follow magic links.
The four are not distinguishable from the errno, but they are distinguishable from three facts the caller can collect without guessing: how many traversals the path actually spends, whether the chain revisits a link, and which flags the failing call used. The rest of this page measures each of those on one host, then puts them behind a small module so a service can answer the question in a log line instead of in a debugger.
The deploy that makes it
A release layout is one directory of versions and one link that names the live one. Both commands below exit zero and both look right in a deploy log; only one of them makes current name the release that was just built. Each row ran five times on a fresh tree, and every arm answered the same way in all five.
| What was run | What the call answered | What current served |
|---|---|---|
ln -sf v2 current | exit 0; current/v2 answers 40 | releases/v1 |
| the same command a second time | exit 0; unchanged | releases/v1 |
ln -sf $APP/releases/v2 current | exit 0; current/v2 serves v2 | releases/v1 |
ln -sfn releases/v2 current | exit 0; 1 link | releases/v2 |
count_links(), then a deploy swaps the link, then open() | 1 link to v1 | v2 |
the same swap, openat2 with RESOLVE_NO_SYMLINKS | 40 | refused |
the same swap, open with O_NOFOLLOW | ok | v2 |
the same swap, current opened once as a directory descriptor and openat(dirfd, "conf/settings") | v1 from both calls | v1 |
The first three rows exit zero and change nothing. ln treats the existing current as a directory, because that is what it links to, so it writes the new link inside the old release. With a relative target the link it writes is releases/v1/v2, and that name, resolved from inside releases/v1, is the link itself: a one-hop loop that answers 40 to anything that opens it. With an absolute target nothing loops, which is the quieter failure: current keeps serving v1, and the deploy log says the new version is live.
None of those three rows produces a forty-one-link chain, and row two says why: running ln -sf again writes the same stray link a second time and changes nothing. The measured accident is a one-hop loop or a stale release. A chain that long is a different shape — a ladder built in one step, not a link added per release — and Section 3 measures it one hop at a time. The two causes share the number and no mechanism, which is why Table 1’s first row asks for a count before it recommends flattening anything.
ln -sfn replaces the link instead of writing through it, which is the only difference between rows three and four. Rows five to eight belong to Section 8: the first three show what a count, a mask and a flag each do once the link has moved, and the last one holds the old release open by its descriptor so the move cannot matter.
| Condition | Value on this host |
|---|---|
| Kernel | Linux 6.12.118-guest-1.2 (x86-64), 2 vCPU |
| Python | 3.12.16 (CPython, glibc build) |
| Temporary root | /tmp on tmpfs, page size 4,096 B |
| Working tree | /workspace on virtiofs |
| Path ceiling | PC_PATH_MAX 4,096 B |
| Link ceiling exposed | getconf SYMLOOP_MAX undefined; pathconf(PC_SYMLINK_MAX) -1 |
| Shell tools | ls (GNU coreutils) 9.7, find (GNU findutils) 4.10.0, tar (GNU tar) 1.35 |
| Repeats | 5 per arm, one fresh tree per round |
The link ceiling is documented as 40 in the kernel source, but this host does not expose it: getconf SYMLOOP_MAX prints undefined and pathconf(PC_SYMLINK_MAX) returns -1. That is why the ceiling below is measured rather than quoted, and why the package states it once instead of asking the platform.
2. One Number, Eighteen Calls
Eighteen calls were made five times each, 90 calls in total, and every arm answered the same way in all five runs. Seven of the eighteen ended in ELOOP, and the other eleven are here because they are what an operator confuses with it.
| Call on this host | Answer | Why |
|---|---|---|
open() a 41-link chain | ELOOP | the budget case: 41 traversals |
open() a 40-link chain | ok | the same shape, one hop shorter |
os.stat() a 41-link chain | ELOOP | stat follows the final link, so it pays the budget |
os.lstat() a 41-link chain | ok | lstat stops at the link and reports it |
listdir() of a directory that links to itself | ELOOP | opening the directory spends the budget |
open() a child below the pair a → b → a | ELOOP | the loop is in an intermediate component |
open() a link to a file with a trailing slash | ENOTDIR | the trailing slash demands a directory |
open() a child below a link to a file | ENOTDIR | a file cannot be a parent component |
open() a missing name | ENOENT | absence, not a loop |
open() a dangling link | ENOENT | the link exists, its target does not |
os.access() a 41-link chain | False, silently | access swallows the refusal |
mkdir() over a link to a directory | EEXIST | the link points at a directory that already exists |
open() a link with O_NOFOLLOW | ELOOP | a one-hop chain refused by a flag |
unlink() the link itself | ok | removing a link resolves nothing |
openat2() a clean file | ok | the syscall is available here |
openat2() a link, RESOLVE_NO_SYMLINKS | ELOOP | any link in the path is refused |
openat2() an intermediate link, same mask | ELOOP | the flag covers every component, not only the last |
openat2() an absolute path, RESOLVE_BENEATH | EXDEV | a refusal that is not about links at all |
Two rows in that table matter more than the rest. lstat never returns ELOOP: it reports the link instead of resolving it, which is what makes a count possible at all. And os.access returned False rather than an error, which is the shape of the bug in Section 6: a readiness probe built on access or exists reports a broken deployment as an empty directory.
Where the Number Comes From
The same failure has a different number on other systems, and a runbook that quotes the Linux number to a macOS user sends them looking for the wrong constant. Two values matter and they are not the same value: how many traversals one resolution may follow, and what number the refused call returns. The table keeps them apart. Only the Linux row was measured here; the other three are quoted from each platform’s own headers and say so.
| Platform | Hop limit per resolution | What a refusal returns | Basis |
|---|---|---|---|
| Linux | 40 (measured here) | 40 — Too many levels of symbolic links | measured on this host |
| macOS (XNU) | 32 (MAXSYMLINKS) | 62 | documented in bsd/sys/param.h and the errno table |
| FreeBSD | 32 (MAXSYMLINKS) | 62 | documented in sys/param.h |
| Windows | 63 reparse points | 1921 ERROR_CANT_RESOLVE_FILENAME; WSAELOOP 10062 | documented by Microsoft (Reparse Points, Programming Considerations) |
The two middle columns answer different questions. A hop limit says how many links one resolution may follow: macOS and FreeBSD stop at 32 traversals and report 62, so a Linux runbook’s 40 is wrong twice over on a Mac. Windows counts 63 reparse points and reports 1921, and Microsoft’s own page adds that the limit falls to 31 when a reparse point targets a fully qualified path, so the larger number is a ceiling and not a promise. The number in the title is the third column.
On Linux the message is the one in the title because strerror(40) returns “Too many levels of symbolic links”, and that string is what every log line, every Coreutils diagnostic and every Python OSError repeats. The number is not the ceiling; the ceiling is the thing the next section measures.
3. The Forty-Hop Budget, Measured
The ladder below is seven chains, from a length too short to fail to the two that do. Each chain ends at the same regular file, each was built fresh in every round, and each was opened once per round, five rounds in total.
| Chain length | Answer | Path bytes |
|---|---|---|
| 36 links | ok | 42 B |
| 37 links | ok | 42 B |
| 38 links | ok | 42 B |
| 39 links | ok | 42 B |
| 40 links | ok | 42 B |
| 41 links | ELOOP | 42 B |
| 42 links | ELOOP | 42 B |
The break sits exactly at the documented 40: a chain of 40 traversals opens, and 41 fails. The path that fails is 42 bytes long, against a PATH_MAX of 4,096, so nothing about the length of the string is involved. What ran out is the counter, and the next table shows what spends it.
| Spent on | Answer | Path bytes | What it shows |
|---|---|---|---|
| One chain, 40 links, absolute targets | ok | 42 B | an absolute link costs one traversal, like a relative one |
| One chain, 41 links, absolute targets | ELOOP | 42 B | the ceiling does not care how a link is written |
| 20 links in one directory, 20 in the next | ok | 50 B | one path, one budget, split across two directories |
| 20 links in one directory, 21 in the next | ELOOP | 50 B | the two directories share the counter |
| 40 links under 12 real directories | ok | 83 B | real directories are walked, not counted |
40 traversals of one link to . | ok | 245 B | one link object, forty visits |
| 41 traversals of the same link | ELOOP | 250 B | the counter counts visits, not objects |
The distinction in the last two rows is the one that costs people an afternoon. A pair of links that point at each other, a directory that links to its own parent, and a single link to . reached forty times all spend the same counter, because the kernel counts traversals and not distinct links. The chain in Table 6 has forty-one different links; the path in Table 7 has one, and both stop at the same number.
A userspace resolver is not bound by the counter
The ceiling applies to one path resolution, and a call such as realpath resolves each component with its own syscall. That is why the same chain that open refuses can be resolved to its target by realpath, and why “realpath worked” is not evidence that the path is usable. Section 6 measures the difference, and Section 8 turns it into a check.
| Resolution | Median per call (min–max of five rounds) | Median ns |
|---|---|---|
| 0 links | 1.04 µs (1.01–1.09) | 1,039 ns |
| 10 links | 1.51 µs (1.50–1.53) | 1,512 ns |
| 20 links | 1.93 µs (1.92–1.97) | 1,928 ns |
| 30 links | 2.38 µs (2.34–2.45) | 2,376 ns |
| 40 links | 2.79 µs (2.78–2.82) | 2,793 ns |
41 links, realpath(strict=True) | 144.25 µs (143.80–145.59) | 144,247 ns |
Each extra hop costs about 43.85 ns on this host, so forty hops cost 2.69 times what a direct open costs. The userspace resolver is a different order of magnitude: 144,247 ns against 1,039 ns, 138.8 times one open, because it makes a syscall per component instead of leaving the walk to the kernel. That is cheap enough to run before an open on a health check and too expensive to run on every request, where the single open, given the right flag, is both the check and the use (Section 8).
4. The Flag That Decides
The same symlink answers differently depending on the flags of the call. The matrix below runs every combination that matters for extraction, deployment and static file serving, five times each, on one tree.
| Call | Answer | What decided it |
|---|---|---|
regular file, O_RDONLY | ok | the file itself |
regular file, O_NOFOLLOW | ok | the flag only refuses links |
link to file, O_RDONLY | ok | the link is followed |
link to file, O_NOFOLLOW | ELOOP | refused at the final component |
link to file, O_PATH | ok | follows, gives a path descriptor |
link to file, O_PATH|O_NOFOLLOW | ok | a descriptor on the link itself |
link to file, O_NOFOLLOW|O_DIRECTORY | ENOTDIR | the link is not followed, and a link is not a directory |
link to file, O_DIRECTORY | ENOTDIR | a file is not a directory |
link to directory, O_RDONLY | ok | the link is followed |
link to directory, O_NOFOLLOW | ELOOP | still a final-component link |
link to directory, O_NOFOLLOW|O_DIRECTORY | ENOTDIR | the same reason, even though the target is one |
| child below a link to a directory | ok | an intermediate link is still followed |
child below a link, O_NOFOLLOW | ok | the flag applies to the final component only |
O_CREAT|O_EXCL over an existing link | EEXIST | exclusive create does not follow |
openat2 regular file, mask 0 | ok | the syscall is available |
openat2 regular file, RESOLVE_NO_SYMLINKS | ok | no link in the path |
openat2 final link, RESOLVE_NO_SYMLINKS | ELOOP | the mask refuses the link |
openat2 intermediate link, same mask | ELOOP | every component is covered |
openat2 a link, RESOLVE_BENEATH, absolute path | EXDEV | an absolute path is refused before it is resolved |
openat2 a regular file, same mask, absolute path | EXDEV | the refusal is about the path, not about links |
openat2 a relative name under a dirfd, same mask | ok | inside the descriptor’s tree, the mask permits it |
openat2 ../file under that dirfd, same mask | EXDEV | the path would climb out of the tree |
openat2 absolute path, RESOLVE_IN_ROOT | ENOENT | the path is re-rooted and no longer exists |
openat2 a file through /proc/self/fd, mask 0 | ok | a magic link is followed by default |
the same path, RESOLVE_NO_MAGICLINKS | ELOOP | magic links are refused |
Three rows repay a second read. O_NOFOLLOW|O_DIRECTORY returns 20 rather than 40, even on a link to a directory: the link is not followed, and what the directory flag then sees is a symlink, so a pipeline that greps for ELOOP reports a missing directory instead. O_PATH|O_NOFOLLOW gives a descriptor whose /proc/self/fd entry is the link itself, which is how the magic-link case in Section 5 is built. And RESOLVE_BENEATH answers with EXDEV for a reason that has nothing to do with filesystems.
What EXDEV means when nothing moved between filesystems
RESOLVE_BENEATH refuses any resolution that would leave the directory the descriptor names: an absolute pathname, or a .. that climbs above it. It answers with 18 in both cases, which is the number a cross-device rename also returns, so a handler that maps EXDEV to “copy then delete” will do the wrong thing with a flag error. A relative name inside a real dirfd is accepted, which is the case worth testing before shipping the mask.
5. Loops the Chain Cannot Explain
A loop is not a chain that grew long. It is a path that keeps returning to a link it has already visited, and the kernel treats it exactly like a long chain: it keeps counting until the budget is gone. The arms below put the loops in different places, and add the one case that is not a link chain at all: the magic link under /proc/self/fd.
| Loop | Answer | What it shows |
|---|---|---|
link to itself, open() | ELOOP | a loop is spent like a chain |
link to itself, lstat() | ok | reports a 6-byte link |
link to itself, readlink() | ok | returns its own name |
a → b → a, open() | ELOOP | two links, one loop |
a → b → a, stat() | ELOOP | stat follows |
a → b → a, lstat() | ok | stops at the first link |
a → b → a, readlink() | ok | returns the next name, not a resolution |
link to . reached 40 times | ok | 245 B path |
| the same link reached 41 times | ELOOP | the counter again |
link to .. reached 40 times | ok | climbing is traversal too |
| the same climb reached 41 times | ELOOP | and it is counted the same way |
open() through a loop to ../file | ELOOP | the loop is in an intermediate component |
listdir() of the top directory | ok | the top itself resolves |
/proc/self/fd of a link descriptor | ELOOP | the magic link re-follows the link |
/proc/self/fd of a file descriptor | ok | nothing to re-follow |
readlink() of that magic link | ok | returns the link’s own path |
openat2 the same, RESOLVE_NO_MAGICLINKS | ELOOP | the mask refuses the magic link |
The first row is the one that breaks the mental model of “too many links”. A single link that points at itself fails, and a naive count of the links in the directory finds one. The kernel is not counting distinct links; it is counting the traversals it has performed, and a loop will perform them until the budget is exhausted. That is why a diagnostic has to detect the revisit, not the length.
The magic-link rows explain a class of container and supervisor bugs that never mention symlinks. O_PATH|O_NOFOLLOW on a link gives a descriptor whose /proc/self/fd entry names the link, and opening that entry resolves it again, so a child that is handed the path builds a loop out of two correct-looking calls. Passing the descriptor avoids the resolution entirely.
The package calls this a cycle after one traversal
The kernel has no cycle detector in this path: it counts to the budget and stops. The module in Section 8 keeps the identities it has visited inside one resolution, so a link that comes back to itself is reported as a cycle on its first revisit rather than after 40 traversals. Both statements are true; they answer different questions.
6. What Python Does With the Same Refusal
Python is where the refusal stops looking like a refusal. The same 41-link chain is an exception for some calls, False for others, and a resolved path for the rest. Twenty-one arms, five runs each, one fresh tree per round:
| Call on the same 41-link chain | Answer | What it means |
|---|---|---|
open() | ELOOP | the kernel answer, unchanged |
os.stat() | ELOOP | follows, so it pays |
os.lstat() | ok | reports the link, size in bytes |
os.path.exists() | False, silently | swallows the error |
os.path.isfile() | False, silently | swallows the error |
os.path.isdir() | False, silently | swallows the error |
os.access() | False, silently | swallows the error |
os.path.realpath() | ok | resolves in userspace |
realpath(strict=True) | ok | still resolves; no exception |
Path.exists() | False, silently | same swallow, newer API |
Path.stat() | ELOOP | raises |
Path.resolve() | ok | userspace |
Path.resolve(strict=True) | ok | userspace |
Path.read_text() | ELOOP | raises |
os.listdir() of a loop | ELOOP | opening the directory pays |
os.walk(), links not followed | ok | 1 directory |
os.walk(), links followed | ok | 161 directories, then silence |
Path.glob('**/*') | ok | 2 entries, none inside the linked directory |
shutil.rmtree() | ok | removes links, never follows |
shutil.copytree(symlinks=True) | ok | 2 entries, the link copied as a link |
shutil.copytree(symlinks=False) | RecursionError | follows until Python’s own limit |
Of those rows, five return False, and they are the rows a health check is most likely to use. A probe that asks os.path.exists(release_link) cannot tell “the release was never deployed” from “the release link is one hop too deep”, and a supervisor that restarts on a failed check restarts forever without ever reporting the number. os.stat() with the errno caught costs one line and turns the silence into a message. The opposite surprise is in the same table: realpath(), Path.resolve() and resolve(strict=True) all returned the target of a chain the kernel refuses.
os.walk(followlinks=True) stopped after 161 directories and said nothing, against 1 directory when links are not followed. The number is not a constant of the kernel; it is how far the walk got on this tree before a scandir returned ELOOP and the generator swallowed it. The point is the silence, not the count: a crawler that follows links can walk a large multiple of the real tree and stop at an unpredictable depth, and glob and copytree answer with their own counts for the same tree.
Why copytree raises RecursionError and not ELOOP
copytree(symlinks=False) resolves each link in userspace and recurses into the result, so it builds deeper and deeper Python frames until the interpreter’s own recursion limit fires. The errno never appears; the traceback names copytree. A handler that catches OSError will not catch it, and a test that asserts ELOOP will pass on the wrong call.
7. What the Shell Tools Do
A deploy script rarely calls open directly. It calls cp, tar, find and readlink, and those tools do not agree about what a link is. The table below runs fourteen commands against one tree that contains all three loop shapes: a link to itself, a directory that links to its parent, and a chain one hop too long.
| Command | Exit | What it did |
|---|---|---|
ls -l the self-link | 0 | prints the link and its target |
ls -lL the self-link | 2 | “cannot access … Too many levels” |
stat the self-link | 0 | reports a symbolic link |
stat -L the self-link | 1 | “cannot statx … Too many levels” |
readlink -f the 41-link chain | 0 | prints the target: userspace resolution |
realpath -e the self-link | 1 | refuses with the same message |
realpath -m the self-link | 0 | prints the unresolved path |
find without -L | 0 | the loop is an entry |
find -L the tree | 1 | three messages: two refusals, one loop |
cp -r the tree | 0 | copies links as links |
cp -rL the tree | 1 | “cannot copy cyclic symbolic link” |
tar -c the tree | 0 | stores links as links |
tar -c -h the tree | 139 | dies with a signal after 9,877–9,883 diagnostics |
du -sL the tree | 1 | two refusals, then a partial total |
readlink -f and realpath -m exit zero on paths that no other tool can use, because both resolve in userspace; a pre-flight check built on either passes a path to cp that cp refuses. And tar -c -h does not fail with a message at all: on this host’s GNU tar 1.35 it died with signal 11, which a shell reports as exit status 139, after 9,877 to 9,883 lines naming the same loop as the recursion deepened.
find -L is the honest one: it exits non-zero and prints “Too many levels of symbolic links” for the link and “File system loop detected” for the directory that contains its parent. Those are the only two sentences in the table that name a cause instead of a symptom, and a log pipeline still has to know both in advance.
The three commands worth keeping in a runbook
# Count the traversals before an open does it for you.
python3 - <<'PY'
import os
path, hops = '/srv/app/current', 0
while os.path.islink(path):
target = os.readlink(path)
path = target if target.startswith('/') else os.path.join(os.path.dirname(path), target)
hops += 1
if hops > 100:
raise SystemExit('a loop, not a chain')
print(hops, 'hops ->', path)
PY
# Every link in a release directory, with its target.
find /srv/releases -maxdepth 2 -type l -printf '%p -> %l\n'
# Archive without dereferencing: links are stored, not followed.
tar -czf app.tgz -C /srv app
8. pathguard: Let the Open Decide, Count to Explain
The module on this page turns the four causes into four answers. Three of its entry points work in userspace, where a chain can be described instead of merely refused; four decide at the open itself, because a count one syscall old is already history; and one turns whichever refusal arrives into a sentence. The table is the surface a caller reaches for, in the order this page argues for it, and the five files behind it are printed in Appendix A rather than quoted twice here.
| Entry point | What it answers | Where the answer comes from |
|---|---|---|
count_links(path, max_links) | how many traversals a path spends, where it stopped, and whether it looped | lstat and readlink, one component per call |
resolve_bounded(path, max_links) | the same chain, followed link by link to the path it names | the same two calls, without asking the kernel to resolve it |
walk_bounded(root, follow_symlinks) | a tree in which a cycle is named once and never entered twice | descriptor identity for every directory entered |
open_no_follow(path, flags) | the file, or a refusal that carries the number of links it measured | O_NOFOLLOW in the call that opens it |
pin_dir(path) | a descriptor a later swap of the link cannot redirect | one open of the link, kept as a directory descriptor |
open_pinned(dirfd, name) | one name beneath the pin, with a link in that name refused | O_NOFOLLOW on the last name of a one-component call |
open_beneath(dirfd, rel_path) | a whole relative path beneath the pin, with every link refused | openat2 with RESOLVE_BENEATH|RESOLVE_NO_SYMLINKS in one syscall, and the component walk only where that syscall is not answered |
explain(exc, flags) | one log sentence naming the cause the errno and the flags support | the number, the flags, and the message |
The budget is a parameter, not a hard-coded belief, so a resolver can stop before the kernel does and report the count it reached. The default is the 40 this host measured, because a check that refuses earlier than the kernel would reject paths that work.
Each component is lstat-ed, so a link is reported rather than followed, and readlink supplies the target that becomes the next component. A repeated state is a loop and is named as one; a path that passes the budget is BudgetExceeded with the count attached. Neither case needs the kernel to fail first.
The walk keeps the identity of every directory it has entered, so a link back to a parent is reported once and never entered twice. open_no_follow adds O_NOFOLLOW itself rather than trusting the caller to remember it, and when the kernel refuses it re-raises the refusal with the number of links the path measured, which is the difference between “a link” and “a chain of 41” in an incident channel.
Pinning a directory, and placing a name beneath it
Rows seven and eight of Table 2 measure the calls the package ships as functions, because a rule that lives only in prose is a rule every caller implements a little differently. pin_dir is the first and the smallest: it opens the live directory once, with O_DIRECTORY, and returns the descriptor. After a deploy replaces current, that descriptor still names the release it named when the call was made.
import os
_O_CLOEXEC = getattr(os, "O_CLOEXEC", 0)
def pin_dir(path: str | os.PathLike[str], flags: int = os.O_RDONLY) -> int:
"""Open ``path`` as a directory and return the descriptor, which no later swap can redirect.
The final component may be a link - pinning ``current`` is the case this exists for - and the
descriptor names the directory that link pointed at when the call was made. ``O_DIRECTORY``
keeps a file from being pinned by mistake. The caller closes the descriptor.
"""
return os.open(path, flags | os.O_DIRECTORY | _O_CLOEXEC)
open_pinned takes one name beneath that descriptor and adds O_NOFOLLOW itself, so a caller cannot forget the flag that is the whole point of the call. One name is not a path, and that limit is exactly where archive extraction goes wrong: the flag covers the last component of the call it is given, so an openat of a/passwd refuses a link called passwd and follows a link called a.
open_beneath closes that hole with one syscall where the kernel has it. openat2 with RESOLVE_BENEATH|RESOLVE_NO_SYMLINKS resolves the whole relative path inside the kernel, so a link anywhere on the way is refused before anything is followed and a path that would leave the descriptor’s directory is refused as well. Only a kernel that does not answer the syscall falls back to a component walk, which opens each directory with O_NOFOLLOW|O_DIRECTORY and the last name with O_NOFOLLOW; the two implementations share one contract and the fallback is what runs on an older host, not what runs first.
The refusal keeps the number the call produced instead of flattening everything to one errno: 40 from openat2 for a link, 18 for a path that would leave the descriptor’s directory, and 20 from the component walk, because O_NOFOLLOW|O_DIRECTORY on a link answers ENOTDIR — the seventh row of Table 9, arriving in a walk instead of in a single call. A bad argument is a different matter from a refusal: an empty path, a double slash, a bare . or a trailing slash is the caller’s mistake and raises ValueError, while only a path that actually leaves the directory — an absolute path, or one with a .. component — raises RootEscape with the number openat2 answers for it.
The count is a diagnosis, not a lock. Rows five to eight of Table 2 measure the window: count_links() named releases/v1, a deploy replaced the link, and the open that followed read releases/v2. The count was right about the path when it looked and wrong one syscall later — the time-of-check to time-of-use gap, which no userspace pre-count closes. A call that resolves and opens together does. O_NOFOLLOW refuses a final component that is a link and leaves an intermediate one alone, which is why row seven still served the new release; openat2 with RESOLVE_NO_SYMLINKS refuses the whole path in the syscall that would have used it, and answered 40 in row six. On a layout where the live path is itself a link, that mask refuses a request that is entirely normal, which is why the package’s own answer to that case is a descriptor rather than a mask: pin current once, then reach every name beneath it with open_beneath, whose RESOLVE_BENEATH names the directory the descriptor holds as the root the path may not leave. Row eight holds that descriptor across the swap, and both openat(dirfd, "conf/settings", O_NOFOLLOW) and an openat2 with RESOLVE_BENEATH read v1 after current had already moved to releases/v2.
So the rule has two halves: count to explain a refusal, and let the open decide. Count before you open on a health check, where the diagnosis is the point and nothing acts on it but a log line. On a path a deploy or another process can rewrite, put the refusal in the flags of the open itself, or hold the directory open once and open names beneath the descriptor, because a count one syscall old is already history. What the module must never do is let exists() decide that a refused path is an empty one.
The behaviours above are pinned by tests in test_pinned.py, printed with the rest in Appendix A. Three of them perform a swap between the pin and the open and read the old release: one with open_pinned, one with openat2, and one with the component walk forced by removing the syscall. Two plant a link to a directory outside the root and require a refusal from each implementation. One shows the call this replaces succeeding through that link, so the hole is measured rather than asserted. One checks that the descriptor the caller passed is still open afterwards. Four hold the interface steady: a format error is a ValueError and never a RootEscape, every .. is a RootEscape, a host without the syscall answers ENOSYS and still walks the path, and the syscall number is asked for only on Linux and only by architecture.
The example this page runs
The file below builds its own tree in a temporary directory and prints seven lines, so a reader can compare their host’s answers with the ones in the tables without installing anything but the package.
"""Run the page's claims against a tree the example builds itself.
python3 eloop_demo.py
It prints seven lines: the count for a 40-link chain, the kernel's refusal at 41, the count the
package gives for the same path, the two kinds of loop the bounded walk reports, the refusal of
``open_no_follow`` on a link, and the sentence ``explain`` writes for it.
"""
from __future__ import annotations
import os
import tempfile
from pathguard import PathRefusal, count_links, explain, open_no_follow, walk_bounded
def chain(root: str, hops: int) -> str:
os.makedirs(root)
with open(os.path.join(root, "target"), "w") as handle:
handle.write("x")
for index in range(hops):
target = f"l{index + 1}" if index < hops - 1 else "target"
os.symlink(target, os.path.join(root, f"l{index}"))
return os.path.join(root, "l0")
def main() -> None:
with tempfile.TemporaryDirectory() as work:
forty = chain(os.path.join(work, "forty"), 40)
over = chain(os.path.join(work, "over"), 41)
print("40-link chain, package:", count_links(forty).summary())
try:
os.close(os.open(over, os.O_RDONLY))
except OSError as exc:
print("41-link chain, kernel:", exc.errno, exc.strerror)
print("41-link chain, package:", count_links(over).summary())
tree = os.path.join(work, "tree")
os.makedirs(os.path.join(tree, "sub"))
open(os.path.join(tree, "file"), "w").close()
os.symlink("..", os.path.join(tree, "sub", "up"))
os.symlink("selfme", os.path.join(tree, "selfme"))
entries = list(walk_bounded(tree, follow_symlinks=True))
refusals = [(entry.path.rsplit(os.sep, 1)[-1], entry.refusal)
for entry in entries if entry.refusal]
print("bounded walk, real directories:",
sum(1 for entry in entries if entry.is_dir and not entry.refusal))
print("bounded walk, refusals:", sorted(refusals))
try:
open_no_follow(os.path.join(tree, "selfme"))
except PathRefusal as exc:
unit = "link" if exc.links == 1 else "links"
print("open_no_follow: errno", exc.errno, "after", exc.links, unit)
print("explain:", explain(exc, flags=os.O_NOFOLLOW))
if __name__ == "__main__":
main()
40-link chain, package: file after 40 links: …/forty/l0 -> …/forty/target
41-link chain, kernel: 40 Too many levels of symbolic links
41-link chain, package: 41 links, over the 40-link budget: …/over/l0
bounded walk, real directories: 2
bounded walk, refusals: [('selfme', 'eloop'), ('up', 'cycle')]
open_no_follow: errno 40 after 1 link
explain: a final component that is a symlink, refused because the open asked not to follow one; the existing link is the bug, not the path length
The suite behind it is 59 tests in four files, printed whole in Appendix A. Every probe that produced a figure on this page is printed in Appendix B, including the helper they import, so the numbers can be re-run rather than believed.
Three sibling runbooks cover the refusals this page does not: errno 11, where a non-blocking write finds the last bytes that fit; errno 12, where a mapping ceiling and three limits answer with one number; and a bad descriptor, where three families of bug arrive as one number. Each is the same shape as this one: one number, several writers, and a measurement that tells them apart.
Questions This Page Answers
Is the limit 40 links or 40 traversals per path?
The budget counts traversals, not links: 40 in one resolution succeed and 41 fail, whether the links form one chain, sit in two directories, or revisit one link object.
Why did a 42-byte path fail when PATH_MAX is much larger?
Because the counter counts symlink traversals, not bytes. The path in Table 6 is 42 bytes and fails with the budget spent, while a path of 83 bytes under twelve real directories opens.
Does lstat ever return ELOOP?
No. It reports the link itself, which is what makes counting possible. Every arm that called lstat on a 41-link chain, a self-link or a loop returned a result in five runs out of five.
Which call answers ENOTDIR instead of ELOOP?
Three cases: a trailing slash on a link to a file, a child below a link to a file, and O_NOFOLLOW|O_DIRECTORY on a link. All three returned 20 on this host, so a grep for the ELOOP message misses them.
Is the number the same on macOS?
No, and two things differ. macOS and FreeBSD allow 32 traversals and report 62; Windows allows 63 reparse points and reports 1921, and the allowance falls to 31 when the target is a fully qualified path. Only the Linux pair was measured here.
Can one symlink cause ELOOP by itself?
Yes, in two ways. A link that points at itself is a loop, and a link opened with O_NOFOLLOW is refused as a final component. Both are one link and one ELOOP.
Why does os.path.exists() return False for a path that is there?
Python’s path checks swallow OSError and report the path as absent. os.stat() raises instead, which is the behaviour a health check wants: an ELOOP is a broken link, not an empty directory.
Why does realpath succeed where open fails?
realpath resolves one component per syscall, so no single call exceeds the budget; it resolved the 41-link chain in 144,247 ns (144.25 µs) against 1,039 ns for one open, 138.8 times the work. Success there does not mean the path can be opened.
Is O_NOFOLLOW enough for safe archive extraction?
Only for the last component of the call it is given, and a pinned descriptor does not change that by itself. It refused the final link and still followed an intermediate one, five runs out of five, and openat(rootfd, "a/passwd", O_NOFOLLOW) follows a in exactly the same way. Two calls close it: openat2 with RESOLVE_BENEATH and RESOLVE_NO_SYMLINKS, which decides the whole relative path in one syscall, or a walk that opens every directory with O_NOFOLLOW|O_DIRECTORY and only the last name with O_NOFOLLOW. This page’s open_beneath() is that pair the other way round: the single syscall first, and the walk only where the kernel does not answer it (Section 8).
Why did tar -h die instead of printing an error?
On this host’s GNU tar 1.35 it died with signal 11 after printing 9,877 to 9,883 diagnostics, in five runs out of five. Archive without -h, or exclude the looping path.
Does find -L stop at the first loop?
No. It exits non-zero and reports every loop it meets, with one message for a link chain and another for a directory that contains its parent.
What is the shortest fix that holds?
Count the traversals to learn which of the four causes you have, then make the open carry the refusal: O_NOFOLLOW if the final component must not be a link, RESOLVE_NO_SYMLINKS if no component may be one, and for a live path that is itself a link, pin it once as a directory descriptor and reach every name beneath it with open_beneath. Keep exactly one link in the release layout — one link to a versioned directory, never a link to a link — so the budget is never a design assumption. A count alone decides nothing when the link can move between the count and the open.
The one-line version
ELOOP is a budget of 40 symlink traversals per resolution, and every repair starts by counting how many the failing path spends. Four causes, one number, and four different fixes: shorten the chain, break the loop, drop O_NOFOLLOW or the link, and stop trusting a userspace resolver’s success as proof of an open.
More one-number runbooks: techbobby.com.
Appendix A: The Package and Its Tests, Printed Whole
Section 8 quotes the parts of the package that carry its argument; the folds below are the files themselves, character for character, so the tree can be rebuilt from this page without the repository. The five package files come first, __init__.py among them, and the four test files after them. The suite runs from the directory above pathguard with pytest pathguard/tests, and its count is the one quoted in the body: 59.
the entry point and its exports pathguard/__init__.py
"""pathguard - decide what a symlink is allowed to do before the kernel decides for you.
The kernel refuses a path after 40 symlink traversals in one resolution, with ``ELOOP`` and the
message "Too many levels of symbolic links". That single number covers a link chain that is one
hop too long, a directory that contains itself, a magic link under ``/proc/self/fd``, and an
``O_NOFOLLOW`` open of a file that is a link - four different repairs behind one refusal.
This package answers the question the kernel will not: *which* of those is it, and can I keep
walking without asking the kernel to resolve a path of unbounded length? It does that by
counting link traversals itself, with ``lstat`` and ``readlink``, so a chain of any length can be
described instead of merely refused. It also holds the two opens that decide: a directory
descriptor pinned once with ``pin_dir``, and a relative path opened beneath one with
``open_beneath``, which refuses every component that is a link.
"""
from __future__ import annotations
from .chain import MAX_LINKS, Chain, Hop, count_links, resolve_bounded
from .errors import BudgetExceeded, CycleFound, PathRefusal, RootEscape, explain
from .pinned import open_beneath, open_pinned, openat2, pin_dir, walk_beneath
from .walk import WalkEntry, open_no_follow, walk_bounded
__version__ = "1.1.0"
__all__ = [
"MAX_LINKS", "Chain", "Hop", "count_links", "resolve_bounded",
"BudgetExceeded", "CycleFound", "PathRefusal", "RootEscape", "explain",
"WalkEntry", "walk_bounded", "open_no_follow",
"pin_dir", "open_pinned", "open_beneath", "walk_beneath", "openat2", "__version__",
]
the counter and the budget pathguard/chain.py
"""Count a link chain in userspace, where the 40-hop ceiling does not apply.
The kernel applies its budget per path resolution. A resolver that calls ``lstat`` and
``readlink`` once per component is not bound by that budget, which is why ``realpath`` on this
host walks a 41-link chain that ``open`` refuses. This module uses the same per-component walk
to *describe* such a chain - and stops at a ceiling the caller chooses, so a pathological link
cannot make the caller loop forever.
"""
from __future__ import annotations
import os
import stat
from collections import deque
from dataclasses import dataclass, field
from .errors import MAX_LINKS, BudgetExceeded, CycleFound
@dataclass(frozen=True)
class Hop:
"""One symlink traversal: which link, what it said, and whether its target was absolute."""
index: int
link: str
target: str
absolute: bool
@dataclass(frozen=True)
class Chain:
"""The outcome of walking a path component by component.
``status`` is one of ``file``, ``dir``, ``other``, ``missing``, ``notdir``, ``cycle`` or
``budget``. ``target`` is the path the walk ended on, or the component it failed at.
``budget`` is the ceiling this walk was given, so the sentence it prints names the number
the caller actually used rather than the module default.
"""
start: str
target: str
status: str
links: int
hops: tuple[Hop, ...] = field(default=())
budget: int = MAX_LINKS
@property
def ok(self) -> bool:
return self.status in {"file", "dir", "other"}
@property
def refused(self) -> bool:
return self.status in {"cycle", "budget"}
def summary(self) -> str:
if self.status == "budget":
return f"{self.links} links, over the {self.budget}-link budget: {self.start}"
if self.status == "cycle":
return f"a link revisits itself after {self.links} traversals: {self.start}"
return f"{self.status} after {self.links} links: {self.start} -> {self.target}"
def _split(path: str) -> deque[str]:
return deque(part for part in path.split("/") if part not in ("", "."))
def count_links(path: str | os.PathLike[str], max_links: int = MAX_LINKS) -> Chain:
"""Walk ``path`` without following the kernel's budget, and describe what is there.
Raises nothing for a chain, a loop or a missing component: those are the answers. Only an
unreadable directory (``EACCES``) escapes, because it is not a statement about links.
The two rules a path carries in its text are kept, because the kernel keeps them: an empty
string is ``missing`` rather than the working directory, and a trailing slash demands a
directory, so a link to a file named with one is ``notdir``. ``..`` is applied to the
component that has already been resolved, and it is refused below a file for the same
reason. Every value the walk keeps is local to the call, so threads can count at once.
"""
start = os.fspath(path)
if not start:
return Chain(start, "", "missing", 0, (), max_links)
absolute = start.startswith("/")
trailing = len(start) > 1 and start.endswith("/")
base = "/" if absolute else os.getcwd()
remaining = _split(start)
hops: list[Hop] = []
seen: set[tuple[str, tuple[str, ...]]] = set()
while remaining:
component = remaining.popleft()
if component == "..":
try:
info = os.lstat(base)
except OSError:
return Chain(start, base, "missing", len(hops), tuple(hops), max_links)
if not stat.S_ISDIR(info.st_mode):
return Chain(start, base, "notdir", len(hops), tuple(hops), max_links)
base = os.path.dirname(base) or "/"
continue
candidate = os.path.join(base, component)
state = (candidate, tuple(remaining))
if state in seen:
return Chain(start, candidate, "cycle", len(hops), tuple(hops), max_links)
seen.add(state)
try:
info = os.lstat(candidate)
except FileNotFoundError:
return Chain(start, candidate, "missing", len(hops), tuple(hops), max_links)
except NotADirectoryError:
return Chain(start, candidate, "notdir", len(hops), tuple(hops), max_links)
if not stat.S_ISLNK(info.st_mode):
base = candidate
continue
if len(hops) >= max_links:
target = os.readlink(candidate)
hops.append(Hop(len(hops), candidate, target, target.startswith("/")))
return Chain(start, candidate, "budget", len(hops), tuple(hops), max_links)
target = os.readlink(candidate)
hops.append(Hop(len(hops), candidate, target, target.startswith("/")))
if target.startswith("/"):
base = "/"
else:
base = os.path.dirname(candidate) or "/"
remaining = _split(target) + remaining
try:
info = os.lstat(base)
except OSError:
return Chain(start, base, "missing", len(hops), tuple(hops), max_links)
if trailing and not stat.S_ISDIR(info.st_mode):
return Chain(start, base, "notdir", len(hops), tuple(hops), max_links)
if stat.S_ISDIR(info.st_mode):
return Chain(start, base, "dir", len(hops), tuple(hops), max_links)
if stat.S_ISREG(info.st_mode):
return Chain(start, base, "file", len(hops), tuple(hops), max_links)
return Chain(start, base, "other", len(hops), tuple(hops), max_links)
def resolve_bounded(path: str | os.PathLike[str], max_links: int = MAX_LINKS) -> Chain:
"""Return the chain when it fits the budget; refuse a loop or an over-budget chain.
The refusal names the count, because "ELOOP" alone cannot tell an operator whether the chain
missed by one hop or by four hundred.
"""
chain = count_links(path, max_links=max_links)
if chain.status == "budget":
raise BudgetExceeded(f"more than {max_links} link traversals",
path=chain.start, links=chain.links)
if chain.status == "cycle":
raise CycleFound("a link that leads back to itself", path=chain.start, links=chain.links)
return chain
the refusals and the sentence pathguard/errors.py
"""The refusals, and what they mean in words a log line can carry."""
from __future__ import annotations
import errno
import os
# The kernel's own ceiling for symlink traversals inside one path resolution. It is not exposed
# by getconf on this host, so the package states it once and every call is measured against it.
MAX_LINKS = 40
ELOOP = errno.ELOOP
ENOENT = errno.ENOENT
ENOTDIR = errno.ENOTDIR
EXDEV = errno.EXDEV
EEXIST = errno.EEXIST
class PathRefusal(OSError):
"""A path this package refused before the kernel had to."""
def __init__(self, message: str, *, path: str = "", links: int = 0,
code: int = ELOOP) -> None:
# The code is the number the call that refused the path answered with: ELOOP for a link
# chain, EXDEV for a path that leaves its root, ENOTDIR for O_NOFOLLOW|O_DIRECTORY on a
# link. A refusal is one object, and the number it carries stays the real one.
super().__init__(code, message, path)
self.links = links
def __str__(self) -> str:
counted = ""
if self.links:
unit = "link" if self.links == 1 else "links"
counted = f" ({self.links} {unit})"
return f"{os.strerror(self.errno)}{counted} - {self.strerror}: {self.filename}"
class BudgetExceeded(PathRefusal):
"""More traversals than the kernel would allow in one resolution."""
class CycleFound(PathRefusal):
"""A link that leads back to a link already traversed in this walk."""
class RootEscape(PathRefusal):
"""A relative path that would leave the directory the descriptor names.
``openat2`` answers this with ``EXDEV``, and the walk refuses it before the kernel sees the
path, so the class carries the number a caller who compares errnos will look for.
"""
def __init__(self, message: str, *, path: str = "") -> None:
super().__init__(message, path=path, code=EXDEV)
def explain(exc: BaseException, *, flags: int = 0) -> str:
"""One sentence for a log line: what this refusal most likely is.
``ELOOP`` is one number with several causes, so the sentence names the cause the flags and
the message support instead of pretending to know which one the kernel hit.
"""
code = getattr(exc, "errno", None)
if code == ELOOP:
if flags & getattr(os, "O_NOFOLLOW", 0):
return ("a final component that is a symlink, refused because the open asked not to "
"follow one; the existing link is the bug, not the path length")
return (f"one of three: a chain longer than {MAX_LINKS} traversals, a directory that "
"revisits itself, or a magic link opened through /proc/self/fd; count the links "
"with count_links() before retrying")
if code == ENOTDIR:
return ("a component that is not a directory: a file with a trailing slash, a link to a "
"file used as a parent, or O_NOFOLLOW combined with O_DIRECTORY")
if code == ENOENT:
return "a missing component, including a link whose target does not exist"
if code == EXDEV:
return "a rename or link across filesystems, or openat2 asked to stay beneath a dirfd"
if code == EEXIST:
return "an exclusive create over a name that already exists"
return f"{type(exc).__name__}: {exc}"
the pinned descriptor and the escape pathguard/pinned.py
"""Pin a directory once, then open names beneath it without letting a link choose the target.
``O_NOFOLLOW`` refuses a link in the last component of the path it is given, and in no other. A
process that pins ``current`` with one open and then opens ``conf/settings`` through that
descriptor fixes the release it reads even when the link moves; that same call still follows a
link planted at ``conf``, because ``conf`` is an intermediate component the flag never saw.
Both repairs live here: ``pin_dir`` keeps the object a link named, ``open_pinned`` opens one name
beneath it with the flag, and ``open_beneath`` opens a whole relative path, refusing every
component that is a link, so an archive entry cannot step outside the directory it was given.
"""
from __future__ import annotations
import ctypes
import errno
import os
import platform
import stat
import sys
from .errors import EXDEV, PathRefusal, RootEscape
# openat2 is an ABI constant of this architecture, not a measurement: x86-64 numbers it 437, and
# the resolve masks are the bits the kernel compares. The number is looked up by machine name
# because ``syscall`` is a Linux interface and an architecture this table does not name has no
# safe number to pass; both are stated once here so a call reads as intent instead of as a
# hexadecimal number nobody can place.
OPENAT2_SYSCALLS = {"x86_64": 437, "amd64": 437, "aarch64": 437, "arm64": 437,
"riscv64": 437, "ppc64le": 437, "s390x": 437, "i386": 437, "i686": 437}
RESOLVE_NO_SYMLINKS = 0x04
RESOLVE_BENEATH = 0x08
_O_CLOEXEC = getattr(os, "O_CLOEXEC", 0)
_LIBC: ctypes.CDLL | None = None
def _syscall_number() -> int | None:
"""openat2's number on this host, or None where the syscall cannot be made.
A Windows or macOS process, and a Linux process on an architecture the table does not
name, get None: every open below then takes the component walk instead of a C library
call whose number would be a guess.
"""
if sys.platform != "linux":
return None
return OPENAT2_SYSCALLS.get(platform.machine().lower())
class OpenHow(ctypes.Structure):
"""The three 64-bit fields ``openat2`` reads."""
_fields_ = [("flags", ctypes.c_uint64), ("mode", ctypes.c_uint64),
("resolve", ctypes.c_uint64)]
def _libc() -> ctypes.CDLL | None:
"""The C library handle, taken on first use and only where openat2 can be called.
Importing this module used to load the C library for every process, including one that only
wanted ``count_links`` on a host without the syscall at all. The handle is now taken when a
call needs it, and never where :func:`_syscall_number` says there is no syscall to make.
"""
global _LIBC
if _syscall_number() is None:
return None
if _LIBC is None:
try:
_LIBC = ctypes.CDLL(None, use_errno=True)
except OSError:
return None
return _LIBC
def openat2(dirfd: int, rel_path: str, flags: int = os.O_RDONLY, resolve: int = 0) -> int:
"""Call ``openat2`` relative to ``dirfd`` and raise the kernel's errno on refusal.
Where the syscall does not exist the call raises ``ENOSYS`` rather than guessing a number,
which is the answer :func:`open_beneath` already knows how to fall back from.
"""
number = _syscall_number()
libc = _libc()
if number is None or libc is None:
raise OSError(errno.ENOSYS, os.strerror(errno.ENOSYS), str(rel_path))
how = OpenHow(flags | _O_CLOEXEC, 0, resolve)
result = libc.syscall(number, dirfd, str(rel_path).encode(),
ctypes.byref(how), ctypes.sizeof(how))
if result < 0:
code = ctypes.get_errno()
raise OSError(code, os.strerror(code), str(rel_path))
return int(result)
def pin_dir(path: str | os.PathLike[str], flags: int = os.O_RDONLY) -> int:
"""Open ``path`` as a directory and return the descriptor, which no later swap can redirect.
The final component may be a link - pinning ``current`` is the case this exists for - and the
descriptor names the directory that link pointed at when the call was made. ``O_DIRECTORY``
keeps a file from being pinned by mistake. The caller closes the descriptor.
"""
return os.open(path, flags | os.O_DIRECTORY | _O_CLOEXEC)
def open_pinned(dirfd: int, name: str, flags: int = os.O_RDONLY) -> int:
"""Open one name directly beneath ``dirfd``, refusing a link in that name.
The name is one component. A relative path belongs to :func:`open_beneath`, because the flag
this call adds covers the last component only and would follow a link in any earlier one.
"""
if not name or "/" in str(name) or str(name) in (".", ".."):
raise PathRefusal("a name beneath a descriptor is one component, not a path",
path=str(name))
return _open_step(str(name), dirfd, str(name), flags | os.O_NOFOLLOW)
def open_beneath(dirfd: int, rel_path: str, flags: int = os.O_RDONLY) -> int:
"""Open a relative path beneath ``dirfd``, refusing every component that is a link.
The default path is one syscall: ``openat2`` with ``RESOLVE_BENEATH|RESOLVE_NO_SYMLINKS``
resolves the whole relative path inside the kernel, where a link answers ELOOP and a path
that would climb out answers EXDEV. A kernel that does not answer the syscall falls back to
:func:`walk_beneath`, which opens one component per syscall with ``O_NOFOLLOW|O_DIRECTORY``
for every directory and ``O_NOFOLLOW`` for the last name, and refuses the same paths.
Two kinds of bad argument are told apart before either implementation sees them, because
they are not escapes: an empty path, a double slash, a bare ``.`` or a trailing slash is the
caller's mistake and raises ``ValueError``. Only a path that would actually leave the
directory - an absolute path, or one with a ``..`` component - raises :class:`RootEscape`.
"""
text = str(rel_path)
if not text:
raise ValueError("open_beneath needs a relative path, not an empty string")
if text.startswith("/"):
raise RootEscape("an absolute path is not beneath the descriptor", path=text)
parts = text.split("/")
if any(part == ".." for part in parts):
raise RootEscape("a '..' component would leave the directory the descriptor names",
path=text)
if any(part in ("", ".") for part in parts):
raise ValueError(f"a path beneath a descriptor has an empty or '.' component: {text!r}")
libc = _libc()
if libc is not None:
try:
return openat2(dirfd, text, flags, RESOLVE_BENEATH | RESOLVE_NO_SYMLINKS)
except OSError as exc:
if exc.errno == errno.ENOSYS:
pass
elif exc.errno == errno.ELOOP:
raise PathRefusal("a component of the path is a symlink",
path=text) from exc
elif exc.errno == EXDEV:
raise RootEscape("a component leaves the directory the descriptor names",
path=text) from exc
else:
raise
return walk_beneath(dirfd, parts, flags)
def walk_beneath(dirfd: int, parts: list[str], flags: int = os.O_RDONLY) -> int:
"""One ``openat`` per component, so no component is resolved by a link the caller did not see.
Each directory is opened with ``O_NOFOLLOW|O_DIRECTORY`` and becomes the descriptor the next
name is opened against; the last name is opened with the caller's flags plus ``O_NOFOLLOW``.
The descriptor the caller passed is duplicated, so it stays theirs to close.
"""
path = "/".join(parts)
current = os.dup(dirfd)
try:
for part in parts[:-1]:
step = _open_step(part, current, path,
os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW)
os.close(current)
current = step
return _open_step(parts[-1], current, path, flags | os.O_NOFOLLOW)
finally:
os.close(current)
def _open_step(name: str, dirfd: int, path: str, flags: int) -> int:
"""Open ``name`` relative to ``dirfd``; a refused component becomes one PathRefusal.
The refusal keeps the number the call answered with: ELOOP for a last name opened with
``O_NOFOLLOW``, and ENOTDIR for a directory step, because ``O_NOFOLLOW|O_DIRECTORY`` on a
link refuses it as something that is not a directory.
"""
try:
return os.open(name, flags | _O_CLOEXEC, dir_fd=dirfd)
except OSError as exc:
if exc.errno in (errno.ELOOP, errno.ENOTDIR):
message, links = _refused(name, dirfd)
raise PathRefusal(message, path=path, links=links, code=exc.errno) from exc
raise
def _refused(name: str, dirfd: int) -> tuple[str, int]:
"""What the refused component is: a link, which spends one traversal, or not a directory."""
try:
if stat.S_ISLNK(os.lstat(name, dir_fd=dirfd).st_mode):
return "a component of the path is a symlink", 1
except OSError:
pass
return "a component of the path is not a directory", 0
the bounded walk over one tree pathguard/walk.py
"""Walk a tree once per directory, and open a leaf without letting a link decide for you.
``os.walk(followlinks=True)`` follows a directory that contains itself until the kernel's budget
stops it, which on this host is 161 directories later and silent. This walk keeps the set of
directory identities it has entered, so a loop is reported as a refused entry at the moment it
would otherwise repeat, and a caller can count what was refused.
"""
from __future__ import annotations
import errno
import os
import stat
from dataclasses import dataclass
from typing import Iterator
from .errors import PathRefusal
@dataclass(frozen=True)
class WalkEntry:
"""One name visited by the walk.
``refusal`` is ``None`` for a plain entry, ``"cycle"`` when a directory was not entered
because it had already been entered, and ``"eloop"`` when the kernel refused to stat the
entry (a link to itself, for example).
"""
path: str
depth: int
is_dir: bool
is_link: bool
refusal: str | None = None
def _identity(path: str) -> tuple[int, int] | None:
try:
info = os.stat(path)
except OSError:
return None
return (info.st_dev, info.st_ino)
def _descend(path: str, depth: int, follow_symlinks: bool, max_depth: int,
max_entries: int, visited: set[tuple[int, int]],
emitted: list[int]) -> Iterator[WalkEntry]:
"""Yield ``path``, then its children in name order, never entering a directory twice."""
is_link = os.path.islink(path)
is_dir = False
if is_link and follow_symlinks:
try:
info = os.stat(path)
except OSError as exc:
yield WalkEntry(path, depth, False, True, "eloop" if exc.errno == errno.ELOOP else None)
emitted[0] += 1
return
if stat.S_ISDIR(info.st_mode):
identity = (info.st_dev, info.st_ino)
# ``depth`` keeps the root itself enterable when the root is a link: its identity is
# already known to the caller, and reporting it as a cycle would hide the whole tree.
if identity in visited and depth:
yield WalkEntry(path, depth, True, True, "cycle")
emitted[0] += 1
return
visited.add(identity)
is_dir = True
else:
yield WalkEntry(path, depth, False, True)
emitted[0] += 1
return
else:
try:
info = os.lstat(path)
except OSError:
return
is_dir = stat.S_ISDIR(info.st_mode)
if is_dir:
identity = (info.st_dev, info.st_ino)
if identity in visited and depth:
yield WalkEntry(path, depth, True, is_link, "cycle")
emitted[0] += 1
return
visited.add(identity)
yield WalkEntry(path, depth, is_dir, is_link)
emitted[0] += 1
if emitted[0] >= max_entries:
return
if is_link and not follow_symlinks:
return
if not is_dir or depth >= max_depth:
return
try:
names = sorted(os.listdir(path))
except OSError:
return
for name in names:
yield from _descend(os.path.join(path, name), depth + 1, follow_symlinks, max_depth,
max_entries, visited, emitted)
if emitted[0] >= max_entries:
return
def walk_bounded(root: str | os.PathLike[str], *, follow_symlinks: bool = False,
max_depth: int = 64, max_entries: int = 100_000) -> Iterator[WalkEntry]:
"""Yield entries under ``root`` without entering a directory twice or exceeding a cap.
Symlinks are entries of their own unless ``follow_symlinks`` is set; then a link to a file is
reported as a file, a link to a directory is entered only if that directory has not been
entered before, and a link the kernel refuses is yielded with ``refusal="eloop"``. A root
that is itself a link is entered once, rather than refused as a cycle. The walk stops after
``max_entries`` entries and descends no deeper than ``max_depth``.
"""
start = os.fspath(root)
identity = _identity(start)
if identity is None:
return
yield from _descend(start, 0, follow_symlinks, max_depth, max_entries, {identity}, [0])
def open_no_follow(path: str | os.PathLike[str], flags: int = os.O_RDONLY) -> int:
"""Open a path whose final component must not be a symlink.
The flag is added here rather than left to the caller, because a helper that forgets it
silently follows the link the caller meant to refuse. A refusal is re-raised with the number
of links the path measured, so the caller can tell a link to a file from a 400-hop chain.
"""
from .chain import count_links
try:
return os.open(path, flags | os.O_NOFOLLOW)
except OSError as exc:
if exc.errno == errno.ELOOP:
chain = count_links(path)
raise PathRefusal("the final component is a symlink",
path=os.fspath(path), links=chain.links) from exc
raise
the counter and the budget pathguard/tests/test_chain.py
"""The chain counter: where the budget sits, what it counts, and how it says so."""
from __future__ import annotations
import errno
import os
from concurrent.futures import ThreadPoolExecutor
import pytest
from pathguard import BudgetExceeded, CycleFound, MAX_LINKS, count_links, resolve_bounded
def make_chain(root, hops: int, *, absolute: bool = False) -> str:
root.mkdir(parents=True, exist_ok=True)
(root / "target").write_text("x")
for index in range(hops):
destination = f"l{index + 1}" if index < hops - 1 else "target"
if absolute:
destination = str(root / destination)
os.symlink(destination, root / f"l{index}")
return str(root / "l0")
def test_forty_links_are_within_the_budget(tmp_path):
chain = count_links(make_chain(tmp_path / "forty", 40))
assert chain.ok and chain.status == "file"
assert chain.links == 40
def test_forty_one_links_exceed_it(tmp_path):
chain = count_links(make_chain(tmp_path / "fortyone", 41))
assert chain.status == "budget"
assert chain.links == 41
def test_the_default_budget_is_the_kernel_ceiling():
assert MAX_LINKS == 40
def test_a_caller_can_lower_the_budget(tmp_path):
chain = count_links(make_chain(tmp_path / "short", 10), max_links=5)
assert chain.status == "budget"
assert chain.links == 6
assert chain.summary() == (f"6 links, over the 5-link budget: {tmp_path / 'short' / 'l0'}")
def test_counting_in_parallel_threads_keeps_each_walk_its_own(tmp_path):
paths = [make_chain(tmp_path / f"t{index}", 41) for index in range(4)]
with ThreadPoolExecutor(max_workers=4) as pool:
counted = list(pool.map(lambda path: count_links(path).links, paths))
assert counted == [41, 41, 41, 41]
def test_an_absolute_chain_pays_the_same_price(tmp_path):
assert count_links(make_chain(tmp_path / "abs", 40, absolute=True)).links == 40
assert count_links(make_chain(tmp_path / "abs41", 41, absolute=True)).status == "budget"
def test_an_empty_path_is_missing_not_the_working_directory():
chain = count_links("")
assert chain.status == "missing"
assert chain.links == 0
assert chain.target == ""
def test_a_trailing_slash_demands_a_directory(tmp_path):
(tmp_path / "file").write_text("x")
os.symlink("file", tmp_path / "link")
(tmp_path / "dir").mkdir()
os.symlink("dir", tmp_path / "dir_link")
assert count_links(str(tmp_path / "link") + "/").status == "notdir"
assert count_links(str(tmp_path / "dir_link") + "/").status == "dir"
assert count_links(str(tmp_path / "dir") + "/").status == "dir"
def test_dotdot_below_a_file_is_not_a_directory(tmp_path):
(tmp_path / "file").write_text("x")
assert count_links(str(tmp_path / "file") + "/..").status == "notdir"
assert count_links(str(tmp_path) + "/..").status == "dir"
def test_a_budget_split_across_directories_is_one_budget(tmp_path):
first = tmp_path / "first"
second = tmp_path / "second"
first.mkdir()
second.mkdir()
final = make_chain(second, 20)
os.symlink(os.path.relpath(final, first), first / "l0")
chain = count_links(first / "l0")
assert chain.links == 21
assert chain.ok
def test_a_plain_file_has_no_hops(tmp_path):
target = tmp_path / "file"
target.write_text("x")
chain = count_links(target)
assert chain.links == 0 and chain.status == "file"
def test_a_directory_target_is_reported_as_one(tmp_path):
directory = tmp_path / "dir"
directory.mkdir()
os.symlink("dir", tmp_path / "link")
assert count_links(tmp_path / "link").status == "dir"
def test_a_link_to_itself_is_a_cycle(tmp_path):
os.symlink("selfme", tmp_path / "selfme")
chain = count_links(tmp_path / "selfme")
assert chain.status == "cycle"
assert chain.links == 1
def test_two_links_that_point_at_each_other_are_a_cycle(tmp_path):
os.symlink("b", tmp_path / "a")
os.symlink("a", tmp_path / "b")
chain = count_links(tmp_path / "a")
assert chain.status == "cycle"
assert chain.links == 2
def test_a_dangling_link_names_the_component_it_stopped_at(tmp_path):
os.symlink("nowhere", tmp_path / "dangling")
chain = count_links(tmp_path / "dangling")
assert chain.status == "missing"
assert chain.links == 1
assert chain.target.endswith("nowhere")
def test_a_file_used_as_a_parent_is_not_a_missing_path(tmp_path):
(tmp_path / "file").write_text("x")
chain = count_links(tmp_path / "file" / "child")
assert chain.status == "notdir"
def test_every_hop_records_its_own_target(tmp_path):
chain = count_links(make_chain(tmp_path / "hop", 3))
assert [hop.target for hop in chain.hops] == ["l1", "l2", "target"]
assert [hop.index for hop in chain.hops] == [0, 1, 2]
assert all(not hop.absolute for hop in chain.hops)
def test_resolve_returns_the_chain_within_budget(tmp_path):
chain = resolve_bounded(make_chain(tmp_path / "ok", 40))
assert chain.ok and chain.target.endswith("target")
def test_resolve_refuses_an_over_budget_chain_with_its_count(tmp_path):
with pytest.raises(BudgetExceeded) as caught:
resolve_bounded(make_chain(tmp_path / "over", 41))
assert caught.value.links == 41
assert caught.value.errno == errno.ELOOP
def test_resolve_refuses_a_cycle(tmp_path):
os.symlink("selfme", tmp_path / "selfme")
with pytest.raises(CycleFound):
resolve_bounded(tmp_path / "selfme")
the bounded walk and its refusals pathguard/tests/test_walk.py
"""The bounded walk: how a directory that contains itself is reported instead of followed."""
from __future__ import annotations
import os
from pathguard import walk_bounded
def build(root):
root.mkdir(parents=True, exist_ok=True)
(root / "sub").mkdir()
(root / "file").write_text("x")
(root / "sub" / "inner").write_text("y")
os.symlink("..", root / "sub" / "up")
os.symlink("selfme", root / "selfme")
return root
def test_the_root_is_the_first_entry(tmp_path):
entries = list(walk_bounded(build(tmp_path / "tree")))
assert entries[0].path == str(tmp_path / "tree")
assert entries[0].depth == 0
def test_a_symlink_is_an_entry_not_a_door(tmp_path):
root = build(tmp_path / "tree")
paths = {entry.path for entry in walk_bounded(root)}
assert str(root / "sub" / "up") in paths
assert str(root / "sub" / "up" / "sub") not in paths
def test_following_symlinks_reports_the_cycle_and_does_not_enter_it(tmp_path):
root = build(tmp_path / "tree")
entries = list(walk_bounded(root, follow_symlinks=True))
cycles = [entry for entry in entries if entry.refusal == "cycle"]
assert len(cycles) == 1
assert cycles[0].path.endswith("up")
def test_following_symlinks_reports_a_self_link_as_eloop(tmp_path):
root = build(tmp_path / "tree")
entries = list(walk_bounded(root, follow_symlinks=True))
refused = [entry for entry in entries if entry.refusal == "eloop"]
assert [entry.path.rsplit("/", 1)[-1] for entry in refused] == ["selfme"]
def test_the_walk_visits_each_real_directory_once(tmp_path):
root = build(tmp_path / "tree")
directories = [entry.path for entry in walk_bounded(root, follow_symlinks=True)
if entry.is_dir and entry.refusal is None]
assert len(directories) == len(set(directories))
def test_a_symlink_root_is_entered_once_when_links_are_followed(tmp_path):
root = build(tmp_path / "tree")
link = tmp_path / "root_link"
os.symlink(root, link)
entries = list(walk_bounded(link, follow_symlinks=True))
assert entries[0].path == str(link)
assert entries[0].is_dir and entries[0].refusal is None
assert any(entry.path.endswith("sub") and entry.is_dir for entry in entries)
assert [entry for entry in entries if entry.refusal == "cycle"][0].path.endswith("up")
def test_max_depth_stops_the_descent_but_not_the_siblings(tmp_path):
root = tmp_path / "tree"
(root / "a" / "b" / "c").mkdir(parents=True)
(root / "sibling").write_text("x")
entries = list(walk_bounded(root, max_depth=1))
depths = {entry.depth for entry in entries}
assert max(depths) == 1
assert any(entry.path.endswith("sibling") for entry in entries)
def test_max_entries_is_a_hard_cap(tmp_path):
root = tmp_path / "tree"
root.mkdir()
for index in range(20):
(root / f"f{index}").write_text("x")
assert len(list(walk_bounded(root, max_entries=5))) == 5
def test_a_missing_root_yields_nothing(tmp_path):
assert list(walk_bounded(tmp_path / "absent")) == []
def test_depth_counts_directories_from_the_root(tmp_path):
root = tmp_path / "tree"
(root / "a" / "b").mkdir(parents=True)
depths = {entry.path: entry.depth for entry in walk_bounded(root)}
assert depths[str(root / "a" / "b")] == 2
def test_the_walk_is_sorted_inside_each_directory(tmp_path):
root = tmp_path / "tree"
root.mkdir()
for name in ("c", "a", "b"):
(root / name).write_text("x")
names = [entry.path.rsplit("/", 1)[-1] for entry in walk_bounded(root)]
assert names == ["tree", "a", "b", "c"]
the pinned descriptor and the escape pathguard/tests/test_pinned.py
"""The pinned descriptor and the component walk: a swap cannot redirect a name already pinned.
Every case here is a shape a deploy or an archive leaves behind: a ``current`` link that moves
between the pin and the open, and a directory the archive wrote a link into earlier in the same
extraction.
"""
from __future__ import annotations
import errno
import os
import pytest
from pathguard import PathRefusal, RootEscape, open_beneath, open_pinned, pin_dir, pinned
def read(fd: int) -> str:
try:
return os.read(fd, 64).decode()
finally:
os.close(fd)
def release_layout(root):
"""Two releases and a ``current`` link, the shape every deploy writes."""
for name in ("v1", "v2"):
(root / "releases" / name / "conf").mkdir(parents=True)
(root / "releases" / name / "conf" / "settings").write_text(name)
os.symlink(root / "releases" / "v1", root / "current")
return root
def swap_current(root) -> None:
"""What the next deploy does: replace the link, leaving the release it named untouched."""
os.unlink(root / "current")
os.symlink(root / "releases" / "v2", root / "current")
def test_a_pinned_directory_still_reads_the_release_it_named(tmp_path):
root = release_layout(tmp_path)
fd = pin_dir(root / "current" / "conf")
try:
swap_current(root)
assert read(open_pinned(fd, "settings")) == "v1"
finally:
os.close(fd)
def test_open_beneath_reads_the_release_the_descriptor_named(tmp_path):
root = release_layout(tmp_path)
fd = pin_dir(root / "current")
try:
swap_current(root)
assert read(open_beneath(fd, "conf/settings")) == "v1"
finally:
os.close(fd)
def test_open_beneath_reads_a_clean_tree(tmp_path):
(tmp_path / "a" / "b").mkdir(parents=True)
(tmp_path / "a" / "b" / "file").write_text("x")
fd = pin_dir(tmp_path)
try:
assert read(open_beneath(fd, "a/b/file")) == "x"
finally:
os.close(fd)
def test_open_pinned_refuses_a_link_in_its_name(tmp_path):
(tmp_path / "target").write_text("x")
os.symlink("target", tmp_path / "link")
fd = pin_dir(tmp_path)
try:
with pytest.raises(PathRefusal) as caught:
open_pinned(fd, "link")
assert caught.value.errno == errno.ELOOP
assert caught.value.links == 1
finally:
os.close(fd)
def test_open_pinned_refuses_a_path_with_a_separator(tmp_path):
(tmp_path / "a").mkdir()
(tmp_path / "a" / "b").write_text("x")
fd = pin_dir(tmp_path)
try:
with pytest.raises(PathRefusal):
open_pinned(fd, "a/b")
finally:
os.close(fd)
def test_one_openat_with_o_nofollow_is_not_enough(tmp_path):
"""The call open_pinned replaces: the flag covered the last name, not the link before it."""
outside = tmp_path / "etc"
outside.mkdir()
(outside / "passwd").write_text("root:x")
root = tmp_path / "extract"
root.mkdir()
os.symlink(outside, root / "a")
fd = pin_dir(root)
try:
plain = os.open("a/passwd", os.O_RDONLY | os.O_NOFOLLOW, dir_fd=fd)
assert read(plain) == "root:x"
finally:
os.close(fd)
def test_the_archive_entry_cannot_leave_the_root_through_a_link(tmp_path):
outside = tmp_path / "etc"
outside.mkdir()
(outside / "passwd").write_text("root:x")
root = tmp_path / "extract"
root.mkdir()
os.symlink(outside, root / "a")
fd = pin_dir(root)
try:
with pytest.raises(PathRefusal) as caught:
open_beneath(fd, "a/passwd")
# ELOOP from openat2, EXDEV if the path were seen as leaving the root, and ENOTDIR from
# the component walk, whose O_NOFOLLOW|O_DIRECTORY answers ENOTDIR for a link.
assert caught.value.errno in (errno.ELOOP, errno.EXDEV, errno.ENOTDIR)
finally:
os.close(fd)
def test_a_link_that_stays_inside_the_root_is_still_refused(tmp_path):
(tmp_path / "real").mkdir()
(tmp_path / "real" / "file").write_text("x")
os.symlink("real", tmp_path / "inside")
fd = pin_dir(tmp_path)
try:
with pytest.raises(PathRefusal) as caught:
open_beneath(fd, "inside/file")
assert caught.value.errno in (errno.ELOOP, errno.EXDEV, errno.ENOTDIR)
finally:
os.close(fd)
def test_a_climb_out_of_the_root_is_refused(tmp_path):
fd = pin_dir(tmp_path)
try:
with pytest.raises(RootEscape) as caught:
open_beneath(fd, "..")
assert caught.value.errno == errno.EXDEV
finally:
os.close(fd)
def test_an_absolute_path_is_refused(tmp_path):
fd = pin_dir(tmp_path)
try:
with pytest.raises(RootEscape) as caught:
open_beneath(fd, "/etc/passwd")
assert caught.value.errno == errno.EXDEV
finally:
os.close(fd)
def test_the_walk_refuses_the_escape_without_openat2(tmp_path, monkeypatch):
monkeypatch.setattr(pinned, "OPENAT2_SYSCALLS", {})
outside = tmp_path / "etc"
outside.mkdir()
(outside / "passwd").write_text("root:x")
root = tmp_path / "extract"
root.mkdir()
os.symlink(outside, root / "a")
fd = pin_dir(root)
try:
with pytest.raises(PathRefusal) as caught:
open_beneath(fd, "a/passwd")
assert caught.value.errno == errno.ENOTDIR
assert caught.value.links == 1
finally:
os.close(fd)
def test_the_walk_reads_the_release_the_descriptor_named(tmp_path, monkeypatch):
monkeypatch.setattr(pinned, "OPENAT2_SYSCALLS", {})
root = release_layout(tmp_path)
fd = pin_dir(root / "current")
try:
swap_current(root)
assert read(open_beneath(fd, "conf/settings")) == "v1"
finally:
os.close(fd)
def test_the_walk_leaves_the_callers_descriptor_open(tmp_path, monkeypatch):
monkeypatch.setattr(pinned, "OPENAT2_SYSCALLS", {})
(tmp_path / "file").write_text("x")
fd = pin_dir(tmp_path)
try:
assert read(open_beneath(fd, "file")) == "x"
assert os.fstat(fd).st_ino == os.stat(tmp_path).st_ino
finally:
os.close(fd)
def test_a_format_error_is_a_value_error_not_an_escape(tmp_path):
"""``a//b``, ``.``, ```` and a trailing slash are the caller's mistake, not a RootEscape."""
(tmp_path / "a").mkdir()
(tmp_path / "a" / "file").write_text("x")
fd = pin_dir(tmp_path)
try:
for bad in ("", ".", "a//file", "a/", "./a/file", "a/./file"):
with pytest.raises(ValueError) as caught:
open_beneath(fd, bad)
assert not isinstance(caught.value, PathRefusal)
assert not isinstance(caught.value, RootEscape)
finally:
os.close(fd)
def test_every_climb_out_of_the_root_is_a_root_escape(tmp_path):
(tmp_path / "a").mkdir()
fd = pin_dir(tmp_path)
try:
for bad in ("..", "a/../a", "../x"):
with pytest.raises(RootEscape) as caught:
open_beneath(fd, bad)
assert caught.value.errno == errno.EXDEV
finally:
os.close(fd)
def test_a_host_without_the_syscall_still_walks_the_path(tmp_path, monkeypatch):
"""openat2 answers ENOSYS where there is no number, and open_beneath falls back to the walk."""
monkeypatch.setattr(pinned, "OPENAT2_SYSCALLS", {})
(tmp_path / "file").write_text("x")
fd = pin_dir(tmp_path)
try:
with pytest.raises(OSError) as caught:
pinned.openat2(fd, "file")
assert caught.value.errno == errno.ENOSYS
assert read(open_beneath(fd, "file")) == "x"
finally:
os.close(fd)
def test_the_syscall_number_is_only_asked_for_on_linux(monkeypatch):
"""Another platform, or an architecture the table does not name, answers None, not a guess."""
monkeypatch.setattr(pinned.sys, "platform", "win32")
assert pinned._syscall_number() is None
monkeypatch.setattr(pinned.sys, "platform", "darwin")
assert pinned._syscall_number() is None
monkeypatch.setattr(pinned.sys, "platform", "linux")
monkeypatch.setattr(pinned.platform, "machine", lambda: "an-architecture-named-by-a-test")
assert pinned._syscall_number() is None
assert pinned._libc() is None
O_NOFOLLOW and the sentence pathguard/tests/test_policy.py
"""The refusal itself: what the helper adds to O_NOFOLLOW, and what the sentence says."""
from __future__ import annotations
import errno
import os
import pytest
from pathguard import PathRefusal, explain, open_no_follow
def test_open_no_follow_reads_a_regular_file(tmp_path):
path = tmp_path / "file"
path.write_text("x")
descriptor = open_no_follow(path)
try:
assert os.read(descriptor, 1) == b"x"
finally:
os.close(descriptor)
def test_open_no_follow_refuses_a_final_symlink(tmp_path):
(tmp_path / "file").write_text("x")
os.symlink("file", tmp_path / "link")
with pytest.raises(PathRefusal) as caught:
open_no_follow(tmp_path / "link")
assert caught.value.errno == errno.ELOOP
assert caught.value.links == 1
def test_open_no_follow_still_follows_an_intermediate_link(tmp_path):
(tmp_path / "dir").mkdir()
(tmp_path / "dir" / "inner").write_text("x")
os.symlink("dir", tmp_path / "link_to_dir")
descriptor = open_no_follow(tmp_path / "link_to_dir" / "inner")
os.close(descriptor)
def test_open_no_follow_keeps_the_callers_flags(tmp_path):
path = tmp_path / "file"
path.write_text("x")
with pytest.raises(FileExistsError):
open_no_follow(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL)
def test_the_refusal_message_carries_the_count(tmp_path):
(tmp_path / "file").write_text("x")
os.symlink("file", tmp_path / "link")
with pytest.raises(PathRefusal) as caught:
open_no_follow(tmp_path / "link")
assert "1 link" in str(caught.value)
assert "1 links" not in str(caught.value)
assert "Too many levels of symbolic links" in str(caught.value)
def test_a_no_follow_refusal_is_explained_by_its_flag():
error = OSError(errno.ELOOP, "Too many levels of symbolic links")
sentence = explain(error, flags=os.O_NOFOLLOW)
assert "final component" in sentence
assert "not the path length" in sentence
def test_an_eloop_without_the_flag_points_at_the_count():
sentence = explain(OSError(errno.ELOOP, "Too many levels of symbolic links"))
assert "count_links" in sentence
def test_not_a_directory_has_three_causes_in_one_sentence():
sentence = explain(OSError(errno.ENOTDIR, "Not a directory"))
assert "trailing slash" in sentence and "O_DIRECTORY" in sentence
def test_a_missing_path_is_named_as_a_missing_component():
assert "missing" in explain(OSError(errno.ENOENT, "No such file or directory"))
def test_an_unknown_errno_still_gets_a_sentence():
sentence = explain(OSError(errno.EIO, "Input/output error"))
assert sentence.startswith("OSError")
def test_explain_does_not_need_a_path():
assert explain(ValueError("not a file error"))
Appendix B: The Probes, Printed Whole
These are the files that produced every figure in Tables 2 through 12, and the counts the body quotes about its own tree. Each writes one record under results/, each record holds five runs per arm, and the helper they share is printed first. Table 2 comes from 11_deploy.py; Tables 3 and the Linux row of Table 5 from 01_facts.py, whose documented block also holds the macOS, FreeBSD and Windows figures the other rows of Table 5 quote; Table 4 from 02_matrix.py; Tables 6 and 7 from 03_hops.py; Table 8 from 08_cost.py; Table 9 from 04_flags.py; Table 10 from 05_loops.py; Table 11 from 06_python.py; Table 12 from 07_shell.py; and the test and line counts from 09_counts.py, which runs the suite it counts. Table 13 is the package’s own entry points, whose code Appendix A prints whole.
five runs, one record sandbox/probelib.py
"""Shared plumbing for the probes on this page: five runs and one record per arm.
Every probe writes ``results/NN_name.json`` with the host it ran on, the notes it computed from
its own arms, and one entry per labelled arm holding all five runs. A probe never writes a
figure it did not observe; the page's values.py reads these files and nothing else.
The one call the probes share but the standard library does not expose is ``openat2``. Its
syscall number is an ABI constant of this architecture, not a measurement, so it is stated once
here and the records say separately whether a real call on this host succeeded.
"""
from __future__ import annotations
import ctypes
import errno
import json
import os
import pathlib
import platform
import shutil
import subprocess
import tempfile
HERE = pathlib.Path(__file__).resolve().parent
RESULTS = HERE.parent / "results"
REPEATS = 5
# x86-64 syscall table: __NR_openat2 is 437. A different architecture numbers it differently,
# which is why the record carries the value it actually used.
OPENAT2_SYSCALL = 437
AT_FDCWD = -100
# The resolve masks are ABI, not measurements. They are named once here so a probe reads as intent
# rather than as a hexadecimal number nobody can place.
RESOLVE_NO_MAGICLINKS = 0x02
RESOLVE_NO_SYMLINKS = 0x04
RESOLVE_BENEATH = 0x08
RESOLVE_IN_ROOT = 0x10
RESOLVE_CACHED = 0x20
LIBC = ctypes.CDLL(None, use_errno=True)
class OpenHow(ctypes.Structure):
"""The three 64-bit fields ``openat2`` reads."""
_fields_ = [("flags", ctypes.c_uint64), ("mode", ctypes.c_uint64),
("resolve", ctypes.c_uint64)]
def openat2(path: str, flags: int = 0, resolve: int = 0, dirfd: int = AT_FDCWD) -> int:
"""Call ``openat2(2)`` and raise ``OSError`` with the kernel's errno on refusal."""
how = OpenHow(flags, 0, resolve)
result = LIBC.syscall(OPENAT2_SYSCALL, dirfd, path.encode(), ctypes.byref(how),
ctypes.sizeof(how))
if result < 0:
code = ctypes.get_errno()
raise OSError(code, os.strerror(code), path)
return int(result)
def openat2_works() -> bool:
"""Whether this host answers the call at all, measured by making one."""
try:
os.close(openat2(os.devnull))
return True
except OSError:
return False
def host() -> dict:
"""What a reader needs to know before comparing their numbers with these."""
return {
"kernel": platform.release(),
"machine": platform.machine(),
"python": platform.python_version(),
"page_size": os.sysconf("SC_PAGE_SIZE"),
"cpus": os.cpu_count(),
"uid": os.getuid(),
"tmp_fstype": fstype("/tmp"),
"work_fstype": fstype(str(HERE.parent)),
"path_max": os.pathconf("/", "PC_PATH_MAX"),
"openat2_works": openat2_works(),
"strerror_eloop": os.strerror(errno.ELOOP),
"strerror_enotdir": os.strerror(errno.ENOTDIR),
"strerror_enoent": os.strerror(errno.ENOENT),
"strerror_exdev": os.strerror(errno.EXDEV),
"coreutils": tool_version("ls", "--version"),
"findutils": tool_version("find", "--version"),
"tar": tool_version("tar", "--version"),
}
def fstype(path: str) -> str:
"""The filesystem type from /proc/self/mounts, longest matching mount point."""
best = ("", "")
for line in pathlib.Path("/proc/self/mounts").read_text().splitlines():
fields = line.split()
if len(fields) < 3:
continue
mount, kind = fields[1], fields[2]
if (path == mount or path.startswith(mount.rstrip("/") + "/")) and len(mount) >= len(best[0]):
best = (mount, kind)
return best[1]
def tool_version(name: str, flag: str) -> str:
"""First line of a tool's version output, or 'absent'."""
path = shutil.which(name)
if not path:
return "absent"
result = subprocess.run([path, flag], capture_output=True, text=True)
line = (result.stdout or result.stderr).strip().splitlines()
return line[0] if line else "unknown"
def record(probe: str, payload: dict) -> dict:
"""Write one probe record, stamped with the host, and return it."""
document = {"probe": probe, "host": host(), "repeats": REPEATS, **payload}
RESULTS.mkdir(parents=True, exist_ok=True)
path = RESULTS / f"{probe}.json"
path.write_text(json.dumps(document, indent=1, ensure_ascii=False) + "\n", encoding="utf-8")
print(f"wrote {path} ({path.stat().st_size} B)")
return document
def unanimous(arm: dict) -> bool:
keys = {(r.get("outcome"), r.get("type"), r.get("errno"), json.dumps(r.get("value"), default=str))
for r in arm["runs"]}
return len(keys) == 1
def tmpdir(prefix: str) -> pathlib.Path:
"""A fresh directory the probe owns; /tmp is tmpfs on this host."""
return pathlib.Path(tempfile.mkdtemp(prefix=prefix, dir="/tmp"))
def cleanup(path: pathlib.Path) -> None:
shutil.rmtree(path, ignore_errors=True)
the host, the number, and the platform limits sandbox/01_facts.py
"""Probe 01: the host, the number, and the documentation that names it.
The figures this page quotes as *measured* are read here, on this host: the interpreter's errno
table, ``getconf`` and ``pathconf``, the mount table, and one real ``openat2`` call. The figures
it quotes as *documented* are typed from each platform's published headers and documentation and
are marked as such, because no part of this probe can read a macOS or Windows constant. The
Windows limit in particular mirrors Microsoft's own wording, quoted in ``documented`` below.
"""
from __future__ import annotations
import errno
import os
import pathlib
import subprocess
import sys
import probelib
def getconf(name: str) -> dict:
"""Run ``getconf`` once and keep what it said, including a refusal."""
result = subprocess.run(["getconf", name], capture_output=True, text=True)
return {"value": (result.stdout or result.stderr).strip(), "rc": result.returncode}
def main() -> None:
work = probelib.tmpdir("eloop_probe_facts_")
try:
symloop = getconf("SYMLOOP_MAX")
measured = {
"errno_eloop": errno.ELOOP,
"errno_enotdir": errno.ENOTDIR,
"errno_enoent": errno.ENOENT,
"errno_exdev": errno.EXDEV,
"errno_eexist": errno.EEXIST,
"strerror_eloop": os.strerror(errno.ELOOP),
"strerror_enotdir": os.strerror(errno.ENOTDIR),
"path_max_tmp": os.pathconf("/tmp", "PC_PATH_MAX"),
"path_max_work": os.pathconf(str(probelib.HERE.parent), "PC_PATH_MAX"),
"name_max_tmp": os.pathconf("/tmp", "PC_NAME_MAX"),
"tmp_fstype": probelib.fstype("/tmp"),
"work_fstype": probelib.fstype(str(probelib.HERE.parent)),
"proc_self_fd_readable": pathlib.Path("/proc/self/fd").is_dir(),
"openat2_works": probelib.openat2_works(),
"o_path": os.O_PATH,
"o_nofollow": os.O_NOFOLLOW,
"o_directory": os.O_DIRECTORY,
"getconf_symloop_max": symloop["value"],
"getconf_symloop_rc": symloop["rc"],
"pathconf_symlink_max": os.pathconf("/", "PC_SYMLINK_MAX"),
}
documented = {
# ABI constants of the x86-64 kernel this host runs; stated, not measured.
"openat2_syscall": probelib.OPENAT2_SYSCALL,
"at_fdcwd": probelib.AT_FDCWD,
"resolve_no_magiclinks": probelib.RESOLVE_NO_MAGICLINKS,
"resolve_no_symlinks": probelib.RESOLVE_NO_SYMLINKS,
"resolve_beneath": probelib.RESOLVE_BENEATH,
"resolve_in_root": probelib.RESOLVE_IN_ROOT,
"resolve_cached": probelib.RESOLVE_CACHED,
# Another platform's published headers and documentation; no probe here can read them.
"macos": {"max_links": 32, "eloop": 62,
"source": "XNU bsd/sys/param.h MAXSYMLINKS 32; sys/errno.h ELOOP 62 "
"(not measured here)"},
"freebsd": {"max_links": 32, "eloop": 62,
"source": "FreeBSD sys/param.h MAXSYMLINKS 32; sys/errno.h ELOOP 62 "
"(not measured here)"},
"windows": {"max_links": 63, "eloop": 1921, "wsa": 10062,
"path_limit_quote": "There is a limit of 63 reparse points on any "
"given path",
"path_limit_caveat": "the limit can drop to 31 when a reparse point "
"targets a fully qualified path",
"source": "Microsoft Learn, Reparse Points and Programming "
"Considerations (Win32 fileio); WinError.h "
"ERROR_CANT_RESOLVE_FILENAME 1921, WSAELOOP 10062 "
"(not measured here)"},
}
runs = [{"outcome": "ok", **{k: measured[k] for k in
("errno_eloop", "strerror_eloop", "path_max_tmp",
"name_max_tmp", "tmp_fstype", "work_fstype",
"getconf_symloop_max", "pathconf_symlink_max",
"openat2_works")}}
for _ in range(probelib.REPEATS)]
record = probelib.record("01_facts", {
"notes": {
"temporary_root": str(work),
"getconf_symloop_max": symloop["value"],
"getconf_symloop_rc": symloop["rc"],
"documented_values_measured_here": 0,
"windows_limit_checked": "2026-12-02, Microsoft Learn: Reparse Points; "
"Programming Considerations (Local File Systems)",
},
"measured": measured,
"documented": documented,
"arms": [{"label": "host_and_number", "runs": runs}],
})
print("kernel", record["host"]["kernel"], "| python", record["host"]["python"],
"| ELOOP", measured["errno_eloop"], measured["strerror_eloop"])
print("fstypes", measured["tmp_fstype"], measured["work_fstype"])
print("getconf SYMLOOP_MAX:", repr(symloop["value"]), "rc", symloop["rc"],
"| pathconf PC_SYMLINK_MAX", measured["pathconf_symlink_max"],
"| openat2 works", measured["openat2_works"])
finally:
probelib.cleanup(work)
if __name__ == "__main__":
sys.exit(main())
eighteen calls sandbox/02_matrix.py
"""Probe 02: one number, many causes - which calls answer 40 and which answer something else.
Each round builds every fixture from scratch and performs each call once, so an arm that mutates
its tree cannot disturb the next arm or the next round. Five rounds give each arm five runs.
"""
from __future__ import annotations
import errno
import os
import sys
import probelib
openat2 = probelib.openat2
def build(root) -> dict[str, str]:
"""Every fixture the matrix needs, built once per round."""
root.mkdir(parents=True, exist_ok=True)
(root / "file").write_text("x")
os.symlink("file", root / "link_to_file")
(root / "dir").mkdir()
(root / "dir" / "inner").write_text("y")
os.symlink("dir", root / "link_to_dir")
os.symlink("nowhere", root / "dangling")
chain41 = root / "chain41"
chain41.mkdir()
for index in range(41):
destination = f"l{index + 1}" if index < 40 else "target"
os.symlink(destination, chain41 / f"l{index}")
(chain41 / "target").write_text("x")
chain40 = root / "chain40"
chain40.mkdir()
for index in range(40):
destination = f"l{index + 1}" if index < 39 else "target"
os.symlink(destination, chain40 / f"l{index}")
(chain40 / "target").write_text("x")
os.symlink("b", root / "a")
os.symlink("a", root / "b")
os.symlink("file", root / "doomed")
paths = {name: str(root / name) for name in
("file", "link_to_file", "dir", "link_to_dir", "dangling", "a", "b", "doomed")}
paths["chain41"] = str(chain41 / "l0")
paths["chain40"] = str(chain40 / "l0")
return paths
def close(fd: int) -> int:
os.close(fd)
return fd
ARMS = [
("open_41_links", lambda p: {"value": close(os.open(p["chain41"], os.O_RDONLY))}),
("open_40_links", lambda p: {"value": close(os.open(p["chain40"], os.O_RDONLY))}),
("stat_41_links", lambda p: {"value": os.stat(p["chain41"]).st_size}),
("lstat_41_links", lambda p: {"value": os.lstat(p["chain41"]).st_size}),
("listdir_cycle", lambda p: {"value": len(os.listdir(p["a"]))}),
("open_cycle_child", lambda p: {"value": close(os.open(p["a"] + "/inner", os.O_RDONLY))}),
("open_link_trailing_slash",
lambda p: {"value": close(os.open(p["link_to_file"] + "/", os.O_RDONLY))}),
("open_link_child",
lambda p: {"value": close(os.open(p["link_to_file"] + "/inner", os.O_RDONLY))}),
("open_missing", lambda p: {"value": close(os.open(p["dir"] + "/missing", os.O_RDONLY))}),
("open_dangling", lambda p: {"value": close(os.open(p["dangling"], os.O_RDONLY))}),
("access_41_links", lambda p: {"value": os.access(p["chain41"], os.R_OK)}),
("mkdir_over_dir_link", lambda p: {"value": os.mkdir(p["link_to_dir"])}),
("open_link_no_follow", lambda p: {"value": close(os.open(p["link_to_file"], os.O_NOFOLLOW))}),
("unlink_the_link",
lambda p: {"value": (os.unlink(p["doomed"]), os.path.lexists(p["doomed"]))[1]}),
("openat2_clean_file", lambda p: {"value": close(openat2(p["file"]))}),
("openat2_no_symlinks_final",
lambda p: {"value": close(openat2(p["link_to_file"], resolve=probelib.RESOLVE_NO_SYMLINKS))}),
("openat2_no_symlinks_intermediate",
lambda p: {"value": close(openat2(p["link_to_dir"] + "/inner", resolve=probelib.RESOLVE_NO_SYMLINKS))}),
("openat2_beneath_absolute",
lambda p: {"value": close(openat2(p["file"], resolve=probelib.RESOLVE_BENEATH))}),
]
def main() -> None:
work = probelib.tmpdir("eloop_probe_matrix_")
collected: dict[str, list[dict]] = {label: [] for label, _ in ARMS}
try:
for round_index in range(probelib.REPEATS):
paths = build(work / f"r{round_index}")
for label, fn in ARMS:
try:
collected[label].append({"outcome": "ok", **fn(paths)})
except BaseException as exc:
collected[label].append({
"outcome": "error", "type": type(exc).__name__,
"errno": getattr(exc, "errno", None),
"strerror": getattr(exc, "strerror", None),
"message": str(exc)[:200]})
merged = [{"label": label, "runs": collected[label]} for label, _ in ARMS]
eloop = [arm["label"] for arm in merged if arm["runs"][0].get("errno") == errno.ELOOP]
record = probelib.record("02_matrix", {
"notes": {
"arms": len(merged),
"calls": len(merged) * probelib.REPEATS,
"eloop_arms": len(eloop),
"eloop_labels": eloop,
"unanimous": all(probelib.unanimous(arm) for arm in merged),
},
"arms": merged,
})
print(f"{record['notes']['arms']} arms x {probelib.REPEATS}; "
f"{record['notes']['eloop_arms']} answered 40; "
f"unanimous={record['notes']['unanimous']}")
for arm in merged:
run = arm["runs"][0]
print(f" {arm['label']:34s} {run['outcome']:5s} {run.get('type') or '':16s} "
f"errno={run.get('errno')} value={run.get('value')}")
finally:
probelib.cleanup(work)
if __name__ == "__main__":
sys.exit(main())
the ladder sandbox/03_hops.py
"""Probe 03: where the ceiling sits, and what is counted toward it.
The ladder walks from 36 to 42 links; the mixed arms split the same budget across two
directories; the prefix arm puts 40 links under twelve real directories; the self-link arm
spends the budget on one link object reached many times. Five rounds, one fresh tree each.
"""
from __future__ import annotations
import errno
import os
import sys
import probelib
LADDER = (36, 37, 38, 39, 40, 41, 42)
def open_once(path: str) -> dict:
"""Open the path once; the byte length is a property of the path, so it is recorded on
success and on refusal alike."""
length = len(path.encode())
fd = os.open(path, os.O_RDONLY)
try:
return {"value": os.read(fd, 1).decode(), "bytes": length, "links": None}
finally:
os.close(fd)
def build_chain(root, hops: int, absolute: bool = False) -> str:
root.mkdir(parents=True, exist_ok=True)
(root / "target").write_text("x")
for index in range(hops):
destination = f"l{index + 1}" if index < hops - 1 else "target"
if absolute:
destination = str(root / destination)
os.symlink(destination, root / f"l{index}")
return str(root / "l0")
def build_self(root, hops: int) -> str:
"""A directory with a link back to itself, reached ``hops`` times in one path."""
root.mkdir(parents=True, exist_ok=True)
(root / "file").write_text("x")
os.symlink(".", root / "self")
return str(root / "/".join(["self"] * hops) / "file")
def build_split(root, left: int, right: int) -> str:
"""``left`` links in one directory, then ``right`` in a second: one path, two ladders."""
root.mkdir(parents=True, exist_ok=True)
first = root / "first"
second = root / "second"
first.mkdir()
second.mkdir()
(second / "target").write_text("x")
for index in range(right):
destination = f"r{index + 1}" if index < right - 1 else "target"
os.symlink(destination, second / f"r{index}")
for index in range(left):
destination = (f"l{index + 1}" if index < left - 1
else "../second/r0")
os.symlink(destination, first / f"l{index}")
return str(first / "l0")
def build_prefixed(root, hops: int, depth: int) -> str:
"""The same 40-link chain, reached through ``depth`` real directories."""
nest = root
for index in range(depth):
nest = nest / f"d{index}"
nest.mkdir(parents=True, exist_ok=True)
(nest / "target").write_text("x")
for index in range(hops):
destination = f"l{index + 1}" if index < hops - 1 else "target"
os.symlink(destination, nest / f"l{index}")
return str(nest / "l0")
def main() -> None:
work = probelib.tmpdir("eloop_probe_hops_")
collected: dict[str, list[dict]] = {}
try:
for round_index in range(probelib.REPEATS):
root = work / f"r{round_index}"
arms = []
for hops in LADDER:
arms.append((f"relative_{hops}", build_chain(root / f"rel{hops}", hops)))
for hops in (40, 41):
arms.append((f"absolute_{hops}",
build_chain(root / f"abs{hops}", hops, absolute=True)))
arms.append(("split_20_20", build_split(root / "split40", 20, 20)))
arms.append(("split_20_21", build_split(root / "split41", 20, 21)))
arms.append(("prefixed_12_dirs_40", build_prefixed(root / "prefixed", 40, 12)))
for hops in (40, 41):
arms.append((f"self_link_{hops}", build_self(root / f"self{hops}", hops)))
arms.append(("plain_file", str(root / "plain")))
(root / "plain").parent.mkdir(parents=True, exist_ok=True)
(root / "plain").write_text("x")
for label, path in arms:
try:
result = open_once(path)
except BaseException as exc:
result = {"outcome": "error", "type": type(exc).__name__,
"errno": getattr(exc, "errno", None),
"strerror": getattr(exc, "strerror", None),
"bytes": len(path.encode()),
"message": str(exc)[:160]}
collected.setdefault(label, []).append({"outcome": "ok", **result})
merged = [{"label": label, "runs": runs} for label, runs in collected.items()]
passing = [arm["label"] for arm in merged if arm["runs"][0]["outcome"] == "ok"]
refused = [arm["label"] for arm in merged if arm["runs"][0].get("errno") == errno.ELOOP]
record = probelib.record("03_hops", {
"notes": {
"ladder": list(LADDER),
"arms": len(merged),
"last_ok_relative": max(int(label.split("_")[1]) for label in passing
if label.startswith("relative_")),
"first_refused_relative": min(int(label.split("_")[1]) for label in refused
if label.startswith("relative_")),
"refused": refused,
"passing": passing,
"unanimous": all(probelib.unanimous(arm) for arm in merged),
},
"arms": merged,
})
print(f"{record['notes']['arms']} arms; last ok {record['notes']['last_ok_relative']} "
f"links, first refused {record['notes']['first_refused_relative']}; "
f"unanimous={record['notes']['unanimous']}")
for arm in merged:
run = arm["runs"][0]
print(f" {arm['label']:22s} {run['outcome']:5s} errno={run.get('errno')} "
f"bytes={run.get('bytes')}")
finally:
probelib.cleanup(work)
if __name__ == "__main__":
sys.exit(main())
flag combinations sandbox/04_flags.py
"""Probe 04: the flag decides which refusal you get.
The same symlink is opened under different flag combinations; the same path is resolved under
different openat2 resolve masks. What changes between an ELOOP and a successful open is one bit.
"""
from __future__ import annotations
import errno
import os
import stat
import sys
import probelib
openat2 = probelib.openat2
def describe(fd: int) -> dict:
"""What the descriptor points at, and what its own /proc entry says."""
info = os.fstat(fd)
entry = f"/proc/self/fd/{fd}"
try:
target = os.readlink(entry)
except OSError as exc:
target = f"{type(exc).__name__}:{exc.errno}"
kind = ("directory" if stat.S_ISDIR(info.st_mode) else "symlink"
if stat.S_ISLNK(info.st_mode) else "file")
os.close(fd)
return {"kind": kind, "target": target, "size": info.st_size}
def build(root) -> dict[str, str]:
root.mkdir(parents=True, exist_ok=True)
(root / "file").write_text("x")
(root / "dir").mkdir()
(root / "dir" / "inner").write_text("y")
os.symlink("file", root / "link_to_file")
os.symlink("dir", root / "link_to_dir")
paths = {name: str(root / name) for name in ("file", "dir", "link_to_file", "link_to_dir")}
paths["inner_via_link"] = str(root / "link_to_dir" / "inner")
return paths
ARMS = [
("file_plain", lambda p: describe(os.open(p["file"], os.O_RDONLY))),
("file_no_follow", lambda p: describe(os.open(p["file"], os.O_RDONLY | os.O_NOFOLLOW))),
("link_plain", lambda p: describe(os.open(p["link_to_file"], os.O_RDONLY))),
("link_no_follow", lambda p: describe(os.open(p["link_to_file"], os.O_RDONLY | os.O_NOFOLLOW))),
("link_path", lambda p: describe(os.open(p["link_to_file"], os.O_PATH))),
("link_path_no_follow",
lambda p: describe(os.open(p["link_to_file"], os.O_PATH | os.O_NOFOLLOW))),
("link_no_follow_directory",
lambda p: describe(os.open(p["link_to_file"], os.O_RDONLY | os.O_NOFOLLOW | os.O_DIRECTORY))),
("link_directory", lambda p: describe(os.open(p["link_to_file"], os.O_RDONLY | os.O_DIRECTORY))),
("dir_link_plain", lambda p: describe(os.open(p["link_to_dir"], os.O_RDONLY))),
("dir_link_no_follow",
lambda p: describe(os.open(p["link_to_dir"], os.O_RDONLY | os.O_NOFOLLOW))),
("dir_link_no_follow_directory",
lambda p: describe(os.open(p["link_to_dir"], os.O_RDONLY | os.O_NOFOLLOW | os.O_DIRECTORY))),
("intermediate_link_plain", lambda p: describe(os.open(p["inner_via_link"], os.O_RDONLY))),
("intermediate_link_no_follow",
lambda p: describe(os.open(p["inner_via_link"], os.O_RDONLY | os.O_NOFOLLOW))),
("create_exclusive_over_link",
lambda p: describe(os.open(p["link_to_file"], os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600))),
("openat2_file_clean", lambda p: describe(openat2(p["file"]))),
("openat2_file_no_symlinks", lambda p: describe(openat2(p["file"], resolve=probelib.RESOLVE_NO_SYMLINKS))),
("openat2_link_no_symlinks",
lambda p: describe(openat2(p["link_to_file"], resolve=probelib.RESOLVE_NO_SYMLINKS))),
("openat2_intermediate_no_symlinks",
lambda p: describe(openat2(p["inner_via_link"], resolve=probelib.RESOLVE_NO_SYMLINKS))),
("openat2_link_beneath", lambda p: describe(openat2(p["link_to_file"], resolve=probelib.RESOLVE_BENEATH))),
("openat2_file_beneath_absolute", lambda p: describe(openat2(p["file"], resolve=probelib.RESOLVE_BENEATH))),
("openat2_file_in_root", lambda p: describe(openat2(p["file"], resolve=probelib.RESOLVE_IN_ROOT))),
]
MAGIC_LABELS = ["openat2_magiclink_plain", "openat2_magiclink_no_magic",
"openat2_beneath_relative_dirfd", "openat2_beneath_escape"]
def magic_link_arms(fd: int) -> list[tuple[str, callable]]:
"""The /proc/self/fd arms need a descriptor the probe owns, not whatever fd 0 happens to be."""
entry = f"/proc/self/fd/{fd}"
return [
("openat2_magiclink_plain", lambda p: describe(openat2(entry))),
("openat2_magiclink_no_magic", lambda p: describe(openat2(entry, resolve=probelib.RESOLVE_NO_MAGICLINKS))),
]
def beneath_arms(dirfd: int) -> list[tuple[str, callable]]:
"""RESOLVE_BENEATH under a real descriptor: a name inside the tree, and a climb out of it."""
return [
("openat2_beneath_relative_dirfd",
lambda p: describe(openat2("inner", resolve=probelib.RESOLVE_BENEATH, dirfd=dirfd))),
("openat2_beneath_escape",
lambda p: describe(openat2("../file", resolve=probelib.RESOLVE_BENEATH, dirfd=dirfd))),
]
def main() -> None:
work = probelib.tmpdir("eloop_probe_flags_")
collected: dict[str, list[dict]] = {label: [] for label, _ in ARMS}
collected.update({label: [] for label in MAGIC_LABELS})
try:
for round_index in range(probelib.REPEATS):
paths = build(work / f"r{round_index}")
fd = os.open(paths["file"], os.O_RDONLY)
dirfd = os.open(paths["dir"], os.O_PATH)
try:
arms = list(ARMS) + magic_link_arms(fd) + beneath_arms(dirfd)
for label, fn in arms:
try:
collected[label].append({"outcome": "ok", **fn(paths)})
except BaseException as exc:
collected[label].append({
"outcome": "error", "type": type(exc).__name__,
"errno": getattr(exc, "errno", None),
"strerror": getattr(exc, "strerror", None),
"message": str(exc)[:200]})
finally:
os.close(fd)
os.close(dirfd)
merged = [{"label": label, "runs": collected[label]}
for label in [label for label, _ in ARMS] + MAGIC_LABELS]
record = probelib.record("04_flags", {
"notes": {
"arms": len(merged),
"unanimous": all(probelib.unanimous(arm) for arm in merged),
"eloop": [arm["label"] for arm in merged if arm["runs"][0].get("errno") == errno.ELOOP],
"ok": [arm["label"] for arm in merged if arm["runs"][0]["outcome"] == "ok"],
},
"arms": merged,
})
print(f"{record['notes']['arms']} arms, unanimous={record['notes']['unanimous']}")
for arm in merged:
run = arm["runs"][0]
print(f" {arm['label']:32s} {run['outcome']:5s} errno={str(run.get('errno')):4s} "
f"kind={run.get('kind')} target={str(run.get('target'))[:40]}")
finally:
probelib.cleanup(work)
if __name__ == "__main__":
sys.exit(main())
loops and magic links sandbox/05_loops.py
"""Probe 05: loops that no link chain explains.
A self-link, a pair that points at each other, a directory that contains itself, and the
/proc/self/fd magic link whose target is a symlink. Each is opened, stated, read through and
listed, so the page can say which call refuses and which call simply reports the text.
"""
from __future__ import annotations
import errno
import os
import sys
import probelib
openat2 = probelib.openat2
def read_one(path: str) -> dict:
fd = os.open(path, os.O_RDONLY)
try:
return {"value": os.read(fd, 1).decode()}
finally:
os.close(fd)
def build(root) -> dict[str, str]:
root.mkdir(parents=True, exist_ok=True)
(root / "file").write_text("x")
os.symlink("file", root / "link")
os.symlink("selfme", root / "selfme")
os.symlink("b", root / "a")
os.symlink("a", root / "b")
growth = root / "growth"
growth.mkdir()
os.symlink(".", growth / "self")
(growth / "file").write_text("x")
climb = root / "climb"
(climb / "sub").mkdir(parents=True)
os.symlink("..", climb / "sub" / "up")
(climb / "file").write_text("x")
paths = {name: str(root / name) for name in ("file", "link", "selfme", "a", "b")}
paths["growth_40"] = str(growth / "/".join(["self"] * 40) / "file")
paths["growth_41"] = str(growth / "/".join(["self"] * 41) / "file")
paths["climb_40"] = str(climb / "/".join(["sub/up"] * 40) / "file")
paths["climb_41"] = str(climb / "/".join(["sub/up"] * 41) / "file")
return paths
def magic_link_arms(paths: dict[str, str]) -> tuple[list[tuple[str, callable]], list[int]]:
"""The /proc/self/fd arms need open descriptors, so they are built per run."""
fd_link = os.open(paths["link"], os.O_PATH | os.O_NOFOLLOW) # fd to a symlink
fd_file = os.open(paths["file"], os.O_RDONLY) # fd to a regular file
arms = [
("magic_link_to_symlink", lambda p: read_one(f"/proc/self/fd/{fd_link}")),
("magic_link_to_file", lambda p: read_one(f"/proc/self/fd/{fd_file}")),
("magic_link_readlink_symlink",
lambda p: {"value": os.path.basename(os.readlink(f"/proc/self/fd/{fd_link}")),
"is_the_link": os.path.realpath(f"/proc/self/fd/{fd_link}") == paths["link"]}),
("magic_link_no_magic", lambda p: {"value": os.close(
openat2(f"/proc/self/fd/{fd_file}", resolve=probelib.RESOLVE_NO_MAGICLINKS))}),
]
return arms, [fd_link, fd_file]
ARMS = [
("self_link_open", lambda p: read_one(p["selfme"])),
("self_link_lstat", lambda p: {"value": os.lstat(p["selfme"]).st_size}),
("self_link_readlink", lambda p: {"value": os.readlink(p["selfme"])}),
("pair_open", lambda p: read_one(p["a"])),
("pair_stat", lambda p: {"value": os.stat(p["a"]).st_size}),
("pair_lstat", lambda p: {"value": os.lstat(p["a"]).st_size}),
("pair_readlink", lambda p: {"value": os.readlink(p["a"])}),
("growth_40_hops", lambda p: read_one(p["growth_40"])),
("growth_41_hops", lambda p: read_one(p["growth_41"])),
("climb_40_hops", lambda p: read_one(p["climb_40"])),
("climb_41_hops", lambda p: read_one(p["climb_41"])),
("loop_through_parent", lambda p: read_one(p["a"] + "/../file")),
("listdir_growth_top", lambda p: {"value": len(os.listdir(os.path.dirname(p["growth_40"])))}),
]
def main() -> None:
work = probelib.tmpdir("eloop_probe_loops_")
magic_labels = ["magic_link_to_symlink", "magic_link_to_file",
"magic_link_readlink_symlink", "magic_link_no_magic"]
collected: dict[str, list[dict]] = {label: [] for label, _ in ARMS}
collected.update({label: [] for label in magic_labels})
try:
for round_index in range(probelib.REPEATS):
paths = build(work / f"r{round_index}")
magic, descriptors = magic_link_arms(paths)
try:
for label, fn in list(ARMS) + magic:
try:
collected[label].append({"outcome": "ok", **fn(paths)})
except BaseException as exc:
collected[label].append({
"outcome": "error", "type": type(exc).__name__,
"errno": getattr(exc, "errno", None),
"strerror": getattr(exc, "strerror", None),
"message": str(exc)[:200]})
finally:
for descriptor in descriptors:
os.close(descriptor)
merged = [{"label": label, "runs": collected[label]}
for label, _ in ARMS] + [{"label": label, "runs": collected[label]}
for label in magic_labels]
record = probelib.record("05_loops", {
"notes": {
"arms": len(merged),
"unanimous": all(probelib.unanimous(arm) for arm in merged),
"eloop": [arm["label"] for arm in merged if arm["runs"][0].get("errno") == errno.ELOOP],
},
"arms": merged,
})
print(f"{record['notes']['arms']} arms, unanimous={record['notes']['unanimous']}")
for arm in merged:
run = arm["runs"][0]
print(f" {arm['label']:28s} {run['outcome']:5s} "
f"errno={str(run.get('errno')):4s} type={str(run.get('type'))[:18]:18s} "
f"value={str(run.get('value'))[:30]}")
finally:
probelib.cleanup(work)
if __name__ == "__main__":
sys.exit(main())
Python’s three behaviours sandbox/06_python.py
"""Probe 06: what the Python layer does with the same refusal.
Three behaviours are mixed in the standard library: raise (``os.stat``), swallow and return
False (``os.path.exists``), and resolve the chain in userspace until it ends (``realpath``). The
traversal arms record how far each walk gets before it is stopped - by the probe's own cap, or,
for the ones that follow links, by the kernel refusing a ``scandir``.
"""
from __future__ import annotations
import errno
import os
import pathlib
import shutil
import sys
import probelib
CAP = 3000
def read_one(path: str) -> dict:
fd = os.open(path, os.O_RDONLY)
try:
return {"value": os.read(fd, 1).decode()}
finally:
os.close(fd)
def build(root) -> dict[str, str]:
root.mkdir(parents=True, exist_ok=True)
(root / "file").write_text("x")
chain = root / "chain41"
chain.mkdir()
for index in range(41):
destination = f"l{index + 1}" if index < 40 else "target"
os.symlink(destination, chain / f"l{index}")
(chain / "target").write_text("x")
cyc = root / "cyc"
cyc.mkdir()
os.symlink("..", cyc / "up")
(cyc / "file").write_text("x")
pairdir = root / "pairdir"
pairdir.mkdir()
os.symlink("b", pairdir / "a")
os.symlink("a", pairdir / "b")
(pairdir / "file").write_text("x")
# A loop tree of its own, beside the walk's tree rather than inside it: a second route back
# into the root would multiply the walk's branches and turn its count into the probe's cap.
doomed = root.parent / "doomed"
doomed.mkdir()
os.symlink("..", doomed / "up")
(doomed / "file").write_text("x")
paths = {"file": str(root / "file"), "chain": str(chain / "l0"),
"cyc": str(cyc), "pair": str(pairdir / "a"), "root": str(root),
"doomed": str(doomed)}
return paths
def walk_cap(root: str, follow: bool) -> dict:
"""Walk until the cap, recording how many directories and how deep."""
seen = 0
deepest = 0
for current, dirs, _files in os.walk(root, followlinks=follow):
seen += 1
deepest = max(deepest, current.count(os.sep))
if seen >= CAP:
break
return {"value": seen, "depth": deepest}
def glob_cap(root: str) -> dict:
seen = 0
for _ in pathlib.Path(root).glob("**/*"):
seen += 1
if seen >= CAP:
break
return {"value": seen}
def copytree_cycles(source: str, target: str, symlinks: bool) -> dict:
shutil.copytree(source, target, symlinks=symlinks, dirs_exist_ok=True)
return {"value": sum(1 for _ in pathlib.Path(target).rglob("*"))}
ARMS = [
("open_41", lambda p: read_one(p["chain"])),
("os_stat_41", lambda p: {"value": os.stat(p["chain"]).st_size}),
("os_lstat_41", lambda p: {"value": os.lstat(p["chain"]).st_size}),
("os_path_exists_41", lambda p: {"value": os.path.exists(p["chain"])}),
("os_path_isfile_41", lambda p: {"value": os.path.isfile(p["chain"])}),
("os_path_isdir_41", lambda p: {"value": os.path.isdir(p["chain"])}),
("os_access_41", lambda p: {"value": os.access(p["chain"], os.R_OK)}),
("realpath_41", lambda p: {"value": os.path.basename(os.path.realpath(p["chain"]))}),
("realpath_strict_41",
lambda p: {"value": os.path.basename(os.path.realpath(p["chain"], strict=True))}),
("path_exists_41", lambda p: {"value": pathlib.Path(p["chain"]).exists()}),
("path_stat_41", lambda p: {"value": pathlib.Path(p["chain"]).stat().st_size}),
("path_resolve_41", lambda p: {"value": pathlib.Path(p["chain"]).resolve().name}),
("path_resolve_strict_41",
lambda p: {"value": pathlib.Path(p["chain"]).resolve(strict=True).name}),
("path_read_text_41", lambda p: {"value": pathlib.Path(p["chain"]).read_text()}),
("listdir_cycle", lambda p: {"value": len(os.listdir(p["pair"]))}),
("walk_cycle_nofollow", lambda p: walk_cap(p["cyc"], False)),
("walk_cycle_follow", lambda p: walk_cap(p["cyc"], True)),
("glob_cycle", lambda p: glob_cap(p["cyc"])),
("rmtree_cycle", lambda p: {"value": (shutil.rmtree(p["doomed"]), "done")[1],
"gone": not os.path.exists(p["doomed"])}),
("copytree_symlinks_true",
lambda p: copytree_cycles(p["cyc"], p["root"] + "/copy_true", True)),
("copytree_symlinks_false",
lambda p: copytree_cycles(p["cyc"], p["root"] + "/copy_false", False)),
]
def main() -> None:
work = probelib.tmpdir("eloop_probe_python_")
collected: dict[str, list[dict]] = {label: [] for label, _ in ARMS}
try:
for round_index in range(probelib.REPEATS):
paths = build(work / f"r{round_index}")
for label, fn in ARMS:
try:
collected[label].append({"outcome": "ok", **fn(paths)})
except BaseException as exc:
collected[label].append({
"outcome": "error", "type": type(exc).__name__,
"errno": getattr(exc, "errno", None),
"strerror": getattr(exc, "strerror", None),
"message": str(exc)[:160]})
merged = [{"label": label, "runs": collected[label]} for label, _ in ARMS]
record = probelib.record("06_python", {
"notes": {
"arms": len(merged),
"cap": CAP,
"unanimous": all(probelib.unanimous(arm) for arm in merged),
"eloop": [arm["label"] for arm in merged if arm["runs"][0].get("errno") == errno.ELOOP],
"swallowed": [arm["label"] for arm in merged
if arm["runs"][0]["outcome"] == "ok"
and arm["runs"][0].get("value") is False],
},
"arms": merged,
})
print(f"{record['notes']['arms']} arms, unanimous={record['notes']['unanimous']}")
for arm in merged:
run = arm["runs"][0]
print(f" {arm['label']:26s} {run['outcome']:5s} "
f"errno={str(run.get('errno')):4s} type={str(run.get('type'))[:18]:18s} "
f"value={str(run.get('value'))[:24]}")
finally:
probelib.cleanup(work)
if __name__ == "__main__":
sys.exit(main())
the shell tools sandbox/07_shell.py
"""Probe 07: the shell tools that a deploy script actually calls.
Each tool runs five times against a tree with three different loops in it: a link to itself, a
directory that contains its own parent, and a chain that is one link too long. What is recorded
is the exit status and the first diagnostic - the two things a pipeline branches on.
"""
from __future__ import annotations
import os
import subprocess
import sys
import probelib
def build(root) -> dict[str, str]:
root.mkdir(parents=True, exist_ok=True)
tree = root / "tree"
(tree / "sub").mkdir(parents=True)
(tree / "file").write_text("x")
os.symlink("selfme", tree / "selfme")
os.symlink("..", tree / "sub" / "up")
chain = tree / "chain"
chain.mkdir()
for index in range(41):
destination = f"l{index + 1}" if index < 40 else "target"
os.symlink(destination, chain / f"l{index}")
(chain / "target").write_text("x")
return {"root": str(root), "tree": str(tree), "self": str(tree / "selfme"),
"chain": str(chain / "l0"), "up": str(tree / "sub" / "up")}
def run(argv: list[str], cwd: str, timeout: int = 90) -> dict:
try:
result = subprocess.run(argv, cwd=cwd, capture_output=True, text=True, timeout=timeout)
except subprocess.TimeoutExpired:
return {"outcome": "timeout", "rc": None, "out_lines": 0, "err_lines": 0,
"messages": [], "first": "", "second": "", "first_out": ""}
err = result.stderr.strip().splitlines()
out = result.stdout.strip().splitlines()
return {"outcome": "ok", "rc": result.returncode, "out_lines": len(out),
"err_lines": len(err),
# Every diagnostic, so a caption that counts messages can be checked against them.
"messages": [line[:160] for line in err[:8]],
"first": err[0][:160] if err else (out[0][:160] if out else ""),
"second": err[1][:160] if len(err) > 1 else "",
"first_out": out[0][:160] if out else ""}
def arms_for(p: dict) -> list[tuple[str, list[str]]]:
return [
("ls_l_symlink", ["ls", "-l", p["self"]]),
("ls_lL_symlink", ["ls", "-lL", p["self"]]),
("stat_symlink", ["stat", p["self"]]),
("stat_L_symlink", ["stat", "-L", p["self"]]),
("readlink_f_chain", ["readlink", "-f", p["chain"]]),
("realpath_e_symlink", ["realpath", "-e", p["self"]]),
("realpath_m_symlink", ["realpath", "-m", p["self"]]),
("find_no_follow", ["find", p["tree"], "-maxdepth", "3"]),
("find_L_tree", ["find", "-L", p["tree"], "-maxdepth", "3"]),
("cp_r_tree", ["cp", "-r", p["tree"], p["root"] + "/copy_plain"]),
("cp_rL_tree", ["cp", "-rL", p["tree"], p["root"] + "/copy_follow"]),
("tar_c_tree", ["tar", "-c", "-f", "/dev/null", p["tree"]]),
("tar_h_tree", ["tar", "-c", "-h", "-f", "/dev/null", p["tree"]]),
("du_L_tree", ["du", "-sL", p["tree"]]),
]
def main() -> None:
work = probelib.tmpdir("eloop_probe_shell_")
labels = [label for label, _ in arms_for({"root": "", "tree": "", "self": "", "chain": "",
"up": ""})]
collected: dict[str, list[dict]] = {label: [] for label in labels}
try:
for round_index in range(probelib.REPEATS):
paths = build(work / f"r{round_index}")
for label, argv in arms_for(paths):
result = run(argv, cwd=paths["root"])
result["messages"] = [line.replace(paths["root"], "<root>")
for line in result["messages"]]
for key in ("first", "second", "first_out"):
result[key] = result[key].replace(paths["root"], "<root>")
collected[label].append(result)
for leftover in ("copy_plain", "copy_follow"):
probelib.cleanup(work / f"r{round_index}" / leftover)
merged = [{"label": label, "runs": collected[label]} for label in labels]
record = probelib.record("07_shell", {
"notes": {
"arms": len(merged),
"unanimous_rc": all(len({run["rc"] for run in arm["runs"]}) == 1 for arm in merged),
"segfault": [arm["label"] for arm in merged
if arm["runs"][0]["rc"] == -11],
"timeouts": [arm["label"] for arm in merged
if arm["runs"][0]["outcome"] == "timeout"],
"condition": "three loops in one tree: selfme -> selfme, sub/up -> .., 41-link chain",
},
"arms": merged,
})
print(f"{record['notes']['arms']} arms, rc unanimous={record['notes']['unanimous_rc']}, "
f"segfault={record['notes']['segfault']}")
for arm in merged:
first_run = arm["runs"][0]
print(f" {arm['label']:20s} rc={str(first_run['rc']):7s} "
f"err_lines={first_run['err_lines']:5d} "
f"| {first_run['first'][:90]}")
finally:
probelib.cleanup(work)
if __name__ == "__main__":
sys.exit(main())
what a hop costs sandbox/08_cost.py
"""Probe 08: what each link in the chain costs before the kernel refuses.
Two thousand opens per run through chains of 0, 10, 20, 30 and 40 links, on tmpfs, with the
directory entries already hot. The median of each round is kept, and the record carries the
median of the five medians with the min-max band, because a two-core host is a noisy clock.
"""
from __future__ import annotations
import os
import statistics
import sys
import time
import probelib
ITERATIONS = 2000
HOPS = (0, 10, 20, 30, 40)
def build_chain(root, hops: int) -> str:
root.mkdir(parents=True, exist_ok=True)
(root / "target").write_text("x")
for index in range(hops):
destination = f"l{index + 1}" if index < hops - 1 else "target"
os.symlink(destination, root / f"l{index}")
return str(root / "target") if hops == 0 else str(root / "l0")
def time_opens(path: str, iterations: int = ITERATIONS) -> dict:
timer = time.perf_counter_ns
start = timer()
for _ in range(iterations):
os.close(os.open(path, os.O_RDONLY))
elapsed = timer() - start
return {"ns_per_open": elapsed / iterations, "iterations": iterations,
"total_ms": elapsed / 1e6}
def time_realpath(root: str) -> dict:
path = os.path.join(root, "l0")
timer = time.perf_counter_ns
start = timer()
for _ in range(200):
os.path.realpath(path, strict=True)
elapsed = timer() - start
return {"ns_per_resolve": elapsed / 200, "iterations": 200, "total_ms": elapsed / 1e6}
def main() -> None:
work = probelib.tmpdir("eloop_probe_cost_")
collected: dict[str, list[float]] = {}
resolve: list[float] = []
try:
for round_index in range(probelib.REPEATS):
root = work / f"r{round_index}"
for hops in HOPS:
path = build_chain(root / f"c{hops}", hops)
result = time_opens(path)
collected.setdefault(f"open_{hops}_links", []).append(result["ns_per_open"])
build_chain(root / "c41", 41)
resolve.append(time_realpath(str(root / "c41"))["ns_per_resolve"])
arms = []
for label, values in collected.items():
median = statistics.median(values)
arms.append({"label": label, "runs": [{"outcome": "ok", "ns_per_open": value}
for value in values],
"median_ns": median, "min_ns": min(values), "max_ns": max(values)})
resolve_median = statistics.median(resolve)
probelib.record("08_cost", {
"notes": {
"iterations_per_run": ITERATIONS,
"hops": list(HOPS),
"realpath_iterations": 200,
"median_ns_by_hops": {label: arm["median_ns"] for label, arm in
zip(collected, arms)},
"realpath_median_ns": resolve_median,
"realpath_min_ns": min(resolve), "realpath_max_ns": max(resolve),
"fstype": probelib.fstype("/tmp"),
},
"arms": arms + [{"label": "realpath_strict_41_links",
"runs": [{"outcome": "ok", "ns_per_resolve": value}
for value in resolve],
"median_ns": resolve_median, "min_ns": min(resolve),
"max_ns": max(resolve)}],
})
for arm in arms:
print(f" {arm['label']:18s} median {arm['median_ns'] / 1000:8.2f} us "
f"(min {arm['min_ns'] / 1000:.2f}, max {arm['max_ns'] / 1000:.2f})")
print(f" {'realpath_41':18s} median {resolve_median / 1000:8.2f} us "
f"(min {min(resolve) / 1000:.2f}, max {max(resolve) / 1000:.2f})")
finally:
probelib.cleanup(work)
if __name__ == "__main__":
sys.exit(main())
the tree’s own counts sandbox/09_counts.py
"""Probe 09: the counts the page quotes about its own tree.
The suite is run here so the number in the prose is the number pytest reported, not a number
someone typed after a green run.
"""
from __future__ import annotations
import json
import pathlib
import re
import subprocess
import sys
import probelib
HERE = probelib.HERE.parent
def lines(path: pathlib.Path) -> int:
return len(path.read_text(encoding="utf-8").splitlines())
def family(directory: pathlib.Path) -> dict:
files = sorted(path for path in directory.glob("*.py") if path.name != "__pycache__")
return {"files": len(files), "lines": sum(lines(path) for path in files),
"names": [path.name for path in files]}
def main() -> None:
package = family(HERE / "pathguard") | {"tests": family(HERE / "pathguard" / "tests")}
probes = family(HERE / "sandbox")
example = family(HERE / "examples")
result = subprocess.run([sys.executable, "-m", "pytest", "pathguard/tests", "-q",
"-p", "no:cacheprovider", "-p", "no:warnings"],
cwd=str(HERE), capture_output=True, text=True)
passed = 0
if match := re.search(r"(\d+) passed", result.stdout + result.stderr):
passed = int(match.group(1))
record = probelib.record("09_counts", {
"notes": {
"package_files": package["files"],
"package_lines": package["lines"],
"test_files": package["tests"]["files"],
"test_lines": package["tests"]["lines"],
"probe_files": probes["files"],
"probe_lines": probes["lines"],
"example_files": example["files"],
"example_lines": example["lines"],
"pytest_passed": passed,
"pytest_rc": result.returncode,
"package_names": package["names"],
"test_names": package["tests"]["names"],
"probe_names": probes["names"],
},
"arms": [{"label": "tree_counts", "runs": [{"outcome": "ok", "pytest_passed": passed}]}],
})
print(json.dumps(record["notes"], indent=1))
if __name__ == "__main__":
sys.exit(main())
the deploy, the window, and the pinned descriptor sandbox/11_deploy.py
"""Probe 11: the deploy command that writes through the link instead of replacing it.
A release layout is one directory of versions and one link that names the live one. Both of these
exit zero and look right in a deploy log, and only one makes ``current`` name the release that was
just built:
ln -sf v2 current # writes *through* current, which is a link to a directory
ln -sfn releases/v2 current # replaces the link itself
The first leaves ``current`` on the old release and drops a link inside it whose target is its own
name, so ``current/v2`` answers ELOOP. The next three arms count a path and then swap the link
underneath the count: a userspace pre-count is a snapshot, and these arms measure what the open
does after the snapshot is stale. The last arm is the repair for exactly that window: resolve
``current`` once into a directory descriptor and open every name beneath it with ``openat``, so
the deploy that replaces the link cannot change what this reader is reading.
"""
from __future__ import annotations
import json
import os
import pathlib
import subprocess
import probelib
from pathguard import count_links
def tree(root: pathlib.Path) -> dict[str, pathlib.Path]:
"""One release layout, built fresh for this run."""
app = root / "app"
for version in ("v1", "v2"):
settings = app / "releases" / version / "conf" / "settings"
settings.parent.mkdir(parents=True)
settings.write_text(f"{version}\n")
os.symlink("releases/v1", app / "current")
return {"app": app, "current": app / "current", "old": app / "releases" / "v1"}
def ln(app: pathlib.Path, *args: str) -> dict:
"""Run ``ln`` from the app directory and keep its exit status and complaint."""
result = subprocess.run(["ln", *args], cwd=str(app), capture_output=True, text=True)
return {"rc": result.returncode, "stderr": result.stderr.strip() or None}
def target(path: pathlib.Path) -> str | None:
return os.readlink(path) if os.path.islink(path) else None
def errno_of(path: pathlib.Path, flags: int = os.O_RDONLY) -> int | None:
"""The errno an open answers with, or None when it succeeds."""
try:
os.close(os.open(str(path), flags))
except OSError as exc:
return exc.errno
return None
def served(app: pathlib.Path) -> str | None:
"""Which release a reader of ``current/conf/settings`` gets."""
try:
return (app / "current" / "conf" / "settings").read_text().strip()
except OSError:
return None
def swap(app: pathlib.Path) -> None:
"""Point the release link at the new version in one rename, as a deploy would."""
fresh = app / "current.next"
os.symlink("releases/v2", fresh)
os.replace(fresh, app / "current")
def ln_sf_relative(root: pathlib.Path, again: bool = False) -> dict:
paths = tree(root)
first = ln(paths["app"], "-sf", "v2", "current")
second = ln(paths["app"], "-sf", "v2", "current") if again else None
stray = paths["old"] / "v2"
return {"outcome": "ok", "rc": first["rc"],
"rc_second": second["rc"] if second else None,
"stderr": first["stderr"],
"current_target": target(paths["current"]), "stray_target": target(stray),
"current_v2_errno": errno_of(paths["current"] / "v2"),
"deep_errno": errno_of(paths["current"] / "v2" / "conf" / "settings"),
"served": served(paths["app"])}
def ln_sf_absolute(root: pathlib.Path) -> dict:
paths = tree(root)
result = ln(paths["app"], "-sf", str(paths["app"] / "releases" / "v2"), "current")
stray = paths["old"] / "v2"
deep = errno_of(paths["current"] / "v2" / "conf" / "settings")
return {"outcome": "ok", "rc": result["rc"], "stderr": result["stderr"],
"current_target": target(paths["current"]), "stray_target": target(stray),
"stray_absolute": (target(stray) or "").startswith("/"),
"current_v2_errno": errno_of(paths["current"] / "v2"),
"stray_served": (paths["app"] / "current" / "v2" / "conf" / "settings")
.read_text().strip() if deep is None else None,
"served": served(paths["app"])}
def ln_sfn_relative(root: pathlib.Path) -> dict:
paths = tree(root)
result = ln(paths["app"], "-sfn", "releases/v2", "current")
chain = count_links(str(paths["current"]))
return {"outcome": "ok", "rc": result["rc"], "stderr": result["stderr"],
"current_target": target(paths["current"]),
"stray_target": target(paths["old"] / "v2"),
"links": chain.links, "status": chain.status,
"current_v2_errno": errno_of(paths["current"] / "v2"),
"served": served(paths["app"])}
def count_then_swap(root: pathlib.Path) -> dict:
"""Count the link, then let a deploy replace it: the count and the read disagree."""
paths = tree(root)
chain = count_links(str(paths["current"]))
counted = chain.target.rsplit("/", 1)[-1]
swap(paths["app"])
return {"outcome": "ok", "counted": counted, "served": served(paths["app"]),
"counted_links": chain.links,
"served_links": count_links(str(paths["current"])).links,
"current_after_swap": target(paths["current"])}
def swap_no_symlinks(root: pathlib.Path) -> dict:
"""The same swap, with the refusal inside the open instead of before it."""
paths = tree(root)
swap(paths["app"])
path = str(paths["app"] / "current" / "conf" / "settings")
try:
with os.fdopen(probelib.openat2(path)) as handle:
plain = handle.read().strip()
except OSError as exc:
plain = f"errno {exc.errno}"
try:
os.close(probelib.openat2(path, resolve=probelib.RESOLVE_NO_SYMLINKS))
except OSError as exc:
refused = exc.errno
else:
refused = None
return {"outcome": "ok", "plain_open_served": plain, "no_symlinks_errno": refused,
"served": served(paths["app"])}
def swap_no_follow(root: pathlib.Path) -> dict:
"""``O_NOFOLLOW`` on the same swapped path: it guards the last component, not the walk."""
paths = tree(root)
swap(paths["app"])
return {"outcome": "ok",
"errno": errno_of(paths["app"] / "current" / "conf" / "settings", os.O_NOFOLLOW),
"served": served(paths["app"])}
def read_fd(fd: int) -> str:
try:
return os.read(fd, 64).decode().strip()
finally:
os.close(fd)
def pin_dirfd_then_swap(root: pathlib.Path) -> dict:
"""Resolve ``current`` once into a directory descriptor, then swap the link under it.
``open(current, O_RDONLY | O_DIRECTORY)`` follows the link once and hands back a descriptor on
the directory it named. Every later ``openat(dirfd, name)`` is resolved inside that directory,
so a deploy that replaces the link afterwards changes nothing the reader sees. This is the arm
that closes the window the previous three measure, and it works on a layout whose live path is
itself a symlink, where ``RESOLVE_NO_SYMLINKS`` on the whole path would refuse a good request.
"""
paths = tree(root)
dirfd = os.open(str(paths["current"]), os.O_RDONLY | os.O_DIRECTORY)
try:
pinned = os.readlink(f"/proc/self/fd/{dirfd}").rsplit("/", 1)[-1]
swap(paths["app"])
current_after = target(paths["current"])
plain_after = served(paths["app"])
no_follow = read_fd(os.open("conf/settings", os.O_RDONLY | os.O_NOFOLLOW, dir_fd=dirfd))
try:
beneath = read_fd(probelib.openat2("conf/settings",
resolve=probelib.RESOLVE_BENEATH,
dirfd=dirfd))
except OSError as exc:
beneath = f"errno {exc.errno}"
finally:
os.close(dirfd)
return {"outcome": "ok", "pinned": pinned, "current_after_swap": current_after,
"plain_after_swap": plain_after, "no_follow_served": no_follow,
"beneath_served": beneath}
ARMS = (("ln_sf_relative", ln_sf_relative),
("ln_sf_relative_twice", lambda root: ln_sf_relative(root, again=True)),
("ln_sf_absolute", ln_sf_absolute),
("ln_sfn_relative", ln_sfn_relative),
("count_then_swap", count_then_swap),
("swap_no_symlinks", swap_no_symlinks),
("swap_no_follow", swap_no_follow),
("pin_dirfd_then_swap", pin_dirfd_then_swap))
def main() -> int:
arms: list[dict] = []
for label, call in ARMS:
runs = []
for _ in range(probelib.REPEATS):
root = probelib.tmpdir("eloop_deploy_")
try:
runs.append(call(root))
finally:
probelib.cleanup(root)
arms.append({"label": label, "runs": runs,
"unanimous": probelib.unanimous({"runs": runs})})
first = {arm["label"]: arm["runs"][0] for arm in arms}
record = probelib.record("11_deploy", {
"notes": {
"arms": len(arms),
"ln_sf_exits_zero": all(run["rc"] == 0 for arm in arms for run in arm["runs"]
if "rc" in run),
"ln_sf_leaves_old_release": first["ln_sf_relative"]["current_target"],
"ln_sf_serves": first["ln_sf_relative"]["served"],
"ln_sf_self_link": first["ln_sf_relative"]["stray_target"],
"ln_sf_self_link_errno": first["ln_sf_relative"]["current_v2_errno"],
"ln_sf_absolute_serves": first["ln_sf_absolute"]["served"],
"ln_sf_absolute_stray_serves": first["ln_sf_absolute"]["stray_served"],
"ln_sfn_target": first["ln_sfn_relative"]["current_target"],
"ln_sfn_links": first["ln_sfn_relative"]["links"],
"ln_sfn_serves": first["ln_sfn_relative"]["served"],
"count_then_swap_counted": first["count_then_swap"]["counted"],
"count_then_swap_served": first["count_then_swap"]["served"],
"no_symlinks_errno": first["swap_no_symlinks"]["no_symlinks_errno"],
"no_follow_errno": first["swap_no_follow"]["errno"],
"no_follow_serves": first["swap_no_follow"]["served"],
"dirfd_pinned": first["pin_dirfd_then_swap"]["pinned"],
"dirfd_current_after_swap": first["pin_dirfd_then_swap"]["current_after_swap"],
"dirfd_plain_after_swap": first["pin_dirfd_then_swap"]["plain_after_swap"],
"dirfd_no_follow_serves": first["pin_dirfd_then_swap"]["no_follow_served"],
"dirfd_beneath_serves": first["pin_dirfd_then_swap"]["beneath_served"],
},
"arms": arms,
})
for arm in record["arms"]:
print(arm["label"], json.dumps(arm["runs"][0]), "unanimous", arm["unanimous"])
return 0
if __name__ == "__main__":
raise SystemExit(main())
