Skip to content

fix(torrent): open torrents with unsafe names, padding files and long lists - #561

Merged
linroid merged 3 commits into
mainfrom
fix/torrent-open-failures
Oct 16, 2026
Merged

linroid merged 3 commits into
mainfrom
fix/torrent-open-failures

Conversation

@linroid

@linroid linroid commented Oct 16, 2026

Copy link
Copy Markdown
Owner

What

Ordinary torrents that Ketch refused, or never finished resolving, now open and download. This covers the "torrents fail to open" findings of the 2026-10-16 torrent review; throughput, client identity and the other findings are separate.

  1. Unsafe names. A v1 name containing : ? " < > | *, ending in . or a space, naming a Windows device (aux.c) or longer than 255 bytes no longer refuses the whole torrent. It is stored, and listed, under the name core's sanitizeFileName makes ("Who?.flac" → "Who_.flac"). Only traversal is refused: empty names, ., .., /, \ and control characters. Collision checks (canonicalTorrentName, ignoring case) run on the cleaned paths.
  2. Metadata that matches but does not parse. It used to be blamed on each peer, so the magnet showed "Finding peers" forever. Now it ends the lookup with UnusableTorrentMetadataException, which resolve reports as KetchError.SourceError with the parser's reason. v2 piece layers fetched from a peer still count as that peer's failures.
  3. BEP 47 padding in v1 torrents (attr p, or BitComet's unmarked _____padding_file_… entries). These are never listed, selected, written or asked of web seeds. The v1 store hashes and serves them as zeros, .pad/<n> duplicates no longer count as colliding paths, and resolved sizes and admission count only content files.
  4. Limits that failed instead of capping. More than 4096 discovered peers no longer fails a magnet lookup: later peers are ignored, and tracker-only lookups count distinct peers instead of attempts. More than 128 trackers in a torrent or magnet keeps the first 128. The v1 parser allows 1,000,000 bencode values, so 10,000 files at any depth parse.
  5. v2 and hybrid magnets keep looking after a timed-out lookup. The retry log line read MagnetUri.infoHash, which throws for btmh magnets; it now uses logTopic. v2 resolution and tracker-only lookups skip trackers Ketch cannot announce to, such as wss:// (TrackerConfiguration.usable), instead of failing. prepare stays strict for tracker edits.
  6. No hard links. torrentPublishCatalogObject (catalog objects and the v2 creation log) used to fail with a non-retried KetchError.Disk on FAT, exFAT and some network shares. Where the file system refuses the link, it now claims the name with an exclusive create and moves the written file over it, so an existing file is still never replaced. An empty file left at the name by a crash between the two steps is read as missing and taken over by the next publication.

Which names each caller checks

  • Original names, traversal only (validateTorrentComponent): the v1 parser, on the name and every path component.
  • On-disk names, the old strict rules (validateDiskComponent / isDiskComponent):
    • TorrentPieceStore.filePath, TorrentV2PieceStore (output and creation log names), TorrentV2Checkpoint, TorrentV2CreationLog, TorrentCheckpointFile and TorrentContentCatalog.
    • TorrentOutputMapping's choice between keeping a v2 name and escaping it.
    • resolveV2Metainfo's display-name fallback.

Compatibility

  • diskComponent returns every name the old validator accepted unchanged, so saved v1 tasks and checkpoints keep their paths. Only names that used to refuse the torrent are cleaned.
  • The v2 output mapping is unchanged, so its %xx names and the saved checkpoints and creation logs that name them still match. A test pins this.
  • v1 tasks saved by older builds may list padding files as real files, select them and own a pad file on disk. Those selections drop the padding, the owned pad file is left alone, and removing the task with its files deletes it.

Testing

  • ./gradlew :library:torrent:jvmTest: 1,319 tests, 0 failures.
  • Compiled compileTestKotlinIosSimulatorArm64 (iOS main and tests) and compileAndroidMain.
  • A regression test per item:
    1. Names: TorrentNamesTest; TorrentMetadataTest (cleaned paths, raw paths, traversal refused, collisions after cleaning); TorrentPieceStoreTest.unsafeNames_storedUnderCleanedNames; TorrentDownloadSourceResolveTest; MetainfoValidationTest; and the pinned v2 mapping in TorrentOutputMappingTest.
    2. Unusable metadata: TorrentMetadataExchangeTest.exchange_infoMatchingItsHashThatDoesNotParse_isUnusable and TorrentMetadataPeersTest.unusableMetadata_endsTheLookup.
    3. Padding: TorrentMetadataTest.fromBencode_v1Padding_keptOutOfTheContentFiles; TorrentPieceStoreTest (never written, read as zeros, older builds' selections and pad files); and TorrentWebSeedTest.multiFile_paddingNeverRequestedAndFilesAskedByTheirTorrentNames, where the mirror is asked for Who%3F.bin, which is stored as Who_.bin.
    4. Limits: the peer cap, 128 trackers in metainfo, magnets and TrackerConfiguration.usable, and 8,000 files ten folders deep.
    5. v2 magnets: TorrentDownloadSourceResolveTest.resolve_v2MagnetNotFoundWhileInfoIsLogged_looksAgain, which runs a real engine with an info logger installed; MagnetTrackersTest for wss:// on a v2 magnet; and a hybrid .torrent with a wss:// tier.
    6. No hard links: TorrentContentCatalogTest (claim then move, never replacing, takeover of an empty name, a catalog without links) and TorrentV2CreationLogTest.
  • Not tried on a real FAT/exFAT volume or network share; the fallback is tested by injecting a link function that refuses.

Not changed (follow-ups)

  • v2 and hybrid names are still escaped byte by byte (Who?.flac becomes %57%68…), because changing that needs a new output-mapping version.
  • Non-UTF-8 cosmetic fields (comment, magnet dn) still refuse the input.
  • The v1 tracker left still counts padding bytes in incomplete pieces.

… lists

Ordinary torrents that Ketch refused, or never finished resolving, now open and download:

- v1 names that some system cannot store (`<>:"|?*`, trailing dots or spaces, Windows device
  names, names over 255 bytes) are cleaned with core's sanitizeFileName instead of refusing the
  torrent; only traversal is refused. Names that were accepted before stay as they are, so saved
  tasks keep their files, and collisions are checked on the cleaned paths. v2 and hybrid names
  keep their %xx escaping.
- BEP 47 padding in v1 torrents (attr `p`, or BitComet's unmarked padding files) is never
  listed, selected, written or asked of web seeds; the v1 store hashes and serves it as zeros.
  Selections older builds saved that name padding files still load.
- Metadata that matches a magnet's hash but does not parse ends the lookup with a clear reason
  instead of being blamed on each peer forever.
- Over 4096 lookup peers, 128 trackers or 100,000 bencode values now cap instead of failing;
  v2 resolution skips trackers Ketch cannot announce to, such as wss://.
- v2 and hybrid magnets keep looking after a timed-out lookup: the retry log read the v1 hash
  and threw.
- Catalog objects and the v2 creation log publish without hard links where the file system has
  none (FAT, exFAT, some network shares): an exclusive create claims the name, then the written
  file moves over it, so an existing file is still never replaced.
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 16, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-10-16T09:07:11.168687Z ca78736 PR opened
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: ca78736514

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Skipping unsupported trackers let a private (or tracker-only) .torrent whose only trackers are
wss:// resolve, then wait forever with no way to find a peer. New metainfo inputs, v1 and v2,
that find peers only through trackers and have no http, https or udp tracker and no web seed
are now refused with that reason. A saved task's metainfo is still read without the check.
@github-actions

Copy link
Copy Markdown
Contributor

Test Results

 1 934 files  + 15   1 962 suites  +15   23m 32s ⏱️ - 1m 0s
13 055 tests +105  12 808 ✅ +105  247 💤 ±0  0 ❌ ±0 
15 700 runs  +175  15 453 ✅ +175  247 💤 ±0  0 ❌ ±0 

Results for commit e5dbb9f. ± Comparison against base commit f9ff4a9.

@linroid
linroid enabled auto-merge (squash) October 16, 2026 12:58
…ures

# Conflicts:
#	AGENTS.md
#	docs/torrent.md
@linroid
linroid merged commit 7b490c7 into main Oct 16, 2026
11 checks passed
@linroid
linroid deleted the fix/torrent-open-failures branch October 16, 2026 13:05
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant