Repository navigation
Expand file tree
/
Copy pathcodegen-interfaces.py
More file actions
executable file
·577 lines (506 loc) · 19.8 KB
/
Copy pathcodegen-interfaces.py
File metadata and controls
executable file
·577 lines (506 loc) · 19.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
#!/usr/bin/env python3
"""Render the four iface-list matchers + their unit tests from
data/interfaces.toml.
Generates one match function per target (kmod C, zygisk Rust,
crates/checks Rust, lsposed Kotlin) so all four platforms agree on
which interface names are VPN tunnels, plus per-language test files
seeded from the same [[test]] vectors so CI catches drift instantly.
Re-run after editing data/interfaces.toml and commit the regenerated
files. CI's lint job re-runs the codegen and fails on drift.
Stdlib only: tomllib (Python 3.11+) is the only non-builtin import,
and that's stdlib too.
"""
from __future__ import annotations
import sys
import tomllib
from pathlib import Path
from typing import Any
sys.path.insert(0, str(Path(__file__).resolve().parent))
from codegen_lib import ( # type: ignore[import-not-found]
REPO_ROOT,
emit_outputs,
generated_header,
lsposed_generated_kt,
)
TOML_PATH = REPO_ROOT / "data" / "interfaces.toml"
# Output paths — kept next to the code that consumes them so include /
# import paths stay short and obvious.
OUT_KMOD = REPO_ROOT / "kmod" / "generated" / "iface_lists.h"
OUT_KMOD_TEST = REPO_ROOT / "kmod" / "test_iface_lists.c"
OUT_ZYGISK = REPO_ROOT / "zygisk" / "src" / "generated" / "iface_lists.rs"
OUT_LSP_NATIVE = REPO_ROOT / "crates" / "checks" / "src" / "generated" / "iface_lists.rs"
OUT_LSP_KT = lsposed_generated_kt("IfaceLists.kt")
OUT_LSP_KT_TEST = lsposed_generated_kt("IfaceListsGeneratedTest.kt", test=True)
GENERATED_HEADER_LINE = generated_header(
"data/interfaces.toml", "python3 scripts/codegen-interfaces.py"
)
# ---------------------------------------------------------------------------
# rule normalization
# ---------------------------------------------------------------------------
VALID_KINDS = ("exact", "prefix", "prefix_digits", "contains")
class Rule:
"""One match rule from the toml, normalized to a known kind.
kind ∈ VALID_KINDS.
needle is the literal string (already lowercased — all targets
fold case at match time).
note is the human comment from the toml, copied into the
generated source so reviewers see why each rule is there.
"""
__slots__ = ("kind", "needle", "note")
def __init__(self, kind: str, needle: str, note: str) -> None:
self.kind = kind
self.needle = needle
self.note = note
class TestVector:
__slots__ = ("name", "is_vpn")
def __init__(self, name: str, is_vpn: bool) -> None:
self.name = name
self.is_vpn = is_vpn
def parse_rule(entry: dict[str, Any]) -> Rule:
match = entry.get("match")
if not isinstance(match, dict):
raise SystemExit(f"entry missing or malformed `match`: {entry!r}")
note = str(entry.get("note", "")).strip()
keys = set(match.keys())
if keys == {"exact"}:
needle = str(match["exact"])
kind = "exact"
elif keys == {"prefix"}:
needle = str(match["prefix"])
kind = "prefix"
elif keys == {"prefix", "suffix"}:
suffix = str(match["suffix"])
if suffix == "digits":
kind = "prefix_digits"
else:
raise SystemExit(f"unsupported suffix {suffix!r}; expected digits")
needle = str(match["prefix"])
elif keys == {"contains"}:
needle = str(match["contains"])
kind = "contains"
else:
raise SystemExit(f"unsupported match shape {keys!r} in entry {entry!r}")
if not needle:
raise SystemExit(f"empty needle in entry {entry!r}")
if not all(0x20 <= ord(c) < 0x7F for c in needle):
raise SystemExit(f"non-ASCII needle {needle!r} in entry {entry!r}")
return Rule(kind, needle.lower(), note)
def parse_test(entry: dict[str, Any]) -> TestVector:
if "name" not in entry or "is_vpn" not in entry:
raise SystemExit(f"[[test]] entry needs name and is_vpn: {entry!r}")
name = str(entry["name"])
if not all(0x20 <= ord(c) < 0x7F for c in name):
raise SystemExit(f"non-ASCII test name {name!r}; the matcher itself is ASCII-only")
return TestVector(name=name, is_vpn=bool(entry["is_vpn"]))
def load() -> tuple[list[Rule], list[Rule], list[TestVector]]:
with TOML_PATH.open("rb") as f:
data = tomllib.load(f)
raw_rules = data.get("vpn") or []
if not isinstance(raw_rules, list) or not raw_rules:
raise SystemExit(f"{TOML_PATH}: missing or empty [[vpn]] table")
rules = [parse_rule(e) for e in raw_rules]
raw_excludes = data.get("exclude") or []
if not isinstance(raw_excludes, list):
raise SystemExit(f"{TOML_PATH}: [[exclude]] must be an array of tables")
excludes = [parse_rule(e) for e in raw_excludes]
tests = [parse_test(e) for e in (data.get("test") or [])]
return rules, excludes, tests
# ---------------------------------------------------------------------------
# escape helpers
# ---------------------------------------------------------------------------
def c_str_lit(s: str) -> str:
out = ['"']
for c in s:
if c == '"':
out.append('\\"')
elif c == "\\":
out.append("\\\\")
elif 0x20 <= ord(c) < 0x7F:
out.append(c)
else:
out.append(f"\\x{ord(c):02x}")
out.append('"')
return "".join(out)
def rust_byte_lit(s: str) -> str:
# Use byte-string with escapes so non-printable / quotes survive.
out = ['b"']
for c in s:
if c == '"':
out.append('\\"')
elif c == "\\":
out.append("\\\\")
elif 0x20 <= ord(c) < 0x7F:
out.append(c)
else:
out.append(f"\\x{ord(c):02x}")
out.append('"')
return "".join(out)
def kt_str_lit(s: str) -> str:
out = ['"']
for c in s:
if c == '"':
out.append('\\"')
elif c == "\\":
out.append("\\\\")
elif c == "$":
out.append("\\$")
elif 0x20 <= ord(c) < 0x7F:
out.append(c)
else:
out.append(f"\\u{ord(c):04x}")
out.append('"')
return "".join(out)
# ---------------------------------------------------------------------------
# C emitter (kmod)
# ---------------------------------------------------------------------------
# Self-contained C matcher helpers (no libc/kernel headers). Literal template
# block — `\t` becomes a tab in the generated header (kernel style), same as
# the rest of the emitter. Shared verbatim by the .ko and the KPM backend.
KMOD_MATCHER_HELPERS = """\
static inline char vpnhide__lc(char c)
{
\treturn (c >= 'A' && c <= 'Z') ? (char)(c - 'A' + 'a') : c;
}
static inline int vpnhide_iface_starts_with_ci(const char *name, const char *prefix)
{
\tint i;
\tfor (i = 0; prefix[i]; i++) {
\t\tif (!name[i])
\t\t\treturn 0;
\t\tif (vpnhide__lc(name[i]) != vpnhide__lc(prefix[i]))
\t\t\treturn 0;
\t}
\treturn 1;
}
static inline int vpnhide_iface_starts_with_then_digits_ci(const char *name,
\t\t\t\t\t\t\t const char *prefix)
{
\tint i = 0;
\tif (!vpnhide_iface_starts_with_ci(name, prefix))
\t\treturn 0;
\twhile (prefix[i])
\t\ti++;
\tif (!name[i])
\t\treturn 0;
\tfor (; name[i]; i++)
\t\tif (name[i] < '0' || name[i] > '9')
\t\t\treturn 0;
\treturn 1;
}
static inline int vpnhide_iface_equals_ci(const char *name, const char *other)
{
\tint i;
\tfor (i = 0; other[i]; i++) {
\t\tif (!name[i])
\t\t\treturn 0;
\t\tif (vpnhide__lc(name[i]) != vpnhide__lc(other[i]))
\t\t\treturn 0;
\t}
\treturn name[i] == '\\0';
}
static inline int vpnhide_iface_contains_ci(const char *name, const char *needle)
{
\tint i, j;
\tif (!needle[0])
\t\treturn 1;
\tfor (i = 0; name[i]; i++) {
\t\tfor (j = 0; needle[j]; j++) {
\t\t\tif (!name[i + j])
\t\t\t\treturn 0;
\t\t\tif (vpnhide__lc(name[i + j]) != vpnhide__lc(needle[j]))
\t\t\t\tbreak;
\t\t}
\t\tif (!needle[j])
\t\t\treturn 1;
\t}
\treturn 0;
}
"""
def emit_kmod(rules: list[Rule], excludes: list[Rule]) -> str:
"""Render an inline header for the kernel module.
Header is dual-target: builds in kernel (default) AND in userspace
when __VPNHIDE_HOST_TEST is defined, so test_iface_lists.c can link
the same matcher.
"""
lines: list[str] = []
lines.append(f"/* {GENERATED_HEADER_LINE} */")
lines.append("#ifndef VPNHIDE_GENERATED_IFACE_LISTS_H")
lines.append("#define VPNHIDE_GENERATED_IFACE_LISTS_H")
lines.append("")
# Self-contained matcher: no <ctype.h>/<string.h>/<stdbool.h>/<linux/*>,
# so the SAME header compiles in every world that consumes it — the
# kretprobe .ko (real kernel headers), the KernelPatch KPM (-nostdinc, no
# libc/ctype stubs), and the host unit test. ASCII case-fold and length
# are done locally; returns int (0/1).
lines.append(KMOD_MATCHER_HELPERS)
lines.append("static inline int vpnhide_iface_is_vpn(const char *name)")
lines.append("{")
lines.append("\tif (!name || !name[0])")
lines.append("\t\treturn 0;")
fn_for_kind = {
"exact": "vpnhide_iface_equals_ci",
"prefix": "vpnhide_iface_starts_with_ci",
"prefix_digits": "vpnhide_iface_starts_with_then_digits_ci",
"contains": "vpnhide_iface_contains_ci",
}
# Exclusions run first: standard non-VPN kernel devices (e.g. the ipip/gre
# fallback netdevs tunl0/gre0/gretap0) that would otherwise match a [[vpn]]
# rule below. A hit here means "definitely not a VPN" — return early.
for r in excludes:
if r.note:
lines.append(f"\t/* not a VPN: {r.note} */")
lines.append(f"\tif ({fn_for_kind[r.kind]}(name, {c_str_lit(r.needle)}))")
lines.append("\t\treturn 0;")
for r in rules:
if r.note:
lines.append(f"\t/* {r.note} */")
lines.append(f"\tif ({fn_for_kind[r.kind]}(name, {c_str_lit(r.needle)}))")
lines.append("\t\treturn 1;")
lines.append("\treturn 0;")
lines.append("}")
lines.append("")
lines.append("#endif /* VPNHIDE_GENERATED_IFACE_LISTS_H */")
lines.append("")
return "\n".join(lines)
def emit_kmod_test(tests: list[TestVector]) -> str:
"""Render a userspace test driver.
Built in CI's lint job (gcc on the host). Includes the same
iface_lists.h that the kernel module uses, but compiles with
libc headers via the !__KERNEL__ branch of the header guard.
"""
lines: list[str] = []
lines.append(f"/* {GENERATED_HEADER_LINE} */")
lines.append("/*")
lines.append(" * Userspace test driver for generated/iface_lists.h.")
lines.append(" * Build: gcc -O2 -Wall -Werror -o test_iface_lists test_iface_lists.c")
lines.append(" * Run: ./test_iface_lists (exit 0 on success, 1 on failure)")
lines.append(" */")
lines.append("")
lines.append("#include <stdbool.h>")
lines.append("#include <stdio.h>")
lines.append("")
lines.append('#include "generated/iface_lists.h"')
lines.append("")
lines.append("static int failures;")
lines.append("")
lines.append("static void check(const char *name, bool expected)")
lines.append("{")
lines.append("\tbool got = vpnhide_iface_is_vpn(name);")
lines.append("\tif (got != expected) {")
lines.append("\t\tfprintf(stderr,")
lines.append('\t\t\t"FAIL: vpnhide_iface_is_vpn(\\"%s\\") = %s, expected %s\\n",')
lines.append('\t\t\tname, got ? "true" : "false",')
lines.append('\t\t\texpected ? "true" : "false");')
lines.append("\t\tfailures++;")
lines.append("\t}")
lines.append("}")
lines.append("")
lines.append("int main(void)")
lines.append("{")
for t in tests:
expected = "true" if t.is_vpn else "false"
lines.append(f"\tcheck({c_str_lit(t.name)}, {expected});")
lines.append("")
lines.append("\tif (failures) {")
lines.append('\t\tfprintf(stderr, "%d test(s) failed\\n", failures);')
lines.append("\t\treturn 1;")
lines.append("\t}")
lines.append(f'\tprintf("OK: {len(tests)} vectors passed\\n");')
lines.append("\treturn 0;")
lines.append("}")
lines.append("")
return "\n".join(lines)
# ---------------------------------------------------------------------------
# Rust emitter (zygisk + crates/checks — same body)
# ---------------------------------------------------------------------------
def _rust_fn(kind: str) -> str:
return {
"exact": "equals_ci",
"prefix": "starts_with_ci",
"prefix_digits": "starts_with_then_digits_ci",
"contains": "contains_ci",
}[kind]
def emit_rust(rules: list[Rule], excludes: list[Rule], tests: list[TestVector]) -> str:
lines: list[str] = []
lines.append(f"// {GENERATED_HEADER_LINE}")
lines.append("")
lines.append("#![allow(dead_code)]")
lines.append("")
lines.append("fn starts_with_ci(name: &[u8], prefix: &[u8]) -> bool {")
lines.append(" if name.len() < prefix.len() {")
lines.append(" return false;")
lines.append(" }")
lines.append(" for (i, &p) in prefix.iter().enumerate() {")
lines.append(" if name[i].to_ascii_lowercase() != p {")
lines.append(" return false;")
lines.append(" }")
lines.append(" }")
lines.append(" true")
lines.append("}")
lines.append("")
lines.append("fn starts_with_then_digits_ci(name: &[u8], prefix: &[u8]) -> bool {")
lines.append(" if !starts_with_ci(name, prefix) {")
lines.append(" return false;")
lines.append(" }")
lines.append(" let rest = &name[prefix.len()..];")
lines.append(" !rest.is_empty() && rest.iter().all(|b| b.is_ascii_digit())")
lines.append("}")
lines.append("")
lines.append("fn equals_ci(name: &[u8], other: &[u8]) -> bool {")
lines.append(" if name.len() != other.len() {")
lines.append(" return false;")
lines.append(" }")
lines.append(" name.iter()")
lines.append(" .zip(other.iter())")
lines.append(" .all(|(a, b)| a.to_ascii_lowercase() == *b)")
lines.append("}")
lines.append("")
lines.append("fn contains_ci(haystack: &[u8], needle: &[u8]) -> bool {")
lines.append(" if needle.is_empty() {")
lines.append(" return true;")
lines.append(" }")
lines.append(" if needle.len() > haystack.len() {")
lines.append(" return false;")
lines.append(" }")
lines.append(" for start in 0..=haystack.len() - needle.len() {")
lines.append(" let window = &haystack[start..start + needle.len()];")
lines.append(" if window")
lines.append(" .iter()")
lines.append(" .zip(needle.iter())")
lines.append(" .all(|(a, b)| a.eq_ignore_ascii_case(b))")
lines.append(" {")
lines.append(" return true;")
lines.append(" }")
lines.append(" }")
lines.append(" false")
lines.append("}")
lines.append("")
lines.append("/// True if the name matches any VPN-iface rule from data/interfaces.toml.")
lines.append("pub fn matches_vpn(name: &[u8]) -> bool {")
lines.append(" if name.is_empty() {")
lines.append(" return false;")
lines.append(" }")
# Exclusions run first: standard non-VPN kernel devices (tunl0/gre0/gretap0)
# that would otherwise match a rule below. A hit means "not a VPN".
for r in excludes:
if r.note:
lines.append(f" // not a VPN: {r.note}")
lines.append(f" if {_rust_fn(r.kind)}(name, {rust_byte_lit(r.needle)}) {{")
lines.append(" return false;")
lines.append(" }")
for r in rules:
if r.note:
lines.append(f" // {r.note}")
lines.append(f" if {_rust_fn(r.kind)}(name, {rust_byte_lit(r.needle)}) {{")
lines.append(" return true;")
lines.append(" }")
lines.append(" false")
lines.append("}")
lines.append("")
# Test module — generated assertions are wide; skip rustfmt rather
# than wrap each assertion across 5 lines.
lines.append("#[cfg(test)]")
lines.append("#[rustfmt::skip]")
lines.append("mod tests {")
lines.append(" use super::*;")
lines.append("")
lines.append(" #[test]")
lines.append(" fn generated_vectors() {")
for t in tests:
# `assert!(x, msg)` / `assert!(!x, msg)` instead of
# `assert_eq!(x, true/false, msg)` — clippy::bool_assert_comparison
# would otherwise fire on every generated row when contributors
# run `cargo clippy --tests`.
prefix = "" if t.is_vpn else "!"
lines.append(
f" assert!({prefix}matches_vpn({rust_byte_lit(t.name)}), "
f'"matches_vpn({t.name!r})");'
)
lines.append(" }")
lines.append("}")
lines.append("")
return "\n".join(lines)
# ---------------------------------------------------------------------------
# Kotlin emitter (production code + separate test class)
# ---------------------------------------------------------------------------
def _kt_cond(r: Rule) -> str:
if r.kind == "exact":
return f"n == {kt_str_lit(r.needle)}"
if r.kind == "prefix":
return f"n.startsWith({kt_str_lit(r.needle)})"
if r.kind == "prefix_digits":
lit = kt_str_lit(r.needle)
return (
f"n.startsWith({lit}) && "
f"n.length > {len(r.needle)} && "
f"n.substring({len(r.needle)}).all {{ it.isDigit() }}"
)
if r.kind == "contains":
return f"n.contains({kt_str_lit(r.needle)})"
raise SystemExit(f"unhandled rule kind {r.kind!r}")
def emit_kotlin(rules: list[Rule], excludes: list[Rule]) -> str:
lines: list[str] = []
lines.append(f"// {GENERATED_HEADER_LINE}")
lines.append("")
lines.append("package dev.okhsunrog.vpnhide.generated")
lines.append("")
lines.append("internal object IfaceLists {")
lines.append(" /** True if `name` looks like a VPN tunnel per data/interfaces.toml. */")
lines.append(" fun isVpnIface(name: String): Boolean {")
lines.append(" if (name.isEmpty()) return false")
lines.append(" val n = name.lowercase()")
# Exclusions run first: standard non-VPN kernel devices (tunl0/gre0/gretap0)
# that would otherwise match a rule below. A hit means "not a VPN".
for r in excludes:
if r.note:
lines.append(f" // not a VPN: {r.note}")
lines.append(f" if ({_kt_cond(r)}) return false")
for r in rules:
if r.note:
lines.append(f" // {r.note}")
lines.append(f" if ({_kt_cond(r)}) return true")
lines.append(" return false")
lines.append(" }")
lines.append("}")
lines.append("")
return "\n".join(lines)
def emit_kotlin_test(tests: list[TestVector]) -> str:
lines: list[str] = []
lines.append(f"// {GENERATED_HEADER_LINE}")
lines.append("")
lines.append("package dev.okhsunrog.vpnhide.generated")
lines.append("")
lines.append("import org.junit.Assert.assertEquals")
lines.append("import org.junit.Test")
lines.append("")
lines.append("class IfaceListsGeneratedTest {")
lines.append(" @Test")
lines.append(" fun `generated vectors`() {")
for t in tests:
expected = "true" if t.is_vpn else "false"
lines.append(
f" assertEquals({kt_str_lit(t.name)}, {expected}, "
f"IfaceLists.isVpnIface({kt_str_lit(t.name)}))"
)
lines.append(" }")
lines.append("}")
lines.append("")
return "\n".join(lines)
# ---------------------------------------------------------------------------
# main
# ---------------------------------------------------------------------------
def main() -> int:
rules, excludes, tests = load()
rust_body = emit_rust(rules, excludes, tests)
return emit_outputs(
{
OUT_KMOD: emit_kmod(rules, excludes),
OUT_KMOD_TEST: emit_kmod_test(tests),
OUT_ZYGISK: rust_body,
OUT_LSP_NATIVE: rust_body,
OUT_LSP_KT: emit_kotlin(rules, excludes),
OUT_LSP_KT_TEST: emit_kotlin_test(tests),
}
)
if __name__ == "__main__":
sys.exit(main())