wuo 0.1.1__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- win_offline_update/__init__.py +1 -0
- win_offline_update/bundle.py +230 -0
- win_offline_update/catalog.py +170 -0
- win_offline_update/cli.py +241 -0
- win_offline_update/downloads.py +280 -0
- win_offline_update/feeds.py +69 -0
- win_offline_update/hooks.py +84 -0
- win_offline_update/models.py +41 -0
- win_offline_update/recovery.cmd.in +215 -0
- win_offline_update/recovery.py +90 -0
- win_offline_update/target.py +105 -0
- win_offline_update/update.py +551 -0
- wuo-0.1.1.dist-info/METADATA +156 -0
- wuo-0.1.1.dist-info/RECORD +17 -0
- wuo-0.1.1.dist-info/WHEEL +4 -0
- wuo-0.1.1.dist-info/entry_points.txt +3 -0
- wuo-0.1.1.dist-info/licenses/LICENSE +674 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""Search and download packages for offline Windows servicing."""
|
|
@@ -0,0 +1,230 @@
|
|
|
1
|
+
"""Package rules and verified recovery bundle preparation."""
|
|
2
|
+
|
|
3
|
+
import json
|
|
4
|
+
import re
|
|
5
|
+
import shutil
|
|
6
|
+
import subprocess
|
|
7
|
+
import tempfile
|
|
8
|
+
from dataclasses import asdict, dataclass
|
|
9
|
+
from pathlib import Path
|
|
10
|
+
from uuid import UUID, uuid4
|
|
11
|
+
|
|
12
|
+
from .downloads import atomic_json, matches_digest, package_hashes, safe_name
|
|
13
|
+
from .hooks import Hook, load_profile
|
|
14
|
+
from .models import Update, UpdateFile
|
|
15
|
+
from .recovery import render_runner
|
|
16
|
+
from .target import TargetIdentity, read_target
|
|
17
|
+
|
|
18
|
+
KB_ID = "950b2422-28ad-4493-a96c-03725fd0d8c2"
|
|
19
|
+
SSU = "SSU-26100.9971-x64.cab"
|
|
20
|
+
SSU_SHA256 = "b86aa6e031fa301464cd119f2f652c4192ad5b344ec6e1b4247d0d9ce528e764"
|
|
21
|
+
PACKAGE_PREFIXES = ("windows11.0-kb5043080-x64_", "windows11.0-kb5132061-x64_")
|
|
22
|
+
JOBS_PATH = Path("ProgramData/WinOfflineUpdate/jobs")
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
@dataclass(frozen=True, slots=True)
|
|
26
|
+
class ServicingPlan:
|
|
27
|
+
files: tuple[UpdateFile, ...]
|
|
28
|
+
commands: tuple[str, ...]
|
|
29
|
+
target_revision: int
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
@dataclass(frozen=True, slots=True)
|
|
33
|
+
class BundlePlan:
|
|
34
|
+
id: str
|
|
35
|
+
update: Update
|
|
36
|
+
target: TargetIdentity
|
|
37
|
+
target_revision: int
|
|
38
|
+
commands: tuple[str, ...]
|
|
39
|
+
hooks: tuple[Hook, ...]
|
|
40
|
+
paths: dict[str, str]
|
|
41
|
+
size: dict[str, int]
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def resolve_plan(update: Update, target: TargetIdentity) -> ServicingPlan:
|
|
45
|
+
if update.id != KB_ID or update.kb != "KB5132061" or update.architecture != "x64":
|
|
46
|
+
raise ValueError("This update currently requires manual servicing.")
|
|
47
|
+
if (target.release, target.build, target.architecture) != (
|
|
48
|
+
"25H2",
|
|
49
|
+
26200,
|
|
50
|
+
"x64",
|
|
51
|
+
) or not 6584 <= target.revision < 9974:
|
|
52
|
+
raise ValueError(
|
|
53
|
+
"KB5132061 requires a supported 25H2 x64 baseline older than 26200.9974."
|
|
54
|
+
)
|
|
55
|
+
selected = []
|
|
56
|
+
for prefix in PACKAGE_PREFIXES:
|
|
57
|
+
candidates = [
|
|
58
|
+
item
|
|
59
|
+
for item in update.files
|
|
60
|
+
if re.fullmatch(re.escape(prefix) + r"[a-f0-9]{40}\.msu", item.name)
|
|
61
|
+
and item.sha256
|
|
62
|
+
]
|
|
63
|
+
if len(candidates) != 1:
|
|
64
|
+
raise ValueError(
|
|
65
|
+
"A Microsoft-verified checkpoint or cumulative package is missing."
|
|
66
|
+
)
|
|
67
|
+
selected.append(candidates[0])
|
|
68
|
+
if len(update.files) != len(selected):
|
|
69
|
+
raise ValueError("Unexpected packages in the Microsoft release file list.")
|
|
70
|
+
return ServicingPlan(tuple(selected), (SSU, f"packages/{selected[-1].name}"), 9974)
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def read_update_id(source: Path) -> str:
|
|
74
|
+
with (source / "manifest.json").open(encoding="utf-8") as stream:
|
|
75
|
+
manifest = json.load(stream)
|
|
76
|
+
try:
|
|
77
|
+
return str(UUID(manifest["update"]["id"]))
|
|
78
|
+
except (KeyError, TypeError, AttributeError, ValueError) as error:
|
|
79
|
+
raise ValueError(
|
|
80
|
+
"No valid Microsoft Catalog update ID in the download manifest."
|
|
81
|
+
) from error
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def prepare(
|
|
85
|
+
update: Update,
|
|
86
|
+
target: TargetIdentity,
|
|
87
|
+
source: Path,
|
|
88
|
+
output: Path,
|
|
89
|
+
*,
|
|
90
|
+
profile: Path | None = None,
|
|
91
|
+
extractor: str = "7z.exe",
|
|
92
|
+
) -> BundlePlan:
|
|
93
|
+
plan = resolve_plan(update, target)
|
|
94
|
+
hooks = load_profile(profile) if profile is not None else ()
|
|
95
|
+
if output.exists():
|
|
96
|
+
raise ValueError("Choose a new directory for the recovery bundle.")
|
|
97
|
+
output.parent.mkdir(parents=True, exist_ok=True)
|
|
98
|
+
job_id = str(uuid4())
|
|
99
|
+
paths: dict[str, str] = {}
|
|
100
|
+
sizes: dict[str, int] = {}
|
|
101
|
+
with tempfile.TemporaryDirectory(dir=output.parent) as scratch:
|
|
102
|
+
bundle = Path(scratch) / "bundle"
|
|
103
|
+
(bundle / "packages").mkdir(parents=True)
|
|
104
|
+
for file in plan.files:
|
|
105
|
+
relative = f"packages/{file.name}"
|
|
106
|
+
path = bundle / relative
|
|
107
|
+
shutil.copyfile(source / file.name, path)
|
|
108
|
+
sha256, sha1 = package_hashes(path)
|
|
109
|
+
if not matches_digest(file, sha256, sha1):
|
|
110
|
+
raise ValueError(f"Microsoft digest mismatch for {file.name}.")
|
|
111
|
+
paths[relative] = sha256
|
|
112
|
+
sizes[relative] = path.stat().st_size
|
|
113
|
+
exe = shutil.which(extractor)
|
|
114
|
+
if exe is None:
|
|
115
|
+
raise ValueError(
|
|
116
|
+
"The Microsoft package requires the 7-Zip command-line extractor."
|
|
117
|
+
)
|
|
118
|
+
extraction = subprocess.run(
|
|
119
|
+
[exe, "e", str(bundle / plan.commands[-1]), SSU, f"-o{bundle}", "-y"],
|
|
120
|
+
capture_output=True,
|
|
121
|
+
check=False,
|
|
122
|
+
)
|
|
123
|
+
cab = bundle / SSU
|
|
124
|
+
if extraction.returncode not in {0, 1} or not cab.is_file():
|
|
125
|
+
raise ValueError(
|
|
126
|
+
f"Could not extract the verified servicing stack (7-Zip {extraction.returncode})."
|
|
127
|
+
)
|
|
128
|
+
digest, _ = package_hashes(cab)
|
|
129
|
+
if digest != SSU_SHA256:
|
|
130
|
+
raise ValueError(
|
|
131
|
+
"Extracted servicing stack does not match the supported package."
|
|
132
|
+
)
|
|
133
|
+
paths[SSU] = digest
|
|
134
|
+
sizes[SSU] = cab.stat().st_size
|
|
135
|
+
result = BundlePlan(
|
|
136
|
+
job_id,
|
|
137
|
+
update,
|
|
138
|
+
target,
|
|
139
|
+
plan.target_revision,
|
|
140
|
+
plan.commands,
|
|
141
|
+
hooks,
|
|
142
|
+
paths,
|
|
143
|
+
sizes,
|
|
144
|
+
)
|
|
145
|
+
if profile is not None:
|
|
146
|
+
snapshot = bundle / "hooks.toml"
|
|
147
|
+
shutil.copyfile(profile, snapshot)
|
|
148
|
+
if load_profile(snapshot) != hooks:
|
|
149
|
+
raise ValueError("The profile changed during preparation.")
|
|
150
|
+
paths[snapshot.name], _ = package_hashes(snapshot)
|
|
151
|
+
script = bundle / "recovery.cmd"
|
|
152
|
+
script.write_bytes(render_runner(result).encode("ascii"))
|
|
153
|
+
paths[script.name], _ = package_hashes(script)
|
|
154
|
+
manifest = asdict(result)
|
|
155
|
+
manifest["target"]["windows"] = str(target.windows)
|
|
156
|
+
atomic_json(bundle / "plan.json", manifest)
|
|
157
|
+
root = target.windows.parent.resolve()
|
|
158
|
+
jobs = root / JOBS_PATH
|
|
159
|
+
if not jobs.resolve().is_relative_to(root):
|
|
160
|
+
raise ValueError(
|
|
161
|
+
"The recovery job directory resolves outside the target Windows volume."
|
|
162
|
+
)
|
|
163
|
+
job = jobs / job_id
|
|
164
|
+
job.mkdir(parents=True)
|
|
165
|
+
marker = job / "target.id"
|
|
166
|
+
try:
|
|
167
|
+
marker.write_bytes(f"{job_id}\r\n".encode("ascii"))
|
|
168
|
+
bundle.rename(output)
|
|
169
|
+
except OSError:
|
|
170
|
+
marker.unlink(missing_ok=True)
|
|
171
|
+
job.rmdir()
|
|
172
|
+
raise
|
|
173
|
+
return result
|
|
174
|
+
|
|
175
|
+
|
|
176
|
+
def verify(bundle: Path, *, post_boot: bool = False) -> None:
|
|
177
|
+
with (bundle / "plan.json").open(encoding="utf-8") as stream:
|
|
178
|
+
manifest = json.load(stream)
|
|
179
|
+
try:
|
|
180
|
+
recorded = manifest["paths"]
|
|
181
|
+
except (KeyError, TypeError) as error:
|
|
182
|
+
raise ValueError("Invalid recovery plan.") from error
|
|
183
|
+
if not isinstance(recorded, dict) or not recorded:
|
|
184
|
+
raise ValueError("The recovery plan has no recorded files.")
|
|
185
|
+
for relative, digest in recorded.items():
|
|
186
|
+
if not isinstance(relative, str) or not isinstance(digest, str):
|
|
187
|
+
raise ValueError("Invalid file or digest in recovery plan.")
|
|
188
|
+
segments = relative.split("/")
|
|
189
|
+
if len(segments) not in {1, 2} or not all(safe_name(part) for part in segments):
|
|
190
|
+
raise ValueError("Unsafe filename in recovery plan.")
|
|
191
|
+
path = bundle / relative
|
|
192
|
+
if (
|
|
193
|
+
not path.is_file()
|
|
194
|
+
or path.is_symlink()
|
|
195
|
+
or not path.resolve().is_relative_to(bundle.resolve())
|
|
196
|
+
):
|
|
197
|
+
raise ValueError(f"Bundle file is missing or unsafe: {relative}")
|
|
198
|
+
actual, _ = package_hashes(path)
|
|
199
|
+
if actual != digest:
|
|
200
|
+
raise ValueError(f"Bundle file digest mismatch: {relative}")
|
|
201
|
+
if post_boot:
|
|
202
|
+
import winreg
|
|
203
|
+
|
|
204
|
+
current = read_target(read_loader=False)
|
|
205
|
+
target = manifest["target"]
|
|
206
|
+
if (
|
|
207
|
+
current.machine_guid != target["machine_guid"]
|
|
208
|
+
or current.build != target["build"]
|
|
209
|
+
or current.revision != manifest["target_revision"]
|
|
210
|
+
):
|
|
211
|
+
raise ValueError(
|
|
212
|
+
f"Expected update not verified on this installation. "
|
|
213
|
+
f"Current build is {current.build}.{current.revision}."
|
|
214
|
+
)
|
|
215
|
+
for hook in manifest["hooks"]:
|
|
216
|
+
if hook["phase"] != "post":
|
|
217
|
+
continue
|
|
218
|
+
root = (
|
|
219
|
+
r"SYSTEM\CurrentControlSet"
|
|
220
|
+
if hook["scope"] == "control-set"
|
|
221
|
+
else "SYSTEM"
|
|
222
|
+
)
|
|
223
|
+
with winreg.OpenKey(
|
|
224
|
+
winreg.HKEY_LOCAL_MACHINE, f"{root}\\{hook['key']}"
|
|
225
|
+
) as key:
|
|
226
|
+
value, kind = winreg.QueryValueEx(key, hook["name"])
|
|
227
|
+
if kind != winreg.REG_DWORD or value != hook["value"]:
|
|
228
|
+
raise ValueError(
|
|
229
|
+
f"Post-boot DWORD assertion failed: {hook['key']} / {hook['name']}"
|
|
230
|
+
)
|
|
@@ -0,0 +1,170 @@
|
|
|
1
|
+
"""Adapter for the Microsoft Update Catalog's public pages."""
|
|
2
|
+
|
|
3
|
+
import base64
|
|
4
|
+
import binascii
|
|
5
|
+
import json
|
|
6
|
+
import re
|
|
7
|
+
from dataclasses import replace
|
|
8
|
+
from uuid import UUID
|
|
9
|
+
|
|
10
|
+
import httpx
|
|
11
|
+
from bs4 import BeautifulSoup
|
|
12
|
+
|
|
13
|
+
from .models import Update, UpdateFile
|
|
14
|
+
|
|
15
|
+
CATALOG = "https://www.catalog.update.microsoft.com"
|
|
16
|
+
UPDATE_LINK = re.compile(r"^([a-f0-9-]{36})_link$", re.IGNORECASE)
|
|
17
|
+
FILE_FIELD = re.compile(
|
|
18
|
+
r"^\s*downloadInformation\[0\]\.files\[(\d+)\]\."
|
|
19
|
+
r"(url|fileName|digest|sha256)\s*=\s*'([^'\r\n]*)';",
|
|
20
|
+
re.MULTILINE,
|
|
21
|
+
)
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
class SourceError(ValueError):
|
|
25
|
+
"""A provider returned an unavailable or unrecognized result."""
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def _update(
|
|
29
|
+
update_id: str, title: str, product: str, kind: str, date: str = ""
|
|
30
|
+
) -> Update:
|
|
31
|
+
arch = re.search(r"\b(arm64|x64|x86)(?:\b|_)", title, re.IGNORECASE)
|
|
32
|
+
kb = re.search(r"\bKB\d+\b", title, re.IGNORECASE)
|
|
33
|
+
route = "See the Microsoft release notes for installation instructions."
|
|
34
|
+
if kind.casefold() == "drivers":
|
|
35
|
+
route = "Extract the driver package and identify its signed INF and matching hardware."
|
|
36
|
+
elif kind.casefold() == "upgrades":
|
|
37
|
+
route = (
|
|
38
|
+
"Use the supported Windows Setup or enablement workflow for this update."
|
|
39
|
+
)
|
|
40
|
+
elif "defender" in title.casefold() or "security platform" in title.casefold():
|
|
41
|
+
route = (
|
|
42
|
+
"Follow the Microsoft instructions for this security component in Windows."
|
|
43
|
+
)
|
|
44
|
+
return Update(
|
|
45
|
+
update_id,
|
|
46
|
+
title,
|
|
47
|
+
product,
|
|
48
|
+
arch.group(1).lower() if arch else None,
|
|
49
|
+
kind,
|
|
50
|
+
date,
|
|
51
|
+
kb.group().upper() if kb else None,
|
|
52
|
+
details_url=f"{CATALOG}/ScopedViewInline.aspx?updateid={update_id}",
|
|
53
|
+
route=route,
|
|
54
|
+
)
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def parse_search(html: str) -> list[Update]:
|
|
58
|
+
page = BeautifulSoup(html, "html.parser")
|
|
59
|
+
results = []
|
|
60
|
+
for link in page.find_all("a", id=UPDATE_LINK):
|
|
61
|
+
match = UPDATE_LINK.fullmatch(str(link["id"]))
|
|
62
|
+
row = link.find_parent("tr")
|
|
63
|
+
if match is None or row is None:
|
|
64
|
+
raise SourceError("Microsoft Catalog search result is missing its row.")
|
|
65
|
+
columns = row.find_all("td", recursive=False)
|
|
66
|
+
if len(columns) < 5:
|
|
67
|
+
raise SourceError("Microsoft Catalog search columns changed.")
|
|
68
|
+
product, kind, date = (cell.get_text(strip=True) for cell in columns[2:5])
|
|
69
|
+
results.append(
|
|
70
|
+
_update(match.group(1), link.get_text(strip=True), product, kind, date)
|
|
71
|
+
)
|
|
72
|
+
if not results and page.find(id="ctl00_catalogBody_noResults") is None:
|
|
73
|
+
raise SourceError("Could not interpret the Microsoft Catalog search response.")
|
|
74
|
+
return results
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def _decode_digest(value: str, expected_length: int) -> str | None:
|
|
78
|
+
if not value:
|
|
79
|
+
return None
|
|
80
|
+
try:
|
|
81
|
+
digest = base64.b64decode(value, validate=True)
|
|
82
|
+
except binascii.Error as error:
|
|
83
|
+
raise SourceError("Microsoft Catalog supplied an invalid digest.") from error
|
|
84
|
+
if len(digest) != expected_length:
|
|
85
|
+
raise SourceError(
|
|
86
|
+
"Microsoft Catalog supplied a digest with an unexpected length."
|
|
87
|
+
)
|
|
88
|
+
return digest.hex()
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def parse_files(html: str) -> tuple[UpdateFile, ...]:
|
|
92
|
+
fields: dict[int, dict[str, str]] = {}
|
|
93
|
+
for index, name, value in FILE_FIELD.findall(html):
|
|
94
|
+
record = fields.setdefault(int(index), {})
|
|
95
|
+
if name in record:
|
|
96
|
+
raise SourceError("Microsoft Catalog listed the same file field twice.")
|
|
97
|
+
record[name] = value
|
|
98
|
+
if not fields or sorted(fields) != list(range(len(fields))):
|
|
99
|
+
raise SourceError("Could not resolve the complete Microsoft Catalog file list.")
|
|
100
|
+
files = []
|
|
101
|
+
for index in range(len(fields)):
|
|
102
|
+
record = fields[index]
|
|
103
|
+
if not record.get("url") or not record.get("fileName"):
|
|
104
|
+
raise SourceError("Microsoft Catalog file entry is incomplete.")
|
|
105
|
+
files.append(
|
|
106
|
+
UpdateFile(
|
|
107
|
+
record["fileName"],
|
|
108
|
+
record["url"],
|
|
109
|
+
_decode_digest(record.get("sha256", ""), 32),
|
|
110
|
+
_decode_digest(record.get("digest", ""), 20),
|
|
111
|
+
)
|
|
112
|
+
)
|
|
113
|
+
return tuple(files)
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
async def search(client: httpx.AsyncClient, query: str) -> list[Update]:
|
|
117
|
+
response = await client.get(f"{CATALOG}/Search.aspx", params={"q": query})
|
|
118
|
+
response.raise_for_status()
|
|
119
|
+
return parse_search(response.text)
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
async def show(client: httpx.AsyncClient, update_id: str) -> Update:
|
|
123
|
+
try:
|
|
124
|
+
update_id = str(UUID(update_id))
|
|
125
|
+
except ValueError as error:
|
|
126
|
+
raise SourceError(
|
|
127
|
+
"Use a Microsoft Catalog update ID from the search results."
|
|
128
|
+
) from error
|
|
129
|
+
response = await client.get(
|
|
130
|
+
f"{CATALOG}/ScopedViewInline.aspx", params={"updateid": update_id}
|
|
131
|
+
)
|
|
132
|
+
if response.status_code == 404 or (
|
|
133
|
+
response.is_redirect
|
|
134
|
+
and response.headers.get("Location", "").startswith("/Thanks.aspx?")
|
|
135
|
+
):
|
|
136
|
+
raise SourceError(f"No public Microsoft Catalog entry for offer {update_id}.")
|
|
137
|
+
response.raise_for_status()
|
|
138
|
+
page = BeautifulSoup(response.text, "html.parser")
|
|
139
|
+
title = page.find(id="ScopedViewHandler_titleText")
|
|
140
|
+
if title is None or not title.get_text(strip=True):
|
|
141
|
+
raise SourceError(f"Microsoft Catalog has no details for {update_id}.")
|
|
142
|
+
|
|
143
|
+
def field(name: str, label: str) -> str:
|
|
144
|
+
node = page.find(id=name)
|
|
145
|
+
return (
|
|
146
|
+
node.get_text(" ", strip=True).removeprefix(label).strip() if node else ""
|
|
147
|
+
)
|
|
148
|
+
|
|
149
|
+
update = _update(
|
|
150
|
+
update_id,
|
|
151
|
+
title.get_text(" ", strip=True),
|
|
152
|
+
field("productsDiv", "Supported products:"),
|
|
153
|
+
field("classificationDiv", "Classification:"),
|
|
154
|
+
)
|
|
155
|
+
architecture = field("archDiv", "Architecture:").casefold()
|
|
156
|
+
declared = {
|
|
157
|
+
"amd64": "x64",
|
|
158
|
+
"x64": "x64",
|
|
159
|
+
"arm64": "arm64",
|
|
160
|
+
"x86": "x86",
|
|
161
|
+
"arm": "arm",
|
|
162
|
+
}.get(architecture)
|
|
163
|
+
if declared:
|
|
164
|
+
update = replace(update, architecture=declared)
|
|
165
|
+
request = [{"size": 0, "updateID": update_id, "uidInfo": update_id}]
|
|
166
|
+
dialog = await client.post(
|
|
167
|
+
f"{CATALOG}/DownloadDialog.aspx", data={"updateIDs": json.dumps(request)}
|
|
168
|
+
)
|
|
169
|
+
dialog.raise_for_status()
|
|
170
|
+
return replace(update, files=parse_files(dialog.text))
|
|
@@ -0,0 +1,241 @@
|
|
|
1
|
+
"""Command-line entry point."""
|
|
2
|
+
|
|
3
|
+
import argparse
|
|
4
|
+
import asyncio
|
|
5
|
+
import json
|
|
6
|
+
import sys
|
|
7
|
+
from collections.abc import Sequence
|
|
8
|
+
from dataclasses import asdict
|
|
9
|
+
from pathlib import Path
|
|
10
|
+
|
|
11
|
+
lazy import httpx
|
|
12
|
+
|
|
13
|
+
from .models import DownloadManifest, Update
|
|
14
|
+
lazy from . import bundle, catalog, downloads, feeds, target
|
|
15
|
+
lazy from .update import run_update
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def _write_updates(updates: list[Update], *, json_output: bool) -> None:
|
|
19
|
+
if json_output:
|
|
20
|
+
print(json.dumps([asdict(update) for update in updates], indent=2))
|
|
21
|
+
return
|
|
22
|
+
if not updates:
|
|
23
|
+
print("No matches on the first Microsoft Catalog results page.")
|
|
24
|
+
for update in updates:
|
|
25
|
+
print(f"{update.id} {update.title}")
|
|
26
|
+
details = [
|
|
27
|
+
update.product,
|
|
28
|
+
update.architecture or "",
|
|
29
|
+
update.classification,
|
|
30
|
+
update.date,
|
|
31
|
+
]
|
|
32
|
+
print(f" {' | '.join(filter(None, details))} | {update.source}")
|
|
33
|
+
if update.files:
|
|
34
|
+
print(f" {update.route}")
|
|
35
|
+
print(f" Details: {update.details_url}")
|
|
36
|
+
for file in update.files:
|
|
37
|
+
print(f" {file.name}\n {file.url}")
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
async def _resolve(client: httpx.AsyncClient, update_id: str) -> Update:
|
|
41
|
+
if update_id.startswith("defender-"):
|
|
42
|
+
return feeds.defender(update_id.removeprefix("defender-"))
|
|
43
|
+
return await catalog.show(client, update_id)
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
async def _run(args: argparse.Namespace) -> int:
|
|
47
|
+
async with httpx.AsyncClient(timeout=httpx.Timeout(30.0, connect=10.0)) as client:
|
|
48
|
+
if args.command == "update":
|
|
49
|
+
identity = await asyncio.to_thread(target.read_target, read_loader=False)
|
|
50
|
+
return await run_update(
|
|
51
|
+
client,
|
|
52
|
+
identity,
|
|
53
|
+
args.output or Path.home() / "Downloads/WindowsOfflineUpdates",
|
|
54
|
+
only=tuple(args.only),
|
|
55
|
+
dry_run=args.dry_run,
|
|
56
|
+
profile=args.profile,
|
|
57
|
+
extractor=args.extractor,
|
|
58
|
+
)
|
|
59
|
+
if args.command == "search":
|
|
60
|
+
updates = await catalog.search(client, args.query)
|
|
61
|
+
updates = [
|
|
62
|
+
item
|
|
63
|
+
for item in updates
|
|
64
|
+
if (args.arch is None or args.arch == item.architecture)
|
|
65
|
+
and (
|
|
66
|
+
args.product is None
|
|
67
|
+
or args.product.casefold() in item.product.casefold()
|
|
68
|
+
)
|
|
69
|
+
and (
|
|
70
|
+
args.kind is None
|
|
71
|
+
or args.kind.casefold() in item.classification.casefold()
|
|
72
|
+
)
|
|
73
|
+
]
|
|
74
|
+
elif args.command == "latest":
|
|
75
|
+
if args.defender:
|
|
76
|
+
updates = [feeds.defender(args.arch)]
|
|
77
|
+
elif args.release:
|
|
78
|
+
updates = [await feeds.latest(client, args.release.upper(), args.arch)]
|
|
79
|
+
else:
|
|
80
|
+
raise ValueError(
|
|
81
|
+
"Supply --release for a cumulative update or use --defender."
|
|
82
|
+
)
|
|
83
|
+
elif args.command == "show":
|
|
84
|
+
updates = [await _resolve(client, args.update_id)]
|
|
85
|
+
elif args.command == "prepare":
|
|
86
|
+
update_id = args.update_id or await asyncio.to_thread(
|
|
87
|
+
bundle.read_update_id, args.download
|
|
88
|
+
)
|
|
89
|
+
selected = await _resolve(client, update_id)
|
|
90
|
+
identity = await asyncio.to_thread(target.read_target)
|
|
91
|
+
plan = await asyncio.to_thread(
|
|
92
|
+
bundle.prepare,
|
|
93
|
+
selected,
|
|
94
|
+
identity,
|
|
95
|
+
args.download,
|
|
96
|
+
args.output,
|
|
97
|
+
profile=args.profile,
|
|
98
|
+
extractor=args.extractor,
|
|
99
|
+
)
|
|
100
|
+
print(
|
|
101
|
+
f"Prepared {selected.kb} for Windows {identity.release} ({identity.build}.{identity.revision})."
|
|
102
|
+
)
|
|
103
|
+
print(f"Package order: {' then '.join(plan.commands)}")
|
|
104
|
+
print(f"Configured registry hooks: {len(plan.hooks)}")
|
|
105
|
+
return 0
|
|
106
|
+
else:
|
|
107
|
+
selected = await _resolve(client, args.update_id)
|
|
108
|
+
print(
|
|
109
|
+
f"Downloading {len(selected.files)} package(s) for {selected.title}",
|
|
110
|
+
file=sys.stderr,
|
|
111
|
+
)
|
|
112
|
+
result: DownloadManifest = await downloads.download(
|
|
113
|
+
client, selected, args.output, concurrency=args.jobs
|
|
114
|
+
)
|
|
115
|
+
if args.json:
|
|
116
|
+
print(json.dumps(asdict(result), indent=2))
|
|
117
|
+
else:
|
|
118
|
+
print(
|
|
119
|
+
f"Saved {len(result.files)} package(s) and manifest.json to {args.output.resolve()}"
|
|
120
|
+
)
|
|
121
|
+
return 0
|
|
122
|
+
_write_updates(updates, json_output=args.json)
|
|
123
|
+
return 0
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
def main(argv: Sequence[str] | None = None) -> int:
|
|
127
|
+
parser = argparse.ArgumentParser(
|
|
128
|
+
prog="wuo",
|
|
129
|
+
description="Find Windows updates and prepare them for offline servicing.",
|
|
130
|
+
)
|
|
131
|
+
commands = parser.add_subparsers(dest="command")
|
|
132
|
+
workflow = commands.add_parser(
|
|
133
|
+
"update",
|
|
134
|
+
help="Find applicable updates, download them and prepare supported WinRE bundles.",
|
|
135
|
+
)
|
|
136
|
+
workflow.add_argument(
|
|
137
|
+
"--only",
|
|
138
|
+
action="append",
|
|
139
|
+
default=[],
|
|
140
|
+
choices=(
|
|
141
|
+
"monthly",
|
|
142
|
+
"features",
|
|
143
|
+
"dotnet",
|
|
144
|
+
"drivers",
|
|
145
|
+
"defender",
|
|
146
|
+
"security-platform",
|
|
147
|
+
"other",
|
|
148
|
+
),
|
|
149
|
+
help="Limit the run to this category. Repeat to select multiple categories.",
|
|
150
|
+
)
|
|
151
|
+
workflow.add_argument(
|
|
152
|
+
"--dry-run",
|
|
153
|
+
action="store_true",
|
|
154
|
+
help="Resolve offers without downloading packages or writing a bundle.",
|
|
155
|
+
)
|
|
156
|
+
workflow.add_argument(
|
|
157
|
+
"--output",
|
|
158
|
+
type=Path,
|
|
159
|
+
help="Destination (default: ~/Downloads/WindowsOfflineUpdates).",
|
|
160
|
+
)
|
|
161
|
+
workflow.add_argument(
|
|
162
|
+
"--profile",
|
|
163
|
+
type=Path,
|
|
164
|
+
help="Optional local registry-hook TOML for recovery bundles.",
|
|
165
|
+
)
|
|
166
|
+
workflow.add_argument(
|
|
167
|
+
"--extractor", default="7z.exe", help="Path to the 7-Zip CLI."
|
|
168
|
+
)
|
|
169
|
+
search = commands.add_parser(
|
|
170
|
+
"search", help="Find published Microsoft Catalog updates."
|
|
171
|
+
)
|
|
172
|
+
search.add_argument("query", help="KB number, title, or quoted hardware ID.")
|
|
173
|
+
search.add_argument("--arch", choices=("x64", "arm64", "x86"))
|
|
174
|
+
search.add_argument("--product")
|
|
175
|
+
search.add_argument(
|
|
176
|
+
"--kind", help="Match a Catalog classification such as Drivers."
|
|
177
|
+
)
|
|
178
|
+
show = commands.add_parser("show", help="Show details and every standalone file.")
|
|
179
|
+
show.add_argument("update_id")
|
|
180
|
+
download = commands.add_parser(
|
|
181
|
+
"download", help="Download all files for a selected update."
|
|
182
|
+
)
|
|
183
|
+
download.add_argument("update_id")
|
|
184
|
+
download.add_argument("--output", type=Path, required=True)
|
|
185
|
+
download.add_argument("--jobs", type=int, default=3)
|
|
186
|
+
latest = commands.add_parser(
|
|
187
|
+
"latest", help="Find a cumulative or Defender intelligence update."
|
|
188
|
+
)
|
|
189
|
+
latest.add_argument("--release", help="Windows release, for example 25H2.")
|
|
190
|
+
latest.add_argument("--arch", choices=("x64", "arm64", "x86"), default="x64")
|
|
191
|
+
latest.add_argument("--defender", action="store_true")
|
|
192
|
+
commands.add_parser(
|
|
193
|
+
"media", help="Show Microsoft's full Windows Setup media download page."
|
|
194
|
+
)
|
|
195
|
+
prepare = commands.add_parser(
|
|
196
|
+
"prepare", help="Prepare a verified offline servicing bundle."
|
|
197
|
+
)
|
|
198
|
+
prepare.add_argument(
|
|
199
|
+
"--download", type=Path, required=True, help="Folder containing package files."
|
|
200
|
+
)
|
|
201
|
+
prepare.add_argument(
|
|
202
|
+
"--update-id", help="Microsoft Catalog ID when importing existing packages."
|
|
203
|
+
)
|
|
204
|
+
prepare.add_argument(
|
|
205
|
+
"--output", type=Path, required=True, help="New recovery bundle directory."
|
|
206
|
+
)
|
|
207
|
+
prepare.add_argument(
|
|
208
|
+
"--profile", type=Path, help="Optional local registry-hook TOML."
|
|
209
|
+
)
|
|
210
|
+
prepare.add_argument("--extractor", default="7z.exe", help="Path to the 7-Zip CLI.")
|
|
211
|
+
verify = commands.add_parser(
|
|
212
|
+
"verify", help="Verify recovery bundle files and optional post-boot state."
|
|
213
|
+
)
|
|
214
|
+
verify.add_argument("--bundle", type=Path, required=True)
|
|
215
|
+
verify.add_argument("--post-boot", action="store_true")
|
|
216
|
+
for command in (search, show, download, latest):
|
|
217
|
+
command.add_argument(
|
|
218
|
+
"--json", action="store_true", help="Print machine-readable results."
|
|
219
|
+
)
|
|
220
|
+
try:
|
|
221
|
+
args = parser.parse_args(argv)
|
|
222
|
+
except SystemExit as result:
|
|
223
|
+
return int(result.code) if isinstance(result.code, int) else 1
|
|
224
|
+
if args.command is None:
|
|
225
|
+
parser.print_help()
|
|
226
|
+
return 0
|
|
227
|
+
if args.command == "media":
|
|
228
|
+
print(feeds.WINDOWS_MEDIA)
|
|
229
|
+
return 0
|
|
230
|
+
try:
|
|
231
|
+
if args.command == "verify":
|
|
232
|
+
bundle.verify(args.bundle, post_boot=args.post_boot)
|
|
233
|
+
print("Verification passed.")
|
|
234
|
+
return 0
|
|
235
|
+
return asyncio.run(_run(args))
|
|
236
|
+
except (ValueError, OSError, httpx.HTTPError) as error:
|
|
237
|
+
print(f"win-offline-update: {error}", file=sys.stderr)
|
|
238
|
+
return 1
|
|
239
|
+
except KeyboardInterrupt:
|
|
240
|
+
print("Download or lookup canceled.", file=sys.stderr)
|
|
241
|
+
return 130
|