62 Commits
Author SHA1 Message Date
Knutwurst bde585eab7 Add a Buy me a coffee link with a QR code to the UI
The sidebar footer and the end of Settings open a dialog with a QR code
for PayPal, so it works from the TV, plus a direct link for phones.
2026-10-16 19:04:03 +02:00
Knutwurst eaab113d8a Add a PayPal donation link to the README and the repo's Sponsor button 2026-10-16 17:42:48 +02:00
Knutwurst c3630000b6 Bump version to 0.2.0 2026-10-16 14:25:40 +02:00
Knutwurst 72b9136ff5 Say PS5 and PS4 games in the README and the UI header 2026-10-16 14:25:39 +02:00
Knutwurst c6f001f857 README: PS4 games are supported 2026-10-16 13:56:41 +02:00
Knutwurst e72c25a56e Update PS4 games too
PS4 patches install on the PS5 through the same loopback route as PS5
updates; the console puts them in /user/patch/<id>/ next to the game.
Tested with Bloodborne (CUSA00207, 01.00 to 01.09) on FW 11.60.

- Installed version: PS4 titles have no CONTENT_VERSION in app.db; use
  APP_VER, which includes an installed patch.
- Update check: Sony lists PS4 patches at a gs-sec URL derived from the
  title id with HMAC-SHA256 (the well-known PS4 update key). A PS4
  package's system_ver is a PS4 firmware in decimal and never blocks it.
- Download: PS4 manifests are served over plain http on gs2 only (its
  https edge has no Sony certificate); allow http for that host's
  manifests, keep everything else https. Piece hashes are SHA-1 there, so
  verification picks SHA-1 or SHA-256 by length.
- After an install, check /user/patch/<id>/patch.json instead of app.json.
  PS4 installs fetch no .crc, so a minute of quiet after reading ends one.
- The UI shows a PS4 badge instead of "not supported".

Also: a list reload no longer ends an install on the card early. The
console writes the new version during the install, and the card briefly
showed Delete before the install poll put it back.
2026-10-16 13:56:41 +02:00
Knutwurst bd08ad70c4 Keep the indeterminate install bar moving across card redraws
Cards are rebuilt on list updates, and each rebuild restarted the bar's
animation. A negative animation-delay taken from the clock lets a new bar
continue where the old one was. The sweep is linear now instead of easing
in from a standstill, and it stops for prefers-reduced-motion.
2026-10-16 12:08:41 +02:00
Knutwurst f0091943f2 Bump version to 0.1.0 2026-10-16 12:04:56 +02:00
Knutwurst c09f0481ab README: automatic rescan, package reuse and cleanup, PS4 not supported 2026-10-16 12:04:56 +02:00
Knutwurst 289688f727 Rescan on its own, track installs, verify and clean up packages
Library
- Rescan when /user/app or Sony's app.db changes, after an install, and on
  the Refresh button (which also asks Sony for updates again). Later scans
  keep a handle to the system root and use relative paths instead of
  swapping the process root while other threads run; app.db is copied out
  first because SQLite resolves relative paths with getcwd(). The scan
  thread gets a 1 MB stack (the default made reads fail with EFAULT).
- Take the newer of app.db and appmeta param.json as installed version:
  app.db lags behind until the game is started.
- A package header decides "fake"; the installer's "fake": true marker
  only says the package didn't come from Sony's CDN, and PatchDL's own
  installs set it too.
- PS4 titles are listed as not supported.

Downloads
- Fetch the manifest's .crc next to the package; the console asks for it.
- Keep the sidecar (with the version) after a download completes, so a
  restart still knows the package is whole.
- A package already on disk without a matching sidecar is hashed against
  the manifest piece by piece; only pieces that don't match are fetched.
  Install refuses an unverified package.

Installs
- One install per title: a second request (another tab, a double click)
  gets install_running; an installed version gets already_installed.
  Download, Cancel and Delete wait until the console is done reading.
- Progress comes from the bytes PatchDL serves to the console (distinct
  ranges), since Sony's status query fails for these installs. Phases:
  waiting, reading with percent, finishing, done or stalled. Each title
  is tracked on its own.
- After an install: check that the installed version matches and the new
  app.json names this package and its size. With "Delete PKG after
  install" on, delete the package only then. The setting existed but was
  never read; the old cleanup trusted app.db alone and deleted packages
  that were never applied.

UI
- Settings list every package on the console with size, version and
  whether it is installed, newer or for a game that's gone, with Delete.
  The storage tile links there.
- The list reloads quietly when the server reports a change.
- Bigger covers on wide screens, "Updates on/off" on the switch, no
  "Shared master" badge, no endless auto-install retries.
2026-10-16 12:04:49 +02:00
Knutwurst 533c25a2ac Install updates with InstallByPackage instead of AppInstallPkg
sceAppInstUtilAppInstallPkg returns 0 but installs no content: it writes
the new version to app.db, the tile and appmeta, while the game keeps
running the old one. That is what #9 and #11 report (version shows new,
game unchanged, install stuck at 0%).

InstallByPackage had been refused with 0x80B2116F because MetaInfo was the
published 48-byte struct. Sony reads past it; the stack bytes there sent
the install down another path. MetaInfo is now 0x70 bytes and fully zeroed.

- Try the package over http://127.0.0.1:12880/api/pkg first, so the console
  streams it from PatchDL, then the LAN address, the /user/data path and
  file://. content_id stays empty.
- Drop the AppInstallPkg fallback: a refusal beats a fake success.
- Wait up to 15 s for the install backend instead of failing the first
  click with "install backend not ready".

Verified on a PS5 (FW 11.60) with Dead Island 2, Ghostwire: Tokyo and
Atlas Fallen: app.pkg replaced, packageDigest equal to Sony's manifest,
games start on the new version.
2026-10-16 12:04:37 +02:00
Knutwurst 70863fb54e Show the newest version and its firmware on every card again
Since the version line rework, "Newest … · needs FW …" only appeared when
the newest patch was newer than the installed one, so up-to-date games,
fake packages and Shadowmount titles lost the firmware information that
0.0.8 showed. It is back whenever Sony reports a newest version, unless
the Update entry already names the same version.
2026-10-15 22:16:20 +02:00
Knutwurst b115c0fd4b Drop leftovers of the "shared master can't install" assumption
/api/pkgmeta now calls a package installable when its embedded title id
matches the installed game, which is what AppInstallPkg goes by, instead
of flagging every shared-master package. The unused UI message for the
old refusal is gone, and web/README.md describes the current policy:
Shadowmount, unknown and fake titles get neither download nor install,
and shared-master packages install like any other.
2026-10-15 22:05:44 +02:00
Knutwurst 7ae09ce571 Allow installing shared-master patches again
The UI hid Install for games whose patch pieces live under another
region's title id. That block predates the switch to AppInstallPkg on the
manifest-assembled package, which carries the installed game's own
content id; Dead Island 2 (EU disc, US master pieces) updated fine that
way. The server has a branch for exactly this case, so the UI now offers
Install again and only keeps the "Shared master" label.
2026-10-15 21:58:06 +02:00
Knutwurst 1739096aa1 Treat Shadowmount titles like fake packages: no download
A mounted image can't take a patch, so a download leads nowhere. The
server now refuses downloads and Prospero links for Shadowmount titles
and skips the Prospero lookup for them; the UI lists them under Not
supported without a button, the same as fake packages.
2026-10-15 21:53:46 +02:00
Knutwurst 25c2adc4bf Bump version to 0.0.9 2026-10-15 21:48:47 +02:00
Knutwurst 36c7c02ebb README: new screenshots with the old-firmware flow on TV and phone 2026-10-15 21:48:47 +02:00
Knutwurst 4379ac3f59 List download-only titles under Not supported, soften the human-check hint
Shadowmount titles can't take a patch, so they no longer sit under Updates.
They move to Not supported and keep their download: Download for Sony
updates, Old FW download for patches from Prospero. Fake packages stay
without any download.

Prospero's human check usually passes without the user noticing, so the
guide now only asks to confirm it if one shows up.
2026-10-15 21:48:47 +02:00
Knutwurst 91cfb2cd02 Flag region patches, check free space, slim the console guide
Disc and store installs whose update Sony serves from another region's
master package can't be installed from homebrew; Sony's installer refused
them in testing. They now sit under Not supported with a short reason
instead of offering a download that leads nowhere.

Before preallocating a package, PatchDL now checks that it fits on /data
with 2 GB to spare and reports how much it needs. The Prospero link check
runs the same test, so the phone gets the answer right away.

The PS5 browser can't copy links, so on the console the old-FW guide only
shows a large QR code and the link for the phone.
2026-10-15 21:31:00 +02:00
Knutwurst bc716339ba README: mention patches for older firmware and the Prospero lookup 2026-10-15 21:21:51 +02:00
Knutwurst fbe984da87 Offer the newest patch that fits the firmware via Prospero Patches
Sony's version.xml only lists the newest patch. When that one needs a
newer firmware, PatchDL now asks Prospero Patches for the version history
and offers the newest patch that still runs on the console. Prospero only
hands out download links after a human check, so a guide with a QR code
moves the user to a phone, where they copy the SC link. PatchDL derives
Sony's manifest from that link and downloads like an official update.

The game list now groups by what the user can do: Updates, Up to date,
Not supported. Update all read a nonexistent state.games and did nothing;
it now uses state.titles.
2026-10-15 21:21:51 +02:00
Knutwurst f251e2aa98 README: show 0.0.8 with game icons and a library screenshot
New screenshots for the hero, games, queue, settings and phone views,
all with game icons. Add a library shot sorted A to Z, mention the
Needs FW label and the package check in the highlights, and answer
which games PatchDL updates in the FAQ.
2026-10-15 11:17:01 +02:00
Knutwurst f6b0bba49a Show game icons and label the firmware a patch needs
- The scan opens each game's icon0.png (app.db icon0Info first, then
  /user/appmeta and the title's sce_sys) while it can still see the
  whole filesystem, and keeps the fd. GET /api/icon/<title_id> serves
  it with a one-day cache. Cards show the icon and fall back to the
  initials; loaded icons are reused across re-renders.
- "Latest x · FW y" read like the console firmware. It now says
  "needs FW y".
2026-10-15 11:08:49 +02:00
Knutwurst 0efa0312d5 Bump version to 0.0.8 2026-10-15 11:00:31 +02:00
Knutwurst ca5977f872 Show the latest official version for fake packages
The update check only reads Sony's version.xml, so it is safe for fake
packages too. Their cards now show the latest version and the firmware
it needs. Download and install stay blocked.
2026-10-15 10:58:42 +02:00
Knutwurst 04d27a9fd5 List only games, keep fake packages visible, sort by name
- Scan only PPSA and CUSA title ids. Homebrew with made-up ids (the
  PatchDL tile, loaders, file managers) no longer shows up as a game.
- Installed fake packages carry "fake": true in app.json, the same
  marker homebrew uses, so they vanished from the list. Titles with an
  app.pkg now stay listed and count as fake when either the marker or
  the package header says so.
- Sort the game list by name.
- "Updatable" only holds titles PatchDL can install. Download-only
  titles (shadowmounts, shared-master patches) with an update move to
  "Can't update" and show "Update · download only".
2026-10-15 10:53:29 +02:00
Knutwurst 9253235a0d Classify installs by package signature, block fake packages
The scanner treated every title with an app.pkg as official unless its
app.json mentioned a URL. That let fake packages through as official, so
PatchDL offered and tried to install Sony patches on them, while disc and
store installs whose app.json lists CDN pieces ended up as unknown.

Read the app.pkg header instead. A PS5 finalized image (\x7FFIH) is
retail when byte 0x05 has bit 0x80 set; a PS4 container (\x7FCNT) is
retail when bit 0 of byte 4 is set. Retail installs count as official,
fake-signed ones as the new "fake" source, unreadable headers stay
unknown.

Fake packages are listed with a "Not supported" label. PatchDL skips
their update check, and the server refuses download, install and the
enable toggle for them. The titles JSON reports pkg_sign for diagnostics.
2026-10-15 10:21:36 +02:00
Knutwurst 664ad3d4fd Show "Needs FW" when a newer patch exceeds the console firmware
A title whose installed version matched the newest compatible patch was
reported as up to date even when Sony offered a newer patch that needs a
higher firmware. It now reports incompatible_fw, so the UI shows
"Needs FW x.xx". The UI drops stale job flags for that state too.

Fixes the Final Fantasy VII Rebirth case in #4.
2026-10-15 10:12:20 +02:00
Knutwurst 9209408c40 README: list firmware 1.00 to 13.60 as supported
SDK 0.44 ships kernel offsets for every firmware from 1.00 to 13.60,
and the AppInstUtil calls and app.db table PatchDL uses exist across
that range. Tested on 11.60 and 13.60.
2026-10-14 19:42:58 +02:00
Knutwurst 3803b9e6eb Release 0.0.7 2026-10-14 17:30:17 +02:00
Knutwurst a15f58fbf2 Tile: fall back to AppInstallAll on firmware 13.xx
Firmware 13.xx no longer exports sceAppInstUtilAppInstallTitleDir, so
the home-screen tile never registered there. When neither the NID nor
the symbol resolves, fall back to sceAppInstUtilAppInstallAll, which
rescans /user/app and picks up the tile directory.

A receipt file is now written only after the installer accepts the
tile, and the stat-guard checks it. Files left behind by a failed
registration no longer count as installed, so the next start retries.

The API probe lists sceAppInstUtilAppInstallAll as well.
2026-10-14 17:15:25 +02:00
Knutwurst cb7a86551b README: point links and badges at the renamed ps5-patchdl repo 2026-10-06 07:45:35 +02:00
Knutwurst ded0a4ddaa README: give all four screenshots the same 16:10 frame 2026-10-05 21:17:00 +02:00
Knutwurst 5cc430ec59 README: landing page with hero, screenshots, FAQ and disclaimer
New hero composite, desktop and phone screenshots rendered from demo
data, highlights, a get-started list, a short FAQ and a clear statement
that PatchDL only fetches official, unmodified updates for games already
on the console. Old photos showing debug output are replaced; the real
home-screen tile photo stays. docs/images/social-preview.png is ready
for the repository's social preview.
2026-10-05 21:15:26 +02:00
Knutwurst b727fd430f Net: drop the unused third-party lookup host
The allowlist carried a non-Sony host for a lookup that was never built;
the function was a stub that always returned -1. Removing both leaves
behaviour unchanged and keeps every request on the PlayStation CDN.
2026-10-05 21:15:26 +02:00
Knutwurst 74ec23aa7e UI: label queued downloads as Queued, plainer header and DNS wording
Jobs waiting for a free slot showed the green Downloading pill, same as
the one that was actually transferring. They now show a neutral Queued
pill. The header eyebrow reads "PS5 update manager" and the DNS tile
says the system DNS is left untouched.
2026-10-05 21:15:26 +02:00
Knutwurst 5dc5ee57b3 Add PS5 GitHub Actions build 2026-06-27 19:19:05 +02:00
Knutwurst 44ab1dd822 README: swap hero and home-screen tile images so each fits its section 2026-06-25 22:31:39 +02:00
Knutwurst 84f5051ba3 README: tighter prose, no em-dashes, fewer adverbs 2026-06-25 22:04:58 +02:00
Knutwurst 0510e3dc34 License: GPL-3.0-or-later
Full GPL-3.0 text in LICENSE, SPDX-License-Identifier header on every
source file, README license section updated. Copyright (C) 2026 Knutwurst.

Tidied a couple of stale comments in patchdl_tile.{c,h} while at it.
2026-06-25 17:01:49 +02:00
Knutwurst edb4c90978 README: rewrite as a tool description with screenshots
Reads like a project README now: what PatchDL is, what the UI looks
like, how to use the settings, how to install. The deeper notes
(target-id matching, source classification, partition layout, console
setup chain) are out — those belong in design docs, not the front door.

Five photos under docs/images/ render inline: home-screen tile, the
desktop browser UI, the mobile settings view, the on-console browser,
and the startup notification. Originals stay in photos/ for future
crops.
2026-06-25 09:00:00 +02:00
Knutwurst ec94f0578b Release 0.0.6 2026-06-25 06:35:01 +02:00
Knutwurst 88368e3df3 Plug response-OOM leak, cap RAM, free pool on shutdown
queue_buffer leaked the MUST_FREE payload (every queue_json_owned/
build_*_json/strdup(resp)) when MHD_create_response_from_buffer hit OOM.
The MUST_FREE contract hands ownership to MHD only on success — on the
NULL return path the caller still owns the buffer, so free it before
bailing. Critical under memory pressure where the first OOM turns into
a cascade.

patchdl_websrv_stop walked the verxml thread + workers but never freed
the remaining dl_job_t entries or g_debug_json. Today main never calls
the function, but the early-failure path inside patchdl_websrv_start
does, and any later graceful-shutdown work would hit the same leak.
Drain g_pool.jobs through free_job_locked under the pool lock; free
g_debug_json under g_mutex.

RAM caps:

- MHD: CONNECTION_LIMIT 64 -> 8 (single-user UI), and
  THREAD_STACK_SIZE = 512 KB. THREAD_PER_CONNECTION on libc's default
  pthread stack (multi-MB) was reserving hundreds of MB of VM per
  burst; the largest stack frame in any handler is the 8 KB sidecar
  buffer, so 512 KB is generous even with curl + openssl in the path.
- patchdl_buf_t caps: manifest 64 -> 16 MiB, version.xml 16 -> 4 MiB.
  Real PS5 manifests are 1-2 MiB; the old caps allowed 64 MiB per
  fetch with multiple fetches possible in flight.
- patchdl_install_status_json: ai_install_status_t (2 KB pad) moves
  from the MHD worker stack to a calloc/free pair so a polling browser
  doesn't keep committing pages on each /api/installstatus tick.
- seed_from_sidecar: 16 KB stack buf -> 8 KB. 4096-piece cap fits with
  the JSON wrapper inside 8 KB.

No functional changes; download/install/scan/tile paths unaffected.
2026-06-25 06:10:48 +02:00
Knutwurst c80be921c5 Release 0.0.5 2026-06-24 22:15:04 +02:00
Knutwurst a371a67521 Net: drop HTTPS pin on the streaming download paths
Real regression from c9d721f: pinning CURLOPT_PROTOCOLS_STR /
REDIR_PROTOCOLS_STR to "https" on the piece downloader (and the simple
file streamer) broke real-world Sony patch downloads. Banishers reliably
aborted after ~73 MB and Last of Us Part I after ~127 MB — the Sony CDN
appears to 302 the piece URL to an http:// signed edge inside its own
infrastructure, and refusing those redirects killed the transfer mid-piece.

The smaller patchdl_http_get path (version.xml + manifest JSON) keeps the
HTTPS pin since those payloads always come back from the public https
endpoints. The defence still holds elsewhere: host_allowed gates every
URL to the Sony CDN allowlist, TLS verifies against the pinned SCEI root
even on a 302, and NOSIGNAL stays so a connection RST can't smuggle a
SIGPIPE back into the worker thread.

For future regressions of this class /api/downloads now exposes the last
CURLcode + HTTP status per job (last_curl_rc, last_http_code) so we don't
have to instrument the binary again to find out what curl returned.
2026-06-24 22:13:16 +02:00
Knutwurst 2bc15cbaa2 UI: Updating now means only the queue; active downloads stay in Updatable
Previous behaviour moved a game out of Updatable the moment it entered
the pool, which made it disappear from the list you came to watch. The
queue chip now means literally that: jobs in state="queued" waiting
for a free pool slot. Active, paused and installing jobs stay under
Updatable so you don't have to switch tabs to see the thing you just
told to download.

Implementation: reconcileFromJobs stamps the raw j.state on the title
as g._jobState; gameCategory routes only "queued" to Updating, every
other live state falls through to the existing Updatable branch.
2026-06-24 22:00:42 +02:00
Knutwurst 81d6f0e332 UI: global download banner above the status strip
A sticky-feeling banner appears whenever any job is queued or active.
It shows the eyebrow (Downloading / Queued), the current title's name,
a "3 of 9" chip when more than one job is in this batch, plus
percent, speed, and ETA. A thin gradient bar runs edge-to-edge along
the bottom so the at-a-glance state matches the per-card progress.

Batch counting: jobs with state in {queued, active, done} make up the
batch; done count + 1 is the current position. When all queued jobs
finish and roll out of the pool list the banner hides on the next poll.

While the active job's manifest is still being fetched (no total_bytes
yet) the bar runs an indeterminate sweep so the user isn't staring at
a frozen 0%. Speed comes from the existing per-job smoothed estimate
in reconcileFromJobs so the banner shares one source of truth with
the per-game tiles.

Render hooks: renderGames() and applyDownloadProgress() both call
renderGlobalStatus(), so every refresh path keeps it in sync without
adding a separate timer.
2026-06-24 21:55:28 +02:00
Knutwurst fcd43b54ae Home-screen tile via sceAppInstUtilAppInstallTitleDir
Write param.json + icon0.png into /user/app/<TITLE_ID>/sce_sys/, then
call sceAppInstUtilAppInstallTitleDir to register the directory as an
app. No package, no code signing — the installer reads the metadata
files directly.

The tile uses TITLE_ID PTDL00001 and deeplinkUri
http://127.0.0.1:12880/, so tapping it opens PatchDL's own UI in the
on-console browser. Only useful while the ELF is running.

Asset pipeline: param.json + icon0.png live under assets/ and get
.incbin'd straight into .rodata. Makefile lists them as TILE_ASSETS so
a touch on either forces a relink.

Stat-guard: file_matches() diffs each asset against the on-disk copy
first; when nothing changed the install API isn't called at all. Keeps
repeated payload starts from re-registering the app. Repeated
/api/install_tile calls return "already installed and up to date".

Backend lazy-load: AppInstUtil isn't mapped until something pokes it,
so the helper polls patchdl_install_backend_check() for up to ~15 s
before resolving sceAppInstUtilAppInstallTitleDir.

Wiring: /api/install_tile POST triggers the install on demand;
patchdl_websrv_start() runs it at startup when home_shortcut is on;
and flipping the toggle from off to on in /api/config also fires it.
All three paths share the stat-guarded helper so they're safe to
repeat.
2026-06-24 21:50:59 +02:00
Knutwurst d0ca22d42d UI: pull version from /api/status instead of hardcoding it
The sidebar tag was a literal "v0.0.3" string in index.html, so a
release bump left the running UI lying about which build it was. Server
now publishes PATCHDL_VERSION via /api/status; renderStatus() drops it
into a #brandVersion span. No more chasing a hardcoded version on every
release.
2026-06-24 21:19:38 +02:00
Knutwurst fb47730d70 Docs: README for 0.0.4 (cross-region install works, UI updates, filename)
README catches up to where the code is:

- The "cross-region install is a known limitation" section is gone. We
  route through sceAppInstUtilAppInstallPkg now, verified end-to-end on
  Dead Island 2 (01.000.001 -> 01.000.011, including the shared-storage
  case where the patch lives under a master title id).
- A Web UI section documents the filter chips (Updatable default,
  Updating separate bucket, All on the right) and Update all.
- Deploy section notes the new filename shape (patchdl_<version>.elf)
  so Payload Manager can parse the version out of it.

deploy_ps5.sh follows: UP_NAME is now patchdl_${VERSION}.elf to match
the released asset naming.
2026-06-24 21:16:31 +02:00
Knutwurst a1d035313e Release 0.0.4
Update all skips shadowmount titles. They pass the download policy but
not the install policy (their app slot has no real source medium), so
sweeping them in would burn tens of GB on a download AppInstUtil would
refuse. Single shadowmount downloads via the per-title button still work
for the "pop the disc in later" workflow.
2026-06-24 20:59:47 +02:00
Knutwurst bffa9b2a3f UI: separate Updating filter for queued/active/paused downloads
Updating gets its own chip so Updatable shows only games the user could
still trigger. Anything mid-flight — queued, actively downloading,
paused with a partial on disk, or installing — moves to the new bucket.

