Compare commits

...

7 Commits

Author SHA1 Message Date
133fccfc5f Correct the handoff counts: 69 left at c058431
Some checks are pending
Pre-commit checks / pre-commit (push) Waiting to run
Shell tests / shell-tests (push) Waiting to run
Shell tests / arch-tests (push) Waiting to run
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011w2Pj4Ek3ZNMQVYcFHgXDY
2026-08-16 21:34:10 +02:00
c05843153d Split setup_dns_blocker.sh, a live systemd unit target
569 -> 211 across three libs. All seven heredocs sit inside functions,
so function boundaries were safe seams.

The script guards its entry with SETUP_DNS_BLOCKER_SKIP_MAIN, which made
a real function-set comparison possible on a script that would otherwise
reconfigure the machine when sourced: an identical 74 names against a
detached worktree at HEAD. The dns-blocklist-refresh unit still resolves
to it and it still parses.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011w2Pj4Ek3ZNMQVYcFHgXDY
2026-08-16 21:31:03 +02:00
636b77a45d Update the handoff: 70 left, and a warning about what remains
The easy shapes are done. What is left has a named blocker in most
cases, so the next session should expect to revert more often than it
lands a split.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011w2Pj4Ek3ZNMQVYcFHgXDY
2026-08-16 21:27:29 +02:00
61d4ef1418 Record that extracting embedded data is free, unlike embedded code
The blocklist move cleared update_android_hosts.sh in one step with no
linter cost; the plagiarism checker's Python did the opposite. Same
shape, very different price, so the doc now contrasts them directly.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011w2Pj4Ek3ZNMQVYcFHgXDY
2026-08-16 21:25:25 +02:00
af3e4a9b13 Split update_android_hosts.sh; extract its blocklist as data
870 -> 146 across three libs, plus 247 lines of hosts entries moved from
a heredoc into data/android_guardian_blocklist.hosts. A data file draws
no linter, unlike extracting an embedded Python program.

The installed blocklist is byte-identical: md5 7d3f2550 on both sides.

The first attempt cut inside the `case` dispatcher and neither the entry
nor a lib parsed. Redone with the case as a hard boundary - this script
has no main(), so the case block and the argument parsing that feeds it
stay in the entry.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011w2Pj4Ek3ZNMQVYcFHgXDY
2026-08-16 21:23:39 +02:00
5558c6546d Record the library entry-point pattern in the shell recipes
Both shared libs split with no consumer edited, verified by diffing the
exported function set rather than trusting a lint.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011w2Pj4Ek3ZNMQVYcFHgXDY
2026-08-16 21:19:25 +02:00
ef0a26abc7 Split scripts/lib/mtk_common.sh with the same entry-point pattern
503 -> 132 across three parts. The seven mtk_root consumers are
untouched because the path they source is unchanged.

Identical 28-function set before and after, checked after each of the
two carves. The `<<<` in this file are here-strings, not heredocs -
worth confirming rather than assuming, after enforce_vbox_hosts.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011w2Pj4Ek3ZNMQVYcFHgXDY
2026-08-16 21:17:50 +02:00
21 changed files with 1749 additions and 1477 deletions

View File

@ -164,6 +164,39 @@ file, and the entry itself still linted clean with `-x`.
still heredoc-unaware, so check for `<<` in the region you are moving before
choosing a boundary.
### A widely-sourced library splits cleanly — keep it as the entry point
`common.sh` (620, sourced by **49** scripts) and `mtk_common.sh` (503, by 7)
both split with no consumer edited: the original file keeps its path and
sources its own parts, which is the shape the handoff prescribes for
`config.sh`. Move any array or constant along with the function that reads it.
**The check that matters is the exported function set**, not a passing lint:
```bash
bash -c 'source <lib>; declare -F | sed "s/declare -f //" | sort'
# diff that against the same run from a detached worktree at HEAD
```
Both gave an identical set (48 and 28 functions). Re-run it after **each**
carve, not just at the end.
### Extracting embedded _data_ is free; embedded _code_ is not
`update_android_hosts.sh` was 870 lines, of which 247 were a heredoc of hosts
entries. Moving that to `data/android_guardian_blocklist.hosts` and `cat`-ing
it cleared the file in one step, and a data file **attracts no linter**.
Verify with a hash of the heredoc body against the extracted file:
```bash
git show HEAD:<script> | awk "/<<'EOF'/,/^EOF$/" | sed '1d;$d' | md5sum
md5sum < <the extracted file>
```
Contrast the next section: extracting an embedded _program_ is the same shape
but a very different cost.
### Extracting an embedded program pulls it into the Python gate
`install_plagiarism_tools.sh` (534) is mostly two heredocs emitting a 224-line

View File

@ -0,0 +1,17 @@
{
"title": "Split update_android_hosts.sh under the 250-line cap",
"objective": "Bring the 870-line Android hosts installer under the cap, extracting its embedded blocklist as a data file rather than leaving 247 lines of hosts entries inside a heredoc.",
"acceptance_criteria": [
"The entry script and all three new libs are at most 250 lines, and the extracted blocklist is data rather than shell.",
"The blocklist the module installs is byte-identical: the md5 of the original heredoc body must equal the md5 of the extracted file.",
"bash -n passes on the entry and every lib. The script dispatches through a `case` rather than a main(), so no seam may fall inside it.",
"The pre-commit shellcheck hook passes on every file, with no new suppression.",
"The entry declares SCRIPT_DIR exactly once, and it uses ${BASH_SOURCE[0]} because the libs resolve the data path through it."
],
"out_of_scope": [
"Executing the script; it pairs with a phone over adb and installs a Magisk module.",
"Changing any blocklist entry.",
"The other over-cap linux_configuration scripts."
],
"verifier": "md5 comparison of the heredoc body against the extracted data file, bash -n on all four shell files, shellcheck -x on the entry and shellcheck on each lib, and check_file_length.sh."
}

View File

@ -0,0 +1,17 @@
{
"title": "Split setup_dns_blocker.sh under the 250-line cap",
"objective": "Bring the DNS blocker setup script under the cap. It is the ExecStart of the live dns-blocklist-refresh.service unit, so the unit path and the script's exported function set must be unchanged.",
"acceptance_criteria": [
"The entry script and all three new libs are at most 250 lines.",
"Sourcing the script yields exactly the same 74 function names as before, diffed against a detached worktree at HEAD. The script exposes SETUP_DNS_BLOCKER_SKIP_MAIN, so this can be checked without running main().",
"systemctl cat dns-blocklist-refresh.service still resolves to the script, and the script still parses.",
"Every seam falls on a function boundary, outside the seven heredocs.",
"The pre-commit shellcheck hook passes on every file, with no new suppression."
],
"out_of_scope": [
"Running main(); it installs dnsmasq, writes systemd units and changes firewall rules on the live machine.",
"Changing any generated config.",
"The other over-cap linux_configuration scripts."
],
"verifier": "SETUP_DNS_BLOCKER_SKIP_MAIN=1 source + `declare -F`, diffed against the same from a worktree at HEAD; plus systemctl cat and bash -n on the unit's ExecStart; plus pre-commit run --files and check_file_length.sh."
}

View File

@ -0,0 +1,17 @@
{
"title": "Split scripts/lib/mtk_common.sh under the 250-line cap",
"objective": "Bring the shared MediaTek library that seven mtk_root scripts source under the cap, using the same entry-point pattern proven on common.sh, without changing any name it exports.",
"acceptance_criteria": [
"mtk_common.sh and all three new parts are at most 250 lines.",
"mtk_common.sh remains the single path every consumer sources; it sources its own parts.",
"Sourcing it yields exactly the same 28 function names as before, checked after EACH carve rather than only at the end.",
"`<<<` occurrences are confirmed to be here-strings rather than heredocs before choosing a seam.",
"The pre-commit shellcheck hook passes on every file, with no new suppression."
],
"out_of_scope": [
"Executing any mtk_root script; they talk to a phone over USB.",
"Changing what any helper does.",
"The other over-cap linux_configuration scripts."
],
"verifier": "A subshell that sources mtk_common.sh and prints `declare -F`, diffed before and after; plus shellcheck -x, meta/scripts/verify_shell_split.sh on two consumers, and check_file_length.sh."
}

View File

@ -0,0 +1,39 @@
{
"intent": "Split update_android_hosts.sh under the cap, extracting its 247-line blocklist as data rather than shell.",
"scope": [
"linux_configuration/scripts/single_use/utils/update_android_hosts.sh (870 -> 146)",
"lib/android_device.sh, android_module.sh, android_commands.sh (new)",
"data/android_guardian_blocklist.hosts (new)",
"Non-goal: no script executed, no generated content changed"
],
"changes": [
"Three libs for device discovery, module building and the subcommands. The script dispatches through a `case` rather than a main(), so the case block and the argument parsing that feeds it stay in the entry.",
"build_module was 287 lines, almost all of it a single heredoc emitting 247 lines of hosts entries. That is data, so it moved to data/android_guardian_blocklist.hosts and the script now cats it. Unlike extracting an embedded Python program, a data file attracts no linter - it is the cheap version of the same move.",
"Two fixes the split exposed: the entry already declared SCRIPT_DIR (with $0, upgraded to ${BASH_SOURCE[0]} since the libs resolve the data path through it), and COMMAND was being assigned at the end of a lib but read by the entry's case - that argument-parsing tail moved back."
],
"verification": [
{
"command": "md5 of the original heredoc body vs the extracted data file",
"result": "pass",
"evidence": "7d3f2550bf24e30017e360c9f4f23b7f on both sides - the blocklist the module installs is byte-identical. For a script whose job is emitting a file, this is the check that matters."
},
{
"command": "bash -n on the entry and each lib",
"result": "fail then pass",
"evidence": "The first attempt cut inside the `case` statement and both the entry and a lib failed to parse. Redone with the case boundary as a hard limit; all four parse now."
},
{
"command": "shellcheck -x on the entry, shellcheck on each lib",
"result": "pass",
"evidence": "Zero findings across all four files, no suppression."
}
],
"risks": [
"Not executed: it pairs with a phone over adb and installs a Magisk module. The content hash covers what it writes; nothing covers the adb interaction.",
"The blocklist now lives two directories from the code that installs it, resolved through SCRIPT_DIR. If the script is ever copied elsewhere without data/, the module builds with an empty blocklist rather than failing loudly."
],
"rollback": [
"git revert the commit; the script returns to 870 lines with the blocklist inline.",
"After rollback, re-run bash -n and shellcheck on the restored script."
]
}

View File

@ -0,0 +1,37 @@
{
"intent": "Split setup_dns_blocker.sh under the cap without disturbing the live systemd unit that runs it.",
"scope": [
"linux_configuration/scripts/single_use/features/setup_dns_blocker.sh (569 -> 211)",
"lib/dns_units.sh, dns_firewall.sh, dns_dhcp.sh (new)",
"Non-goal: main() not run"
],
"changes": [
"Three libs: the dnsmasq config and systemd unit writers, the validation and firewall block, and the DHCP-server and status block. All seven heredocs sit inside functions, so function boundaries were safe seams.",
"The script guards its own entry with SETUP_DNS_BLOCKER_SKIP_MAIN, which made a proper function-set comparison possible on a script that otherwise reconfigures the machine when sourced."
],
"verification": [
{
"command": "SETUP_DNS_BLOCKER_SKIP_MAIN=1 source the script and diff `declare -F` against a detached worktree at HEAD",
"result": "pass",
"evidence": "Identical 74-function set (its own plus common.sh's). This is the same check used for the two shared libs, and it is available here only because the script provides that escape hatch."
},
{
"command": "systemctl cat dns-blocklist-refresh.service, test -f its ExecStart, bash -n that file",
"result": "pass",
"evidence": "Still resolves to the split script and still parses. This is one of only two units pointing into the repo."
},
{
"command": "bash -n on the entry and each lib; pre-commit run --files",
"result": "pass",
"evidence": "All four parse and the gate is clean, with no suppression."
}
],
"risks": [
"main() was not run: it installs dnsmasq, writes units, and changes nftables and DHCP settings on the live LAN. The function-set diff proves the surface, not the behaviour.",
"The refresh timer invokes the script with `refresh`, which reaches cmd_refresh through the same dispatch; that path is covered by the function-set check but not executed."
],
"rollback": [
"git revert the commit; the script returns to 569 lines and the three libs disappear.",
"After rollback, re-run the SKIP_MAIN function-set check and expect the same 74 names."
]
}

View File

@ -0,0 +1,38 @@
{
"intent": "Split scripts/lib/mtk_common.sh with the same entry-point pattern used for common.sh.",
"scope": [
"linux_configuration/scripts/lib/mtk_common.sh (503 -> 132)",
"lib/mtk_device.sh, mtk_classify.sh, mtk_partitions.sh (new)",
"Non-goal: no behaviour change, no change to the public surface"
],
"changes": [
"mtk_common.sh keeps its logging, path and sanitising helpers and sources three new parts: adb/device selection, device classification, and partition discovery.",
"The seven mtk_root scripts that source it are untouched, because the path they source is unchanged.",
"The `<<<` occurrences in this file are here-strings, not heredocs, so the heredoc hazard did not apply - worth checking rather than assuming, given the enforce_vbox_hosts failure."
],
"verification": [
{
"command": "source mtk_common.sh in a subshell and diff `declare -F` before and after",
"result": "pass",
"evidence": "Identical 28-function set, checked after each of the two carves rather than only at the end."
},
{
"command": "shellcheck -x mtk_common.sh and shellcheck on each part",
"result": "pass",
"evidence": "Zero findings, no suppression."
},
{
"command": "meta/scripts/verify_shell_split.sh on 20-dump-stock.sh and install.sh",
"result": "pass",
"evidence": "Both consumers report 'libs sourced, functions defined' - they source mtk_common.sh from a sibling directory and still resolve everything through the new chain."
}
],
"risks": [
"None of the seven mtk_root consumers was executed: they talk to a phone over USB. The function-set diff plus the stubbed runs are the available evidence.",
"_MTK_LIB_DIR uses ${BASH_SOURCE[0]} because this file is only ever sourced; $0 would point at the calling script."
],
"rollback": [
"git revert the commit; mtk_common.sh returns to 503 lines and the three parts disappear.",
"After rollback, re-run the declare -F diff and expect the same 28 functions."
]
}

View File

