Repository navigation
Expand file tree
/
Copy pathwire-web.py
More file actions
323 lines (296 loc) · 24.8 KB
/
Copy pathwire-web.py
File metadata and controls
323 lines (296 loc) · 24.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
"""Authenticated LAN web console for a self-hosted Wire server."""
from __future__ import annotations
import base64, binascii, hashlib, hmac, html, json, os, secrets, socket, struct, threading, time, zipfile
from http import cookies
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path
from urllib.parse import parse_qs, urlparse
from cryptography.fernet import Fernet, InvalidToken
STATE = Path(os.environ.get("WIRE_STATE", "/data"))
BACKUPS = Path(os.environ.get("WIRE_BACKUP_DIR", "/backups"))
STARTED = time.time(); SESSION_TTL = 12 * 60 * 60; MAX_SESSIONS = 256
SESSIONS: dict[str, tuple[str, float]] = {}; ATTEMPTS: dict[str, list[float]] = {}; LOCK = threading.Lock()
TURN_PROBE_HOST = os.environ.get("WIRE_TURN_PROBE_HOST", "").strip()
TURN_PROBE_PORT = int(os.environ.get("WIRE_TURN_PROBE_PORT", "3478"))
MAX_WEB_CONNECTIONS = 32
def load(name, fallback):
try:
value = json.loads((STATE / name).read_text(encoding="utf-8"))
return value if isinstance(value, type(fallback)) else fallback
except (OSError, ValueError): return fallback
def esc(value): return html.escape(str(value))
def backup_inventory(limit=8):
"""Return recent backup metadata and verify every displayed archive."""
archives = []
for item in BACKUPS.glob("wire-state-*.zip"):
try: archives.append((item.stat().st_mtime, item))
except OSError: continue
archives.sort(key=lambda item: item[0], reverse=True)
entries = []
for _, latest in archives[:limit]:
try:
stat = latest.stat()
with zipfile.ZipFile(latest) as archive:
manifest_entry = archive.getinfo("manifest.json")
if manifest_entry.file_size > 1024 * 1024: raise ValueError("oversized manifest")
manifest = json.loads(archive.read(manifest_entry))
hashes = manifest.get("files") if manifest.get("format") == 1 else None
if not isinstance(hashes, dict) or not hashes or len(hashes) > 32: raise ValueError("invalid manifest")
infos = {item.filename: item for item in archive.infolist()}
for name, expected in hashes.items():
if not isinstance(name, str) or not isinstance(expected, str): raise ValueError("invalid checksum")
entry = infos.get(f"state/{name}")
if entry is None or entry.file_size > 512 * 1024 * 1024: raise ValueError("unsafe backup entry")
digest = hashlib.sha256()
with archive.open(entry) as source:
while chunk := source.read(1024 * 1024): digest.update(chunk)
actual = digest.hexdigest()
if not hmac.compare_digest(actual, expected): raise ValueError("checksum mismatch")
ok = True
except (OSError, KeyError, ValueError, zipfile.BadZipFile, json.JSONDecodeError):
ok = False
try: stat = latest.stat()
except OSError: continue
entries.append({"name": latest.name, "ok": ok, "age": max(0, int(time.time() - stat.st_mtime)),
"size": stat.st_size})
return entries
def verify_latest_backup():
entries = backup_inventory()
latest = entries[0] if entries else None
return {"count": len(list(BACKUPS.glob("wire-state-*.zip"))), "ok": bool(latest and latest["ok"]),
"age": latest["age"] if latest else None, "name": latest["name"] if latest else None}
def turn_reachable(host=None, port=None, timeout=0.6):
"""Probe the configured local Coturn listener with a STUN binding request."""
host, port = host or TURN_PROBE_HOST, port or TURN_PROBE_PORT
if not host: return None
transaction = os.urandom(12)
request = struct.pack("!HHI12s", 1, 0, 0x2112A442, transaction)
connection = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
connection.settimeout(timeout)
try:
connection.sendto(request, (host, int(port)))
response, _ = connection.recvfrom(2048)
return len(response) >= 20 and response[:2] == b"\x01\x01" and response[8:20] == transaction
except (OSError, ValueError):
return False
finally:
connection.close()
def server_security_status(backups=None):
backups = backup_inventory() if backups is None else backups
latest = backups[0] if backups else None
backup = {"count": len(backups), "ok": bool(latest and latest["ok"]),
"age": latest["age"] if latest else None, "name": latest["name"] if latest else None}
required = ("server-signing-key", "server-certificate.pem", "server-tls-key.pem")
identity_ok = all((STATE / name).is_file() and (STATE / name).stat().st_size > 0 for name in required)
return {"identity": identity_ok, "turn": turn_reachable(), "backup": backup}
STYLE = """
:root{--bg:#07090d;--panel:#0d1219;--card:#121922;--line:#252e3b;--text:#f4f7fb;--muted:#8e9aac;--mint:#6ee7c8;--blue:#79a8ff;--danger:#ff8e9a}*{box-sizing:border-box}body{margin:0;background:radial-gradient(circle at 80% -10%,#173f40,transparent 32%),var(--bg);color:var(--text);font:15px Inter,Segoe UI,system-ui,sans-serif;min-height:100vh}.shell{display:grid;grid-template-columns:250px 1fr;min-height:100vh}aside{border-right:1px solid var(--line);padding:28px 18px;background:#090c11ee;position:sticky;top:0;height:100vh}.brand{font-size:22px;font-weight:900;letter-spacing:.18em;margin:0 10px 36px}.brand i{display:inline-block;width:11px;height:11px;border-radius:50%;background:var(--mint);box-shadow:0 0 22px var(--mint);margin-right:11px}nav{display:grid;gap:6px}nav a{color:var(--muted);padding:12px 14px;border-radius:11px;text-decoration:none}nav a:hover{background:#121a23;color:var(--text)}nav a.on{background:var(--mint);color:#07110f;font-weight:800}.logout{position:absolute;bottom:25px;left:18px;right:18px}.logout button{margin:0;background:#141b24;color:var(--muted);border:1px solid var(--line)}main{padding:42px;max-width:1220px;width:100%;margin:auto}header{display:flex;justify-content:space-between;align-items:end;margin-bottom:28px}h1{font-size:32px;margin:0 0 6px}h2{font-size:17px;margin:0 0 17px}.muted,small{color:var(--muted)}.live,.pill{display:inline-flex;border:1px solid #31574e;background:#10221e;color:var(--mint);padding:7px 12px;border-radius:999px;font-weight:700}.pill{padding:4px 9px;font-size:12px}.grid{display:grid;grid-template-columns:repeat(12,1fr);gap:16px}.card{grid-column:span 4;background:linear-gradient(145deg,#131a23,#0d1218);border:1px solid var(--line);border-radius:18px;padding:22px;box-shadow:0 18px 50px #0004}.wide{grid-column:span 8}.full{grid-column:1/-1}.num{font-size:34px;font-weight:850;margin-top:8px}.list-row{display:flex;align-items:center;justify-content:space-between;gap:14px;padding:13px 2px;border-bottom:1px solid #1d2631}.list-row:last-child{border:0}.person{display:flex;align-items:center;gap:13px}.avatar{display:grid;place-items:center;width:40px;height:40px;border-radius:12px;background:#1b2c31;color:var(--mint);font-weight:850}.stack{display:flex;flex-direction:column;gap:3px}.note{color:#b5bfcc;line-height:1.7}.ok{color:var(--mint)}.bad{color:var(--danger)}.metric{display:flex;justify-content:space-between;padding:10px 0;border-bottom:1px solid #1d2631}.metric:last-child{border:0}.login{width:min(430px,calc(100% - 32px));margin:12vh auto;padding:36px}.login.card{display:block}label{display:block;color:var(--muted);margin:18px 0 7px}input{width:100%;border:1px solid var(--line);border-radius:11px;padding:13px 14px;background:#090d12;color:var(--text);font:inherit;outline:none}input:focus{border-color:var(--mint)}button{width:100%;margin-top:22px;padding:13px;border:0;border-radius:11px;background:var(--mint);color:#07110f;font-weight:850;font:inherit;cursor:pointer}.error{color:var(--danger);margin-top:16px}.empty{padding:22px;text-align:center;color:var(--muted);border:1px dashed var(--line);border-radius:13px}@media(max-width:780px){.shell{display:block}aside{height:auto;position:static;border-right:0;border-bottom:1px solid var(--line);padding:18px}.brand{margin:0 0 14px}nav{grid-template-columns:repeat(5,1fr)}nav a{text-align:center;padding:10px 4px;font-size:12px}.logout{position:static;margin-top:12px}main{padding:24px 16px}.card,.wide{grid-column:1/-1}header{align-items:start}.live{font-size:12px}}
"""
def shell(content, title="Wire"):
return f'<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>{esc(title)}</title><style>{STYLE}</style></head><body>{content}</body></html>'.encode()
def login_page(error=""):
message = f'<p class="error">{esc(error)}</p>' if error else ""
return shell(f'<section class="card login"><div class="brand"><i></i>WIRE</div><h1>Welcome back</h1><p class="muted">Sign in with your existing Wire account.</p><form method="post" action="/login"><label>Username</label><input name="username" minlength="3" maxlength="24" required autocomplete="username"><label>Password</label><input name="password" type="password" required autocomplete="current-password"><button>Sign in</button>{message}</form></section>', "Sign in · Wire")
def verify_account(username, password):
backup = load("identity-backups.json", {}).get(username.lower())
if not isinstance(backup, dict): return None
try:
# Accounts created before KDF metadata was stored use the client's
# legacy scrypt parameters. Matching that exact fallback is required:
# choosing a newer default derives a different key and rejects the
# user's otherwise-correct password.
kdf = backup.get("kdf") or {}; n, r, p = int(kdf.get("n", 2**14)), int(kdf.get("r", 8)), int(kdf.get("p", 1))
# Match the client whitelist exactly. Merely bounding each number still
# permits combinations whose memory/work cost can exhaust the web host.
if n not in (2**14, 2**15, 2**16, 2**17) or r != 8 or not 1 <= p <= 5: return None
salt = base64.b64decode(backup["salt"], validate=True)
secret = hashlib.scrypt(password.encode(), salt=salt, n=n, r=r, p=p, dklen=32)
account = json.loads(Fernet(base64.urlsafe_b64encode(secret)).decrypt(backup["ciphertext"].encode()))
return account if isinstance(account, dict) and str(account.get("name", "")).lower() == username.lower() else None
except (KeyError, ValueError, TypeError, InvalidToken, json.JSONDecodeError): return None
def allow_attempt(address):
now = time.monotonic()
with LOCK:
recent = [x for x in ATTEMPTS.get(address, []) if now - x < 900]
if len(recent) >= 8: ATTEMPTS[address] = recent; return False
recent.append(now); ATTEMPTS[address] = recent; return True
def age_text(seconds):
if seconds is None: return "never"
if seconds < 60: return "just now"
if seconds < 3600: return f"{seconds // 60}m ago"
if seconds < 86400: return f"{seconds // 3600}h ago"
return f"{seconds // 86400}d ago"
def size_text(size):
value = float(size)
for unit in ("B", "KB", "MB", "GB"):
if value < 1024 or unit == "GB": return f"{value:.0f} {unit}" if unit == "B" else f"{value:.1f} {unit}"
value /= 1024
def state_size():
try: return sum(item.stat().st_size for item in STATE.iterdir() if item.is_file())
except OSError: return 0
def user_context(username):
users, groups = load("users.json", {}), load("groups.json", {})
record = users.get(username, {})
if not isinstance(record, dict): record = {}
raw_friends = record.get("friends", [])
if not isinstance(raw_friends, list): raw_friends = []
friends = [item for item in raw_friends if isinstance(item, str) and isinstance(users.get(item), dict)]
memberships = [group for group in groups.values() if isinstance(group, dict)
and isinstance(group.get("members"), list) and username in group["members"]]
return users, groups, record, friends, memberships
def app_page(username, active, title, subtitle, content):
links = (("overview", "/", "Overview"), ("people", "/people", "People"),
("groups", "/groups", "Groups"), ("account", "/account", "Account"),
("server", "/server", "Server"))
nav = "".join(f'<a class="{"on" if active == key else ""}" href="{href}">{label}</a>' for key, href, label in links)
return shell(f'<div class="shell"><aside><div class="brand"><i></i>WIRE</div><nav>{nav}</nav><form class="logout" method="post" action="/logout"><button>Sign out</button></form></aside><main><header><div><h1>{esc(title)}</h1><div class="muted">{esc(subtitle)}</div></div><div class="live">● Connected</div></header>{content}</main></div>', f'{title} - Wire')
def people_rows(friends, users):
if not friends: return '<div class="empty">No friends yet. Add people from the Wire terminal with <b>/friend username</b>.</div>'
return "".join(
f'<div class="list-row"><div class="person"><span class="avatar">{esc(users[key].get("name", key)[:1].upper())}</span>'
f'<span class="stack"><b>{esc(users[key].get("name", key))}</b><small>Encrypted contact</small></span></div>'
f'<span class="pill">{"Do not disturb" if users[key].get("dnd") else "Friend"}</span></div>' for key in friends)
def overview_page(username):
users, groups, record, friends, memberships = user_context(username)
backups = backup_inventory(); security = server_security_status(backups)
latest = backups[0] if backups else None
healthy = security["identity"] and security["turn"] is True and bool(latest and latest["ok"])
content = f'''<div class="grid">
<section class="card"><span class="muted">Friends</span><div class="num">{len(friends)}</div><small>trusted contacts</small></section>
<section class="card"><span class="muted">Groups</span><div class="num">{len(memberships)}</div><small>encrypted rooms</small></section>
<section class="card"><span class="muted">Server health</span><div class="num {"ok" if healthy else "bad"}">{"Good" if healthy else "Check"}</div><small>{"all local checks pass" if healthy else "open Server for details"}</small></section>
<section class="card wide"><h2>Recent people</h2>{people_rows(friends[:5], users)}</section>
<section class="card"><h2>Privacy by design</h2><p class="note">Messages, files, settings, and history stay encrypted. This console displays account metadata and service health—not conversation contents or private keys.</p></section>
<section class="card full"><h2>Quick start</h2><div class="metric"><span>Open a conversation</span><b>open username</b></div><div class="metric"><span>Send any file or image</span><b>/send path</b></div><div class="metric"><span>Share a screen or application</span><b>/share</b></div></section>
</div>'''
return app_page(username, "overview", f'Hello, {record.get("name", username)}', "Your private Wire home", content)
def people_page(username):
users, groups, record, friends, memberships = user_context(username)
content = f'<div class="grid"><section class="card full"><h2>Your friends · {len(friends)}</h2>{people_rows(friends, users)}</section></div>'
return app_page(username, "people", "People", "Contacts trusted by your Wire account", content)
def groups_page(username):
users, groups, record, friends, memberships = user_context(username)
rows = []
for group in sorted(memberships, key=lambda item: str(item.get("name", "")).lower()):
raw_members = group.get("members", []) if isinstance(group.get("members"), list) else []
raw_admins = group.get("admins", []) if isinstance(group.get("admins"), list) else []
raw_pins = group.get("pins", []) if isinstance(group.get("pins"), list) else []
members = [item for item in raw_members if item in users]
role = "Owner" if group.get("owner") == username else "Admin" if username in raw_admins else "Member"
owner = users.get(group.get("owner"), {}).get("name", group.get("owner", "Unknown"))
rows.append(f'<div class="list-row"><div class="stack"><b>{esc(group.get("name", "Unnamed group"))}</b><small>{len(members)} members · owner {esc(owner)} · {len(raw_pins)} pins</small></div><span class="pill">{role}</span></div>')
group_rows = "".join(rows) if rows else '<div class="empty">No group memberships yet.</div>'
content = f'<div class="grid"><section class="card full"><h2>Your groups · {len(memberships)}</h2>{group_rows}</section></div>'
return app_page(username, "groups", "Groups", "Rooms and membership roles", content)
def account_page(username):
users, groups, record, friends, memberships = user_context(username)
try:
public_key = base64.b64decode(record.get("public", ""), validate=True)
if len(public_key) != 32: raise ValueError("invalid public key")
digest = hashlib.sha256(public_key).hexdigest().upper()
fingerprint = " ".join(digest[index:index + 4] for index in range(0, len(digest), 4))
except (TypeError, ValueError, binascii.Error):
fingerprint = "Unavailable"
has_backup = isinstance(load("identity-backups.json", {}).get(username), dict)
content = f'''<div class="grid">
<section class="card full"><h2>Safety fingerprint</h2><p class="note">Compare this fingerprint through another trusted channel when verifying your account identity.</p><p style="word-spacing:.35em;line-height:1.8"><b>{fingerprint}</b></p></section>
<section class="card"><span class="muted">Identity backup</span><div class="num {"ok" if has_backup else "bad"}">{"Saved" if has_backup else "Missing"}</div></section>
<section class="card"><span class="muted">Do not disturb</span><div class="num">{"On" if record.get("dnd") else "Off"}</div></section>
<section class="card"><span class="muted">Group invites</span><div class="num">{"Allowed" if record.get("allow_group_invites", True) else "Blocked"}</div></section>
<section class="card full"><h2>Account privacy</h2><div class="metric"><span>Private identity keys</span><b class="ok">Not exposed to this page</b></div><div class="metric"><span>Message contents</span><b class="ok">Not exposed to this page</b></div><div class="metric"><span>Account deletion</span><b>Available in Wire /settings</b></div></section>
</div>'''
return app_page(username, "account", "Account", "Identity and privacy preferences", content)
def server_page(username):
backups = backup_inventory(); security = server_security_status(backups)
turn = "Reachable" if security["turn"] is True else "Not configured" if security["turn"] is None else "Unreachable"
backup_rows = "".join(f'<div class="list-row"><span class="stack"><b>{esc(item["name"])}</b><small>{age_text(item["age"])} · {size_text(item["size"])}</small></span><span class="pill {"ok" if item["ok"] else "bad"}">{"Verified" if item["ok"] else "Damaged"}</span></div>' for item in backups)
content = f'''<div class="grid">
<section class="card"><span class="muted">Server identity</span><div class="num {"ok" if security["identity"] else "bad"}">{"Protected" if security["identity"] else "Check"}</div></section>
<section class="card"><span class="muted">TURN listener</span><div class="num {"ok" if security["turn"] is True else "bad"}">{turn}</div></section>
<section class="card"><span class="muted">State storage</span><div class="num">{size_text(state_size())}</div><small>metadata and ciphertext</small></section>
<section class="card full"><h2>Backup history</h2>{backup_rows or '<div class="empty">No server backups were found.</div>'}</section>
<section class="card full"><h2>Security boundaries</h2><div class="metric"><span>Conversation contents</span><b class="ok">End-to-end encrypted</b></div><div class="metric"><span>Identity backup</span><b class="ok">Password encrypted</b></div><div class="metric"><span>Web access</span><b>LAN only</b></div><div class="metric"><span>Web uptime</span><b>{age_text(int(time.time()-STARTED)).removesuffix(' ago')}</b></div></section>
</div>'''
return app_page(username, "server", "Server", "Health, backups, and privacy status", content)
class Handler(BaseHTTPRequestHandler):
def setup(self):
super().setup()
self.connection.settimeout(10)
def session_user(self):
try: item = cookies.SimpleCookie(self.headers.get("Cookie", "")).get("wire_session")
except cookies.CookieError: return None
if not item: return None
with LOCK:
session = SESSIONS.get(item.value)
if not session or session[1] < time.time(): SESSIONS.pop(item.value, None); return None
return session[0]
def reply(self, code, body, mime="text/html; charset=utf-8", extra=None):
self.send_response(code); self.send_header("Content-Type", mime); self.send_header("Content-Length", str(len(body)))
for key, value in (extra or {}).items(): self.send_header(key, value)
self.send_header("X-Frame-Options", "DENY"); self.send_header("X-Content-Type-Options", "nosniff")
self.send_header("Referrer-Policy", "no-referrer"); self.send_header("Permissions-Policy", "camera=(), microphone=(), geolocation=()")
self.send_header("Cross-Origin-Resource-Policy", "same-origin")
self.send_header("Content-Security-Policy", "default-src 'none'; style-src 'unsafe-inline'; form-action 'self'; frame-ancestors 'none'; base-uri 'none'")
self.send_header("Cache-Control", "no-store"); self.end_headers(); self.wfile.write(body)
def do_GET(self):
path = urlparse(self.path).path
if path == "/api/health": self.reply(200, b'{"ok":true,"service":"wire-web"}', "application/json"); return
if path == "/logout": self.reply(405, b"method not allowed", "text/plain", {"Allow":"POST"}); return
user = self.session_user()
if not user:
if path in ("/", "/people", "/groups", "/account", "/server"): self.reply(200, login_page()); return
self.reply(404, b"not found", "text/plain"); return
pages = {"/": overview_page, "/people": people_page, "/groups": groups_page,
"/account": account_page, "/server": server_page}
page = pages.get(path)
if not page: self.reply(404, b"not found", "text/plain"); return
self.reply(200, page(user))
def do_POST(self):
path = urlparse(self.path).path
if path == "/logout":
try: item = cookies.SimpleCookie(self.headers.get("Cookie", "")).get("wire_session")
except cookies.CookieError: item = None
if item:
with LOCK: SESSIONS.pop(item.value, None)
self.reply(303, b"", "text/plain", {"Location":"/", "Set-Cookie":"wire_session=; Path=/; Max-Age=0; HttpOnly; SameSite=Strict"}); return
if path != "/login": self.reply(404, b"not found", "text/plain"); return
try:
length = int(self.headers.get("Content-Length", "0"))
if not 1 <= length <= 4096: raise ValueError
form = parse_qs(self.rfile.read(length).decode(), keep_blank_values=True)
username, password = form.get("username", [""])[0].strip(), form.get("password", [""])[0]
except (ValueError, UnicodeDecodeError): self.reply(400, login_page("Invalid request.")); return
if not allow_attempt(self.client_address[0]): self.reply(429, login_page("Too many attempts. Try again later.")); return
if not verify_account(username, password): self.reply(401, login_page("Incorrect username or password.")); return
token = secrets.token_urlsafe(32)
with LOCK:
ATTEMPTS.pop(self.client_address[0], None)
now = time.time()
for saved_token, item in list(SESSIONS.items()):
if item[1] < now: SESSIONS.pop(saved_token, None)
while len(SESSIONS) >= MAX_SESSIONS: SESSIONS.pop(next(iter(SESSIONS)))
SESSIONS[token] = (username.lower(), now + SESSION_TTL)
self.reply(303, b"", "text/plain", {"Location":"/", "Set-Cookie":f"wire_session={token}; Path=/; Max-Age={SESSION_TTL}; HttpOnly; SameSite=Strict"})
def log_message(self, fmt, *args): print("wire-web:", fmt % args, flush=True)
class WireWebServer(ThreadingHTTPServer):
"""Bound concurrent/slow clients so the LAN console cannot exhaust RAM."""
daemon_threads = True
block_on_close = False
def __init__(self, address, handler):
self.slots = threading.BoundedSemaphore(MAX_WEB_CONNECTIONS)
super().__init__(address, handler)
def process_request(self, request, client_address):
if not self.slots.acquire(blocking=False):
request.close()
return
super().process_request(request, client_address)
def process_request_thread(self, request, client_address):
try:
super().process_request_thread(request, client_address)
finally:
self.slots.release()
if __name__ == "__main__":
print("Wire web UI listening on 8097", flush=True)
# The container must accept traffic from its bridge interface. Host-side
# exposure is restricted by the TrueNAS port mapping/firewall.
WireWebServer(("0.0.0.0", 8097), Handler).serve_forever() # nosec B104