summaryrefslogtreecommitdiff
path: root/server/cgi/thb.py
blob: e8c69580b62786a2210e346ed8718ebb61710146 (plain) (blame)
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
#!/usr/bin/env python3
"""THB server, CGI edition (lighttpd + mod_cgi).

The Android app talks to the same /api/... routes as thb_server.py; this script
only adapts them to the CGI environment.  State lives in ../keys/tags.json and
writes are serialised with an flock (several CGI processes can run at once).
"""
import fcntl
import json
import os
import re
import sys
from pathlib import Path
from urllib.parse import parse_qs, urlparse

BASE = Path(__file__).resolve().parent.parent          # /opt/thb
sys.path.insert(0, str(BASE / "server"))

import thb_server as srv  # noqa: E402
import qr as qrmod  # noqa: E402  (pure-python QR encoder, server/qr.py)

LOCK_PATH = BASE / "keys" / ".lock"

# When the local box has no os-findmy environment (Debian ARM), the FindMy fetch
# is forwarded to the PC that does (thb_server.py on :8787).
UPSTREAM = os.environ.get("THB_UPSTREAM", "").rstrip("/")

REASONS = {
    200: "OK", 201: "Created", 204: "No Content", 400: "Bad Request",
    401: "Unauthorized", 404: "Not Found", 500: "Internal Server Error",
}


def _send(code, body, ctype="application/json; charset=utf-8"):
    if isinstance(body, str):
        body = body.encode("utf-8")
    out = sys.stdout.buffer
    out.write(("Status: %d %s\r\n" % (code, REASONS.get(code, "OK"))).encode())
    out.write(("Content-Type: %s\r\n" % ctype).encode())
    out.write(b"Access-Control-Allow-Origin: *\r\n")
    out.write(b"Access-Control-Allow-Methods: GET,POST,DELETE,OPTIONS\r\n")
    out.write(b"Access-Control-Allow-Headers: Content-Type,X-Auth\r\n")
    out.write(b"Cache-Control: no-store\r\n")
    out.write(("Content-Length: %d\r\n\r\n" % len(body)).encode())
    out.write(body)


def send_json(code, obj):
    _send(code, json.dumps(obj, ensure_ascii=False))


def read_json_body():
    n = int(os.environ.get("CONTENT_LENGTH") or 0)
    if n <= 0:
        return {}
    raw = sys.stdin.buffer.read(n)
    try:
        return json.loads(raw.decode("utf-8"))
    except Exception:  # noqa: BLE001 - bad body is the client's problem
        return {}


def locked(fn):
    """Run fn() with an exclusive lock on the tag database."""
    LOCK_PATH.parent.mkdir(parents=True, exist_ok=True)
    with open(LOCK_PATH, "w") as fh:
        fcntl.flock(fh, fcntl.LOCK_EX)
        try:
            return fn()
        finally:
            fcntl.flock(fh, fcntl.LOCK_UN)


def fetch_locked(fn):
    """One Apple fetch at a time.

    The emulated Mac keeps its ADI state in a single file under
    /opt/findmy/state, and two emulators writing it at once would corrupt it.
    """
    path = LOCK_PATH.parent / ".fetch.lock"
    path.parent.mkdir(parents=True, exist_ok=True)
    with open(path, "w") as fh:
        fcntl.flock(fh, fcntl.LOCK_EX)
        try:
            return fn()
        finally:
            fcntl.flock(fh, fcntl.LOCK_UN)


def authorized():
    if not srv.TOKEN:
        return True
    return os.environ.get("HTTP_X_AUTH", "") == srv.TOKEN


def serve_static(rel):
    site = srv.SITE.resolve()
    target = (site / rel).resolve()
    if not str(target).startswith(str(site)) or not target.is_file():
        return send_json(404, {"error": "not found"})
    ctype = {
        ".html": "text/html; charset=utf-8",
        ".json": "application/json; charset=utf-8",
        ".css": "text/css; charset=utf-8",
        ".js": "application/javascript; charset=utf-8",
        ".png": "image/png",
        ".svg": "image/svg+xml",
    }.get(target.suffix, "application/octet-stream")
    _send(200, target.read_bytes(), ctype)