@ -0,0 +1,88 @@
#!/bin/bash
# Device classification, partition discovery and layout checks.
#
# Sourced by mtk_common.sh, which stays the single entry point the
# mtk_root scripts source, so their public surface is unchanged.
# ----------------------------------------------------------------------------
# Classification
# ----------------------------------------------------------------------------
# classify_device
# Sets MTK_DEVICE_CLASS to ULEFONE, PIXEL or UNKNOWN, and MTK_CLASS_REASON to
# a human-readable explanation of how it got there.
#
# ULEFONE requires a positive MediaTek signal AND a vendor/model match - both,
# never either, and never "not a Pixel, so presumably the Ulefone". A third
# phone attached by accident must land in UNKNOWN.
classify_device() {
local manufacturer="" model="" platform="" hardware="" device=""
local mtk_match=0 ulefone_match=0 pixel_match=0
manufacturer="$(dev_getprop ro.product.manufacturer)"
model="$(dev_getprop ro.product.model)"
platform="$(dev_getprop ro.board.platform)"
hardware="$(dev_getprop ro.hardware)"
device="$(dev_getprop ro.product.device)"
MTK_PROP_MANUFACTURER="$manufacturer"
MTK_PROP_MODEL="$model"
MTK_PROP_PLATFORM="$platform"
MTK_PROP_HARDWARE="$hardware"
MTK_PROP_DEVICE="$device"
if [[ $platform =~ $MTK_PLATFORM_PATTERN ]] || [[ $hardware =~ $MTK_PLATFORM_PATTERN ]]; then
mtk_match=1
fi
if [[ $manufacturer =~ $ULEFONE_VENDOR_PATTERN ]] || [[ $model =~ $ULEFONE_MODEL_PATTERN ]]; then
ulefone_match=1
fi
if [[ $manufacturer =~ $PIXEL_VENDOR_PATTERN ]] && [[ $model =~ $PIXEL_MODEL_PATTERN ]]; then
pixel_match=1
fi
if [[ $mtk_match -eq 1 && $ulefone_match -eq 1 ]]; then
MTK_DEVICE_CLASS="ULEFONE"
MTK_CLASS_REASON="MediaTek platform [${platform:-unset}/${hardware:-unset}] and Ulefone identity [${manufacturer} ${model}]"
elif [[ $pixel_match -eq 1 ]]; then
MTK_DEVICE_CLASS="PIXEL"
MTK_CLASS_REASON="Google Pixel identity [${manufacturer} ${model}]"
else
MTK_DEVICE_CLASS="UNKNOWN"
MTK_CLASS_REASON="no rule matched: manufacturer=[${manufacturer}] model=[${model}] platform=[${platform}] hardware=[${hardware}]"
fi
export MTK_DEVICE_CLASS MTK_CLASS_REASON
export MTK_PROP_MANUFACTURER MTK_PROP_MODEL MTK_PROP_PLATFORM MTK_PROP_HARDWARE MTK_PROP_DEVICE
}
# mtk_explain_classification - why classify_device decided what it did.
mtk_explain_classification() {
printf 'ro.product.manufacturer = %s\n' "${MTK_PROP_MANUFACTURER:-}"
printf 'ro.product.model = %s\n' "${MTK_PROP_MODEL:-}"
printf 'ro.product.device = %s\n' "${MTK_PROP_DEVICE:-}"
printf 'ro.board.platform = %s\n' "${MTK_PROP_PLATFORM:-}"
printf 'ro.hardware = %s\n' "${MTK_PROP_HARDWARE:-}"
printf '\n'
printf 'MediaTek pattern : %s\n' "$MTK_PLATFORM_PATTERN"
printf 'Ulefone vendor : %s\n' "$ULEFONE_VENDOR_PATTERN"
printf 'Ulefone model : %s\n' "$ULEFONE_MODEL_PATTERN"
printf 'Pixel vendor : %s\n' "$PIXEL_VENDOR_PATTERN"
printf 'Pixel model : %s\n' "$PIXEL_MODEL_PATTERN"
printf '\n'
printf 'Verdict: %s\n' "${MTK_DEVICE_CLASS:-unset}"
printf 'Reason : %s\n' "${MTK_CLASS_REASON:-unset}"
}
# mtk_assert_mediatek
# A positive assertion, deliberately not "is not a Pixel". Used to gate the
# only script that touches partitions.
mtk_assert_mediatek() {
if [[ ${MTK_PROP_PLATFORM:-} =~ $MTK_PLATFORM_PATTERN ]]; then
return 0
fi
if [[ ${MTK_PROP_HARDWARE:-} =~ $MTK_PLATFORM_PATTERN ]]; then
return 0
fi
return 1
}

View File

