diff --git a/.github/workflows/promote.yml b/.github/workflows/promote.yml
new file mode 100644
index 0000000..3ca44c5
--- /dev/null
+++ b/.github/workflows/promote.yml
@@ -0,0 +1,55 @@
+name: promote
+
+# Hands a tested version to every PC (0.5.8). release.yml publishes a new version as a TEST version (a
+# pre-release), which installed PCs do not take by themselves because GitHub's "latest release" is never a
+# pre-release. Once it has been tried on the test PCs: Actions > promote > Run workflow. This turns the
+# pre-release into a full release, marks it as the latest and rewrites its text from CHANGELOG.md (on the branch
+# the workflow runs from) without the test note. PCs then offer it within a day (docs/releasing.md).
+
+on:
+ workflow_dispatch:
+ inputs:
+ version:
+ description: 'Version to hand to every PC, for example 0.5.8 (empty: the one in Directory.Build.props)'
+ required: false
+ default: ''
+
+permissions:
+ contents: write
+
+jobs:
+ promote:
+ name: Hand the tested version to every PC
+ runs-on: ubuntu-latest
+
+ steps:
+ - name: Check out
+ uses: actions/checkout@v4
+
+ - name: Make it a full release
+ shell: bash
+ env:
+ GH_TOKEN: ${{ github.token }}
+ REQUESTED: ${{ inputs.version }}
+ run: |
+ set -euo pipefail
+ version="${REQUESTED:-$(sed -n 's:.*\(.*\).*:\1:p' Directory.Build.props | head -n 1)}"
+ if ! [[ "$version" =~ ^[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
+ echo "::error::\"$version\" is not a version like 0.5.8."
+ exit 1
+ fi
+ tag="v$version"
+ if ! assets=$(gh release view "$tag" --json assets --jq '.assets[].name'); then
+ echo "::error::There is no release $tag. Publish it as a test version first (Actions, release, Run workflow)."
+ exit 1
+ fi
+ for name in "PrintVect-Setup-$version.exe" "PrintVect-Setup-$version.exe.sha256"; do
+ if ! grep -qxF "$name" <<<"$assets"; then
+ echo "::error::Release $tag lacks $name, so it cannot go to every PC. Run the release workflow for it again."
+ exit 1
+ fi
+ done
+ python3 tools/release_notes.py "$version" --out release-notes.md
+ gh release edit "$tag" --prerelease=false --latest --notes-file release-notes.md
+ echo "::notice::$tag is now the latest release: every PC that runs PrintVect offers it within a day."
+ echo "https://github.com/$GITHUB_REPOSITORY/releases/tag/$tag"
diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml
index 4746464..8159ba2 100644
--- a/.github/workflows/release.yml
+++ b/.github/workflows/release.yml
@@ -2,11 +2,16 @@ name: release
# Publishes a GitHub Release carrying the setup program. Every installed PrintVect looks at the latest
# release once a day (Settings tab, Updates) and offers it with one click, so this is how an update
-# reaches every PC. Three ways to start it (docs/releasing.md):
-# 1. on the GitHub website: Releases > Draft a new release, new tag v, target = the branch, Publish;
-# the setup program and its checksum are added to that release a few minutes later;
+# reaches every PC. Since 0.5.8 a new version is published as a TEST version (a pre-release) first:
+# GitHub's "latest release" is never a pre-release, so PCs do not install it by themselves. Once it has
+# been tried, Actions > promote > Run workflow hands it to every PC. Ways to start this one (docs/releasing.md):
+# 1. Actions > release > Run workflow (the tag is created from Directory.Build.props; "stage" picks a test
+# version, the default, or straight to every PC);
# 2. push a tag that matches in Directory.Build.props: git tag v0.2.0 && git push origin v0.2.0
-# 3. Actions > release > Run workflow (the tag is then created from Directory.Build.props).
+# (a test version);
+# 3. on the GitHub website: Releases > Draft a new release, new tag v, target = the branch, tick
+# "Set as a pre-release" for a test version, Publish; the setup program and its checksum are added later.
+# The release text is "what changed" from CHANGELOG.md (tools/release_notes.py), so write that section first.
# A version whose release already carries a setup program is left alone (warning in the run), so
# raise (all three lines in Directory.Build.props) before publishing the next one.
@@ -16,6 +21,12 @@ on:
release:
types: [published]
workflow_dispatch:
+ inputs:
+ stage:
+ description: 'test = a pre-release only the PCs you install it on get (promote it later); everyone = every PC at once'
+ type: choice
+ options: [test, everyone]
+ default: test
# A release made on the website fires both "push tag" and "release published": run them one after the other.
concurrency:
@@ -123,25 +134,41 @@ jobs:
shell: pwsh
env:
GH_TOKEN: ${{ github.token }}
+ # Run workflow picks the stage; a pushed tag makes a test version.
+ STAGE: ${{ github.event.inputs.stage || 'test' }}
run: |
$exe = "artifacts\installer\PrintVect-Setup-$env:VERSION.exe"
if ($env:EXISTING -eq '1') {
- # The release was made on the website: just add the files to it.
+ # The release was made on the website: add the files to it, and its text when none was typed.
gh release upload $env:TAG $exe "$exe.sha256" --clobber
if ($LASTEXITCODE -ne 0) { throw "gh release upload failed with exit code $LASTEXITCODE" }
+ $existing = gh release view $env:TAG --json body,isPrerelease | ConvertFrom-Json
+ if ([string]::IsNullOrWhiteSpace($existing.body)) {
+ $noteArgs = @($env:VERSION, '--out', 'release-notes.md')
+ if ($existing.isPrerelease) { $noteArgs += '--test' }
+ python tools/release_notes.py @noteArgs
+ if ($LASTEXITCODE -ne 0) { throw "tools/release_notes.py failed with exit code $LASTEXITCODE" }
+ gh release edit $env:TAG --notes-file release-notes.md
+ if ($LASTEXITCODE -ne 0) { throw "gh release edit failed with exit code $LASTEXITCODE" }
+ }
} else {
- $notes = "PrintVect $env:VERSION`n`n" +
- "PrintVect shares a printer with every Windows PC and laptop on your network, at home or in the office, " +
- "with no printer driver to install and no Windows password on the PCs that print. " +
- "What it does and how to use it: https://github.com/rahulranjan-dev-py/PrintVect#readme`n`n" +
- "Download **PrintVect-Setup-$env:VERSION.exe** and run it on a PC that does not have PrintVect yet. " +
- "PCs that already run PrintVect find this version by themselves within a day (Settings tab, Updates) " +
- "and install it with one click.`n`n" +
- "The .sha256 file is the checksum PrintVect verifies after downloading."
+ $test = $env:STAGE -ne 'everyone'
+ $noteArgs = @($env:VERSION, '--out', 'release-notes.md')
+ if ($test) { $noteArgs += '--test' }
+ python tools/release_notes.py @noteArgs
+ if ($LASTEXITCODE -ne 0) { throw "tools/release_notes.py failed with exit code $LASTEXITCODE" }
# Draft first, then publish: the release never shows up without its files.
- gh release create $env:TAG --target $env:GITHUB_SHA --title "PrintVect $env:VERSION" --notes $notes --draft $exe "$exe.sha256"
+ gh release create $env:TAG --target $env:GITHUB_SHA --title "PrintVect $env:VERSION" --notes-file release-notes.md --draft $exe "$exe.sha256"
if ($LASTEXITCODE -ne 0) { throw "gh release create failed with exit code $LASTEXITCODE" }
- gh release edit $env:TAG --draft=false
+ if ($test) {
+ # A pre-release is never GitHub's "latest release", which is what installed PCs ask for.
+ gh release edit $env:TAG --draft=false --prerelease
+ } else {
+ gh release edit $env:TAG --draft=false --latest
+ }
if ($LASTEXITCODE -ne 0) { throw "gh release edit failed with exit code $LASTEXITCODE" }
+ if ($test) {
+ Write-Host "::notice::Published TEST version $env:TAG (pre-release): installed PCs do not take it by themselves. Once it works: Actions, promote, Run workflow."
+ }
}
Write-Host "Published https://github.com/$env:GITHUB_REPOSITORY/releases/tag/$env:TAG"
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 6db1923..fe7d3fc 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -4,7 +4,46 @@ Newest first. Each version is a [release](https://github.com/rahulranjan-dev-py/
program; PCs that run PrintVect offer the newest one by themselves (Settings, Updates). **Tested** says how far the
version was tried on the office's PCs (Windows 10 and 11).
-## 0.5.7
+## 0.5.8
+
+Security fixes from a review of the design.
+
+The sharing PIN is harder to steal and to guess. It never crosses the network any more, not even as the plain
+SHA-256 hash earlier versions sent, which anyone watching the network could reuse as the password forever. Each job
+carries a one-time proof of the PIN instead: it is made for that job only and works for nothing else. A PC that sends
+5 wrong PINs has to wait 15 minutes before the PC with the printer checks its PIN again, twice as long each further
+time (at most 4 hours). With a PIN, the list of PCs that print here only shows PCs that know the PIN. **Update every
+PC**: with a sharing PIN, a PC on 0.5.7 and a PC on 0.5.8 cannot print to each other.
+
+Another PC can no longer take over a printer by answering with the same PC name when the real one has moved or is
+switched off. Each PC that shares printers now has its own secret identity key, and every PC that adds one of its
+printers remembers it (printers added before learn it within a few minutes). A printer follows its PC to a new address
+only when the PC there proves it holds that key; otherwise nothing is sent and the job says why.
+
+The administrator helper can no longer be tricked through the shared data folder: every user may write in
+`C:\ProgramData\PrintVect`, so another user could put a link (junction) there that leads to a Windows folder and wait
+for the helper to give "Users: Modify" rights or delete files through it. The helper now refuses to create, change or
+delete anything through such a link and says what to remove.
+
+A PC that shares printers can no longer be flooded: it serves at most 32 connections at once (8 from one PC, and 120
+new ones a minute from one PC), closes a connection that sends nothing within 15 seconds, keeps at most 1 GB of
+documents waiting and stops taking more when its disk is nearly full (the job waits for Retry on the sending PC). A
+file that is not a print document is deleted at once, and files kept after a failed print are deleted after a day,
+checked every hour instead of only when sharing starts.
+
+Updates are checked more strictly: a release without its checksum file is no longer installed (it used to install
+after a size check only), and the downloaded setup program, which sits in a folder every user may write to, is held
+so nobody can change it and checked again just before it starts.
+
+New versions are published as test versions first: they reach only the PCs they are installed on by hand, and every
+other PC gets them once they are handed over (Actions, promote). The release text now says what changed, taken from
+this file.
+
+The sharing PIN is no longer written in plain text in `config.json` (which every user of the PC can open): it is kept
+protected by Windows for that PC, and a PIN saved by an earlier version is converted at the first start. The 10.8 MB
+demo video left the repository's files; the README plays the copy uploaded to GitHub. **Tested:** awaiting test.
+
+## 0.5.7 (2026-10-29)
The copies window: it opens about 2 to 3 seconds sooner after a program prints (the PC now looks at the finished
print file within half a second instead of waiting for its 2-second check), it is as tall as its content so the
diff --git a/CLAUDE.md b/CLAUDE.md
index 2049694..fa9a239 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -10,7 +10,7 @@ docs/brief.md. Wire protocol: docs/protocol.md. Manual tests: docs/testing.md.
- No NuGet in shipped code except Newtonsoft.Json. Test-only packages: MSTest. Ask before adding anything.
- Printing and discovery are LAN only. The one internet call (owner's request, 2026-10-09) is the update check:
Core/Update/UpdateChecker asks GitHub Releases of this repo over HTTPS (daily + Check now, off switch in Settings),
- downloads PrintVect-Setup-.exe, verifies size + .sha256, runs it /SILENT (UAC prompt; the setup ends the app
+ downloads PrintVect-Setup-.exe, verifies size + .sha256 (no .sha256 = no update; held open and re-hashed just before it starts, 0.5.8), runs it /SILENT (UAC prompt; the setup ends the app
and restarts it). No telemetry, no crash reporting, nothing else leaves the office.
- Host role runs as a tray app in the logged-in user's session, never as a Windows Service
(System.Printing does not work in Session 0).
@@ -18,7 +18,7 @@ docs/brief.md. Wire protocol: docs/protocol.md. Manual tests: docs/testing.md.
- Protocol identifiers: discovery text `PVECT-DISCOVER 1`, TCP magic `PVCT`, `"app":"PrintVect"`.
- All admin work lives in src/PrintVect.Elevate (requireAdministrator manifest, launched with
ShellExecute "runas"). PrintVect.App is asInvoker and runs as a standard user.
-- Data in %ProgramData%\PrintVect\ : config.json, spool\, logs\ (daily files, keep 14 days), jobs-host.json and
+- Data in %ProgramData%\PrintVect\ : config.json (PIN and host key DPAPI-protected for the PC, 0.5.8), spool\, logs\ (daily files, keep 14 days), jobs-host.json and
jobs-client.json (job history, last 200, saved a second after a change), updates\ (downloaded setup + its log).
- All user-visible text lives in src/PrintVect.App/Strings.resx from day one (Hindi is Phase 2).
- MIT licence (LICENSE in repo root).
@@ -34,7 +34,7 @@ docs/brief.md. Wire protocol: docs/protocol.md. Manual tests: docs/testing.md.
PrintVect-test-page.xps is a ready-made one-page test file (tools/make_test_page.py rebuilds it).
- src/PrintVect.Elevate tiny console exe, requireAdministrator. Commands add-printer, remove-printer, remove-all
(XcvData AddPort/DeletePort on the Local Port monitor, AddPrinter, DeletePrinter, Users:Modify ACL
- on spool\; when no XPS writer driver is installed it installs Windows' own from the driver store
+ on spool\ via a handle; SafeFolders refuses junctions/links in the data folder, 0.5.8; when no XPS writer driver is installed it installs Windows' own from the driver store
(InstallPrinterDriverFromPackage) or turns on the feature with DISM Printing-XPSServices-Features);
autostart /on yes|no (HKLM Run); network-private /networks (0.5.0). Result: exit code + JSON.
- tests/PrintVect.Tests MSTest, net48. Unit-tests framing, discovery JSON, config, file-stability, updates (loopback HTTP).
@@ -51,8 +51,9 @@ because it writes .xps; v4 writes .oxps; Local Port -> spool\\job.xps) -> Sp
polling, re-checks within 0.5 s; taken when exclusively openable and size stable 0.5 s) -> rename to job-.xps/.oxps
(XpsFormatSniffer looks inside: namespace openxps.org = oxps; it also reads the docProps title; the v4 writer stores
none, so the document name comes from EnumJobs on the virtual printer while the port writes) -> ClientService sends
-(3 tries, each IP then PC name; after the first failure one 3 s discovery search follows a host that moved (0.5.0);
-then pending\ and Retry resends under the same job id; sent\ kept 1 h, failed\ last 20) and polls status.
+(3 tries, each IP then PC name; after the first failure one 3 s discovery search follows a host that moved (0.5.0); a new address or the name's
+address is used only once it signs a challenge with the host key remembered for the printer (0.5.8, HostIdentity, MovedHostCheck); then pending\
+and Retry resends under the same job id; sent\ kept 1 h, failed\ last 20) and polls status.
Host: receive into spool\incoming\ -> verify size, sniff the real format -> HostPrintEngine -> reply JSON -> watch the
job (up to 60 s before replying). One job at a time per printer, arrival order, on that printer's worker thread (never
the UI thread). Printer statuses and printing sit behind IPrinterStatusSource / IPrintEngine so HostService is
@@ -63,23 +64,22 @@ unit-tested with fakes over loopback TCP (tests never load System.Printing, whic
page is open, and once when a job cannot reach its host; hosts reply by UDP unicast with a JSON printer list.
- Job: TCP 9151, one job per connection: `PVCT` + 4-byte LE header length + UTF-8 JSON header + file bytes. Host
answers one JSON line ({ok, jobId, state, message}) and closes. Status: header {"type":"status","jobId"}, no body.
-- List: header {"type":"list"}, reply = discovery JSON + ok. Hello (M6b-2): {"type":"hello",client,os,appVersion,
+- List: header {"type":"list"}, reply = discovery JSON (with hostKey; hostSig when the request has a challenge, 0.5.8) + ok. Hello (M6b-2): {"type":"hello",client,os,appVersion,
printers} every 5 min to each host used -> its "PCs that use this PC". Refusals: drained, ok=false; "retry":true =
keep for Retry (lost job, PIN). A job id already printed or still queued gets its state back, never printed twice.
-- Sharing PIN: header carries its SHA-256 hex; empty = open on the LAN. Limits: file 200 MB, connect 5 s, transfer 5 min,
- discovery 2 s. Manual IP/name entry always exists.
+- Sharing PIN (0.5.8, PinProof): job and hello carry nonce, time, pinProof = PBKDF2-SHA256(PIN, salt nonce/time/printer/jobId/size, 20000);
+ time within 24 h; the old plain hash "pin" is refused; 5 wrong per address -> wait 15 min, doubling to 4 h (PinAttemptLimiter).
+ Empty PIN = open on the LAN. Limits: file 200 MB, connect 5 s, header 15 s, transfer 5 min, discovery 2 s; host (0.5.8, ConnectionLimiter): 32 connections, 8 per address, 120/min per address; incoming <= 1 GB and 256 MB disk free (unused files evicted first, else retry), non-XPS deleted, unused files gone after 24 h (hourly). Manual IP/name entry always exists.
## Workflow
- One milestone at a time (M0..M6 in the brief, section 9). Finish, build, hand over test steps,
then wait for the owner's result before starting the next one. M4 (Windows 7 pass) is skipped:
the office has no Windows 7 PC (owner, 2026-10-06); keep Windows 7 paths only where they cost nothing. M6: M6a
- updates, M6b-1 new look, M6b-2 hardening; then 0.4.1 (jobs menu), 0.5.0 (redesign, colours, hotspot), 0.5.1-0.5.3 (look fixes), 0.5.4, 0.5.5 (no office words: homes too), 0.5.6 (menu fits), 0.5.7 (copies window).
-- Build: `msbuild PrintVect.sln /p:Configuration=Release` (VS 2022 Build Tools + .NET Framework
- 4.8 targeting pack). `dotnet build PrintVect.sln -c Release` also works with the .NET 8 SDK.
-- Tests: `dotnet test tests/PrintVect.Tests/PrintVect.Tests.csproj -c Release`. CI: .github/workflows/build.yml
- (windows-latest) builds, tests, makes the setup program; release.yml publishes a release (Run workflow on main).
-- Claude Code cannot see a printer or run Windows print APIs: design every feature so the owner can verify it from a
- log file or Diagnostics, and log every job step with its jobId on both sides.
+ updates, M6b-1 new look, M6b-2 hardening; then 0.4.1 (jobs menu), 0.5.0 (redesign, colours, hotspot), 0.5.1-0.5.3 (look fixes), 0.5.4, 0.5.5 (no office words: homes too), 0.5.6 (menu fits), 0.5.7 (copies window), 0.5.8 (security review: PIN proof, host identity, Elevate link guard, host flood limits, strict updates, test releases).
+- Build: `msbuild PrintVect.sln /p:Configuration=Release` (VS 2022 Build Tools + .NET Framework 4.8 targeting pack); `dotnet build PrintVect.sln -c Release` (.NET 8 SDK) too.
+- Tests: `dotnet test tests/PrintVect.Tests/PrintVect.Tests.csproj -c Release`. CI: .github/workflows/build.yml (windows-latest) builds, tests, makes the setup program;
+ release.yml publishes a TEST version (pre-release, never "latest", so PCs skip it; text = CHANGELOG section via tools/release_notes.py); promote.yml makes it the latest release for every PC (0.5.8).
+- Claude Code cannot see a printer or run Windows print APIs: design every feature so the owner can verify it from a log file or Diagnostics, and log every job step with its jobId on both sides.
- Commit after each milestone: `M2: client virtual printer and spool watcher`.
- Files under %ProgramData% belong to the user who created them: the installer grants Users modify rights on
%ProgramData%\PrintVect, and the logger still falls back to PrintVect--.log if a file is not writable.
diff --git a/Directory.Build.props b/Directory.Build.props
index 47b5f82..5b9a605 100644
--- a/Directory.Build.props
+++ b/Directory.Build.props
@@ -12,9 +12,9 @@
en
- 0.5.7
- 0.5.7.0
- 0.5.7.0
+ 0.5.8
+ 0.5.8.0
+ 0.5.8.0
PrintVect
PrintVect
PrintVect contributors
diff --git a/README.md b/README.md
index 58fbfdd..48a7710 100644
--- a/README.md
+++ b/README.md
@@ -104,7 +104,9 @@ report to copy.
- Finding printers (UDP 9150) and print jobs (TCP 9151) stay on your local network. The setup program opens those
ports in Windows Firewall for PrintVect only, on private and domain networks only, never on public ones.
- Without a sharing PIN, any PC on the same network can print to the shared printers; set the same PIN on every
- PC to limit that (Settings, Security). Print jobs are not encrypted on the network.
+ PC to limit that (Settings, Security). The PIN itself never crosses the network: each job carries a one-time
+ proof of it, and a PC that sends 5 wrong PINs has to wait. Longer PINs (8 or more characters) are harder to guess.
+ Print jobs are not encrypted on the network.
- PrintVect runs as a normal user. Only its small helper, `PrintVect.Elevate.exe`, asks for administrator rights,
for the few tasks that need them: adding or removing a printer, starting with Windows, making a network private.
- The only internet connection is the update check: once a day PrintVect asks GitHub for this repository's latest
@@ -133,7 +135,10 @@ Requirements:
- Chrome or Edge may hold the download back; choose **Keep** in the downloads list (Ctrl+J).
- On a Windows 11 PC with Smart App Control On (Windows Security, App & browser control) Windows refuses to run the
unsigned setup program ("An Application Control policy has blocked this file"), including through Update now.
-- The `.sha256` file next to each setup program is its checksum; PrintVect checks it before installing an update.
+- The `.sha256` file next to each setup program is its checksum; PrintVect checks it before installing an update,
+ installs no release without one, and checks the downloaded file once more, held so nobody can change it, just
+ before it starts. The checksum comes from the same GitHub release, so it proves the file arrived intact, not who
+ made it: only code signing (see CODE_SIGNING.md) would.
## Using it
@@ -256,6 +261,10 @@ netsh advfirewall firewall add rule name="PrintVect Discovery (UDP-In)" dir=in a
| "The update did not run (the setup program ended with code ...)" | The Windows permission question was answered No, or the setup failed: the reason is in `C:\ProgramData\PrintVect\updates\update-.log`. Press **Update now** again. |
| After an update PrintVect did not come back | Start it from the Start menu; the update itself is complete. Tell the person who supports PrintVect which version the window shows. |
| A job waits with "asks for the sharing PIN" | The two PCs have different sharing PINs (or one has none). Set the same PIN in Settings on both, then press **Retry waiting** (Printers on other PCs) on the PC that printed. |
+| A job waits with "Too many wrong sharing PINs" | That PC sent 5 wrong PINs, so the PC with the printer ignores it for the minutes the message names (longer each time). Set the same PIN on both PCs, wait, then press **Retry waiting**. |
+| A job waits with "it is not ..., the PC this printer was added from" | A PC answered with the name of the PC that has the printer but could not prove it is that PC, so nothing was sent to it. If the PC with the printer was set up again (new Windows, or PrintVect removed and installed again), remove its printer on this PC and add it again (Printers on other PCs). |
+| A job waits with "runs a PrintVect older than 0.5.8" | The PC with the printer has a sharing PIN and the PC that printed has an old PrintVect. Update it (Settings, Updates, Check now), then press **Retry waiting**. |
+| A job waits with "already holds ... of documents waiting to print" or "is nearly full" | The PC with the printer has 1 GB of documents waiting (a paused printer?) or little disk space left. Resume the printer or free some space on that PC, then press **Retry waiting**. |
| A job waits with "is paused there" | Someone pressed **Pause** on the PC that has the printer. Press **Resume** there (Share my printers). |
| A job waits with "stopped answering after it received this job" | The PC with the printer was switched off or lost the network during the job. When it is back, check whether the page came out; if not, press **Retry waiting** (or right-click the job, **Retry**). A page that already printed is never printed twice. |
| Update now says jobs are still being handled | A shared printer is paused with jobs waiting. Resume it (or wait until they printed), then press Update now again. |
diff --git a/SECURITY.md b/SECURITY.md
index 074ea64..fcf0d50 100644
--- a/SECURITY.md
+++ b/SECURITY.md
@@ -17,7 +17,23 @@ These are known limits of the design, not vulnerabilities:
- PrintVect is meant for a trusted home or office network. Its ports (UDP 9150, TCP 9151) are opened in Windows Firewall on
private and domain networks only.
-- Without a sharing PIN, any PC on the same network can print to the shared printers. With a PIN, every job must carry
- the PIN's SHA-256 hash. Print jobs are not encrypted on the network.
+- Without a sharing PIN, any PC on the same network can print to the shared printers. With a PIN (0.5.8), every job and
+ hello carries a one-time proof of it (PBKDF2-SHA256 salted with that request), never the PIN or a plain hash of it,
+ and a PC that sends 5 wrong PINs must wait 15 minutes, twice as long each further time. Someone who records the
+ network traffic can still try to guess a short PIN offline, so use 8 or more characters where that matters. Print
+ jobs are not encrypted on the network.
+- config.json keeps the PIN and the PC's identity key protected with Windows DPAPI for that PC (0.5.8), so they do not
+ show in the file or in a copy taken elsewhere. Any program running on that PC can still read them back, so the PIN
+ protects against other PCs, not against other people who use the same PC.
+- A PC name and printer ids can be claimed by any PC on the network. Since 0.5.8 a printer follows its host to a new
+ address only when the PC there proves, by signing a random challenge with the host's identity key, that it is the
+ PC the printer was added from. Someone who can intercept the network traffic itself (not just answer on it) is
+ outside what PrintVect can stop.
+- Every user may write in `C:\ProgramData\PrintVect`. The administrator helper (`PrintVect.Elevate.exe`) checks that no
+ folder it creates, gives rights on, deletes or writes its log and result in is a junction or symbolic link, and
+ gives the spool folder its rights through a handle to the folder it checked (0.5.8).
- The setup program and the program files are not code-signed yet (see [CODE_SIGNING.md](CODE_SIGNING.md)); the
- updater checks each downloaded setup program's size and SHA-256 against the release before running it.
+ updater checks each downloaded setup program's size and SHA-256 against the release before running it. The checksum
+ file comes from the same GitHub release, so it catches a damaged download, not a release replaced by someone who
+ took over the repository. Since 0.5.8 a release without a checksum file is not installed, and the setup program is
+ held open (nobody can change, delete or rename it or its folder) and checked again just before it starts.
diff --git a/docs/media/printvect-demo-poster.jpg b/docs/media/printvect-demo-poster.jpg
deleted file mode 100644
index ca0bdfc..0000000
Binary files a/docs/media/printvect-demo-poster.jpg and /dev/null differ
diff --git a/docs/media/printvect-demo.mp4 b/docs/media/printvect-demo.mp4
deleted file mode 100644
index 97362ec..0000000
Binary files a/docs/media/printvect-demo.mp4 and /dev/null differ
diff --git a/docs/protocol.md b/docs/protocol.md
index dd06d36..9dadfa7 100644
--- a/docs/protocol.md
+++ b/docs/protocol.md
@@ -27,7 +27,7 @@ relay) and **631** are never allowed.
| Job transfer | TCP 9151, one job per connection | `PVCT` (4 ASCII bytes), 4-byte little-endian header length, UTF-8 JSON header, then the raw file bytes. The host answers one JSON line, then closes. |
| Status query | TCP 9151 | Same framing with header `{"type":"status","jobId":"guid"}` and no body. Same reply format. |
| Printer list | TCP 9151 | Same framing with header `{"type":"list","v":1}` and no body. The host answers the discovery-reply JSON below plus `"ok":true`. Used by `pvct-send list` and by manual "Add by IP" (M3), which cannot rely on UDP broadcast. |
-| Hello (presence) | TCP 9151 | Same framing with header `{"type":"hello","v":1,"client":"COUNTER3","user":"clerk","os":"Windows 10 Pro 22H2 (build 19045.4894)","appVersion":"0.4.0","printers":["…"]}` and no body (0.4.0, M6b-2). A client sends it 15 s after start, after adding a printer, and every 5 minutes to each host whose printers it has added. The host answers `{"ok":true,"message":"…"}` and lists the PC on its Share page; a job also marks its PC as seen. A host before 0.4.0 answers ok=false ("unknown request type"), which the client ignores. |
+| Hello (presence) | TCP 9151 | Same framing with header `{"type":"hello","v":1,"client":"COUNTER3","user":"clerk","os":"Windows 10 Pro 22H2 (build 19045.4894)","appVersion":"0.4.0","printers":["…"]}` and no body (0.4.0, M6b-2). A client sends it 15 s after start, after adding a printer, and every 5 minutes to each host whose printers it has added. The host answers `{"ok":true,"message":"…"}` and lists the PC on its Share page; a job also marks its PC as seen. A host before 0.4.0 answers ok=false ("unknown request type"), which the client ignores. With a sharing PIN (0.5.8) the hello carries `nonce`, `time` and `pinProof` like a job; a host with a PIN lists only PCs that prove it, and a client whose hello is refused sends that host no more hellos until its PIN changes or it restarts. |
## Discovery reply
@@ -40,10 +40,28 @@ relay) and **631** are never allowed.
"port": 9151,
"printers": [
{ "id": "…", "name": "HP LaserJet 1020", "friendly": "Counter 1 Laser", "status": "ready" }
- ]
+ ],
+ "hostKey": "base64 RSA public key (0.5.8)"
}
```
+### Host identity (0.5.8)
+
+A PC name and printer ids travel openly, so any PC could claim them. Each host therefore makes an RSA-2048 identity
+key on first start (kept in its `config.json`, protected with Windows DPAPI for that PC) and sends the public half as
+`hostKey` (an RSA CSP blob in base64) in discovery and list replies. A list request may carry `"challenge"` (32 hex
+digits); the reply then has `"hostSig"`: base64 RSA-SHA256 (PKCS#1 v1.5) signature of the UTF-8 text
+`PrintVect host 1`, the challenge, the host name in capitals and the address the request reached (as the host's
+socket sees it), joined by line feeds.
+
+A client remembers the key's fingerprint (SHA-256 of the blob, hex) with each printer: when the printer is added,
+proven with a challenge at the address it is added with, or, for printers added before 0.5.8, after the host's next
+answered hello, proven the same way at the printer's own address. Before a printer follows its host to a new
+address (discovery, or the search after a job could not reach it), the PC there must sign a fresh challenge for that
+address with the remembered key; one that claims the host's name or printers without it gets no jobs, and the job
+says why. A printer with no key yet remembers the first one proven to it; a host before 0.5.8 (no key) is followed
+as before. The signed address stops a PC from passing on the real host's answer from elsewhere.
+
## Job header
```json
@@ -58,10 +76,22 @@ relay) and **631** are never allowed.
"client": "COUNTER3",
"user": "user1",
"doc": "optional document title",
- "pin": "sha256-hex of the shared PIN, or empty"
+ "nonce": "32 hex digits, new for every request (only with a sharing PIN)",
+ "time": 1793260800,
+ "pinProof": "64 hex digits (only with a sharing PIN)"
}
```
+The sharing PIN never travels (0.5.8). With a PIN set, the sender makes a one-time proof just before it sends:
+`pinProof` = lowercase hex of PBKDF2-HMAC-SHA256 (20,000 rounds, 32 bytes) with the PIN in UTF-8 as the password and
+as salt the UTF-8 text `PrintVect PIN 1`, type, nonce, time, printerId, jobId and size, joined by line feeds (an
+absent field is empty). `time` is in seconds since 1970 (UTC); the host refuses a proof more than 24 hours away from
+its own clock, and one made for another job, printer or size does not match. A host with a PIN refuses a request
+without a proof with `retry:true`; a request with only the `pin` field of earlier versions (SHA-256 of the PIN) is
+refused with a message to update the sender. After 5 wrong proofs from one address the host refuses that address for
+15 minutes without checking, twice as long after each further 5 (at most 4 hours); a right PIN or a day without a
+wrong one starts afresh. A hello proves the PIN the same way (with `printerId`, `jobId` and `size` empty and 0).
+
`copies` (optional, default 1, at most 99) asks the host to print the document that many times; the client
fills it from the XPS print ticket inside the file (`JobCopiesAllDocuments`), which Word and Excel set when the
user chooses copies. A host that receives no `copies` reads the ticket itself.
@@ -102,11 +132,17 @@ printer name (case-insensitive), so a person can type a name into `pvct-send`.
## Rules
-- Optional sharing PIN (the office PIN until 0.5.4), set in Settings on both sides (Set PIN…, 0.4.0). The header carries the
- SHA-256 of the PIN; the host rejects a mismatch with a clear message and `retry:true`.
- An empty PIN means open to the LAN.
+- Optional sharing PIN (the office PIN until 0.5.4), set in Settings on both sides (Set PIN…, 0.4.0). Each job and
+ hello carries a one-time proof of it (0.5.8; before: its SHA-256); the host rejects a mismatch with a clear message
+ and `retry:true`, and makes an address that sent 5 wrong PINs wait. An empty PIN means open to the LAN.
- Limits: max file 200 MB, connect timeout 5 s, transfer timeout 5 min,
discovery timeout 2 s.
+- Host limits (0.5.8): the request header must arrive within 15 s of connecting; at most 32 connections are served at
+ once, 8 from one address, and 120 new ones a minute from one address (more are closed at once, logged once a minute).
+ Received documents may take at most 1 GB in `spool\incoming\`, and a job is refused when it would leave less than
+ 256 MB free on that disk; older files no job waits for are deleted first to make room, and a refused job gets
+ `retry:true`. A file that is not XPS is deleted at once; files kept after a failed print are deleted after 24 hours
+ (checked every hour).
- Manual host entry (IP or PC name) is always available, because UDP
broadcast does not cross subnets or VLANs.
- Every job step is logged with its `jobId` on both sides, so a failed job
@@ -119,6 +155,6 @@ printer name (case-insensitive), so a person can type a name into `pvct-send`.
| Framing + JSON classes (`Core/Protocol`) | M1 | done |
| TCP job, status and list requests (host) | M1 | done |
| Client sender (`JobClient`, pvct-send) | M1 | done |
-| PIN check on the host | M1 | done; PIN screen in Settings since M6b-2 |
+| PIN check on the host | M1 | done; PIN screen in Settings since M6b-2; one-time proof and wrong-PIN wait since 0.5.8 |
| UDP discovery | M3 | done |
| Hello (presence), `retry`, paused status, resend not printed twice | M6b-2 | done |
diff --git a/docs/releasing.md b/docs/releasing.md
index 1c3f67a..7283e87 100644
--- a/docs/releasing.md
+++ b/docs/releasing.md
@@ -1,25 +1,53 @@
# Publishing a new version
PCs that run PrintVect look at this repository's **latest release** once a day and offer it with one
-click, so an update reaches the office by making a release. First the version number must go up:
-raise the three version lines in `Directory.Build.props` (for example `0.2.0` to `0.2.1`), commit,
-push, and wait for the green build. Then, on the GitHub website:
-
-1. Open `https://github.com/rahulranjan-dev-py/PrintVect/releases/new`.
-2. Click **Choose a tag**, type `v0.2.1`, then click **Create new tag: v0.2.1 on publish**.
-3. Click **Target: main** and pick the branch that has the new version. Do not skip this.
-4. In **Release title** type `PrintVect 0.2.1`. Leave everything else as it is.
-5. Click **Publish release**.
-6. Wait five minutes and refresh: the release now lists `PrintVect-Setup-0.2.1.exe` and
- `PrintVect-Setup-0.2.1.exe.sha256`, built and attached by GitHub (Actions, run named **release**).
-
-Until the files are there, the PCs report "release v0.2.1 has no PrintVect-Setup file attached" and
-try again later. Drafts and pre-releases are ignored by the PCs. A release whose version already has
-a setup program is left alone (the run only warns), so the version number must always go up first.
-For people with git, pushing a tag (`git tag v0.2.1 && git push origin v0.2.1`) does the same, and so
-does **Actions**, **release**, **Run workflow** once the workflow file is on the default branch.
+click, so an update reaches every PC by making a release. GitHub's "latest release" is never a
+**pre-release**, and that is how a new version is tried first (0.5.8): it is published as a **test
+version** (a pre-release) that only the PCs you install it on get, and handed to every PC once it works.
+
+## 1. Get the version ready
+
+1. Raise the three version lines in `Directory.Build.props` (for example `0.2.0` to `0.2.1`).
+2. Write what changed under a heading `## 0.2.1` at the top of `CHANGELOG.md`, ending with
+ `**Tested:** awaiting test.` This text becomes the release text, so write it for the people who use PrintVect.
+3. Commit, push, and wait for the green build (a pull request merged into `main`).
+
+## 2. Publish it as a test version
+
+On GitHub: **Actions**, **release**, **Run workflow**, branch `main`, stage **test**, **Run workflow**.
+Five minutes later the release `v0.2.1` is there, marked **Pre-release**, with `PrintVect-Setup-0.2.1.exe`,
+`PrintVect-Setup-0.2.1.exe.sha256` and the text from `CHANGELOG.md` under a "Test version" note.
+
+PCs that run PrintVect do **not** take it by themselves. On each PC you test on, download
+`PrintVect-Setup-0.2.1.exe` from that release and run it: it updates PrintVect in place and keeps the
+settings and added printers. Follow the steps for that version in `docs/testing.md`.
+
+## 3. Hand it to every PC
+
+When the test PCs work: change `**Tested:** awaiting test.` in `CHANGELOG.md` to what was tested (for example
+`**Tested:** Windows 10 and 11, 2026-11-02.`) and get that onto `main`. Then **Actions**, **promote**,
+**Run workflow**, branch `main` (leave the version empty for the one in `Directory.Build.props`, or type it).
+The release loses its Pre-release mark, becomes the latest release, and its text is written again from
+`CHANGELOG.md` without the test note. The same can be done on the release page (Edit, untick
+"Set as a pre-release", tick "Set as the latest release", Update release), but then the text stays as it was.
On each PC, PrintVect then shows a balloon and a yellow strip "A newer PrintVect (0.2.1) is ready to
-install". **Update now** downloads the setup program into `C:\ProgramData\PrintVect\updates\`, checks
-its size and SHA-256, and runs it silently; Windows asks the usual permission question once, PrintVect
+install" within a day. **Update now** downloads the setup program into `C:\ProgramData\PrintVect\updates\`,
+checks its size and SHA-256 (a release without its `.sha256` is not installed, 0.5.8), checks the file again
+just before it starts, and runs it silently; Windows asks the usual permission question once, PrintVect
closes for a few seconds and opens again as the new version. Nothing is installed without that click.
+
+## Other ways, and what to know
+
+- **Straight to every PC** (an urgent fix): **Run workflow** with stage **everyone**. Use it rarely: the version
+ then reaches every PC within a day untried.
+- **Pushing a tag** (`git tag v0.2.1 && git push origin v0.2.1`) makes a test version, as Run workflow does.
+- **On the GitHub website**: Releases, **Draft a new release**, **Choose a tag** `v0.2.1` (**Create new tag on
+ publish**), **Target** = the branch with the new version, title `PrintVect 0.2.1`, tick **Set as a
+ pre-release** for a test version, **Publish release**. The setup program and its checksum are attached a few
+ minutes later (Actions, run named **release**), and the text from `CHANGELOG.md` when none was typed. Until the
+ files are there, the PCs report "release v0.2.1 has no PrintVect-Setup file attached" and try again later.
+- A release whose version already has a setup program is left alone (the run only warns), so the version number
+ must always go up first. Drafts and pre-releases are ignored by the PCs.
+- The release text comes from `tools/release_notes.py`: it fails the run when `CHANGELOG.md` has no section for
+ the version, so nothing is published without saying what changed.
diff --git a/docs/testing.md b/docs/testing.md
index f3c9172..1c9c236 100644
--- a/docs/testing.md
+++ b/docs/testing.md
@@ -636,6 +636,107 @@ while a file waits, and half a second of no change is enough (the file must stil
| 4 | Print again, turn on **Don't ask again on this PC**, Print. Print once more. | The first job prints; the next one goes without the window. Settings, General: **Ask how many copies** is off. Turn it on: the window is back for the next job. |
| 5 | Open the newest log in `C:\ProgramData\PrintVect\logs\`. | For the job of step 2: "Print job … is being written", then "New print job for …" about a second later or less (0.5.6: up to 4), then "Copies question: 2." |
+## 0.5.8: security fixes from the review
+
+The owner's security review of 2026-10-29 listed six problems; they are fixed one by one in this version, and each has
+its own steps below. Tell me to publish v0.5.8 once all are done, then on **every** PC: Settings, Check now, Update now.
+
+### 1. The sharing PIN never crosses the network
+
+The PIN travelled as its plain SHA-256 hash, which worked as the
+password forever for anyone who saw it, and the host never slowed down wrong guesses. Now each job and hello carries a
+one-time proof of the PIN (made for that job, printer and size, valid for a day), and after 5 wrong PINs from one PC
+the host checks that PC's PIN again only after 15 minutes, then 30, 60, up to 4 hours. A right PIN starts afresh.
+Use two PCs that both have a sharing PIN: HOST has the printer, CLIENT prints.
+
+| # | Do this | Expect this |
+|---|---------|-------------|
+| 0 | Tell me to publish v0.5.8. On **every** PC: Settings, Check now, Update now. | "Version 0.5.8 · up to date" under the menu. With a PIN, PCs on 0.5.7 and 0.5.8 cannot print to each other until both are updated. |
+| 1 | Same PIN on both. Print a page from Notepad on CLIENT. | It prints as before. HOST's log: "Job from …", then "File received". |
+| 2 | HOST: Share my printers, "PCs that use this PC". | CLIENT is listed (within 5 minutes of its start). |
+| 3 | CLIENT: Settings, Security, Change PIN to a different one. Print a page. | The job waits: "HOST asks for the sharing PIN, and this job came with a different one." HOST's log: "Wrong sharing PIN from CLIENT (192.168.…); 4 more wrong tries before it has to wait." |
+| 4 | On CLIENT press **Retry waiting** until the message changes (at most 4 more times). | "Too many wrong sharing PINs came from CLIENT, so HOST checks its PIN again in 15 minutes." HOST's log: "… it waits 15 minutes before its PIN is checked again." The hello CLIENT sends every 5 minutes also counts, so this may come sooner. |
+| 5 | CLIENT: set the right PIN again; press Retry waiting at once. | Still "Too many wrong sharing PINs … in 15 minutes" (or fewer): the wait holds even for the right PIN. To skip it: Exit PrintVect on HOST and start it again. |
+| 6 | After the wait (or the restart), press Retry waiting. | The job prints. CLIENT's log: "Presence: HOST refused the hello (…)" from step 3, and from now on hellos are answered again. |
+| 7 | (If a PC with 0.5.7 is still around) print from it to HOST. | The job waits: "… runs a PrintVect older than 0.5.8 … Update PrintVect on …". |
+
+### 2. Only the real host is followed to a new address
+
+When a job could not reach its host, PrintVect followed any PC that answered with the host's PC name or printer ids,
+which travel openly, and sent the document (and the PIN check) there. Now each host has a secret identity key, made
+on its first start of 0.5.8 and kept in its config.json protected for that PC, and a printer follows its host only
+when the PC at the new address signs a random challenge with the key remembered for that printer.
+
+| # | Do this | Expect this |
+|---|---------|-------------|
+| 1 | After the update, open HOST's newest log. | Once, near the start: "Made this PC's identity key (fingerprint …)". |
+| 2 | On CLIENT (its printers were added before 0.5.8), wait 5 minutes after PrintVect starts; open its newest log. Then Settings, Diagnostics, Copy report. | "Remembered the identity key of HOST (…) for 1 printer(s)". The report: "added printers whose host's key is remembered: 1 of 1". A printer added from now on remembers the key at once. |
+| 3 | Move HOST to another address (connect it to the phone hotspot as in 0.5.0, with CLIENT on the same hotspot). Print from CLIENT. | It prints. CLIENT's log: "HOST now answers at … (was …); sending there." |
+| 4 | (Optional, needs a spare PC with PrintVect) give the spare PC HOST's PC name, share a printer on it, switch HOST off. Print from CLIENT. | Nothing prints on the spare PC. The job waits: "A PC calling itself HOST answers at …, but it is not HOST, the PC this printer was added from … Nothing was sent there." Give the spare PC its own name back afterwards. |
+
+### 3. The administrator helper never follows a link in the data folder
+
+Every user may write in `C:\ProgramData\PrintVect`. Another user could replace a folder there (spool, logs, or the
+folder of a printer about to be added) with a junction to a Windows folder; PrintVect.Elevate, running as
+administrator, then gave "Users: Modify" on the Windows folder or deleted files in it. Now it checks every folder on
+the way and refuses.
+
+| # | Do this | Expect this |
+|---|---------|-------------|
+| 1 | On CLIENT: Printers on other PCs, remove a printer, add it again. | Works as before (one Windows permission question each time). The newest `PrintVect-Elevate-….log` says "Users may now modify C:\ProgramData\PrintVect\spool\ and the files in it." |
+| 2 | Note the `` from that line. Remove the printer again. Open Command Prompt (not as administrator) and type `mkdir C:\Users\Public\linktest` then `mklink /J C:\ProgramData\PrintVect\spool\ C:\Users\Public\linktest`. Add the printer again. | It is refused: "PrintVect did not touch C:\ProgramData\PrintVect\spool\: it is a link to another place … Delete … then try again." `C:\Users\Public\linktest` (right-click, Properties, Security) has no new "Users" entry. |
+| 3 | Type `rmdir C:\ProgramData\PrintVect\spool\` (removes the link only) and add the printer again. | Added as in step 1. |
+
+### 4. A host cannot be flooded
+
+There was no limit on connections, files that were not XPS stayed in `spool\incoming\` (up to 200 MB each), and old
+files were cleaned up only when sharing started. Now: 32 connections at once (8 per PC, 120 a minute per PC), 15 s
+to send the request, at most 1 GB waiting and 256 MB left free on the disk, junk deleted at once, and an hourly
+clean-up of files kept after a failed print (after 24 hours).
+
+| # | Do this | Expect this |
+|---|---------|-------------|
+| 1 | Print from CLIENT as usual, several pages in a row. | Everything prints as before. |
+| 2 | On CLIENT, make a text file `junk.xps` (Notepad, type anything, save with that name) and send it from Command Prompt in the PrintVect folder: `pvct-send junk.xps HOST`. | Refused: "The file is not an XPS document (…); HOST deleted it." `C:\ProgramData\PrintVect\spool\incoming` on HOST holds no file for it. |
+| 3 | On CLIENT, open PowerShell and type `$c = 1..12 \| % { New-Object Net.Sockets.TcpClient('HOST', 9151) }` (HOST = its PC name). Wait 20 seconds, then print a page. | HOST's log: "Closed a connection from 192.168.… at once: 8 connections from … are open already." (once a minute at most), then for the 8 it served "sent no request within 15 s; closed". The page prints. |
+| 4 | Pause a printer on HOST (Share my printers), print 3 pages from CLIENT, wait a day with HOST running, then Resume. | The 3 jobs wait and then print: files of waiting jobs are never cleaned up. |
+
+### 5. Updates are checked more strictly
+
+The checksum file was optional (without it the update installed after a size check only), and the setup program
+waited in `C:\ProgramData\PrintVect\updates`, where every user may write, between its check and its start. Now a
+release without a checksum file is not installed, and the setup program is held (nobody can change, delete or rename
+it or its folder) and checked again just before it starts. Code signing remains the real fix (CODE_SIGNING.md).
+
+| # | Do this | Expect this |
+|---|---------|-------------|
+| 1 | When 0.5.8 is on all PCs and a later version is published: Settings, Check now, Update now. | The update installs as before. The PC's log: "the checksum … matches", then "checked again just before starting it: the SHA-256 still matches", then "Update: starting …". |
+| 2 | Nothing to do for a release without a checksum file: every release made by release.yml has one. If one ever lacks it, Update now says "version … has no checksum file, so PrintVect cannot check the download and does not install it". | |
+
+### 6. New versions go to test PCs first
+
+Every release went to every PC within a day, tested or not. Now release.yml publishes a test version (a GitHub
+pre-release), which installed PCs ignore because they ask GitHub for its "latest release", and promote.yml hands it to
+every PC. The release text is the version's section of CHANGELOG.md. The whole flow is in `docs/releasing.md`.
+
+| # | Do this | Expect this |
+|---|---------|-------------|
+| 1 | After the pull request is merged: Actions, release, Run workflow, branch main, stage **test**. | Release v0.5.8 marked **Pre-release**, with the setup program, its .sha256, a "Test version" note and "What changed in 0.5.8" from CHANGELOG.md. |
+| 2 | On a PC with 0.5.7: Settings, Check now. | "up to date" (0.5.7 is still the latest release): the test version is not offered. |
+| 3 | On your test PCs: download PrintVect-Setup-0.5.8.exe from that release and run it. Do the steps of sections 1 to 5 above. | "Version 0.5.8" under the menu; settings and printers kept. |
+| 4 | When they work, tell me the result (I write it into CHANGELOG.md), then Actions, promote, Run workflow, branch main. | The release loses "Pre-release" and shows "Latest", without the test note. Other PCs offer 0.5.8 within a day (or at once with Check now). |
+
+### 7. Smaller points
+
+Anyone on the network could add made-up PCs to "PCs that use this PC" (fixed in section 1: with a PIN, a hello must
+prove it); the PIN stood in plain text in config.json, which every user of the PC can open; the 10.8 MB demo video
+was committed although the README plays the copy uploaded to GitHub.
+
+| # | Do this | Expect this |
+|---|---------|-------------|
+| 1 | On a PC that had a PIN before the update, open `C:\ProgramData\PrintVect\config.json` in Notepad. | No `"Pin": "…"` line; a long `"PinProtected"` value instead. The log of the first start: "the sharing PIN was kept in plain text; config.json now keeps it protected for this PC." Printing with the PIN works as before. |
+| 2 | Settings, Security, Change PIN; then look at config.json again. | Still no PIN in plain text; the other PCs need the new PIN as before. |
+
## Later
Phase 2 items (brief section 9): raw port-9100 relay, Hindi UI, optional service host, job counter per user.
diff --git a/installer/PrintVect.iss b/installer/PrintVect.iss
index b19b0c2..ed94935 100644
--- a/installer/PrintVect.iss
+++ b/installer/PrintVect.iss
@@ -1,5 +1,5 @@
; PrintVect installer (Inno Setup 6, milestone M5; silent in-app updates since M6a).
-; CI builds it with: ISCC.exe /DAppVersion=0.5.7 /DSourceDir= installer\PrintVect.iss
+; CI builds it with: ISCC.exe /DAppVersion=0.5.8 /DSourceDir= installer\PrintVect.iss
; The source folder is what the build workflow collects: PrintVect.App.exe, PrintVect.Core.dll,
; Newtonsoft.Json.dll, PrintVect.Elevate.exe, pvct-send.exe, Fonts\, the sample .xps files, README.md, LICENSE.
; An update from inside PrintVect runs this same program as PrintVect-Setup-.exe /SILENT /NORESTART /LOG=...
@@ -7,7 +7,7 @@
; PrintVect (PrepareToInstall below), installs over the old files and starts PrintVect again as the signed-in user.
#ifndef AppVersion
- #define AppVersion "0.5.7"
+ #define AppVersion "0.5.8"
#endif
#ifndef SourceDir
#define SourceDir "..\artifacts\PrintVect"
diff --git a/src/PrintVect.App/Client/ClientController.cs b/src/PrintVect.App/Client/ClientController.cs
index 745a257..e0610dd 100644
--- a/src/PrintVect.App/Client/ClientController.cs
+++ b/src/PrintVect.App/Client/ClientController.cs
@@ -20,7 +20,8 @@ namespace PrintVect.App.Client
/// Glue between the Office printers page and the Core client service: finds hosts (UDP discovery while the
/// page is open, or a typed name), adds and removes virtual printers through PrintVect.Elevate.exe, keeps
/// config.json and the job history in step, follows a host that changed its address (also by searching for it
- /// when a job cannot reach it, 0.5.0), and re-raises events on the UI thread.
+ /// when a job cannot reach it, 0.5.0) once it proves its identity key (0.5.8, MovedHostCheck), and re-raises events
+ /// on the UI thread.
///
internal sealed class ClientController : IDisposable
{
@@ -37,6 +38,8 @@ internal sealed class ClientController : IDisposable
private readonly DiscoveryClient _discovery;
private readonly JobHistoryStore _history;
private readonly PresenceAnnouncer _presence;
+ private readonly HashSet _checking = new HashSet(StringComparer.OrdinalIgnoreCase);
+ private readonly HashSet _refusedMoves = new HashSet(StringComparer.OrdinalIgnoreCase);
public ClientController(AppPaths paths, ConfigStore store, AppConfig config, SynchronizationContext ui)
{
@@ -70,7 +73,8 @@ public ClientController(AppPaths paths, ConfigStore store, AppConfig config, Syn
};
_service.JobFinished += (s, record) => Post(() => Raise(JobFinished, record));
- _presence = new PresenceAnnouncer(sender, () => _service.WatchedPrinters);
+ _presence = new PresenceAnnouncer(sender, () => _service.WatchedPrinters) { Pin = config.Pin };
+ _presence.HostAnswered += (s, printer) => Post(() => LearnHostKey(printer));
_discovery = new DiscoveryClient(config.DiscoveryPort);
_discovery.HostsChanged += (s, e) => Post(OnHostsChanged);
@@ -177,37 +181,125 @@ public void SearchNow()
}
///
- /// A job could not reach its host (0.5.0): ask the office once and listen for a few seconds. When the host answers
- /// from another address (a phone hotspot hands out a new one each time), the printer takes it at once and
- /// config.json is saved on the UI thread. Runs on the sending thread.
+ /// A job could not reach its host (0.5.0): ask the office once and listen for a few seconds. When a PC answers
+ /// for the host from another address (a phone hotspot hands out a new one each time) and proves it is that
+ /// host (0.5.8), the printer takes the address at once and config.json is saved on the UI thread. A PC that
+ /// claims the host's name or printers without its identity key gets nothing. Runs on the sending thread.
///
- private async Task FindHostAgainAsync(RemotePrinter printer, CancellationToken ct)
+ private async Task FindHostAgainAsync(RemotePrinter printer, CancellationToken ct)
{
string before = printer.HostIp;
- int portBefore = printer.Port;
Log.Info("Looking for " + printer.HostName + " on the network (it did not answer at " + before + ").");
await _discovery.SearchAsync(FindHostListen, ct).ConfigureAwait(false);
- DiscoveredHost host = _discovery.Hosts.FirstOrDefault(h => !string.IsNullOrEmpty(h.Ip)
- && (h.Printers.Any(p => string.Equals(p.Id, printer.PrinterId, StringComparison.OrdinalIgnoreCase))
- || string.Equals(h.Host, printer.HostName, StringComparison.OrdinalIgnoreCase)));
- if (host == null)
+ List claims = _discovery.Hosts.Where(h => !string.IsNullOrEmpty(h.Ip) && ClaimsToBe(h, printer)).ToList();
+ if (claims.Count == 0)
{
- return false;
+ return HostSearchOutcome.NotFound;
+ }
+ string refusal = null;
+ foreach (DiscoveredHost host in claims)
+ {
+ int port = host.Port > 0 ? host.Port : printer.Port;
+ foreach (string address in AddressesOf(host).Where(a => !string.Equals(a, before, StringComparison.OrdinalIgnoreCase) || port != printer.Port))
+ {
+ MovedHostVerdict verdict = await MovedHostCheck.CheckAsync(printer, address, port, ct).ConfigureAwait(false);
+ if (verdict.Problem != null)
+ {
+ Log.Warn("Not following " + printer.HostName + " to " + address + ": " + verdict.Problem);
+ refusal = verdict.Problem;
+ continue;
+ }
+ printer.HostIp = address;
+ printer.Port = port;
+ if (string.IsNullOrEmpty(printer.HostKeyId) && verdict.KeyId != null)
+ {
+ printer.HostKeyId = verdict.KeyId;
+ }
+ Post(() =>
+ {
+ TrySave();
+ Raise(PrintersChanged);
+ });
+ return HostSearchOutcome.Followed;
+ }
}
- bool moved = !string.Equals(host.Ip, before, StringComparison.OrdinalIgnoreCase) || (host.Port > 0 && host.Port != portBefore);
- if (!moved)
+ if (refusal == null)
{
Log.Info(printer.HostName + " answers the search at the same address " + before + ".");
- return false;
+ return HostSearchOutcome.NotFound;
}
- printer.HostIp = host.Ip;
- if (host.Port > 0) printer.Port = host.Port;
- Post(() =>
+ return HostSearchOutcome.Refused(refusal + " Nothing was sent there. If " + printer.HostName
+ + " was set up again, remove its printer on this PC and add it again.");
+ }
+
+ /// A host that answered discovery says it is the printer's host: same printer id or same PC name. Anyone can say so.
+ private static bool ClaimsToBe(DiscoveredHost host, RemotePrinter printer)
+ {
+ return host.Printers.Any(p => string.Equals(p.Id, printer.PrinterId, StringComparison.OrdinalIgnoreCase))
+ || string.Equals(host.Host, printer.HostName, StringComparison.OrdinalIgnoreCase);
+ }
+
+ /// The address in use first, then every other address that answered with the same PC name lately.
+ private static IEnumerable AddressesOf(DiscoveredHost host)
+ {
+ yield return host.Ip;
+ foreach (string other in host.Addresses.OrderByDescending(a => a.Value).Select(a => a.Key))
{
- TrySave();
- Raise(PrintersChanged);
+ if (!string.Equals(other, host.Ip, StringComparison.OrdinalIgnoreCase)) yield return other;
+ }
+ }
+
+ ///
+ /// On the UI thread: the host of took a hello. Printers of that host added before
+ /// 0.5.8 have no identity key remembered yet; ask the host to prove one at the printer's own address and keep it.
+ ///
+ private void LearnHostKey(RemotePrinter answered)
+ {
+ List unknown = _config.RemotePrinters
+ .Where(p => string.IsNullOrEmpty(p.HostKeyId) && string.Equals(p.HostIp, answered.HostIp, StringComparison.OrdinalIgnoreCase)
+ && p.Port == answered.Port)
+ .ToList();
+ string key = "learn|" + answered.HostIp + ":" + answered.Port;
+ if (unknown.Count == 0 || !_checking.Add(key))
+ {
+ return;
+ }
+ RemotePrinter first = unknown[0];
+ Task.Run(async () =>
+ {
+ MovedHostVerdict verdict;
+ try
+ {
+ verdict = await MovedHostCheck.CheckAsync(first, first.HostIp, first.Port, CancellationToken.None).ConfigureAwait(false);
+ }
+ catch (Exception ex)
+ {
+ verdict = new MovedHostVerdict { Problem = ex.Message };
+ }
+ Post(() =>
+ {
+ _checking.Remove(key);
+ if (verdict.Problem != null)
+ {
+ if (_refusedMoves.Add(key))
+ {
+ Log.Warn("The identity key of " + first.HostName + " could not be learned: " + verdict.Problem);
+ }
+ return;
+ }
+ if (verdict.KeyId == null)
+ {
+ return; // a host before 0.5.8: nothing to learn yet
+ }
+ foreach (RemotePrinter printer in unknown.Where(p => string.IsNullOrEmpty(p.HostKeyId)))
+ {
+ printer.HostKeyId = verdict.KeyId;
+ }
+ Log.Info("Remembered the identity key of " + first.HostName + " (" + verdict.KeyId.Substring(0, 16) + "…) for "
+ + unknown.Count + " printer(s); jobs follow it to a new address only when it proves this key.");
+ TrySave();
+ });
});
- return true;
}
/// Whether a job printed on this PC first asks how many copies (Settings, and "Don't ask again").
@@ -231,10 +323,11 @@ public bool SetAskCopies(bool ask)
return saved;
}
- /// The office PIN changed in Settings: every job from now on carries it.
+ /// The sharing PIN changed in Settings: every job and hello from now on proves it.
public void ApplyPin(string pin)
{
_service.Pin = pin ?? "";
+ _presence.Pin = pin ?? "";
}
public void ApplyKeepSentFilesHours(int hours)
@@ -319,37 +412,71 @@ public async Task LookupHostAsync(string hostOrIp, CancellationToken
return reply;
}
- /// On the UI thread: a host appeared, changed or left. Follows hosts whose address changed (DHCP).
+ ///
+ /// On the UI thread: a host appeared, changed or left. A printer follows its host to a new address (DHCP) only
+ /// after the PC there proves it is that host (0.5.8); the check runs in the background.
+ ///
private void OnHostsChanged()
{
- bool printersChanged = false;
foreach (DiscoveredHost host in _discovery.Hosts)
{
if (string.IsNullOrEmpty(host.Ip)) continue;
foreach (RemotePrinter printer in _config.RemotePrinters)
{
- bool sameHost = host.Printers.Any(p => string.Equals(p.Id, printer.PrinterId, StringComparison.OrdinalIgnoreCase))
- || string.Equals(host.Host, printer.HostName, StringComparison.OrdinalIgnoreCase);
- if (!sameHost) continue;
- bool moved = !string.Equals(printer.HostIp, host.Ip, StringComparison.OrdinalIgnoreCase)
- || (host.Port > 0 && printer.Port != host.Port);
- if (!moved) continue;
- Log.Info("Host " + host.Host + " for \"" + printer.LocalPrinterName + "\" now answers at " + host.Ip + ":" + host.Port
- + " (was " + printer.HostIp + ":" + printer.Port + "); updating config.json.");
- printer.HostIp = host.Ip;
- if (host.Port > 0) printer.Port = host.Port;
- if (!string.IsNullOrWhiteSpace(host.Host)) printer.HostName = host.Host;
- printersChanged = true;
- try { _service.StartWatching(printer); }
- catch (Exception ex) { Log.Warn("Watcher of \"" + printer.LocalPrinterName + "\" could not take the new address: " + ex.Message); }
+ int port = host.Port > 0 ? host.Port : printer.Port;
+ bool moved = !string.Equals(printer.HostIp, host.Ip, StringComparison.OrdinalIgnoreCase) || printer.Port != port;
+ if (moved && ClaimsToBe(host, printer))
+ {
+ FollowIfProven(printer, host.Ip, port, host.Host);
+ }
}
}
- if (printersChanged)
+ Raise(FoundChanged);
+ }
+
+ /// Checks in the background whether the PC at the new address is the printer's host, then follows it on the UI thread.
+ private void FollowIfProven(RemotePrinter printer, string address, int port, string hostName)
+ {
+ string key = printer.PrinterId + "|" + address + ":" + port;
+ if (!_checking.Add(key))
{
- TrySave();
- Raise(PrintersChanged);
+ return;
}
- Raise(FoundChanged);
+ Task.Run(async () =>
+ {
+ MovedHostVerdict verdict;
+ try
+ {
+ verdict = await MovedHostCheck.CheckAsync(printer, address, port, CancellationToken.None).ConfigureAwait(false);
+ }
+ catch (Exception ex)
+ {
+ verdict = new MovedHostVerdict { Problem = ex.Message };
+ }
+ Post(() =>
+ {
+ _checking.Remove(key);
+ if (verdict.Problem != null)
+ {
+ if (_refusedMoves.Add(key))
+ {
+ Log.Warn("Not following " + printer.HostName + " for \"" + printer.LocalPrinterName + "\" to " + address + ": " + verdict.Problem
+ + " If " + printer.HostName + " was set up again, remove this printer and add it again.");
+ }
+ return;
+ }
+ Log.Info("Host " + hostName + " for \"" + printer.LocalPrinterName + "\" now answers at " + address + ":" + port
+ + " (was " + printer.HostIp + ":" + printer.Port + ") and proved its identity; updating config.json.");
+ printer.HostIp = address;
+ printer.Port = port;
+ if (!string.IsNullOrWhiteSpace(hostName)) printer.HostName = hostName.Trim();
+ if (string.IsNullOrEmpty(printer.HostKeyId) && verdict.KeyId != null) printer.HostKeyId = verdict.KeyId;
+ try { _service.StartWatching(printer); }
+ catch (Exception ex) { Log.Warn("Watcher of \"" + printer.LocalPrinterName + "\" could not take the new address: " + ex.Message); }
+ TrySave();
+ Raise(PrintersChanged);
+ });
+ });
}
/// Creates the virtual printer (UAC prompt) and remembers it. The result's Message is for the user.
@@ -378,6 +505,9 @@ public async Task AddPrinterAsync(ListReply host, PrinterInfo pri
arguments.Options[ElevateCommands.OptionFolder] = folder;
arguments.Options[ElevateCommands.OptionPort] = port;
+ int jobPort = host.Port > 0 ? host.Port : _config.JobPort;
+ string keyId = await ProvenKeyAsync(new RemotePrinter { PrinterId = printer.Id, HostName = hostName }, hostIp, jobPort).ConfigureAwait(true);
+
Log.Info("Adding printer \"" + friendly + "\" of " + hostName + " (" + hostIp + ") as \"" + localName + "\", id " + printer.Id + ".");
ElevateResult result = await ElevateLauncher.RunAsync(_paths, arguments).ConfigureAwait(true);
if (!result.Ok)
@@ -390,9 +520,10 @@ public async Task AddPrinterAsync(ListReply host, PrinterInfo pri
PrinterId = printer.Id,
HostName = hostName,
HostIp = hostIp,
- Port = host.Port > 0 ? host.Port : _config.JobPort,
+ Port = jobPort,
LocalPrinterName = localName,
- FriendlyName = friendly
+ FriendlyName = friendly,
+ HostKeyId = keyId
};
_config.RemotePrinters.Add(remote);
if (!TrySave())
@@ -414,6 +545,28 @@ public async Task AddPrinterAsync(ListReply host, PrinterInfo pri
return result;
}
+ ///
+ /// The identity key the host proves at the address the printer is added with (0.5.8), or null (a host before
+ /// 0.5.8, or no proof: the key is then learned after its first hello).
+ ///
+ private static async Task ProvenKeyAsync(RemotePrinter printer, string address, int port)
+ {
+ try
+ {
+ MovedHostVerdict verdict = await MovedHostCheck.CheckAsync(printer, address, port, CancellationToken.None).ConfigureAwait(false);
+ if (verdict.Problem != null)
+ {
+ Log.Warn("The identity key of " + printer.HostName + " was not taken: " + verdict.Problem);
+ }
+ return verdict.Problem == null ? verdict.KeyId : null;
+ }
+ catch (Exception ex)
+ {
+ Log.Warn("The identity key of " + printer.HostName + " could not be checked: " + ex.Message);
+ return null;
+ }
+ }
+
/// Deletes the virtual printer, its port and folder (UAC prompt) and forgets it.
public async Task RemovePrinterAsync(RemotePrinter printer)
{
diff --git a/src/PrintVect.App/Host/HostController.cs b/src/PrintVect.App/Host/HostController.cs
index c874580..274b5df 100644
--- a/src/PrintVect.App/Host/HostController.cs
+++ b/src/PrintVect.App/Host/HostController.cs
@@ -45,6 +45,7 @@ public HostController(AppPaths paths, ConfigStore store, AppConfig config, Synch
_service.Jobs.Changed += (s, record) => _history.QueueSave();
_discovery = new DiscoveryResponder(address => _service.BuildListReplyFor(address));
_service.Pin = config.Pin;
+ LoadIdentity();
DropPrintVectPrinters();
_service.UpdateSharedPrinters(config.SharedPrinters);
_service.JobReceived += (s, record) => Post(() => Raise(JobReceived, record));
@@ -349,6 +350,36 @@ public IEnumerable DescribeForDiagnostics()
return lines;
}
+ ///
+ /// This PC's identity key (0.5.8), read or made in the background (making one takes a moment); replies go out
+ /// without it until it is ready. A new key is kept in config.json on the UI thread.
+ ///
+ private void LoadIdentity()
+ {
+ string saved = _config.HostKey;
+ Task.Run(() =>
+ {
+ try
+ {
+ string newKey;
+ HostIdentity identity = HostIdentity.LoadOrCreate(saved, out newKey);
+ Post(() =>
+ {
+ if (newKey != null)
+ {
+ _config.HostKey = newKey;
+ TrySave();
+ }
+ _service.Identity = identity;
+ });
+ }
+ catch (Exception ex)
+ {
+ Log.Error("This PC's identity key could not be read or made; other PCs cannot follow it to a new address.", ex);
+ }
+ });
+ }
+
private bool TrySave()
{
try
@@ -392,6 +423,8 @@ public void Dispose()
_discovery.Dispose();
_service.Dispose();
_history.Dispose();
+ HostIdentity identity = _service.Identity;
+ if (identity != null) identity.Dispose();
}
}
}
diff --git a/src/PrintVect.App/Strings.Designer.cs b/src/PrintVect.App/Strings.Designer.cs
index 6642394..44b103f 100644
--- a/src/PrintVect.App/Strings.Designer.cs
+++ b/src/PrintVect.App/Strings.Designer.cs
@@ -2467,7 +2467,7 @@ internal static string SharingDialogPinAgain {
}
///
- /// Looks up a localized string similar to Every PC that prints here needs the same PIN in its Settings. Use 4 to 12 characters. Leave it blank [rest of string was truncated].
+ /// Looks up a localized string similar to Every PC that prints here needs the same PIN in its Settings. Use 4 to 12 characters (8 or more are [rest of string was truncated].
///
internal static string SharingDialogPinHelp {
get {
@@ -2736,6 +2736,15 @@ internal static string UpdateJobsBusy {
}
}
+ ///
+ /// Looks up a localized string similar to The update was not started: {0}. Press Update now to download it again..
+ ///
+ internal static string UpdateNotStarted {
+ get {
+ return ResourceManager.GetString("UpdateNotStarted", resourceCulture);
+ }
+ }
+
///
/// Looks up a localized string similar to The setup program could not be started: {0}.
///
diff --git a/src/PrintVect.App/Strings.resx b/src/PrintVect.App/Strings.resx
index 5c51043..19eaa18 100644
--- a/src/PrintVect.App/Strings.resx
+++ b/src/PrintVect.App/Strings.resx
@@ -358,6 +358,9 @@ Details: {0}
The update did not run (the setup program ended with code {0}). Press Update now again and answer Yes to the Windows permission question.
+
+ The update was not started: {0}. Press Update now to download it again.
+
The update could not be downloaded: {0}. Press Update now to try again.
@@ -493,7 +496,7 @@ Any PC on the network can then print here, and PCs that still ask for a PIN will
Change the sharing PIN
- Every PC that prints through PrintVect must have the same PIN: a PC that shares printers refuses jobs with a different one. Use 4 to 12 characters; digits are easiest to pass on.
+ Every PC that prints through PrintVect must have the same PIN: a PC that shares printers refuses jobs with a different one. Use 4 to 12 characters; 8 or more are much harder to guess.
New PIN
@@ -1031,7 +1034,7 @@ Jobs that are still waiting or printing stay. Nothing is printed, cancelled or d
Type the PIN again
- Every PC that prints here needs the same PIN in its Settings. Use 4 to 12 characters. Leave it blank to share without a PIN.
+ Every PC that prints here needs the same PIN in its Settings. Use 4 to 12 characters (8 or more are much harder to guess). Leave it blank to share without a PIN.
This PC already has a sharing PIN. Other PCs need the same PIN in their Settings to print here.
diff --git a/src/PrintVect.App/Update/UpdateController.cs b/src/PrintVect.App/Update/UpdateController.cs
index 278e249..1978a25 100644
--- a/src/PrintVect.App/Update/UpdateController.cs
+++ b/src/PrintVect.App/Update/UpdateController.cs
@@ -170,7 +170,7 @@ public async Task InstallAsync()
Phase = UpdatePhase.Downloading;
RaiseChanged();
- string path;
+ VerifiedSetup setup;
try
{
var progress = new Progress(p =>
@@ -178,7 +178,7 @@ public async Task InstallAsync()
Progress = p;
RaiseChanged();
});
- path = await _checker.DownloadAsync(release, _paths.UpdatesDir, progress, _stopping.Token);
+ setup = await _checker.DownloadAsync(release, _paths.UpdatesDir, progress, _stopping.Token);
}
catch (OperationCanceledException)
{
@@ -210,14 +210,17 @@ public async Task InstallAsync()
Phase = UpdatePhase.Installing;
RaiseChanged();
Process process;
+ SetupHold hold = null;
try
{
- process = UpdateInstaller.Start(path);
+ hold = UpdateInstaller.Hold(setup); // checked again, and nobody can change it until the setup has run (0.5.8)
+ process = UpdateInstaller.Start(hold);
}
catch (Exception ex)
{
+ if (hold != null) hold.Dispose();
Log.Error("Update: the setup program could not be started.", ex);
- LastInstallError = StartFailure(ex);
+ LastInstallError = ex is UpdateVerificationException ? string.Format(Strings.UpdateNotStarted, ex.Message) : StartFailure(ex);
Phase = UpdatePhase.Idle;
RaiseChanged();
return LastInstallError;
@@ -225,9 +228,9 @@ public async Task InstallAsync()
if (process == null)
{
Log.Warn("Update: Windows started the setup program but gave no handle to wait for; this program keeps running until the setup ends it.");
- return null;
+ return null; // the hold stays until this program ends
}
- WatchSetup(process, path);
+ WatchSetup(process, hold);
return null;
}
@@ -369,8 +372,9 @@ private async Task CheckAsync()
}
}
- private async void WatchSetup(Process process, string path)
+ private async void WatchSetup(Process process, SetupHold hold)
{
+ string path = hold.Path;
int code;
try
{
@@ -388,6 +392,7 @@ private async void WatchSetup(Process process, string path)
finally
{
process.Dispose();
+ hold.Dispose();
}
if (_disposed)
{
diff --git a/src/PrintVect.App/app.manifest b/src/PrintVect.App/app.manifest
index 86c103b..522b8fd 100644
--- a/src/PrintVect.App/app.manifest
+++ b/src/PrintVect.App/app.manifest
@@ -1,6 +1,6 @@
-
+
diff --git a/src/PrintVect.Core/Client/ClientService.cs b/src/PrintVect.Core/Client/ClientService.cs
index 370a947..135442a 100644
--- a/src/PrintVect.Core/Client/ClientService.cs
+++ b/src/PrintVect.Core/Client/ClientService.cs
@@ -50,7 +50,7 @@ public ClientService(AppPaths paths, IJobSender sender, ClientJobTracker tracker
public ClientJobTracker Jobs { get; }
- /// The office PIN sent with every job; empty when the hosts are open.
+ /// The sharing PIN every job proves (PinProof); empty when the hosts are open.
public string Pin { get; set; } = "";
/// Hours a sent file is kept in sent\ for diagnostics.
@@ -80,11 +80,11 @@ public ClientService(AppPaths paths, IJobSender sender, ClientJobTracker tracker
public Func> AskCopies { get; set; }
///
- /// Looks for a host that did not answer at its address (0.5.0): true when it was found somewhere else and the
- /// printer now carries the new address. A PC on a phone hotspot gets a new address each time it connects.
- /// Null: no search (tests, pvct-send).
+ /// Looks for a host that did not answer at its address (0.5.0): Moved when it was found somewhere else, proved
+ /// it is that host (0.5.8), and the printer now carries the new address; Refusal when a PC answered for it but
+ /// could not prove it. A PC on a phone hotspot gets a new address each time it connects. Null: no search.
///
- public Func> FindHost { get; set; }
+ public Func> FindHost { get; set; }
/// Raised on a thread-pool thread when a job reaches a final state (printed, error, pending).
public event EventHandler JobFinished;
@@ -477,6 +477,7 @@ private async Task SendWithRetriesAsync(RemotePrinter printer, ClientJobRecord r
{
string jobId = record.JobId;
string lastError = null;
+ string refusal = null;
TimeSpan[] delays = RetryDelays == null || RetryDelays.Length == 0 ? new[] { TimeSpan.Zero } : RetryDelays;
bool searched = false;
bool foundAgain = false;
@@ -526,7 +527,9 @@ private async Task SendWithRetriesAsync(RemotePrinter printer, ClientJobRecord r
searched = true;
try
{
- foundAgain = await SearchForHostAsync(printer, record, ct).ConfigureAwait(false);
+ HostSearchOutcome outcome = await SearchForHostAsync(printer, record, ct).ConfigureAwait(false);
+ foundAgain = outcome.Moved;
+ refusal = outcome.Refusal;
}
catch (OperationCanceledException)
{
@@ -537,19 +540,20 @@ private async Task SendWithRetriesAsync(RemotePrinter printer, ClientJobRecord r
}
Finish(record, ClientJobStates.Pending,
- printer.HostName + " did not answer (" + delays.Length + " tries). " + lastError + " The document is kept on this PC: "
+ printer.HostName + " did not answer (" + delays.Length + " tries). " + lastError + (refusal == null ? "" : " " + refusal)
+ + " The document is kept on this PC: "
+ "when " + printer.HostName + " is back, press Retry waiting.", ClientPrinterNames.PendingFolderName);
}
- /// One search of the office for a host that did not answer; false when it was not found elsewhere.
- private async Task SearchForHostAsync(RemotePrinter printer, ClientJobRecord record, CancellationToken ct)
+ /// One search of the office for a host that did not answer (and, 0.5.8, whether a PC that answered for it is really it).
+ private async Task SearchForHostAsync(RemotePrinter printer, ClientJobRecord record, CancellationToken ct)
{
Update(record, ClientJobStates.Sending, "Looking for " + printer.HostName + " on the network.");
string before = printer.HostIp;
- bool found;
+ HostSearchOutcome outcome;
try
{
- found = await FindHost(printer, ct).ConfigureAwait(false);
+ outcome = await FindHost(printer, ct).ConfigureAwait(false) ?? HostSearchOutcome.NotFound;
}
catch (OperationCanceledException)
{
@@ -558,17 +562,21 @@ private async Task SearchForHostAsync(RemotePrinter printer, ClientJobReco
catch (Exception ex)
{
Log.Warn(record.JobId, "The search for " + printer.HostName + " failed: " + ex.Message);
- return false;
+ return HostSearchOutcome.NotFound;
}
- if (found)
+ if (outcome.Moved)
{
Log.Info(record.JobId, printer.HostName + " now answers at " + printer.HostIp + " (was " + before + "); sending there.");
}
+ else if (outcome.Refusal != null)
+ {
+ Log.Warn(record.JobId, "Not following " + printer.HostName + ": " + outcome.Refusal);
+ }
else
{
Log.Info(record.JobId, printer.HostName + " was not found at another address.");
}
- return found;
+ return outcome;
}
private async Task HandleReplyAsync(RemotePrinter printer, ClientJobRecord record, JobReply reply, CancellationToken ct)
diff --git a/src/PrintVect.Core/Client/IJobSender.cs b/src/PrintVect.Core/Client/IJobSender.cs
index bf559df..605d76a 100644
--- a/src/PrintVect.Core/Client/IJobSender.cs
+++ b/src/PrintVect.Core/Client/IJobSender.cs
@@ -1,4 +1,7 @@
using System;
+using System.Linq;
+using System.Net;
+using System.Net.Sockets;
using System.Threading;
using System.Threading.Tasks;
using PrintVect.Core.Config;
@@ -17,7 +20,8 @@ public interface IJobSender
///
/// The real sender: TCP to the host's IP address first and, when that fails and a PC name is
- /// known, to the name (DHCP may have moved the host; brief 11.5).
+ /// known, to the name (DHCP may have moved the host; brief 11.5). Any PC can answer to a name, so for a printer
+ /// whose host key is remembered (0.5.8) the name is looked up and only an address that proves that key is used.
///
public sealed class TcpJobSender : IJobSender
{
@@ -33,7 +37,8 @@ public async Task SendAsync(RemotePrinter printer, RequestHeader heade
catch (HostUnreachableException ex) when (second != null)
{
Log.Warn(header.JobId, first + " did not answer (" + ex.Message + "); trying the PC name " + second + ".");
- return await Client(second, printer).SendJobAsync(header, filePath, null, ct).ConfigureAwait(false);
+ string checkedAddress = await CheckedAsync(printer, second, ct).ConfigureAwait(false);
+ return await Client(checkedAddress, printer).SendJobAsync(header, filePath, null, ct).ConfigureAwait(false);
}
}
@@ -48,7 +53,8 @@ public async Task StatusAsync(RemotePrinter printer, string jobId, Can
}
catch (HostUnreachableException) when (second != null)
{
- return await Client(second, printer).QueryStatusAsync(jobId, ct).ConfigureAwait(false);
+ string checkedAddress = await CheckedAsync(printer, second, ct).ConfigureAwait(false);
+ return await Client(checkedAddress, printer).QueryStatusAsync(jobId, ct).ConfigureAwait(false);
}
}
@@ -63,10 +69,45 @@ public async Task HelloAsync(RemotePrinter printer, RequestHeader head
}
catch (HostUnreachableException) when (second != null)
{
- return await Client(second, printer).SendHelloAsync(header, ct).ConfigureAwait(false);
+ string checkedAddress = await CheckedAsync(printer, second, ct).ConfigureAwait(false);
+ return await Client(checkedAddress, printer).SendHelloAsync(header, ct).ConfigureAwait(false);
}
}
+ ///
+ /// The PC name as it is for a printer without a remembered host key (as before 0.5.8); else the first address
+ /// the name leads to that proves the key (MovedHostCheck). Throws HostUnreachableException when none does.
+ ///
+ private static async Task CheckedAsync(RemotePrinter printer, string name, CancellationToken ct)
+ {
+ IPAddress literal;
+ if (string.IsNullOrEmpty(printer.HostKeyId) || IPAddress.TryParse(name, out literal))
+ {
+ return name;
+ }
+ IPAddress[] addresses;
+ try
+ {
+ addresses = await Dns.GetHostAddressesAsync(name).ConfigureAwait(false);
+ }
+ catch (Exception ex) when (ex is SocketException || ex is ArgumentException)
+ {
+ throw new HostUnreachableException(printer.HostName + " did not answer at " + printer.HostIp + ", and its name leads nowhere (" + ex.Message + ").", ex);
+ }
+ string problem = null;
+ foreach (IPAddress address in addresses.Where(a => a.AddressFamily == AddressFamily.InterNetwork))
+ {
+ string ip = address.ToString();
+ if (string.Equals(ip, printer.HostIp, StringComparison.OrdinalIgnoreCase)) continue; // just failed
+ MovedHostVerdict verdict = await MovedHostCheck.CheckAsync(printer, ip, printer.Port, ct).ConfigureAwait(false);
+ if (verdict.Problem == null) return ip;
+ problem = verdict.Problem;
+ }
+ throw new HostUnreachableException(printer.HostName + " did not answer at " + printer.HostIp + (problem == null
+ ? ", and its name leads to no other address."
+ : ", and its name leads elsewhere: " + problem + " Nothing was sent there."));
+ }
+
private static JobClient Client(string address, RemotePrinter printer)
{
return new JobClient(address, printer.Port) { DisplayName = printer.HostName };
diff --git a/src/PrintVect.Core/Client/MovedHostCheck.cs b/src/PrintVect.Core/Client/MovedHostCheck.cs
new file mode 100644
index 0000000..7ee9729
--- /dev/null
+++ b/src/PrintVect.Core/Client/MovedHostCheck.cs
@@ -0,0 +1,105 @@
+using System;
+using System.Threading;
+using System.Threading.Tasks;
+using PrintVect.Core.Config;
+using PrintVect.Core.Protocol;
+
+namespace PrintVect.Core.Client
+{
+ /// What a search for a host that did not answer found (ClientService.FindHost).
+ public sealed class HostSearchOutcome
+ {
+ public static readonly HostSearchOutcome NotFound = new HostSearchOutcome(false, null);
+ public static readonly HostSearchOutcome Followed = new HostSearchOutcome(true, null);
+
+ private HostSearchOutcome(bool moved, string refusal)
+ {
+ Moved = moved;
+ Refusal = refusal;
+ }
+
+ /// The printer now carries the host's new address.
+ public bool Moved { get; }
+
+ /// A PC answered for the host but did not prove it is that host: why, in plain words. Null otherwise.
+ public string Refusal { get; }
+
+ public static HostSearchOutcome Refused(string reason)
+ {
+ return new HostSearchOutcome(false, reason);
+ }
+ }
+
+ /// The answer of MovedHostCheck: Problem is null when the printer may follow; KeyId is the fingerprint proven.
+ public sealed class MovedHostVerdict
+ {
+ public string Problem { get; set; }
+ public string KeyId { get; set; }
+ }
+
+ ///
+ /// Whether a printer may follow its host to a new address (0.5.8). Any PC can answer discovery with the host's
+ /// PC name and printer ids, which travel openly, so a PC that claims them must also sign a random challenge,
+ /// together with its name and the address it answers on, with the identity key remembered for the printer
+ /// (RemotePrinter.HostKeyId; HostKeys). The same check at the printer's own address is how a printer learns the
+ /// key: when it is added, or, for printers added before 0.5.8, after the host answers a hello. A printer with no
+ /// key yet remembers the first one proven to it; an older host without a key is followed as before 0.5.8.
+ ///
+ public static class MovedHostCheck
+ {
+ ///
+ /// Asks the PC at to prove it is the printer's host. The verdict's Problem is null when
+ /// the printer may follow it; its KeyId is the fingerprint to remember when the printer had none.
+ ///
+ public static async Task CheckAsync(RemotePrinter printer, string address, int port, CancellationToken ct)
+ {
+ if (printer == null) throw new ArgumentNullException(nameof(printer));
+ string challenge = HostKeys.NewChallenge();
+ ListReply reply;
+ try
+ {
+ reply = await new JobClient(address, port) { DisplayName = printer.HostName }.ListPrintersAsync(ct, challenge).ConfigureAwait(false);
+ }
+ catch (OperationCanceledException)
+ {
+ throw;
+ }
+ catch (Exception ex)
+ {
+ return new MovedHostVerdict { Problem = "the PC at " + address + " did not answer the identity check (" + ex.Message + ")." };
+ }
+ string keyId;
+ string problem = Judge(printer, address, challenge, reply, out keyId);
+ return new MovedHostVerdict { Problem = problem, KeyId = keyId };
+ }
+
+ /// The decision itself, for a reply already received. Null: follow.
+ public static string Judge(RemotePrinter printer, string address, string challenge, ListReply reply, out string keyId)
+ {
+ keyId = null;
+ string host = string.IsNullOrWhiteSpace(printer.HostName) ? "the PC with this printer" : printer.HostName;
+ string claimed = reply == null || string.IsNullOrWhiteSpace(reply.Host) ? "A PC" : "A PC calling itself " + reply.Host.Trim();
+ if (reply == null || !reply.Ok)
+ {
+ return "the PC at " + address + " refused the identity check" + (reply == null || string.IsNullOrEmpty(reply.Message) ? "." : ": " + reply.Message);
+ }
+ if (string.IsNullOrEmpty(reply.HostKey))
+ {
+ return string.IsNullOrEmpty(printer.HostKeyId)
+ ? null // a host before 0.5.8 and a printer that never learned a key: as before
+ : claimed + " answers at " + address + " but cannot prove it is " + host + ", the PC this printer was added from.";
+ }
+ string offered = HostKeys.KeyIdOf(reply.HostKey);
+ if (!string.IsNullOrEmpty(printer.HostKeyId) && !string.Equals(offered, printer.HostKeyId, StringComparison.OrdinalIgnoreCase))
+ {
+ return claimed + " answers at " + address + ", but it is not " + host + ", the PC this printer was added from (its identity key differs).";
+ }
+ if (!HostKeys.Verify(reply.HostKey, challenge, reply.Host, address, reply.HostSig))
+ {
+ return claimed + " answers at " + address + " but did not prove it is " + host + " (its identity check failed).";
+ }
+ keyId = offered;
+ return null;
+ }
+ }
+}
diff --git a/src/PrintVect.Core/Client/PresenceAnnouncer.cs b/src/PrintVect.Core/Client/PresenceAnnouncer.cs
index 331fee3..88ff4eb 100644
--- a/src/PrintVect.Core/Client/PresenceAnnouncer.cs
+++ b/src/PrintVect.Core/Client/PresenceAnnouncer.cs
@@ -13,7 +13,9 @@ namespace PrintVect.Core.Client
///
/// The light presence signal (M6b-2): every few minutes, this PC says hello to each host whose printers it has
/// added, so that host can list the PCs that use it with their Windows and PrintVect versions. A host that does
- /// not answer is simply tried again next time; the log notes only changes, not every quiet round.
+ /// not answer is simply tried again next time; the log notes only changes, not every quiet round. A host that
+ /// refuses the hello (a different sharing PIN, 0.5.8) gets no more hellos until this PC's PIN changes, so a wrong
+ /// PIN does not keep counting as wrong tries there and make that host wait before it takes this PC's jobs.
///
public sealed class PresenceAnnouncer : IDisposable
{
@@ -23,10 +25,12 @@ public sealed class PresenceAnnouncer : IDisposable
private readonly IJobSender _sender;
private readonly Func> _printers;
private readonly Dictionary _lastAnswered = new Dictionary(StringComparer.OrdinalIgnoreCase);
+ private readonly HashSet _refused = new HashSet(StringComparer.OrdinalIgnoreCase);
private readonly CancellationTokenSource _stopping = new CancellationTokenSource();
private readonly Timer _timer;
private int _running;
private string _windows;
+ private string _pin = "";
public PresenceAnnouncer(IJobSender sender, Func> printers)
{
@@ -39,6 +43,23 @@ public PresenceAnnouncer(IJobSender sender, Func> printers)
public TimeSpan Interval { get; set; } = DefaultInterval;
+ /// Raised on a thread-pool thread with one printer of a host that answered a hello (0.5.8: its key can be learned).
+ public event EventHandler HostAnswered;
+
+ /// The sharing PIN each hello proves; a change lets refused hosts hear from this PC again.
+ public string Pin
+ {
+ get { return Volatile.Read(ref _pin); }
+ set
+ {
+ Volatile.Write(ref _pin, value ?? "");
+ lock (_refused)
+ {
+ _refused.Clear();
+ }
+ }
+ }
+
public void Start(TimeSpan firstDelay)
{
_timer.Change(firstDelay, Interval);
@@ -88,7 +109,11 @@ public async Task AnnounceAsync(CancellationToken ct)
.GroupBy(p => string.IsNullOrWhiteSpace(p.HostName) ? p.HostIp ?? "" : p.HostName, StringComparer.OrdinalIgnoreCase))
{
ct.ThrowIfCancellationRequested();
- RequestHeader header = RequestHeader.ForHello(_windows, AppInfo.Version, host.Select(p => p.PrinterId));
+ lock (_refused)
+ {
+ if (_refused.Contains(host.Key)) continue;
+ }
+ RequestHeader header = RequestHeader.ForHello(_windows, AppInfo.Version, host.Select(p => p.PrinterId), Pin);
bool answered;
string detail;
try
@@ -96,6 +121,20 @@ public async Task AnnounceAsync(CancellationToken ct)
JobReply reply = await _sender.HelloAsync(host.First(), header, ct).ConfigureAwait(false);
answered = reply != null && reply.Ok;
detail = reply == null ? "no answer" : reply.Message;
+ if (reply != null && !reply.Ok)
+ {
+ lock (_refused)
+ {
+ _refused.Add(host.Key);
+ }
+ Log.Info("Presence: " + host.Key + " refused the hello (" + reply.Message + "); no more hellos to it until the sharing PIN "
+ + "changes on this PC or PrintVect starts again.");
+ continue;
+ }
+ if (answered)
+ {
+ RaiseHostAnswered(host.First());
+ }
}
catch (OperationCanceledException)
{
@@ -110,6 +149,14 @@ public async Task AnnounceAsync(CancellationToken ct)
}
}
+ private void RaiseHostAnswered(RemotePrinter printer)
+ {
+ EventHandler handler = HostAnswered;
+ if (handler == null) return;
+ try { handler(this, printer); }
+ catch (Exception ex) { Log.Error("Presence: a listener for " + printer.HostName + "'s answer failed.", ex); }
+ }
+
private void NoteChange(string host, bool answered, string detail)
{
bool before;
diff --git a/src/PrintVect.Core/Config/AppConfig.cs b/src/PrintVect.Core/Config/AppConfig.cs
index 3d09136..449f0fb 100644
--- a/src/PrintVect.Core/Config/AppConfig.cs
+++ b/src/PrintVect.Core/Config/AppConfig.cs
@@ -1,4 +1,5 @@
using System.Collections.Generic;
+using Newtonsoft.Json;
namespace PrintVect.Core.Config
{
@@ -27,9 +28,28 @@ public sealed class AppConfig
/// TCP port on which a host receives print jobs.
public int JobPort { get; set; } = DefaultJobPort;
- /// Optional shared PIN. Empty means open to everyone on the office network.
+ ///
+ /// Optional sharing PIN, in memory only. Empty means open to every PC on the network. config.json keeps it
+ /// protected (PinProtected, 0.5.8); ConfigStore turns one into the other.
+ ///
+ [JsonIgnore]
public string Pin { get; set; } = "";
+ ///
+ /// The sharing PIN as config.json keeps it (0.5.8): protected with Windows DPAPI for this PC (MachineProtection),
+ /// so it does not show in the file or in a copy of it. Empty: no PIN.
+ ///
+ public string PinProtected { get; set; } = "";
+
+ /// Before 0.5.8 config.json kept the PIN in plain text under "Pin": read once, never written again.
+ [JsonProperty("Pin")]
+ public string LegacyPin { get; set; }
+
+ public bool ShouldSerializeLegacyPin()
+ {
+ return false;
+ }
+
/// Whether this PC currently offers its printers to the office (host role).
public bool SharingEnabled { get; set; }
@@ -57,6 +77,12 @@ public sealed class AppConfig
///
public bool CheckForUpdates { get; set; } = true;
+ ///
+ /// This PC's identity key as a host (0.5.8), protected so that only this PC can read it (MachineProtection).
+ /// Other PCs check it before they follow this PC to a new address. Made on first start; never shared.
+ ///
+ public string HostKey { get; set; } = "";
+
/// The version that ran last time, so the first start after an update can say so.
public string LastRunVersion { get; set; } = "";
@@ -94,5 +120,11 @@ public sealed class RemotePrinter
/// Name of the virtual printer on this PC, e.g. "PrintVect - Counter 1 Laser @COUNTER1".
public string LocalPrinterName { get; set; }
public string FriendlyName { get; set; }
+
+ ///
+ /// Fingerprint of the host's identity key (0.5.8), remembered when the printer is added, or at the host's first
+ /// answer for printers added before. Jobs follow the host to a new address only when it proves this key.
+ ///
+ public string HostKeyId { get; set; }
}
}
diff --git a/src/PrintVect.Core/Config/ConfigStore.cs b/src/PrintVect.Core/Config/ConfigStore.cs
index ddcd67f..9bc7ce5 100644
--- a/src/PrintVect.Core/Config/ConfigStore.cs
+++ b/src/PrintVect.Core/Config/ConfigStore.cs
@@ -68,13 +68,56 @@ public AppConfig Load()
return new AppConfig();
}
+ bool plainPin = ReadPin(config);
foreach (string warning in Normalize(config))
{
Log.Warn("Config: " + warning);
}
+ if (plainPin)
+ {
+ try
+ {
+ Save(config);
+ Log.Info("Config: the sharing PIN was kept in plain text; config.json now keeps it protected for this PC.");
+ }
+ catch (Exception ex)
+ {
+ Log.Error("Config: the sharing PIN could not be written protected yet; it is the next time the settings are saved.", ex);
+ }
+ }
return config;
}
+ ///
+ /// Fills AppConfig.Pin from the file: from PinProtected, or from the plain "Pin" of a file written before 0.5.8
+ /// (then true: the file should be saved again so the plain PIN leaves it).
+ ///
+ private static bool ReadPin(AppConfig config)
+ {
+ if (!string.IsNullOrEmpty(config.LegacyPin))
+ {
+ config.Pin = config.LegacyPin;
+ config.LegacyPin = null;
+ return true;
+ }
+ config.LegacyPin = null;
+ if (string.IsNullOrEmpty(config.PinProtected))
+ {
+ config.Pin = "";
+ return false;
+ }
+ byte[] pin = MachineProtection.Unprotect(config.PinProtected);
+ if (pin == null)
+ {
+ Log.Warn("Config: the sharing PIN in config.json was protected on another PC (or is damaged) and cannot be read here, "
+ + "so this PC has no PIN now. Set it again in Settings, Security.");
+ config.Pin = "";
+ return false;
+ }
+ config.Pin = Utf8NoBom.GetString(pin);
+ return false;
+ }
+
/// Writes the file. Writes to a temporary file first so a crash never leaves half a file.
public void Save(AppConfig config)
{
@@ -83,6 +126,7 @@ public void Save(AppConfig config)
throw new ArgumentNullException(nameof(config));
}
Normalize(config);
+ config.PinProtected = string.IsNullOrEmpty(config.Pin) ? "" : MachineProtection.Protect(Utf8NoBom.GetBytes(config.Pin));
string directory = System.IO.Path.GetDirectoryName(Path);
if (!string.IsNullOrEmpty(directory))
@@ -151,6 +195,10 @@ public static IList Normalize(AppConfig config)
config.Pin = "";
}
config.Pin = config.Pin.Trim();
+ if (config.PinProtected == null)
+ {
+ config.PinProtected = "";
+ }
if (string.IsNullOrWhiteSpace(config.Language))
{
@@ -162,6 +210,11 @@ public static IList Normalize(AppConfig config)
config.LastRunVersion = "";
}
+ if (config.HostKey == null)
+ {
+ config.HostKey = "";
+ }
+
string theme = (config.Theme ?? "").Trim().ToLowerInvariant();
if (theme != AppConfig.ThemeSystem && theme != AppConfig.ThemeLight && theme != AppConfig.ThemeDark)
{
diff --git a/src/PrintVect.Core/Config/MachineProtection.cs b/src/PrintVect.Core/Config/MachineProtection.cs
new file mode 100644
index 0000000..75ea4e3
--- /dev/null
+++ b/src/PrintVect.Core/Config/MachineProtection.cs
@@ -0,0 +1,42 @@
+using System;
+using System.Security.Cryptography;
+using System.Text;
+
+namespace PrintVect.Core.Config
+{
+ ///
+ /// Keeps a secret in config.json unreadable on any other PC (0.5.8): Windows DPAPI with the machine's key, so it
+ /// survives a change of the user who is logged in but means nothing in a copy of the file taken elsewhere.
+ ///
+ public static class MachineProtection
+ {
+ private static readonly byte[] Entropy = Encoding.UTF8.GetBytes("PrintVect config 1");
+
+ public static string Protect(byte[] secret)
+ {
+ if (secret == null) throw new ArgumentNullException(nameof(secret));
+ return Convert.ToBase64String(ProtectedData.Protect(secret, Entropy, DataProtectionScope.LocalMachine));
+ }
+
+ /// The secret, or null when the text was not protected on this PC (copied from another one, or damaged).
+ public static byte[] Unprotect(string protectedText)
+ {
+ if (string.IsNullOrWhiteSpace(protectedText))
+ {
+ return null;
+ }
+ try
+ {
+ return ProtectedData.Unprotect(Convert.FromBase64String(protectedText.Trim()), Entropy, DataProtectionScope.LocalMachine);
+ }
+ catch (FormatException)
+ {
+ return null;
+ }
+ catch (CryptographicException)
+ {
+ return null;
+ }
+ }
+ }
+}
diff --git a/src/PrintVect.Core/Diagnostics/DiagnosticsReport.cs b/src/PrintVect.Core/Diagnostics/DiagnosticsReport.cs
index 4d25d4f..7552a21 100644
--- a/src/PrintVect.Core/Diagnostics/DiagnosticsReport.cs
+++ b/src/PrintVect.Core/Diagnostics/DiagnosticsReport.cs
@@ -2,6 +2,7 @@
using System.Collections.Generic;
using System.Globalization;
using System.IO;
+using System.Linq;
using System.Text;
using PrintVect.Core.Config;
using PrintVect.Core.Logging;
@@ -125,6 +126,9 @@ private static IEnumerable DescribeConfig(AppPaths paths, AppConfig conf
lines.Add("Sharing: " + (config.SharingEnabled ? "ON" : "OFF")
+ ", shared printers: " + config.SharedPrinters.Count
+ ", remote printers added: " + config.RemotePrinters.Count);
+ lines.Add("Identity key of this PC: " + (string.IsNullOrEmpty(config.HostKey) ? "not made yet" : "kept (protected for this PC)")
+ + "; added printers whose host's key is remembered: " + config.RemotePrinters.Count(p => !string.IsNullOrEmpty(p.HostKeyId))
+ + " of " + config.RemotePrinters.Count);
lines.Add("Start with Windows: " + (config.StartWithWindows ? "yes" : "no")
+ ", keep sent files: " + config.KeepSentFilesHours + " h, language: " + config.Language
+ ", daily update check: " + (config.CheckForUpdates ? "on" : "off") + ", colours: " + config.Theme);
diff --git a/src/PrintVect.Core/Elevation/ElevateLauncher.cs b/src/PrintVect.Core/Elevation/ElevateLauncher.cs
index b5ce603..2b0e66c 100644
--- a/src/PrintVect.Core/Elevation/ElevateLauncher.cs
+++ b/src/PrintVect.Core/Elevation/ElevateLauncher.cs
@@ -44,6 +44,13 @@ private static ElevateResult Run(string exePath, AppPaths paths, ElevateArgument
+ ". Copy the whole PrintVect folder again, or run the installer.");
}
+ string link = SafeFolders.FirstLinkInDataFolders(paths);
+ if (link != null)
+ {
+ Log.Warn("Not starting " + ExeName + ": " + link + " is a junction or symbolic link.");
+ return Fail(command, new LinkFoundException(link).Message);
+ }
+
string resultFile = Path.Combine(paths.SpoolDir, "elevate-" + Guid.NewGuid().ToString("N") + ".json");
arguments.Options[ElevateCommands.OptionResult] = resultFile;
string commandLine = arguments.ToCommandLine();
diff --git a/src/PrintVect.Core/Elevation/SafeFolders.cs b/src/PrintVect.Core/Elevation/SafeFolders.cs
new file mode 100644
index 0000000..f39e216
--- /dev/null
+++ b/src/PrintVect.Core/Elevation/SafeFolders.cs
@@ -0,0 +1,251 @@
+using System;
+using System.ComponentModel;
+using System.IO;
+using System.Runtime.InteropServices;
+using System.Security.AccessControl;
+using System.Security.Principal;
+using System.Text;
+using Microsoft.Win32.SafeHandles;
+using PrintVect.Core.Config;
+
+namespace PrintVect.Core.Elevation
+{
+ /// A folder PrintVect works in turned out to be a junction or symbolic link (0.5.8, SafeFolders).
+ public sealed class LinkFoundException : IOException
+ {
+ public LinkFoundException(string path)
+ : base("PrintVect did not touch " + path + ": it is a link to another place (a junction or symbolic link), which PrintVect never "
+ + "makes. Another user of this PC may have put it there to misuse the administrator rights of PrintVect.Elevate. "
+ + "Delete " + path + " (the link only, not where it leads), then try again.")
+ {
+ Path = path;
+ }
+
+ public string Path { get; }
+ }
+
+ ///
+ /// Every user may write in %ProgramData%\PrintVect, so any of them could replace a folder there with a junction to a
+ /// system folder before an administrator command runs (0.5.8). PrintVect.Elevate therefore creates, opens, grants
+ /// rights on and deletes folders there only after making sure that no folder on the way is a link, and grants the
+ /// spool rights through a handle to the very folder it checked (so it cannot be swapped in between).
+ ///
+ public static class SafeFolders
+ {
+ /// The folder that holds the data folder (%ProgramData%): links are looked for below it.
+ public static string TopOf(AppPaths paths)
+ {
+ return System.IO.Path.GetDirectoryName(Full(paths.Root));
+ }
+
+ /// The first link among the data, spool and logs folders, or null: what every administrator command needs.
+ public static string FirstLinkInDataFolders(AppPaths paths)
+ {
+ string top = TopOf(paths);
+ return FirstLink(top, paths.SpoolDir) ?? FirstLink(top, paths.LogsDir);
+ }
+
+ ///
+ /// The first existing folder or file from the child of down to that
+ /// is a junction or symbolic link, or null. must lie below .
+ ///
+ public static string FirstLink(string top, string path)
+ {
+ string root = Full(top);
+ string full = Full(path);
+ if (!full.StartsWith(root + "\\", StringComparison.OrdinalIgnoreCase) && !full.StartsWith(root + "/", StringComparison.Ordinal))
+ {
+ throw new ArgumentException(path + " is not inside " + top + ".", nameof(path));
+ }
+ string current = root;
+ foreach (string part in full.Substring(root.Length).Split(new[] { '\\', '/' }, StringSplitOptions.RemoveEmptyEntries))
+ {
+ current = System.IO.Path.Combine(current, part);
+ FileAttributes attributes;
+ try
+ {
+ attributes = File.GetAttributes(current); // of the entry itself: a link is not followed at the last step
+ }
+ catch (FileNotFoundException)
+ {
+ return null; // nothing deeper exists either
+ }
+ catch (DirectoryNotFoundException)
+ {
+ return null;
+ }
+ if ((attributes & FileAttributes.ReparsePoint) != 0)
+ {
+ return current;
+ }
+ }
+ return null;
+ }
+
+ /// Throws LinkFoundException when FirstLink finds one.
+ public static void RefuseLinks(string top, string path)
+ {
+ string link = FirstLink(top, path);
+ if (link != null)
+ {
+ throw new LinkFoundException(link);
+ }
+ }
+
+ /// Creates (and the folders on the way) below , refusing links.
+ public static void CreateFolder(string top, string folder)
+ {
+ RefuseLinks(top, folder);
+ Directory.CreateDirectory(folder);
+ RefuseLinks(top, folder);
+ }
+
+ ///
+ /// Lets every user of the PC rename and delete the files the spooler writes into
+ /// (ProgramData gives Users only create rights; files there belong to whoever created them). The folder is
+ /// opened without following a link, checked to be the real folder at that path, and changed through that handle.
+ ///
+ public static void GrantUsersModify(string top, string folder)
+ {
+ CreateFolder(top, folder);
+ using (SafeFileHandle handle = Open(folder, ReadControl | WriteDac | FileReadAttributes, true))
+ {
+ ByHandleFileInformation info;
+ if (!GetFileInformationByHandle(handle, out info))
+ {
+ throw new Win32Exception(Marshal.GetLastWin32Error(), "The folder " + folder + " could not be checked");
+ }
+ if ((info.FileAttributes & (uint)FileAttributes.ReparsePoint) != 0 || (info.FileAttributes & (uint)FileAttributes.Directory) == 0)
+ {
+ throw new LinkFoundException(folder);
+ }
+ string expected;
+ using (SafeFileHandle topHandle = Open(top, FileReadAttributes, false))
+ {
+ expected = FinalPath(topHandle) + Full(folder).Substring(Full(top).Length);
+ }
+ string actual = FinalPath(handle);
+ if (!string.Equals(actual, expected, StringComparison.OrdinalIgnoreCase))
+ {
+ throw new LinkFoundException(folder + " (it leads to " + actual + ")");
+ }
+
+ var security = new HandleSecurity(handle);
+ security.Add(new FileSystemAccessRule(new SecurityIdentifier(WellKnownSidType.BuiltinUsersSid, null),
+ FileSystemRights.Modify | FileSystemRights.Synchronize,
+ InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit, PropagationFlags.None, AccessControlType.Allow));
+ security.Save(handle);
+ }
+ }
+
+ private static string Full(string path)
+ {
+ return System.IO.Path.GetFullPath(path).TrimEnd('\\', '/');
+ }
+
+ private static SafeFileHandle Open(string path, uint access, bool noFollow)
+ {
+ SafeFileHandle handle = CreateFile(path, access, FileShare.ReadWrite | FileShare.Delete, IntPtr.Zero, FileMode.Open,
+ FileFlagBackupSemantics | (noFollow ? FileFlagOpenReparsePoint : 0), IntPtr.Zero);
+ if (handle.IsInvalid)
+ {
+ int error = Marshal.GetLastWin32Error();
+ handle.Dispose();
+ throw new Win32Exception(error, "The folder " + path + " could not be opened");
+ }
+ return handle;
+ }
+
+ /// The path Windows itself gives the opened folder, without the \\?\ prefix.
+ private static string FinalPath(SafeFileHandle handle)
+ {
+ var buffer = new StringBuilder(1024);
+ uint length = GetFinalPathNameByHandle(handle, buffer, (uint)buffer.Capacity, 0);
+ if (length == 0 || length >= buffer.Capacity)
+ {
+ throw new Win32Exception(Marshal.GetLastWin32Error(), "The real path of a folder could not be read");
+ }
+ string path = buffer.ToString();
+ if (path.StartsWith(@"\\?\UNC\", StringComparison.OrdinalIgnoreCase)) return @"\\" + path.Substring(8).TrimEnd('\\');
+ if (path.StartsWith(@"\\?\", StringComparison.Ordinal)) return path.Substring(4).TrimEnd('\\');
+ return path.TrimEnd('\\');
+ }
+
+ /// A folder's access list read and written through an open handle (NativeObjectSecurity does the Windows calls).
+ private sealed class HandleSecurity : NativeObjectSecurity
+ {
+ public HandleSecurity(SafeHandle handle) : base(true, ResourceType.FileObject, handle, AccessControlSections.Access)
+ {
+ }
+
+ public void Add(FileSystemAccessRule rule)
+ {
+ AddAccessRule(rule);
+ }
+
+ public void Save(SafeHandle handle)
+ {
+ Persist(handle, AccessControlSections.Access);
+ }
+
+ public override Type AccessRightType
+ {
+ get { return typeof(FileSystemRights); }
+ }
+
+ public override Type AccessRuleType
+ {
+ get { return typeof(FileSystemAccessRule); }
+ }
+
+ public override Type AuditRuleType
+ {
+ get { return typeof(FileSystemAuditRule); }
+ }
+
+ public override AccessRule AccessRuleFactory(IdentityReference identityReference, int accessMask, bool isInherited,
+ InheritanceFlags inheritanceFlags, PropagationFlags propagationFlags, AccessControlType type)
+ {
+ return new FileSystemAccessRule(identityReference, (FileSystemRights)accessMask, inheritanceFlags, propagationFlags, type);
+ }
+
+ public override AuditRule AuditRuleFactory(IdentityReference identityReference, int accessMask, bool isInherited,
+ InheritanceFlags inheritanceFlags, PropagationFlags propagationFlags, AuditFlags flags)
+ {
+ return new FileSystemAuditRule(identityReference, (FileSystemRights)accessMask, inheritanceFlags, propagationFlags, flags);
+ }
+ }
+
+ private const uint ReadControl = 0x00020000;
+ private const uint WriteDac = 0x00040000;
+ private const uint FileReadAttributes = 0x00000080;
+ private const uint FileFlagBackupSemantics = 0x02000000;
+ private const uint FileFlagOpenReparsePoint = 0x00200000;
+
+ [StructLayout(LayoutKind.Sequential)]
+ private struct ByHandleFileInformation
+ {
+ public uint FileAttributes;
+ public System.Runtime.InteropServices.ComTypes.FILETIME CreationTime;
+ public System.Runtime.InteropServices.ComTypes.FILETIME LastAccessTime;
+ public System.Runtime.InteropServices.ComTypes.FILETIME LastWriteTime;
+ public uint VolumeSerialNumber;
+ public uint FileSizeHigh;
+ public uint FileSizeLow;
+ public uint NumberOfLinks;
+ public uint FileIndexHigh;
+ public uint FileIndexLow;
+ }
+
+ [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
+ private static extern SafeFileHandle CreateFile(string fileName, uint desiredAccess, FileShare shareMode, IntPtr securityAttributes,
+ FileMode creationDisposition, uint flagsAndAttributes, IntPtr templateFile);
+
+ [DllImport("kernel32.dll", SetLastError = true)]
+ [return: MarshalAs(UnmanagedType.Bool)]
+ private static extern bool GetFileInformationByHandle(SafeFileHandle file, out ByHandleFileInformation information);
+
+ [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
+ private static extern uint GetFinalPathNameByHandle(SafeFileHandle file, StringBuilder path, uint length, uint flags);
+ }
+}
diff --git a/src/PrintVect.Core/Host/ConnectionLimiter.cs b/src/PrintVect.Core/Host/ConnectionLimiter.cs
new file mode 100644
index 0000000..9bf12f3
--- /dev/null
+++ b/src/PrintVect.Core/Host/ConnectionLimiter.cs
@@ -0,0 +1,100 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+
+namespace PrintVect.Core.Host
+{
+ ///
+ /// How many job-port connections a host serves at once (0.5.8): at most 32 in all and 8 from one address, and at most
+ /// 120 new ones a minute from one address. A connection beyond that is closed at once, so one PC that opens
+ /// connections in a loop cannot use up the host or fill its log. A PC that prints normally needs a few at most.
+ ///
+ public sealed class ConnectionLimiter
+ {
+ public const int DefaultMaxTotal = 32;
+ public const int DefaultMaxPerAddress = 8;
+ public const int DefaultMaxPerMinute = 120;
+
+ private const int ForgetAbove = 256;
+ private readonly Dictionary _byAddress = new Dictionary(StringComparer.OrdinalIgnoreCase);
+ private readonly object _gate = new object();
+ private int _open;
+
+ public int MaxTotal { get; set; } = DefaultMaxTotal;
+ public int MaxPerAddress { get; set; } = DefaultMaxPerAddress;
+ public int MaxPerMinute { get; set; } = DefaultMaxPerMinute;
+
+ /// Null when the connection may be served (then Leave must follow), else why not.
+ public string TryEnter(string address, DateTime utcNow)
+ {
+ address = address ?? "";
+ lock (_gate)
+ {
+ if (_byAddress.Count > ForgetAbove)
+ {
+ Forget(utcNow);
+ }
+ Entry entry;
+ if (!_byAddress.TryGetValue(address, out entry))
+ {
+ entry = new Entry();
+ _byAddress[address] = entry;
+ }
+ entry.Recent.RemoveAll(t => utcNow - t > TimeSpan.FromMinutes(1));
+ if (_open >= MaxTotal)
+ {
+ return MaxTotal + " connections are open already";
+ }
+ if (entry.Open >= MaxPerAddress)
+ {
+ return MaxPerAddress + " connections from " + address + " are open already";
+ }
+ if (entry.Recent.Count >= MaxPerMinute)
+ {
+ return MaxPerMinute + " connections from " + address + " in the last minute";
+ }
+ entry.Recent.Add(utcNow);
+ entry.Open++;
+ _open++;
+ return null;
+ }
+ }
+
+ public void Leave(string address)
+ {
+ lock (_gate)
+ {
+ Entry entry;
+ if (_byAddress.TryGetValue(address ?? "", out entry) && entry.Open > 0)
+ {
+ entry.Open--;
+ _open--;
+ }
+ }
+ }
+
+ /// Drops addresses with nothing open and nothing in the last minute (many addresses must not grow the table).
+ private void Forget(DateTime utcNow)
+ {
+ foreach (Entry entry in _byAddress.Values)
+ {
+ entry.Recent.RemoveAll(t => utcNow - t > TimeSpan.FromMinutes(1));
+ }
+ foreach (string quiet in _byAddress.Where(e => e.Value.Open == 0 && e.Value.Recent.Count == 0).Select(e => e.Key).ToList())
+ {
+ _byAddress.Remove(quiet);
+ }
+ }
+
+ public int OpenCount
+ {
+ get { lock (_gate) { return _open; } }
+ }
+
+ private sealed class Entry
+ {
+ public int Open;
+ public readonly List Recent = new List();
+ }
+ }
+}
diff --git a/src/PrintVect.Core/Host/HostIdentity.cs b/src/PrintVect.Core/Host/HostIdentity.cs
new file mode 100644
index 0000000..cf8e7a6
--- /dev/null
+++ b/src/PrintVect.Core/Host/HostIdentity.cs
@@ -0,0 +1,85 @@
+using System;
+using System.Security.Cryptography;
+using PrintVect.Core.Config;
+using PrintVect.Core.Logging;
+using PrintVect.Core.Protocol;
+
+namespace PrintVect.Core.Host
+{
+ ///
+ /// This PC's identity as a host (0.5.8): an RSA-2048 key made on first start and kept in config.json, protected
+ /// for this PC (MachineProtection). The public half goes out with every list and discovery reply; a list request
+ /// with a challenge gets it signed (HostKeys), so a client follows this PC to a new address only when it really is
+ /// this PC.
+ ///
+ public sealed class HostIdentity : IDisposable
+ {
+ private readonly RSACryptoServiceProvider _rsa;
+ private readonly object _gate = new object();
+
+ private HostIdentity(RSACryptoServiceProvider rsa)
+ {
+ _rsa = rsa;
+ PublicKey = Convert.ToBase64String(rsa.ExportCspBlob(false));
+ KeyId = HostKeys.KeyIdOf(PublicKey);
+ }
+
+ /// The public key, base64 (what clients receive).
+ public string PublicKey { get; }
+
+ /// Its fingerprint (what clients remember).
+ public string KeyId { get; }
+
+ public static HostIdentity Create()
+ {
+ return new HostIdentity(new RSACryptoServiceProvider(2048) { PersistKeyInCsp = false });
+ }
+
+ ///
+ /// The key kept in config.json (AppConfig.HostKey), or a new one when there is none or it cannot be read here;
+ /// is then what config.json must keep from now on (else null).
+ ///
+ public static HostIdentity LoadOrCreate(string protectedKey, out string newProtectedKey)
+ {
+ newProtectedKey = null;
+ byte[] blob = MachineProtection.Unprotect(protectedKey);
+ if (blob != null)
+ {
+ try
+ {
+ var rsa = new RSACryptoServiceProvider { PersistKeyInCsp = false };
+ rsa.ImportCspBlob(blob);
+ return new HostIdentity(rsa);
+ }
+ catch (CryptographicException ex)
+ {
+ Log.Warn("This PC's identity key in config.json cannot be read (" + ex.Message + "); making a new one.");
+ }
+ }
+ else if (!string.IsNullOrWhiteSpace(protectedKey))
+ {
+ Log.Warn("The identity key in config.json was not made on this PC (copied from another one?); making a new one. "
+ + "If this PC's address changes, PCs that added its printers before must add them again.");
+ }
+
+ HostIdentity identity = Create();
+ newProtectedKey = MachineProtection.Protect(identity._rsa.ExportCspBlob(true));
+ Log.Info("Made this PC's identity key (fingerprint " + identity.KeyId.Substring(0, 16) + "…); other PCs remember it when they add a printer from here.");
+ return identity;
+ }
+
+ /// Base64 signature of the challenge, this PC's name and the address the asker reached it on.
+ public string Sign(string challenge, string hostName, string address)
+ {
+ lock (_gate)
+ {
+ return Convert.ToBase64String(_rsa.SignData(HostKeys.Message(challenge, hostName, address), HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1));
+ }
+ }
+
+ public void Dispose()
+ {
+ _rsa.Dispose();
+ }
+ }
+}
diff --git a/src/PrintVect.Core/Host/HostService.cs b/src/PrintVect.Core/Host/HostService.cs
index 7521668..f869b7c 100644
--- a/src/PrintVect.Core/Host/HostService.cs
+++ b/src/PrintVect.Core/Host/HostService.cs
@@ -29,9 +29,15 @@ public sealed class HostService : IDisposable
private readonly JobTracker _tracker;
private readonly IncomingSpool _spool;
private readonly ConcurrentDictionary _connections = new ConcurrentDictionary();
+ private readonly PinAttemptLimiter _pinTries = new PinAttemptLimiter();
+ private readonly Dictionary _refusedConnections = new Dictionary(StringComparer.OrdinalIgnoreCase);
+ private readonly object _spaceGate = new object();
+ private long _reservedBytes;
+ private Timer _sweep;
private readonly object _lifecycle = new object();
private SharedPrinter[] _shared = new SharedPrinter[0];
private string _pin = "";
+ private HostIdentity _identity;
private TcpListener _listener;
private CancellationTokenSource _stopping;
private PrintDispatcher _dispatcher;
@@ -63,6 +69,34 @@ public string Pin
set { Volatile.Write(ref _pin, value ?? ""); }
}
+ ///
+ /// This PC's identity key (0.5.8): its public half goes out with list and discovery replies, and a list request
+ /// with a challenge gets it signed. Null until it is loaded (the replies then go without it).
+ ///
+ public HostIdentity Identity
+ {
+ get { return Volatile.Read(ref _identity); }
+ set { Volatile.Write(ref _identity, value); }
+ }
+
+ /// Limits on simultaneous and repeated connections to the job port (0.5.8).
+ public ConnectionLimiter Connections { get; } = new ConnectionLimiter();
+
+ /// A connection must send its request within this time, or it is closed (0.5.8).
+ public TimeSpan HeaderTimeout { get; set; } = TimeSpan.FromSeconds(15);
+
+ ///
+ /// The most that received documents may take in spool\incoming\ together (0.5.8). Older files no job waits for are
+ /// deleted first to make room; a job that still does not fit is refused and waits for Retry on the sender.
+ ///
+ public long MaxIncomingBytes { get; set; } = 1024L * 1024 * 1024;
+
+ /// A job is refused when it would leave less than this free on the disk of spool\incoming\ (0.5.8).
+ public long MinFreeDiskBytes { get; set; } = 256L * 1024 * 1024;
+
+ /// Received files no job waits for any more (failed prints, leftovers) are deleted after this (0.5.8: every hour).
+ public TimeSpan KeepUnusedFilesFor { get; set; } = TimeSpan.FromHours(24);
+
/// The port actually bound (useful when 0 was requested).
public int Port { get; private set; }
@@ -135,7 +169,7 @@ public void Start(int port)
}
_spool.Ensure();
- int swept = _spool.SweepOlderThan(TimeSpan.FromHours(24));
+ int swept = _spool.DeleteUnusedOlderThan(KeepUnusedFilesFor, ActiveFiles());
var listener = new TcpListener(IPAddress.Any, port);
listener.Start(16);
@@ -145,6 +179,7 @@ public void Start(int port)
_dispatcher = new PrintDispatcher(_engine);
ApplyPauses(_dispatcher, new SharedPrinter[0], Volatile.Read(ref _shared));
StartedAt = DateTime.Now;
+ _sweep = new Timer(_ => SweepUnusedFiles(), null, TimeSpan.FromHours(1), TimeSpan.FromHours(1));
CancellationToken token = _stopping.Token;
Task acceptLoop = Task.Run(() => AcceptLoopAsync(listener, token));
@@ -160,6 +195,7 @@ public void Stop()
TcpListener listener;
CancellationTokenSource stopping;
PrintDispatcher dispatcher;
+ Timer sweep;
lock (_lifecycle)
{
if (_listener == null)
@@ -169,11 +205,17 @@ public void Stop()
listener = _listener;
stopping = _stopping;
dispatcher = _dispatcher;
+ sweep = _sweep;
_listener = null;
_stopping = null;
_dispatcher = null;
+ _sweep = null;
StartedAt = null;
}
+ if (sweep != null)
+ {
+ sweep.Dispose();
+ }
Log.Info("Sharing OFF: closing the job listener on port " + Port + ".");
stopping.Cancel();
@@ -222,12 +264,22 @@ private async Task AcceptLoopAsync(TcpListener listener, CancellationToken ct)
continue;
}
+ string address = RemoteAddress(Describe(client));
+ string tooMany = Connections.TryEnter(address, DateTime.UtcNow);
+ if (tooMany != null)
+ {
+ NoteRefusedConnection(address, tooMany);
+ SafeClose(client);
+ continue;
+ }
+
_connections.TryAdd(client, 0);
TcpClient accepted = client;
Task tracked = Task.Run(() => HandleConnectionAsync(accepted, ct)).ContinueWith(t =>
{
byte unused;
_connections.TryRemove(accepted, out unused);
+ Connections.Leave(address);
if (t.IsFaulted)
{
Log.Error("A connection handler failed unexpectedly.", t.Exception == null ? null : t.Exception.GetBaseException());
@@ -237,6 +289,108 @@ private async Task AcceptLoopAsync(TcpListener listener, CancellationToken ct)
Log.Info("Job listener stopped.");
}
+ /// Logs a connection closed by ConnectionLimiter at most once a minute per address, with how many since.
+ private void NoteRefusedConnection(string address, string reason)
+ {
+ DateTime now = DateTime.UtcNow;
+ int skipped;
+ lock (_refusedConnections)
+ {
+ RefusedConnections note;
+ if (_refusedConnections.TryGetValue(address, out note) && now - note.LoggedAt < TimeSpan.FromMinutes(1))
+ {
+ note.Since++;
+ return;
+ }
+ skipped = note == null ? 0 : note.Since;
+ if (_refusedConnections.Count > 256) _refusedConnections.Clear();
+ _refusedConnections[address] = new RefusedConnections { LoggedAt = now };
+ }
+ Log.Warn("Closed a connection from " + address + " at once: " + reason + (skipped > 0 ? " (" + skipped + " more closed since the last note)." : "."));
+ }
+
+ private sealed class RefusedConnections
+ {
+ public DateTime LoggedAt;
+ public int Since;
+ }
+
+ /// The files of jobs still waiting or printing: never deleted to make room.
+ private ICollection ActiveFiles()
+ {
+ return new HashSet(_tracker.All().Where(r => !JobStates.IsFinal(r.State) && !string.IsNullOrEmpty(r.FilePath))
+ .Select(r => Path.GetFullPath(r.FilePath)), StringComparer.OrdinalIgnoreCase);
+ }
+
+ private void SweepUnusedFiles()
+ {
+ try
+ {
+ _spool.DeleteUnusedOlderThan(KeepUnusedFilesFor, ActiveFiles());
+ }
+ catch (Exception ex)
+ {
+ Log.Error("The hourly clean-up of " + _spool.Directory + " failed; it runs again in an hour.", ex);
+ }
+ }
+
+ ///
+ /// Keeps room for a job of bytes (0.5.8): null when it fits (then ReleaseSpace must follow),
+ /// else the plain reason it does not. Unused older files are deleted first to make room.
+ ///
+ private string ReserveSpace(string jobId, long size)
+ {
+ string host = Environment.MachineName;
+ lock (_spaceGate)
+ {
+ long used = _spool.TotalBytes();
+ long over = used + _reservedBytes + size - MaxIncomingBytes;
+ if (over > 0)
+ {
+ used -= _spool.FreeUnused(over, ActiveFiles());
+ }
+ if (used + _reservedBytes + size > MaxIncomingBytes)
+ {
+ return host + " already holds " + Megabytes(used + _reservedBytes) + " of documents waiting to print, the most it keeps. "
+ + "This job waits on the PC that sent it: press Retry waiting once those have printed.";
+ }
+ long free = FreeDiskBytes(jobId);
+ if (free >= 0 && free - size < MinFreeDiskBytes)
+ {
+ return "The disk of " + host + " is nearly full (" + Megabytes(free) + " free), so it takes no more documents. "
+ + "Free some space on " + host + ", then press Retry waiting.";
+ }
+ _reservedBytes += size;
+ return null;
+ }
+ }
+
+ private void ReleaseSpace(long size)
+ {
+ lock (_spaceGate)
+ {
+ _reservedBytes -= size;
+ }
+ }
+
+ private long FreeDiskBytes(string jobId)
+ {
+ try
+ {
+ return new DriveInfo(Path.GetPathRoot(Path.GetFullPath(_spool.Directory))).AvailableFreeSpace;
+ }
+ catch (Exception ex)
+ {
+ Log.Warn(jobId, "The free space on the disk of " + _spool.Directory + " could not be read: " + ex.Message);
+ return -1;
+ }
+ }
+
+ private static string Megabytes(long bytes)
+ {
+ return (bytes / (1024 * 1024)).ToString("N0", CultureInfo.CurrentCulture) + " MB";
+ }
+
private async Task HandleConnectionAsync(TcpClient client, CancellationToken ct)
{
string remote = Describe(client);
@@ -248,7 +402,8 @@ private async Task HandleConnectionAsync(TcpClient client, CancellationToken ct)
using (var timeout = CancellationTokenSource.CreateLinkedTokenSource(ct))
using (timeout.Token.Register(() => SafeClose(client)))
{
- timeout.CancelAfter(ProtocolConstants.TransferTimeout);
+ timeout.CancelAfter(HeaderTimeout); // the request must come at once (0.5.8); the transfer then gets its 5 minutes
+ bool headerRead = false;
NetworkStream stream = null;
try
{
@@ -257,6 +412,8 @@ private async Task HandleConnectionAsync(TcpClient client, CancellationToken ct)
Log.Info("Connection from " + remote + ".");
RequestHeader header = await Framing.ReadHeaderAsync(stream, timeout.Token).ConfigureAwait(false);
+ headerRead = true;
+ timeout.CancelAfter(ProtocolConstants.TransferTimeout);
jobId = header.JobId;
object reply;
@@ -274,7 +431,7 @@ private async Task HandleConnectionAsync(TcpClient client, CancellationToken ct)
switch (header.Type)
{
case RequestTypes.List:
- reply = BuildListReply(localIp);
+ reply = BuildListReply(localIp, header.Challenge);
break;
case RequestTypes.Status:
reply = HandleStatus(header);
@@ -283,7 +440,7 @@ private async Task HandleConnectionAsync(TcpClient client, CancellationToken ct)
reply = await HandleJobAsync(header, stream, remote, timeout.Token).ConfigureAwait(false);
break;
case RequestTypes.Hello:
- reply = HandleHello(header, client);
+ reply = HandleHello(header, remote);
break;
default:
Log.Warn(jobId, "Unknown request type \"" + header.Type + "\" from " + remote + ".");
@@ -310,8 +467,9 @@ private async Task HandleConnectionAsync(TcpClient client, CancellationToken ct)
}
catch (Exception ex) when (timeout.IsCancellationRequested)
{
- Log.Warn(jobId, "Connection from " + remote + " timed out after " + ProtocolConstants.TransferTimeout.TotalMinutes
- + " minutes (" + ex.GetType().Name + ").");
+ Log.Warn(jobId, "Connection from " + remote + (headerRead
+ ? " timed out after " + ProtocolConstants.TransferTimeout.TotalMinutes + " minutes"
+ : " sent no request within " + HeaderTimeout.TotalSeconds + " s; closed") + " (" + ex.GetType().Name + ").");
}
catch (Exception ex)
{
@@ -329,7 +487,7 @@ public ListReply BuildListReplyFor(System.Net.IPAddress remote)
return BuildListReply(local == null ? "" : local.ToString());
}
- private ListReply BuildListReply(string localIp)
+ private ListReply BuildListReply(string localIp, string challenge = null)
{
SharedPrinter[] shared = Volatile.Read(ref _shared);
IList statuses;
@@ -343,7 +501,12 @@ private ListReply BuildListReply(string localIp)
statuses = new List();
}
- var reply = new ListReply { Host = Environment.MachineName, Ip = localIp, Port = Port };
+ HostIdentity identity = Identity;
+ var reply = new ListReply { Host = Environment.MachineName, Ip = localIp, Port = Port, HostKey = identity == null ? null : identity.PublicKey };
+ if (identity != null && !string.IsNullOrEmpty(challenge))
+ {
+ reply.HostSig = identity.Sign(challenge, reply.Host, localIp); // proves this PC answers on this address
+ }
foreach (SharedPrinter printer in shared)
{
LocalPrinterInfo local = statuses.FirstOrDefault(s => string.Equals(s.Name, printer.LocalName, StringComparison.OrdinalIgnoreCase));
@@ -426,13 +589,14 @@ private async Task HandleJobAsync(RequestHeader header, NetworkStream
remote, header.Client, header.User, header.PrinterId, header.Doc, header.Format, header.Size));
SharedPrinter printer;
- string refusal = Validate(header, out printer);
+ bool pinRefused;
+ string refusal = Validate(header, RemoteAddress(remote), out printer, out pinRefused);
if (refusal != null)
{
Log.Warn(jobId, "Refused: " + refusal);
await DrainBodyAsync(stream, header, jobId, ct).ConfigureAwait(false);
JobReply refused = JobReply.Error(jobId, refusal);
- refused.Retry = !PinHash.Matches(Pin, header.Pin); // once the PINs match, the same job can go again
+ refused.Retry = pinRefused; // once the PINs match, the same job can go again
return refused;
}
Presence.Seen(header.Client, RemoteAddress(remote), null, null, header.User);
@@ -454,6 +618,28 @@ private async Task HandleJobAsync(RequestHeader header, NetworkStream
};
}
+ string noRoom = ReserveSpace(jobId, header.Size);
+ if (noRoom != null)
+ {
+ Log.Warn(jobId, "Refused: " + noRoom);
+ await DrainBodyAsync(stream, header, jobId, ct).ConfigureAwait(false);
+ JobReply full = JobReply.Error(jobId, noRoom);
+ full.Retry = true;
+ return full;
+ }
+ try
+ {
+ return await ReceiveAndPrintAsync(header, jobId, printer, remote, stream, ct).ConfigureAwait(false);
+ }
+ finally
+ {
+ ReleaseSpace(header.Size);
+ }
+ }
+
+ private async Task ReceiveAndPrintAsync(RequestHeader header, string jobId, SharedPrinter printer, string remote, NetworkStream stream,
+ CancellationToken ct)
+ {
string path = _spool.PathFor(jobId, header.Format);
JobRecord record = _tracker.Add(new JobRecord
{
@@ -509,9 +695,9 @@ private async Task HandleJobAsync(RequestHeader header, NetworkStream
XpsFileInfo content = XpsFormatSniffer.Inspect(path);
if (!content.IsXpsPackage)
{
- string message = "The file is not an XPS document (" + content.Problem + "). It was kept at "
- + path + " on " + Environment.MachineName + " for diagnosis.";
+ string message = "The file is not an XPS document (" + content.Problem + "); " + Environment.MachineName + " deleted it.";
Log.Warn(jobId, message);
+ _spool.DeleteQuietly(path, jobId); // 0.5.8: junk is not kept (it filled the disk)
RaiseFinished(_tracker.Update(jobId, JobStates.Error, message));
return JobReply.Error(jobId, message);
}
@@ -616,14 +802,76 @@ public string CancelQueued(string jobId)
return null;
}
- /// A client says it uses this host's printers; it is listed on the Share page with its Windows version.
- private JobReply HandleHello(RequestHeader header, TcpClient client)
+ ///
+ /// A client says it uses this host's printers; it is listed on the Share page with its Windows version. With a
+ /// sharing PIN, only a PC that proves the PIN is listed (0.5.8), so nobody can fill the list with made-up PCs.
+ ///
+ private JobReply HandleHello(RequestHeader header, string remote)
{
- string name = string.IsNullOrWhiteSpace(header.Client) ? RemoteAddress(Describe(client)) : header.Client.Trim();
- Presence.Seen(name, RemoteAddress(Describe(client)), header.Os, header.AppVersion, header.User);
+ string address = RemoteAddress(remote);
+ string name = string.IsNullOrWhiteSpace(header.Client) ? address : header.Client.Trim();
+ string refusal = CheckPin(header, address);
+ if (refusal != null)
+ {
+ Log.Warn("Hello from " + name + " (" + address + ") refused: " + refusal);
+ return JobReply.Error(null, refusal);
+ }
+ Presence.Seen(name, address, header.Os, header.AppVersion, header.User);
return new JobReply { Ok = true, Message = Environment.MachineName + " knows that " + name + " uses its printers." };
}
+ ///
+ /// Null when the request may go on: this PC has no sharing PIN, or the request proves it (PinProof). Else the
+ /// plain reason. Wrong PINs are counted per address; after 5 the address waits (PinAttemptLimiter).
+ ///
+ private string CheckPin(RequestHeader header, string address)
+ {
+ string pin = Pin;
+ if (string.IsNullOrEmpty(pin))
+ {
+ return null;
+ }
+ string host = Environment.MachineName;
+ string sender = string.IsNullOrWhiteSpace(header.Client) ? address : header.Client.Trim();
+ string what = header.Type == RequestTypes.Hello ? "the hello from " + sender : "this job";
+ string again = "Set the same sharing PIN in PrintVect Settings on both PCs.";
+ DateTime now = DateTime.UtcNow;
+ TimeSpan wait = _pinTries.WaitFor(address, now);
+ if (wait > TimeSpan.Zero)
+ {
+ return "Too many wrong sharing PINs came from " + sender + ", so " + host + " checks its PIN again in " + Minutes(wait)
+ + ". " + again;
+ }
+ switch (PinProof.Check(pin, header, now))
+ {
+ case PinCheck.Open:
+ case PinCheck.Accepted:
+ _pinTries.Succeeded(address);
+ return null;
+ case PinCheck.Outdated:
+ return sender + " runs a PrintVect older than 0.5.8, which sends the sharing PIN in a way " + host
+ + " no longer accepts. Update PrintVect on " + sender + " (Settings, Updates, Check now).";
+ case PinCheck.ClockOff:
+ return "The clocks of " + sender + " (" + PinProof.TimeOf(header).ToString("g", CultureInfo.CurrentCulture) + ") and " + host
+ + " (" + DateTime.Now.ToString("g", CultureInfo.CurrentCulture) + ") differ by more than a day, so " + host
+ + " cannot check the sharing PIN. Set the right date and time on both PCs (Windows Settings, Time & language).";
+ case PinCheck.Wrong:
+ int left = _pinTries.Failed(address, now);
+ Log.Warn(header.JobId, "Wrong sharing PIN from " + sender + " (" + address + "); "
+ + (left > 0 ? left + " more wrong tr" + (left == 1 ? "y" : "ies") + " before it has to wait."
+ : "it waits " + Minutes(_pinTries.WaitFor(address, now)) + " before its PIN is checked again."));
+ return host + " asks for the sharing PIN, and " + what + " came with a different one. " + again;
+ default:
+ return host + " asks for the sharing PIN, and " + what + " came without one. " + again;
+ }
+ }
+
+ private static string Minutes(TimeSpan wait)
+ {
+ int minutes = Math.Max(1, (int)Math.Ceiling(wait.TotalMinutes));
+ return minutes == 1 ? "1 minute" : minutes + " minutes";
+ }
+
/// "10.0.0.5:51234" gives "10.0.0.5".
private static string RemoteAddress(string endpoint)
{
@@ -632,15 +880,16 @@ private static string RemoteAddress(string endpoint)
return colon > 0 ? endpoint.Substring(0, colon) : endpoint;
}
- private string Validate(RequestHeader header, out SharedPrinter printer)
+ private string Validate(RequestHeader header, string address, out SharedPrinter printer, out bool pinRefused)
{
printer = null;
string host = Environment.MachineName;
- if (!PinHash.Matches(Pin, header.Pin))
+ string pinProblem = CheckPin(header, address);
+ pinRefused = pinProblem != null;
+ if (pinRefused)
{
- return host + " asks for the sharing PIN, and this job came with a different one or none. "
- + "Set the same sharing PIN in PrintVect Settings on both PCs.";
+ return pinProblem;
}
if (!JobFormats.IsKnown(header.Format))
{
@@ -720,7 +969,7 @@ private void OnPrintFinished(string jobId, string path, Task task)
}
else
{
- Log.Info(jobId, "File kept for diagnosis: " + path);
+ Log.Info(jobId, "File kept for diagnosis (deleted after " + KeepUnusedFilesFor.TotalHours + " hours, or sooner to make room): " + path);
}
Log.Info(jobId, "Finished: " + outcome.State + ". " + outcome.Message);
RaiseFinished(snapshot);
diff --git a/src/PrintVect.Core/Host/IncomingSpool.cs b/src/PrintVect.Core/Host/IncomingSpool.cs
index 23ccab8..cbc927c 100644
--- a/src/PrintVect.Core/Host/IncomingSpool.cs
+++ b/src/PrintVect.Core/Host/IncomingSpool.cs
@@ -1,5 +1,7 @@
using System;
+using System.Collections.Generic;
using System.IO;
+using System.Linq;
using PrintVect.Core.Config;
using PrintVect.Core.Logging;
@@ -45,30 +47,23 @@ public void DeleteQuietly(string path, string jobId)
}
}
- /// Removes leftovers from earlier runs. Returns how many files were deleted.
- public int SweepOlderThan(TimeSpan age)
+ /// The size of every file in the folder together.
+ public long TotalBytes()
{
- if (!System.IO.Directory.Exists(Directory))
- {
- return 0;
- }
+ return Files().Sum(f => f.Length);
+ }
- int deleted = 0;
+ ///
+ /// Removes received files no job waits for any more (kept after a failed print, or left by an earlier run)
+ /// that are older than . Returns how many were deleted.
+ ///
+ public int DeleteUnusedOlderThan(TimeSpan age, ICollection inUse)
+ {
DateTime cutoff = DateTime.Now - age;
- foreach (string file in System.IO.Directory.GetFiles(Directory))
+ int deleted = 0;
+ foreach (FileInfo file in Unused(inUse).Where(f => f.LastWriteTime < cutoff))
{
- try
- {
- if (File.GetLastWriteTime(file) < cutoff)
- {
- File.Delete(file);
- deleted++;
- }
- }
- catch (Exception ex)
- {
- Log.Warn("Could not delete old spool file " + file + ": " + ex.Message);
- }
+ if (TryDelete(file)) deleted++;
}
if (deleted > 0)
{
@@ -76,5 +71,47 @@ public int SweepOlderThan(TimeSpan age)
}
return deleted;
}
+
+ /// Deletes unused files, oldest first, until are free. Returns the bytes freed.
+ public long FreeUnused(long bytes, ICollection inUse)
+ {
+ long freed = 0;
+ foreach (FileInfo file in Unused(inUse).OrderBy(f => f.LastWriteTimeUtc))
+ {
+ if (freed >= bytes) break;
+ long length = file.Length;
+ if (TryDelete(file)) freed += length;
+ }
+ if (freed > 0)
+ {
+ Log.Info("Deleted " + freed + " bytes of older received files to make room in " + Directory);
+ }
+ return freed;
+ }
+
+ private IEnumerable Files()
+ {
+ var folder = new DirectoryInfo(Directory);
+ return folder.Exists ? folder.GetFiles() : new FileInfo[0];
+ }
+
+ private IEnumerable Unused(ICollection inUse)
+ {
+ return Files().Where(f => inUse == null || !inUse.Contains(f.FullName)).ToList();
+ }
+
+ private static bool TryDelete(FileInfo file)
+ {
+ try
+ {
+ file.Delete();
+ return true;
+ }
+ catch (Exception ex)
+ {
+ Log.Warn("Could not delete the received file " + file.FullName + ": " + ex.Message);
+ return false;
+ }
+ }
}
}
diff --git a/src/PrintVect.Core/Host/PinAttemptLimiter.cs b/src/PrintVect.Core/Host/PinAttemptLimiter.cs
new file mode 100644
index 0000000..d3e5589
--- /dev/null
+++ b/src/PrintVect.Core/Host/PinAttemptLimiter.cs
@@ -0,0 +1,95 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+
+namespace PrintVect.Core.Host
+{
+ ///
+ /// Wrong sharing PINs per sending address (0.5.8). After 5 wrong tries the address waits 15 minutes before it may
+ /// try again, twice as long after each further 5 (at most 4 hours). A right PIN, or a day without a wrong one,
+ /// forgets the address. Trying every 4-digit PIN this way takes about a year instead of seconds.
+ ///
+ public sealed class PinAttemptLimiter
+ {
+ public const int TriesBeforeWait = 5;
+ public static readonly TimeSpan FirstWait = TimeSpan.FromMinutes(15);
+ public static readonly TimeSpan LongestWait = TimeSpan.FromHours(4);
+ public static readonly TimeSpan ForgetAfter = TimeSpan.FromDays(1);
+ private const int MaxAddresses = 1024;
+
+ private readonly Dictionary _entries = new Dictionary(StringComparer.OrdinalIgnoreCase);
+ private readonly object _gate = new object();
+
+ /// How long must still wait before its PIN is checked again; zero when it may try.
+ public TimeSpan WaitFor(string address, DateTime utcNow)
+ {
+ lock (_gate)
+ {
+ Entry entry = Find(address ?? "", utcNow);
+ return entry == null || entry.WaitUntil <= utcNow ? TimeSpan.Zero : entry.WaitUntil - utcNow;
+ }
+ }
+
+ /// Notes a wrong PIN. Returns the tries left before a wait; 0 means the address now waits.
+ public int Failed(string address, DateTime utcNow)
+ {
+ address = address ?? "";
+ lock (_gate)
+ {
+ Entry entry = Find(address, utcNow);
+ if (entry == null)
+ {
+ if (_entries.Count >= MaxAddresses)
+ {
+ _entries.Remove(_entries.OrderBy(e => e.Value.LastWrong).First().Key);
+ }
+ entry = new Entry();
+ _entries[address] = entry;
+ }
+ entry.Wrong++;
+ entry.LastWrong = utcNow;
+ if (entry.Wrong < TriesBeforeWait)
+ {
+ return TriesBeforeWait - entry.Wrong;
+ }
+ double minutes = Math.Min(FirstWait.TotalMinutes * Math.Pow(2, entry.Waits), LongestWait.TotalMinutes);
+ entry.WaitUntil = utcNow + TimeSpan.FromMinutes(minutes);
+ entry.Waits++;
+ entry.Wrong = 0;
+ return 0;
+ }
+ }
+
+ /// A right PIN: the address starts afresh.
+ public void Succeeded(string address)
+ {
+ lock (_gate)
+ {
+ _entries.Remove(address ?? "");
+ }
+ }
+
+ private Entry Find(string address, DateTime utcNow)
+ {
+ Entry entry;
+ if (!_entries.TryGetValue(address, out entry))
+ {
+ return null;
+ }
+ if (entry.WaitUntil <= utcNow && utcNow - entry.LastWrong > ForgetAfter)
+ {
+ _entries.Remove(address);
+ return null;
+ }
+ return entry;
+ }
+
+ private sealed class Entry
+ {
+ public int Wrong;
+ public int Waits;
+ public DateTime LastWrong;
+ public DateTime WaitUntil;
+ }
+ }
+}
diff --git a/src/PrintVect.Core/PrintVect.Core.csproj b/src/PrintVect.Core/PrintVect.Core.csproj
index dd0eb21..871e8f8 100644
--- a/src/PrintVect.Core/PrintVect.Core.csproj
+++ b/src/PrintVect.Core/PrintVect.Core.csproj
@@ -14,6 +14,8 @@
+
+
diff --git a/src/PrintVect.Core/Protocol/HostKeys.cs b/src/PrintVect.Core/Protocol/HostKeys.cs
new file mode 100644
index 0000000..2687fbf
--- /dev/null
+++ b/src/PrintVect.Core/Protocol/HostKeys.cs
@@ -0,0 +1,112 @@
+using System;
+using System.Globalization;
+using System.Net;
+using System.Security.Cryptography;
+using System.Text;
+
+namespace PrintVect.Core.Protocol
+{
+ ///
+ /// A host's identity key as other PCs see it (0.5.8): the public half (an RSA CSP blob in base64) travels in list
+ /// and discovery replies, and a client remembers its fingerprint (KeyIdOf) for each printer it adds. A PC
+ /// name or printer id can be claimed by any PC; only the real host can sign a client's random challenge, together
+ /// with its name and the address it answers on, with the key behind that fingerprint.
+ ///
+ public static class HostKeys
+ {
+ private const string Label = "PrintVect host 1";
+
+ /// A fresh random challenge, 32 hex digits.
+ public static string NewChallenge()
+ {
+ var bytes = new byte[16];
+ using (var random = RandomNumberGenerator.Create())
+ {
+ random.GetBytes(bytes);
+ }
+ return Hex(bytes);
+ }
+
+ /// The fingerprint a client remembers: SHA-256 of the public key, 64 hex digits. Null for a missing or broken key.
+ public static string KeyIdOf(string publicKey)
+ {
+ byte[] blob = Decode(publicKey);
+ if (blob == null)
+ {
+ return null;
+ }
+ using (var sha = SHA256.Create())
+ {
+ return Hex(sha.ComputeHash(blob));
+ }
+ }
+
+ /// What the host signs: the challenge, its name and the address the asker reached it on.
+ public static byte[] Message(string challenge, string hostName, string address)
+ {
+ return Encoding.UTF8.GetBytes(string.Join("\n", Label, challenge ?? "", (hostName ?? "").Trim().ToUpperInvariant(), NormalAddress(address)));
+ }
+
+ /// True when is the holder of signing that challenge, name and address.
+ public static bool Verify(string publicKey, string challenge, string hostName, string address, string signature)
+ {
+ byte[] blob = Decode(publicKey);
+ byte[] sig = Decode(signature);
+ if (blob == null || sig == null || string.IsNullOrEmpty(challenge))
+ {
+ return false;
+ }
+ try
+ {
+ using (var rsa = new RSACryptoServiceProvider { PersistKeyInCsp = false })
+ {
+ rsa.ImportCspBlob(blob);
+ return rsa.VerifyData(Message(challenge, hostName, address), sig, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1);
+ }
+ }
+ catch (CryptographicException)
+ {
+ return false; // not an RSA public key: certainly not the host's
+ }
+ }
+
+ /// "192.168.010.005" and "192.168.10.5" are the same address; a name stays as it is (upper case).
+ internal static string NormalAddress(string address)
+ {
+ IPAddress parsed;
+ string text = (address ?? "").Trim();
+ if (IPAddress.TryParse(text, out parsed))
+ {
+ if (parsed.IsIPv4MappedToIPv6) parsed = parsed.MapToIPv4();
+ return parsed.ToString();
+ }
+ return text.ToUpperInvariant();
+ }
+
+ private static byte[] Decode(string base64)
+ {
+ if (string.IsNullOrWhiteSpace(base64))
+ {
+ return null;
+ }
+ try
+ {
+ return Convert.FromBase64String(base64.Trim());
+ }
+ catch (FormatException)
+ {
+ return null;
+ }
+ }
+
+ private static string Hex(byte[] bytes)
+ {
+ var sb = new StringBuilder(bytes.Length * 2);
+ foreach (byte b in bytes)
+ {
+ sb.Append(b.ToString("x2", CultureInfo.InvariantCulture));
+ }
+ return sb.ToString();
+ }
+ }
+}
diff --git a/src/PrintVect.Core/Protocol/JobClient.cs b/src/PrintVect.Core/Protocol/JobClient.cs
index 17003a1..823afe9 100644
--- a/src/PrintVect.Core/Protocol/JobClient.cs
+++ b/src/PrintVect.Core/Protocol/JobClient.cs
@@ -41,9 +41,10 @@ public string DisplayName
public TimeSpan ConnectTimeout { get; set; } = ProtocolConstants.ConnectTimeout;
public TimeSpan TransferTimeout { get; set; } = ProtocolConstants.TransferTimeout;
- public async Task ListPrintersAsync(CancellationToken ct)
+ /// 0.5.8: asks the host to sign this with its identity key (HostKeys); null for a plain list.
+ public async Task ListPrintersAsync(CancellationToken ct, string challenge = null)
{
- string line = await ExchangeAsync(RequestHeader.ForList(), null, null, ct).ConfigureAwait(false);
+ string line = await ExchangeAsync(RequestHeader.ForList(challenge), null, null, ct).ConfigureAwait(false);
return Framing.ParseReply(line);
}
@@ -96,6 +97,10 @@ public async Task SendJobAsync(RequestHeader header, string filePath,
private async Task ExchangeAsync(RequestHeader header, string bodyPath, IProgress progress, CancellationToken ct)
{
+ if (!string.IsNullOrEmpty(header.PinToSign))
+ {
+ PinProof.Sign(header, header.PinToSign, DateTime.UtcNow); // fresh for every try: a new nonce and time
+ }
using (var client = new TcpClient())
using (var timeout = CancellationTokenSource.CreateLinkedTokenSource(ct))
using (timeout.Token.Register(() => SafeClose(client)))
diff --git a/src/PrintVect.Core/Protocol/Messages.cs b/src/PrintVect.Core/Protocol/Messages.cs
index 3a06823..8da8ce2 100644
--- a/src/PrintVect.Core/Protocol/Messages.cs
+++ b/src/PrintVect.Core/Protocol/Messages.cs
@@ -88,9 +88,31 @@ public sealed class RequestHeader
[JsonProperty("doc", NullValueHandling = NullValueHandling.Ignore)]
public string Doc { get; set; }
- /// SHA-256 hex of the shared PIN, or empty/absent when no PIN is used.
+ ///
+ /// Before 0.5.8: SHA-256 hex of the sharing PIN. No longer sent; a host that sees it tells the sender to update.
+ ///
[JsonProperty("pin", NullValueHandling = NullValueHandling.Ignore)]
- public string Pin { get; set; }
+ public string LegacyPinHash { get; set; }
+
+ /// 0.5.8: a random value that makes the PIN proof of this request one of a kind.
+ [JsonProperty("nonce", NullValueHandling = NullValueHandling.Ignore)]
+ public string Nonce { get; set; }
+
+ /// 0.5.8: when the PIN proof was made, in seconds since 1970 (UTC).
+ [JsonProperty("time", DefaultValueHandling = DefaultValueHandling.Ignore)]
+ public long Time { get; set; }
+
+ /// 0.5.8: the one-time proof that the sender knows the sharing PIN (PinProof); absent without a PIN.
+ [JsonProperty("pinProof", NullValueHandling = NullValueHandling.Ignore)]
+ public string Proof { get; set; }
+
+ /// List only (0.5.8): a random value the host signs with its identity key (ListReply.HostSig).
+ [JsonProperty("challenge", NullValueHandling = NullValueHandling.Ignore)]
+ public string Challenge { get; set; }
+
+ /// The PIN that JobClient proves just before sending. Never written to the network.
+ [JsonIgnore]
+ public string PinToSign { get; set; }
/// Copies the host should print; 1 when absent. Read from the XPS print ticket on the client (M3).
[Newtonsoft.Json.JsonProperty("copies", DefaultValueHandling = Newtonsoft.Json.DefaultValueHandling.Ignore)]
@@ -108,7 +130,7 @@ public sealed class RequestHeader
[JsonProperty("printers", NullValueHandling = NullValueHandling.Ignore)]
public List Printers { get; set; }
- public static RequestHeader ForHello(string os, string appVersion, IEnumerable printerIds)
+ public static RequestHeader ForHello(string os, string appVersion, IEnumerable printerIds, string pin = null)
{
return new RequestHeader
{
@@ -117,13 +139,14 @@ public static RequestHeader ForHello(string os, string appVersion, IEnumerable() : new List(printerIds)
+ Printers = printerIds == null ? new List() : new List(printerIds),
+ PinToSign = pin
};
}
- public static RequestHeader ForList()
+ public static RequestHeader ForList(string challenge = null)
{
- return new RequestHeader { Type = RequestTypes.List };
+ return new RequestHeader { Type = RequestTypes.List, Challenge = challenge };
}
public static RequestHeader ForStatus(string jobId)
@@ -144,7 +167,7 @@ public static RequestHeader ForJob(string printerId, string fileName, string for
Client = Environment.MachineName,
User = Environment.UserName,
Doc = doc ?? "",
- Pin = string.IsNullOrEmpty(pin) ? "" : PinHash.Compute(pin)
+ PinToSign = pin
};
}
}
@@ -225,5 +248,13 @@ public sealed class ListReply
[JsonProperty("message", NullValueHandling = NullValueHandling.Ignore)]
public string Message { get; set; }
+
+ /// 0.5.8: the host's public identity key (HostKeys); a client remembers its fingerprint with each printer.
+ [JsonProperty("hostKey", NullValueHandling = NullValueHandling.Ignore)]
+ public string HostKey { get; set; }
+
+ /// 0.5.8, list replies to a request with a challenge: the host's signature of challenge, name and address.
+ [JsonProperty("hostSig", NullValueHandling = NullValueHandling.Ignore)]
+ public string HostSig { get; set; }
}
}
diff --git a/src/PrintVect.Core/Protocol/PinHash.cs b/src/PrintVect.Core/Protocol/PinHash.cs
deleted file mode 100644
index fc38053..0000000
--- a/src/PrintVect.Core/Protocol/PinHash.cs
+++ /dev/null
@@ -1,34 +0,0 @@
-using System;
-using System.Security.Cryptography;
-using System.Text;
-
-namespace PrintVect.Core.Protocol
-{
- /// The optional shared PIN travels as a SHA-256 hex digest, never in clear (brief, section 6).
- public static class PinHash
- {
- public static string Compute(string pin)
- {
- using (var sha = SHA256.Create())
- {
- byte[] hash = sha.ComputeHash(Encoding.UTF8.GetBytes(pin ?? ""));
- var sb = new StringBuilder(hash.Length * 2);
- foreach (byte b in hash)
- {
- sb.Append(b.ToString("x2"));
- }
- return sb.ToString();
- }
- }
-
- /// True when the host has no PIN, or the header carries the digest of the host's PIN.
- public static bool Matches(string hostPin, string headerPinDigest)
- {
- if (string.IsNullOrEmpty(hostPin))
- {
- return true;
- }
- return string.Equals(Compute(hostPin), headerPinDigest ?? "", StringComparison.OrdinalIgnoreCase);
- }
- }
-}
diff --git a/src/PrintVect.Core/Protocol/PinProof.cs b/src/PrintVect.Core/Protocol/PinProof.cs
new file mode 100644
index 0000000..e4d5063
--- /dev/null
+++ b/src/PrintVect.Core/Protocol/PinProof.cs
@@ -0,0 +1,117 @@
+using System;
+using System.Globalization;
+using System.Security.Cryptography;
+using System.Text;
+
+namespace PrintVect.Core.Protocol
+{
+ /// What a host found when it checked a request against its sharing PIN.
+ public enum PinCheck
+ {
+ /// The host has no PIN: open to the network.
+ Open,
+ Accepted,
+ /// No proof at all (the sender has no PIN set).
+ Missing,
+ /// Only the plain hash of PrintVect before 0.5.8: the sender must be updated.
+ Outdated,
+ /// The proof's time is more than ClockTolerance away from the host's clock.
+ ClockOff,
+ Wrong
+ }
+
+ ///
+ /// The sharing PIN never travels, not even as a hash (0.5.8). A job or hello carries a one-time proof instead:
+ /// PBKDF2-HMAC-SHA256 of the PIN, salted with the request's random nonce, its time and the job's printer, id and
+ /// size. A recorded proof does not work for another job, and every guess at the PIN costs the guesser the same
+ /// 20,000 rounds. Before 0.5.8 the header carried SHA-256 of the PIN, which anyone who saw it could reuse forever.
+ /// A short PIN can still be guessed from recorded traffic with enough computing power: longer PINs are safer.
+ ///
+ public static class PinProof
+ {
+ public const int Iterations = 20000;
+
+ /// How far the two PCs' clocks may differ. A recorded proof is refused after this.
+ public static readonly TimeSpan ClockTolerance = TimeSpan.FromHours(24);
+
+ private const string Label = "PrintVect PIN 1";
+
+ /// Sets the header's nonce, time and proof for (just before it is sent).
+ public static void Sign(RequestHeader header, string pin, DateTime utcNow)
+ {
+ if (header == null) throw new ArgumentNullException(nameof(header));
+ if (string.IsNullOrEmpty(pin))
+ {
+ header.Nonce = null;
+ header.Time = 0;
+ header.Proof = null;
+ return;
+ }
+ header.Nonce = Guid.NewGuid().ToString("N");
+ header.Time = UnixSeconds(utcNow);
+ header.Proof = Compute(pin, header);
+ }
+
+ /// Checks a received header against the host's PIN.
+ public static PinCheck Check(string hostPin, RequestHeader header, DateTime utcNow)
+ {
+ if (string.IsNullOrEmpty(hostPin))
+ {
+ return PinCheck.Open;
+ }
+ if (header == null || string.IsNullOrEmpty(header.Proof) || string.IsNullOrEmpty(header.Nonce) || header.Time <= 0)
+ {
+ return header != null && !string.IsNullOrEmpty(header.LegacyPinHash) ? PinCheck.Outdated : PinCheck.Missing;
+ }
+ long skew = Math.Abs(UnixSeconds(utcNow) - header.Time);
+ if (skew > (long)ClockTolerance.TotalSeconds)
+ {
+ return PinCheck.ClockOff;
+ }
+ return FixedTimeEquals(Compute(hostPin, header), header.Proof.ToLowerInvariant()) ? PinCheck.Accepted : PinCheck.Wrong;
+ }
+
+ /// The header's time as the host's local clock reads it, for messages.
+ public static DateTime TimeOf(RequestHeader header)
+ {
+ return new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).AddSeconds(header.Time).ToLocalTime();
+ }
+
+ private static string Compute(string pin, RequestHeader header)
+ {
+ string salt = string.Join("\n", Label, header.Type ?? "", header.Nonce ?? "",
+ header.Time.ToString(CultureInfo.InvariantCulture), header.PrinterId ?? "", header.JobId ?? "",
+ header.Size.ToString(CultureInfo.InvariantCulture));
+ using (var kdf = new Rfc2898DeriveBytes(Encoding.UTF8.GetBytes(pin), Encoding.UTF8.GetBytes(salt), Iterations, HashAlgorithmName.SHA256))
+ {
+ byte[] proof = kdf.GetBytes(32);
+ var sb = new StringBuilder(proof.Length * 2);
+ foreach (byte b in proof)
+ {
+ sb.Append(b.ToString("x2", CultureInfo.InvariantCulture));
+ }
+ return sb.ToString();
+ }
+ }
+
+ private static long UnixSeconds(DateTime utc)
+ {
+ return (long)(utc.ToUniversalTime() - new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)).TotalSeconds;
+ }
+
+ /// Compares without stopping at the first difference, so timing tells a guesser nothing.
+ private static bool FixedTimeEquals(string a, string b)
+ {
+ if (a.Length != b.Length)
+ {
+ return false;
+ }
+ int diff = 0;
+ for (int i = 0; i < a.Length; i++)
+ {
+ diff |= a[i] ^ b[i];
+ }
+ return diff == 0;
+ }
+ }
+}
diff --git a/src/PrintVect.Core/Update/Sha256Hex.cs b/src/PrintVect.Core/Update/Sha256Hex.cs
index e8faa28..b90f236 100644
--- a/src/PrintVect.Core/Update/Sha256Hex.cs
+++ b/src/PrintVect.Core/Update/Sha256Hex.cs
@@ -21,6 +21,16 @@ public static string OfFile(string path)
}
}
+ /// Of a stream already open, read from its start (the stream stays open).
+ public static string OfStream(Stream stream)
+ {
+ stream.Position = 0;
+ using (var sha = SHA256.Create())
+ {
+ return ToHex(sha.ComputeHash(stream));
+ }
+ }
+
public static string OfBytes(byte[] data)
{
using (var sha = SHA256.Create())
diff --git a/src/PrintVect.Core/Update/UpdateChecker.cs b/src/PrintVect.Core/Update/UpdateChecker.cs
index b70a4a3..1c14b6b 100644
--- a/src/PrintVect.Core/Update/UpdateChecker.cs
+++ b/src/PrintVect.Core/Update/UpdateChecker.cs
@@ -54,6 +54,21 @@ public sealed class UpdateVerificationException : Exception
public UpdateVerificationException(string message) : base(message) { }
}
+ /// A downloaded setup program and what was verified about it, to be checked again just before it runs.
+ public sealed class VerifiedSetup
+ {
+ public VerifiedSetup(string path, string sha256, long size)
+ {
+ Path = path;
+ Sha256 = sha256;
+ Size = size;
+ }
+
+ public string Path { get; }
+ public string Sha256 { get; }
+ public long Size { get; }
+ }
+
///
/// The one place PrintVect talks to the internet (CLAUDE.md): it asks GitHub for this
/// repository's latest release, compares its version with the running program, and can download
@@ -145,16 +160,23 @@ public async Task CheckAsync(CancellationToken ct)
}
///
- /// Downloads the release's setup program into , checks its size
- /// and (when the release carries one) its SHA-256, and returns the verified file's path.
- /// Older files in the folder are removed first. Throws on any failure; nothing half-done is left behind.
+ /// Downloads the release's setup program into , checks its size and its SHA-256
+ /// against the release's checksum file, and returns the verified file. A release without a checksum file is
+ /// refused (0.5.8; it used to install after a size check only). Older files in the folder are removed first.
+ /// Throws on any failure; nothing half-done is left behind.
///
- public async Task DownloadAsync(ReleaseInfo release, string folder, IProgress progress, CancellationToken ct)
+ public async Task DownloadAsync(ReleaseInfo release, string folder, IProgress progress, CancellationToken ct)
{
if (release == null || release.Installer == null)
{
throw new ArgumentException("The release has no setup program.", nameof(release));
}
+ if (release.InstallerHash == null)
+ {
+ Log.Warn("Update: release " + release.Tag + " has no checksum file (" + release.Installer.Name + ReleaseInfo.HashExtension + "); not downloaded.");
+ throw new UpdateVerificationException("version " + release.Tag + " on github.com has no checksum file, so PrintVect cannot check "
+ + "the download and does not install it");
+ }
Directory.CreateDirectory(folder);
string target = Path.Combine(folder, SafeFileName(release.Installer.Name));
string part = target + PartExtension;
@@ -165,23 +187,20 @@ public async Task DownloadAsync(ReleaseInfo release, string folder, IPro
{
using (HttpClient client = CreateClient(DownloadTimeout))
{
- string expectedHash = null;
- if (release.InstallerHash != null)
+ string expectedHash;
+ using (HttpResponseMessage hashResponse = await client.GetAsync(release.InstallerHash.Url, ct).ConfigureAwait(false))
{
- using (HttpResponseMessage hashResponse = await client.GetAsync(release.InstallerHash.Url, ct).ConfigureAwait(false))
- {
- if (!hashResponse.IsSuccessStatusCode)
- {
- throw new HttpRequestException("github.com answered " + (int)hashResponse.StatusCode + " "
- + hashResponse.ReasonPhrase + " for the checksum file");
- }
- string text = await hashResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
- expectedHash = Sha256Hex.ParseHashText(text);
- }
- if (expectedHash == null)
+ if (!hashResponse.IsSuccessStatusCode)
{
- throw new UpdateVerificationException("the checksum file " + release.InstallerHash.Name + " on github.com holds no SHA-256");
+ throw new HttpRequestException("github.com answered " + (int)hashResponse.StatusCode + " "
+ + hashResponse.ReasonPhrase + " for the checksum file");
}
+ string text = await hashResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
+ expectedHash = Sha256Hex.ParseHashText(text);
+ }
+ if (expectedHash == null)
+ {
+ throw new UpdateVerificationException("the checksum file " + release.InstallerHash.Name + " on github.com holds no SHA-256");
}
using (HttpResponseMessage response = await client.GetAsync(release.Installer.Url, HttpCompletionOption.ResponseHeadersRead, ct).ConfigureAwait(false))
@@ -214,28 +233,21 @@ public async Task DownloadAsync(ReleaseInfo release, string folder, IPro
{
throw new UpdateVerificationException("the downloaded file is incomplete (" + actual + " of " + release.Installer.Size + " bytes)");
}
- if (expectedHash != null)
+ string actualHash = Sha256Hex.OfFile(part);
+ if (!Sha256Hex.Equal(actualHash, expectedHash))
{
- string actualHash = Sha256Hex.OfFile(part);
- if (!Sha256Hex.Equal(actualHash, expectedHash))
- {
- Log.Error("Update: checksum mismatch for " + part + ": expected " + expectedHash + ", got " + actualHash + ".");
- throw new UpdateVerificationException("the downloaded file is damaged (its checksum differs from the one on github.com)");
- }
- Log.Info("Update: " + actual + " bytes downloaded; the checksum " + actualHash + " matches.");
+ Log.Error("Update: checksum mismatch for " + part + ": expected " + expectedHash + ", got " + actualHash + ".");
+ throw new UpdateVerificationException("the downloaded file is damaged (its checksum differs from the one on github.com)");
}
- else
+ Log.Info("Update: " + actual + " bytes downloaded; the checksum " + actualHash + " matches.");
+
+ if (File.Exists(target))
{
- Log.Warn("Update: release " + release.Tag + " has no checksum file; only the size (" + actual + " bytes) was checked.");
+ File.Delete(target);
}
+ File.Move(part, target);
+ return new VerifiedSetup(target, actualHash, actual);
}
-
- if (File.Exists(target))
- {
- File.Delete(target);
- }
- File.Move(part, target);
- return target;
}
catch
{
diff --git a/src/PrintVect.Core/Update/UpdateInstaller.cs b/src/PrintVect.Core/Update/UpdateInstaller.cs
index 1b26003..78ded26 100644
--- a/src/PrintVect.Core/Update/UpdateInstaller.cs
+++ b/src/PrintVect.Core/Update/UpdateInstaller.cs
@@ -11,7 +11,28 @@ namespace PrintVect.Core.Update
/// and only then does its "Start PrintVect now" step run as the signed-in user again instead
/// of as the administrator. /SILENT shows just the progress bar. The setup ends the running
/// PrintVect itself (taskkill in its PrepareToInstall step) and starts the new one when done.
+ /// Every user may write in the updates folder, so the verified file is held open (Hold) from its last check until
+ /// the setup has started (0.5.8): nobody can change, replace or rename it, or a folder above it, in between.
///
+ /// The verified setup program held open (UpdateInstaller.Hold); disposing lets go of it.
+ public sealed class SetupHold : IDisposable
+ {
+ private readonly FileStream _stream;
+
+ internal SetupHold(string path, FileStream stream)
+ {
+ Path = path;
+ _stream = stream;
+ }
+
+ public string Path { get; }
+
+ public void Dispose()
+ {
+ _stream.Dispose();
+ }
+ }
+
public static class UpdateInstaller
{
public const string LogPrefix = "update-";
@@ -44,12 +65,43 @@ public static Version VersionFromFileName(string fileName)
return AppVersions.Parse(middle);
}
- public static Process Start(string installerPath)
+ ///
+ /// Opens the verified setup program so that no one can write, delete or rename it while the hold lasts, and
+ /// checks its size and SHA-256 again through that very handle. Throws UpdateVerificationException when it
+ /// changed after the download was checked.
+ ///
+ public static SetupHold Hold(VerifiedSetup setup)
{
- if (!File.Exists(installerPath))
+ if (setup == null) throw new ArgumentNullException(nameof(setup));
+ if (!File.Exists(setup.Path))
+ {
+ throw new FileNotFoundException("The setup program is missing.", setup.Path);
+ }
+ var stream = new FileStream(setup.Path, FileMode.Open, FileAccess.Read, FileShare.Read);
+ try
{
- throw new FileNotFoundException("The setup program is missing.", installerPath);
+ string hash = Sha256Hex.OfStream(stream);
+ if (stream.Length != setup.Size || !Sha256Hex.Equal(hash, setup.Sha256))
+ {
+ Log.Error("Update: " + setup.Path + " changed after it was checked (" + stream.Length + " bytes, SHA-256 " + hash
+ + "; checked: " + setup.Size + " bytes, " + setup.Sha256 + "). It is not started.");
+ throw new UpdateVerificationException("the downloaded setup program was changed on this PC after it was checked");
+ }
+ Log.Info("Update: " + setup.Path + " checked again just before starting it: the SHA-256 still matches.");
+ return new SetupHold(setup.Path, stream);
}
+ catch
+ {
+ stream.Dispose();
+ throw;
+ }
+ }
+
+ /// Starts the held setup program; keep the hold until it ends (or this program is ended by it).
+ public static Process Start(SetupHold hold)
+ {
+ if (hold == null) throw new ArgumentNullException(nameof(hold));
+ string installerPath = hold.Path;
var info = new ProcessStartInfo(installerPath, BuildArguments(LogPathFor(installerPath)))
{
UseShellExecute = true,
diff --git a/src/PrintVect.Elevate/Program.cs b/src/PrintVect.Elevate/Program.cs
index da18147..8e9cf41 100644
--- a/src/PrintVect.Elevate/Program.cs
+++ b/src/PrintVect.Elevate/Program.cs
@@ -33,6 +33,13 @@ private static int Main(string[] args)
_paths = AppPaths.Default();
try
{
+ // Every user may write in the data folder: never follow a link planted there with administrator rights (0.5.8).
+ string link = SafeFolders.FirstLinkInDataFolders(_paths);
+ if (link != null)
+ {
+ Console.Error.WriteLine(new LinkFoundException(link).Message);
+ return ElevateExitCodes.Failed;
+ }
_paths.EnsureDirectories();
Log.Initialize(_paths.LogsDir, LogPrefix);
}
@@ -145,7 +152,9 @@ private static ElevateResult AddPrinter(ElevateResult result, ElevateArguments a
return result;
}
- VirtualPrinters.GrantUsersModify(folder);
+ SafeFolders.GrantUsersModify(SafeFolders.TopOf(_paths), folder); // refuses a junction or link on the way (0.5.8)
+ Log.Info("Users may now modify " + folder + " and the files in it.");
+ SafeFolders.RefuseLinks(SafeFolders.TopOf(_paths), port);
VirtualPrinters.AddLocalPort(port);
bool existed = VirtualPrinters.PrinterExists(name);
@@ -319,6 +328,7 @@ private static bool DeleteFolder(string folder)
{
try
{
+ SafeFolders.RefuseLinks(SafeFolders.TopOf(_paths), folder); // never delete where a planted link leads (0.5.8)
if (Directory.Exists(folder))
{
Directory.Delete(folder, true);
@@ -415,7 +425,14 @@ private static void WriteResult(string resultFile, ElevateResult result)
try
{
string folder = Path.GetDirectoryName(resultFile);
- if (!string.IsNullOrEmpty(folder))
+ string top = SafeFolders.TopOf(_paths);
+ bool inDataFolder = !string.IsNullOrEmpty(folder) && Path.GetFullPath(resultFile).StartsWith(top + "\\", StringComparison.OrdinalIgnoreCase);
+ if (inDataFolder)
+ {
+ SafeFolders.CreateFolder(top, folder);
+ SafeFolders.RefuseLinks(top, resultFile);
+ }
+ else if (!string.IsNullOrEmpty(folder))
{
Directory.CreateDirectory(folder);
}
diff --git a/src/PrintVect.Elevate/VirtualPrinters.cs b/src/PrintVect.Elevate/VirtualPrinters.cs
index b6db667..28d7f54 100644
--- a/src/PrintVect.Elevate/VirtualPrinters.cs
+++ b/src/PrintVect.Elevate/VirtualPrinters.cs
@@ -335,21 +335,6 @@ public static IList LocalPrinters()
}
}
- ///
- /// Lets every user of the PC rename and delete the files the spooler writes into the folder
- /// (ProgramData gives Users only create rights; files there belong to whoever created them).
- ///
- public static void GrantUsersModify(string folder)
- {
- Directory.CreateDirectory(folder);
- DirectorySecurity security = Directory.GetAccessControl(folder);
- var users = new SecurityIdentifier(WellKnownSidType.BuiltinUsersSid, null);
- security.AddAccessRule(new FileSystemAccessRule(users, FileSystemRights.Modify | FileSystemRights.Synchronize,
- InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit, PropagationFlags.None, AccessControlType.Allow));
- Directory.SetAccessControl(folder, security);
- Log.Info("Users may now modify " + folder + " and the files in it.");
- }
-
private static string Describe(int error)
{
return new Win32Exception(error).Message + " (error " + error + ")";
diff --git a/src/PrintVect.Elevate/app.manifest b/src/PrintVect.Elevate/app.manifest
index ac049e0..c140dc6 100644
--- a/src/PrintVect.Elevate/app.manifest
+++ b/src/PrintVect.Elevate/app.manifest
@@ -1,6 +1,6 @@
-
+
diff --git a/src/PrintVect.Send/app.manifest b/src/PrintVect.Send/app.manifest
index 8ecff5a..b5090fa 100644
--- a/src/PrintVect.Send/app.manifest
+++ b/src/PrintVect.Send/app.manifest
@@ -1,6 +1,6 @@
-
+
diff --git a/tests/PrintVect.Tests/ClientServiceTests.cs b/tests/PrintVect.Tests/ClientServiceTests.cs
index 366f5b8..4bbded0 100644
--- a/tests/PrintVect.Tests/ClientServiceTests.cs
+++ b/tests/PrintVect.Tests/ClientServiceTests.cs
@@ -30,11 +30,12 @@ public Task SendAsync(RemotePrinter printer, RequestHeader header, str
}
public readonly List Hellos = new List();
+ public Func OnHello = h => new JobReply { Ok = true, Message = "hello" };
public Task HelloAsync(RemotePrinter printer, RequestHeader header, CancellationToken ct)
{
lock (Hellos) Hellos.Add(header);
- return Task.FromResult(new JobReply { Ok = true, Message = "hello" });
+ return Task.FromResult(OnHello(header));
}
public Task StatusAsync(RemotePrinter printer, string jobId, CancellationToken ct)
@@ -282,7 +283,7 @@ public void AJobIsSentWithTheRightHeaderAndKeptInSent()
Assert.AreEqual(JobFormats.Oxps, header.Format);
Assert.AreEqual(record.JobId, header.JobId);
Assert.AreEqual("Letter to RMS", header.Doc);
- Assert.AreEqual(PinHash.Compute("1234"), header.Pin);
+ Assert.AreEqual("1234", header.PinToSign, "JobClient proves this PIN just before sending");
Assert.IsTrue(record.FilePath.Contains(Path.DirectorySeparatorChar + ClientPrinterNames.SentFolderName + Path.DirectorySeparatorChar), record.FilePath);
Assert.IsTrue(File.Exists(record.FilePath));
Assert.AreEqual(1, service.Jobs.CountToday(ClientJobStates.Printed));
@@ -549,6 +550,25 @@ public async Task PresenceSaysHelloOncePerHostWithItsPrinters()
Assert.IsFalse(string.IsNullOrEmpty(counter1.AppVersion));
}
+ [TestMethod]
+ public async Task PresenceProvesThePin_AndStopsSayingHelloWhereItWasRefused()
+ {
+ var sender = new FakeJobSender { OnHello = h => new JobReply { Ok = false, Message = "COUNTER1 asks for the sharing PIN" } };
+ RemotePrinter a = Printer();
+ using (var announcer = new PresenceAnnouncer(sender, () => new List { a }) { Pin = "1234" })
+ {
+ await announcer.AnnounceAsync(CancellationToken.None);
+ Assert.AreEqual("1234", sender.Hellos.Single().PinToSign);
+
+ await announcer.AnnounceAsync(CancellationToken.None);
+ Assert.AreEqual(1, sender.Hellos.Count, "a wrong PIN must not keep counting as wrong tries on the host");
+
+ announcer.Pin = "5678";
+ await announcer.AnnounceAsync(CancellationToken.None);
+ Assert.AreEqual(2, sender.Hellos.Count, "a new PIN is tried");
+ }
+ }
+
[TestMethod]
public void TheCopiesAnswerIsSentToTheHost()
{
@@ -769,7 +789,7 @@ public void AHostThatMovedIsFoundAgainAndTheJobPrintsThereAtOnce()
{
Interlocked.Increment(ref searches);
p.HostIp = "10.0.0.2";
- return Task.FromResult(true);
+ return Task.FromResult(HostSearchOutcome.Followed);
};
var paths = new AppPaths(temp.Path);
service.StartWatching(printer);
@@ -797,7 +817,7 @@ public void AHostThatIsNotFoundIsSearchedForOnceAndTheJobWaits()
service.FindHost = (p, ct) =>
{
Interlocked.Increment(ref searches);
- return Task.FromResult(false);
+ return Task.FromResult(HostSearchOutcome.NotFound);
};
var paths = new AppPaths(temp.Path);
RemotePrinter printer = Printer();
@@ -812,5 +832,29 @@ public void AHostThatIsNotFoundIsSearchedForOnceAndTheJobWaits()
}
}
}
+
+ [TestMethod]
+ public void APcThatCannotProveItIsTheHostGetsNothing_AndTheJobSaysWhy()
+ {
+ using (var temp = new TempFolder())
+ {
+ var sender = new FakeJobSender { OnSend = h => null };
+ using (ClientService service = Service(temp, sender, 0, 10, 10))
+ {
+ service.FindHost = (p, ct) => Task.FromResult(HostSearchOutcome.Refused(
+ "A PC calling itself COUNTER1 answers at 192.168.10.66, but it is not COUNTER1. Nothing was sent there."));
+ var paths = new AppPaths(temp.Path);
+ RemotePrinter printer = Printer();
+ service.StartWatching(printer);
+
+ ClientJobRecord record = DropAndWait(service, paths, printer, true, "Not for strangers");
+
+ Assert.AreEqual(ClientJobStates.Pending, record.State, "kept for Retry");
+ StringAssert.Contains(record.Message, "it is not COUNTER1");
+ Assert.AreEqual("127.0.0.1", printer.HostIp);
+ Assert.IsTrue(sender.Sent.All(h => h != null) && sender.Sent.Count == 3, "only the host's own address was tried");
+ }
+ }
+ }
}
}
diff --git a/tests/PrintVect.Tests/ConfigStoreTests.cs b/tests/PrintVect.Tests/ConfigStoreTests.cs
index 1ca4e14..f2c1c66 100644
--- a/tests/PrintVect.Tests/ConfigStoreTests.cs
+++ b/tests/PrintVect.Tests/ConfigStoreTests.cs
@@ -26,6 +26,23 @@ public void LoadOrCreate_WhenFileMissing_WritesDefaults()
}
}
+ [TestMethod]
+ public void APlainPinFromBefore058_IsReadAndThenKeptProtected()
+ {
+ using (var temp = new TempFolder())
+ {
+ var store = new ConfigStore(temp.File("config.json"));
+ File.WriteAllText(store.Path, "{ \"JobPort\": 9151, \"Pin\": \"2468\" }");
+
+ AppConfig config = store.Load();
+
+ Assert.AreEqual("2468", config.Pin);
+ string json = File.ReadAllText(store.Path);
+ Assert.IsFalse(json.Contains("2468"), "saved again at once without the plain PIN: " + json);
+ Assert.AreEqual("2468", store.Load().Pin);
+ }
+ }
+
[TestMethod]
public void SaveThenLoad_RoundTripsEveryField()
{
@@ -56,8 +73,11 @@ public void SaveThenLoad_RoundTripsEveryField()
};
store.Save(original);
+ string json = File.ReadAllText(store.Path);
AppConfig loaded = store.Load();
+ Assert.IsFalse(json.Contains("4321"), "the PIN is not in the file in plain text: " + json);
+ StringAssert.Contains(json, "PinProtected");
Assert.AreEqual(9250, loaded.DiscoveryPort);
Assert.AreEqual(9251, loaded.JobPort);
Assert.AreEqual("4321", loaded.Pin);
diff --git a/tests/PrintVect.Tests/FloodLimitsTests.cs b/tests/PrintVect.Tests/FloodLimitsTests.cs
new file mode 100644
index 0000000..4aeb693
--- /dev/null
+++ b/tests/PrintVect.Tests/FloodLimitsTests.cs
@@ -0,0 +1,77 @@
+using System;
+using System.IO;
+using Microsoft.VisualStudio.TestTools.UnitTesting;
+using PrintVect.Core.Config;
+using PrintVect.Core.Host;
+
+namespace PrintVect.Tests
+{
+ [TestClass]
+ public class ConnectionLimiterTests
+ {
+ private static readonly DateTime Now = new DateTime(2026, 10, 29, 9, 0, 0, DateTimeKind.Utc);
+
+ [TestMethod]
+ public void OnePcGetsAFewConnectionsAtOnce_OthersAreNotAffected()
+ {
+ var limiter = new ConnectionLimiter { MaxPerAddress = 2 };
+ Assert.IsNull(limiter.TryEnter("192.168.10.23", Now));
+ Assert.IsNull(limiter.TryEnter("192.168.10.23", Now));
+ Assert.IsNotNull(limiter.TryEnter("192.168.10.23", Now));
+ Assert.IsNull(limiter.TryEnter("192.168.10.24", Now));
+
+ limiter.Leave("192.168.10.23");
+ Assert.IsNull(limiter.TryEnter("192.168.10.23", Now), "a closed connection frees its place");
+ Assert.AreEqual(3, limiter.OpenCount);
+ }
+
+ [TestMethod]
+ public void TheHostServesAtMostSoManyInAll()
+ {
+ var limiter = new ConnectionLimiter { MaxTotal = 3 };
+ for (int i = 1; i <= 3; i++) Assert.IsNull(limiter.TryEnter("192.168.10." + i, Now));
+ StringAssert.Contains(limiter.TryEnter("192.168.10.9", Now), "3 connections");
+ }
+
+ [TestMethod]
+ public void TooManyNewConnectionsInAMinute_AreRefusedUntilTheMinuteIsOver()
+ {
+ var limiter = new ConnectionLimiter { MaxPerMinute = 3 };
+ for (int i = 0; i < 3; i++)
+ {
+ Assert.IsNull(limiter.TryEnter("192.168.10.23", Now.AddSeconds(i)));
+ limiter.Leave("192.168.10.23");
+ }
+ Assert.IsNotNull(limiter.TryEnter("192.168.10.23", Now.AddSeconds(10)));
+ Assert.IsNull(limiter.TryEnter("192.168.10.23", Now.AddSeconds(61)));
+ }
+ }
+
+ [TestClass]
+ public class IncomingSpoolTests
+ {
+ [TestMethod]
+ public void OldFilesNoJobWaitsFor_AreDeleted_OthersStay()
+ {
+ using (var temp = new TempFolder())
+ {
+ var spool = new IncomingSpool(new AppPaths(temp.Path));
+ spool.Ensure();
+ string oldUnused = Path.Combine(spool.Directory, "old-unused.xps");
+ string oldWaiting = Path.Combine(spool.Directory, "old-waiting.xps");
+ string recent = Path.Combine(spool.Directory, "recent.xps");
+ foreach (string file in new[] { oldUnused, oldWaiting, recent }) File.WriteAllBytes(file, new byte[1000]);
+ File.SetLastWriteTime(oldUnused, DateTime.Now.AddHours(-25));
+ File.SetLastWriteTime(oldWaiting, DateTime.Now.AddHours(-25));
+
+ int deleted = spool.DeleteUnusedOlderThan(TimeSpan.FromHours(24), new[] { Path.GetFullPath(oldWaiting) });
+
+ Assert.AreEqual(1, deleted);
+ Assert.IsFalse(File.Exists(oldUnused));
+ Assert.IsTrue(File.Exists(oldWaiting), "a job still waits for it (a paused printer)");
+ Assert.IsTrue(File.Exists(recent));
+ Assert.AreEqual(2000, spool.TotalBytes());
+ }
+ }
+ }
+}
diff --git a/tests/PrintVect.Tests/FramingTests.cs b/tests/PrintVect.Tests/FramingTests.cs
index 6ab52f0..1dc67da 100644
--- a/tests/PrintVect.Tests/FramingTests.cs
+++ b/tests/PrintVect.Tests/FramingTests.cs
@@ -4,6 +4,7 @@
using System.Threading;
using System.Threading.Tasks;
using Microsoft.VisualStudio.TestTools.UnitTesting;
+using PrintVect.Core.Host;
using PrintVect.Core.Protocol;
namespace PrintVect.Tests
@@ -47,7 +48,8 @@ public async Task Header_RoundTripsThroughAStream()
Assert.AreEqual("COUNTER3", decoded.Client);
Assert.AreEqual("user1", decoded.User);
Assert.AreEqual("Letter to HQ", decoded.Doc);
- Assert.AreEqual(PinHash.Compute("1234"), decoded.Pin);
+ Assert.IsNull(decoded.PinToSign, "the PIN itself never travels");
+ Assert.IsNull(decoded.LegacyPinHash, "nor its plain hash (before 0.5.8)");
Assert.AreEqual(stream.Length, stream.Position, "nothing may be left unread");
}
@@ -198,31 +200,118 @@ private sealed class SynchronousProgress : IProgress
}
[TestClass]
- public class PinHashTests
+ public class PinProofTests
{
+ private static RequestHeader SignedJob(string pin, DateTime utcNow)
+ {
+ RequestHeader header = RequestHeader.ForJob("abc123", "a.xps", "xps", 5000, "Letter", null);
+ PinProof.Sign(header, pin, utcNow);
+ return header;
+ }
+
+ [TestMethod]
+ public void TheRightPinIsAccepted_AndNeitherThePinNorItsHashTravels()
+ {
+ DateTime now = DateTime.UtcNow;
+ RequestHeader header = SignedJob("1234", now);
+
+ Assert.AreEqual(PinCheck.Accepted, PinProof.Check("1234", header, now));
+ string json = Encoding.UTF8.GetString(Framing.EncodeHeader(header));
+ Assert.IsFalse(json.Contains("1234"), json);
+ Assert.IsFalse(json.Contains("03ac674216f3e15c761ee1a5e255f067953623c8b388b4459e13f978d7c846f4"), "the plain SHA-256 of 1234: " + json);
+ StringAssert.Contains(json, "\"pinProof\":");
+ }
+
+ [TestMethod]
+ public void EveryRequestGetsItsOwnProof()
+ {
+ DateTime now = DateTime.UtcNow;
+ Assert.AreNotEqual(SignedJob("1234", now).Proof, SignedJob("1234", now).Proof);
+ }
+
+ [TestMethod]
+ public void AWrongPinOrAChangedJobIsRefused()
+ {
+ DateTime now = DateTime.UtcNow;
+ Assert.AreEqual(PinCheck.Wrong, PinProof.Check("4321", SignedJob("1234", now), now));
+
+ RequestHeader replayed = SignedJob("1234", now);
+ replayed.JobId = Guid.NewGuid().ToString("D"); // a recorded proof reused for another job
+ Assert.AreEqual(PinCheck.Wrong, PinProof.Check("1234", replayed, now));
+
+ RequestHeader bigger = SignedJob("1234", now);
+ bigger.Size = 6000;
+ Assert.AreEqual(PinCheck.Wrong, PinProof.Check("1234", bigger, now));
+
+ RequestHeader otherPrinter = SignedJob("1234", now);
+ otherPrinter.PrinterId = "def456";
+ Assert.AreEqual(PinCheck.Wrong, PinProof.Check("1234", otherPrinter, now));
+ }
+
[TestMethod]
- public void Compute_IsLowercaseSha256Hex()
+ public void AnOpenHostAcceptsAnything_AndAPinHostTellsMissingFromOutdated()
{
- Assert.AreEqual("03ac674216f3e15c761ee1a5e255f067953623c8b388b4459e13f978d7c846f4", PinHash.Compute("1234"));
- Assert.AreEqual(64, PinHash.Compute("").Length);
+ DateTime now = DateTime.UtcNow;
+ RequestHeader none = SignedJob(null, now);
+ Assert.AreEqual(PinCheck.Open, PinProof.Check("", none, now));
+ Assert.AreEqual(PinCheck.Open, PinProof.Check(null, SignedJob("1234", now), now));
+ Assert.AreEqual(PinCheck.Missing, PinProof.Check("1234", none, now));
+
+ none.LegacyPinHash = "03ac674216f3e15c761ee1a5e255f067953623c8b388b4459e13f978d7c846f4"; // what 0.5.7 sent
+ Assert.AreEqual(PinCheck.Outdated, PinProof.Check("1234", none, now), "the old plain hash is never accepted");
}
[TestMethod]
- public void Matches_OpenHostAcceptsAnything()
+ public void AProofFromMoreThanADayAwayIsRefused()
{
- Assert.IsTrue(PinHash.Matches("", null));
- Assert.IsTrue(PinHash.Matches(null, "whatever"));
+ DateTime now = DateTime.UtcNow;
+ Assert.AreEqual(PinCheck.Accepted, PinProof.Check("1234", SignedJob("1234", now.AddHours(-23)), now));
+ Assert.AreEqual(PinCheck.ClockOff, PinProof.Check("1234", SignedJob("1234", now.AddHours(-25)), now));
+ Assert.AreEqual(PinCheck.ClockOff, PinProof.Check("1234", SignedJob("1234", now.AddHours(25)), now));
}
+ }
+ [TestClass]
+ public class PinAttemptLimiterTests
+ {
[TestMethod]
- public void Matches_RequiresTheRightDigest()
+ public void FiveWrongTriesMakeTheAddressWait_LongerEachTime()
{
- Assert.IsTrue(PinHash.Matches("1234", PinHash.Compute("1234")));
- Assert.IsTrue(PinHash.Matches("1234", PinHash.Compute("1234").ToUpperInvariant()));
- Assert.IsFalse(PinHash.Matches("1234", PinHash.Compute("4321")));
- Assert.IsFalse(PinHash.Matches("1234", ""));
- Assert.IsFalse(PinHash.Matches("1234", null));
- Assert.IsFalse(PinHash.Matches("1234", "1234"), "the clear PIN is never accepted");
+ var limiter = new PinAttemptLimiter();
+ DateTime now = new DateTime(2026, 10, 29, 9, 0, 0, DateTimeKind.Utc);
+ for (int i = 1; i < PinAttemptLimiter.TriesBeforeWait; i++)
+ {
+ Assert.AreEqual(PinAttemptLimiter.TriesBeforeWait - i, limiter.Failed("192.168.10.23", now));
+ Assert.AreEqual(TimeSpan.Zero, limiter.WaitFor("192.168.10.23", now));
+ }
+ Assert.AreEqual(0, limiter.Failed("192.168.10.23", now));
+ Assert.AreEqual(PinAttemptLimiter.FirstWait, limiter.WaitFor("192.168.10.23", now));
+ Assert.AreEqual(TimeSpan.Zero, limiter.WaitFor("192.168.10.24", now), "another PC is not affected");
+
+ now += PinAttemptLimiter.FirstWait;
+ Assert.AreEqual(TimeSpan.Zero, limiter.WaitFor("192.168.10.23", now));
+ for (int i = 0; i < PinAttemptLimiter.TriesBeforeWait; i++) limiter.Failed("192.168.10.23", now);
+ Assert.AreEqual(TimeSpan.FromMinutes(30), limiter.WaitFor("192.168.10.23", now), "twice as long the second time");
+
+ for (int round = 0; round < 10; round++)
+ {
+ now += limiter.WaitFor("192.168.10.23", now);
+ for (int i = 0; i < PinAttemptLimiter.TriesBeforeWait; i++) limiter.Failed("192.168.10.23", now);
+ }
+ Assert.AreEqual(PinAttemptLimiter.LongestWait, limiter.WaitFor("192.168.10.23", now), "never longer than 4 hours");
+ }
+
+ [TestMethod]
+ public void ARightPinOrAQuietDayStartsAfresh()
+ {
+ var limiter = new PinAttemptLimiter();
+ DateTime now = new DateTime(2026, 10, 29, 9, 0, 0, DateTimeKind.Utc);
+ limiter.Failed("192.168.10.23", now);
+ limiter.Failed("192.168.10.23", now);
+ limiter.Succeeded("192.168.10.23");
+ Assert.AreEqual(PinAttemptLimiter.TriesBeforeWait - 1, limiter.Failed("192.168.10.23", now));
+
+ Assert.AreEqual(PinAttemptLimiter.TriesBeforeWait - 1, limiter.Failed("192.168.10.23", now + PinAttemptLimiter.ForgetAfter + TimeSpan.FromMinutes(1)));
}
}
}
diff --git a/tests/PrintVect.Tests/HostIdentityTests.cs b/tests/PrintVect.Tests/HostIdentityTests.cs
new file mode 100644
index 0000000..e1d0a10
--- /dev/null
+++ b/tests/PrintVect.Tests/HostIdentityTests.cs
@@ -0,0 +1,126 @@
+using System;
+using System.Threading;
+using System.Threading.Tasks;
+using Microsoft.VisualStudio.TestTools.UnitTesting;
+using PrintVect.Core.Client;
+using PrintVect.Core.Config;
+using PrintVect.Core.Host;
+using PrintVect.Core.Logging;
+using PrintVect.Core.Protocol;
+
+namespace PrintVect.Tests
+{
+ [TestClass]
+ public class HostIdentityTests
+ {
+ // Made once: an RSA key takes a moment.
+ private static readonly HostIdentity _real = HostIdentity.Create();
+ private static readonly HostIdentity _impostor = HostIdentity.Create();
+
+ private static ListReply Answer(HostIdentity identity, string challenge, string host, string address)
+ {
+ return new ListReply { Host = host, Ip = address, Port = 9151, HostKey = identity.PublicKey, HostSig = identity.Sign(challenge, host, address) };
+ }
+
+ private static RemotePrinter Printer(string keyId)
+ {
+ return new RemotePrinter { PrinterId = "0afbc594d5975d71", HostName = "COUNTER1", HostIp = "192.168.10.20", HostKeyId = keyId };
+ }
+
+ [TestMethod]
+ public void ASignatureHoldsOnlyForItsChallengeNameAndAddress()
+ {
+ string challenge = HostKeys.NewChallenge();
+ string sig = _real.Sign(challenge, "COUNTER1", "192.168.10.31");
+
+ Assert.IsTrue(HostKeys.Verify(_real.PublicKey, challenge, "counter1", "192.168.10.31", sig), "names compare without case");
+ Assert.IsFalse(HostKeys.Verify(_real.PublicKey, HostKeys.NewChallenge(), "COUNTER1", "192.168.10.31", sig), "another challenge");
+ Assert.IsFalse(HostKeys.Verify(_real.PublicKey, challenge, "COUNTER1", "192.168.10.32", sig), "another address: a relayed answer");
+ Assert.IsFalse(HostKeys.Verify(_real.PublicKey, challenge, "COUNTER2", "192.168.10.31", sig), "another name");
+ Assert.IsFalse(HostKeys.Verify(_impostor.PublicKey, challenge, "COUNTER1", "192.168.10.31", sig), "another key");
+ Assert.IsFalse(HostKeys.Verify("not base64!", challenge, "COUNTER1", "192.168.10.31", sig));
+ Assert.AreEqual(64, _real.KeyId.Length);
+ Assert.AreNotEqual(_real.KeyId, _impostor.KeyId);
+ }
+
+ [TestMethod]
+ public void APrinterFollowsOnlyTheHostWhoseKeyItRemembers()
+ {
+ string challenge = HostKeys.NewChallenge();
+ string keyId;
+
+ Assert.IsNull(MovedHostCheck.Judge(Printer(_real.KeyId), "192.168.10.31", challenge, Answer(_real, challenge, "COUNTER1", "192.168.10.31"), out keyId));
+ Assert.AreEqual(_real.KeyId, keyId);
+
+ string impostor = MovedHostCheck.Judge(Printer(_real.KeyId), "192.168.10.66", challenge, Answer(_impostor, challenge, "COUNTER1", "192.168.10.66"), out keyId);
+ StringAssert.Contains(impostor, "not COUNTER1");
+
+ ListReply claimsTheRealKey = Answer(_impostor, challenge, "COUNTER1", "192.168.10.66");
+ claimsTheRealKey.HostKey = _real.PublicKey; // copied from the real host's discovery reply, but it cannot sign with it
+ Assert.IsNotNull(MovedHostCheck.Judge(Printer(_real.KeyId), "192.168.10.66", challenge, claimsTheRealKey, out keyId));
+
+ ListReply relayed = Answer(_real, challenge, "COUNTER1", "192.168.10.31"); // the real host's answer, passed on from another address
+ Assert.IsNotNull(MovedHostCheck.Judge(Printer(_real.KeyId), "192.168.10.66", challenge, relayed, out keyId));
+
+ ListReply noKey = new ListReply { Host = "COUNTER1", Ip = "192.168.10.66", Port = 9151 };
+ Assert.IsNotNull(MovedHostCheck.Judge(Printer(_real.KeyId), "192.168.10.66", challenge, noKey, out keyId), "a remembered key is never given up");
+ }
+
+ [TestMethod]
+ public void APrinterWithoutAKeyLearnsTheFirstProvenOne_AndFollowsAnOlderHostAsBefore()
+ {
+ string challenge = HostKeys.NewChallenge();
+ string keyId;
+
+ Assert.IsNull(MovedHostCheck.Judge(Printer(null), "192.168.10.31", challenge, Answer(_real, challenge, "COUNTER1", "192.168.10.31"), out keyId));
+ Assert.AreEqual(_real.KeyId, keyId);
+
+ Assert.IsNull(MovedHostCheck.Judge(Printer(null), "192.168.10.31", challenge, new ListReply { Host = "COUNTER1", Port = 9151 }, out keyId),
+ "a host before 0.5.8 has no key");
+ Assert.IsNull(keyId);
+ }
+
+ [TestMethod]
+ public async Task ARealHostProvesItselfOverTheNetwork()
+ {
+ using (var temp = new TempFolder())
+ {
+ var paths = new AppPaths(temp.Path);
+ paths.EnsureDirectories();
+ Log.Initialize(paths.LogsDir, "PrintVect");
+ using (var host = new HostService(paths, new FakePrintEngine(), new FakePrinters(), new JobTracker()) { Identity = _real })
+ {
+ host.Start(0);
+ var printer = new RemotePrinter { PrinterId = "abc123", HostName = Environment.MachineName, HostKeyId = _real.KeyId };
+
+ MovedHostVerdict proven = await MovedHostCheck.CheckAsync(printer, "127.0.0.1", host.Port, CancellationToken.None);
+ printer.HostKeyId = _impostor.KeyId;
+ MovedHostVerdict other = await MovedHostCheck.CheckAsync(printer, "127.0.0.1", host.Port, CancellationToken.None);
+
+ Assert.IsNull(proven.Problem, proven.Problem);
+ Assert.AreEqual(_real.KeyId, proven.KeyId);
+ Assert.IsNotNull(other.Problem);
+ host.Stop();
+ }
+ Log.Shutdown();
+ }
+ }
+
+ [TestMethod]
+ public void TheKeyIsKeptProtectedAndReadBack()
+ {
+ string saved;
+ using (HostIdentity made = HostIdentity.LoadOrCreate("", out saved))
+ {
+ Assert.IsNotNull(saved, "a new key is handed back to be kept in config.json");
+ string again;
+ using (HostIdentity loaded = HostIdentity.LoadOrCreate(saved, out again))
+ {
+ Assert.IsNull(again, "nothing new to keep");
+ Assert.AreEqual(made.KeyId, loaded.KeyId);
+ }
+ }
+ Assert.IsNull(MachineProtection.Unprotect("bm90IHByb3RlY3RlZA=="), "text protected elsewhere (or not at all) is not a key");
+ }
+ }
+}
diff --git a/tests/PrintVect.Tests/HostTests.cs b/tests/PrintVect.Tests/HostTests.cs
index c517e57..14eeb4c 100644
--- a/tests/PrintVect.Tests/HostTests.cs
+++ b/tests/PrintVect.Tests/HostTests.cs
@@ -243,6 +243,76 @@ public async Task SendJob_WrongPin_IsRefusedWithReason()
Assert.AreEqual(0, Directory.GetFiles(_host.IncomingDirectory).Length, "refused jobs leave no file behind");
}
+ [TestMethod]
+ public async Task SendJob_ThePlainPinHashOfOlderVersions_IsRefusedWithUpdateAdvice()
+ {
+ _host.Pin = "1234";
+ RequestHeader header = RequestHeader.ForJob("abc123", "a.xps", "xps", 0, "", null);
+ header.LegacyPinHash = "03ac674216f3e15c761ee1a5e255f067953623c8b388b4459e13f978d7c846f4"; // SHA-256 of 1234, as 0.5.7 sent it
+
+ JobReply reply = await Client().SendJobAsync(header, WriteXps(5000), null, CancellationToken.None);
+
+ Assert.IsFalse(reply.Ok);
+ Assert.IsTrue(reply.Retry);
+ StringAssert.Contains(reply.Message, "0.5.8");
+ Assert.AreEqual(0, _engine.Requests.Count);
+ }
+
+ [TestMethod]
+ public async Task SendJob_AfterFiveWrongPins_EvenTheRightOneWaits()
+ {
+ _host.Pin = "1234";
+ string file = WriteXps(5000);
+ for (int i = 0; i < PinAttemptLimiter.TriesBeforeWait; i++)
+ {
+ JobReply wrong = await Client().SendJobAsync(RequestHeader.ForJob("abc123", "a.xps", "xps", 0, "", "000" + i), file, null, CancellationToken.None);
+ Assert.IsFalse(wrong.Ok);
+ }
+
+ JobReply right = await Client().SendJobAsync(RequestHeader.ForJob("abc123", "a.xps", "xps", 0, "", "1234"), file, null, CancellationToken.None);
+
+ Assert.IsFalse(right.Ok, "guessing on stops for a while");
+ Assert.IsTrue(right.Retry, "the job waits for Retry");
+ StringAssert.Contains(right.Message, "15 minutes");
+ Assert.AreEqual(0, _engine.Requests.Count);
+ }
+
+ [TestMethod]
+ public async Task SendJob_ARecordedProofDoesNotWorkForAnotherJob()
+ {
+ _host.Pin = "1234";
+ string file = WriteXps(5000);
+ RequestHeader recorded = RequestHeader.ForJob("abc123", "a.xps", "xps", 0, "", "1234");
+ JobReply first = await Client().SendJobAsync(recorded, file, null, CancellationToken.None);
+ Assert.IsTrue(first.Ok, first.Message);
+
+ RequestHeader forged = RequestHeader.ForJob("abc123", "a.xps", "xps", 0, "", null);
+ forged.Nonce = recorded.Nonce;
+ forged.Time = recorded.Time;
+ forged.Proof = recorded.Proof; // a new job id: someone who saw the first job's header
+ JobReply second = await Client().SendJobAsync(forged, file, null, CancellationToken.None);
+
+ Assert.IsFalse(second.Ok);
+ Assert.AreEqual(1, _engine.Requests.Count);
+ }
+
+ [TestMethod]
+ public async Task Hello_WithAPinOnTheHost_ListsOnlyPcsThatProveIt()
+ {
+ _host.Pin = "1234";
+ RequestHeader stranger = RequestHeader.ForHello("Windows 11 Pro", "0.5.8", new[] { "abc123" });
+ stranger.Client = "MADE-UP-PC";
+ RequestHeader friend = RequestHeader.ForHello("Windows 11 Pro", "0.5.8", new[] { "abc123" }, "1234");
+ friend.Client = "COUNTER3";
+
+ JobReply refused = await Client().SendHelloAsync(stranger, CancellationToken.None);
+ JobReply welcomed = await Client().SendHelloAsync(friend, CancellationToken.None);
+
+ Assert.IsFalse(refused.Ok);
+ Assert.IsTrue(welcomed.Ok, welcomed.Message);
+ Assert.AreEqual("COUNTER3", _host.Presence.All().Single().Name);
+ }
+
[TestMethod]
public async Task SendJob_UnknownPrinter_ListsTheSharedOnes()
{
@@ -270,7 +340,7 @@ public async Task SendJob_BadFormat_IsRefused()
}
[TestMethod]
- public async Task SendJob_NotAnXpsFile_IsRefusedAndKept()
+ public async Task SendJob_NotAnXpsFile_IsRefusedAndDeleted()
{
string file = _temp.File("junk.xps");
File.WriteAllText(file, "this is not a zip file at all");
@@ -279,10 +349,85 @@ public async Task SendJob_NotAnXpsFile_IsRefusedAndKept()
Assert.IsFalse(reply.Ok);
StringAssert.Contains(reply.Message, "not an XPS document");
- Assert.AreEqual(1, Directory.GetFiles(_host.IncomingDirectory).Length, "kept for diagnosis");
+ StringAssert.Contains(reply.Message, "deleted");
+ Assert.AreEqual(0, Directory.GetFiles(_host.IncomingDirectory).Length, "junk must not fill the disk");
Assert.AreEqual(0, _engine.Requests.Count);
}
+ /// True when the host closed the connection (read returns 0 or the connection was reset) within the time.
+ private static async Task ClosedByHostWithin(TcpClient raw, TimeSpan within)
+ {
+ NetworkStream stream = raw.GetStream();
+ var buffer = new byte[16];
+ Task read = stream.ReadAsync(buffer, 0, buffer.Length);
+ if (await Task.WhenAny(read, Task.Delay(within)) != read)
+ {
+ return false;
+ }
+ try
+ {
+ return await read == 0;
+ }
+ catch (IOException)
+ {
+ return true;
+ }
+ }
+
+ [TestMethod]
+ public async Task AConnectionThatSendsNothing_IsClosedAfterTheHeaderTimeout()
+ {
+ _host.HeaderTimeout = TimeSpan.FromMilliseconds(300);
+ using (var raw = new TcpClient())
+ {
+ await raw.ConnectAsync("127.0.0.1", _host.Port);
+ Assert.IsTrue(await ClosedByHostWithin(raw, TimeSpan.FromSeconds(5)), "a silent connection must not hold the host for 5 minutes");
+ }
+ }
+
+ [TestMethod]
+ public async Task TooManyConnectionsFromOnePc_AreClosedAtOnce()
+ {
+ _host.Connections.MaxPerAddress = 2;
+ using (var first = new TcpClient())
+ using (var second = new TcpClient())
+ using (var third = new TcpClient())
+ {
+ await first.ConnectAsync("127.0.0.1", _host.Port);
+ await second.ConnectAsync("127.0.0.1", _host.Port);
+ for (int i = 0; i < 50 && _host.Connections.OpenCount < 2; i++) await Task.Delay(20);
+ await third.ConnectAsync("127.0.0.1", _host.Port);
+
+ Assert.IsTrue(await ClosedByHostWithin(third, TimeSpan.FromSeconds(5)), "the third connection is closed at once");
+ }
+ for (int i = 0; i < 100 && _host.Connections.OpenCount > 0; i++) await Task.Delay(20);
+
+ ListReply list = await Client().ListPrintersAsync(CancellationToken.None);
+ Assert.IsTrue(list.Ok, "once they are closed, the PC is served again");
+ }
+
+ [TestMethod]
+ public async Task TheIncomingFolderHasACap_OlderUnusedFilesMakeRoomFirst()
+ {
+ _host.UpdateSharedPrinters(new[] { new SharedPrinter { Id = "abc123", LocalName = "Fake Printer", FriendlyName = "Counter 1 Laser", Paused = true } });
+ _host.MaxIncomingBytes = 250 * 1024;
+ string stray = Path.Combine(_host.IncomingDirectory, Guid.NewGuid().ToString("D") + ".xps"); // left by a failed print
+ File.WriteAllBytes(stray, new byte[100 * 1024]);
+ File.SetLastWriteTime(stray, DateTime.Now.AddHours(-2));
+
+ JobReply a = await Client().SendJobAsync(RequestHeader.ForJob("abc123", "a.xps", "xps", 0, "A", null), WriteXps(100 * 1024), null, CancellationToken.None);
+ JobReply b = await Client().SendJobAsync(RequestHeader.ForJob("abc123", "b.xps", "xps", 0, "B", null), WriteXps(100 * 1024), null, CancellationToken.None);
+ JobReply c = await Client().SendJobAsync(RequestHeader.ForJob("abc123", "c.xps", "xps", 0, "C", null), WriteXps(100 * 1024), null, CancellationToken.None);
+
+ Assert.IsTrue(a.Ok, a.Message);
+ Assert.IsTrue(b.Ok, b.Message);
+ Assert.IsFalse(File.Exists(stray), "the unused file made room for B");
+ Assert.IsFalse(c.Ok, "A and B wait for the paused printer and are never deleted");
+ Assert.IsTrue(c.Retry, "C waits for Retry on the sender");
+ StringAssert.Contains(c.Message, "already holds");
+ Assert.AreEqual(2, Directory.GetFiles(_host.IncomingDirectory).Length);
+ }
+
[TestMethod]
public async Task SendJob_PrinterFailure_IsReportedAndFileKept()
{
diff --git a/tests/PrintVect.Tests/SafeFoldersTests.cs b/tests/PrintVect.Tests/SafeFoldersTests.cs
new file mode 100644
index 0000000..fc66470
--- /dev/null
+++ b/tests/PrintVect.Tests/SafeFoldersTests.cs
@@ -0,0 +1,94 @@
+using System;
+using System.Diagnostics;
+using System.IO;
+using System.Linq;
+using System.Security.AccessControl;
+using System.Security.Principal;
+using Microsoft.VisualStudio.TestTools.UnitTesting;
+using PrintVect.Core.Diagnostics;
+using PrintVect.Core.Elevation;
+
+namespace PrintVect.Tests
+{
+ [TestClass]
+ public class SafeFoldersTests
+ {
+ /// A junction on Windows (no administrator rights needed), a symbolic link elsewhere.
+ private static void MakeLink(string link, string target)
+ {
+ ProcessStartInfo info = WindowsInfo.IsWindows
+ ? new ProcessStartInfo("cmd.exe", "/c mklink /J \"" + link + "\" \"" + target + "\"")
+ : new ProcessStartInfo("ln", "-s \"" + target + "\" \"" + link + "\"");
+ info.UseShellExecute = false;
+ info.CreateNoWindow = true;
+ info.RedirectStandardOutput = true;
+ using (Process process = Process.Start(info))
+ {
+ process.StandardOutput.ReadToEnd();
+ process.WaitForExit();
+ Assert.AreEqual(0, process.ExitCode, "the link could not be made");
+ }
+ }
+
+ [TestMethod]
+ public void FindsALinkAnywhereOnTheWay()
+ {
+ using (var temp = new TempFolder())
+ {
+ string top = temp.Path;
+ string elsewhere = Directory.CreateDirectory(Path.Combine(top, "Windows")).FullName;
+ string spool = Directory.CreateDirectory(Path.Combine(top, "PrintVect", "spool")).FullName;
+ Directory.CreateDirectory(Path.Combine(spool, "0afbc594d5975d71"));
+ MakeLink(Path.Combine(spool, "planted"), elsewhere);
+
+ Assert.IsNull(SafeFolders.FirstLink(top, Path.Combine(spool, "0afbc594d5975d71")));
+ Assert.IsNull(SafeFolders.FirstLink(top, Path.Combine(spool, "not-there-yet", "job.xps")), "missing folders are not links");
+ Assert.AreEqual(Path.Combine(spool, "planted"), SafeFolders.FirstLink(top, Path.Combine(spool, "planted")));
+ Assert.AreEqual(Path.Combine(spool, "planted"), SafeFolders.FirstLink(top, Path.Combine(spool, "planted", "deeper", "job.xps")));
+ }
+ }
+
+ [TestMethod]
+ public void CreatesNothingThroughALinkedParent()
+ {
+ using (var temp = new TempFolder())
+ {
+ string top = temp.Path;
+ string elsewhere = Directory.CreateDirectory(Path.Combine(top, "System32")).FullName;
+ Directory.CreateDirectory(Path.Combine(top, "PrintVect"));
+ MakeLink(Path.Combine(top, "PrintVect", "spool"), elsewhere); // spool itself replaced by a link
+
+ Assert.ThrowsException(() => SafeFolders.CreateFolder(top, Path.Combine(top, "PrintVect", "spool", "abc")));
+ Assert.AreEqual(0, Directory.GetDirectories(elsewhere).Length, "nothing was made where the link leads");
+ }
+ }
+
+ [TestMethod]
+ public void GrantsUsersModifyOnTheRealFolder_AndRefusesALink()
+ {
+ if (!WindowsInfo.IsWindows)
+ {
+ Assert.Inconclusive("folder rights and junctions are Windows features");
+ }
+ using (var temp = new TempFolder())
+ {
+ string top = temp.Path;
+ string elsewhere = Directory.CreateDirectory(Path.Combine(top, "System32")).FullName;
+ string spool = Directory.CreateDirectory(Path.Combine(top, "PrintVect", "spool")).FullName;
+ string real = Path.Combine(spool, "0afbc594d5975d71");
+ string planted = Path.Combine(spool, "1bbbbbbbbbbbbbbb");
+ MakeLink(planted, elsewhere);
+
+ SafeFolders.GrantUsersModify(top, real);
+ var users = new SecurityIdentifier(WellKnownSidType.BuiltinUsersSid, null);
+ AuthorizationRuleCollection rules = Directory.GetAccessControl(real).GetAccessRules(true, false, typeof(SecurityIdentifier));
+ Assert.IsTrue(rules.OfType().Any(r => r.IdentityReference.Equals(users)
+ && (r.FileSystemRights & FileSystemRights.Modify) == FileSystemRights.Modify && r.AccessControlType == AccessControlType.Allow));
+
+ Assert.ThrowsException(() => SafeFolders.GrantUsersModify(top, planted));
+ AuthorizationRuleCollection after = Directory.GetAccessControl(elsewhere).GetAccessRules(true, false, typeof(SecurityIdentifier));
+ Assert.IsFalse(after.OfType().Any(r => r.IdentityReference.Equals(users)), "the folder behind the link is untouched");
+ }
+ }
+ }
+}
diff --git a/tests/PrintVect.Tests/UpdateTests.cs b/tests/PrintVect.Tests/UpdateTests.cs
index 8c1295b..08935f1 100644
--- a/tests/PrintVect.Tests/UpdateTests.cs
+++ b/tests/PrintVect.Tests/UpdateTests.cs
@@ -1,6 +1,7 @@
using System;
using System.Collections.Generic;
using System.IO;
+using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
@@ -8,6 +9,7 @@
using System.Threading.Tasks;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using PrintVect.Core;
+using PrintVect.Core.Diagnostics;
using PrintVect.Core.Update;
namespace PrintVect.Tests
@@ -392,8 +394,11 @@ public async Task DownloadsAndVerifiesTheSetupProgram()
var seen = new List();
var progress = new SynchronousProgress(seen.Add);
- string path = await checker.DownloadAsync(result.Release, folder, progress, CancellationToken.None);
+ VerifiedSetup setup = await checker.DownloadAsync(result.Release, folder, progress, CancellationToken.None);
+ string path = setup.Path;
Assert.AreEqual(Path.Combine(folder, "PrintVect-Setup-9.9.9.exe"), path);
+ Assert.AreEqual(Sha256Hex.OfBytes(installer), setup.Sha256);
+ Assert.AreEqual(installer.Length, setup.Size);
CollectionAssert.AreEqual(installer, File.ReadAllBytes(path));
Assert.IsFalse(File.Exists(path + UpdateChecker.PartExtension));
Assert.IsFalse(File.Exists(Path.Combine(folder, "PrintVect-Setup-0.1.0.exe")), "older downloads are removed");
@@ -420,16 +425,49 @@ public async Task RejectsADamagedOrIncompleteDownload()
StringAssert.Contains(damaged.Message, "checksum");
Assert.AreEqual(0, Directory.GetFiles(temp.Path).Length, "nothing is left behind");
- ReleaseInfo wrongSize = ReleaseInfo.Parse(ReleaseInfoTests.ReleaseJson("v9.9.9", github.BaseUrl, 5, false));
+ ReleaseInfo wrongSize = ReleaseInfo.Parse(ReleaseInfoTests.ReleaseJson("v9.9.9", github.BaseUrl, 5, true));
UpdateVerificationException incomplete = await Assert.ThrowsExceptionAsync(
() => checker.DownloadAsync(wrongSize, temp.Path, null, CancellationToken.None));
StringAssert.Contains(incomplete.Message, "incomplete");
Assert.AreEqual(0, Directory.GetFiles(temp.Path).Length);
- // Without a checksum file the size is all that can be checked, and it matches here.
+ // 0.5.8: without a checksum file nothing is downloaded or installed (a size check alone proves nothing).
ReleaseInfo noHash = ReleaseInfo.Parse(ReleaseInfoTests.ReleaseJson("v9.9.9", github.BaseUrl, installer.Length, false));
- string path = await checker.DownloadAsync(noHash, temp.Path, null, CancellationToken.None);
- CollectionAssert.AreEqual(installer, File.ReadAllBytes(path));
+ UpdateVerificationException unchecked_ = await Assert.ThrowsExceptionAsync(
+ () => checker.DownloadAsync(noHash, temp.Path, null, CancellationToken.None));
+ StringAssert.Contains(unchecked_.Message, "no checksum file");
+ Assert.AreEqual(0, Directory.GetFiles(temp.Path).Length);
+ }
+ }
+
+ [TestMethod]
+ public async Task TheSetupIsCheckedAgainJustBeforeItRuns_AndHeldUnchangeable()
+ {
+ byte[] installer = SampleInstaller();
+ using (var github = new FakeGitHub())
+ using (var temp = new TempFolder())
+ {
+ github.Installer = installer;
+ github.HashText = Sha256Hex.OfBytes(installer) + " PrintVect-Setup-9.9.9.exe\n";
+ var checker = new UpdateChecker(github.FeedUrl, Current);
+ ReleaseInfo release = ReleaseInfo.Parse(ReleaseInfoTests.ReleaseJson("v9.9.9", github.BaseUrl, installer.Length, true));
+
+ VerifiedSetup setup = await checker.DownloadAsync(release, temp.Path, null, CancellationToken.None);
+ using (SetupHold hold = UpdateInstaller.Hold(setup))
+ {
+ Assert.AreEqual(setup.Path, hold.Path);
+ if (WindowsInfo.IsWindows)
+ {
+ Assert.ThrowsException(() => File.WriteAllBytes(setup.Path, new byte[] { 1 }), "nobody can change it while it is held");
+ Assert.ThrowsException(() => File.Delete(setup.Path));
+ Assert.ThrowsException(() => Directory.Move(temp.Path, temp.Path + "-moved"),
+ "nor rename the folder to put another one in its place");
+ }
+ }
+
+ File.WriteAllBytes(setup.Path, installer.Reverse().ToArray()); // another user swaps the file after the download
+ UpdateVerificationException changed = Assert.ThrowsException(() => UpdateInstaller.Hold(setup));
+ StringAssert.Contains(changed.Message, "changed on this PC");
}
}
diff --git a/tools/release_notes.py b/tools/release_notes.py
new file mode 100644
index 0000000..bb49cb9
--- /dev/null
+++ b/tools/release_notes.py
@@ -0,0 +1,76 @@
+#!/usr/bin/env python3
+"""Writes the text of a GitHub release from CHANGELOG.md (used by .github/workflows/release.yml and promote.yml).
+
+A test version (pre-release) says so at the top: PCs that run PrintVect do not install it by themselves, because
+GitHub's "latest release", which they ask for, never is a pre-release. promote.yml rewrites the text without that
+note when the version is handed to every PC.
+
+ python3 tools/release_notes.py 0.5.8 --test --out release-notes.md
+"""
+import argparse
+import os
+import re
+import sys
+
+ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
+REPO = "https://github.com/rahulranjan-dev-py/PrintVect"
+
+
+def changes_for(version, changelog):
+ """The text under "## " (with or without a date after it), up to the next "## " heading."""
+ pattern = r"^## " + re.escape(version) + r"(?![0-9.])[^\n]*\n(.*?)(?=^## |\Z)"
+ match = re.search(pattern, changelog, re.MULTILINE | re.DOTALL)
+ return match.group(1).strip() if match else None
+
+
+def unwrap(text):
+ """Joins the lines of each plain paragraph: GitHub shows a line break in release text as a break."""
+ blocks = []
+ for block in re.split(r"\n\s*\n", text):
+ lines = block.split("\n")
+ plain = not any(re.match(r"\s*([-*+|#>]|[0-9]+\.)\s", line) for line in lines)
+ blocks.append(" ".join(line.strip() for line in lines) if plain else block)
+ return "\n\n".join(blocks)
+
+
+def notes(version, test, changelog):
+ changes = changes_for(version, changelog)
+ if changes is not None:
+ changes = unwrap(changes)
+ if changes is None:
+ sys.exit("CHANGELOG.md has no section \"## %s\": write what changed there first." % version)
+ parts = []
+ if test:
+ parts.append("**Test version.** PCs that run PrintVect do not install it by themselves. To try it, download "
+ "**PrintVect-Setup-%s.exe** below and run it on the PCs you test on. Once it works, it is handed to "
+ "every PC with Actions, **promote**, Run workflow (docs/releasing.md)." % version)
+ parts.append("## What changed in %s\n\n%s" % (version, changes))
+ parts.append("PrintVect shares a printer with every Windows PC and laptop on your network, at home or in the office, "
+ "with no printer driver to install and no Windows password on the PCs that print. "
+ "What it does and how to use it: %s#readme" % REPO)
+ if not test:
+ parts.append("Download **PrintVect-Setup-%s.exe** and run it on a PC that does not have PrintVect yet. "
+ "PCs that already run PrintVect find this version by themselves within a day (Settings tab, Updates) "
+ "and install it with one click." % version)
+ parts.append("The .sha256 file is the checksum PrintVect verifies after downloading. All versions and what each "
+ "changed: %s/blob/main/CHANGELOG.md" % REPO)
+ return "\n\n".join(parts) + "\n"
+
+
+def main():
+ parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
+ parser.add_argument("version", help="for example 0.5.8")
+ parser.add_argument("--test", action="store_true", help="a test version (pre-release)")
+ parser.add_argument("--out", default="release-notes.md")
+ args = parser.parse_args()
+ if not re.fullmatch(r"[0-9]+\.[0-9]+\.[0-9]+", args.version):
+ sys.exit("The version must look like 0.5.8, not \"%s\"." % args.version)
+ with open(os.path.join(ROOT, "CHANGELOG.md"), encoding="utf-8") as f:
+ changelog = f.read().replace("\r\n", "\n")
+ with open(args.out, "w", encoding="utf-8", newline="\n") as f:
+ f.write(notes(args.version, args.test, changelog))
+ print("wrote", args.out)
+
+
+if __name__ == "__main__":
+ main()