Repository navigation
Expand file tree
/
Copy pathbuild.py
More file actions
executable file
·180 lines (148 loc) · 6.29 KB
/
Copy pathbuild.py
File metadata and controls
executable file
·180 lines (148 loc) · 6.29 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
#!/usr/bin/env python3
import argparse
import gzip
import hashlib
import json
import shutil
import struct
import tarfile
import tempfile
import urllib.request
from pathlib import Path
ROOT = Path(__file__).resolve().parent
EXPECTED_MODULE = "fastnet"
EM_AARCH64 = 183
PT_INTERP = 3
def digest(path, algorithm):
checksum = hashlib.new(algorithm)
with Path(path).open("rb") as reader:
for chunk in iter(lambda: reader.read(1024 * 1024), b""):
checksum.update(chunk)
return checksum.hexdigest()
def load_config(root):
return json.loads((Path(root) / "config.json.js").read_text(encoding="utf-8"))
def write_config(root, config):
(Path(root) / "config.json.js").write_text(
json.dumps(config, sort_keys=True, indent=4, ensure_ascii=False) + "\n",
encoding="utf-8",
)
def validate_module_name(module):
if module != EXPECTED_MODULE:
raise ValueError(f"module must be {EXPECTED_MODULE}")
def safe_extract(archive_path, destination):
destination = Path(destination).resolve()
with tarfile.open(archive_path, "r:*") as archive:
for member in archive.getmembers():
member_path = Path(member.name)
target = (destination / member_path).resolve()
if (
member_path.is_absolute()
or ".." in member_path.parts
or (target != destination and destination not in target.parents)
or not (member.isdir() or member.isfile())
):
raise ValueError(f"unsafe artifact member: {member.name}")
archive.extractall(destination, filter="data")
def validate_aarch64_static_elf(path):
data = Path(path).read_bytes()
if len(data) < 64 or data[:4] != b"\x7fELF" or data[4] != 2:
raise ValueError("runtime must be a static aarch64 ELF")
endian = "<" if data[5] == 1 else ">" if data[5] == 2 else None
if endian is None or struct.unpack_from(endian + "H", data, 18)[0] != EM_AARCH64:
raise ValueError("runtime must be a static aarch64 ELF")
program_offset = struct.unpack_from(endian + "Q", data, 32)[0]
program_size = struct.unpack_from(endian + "H", data, 54)[0]
program_count = struct.unpack_from(endian + "H", data, 56)[0]
for index in range(program_count):
offset = program_offset + index * program_size
if offset + 4 > len(data):
raise ValueError("runtime has an invalid ELF program table")
if struct.unpack_from(endian + "I", data, offset)[0] == PT_INTERP:
raise ValueError("runtime must be a static aarch64 ELF")
def download(url, destination):
with urllib.request.urlopen(url, timeout=120) as response:
with Path(destination).open("wb") as writer:
shutil.copyfileobj(response, writer)
def stage_runtime(root, module_dir, config, runtime_archive=None):
expected = str(config.get("artifact_sha256", "")).strip().lower()
if len(expected) != 64:
raise ValueError("artifact_sha256 must be a SHA-256 checksum")
with tempfile.TemporaryDirectory(prefix=".fastnet-runtime-", dir=root) as temp_dir:
temp = Path(temp_dir)
archive = Path(runtime_archive) if runtime_archive else temp / "runtime.tar.gz"
if runtime_archive is None:
url = str(config.get("artifact_url", "")).strip()
if not url:
raise ValueError("artifact_url is required")
download(url, archive)
if digest(archive, "sha256").lower() != expected:
raise ValueError("runtime artifact sha256 mismatch")
extracted = temp / "extracted"
extracted.mkdir()
safe_extract(archive, extracted)
runtime = extracted / f"fastnet-binary-{config['runtime_version']}" / "FastNet.aarch64"
if not runtime.is_file():
raise FileNotFoundError(f"missing aarch64 runtime: {runtime.name}")
validate_aarch64_static_elf(runtime)
bin_dir = module_dir / "bin"
bin_dir.mkdir(parents=True, exist_ok=True)
compressed = bin_dir / "fastnet_bin.gz"
with runtime.open("rb") as source, compressed.open("wb") as raw_output:
with gzip.GzipFile(
filename="",
mode="wb",
compresslevel=9,
fileobj=raw_output,
mtime=0,
) as output:
shutil.copyfileobj(source, output)
return compressed
def package_module(root, module_dir):
package_path = Path(root) / "fastnet.tar.gz"
if package_path.exists():
package_path.unlink()
def normalize_member(member):
if Path(member.name).name == ".gitkeep":
return None
member.uid = 0
member.gid = 0
member.uname = ""
member.gname = ""
member.mtime = 0
if member.isdir():
member.mode = 0o755
elif member.isfile():
member.mode = 0o755 if member.mode & 0o111 else 0o644
return member
with package_path.open("wb") as raw_output:
with gzip.GzipFile(
filename="",
mode="wb",
compresslevel=9,
fileobj=raw_output,
mtime=0,
) as compressed_output:
with tarfile.open(fileobj=compressed_output, mode="w") as package:
package.add(module_dir, arcname=module_dir.name, filter=normalize_member)
return package_path
def build_module(root=ROOT, runtime_archive=None):
root = Path(root)
config = load_config(root)
validate_module_name(config.get("module"))
module_dir = root / EXPECTED_MODULE
if not module_dir.is_dir():
raise FileNotFoundError(f"missing module directory: {module_dir}")
stage_runtime(root, module_dir, config, runtime_archive=runtime_archive)
(module_dir / "version").write_text(config["version"] + "\n", encoding="utf-8")
package = package_module(root, module_dir)
config["md5"] = digest(package, "md5")
write_config(root, config)
return config
def main():
parser = argparse.ArgumentParser(description="Build the FastNet ASUSWRT package")
parser.add_argument("--runtime-archive", help="Use a local pinned FastNet runtime archive")
args = parser.parse_args()
config = build_module(runtime_archive=args.runtime_archive)
print(f"build done fastnet.tar.gz md5={config['md5']}")
if __name__ == "__main__":
main()