- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.py
More file actions
Latest commit
326 lines (282 loc) · 11.1 KB
/
Copy pathserver.py
File metadata and controls
326 lines (282 loc) · 11.1 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
#!/usr/bin/env python3
from __future__ importannotations
importjson
importmimetypes
importos
importsocketserver
importurllib.parse
fromhttp.serverimportBaseHTTPRequestHandler, ThreadingHTTPServer
frompathlibimportPath
fromtypingimportAny
fromlib.authimportcheck_bearer, ip_allowed, load_allow_cidrs, token_configured
fromlib.netbotimport (
MOBILE_SHORTCUTS,
bridge_health,
load_catalog,
local_get,
mobile_shortcut,
netbot_get,
netbot_invoke,
)
fromlib.runnerimport (
install_tool,
list_scripts,
restart_api_services,
run_script,
run_system_probe,
sync_api_files,
)
PORT=int(os.environ.get("PORT", "9378"))
BIND_ADDRESS=os.environ.get("BIND_ADDRESS", "").strip()
ALLOW_CIDRS=load_allow_cidrs()
STATIC_DIR=Path(__file__).resolve().parent/"static"
defjson_response(handler: BaseHTTPRequestHandler, status: int, body: Any) ->None:
payload=json.dumps(body).encode("utf-8")
handler.send_response(status)
handler.send_header("Content-Type", "application/json; charset=utf-8")
handler.send_header("Cache-Control", "no-store")
handler.send_header("Content-Length", str(len(payload)))
handler.end_headers()
handler.wfile.write(payload)
classFirewallaApiHandler(BaseHTTPRequestHandler):
server_version="array-firewalla-api/2.0"
deflog_message(self, fmt: str, *args: object) ->None:
print(f"[firewalla-api] {self.address_string()}{fmt%args}")
def_client_ip(self) ->str:
returnself.client_address[0]
def_reject_unless_allowed(self) ->bool:
ip=self._client_ip()
ifnotip_allowed(ip, ALLOW_CIDRS):
json_response(
self,
403,
{"error": "forbidden", "detail": "LAN clients only", "clientIp": ip},
)
returnFalse
returnTrue
def_reject_unless_authed(self) ->bool:
ifnotcheck_bearer(self.headers.get("Authorization")):
json_response(self, 401, {"error": "unauthorized"})
returnFalse
returnTrue
def_read_json(self) ->dict[str, Any]:
length=int(self.headers.get("Content-Length", "0") or0)
raw=self.rfile.read(length) iflengthelseb""
ifnotraw:
return {}
returnjson.loads(raw.decode("utf-8"))
def_parsed_path(self) ->tuple[str, dict[str, list[str]]]:
parsed=urllib.parse.urlparse(self.path)
returnparsed.path, urllib.parse.parse_qs(parsed.query)
def_handle_health(self) ->None:
bridge: dict[str, Any] = {"ok": False}
try:
bridge=bridge_health()
exceptExceptionasexc: # noqa: BLE001
bridge= {"ok": False, "error": str(exc)}
json_response(
self,
200,
{
"ok": True,
"service": "array-firewalla-api",
"version": 2,
"bindAddress": BIND_ADDRESS,
"port": PORT,
"allowCidrs": list(ALLOW_CIDRS),
"tokenRequired": token_configured(),
"toolsDir": os.environ.get("FIREWALLA_TOOLS_DIR", "/home/pi/gaming-tools"),
"netbotBridge": bridge,
"mobileParity": "POST /api/v1/netbot with {mtype,data} — same netbot path as mobile app",
},
)
def_handle_catalog(self) ->None:
json_response(
self,
200,
{
"netbotItems": load_catalog(),
"mobileShortcuts": sorted(MOBILE_SHORTCUTS.keys()),
"usage": {
"generic": "POST /api/v1/netbot {mtype: get|cmd|set, data: {item, value?}}",
"shortcut": "GET /api/v1/mobile/{shortcut}",
"localHost": "GET /api/v1/local/host/all (production FireAPI local)",
},
},
)
def_handle_mobile_shortcut(self, name: str) ->None:
result=mobile_shortcut(name)
json_response(self, 200, {"ok": True, "shortcut": name, "result": result})
def_handle_netbot_get_item(self, item: str, query: dict[str, list[str]]) ->None:
value_raw= (query.get("value") or [None])[0]
value=json.loads(value_raw) ifvalue_rawelseNone
result=netbot_get(item, value)
json_response(self, 200, {"ok": True, "result": result})
def_handle_netbot_post(self, body: dict[str, Any]) ->None:
mtype=body.get("mtype")
data=body.get("data") or {}
target=body.get("target")
ifnotmtype:
json_response(self, 400, {"error": "mtype required (get, cmd, set, ...)"})
return
result=netbot_invoke(str(mtype), dict(data), target=target)
json_response(self, 200, {"ok": True, "result": result})
def_handle_local(self, subpath: str) ->None:
result=local_get(subpath)
json_response(self, 200, result)
def_serve_static(self, path: str) ->bool:
rel=path.lstrip("/")
ifrelin ("", "index.html"):
rel="index.html"
elifrel.startswith("static/"):
rel=rel[len("static/") :]
ifnotrelor".."inrelorrel.startswith("/"):
returnFalse
file_path= (STATIC_DIR/rel).resolve()
ifnotstr(file_path).startswith(str(STATIC_DIR.resolve())):
returnFalse
ifnotfile_path.is_file():
returnFalse
content=file_path.read_bytes()
mime, _=mimetypes.guess_type(str(file_path))
self.send_response(200)
self.send_header("Content-Type", mimeor"application/octet-stream")
self.send_header("Cache-Control", "no-cache")
self.send_header("Content-Length", str(len(content)))
self.end_headers()
self.wfile.write(content)
returnTrue
defdo_GET(self) ->None:
ifnotself._reject_unless_allowed():
return
path, query=self._parsed_path()
ifpath=="/api/health":
self._handle_health()
return
ifpath=="/api/v1/catalog":
ifnotself._reject_unless_authed():
return
self._handle_catalog()
return
ifpath=="/api/v1/mobile":
ifnotself._reject_unless_authed():
return
json_response(self, 200, {"shortcuts": MOBILE_SHORTCUTS})
return
ifpath.startswith("/api/v1/mobile/"):
ifnotself._reject_unless_authed():
return
name=path[len("/api/v1/mobile/") :]
try:
self._handle_mobile_shortcut(name)
exceptExceptionasexc: # noqa: BLE001
json_response(self, 400, {"error": str(exc)})
return
ifpath.startswith("/api/v1/netbot/"):
ifnotself._reject_unless_authed():
return
item=path[len("/api/v1/netbot/") :]
try:
self._handle_netbot_get_item(item, query)
exceptExceptionasexc: # noqa: BLE001
json_response(self, 400, {"error": str(exc)})
return
ifpath.startswith("/api/v1/local/"):
ifnotself._reject_unless_authed():
return
subpath=path[len("/api/v1/local/") :]
try:
self._handle_local(subpath)
exceptExceptionasexc: # noqa: BLE001
json_response(self, 502, {"error": str(exc)})
return
ifpath=="/api/v1/scripts":
ifnotself._reject_unless_authed():
return
json_response(self, 200, {"scripts": list_scripts()})
return
ifpath=="/api/v1/system":
ifnotself._reject_unless_authed():
return
try:
json_response(self, 200, run_system_probe())
exceptExceptionasexc: # noqa: BLE001
json_response(self, 500, {"error": str(exc)})
return
ifpath=="/"orpath.startswith("/static/"):
ifself._serve_static(path):
return
json_response(self, 404, {"error": "not found"})
defdo_POST(self) ->None:
ifnotself._reject_unless_allowed():
return
path, _query=self._parsed_path()
ifpath=="/api/v1/netbot":
ifnotself._reject_unless_authed():
return
try:
self._handle_netbot_post(self._read_json())
exceptExceptionasexc: # noqa: BLE001
json_response(self, 400, {"error": str(exc)})
return
ifpath=="/api/v1/run":
ifnotself._reject_unless_authed():
return
try:
body=self._read_json()
result=run_script(
body.get("script", ""),
list(body.get("args") or []),
sudo=bool(body.get("sudo")),
payload=body.get("payload"),
)
json_response(self, 200, result)
exceptExceptionasexc: # noqa: BLE001
json_response(self, 400, {"error": str(exc)})
return
ifpath=="/api/v1/tools/update":
ifnotself._reject_unless_authed():
return
try:
body=self._read_json()
mode=int(body.get("mode", "755"), 8)
result=install_tool(
body.get("name", ""),
body.get("content", ""),
mode=mode,
)
json_response(self, 200, result)
exceptExceptionasexc: # noqa: BLE001
json_response(self, 400, {"error": str(exc)})
return
ifpath=="/api/v1/admin/sync":
ifnotself._reject_unless_authed():
return
try:
body=self._read_json()
result=sync_api_files(list(body.get("files") or []))
json_response(self, 200, result)
exceptExceptionasexc: # noqa: BLE001
json_response(self, 400, {"error": str(exc)})
return
ifpath=="/api/v1/admin/restart":
ifnotself._reject_unless_authed():
return
try:
json_response(self, 200, restart_api_services(detach=True))
exceptExceptionasexc: # noqa: BLE001
json_response(self, 400, {"error": str(exc)})
return
json_response(self, 404, {"error": "not found"})
defmain() ->None:
ifnotBIND_ADDRESS:
raiseSystemExit("BIND_ADDRESS is required (set in /etc/default/firewalla-api)")
ifnotALLOW_CIDRS:
raiseSystemExit("FIREWALLA_API_ALLOW_CIDRS is required (set in /etc/default/firewalla-api)")
withThreadingHTTPServer((BIND_ADDRESS, PORT), FirewallaApiHandler) ashttpd:
print(f"array-firewalla-api listening on http://{BIND_ADDRESS}:{PORT}")
print(f" allow CIDRs: {', '.join(ALLOW_CIDRS)}")
print(f" token required: {token_configured()}")
httpd.serve_forever()
if__name__=="__main__":
main()