def do_get(path, q):
    parts = [p for p in path.split("/") if p]
    if path == "/api/health":
        return send_json(200, {
            "ok": True,
            "server": "THB",
            "cgi": True,
            "osf": bool(srv.OSF_PY and srv.OSF_PY.exists()),
            "session": bool(srv.SESSION_FILE and srv.SESSION_FILE.exists()),
            "time": srv.datetime.now(srv.timezone.utc).isoformat(),
        })
    if not authorized():
        return send_json(401, {"error": "unauthorized"})
    if path == "/api/qr":
        # PNG of the same QR that 設定 → QR 表示 makes, so the phone can scan the
        # server settings instead of typing them.
        url = (q.get("u", [""])[0] or os.environ.get("THB_PUBLIC_URL", "")).strip()
        if not url:
            url = "https://%s/thb" % (os.environ.get("HTTP_HOST") or "dangofactory.net")
        text = qrmod.config_text(url, srv.TOKEN)
        try:
            scale = max(1, min(20, int(q.get("scale", ["8"])[0])))
            margin = max(0, min(16, int(q.get("margin", ["4"])[0])))
        except ValueError:
            return send_json(400, {"error": "bad scale/margin"})
        return _send(200, qrmod.png_bytes(qrmod.encode(text), scale, margin), "image/png")
    if path in ("/api/tags", "/api/tags/"):
        return send_json(200, {"tags": [srv.public_tag(t) for t in srv.load_tags()["tags"]]})
    if len(parts) == 3 and parts[:2] == ["api", "tags"]:
        t = next((x for x in srv.load_tags()["tags"] if x["id"] == parts[2]), None)
        return send_json(200, srv.public_tag(t)) if t else send_json(404, {"error": "not found"})
    if len(parts) == 4 and parts[:2] == ["api", "tags"] and parts[3] == "locations":
        days = int(q.get("days", ["7"])[0])
        t = next((x for x in srv.load_tags()["tags"] if x["id"] == parts[2]), None)
        if not t:
            return send_json(404, {"error": "not found"})
        return send_json(200, {"id": t["id"], "points": t.get("points", []), "days": days})
    if path.startswith("/site/"):
        return serve_static(path[len("/site/"):])
    if path in ("/", "", "/index.html"):
        return serve_static("index.html")
    return send_json(404, {"error": "not found"})


def do_post(path, q):
    parts = [p for p in path.split("/") if p]
    if path != "/api/health" and not authorized():
        return send_json(401, {"error": "unauthorized"})

    if path in ("/api/self/points", "/api/self/points/"):
        body = read_json_body()
        pts = body.get("points") or []
        name = str(body.get("name") or "").strip()[:60] or "この端末"
        if not isinstance(pts, list):
            return send_json(400, {"error": "points must be a list"})

        def add_self():
            db = srv.load_tags()
            t = next((x for x in db["tags"] if x["id"] == "self"), None)
            if t is None:
                t = {
                    "id": "self",
                    "name": name,
                    "created": srv.datetime.now(srv.timezone.utc).isoformat(),
                    "updated": None,
                    "points": [],
                    **srv.new_keypair(),
                }
                db["tags"].append(t)
            before = len(t.get("points", []))
            t["points"] = srv.merge_points(t.get("points", []), pts)
            t["updated"] = srv.datetime.now(srv.timezone.utc).isoformat()
            srv.save_tags(db)
            return t, before

        t, before = locked(add_self)
        return send_json(200, {
            "id": "self",
            "added": len(t["points"]) - before,
            "total": len(t["points"]),
            "last": t["points"][-1] if t["points"] else None,
        })

    if path in ("/api/tags", "/api/tags/"):
        body = read_json_body()
        name = str(body.get("name") or "").strip()[:60] or "THB"
        tag = {
            "id": srv.uuid.uuid4().hex[:12],
            "name": name,
            "created": srv.datetime.now(srv.timezone.utc).isoformat(),
            "updated": None,
            "points": [],
            **srv.new_keypair(),
        }

        def add_tag():
            db = srv.load_tags()
            db["tags"].append(tag)
            srv.save_tags(db)

        locked(add_tag)
        return send_json(201, srv.public_tag(tag))

    if len(parts) == 4 and parts[:2] == ["api", "tags"] and parts[3] == "name":
        body = read_json_body()
        name = str(body.get("name") or "").strip()[:60]
        if not name:
            return send_json(400, {"error": "name is empty"})

        def rename():
            db = srv.load_tags()
            t2 = next((x for x in db["tags"] if x["id"] == parts[2]), None)
            if t2 is not None:
                t2["name"] = name
                srv.save_tags(db)
            return t2

        t2 = locked(rename)
        if t2 is None:
            return send_json(404, {"error": "not found"})
        return send_json(200, srv.public_tag(t2))

    if len(parts) == 4 and parts[:2] == ["api", "tags"] and parts[3] == "refresh":
        days = int(q.get("days", ["7"])[0])
        t = next((x for x in srv.load_tags()["tags"] if x["id"] == parts[2]), None)
        if not t:
            return send_json(404, {"error": "not found"})

        # No local os-findmy environment: forward the fetch to the PC.
        if not srv.OSF_PY and UPSTREAM:
            import urllib.error
            import urllib.request
            url = "%s/api/tags/%s/refresh?days=%d" % (UPSTREAM, parts[2], days)
            req = urllib.request.Request(url, data=b"{}", method="POST")
            req.add_header("Content-Type", "application/json")
            if srv.TOKEN:
                req.add_header("X-Auth", srv.TOKEN)
            try:
                with urllib.request.urlopen(req, timeout=180) as r:
                    result = json.loads(r.read().decode("utf-8"))
            except urllib.error.HTTPError as e:
                body = e.read().decode("utf-8", "replace")
                try:
                    return send_json(e.code, json.loads(body))
                except ValueError:
                    return send_json(e.code, {"error": body[:200]})
            except Exception as e:  # noqa: BLE001
                return send_json(502, {"error": "upstream %s: %s" % (UPSTREAM, e)})

            # Pull the points the PC just collected into the local copy too.
            try:
                with urllib.request.urlopen(
                        "%s/api/tags/%s" % (UPSTREAM, parts[2]), timeout=30) as r:
                    remote = json.loads(r.read().decode("utf-8"))

                def merge_remote():
                    db = srv.load_tags()
                    t2 = next((x for x in db["tags"] if x["id"] == parts[2]), None)
                    if t2 is not None:
                        t2["points"] = srv.merge_points(
                            t2.get("points", []), remote.get("points", []))
                        t2["updated"] = srv.datetime.now(srv.timezone.utc).isoformat()
                        srv.save_tags(db)

                locked(merge_remote)
            except Exception:  # noqa: BLE001 - the refresh itself succeeded
                pass
            return send_json(200, result)

        try:
            res = fetch_locked(lambda: srv.fetch_for_tag(t, days))
        except Exception as e:  # noqa: BLE001 - report the reason to the phone
            return send_json(500, {"error": str(e)})

        def merge_refresh():
            db = srv.load_tags()
            t2 = next((x for x in db["tags"] if x["id"] == parts[2]), t)
            before = len(t2.get("points", []))
            t2["points"] = srv.merge_points(t2.get("points", []), res.get("points", []))
            t2["updated"] = srv.datetime.now(srv.timezone.utc).isoformat()
            srv.save_tags(db)
            return t2, before

        t, before = locked(merge_refresh)
        return send_json(200, {
            "id": t["id"],
            "encrypted": res.get("encrypted", 0),
            "added": len(t["points"]) - before,
            "total": len(t["points"]),
            "last": t["points"][-1] if t["points"] else None,
        })

    if len(parts) == 4 and parts[:2] == ["api", "tags"] and parts[3] == "points":
        body = read_json_body()
        pts = body.get("points") or []
        if not isinstance(pts, list):
            return send_json(400, {"error": "points must be a list"})

        def merge_points():
            db = srv.load_tags()
            t = next((x for x in db["tags"] if x["id"] == parts[2]), None)
            if not t:
                return None, 0
            before = len(t.get("points", []))
            t["points"] = srv.merge_points(t.get("points", []), pts)
            t["updated"] = srv.datetime.now(srv.timezone.utc).isoformat()
            srv.save_tags(db)
            return t, before

        t, before = locked(merge_points)
        if t is None:
            return send_json(404, {"error": "not found"})
        return send_json(200, {
            "id": t["id"],
            "added": len(t["points"]) - before,
            "total": len(t["points"]),
            "last": t["points"][-1] if t["points"] else None,
        })

    return send_json(404, {"error": "not found"})