Implemented in gameCategory(): downloading is true for both queued and
active jobs, so wartende Downloads (the user's words) show up in the
same list as the one actively transferring.
2026-06-24 20:57:17 +02:00
Knutwurst 3f4c4a15f5 UI: default to Updatable filter, add Update All, move All to the right
The Updatable chip is now the first segment and selected on load — the
common case (looking at what needs an update) doesn't need a click. All
moves to the right end of the strip.

Update All queues a download for every game whose status is "available"
and whose source/policy allow it (skips downloading/downloaded jobs).
With install_after_download on, the existing auto-install pipeline
picks each finished download up automatically.
2026-06-24 20:51:11 +02:00
Knutwurst c9d721fea6 Polish: NOSIGNAL + HTTPS pin on all transports, bounded kill loop
The three other curl_easy code paths (downloader, piece pool, net_diag)
now set CURLOPT_NOSIGNAL=1L plus PROTOCOLS_STR/REDIR_PROTOCOLS_STR =
"https" — matching what patchdl_http_get already does. SIGPIPE on a
broken connection in a worker thread previously could crash the process;
the protocol pin keeps a redirect from sliding off https.

patchdl_proc_kill_others is now bounded to 8 iterations. If kill returns
success but the process never exits (zombie / unusual proc-table state),
sleep(1) × N would otherwise stall startup indefinitely.

lookup_tsv rejects URLs that don't start with https://. The TSV file
lives under /data/patchdl and is writable by anyone with /data access;
patchdl_http_get's host_allowed gate still applies, but failing earlier
keeps a poisoned line from even reaching the network layer.
2026-06-24 20:41:26 +02:00
Knutwurst 73c75ddd83 Medium hardening: JSON escapes, policy whitelist, scan lock, EVP check
json_get_str now decodes the common JSON escapes (\" \\ \/ \n \r \t \b
\f) and collapses \uXXXX to '?'. Previously \" terminated the value
early and \\ was copied literal, so a body containing escapes turned
into garbage at the install backend.

default_policy is constrained to "allow" or "deny" before being stored,
so a malformed POST can't write an arbitrary string into config.json
and round-trip it back out of /api/config as broken JSON.

/api/manifest/<tid>, /api/pkgverify/<tid>, /api/pkgmeta/<tid> now run
path_segment_safe(tid) explicitly. The lookup gate they relied on
(get_title_action_info) is defense-by-coincidence — a future refactor
that populates g_titles via another path would lose the check.

patchdl_scan and patchdl_scan_debug_json perform a process-wide vnode
swap that is only safe single-threaded. patchdl_scan_lock() is now
called once right after MHD_start_daemon; subsequent calls return -1 /
NULL instead of racing the worker threads.

EVP_DigestFinal_ex return code is now checked. A failed final left dig
uninitialized; hex_encode would have produced empty hex and a silent
-2 with no diagnostic. patchdl_sha256_fd_region switches its inner
sprintf to snprintf — same effect, no -Wformat-security warning.
2026-06-24 20:39:43 +02:00
Knutwurst fcb0a5c3b0 Concurrency: atomic g_stage/g_err, snapshot pkg_diag, safe open, SQLite mutex
g_stage and g_err are now _Atomic. The backend init thread publishes
stage transitions and function-pointer assignments; HTTP request
handlers read g_stage to decide whether to call the Sony API. With the
old `volatile int` reads, nothing in the C memory model ordered the
function-pointer loads against the stage check — a stage==5 sighting
could (in theory) come before the pointer stores were visible. Default
seq_cst on _Atomic gives us the acquire/release pairing for free.

/api/pkgdiag returned g_pkg_diag_json directly with RESPMEM_PERSISTENT,
so MHD's writer thread could read the buffer while record_pkg_diag was
mid-snprintf — torn JSON or a missing NUL terminator. Snapshot under
g_mutex into a heap copy and queue with RESPMEM_MUST_FREE instead.

patchdl_net.c gets fopen_safe(): open() with O_NOFOLLOW|O_CLOEXEC and
mode 0600, then fdopen. The old fopen("wb") follows symlinks (a
malicious symlink at dest_path could redirect the write) and creates
mode 0666 (libc default). Both download paths now use it.

patchdl_appdb opens SQLite with SQLITE_OPEN_FULLMUTEX. Today the scan
runs on the startup thread only, but a future rescan triggered from the
HTTP thread would otherwise race the handle.
2026-06-24 20:35:31 +02:00
Knutwurst a6d9f939b5 OOM/stack protection: cap POST body, validate basename, heap playgo
POST handler: cap accumulated body at PATCHDL_POST_MAX_BYTES (64 KiB).
A LAN client streaming gigabytes into /api/config would otherwise grow
the per-connection buffer until OOM-kill. Past the cap, further chunks
are dropped and the final call returns 413.

title_pkg_path: the basename comes from the patch_url and ultimately
from version.xml via the Sony CDN. A poisoned manifest with a basename
like ".." or one containing delimiters would compose a dest path that
escapes /data/patchdl/<tid>/. Validate the basename through
path_segment_safe and fall back to "<title_id>.pkg" on rejection.
cleanup_installed_download now routes through the same helper instead
of doing its own basename extraction.

ai_install_by_package's playgo struct is 0x2700 bytes — comfortably
fine on its own, but on the MHD worker stack alongside meta/pkg/uris
buffers and Sony's own frame use it leaves little headroom. Move it to
the heap in both patchdl_install_local_pkg and patchdl_install_by_uri.
2026-06-24 20:32:45 +02:00
Knutwurst 5ba72b850c Net: scope JSON parser, cap manifest, harden DNS/CURL allowlist
Manifest JSON parser used substring scans with no per-piece scope; a key
defined in a later piece could be misattributed to the current one, and
the escape handling silently dropped the byte after a backslash even for
unknown escapes. json_string_after/json_u64_after now take an optional
limit pointer (NULL = legacy unbounded), and the manifest loops pass
obj_end so per-piece reads can't leak across pieces. JSON escapes are
decoded properly: \" \\ \/ \n \r \t \b \f; unknown \X drops the
backslash and keeps the payload byte.

Sanity caps on assembled manifests: PATCHDL_MAX_PIECES (4096),
PATCHDL_MAX_PIECE_BYTES (8 GiB), PATCHDL_MAX_TOTAL_BYTES (200 GiB).
A malformed manifest with a single multi-TB piece or millions of entries
is now rejected before any disk activity.

patchdl_buf_t gains an optional `max` field; write_cb fails the transfer
when growth would exceed it. patchdl_http_get preserves the caller-set
max across its internal memset(). verxml_query caps at 16 MiB,
fetch_manifest and download_manifest at 64 MiB.

host_allowed switches to strcasecmp (DNS is case-insensitive; an upstream
redirect could otherwise drop out of the list). CURLOPT_PROTOCOLS_STR /
REDIR_PROTOCOLS_STR pin all traffic and redirects to HTTPS.
CURLOPT_NOSIGNAL=1 prevents libcurl from raising SIGPIPE in a worker.

DNS label parser bounds-checks the length byte before incrementing pos,
so a malformed response with a 0xFF label near the end can no longer
read past the receive buffer.

extract_title_id used `p[8]` as the loop guard, which crossed the NUL
terminator on strings shorter than 9 chars (UB). Replaced with a
strlen-based bound.
2026-06-24 20:29:24 +02:00
Knutwurst 2f3490f21a Install: pad Sony output buffers, validate ids spliced into URIs
Sony's GetTitleIdFromPkg, GetContentIdFromPkg and GetInstallStatus take
output buffers with no length hint. We sized them to the visible id
length (0x30 / 0x40), but the firmware may NUL-pad more — that class of
bug already crashed the process once (commit 970c7d8). Switch all three
calls to padded AI_*_OUT_SIZE temporaries and copy_bounded() the safe
portion back into the right-sized destination.

patchdl_install_local_pkg extracts title_id and file_base from the
caller's local_path and splices them into http://127.0.0.1:.../api/pkg/
and the LAN equivalent that get fed to InstallByPackage. A path with
CRLF or '/' embedded in the basename would inject into Sony's HTTP
request line. install_id_safe() now gates both before they reach the
URI builders; on failure the loop / LAN URI is simply omitted (the
direct sdk_path and file:// URIs still run).

title_id_eq9() replaces strncmp(...,9): PS4/PS5 ids are exactly 9
chars (4 letters + 5 digits), and a prefix match would let PPSA12345
collide with PPSA12345EVIL when a future caller passes a longer string.
2026-06-24 20:24:20 +02:00
Knutwurst 80c47d6777 Validate install endpoints; cap MHD connections
/api/install_aip path must be PATCHDL_DL_DIR/<safe-title-id>/<safe-filename>,
rejecting attempts to point AppInstUtil at arbitrary on-disk PKGs (e.g.
/system/..., /user/uploads/...). local_install_path_safe enforces the
shape and reuses path_segment_safe for both segments.

/api/install_uri requires https:// to a Sony CDN host (subdomain match
against sgst/gst/gs2.*.playstation.net). file://, http://, and arbitrary
hosts are refused. The CDN list duplicates patchdl_net.c's ALLOWED_HOSTS
deliberately — both layers gate independently, both must stay in sync.

content_id / title_id from both endpoints now go through path_segment_safe
before reaching the install backend, so they cannot smuggle delimiters or
control chars into Sony's HTTP fetch.

MHD gets CONNECTION_LIMIT=64 (was unbounded with THREAD_PER_CONNECTION),
PER_IP_CONNECTION_LIMIT=8, CONNECTION_TIMEOUT=30s. A noisy LAN client
can no longer exhaust pthreads on the PS5.
2026-06-24 20:21:43 +02:00
Knutwurst 970c7d8f1d Install patches via sceAppInstUtilAppInstallPkg; fix GetInstallStatus ABI
sceAppInstUtilInstallByPackage returns 0x80B21163 from payload context
(process privilege rejection). sceAppInstUtilAppInstallPkg accepts the
same PKG with rc=0 and does install it. Switch all install paths to use
AppInstallPkg.

do_install (cross-region): require assembled PKG from the manifest
download; InstallByPackage and DP.pkg fallbacks are removed since both
are dead ends in this process context. do_install (same-region): also
switched to AppInstallPkg. do_download: removed the DP.pkg shortcut so
the manifest-assembled full PKG is downloaded as before.

sceAppInstUtilGetInstallStatus ABI: first arg is an output buffer for
the current install's content_id, not an input query. Passing our
tracking buffer there was overwriting it with zeros (disc game has no
explicit content_id). Fix: use a fresh output buffer; keep `cid` from
g_last_content_id untouched. Also add 2048-byte padding to
ai_install_status_t against firmware struct size variance.

New APIs: patchdl_install_by_uri, patchdl_install_app_pkg,
patchdl_install_debug_state. New endpoints: /api/install_uri,
/api/install_aip, /api/debug_install. delta_url propagated through
verxml → scan → websrv for future DP.pkg tracking.

Verified on device (FW 11.60, BD-JB+PPPwn): Dead Island 2 PPSA03099
updated from 01.000.001 to 01.000.011.
2026-06-24 20:04:11 +02:00
Knutwurst 983f39fa89 Harden AppInstUtil install path and status tracking 2026-06-24 17:19:34 +02:00
51 changed files with 6228 additions and 476 deletions

No files matched your search

+1
View File
@@ -0,0 +1 @@
custom: ["https://paypal.me/oliverkoester"]
+6
View File
@@ -0,0 +1,6 @@
# Files included in the release archive.
# One path per line, relative to the repository root.
patchdl-ps5.elf
README.md
LICENSE
+148
View File
@@ -0,0 +1,148 @@
name: PS5 Build and Release
on:
push:
paths-ignore:
- "**/*.md"
- "docs/**"
- "photos/**"
pull_request:
paths-ignore:
- "**/*.md"
- "docs/**"
- "photos/**"
workflow_dispatch:
concurrency:
group: ${{ github.workflow }}-${{ github.ref }}-${{ github.event_name }}
cancel-in-progress: false
permissions:
contents: read
jobs:
build:
outputs:
archive_name: ${{ steps.package.outputs.archive_name }}
runs-on: ubuntu-latest
steps:
- name: Checkout PatchDL
uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Checkout pacbrew-repo
uses: actions/checkout@v4
with:
repository: ps5-payload-dev/pacbrew-repo
path: pacbrew-repo
- name: Checkout SDK stubs
uses: actions/checkout@v4
with:
repository: ps5-payload-dev/sdk
path: ps5-sdk
- name: Setup build environment
run: |
sudo apt update
sudo apt install -y \
autoconf \
automake \
build-essential \
clang-18 \
cmake \
curl \
git \
libarchive-tools \
libtool \
lld-18 \
makepkg \
meson \
ninja-build \
pacman-package-manager \
pkg-config \
python3 \
zip
- name: Build and install pacbrew packages
shell: bash
run: |
set -euo pipefail
build_and_install() {
local package_dir="$1"
pushd "pacbrew-repo/${package_dir}"
makepkg -c -f
sudo pacman --noconfirm -U ./ps5-payload-*.pkg.tar.gz
popd
}
build_and_install sdk
build_and_install libcxx
build_and_install zlib
build_and_install zstd
build_and_install openssl
build_and_install libpsl
build_and_install curl
- name: Build payload
env:
PS5_PAYLOAD_SDK: /opt/ps5-payload-sdk
PS5_SCE_STUBS_DIR: ${{ github.workspace }}/ps5-sdk/sce_stubs
run: |
scripts/build_ps5.sh clean all
- name: Create release archive
id: package
shell: bash
run: |
set -euo pipefail
version_tag="$(git describe --abbrev=6 --dirty --always --tags 2>/dev/null || echo "${GITHUB_SHA::7}")"
archive_name="PatchDL_${version_tag}.zip"
manifest_file=".github/release-files.txt"
mapfile -t release_files < <(grep -Ev '^[[:space:]]*(#|$)' "${manifest_file}")
if [ "${#release_files[@]}" -eq 0 ]; then
echo "Release manifest is empty: ${manifest_file}" >&2
exit 1
fi
for release_file in "${release_files[@]}"; do
if [ ! -f "${release_file}" ]; then
echo "Missing release file: ${release_file}" >&2
exit 1
fi
done
zip -9 "${archive_name}" "${release_files[@]}"
echo "archive_name=${archive_name}" >> "$GITHUB_OUTPUT"
- name: Upload build artifacts
uses: actions/upload-artifact@v4
with:
name: ${{ steps.package.outputs.archive_name }}
path: ${{ steps.package.outputs.archive_name }}
if-no-files-found: error
release:
needs: build
permissions:
contents: write
if: startsWith(github.ref, 'refs/tags/')
runs-on: ubuntu-latest
steps:
- name: Download build artifacts
uses: actions/download-artifact@v4
with:
name: ${{ needs.build.outputs.archive_name }}
path: dist
- name: Create GitHub Release
uses: softprops/action-gh-release@v2
with:
tag_name: ${{ github.ref_name }}
generate_release_notes: true
files: dist/${{ needs.build.outputs.archive_name }}
+674
View File
@@ -0,0 +1,674 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<https://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<https://www.gnu.org/licenses/why-not-lgpl.html>.
+9 -3
View File
@@ -20,10 +20,16 @@ SRCS := src/main.c \
src/patchdl_scan.c \
src/patchdl_appdb.c \
src/patchdl_net.c \
src/patchdl_prospero.c \
src/patchdl_resolve.c \
src/patchdl_verxml.c \
src/patchdl_install.c \
src/patchdl_notify.c
src/patchdl_notify.c \
src/patchdl_tile.c
# patchdl_tile.c uses .incbin to embed param.json + icon0.png; touching the
# assets must trigger a rebuild.
TILE_ASSETS := assets/param.json assets/icon0.png
WEB_ASSETS := web/index.html web/styles.css web/app.js
GEN_SRCS := $(patsubst web/%,gen/web/%.c,$(WEB_ASSETS))
@@ -56,8 +62,8 @@ gen/web/%.c: web/% scripts/gen_asset_module.py | gen/web
$(SQLITE_OBJ): $(SQLITE_DIR)/sqlite3.c
$(CC) $(SQLITE_CFLAGS) -c -o $@ $<
$(BIN): $(SRCS) $(GEN_SRCS) $(SQLITE_OBJ)
$(CC) $(CFLAGS) -o $@ $^ $(LDADD)
$(BIN): $(SRCS) $(GEN_SRCS) $(SQLITE_OBJ) $(TILE_ASSETS)
$(CC) $(CFLAGS) -o $@ $(SRCS) $(GEN_SRCS) $(SQLITE_OBJ) $(LDADD)
test: $(BIN)
$(PS5_DEPLOY) -h $(PS5_HOST) -p $(PS5_PORT) $^
+116 -87
View File
@@ -1,123 +1,152 @@
# PatchDL
<h1 align="center">PatchDL</h1>
A standalone PlayStation 5 ELF payload that downloads and installs official game
patches on your terms. It serves its own dark-mode web UI and runs without
etaHEN.
<p align="center">
<img src="docs/images/hero.jpg" alt="PatchDL in a desktop browser and on a phone, fetching a patch that runs on an older firmware" width="900">
</p>
PatchDL is built for setups where nanoDNS blocks Sony's servers for the whole
console. It resolves the Sony patch CDN on its own DNS path, so the rest of the
system stays offline and only the patches you pick get fetched.
<p align="center">
<b>Official updates for your PS5 and PS4 games, from any browser.</b><br>
PatchDL finds the newest update for every PS5 and PS4 game on your console, downloads it at full speed and installs it.<br>
Run it from your phone, your laptop or the PS5 itself.
</p>
by Knutwurst
<p align="center">
<img src="https://img.shields.io/github/v/release/knutwurst/ps5-patchdl?style=for-the-badge&label=release&color=22c55e" alt="Latest release">
<img src="https://img.shields.io/github/downloads/knutwurst/ps5-patchdl/total?style=for-the-badge&color=22c55e" alt="Downloads">
<img src="https://img.shields.io/badge/games-PS5%20%7C%20PS4-22c55e?style=for-the-badge" alt="PS5 and PS4 games">
<img src="https://img.shields.io/badge/FW-1.00%E2%80%9313.60-22c55e?style=for-the-badge" alt="Firmware 1.00 to 13.60">
<img src="https://img.shields.io/badge/UI-any%20browser-22c55e?style=for-the-badge" alt="Web UI in any browser">
<img src="https://img.shields.io/github/license/knutwurst/ps5-patchdl?style=for-the-badge&color=3a3a3a" alt="License">
</p>
## What it does
<p align="center">
<a href="https://github.com/knutwurst/ps5-patchdl/releases/latest">
<img src="https://img.shields.io/badge/Download-latest%20release-22c55e?style=for-the-badge&logo=github&logoColor=white" alt="Download the latest release" height="42">
</a>
</p>
- Scans installed titles and classifies each: genuine install, ShadowMountPlus
mount, preinstall, or unknown.
- Reads the title name, installed version, and Sony `version.xml` URL from the
PS5 app database.
- Fetches each title's `version.xml` past nanoDNS (a raw DNS query to 1.1.1.1)
and verifies TLS against the pinned SCEI DNAS root.
- Picks the newest patch compatible with the current firmware
(`system_ver <= firmware`), so an update never forces a firmware upgrade.
- Downloads the patch from Sony's manifest pieces into one local `.pkg`, then
installs it through Sony's AppInstUtil service.
<p align="center">
If you like what I do, you can buy me a coffee*:
<a href="https://paypal.me/oliverkoester"><img src="https://img.shields.io/badge/Donate-PayPal-22c55e?style=flat-square&logo=paypal&logoColor=white" alt="Donate via PayPal"></a><br>
<sub>*It doesn't have to be a generous donation. A few cents are enough to show me who is interested in further development. So the motivation stays and I just know that I am not programming for the bin ;)</sub>
</p>
## Downloading
---
PatchDL pulls each patch over a pool of connections instead of one stream, which
lifts the ~7 MB/s per-connection ceiling on the Sony CDN. Set the connection
count (1 to 16) in Settings with the stepper; the change applies live, with no
payload restart. One patch downloads at a time and further requests queue.
## Highlights
Downloads survive interruptions:
- **PS5 and PS4 games.** PatchDL updates both, straight from Sony's servers. PS4 updates land where the console keeps them, next to the game.
- **Your whole library at a glance.** Every installed game shows up with its icon, its version and the newest update Sony offers for it, sorted A to Z. Install or remove a game and the list follows within seconds, no restart needed.
- **Update all.** One click queues every game that has an update. PatchDL works through the queue and installs each update as soon as it lands.
- **Fast downloads.** Up to 16 parallel connections per update. Change the number in Settings while a download runs.
- **Survives reboots.** Pause, resume, or lose power: PatchDL saves progress after every finished piece and continues where it stopped.
- **Made for your firmware.** You only see updates your console can run. When Sony's newest patch needs a newer firmware, PatchDL finds the newest one that still runs on yours and helps you get it: scan a QR code with your phone, copy one link, and the PS5 does the rest.
- **Knows where each game came from.** PatchDL checks every game's package and recognizes disc and PlayStation Store installs. It only ever patches games Sony signed.
- **Checked against Sony's checksums.** Turn on verification and PatchDL compares every piece with the SHA-256 Sony publishes for it.
- **Reuses what's already there.** If the update package is already on the console, PatchDL checks it against Sony's checksums and downloads only the pieces that don't match.
- **Keeps your storage tidy.** After an install, PatchDL confirms the game runs the new version and then deletes the package. Prefer to keep packages? Turn that off, and Settings lists every package on the console with its size and version, ready to delete.
- **A tile on your home screen.** One toggle adds PatchDL to the PS5 home screen. Tap it and the UI opens in the console's browser.
- **Live progress.** A banner at the top shows the current game, speed, time left and where you are in the queue. During an install, the game's card shows how much of the update the console has read.
- **Resume across a reboot.** PatchDL records progress per manifest piece in a
sidecar beside the `.pkg`, written after every completed piece, so a reboot or
relaunch continues where it stopped.
- **Pause, Resume, Cancel.** Pause keeps the partial file, Resume continues it,
Cancel deletes it. All three work at any point in a download.
- **Verification.** Turn on "Verify downloaded pieces (SHA-256)" to check each
piece against its manifest hash while downloading. After a download you can
also verify the assembled package on-device against Sony's per-piece hashes
(`GET /api/pkgverify/<title_id>`).
## Screenshots
Patches download to `/data/patchdl` on the internal SSD. Large retail updates
run tens of GB.
<table>
<tr>
<td align="center" width="50%"><img src="docs/images/games.jpg" width="420" alt="Games view with a running download"><br><sub><b>Games</b> &nbsp;·&nbsp; every update waiting for you, one click away</sub></td>
<td align="center" width="50%"><img src="docs/images/library.jpg" width="420" alt="Full library with game icons, sorted by name"><br><sub><b>Library</b> &nbsp;·&nbsp; icons, versions and firmware needs, A to Z</sub></td>
</tr>
<tr>
<td align="center" width="50%"><img src="docs/images/oldfw.jpg" width="420" alt="QR code on the TV and the step-by-step guide on a phone"><br><sub><b>Older firmware</b> &nbsp;·&nbsp; scan on the TV, paste one link on your phone</sub></td>
<td align="center" width="50%"><img src="docs/images/settings.jpg" width="420" alt="Settings view"><br><sub><b>Settings</b> &nbsp;·&nbsp; changes apply right away, no restart</sub></td>
</tr>
<tr>
<td align="center" colspan="2"><img src="docs/images/tile-homescreen.jpg" width="420" alt="PatchDL tile on the PS5 home screen"><br><sub><b>Home screen</b> &nbsp;·&nbsp; the PatchDL tile on a real PS5</sub></td>
</tr>
</table>
## Safety model
## Fits any screen
Deny-by-default. A patch installs only for a genuine install, and only when the
patch metadata targets the installed game:
Start an update from the couch with your phone, check on it from your laptop, or open it on the TV. The UI adapts to whatever screen it's on.
| Source | Check | Download | Install |
|-----------------------|-------|----------|---------|
| official | yes | yes | yes |
| shadowmount | yes | yes | no |
| preinstall / unknown | yes | no | no |
<p align="center">
<img src="docs/images/phones.jpg" alt="PatchDL on a phone: game list and Settings" width="560">
</p>
Two guards stop the wrong target being installed: the patch target id (from
`version.xml` / `manifest_url`) must match the installed game, and the install
call receives the installed game's content id from app.db. PatchDL refuses a
true target-title mismatch rather than installing a phantom title.
## Get started
All writes stay under `/data/patchdl`. PatchDL never writes to the system
partition and never touches firmware.
1. Download `patchdl_<version>.elf` from the [latest release](https://github.com/knutwurst/ps5-patchdl/releases/latest).
2. Send it to your PS5 with the ELF loader you already use.
3. A notification on the TV shows the address, for example `http://192.168.0.42:12880/`. Open it in any browser on your network.
4. Optional: switch on **Home-screen shortcut** in Settings to get the PatchDL tile.
## Settings
**You need** a PS5 that can load ELF payloads. PatchDL runs on firmware 1.00 to 13.60 (tested on 11.60 and 13.60).
Settings persist to `/data/patchdl/config.json` and survive a restart:
## Good to know
- Default policy (allow or deny) and a per-game enable toggle.
- Install after download, as a global default with a per-game override.
- Delete the PKG after a successful install.
- Verify downloaded pieces (SHA-256).
- Parallel download connections (1 to 16), applied live.
**Does PatchDL download games?**
No. It fetches updates for games that are already installed on your console. Nothing else.
## Build
**Which games does PatchDL update?**
PS5 and PS4 games you installed from disc or from the PlayStation Store. PatchDL reads each game's package before it offers anything, and it leaves every other title alone.
Requires `ps5-payload-dev/sdk`. The network and install features need the
prebuilt libcurl + OpenSSL from `ps5-payload-dev/pacbrew-repo` in the SDK sysroot
(`target/user/homebrew`); `scripts/build_ps5.sh` enables them when present.
libmicrohttpd is vendored under `vendor/etahen`, SQLite under `vendor/sqlite`.
**Where do the updates come from?**
From Sony's official update servers, the same files your console downloads on its own. PatchDL downloads only from a short list of PlayStation CDN hosts. To find older patches it also asks [Prospero Patches](https://prosperopatches.com/) which versions exist for a game. That lookup sends the game's title ID and nothing else.
**Can I get an older patch that runs on my firmware?**
Yes. Sony still hosts older patches, but its servers only tell your console about the newest one. When that one needs a newer firmware, PatchDL looks up the version history on [Prospero Patches](https://prosperopatches.com/) and lists the game under *Updates* with an **Old FW patch** button. Tap it and scan the QR code with your phone. Open the game on Prospero, pick the version PatchDL names (confirm the human check if one shows up) and copy the **SC** link. Paste it on your phone, and the PS5 downloads the patch from Sony and handles it like any other update.
**Does it change the updates?**
No. Each package stays exactly as Sony published it, and the console's own installer applies it.
**Does it delete the package after installing?**
Only once the install is confirmed: the game reports the new version and the console's installer recorded this exact package. If either check fails, the package stays. Switch off **Delete PKG after install** in Settings to keep every package.
**Will it touch my system software?**
No. PatchDL never downloads system software, and it only offers game updates that run on the firmware you have.
**What about disc games?**
Put the disc in, same as with any update.
**What happens if the power goes out?**
Start PatchDL again and press Resume. Finished pieces stay on disk.
## Disclaimer
PatchDL is an independent project. It is not affiliated with, endorsed by or sponsored by Sony Interactive Entertainment. "PlayStation" and "PS5" are trademarks of Sony Interactive Entertainment Inc. and appear here only to name the console PatchDL works with.
PatchDL downloads official, unmodified game updates that Sony publishes for games already installed on your console. It does not download games, does not contain or distribute Sony software, keys or game content, and does not install unsigned or modified packages. Use it with games you own, and follow the laws of your country and the terms that apply to you. This project does not support piracy, and issues about pirated content will be closed.
<details>
<summary><b>Build from source</b></summary>
<br>
```sh
scripts/build_ps5.sh # produces patchdl-ps5.elf
```
## Deploy
You need the [ps5-payload-dev SDK](https://github.com/ps5-payload-dev/sdk), version 0.44 or newer for firmware 1.00 to 13.60, with `libcurl` and `OpenSSL` from its [pacbrew-repo](https://github.com/ps5-payload-dev/pacbrew-repo). `libmicrohttpd` and SQLite are vendored. GitHub Actions builds every push; tagged builds become releases.
This console uses the BD-JB autoloader with itsPLK's Payload Manager on port 8084
(not a 9021 elfldr). `scripts/deploy_ps5.sh` uploads the version-named ELF and
launches it; the payload replaces any running instance.
To try a build on your own console:
```sh
PS5_HOST=<console-ip> scripts/deploy_ps5.sh
```
On start it shows an on-screen notification with the URL. Open the web UI at:
</details>
```text
http://<console-ip>:12880/
```
## Credits
## Status
PatchDL is written in C and builds on [libmicrohttpd](https://www.gnu.org/software/libmicrohttpd/), [libcurl](https://curl.se/), [OpenSSL](https://www.openssl.org/), [SQLite](https://sqlite.org/) and the [ps5-payload-dev SDK](https://github.com/ps5-payload-dev/sdk). The version history behind older patches comes from [Prospero Patches](https://prosperopatches.com/). Thanks to everyone behind them.
Verified on firmware 11.60: title scan, source classification, version
resolution past the nanoDNS block, firmware-compatibility filtering, the parallel
download pool, reboot-safe resume, and on-device SHA-256 verification. A full
Dead Island 2 update (61.6 GB) downloaded and verified byte-perfect across
several reboots.
## Support
Install works for same-region patches, where Sony stores the patch bytes under
the installed game's own title id.
If you like what I do, you can buy me a coffee*: [![Donate](https://img.shields.io/badge/Donate-PayPal-22c55e?style=flat-square&logo=paypal&logoColor=white)](https://paypal.me/oliverkoester)
Cross-region patches are a known limitation. Sony sometimes packages a regional
patch under a different (master) storage title and ships it as a debug-magic
container. PatchDL downloads such a patch and verifies it against Sony's hashes,
but the on-console installer (`InstallByPackage`) rejects it on 11.60, and the
homebrew alternative (BGFT register) returns "not supported" outside the system
process. Installing that class of patch needs Sony's authenticated updater, which
nanoDNS blocks. The web UI marks a title "Installing…" and reads progress from the
PS5's own notifications. Disc games need the disc inserted for their patch to
apply, which is a normal Sony requirement.
<sub>*It doesn't have to be a generous donation. A few cents are enough to show me who is interested in further development. So the motivation stays and I just know that I am not programming for the bin ;)</sub>
## License
PatchDL is free software under the **GNU General Public License v3.0 or later**. See [LICENSE](LICENSE). Use it, study it, change it, share it. Forks stay under the same license.
Copyright © 2026 Knutwurst.
BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 21 KiB

+20
View File
@@ -0,0 +1,20 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512">
<defs>
<linearGradient id="bg" x1="0" y1="0" x2="0" y2="1">
<stop offset="0" stop-color="#0f2a1e"/>
<stop offset="1" stop-color="#0a1612"/>
</linearGradient>
<linearGradient id="badge" x1="0" y1="0" x2="0" y2="1">
<stop offset="0" stop-color="#21d07a"/>
<stop offset="1" stop-color="#179a59"/>
</linearGradient>
</defs>
<rect width="512" height="512" rx="72" fill="url(#bg)"/>
<rect x="56" y="56" width="160" height="160" rx="36" fill="url(#badge)"/>
<text x="136" y="178" font-family="Helvetica,Arial,sans-serif" font-size="116"
font-weight="800" fill="#0a1612" text-anchor="middle">PD</text>
<text x="256" y="346" font-family="Helvetica,Arial,sans-serif" font-size="80"
font-weight="700" fill="#e7ecea" text-anchor="middle">PatchDL</text>
<text x="256" y="404" font-family="Helvetica,Arial,sans-serif" font-size="32"
font-weight="500" fill="#7a8f86" text-anchor="middle">PS5 Patch Tool</text>
</svg>

After

Width:  |  Height:  |  Size: 1.0 KiB

+10
View File
@@ -0,0 +1,10 @@
{
"titleId": "PTDL00001",
"deeplinkUri": "http://127.0.0.1:12880/",
"localizedParameters": {
"defaultLanguage": "en-US",
"en-US": {
"titleName": "PatchDL"
}
}
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 152 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 196 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 144 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 173 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 156 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 111 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 197 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 171 KiB

+1 -1
View File
@@ -19,7 +19,7 @@ VERSION=$(sed -n 's/.*PATCHDL_VERSION[^"]*"\([^"]*\)".*/\1/p' "$ROOT_DIR/src/pat
SRC_ELF="$ROOT_DIR/patchdl-ps5.elf"
[ -f "$SRC_ELF" ] || { echo "build first: $SRC_ELF missing" >&2; exit 1; }
UP_NAME="patchdl-ps5-v${VERSION}.elf"
UP_NAME="patchdl_${VERSION}.elf"
TMP_ELF="$ROOT_DIR/$UP_NAME"
cp "$SRC_ELF" "$TMP_ELF"
+9
View File
@@ -1,3 +1,12 @@
/* SPDX-License-Identifier: GPL-3.0-or-later
* Copyright (C) 2026 Knutwurst
*
* PatchDL is free software: you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free
* Software Foundation, either version 3 of the License, or (at your option)
* any later version. See the LICENSE file in the project root for details.
*/
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
+118 -6
View File
@@ -1,12 +1,76 @@
/* SPDX-License-Identifier: GPL-3.0-or-later
* Copyright (C) 2026 Knutwurst
*
* PatchDL is free software: you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free
* Software Foundation, either version 3 of the License, or (at your option)
* any later version. See the LICENSE file in the project root for details.
*/
#include "patchdl_appdb.h"
#include <errno.h>
#include <fcntl.h>
#include <sqlite3.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#define APP_DB_URI \
"file:/system_data/priv/mms/app.db?immutable=1"
/* A rescan can't open app.db by a relative path: SQLite turns it into an
absolute one with getcwd(), which resolves inside our own root again. So
it copies the file out through the working directory (the system root,
see patchdl_scan) and opens the copy. */
#define APP_DB_REL "system_data/priv/mms/app.db"
#define APP_DB_SNAPSHOT "/data/patchdl/.appdb.snapshot"
#define APP_DB_URI_SNAPSHOT "file:" APP_DB_SNAPSHOT "?immutable=1"
static char g_appdb_err[64];
const char *
patchdl_appdb_error(void) {
return g_appdb_err;
}
static int
snapshot_appdb(void) {
char *buf;
ssize_t n;
int in, out, rc = 0;
if ((in = open(APP_DB_REL, O_RDONLY | O_CLOEXEC)) < 0) {
snprintf(g_appdb_err, sizeof g_appdb_err, "open app.db errno %d", errno);
return -1;
}
out = open(APP_DB_SNAPSHOT, O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC, 0600);
if (out < 0) {
snprintf(g_appdb_err, sizeof g_appdb_err, "open snapshot errno %d", errno);
close(in);
return -1;
}
if (!(buf = malloc(65536))) {
close(in);
close(out);
return -1;
}
while ((n = read(in, buf, 65536)) > 0)
if (write(out, buf, (size_t)n) != n) {
snprintf(g_appdb_err, sizeof g_appdb_err, "write snapshot errno %d", errno);
rc = -1;
break;
}
if (n < 0) {
snprintf(g_appdb_err, sizeof g_appdb_err, "read app.db errno %d", errno);
rc = -1;
}
free(buf);
close(in);
close(out);
if (rc) unlink(APP_DB_SNAPSHOT);
return rc;
}
#define APPDB_MAX 1024
@@ -51,8 +115,9 @@ json_str(const char *json, const char *key, char *out, size_t out_sz) {
out[--len] = '\0';
}
int
patchdl_appdb_load(patchdl_appinfo_t **out, size_t *count) {
static int
load_db(const char *uri, patchdl_appinfo_t **out, size_t *count) {
int step = SQLITE_DONE;
sqlite3 *db = NULL;
sqlite3_stmt *stmt = NULL;
patchdl_appinfo_t *arr;
@@ -61,8 +126,12 @@ patchdl_appdb_load(patchdl_appinfo_t **out, size_t *count) {
*out = NULL;
*count = 0;
if (sqlite3_open_v2(APP_DB_URI, &db,
SQLITE_OPEN_READONLY | SQLITE_OPEN_URI, NULL) != SQLITE_OK) {
/* FULLMUTEX: today only the startup thread calls this, but future code
paths (a manual rescan triggered from the HTTP thread) would otherwise
race the SQLite handle. Cost is one mutex per call. */
if (sqlite3_open_v2(uri, &db,
SQLITE_OPEN_READONLY | SQLITE_OPEN_URI |
SQLITE_OPEN_FULLMUTEX, NULL) != SQLITE_OK) {
if (db) sqlite3_close(db);
return -1;
}
@@ -81,7 +150,7 @@ patchdl_appdb_load(patchdl_appinfo_t **out, size_t *count) {
return -1;
}
while (sqlite3_step(stmt) == SQLITE_ROW && n < APPDB_MAX) {
while ((step = sqlite3_step(stmt)) == SQLITE_ROW && n < APPDB_MAX) {
patchdl_appinfo_t *e = &arr[n];
const char *tid = (const char *)sqlite3_column_text(stmt, 0);
const char *name = (const char *)sqlite3_column_text(stmt, 1);
@@ -95,13 +164,44 @@ patchdl_appdb_load(patchdl_appinfo_t **out, size_t *count) {
if (json) {
json_str(json, "CONTENT_VERSION", e->content_version,
sizeof(e->content_version));
/* PS4 titles carry no CONTENT_VERSION; APP_VER is theirs, and
it includes an installed patch. */
if (!e->content_version[0])
json_str(json, "APP_VER", e->content_version,
sizeof(e->content_version));
json_str(json, "VERSION_FILE_URI", e->version_file_uri,
sizeof(e->version_file_uri));
}
n++;
}
sqlite3_finalize(stmt);
/* Anything but the end of the table (or the row cap) means the read
broke off, e.g. on a copy taken while the console wrote the file:
report failure instead of a list that silently lacks titles. */
if (step != SQLITE_DONE && step != SQLITE_ROW) {
free(arr);
sqlite3_close(db);
return -1;
}
/* Icon paths in a separate query: if a firmware lacks the icon0Info
column, only the icons go missing, not the whole title list. */
if (sqlite3_prepare_v2(db,
"SELECT titleId, icon0Info FROM tbl_contentinfo "
"WHERE icon0Info IS NOT NULL AND icon0Info != '';",
-1, &stmt, NULL) == SQLITE_OK) {
while (sqlite3_step(stmt) == SQLITE_ROW) {
const char *tid = (const char *)sqlite3_column_text(stmt, 0);
const char *icon = (const char *)sqlite3_column_text(stmt, 1);
patchdl_appinfo_t *e;
if (!tid || !icon) continue;
e = (patchdl_appinfo_t *)patchdl_appdb_find(arr, n, tid);
if (!e || e->icon_path[0]) continue;
strncpy(e->icon_path, icon, sizeof(e->icon_path) - 1);
e->icon_path[strcspn(e->icon_path, "?")] = '\0';
}
sqlite3_finalize(stmt);
}
sqlite3_close(db);
*out = arr;
@@ -109,6 +209,18 @@ patchdl_appdb_load(patchdl_appinfo_t **out, size_t *count) {
return 0;
}
int
patchdl_appdb_load(patchdl_appinfo_t **out, size_t *count, int relative) {
int rc;
*out = NULL;
*count = 0;
if (!relative) return load_db(APP_DB_URI, out, count);
if (snapshot_appdb()) return -2;
rc = load_db(APP_DB_URI_SNAPSHOT, out, count);
unlink(APP_DB_SNAPSHOT);
return rc;
}
void
patchdl_appdb_free(patchdl_appinfo_t *arr) {
free(arr);
+16 -3
View File
@@ -1,3 +1,12 @@
/* SPDX-License-Identifier: GPL-3.0-or-later
* Copyright (C) 2026 Knutwurst
*
* PatchDL is free software: you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free
* Software Foundation, either version 3 of the License, or (at your option)
* any later version. See the LICENSE file in the project root for details.
*/
#pragma once
#include <stddef.h>
@@ -8,13 +17,17 @@ typedef struct {
char content_id[64];
char content_version[16];
char version_file_uri[256]; /* Sony version.xml URL (UUID assigned) */
char icon_path[256]; /* icon0Info without its "?ts=" suffix, or "" */
} patchdl_appinfo_t;
/* Read the PS5 app database (tbl_contentinfo) for installed-title metadata.
Returns 0 on success with a malloc'd array (caller frees with
patchdl_appdb_free). Requires the root-vnode swap + elevated authid to be
in effect (the caller arranges this). */
int patchdl_appdb_load(patchdl_appinfo_t **out, size_t *count);
patchdl_appdb_free). Requires elevated authid plus either the root-vnode
swap or, with `relative` set, the working directory at the system root
(the caller arranges this). */
int patchdl_appdb_load(patchdl_appinfo_t **out, size_t *count, int relative);
/* Why the last relative load failed to copy app.db (errno text), or "". */
const char *patchdl_appdb_error(void);
void patchdl_appdb_free(patchdl_appinfo_t *arr);
const patchdl_appinfo_t *patchdl_appdb_find(const patchdl_appinfo_t *arr,
+9
View File
@@ -1,3 +1,12 @@
/* SPDX-License-Identifier: GPL-3.0-or-later
* Copyright (C) 2026 Knutwurst
*
* PatchDL is free software: you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free
* Software Foundation, either version 3 of the License, or (at your option)
* any later version. See the LICENSE file in the project root for details.
*/
#include "patchdl_assets.h"
#include <stdlib.h>
+9
View File
@@ -1,3 +1,12 @@
/* SPDX-License-Identifier: GPL-3.0-or-later
* Copyright (C) 2026 Knutwurst
*
* PatchDL is free software: you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free
* Software Foundation, either version 3 of the License, or (at your option)
* any later version. See the LICENSE file in the project root for details.
*/
#pragma once
#include <stddef.h>
+9
View File
@@ -1,3 +1,12 @@
/* SPDX-License-Identifier: GPL-3.0-or-later
* Copyright (C) 2026 Knutwurst
*
* PatchDL is free software: you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free
* Software Foundation, either version 3 of the License, or (at your option)
* any later version. See the LICENSE file in the project root for details.
*/
#pragma once
/*
+9
View File
@@ -1,3 +1,12 @@
/* SPDX-License-Identifier: GPL-3.0-or-later
* Copyright (C) 2026 Knutwurst
*
* PatchDL is free software: you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free
* Software Foundation, either version 3 of the License, or (at your option)
* any later version. See the LICENSE file in the project root for details.
*/
#include "patchdl_fw.h"
#include <ps5/kernel.h>
+9
View File
@@ -1,3 +1,12 @@
/* SPDX-License-Identifier: GPL-3.0-or-later
* Copyright (C) 2026 Knutwurst
*
* PatchDL is free software: you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free
* Software Foundation, either version 3 of the License, or (at your option)
* any later version. See the LICENSE file in the project root for details.
*/
#pragma once
#include <stdint.h>
+409 -71
View File
@@ -1,3 +1,12 @@
/* SPDX-License-Identifier: GPL-3.0-or-later
* Copyright (C) 2026 Knutwurst
*
* PatchDL is free software: you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free
* Software Foundation, either version 3 of the License, or (at your option)
* any later version. See the LICENSE file in the project root for details.
*/
#include "patchdl_install.h"
#include <arpa/inet.h>
@@ -7,9 +16,13 @@
#include <pthread.h>
#include <stddef.h>
#include <stdbool.h>
#include <stdint.h>
#include <stdatomic.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/socket.h>
#include <sys/stat.h>
@@ -36,6 +49,12 @@ typedef struct {
const char *content_id;
const char *content_name;
const char *icon_url;
/* Sony reads past the six pointers. The 8 bytes after icon_url select the
install mode: 0 = plain install, other values take a patch/cancel path
that refuses with 0x80B2116F. Left as stack garbage they caused our
intermittent 0x80B2116F (measured by ps5upload on FW 13.60). */
uint64_t unknown_30;
uint64_t reserved[7];
} ai_meta_info_t;
typedef struct {
@@ -45,6 +64,42 @@ typedef struct {
long unknown[810];
} ai_playgo_info_t;
typedef struct {
int32_t error_code;
int32_t version;
char description[512];
char type[9];
} ai_install_error_t;
typedef struct {
char status[16];
char src_type[8];
uint32_t remain_time;
uint64_t downloaded_size;
uint64_t initial_chunk_size;
uint64_t total_size;
uint32_t promote_progress;
ai_install_error_t error_info;
int32_t local_copy_percent;
bool is_copy_only;
char _pad[2048]; /* safety margin — actual Sony struct may be larger */
} ai_install_status_t;
/* Padded buffers for Sony output writes whose actual size is reverse-engineered.
The visible content fits in 0x30 (content_id) / 16 (title_id) bytes, but the
firmware may NUL-pad or write more. Used as caller-side temporaries that are
then copy_bounded()-d into the right-sized destination. */
#define AI_CONTENTID_OUT_SIZE 256
#define AI_TITLEID_OUT_SIZE 128
#define STATIC_ASSERT(c, n) typedef char static_assert_##n[(c) ? 1 : -1]
STATIC_ASSERT(sizeof(ai_pkg_info_t) == 0x38, pkg_info_size);
STATIC_ASSERT(sizeof(ai_meta_info_t) == 0x70, meta_info_size);
STATIC_ASSERT(sizeof(ai_playgo_info_t) == 0x2700, playgo_info_size);
STATIC_ASSERT(offsetof(ai_meta_info_t, uri) == 0, meta_uri_offset);
STATIC_ASSERT(offsetof(ai_meta_info_t, icon_url) == (5 * sizeof(void *)),
meta_icon_offset);
/* Sysmodule IDs (from ps5-payload-dev/sdk crt/rtld_sprx.c). */
#define SYSMOD_IPMI 0x8000001d
#define SYSMOD_USERSERVICE 0x80000011
@@ -58,12 +113,14 @@ typedef int (*ai_install_by_pkg_fn)(ai_meta_info_t *meta, ai_pkg_info_t *info,
ai_playgo_info_t *playgo);
typedef int (*ai_title_from_pkg_fn)(const char *path, char *title_id, int *is_app);
typedef int (*ai_content_from_pkg_fn)(const char *path, char *content_id, int *is_app);
typedef int (*ai_get_status_fn)(char *content_id_out, ai_install_status_t *status);
static ai_init_fn ai_initialize;
static ai_install_pkg_fn ai_install_pkg;
static ai_install_by_pkg_fn ai_install_by_package;
static ai_title_from_pkg_fn ai_title_from_pkg;
static ai_content_from_pkg_fn ai_content_from_pkg;
static ai_get_status_fn ai_get_status;
/* Resolve + initialize the AppInstUtil backend WITHOUT linking the sce libs
(that makes the ELF unloadable by the elfldr) and WITHOUT raw
@@ -72,11 +129,18 @@ static ai_content_from_pkg_fn ai_content_from_pkg;
symbols via the kernel dynlib helpers. Runs in a detached thread; the HTTP
handler reports the stage and never blocks.
stage: 0 idle, 1 resolve loader, 2 load modules, 3 resolve symbols,
4 initialize, 5 ready, negative = failure at that step. */
static volatile int g_stage;
static int g_err;
4 initialize, 5 ready, negative = failure at that step.
Stored as _Atomic so the worker's release-store and the request handlers'
acquire-loads pair properly — the function pointers they read after
stage==5 must not be reordered ahead of the stage check. */
static _Atomic int g_stage;
static _Atomic int g_err;
static pthread_mutex_t g_mtx = PTHREAD_MUTEX_INITIALIZER;
static char g_probe_json[2048]; /* filled by the backend thread */
static char g_last_content_id[AI_CONTENTID_SIZE];
static char g_last_target_title_id[32];
static char g_last_method[32];
static int g_last_start_rc;
static intptr_t
dynsym(const char *module, const char *sym) {
@@ -112,6 +176,63 @@ local_ip(char *out, size_t n) {
freeifaddrs(ifa);
}
static void
copy_bounded(char *dst, size_t dst_sz, const char *src, size_t src_sz) {
size_t n;
if (!dst || !dst_sz) return;
dst[0] = '\0';
if (!src || !src_sz) return;
for (n = 0; n + 1 < dst_sz && n < src_sz && src[n]; n++)
dst[n] = src[n];
dst[n] = '\0';
}
/* Conservative whitelist for ids/filenames that we extract from a local path
and inject into URIs/log lines passed to AppInstUtil. Rejects CRLF, '/',
'\\', NUL, control chars, anything that could change URI semantics. */
static int
install_id_safe(const char *s) {
if (!s || !s[0]) return 0;
for (const char *p = s; *p; p++) {
if (!((*p >= 'A' && *p <= 'Z') ||
(*p >= 'a' && *p <= 'z') ||
(*p >= '0' && *p <= '9') ||
*p == '_' || *p == '-' || *p == '.'))
return 0;
}
return 1;
}
/* Exact match for PS4/PS5 title ids (9 chars: 4 letters + 5 digits). A bare
strncmp(...,9) would also match longer ids that share a 9-char prefix and
could collide PPSA12345 with PPSA12345EVIL. */
static int
title_id_eq9(const char *a, const char *b) {
if (!a || !b) return 0;
if (strnlen(a, 16) != 9 || strnlen(b, 16) != 9) return 0;
return strncmp(a, b, 9) == 0;
}
static void
remember_install(const char *target_title_id, const char *method,
const ai_pkg_info_t *pkg, const char *fallback_content_id,
int rc) {
char cid[AI_CONTENTID_SIZE] = {0};
if (pkg)
copy_bounded(cid, sizeof(cid), pkg->content_id, sizeof(pkg->content_id));
if (!cid[0] && fallback_content_id)
copy_bounded(cid, sizeof(cid), fallback_content_id, strlen(fallback_content_id));
pthread_mutex_lock(&g_mtx);
snprintf(g_last_content_id, sizeof(g_last_content_id), "%s", cid);
snprintf(g_last_target_title_id, sizeof(g_last_target_title_id), "%s",
target_title_id ? target_title_id : "");
snprintf(g_last_method, sizeof(g_last_method), "%s", method ? method : "");
g_last_start_rc = rc;
pthread_mutex_unlock(&g_mtx);
}
/* Resolve (dlsym, never call) a list of candidate patch-install symbols and
record which exist. Runs inside the backend thread, where the AppInstUtil
module is already loaded — the same proven-safe context as the normal symbol
@@ -122,10 +243,12 @@ fill_probe(void) {
"sceAppInstUtilInitialize",
"sceAppInstUtilAppInstallPkg",
"sceAppInstUtilAppInstallTitleDir", /* takes an explicit title id */
"sceAppInstUtilAppInstallAll", /* tile fallback on 13.xx */
"sceAppInstUtilInstallByPackage",
"sceAppInstUtilInstallByPackageEx",
"sceAppInstUtilGetTitleIdFromPkg",
"sceAppInstUtilGetContentIdFromPkg",
"sceAppInstUtilGetInstallStatus",
"sceAppInstUtilAppExist",
"sceAppInstUtilAppGetInstallStatus",
"sceAppInstUtilAppInstallStatus",
@@ -209,6 +332,8 @@ backend_init_thread(void *arg) {
"sceAppInstUtilGetTitleIdFromPkg");
ai_content_from_pkg = (ai_content_from_pkg_fn)dynsym("libSceAppInstUtil.sprx",
"sceAppInstUtilGetContentIdFromPkg");
ai_get_status = (ai_get_status_fn)dynsym("libSceAppInstUtil.sprx",
"sceAppInstUtilGetInstallStatus");
/* Read-only feasibility probe — module is loaded, safe context. */
fill_probe();
@@ -241,6 +366,16 @@ backend_start(void) {
pthread_mutex_unlock(&g_mtx);
}
/* Start the backend if needed and give it up to 15 s to come up (it loads a
system module and resolves symbols in its own thread), so an install
request right after startup doesn't fail just because it was early. */
static void
backend_wait(void) {
backend_start();
for (int i = 0; i < 150 && g_stage > 0 && g_stage != 5; i++)
usleep(100 * 1000);
}
static const char *
stage_str(int s) {
switch (s) {
@@ -295,7 +430,10 @@ patchdl_install_pkg_meta(const char *local_path, char *content_id, size_t cid_sz
char *title_id, size_t tid_sz, int *is_app,
char *msg, size_t msg_sz) {
char sdk_path[1024];
char cid[64] = {0}, tid[48] = {0};
/* Padded output buffers — Sony's GetContentIdFromPkg / GetTitleIdFromPkg
take no length hint; firmware may NUL-pad more than the visible id. */
char cid[AI_CONTENTID_OUT_SIZE] = {0};
char tid[AI_TITLEID_OUT_SIZE] = {0};
int app_c = 0, app_t = 0, ok = 0;
struct stat st;
@@ -307,7 +445,7 @@ patchdl_install_pkg_meta(const char *local_path, char *content_id, size_t cid_sz
snprintf(msg, msg_sz, "package not on disk");
return -1;
}
backend_start();
backend_wait();
if (g_stage != 5) {
snprintf(msg, msg_sz, "install backend not ready: %s", stage_str(g_stage));
return -1;
@@ -319,25 +457,134 @@ patchdl_install_pkg_meta(const char *local_path, char *content_id, size_t cid_sz
if (ai_content_from_pkg &&
ai_content_from_pkg(sdk_path, cid, &app_c) == 0 && cid[0]) {
if (content_id && cid_sz) {
strncpy(content_id, cid, cid_sz - 1);
content_id[cid_sz - 1] = '\0';
}
copy_bounded(content_id, cid_sz, cid, sizeof(cid));
if (is_app) *is_app = app_c;
ok = 1;
}
if (ai_title_from_pkg &&
ai_title_from_pkg(sdk_path, tid, &app_t) == 0 && tid[0]) {
if (title_id && tid_sz) {
strncpy(title_id, tid, tid_sz - 1);
title_id[tid_sz - 1] = '\0';
}
copy_bounded(title_id, tid_sz, tid, sizeof(tid));
ok = 1;
}
snprintf(msg, msg_sz, ok ? "ok" : "could not read pkg metadata");
return ok ? 0 : -1;
}
void
patchdl_install_debug_state(char *out, size_t out_sz) {
char cid[AI_CONTENTID_SIZE];
char tid[32], method[32];
int start_rc;
int stage;
pthread_mutex_lock(&g_mtx);
memcpy(cid, g_last_content_id, sizeof(cid));
snprintf(tid, sizeof(tid), "%s", g_last_target_title_id);
snprintf(method, sizeof(method), "%s", g_last_method);
start_rc = g_last_start_rc;
stage = g_stage;
pthread_mutex_unlock(&g_mtx);
snprintf(out, out_sz,
"{\"stage\":%d,\"cid_len\":%d,\"cid_hex\":\"%02x%02x%02x%02x\","
"\"content_id\":\"%s\",\"target_title_id\":\"%s\","
"\"method\":\"%s\",\"start_rc\":%d}",
stage,
(int)strnlen(cid, sizeof(cid)),
(unsigned char)cid[0], (unsigned char)cid[1],
(unsigned char)cid[2], (unsigned char)cid[3],
cid, tid, method, start_rc);
}
int
patchdl_install_status_json(char *out, size_t out_sz) {
char cid[AI_CONTENTID_SIZE];
char tid[32];
char method[32];
int start_rc;
/* ai_install_status_t carries a 2 KB safety pad; live on the heap so
a frequently-polled /api/installstatus doesn't keep committing pages
on every MHD worker's stack. */
ai_install_status_t *st = NULL;
char status[17], src_type[9];
int rc;
int progress = 0;
int terminal = 0;
if (!out || !out_sz)
return -1;
backend_start();
pthread_mutex_lock(&g_mtx);
snprintf(cid, sizeof(cid), "%s", g_last_content_id);
snprintf(tid, sizeof(tid), "%s", g_last_target_title_id);
snprintf(method, sizeof(method), "%s", g_last_method);
start_rc = g_last_start_rc;
pthread_mutex_unlock(&g_mtx);
if (!cid[0]) {
snprintf(out, out_sz, "{\"active\":false}");
return -1;
}
if (g_stage != 5) {
snprintf(out, out_sz,
"{\"active\":true,\"content_id\":\"%s\",\"target_title_id\":\"%s\","
"\"method\":\"%s\",\"start_rc\":%d,\"status\":\"backend_not_ready\","
"\"stage\":\"%s\"}",
cid, tid, method, start_rc, stage_str(g_stage));
return -1;
}
if (!ai_get_status) {
snprintf(out, out_sz,
"{\"active\":true,\"content_id\":\"%s\",\"target_title_id\":\"%s\","
"\"method\":\"%s\",\"start_rc\":%d,\"status\":\"unavailable\","
"\"message\":\"sceAppInstUtilGetInstallStatus not exported\"}",
cid, tid, method, start_rc);
return -1;
}
st = calloc(1, sizeof(*st));
if (!st) {
snprintf(out, out_sz, "{\"error\":\"oom\"}");
return -1;
}
/* sceAppInstUtilGetInstallStatus(char *content_id_out, status_t *status):
first arg is an OUTPUT buffer that receives the current install's content_id.
Do NOT pass `cid` there — it would be overwritten. The visible id fits in
0x30 bytes but Sony's NUL-pad length is unknown; use a padded buffer. */
{
char ai_cid_out[AI_CONTENTID_OUT_SIZE] = {0};
rc = ai_get_status(ai_cid_out, st);
(void)ai_cid_out; /* returned content_id for future use */
}
copy_bounded(status, sizeof(status), st->status, sizeof(st->status));
copy_bounded(src_type, sizeof(src_type), st->src_type, sizeof(st->src_type));
if (st->total_size > 0)
progress = (int)((st->downloaded_size * 100) / st->total_size);
if (progress < 0) progress = 0;
if (progress > 100) progress = 100;
terminal = (!strcmp(status, "playable") ||
!strcmp(status, "error") ||
!strcmp(status, "none"));
snprintf(out, out_sz,
"{\"active\":true,\"terminal\":%s,\"content_id\":\"%s\","
"\"target_title_id\":\"%s\",\"method\":\"%s\",\"start_rc\":%d,"
"\"rc\":%d,\"status\":\"%s\",\"src_type\":\"%s\","
"\"progress\":%d,\"downloaded_size\":%llu,\"total_size\":%llu,"
"\"promote_progress\":%u,\"error_code\":%d}",
terminal ? "true" : "false", cid, tid, method, start_rc, rc,
status, src_type, progress,
(unsigned long long)st->downloaded_size,
(unsigned long long)st->total_size,
(unsigned)st->promote_progress,
(int)st->error_info.error_code);
free(st);
return rc;
}
int
patchdl_install_local_pkg(const char *local_path, const char *expected_title_id,
const char *storage_title_id,
@@ -346,7 +593,7 @@ patchdl_install_local_pkg(const char *local_path, const char *expected_title_id,
char sdk_path[1024];
char pkg_tid[48] = {0};
struct stat st;
int rc;
int rc = -1;
int pkg_tid_mismatch = 0;
if (!local_path || !local_path[0]) {
@@ -358,7 +605,7 @@ patchdl_install_local_pkg(const char *local_path, const char *expected_title_id,
return -1;
}
backend_start();
backend_wait();
if (g_stage != 5) {
snprintf(msg, msg_sz, "install backend not ready: %s", stage_str(g_stage));
return -1;
@@ -380,15 +627,20 @@ patchdl_install_local_pkg(const char *local_path, const char *expected_title_id,
such packages to the raw AppInstallPkg path. */
if (storage_title_id && storage_title_id[0] &&
expected_title_id && expected_title_id[0] &&
strncmp(storage_title_id, expected_title_id, 9) != 0) {
!title_id_eq9(storage_title_id, expected_title_id)) {
pkg_tid_mismatch = 1;
strncpy(pkg_tid, storage_title_id, sizeof(pkg_tid) - 1);
pkg_tid[sizeof(pkg_tid) - 1] = '\0';
}
if (ai_title_from_pkg && expected_title_id && expected_title_id[0]) {
/* Sony's GetTitleIdFromPkg writes into the output buffer with no length
hint — pad generously and copy the safe portion into pkg_tid. */
char tid_out[AI_TITLEID_OUT_SIZE] = {0};
int is_app = 0;
if (ai_title_from_pkg(sdk_path, pkg_tid, &is_app) == 0 && pkg_tid[0] &&
strncmp(pkg_tid, expected_title_id, 9) != 0) {
pkg_tid_mismatch = 1;
if (ai_title_from_pkg(sdk_path, tid_out, &is_app) == 0 && tid_out[0]) {
if (!title_id_eq9(tid_out, expected_title_id))
pkg_tid_mismatch = 1;
copy_bounded(pkg_tid, sizeof(pkg_tid), tid_out, sizeof(tid_out));
}
}
if (pkg_tid_mismatch && (!target_content_id || !target_content_id[0])) {
@@ -397,21 +649,29 @@ patchdl_install_local_pkg(const char *local_path, const char *expected_title_id,
pkg_tid, expected_title_id);
return -1;
}
/* Preferred path: InstallByPackage accepts target metadata. Use it first,
and use it exclusively when the downloaded bytes report a master/storage
title id that differs from the target regional title id. */
/* Preferred path: etaHEN's DPI uses InstallByPackage with the installed
game's content_id in MetaInfo so AppInstUtil binds the install to the
right title slot. For shared-master cross-region packages the pkg bytes
carry a different title id than the installed game; passing content_id
is what etaHEN does to route the install correctly. */
{
char file_uri[1100];
char http_loop_uri[1200] = {0};
char http_lan_uri[1200] = {0};
const char *uris[4];
ai_meta_info_t meta = {0};
ai_pkg_info_t pkg = {0};
ai_playgo_info_t playgo = {0};
int rc2 = -1;
const char *title_dir;
const char *file_base;
char file_uri[1100];
char http_loop_uri[1200] = {0};
char http_lan_uri[1200] = {0};
const char *uris[4];
ai_meta_info_t meta = {0};
ai_pkg_info_t pkg = {0};
/* playgo is 0x2700 bytes — too big for the MHD worker stack alongside
uris, meta, pkg, resp buffers, and Sony's own frame use. */
ai_playgo_info_t *playgo = calloc(1, sizeof(*playgo));
int rc2 = -1;
const char *title_dir;
const char *file_base;
if (!playgo) {
snprintf(msg, msg_sz, "out of memory");
return -1;
}
snprintf(file_uri, sizeof(file_uri), "file://%s", sdk_path);
title_dir = strstr(local_path, "/data/patchdl/");
@@ -423,69 +683,147 @@ patchdl_install_local_pkg(const char *local_path, const char *expected_title_id,
if (tlen > 0 && tlen < sizeof(title_id)) {
char ip[INET_ADDRSTRLEN] = {0};
memcpy(title_id, t, tlen);
snprintf(http_loop_uri, sizeof(http_loop_uri),
"http://127.0.0.1:%d/api/pkg/%s/%s",
PATCHDL_HTTP_PORT, title_id, file_base + 1);
local_ip(ip, sizeof(ip));
if (ip[0])
snprintf(http_lan_uri, sizeof(http_lan_uri),
"http://%s:%d/api/pkg/%s/%s",
ip, PATCHDL_HTTP_PORT, title_id, file_base + 1);
/* CRLF/path-injection guard: anything we splice into the loop /
LAN URI lands inside Sony's HTTP request line. Reject ids
or filenames carrying delimiters or control chars. */
if (install_id_safe(title_id) && install_id_safe(file_base + 1)) {
snprintf(http_loop_uri, sizeof(http_loop_uri),
"http://127.0.0.1:%d/api/pkg/%s/%s",
PATCHDL_HTTP_PORT, title_id, file_base + 1);
local_ip(ip, sizeof(ip));
if (ip[0])
snprintf(http_lan_uri, sizeof(http_lan_uri),
"http://%s:%d/api/pkg/%s/%s",
ip, PATCHDL_HTTP_PORT, title_id, file_base + 1);
}
}
}
uris[0] = sdk_path; /* /user/data/... — the allowlisted path */
uris[1] = file_uri; /* file:///user/data/... */
uris[2] = http_loop_uri[0] ? http_loop_uri : NULL;
uris[3] = http_lan_uri[0] ? http_lan_uri : NULL;
/* Stream install first: Sony's installer pulls the package from our
own /api/pkg over HTTP (ranges), the route that writes the content.
The bare path forms come last. */
uris[0] = http_loop_uri[0] ? http_loop_uri : NULL;
uris[1] = http_lan_uri[0] ? http_lan_uri : NULL;
uris[2] = sdk_path; /* /user/data/... */
uris[3] = file_uri; /* file:///user/data/... */
meta.ex_uri = "";
meta.playgo_scenario_id = "";
meta.content_id = target_content_id ? target_content_id : "";
/* Empty: the installer takes the id from the package itself. */
meta.content_id = "";
meta.content_name = "PatchDL";
meta.icon_url = "";
{
char tries[260] = {0};
const char *labels[4] = { "userdata", "file", "loop", "lan" };
const char *labels[4] = { "loop", "lan", "userdata", "file" };
for (int i = 0; i < 4; i++) {
if (!uris[i]) continue;
memset(&pkg, 0, sizeof(pkg));
memset(&playgo, 0, sizeof(playgo));
memset(playgo, 0, sizeof(*playgo));
meta.uri = uris[i];
rc2 = ai_install_by_package(&meta, &pkg, &playgo);
rc2 = ai_install_by_package(&meta, &pkg, playgo);
{
size_t l = strlen(tries);
snprintf(tries + l, sizeof(tries) - l, "%s%s=0x%08x",
l ? "," : "", labels[i], (unsigned)rc2);
}
if (rc2 == 0) {
snprintf(msg, msg_sz, "install started (InstallByPackage%s)",
pkg_tid_mismatch ? ", shared master bytes" : "");
remember_install(expected_title_id, "InstallByPackage",
&pkg, target_content_id, rc2);
snprintf(msg, msg_sz, "install started (InstallByPackage, content %.47s)",
pkg.content_id[0] ? pkg.content_id :
(target_content_id ? target_content_id : ""));
free(playgo);
return 0;
}
}
rc = rc2;
if (pkg_tid_mismatch) {
snprintf(msg, msg_sz,
"install rejected (pkg %.12s -> %.12s; tries: %s)",
pkg_tid, expected_title_id ? expected_title_id : "", tries);
return rc ? rc : -1;
}
}
free(playgo);
}
/* Last resort for normal same-title packages only. This path has no target
metadata parameter, so it is intentionally skipped for shared-master
region bytes. */
{
ai_pkg_info_t pkg = {0};
int rc2 = ai_install_pkg(sdk_path, &pkg);
if (rc2 == 0) {
snprintf(msg, msg_sz, "install started (AppInstallPkg)");
return 0;
}
snprintf(msg, msg_sz,
"install rejected (InstallByPackage=0x%08x, AppInstallPkg=0x%08x)",
(unsigned)rc, (unsigned)rc2);
return rc2 ? rc2 : (rc ? rc : -1);
/* No AppInstallPkg fallback: it returns 0 and writes only the app
metadata (version, tile) without installing any content, which shows
up as "updated" while the game still runs the old version. */
snprintf(msg, msg_sz, "install rejected (InstallByPackage=0x%08x)", (unsigned)rc);
return rc ? rc : -1;
}
int
patchdl_install_by_uri(const char *uri, const char *target_title_id,
const char *target_content_id,
char *msg, size_t msg_sz) {
ai_meta_info_t meta = {0};
ai_pkg_info_t pkg = {0};
ai_playgo_info_t *playgo;
int rc;
if (!uri || !uri[0]) {
snprintf(msg, msg_sz, "no uri");
return -1;
}
backend_wait();
if (g_stage != 5) {
snprintf(msg, msg_sz, "install backend not ready: %s", stage_str(g_stage));
return -1;
}
playgo = calloc(1, sizeof(*playgo));
if (!playgo) { snprintf(msg, msg_sz, "out of memory"); return -1; }
meta.uri = uri;
meta.ex_uri = "";
meta.playgo_scenario_id = "";
meta.content_id = target_content_id ? target_content_id : "";
meta.content_name = "PatchDL";
meta.icon_url = "";
rc = ai_install_by_package(&meta, &pkg, playgo);
remember_install(target_title_id, "InstallByURI", &pkg, target_content_id, rc);
free(playgo);
if (rc == 0) {
snprintf(msg, msg_sz, "install started (InstallByPackage/uri, content %.47s)",
pkg.content_id[0] ? pkg.content_id :
(target_content_id ? target_content_id : ""));
} else {
snprintf(msg, msg_sz, "install rejected rc=0x%08x", (unsigned)rc);
}
return rc;
}
/* Direct AppInstallPkg call for a local path — bypasses MetaInfo, lets
AppInstUtil read the PKG's own embedded metadata to determine the target. */
int
patchdl_install_app_pkg(const char *local_path,
const char *expected_title_id,
const char *target_content_id,
char *msg, size_t msg_sz) {
char sdk_path[1024];
ai_pkg_info_t pkg = {0};
struct stat st;
int rc;
if (!local_path || !local_path[0]) { snprintf(msg, msg_sz, "no path"); return -1; }
if (stat(local_path, &st) != 0) { snprintf(msg, msg_sz, "package not downloaded"); return -1; }
backend_wait();
if (g_stage != 5) {
snprintf(msg, msg_sz, "install backend not ready: %s", stage_str(g_stage));
return -1;
}
if (!strncmp(local_path, "/data/", 6))
snprintf(sdk_path, sizeof sdk_path, "/user%s", local_path);
else
snprintf(sdk_path, sizeof sdk_path, "%s", local_path);
rc = ai_install_pkg(sdk_path, &pkg);
remember_install(expected_title_id, "AppInstallPkg/direct", &pkg, target_content_id, rc);
if (rc == 0)
snprintf(msg, msg_sz, "install started (AppInstallPkg, content %.47s)",
pkg.content_id[0] ? pkg.content_id :
(target_content_id ? target_content_id : ""));
else
snprintf(msg, msg_sz, "install rejected rc=0x%08x", (unsigned)rc);
return rc;
}
+39 -3
View File
@@ -1,3 +1,12 @@
/* SPDX-License-Identifier: GPL-3.0-or-later
* Copyright (C) 2026 Knutwurst
*
* PatchDL is free software: you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free
* Software Foundation, either version 3 of the License, or (at your option)
* any later version. See the LICENSE file in the project root for details.
*/
#pragma once
#include <stddef.h>
@@ -14,9 +23,10 @@
*/
/* `expected_title_id` is the title id of the installed game the patch is for.
`storage_title_id` is the title id embedded in the delta_url storage path.
`target_content_id` is the installed game's content id from app.db; when
present it is passed to InstallByPackage so Sony's installer has the target
metadata even for region-shared/master-storage patch bytes. */
`target_content_id` is the installed game's content id from app.db; it is
retained for diagnostics and status fallback. Normal same-title installs
deliberately pass an empty MetaInfo.content_id, matching etaHEN's native DPI
path and letting AppInstUtil bind the package to its signed metadata. */
int patchdl_install_local_pkg(const char *local_path,
const char *expected_title_id,
const char *storage_title_id,
@@ -37,3 +47,29 @@ int patchdl_install_api_probe(char *out, size_t out_sz);
int patchdl_install_pkg_meta(const char *local_path, char *content_id, size_t cid_sz,
char *title_id, size_t tid_sz, int *is_app,
char *msg, size_t msg_sz);
/* Read-only: report the last AppInstUtil install task PatchDL started, using
sceAppInstUtilGetInstallStatus when present. No install, no mutation. */
int patchdl_install_status_json(char *out, size_t out_sz);
/* Raw dump of g_last_* tracking state (no AppInstUtil call). For diagnosis. */
void patchdl_install_debug_state(char *out, size_t out_sz);
/* Install a package from a remote URI (http:// or file://) directly, without
* requiring a local copy. Used for shared-master delta packages where the
* version.xml targets a different title id than the CDN storage path.
* `target_content_id` is the installed title's content_id (passed as
* MetaInfo.content_id so AppInstUtil binds the install to the right title).
*/
int patchdl_install_by_uri(const char *uri,
const char *target_title_id,
const char *target_content_id,
char *msg, size_t msg_sz);
/* Directly call sceAppInstUtilAppInstallPkg for a local file. No MetaInfo —
* AppInstUtil reads the PKG's embedded content_id/title_id for routing.
* Use when InstallByPackage is unavailable (privilege). */
int patchdl_install_app_pkg(const char *local_path,
const char *expected_title_id,
const char *target_content_id,
char *msg, size_t msg_sz);
+295 -43
View File
@@ -1,7 +1,17 @@
/* SPDX-License-Identifier: GPL-3.0-or-later
* Copyright (C) 2026 Knutwurst
*
* PatchDL is free software: you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free
* Software Foundation, either version 3 of the License, or (at your option)
* any later version. See the LICENSE file in the project root for details.
*/
#include "patchdl_net.h"
#include <arpa/inet.h>
#include <errno.h>
#include <fcntl.h>
#include <netinet/in.h>
#include <pthread.h>
#include <stdio.h>
@@ -9,6 +19,7 @@
#include <string.h>
#include <strings.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <sys/time.h>
#include <unistd.h>
@@ -22,32 +33,75 @@
#define DNS_PORT 53
#define DNS_TIMEOUT_MS 3000
/* Manifest sanity caps — reject anything bigger than a real PS5 patch. The
largest title we've seen tops out around 70 GB / 18 pieces. */
#define PATCHDL_MAX_PIECES 4096
#define PATCHDL_MAX_PIECE_BYTES (8ULL * 1024 * 1024 * 1024) /* 8 GiB */
#define PATCHDL_MAX_TOTAL_BYTES (200ULL * 1024 * 1024 * 1024) /* 200 GiB */
/* In-RAM buffer caps for full HTTP body fetches. version.xml is a few KB,
manifest JSON is a few MB at most — fail-closed beyond that. The
manifest cap is sized for ~4096 pieces × ~3 KB JSON each with plenty of
headroom; real PS5 manifests are 1-2 MB. */
#define PATCHDL_BUF_MAX_VERXML (4 * 1024 * 1024)
#define PATCHDL_BUF_MAX_MANIFEST (16 * 1024 * 1024)
#ifdef PATCHDL_HAVE_CURL
/* Replacement for fopen("wb"/"r+b") that refuses to follow a symlink at the
destination (would let a malicious symlink redirect the download) and pins
the new file's mode to 0600. Returns NULL on any open error. */
static FILE *
fopen_safe(const char *path, int rw_existing) {
int flags = O_CLOEXEC | O_NOFOLLOW;
int fd;
flags |= rw_existing ? O_RDWR : (O_WRONLY | O_CREAT | O_TRUNC);
fd = open(path, flags, 0600);
if (fd < 0) return NULL;
return fdopen(fd, rw_existing ? "r+b" : "wb");
}
#endif
#ifdef PATCHDL_HAVE_CURL
static const char *ALLOWED_HOSTS[] = {
"sgst.prod.dl.playstation.net",
"gst.prod.dl.playstation.net",
"gs2.ww.prod.dl.playstation.net",
"prosperopatches.com",
"gs-sec.ww.np.dl.playstation.net", /* PS4 update lists */
NULL,
};
/* PS4 package manifests are published on gs2 over plain http only (https
there is a CloudFront edge without Sony's certificate). The console's own
installer checks the package signature, so a forged manifest can't get an
unsigned package installed. Everything else stays https-only. */
#define PLAIN_HTTP_HOST "gs2.ww.prod.dl.playstation.net"
static int
host_allowed(const char *host) {
size_t hlen = strlen(host);
/* DNS is case-insensitive; an upstream redirect to "SGST.prod..." would
otherwise drop out of the allowlist. */
for (int i = 0; ALLOWED_HOSTS[i]; i++) {
if (!strcmp(host, ALLOWED_HOSTS[i]))
if (!strcasecmp(host, ALLOWED_HOSTS[i]))
return 1;
size_t alen = strlen(ALLOWED_HOSTS[i]);
if (hlen > alen + 1 &&
host[hlen - alen - 1] == '.' &&
!strcmp(host + hlen - alen, ALLOWED_HOSTS[i]))
!strcasecmp(host + hlen - alen, ALLOWED_HOSTS[i]))
return 1;
}
return 0;
}
/* Extract hostname from https://host/path or http://host/path */
/* Manifest piece hashes: PS5 manifests carry SHA-256 (64 hex digits), PS4
manifests SHA-1 (40). */
static const EVP_MD *
digest_for(const char *hex) {
return (hex && strlen(hex) == 40) ? EVP_sha1() : EVP_sha256();
}
static int
url_host(const char *url, char *out, size_t out_sz) {
const char *p = strstr(url, "://");
@@ -145,6 +199,10 @@ dns_resolve(const char *host, char *ip_out, size_t ip_sz) {
while (pos < (size_t)n) {
if (!resp[pos]) { pos++; break; }
if ((resp[pos] & 0xC0) == 0xC0) { pos += 2; break; }
/* Bounds-check the label length BEFORE the increment — a malformed
response with a 0xFF label byte near the end would otherwise walk
past `n`. */
if (pos + 1 + (size_t)resp[pos] >= (size_t)n) { g_dns_step = 5; return -1; }
pos += 1 + resp[pos];
}
if (pos + 4 > (size_t)n) { g_dns_step = 5; return -1; }
@@ -156,8 +214,10 @@ dns_resolve(const char *host, char *ip_out, size_t ip_sz) {
if ((resp[pos] & 0xC0) == 0xC0) {
pos += 2;
} else {
while (pos < (size_t)n && resp[pos])
while (pos < (size_t)n && resp[pos]) {
if (pos + 1 + (size_t)resp[pos] >= (size_t)n) break;
pos += 1 + resp[pos];
}
pos++;
}
if (pos + 10 > (size_t)n) break;
@@ -222,7 +282,12 @@ static size_t
write_cb(void *ptr, size_t size, size_t nmemb, void *userdata) {
patchdl_buf_t *b = userdata;
size_t total = size * nmemb;
char *newp = realloc(b->data, b->size + total + 1);
char *newp;
/* Overflow guard before the cap check (b->size+total may wrap on 32-bit). */
if (total > (size_t)-1 - b->size - 1) return 0;
/* Cap accumulation so a hostile CDN can't drive unbounded RAM growth. */
if (b->max && b->size + total > b->max) return 0;
newp = realloc(b->data, b->size + total + 1);
if (!newp) return 0;
b->data = newp;
memcpy(b->data + b->size, ptr, total);
@@ -240,8 +305,11 @@ patchdl_http_get(const char *url, patchdl_buf_t *out) {
struct curl_slist *resolve_list = NULL;
struct curl_blob ca_blob;
int plain = !strncmp(url, "http://", 7);
if (url_host(url, host, sizeof(host))) return -1;
if (!host_allowed(host)) return -1;
if (plain && strcasecmp(host, PLAIN_HTTP_HOST)) return -1;
if (dns_lookup(host, ip, sizeof(ip))) return -1;
snprintf(resolve_str, sizeof(resolve_str), "%s:443:%s", host, ip);
@@ -252,7 +320,11 @@ patchdl_http_get(const char *url, patchdl_buf_t *out) {
snprintf(resolve_80, sizeof(resolve_80), "%s:80:%s", host, ip);
resolve_list = curl_slist_append(resolve_list, resolve_80);
memset(out, 0, sizeof(*out));
{
size_t caller_max = out->max;
memset(out, 0, sizeof(*out));
out->max = caller_max;
}
curl = curl_easy_init();
if (!curl) { curl_slist_free_all(resolve_list); return -1; }
@@ -277,6 +349,13 @@ patchdl_http_get(const char *url, patchdl_buf_t *out) {
curl_easy_setopt(curl, CURLOPT_TIMEOUT, 15L);
curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);
curl_easy_setopt(curl, CURLOPT_MAXREDIRS, 3L);
/* Redirects must stay on HTTPS — host_allowed gates the initial URL, but
once libcurl follows a 302 we want the protocol pinned too. The _STR
variants replaced the bitfield options in libcurl 7.85. Plain http only
for the PS4 manifest host (see PLAIN_HTTP_HOST). */
curl_easy_setopt(curl, CURLOPT_PROTOCOLS_STR, plain ? "http" : "https");
curl_easy_setopt(curl, CURLOPT_REDIR_PROTOCOLS_STR, "https");
curl_easy_setopt(curl, CURLOPT_NOSIGNAL, 1L);
curl_easy_setopt(curl, CURLOPT_USERAGENT, "patchdl/1.0");
res = curl_easy_perform(curl);
@@ -292,6 +371,90 @@ patchdl_http_get(const char *url, patchdl_buf_t *out) {
return 0;
}
/* ---------- external-host HTTP (no Sony CA, no allowlist) -------------- */
static int
http_external(const char *url, const char *method,
const char *content_type, const char *body,
patchdl_buf_t *out) {
#ifndef PATCHDL_HAVE_CURL
(void)url; (void)method; (void)content_type; (void)body; (void)out;
return -1;
#else
CURL *curl;
CURLcode res;
char host[256], ip[INET_ADDRSTRLEN];
char resolve_str[512];
struct curl_slist *resolve_list = NULL;
struct curl_slist *headers = NULL;
if (url_host(url, host, sizeof(host))) return -1;
if (dns_lookup(host, ip, sizeof(ip))) return -1;
snprintf(resolve_str, sizeof(resolve_str), "%s:443:%s", host, ip);
resolve_list = curl_slist_append(NULL, resolve_str);
{
size_t caller_max = out->max;
memset(out, 0, sizeof(*out));
out->max = caller_max;
}
curl = curl_easy_init();
if (!curl) { curl_slist_free_all(resolve_list); return -1; }
curl_easy_setopt(curl, CURLOPT_URL, url);
curl_easy_setopt(curl, CURLOPT_RESOLVE, resolve_list);
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_cb);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, out);
curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0L);
curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 0L);
curl_easy_setopt(curl, CURLOPT_TIMEOUT, 10L);
curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);
curl_easy_setopt(curl, CURLOPT_MAXREDIRS, 3L);
curl_easy_setopt(curl, CURLOPT_PROTOCOLS_STR, "https");
curl_easy_setopt(curl, CURLOPT_REDIR_PROTOCOLS_STR, "https");
curl_easy_setopt(curl, CURLOPT_NOSIGNAL, 1L);
curl_easy_setopt(curl, CURLOPT_USERAGENT,
"Mozilla/5.0 (PlayStation; PatchDL)");
if (body) {
if (content_type) {
char ct[256];
snprintf(ct, sizeof(ct), "Content-Type: %s", content_type);
headers = curl_slist_append(headers, ct);
}
headers = curl_slist_append(headers, "Accept: application/json");
curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, body);
}
res = curl_easy_perform(curl);
curl_easy_cleanup(curl);
curl_slist_free_all(resolve_list);
curl_slist_free_all(headers);
if (res != CURLE_OK) {
free(out->data);
out->data = NULL;
out->size = 0;
return -1;
}
return 0;
#endif
}
int
patchdl_http_get_external(const char *url, patchdl_buf_t *out) {
return http_external(url, "GET", NULL, NULL, out);
}
int
patchdl_http_post_external(const char *url, const char *content_type,
const char *body, patchdl_buf_t *out) {
return http_external(url, "POST", content_type, body, out);
}
/* Write sink: tees the body to the file and, when verifying, into a running
SHA-256. curl always calls with size==1, so nmemb is the byte count. */
typedef struct {
@@ -372,7 +535,7 @@ http_download_to_file_progress(const char *url, FILE *fp, long long *bytes_out,
if (verify) {
sink.md = EVP_MD_CTX_new();
if (sink.md)
EVP_DigestInit_ex(sink.md, EVP_sha256(), NULL);
EVP_DigestInit_ex(sink.md, digest_for(expected_sha256_hex), NULL);
}
snprintf(rs443, sizeof(rs443), "%s:443:%s", host, ip);
@@ -401,6 +564,13 @@ http_download_to_file_progress(const char *url, FILE *fp, long long *bytes_out,
curl_easy_setopt(curl, CURLOPT_SSL_CIPHER_LIST, "DEFAULT@SECLEVEL=0");
curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);
curl_easy_setopt(curl, CURLOPT_MAXREDIRS, 5L);
/* HTTPS pin removed on the streaming download path: the Sony CDN sometimes
302s a piece URL to a signed http:// edge inside its own infrastructure,
and refusing those redirects was breaking real-world downloads.
host_allowed + TLS-against-pinned-root on every leg already gate the
hosts we'll talk to. NOSIGNAL stays — it protects the worker from a
SIGPIPE on connection RST. */
curl_easy_setopt(curl, CURLOPT_NOSIGNAL, 1L);
curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT, 20L);
/* No total timeout (patches can be large); abort only on a long stall. */
curl_easy_setopt(curl, CURLOPT_LOW_SPEED_LIMIT, 1024L);
@@ -437,8 +607,11 @@ http_download_to_file_progress(const char *url, FILE *fp, long long *bytes_out,
unsigned char dig[EVP_MAX_MD_SIZE];
unsigned int dlen = 0;
char hex[2 * EVP_MAX_MD_SIZE + 1];
EVP_DigestFinal_ex(sink.md, dig, &dlen);
int ok = EVP_DigestFinal_ex(sink.md, dig, &dlen);
EVP_MD_CTX_free(sink.md);
/* Fail-closed on a digest API failure — otherwise hex would be empty
and we'd silently report -2 with no diagnostic. */
if (ok != 1 || dlen == 0) return -2;
hex_encode(dig, dlen, hex, sizeof(hex));
if (strcasecmp(hex, expected_sha256_hex) != 0)
return -2; /* integrity mismatch */
@@ -452,7 +625,7 @@ int
patchdl_http_download_progress(const char *url, const char *dest_path,
long long *bytes_out,
patchdl_download_progress_cb cb, void *ctx) {
FILE *fp = fopen(dest_path, "wb");
FILE *fp = fopen_safe(dest_path, 0);
progress_state_t progress = { cb, ctx, 0, 0 };
int rc;
@@ -473,8 +646,24 @@ patchdl_http_download(const char *url, const char *dest_path,
return patchdl_http_download_progress(url, dest_path, bytes_out, NULL, NULL);
}
/* Substring scan bounded to [p, limit). NULL limit means search to NUL.
Returns NULL if needle is not found before limit. */
static const char *
strstr_bounded(const char *p, const char *needle, const char *limit) {
const char *hit = strstr(p, needle);
if (!hit) return NULL;
if (limit && hit >= limit) return NULL;
return hit;
}
/* Read "key": "value" starting from p. Search and read are bounded by `limit`
(pass NULL to search to end of buffer). Decodes \\ \" \/ \n \r \t \b \f; any
other \X is copied without the backslash. \uXXXX is left as the raw 6 bytes
(we don't need Unicode for manifest fields). limit==NULL keeps legacy
end-of-string scope for callers that don't need the cap. */
static int
json_string_after(const char *p, const char *key, char *out, size_t out_sz) {
json_string_after(const char *p, const char *key, char *out, size_t out_sz,
const char *limit) {
char needle[48];
const char *q;
size_t n = 0;
@@ -482,35 +671,59 @@ json_string_after(const char *p, const char *key, char *out, size_t out_sz) {
if (!p || !out || out_sz == 0) return -1;
out[0] = '\0';
snprintf(needle, sizeof(needle), "\"%s\"", key);
q = strstr(p, needle);
q = strstr_bounded(p, needle, limit);
if (!q) return -1;
q += strlen(needle);
while (*q == ' ' || *q == '\t' || *q == '\r' || *q == '\n') q++;
while ((!limit || q < limit) &&
(*q == ' ' || *q == '\t' || *q == '\r' || *q == '\n')) q++;
if (limit && q >= limit) return -1;
if (*q++ != ':') return -1;
while (*q == ' ' || *q == '\t' || *q == '\r' || *q == '\n') q++;
while ((!limit || q < limit) &&
(*q == ' ' || *q == '\t' || *q == '\r' || *q == '\n')) q++;
if (limit && q >= limit) return -1;
if (*q++ != '"') return -1;
while (*q && *q != '"' && n + 1 < out_sz) {
if (*q == '\\' && q[1]) q++;
out[n++] = *q++;
while ((!limit || q < limit) && *q && *q != '"' && n + 1 < out_sz) {
if (*q == '\\' && q[1] && (!limit || q + 1 < limit)) {
q++;
switch (*q) {
case '"': out[n++] = '"'; break;
case '\\': out[n++] = '\\'; break;
case '/': out[n++] = '/'; break;
case 'n': out[n++] = '\n'; break;
case 'r': out[n++] = '\r'; break;
case 't': out[n++] = '\t'; break;
case 'b': out[n++] = '\b'; break;
case 'f': out[n++] = '\f'; break;
default: out[n++] = *q; break; /* unknown escape: keep payload */
}
q++;
} else {
out[n++] = *q++;
}
}
out[n] = '\0';
return n ? 0 : -1;
}
static int
json_u64_after(const char *p, const char *key, unsigned long long *out) {
json_u64_after(const char *p, const char *key, unsigned long long *out,
const char *limit) {
char needle[48];
const char *q;
if (!p || !out) return -1;
snprintf(needle, sizeof(needle), "\"%s\"", key);
q = strstr(p, needle);
q = strstr_bounded(p, needle, limit);
if (!q) return -1;
q += strlen(needle);
while (*q == ' ' || *q == '\t' || *q == '\r' || *q == '\n') q++;
while ((!limit || q < limit) &&
(*q == ' ' || *q == '\t' || *q == '\r' || *q == '\n')) q++;
if (limit && q >= limit) return -1;
if (*q++ != ':') return -1;
while (*q == ' ' || *q == '\t' || *q == '\r' || *q == '\n') q++;
while ((!limit || q < limit) &&
(*q == ' ' || *q == '\t' || *q == '\r' || *q == '\n')) q++;
if (limit && q >= limit) return -1;
if (*q < '0' || *q > '9') return -1;
*out = strtoull(q, NULL, 10);
return 0;
@@ -530,6 +743,8 @@ patchdl_http_download_manifest_progress(const char *manifest_url,
int count = 0, started, rc = -1;
if (bytes_out) *bytes_out = 0;
memset(&manifest, 0, sizeof(manifest));
manifest.max = PATCHDL_BUF_MAX_MANIFEST;
if (patchdl_http_get(manifest_url, &manifest))
return -1;
if (!manifest.data || !manifest.size) {
@@ -545,17 +760,17 @@ patchdl_http_download_manifest_progress(const char *manifest_url,
/* Bound the scan to the pieces array; otherwise a later "url" key in the
manifest (e.g. playgoChunkCrcUrl) could be appended as a bogus piece. */
pieces_end = strchr(pieces, ']');
json_u64_after(manifest.data, "originalFileSize", &manifest_total);
json_u64_after(manifest.data, "originalFileSize", &manifest_total, NULL);
/* Resume: reopen the existing partial and keep its bytes; else start clean.
Fully-downloaded pieces are skipped; the one piece that was only partially
written continues mid-piece via an HTTP byte range (with a fall back to
re-fetching it whole if the CDN ignores the range). */
if (resume) {
fp = fopen(dest_path, "r+b");
fp = fopen_safe(dest_path, 1);
if (fp) { fseek(fp, 0, SEEK_END); have = ftell(fp); if (have < 0) have = 0; }
}
if (!fp) { fp = fopen(dest_path, "wb"); have = 0; }
if (!fp) { fp = fopen_safe(dest_path, 0); have = 0; }
if (!fp) { free(manifest.data); return -1; }
started = (have <= 0);
@@ -569,11 +784,13 @@ patchdl_http_download_manifest_progress(const char *manifest_url,
int have_offset, drc;
const char *want_hash;
const char *obj_end = strchr(p, '}');
const char *piece_limit = (obj_end && (!pieces_end || obj_end < pieces_end))
? obj_end : pieces_end;
if (json_string_after(p, "url", url, sizeof(url)))
if (json_string_after(p, "url", url, sizeof(url), piece_limit))
break;
json_u64_after(p, "fileSize", &expected);
have_offset = (json_u64_after(p, "fileOffset", &offset) == 0);
json_u64_after(p, "fileSize", &expected, piece_limit);
have_offset = (json_u64_after(p, "fileOffset", &offset, piece_limit) == 0);
/* Piece already fully present from a previous run: skip the download. */
if (!started && have_offset && expected &&
@@ -614,7 +831,7 @@ patchdl_http_download_manifest_progress(const char *manifest_url,
/* A ranged piece can't be hashed (only its tail is fetched). */
want_hash = NULL;
if (range_start == 0 && verify) {
json_string_after(p, "hashValue", hash, sizeof(hash));
json_string_after(p, "hashValue", hash, sizeof(hash), piece_limit);
want_hash = hash[0] ? hash : NULL;
}
@@ -634,7 +851,8 @@ patchdl_http_download_manifest_progress(const char *manifest_url,
total = (long long)offset;
range_start = 0;
if (verify) {
json_string_after(p, "hashValue", hash, sizeof(hash));
json_string_after(p, "hashValue", hash, sizeof(hash),
piece_limit);
want_hash = hash[0] ? hash : NULL;
}
progress.base = total;
@@ -720,7 +938,8 @@ int
patchdl_http_download_piece(const char *url, int fd,
long long file_offset, long long file_size,
const char *expected_sha256_or_null,
patchdl_piece_ctx_t *ctx) {
patchdl_piece_ctx_t *ctx,
int *curl_rc_out, long *http_code_out) {
CURL *curl;
CURLcode res;
long http_code = 0;
@@ -730,6 +949,9 @@ patchdl_http_download_piece(const char *url, int fd,
piece_sink_t sink;
int verify = (expected_sha256_or_null && expected_sha256_or_null[0]);
if (curl_rc_out) *curl_rc_out = 0;
if (http_code_out) *http_code_out = 0;
if (url_host(url, host, sizeof(host))) return -1;
if (!host_allowed(host)) return -1;
if (dns_lookup(host, ip, sizeof(ip))) return -1;
@@ -740,7 +962,7 @@ patchdl_http_download_piece(const char *url, int fd,
sink.bytes_slot = ctx ? ctx->bytes_slot : NULL;
if (verify) {
sink.md = EVP_MD_CTX_new();
if (sink.md) EVP_DigestInit_ex(sink.md, EVP_sha256(), NULL);
if (sink.md) EVP_DigestInit_ex(sink.md, digest_for(expected_sha256_or_null), NULL);
}
snprintf(rs443, sizeof(rs443), "%s:443:%s", host, ip);
@@ -769,6 +991,9 @@ patchdl_http_download_piece(const char *url, int fd,
curl_easy_setopt(curl, CURLOPT_SSL_CIPHER_LIST, "DEFAULT@SECLEVEL=0");
curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);
curl_easy_setopt(curl, CURLOPT_MAXREDIRS, 5L);
/* HTTPS pin removed on the streaming piece path — see the same change in
http_download_to_file_progress for the why. */
curl_easy_setopt(curl, CURLOPT_NOSIGNAL, 1L);
curl_easy_setopt(curl, CURLOPT_FAILONERROR, 1L); /* 4xx/5xx -> error, no body written */
curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT, 20L);
curl_easy_setopt(curl, CURLOPT_LOW_SPEED_LIMIT, 1024L);
@@ -785,6 +1010,9 @@ patchdl_http_download_piece(const char *url, int fd,
curl_easy_cleanup(curl);
curl_slist_free_all(rl);
if (curl_rc_out) *curl_rc_out = (int)res;
if (http_code_out) *http_code_out = http_code;
if (res != CURLE_OK) {
if (sink.md) EVP_MD_CTX_free(sink.md);
return -1; /* network error / abort */
@@ -797,8 +1025,9 @@ patchdl_http_download_piece(const char *url, int fd,
unsigned char dig[EVP_MAX_MD_SIZE];
unsigned int dl = 0;
char hex[2 * EVP_MAX_MD_SIZE + 1];
EVP_DigestFinal_ex(sink.md, dig, &dl);
int ok = EVP_DigestFinal_ex(sink.md, dig, &dl);
EVP_MD_CTX_free(sink.md);
if (ok != 1 || dl == 0) return -2;
hex_encode(dig, dl, hex, sizeof(hex));
if (strcasecmp(hex, expected_sha256_or_null) != 0)
return -2; /* integrity mismatch */
@@ -807,10 +1036,12 @@ patchdl_http_download_piece(const char *url, int fd,
return 0;
}
/* Read-only: SHA-256 a [offset, offset+size) region of fd into out_hex (>=65
bytes). Uses pread so it doesn't disturb the fd offset. 0 on success. */
/* Read-only: hash a [offset, offset+size) region of fd into out_hex (>=65
bytes), with the algorithm `like_hex` is written in (see digest_for). Uses
pread so it doesn't disturb the fd offset. 0 on success. */
int
patchdl_sha256_fd_region(int fd, long long offset, long long size, char *out_hex) {
patchdl_hash_fd_region(int fd, long long offset, long long size,
const char *like_hex, char *out_hex) {
EVP_MD_CTX *md;
unsigned char *buf;
long long pos = offset, remaining = size;
@@ -822,7 +1053,7 @@ patchdl_sha256_fd_region(int fd, long long offset, long long size, char *out_hex
if (!md) return -1;
buf = malloc(CHUNK);
if (!buf) { EVP_MD_CTX_free(md); return -1; }
EVP_DigestInit_ex(md, EVP_sha256(), NULL);
EVP_DigestInit_ex(md, digest_for(like_hex), NULL);
while (remaining > 0) {
size_t want = remaining > (long long)CHUNK ? CHUNK : (size_t)remaining;
ssize_t got = pread(fd, buf, want, (off_t)pos);
@@ -833,8 +1064,9 @@ patchdl_sha256_fd_region(int fd, long long offset, long long size, char *out_hex
{
unsigned char dig[EVP_MAX_MD_SIZE];
unsigned int dl = 0, i;
EVP_DigestFinal_ex(md, dig, &dl);
for (i = 0; i < dl; i++) sprintf(out_hex + 2 * i, "%02x", dig[i]);
int ok = EVP_DigestFinal_ex(md, dig, &dl);
if (ok != 1 || dl == 0) { free(buf); EVP_MD_CTX_free(md); return -1; }
for (i = 0; i < dl; i++) snprintf(out_hex + 2 * i, 3, "%02x", dig[i]);
out_hex[2 * dl] = '\0';
}
free(buf);
@@ -859,6 +1091,8 @@ patchdl_fetch_manifest(const char *manifest_url, patchdl_manifest_t *out) {
long long running = 0;
memset(out, 0, sizeof(*out));
memset(&buf, 0, sizeof(buf));
buf.max = PATCHDL_BUF_MAX_MANIFEST;
if (patchdl_http_get(manifest_url, &buf)) return -1;
if (!buf.data || !buf.size) { free(buf.data); return -1; }
@@ -872,20 +1106,33 @@ patchdl_fetch_manifest(const char *manifest_url, patchdl_manifest_t *out) {
out->pieces = calloc((size_t)cap, sizeof(patchdl_piece_t));
if (!out->pieces) { free(buf.data); return -1; }
/* Sanity caps: refuse a manifest that would let a CDN drive multi-TB
allocations or millions of pieces. The biggest real PS5 patch we've
seen is ~70 GB / 18 pieces; these limits leave room to spare. */
if (cap > PATCHDL_MAX_PIECES) { free(buf.data); return -1; }
p = pieces;
while ((p = strstr(p, "\"url\"")) && (!pieces_end || p < pieces_end) && n < cap) {
char url[768] = {0};
unsigned long long sz = 0, off = 0;
const char *obj_end = strchr(p, '}');
const char *piece_limit = (obj_end && (!pieces_end || obj_end < pieces_end))
? obj_end : pieces_end;
if (json_string_after(p, "url", url, sizeof(url)))
if (json_string_after(p, "url", url, sizeof(url), piece_limit))
break;
json_u64_after(p, "fileSize", &sz);
if (json_u64_after(p, "fileOffset", &off) != 0)
json_u64_after(p, "fileSize", &sz, piece_limit);
if (json_u64_after(p, "fileOffset", &off, piece_limit) != 0)
off = (unsigned long long)running; /* no offset -> assume contiguous */
/* Validate tiling: pieces must be in order, contiguous, non-empty. */
if ((long long)off != running || sz == 0) {
/* Validate tiling: pieces must be in order, contiguous, non-empty,
and each individually under the per-piece cap. */
if ((long long)off != running || sz == 0 || sz > PATCHDL_MAX_PIECE_BYTES) {
patchdl_manifest_free(out);
free(buf.data);
return -1;
}
if ((unsigned long long)running + sz > PATCHDL_MAX_TOTAL_BYTES) {
patchdl_manifest_free(out);
free(buf.data);
return -1;
@@ -894,7 +1141,7 @@ patchdl_fetch_manifest(const char *manifest_url, patchdl_manifest_t *out) {
out->pieces[n].offset = (long long)off;
out->pieces[n].size = (long long)sz;
json_string_after(p, "hashValue", out->pieces[n].hash,
sizeof(out->pieces[n].hash));
sizeof(out->pieces[n].hash), piece_limit);
if (!out->pieces[n].url) {
patchdl_manifest_free(out);
free(buf.data);
@@ -905,6 +1152,8 @@ patchdl_fetch_manifest(const char *manifest_url, patchdl_manifest_t *out) {
out->count = n; /* keep current so manifest_free frees exactly n */
p = obj_end ? obj_end + 1 : p + 5;
}
json_string_after(buf.data, "playgoChunkCrcUrl", out->crc_url,
sizeof(out->crc_url), NULL);
free(buf.data);
if (n == 0) { patchdl_manifest_free(out); return -1; }
out->total = running; /* authoritative assembled size */
@@ -944,6 +1193,9 @@ patchdl_net_diag(const char *url, char *out_json, size_t sz) {
curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 1L);
curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 2L);
curl_easy_setopt(curl, CURLOPT_SSL_CIPHER_LIST, "DEFAULT@SECLEVEL=0");
curl_easy_setopt(curl, CURLOPT_PROTOCOLS_STR, "https");
curl_easy_setopt(curl, CURLOPT_REDIR_PROTOCOLS_STR, "https");
curl_easy_setopt(curl, CURLOPT_NOSIGNAL, 1L);
curl_easy_setopt(curl, CURLOPT_TIMEOUT, 15L);
res = curl_easy_perform(curl);
curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &http_code);
+30 -7
View File
@@ -1,3 +1,12 @@
/* SPDX-License-Identifier: GPL-3.0-or-later
* Copyright (C) 2026 Knutwurst
*
* PatchDL is free software: you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free
* Software Foundation, either version 3 of the License, or (at your option)
* any later version. See the LICENSE file in the project root for details.
*/
#pragma once
#include <stddef.h>
@@ -6,6 +15,7 @@ typedef struct {
char *data;
size_t size;
size_t cap;
size_t max; /* 0 = unbounded (legacy). Otherwise write_cb fails past this. */
} patchdl_buf_t;
patchdl_buf_t *patchdl_buf_new(void);
@@ -19,6 +29,13 @@ void patchdl_net_global_cleanup(void);
int patchdl_http_get(const char *url, patchdl_buf_t *out);
/* External-host variants: no Sony CA pinning, no Sony host allowlist.
SSL peer verification is disabled (PS5 has no system CA store; these
are used for public metadata only, never for sensitive data). */
int patchdl_http_get_external(const char *url, patchdl_buf_t *out);
int patchdl_http_post_external(const char *url, const char *content_type,
const char *body, patchdl_buf_t *out);
/* ---- parallel piece download (used by the connection pool) ------------- */
/* One piece of a split manifest package. `url` is heap-allocated. */
@@ -26,13 +43,14 @@ typedef struct {
char *url;
long long offset; /* byte offset of this piece in the assembled file */
long long size; /* exact length of this piece */
char hash[80]; /* manifest SHA-256 hex, or "" */
char hash[80]; /* manifest hash hex (SHA-256, or SHA-1 for PS4), or "" */
} patchdl_piece_t;
typedef struct {
patchdl_piece_t *pieces;
int count;
long long total; /* assembled file size = sum of piece sizes */
char crc_url[768]; /* playgoChunkCrcUrl, or "" */
} patchdl_manifest_t;
/* Fetch + parse a Sony JSON manifest into a validated, contiguously-tiled
@@ -41,6 +59,7 @@ typedef struct {
int patchdl_fetch_manifest(const char *manifest_url, patchdl_manifest_t *out);
void patchdl_manifest_free(patchdl_manifest_t *m);
/* Live state shared with one in-flight piece download. The worker owns these;
the curl callbacks read `abort` (set elsewhere) and publish progress into
`bytes_slot` (single-writer per worker slot). */
@@ -51,16 +70,20 @@ typedef struct {
/* Download one whole piece and pwrite it into `fd` at `file_offset`. Concurrent
non-overlapping pieces of the same fd are safe. Returns 0 on success (and
fdatasyncs fd), -1 on network/IO/abort, -2 on a SHA-256 mismatch. */
fdatasyncs fd), -1 on network/IO/abort, -2 on a SHA-256 mismatch.
`curl_rc_out`/`http_code_out` (either may be NULL) receive the last libcurl
CURLcode + HTTP status for failure diagnosis. */
int patchdl_http_download_piece(const char *url, int fd,
long long file_offset, long long file_size,
const char *expected_sha256_or_null,
patchdl_piece_ctx_t *ctx);
patchdl_piece_ctx_t *ctx,
int *curl_rc_out, long *http_code_out);
/* Read-only: SHA-256 a [offset, offset+size) region of fd into out_hex
(caller provides >= 65 bytes). Returns 0 on success. */
int patchdl_sha256_fd_region(int fd, long long offset, long long size,
char *out_hex);
/* Read-only: hash a [offset, offset+size) region of fd into out_hex
(caller provides >= 65 bytes), SHA-1 if like_hex has 40 hex digits (PS4
manifests), else SHA-256. Returns 0 on success. */
int patchdl_hash_fd_region(int fd, long long offset, long long size,
const char *like_hex, char *out_hex);
/* Progress callback. Return non-zero to ABORT the in-flight download (used to
cancel large patch downloads); return 0 to continue. */
+9
View File
@@ -1,3 +1,12 @@
/* SPDX-License-Identifier: GPL-3.0-or-later
* Copyright (C) 2026 Knutwurst
*
* PatchDL is free software: you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free
* Software Foundation, either version 3 of the License, or (at your option)
* any later version. See the LICENSE file in the project root for details.
*/
#include "patchdl_notify.h"
#include "patchdl_version.h"
+9
View File
@@ -1,3 +1,12 @@
/* SPDX-License-Identifier: GPL-3.0-or-later
* Copyright (C) 2026 Knutwurst
*
* PatchDL is free software: you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free
* Software Foundation, either version 3 of the License, or (at your option)
* any later version. See the LICENSE file in the project root for details.
*/
#pragma once
/* Send an on-screen PS5 notification at startup showing the web UI URL
+13 -1
View File
@@ -1,3 +1,12 @@
/* SPDX-License-Identifier: GPL-3.0-or-later
* Copyright (C) 2026 Knutwurst
*
* PatchDL is free software: you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free
* Software Foundation, either version 3 of the License, or (at your option)
* any later version. See the LICENSE file in the project root for details.
*/
#include "patchdl_proc.h"
#include <signal.h>
@@ -65,7 +74,10 @@ patchdl_proc_kill_others(const char *name) {
int killed = 0;
pid_t pid;
while ((pid = find_pid(name)) > 0) {
/* Bound the loop: at startup we expect 0-1 stale instance. A pathological
proc table (or kill returning success but the process not exiting) would
otherwise stall startup for sleep(1) × N. */
while (killed < 8 && (pid = find_pid(name)) > 0) {
if (kill(pid, SIGKILL))
break;
killed++;
+9
View File
@@ -1,3 +1,12 @@
/* SPDX-License-Identifier: GPL-3.0-or-later
* Copyright (C) 2026 Knutwurst
*
* PatchDL is free software: you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free
* Software Foundation, either version 3 of the License, or (at your option)
* any later version. See the LICENSE file in the project root for details.
*/
#pragma once
/* Set this process's (main thread) name as shown in the PS5 process list. */
+157
View File
@@ -0,0 +1,157 @@
/* SPDX-License-Identifier: GPL-3.0-or-later
* Copyright (C) 2026 Knutwurst
*
* PatchDL is free software: you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free
* Software Foundation, either version 3 of the License, or (at your option)
* any later version. See the LICENSE file in the project root for details.
*/
#include "patchdl_prospero.h"
#include "patchdl_net.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define PROSPERO_BASE "https://prosperopatches.com"
#define PROSPERO_API PROSPERO_BASE "/api/internal"
#define BUF_MAX (512 * 1024)
/* Prospero firmware strings use the same hex-digits-as-decimal encoding
as Sony's system_ver: "10.20.00.06" packs to 0x10200006. Parse with
%x so the hex bytes compare correctly against g_fw.bin. */
static uint32_t
fw_str_to_bin(const char *s) {
unsigned a = 0, b = 0, c = 0, d = 0;
sscanf(s, "%x.%x.%x.%x", &a, &b, &c, &d);
return (a << 24) | (b << 16) | (c << 8) | d;
}
static void
fw_bin_to_display(uint32_t bin, char *out, size_t sz) {
snprintf(out, sz, "%x.%02x", (bin >> 24) & 0xff, (bin >> 16) & 0xff);
}
/* Extract the first occurrence of `data-key="<hex>"` from HTML. */
static int
extract_data_key(const char *html, char *out, size_t out_sz) {
const char *needle = "data-key=\"";
const char *p = strstr(html, needle);
if (!p) return -1;
p += strlen(needle);
size_t len = 0;
while (p[len] && p[len] != '"' && len < out_sz - 1)
len++;
if (!len || p[len] != '"') return -1;
memcpy(out, p, len);
out[len] = '\0';
return 0;
}
/* Find the next JSON string value for a given key inside a JSON object
fragment. Crude but sufficient for the predictable Prospero response. */
static const char *
json_str_val(const char *json, const char *key, char *out, size_t out_sz) {
char needle[64];
snprintf(needle, sizeof(needle), "\"%s\"", key);
const char *p = strstr(json, needle);
if (!p) return NULL;
p += strlen(needle);
while (*p == ' ' || *p == ':') p++;
if (*p != '"') return NULL;
p++;
size_t len = 0;
while (p[len] && p[len] != '"' && len < out_sz - 1)
len++;
memcpy(out, p, len);
out[len] = '\0';
return p + len + 1;
}
/* Check if a JSON fragment contains "success":true */
static int
json_success(const char *json) {
const char *p = strstr(json, "\"success\"");
if (!p) return 0;
p += 9;
while (*p == ' ' || *p == ':') p++;
return !strncmp(p, "true", 4);
}
int
patchdl_prospero_query(const char *title_id, uint32_t fw_bin,
patchdl_prospero_result_t *out) {
patchdl_buf_t buf;
char url[256], key[128], body[256];
char best_ver[16] = {0}, best_size[16] = {0};
uint32_t best_fw = 0;
if (!title_id || !out) return -1;
memset(out, 0, sizeof(*out));
/* Step 1: fetch the title page to get the data-key. */
memset(&buf, 0, sizeof(buf));
buf.max = BUF_MAX;
snprintf(url, sizeof(url), "%s/%.16s", PROSPERO_BASE, title_id);
if (patchdl_http_get_external(url, &buf)) return -1;
if (!buf.data) return -1;
if (extract_data_key(buf.data, key, sizeof(key))) {
free(buf.data);
return -1;
}
free(buf.data);
/* Step 2: POST loadpatches. The API expects JSON in the body but
application/x-www-form-urlencoded as Content-Type — this is how
the website and every known third-party client calls it. */
snprintf(body, sizeof(body),
"{\"titleid\":\"%.16s\",\"key\":\"%s\"}", title_id, key);
memset(&buf, 0, sizeof(buf));
buf.max = BUF_MAX;
if (patchdl_http_post_external(
PROSPERO_API "/loadpatches",
"application/x-www-form-urlencoded; charset=UTF-8",
body, &buf)) return -1;
if (!buf.data) return -1;
if (!json_success(buf.data)) {
free(buf.data);
return -1;
}
/* Walk the patches array. Each entry looks like:
{"content_ver":"01.003.000","required_firmware":"07.01.01.00",...}
Find the newest version whose firmware requirement is met. */
const char *cursor = buf.data;
while ((cursor = strstr(cursor, "\"content_ver\""))) {
char ver[16] = {0}, fw[32] = {0}, size[16] = {0};
json_str_val(cursor, "content_ver", ver, sizeof(ver));
json_str_val(cursor, "filesize", size, sizeof(size));
json_str_val(cursor, "required_firmware", fw, sizeof(fw));
if (ver[0] && fw[0]) {
uint32_t pkg_fw = fw_str_to_bin(fw);
if (pkg_fw <= fw_bin) {
if (!best_ver[0] || strcmp(ver, best_ver) > 0) {
strncpy(best_ver, ver, sizeof(best_ver) - 1);
memcpy(best_size, size, sizeof(best_size));
best_fw = pkg_fw;
}
}
}
cursor++;
}
free(buf.data);
if (best_ver[0]) {
strncpy(out->version, best_ver, sizeof(out->version) - 1);
fw_bin_to_display(best_fw, out->required_fw, sizeof(out->required_fw));
memcpy(out->size, best_size, sizeof(out->size));
out->found = 1;
}
return 0;
}
+27
View File
@@ -0,0 +1,27 @@
/* SPDX-License-Identifier: GPL-3.0-or-later
* Copyright (C) 2026 Knutwurst
*
* PatchDL is free software: you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free
* Software Foundation, either version 3 of the License, or (at your option)
* any later version. See the LICENSE file in the project root for details.
*/
#pragma once
#include <stdint.h>
typedef struct {
char version[16]; /* e.g. "01.003.000" */
char required_fw[16]; /* PatchDL display format, e.g. "7.01" */
char size[16]; /* Prospero's label, e.g. "71.7 GB" (GiB, rounded up) */
int found;
} patchdl_prospero_result_t;
/* Query prosperopatches.com for the newest patch of `title_id` whose
firmware requirement is <= fw_bin. Returns 0 on success (result may
still have found==0 if no compatible patch exists), -1 on network or
parse failure. Best-effort: a failure means the UI shows no Prospero
data, nothing breaks. */
int patchdl_prospero_query(const char *title_id, uint32_t fw_bin,
patchdl_prospero_result_t *out);
+49 -11
View File
@@ -1,5 +1,15 @@
/* SPDX-License-Identifier: GPL-3.0-or-later
* Copyright (C) 2026 Knutwurst
*
* PatchDL is free software: you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free
* Software Foundation, either version 3 of the License, or (at your option)
* any later version. See the LICENSE file in the project root for details.
*/
#include "patchdl_resolve.h"
#include <openssl/hmac.h>
#include <stdio.h>
#include <string.h>
@@ -27,6 +37,14 @@ lookup_tsv(const char *title_id, char *url_out, size_t url_sz) {
fclose(fp);
return -1;
}
/* Defense in depth: the TSV file lives under /data/patchdl, writable
by anyone with /data access. patchdl_http_get also enforces
host_allowed, but rejecting non-https / non-Sony schemes here means
a poisoned line can't even reach the network layer. */
if (strncmp(url, "https://", 8) != 0) {
fclose(fp);
return -1;
}
memcpy(url_out, url, len + 1);
fclose(fp);
return 0;
@@ -35,20 +53,43 @@ lookup_tsv(const char *title_id, char *url_out, size_t url_sz) {
return -1;
}
/* PS4 titles: Sony's update list lives at a path derived from the title id
with HMAC-SHA256 under a key that is part of the PS4 system software and
widely published (it's how every PS4 update checker finds patches). */
static const unsigned char PS4_UPDATE_KEY[32] = {
0xAD, 0x62, 0xE3, 0x7F, 0x90, 0x5E, 0x06, 0xBC, 0x19, 0x59, 0x31, 0x42,
0x28, 0x1C, 0x11, 0x2C, 0xEC, 0x0E, 0x7E, 0xC3, 0xE9, 0x7E, 0xFD, 0xCA,
0xEF, 0xCD, 0xBA, 0xAF, 0xA6, 0x37, 0x8D, 0x84,
};
static int
lookup_prosperopatches(const char *title_id, char *url_out, size_t url_sz) {
/* TODO: implement live lookup once API endpoint is confirmed on-device.
prosperopatches.com serves Sony CDN index links for PS5 titles. */
(void)title_id;
(void)url_out;
(void)url_sz;
return -1;
ps4_update_url(const char *title_id, char *url_out, size_t url_sz) {
unsigned char mac[32];
unsigned int mac_len = 0;
char msg[24], hex[65];
int n;
if (strlen(title_id) != 9) return -1;
n = snprintf(msg, sizeof msg, "np_%s", title_id);
if (!HMAC(EVP_sha256(), PS4_UPDATE_KEY, sizeof PS4_UPDATE_KEY,
(const unsigned char *)msg, (size_t)n, mac, &mac_len) ||
mac_len != sizeof mac)
return -1;
for (unsigned i = 0; i < mac_len; i++)
snprintf(hex + 2 * i, 3, "%02x", mac[i]);
n = snprintf(url_out, url_sz,
"https://gs-sec.ww.np.dl.playstation.net/plo/np/%s/%s/%s-ver.xml",
title_id, hex, title_id);
return (n > 0 && (size_t)n < url_sz) ? 0 : -1;
}
int
patchdl_resolve_url(const char *title_id, char *url_out, size_t url_sz) {
if (!title_id) return -1;
if (!strncmp(title_id, "CUSA", 4))
return ps4_update_url(title_id, url_out, url_sz);
/* Only PS5 native title IDs (PPSA/PPSE/PPSH/PPSJ/PPSC) */
if (strncmp(title_id, "PPSA", 4) &&
strncmp(title_id, "PPSE", 4) &&
@@ -57,8 +98,5 @@ patchdl_resolve_url(const char *title_id, char *url_out, size_t url_sz) {
strncmp(title_id, "PPSC", 4))
return -1;
if (!lookup_tsv(title_id, url_out, url_sz))
return 0;
return lookup_prosperopatches(title_id, url_out, url_sz);
return lookup_tsv(title_id, url_out, url_sz);
}
+9
View File
@@ -1,3 +1,12 @@
/* SPDX-License-Identifier: GPL-3.0-or-later
* Copyright (C) 2026 Knutwurst
*
* PatchDL is free software: you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free
* Software Foundation, either version 3 of the License, or (at your option)
* any later version. See the LICENSE file in the project root for details.
*/
#pragma once
#include <stddef.h>
+314 -41
View File
@@ -1,10 +1,21 @@
/* SPDX-License-Identifier: GPL-3.0-or-later
* Copyright (C) 2026 Knutwurst
*
* PatchDL is free software: you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free
* Software Foundation, either version 3 of the License, or (at your option)
* any later version. See the LICENSE file in the project root for details.
*/
#include "patchdl_scan.h"
#include "patchdl_appdb.h"
#include <ps5/kernel.h>
#include <dirent.h>
#include <fcntl.h>
#include <limits.h>
#include <stdatomic.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
@@ -23,6 +34,26 @@ static const char *SCAN_DIRS[] = {
NULL,
};
/* The first scan runs single-threaded with the process root swapped to the
system root and keeps a handle to that root. Later scans (other threads are
running, so the root must not move) change only the working directory to
it and drop the leading '/' of every path, see sys_path. Nothing else in
PatchDL opens relative paths. */
static int g_sysroot_fd = -1;
static int g_rel_paths;
/* Step the running scan is in, for diagnosing slow rescans. */
static const char *volatile g_scan_step = "idle";
const char *
patchdl_scan_step(void) {
return g_scan_step;
}
static const char *
sys_path(const char *p) {
return (g_rel_paths && p[0] == '/') ? p + 1 : p;
}
/* ---------- param.json -------------------------------------------------- */
static int
@@ -80,7 +111,7 @@ try_param_json(const char *dir, patchdl_title_t *t) {
size_t n;
snprintf(path, sizeof(path), "%s/sce_sys/param.json", dir);
fp = fopen(path, "r");
fp = fopen(sys_path(path), "r");
if (!fp) return -1;
n = fread(buf, 1, sizeof(buf) - 1, fp);
fclose(fp);
@@ -179,7 +210,7 @@ try_param_sfo(const char *dir, patchdl_title_t *t) {
struct stat st;
snprintf(path, sizeof(path), "%s/sce_sys/param.sfo", dir);
fp = fopen(path, "rb");
fp = fopen(sys_path(path), "rb");
if (!fp) return -1;
if (fstat(fileno(fp), &st) || (size_t)st.st_size > sizeof(buf)) {
@@ -208,7 +239,7 @@ path_exists(const char *dir, const char *rel) {
char p[PATH_MAX];
struct stat st;
snprintf(p, sizeof(p), "%s/%s", dir, rel);
return stat(p, &st) == 0;
return stat(sys_path(p), &st) == 0;
}
/* Read up to sz-1 bytes of dir/rel into buf (NUL-terminated). 0 on success. */
@@ -219,7 +250,7 @@ read_small_file(const char *dir, const char *rel, char *buf, size_t sz) {
size_t n;
snprintf(p, sizeof(p), "%s/%s", dir, rel);
fp = fopen(p, "rb");
fp = fopen(sys_path(p), "rb");
if (!fp) return -1;
n = fread(buf, 1, sz - 1, fp);
fclose(fp);
@@ -227,13 +258,42 @@ read_small_file(const char *dir, const char *rel, char *buf, size_t sz) {
return 0;
}
/* Keep only actual games. Skip PS5 system apps (NPXS), the Payload Manager
fake app (PLDM) and ELF-loader homebrew (PSPS). */
/* Tell a Sony-signed package from a debug/fake-signed one by its header.
PS5 finalized image "\x7FFIH": byte 0x05 is 0x80 for retail, 0x00 for
debug (matches Sony's CDN patches, which start 7F 46 49 48 01 80).
PS4 container "\x7FCNT": bit 0 of byte 4 is set for retail, clear for a
fake package (same test Itemzflow uses). */
static patchdl_pkg_sign_t
pkg_sign_state(const char *dir) {
char p[PATH_MAX];
unsigned char h[8];
FILE *fp;
size_t n;
snprintf(p, sizeof(p), "%s/app.pkg", dir);
fp = fopen(sys_path(p), "rb");
if (!fp) return PATCHDL_PKG_UNREAD;
n = fread(h, 1, sizeof(h), fp);
fclose(fp);
if (n < sizeof(h)) return PATCHDL_PKG_UNREAD;
if (!memcmp(h, "\x7f" "FIH", 4))
return (h[5] & 0x80) ? PATCHDL_PKG_RETAIL : PATCHDL_PKG_FAKE;
if (!memcmp(h, "\x7f" "CNT", 4))
return (h[4] & 0x01) ? PATCHDL_PKG_RETAIL : PATCHDL_PKG_FAKE;
return PATCHDL_PKG_UNREAD;
}
/* Keep only actual games: PS5 (PPSA) and PS4 (CUSA) title ids followed by
five digits. System apps (NPXS) and homebrew with made-up ids (PatchDL's
own tile PTDL00001, loaders, file managers) have no Sony updates. */
static int
is_game_title(const char *title_id) {
if (!strncmp(title_id, "NPXS", 4)) return 0;
if (!strncmp(title_id, "PLDM", 4)) return 0;
if (!strncmp(title_id, "PSPS", 4)) return 0;
if (strncmp(title_id, "PPSA", 4) && strncmp(title_id, "CUSA", 4))
return 0;
for (int i = 4; i < 9; i++)
if (title_id[i] < '0' || title_id[i] > '9')
return 0;
return 1;
}
@@ -260,19 +320,23 @@ mount_is_shadow(const char *title_id, const struct statfs *mounts, int nmounts)
* Classify each /user/app/<TID> (verified on fw 11.60):
* - mount table references /mnt/shadowmnt for the title -> ShadowMountPlus
* mount (authoritative; mount.lnk is only a fallback hint)
* - app.pkg (no shadow mount) -> genuine install; app.json with CDN piece
* URLs means a not-downloaded preinstall stub, local URLs a real install
* - app.json with "fake":true -> homebrew fake (skip)
* - app.pkg (no shadow mount) -> its header decides: Sony-signed is a
* genuine install (store or disc), debug/fake-signed is a fake package
* (listed, but never checked, downloaded or patched), unreadable is unknown
* - app.json with "fake":true and no app.pkg -> homebrew (skip). With an
* app.pkg the marker only says the package did not come from Sony's CDN
* (PatchDL's own loopback install sets it too), so the header decides.
*/
static int
scan_one(const char *base, const char *name, patchdl_title_t *t,
const struct statfs *mounts, int nmounts) {
char dir[PATH_MAX];
char appjson[4096];
int has_mountlnk, has_app_pkg, has_paramjson, is_shadow, is_fake = 0, is_cdn = 0;
int has_mountlnk, has_app_pkg, has_paramjson, is_shadow, is_fake = 0;
snprintf(dir, sizeof(dir), "%s/%s", base, name);
memset(t, 0, sizeof(*t));
t->icon_fd = -1;
strncpy(t->source_path, dir, sizeof(t->source_path) - 1);
strncpy(t->title_id, name, sizeof(t->title_id) - 1);
@@ -288,10 +352,10 @@ scan_one(const char *base, const char *name, patchdl_title_t *t,
if (!read_small_file(dir, "app.json", appjson, sizeof(appjson))) {
if (strstr(appjson, "\"fake\"") && strstr(appjson, "true"))
is_fake = 1;
if (strstr(appjson, "http"))
is_cdn = 1; /* piece URLs point at the Sony CDN -> preinstall */
}
if (is_fake)
/* "fake": true marks both homebrew and installed fake packages. Only
homebrew (no app.pkg) drops out; a fake package stays in the list. */
if (is_fake && !has_app_pkg)
return -1;
/* app.pkg is the on-disk package of a genuine install; ShadowMountPlus
@@ -299,8 +363,16 @@ scan_one(const char *base, const char *name, patchdl_title_t *t,
app.pkg is the reliable genuine-vs-shadow discriminator — independent of
whether the shadow image is currently mounted. */
if (has_app_pkg) {
t->source_type = is_cdn ? PATCHDL_SOURCE_UNKNOWN /* CDN pkg = preinstall */
: PATCHDL_SOURCE_OFFICIAL;
/* app.json piece URLs are no signal: disc and store installs carry
CDN URLs there too. The package header is. */
t->pkg_sign = pkg_sign_state(dir);
/* The header wins over the installer's fake marker: a retail package
installed from a local URL is marked fake but is still Sony's. The
marker only decides when the header can't be read. */
t->source_type = t->pkg_sign == PATCHDL_PKG_RETAIL ? PATCHDL_SOURCE_OFFICIAL
: (is_fake || t->pkg_sign == PATCHDL_PKG_FAKE)
? PATCHDL_SOURCE_FAKE
: PATCHDL_SOURCE_UNKNOWN;
} else if (is_shadow || has_mountlnk || has_paramjson ||
path_exists(dir, "sce_sys/param.sfo")) {
if (try_param_json(dir, t)) /* metadata from the mounted sce_sys */
@@ -332,7 +404,7 @@ scan_base(const char *base, patchdl_title_t *arr, size_t *cnt, size_t cap,
DIR *d;
struct dirent *de;
d = opendir(base);
d = opendir(sys_path(base));
if (!d) return;
while ((de = readdir(d))) {
@@ -355,20 +427,90 @@ patchdl_source_str(patchdl_source_t src) {
case PATCHDL_SOURCE_OFFICIAL: return "official";
case PATCHDL_SOURCE_EXTERNAL: return "external";
case PATCHDL_SOURCE_SHADOWMOUNT: return "shadowmount";
case PATCHDL_SOURCE_FAKE: return "fake";
default: return "unknown";
}
}
/* Open a title's icon0.png while the scan still sees the whole filesystem.
The web server can't reach these paths later, but an fd opened now stays
readable. Tries the app.db path first, then the usual install locations.
Returns an fd to a non-empty PNG of sane size, or -1. */
#define ICON_MAX_BYTES (4 * 1024 * 1024)
static int
open_png(const char *path) {
unsigned char magic[8];
struct stat st;
int fd;
if (!path || path[0] != '/') return -1;
fd = open(sys_path(path), O_RDONLY | O_CLOEXEC);
if (fd < 0) return -1;
if (fstat(fd, &st) || !S_ISREG(st.st_mode) ||
st.st_size < 8 || st.st_size > ICON_MAX_BYTES ||
pread(fd, magic, 8, 0) != 8 ||
memcmp(magic, "\x89PNG\r\n\x1a\n", 8)) {
close(fd);
return -1;
}
return fd;
}
static int
open_icon(const patchdl_title_t *t, const char *db_path) {
static const char *const candidates[] = {
"/user/appmeta/%s/icon0.png",
"/user/appmeta/external/%s/icon0.png",
"%s/sce_sys/icon0.png", /* source_path, e.g. a shadowmount */
NULL,
};
char path[PATH_MAX];
int fd = open_png(db_path);
for (int i = 0; fd < 0 && candidates[i]; i++) {
snprintf(path, sizeof(path), candidates[i],
i < 2 ? t->title_id : t->source_path);
fd = open_png(path);
}
return fd;
}
/* After an install the console rewrites /user/appmeta/<id>/param.json at
once, while app.db keeps the old CONTENT_VERSION until later (seen: until
the game was started). Take the newer of the two so a finished update
doesn't look pending. */
static void
newer_appmeta_version(patchdl_title_t *t) {
char path[PATH_MAX], buf[8192], ver[16] = {0};
FILE *fp;
size_t n;
snprintf(path, sizeof(path), "/user/appmeta/%s/param.json", t->title_id);
if (!(fp = fopen(sys_path(path), "r"))) return;
n = fread(buf, 1, sizeof(buf) - 1, fp);
fclose(fp);
buf[n] = '\0';
if (json_str(buf, "contentVersion", ver, sizeof(ver)) == 0 &&
strcmp(ver, t->installed_version) > 0)
snprintf(t->installed_version, sizeof(t->installed_version), "%s", ver);
}
/* Overlay app.db metadata (real title name, installed version, version.xml
URL) onto the scanned titles. Genuine installs have no readable param.json,
so this is the only source of their name/version. */
static void
static int
merge_appdb(patchdl_title_t *arr, size_t cnt) {
patchdl_appinfo_t *info = NULL;
size_t n = 0;
if (patchdl_appdb_load(&info, &n))
return;
{
int rc = patchdl_appdb_load(&info, &n, g_rel_paths);
if (rc) {
g_scan_step = rc == -2 ? patchdl_appdb_error() : "fail: appdb read";
return -1;
}
}
for (size_t i = 0; i < cnt; i++) {
const patchdl_appinfo_t *a = patchdl_appdb_find(info, n, arr[i].title_id);
@@ -386,31 +528,94 @@ merge_appdb(patchdl_title_t *arr, size_t cnt) {
sizeof(arr[i].version_file_uri) - 1);
}
g_scan_step = "icons";
for (size_t i = 0; i < cnt; i++) {
const patchdl_appinfo_t *a = patchdl_appdb_find(info, n, arr[i].title_id);
arr[i].icon_fd = open_icon(&arr[i], a ? a->icon_path : NULL);
if (arr[i].pkg_sign != PATCHDL_PKG_NONE)
newer_appmeta_version(&arr[i]);
}
patchdl_appdb_free(info);
return 0;
}
int
patchdl_scan(patchdl_title_t **titles_out, size_t *count_out) {
/* See patchdl_scan_lock — once set, patchdl_scan no longer swaps the root
(it rescans via the kept system root handle) and the debug dump returns
NULL, so neither can race the running MHD threads. */
static _Atomic int g_scan_locked = 0;
void
patchdl_scan_lock(void) {
atomic_store(&g_scan_locked, 1);
}
static int
scan_all(patchdl_title_t **titles_out, size_t *count_out) {
patchdl_title_t *arr;
size_t cnt = 0;
pid_t pid = getpid();
intptr_t saved_root = 0, root_vnode;
int using_vswap = 0;
struct statfs *mounts = NULL;
int nmounts;
arr = calloc(MAX_TITLES, sizeof(*arr));
if (!arr) return -1;
if (!arr) { g_scan_step = "fail: oom"; return -1; }
/* Global mount table for shadowmount detection. getmntinfo's buffer is
libc-managed — must NOT be freed. */
g_scan_step = "mounts";
nmounts = getmntinfo(&mounts, MNT_NOWAIT);
if (nmounts < 0) { nmounts = 0; mounts = NULL; }
for (int i = 0; SCAN_DIRS[i]; i++) {
g_scan_step = SCAN_DIRS[i];
scan_base(SCAN_DIRS[i], arr, &cnt, MAX_TITLES, mounts, nmounts);
}
g_scan_step = "appdb";
/* At startup a list without app.db data still beats none. A rescan
without it would wipe names and versions of a good list: fail instead
and keep the old one. */
if (merge_appdb(arr, cnt) && g_rel_paths) {
free(arr);
return -1;
}
g_scan_step = "idle";
*titles_out = arr;
*count_out = cnt;
return 0;
}
/* A rescan while other threads run: resolve every path from the system root
kept by the first scan, without touching the process root. */
static int
rescan_relative(patchdl_title_t **titles_out, size_t *count_out) {
int cwd, rc;
if (g_sysroot_fd < 0) { g_scan_step = "fail: no system root handle"; return -1; }
cwd = open(".", O_RDONLY | O_DIRECTORY | O_CLOEXEC);
if (cwd < 0) { g_scan_step = "fail: open cwd"; return -1; }
if (fchdir(g_sysroot_fd)) { g_scan_step = "fail: fchdir"; close(cwd); return -1; }
g_rel_paths = 1;
rc = scan_all(titles_out, count_out);
g_rel_paths = 0;
(void)fchdir(cwd); /* best effort: nothing else uses the cwd */
close(cwd);
return rc;
}
int
patchdl_scan(patchdl_title_t **titles_out, size_t *count_out) {
pid_t pid = getpid();
intptr_t saved_root = 0, root_vnode;
int using_vswap = 0, rc;
/* Elevate so privileged paths (the app.db under /system_data) are
readable; same authid ftpsrv uses. No-op without kernel R/W. */
kernel_set_ucred_authid(pid, 0x4801000000000013L);
/* Global mount table for shadowmount detection. getmntinfo's buffer is
libc-managed — must NOT be freed. */
nmounts = getmntinfo(&mounts, MNT_NOWAIT);
if (nmounts < 0) { nmounts = 0; mounts = NULL; }
if (atomic_load(&g_scan_locked))
return rescan_relative(titles_out, count_out);
root_vnode = kernel_get_root_vnode();
if (root_vnode) {
@@ -421,25 +626,91 @@ patchdl_scan(patchdl_title_t **titles_out, size_t *count_out) {
if (saved_root) {
kernel_set_proc_rootdir(pid, root_vnode);
using_vswap = 1;
if (g_sysroot_fd < 0)
g_sysroot_fd = open("/", O_RDONLY | O_DIRECTORY | O_CLOEXEC);
}
}
for (int i = 0; SCAN_DIRS[i]; i++)
scan_base(SCAN_DIRS[i], arr, &cnt, MAX_TITLES, mounts, nmounts);
merge_appdb(arr, cnt);
rc = scan_all(titles_out, count_out);
if (using_vswap)
kernel_set_proc_rootdir(pid, saved_root);
return rc;
}
*titles_out = arr;
*count_out = cnt;
return 0;
static const char *PATCH_DIRS[] = {
"/user/patch",
"/mnt/ext0/user/patch",
"/mnt/ext1/user/patch",
NULL,
};
static int
read_title_file(const char *const *bases, const char *title_id, const char *name,
char *buf, size_t sz) {
char path[PATH_MAX];
if (g_sysroot_fd < 0 || !sz) return -1;
for (int i = 0; bases[i]; i++) {
int fd;
ssize_t n;
snprintf(path, sizeof(path), "%s/%s/%s", bases[i] + 1, title_id, name);
fd = openat(g_sysroot_fd, path, O_RDONLY | O_CLOEXEC);
if (fd < 0) continue;
n = read(fd, buf, sz - 1);
close(fd);
if (n < 0) return -1;
buf[n] = '\0';
return 0;
}
return -1;
}
int
patchdl_scan_read_app_file(const char *title_id, const char *name,
char *buf, size_t sz) {
return read_title_file(SCAN_DIRS, title_id, name, buf, sz);
}
int
patchdl_scan_read_patch_file(const char *title_id, const char *name,
char *buf, size_t sz) {
return read_title_file(PATCH_DIRS, title_id, name, buf, sz);
}
/* Fold one stat result into an FNV-1a hash. */
static unsigned long long
sig_add(unsigned long long h, const char *rel) {
struct stat st;
long long v[4] = {0};
if (fstatat(g_sysroot_fd, rel, &st, 0) == 0) {
v[0] = (long long)st.st_mtim.tv_sec;
v[1] = (long long)st.st_mtim.tv_nsec;
v[2] = (long long)st.st_size;
v[3] = (long long)st.st_ino;
}
for (size_t i = 0; i < sizeof v; i++) {
h ^= ((const unsigned char *)v)[i];
h *= 1099511628211ULL;
}
return h;
}
unsigned long long
patchdl_scan_signature(void) {
unsigned long long h = 14695981039346656037ULL;
if (g_sysroot_fd < 0) return 0;
for (int i = 0; SCAN_DIRS[i]; i++)
h = sig_add(h, SCAN_DIRS[i] + 1);
h = sig_add(h, "system_data/priv/mms/app.db");
h = sig_add(h, "system_data/priv/mms/app.db-wal");
return h ? h : 1;
}
void
patchdl_scan_free(patchdl_title_t *titles, size_t count) {
(void)count;
for (size_t i = 0; titles && i < count; i++)
if (titles[i].icon_fd >= 0)
close(titles[i].icon_fd);
free(titles);
}
@@ -467,6 +738,8 @@ patchdl_scan_debug_json(void) {
char tmp[2048];
pid_t pid = getpid();
intptr_t saved_root = 0, root_vnode;
if (atomic_load(&g_scan_locked)) return NULL;
int using_vswap = 0;
struct statfs *mounts = NULL;
int nmounts;
+56
View File
@@ -1,3 +1,12 @@
/* SPDX-License-Identifier: GPL-3.0-or-later
* Copyright (C) 2026 Knutwurst
*
* PatchDL is free software: you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free
* Software Foundation, either version 3 of the License, or (at your option)
* any later version. See the LICENSE file in the project root for details.
*/
#pragma once
#include <stddef.h>
@@ -8,8 +17,17 @@ typedef enum {
PATCHDL_SOURCE_EXTERNAL = 1,
PATCHDL_SOURCE_SHADOWMOUNT = 2,
PATCHDL_SOURCE_UNKNOWN = 3,
PATCHDL_SOURCE_FAKE = 4, /* debug/fake-signed package: not supported */
} patchdl_source_t;
/* Signing state read from the installed app.pkg header. */
typedef enum {
PATCHDL_PKG_NONE = 0, /* no app.pkg */
PATCHDL_PKG_RETAIL = 1,
PATCHDL_PKG_FAKE = 2,
PATCHDL_PKG_UNREAD = 3, /* app.pkg present but header unreadable/unknown */
} patchdl_pkg_sign_t;
typedef struct {
char title_id[32];
char content_id[64];
@@ -19,16 +37,29 @@ typedef struct {
char mount_from[256];
char version_file_uri[256]; /* from app.db, for version.xml */
patchdl_source_t source_type;
patchdl_pkg_sign_t pkg_sign; /* app.pkg header verdict, for diagnostics */
int icon_fd; /* open icon0.png, or -1; see patchdl_scan */
/* populated by background verxml fetch — guarded by websrv mutex */
char compatible_version[16];
char latest_version[16];
char latest_required_fw[16];
char patch_url[512]; /* manifest_url if present, otherwise pkg URL */
char delta_url[512]; /* DP.pkg bootstrap URL (always a PKG) */
char patch_title_id[16]; /* target title id from version.xml */
char patch_storage_title_id[16]; /* title id embedded in delta_url */
int verxml_done;
/* Prospero Patches lookup (best compatible patch from version history) */
char prospero_version[16];
char prospero_required_fw[16];
char prospero_size[16];
int prospero_done;
/* Manifest URL derived from a link the user pasted from Prospero. When
set it replaces patch_url for download and install. */
char manual_url[512];
char manual_version[16];
int enabled; /* user policy, persisted in config.json */
int resumable; /* a partial download is on disk */
int downloaded; /* a finished download is on disk */
long long partial_bytes; /* size of that partial, for the UI */
} patchdl_title_t;
@@ -39,3 +70,28 @@ const char *patchdl_source_str(patchdl_source_t src);
/* Diagnostic: malloc'd JSON dump of the mount table + scan-base directory
listings. Caller frees. */
char *patchdl_scan_debug_json(void);
/* Cheap change check for the automatic rescan: a hash over the title
directories and Sony's app.db. 0 when it can't be computed (no system root
handle), so callers never rescan on it. */
unsigned long long patchdl_scan_signature(void);
/* Name of the step the running scan is in ("idle" when none). */
const char *patchdl_scan_step(void);
/* Read <title dir>/<name> of an installed title (e.g. app.json) through the
kept system root handle; thread-safe, no working-directory change.
0 on success with a NUL-terminated buf. */
int patchdl_scan_read_app_file(const char *title_id, const char *name,
char *buf, size_t sz);
/* Same for an installed PS4 patch: /user/patch/<id>/<name>. */
int patchdl_scan_read_patch_file(const char *title_id, const char *name,
char *buf, size_t sz);
/* Mark scan/debug as no longer safe to call (must be set after MHD worker
threads come up — patchdl_scan performs a process-wide vnode swap that
would race any concurrent thread). After this is set, patchdl_scan rescans
through the system root handle kept by the first scan (working directory
only, one caller at a time) and the debug dump returns NULL. Call once
during startup, after MHD_start_daemon. */
void patchdl_scan_lock(void);
+231
View File
@@ -0,0 +1,231 @@
/* SPDX-License-Identifier: GPL-3.0-or-later
* Copyright (C) 2026 Knutwurst
*
* PatchDL is free software: you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free
* Software Foundation, either version 3 of the License, or (at your option)
* any later version. See the LICENSE file in the project root for details.
*/
#include "patchdl_tile.h"
#include "patchdl_install.h"
#include <errno.h>
#include <fcntl.h>
#include <stddef.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <unistd.h>
#include <ps5/kernel.h>
/* Embed the tile assets into .rodata directly via .incbin — no codegen step,
no Python helper, no second translation unit. */
#define INCASSET(name, file) \
__asm__(".section .rodata\n" \
".global " #name "\n" \
".global " #name "_end\n" \
".global " #name "_size\n" \
".align 16\n" #name ":\n" \
".incbin \"" file "\"\n" #name "_end:\n" #name "_size:\n" \
".quad " #name "_end - " #name "\n" \
".previous\n"); \
extern const uint8_t name[]; \
extern const size_t name##_size;
INCASSET(tile_param_json, "assets/param.json");
INCASSET(tile_icon0_png, "assets/icon0.png");
#define TILE_TITLE_ID "PTDL00001"
/* Forward decls — we resolve sceAppInstUtilInitialize/AppInstallTitleDir at
runtime via the kernel dynlib helpers so the ELF stays loader-friendly. */
typedef int (*ai_init_fn)(void);
typedef int (*ai_install_dir_fn)(const char *title_id, const char *parent_dir,
void *opts);
typedef int (*ai_install_all_fn)(void *opts);
static intptr_t
dynsym_by_name(const char *sym) {
uint32_t h = 0;
if (kernel_dynlib_handle(-1, "libSceAppInstUtil.sprx", &h) < 0) return 0;
return kernel_dynlib_dlsym(-1, h, sym);
}
static intptr_t
dynsym_by_nid(const char *nid) {
uint32_t h = 0;
if (kernel_dynlib_handle(-1, "libSceAppInstUtil.sprx", &h) < 0) return 0;
return kernel_dynlib_resolve(-1, h, nid);
}
static int
write_all(const char *path, const uint8_t *data, size_t size) {
int fd;
ssize_t w;
size_t off = 0;
/* O_NOFOLLOW + 0600: don't follow a symlink at the destination, and don't
create the file with the libc default 0666 mode. Same pattern as the
net layer's fopen_safe. */
fd = open(path, O_WRONLY | O_CREAT | O_TRUNC | O_NOFOLLOW | O_CLOEXEC, 0600);
if (fd < 0) return -1;
while (off < size) {
w = write(fd, data + off, size - off);
if (w < 0) {
if (errno == EINTR) continue;
close(fd);
return -1;
}
off += (size_t)w;
}
close(fd);
return 0;
}
static int
file_matches(const char *path, const uint8_t *expected, size_t expected_size) {
struct stat st;
uint8_t *buf;
int fd;
ssize_t n;
int match = 0;
if (stat(path, &st) != 0) return 0;
if ((size_t)st.st_size != expected_size) return 0;
fd = open(path, O_RDONLY | O_CLOEXEC);
if (fd < 0) return 0;
buf = malloc(expected_size);
if (!buf) { close(fd); return 0; }
n = read(fd, buf, expected_size);
close(fd);
if (n == (ssize_t)expected_size && memcmp(buf, expected, expected_size) == 0)
match = 1;
free(buf);
return match;
}
int
patchdl_tile_install_if_needed(char *msg, size_t msg_sz) {
char base_dir[128];
char sce_sys_dir[160];
char param_path[192];
char icon_path[192];
char receipt_path[192];
ai_init_fn ai_initialize = NULL;
ai_install_dir_fn ai_install_title = NULL;
ai_install_all_fn ai_install_all = NULL;
int rc;
snprintf(base_dir, sizeof base_dir, "/user/app/%s", TILE_TITLE_ID);
snprintf(sce_sys_dir, sizeof sce_sys_dir, "/user/app/%s/sce_sys", TILE_TITLE_ID);
snprintf(param_path, sizeof param_path, "/user/app/%s/sce_sys/param.json", TILE_TITLE_ID);
snprintf(icon_path, sizeof icon_path, "/user/app/%s/sce_sys/icon0.png", TILE_TITLE_ID);
/* Written only after the installer accepted the tile. Without it, files
left behind by a failed registration would pass the stat-guard below
and the tile would never be retried. */
snprintf(receipt_path, sizeof receipt_path, "/user/app/%s/.patchdl_registered", TILE_TITLE_ID);
/* stat-guard: if everything on disk already matches, do nothing. Re-running
the install API every payload start would be wasted work and burns the
only safe path through Sony's installer state machine. */
{
struct stat st;
if (stat(receipt_path, &st) == 0 &&
file_matches(param_path, tile_param_json, tile_param_json_size) &&
file_matches(icon_path, tile_icon0_png, tile_icon0_png_size)) {
snprintf(msg, msg_sz, "tile already installed and up to date");
return 0;
}
}
/* AppInstUtil is loaded lazily by the install backend thread. Poke it +
poll briefly so libSceAppInstUtil.sprx is mapped before we try to
resolve symbols out of it. Bounded to a few seconds so a stuck init
doesn't wedge an MHD worker forever. */
{
char ready_msg[128];
int ready = -1;
for (int i = 0; i < 60 && ready != 0; i++) {
ready = patchdl_install_backend_check(ready_msg, sizeof ready_msg);
if (ready != 0) usleep(250 * 1000);
}
if (ready != 0) {
snprintf(msg, msg_sz,
"install backend not ready: %s", ready_msg);
return -1;
}
}
/* Resolve the install API now so we can fail fast before touching disk.
The symbol export is Sony-private, so the NID resolver is the more
reliable lookup — try NID first, fall back to the by-name dlsym. */
ai_install_title = (ai_install_dir_fn)dynsym_by_nid("Wudg3Xe3heE");
if (!ai_install_title)
ai_install_title = (ai_install_dir_fn)dynsym_by_name(
"sceAppInstUtilAppInstallTitleDir");
/* Firmware 13.xx no longer exports AppInstallTitleDir. AppInstallAll
rescans /user/app and registers the tile directory the same way. */
if (!ai_install_title)
ai_install_all = (ai_install_all_fn)dynsym_by_name(
"sceAppInstUtilAppInstallAll");
if (!ai_install_title && !ai_install_all) {
snprintf(msg, msg_sz,
"neither AppInstallTitleDir nor AppInstallAll resolved");
return -1;
}
ai_initialize = (ai_init_fn)dynsym_by_name("sceAppInstUtilInitialize");
if (ai_initialize) {
rc = ai_initialize();
/* SCE_OK == 0; a non-zero rc here usually means "already initialised"
in this process, which is fine. We only bail on a clearly fatal
code (anything that isn't already the success case). */
if (rc != 0 && rc != 0x80B21161 /* ALREADY_INITIALIZED */) {
snprintf(msg, msg_sz,
"sceAppInstUtilInitialize failed 0x%08x", (unsigned)rc);
return -1;
}
}
if (mkdir(base_dir, 0755) && errno != EEXIST) {
snprintf(msg, msg_sz, "mkdir %s failed errno=%d", base_dir, errno);
return -1;
}
if (mkdir(sce_sys_dir, 0755) && errno != EEXIST) {
snprintf(msg, msg_sz, "mkdir %s failed errno=%d", sce_sys_dir, errno);
return -1;
}
unlink(receipt_path);
if (write_all(param_path, tile_param_json, tile_param_json_size)) {
snprintf(msg, msg_sz, "write param.json failed errno=%d", errno);
return -1;
}
if (write_all(icon_path, tile_icon0_png, tile_icon0_png_size)) {
snprintf(msg, msg_sz, "write icon0.png failed errno=%d", errno);
return -1;
}
rc = ai_install_title ? ai_install_title(TILE_TITLE_ID, "/user/app/", NULL)
: ai_install_all(NULL);
if (rc != 0) {
snprintf(msg, msg_sz, "%s(%s) returned 0x%08x",
ai_install_title ? "AppInstallTitleDir" : "AppInstallAll",
TILE_TITLE_ID, (unsigned)rc);
return -1;
}
(void)write_all(receipt_path, (const uint8_t *)"1", 1);
snprintf(msg, msg_sz, "tile installed (%s via %s)", TILE_TITLE_ID,
ai_install_title ? "AppInstallTitleDir" : "AppInstallAll");
return 0;
}
+29
View File
@@ -0,0 +1,29 @@
/* SPDX-License-Identifier: GPL-3.0-or-later
* Copyright (C) 2026 Knutwurst
*
* PatchDL is free software: you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free
* Software Foundation, either version 3 of the License, or (at your option)
* any later version. See the LICENSE file in the project root for details.
*/
#pragma once
#include <stddef.h>
/* Install / refresh the PatchDL home-screen tile.
*
* Writes param.json + icon0.png into /user/app/<TITLE_ID>/sce_sys/ and asks
* the on-console installer to register the directory as an app. The tile's
* deeplinkUri opens the on-console browser at http://127.0.0.1:12880/, i.e.
* PatchDL's own UI — only useful while the ELF is running.
*
* No package, no code signing — files only; the installer reads the
* directory directly.
*
* stat-guard: the asset bytes are diffed against the on-disk copy first;
* if nothing changed the install call isn't made at all (avoids a costly
* re-register every payload start). Returns 0 on success or when nothing
* needed doing.
*/
int patchdl_tile_install_if_needed(char *msg, size_t msg_sz);
+10 -1
View File
@@ -1,3 +1,12 @@
/* SPDX-License-Identifier: GPL-3.0-or-later
* Copyright (C) 2026 Knutwurst
*
* PatchDL is free software: you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free
* Software Foundation, either version 3 of the License, or (at your option)
* any later version. See the LICENSE file in the project root for details.
*/
#pragma once
#define PATCHDL_VERSION "0.0.3"
#define PATCHDL_VERSION "0.2.0"
+37 -10
View File
@@ -1,3 +1,12 @@
/* SPDX-License-Identifier: GPL-3.0-or-later
* Copyright (C) 2026 Knutwurst
*
* PatchDL is free software: you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free
* Software Foundation, either version 3 of the License, or (at your option)
* any later version. See the LICENSE file in the project root for details.
*/
#include "patchdl_verxml.h"
#include "patchdl_net.h"
@@ -66,14 +75,20 @@ ver_gt(const char *a, const char *b) {
from a string such as nptitleid, manifest_url, or delta_url. */
static void
extract_title_id(const char *s, char *out, size_t sz) {
size_t len;
out[0] = '\0';
if (sz < 10 || !s) return;
for (const char *p = s; p[0] && p[8]; p++) {
len = strlen(s);
if (len < 9) return;
/* `len - 9` is the last position where a 9-char id can still fit; this
avoids reading p[8] past the NUL terminator. */
for (size_t i = 0; i <= len - 9; i++) {
const char *p = s + i;
int ok = 1;
for (int i = 0; i < 4 && ok; i++)
if (p[i] < 'A' || p[i] > 'Z') ok = 0;
for (int i = 4; i < 9 && ok; i++)
if (p[i] < '0' || p[i] > '9') ok = 0;
for (int k = 0; k < 4 && ok; k++)
if (p[k] < 'A' || p[k] > 'Z') ok = 0;
for (int k = 4; k < 9 && ok; k++)
if (p[k] < '0' || p[k] > '9') ok = 0;
if (ok) {
memcpy(out, p, 9);
out[9] = '\0';
@@ -119,20 +134,26 @@ parse_packages(const char *xml, uint32_t fw_bin, patchdl_verinfo_t *out) {
char murl[512] = {0};
/* PS5 version.xml uses content_ver; PS4 uses version. */
if (attr_val(p, tag_end, "content_ver", ver, sizeof(ver)))
int is_ps4 = attr_val(p, tag_end, "content_ver", ver, sizeof(ver)) != 0;
if (is_ps4)
attr_val(p, tag_end, "version", ver, sizeof(ver));
attr_val(p, tag_end, "system_ver", sver, sizeof(sver));
attr_val(p, tag_end, "delta_url", durl, sizeof(durl));
attr_val(p, tag_end, "manifest_url", murl, sizeof(murl));
if (ver[0] && sver[0]) {
uint32_t pkg_sver = parse_hex(sver);
if (ver[0] && (sver[0] || is_ps4)) {
/* A PS4 patch's system_ver is a PS4 firmware (in decimal); the
PS5 runs PS4 games regardless, so it never blocks one. */
uint32_t pkg_sver = is_ps4 ? 0 : parse_hex(sver);
/* Track latest overall */
if (!out->latest_version[0] || ver_gt(ver, out->latest_version)) {
strncpy(out->latest_version, ver, sizeof(out->latest_version) - 1);
fw_bin_to_str(pkg_sver, out->latest_required_fw,
sizeof(out->latest_required_fw));
if (is_ps4)
out->latest_required_fw[0] = '\0';
else
fw_bin_to_str(pkg_sver, out->latest_required_fw,
sizeof(out->latest_required_fw));
}
/* Track latest compatible + its installable patch source. PS5
@@ -148,6 +169,8 @@ parse_packages(const char *xml, uint32_t fw_bin, patchdl_verinfo_t *out) {
sizeof(out->compatible_version) - 1);
strncpy(out->compatible_url, murl[0] ? murl : durl,
sizeof(out->compatible_url) - 1);
if (durl[0])
strncpy(out->delta_url, durl, sizeof(out->delta_url) - 1);
extract_title_id(durl, out->compatible_storage_title,
sizeof(out->compatible_storage_title));
if (root_title[0]) {
@@ -175,6 +198,10 @@ patchdl_verxml_query(const char *url, uint32_t fw_bin, patchdl_verinfo_t *out) {
if (!url || !out) return -1;
memset(out, 0, sizeof(*out));
/* version.xml is a few KB in practice; cap so a misbehaving CDN can't
slurp unbounded RAM into the buffer. */
memset(&buf, 0, sizeof(buf));
buf.max = 4 * 1024 * 1024;
if (patchdl_http_get(url, &buf)) return -1;
if (!buf.data || !buf.size) { free(buf.data); return -1; }
+10
View File
@@ -1,3 +1,12 @@
/* SPDX-License-Identifier: GPL-3.0-or-later
* Copyright (C) 2026 Knutwurst
*
* PatchDL is free software: you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free
* Software Foundation, either version 3 of the License, or (at your option)
* any later version. See the LICENSE file in the project root for details.
*/
#pragma once
#include <stdint.h>
@@ -7,6 +16,7 @@ typedef struct {
char latest_version[16]; /* highest pkg overall, or "" */
char latest_required_fw[16]; /* fw str for latest pkg, e.g. "11.60", or "" */
char compatible_url[512]; /* manifest_url if present, otherwise pkg URL */
char delta_url[512]; /* DP.pkg bootstrap URL (always a PKG, never JSON) */
char compatible_title[16]; /* target title id from version.xml/manifest_url */
char compatible_storage_title[16]; /* title id embedded in delta_url storage path */
} patchdl_verinfo_t;
+1870 -128
View File
File diff suppressed because it is too large. Load diff
+9
View File
@@ -1,3 +1,12 @@
/* SPDX-License-Identifier: GPL-3.0-or-later
* Copyright (C) 2026 Knutwurst
*
* PatchDL is free software: you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free
* Software Foundation, either version 3 of the License, or (at your option)
* any later version. See the LICENSE file in the project root for details.
*/
#pragma once
int patchdl_websrv_start(unsigned short port);
+16 -6
View File
@@ -16,6 +16,9 @@ GET /api/config
POST /api/config
GET /api/titles
GET /api/downloads
GET /api/installstatus
GET /api/pkgmeta/:title_id
GET /api/pkgverify/:title_id
POST /api/titles/:title_id/check
POST /api/titles/:title_id/download
POST /api/titles/:title_id/install
@@ -36,8 +39,9 @@ The UI assumes deny-by-default behavior:
"source_policy": {
"official": { "allow_check": true, "allow_download": true, "allow_install": true },
"external": { "allow_check": true, "allow_download": true, "allow_install": true },
"shadowmount": { "allow_check": true, "allow_download": true, "allow_install": false },
"unknown": { "allow_check": true, "allow_download": false, "allow_install": false }
"shadowmount": { "allow_check": true, "allow_download": false, "allow_install": false },
"unknown": { "allow_check": true, "allow_download": false, "allow_install": false },
"fake": { "allow_check": true, "allow_download": false, "allow_install": false }
},
"cdn_allowlist": [
"sgst.prod.dl.playstation.net",
@@ -67,7 +71,7 @@ Per-title source fields:
"source_path": "/system_ex/app/PPSA90001_00",
"mount_from": "/mnt/usb0/itemzflow/Shadowmounted Test Title",
"enabled": true,
"mode": "download_only"
"mode": "disabled"
}
```
@@ -80,11 +84,17 @@ shadowmount
unknown
```
The frontend treats `shadowmount` as download-only and `unknown` as blocked for
downloads and installs. Backend code should enforce the same policy even if a
client sends a forged request.
The frontend lists `shadowmount`, `unknown` and `fake` titles under *Not
supported* and offers neither download nor install for them. The backend refuses
both as well, even if a client sends a forged request.
For PS5 game updates, the backend may turn a Sony `manifest_url` into a merged
local `.pkg` by downloading all manifest pieces. The `delta_url` `*-DP.pkg` is
not shown as a separate user action because it can bootstrap the storage/master
title instead of the installed regional target.
If `patch_storage_match` is false, the CDN stores the patch pieces under another
regional (master) title id. That is fine: the merged `.pkg` assembled from the
manifest carries the installed title's own content id, and AppInstUtil
`AppInstallPkg` installs it onto that title. The UI only adds a "Shared master"
label.
+1071 -41
View File
File diff suppressed because it is too large. Load diff
+46 -9
View File
@@ -39,7 +39,7 @@
<div class="brand-mark">PD</div>
<div>
<strong>PatchDL</strong>
<span>by Knutwurst · v0.0.3</span>
<span>by Knutwurst · <span id="brandVersion">--</span></span>
</div>
</div>
@@ -58,6 +58,7 @@
<div class="rail-foot">
<span id="railFw">FW --</span>
<span id="railSpace">-- free</span>
<button type="button" class="link-button rail-donate" data-donate>Buy me a coffee</button>
</div>
</aside>
@@ -66,16 +67,43 @@
<section class="view is-active" data-view="games">
<header class="topbar">
<div>
<p class="eyebrow">Standalone ELF Web UI</p>
<p class="eyebrow">PS5 &amp; PS4 game updates</p>
<h1>Games</h1>
</div>
<div class="topbar-actions">
<button class="primary-button" id="updateAllBtn" title="Download (and optionally install) every game that has an available, allowed update">
<svg><use href="#icon-download"></use></svg>
Update all
</button>
<button class="icon-button" id="refreshBtn" title="Refresh status and games" aria-label="Refresh">
<svg><use href="#icon-refresh"></use></svg>
</button>
</div>
</header>
<aside id="globalDl" class="global-dl" hidden aria-live="polite">
<div class="global-dl-row">
<span class="global-dl-pulse" aria-hidden="true"></span>
<div class="global-dl-text">
<div class="global-dl-line1">
<span class="global-dl-eyebrow" id="globalDlState">Downloading</span>
<strong class="global-dl-name" id="globalDlName">—</strong>
<span class="global-dl-position" id="globalDlPosition" hidden></span>
</div>
<div class="global-dl-line2">
<span id="globalDlPct">0%</span>
<span class="global-dl-sep" aria-hidden="true">·</span>
<span id="globalDlSpeed">—</span>
<span class="global-dl-sep" aria-hidden="true">·</span>
<span id="globalDlEta">—</span>
</div>
</div>
</div>
<div class="global-dl-track">
<i class="global-dl-bar" id="globalDlBar" style="width:0%"></i>
</div>
</aside>
<section class="status-strip" aria-label="System status">
<article class="metric">
<span>Firmware</span>
@@ -85,7 +113,7 @@
<article class="metric">
<span>DNS Guard</span>
<strong id="dnsValue">--</strong>
<em>Sony blocked by nanoDNS</em>
<em>System DNS left untouched</em>
</article>
<article class="metric">
<span>CDN Access</span>
@@ -105,11 +133,10 @@
<input id="searchInput" type="search" placeholder="Search title, Title ID, or Content ID" />
</div>
<div class="segmented" role="group" aria-label="Filter">
<button class="is-selected" data-filter="all" aria-pressed="true">All</button>
<button data-filter="updatable" aria-pressed="false">Updatable</button>
<button data-filter="uptodate" aria-pressed="false">Up to date</button>
<button data-filter="needsfw" aria-pressed="false">Needs FW</button>
<button data-filter="blocked" aria-pressed="false">Can't update</button>
<button class="is-selected" data-filter="updates" aria-pressed="true">Updates <span class="chip-count"></span></button>
<button data-filter="uptodate" aria-pressed="false">Up to date <span class="chip-count"></span></button>
<button data-filter="blocked" aria-pressed="false">Not supported <span class="chip-count"></span></button>
<button data-filter="all" aria-pressed="false">All <span class="chip-count"></span></button>
</div>
</div>
@@ -143,7 +170,7 @@
<label class="field">
<span>Download Folder</span>
<input id="downloadDir" type="text" spellcheck="false" readonly
title="Patches always download internally and are removed after install" />
title="Patches always download to the console's internal storage" />
</label>
<label class="switch-row">
@@ -208,6 +235,16 @@
<span>Install Protection</span>
<div id="sourcePolicyList"></div>
</div>
<div class="storage-list">
<span>Downloads on console <em id="storageTotal"></em></span>
<div id="storageList"></div>
</div>
<div class="donate-row">
<span>Like PatchDL? You can buy me a coffee.</span>
<button type="button" class="row-button is-ghost" data-donate>Buy me a coffee</button>
</div>
</div>
</section>
+301 -4
View File
@@ -116,6 +116,23 @@ svg {
font-size: 12px;
}
.rail-foot span { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.rail-foot .rail-donate { justify-self: start; margin-top: 4px; }
.donate-row {
display: flex;
flex-wrap: wrap;
align-items: center;
justify-content: space-between;
gap: 10px;
margin-top: 16px;
padding: 12px;
border: 1px solid var(--border);
border-radius: 8px;
background: var(--surface-2);
color: var(--muted);
}
.donate-row .row-button { width: auto; padding: 0 16px; }
.donate-open { display: inline-flex; align-items: center; justify-content: center; text-decoration: none; justify-self: start; padding: 0 18px; }
/* ---------------- views + topbar ---------------- */
@@ -173,6 +190,105 @@ h2 { font-size: 18px; line-height: 1.2; }
margin-bottom: 18px;
}
/* ---------------- global download banner ---------------- */
/* Sticky banner above the status strip, visible only while at least one
download is queued/active. The pulse dot and gradient bar at the bottom
echo the per-game card progress styling so the two read as one system. */
.global-dl {
position: relative;
display: flex;
flex-direction: column;
gap: 12px;
margin-bottom: 18px;
padding: 16px 18px 0;
border: 1px solid var(--border);
background:
radial-gradient(120% 80% at 0% 0%, var(--green-soft), transparent 60%),
linear-gradient(180deg, rgba(56, 193, 114, 0.06), transparent 60%),
var(--surface);
border-radius: var(--radius);
overflow: hidden;
}
.global-dl[hidden] { display: none; }
.global-dl-row {
display: flex;
align-items: center;
gap: 14px;
min-width: 0;
}
.global-dl-pulse {
flex: none;
width: 12px;
height: 12px;
border-radius: 50%;
background: var(--green);
box-shadow: 0 0 0 0 var(--green);
animation: globalDlPulse 1.6s ease-out infinite;
}
@keyframes globalDlPulse {
0% { box-shadow: 0 0 0 0 rgba(56, 193, 114, 0.55); }
70% { box-shadow: 0 0 0 14px rgba(56, 193, 114, 0); }
100% { box-shadow: 0 0 0 0 rgba(56, 193, 114, 0); }
}
.global-dl-text { display: flex; flex-direction: column; gap: 4px; min-width: 0; flex: 1; }
.global-dl-line1 {
display: flex; align-items: baseline; gap: 10px;
min-width: 0; flex-wrap: wrap;
}
.global-dl-eyebrow {
text-transform: uppercase; letter-spacing: 0.08em;
font-size: 11px; font-weight: 600; color: var(--green-dark);
}
.global-dl-name {
font-size: 16px; font-weight: 600; color: #fff;
overflow: hidden; text-overflow: ellipsis; white-space: nowrap;
min-width: 0; flex: 1;
}
.global-dl-position {
font-size: 12px; color: var(--muted);
padding: 2px 8px; border-radius: 999px;
background: rgba(255, 255, 255, 0.04); border: 1px solid var(--border);
}
.global-dl-position[hidden] { display: none; }
.global-dl-line2 {
display: flex; align-items: center; gap: 8px;
font-size: 12px; color: var(--muted);
font-variant-numeric: tabular-nums;
}
.global-dl-line2 b { color: #d6dde4; font-weight: 600; }
.global-dl-sep { opacity: 0.5; }
.global-dl-track {
position: relative;
height: 3px;
margin: 0 -18px; /* extend bar edge-to-edge */
background: rgba(56, 193, 114, 0.08);
overflow: hidden;
}
.global-dl-bar {
display: block;
height: 100%;
width: 0%;
background: linear-gradient(90deg, var(--green) 0%, var(--green-dark) 100%);
box-shadow: 0 0 12px rgba(56, 193, 114, 0.4);
transition: width 400ms ease-out;
}
.global-dl-bar.is-indeterminate {
width: 32% !important;
animation: globalDlIndet 1.6s ease-in-out infinite;
}
@keyframes globalDlIndet {
0% { transform: translateX(-100%); }
100% { transform: translateX(320%); }
}
.metric {
min-width: 0;
padding: 14px 16px;
@@ -239,6 +355,8 @@ h2 { font-size: 18px; line-height: 1.2; }
white-space: nowrap;
}
.segmented button.is-selected { background: var(--surface); color: var(--ink); }
.chip-count { margin-left: 4px; color: var(--muted); font-weight: 600; font-variant-numeric: tabular-nums; }
.chip-count:empty { display: none; }
/* ---------------- game cards ---------------- */
@@ -269,13 +387,15 @@ h2 { font-size: 18px; line-height: 1.2; }
.cover {
display: grid;
place-items: center;
width: 48px; height: 48px;
width: 64px; height: 64px;
color: #fff;
background: linear-gradient(135deg, #2d6d9d, #247857);
border-radius: 10px;
font-size: 14px;
border-radius: 12px;
font-size: 16px;
font-weight: 800;
overflow: hidden;
}
.cover img { width: 100%; height: 100%; object-fit: cover; display: block; }
.card-body { min-width: 0; }
.card-body h3 { margin: 0 0 6px; overflow-wrap: anywhere; font-size: 16px; }
@@ -292,6 +412,10 @@ h2 { font-size: 18px; line-height: 1.2; }
color: var(--muted);
}
.versions b { color: var(--ink); font-weight: 700; }
.card-note { flex-basis: 100%; line-height: 1.45; }
.card-note.is-warn { color: var(--amber); }
.prospero-line a { color: var(--blue); text-decoration: none; }
.prospero-line a:hover { text-decoration: underline; }
.card-actions {
display: flex;
@@ -317,6 +441,7 @@ h2 { font-size: 18px; line-height: 1.2; }
.pill.warn { border-color: rgba(242, 184, 75, 0.38); background: var(--amber-soft); color: var(--amber); }
.pill.external { border-color: rgba(88, 166, 255, 0.34); background: var(--blue-soft); color: var(--blue); }
.pill.shadow { border-color: rgba(181, 146, 255, 0.34); background: rgba(181, 146, 255, 0.14); color: #c7b1ff; }
.pill.prospero { border-color: rgba(64, 201, 198, 0.38); background: rgba(64, 201, 198, 0.14); color: #6fe0dc; }
.pill.blocked { border-color: rgba(255, 107, 107, 0.34); background: var(--red-soft); color: var(--red); }
.pill.live { border-color: rgba(56, 193, 114, 0.5); background: var(--green-soft); color: var(--green-dark); }
.pill.live::before {
@@ -358,6 +483,17 @@ h2 { font-size: 18px; line-height: 1.2; }
background: linear-gradient(90deg, var(--green), var(--blue));
transition: width 320ms ease;
}
.progress.is-indeterminate > i {
animation: progressSweep 1.6s linear infinite; /* duration = INDET_MS */
transition: none;
}
@keyframes progressSweep {
from { transform: translateX(-100%); }
to { transform: translateX(320%); }
}
@media (prefers-reduced-motion: reduce) {
.progress.is-indeterminate > i { animation: none; width: 100% !important; opacity: 0.5; }
}
.progress-meta {
display: flex;
flex-wrap: wrap;
@@ -451,8 +587,39 @@ h2 { font-size: 18px; line-height: 1.2; }
.toggle input:checked + .track::after { transform: translateX(18px); background: var(--green); }
.toggle input:focus-visible + .track { outline: 2px solid var(--blue); outline-offset: 2px; }
.toggle .label { font-size: 12px; color: var(--muted); min-width: 22px; }
.lead .toggle .label { white-space: nowrap; }
.allowlist, .source-policy { display: grid; gap: 8px; margin-top: 16px; }
.allowlist, .source-policy, .storage-list { display: grid; gap: 8px; margin-top: 16px; }
.storage-list > span em { color: var(--muted); font-style: normal; margin-left: 6px; }
.storage-list > div { display: grid; gap: 8px; }
.storage-row {
display: grid;
grid-template-columns: minmax(0, 1fr) auto auto auto;
gap: 10px;
align-items: center;
padding: 10px;
background: var(--surface-2);
border: 1px solid var(--border);
border-radius: 8px;
}
.storage-row strong { font-size: 13px; overflow-wrap: anywhere; }
.storage-row em { color: var(--muted); font-style: normal; font-size: 12px; }
.storage-row b { font-variant-numeric: tabular-nums; }
.storage-empty { color: var(--muted); font-size: 13px; }
.link-button {
padding: 0;
border: 0;
background: none;
color: var(--blue);
font: inherit;
cursor: pointer;
text-decoration: underline;
text-underline-offset: 2px;
}
.link-button:hover { color: var(--ink); }
@media (max-width: 640px) {
.storage-row { grid-template-columns: minmax(0, 1fr) auto; }
}
.allowlist div { display: flex; flex-wrap: wrap; gap: 6px; }
.source-policy > div { display: grid; gap: 8px; }
@@ -528,8 +695,138 @@ pre {
}
.toast.is-visible { opacity: 1; transform: translate(-50%, 0); }
/* ---------------- older patch guide (Prospero) ---------------- */
.guide-backdrop {
position: fixed;
inset: 0;
z-index: 15; /* below the toast (20) */
display: grid;
grid-template-columns: minmax(0, 560px); /* an auto track would grow to the content */
justify-content: center;
align-content: center;
padding: 24px 16px;
overflow-y: auto;
background: rgba(5, 7, 9, 0.72);
}
.guide {
display: grid;
gap: 16px;
padding: 22px;
border: 1px solid var(--border);
border-radius: 14px;
background: var(--surface);
box-shadow: var(--shadow);
}
/* minmax(0, 1fr): without it an <input>'s intrinsic width pushes the tracks wider than the sheet */
.guide, .guide-steps, .guide-steps li { grid-template-columns: minmax(0, 1fr); }
.guide-head { display: flex; align-items: flex-start; justify-content: space-between; gap: 12px; }
.guide-head > div { min-width: 0; }
.guide-head h2 { margin: 0; font-size: 22px; }
.guide-game { margin: 4px 0 0; color: var(--muted); }
.guide-close { flex: none; width: 40px; padding: 0; font-size: 22px; line-height: 1; }
.guide-why { margin: 0; color: var(--muted); line-height: 1.55; }
.guide-why b { color: var(--ink); }
.guide-qr {
display: flex;
align-items: center;
gap: 16px;
padding: 14px;
border: 1px solid var(--border);
border-radius: var(--radius);
background: var(--surface-2);
}
.guide-qr .qr { flex: none; width: 148px; height: 148px; border-radius: 6px; }
.guide-qr > div { display: grid; gap: 6px; min-width: 0; }
.guide-qr span { color: var(--muted); line-height: 1.5; }
.guide-qr code { overflow-wrap: anywhere; color: var(--blue-dark); font-size: 13px; }
/* Console view: the PS5 can't copy links, so it only hands over to a phone. */
.guide.is-handoff { width: min(560px, 100%); justify-self: center; text-align: center; }
.guide.is-handoff .guide-head { text-align: left; }
.guide-handoff { display: grid; justify-items: center; gap: 12px; }
.guide-handoff .qr { width: min(420px, 100%); height: auto; aspect-ratio: 1; border-radius: 8px; }
.guide-handoff p { margin: 0; color: var(--muted); line-height: 1.5; }
.guide-handoff code { overflow-wrap: anywhere; color: var(--blue-dark); font-size: 16px; }
.guide-steps { display: grid; gap: 12px; margin: 0; padding: 0; list-style: none; counter-reset: step; }
.guide-steps li {
display: grid;
gap: 10px;
padding: 14px 14px 14px 52px;
position: relative;
border: 1px solid var(--border);
border-radius: var(--radius);
counter-increment: step;
}
.guide-steps li::before {
content: counter(step);
position: absolute;
left: 14px;
top: 14px;
width: 26px;
height: 26px;
display: grid;
place-items: center;
border-radius: 50%;
background: var(--green-soft);
color: var(--green-dark);
font-weight: 800;
font-size: 13px;
}
.guide-step-text { display: grid; gap: 4px; }
.guide-step-text span { color: var(--muted); line-height: 1.5; }
.guide-step-text b { color: var(--ink); }
.guide-open { width: auto; justify-self: start; padding: 0 18px; text-decoration: none; }
.guide-paste { display: flex; gap: 8px; }
.guide-input {
flex: 1;
min-width: 0;
width: 100%;
height: 44px;
padding: 0 12px;
border: 1px solid var(--border);
border-radius: 8px;
background: var(--bg);
color: var(--ink);
font-size: 16px; /* below 16px iOS zooms the page on focus */
}
.guide-input::placeholder { color: var(--muted); }
.guide-input:focus { outline: none; border-color: var(--blue); }
.guide-start { width: auto; flex: none; min-height: 44px; padding: 0 18px; }
.guide-status:empty { display: none; }
.guide-status { display: grid; gap: 8px; }
.guide-msg { margin: 0; line-height: 1.5; }
.guide-msg.is-idle, .guide-msg.is-busy { color: var(--muted); }
.guide-msg.is-ok { color: var(--green-dark); }
.guide-msg.is-warn { color: var(--amber-dark); }
.guide-msg.is-error { color: var(--red); }
.guide-action { width: auto; justify-self: start; padding: 0 16px; }
.guide-progress { display: grid; gap: 6px; margin-top: 8px; color: var(--muted); font-size: 13px; }
@media (max-width: 720px) {
/* Already on a phone: the hand-off QR has nothing to add. */
.guide-qr { display: none; }
.guide-backdrop { align-content: start; padding: 12px; }
.guide { padding: 16px; }
}
/* ---------------- responsive ---------------- */
/* Wide screens (desktop, PS5 browser): bigger covers so a card doesn't look
empty. */
@media (min-width: 900px) {
.game-card { padding: 18px 20px; }
.cover { width: 104px; height: 104px; border-radius: 14px; font-size: 22px; }
.card-row { gap: 20px; }
.card-body h3 { font-size: 19px; margin-bottom: 8px; }
.subline { font-size: 13px; }
.versions { font-size: 13px; }
}
@media (max-width: 1024px) {
.app-shell { grid-template-columns: 1fr; }
.rail {