@ -123,381 +123,10 @@ dev_list_by_name() {
mtk_adb shell 'ls -1 /dev/block/by-name/ 2>/dev/null' 2>/dev/null | tr -d '\r' || true
}
# mtk_adb <args...> - serial-pinned adb, so a second phone plugged in midway
# cannot silently become the target.
mtk_adb() {
adb -s "${MTK_SERIAL:?mtk_select_device must run first}" "$@"
}
# ----------------------------------------------------------------------------
# Device presence and authorization
# ----------------------------------------------------------------------------
# mtk_list_devices - prints "<serial> <state>" per attached device.
mtk_list_devices() {
adb devices 2>/dev/null |
awk 'NR > 1 && $2 ~ /^(device|offline|unauthorized|recovery|sideload)$/ { print $1, $2 }'
}
# mtk_device_state <serial> - device|unauthorized|offline|absent
mtk_device_state() {
local serial="$1"
local state=""
state="$(mtk_list_devices | awk -v s="$serial" '$1 == s { print $2; exit }')"
printf '%s' "${state:-absent}"
}
# mtk_select_device [requested-serial]
# Sets MTK_SERIAL. Refuses when the choice is ambiguous rather than picking
# one - a wrong guess here targets the wrong phone.
mtk_select_device() {
local requested="${1:-${MTK_SERIAL:-}}"
local -a device_rows=()
local -a serials=()
local row=""
if [[ -n ${MTK_ROOT_FIXTURE:-} ]]; then
MTK_SERIAL="${MTK_SERIAL:-fixture}"
export MTK_SERIAL
return 0
fi
mapfile -t device_rows < <(mtk_list_devices)
if [[ ${#device_rows[@]} -eq 0 ]]; then
mtk_error "No device visible to adb."
mtk_error "Check: cable seated, USB debugging enabled, and try 'adb devices'."
return 1
fi
for row in "${device_rows[@]}"; do
serials+=("${row%% *}")
done
if [[ -n $requested ]]; then
for row in "${serials[@]}"; do
if [[ $row == "$requested" ]]; then
MTK_SERIAL="$requested"
export MTK_SERIAL
return 0
fi
done
mtk_error "Requested serial '${requested}' is not attached. Attached: ${serials[*]}"
return 1
fi
if [[ ${#serials[@]} -gt 1 ]]; then
mtk_error "Multiple devices attached (${serials[*]}); refusing to guess."
mtk_error "Re-run with --serial <serial>."
return 1
fi
MTK_SERIAL="${serials[0]}"
export MTK_SERIAL
return 0
}
# mtk_require_authorized
# An unauthorized device answers every getprop with an empty string, which
# reads exactly like "this device has no properties". Catch it up front so the
# report never blames the device for a prompt sitting unanswered on its screen.
mtk_require_authorized() {
local state=""
[[ -n ${MTK_ROOT_FIXTURE:-} ]] && return 0
state="$(mtk_device_state "${MTK_SERIAL}")"
case "$state" in
device)
return 0
;;
unauthorized)
mtk_error "Device ${MTK_SERIAL} is UNAUTHORIZED."
mtk_error "The RSA authorization prompt is on the phone's screen - unlock it and tap Allow."
mtk_error "If no prompt appears: revoke USB debugging authorizations on the phone, then replug."
return 1
;;
offline)
mtk_error "Device ${MTK_SERIAL} is OFFLINE. Replug the cable, or run 'adb kill-server'."
return 1
;;
*)
mtk_error "Device ${MTK_SERIAL} is in state '${state}', which this toolkit does not read."
return 1
;;
esac
}
# ----------------------------------------------------------------------------
# Classification
# ----------------------------------------------------------------------------
# classify_device
# Sets MTK_DEVICE_CLASS to ULEFONE, PIXEL or UNKNOWN, and MTK_CLASS_REASON to
# a human-readable explanation of how it got there.
#
# ULEFONE requires a positive MediaTek signal AND a vendor/model match - both,
# never either, and never "not a Pixel, so presumably the Ulefone". A third
# phone attached by accident must land in UNKNOWN.
classify_device() {
local manufacturer="" model="" platform="" hardware="" device=""
local mtk_match=0 ulefone_match=0 pixel_match=0
manufacturer="$(dev_getprop ro.product.manufacturer)"
model="$(dev_getprop ro.product.model)"
platform="$(dev_getprop ro.board.platform)"
hardware="$(dev_getprop ro.hardware)"
device="$(dev_getprop ro.product.device)"
MTK_PROP_MANUFACTURER="$manufacturer"
MTK_PROP_MODEL="$model"
MTK_PROP_PLATFORM="$platform"
MTK_PROP_HARDWARE="$hardware"
MTK_PROP_DEVICE="$device"
if [[ $platform =~ $MTK_PLATFORM_PATTERN ]] || [[ $hardware =~ $MTK_PLATFORM_PATTERN ]]; then
mtk_match=1
fi
if [[ $manufacturer =~ $ULEFONE_VENDOR_PATTERN ]] || [[ $model =~ $ULEFONE_MODEL_PATTERN ]]; then
ulefone_match=1
fi
if [[ $manufacturer =~ $PIXEL_VENDOR_PATTERN ]] && [[ $model =~ $PIXEL_MODEL_PATTERN ]]; then
pixel_match=1
fi
if [[ $mtk_match -eq 1 && $ulefone_match -eq 1 ]]; then
MTK_DEVICE_CLASS="ULEFONE"
MTK_CLASS_REASON="MediaTek platform [${platform:-unset}/${hardware:-unset}] and Ulefone identity [${manufacturer} ${model}]"
elif [[ $pixel_match -eq 1 ]]; then
MTK_DEVICE_CLASS="PIXEL"
MTK_CLASS_REASON="Google Pixel identity [${manufacturer} ${model}]"
else
MTK_DEVICE_CLASS="UNKNOWN"
MTK_CLASS_REASON="no rule matched: manufacturer=[${manufacturer}] model=[${model}] platform=[${platform}] hardware=[${hardware}]"
fi
export MTK_DEVICE_CLASS MTK_CLASS_REASON
export MTK_PROP_MANUFACTURER MTK_PROP_MODEL MTK_PROP_PLATFORM MTK_PROP_HARDWARE MTK_PROP_DEVICE
}
# mtk_explain_classification - why classify_device decided what it did.
mtk_explain_classification() {
printf 'ro.product.manufacturer = %s\n' "${MTK_PROP_MANUFACTURER:-}"
printf 'ro.product.model = %s\n' "${MTK_PROP_MODEL:-}"
printf 'ro.product.device = %s\n' "${MTK_PROP_DEVICE:-}"
printf 'ro.board.platform = %s\n' "${MTK_PROP_PLATFORM:-}"
printf 'ro.hardware = %s\n' "${MTK_PROP_HARDWARE:-}"
printf '\n'
printf 'MediaTek pattern : %s\n' "$MTK_PLATFORM_PATTERN"
printf 'Ulefone vendor : %s\n' "$ULEFONE_VENDOR_PATTERN"
printf 'Ulefone model : %s\n' "$ULEFONE_MODEL_PATTERN"
printf 'Pixel vendor : %s\n' "$PIXEL_VENDOR_PATTERN"
printf 'Pixel model : %s\n' "$PIXEL_MODEL_PATTERN"
printf '\n'
printf 'Verdict: %s\n' "${MTK_DEVICE_CLASS:-unset}"
printf 'Reason : %s\n' "${MTK_CLASS_REASON:-unset}"
}
# mtk_assert_mediatek
# A positive assertion, deliberately not "is not a Pixel". Used to gate the
# only script that touches partitions.
mtk_assert_mediatek() {
if [[ ${MTK_PROP_PLATFORM:-} =~ $MTK_PLATFORM_PATTERN ]]; then
return 0
fi
if [[ ${MTK_PROP_HARDWARE:-} =~ $MTK_PLATFORM_PATTERN ]]; then
return 0
fi
return 1
}
# ----------------------------------------------------------------------------
# Partition discovery
# ----------------------------------------------------------------------------
# discover_partitions
# Sets MTK_AB_SCHEME, MTK_SLOT_SUFFIX, MTK_RAMDISK_PART, MTK_VBMETA_PART,
# MTK_BY_NAME (newline-separated listing).
#
# The governing rule: never name a partition in a conditional that was not
# first observed in the listing. The AOSP rule (devices launching on Android
# 13+ carry the ramdisk in init_boot; earlier ones keep it in boot) explains
# WHY the preference order below is correct, but the code never consults the
# API level to decide - it reads the filesystem. That is what lets one code
# path serve both a Pixel (no init_boot -> falls through to boot) and a
# 13-launch MediaTek device (init_boot present -> taken) without branching on
# device identity.
discover_partitions() {
local entries="" suffix="" candidate="" name=""
entries="$(dev_list_by_name)"
MTK_BY_NAME="$entries"
export MTK_BY_NAME
if [[ -z $entries ]]; then
MTK_AB_SCHEME="unknown"
MTK_SLOT_SUFFIX=""
MTK_RAMDISK_PART=""
MTK_VBMETA_PART=""
export MTK_AB_SCHEME MTK_SLOT_SUFFIX MTK_RAMDISK_PART MTK_VBMETA_PART
return 1
fi
# Slot scheme comes from observed suffixes, not from a product table.
if grep -qE '_a$' <<<"$entries"; then
MTK_AB_SCHEME="A/B"
else
MTK_AB_SCHEME="A-only"
fi
# Prefer the device's own view of the active slot; fall back to _a only
# because a dump has to start somewhere, and say so in the report.
suffix="$(dev_getprop ro.boot.slot_suffix)"
if [[ -z $suffix && $MTK_AB_SCHEME == "A/B" ]]; then
suffix="_a"
MTK_SLOT_ASSUMED=1
else
MTK_SLOT_ASSUMED=0
fi
MTK_SLOT_SUFFIX="$suffix"
# init_boot first: its presence is decisive. A device that has it keeps the
# ramdisk there even though boot also exists, so checking boot first would
# pick the wrong partition on exactly the hardware this toolkit is for.
MTK_RAMDISK_PART=""
for candidate in init_boot boot; do
for name in "${candidate}${suffix}" "${candidate}"; do
if grep -qxF -- "$name" <<<"$entries"; then
MTK_RAMDISK_PART="$name"
break 2
fi
done
done
MTK_VBMETA_PART=""
for name in "vbmeta${suffix}" "vbmeta"; do
if grep -qxF -- "$name" <<<"$entries"; then
MTK_VBMETA_PART="$name"
break
fi
done
export MTK_AB_SCHEME MTK_SLOT_SUFFIX MTK_RAMDISK_PART MTK_VBMETA_PART MTK_SLOT_ASSUMED
[[ -n $MTK_RAMDISK_PART ]]
}
# mtk_ramdisk_carrier - "init_boot" or "boot", suffix stripped.
mtk_ramdisk_carrier() {
local part="${MTK_RAMDISK_PART:-}"
printf '%s' "${part%_[ab]}"
}
# mtk_check_layout_expectation
# Cross-check only. first_api_level >= 33 predicts init_boot; below predicts
# boot. A mismatch means either a vendor deviation or a bad read - the human
# should look, but the filesystem still wins.
mtk_check_layout_expectation() {
local api_level="" carrier="" expected=""
api_level="$(dev_getprop ro.product.first_api_level)"
carrier="$(mtk_ramdisk_carrier)"
[[ -z $api_level || -z $carrier ]] && return 0
[[ $api_level =~ ^[0-9]+$ ]] || return 0
if [[ $api_level -ge 33 ]]; then
expected="init_boot"
else
expected="boot"
fi
if [[ $carrier != "$expected" ]]; then
mtk_warn "Layout disagrees with expectation: first_api_level=${api_level} predicts '${expected}', device shows '${carrier}'."
mtk_warn "Trusting the device. Verify before flashing anything."
return 1
fi
return 0
}
# ----------------------------------------------------------------------------
# Host environment checks (read-only; install.sh owns the mutating half)
# ----------------------------------------------------------------------------
# mtk_udev_catchall_files
# Prints any rules file containing an ACTIVE wildcard-vendor rule granting
# world read/write. Such a rule applies to every USB device on the system -
# storage, security keys, everything - not just phones.
#
# Commented-out lines are ignored: --fix-udev disables a rule by commenting it
# rather than deleting it, so matching those would leave the check permanently
# red after it had already been dealt with. Only *.rules files are considered,
# since udev itself skips any other suffix (including our .bak- backups).
mtk_udev_catchall_files() {
local file=""
for file in /etc/udev/rules.d/*.rules; do
[[ -f $file ]] || continue
if grep -qE '^[^#]*idVendor\}=="\*"[^#]*MODE="0666"|^[^#]*MODE="0666"[^#]*idVendor\}=="\*"' \
"$file" 2>/dev/null; then
printf '%s\n' "$file"
fi
done
}
# mtk_check_venv - is the mtkclient venv actually usable?
# Checks importability, not directory existence: the venv found on this host
# in Aug 2026 existed, looked complete, and failed at `import usb` because a
# Python upgrade had orphaned it.
mtk_check_venv() {
local python_bin=""
python_bin="$(mtk_venv_python)"
if [[ ! -x $python_bin ]]; then
printf 'missing: no interpreter at %s' "$python_bin"
return 1
fi
if ! "$python_bin" -c 'import usb, usb.core, serial' 2>/dev/null; then
local err=""
err="$("$python_bin" -c 'import usb, usb.core, serial' 2>&1 | tail -1)"
printf 'broken: %s' "$err"
return 1
fi
printf 'ok: %s' "$("$python_bin" --version 2>&1)"
return 0
}
# mtk_sha256 <file>
mtk_sha256() {
sha256sum "$1" | awk '{ print $1 }'
}
# mtk_file_size <file>
mtk_file_size() {
stat -c '%s' "$1"
}
# mtk_sane_ramdisk_size <bytes>
# A dump outside this band is not necessarily wrong, but it is worth stopping
# for: an empty or truncated read and an accidental whole-disk grab both look
# like success to mtkclient's exit code.
mtk_sane_ramdisk_size() {
local size="$1"
if [[ ! $size =~ ^[0-9]+$ ]]; then
printf 'size is not a number: %s' "$size"
return 1
fi
if [[ $size -lt $MTK_RAMDISK_MIN_BYTES ]]; then
printf 'implausibly small: %s bytes (< %s)' "$size" "$MTK_RAMDISK_MIN_BYTES"
return 1
fi
if [[ $size -gt $MTK_RAMDISK_MAX_BYTES ]]; then
printf 'implausibly large: %s bytes (> %s)' "$size" "$MTK_RAMDISK_MAX_BYTES"
return 1
fi
printf '%s bytes' "$size"
return 0
}
_MTK_LIB_DIR="$(dirname "$(readlink -f "${BASH_SOURCE[0]}")")"
# shellcheck source=mtk_device.sh
source "$_MTK_LIB_DIR/mtk_device.sh"
# shellcheck source=mtk_classify.sh
source "$_MTK_LIB_DIR/mtk_classify.sh"
# shellcheck source=mtk_partitions.sh
source "$_MTK_LIB_DIR/mtk_partitions.sh"

View File

@ -0,0 +1,111 @@
#!/bin/bash
# adb wrappers, device listing, selection and authorisation.
#
# Sourced by mtk_common.sh, which stays the single entry point the
# mtk_root scripts source, so their public surface is unchanged.
# mtk_adb <args...> - serial-pinned adb, so a second phone plugged in midway
# cannot silently become the target.
mtk_adb() {
adb -s "${MTK_SERIAL:?mtk_select_device must run first}" "$@"
}
# ----------------------------------------------------------------------------
# Device presence and authorization
# ----------------------------------------------------------------------------
# mtk_list_devices - prints "<serial> <state>" per attached device.
mtk_list_devices() {
adb devices 2>/dev/null |
awk 'NR > 1 && $2 ~ /^(device|offline|unauthorized|recovery|sideload)$/ { print $1, $2 }'
}
# mtk_device_state <serial> - device|unauthorized|offline|absent
mtk_device_state() {
local serial="$1"
local state=""
state="$(mtk_list_devices | awk -v s="$serial" '$1 == s { print $2; exit }')"
printf '%s' "${state:-absent}"
}
# mtk_select_device [requested-serial]
# Sets MTK_SERIAL. Refuses when the choice is ambiguous rather than picking
# one - a wrong guess here targets the wrong phone.
mtk_select_device() {
local requested="${1:-${MTK_SERIAL:-}}"
local -a device_rows=()
local -a serials=()
local row=""
if [[ -n ${MTK_ROOT_FIXTURE:-} ]]; then
MTK_SERIAL="${MTK_SERIAL:-fixture}"
export MTK_SERIAL
return 0
fi
mapfile -t device_rows < <(mtk_list_devices)
if [[ ${#device_rows[@]} -eq 0 ]]; then
mtk_error "No device visible to adb."
mtk_error "Check: cable seated, USB debugging enabled, and try 'adb devices'."
return 1
fi
for row in "${device_rows[@]}"; do
serials+=("${row%% *}")
done
if [[ -n $requested ]]; then
for row in "${serials[@]}"; do
if [[ $row == "$requested" ]]; then
MTK_SERIAL="$requested"
export MTK_SERIAL
return 0
fi
done
mtk_error "Requested serial '${requested}' is not attached. Attached: ${serials[*]}"
return 1
fi
if [[ ${#serials[@]} -gt 1 ]]; then
mtk_error "Multiple devices attached (${serials[*]}); refusing to guess."
mtk_error "Re-run with --serial <serial>."
return 1
fi
MTK_SERIAL="${serials[0]}"
export MTK_SERIAL
return 0
}
# mtk_require_authorized
# An unauthorized device answers every getprop with an empty string, which
# reads exactly like "this device has no properties". Catch it up front so the
# report never blames the device for a prompt sitting unanswered on its screen.
mtk_require_authorized() {
local state=""
[[ -n ${MTK_ROOT_FIXTURE:-} ]] && return 0
state="$(mtk_device_state "${MTK_SERIAL}")"
case "$state" in
device)
return 0
;;
unauthorized)
mtk_error "Device ${MTK_SERIAL} is UNAUTHORIZED."
mtk_error "The RSA authorization prompt is on the phone's screen - unlock it and tap Allow."
mtk_error "If no prompt appears: revoke USB debugging authorizations on the phone, then replug."
return 1
;;
offline)
mtk_error "Device ${MTK_SERIAL} is OFFLINE. Replug the cable, or run 'adb kill-server'."
return 1
;;
*)
mtk_error "Device ${MTK_SERIAL} is in state '${state}', which this toolkit does not read."
return 1
;;
esac
}

View File

@ -0,0 +1,195 @@
#!/bin/bash
# Partition discovery, ramdisk carrier and layout expectations.
#
# Sourced by mtk_common.sh, which stays the single entry point the
# mtk_root scripts source, so their public surface is unchanged.
# ----------------------------------------------------------------------------
# Partition discovery
# ----------------------------------------------------------------------------
# discover_partitions
# Sets MTK_AB_SCHEME, MTK_SLOT_SUFFIX, MTK_RAMDISK_PART, MTK_VBMETA_PART,
# MTK_BY_NAME (newline-separated listing).
#
# The governing rule: never name a partition in a conditional that was not
# first observed in the listing. The AOSP rule (devices launching on Android
# 13+ carry the ramdisk in init_boot; earlier ones keep it in boot) explains
# WHY the preference order below is correct, but the code never consults the
# API level to decide - it reads the filesystem. That is what lets one code
# path serve both a Pixel (no init_boot -> falls through to boot) and a
# 13-launch MediaTek device (init_boot present -> taken) without branching on
# device identity.
discover_partitions() {
local entries="" suffix="" candidate="" name=""
entries="$(dev_list_by_name)"
MTK_BY_NAME="$entries"
export MTK_BY_NAME
if [[ -z $entries ]]; then
MTK_AB_SCHEME="unknown"
MTK_SLOT_SUFFIX=""
MTK_RAMDISK_PART=""
MTK_VBMETA_PART=""
export MTK_AB_SCHEME MTK_SLOT_SUFFIX MTK_RAMDISK_PART MTK_VBMETA_PART
return 1
fi
# Slot scheme comes from observed suffixes, not from a product table.
if grep -qE '_a$' <<<"$entries"; then
MTK_AB_SCHEME="A/B"
else
MTK_AB_SCHEME="A-only"
fi
# Prefer the device's own view of the active slot; fall back to _a only
# because a dump has to start somewhere, and say so in the report.
suffix="$(dev_getprop ro.boot.slot_suffix)"
if [[ -z $suffix && $MTK_AB_SCHEME == "A/B" ]]; then
suffix="_a"
MTK_SLOT_ASSUMED=1
else
MTK_SLOT_ASSUMED=0
fi
MTK_SLOT_SUFFIX="$suffix"
# init_boot first: its presence is decisive. A device that has it keeps the
# ramdisk there even though boot also exists, so checking boot first would
# pick the wrong partition on exactly the hardware this toolkit is for.
MTK_RAMDISK_PART=""
for candidate in init_boot boot; do
for name in "${candidate}${suffix}" "${candidate}"; do
if grep -qxF -- "$name" <<<"$entries"; then
MTK_RAMDISK_PART="$name"
break 2
fi
done
done
MTK_VBMETA_PART=""
for name in "vbmeta${suffix}" "vbmeta"; do
if grep -qxF -- "$name" <<<"$entries"; then
MTK_VBMETA_PART="$name"
break
fi
done
export MTK_AB_SCHEME MTK_SLOT_SUFFIX MTK_RAMDISK_PART MTK_VBMETA_PART MTK_SLOT_ASSUMED
[[ -n $MTK_RAMDISK_PART ]]
}
# mtk_ramdisk_carrier - "init_boot" or "boot", suffix stripped.
mtk_ramdisk_carrier() {
local part="${MTK_RAMDISK_PART:-}"
printf '%s' "${part%_[ab]}"
}
# mtk_check_layout_expectation
# Cross-check only. first_api_level >= 33 predicts init_boot; below predicts
# boot. A mismatch means either a vendor deviation or a bad read - the human
# should look, but the filesystem still wins.
mtk_check_layout_expectation() {
local api_level="" carrier="" expected=""
api_level="$(dev_getprop ro.product.first_api_level)"
carrier="$(mtk_ramdisk_carrier)"
[[ -z $api_level || -z $carrier ]] && return 0
[[ $api_level =~ ^[0-9]+$ ]] || return 0
if [[ $api_level -ge 33 ]]; then
expected="init_boot"
else
expected="boot"
fi
if [[ $carrier != "$expected" ]]; then
mtk_warn "Layout disagrees with expectation: first_api_level=${api_level} predicts '${expected}', device shows '${carrier}'."
mtk_warn "Trusting the device. Verify before flashing anything."
return 1
fi
return 0
}
# ----------------------------------------------------------------------------
# Host environment checks (read-only; install.sh owns the mutating half)
# ----------------------------------------------------------------------------
# mtk_udev_catchall_files
# Prints any rules file containing an ACTIVE wildcard-vendor rule granting
# world read/write. Such a rule applies to every USB device on the system -
# storage, security keys, everything - not just phones.
#
# Commented-out lines are ignored: --fix-udev disables a rule by commenting it
# rather than deleting it, so matching those would leave the check permanently
# red after it had already been dealt with. Only *.rules files are considered,
# since udev itself skips any other suffix (including our .bak- backups).
mtk_udev_catchall_files() {
local file=""
for file in /etc/udev/rules.d/*.rules; do
[[ -f $file ]] || continue
if grep -qE '^[^#]*idVendor\}=="\*"[^#]*MODE="0666"|^[^#]*MODE="0666"[^#]*idVendor\}=="\*"' \
"$file" 2>/dev/null; then
printf '%s\n' "$file"
fi
done
}
# mtk_check_venv - is the mtkclient venv actually usable?
# Checks importability, not directory existence: the venv found on this host
# in Aug 2026 existed, looked complete, and failed at `import usb` because a
# Python upgrade had orphaned it.
mtk_check_venv() {
local python_bin=""
python_bin="$(mtk_venv_python)"
if [[ ! -x $python_bin ]]; then
printf 'missing: no interpreter at %s' "$python_bin"
return 1
fi
if ! "$python_bin" -c 'import usb, usb.core, serial' 2>/dev/null; then
local err=""
err="$("$python_bin" -c 'import usb, usb.core, serial' 2>&1 | tail -1)"
printf 'broken: %s' "$err"
return 1
fi
printf 'ok: %s' "$("$python_bin" --version 2>&1)"
return 0
}
# mtk_sha256 <file>
mtk_sha256() {
sha256sum "$1" | awk '{ print $1 }'
}
# mtk_file_size <file>
mtk_file_size() {
stat -c '%s' "$1"
}
# mtk_sane_ramdisk_size <bytes>
# A dump outside this band is not necessarily wrong, but it is worth stopping
# for: an empty or truncated read and an accidental whole-disk grab both look
# like success to mtkclient's exit code.
mtk_sane_ramdisk_size() {
local size="$1"
if [[ ! $size =~ ^[0-9]+$ ]]; then
printf 'size is not a number: %s' "$size"
return 1
fi
if [[ $size -lt $MTK_RAMDISK_MIN_BYTES ]]; then
printf 'implausibly small: %s bytes (< %s)' "$size" "$MTK_RAMDISK_MIN_BYTES"
return 1
fi
if [[ $size -gt $MTK_RAMDISK_MAX_BYTES ]]; then
printf 'implausibly large: %s bytes (> %s)' "$size" "$MTK_RAMDISK_MAX_BYTES"
return 1
fi
printf '%s bytes' "$size"
return 0
}

View File

@ -0,0 +1,188 @@
#!/bin/bash
# Static IP, DHCP server config and the status report.
#
# Sourced by setup_dns_blocker.sh; split out to keep it under the 250-line cap.
# Sourced rather than run, so it inherits the caller's strict mode.
configure_static_ip() {
has_cmd nmcli || die "nmcli (NetworkManager) not found; cannot pin a static IP automatically."
local con
con="$(nm_connection)"
[[ -n $con ]] || die "No active NetworkManager connection on ${LAN_IFACE}."
log_info "Pinning ${LAN_IFACE} to static ${LAN_IP}/24 (gw ${GATEWAY}) on '${con}'..."
nmcli con mod "$con" \
ipv4.method manual \
ipv4.addresses "${LAN_IP}/24" \
ipv4.gateway "$GATEWAY" \
ipv4.dns "$GATEWAY"
nmcli con up "$con" >/dev/null
# Safety self-check: if the static config broke connectivity, auto-revert to
# DHCP-client mode immediately so the machine never ends up stranded.
if ping -c1 -W3 "$GATEWAY" >/dev/null 2>&1; then
log_ok "Static IP applied; gateway reachable. ${LAN_IFACE} no longer needs external DHCP."
else
log_error "Gateway unreachable after static IP change -- auto-reverting to DHCP."
revert_nic_to_dhcp "$con"
die "Static IP self-check failed; reverted to DHCP. DHCP mode aborted (no changes kept)."
fi
}
write_dhcp_conf() {
local mac net_prefix
mac="$(cat "/sys/class/net/${LAN_IFACE}/address")"
net_prefix="${LAN_IP%.*}"
log_info "Writing ${DHCP_CONF} (range ${net_prefix}.${DHCP_START_HOST}-${net_prefix}.${DHCP_END_HOST}, DNS ${LAN_IP})."
cat >"$DHCP_CONF" <<EOF
# Managed by setup_dns_blocker.sh -- this PC is the LAN DHCP server.
# Only serve leases once the router's own DHCP is disabled (two servers clash).
dhcp-authoritative
dhcp-range=${net_prefix}.${DHCP_START_HOST},${net_prefix}.${DHCP_END_HOST},${DHCP_LEASE}
dhcp-option=option:router,${GATEWAY}
dhcp-option=option:dns-server,${LAN_IP}
# Reserve this PC's static address against its own MAC.
dhcp-host=${mac},${LAN_IP}
# Log every DHCP transaction (low volume; satisfies "log failures").
log-dhcp
EOF
}
cmd_dhcp() {
detect_lan
is_service_active dnsmasq ||
die "Run 'setup' first -- dnsmasq must be configured before enabling DHCP mode."
echo
log_warn "DHCP takeover: this PC (${LAN_IP}) will become the LAN's DHCP server."
log_warn "Disable the router's DHCP FIRST (untick 'wlacz serwer DHCP' -> Zapisz),"
log_warn "otherwise two DHCP servers will fight on the LAN."
if ! ask_yes_no "Have you already disabled the router's DHCP server?"; then
log_warn "Not activating -- two DHCP servers on one LAN conflict."
log_warn "Disable the router's DHCP ('wlacz serwer DHCP' -> Zapisz), then re-run: sudo ${SELF} dhcp"
return 0
fi
configure_static_ip
write_dhcp_conf
dnsmasq --test >/dev/null 2>&1 || die "dnsmasq config invalid after adding DHCP -- not restarting."
systemctl restart dnsmasq
log_ok "This PC is now the LAN DHCP server; new leases advertise ${LAN_IP} as DNS."
log_info "Reconnect a device's WiFi to pick up the new lease, then browse to a blocked site to confirm."
cat <<EOF
---- IF ANYTHING GOES WRONG (one command, cannot lock you out) ------------
sudo ${SELF} dhcp-off
-> stops serving DHCP, KEEPS this PC online on ${LAN_IP}.
Then re-tick the router's DHCP ('wlacz serwer DHCP' -> Zapisz) so other
devices get addresses again. This PC stays reachable throughout.
--------------------------------------------------------------------------
EOF
}
# Roll back DHCP mode: stop serving leases. KEEPS this PC on its static IP so
# running rollback can never strand the machine (the router reserves ${LAN_IP}
# anyway). Re-enable the router's DHCP afterwards for the other devices.
cmd_dhcp_off() {
detect_lan
if [[ -f $DHCP_CONF ]]; then
rm -f "$DHCP_CONF"
log_ok "Removed ${DHCP_CONF} (PC no longer serves DHCP)."
else
log_info "No DHCP config present; nothing to remove."
fi
is_service_active dnsmasq && systemctl restart dnsmasq
log_ok "DHCP serving stopped. This PC keeps its static IP (${LAN_IP}); still online."
log_warn "Now re-enable the router's DHCP ('wlacz serwer DHCP' -> Zapisz) so other devices get addresses."
log_info "Optional: to also put THIS PC back on router DHCP (after re-enabling it above), run:"
log_info " nmcli con mod '$(nm_connection)' ipv4.method auto ipv4.addresses '' ipv4.gateway '' ipv4.dns '' && nmcli con up '$(nm_connection)'"
}
# ---- Status ----------------------------------------------------------------
status_line() {
# $1 ok/bad flag ("0" ok), $2 message
if [[ $1 == "0" ]]; then log_ok "$2"; else log_warn "$2"; fi
}
cmd_status() {
detect_lan
echo "=== LAN DNS blocker status ==="
if is_service_active dnsmasq; then
status_line 0 "dnsmasq: active"
else
status_line 1 "dnsmasq: NOT active"
fi
if is_service_enabled dnsmasq; then
status_line 0 "dnsmasq: enabled at boot"
else
status_line 1 "dnsmasq: NOT enabled"
fi
if [[ -f $DNSMASQ_DROPIN ]]; then
status_line 0 "Restart=always drop-in present"
else
status_line 1 "Restart drop-in missing"
fi
if [[ -f $FEED ]]; then
status_line 0 "blocklist feed: $(wc -l <"$FEED") lines, updated $(date -r "$FEED" '+%Y-%m-%d %H:%M')"
else
status_line 1 "blocklist feed missing: ${FEED}"
fi
if ss -tulnp 2>/dev/null | grep -qE "${LAN_IP}:53|:53 "; then
status_line 0 "listening on ${LAN_IP}:53"
else
status_line 1 "not listening on ${LAN_IP}:53"
fi
local fw_input
fw_input="$(nft list chain inet filter input 2>/dev/null || true)"
if [[ $fw_input == *"policy drop"* ]]; then
if [[ $fw_input == *"dport 53"* ]]; then
status_line 0 "firewall: DNS/DHCP open for LAN"
else
status_line 1 "firewall loaded but DNS/DHCP NOT open -- run: sudo ${WG_SCRIPT} allow-dns"
fi
elif [[ $EUID -ne 0 ]]; then
log_info "firewall: run 'sudo $0 status' to inspect nftables (needs root)"
else
status_line 0 "firewall: no default-drop ruleset loaded (DNS/DHCP not filtered)"
fi
if systemctl is-active dns-blocklist-refresh.timer &>/dev/null; then
status_line 0 "refresh timer: active (next $(systemctl show -p NextElapseUSecRealtime --value dns-blocklist-refresh.timer 2>/dev/null))"
else
status_line 1 "refresh timer: NOT active"
fi
if [[ -f $DHCP_CONF ]]; then
if ss -ulnp 2>/dev/null | grep -q ':67 '; then
status_line 0 "DHCP mode: ON (serving leases; PC is the LAN DHCP server)"
else
status_line 1 "DHCP mode: config present but not serving -- restart dnsmasq"
fi
else
status_line 0 "DHCP mode: off (using router DHCP / manual per-device DNS)"
fi
echo
echo "=== Live resolution test (via ${LAN_IP}) ==="
if has_cmd dig; then
local blocked passthru
blocked="$(dig +short +time=2 +tries=1 @"${LAN_IP}" youtube.com 2>/dev/null | head -1)"
passthru="$(dig +short +time=2 +tries=1 @"${LAN_IP}" example.com 2>/dev/null | head -1)"
if [[ $blocked == "0.0.0.0" ]]; then
status_line 0 "youtube.com -> ${blocked} (BLOCKED, correct)"
else
status_line 1 "youtube.com -> ${blocked:-<no answer>} (expected 0.0.0.0)"
fi
if [[ -n $passthru && $passthru != "0.0.0.0" ]]; then
status_line 0 "example.com -> ${passthru} (passthrough, correct)"
else
status_line 1 "example.com -> ${passthru:-<no answer>} (expected a real IP)"
fi
else
log_warn "install 'dig' (bind) to run the live resolution test."
fi
if [[ -s $LOG_FILE ]]; then
echo
echo "=== Recent dnsmasq log (${LOG_FILE}) ==="
tail -5 "$LOG_FILE"
fi
}

View File

@ -0,0 +1,86 @@
#!/bin/bash
# Validation, firewall rules and the allow-DNS flag.
#
# Sourced by setup_dns_blocker.sh; split out to keep it under the 250-line cap.
# Sourced rather than run, so it inherits the caller's strict mode.
validate_and_enable() {
log_info "Validating dnsmasq configuration..."
dnsmasq --test 2>&1 | tail -3
dnsmasq --test >/dev/null 2>&1 || die "dnsmasq config failed validation -- not enabling."
log_ok "dnsmasq config valid."
systemctl daemon-reload
enable_service dnsmasq
# enable --now does not restart an already-running daemon, so restart to
# apply config changes on idempotent re-runs.
systemctl restart dnsmasq
systemctl enable --now dns-blocklist-refresh.timer
systemctl enable --now dnsmasq-watchdog.timer
log_ok "dnsmasq, the daily refresh timer, and the watchdog are enabled."
}
# Open port 53 for LAN clients -- but only touch the firewall if it is already
# the active (wireguard-managed) default-drop ruleset. If nftables is inactive,
# port 53 is already reachable and force-loading the firewall here could
# disrupt other services, so we only persist the intent and instruct the user.
# A default-drop nftables ruleset can be loaded in the kernel even while
# nftables.service reads "inactive", so detect the actual ruleset, not the unit.
firewall_is_loaded() {
# Capture then match (no 'grep -q' pipe: it closes early -> SIGPIPE on nft ->
# pipefail makes the whole pipeline fail, a false negative under set -o pipefail).
local rules
rules="$(nft list chain inet filter input 2>/dev/null || true)"
[[ $rules == *"policy drop"* ]]
}
configure_firewall() {
if firewall_is_loaded; then
log_info "Default-drop firewall detected; opening DNS/DHCP for the LAN via the firewall owner."
bash "$WG_SCRIPT" allow-dns
else
log_warn "No default-drop firewall loaded -- DNS/DHCP already reachable on the LAN."
persist_allow_dns_flag
log_warn "If you later enable the default-drop firewall, run: sudo ${WG_SCRIPT} allow-dns"
fi
}
# Record ALLOW_DNS=true in the wireguard config so a future firewall apply keeps
# :53 open for the LAN, without activating the firewall now.
persist_allow_dns_flag() {
local cfg="${SCRIPT_DIR}/.wireguard_ssh.conf"
[[ -f $cfg ]] || return 0
if grep -qE '^ALLOW_DNS=' "$cfg"; then
sed -i 's/^ALLOW_DNS=.*/ALLOW_DNS="true"/' "$cfg"
else
printf 'ALLOW_DNS="true"\n' >>"$cfg"
fi
log_ok "Persisted ALLOW_DNS=true in ${cfg} for the next firewall apply."
}
print_manual_steps() {
cat <<EOF
============================================================================
Manual steps this script cannot do (they are on the router / phone)
============================================================================
The PC (${LAN_IP}) is not the gateway, so devices only use it as DNS if they
are pointed at it. Pick ONE delivery method:
A) If your router lets you set the DHCP "DNS server" it advertises:
set it to ${LAN_IP} and ONLY that (no secondary DNS -- a backup DNS
silently disables blocking). Also reserve ${LAN_IP} for this PC.
B) If your router CANNOT set the advertised DNS (many ISP routers can't):
run './setup_dns_blocker.sh dhcp' to make THIS PC the LAN DHCP server
(disable the router's DHCP first). Fully automatic for every device.
C) Or set DNS = ${LAN_IP} by hand on each device (phone: WiFi -> Static -> DNS).
PHONE (all methods) -- turn Private DNS OFF (Settings -> Network -> Private
DNS -> Off). Android's default "Automatic" uses DoH and bypasses LAN DNS.
This is a toggle, not an app, so it keeps the "no extra app" rule.
Known limitations (voluntary DNS): a device using DoH, a VPN, or a manually
set DNS bypasses this. It cannot be forced because the PC is not in the
traffic path. Works for the common case (devices that honor network DNS).
============================================================================
EOF
}

View File

@ -0,0 +1,109 @@
#!/bin/bash
# dnsmasq config, drop-in, refresh timer and watchdog units.
#
# Sourced by setup_dns_blocker.sh; split out to keep it under the 250-line cap.
# Sourced rather than run, so it inherits the caller's strict mode.
write_dnsmasq_conf() {
ensure_dir "$(dirname "$DNSMASQ_CONF")" # /etc/dnsmasq.d may not exist yet
log_info "Writing ${DNSMASQ_CONF} (listen on ${LAN_IFACE}/${LAN_IP}, upstream ${UPSTREAM})."
cat >"$DNSMASQ_CONF" <<EOF
# Managed by setup_dns_blocker.sh -- LAN DNS blocker.
# Serves the identical blocklist as /etc/hosts to LAN clients via addn-hosts.
# Do not edit by hand; re-run 'setup_dns_blocker.sh setup' instead.
# Listen only on the LAN interface (leaves 127.0.0.53 free for the
# systemd-resolved stub that the /etc/hosts installer enables).
interface=${LAN_IFACE}
bind-interfaces
# Do NOT read /etc/hosts (huge + immutable); the blocklist comes from the feed.
no-hosts
addn-hosts=${FEED}
# Forward everything not in the blocklist to the upstream resolver ONLY.
# no-resolv: ignore /etc/resolv.conf so we never chain through the
# systemd-resolved stub (127.0.0.53) that the /etc/hosts installer enables.
no-resolv
server=${UPSTREAM}
domain-needed
bogus-priv
cache-size=10000
# Log dnsmasq's own messages (startup, upstream failures) -- "log failures".
log-facility=${LOG_FILE}
# log-queries # opt-in: full per-query log (verbose + privacy). Off by default.
EOF
}
install_restart_dropin() {
ensure_dir "$DNSMASQ_DROPIN_DIR"
cat >"$DNSMASQ_DROPIN" <<'EOF'
# Managed by setup_dns_blocker.sh -- keep the resolver up and wait for the
# network so bind-interfaces can bind the LAN address at boot.
[Unit]
After=network-online.target
Wants=network-online.target
[Service]
Restart=always
RestartSec=5
EOF
}
install_refresh_timer() {
cat >"$REFRESH_SERVICE" <<EOF
[Unit]
Description=Rebuild the LAN DNS blocklist and reload dnsmasq
After=network-online.target
[Service]
Type=oneshot
ExecStart=${SELF} refresh
EOF
cat >"$REFRESH_TIMER" <<'EOF'
[Unit]
Description=Daily rebuild of the LAN DNS blocklist
[Timer]
OnCalendar=daily
Persistent=true
RandomizedDelaySec=15m
[Install]
WantedBy=timers.target
EOF
}
# The whole LAN's DHCP/DNS depends on this one process. Restart=always in the
# drop-in only catches an actual crash; an incident on 2026-07-23 found
# dnsmasq dead with ZERO error logged (no crash, no "Stopping"/"Stopped" line
# either -- consistent with something issuing a plain stop, not a failure) and
# it stayed down for hours, silently, until noticed by a phone unable to join
# WiFi. Mirrors the existing shutdown-timer-monitor-watchdog pattern used
# elsewhere in this repo: same 5-minute cadence, same is-active-or-start shape,
# plus a logger call so a future incident leaves a trace instead of none.
install_watchdog() {
cat >"$WATCHDOG_SERVICE" <<'EOF'
[Unit]
Description=Watchdog for dnsmasq (LAN DHCP/DNS)
After=multi-user.target
[Service]
Type=oneshot
ExecStart=/bin/bash -c 'systemctl is-active --quiet dnsmasq || { logger -t dnsmasq-watchdog "dnsmasq was down -- restarting"; systemctl restart dnsmasq; }'
EOF
cat >"$WATCHDOG_TIMER" <<'EOF'
[Unit]
Description=Watchdog Timer for dnsmasq
[Timer]
OnBootSec=60
OnUnitActiveSec=300
Persistent=true
[Install]
WantedBy=timers.target
EOF
}

View File

@ -114,190 +114,14 @@ build_feed() {
log_ok "Feed built: ${count} lines at ${FEED}."
}
write_dnsmasq_conf() {
ensure_dir "$(dirname "$DNSMASQ_CONF")" # /etc/dnsmasq.d may not exist yet
log_info "Writing ${DNSMASQ_CONF} (listen on ${LAN_IFACE}/${LAN_IP}, upstream ${UPSTREAM})."
cat >"$DNSMASQ_CONF" <<EOF
# Managed by setup_dns_blocker.sh -- LAN DNS blocker.
# Serves the identical blocklist as /etc/hosts to LAN clients via addn-hosts.
# Do not edit by hand; re-run 'setup_dns_blocker.sh setup' instead.
SCRIPT_DIR="$(dirname "$(readlink -f "${BASH_SOURCE[0]}")")"
# shellcheck source=lib/dns_units.sh
source "$SCRIPT_DIR/lib/dns_units.sh"
# shellcheck source=lib/dns_firewall.sh
source "$SCRIPT_DIR/lib/dns_firewall.sh"
# shellcheck source=lib/dns_dhcp.sh
source "$SCRIPT_DIR/lib/dns_dhcp.sh"
# Listen only on the LAN interface (leaves 127.0.0.53 free for the
# systemd-resolved stub that the /etc/hosts installer enables).
interface=${LAN_IFACE}
bind-interfaces
# Do NOT read /etc/hosts (huge + immutable); the blocklist comes from the feed.
no-hosts
addn-hosts=${FEED}
# Forward everything not in the blocklist to the upstream resolver ONLY.
# no-resolv: ignore /etc/resolv.conf so we never chain through the
# systemd-resolved stub (127.0.0.53) that the /etc/hosts installer enables.
no-resolv
server=${UPSTREAM}
domain-needed
bogus-priv
cache-size=10000
# Log dnsmasq's own messages (startup, upstream failures) -- "log failures".
log-facility=${LOG_FILE}
# log-queries # opt-in: full per-query log (verbose + privacy). Off by default.
EOF
}
install_restart_dropin() {
ensure_dir "$DNSMASQ_DROPIN_DIR"
cat >"$DNSMASQ_DROPIN" <<'EOF'
# Managed by setup_dns_blocker.sh -- keep the resolver up and wait for the
# network so bind-interfaces can bind the LAN address at boot.
[Unit]
After=network-online.target
Wants=network-online.target
[Service]
Restart=always
RestartSec=5
EOF
}
install_refresh_timer() {
cat >"$REFRESH_SERVICE" <<EOF
[Unit]
Description=Rebuild the LAN DNS blocklist and reload dnsmasq
After=network-online.target
[Service]
Type=oneshot
ExecStart=${SELF} refresh
EOF
cat >"$REFRESH_TIMER" <<'EOF'
[Unit]
Description=Daily rebuild of the LAN DNS blocklist
[Timer]
OnCalendar=daily
Persistent=true
RandomizedDelaySec=15m
[Install]
WantedBy=timers.target
EOF
}
# The whole LAN's DHCP/DNS depends on this one process. Restart=always in the
# drop-in only catches an actual crash; an incident on 2026-07-23 found
# dnsmasq dead with ZERO error logged (no crash, no "Stopping"/"Stopped" line
# either -- consistent with something issuing a plain stop, not a failure) and
# it stayed down for hours, silently, until noticed by a phone unable to join
# WiFi. Mirrors the existing shutdown-timer-monitor-watchdog pattern used
# elsewhere in this repo: same 5-minute cadence, same is-active-or-start shape,
# plus a logger call so a future incident leaves a trace instead of none.
install_watchdog() {
cat >"$WATCHDOG_SERVICE" <<'EOF'
[Unit]
Description=Watchdog for dnsmasq (LAN DHCP/DNS)
After=multi-user.target
[Service]
Type=oneshot
ExecStart=/bin/bash -c 'systemctl is-active --quiet dnsmasq || { logger -t dnsmasq-watchdog "dnsmasq was down -- restarting"; systemctl restart dnsmasq; }'
EOF
cat >"$WATCHDOG_TIMER" <<'EOF'
[Unit]
Description=Watchdog Timer for dnsmasq
[Timer]
OnBootSec=60
OnUnitActiveSec=300
Persistent=true
[Install]
WantedBy=timers.target
EOF
}
validate_and_enable() {
log_info "Validating dnsmasq configuration..."
dnsmasq --test 2>&1 | tail -3
dnsmasq --test >/dev/null 2>&1 || die "dnsmasq config failed validation -- not enabling."
log_ok "dnsmasq config valid."
systemctl daemon-reload
enable_service dnsmasq
# enable --now does not restart an already-running daemon, so restart to
# apply config changes on idempotent re-runs.
systemctl restart dnsmasq
systemctl enable --now dns-blocklist-refresh.timer
systemctl enable --now dnsmasq-watchdog.timer
log_ok "dnsmasq, the daily refresh timer, and the watchdog are enabled."
}
# Open port 53 for LAN clients -- but only touch the firewall if it is already
# the active (wireguard-managed) default-drop ruleset. If nftables is inactive,
# port 53 is already reachable and force-loading the firewall here could
# disrupt other services, so we only persist the intent and instruct the user.
# A default-drop nftables ruleset can be loaded in the kernel even while
# nftables.service reads "inactive", so detect the actual ruleset, not the unit.
firewall_is_loaded() {
# Capture then match (no 'grep -q' pipe: it closes early -> SIGPIPE on nft ->
# pipefail makes the whole pipeline fail, a false negative under set -o pipefail).
local rules
rules="$(nft list chain inet filter input 2>/dev/null || true)"
[[ $rules == *"policy drop"* ]]
}
configure_firewall() {
if firewall_is_loaded; then
log_info "Default-drop firewall detected; opening DNS/DHCP for the LAN via the firewall owner."
bash "$WG_SCRIPT" allow-dns
else
log_warn "No default-drop firewall loaded -- DNS/DHCP already reachable on the LAN."
persist_allow_dns_flag
log_warn "If you later enable the default-drop firewall, run: sudo ${WG_SCRIPT} allow-dns"
fi
}
# Record ALLOW_DNS=true in the wireguard config so a future firewall apply keeps
# :53 open for the LAN, without activating the firewall now.
persist_allow_dns_flag() {
local cfg="${SCRIPT_DIR}/.wireguard_ssh.conf"
[[ -f $cfg ]] || return 0
if grep -qE '^ALLOW_DNS=' "$cfg"; then
sed -i 's/^ALLOW_DNS=.*/ALLOW_DNS="true"/' "$cfg"
else
printf 'ALLOW_DNS="true"\n' >>"$cfg"
fi
log_ok "Persisted ALLOW_DNS=true in ${cfg} for the next firewall apply."
}
print_manual_steps() {
cat <<EOF
============================================================================
Manual steps this script cannot do (they are on the router / phone)
============================================================================
The PC (${LAN_IP}) is not the gateway, so devices only use it as DNS if they
are pointed at it. Pick ONE delivery method:
A) If your router lets you set the DHCP "DNS server" it advertises:
set it to ${LAN_IP} and ONLY that (no secondary DNS -- a backup DNS
silently disables blocking). Also reserve ${LAN_IP} for this PC.
B) If your router CANNOT set the advertised DNS (many ISP routers can't):
run './setup_dns_blocker.sh dhcp' to make THIS PC the LAN DHCP server
(disable the router's DHCP first). Fully automatic for every device.
C) Or set DNS = ${LAN_IP} by hand on each device (phone: WiFi -> Static -> DNS).
PHONE (all methods) -- turn Private DNS OFF (Settings -> Network -> Private
DNS -> Off). Android's default "Automatic" uses DoH and bypasses LAN DNS.
This is a toggle, not an app, so it keeps the "no extra app" rule.
Known limitations (voluntary DNS): a device using DoH, a VPN, or a manually
set DNS bypasses this. It cannot be forced because the PC is not in the
traffic path. Works for the common case (devices that honor network DNS).
============================================================================
EOF
}
cmd_setup() {
detect_lan
@ -342,188 +166,6 @@ revert_nic_to_dhcp() {
nmcli con up "$con" >/dev/null 2>&1 || true
}
configure_static_ip() {
has_cmd nmcli || die "nmcli (NetworkManager) not found; cannot pin a static IP automatically."
local con
con="$(nm_connection)"
[[ -n $con ]] || die "No active NetworkManager connection on ${LAN_IFACE}."
log_info "Pinning ${LAN_IFACE} to static ${LAN_IP}/24 (gw ${GATEWAY}) on '${con}'..."
nmcli con mod "$con" \
ipv4.method manual \
ipv4.addresses "${LAN_IP}/24" \
ipv4.gateway "$GATEWAY" \
ipv4.dns "$GATEWAY"
nmcli con up "$con" >/dev/null
# Safety self-check: if the static config broke connectivity, auto-revert to
# DHCP-client mode immediately so the machine never ends up stranded.
if ping -c1 -W3 "$GATEWAY" >/dev/null 2>&1; then
log_ok "Static IP applied; gateway reachable. ${LAN_IFACE} no longer needs external DHCP."
else
log_error "Gateway unreachable after static IP change -- auto-reverting to DHCP."
revert_nic_to_dhcp "$con"
die "Static IP self-check failed; reverted to DHCP. DHCP mode aborted (no changes kept)."
fi
}
write_dhcp_conf() {
local mac net_prefix
mac="$(cat "/sys/class/net/${LAN_IFACE}/address")"
net_prefix="${LAN_IP%.*}"
log_info "Writing ${DHCP_CONF} (range ${net_prefix}.${DHCP_START_HOST}-${net_prefix}.${DHCP_END_HOST}, DNS ${LAN_IP})."
cat >"$DHCP_CONF" <<EOF
# Managed by setup_dns_blocker.sh -- this PC is the LAN DHCP server.
# Only serve leases once the router's own DHCP is disabled (two servers clash).
dhcp-authoritative
dhcp-range=${net_prefix}.${DHCP_START_HOST},${net_prefix}.${DHCP_END_HOST},${DHCP_LEASE}
dhcp-option=option:router,${GATEWAY}
dhcp-option=option:dns-server,${LAN_IP}
# Reserve this PC's static address against its own MAC.
dhcp-host=${mac},${LAN_IP}
# Log every DHCP transaction (low volume; satisfies "log failures").
log-dhcp
EOF
}
cmd_dhcp() {
detect_lan
is_service_active dnsmasq ||
die "Run 'setup' first -- dnsmasq must be configured before enabling DHCP mode."
echo
log_warn "DHCP takeover: this PC (${LAN_IP}) will become the LAN's DHCP server."
log_warn "Disable the router's DHCP FIRST (untick 'wlacz serwer DHCP' -> Zapisz),"
log_warn "otherwise two DHCP servers will fight on the LAN."
if ! ask_yes_no "Have you already disabled the router's DHCP server?"; then
log_warn "Not activating -- two DHCP servers on one LAN conflict."
log_warn "Disable the router's DHCP ('wlacz serwer DHCP' -> Zapisz), then re-run: sudo ${SELF} dhcp"
return 0
fi
configure_static_ip
write_dhcp_conf
dnsmasq --test >/dev/null 2>&1 || die "dnsmasq config invalid after adding DHCP -- not restarting."
systemctl restart dnsmasq
log_ok "This PC is now the LAN DHCP server; new leases advertise ${LAN_IP} as DNS."
log_info "Reconnect a device's WiFi to pick up the new lease, then browse to a blocked site to confirm."
cat <<EOF
---- IF ANYTHING GOES WRONG (one command, cannot lock you out) ------------
sudo ${SELF} dhcp-off
-> stops serving DHCP, KEEPS this PC online on ${LAN_IP}.
Then re-tick the router's DHCP ('wlacz serwer DHCP' -> Zapisz) so other
devices get addresses again. This PC stays reachable throughout.
--------------------------------------------------------------------------
EOF
}
# Roll back DHCP mode: stop serving leases. KEEPS this PC on its static IP so
# running rollback can never strand the machine (the router reserves ${LAN_IP}
# anyway). Re-enable the router's DHCP afterwards for the other devices.
cmd_dhcp_off() {
detect_lan
if [[ -f $DHCP_CONF ]]; then
rm -f "$DHCP_CONF"
log_ok "Removed ${DHCP_CONF} (PC no longer serves DHCP)."
else
log_info "No DHCP config present; nothing to remove."
fi
is_service_active dnsmasq && systemctl restart dnsmasq
log_ok "DHCP serving stopped. This PC keeps its static IP (${LAN_IP}); still online."
log_warn "Now re-enable the router's DHCP ('wlacz serwer DHCP' -> Zapisz) so other devices get addresses."
log_info "Optional: to also put THIS PC back on router DHCP (after re-enabling it above), run:"
log_info " nmcli con mod '$(nm_connection)' ipv4.method auto ipv4.addresses '' ipv4.gateway '' ipv4.dns '' && nmcli con up '$(nm_connection)'"
}
# ---- Status ----------------------------------------------------------------
status_line() {
# $1 ok/bad flag ("0" ok), $2 message
if [[ $1 == "0" ]]; then log_ok "$2"; else log_warn "$2"; fi
}
cmd_status() {
detect_lan
echo "=== LAN DNS blocker status ==="
if is_service_active dnsmasq; then
status_line 0 "dnsmasq: active"
else
status_line 1 "dnsmasq: NOT active"
fi
if is_service_enabled dnsmasq; then
status_line 0 "dnsmasq: enabled at boot"
else
status_line 1 "dnsmasq: NOT enabled"
fi
if [[ -f $DNSMASQ_DROPIN ]]; then
status_line 0 "Restart=always drop-in present"
else
status_line 1 "Restart drop-in missing"
fi
if [[ -f $FEED ]]; then
status_line 0 "blocklist feed: $(wc -l <"$FEED") lines, updated $(date -r "$FEED" '+%Y-%m-%d %H:%M')"
else
status_line 1 "blocklist feed missing: ${FEED}"
fi
if ss -tulnp 2>/dev/null | grep -qE "${LAN_IP}:53|:53 "; then
status_line 0 "listening on ${LAN_IP}:53"
else
status_line 1 "not listening on ${LAN_IP}:53"
fi
local fw_input
fw_input="$(nft list chain inet filter input 2>/dev/null || true)"
if [[ $fw_input == *"policy drop"* ]]; then
if [[ $fw_input == *"dport 53"* ]]; then
status_line 0 "firewall: DNS/DHCP open for LAN"
else
status_line 1 "firewall loaded but DNS/DHCP NOT open -- run: sudo ${WG_SCRIPT} allow-dns"
fi
elif [[ $EUID -ne 0 ]]; then
log_info "firewall: run 'sudo $0 status' to inspect nftables (needs root)"
else
status_line 0 "firewall: no default-drop ruleset loaded (DNS/DHCP not filtered)"
fi
if systemctl is-active dns-blocklist-refresh.timer &>/dev/null; then
status_line 0 "refresh timer: active (next $(systemctl show -p NextElapseUSecRealtime --value dns-blocklist-refresh.timer 2>/dev/null))"
else
status_line 1 "refresh timer: NOT active"
fi
if [[ -f $DHCP_CONF ]]; then
if ss -ulnp 2>/dev/null | grep -q ':67 '; then
status_line 0 "DHCP mode: ON (serving leases; PC is the LAN DHCP server)"
else
status_line 1 "DHCP mode: config present but not serving -- restart dnsmasq"
fi
else
status_line 0 "DHCP mode: off (using router DHCP / manual per-device DNS)"
fi
echo
echo "=== Live resolution test (via ${LAN_IP}) ==="
if has_cmd dig; then
local blocked passthru
blocked="$(dig +short +time=2 +tries=1 @"${LAN_IP}" youtube.com 2>/dev/null | head -1)"
passthru="$(dig +short +time=2 +tries=1 @"${LAN_IP}" example.com 2>/dev/null | head -1)"
if [[ $blocked == "0.0.0.0" ]]; then
status_line 0 "youtube.com -> ${blocked} (BLOCKED, correct)"
else
status_line 1 "youtube.com -> ${blocked:-<no answer>} (expected 0.0.0.0)"
fi
if [[ -n $passthru && $passthru != "0.0.0.0" ]]; then
status_line 0 "example.com -> ${passthru} (passthrough, correct)"
else
status_line 1 "example.com -> ${passthru:-<no answer>} (expected a real IP)"
fi
else
log_warn "install 'dig' (bind) to run the live resolution test."
fi
if [[ -s $LOG_FILE ]]; then
echo
echo "=== Recent dnsmasq log (${LOG_FILE}) ==="
tail -5 "$LOG_FILE"
fi
}
usage() {
cat <<EOF

View File

@ -0,0 +1,247 @@
# ============================================
# Custom blocking entries - Android Guardian
# ============================================
# YouTube
0.0.0.0 youtube.com
0.0.0.0 www.youtube.com
0.0.0.0 m.youtube.com
0.0.0.0 youtu.be
0.0.0.0 youtube-nocookie.com
0.0.0.0 www.youtube-nocookie.com
0.0.0.0 youtubei.googleapis.com
0.0.0.0 youtube.googleapis.com
0.0.0.0 yt3.ggpht.com
0.0.0.0 ytimg.com
0.0.0.0 i.ytimg.com
0.0.0.0 s.ytimg.com
0.0.0.0 i9.ytimg.com
0.0.0.0 googlevideo.com
# Alternative YouTube Frontends (Invidious, Piped, etc.)
0.0.0.0 invidious.io
0.0.0.0 www.invidious.io
0.0.0.0 invidio.us
0.0.0.0 vid.puffyan.us
0.0.0.0 invidious.snopyta.org
0.0.0.0 yewtu.be
0.0.0.0 invidious.kavin.rocks
0.0.0.0 inv.riverside.rocks
0.0.0.0 invidious.namazso.eu
0.0.0.0 invidious.nerdvpn.de
0.0.0.0 invidious.projectsegfau.lt
0.0.0.0 invidious.slipfox.xyz
0.0.0.0 invidious.privacydev.net
0.0.0.0 invidious.perennialte.ch
0.0.0.0 invidious.protokoll-11.de
0.0.0.0 invidious.einfachzocken.eu
0.0.0.0 invidious.fdn.fr
0.0.0.0 inv.in.projectsegfau.lt
0.0.0.0 invidious.tiekoetter.com
0.0.0.0 invidious.lunar.icu
0.0.0.0 iv.ggtyler.dev
0.0.0.0 iv.melmac.space
0.0.0.0 piped.video
0.0.0.0 www.piped.video
0.0.0.0 piped.kavin.rocks
0.0.0.0 piped.mha.fi
0.0.0.0 piped.mint.lgbt
0.0.0.0 piped.projectsegfau.lt
0.0.0.0 piped.privacydev.net
0.0.0.0 piped.smnz.de
0.0.0.0 piped.adminforge.de
0.0.0.0 watch.whatever.social
0.0.0.0 piped.lunar.icu
0.0.0.0 viewtube.io
0.0.0.0 www.viewtube.io
0.0.0.0 freetube.io
0.0.0.0 www.freetube.io
0.0.0.0 tubo.media
0.0.0.0 www.tubo.media
0.0.0.0 materialious.nadeko.net
0.0.0.0 clipious.org
0.0.0.0 www.clipious.org
0.0.0.0 newpipe.net
0.0.0.0 www.newpipe.net
0.0.0.0 newpipe.schabi.org
0.0.0.0 grayjay.app
0.0.0.0 www.grayjay.app
0.0.0.0 libretube.dev
0.0.0.0 www.libretube.dev
0.0.0.0 hyperion.deishelon.com
0.0.0.0 inv.n8pjl.ca
0.0.0.0 inv.zzls.xyz
0.0.0.0 inv.tux.pizza
0.0.0.0 invidious.incogniweb.net
0.0.0.0 invidious.drgns.space
0.0.0.0 invidious.io.lol
# Discord (media only - voice chat allowed)
0.0.0.0 cdn.discordapp.com
0.0.0.0 media.discordapp.net
0.0.0.0 images-ext-1.discordapp.net
0.0.0.0 images-ext-2.discordapp.net
0.0.0.0 tenor.com
0.0.0.0 giphy.com
# Food Delivery Services
# Polish services
0.0.0.0 pyszne.pl
0.0.0.0 www.pyszne.pl
0.0.0.0 m.pyszne.pl
0.0.0.0 api.pyszne.pl
0.0.0.0 app.pyszne.pl
0.0.0.0 glovo.com
0.0.0.0 www.glovo.com
0.0.0.0 m.glovo.com
0.0.0.0 api.glovo.com
0.0.0.0 glovoapp.com
0.0.0.0 www.glovoapp.com
0.0.0.0 bolt.eu
:: bolt.eu
0.0.0.0 www.bolt.eu
:: www.bolt.eu
0.0.0.0 food.bolt.eu
:: food.bolt.eu
0.0.0.0 m.bolt.eu
:: m.bolt.eu
0.0.0.0 api.bolt.eu
:: api.bolt.eu
0.0.0.0 node.bolt.eu
:: node.bolt.eu
0.0.0.0 gw.bolt.eu
:: gw.bolt.eu
0.0.0.0 client-api.bolt.eu
:: client-api.bolt.eu
0.0.0.0 auth.bolt.eu
:: auth.bolt.eu
0.0.0.0 cdn.bolt.eu
:: cdn.bolt.eu
0.0.0.0 images.bolt.eu
:: images.bolt.eu
0.0.0.0 static.bolt.eu
:: static.bolt.eu
0.0.0.0 assets.bolt.eu
:: assets.bolt.eu
0.0.0.0 fleet.bolt.eu
:: fleet.bolt.eu
0.0.0.0 user.bolt.eu
:: user.bolt.eu
0.0.0.0 courier.bolt.eu
:: courier.bolt.eu
0.0.0.0 rider.bolt.eu
:: rider.bolt.eu
0.0.0.0 restaurant.bolt.eu
:: restaurant.bolt.eu
0.0.0.0 partner-food.bolt.eu
:: partner-food.bolt.eu
0.0.0.0 wolt.com
0.0.0.0 www.wolt.com
0.0.0.0 m.wolt.com
0.0.0.0 api.wolt.com
0.0.0.0 restaurant-api.wolt.com
0.0.0.0 consumer-api.wolt.com
0.0.0.0 woltwojta.pl
0.0.0.0 www.woltwojta.pl
0.0.0.0 jush.pl
0.0.0.0 www.jush.pl
0.0.0.0 m.jush.pl
0.0.0.0 api.jush.pl
0.0.0.0 delio.pl
0.0.0.0 www.delio.pl
0.0.0.0 m.delio.pl
0.0.0.0 api.delio.pl
0.0.0.0 delio.com
0.0.0.0 www.delio.com
0.0.0.0 delio.com.pl
0.0.0.0 www.delio.com.pl
0.0.0.0 api.delio.com.pl
0.0.0.0 lisek.app
0.0.0.0 www.lisek.app
0.0.0.0 api.lisek.app
0.0.0.0 stava.app
0.0.0.0 www.stava.app
0.0.0.0 api.stava.app
0.0.0.0 barbora.pl
0.0.0.0 www.barbora.pl
0.0.0.0 api.barbora.pl
0.0.0.0 frisco.pl
0.0.0.0 www.frisco.pl
0.0.0.0 api.frisco.pl
0.0.0.0 szama.pl
0.0.0.0 www.szama.pl
0.0.0.0 api.szama.pl
0.0.0.0 auchandirect.pl
0.0.0.0 www.auchandirect.pl
0.0.0.0 zakupy.biedronka.pl
0.0.0.0 ezakupy.tesco.pl
0.0.0.0 www.ezakupy.tesco.pl
# International services
0.0.0.0 ubereats.com
0.0.0.0 www.ubereats.com
0.0.0.0 m.ubereats.com
0.0.0.0 api.ubereats.com
0.0.0.0 uber.com
0.0.0.0 www.uber.com
0.0.0.0 m.uber.com
0.0.0.0 api.uber.com
0.0.0.0 login.uber.com
0.0.0.0 auth.uber.com
0.0.0.0 deliveroo.com
0.0.0.0 www.deliveroo.com
0.0.0.0 m.deliveroo.com
0.0.0.0 api.deliveroo.com
0.0.0.0 deliveroo.co.uk
0.0.0.0 www.deliveroo.co.uk
0.0.0.0 foodpanda.com
0.0.0.0 www.foodpanda.com
0.0.0.0 m.foodpanda.com
0.0.0.0 api.foodpanda.com
0.0.0.0 grubhub.com
0.0.0.0 www.grubhub.com
0.0.0.0 m.grubhub.com
0.0.0.0 api.grubhub.com
0.0.0.0 doordash.com
0.0.0.0 www.doordash.com
0.0.0.0 m.doordash.com
0.0.0.0 api.doordash.com
0.0.0.0 justeat.com
0.0.0.0 www.justeat.com
0.0.0.0 m.justeat.com
0.0.0.0 justeat.co.uk
0.0.0.0 www.justeat.co.uk
0.0.0.0 postmates.com
0.0.0.0 www.postmates.com
0.0.0.0 seamless.com
0.0.0.0 www.seamless.com
0.0.0.0 getir.com
0.0.0.0 www.getir.com
0.0.0.0 api.getir.com
0.0.0.0 flink.com
0.0.0.0 www.flink.com
0.0.0.0 gorillas.io
0.0.0.0 www.gorillas.io
0.0.0.0 gopuff.com
0.0.0.0 www.gopuff.com
0.0.0.0 instacart.com
0.0.0.0 www.instacart.com
0.0.0.0 takeaway.com
0.0.0.0 www.takeaway.com
0.0.0.0 api.takeaway.com
# Fast Food
0.0.0.0 mcdonalds.com
0.0.0.0 www.mcdonalds.com
0.0.0.0 mcdonalds.pl
0.0.0.0 www.mcdonalds.pl
0.0.0.0 kfc.com
0.0.0.0 www.kfc.com
0.0.0.0 kfc.pl
0.0.0.0 www.kfc.pl
0.0.0.0 burgerking.com
0.0.0.0 www.burgerking.com
0.0.0.0 pizzahut.com
0.0.0.0 www.pizzahut.com
0.0.0.0 dominos.com
0.0.0.0 www.dominos.com

View File

@ -0,0 +1,243 @@
#!/bin/bash
# The install, status, disable and app-blocking subcommands.
#
# Sourced by update_android_hosts.sh; split out to keep it under the 250-line cap.
# Sourced rather than run, so it inherits the caller's strict mode.
# Install/update the guardian module
cmd_install() {
ensure_device_ready
local module_zip
module_zip=$(build_module)
log "Pushing module to device..."
adb push "$module_zip" /sdcard/android_guardian.zip || die "Failed to push module"
log "Installing module..."
adb shell "su -c 'mkdir -p $MODULE_DEST'" || die "Failed to create module directory"
adb shell "su -c 'cd $MODULE_DEST && unzip -o /sdcard/android_guardian.zip'" || die "Failed to extract module"
adb shell "su -c 'chmod 755 $MODULE_DEST/*.sh'"
adb shell "su -c 'rm /sdcard/android_guardian.zip'"
# Set up guardian data directory
log "Setting up guardian data..."
adb shell "su -c 'mkdir -p $GUARDIAN_DATA_DIR'"
adb shell "su -c 'echo ENABLED > $GUARDIAN_DATA_DIR/control'"
# Copy blocked apps list
adb push "$GUARDIAN_MODULE_DIR/blocked_apps.txt" /sdcard/blocked_apps.txt || die "Failed to push blocked apps list"
adb shell "su -c 'cp /sdcard/blocked_apps.txt $GUARDIAN_DATA_DIR/blocked_apps.txt'"
adb shell "su -c 'rm /sdcard/blocked_apps.txt'"
# Create hosts backup for tamper protection
adb shell "su -c 'cp $MODULE_DEST/system/etc/hosts $GUARDIAN_DATA_DIR/hosts.backup'"
# Immediately uninstall any currently installed blocked apps
log "Checking for blocked apps to remove..."
uninstall_blocked_apps
echo ""
echo "=========================================="
echo " ✓ Android Guardian installed!"
echo "=========================================="
echo ""
echo "Features enabled:"
echo " • Hosts-based ad/tracker blocking"
echo " • App installation blocking"
echo " • Tamper protection"
echo ""
echo "⚠️ This can ONLY be controlled via ADB:"
echo " Disable: $0 disable"
echo " Enable: $0 enable"
echo " Status: $0 status"
echo ""
echo "Reboot your device to activate the module."
echo ""
}
# Uninstall currently installed blocked apps
uninstall_blocked_apps() {
local blocked_apps
blocked_apps=$(grep -v '^#' "$GUARDIAN_MODULE_DIR/blocked_apps.txt" | grep -v '^$' || true)
for package in $blocked_apps; do
if adb shell "pm list packages" 2>/dev/null | grep -q "package:$package"; then
log "Uninstalling blocked app: $package"
adb shell "pm uninstall $package" 2>/dev/null || true
fi
done
}
# Show status
cmd_status() {
ensure_device_ready
echo ""
echo "=== Android Guardian Status ==="
echo ""
# Check if module is installed
if adb shell "su -c 'test -d $MODULE_DEST'" 2>/dev/null; then
echo "Module: INSTALLED"
else
echo "Module: NOT INSTALLED"
return
fi
# Check control status
local status
status=$(adb shell "su -c 'cat $GUARDIAN_DATA_DIR/control 2>/dev/null || echo UNKNOWN'" | tr -d '\r')
echo "Status: $status"
# Check if module is "disabled" in Magisk UI (should be auto-fixed by watchdog)
local magisk_disabled
if adb shell "su -c 'test -f $MODULE_DEST/disable'" 2>/dev/null; then
magisk_disabled="YES (watchdog should fix this)"
else
magisk_disabled="No"
fi
echo "Magisk UI disabled: $magisk_disabled"
# Check if watchdog is running
local watchdog_running
watchdog_running=$(adb shell "su -c 'pgrep -f watchdog.sh 2>/dev/null | wc -l'" | tr -d '\r')
if [ "$watchdog_running" -gt 0 ] 2>/dev/null; then
echo "Watchdog: RUNNING ($watchdog_running processes)"
else
echo "Watchdog: NOT RUNNING (reboot phone to start)"
fi
# Check hosts file
local hosts_entries
hosts_entries=$(adb shell "su -c 'grep -c \"^0.0.0.0\" /system/etc/hosts 2>/dev/null || echo 0'" | tr -d '\r')
echo "Blocked domains: $hosts_entries"
# Check blocked apps count
local blocked_count
blocked_count=$(adb shell "su -c 'grep -v \"^#\" $GUARDIAN_DATA_DIR/blocked_apps.txt 2>/dev/null | grep -v \"^$\" | wc -l || echo 0'" | tr -d '\r')
echo "Blocked app rules: $blocked_count packages"
echo ""
echo "Protection: Module cannot be disabled from Magisk UI"
echo " Only controllable via: $0 disable/enable"
echo ""
}
# Disable guardian
cmd_disable() {
ensure_device_ready
log "Disabling Android Guardian..."
adb shell "su -c 'echo DISABLED > $GUARDIAN_DATA_DIR/control'" || die "Failed to disable guardian"
echo ""
echo "✓ Guardian DISABLED"
echo " Hosts blocking still active until reboot"
echo " App blocking service paused"
echo ""
echo "To re-enable: $0 enable"
echo ""
}
# Enable guardian
cmd_enable() {
ensure_device_ready
log "Enabling Android Guardian..."
adb shell "su -c 'echo ENABLED > $GUARDIAN_DATA_DIR/control'" || die "Failed to enable guardian"
echo ""
echo "✓ Guardian ENABLED"
echo ""
}
# Uninstall module
cmd_uninstall() {
ensure_device_ready
# Check if disabled first
local status
status=$(adb shell "su -c 'cat $GUARDIAN_DATA_DIR/control 2>/dev/null || echo ENABLED'" | tr -d '\r')
if [[ $status != "DISABLED" ]]; then
echo ""
echo "⚠️ Guardian must be disabled before uninstalling!"
echo " Run: $0 disable"
echo " Then: $0 uninstall"
echo ""
exit 1
fi
log "Removing Android Guardian..."
adb shell "su -c 'rm -rf $MODULE_DEST'"
adb shell "su -c 'rm -rf $GUARDIAN_DATA_DIR'"
echo ""
echo "✓ Guardian uninstalled"
echo " Reboot to remove hosts blocking"
echo ""
}
# Show logs
cmd_logs() {
ensure_device_ready
echo "=== Guardian Logs ==="
adb shell "su -c 'cat $GUARDIAN_DATA_DIR/guardian.log 2>/dev/null || echo \"No logs yet\"'"
}
# Block an app
cmd_block_app() {
local package="${1:-}"
if [[ -z $package ]]; then
echo "Usage: $0 block-app <package.name>"
echo "Example: $0 block-app com.ubercab.eats"
exit 1
fi
ensure_device_ready
log "Adding $package to block list..."
adb shell "su -c 'echo \"$package\" >> $GUARDIAN_DATA_DIR/blocked_apps.txt'"
# Also add to local file
echo "$package" >>"$GUARDIAN_MODULE_DIR/blocked_apps.txt"
# Try to uninstall if currently installed
if adb shell "pm list packages" 2>/dev/null | grep -q "package:$package"; then
log "Uninstalling $package..."
adb shell "pm uninstall $package" 2>/dev/null || true
fi
echo "✓ $package added to block list"
}
# Unblock an app
cmd_unblock_app() {
local package="${1:-}"
if [[ -z $package ]]; then
echo "Usage: $0 unblock-app <package.name>"
exit 1
fi
ensure_device_ready
log "Removing $package from block list..."
adb shell "su -c 'grep -v \"^$package\$\" $GUARDIAN_DATA_DIR/blocked_apps.txt > $GUARDIAN_DATA_DIR/blocked_apps.tmp && mv $GUARDIAN_DATA_DIR/blocked_apps.tmp $GUARDIAN_DATA_DIR/blocked_apps.txt'"
# Also remove from local file
grep -v "^$package$" "$GUARDIAN_MODULE_DIR/blocked_apps.txt" >"$GUARDIAN_MODULE_DIR/blocked_apps.tmp" && mv "$GUARDIAN_MODULE_DIR/blocked_apps.tmp" "$GUARDIAN_MODULE_DIR/blocked_apps.txt"
echo "✓ $package removed from block list"
}
# List blocked apps
cmd_list_blocked() {
ensure_device_ready
echo "=== Blocked Apps ==="
adb shell "su -c 'cat $GUARDIAN_DATA_DIR/blocked_apps.txt 2>/dev/null'" | grep -v "^#" | grep -v "^$" || echo "No blocked apps"
}

View File

@ -0,0 +1,210 @@
#!/bin/bash
# Device discovery, pairing and connection.
#
# Sourced by update_android_hosts.sh; split out to keep it under the 250-line cap.
# Sourced rather than run, so it inherits the caller's strict mode.
# Discover Android devices on the network using mDNS
discover_android_device() {
local found_address=""
# Ensure avahi-browse is available
if ! command -v avahi-browse &>/dev/null; then
if command -v pacman &>/dev/null; then
echo "Installing avahi for device discovery..." >&2
sudo pacman -S --noconfirm avahi nss-mdns &>/dev/null || true
sudo systemctl enable --now avahi-daemon &>/dev/null || true
elif command -v apt-get &>/dev/null; then
sudo apt-get install -y avahi-utils &>/dev/null || true
fi
fi
if command -v avahi-browse &>/dev/null; then
echo "Scanning for Android devices (5 seconds)..." >&2
# Android wireless debugging advertises as _adb-tls-connect._tcp
local discovery_result
discovery_result=$(timeout 5 avahi-browse -rpt _adb-tls-connect._tcp 2>/dev/null | grep "^=" | head -1)
if [[ -n $discovery_result ]]; then
# Parse: =;eth0;IPv4;adb-...;_adb-tls-connect._tcp;local;hostname.local;192.168.x.x;port;...
local ip port
ip=$(echo "$discovery_result" | cut -d';' -f8)
port=$(echo "$discovery_result" | cut -d';' -f9)
if [[ -n $ip && -n $port ]]; then
found_address="$ip:$port"
echo "✓ Found device: $found_address" >&2
fi
fi
fi
# Fallback: try adb's mdns discovery
if [[ -z $found_address ]]; then
echo "Trying adb mdns discovery..." >&2
# adb can discover devices via mdns
local mdns_result
mdns_result=$(timeout 5 adb mdns services 2>/dev/null | grep -E "adb-tls-connect|_adb\._tcp" | head -1)
if [[ -n $mdns_result ]]; then
# Try to extract IP:port from the result
local service_name
service_name=$(echo "$mdns_result" | awk '{print $1}')
if [[ -n $service_name ]]; then
# Try connecting via service name
echo "Found service: $service_name" >&2
fi
fi
fi
# Return found address (or empty)
echo "$found_address"
}
# Pair with device over WiFi (Android 11+)
cmd_pair() {
ensure_adb_installed
echo ""
echo "=== Wireless ADB Pairing (Android 11+) ==="
echo ""
echo "On your phone:"
echo " 1. Go to Settings > Developer Options > Wireless debugging"
echo " 2. Enable Wireless debugging"
echo " 3. Tap 'Pair device with pairing code'"
echo " 4. Note the IP:port and pairing code shown"
echo ""
read -rp "Enter pairing IP:port (e.g., 192.168.1.100:37123): " pair_address
read -rp "Enter pairing code: " pair_code
if [[ -z $pair_address || -z $pair_code ]]; then
die "Pairing address and code are required"
fi
log "Pairing with device at $pair_address..."
if adb pair "$pair_address" "$pair_code"; then
echo ""
echo "✓ Pairing successful!"
echo ""
echo "Now get the connection address:"
echo " On phone: Wireless debugging screen shows IP:port under 'IP address & Port'"
echo " (This is DIFFERENT from the pairing port)"
echo ""
read -rp "Enter connection IP:port (e.g., 192.168.1.100:41567): " connect_address
if [[ -n $connect_address ]]; then
# Save for future connections
mkdir -p "$(dirname "$WIRELESS_CONFIG")"
echo "$connect_address" >"$WIRELESS_CONFIG"
log "Saved connection address for future use"
# Connect now
cmd_connect
fi
else
die "Pairing failed. Make sure the code is correct and you're on the same network."
fi
}
# Connect to already-paired device
cmd_connect() {
ensure_adb_installed
local connect_address=""
# Check for saved address
if [[ -f $WIRELESS_CONFIG ]]; then
connect_address=$(cat "$WIRELESS_CONFIG")
log "Using saved address: $connect_address"
fi
# Try auto-discovery if no saved address
if [[ -z $connect_address ]]; then
echo ""
log "Searching for Android devices on network..."
connect_address=$(discover_android_device)
fi
# Manual fallback
if [[ -z $connect_address ]]; then
echo ""
echo "Auto-discovery failed. Enter address manually."
echo "On phone: Settings > Developer Options > Wireless debugging"
echo "Look for IP address & Port (NOT the pairing port)"
echo ""
read -rp "Enter connection IP:port (e.g., 192.168.1.100:41567): " connect_address
if [[ -z $connect_address ]]; then
die "Connection address is required"
fi
fi
# Save for future
mkdir -p "$(dirname "$WIRELESS_CONFIG")"
echo "$connect_address" >"$WIRELESS_CONFIG"
log "Connecting to $connect_address..."
if adb connect "$connect_address" | grep -q "connected"; then
echo ""
echo "✓ Connected to device wirelessly!"
echo ""
# Verify connection
if adb devices | grep -q "$connect_address"; then
echo "Device ready. You can now run other commands."
fi
else
echo ""
echo "Connection failed. Possible issues:"
echo " - Wireless debugging not enabled on phone"
echo " - Phone and PC not on same WiFi network"
echo " - Port changed (check Wireless debugging screen)"
echo " - May need to pair first: $0 pair"
echo ""
# Clear saved config since it failed
rm -f "$WIRELESS_CONFIG"
exit 1
fi
}
# Disconnect wireless ADB
cmd_disconnect() {
ensure_adb_installed
log "Disconnecting all wireless devices..."
adb disconnect
echo "✓ Disconnected"
}
# Check device connection and root
ensure_device_ready() {
ensure_adb_installed
# Check if any device is connected
if ! adb devices | grep -qE "device$|:.*device$"; then
echo ""
echo "No device connected!"
echo ""
echo "Options:"
echo " 1. Connect USB cable with debugging enabled"
echo " 2. Use wireless: $0 pair (first time) or $0 connect"
echo ""
# Check if we have a saved wireless config
if [[ -f $WIRELESS_CONFIG ]]; then
read -rp "Try connecting to saved wireless device? [Y/n]: " try_wireless
if [[ ${try_wireless,,} != "n" ]]; then
cmd_connect
else
exit 1
fi
else
exit 1
fi
fi
check_adb_device
check_adb_root
}

View File

@ -0,0 +1,49 @@
#!/bin/bash
# Building the Magisk hosts module.
#
# Sourced by update_android_hosts.sh; split out to keep it under the 250-line cap.
# Sourced rather than run, so it inherits the caller's strict mode.
# Build the module zip
build_module() {
local tmp_dir="$WORK_DIR/guardian_module"
local module_zip="$WORK_DIR/android_guardian.zip"
echo "[BUILD] Building Android Guardian module..." >&2
rm -rf "$tmp_dir"
mkdir -p "$tmp_dir/system/etc"
# Copy module files
cp "$GUARDIAN_MODULE_DIR/module.prop" "$tmp_dir/"
cp "$GUARDIAN_MODULE_DIR/service.sh" "$tmp_dir/"
cp "$GUARDIAN_MODULE_DIR/post-fs-data.sh" "$tmp_dir/"
cp "$GUARDIAN_MODULE_DIR/uninstall.sh" "$tmp_dir/"
# Build hosts file
local hosts_file="$tmp_dir/system/etc/hosts"
if [[ -f /etc/hosts.stevenblack ]]; then
echo "[BUILD] Using StevenBlack hosts cache..." >&2
cp /etc/hosts.stevenblack "$hosts_file"
elif [[ -f /etc/hosts ]]; then
echo "[BUILD] Using /etc/hosts..." >&2
cp /etc/hosts "$hosts_file"
else
die "No hosts file found"
fi
# Append custom blocking entries
# The blocklist is a data file, not a heredoc: 248 lines of hosts
# entries that belong under data/ where they can be diffed and edited
# without touching shell.
cat "$SCRIPT_DIR/data/android_guardian_blocklist.hosts" >>"$hosts_file"
local total_entries
total_entries=$(grep -c "^0\.0\.0\.0 " "$hosts_file" || echo 0)
echo "[BUILD] Hosts file contains $total_entries blocked domains" >&2
# Create zip
(cd "$tmp_dir" && zip -r "$module_zip" . -x "*.DS_Store") >/dev/null
echo "$module_zip"
}

View File

@ -4,7 +4,7 @@
set -euo pipefail
# Source common library
SCRIPT_DIR="$(dirname "$(readlink -f "$0")")"
SCRIPT_DIR="$(dirname "$(readlink -f "${BASH_SOURCE[0]}")")"
# shellcheck source=../../lib/common.sh
source "$SCRIPT_DIR/../../lib/common.sh"
# shellcheck source=../../lib/android.sh
@ -83,737 +83,13 @@ EOF
# Wireless ADB connection file
WIRELESS_CONFIG="$HOME/.config/android_guardian_wireless"
# Discover Android devices on the network using mDNS
discover_android_device() {
local found_address=""
# shellcheck source=lib/android_device.sh
source "$SCRIPT_DIR/lib/android_device.sh"
# shellcheck source=lib/android_module.sh
source "$SCRIPT_DIR/lib/android_module.sh"
# shellcheck source=lib/android_commands.sh
source "$SCRIPT_DIR/lib/android_commands.sh"
# Ensure avahi-browse is available
if ! command -v avahi-browse &>/dev/null; then
if command -v pacman &>/dev/null; then
echo "Installing avahi for device discovery..." >&2
sudo pacman -S --noconfirm avahi nss-mdns &>/dev/null || true
sudo systemctl enable --now avahi-daemon &>/dev/null || true
elif command -v apt-get &>/dev/null; then
sudo apt-get install -y avahi-utils &>/dev/null || true
fi
fi
if command -v avahi-browse &>/dev/null; then
echo "Scanning for Android devices (5 seconds)..." >&2
# Android wireless debugging advertises as _adb-tls-connect._tcp
local discovery_result
discovery_result=$(timeout 5 avahi-browse -rpt _adb-tls-connect._tcp 2>/dev/null | grep "^=" | head -1)
if [[ -n $discovery_result ]]; then
# Parse: =;eth0;IPv4;adb-...;_adb-tls-connect._tcp;local;hostname.local;192.168.x.x;port;...
local ip port
ip=$(echo "$discovery_result" | cut -d';' -f8)
port=$(echo "$discovery_result" | cut -d';' -f9)
if [[ -n $ip && -n $port ]]; then
found_address="$ip:$port"
echo "✓ Found device: $found_address" >&2
fi
fi
fi
# Fallback: try adb's mdns discovery
if [[ -z $found_address ]]; then
echo "Trying adb mdns discovery..." >&2
# adb can discover devices via mdns
local mdns_result
mdns_result=$(timeout 5 adb mdns services 2>/dev/null | grep -E "adb-tls-connect|_adb\._tcp" | head -1)
if [[ -n $mdns_result ]]; then
# Try to extract IP:port from the result
local service_name
service_name=$(echo "$mdns_result" | awk '{print $1}')
if [[ -n $service_name ]]; then
# Try connecting via service name
echo "Found service: $service_name" >&2
fi
fi
fi
# Return found address (or empty)
echo "$found_address"
}
# Pair with device over WiFi (Android 11+)
cmd_pair() {
ensure_adb_installed
echo ""
echo "=== Wireless ADB Pairing (Android 11+) ==="
echo ""
echo "On your phone:"
echo " 1. Go to Settings > Developer Options > Wireless debugging"
echo " 2. Enable Wireless debugging"
echo " 3. Tap 'Pair device with pairing code'"
echo " 4. Note the IP:port and pairing code shown"
echo ""
read -rp "Enter pairing IP:port (e.g., 192.168.1.100:37123): " pair_address
read -rp "Enter pairing code: " pair_code
if [[ -z $pair_address || -z $pair_code ]]; then
die "Pairing address and code are required"
fi
log "Pairing with device at $pair_address..."
if adb pair "$pair_address" "$pair_code"; then
echo ""
echo "✓ Pairing successful!"
echo ""
echo "Now get the connection address:"
echo " On phone: Wireless debugging screen shows IP:port under 'IP address & Port'"
echo " (This is DIFFERENT from the pairing port)"
echo ""
read -rp "Enter connection IP:port (e.g., 192.168.1.100:41567): " connect_address
if [[ -n $connect_address ]]; then
# Save for future connections
mkdir -p "$(dirname "$WIRELESS_CONFIG")"
echo "$connect_address" >"$WIRELESS_CONFIG"
log "Saved connection address for future use"
# Connect now
cmd_connect
fi
else
die "Pairing failed. Make sure the code is correct and you're on the same network."
fi
}
# Connect to already-paired device
cmd_connect() {
ensure_adb_installed
local connect_address=""
# Check for saved address
if [[ -f $WIRELESS_CONFIG ]]; then
connect_address=$(cat "$WIRELESS_CONFIG")
log "Using saved address: $connect_address"
fi
# Try auto-discovery if no saved address
if [[ -z $connect_address ]]; then
echo ""
log "Searching for Android devices on network..."
connect_address=$(discover_android_device)
fi
# Manual fallback
if [[ -z $connect_address ]]; then
echo ""
echo "Auto-discovery failed. Enter address manually."
echo "On phone: Settings > Developer Options > Wireless debugging"
echo "Look for IP address & Port (NOT the pairing port)"
echo ""
read -rp "Enter connection IP:port (e.g., 192.168.1.100:41567): " connect_address
if [[ -z $connect_address ]]; then
die "Connection address is required"
fi
fi
# Save for future
mkdir -p "$(dirname "$WIRELESS_CONFIG")"
echo "$connect_address" >"$WIRELESS_CONFIG"
log "Connecting to $connect_address..."
if adb connect "$connect_address" | grep -q "connected"; then
echo ""
echo "✓ Connected to device wirelessly!"
echo ""
# Verify connection
if adb devices | grep -q "$connect_address"; then
echo "Device ready. You can now run other commands."
fi
else
echo ""
echo "Connection failed. Possible issues:"
echo " - Wireless debugging not enabled on phone"
echo " - Phone and PC not on same WiFi network"
echo " - Port changed (check Wireless debugging screen)"
echo " - May need to pair first: $0 pair"
echo ""
# Clear saved config since it failed
rm -f "$WIRELESS_CONFIG"
exit 1
fi
}
# Disconnect wireless ADB
cmd_disconnect() {
ensure_adb_installed
log "Disconnecting all wireless devices..."
adb disconnect
echo "✓ Disconnected"
}
# Check device connection and root
ensure_device_ready() {
ensure_adb_installed
# Check if any device is connected
if ! adb devices | grep -qE "device$|:.*device$"; then
echo ""
echo "No device connected!"
echo ""
echo "Options:"
echo " 1. Connect USB cable with debugging enabled"
echo " 2. Use wireless: $0 pair (first time) or $0 connect"
echo ""
# Check if we have a saved wireless config
if [[ -f $WIRELESS_CONFIG ]]; then
read -rp "Try connecting to saved wireless device? [Y/n]: " try_wireless
if [[ ${try_wireless,,} != "n" ]]; then
cmd_connect
else
exit 1
fi
else
exit 1
fi
fi
check_adb_device
check_adb_root
}
# Build the module zip
build_module() {
local tmp_dir="$WORK_DIR/guardian_module"
local module_zip="$WORK_DIR/android_guardian.zip"
echo "[BUILD] Building Android Guardian module..." >&2
rm -rf "$tmp_dir"
mkdir -p "$tmp_dir/system/etc"
# Copy module files
cp "$GUARDIAN_MODULE_DIR/module.prop" "$tmp_dir/"
cp "$GUARDIAN_MODULE_DIR/service.sh" "$tmp_dir/"
cp "$GUARDIAN_MODULE_DIR/post-fs-data.sh" "$tmp_dir/"
cp "$GUARDIAN_MODULE_DIR/uninstall.sh" "$tmp_dir/"
# Build hosts file
local hosts_file="$tmp_dir/system/etc/hosts"
if [[ -f /etc/hosts.stevenblack ]]; then
echo "[BUILD] Using StevenBlack hosts cache..." >&2
cp /etc/hosts.stevenblack "$hosts_file"
elif [[ -f /etc/hosts ]]; then
echo "[BUILD] Using /etc/hosts..." >&2
cp /etc/hosts "$hosts_file"
else
die "No hosts file found"
fi
# Append custom blocking entries
cat >>"$hosts_file" <<'CUSTOM_EOF'
# ============================================
# Custom blocking entries - Android Guardian
# ============================================
# YouTube
0.0.0.0 youtube.com
0.0.0.0 www.youtube.com
0.0.0.0 m.youtube.com
0.0.0.0 youtu.be
0.0.0.0 youtube-nocookie.com
0.0.0.0 www.youtube-nocookie.com
0.0.0.0 youtubei.googleapis.com
0.0.0.0 youtube.googleapis.com
0.0.0.0 yt3.ggpht.com
0.0.0.0 ytimg.com
0.0.0.0 i.ytimg.com
0.0.0.0 s.ytimg.com
0.0.0.0 i9.ytimg.com
0.0.0.0 googlevideo.com
# Alternative YouTube Frontends (Invidious, Piped, etc.)
0.0.0.0 invidious.io
0.0.0.0 www.invidious.io
0.0.0.0 invidio.us
0.0.0.0 vid.puffyan.us
0.0.0.0 invidious.snopyta.org
0.0.0.0 yewtu.be
0.0.0.0 invidious.kavin.rocks
0.0.0.0 inv.riverside.rocks
0.0.0.0 invidious.namazso.eu
0.0.0.0 invidious.nerdvpn.de
0.0.0.0 invidious.projectsegfau.lt
0.0.0.0 invidious.slipfox.xyz
0.0.0.0 invidious.privacydev.net
0.0.0.0 invidious.perennialte.ch
0.0.0.0 invidious.protokoll-11.de
0.0.0.0 invidious.einfachzocken.eu
0.0.0.0 invidious.fdn.fr
0.0.0.0 inv.in.projectsegfau.lt
0.0.0.0 invidious.tiekoetter.com
0.0.0.0 invidious.lunar.icu
0.0.0.0 iv.ggtyler.dev
0.0.0.0 iv.melmac.space
0.0.0.0 piped.video
0.0.0.0 www.piped.video
0.0.0.0 piped.kavin.rocks
0.0.0.0 piped.mha.fi
0.0.0.0 piped.mint.lgbt
0.0.0.0 piped.projectsegfau.lt
0.0.0.0 piped.privacydev.net
0.0.0.0 piped.smnz.de
0.0.0.0 piped.adminforge.de
0.0.0.0 watch.whatever.social
0.0.0.0 piped.lunar.icu
0.0.0.0 viewtube.io
0.0.0.0 www.viewtube.io
0.0.0.0 freetube.io
0.0.0.0 www.freetube.io
0.0.0.0 tubo.media
0.0.0.0 www.tubo.media
0.0.0.0 materialious.nadeko.net
0.0.0.0 clipious.org
0.0.0.0 www.clipious.org
0.0.0.0 newpipe.net
0.0.0.0 www.newpipe.net
0.0.0.0 newpipe.schabi.org
0.0.0.0 grayjay.app
0.0.0.0 www.grayjay.app
0.0.0.0 libretube.dev
0.0.0.0 www.libretube.dev
0.0.0.0 hyperion.deishelon.com
0.0.0.0 inv.n8pjl.ca
0.0.0.0 inv.zzls.xyz
0.0.0.0 inv.tux.pizza
0.0.0.0 invidious.incogniweb.net
0.0.0.0 invidious.drgns.space
0.0.0.0 invidious.io.lol
# Discord (media only - voice chat allowed)
0.0.0.0 cdn.discordapp.com
0.0.0.0 media.discordapp.net
0.0.0.0 images-ext-1.discordapp.net
0.0.0.0 images-ext-2.discordapp.net
0.0.0.0 tenor.com
0.0.0.0 giphy.com
# Food Delivery Services
# Polish services
0.0.0.0 pyszne.pl
0.0.0.0 www.pyszne.pl
0.0.0.0 m.pyszne.pl
0.0.0.0 api.pyszne.pl
0.0.0.0 app.pyszne.pl
0.0.0.0 glovo.com
0.0.0.0 www.glovo.com
0.0.0.0 m.glovo.com
0.0.0.0 api.glovo.com
0.0.0.0 glovoapp.com
0.0.0.0 www.glovoapp.com
0.0.0.0 bolt.eu
:: bolt.eu
0.0.0.0 www.bolt.eu
:: www.bolt.eu
0.0.0.0 food.bolt.eu
:: food.bolt.eu
0.0.0.0 m.bolt.eu
:: m.bolt.eu
0.0.0.0 api.bolt.eu
:: api.bolt.eu
0.0.0.0 node.bolt.eu
:: node.bolt.eu
0.0.0.0 gw.bolt.eu
:: gw.bolt.eu
0.0.0.0 client-api.bolt.eu
:: client-api.bolt.eu
0.0.0.0 auth.bolt.eu
:: auth.bolt.eu
0.0.0.0 cdn.bolt.eu
:: cdn.bolt.eu
0.0.0.0 images.bolt.eu
:: images.bolt.eu
0.0.0.0 static.bolt.eu
:: static.bolt.eu
0.0.0.0 assets.bolt.eu
:: assets.bolt.eu
0.0.0.0 fleet.bolt.eu
:: fleet.bolt.eu
0.0.0.0 user.bolt.eu
:: user.bolt.eu
0.0.0.0 courier.bolt.eu
:: courier.bolt.eu
0.0.0.0 rider.bolt.eu
:: rider.bolt.eu
0.0.0.0 restaurant.bolt.eu
:: restaurant.bolt.eu
0.0.0.0 partner-food.bolt.eu
:: partner-food.bolt.eu
0.0.0.0 wolt.com
0.0.0.0 www.wolt.com
0.0.0.0 m.wolt.com
0.0.0.0 api.wolt.com
0.0.0.0 restaurant-api.wolt.com
0.0.0.0 consumer-api.wolt.com
0.0.0.0 woltwojta.pl
0.0.0.0 www.woltwojta.pl
0.0.0.0 jush.pl
0.0.0.0 www.jush.pl
0.0.0.0 m.jush.pl
0.0.0.0 api.jush.pl
0.0.0.0 delio.pl
0.0.0.0 www.delio.pl
0.0.0.0 m.delio.pl
0.0.0.0 api.delio.pl
0.0.0.0 delio.com
0.0.0.0 www.delio.com
0.0.0.0 delio.com.pl
0.0.0.0 www.delio.com.pl
0.0.0.0 api.delio.com.pl
0.0.0.0 lisek.app
0.0.0.0 www.lisek.app
0.0.0.0 api.lisek.app
0.0.0.0 stava.app
0.0.0.0 www.stava.app
0.0.0.0 api.stava.app
0.0.0.0 barbora.pl
0.0.0.0 www.barbora.pl
0.0.0.0 api.barbora.pl
0.0.0.0 frisco.pl
0.0.0.0 www.frisco.pl
0.0.0.0 api.frisco.pl
0.0.0.0 szama.pl
0.0.0.0 www.szama.pl
0.0.0.0 api.szama.pl
0.0.0.0 auchandirect.pl
0.0.0.0 www.auchandirect.pl
0.0.0.0 zakupy.biedronka.pl
0.0.0.0 ezakupy.tesco.pl
0.0.0.0 www.ezakupy.tesco.pl
# International services
0.0.0.0 ubereats.com
0.0.0.0 www.ubereats.com
0.0.0.0 m.ubereats.com
0.0.0.0 api.ubereats.com
0.0.0.0 uber.com
0.0.0.0 www.uber.com
0.0.0.0 m.uber.com
0.0.0.0 api.uber.com
0.0.0.0 login.uber.com
0.0.0.0 auth.uber.com
0.0.0.0 deliveroo.com
0.0.0.0 www.deliveroo.com
0.0.0.0 m.deliveroo.com
0.0.0.0 api.deliveroo.com
0.0.0.0 deliveroo.co.uk
0.0.0.0 www.deliveroo.co.uk
0.0.0.0 foodpanda.com
0.0.0.0 www.foodpanda.com
0.0.0.0 m.foodpanda.com
0.0.0.0 api.foodpanda.com
0.0.0.0 grubhub.com
0.0.0.0 www.grubhub.com
0.0.0.0 m.grubhub.com
0.0.0.0 api.grubhub.com
0.0.0.0 doordash.com
0.0.0.0 www.doordash.com
0.0.0.0 m.doordash.com
0.0.0.0 api.doordash.com
0.0.0.0 justeat.com
0.0.0.0 www.justeat.com
0.0.0.0 m.justeat.com
0.0.0.0 justeat.co.uk
0.0.0.0 www.justeat.co.uk
0.0.0.0 postmates.com
0.0.0.0 www.postmates.com
0.0.0.0 seamless.com
0.0.0.0 www.seamless.com
0.0.0.0 getir.com
0.0.0.0 www.getir.com
0.0.0.0 api.getir.com
0.0.0.0 flink.com
0.0.0.0 www.flink.com
0.0.0.0 gorillas.io
0.0.0.0 www.gorillas.io
0.0.0.0 gopuff.com
0.0.0.0 www.gopuff.com
0.0.0.0 instacart.com
0.0.0.0 www.instacart.com
0.0.0.0 takeaway.com
0.0.0.0 www.takeaway.com
0.0.0.0 api.takeaway.com
# Fast Food
0.0.0.0 mcdonalds.com
0.0.0.0 www.mcdonalds.com
0.0.0.0 mcdonalds.pl
0.0.0.0 www.mcdonalds.pl
0.0.0.0 kfc.com
0.0.0.0 www.kfc.com
0.0.0.0 kfc.pl
0.0.0.0 www.kfc.pl
0.0.0.0 burgerking.com
0.0.0.0 www.burgerking.com
0.0.0.0 pizzahut.com
0.0.0.0 www.pizzahut.com
0.0.0.0 dominos.com
0.0.0.0 www.dominos.com
CUSTOM_EOF
local total_entries
total_entries=$(grep -c "^0\.0\.0\.0 " "$hosts_file" || echo 0)
echo "[BUILD] Hosts file contains $total_entries blocked domains" >&2
# Create zip
(cd "$tmp_dir" && zip -r "$module_zip" . -x "*.DS_Store") >/dev/null
echo "$module_zip"
}
# Install/update the guardian module
cmd_install() {
ensure_device_ready
local module_zip
module_zip=$(build_module)
log "Pushing module to device..."
adb push "$module_zip" /sdcard/android_guardian.zip || die "Failed to push module"
log "Installing module..."
adb shell "su -c 'mkdir -p $MODULE_DEST'" || die "Failed to create module directory"
adb shell "su -c 'cd $MODULE_DEST && unzip -o /sdcard/android_guardian.zip'" || die "Failed to extract module"
adb shell "su -c 'chmod 755 $MODULE_DEST/*.sh'"
adb shell "su -c 'rm /sdcard/android_guardian.zip'"
# Set up guardian data directory
log "Setting up guardian data..."
adb shell "su -c 'mkdir -p $GUARDIAN_DATA_DIR'"
adb shell "su -c 'echo ENABLED > $GUARDIAN_DATA_DIR/control'"
# Copy blocked apps list
adb push "$GUARDIAN_MODULE_DIR/blocked_apps.txt" /sdcard/blocked_apps.txt || die "Failed to push blocked apps list"
adb shell "su -c 'cp /sdcard/blocked_apps.txt $GUARDIAN_DATA_DIR/blocked_apps.txt'"
adb shell "su -c 'rm /sdcard/blocked_apps.txt'"
# Create hosts backup for tamper protection
adb shell "su -c 'cp $MODULE_DEST/system/etc/hosts $GUARDIAN_DATA_DIR/hosts.backup'"
# Immediately uninstall any currently installed blocked apps
log "Checking for blocked apps to remove..."
uninstall_blocked_apps
echo ""
echo "=========================================="
echo " ✓ Android Guardian installed!"
echo "=========================================="
echo ""
echo "Features enabled:"
echo " • Hosts-based ad/tracker blocking"
echo " • App installation blocking"
echo " • Tamper protection"
echo ""
echo "⚠️ This can ONLY be controlled via ADB:"
echo " Disable: $0 disable"
echo " Enable: $0 enable"
echo " Status: $0 status"
echo ""
echo "Reboot your device to activate the module."
echo ""
}
# Uninstall currently installed blocked apps
uninstall_blocked_apps() {
local blocked_apps
blocked_apps=$(grep -v '^#' "$GUARDIAN_MODULE_DIR/blocked_apps.txt" | grep -v '^$' || true)
for package in $blocked_apps; do
if adb shell "pm list packages" 2>/dev/null | grep -q "package:$package"; then
log "Uninstalling blocked app: $package"
adb shell "pm uninstall $package" 2>/dev/null || true
fi
done
}
# Show status
cmd_status() {
ensure_device_ready
echo ""
echo "=== Android Guardian Status ==="
echo ""
# Check if module is installed
if adb shell "su -c 'test -d $MODULE_DEST'" 2>/dev/null; then
echo "Module: INSTALLED"
else
echo "Module: NOT INSTALLED"
return
fi
# Check control status
local status
status=$(adb shell "su -c 'cat $GUARDIAN_DATA_DIR/control 2>/dev/null || echo UNKNOWN'" | tr -d '\r')
echo "Status: $status"
# Check if module is "disabled" in Magisk UI (should be auto-fixed by watchdog)
local magisk_disabled
if adb shell "su -c 'test -f $MODULE_DEST/disable'" 2>/dev/null; then
magisk_disabled="YES (watchdog should fix this)"
else
magisk_disabled="No"
fi
echo "Magisk UI disabled: $magisk_disabled"
# Check if watchdog is running
local watchdog_running
watchdog_running=$(adb shell "su -c 'pgrep -f watchdog.sh 2>/dev/null | wc -l'" | tr -d '\r')
if [ "$watchdog_running" -gt 0 ] 2>/dev/null; then
echo "Watchdog: RUNNING ($watchdog_running processes)"
else
echo "Watchdog: NOT RUNNING (reboot phone to start)"
fi
# Check hosts file
local hosts_entries
hosts_entries=$(adb shell "su -c 'grep -c \"^0.0.0.0\" /system/etc/hosts 2>/dev/null || echo 0'" | tr -d '\r')
echo "Blocked domains: $hosts_entries"
# Check blocked apps count
local blocked_count
blocked_count=$(adb shell "su -c 'grep -v \"^#\" $GUARDIAN_DATA_DIR/blocked_apps.txt 2>/dev/null | grep -v \"^$\" | wc -l || echo 0'" | tr -d '\r')
echo "Blocked app rules: $blocked_count packages"
echo ""
echo "Protection: Module cannot be disabled from Magisk UI"
echo " Only controllable via: $0 disable/enable"
echo ""
}
# Disable guardian
cmd_disable() {
ensure_device_ready
log "Disabling Android Guardian..."
adb shell "su -c 'echo DISABLED > $GUARDIAN_DATA_DIR/control'" || die "Failed to disable guardian"
echo ""
echo "✓ Guardian DISABLED"
echo " Hosts blocking still active until reboot"
echo " App blocking service paused"
echo ""
echo "To re-enable: $0 enable"
echo ""
}
# Enable guardian
cmd_enable() {
ensure_device_ready
log "Enabling Android Guardian..."
adb shell "su -c 'echo ENABLED > $GUARDIAN_DATA_DIR/control'" || die "Failed to enable guardian"
echo ""
echo "✓ Guardian ENABLED"
echo ""
}
# Uninstall module
cmd_uninstall() {
ensure_device_ready
# Check if disabled first
local status
status=$(adb shell "su -c 'cat $GUARDIAN_DATA_DIR/control 2>/dev/null || echo ENABLED'" | tr -d '\r')
if [[ $status != "DISABLED" ]]; then
echo ""
echo "⚠️ Guardian must be disabled before uninstalling!"
echo " Run: $0 disable"
echo " Then: $0 uninstall"
echo ""
exit 1
fi
log "Removing Android Guardian..."
adb shell "su -c 'rm -rf $MODULE_DEST'"
adb shell "su -c 'rm -rf $GUARDIAN_DATA_DIR'"
echo ""
echo "✓ Guardian uninstalled"
echo " Reboot to remove hosts blocking"
echo ""
}
# Show logs
cmd_logs() {
ensure_device_ready
echo "=== Guardian Logs ==="
adb shell "su -c 'cat $GUARDIAN_DATA_DIR/guardian.log 2>/dev/null || echo \"No logs yet\"'"
}
# Block an app
cmd_block_app() {
local package="${1:-}"
if [[ -z $package ]]; then
echo "Usage: $0 block-app <package.name>"
echo "Example: $0 block-app com.ubercab.eats"
exit 1
fi
ensure_device_ready
log "Adding $package to block list..."
adb shell "su -c 'echo \"$package\" >> $GUARDIAN_DATA_DIR/blocked_apps.txt'"
# Also add to local file
echo "$package" >>"$GUARDIAN_MODULE_DIR/blocked_apps.txt"
# Try to uninstall if currently installed
if adb shell "pm list packages" 2>/dev/null | grep -q "package:$package"; then
log "Uninstalling $package..."
adb shell "pm uninstall $package" 2>/dev/null || true
fi
echo "✓ $package added to block list"
}
# Unblock an app
cmd_unblock_app() {
local package="${1:-}"
if [[ -z $package ]]; then
echo "Usage: $0 unblock-app <package.name>"
exit 1
fi
ensure_device_ready
log "Removing $package from block list..."
adb shell "su -c 'grep -v \"^$package\$\" $GUARDIAN_DATA_DIR/blocked_apps.txt > $GUARDIAN_DATA_DIR/blocked_apps.tmp && mv $GUARDIAN_DATA_DIR/blocked_apps.tmp $GUARDIAN_DATA_DIR/blocked_apps.txt'"
# Also remove from local file
grep -v "^$package$" "$GUARDIAN_MODULE_DIR/blocked_apps.txt" >"$GUARDIAN_MODULE_DIR/blocked_apps.tmp" && mv "$GUARDIAN_MODULE_DIR/blocked_apps.tmp" "$GUARDIAN_MODULE_DIR/blocked_apps.txt"
echo "✓ $package removed from block list"
}
# List blocked apps
cmd_list_blocked() {
ensure_device_ready
echo "=== Blocked Apps ==="
adb shell "su -c 'cat $GUARDIAN_DATA_DIR/blocked_apps.txt 2>/dev/null'" | grep -v "^#" | grep -v "^$" || echo "No blocked apps"
}
# Main
# Initialize Android script (handles sudo, sets WORK_DIR)

View File

@ -6,8 +6,8 @@
## Where things stand
**73 files** over 250 lines (was 183). Everything is committed and pushed to
`main` at `a68313f`. `focus_owner/analysis_options.yaml` has an uncommitted
**69 files** over 250 lines (was 183 — 62% cleared). Everything is committed
and pushed to `main` at `c058431`. `focus_owner/analysis_options.yaml` has an uncommitted
change from an earlier session — **leave it unstaged**, it is not ours.
**`python_pkg/` is DONE — 50 violations → 0.** Do not reopen it. Cleared one
@ -16,7 +16,8 @@ at 402), `code_tutor` (13→0, 216→217), then `android_ui`, `app_icons`,
`token_audit`, `focus_policy`, `random_jpg` (57/44/81/137/14), then
`wsg_grabber`'s six test modules (277).
**`linux_configuration` is 84 → 42**, in fourteen batches. **All 12 prose files
**`linux_configuration` is 84 → 38**, in eighteen batches. Both shared libs
(`common.sh`, `mtk_common.sh`) are done via the entry-point pattern. **All 12 prose files
are done** (8 split, 2 deleted as completed-work records on the user's ruling).
**`kcd2_dice_solver` is 12 → 4**, all four remaining being source files. The
shell pattern is settled and scripted — read `docs/shell-split-recipes.md`