def do_delete(path):
    if not authorized():
        return send_json(401, {"error": "unauthorized"})
    m = re.fullmatch(r"/api/tags/([0-9a-zA-Z]+)/?", path)
    if not m:
        return send_json(404, {"error": "not found"})
    tag_id = m.group(1)

    def delete():
        db = srv.load_tags()
        t = next((x for x in db["tags"] if x["id"] == tag_id), None)
        if t is None:
            return None
        if tag_id == "self" or t.get("protected"):
            return "protected"
        before = len(db["tags"])
        db["tags"] = [x for x in db["tags"] if x["id"] != tag_id]
        srv.save_tags(db)
        return before - len(db["tags"])

    res = locked(delete)
    if res is None:
        return send_json(404, {"error": "not found"})
    if res == "protected":
        return send_json(403, {"error": "この端末の記録は削除できません"})
    return send_json(200, {"deleted": res})


def main():
    srv.TOKEN = os.environ.get("THB_TOKEN", "")
    method = os.environ.get("REQUEST_METHOD", "GET").upper()
    path = os.environ.get("PATH_INFO") or ""
    if not path or path == "/":
        path = urlparse(os.environ.get("REQUEST_URI", "/")).path
        # strip the mount point (/thb)
        if path.startswith("/thb/"):
            path = path[len("/thb"):]
        elif path == "/thb":
            path = "/"
    q = parse_qs(os.environ.get("QUERY_STRING", ""))
    try:
        if method == "OPTIONS":
            _send(204, b"")
        elif method == "GET":
            do_get(path, q)
        elif method == "POST":
            do_post(path, q)
        elif method == "DELETE":
            do_delete(path)
        else:
            send_json(405, {"error": "method not allowed"})
    except Exception as e:  # noqa: BLE001 - never let a CGI crash silently
        import traceback
        traceback.print_exc(file=sys.stderr)
        send_json(500, {"error": "%s: %s" % (type(e).__name__, e)})


if __name__ == "__main__":
    main()