-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
1826 lines (1633 loc) · 72.1 KB
/
Copy pathapp.py
File metadata and controls
1826 lines (1633 loc) · 72.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
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
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""
Log Parser — standalone Flask web app.
Upload a tar/tar.gz/zip archive or multiple individual RDKB device logs,
then view them separately or merged into one chronological, color-coded,
paginated timeline with timestamp-range filtering.
Run: python app.py (listens on 0.0.0.0:5100 by default)
"""
from __future__ import annotations
import hashlib
import json
import os
import re
import shutil
import tempfile
import time
import uuid
from flask import (
Flask, Response, flash, jsonify, redirect, render_template, request, session,
url_for,
)
from markupsafe import Markup, escape
from werkzeug.utils import secure_filename
import ingest
from auth import LoginThrottle, UserStore, UserStoreError
from logmodel import (
LEVEL_ORDER, LogSource, Page, classify_is_log, color_for, file_category,
filter_by_level, filter_by_text, filter_records, level_counts,
merge_records, paginate, parse_source,
)
from timestamps import (
ParserConfig, format_canonical, parse_filter_bound,
)
from workspaces import WorkspaceError, WorkspaceStore, slugify as ws_slugify
from bookmarks import BookmarkStore
from notepad import NotepadStore
# --- Configuration --------------------------------------------------------------
PORT = int(os.environ.get("LOG_PARSER_PORT", "5100"))
MAX_CONTENT_LENGTH = int(os.environ.get("LOG_PARSER_MAX_UPLOAD", str(256 * 1024 * 1024))) # 256 MB
DEFAULT_PAGE_SIZE = int(os.environ.get("LOG_PARSER_PAGE_SIZE", "1000"))
# Pagination is ON by default (1000 lines/page) so huge logs don't load at once.
# Set LOG_PARSER_PAGINATE=0 to render everything on one page instead.
PAGINATE = os.environ.get("LOG_PARSER_PAGINATE", "1") == "1"
ASSUMED_YEAR = os.environ.get("LOG_PARSER_ASSUMED_YEAR") # for yearless syslog
# Optional: constrain server-side path reads to within this root (realpath).
# Empty = unrestricted (this is a local single-user tool reading your own logs).
ALLOWED_ROOT = os.environ.get("LOG_PARSER_ALLOWED_ROOT", "").strip()
HERE = os.path.dirname(os.path.abspath(__file__))
# Local copy of allowed users (username + SHA-256 pass_hash), imported from the
# shared db.json via import_users.py. The app never reads the shared file.
USERS_DB = os.environ.get("LOG_PARSER_USERS_DB", os.path.join(HERE, "users.json"))
# Root of per-user persistent workspace storage.
DATA_ROOT = os.environ.get("LOG_PARSER_DATA_ROOT", os.path.join(HERE, "data"))
# Per-user storage quota (default 500 MB).
USER_QUOTA = int(os.environ.get("LOG_PARSER_USER_QUOTA", str(500 * 1024 * 1024)))
WORK_ROOT = os.path.join(tempfile.gettempdir(), "log-parser")
SESSION_MAX_AGE = 6 * 3600 # sweep working dirs older than 6h on startup
# Named source presets (quick templates). Files are matched by normalized
# basename stem — case-insensitive and ignoring extensions / rotation suffixes —
# so `wifiHal.txt`, `wifiHAL`, and `wifiHal.txt.0` all match `wifihal`.
PRESETS = {
"wifi": {
"label": "WiFi Analysis",
"files": {
"wifidmcli", "wifihal", "wifimgr", "wifimon",
"wifiwebconfig", "wifictrl", "messages",
},
},
}
# Display order / labels / icons for the non-log file categories (the chips
# shown above the logs). Only categories that actually have files are shown.
_CAT_META = [
("conf", "Config", "\u2699"),
("xml", "XML", "\u25c7"),
("db", "Database", "\U0001f5c3"),
("pid", "PID / state", "\U0001f516"),
("cert", "Certs / keys", "\U0001f511"),
("image", "Images", "\U0001f5bc"),
("web", "Web", "\U0001f310"),
("capture", "Binary", "\U0001f4e6"),
("other", "Other", "\u2022"),
]
def _log_stem(name: str) -> str:
"""Normalize a source name to a comparable stem: basename, lowercased, with
extensions (.txt/.log/.out/.err/.gz) and rotation suffixes (.0/.1…) removed."""
base = name.rsplit("/", 1)[-1].lower()
prev = None
while prev != base:
prev = base
base = re.sub(r"\.\d+$", "", base) # rotation .0/.1
base = re.sub(r"\.(txt|log|out|err|gz|bz2|xz)$", "", base) # extension
return base
def _preset_matches(name: str, wanted_stems: set) -> bool:
return _log_stem(name) in wanted_stems
app = Flask(__name__)
app.config["MAX_CONTENT_LENGTH"] = MAX_CONTENT_LENGTH
app.secret_key = os.environ.get("LOG_PARSER_SECRET", os.urandom(24).hex())
# Session-cookie hardening. Set LOG_PARSER_COOKIE_SECURE=1 when served over HTTPS.
app.config.update(
SESSION_COOKIE_HTTPONLY=True,
SESSION_COOKIE_SAMESITE="Lax",
SESSION_COOKIE_SECURE=os.environ.get("LOG_PARSER_COOKIE_SECURE", "0") == "1",
)
# Authentication + persistent per-user workspace storage.
ADMIN_USERS = [u.strip() for u in os.environ.get("LOG_PARSER_ADMINS", "admin").split(",") if u.strip()]
USERS = UserStore(USERS_DB, admin_usernames=ADMIN_USERS)
THROTTLE = LoginThrottle()
WORKSPACES = WorkspaceStore(DATA_ROOT, USER_QUOTA)
BOOKMARKS = BookmarkStore(DATA_ROOT)
NOTEPAD = NotepadStore(DATA_ROOT)
try:
USERS.ensure_admins(ADMIN_USERS)
except Exception as _exc: # noqa: BLE001 (best-effort bootstrap; store may be read-only)
app.logger.warning("Could not bootstrap admin accounts: %s", _exc)
# In-memory registry: session_id -> {"dir": str, "sources": {id: LogSource}}
_SESSIONS: dict[str, dict] = {}
@app.context_processor
def _inject_user():
username = session.get("username")
admin = False
if username:
try:
admin = USERS.is_admin(username)
except Exception: # noqa: BLE001
admin = False
return {"current_user": username, "is_admin": admin}
# Endpoints reachable without an authenticated session.
_PUBLIC_ENDPOINTS = {"login", "static", "about", "set_password"}
def _is_safe_next(target: str) -> bool:
"""Only allow local, relative redirect targets (guards against open redirects)."""
return bool(target) and target.startswith("/") and not target.startswith("//")
@app.before_request
def _require_login():
if request.endpoint in _PUBLIC_ENDPOINTS:
return None
if session.get("username"):
return None
if request.method == "GET":
nxt = request.full_path if request.query_string else request.path
return redirect(url_for("login", next=nxt))
return redirect(url_for("login"))
@app.template_filter("highlight")
def _highlight(text: str, query: str, jump: str = ""):
"""Escape line text, then wrap case-insensitive matches of the search
term(s) in <mark>. Multiple ``query`` terms may be separated by ``|``; the
``jump`` term (Global search) gets a distinct <mark class="jmark">.
Escaping happens before insertion (XSS-safe)."""
escaped = str(escape(text))
alts = []
seen = set()
if jump:
j = str(escape(jump))
alts.append(("j", re.escape(j)))
seen.add(j.casefold())
# Collect the distinct "message contains" terms; longer ones first so they
# win over shorter overlapping terms in the alternation.
terms = []
for term in query.split("|"):
term = term.strip()
if not term:
continue
esc = str(escape(term))
key = esc.casefold()
if key in seen:
continue
seen.add(key)
terms.append(esc)
terms.sort(key=len, reverse=True)
for i, esc in enumerate(terms):
alts.append((f"q{i}", re.escape(esc)))
if not alts:
return Markup(escaped)
pattern = re.compile("|".join(f"(?P<{n}>{p})" for n, p in alts), re.IGNORECASE)
def _repl(m):
if m.lastgroup == "j":
return f'<mark class="jmark">{m.group(0)}</mark>'
return f"<mark>{m.group(0)}</mark>"
return Markup(pattern.sub(_repl, escaped))
# Origin path segments surfaced in a source's short label. Matched as exact
# path components (case-insensitive) so unrelated names like "mytmp" don't hit.
# ``rdklogs`` is checked first as it is the more specific origin.
_ORIGIN_SEGMENTS = ("rdklogs", "tmp")
@app.template_filter("short_source")
def _short_source(name: str) -> str:
"""Compact label for a source: just the filename plus a ``/tmp`` or
``/rdklogs`` origin tag when the path carries one.
Log dumps use deep relative paths (optionally prefixed with a bundle
label), e.g. ``2026-05-05 06:00:00/rdklogs/logs/WiFilog.txt.0``. Showing
those in full clutters the log view, so each collapses to::
rdklogs/logs/WiFilog.txt.0 -> /rdklogs/WiFilog.txt.0
run/tmp/CcspWifiSsp.txt.0 -> /tmp/CcspWifiSsp.txt.0
nvram/logs/dhd.log -> dhd.log
"""
if not name:
return name
base = name.rsplit("/", 1)[-1]
segments = name.lower().split("/")
for origin in _ORIGIN_SEGMENTS:
if origin in segments:
return f"/{origin}/{base}"
return base
def _parser_config() -> ParserConfig:
year = int(ASSUMED_YEAR) if ASSUMED_YEAR else None
return ParserConfig(assumed_year=year)
def _sweep_stale_dirs() -> None:
"""Best-effort removal of working dirs left over from old sessions."""
if not os.path.isdir(WORK_ROOT):
return
now = time.time()
for name in os.listdir(WORK_ROOT):
path = os.path.join(WORK_ROOT, name)
try:
if now - os.path.getmtime(path) > SESSION_MAX_AGE:
shutil.rmtree(path, ignore_errors=True)
except OSError:
pass
def _get_session_id() -> str:
sid = session.get("sid")
if not sid:
sid = uuid.uuid4().hex
session["sid"] = sid
return sid
def _reset_workdir(sid: str) -> str:
"""Create a fresh isolated working directory for this session."""
prev = _SESSIONS.get(sid)
if prev and os.path.isdir(prev["dir"]):
shutil.rmtree(prev["dir"], ignore_errors=True)
os.makedirs(WORK_ROOT, exist_ok=True)
workdir = tempfile.mkdtemp(prefix=f"{sid}-", dir=WORK_ROOT)
_SESSIONS[sid] = {"dir": workdir, "sources": {}}
return workdir
def _current(sid: str) -> dict | None:
return _SESSIONS.get(sid)
def _bookmark_scope(state) -> str:
"""Identity for the currently loaded logs so notes stay per log folder.
Saved workspaces are keyed by their slug; a fresh upload is keyed by a
stable hash of its source file names, so re-uploading the same folder
reuses its notes while a different folder keeps its own separate set."""
if not state:
return ""
# A shared workspace uses the OWNER's stable scope (set at load time) so
# everyone with access reads/writes the same note set. Owned workspaces set
# the same "ws:<name>" scope, keeping existing notes intact.
scope = state.get("ws_scope")
if scope:
return scope
slug = state.get("loaded_from")
if slug:
return "ws:" + str(slug)
sources = state.get("sources") or {}
names = sorted(s.name for s in sources.values())
if not names:
return ""
digest = hashlib.sha1("\n".join(names).encode("utf-8")).hexdigest()
return "up:" + digest[:16]
def _notes_owner(state) -> str:
"""Whose bookmark store holds the current view's notes. For a workspace
shared with the caller this is the workspace OWNER (so shared notes are
visible and collaborative); otherwise it's the current user."""
if state and state.get("ws_owner"):
return state["ws_owner"]
return session.get("username", "")
def _bundle_label(name: str) -> str:
"""Derive a short, readable label for a nested archive bundle.
Bundle filenames look like
``2026-05-07 06:00:00-4075C33AE01E_Logs_05-07-26-06-37AM.tgz`` — use the
leading timestamp when present, otherwise the filename without extension.
"""
base = os.path.basename(name)
m = re.match(r"^(\d{4}-\d{2}-\d{2}[ T]\d{2}:\d{2}:\d{2})", base)
if m:
return m.group(1)
for ext in (".tar.gz", ".tgz", ".tar", ".zip"):
if base.lower().endswith(ext):
return base[: -len(ext)]
return base
def _human_size(num: int) -> str:
size = float(num)
for unit in ("B", "KB", "MB", "GB"):
if size < 1024 or unit == "GB":
return f"{size:.0f} {unit}" if unit == "B" else f"{size:.1f} {unit}"
size /= 1024
return f"{num} B"
def _register_source_groups(sid: str, groups: list[tuple]) -> None:
"""Register sources from one or more (label, root, files) groups.
When more than one group is provided, each source name is prefixed with the
group's label so bundles from different time windows stay distinguishable.
"""
cfg = _parser_config()
sources: dict[int, LogSource] = {}
idx = 0
multi = len(groups) > 1
for label, root, files in groups:
for path in sorted(files, key=lambda p: os.path.relpath(p, root).lower()):
rel = os.path.relpath(path, root).replace(os.sep, "/")
name = f"{label}/{rel}" if (multi and label) else rel
src = LogSource(source_id=idx, name=name, path=path, color=color_for(idx))
try:
parse_source(src, cfg)
except OSError:
continue
src.is_log = classify_is_log(src.name, src.line_count, src.parsed_count)
src.category = file_category(src.name, src.is_log)
sources[idx] = src
idx += 1
_SESSIONS[sid]["sources"] = sources
def _split_counts(sid: str) -> tuple:
"""(#log files, #non-log files) currently registered for this session."""
srcs = list(_SESSIONS[sid]["sources"].values())
logs = sum(1 for s in srcs if getattr(s, "is_log", True))
return logs, len(srcs) - logs
def _collect_from_path(path: str, workdir: str) -> list[str]:
"""Collect log files from a server-side path (directory or file).
Directories are walked recursively; a single archive file is extracted into
the working directory. Raises ``ingest.IngestError`` for invalid, missing,
or (when a root is configured) forbidden paths.
"""
real = os.path.realpath(os.path.expanduser(path))
if ALLOWED_ROOT:
root = os.path.realpath(ALLOWED_ROOT)
if real != root and not real.startswith(root + os.sep):
raise ingest.IngestError(
f"Path is outside the allowed root ({ALLOWED_ROOT})")
if not os.path.exists(real):
raise ingest.IngestError(f"Path does not exist: {path}")
if os.path.isdir(real):
files = ingest.collect_log_files(real)
if not files:
raise ingest.IngestError(f"No files found in directory: {path}")
return files
# A single file: extract if it is an archive, otherwise use it directly.
if ingest.is_archive(os.path.basename(real)):
extract_dir = os.path.join(workdir, "extracted", os.path.basename(real))
os.makedirs(extract_dir, exist_ok=True)
return ingest.extract_archive(real, extract_dir)
return [real]
def _expand_deep_archives(archives: list[str], workdir: str,
depth: int = 0) -> list[tuple]:
"""Recursively extract incidental/nested archives (e.g. nvram/logs/dhd_*.tar.gz)
and return ``(label, root, files)`` groups of the plain files inside them.
These are archives that are NOT top-level selectable bundles — they should be
unpacked and shown as sources rather than cluttering the bundle picker."""
groups: list[tuple] = []
if depth > 4:
return groups
for i, arc in enumerate(archives):
edir = os.path.join(workdir, "deep", str(depth),
f"{i}_{os.path.basename(arc)}")
os.makedirs(edir, exist_ok=True)
try:
files = ingest.extract_archive(arc, edir)
except ingest.IngestError:
continue
inner = [f for f in files if ingest.is_archive(os.path.basename(f))]
plain = [f for f in files if f not in set(inner)]
if plain:
groups.append((_bundle_label(arc), edir, plain))
groups.extend(_expand_deep_archives(inner, edir, depth + 1))
return groups
def _finalize_collected(sid: str, collected: list[str]):
"""Show the bundle picker only when the upload is primarily a *collection of
archives* (a zip/folder of per-time-window bundles). Archives that are merely
incidental among log files (e.g. ``nvram/logs/dhd_*.tar.gz``) are auto-extracted
and registered as sources instead of appearing in the picker."""
if not collected:
flash("No log files were found.", "error")
return redirect(url_for("index"))
archives = [p for p in collected if ingest.is_archive(os.path.basename(p))]
plain = [p for p in collected if p not in set(archives)]
# Bundle picker only when archives dominate the content (few/no plain logs
# alongside). A handful of archives among many logs => auto-extract them.
if archives and len(archives) > len(plain):
archives_meta = [
{"id": i, "path": p, "name": os.path.basename(p),
"label": _bundle_label(p), "size": os.path.getsize(p),
"size_h": _human_size(os.path.getsize(p))}
for i, p in enumerate(sorted(archives, key=lambda x: os.path.basename(x).lower()))
]
_SESSIONS[sid]["pending"] = {"archives": archives_meta, "plain": plain}
flash(f"Found {len(archives_meta)} log bundle(s) — choose which to analyze.", "info")
return redirect(url_for("select"))
# Otherwise register the plain logs plus anything inside incidental archives.
workdir = _SESSIONS[sid]["dir"]
groups: list[tuple] = []
if plain:
proot = os.path.commonpath(plain) if len(plain) > 1 else os.path.dirname(plain[0])
groups.append((None, proot, plain))
groups.extend(_expand_deep_archives(archives, workdir))
if not groups:
flash("No readable log files were found.", "error")
return redirect(url_for("index"))
_register_source_groups(sid, groups)
logs, others = _split_counts(sid)
msg = f"Loaded {logs} log file(s)."
if others:
msg += f" {others} non-log file(s) set aside \u2014 use \u201cShow other files\u201d to view them."
flash(msg, "info")
return redirect(url_for("view"))
# --- Routes ---------------------------------------------------------------------
@app.route("/login", methods=["GET", "POST"])
def login():
if session.get("username"):
return redirect(url_for("index"))
next_url = request.values.get("next", "")
if not _is_safe_next(next_url):
next_url = ""
if request.method == "POST":
username = request.form.get("username", "").strip()
password = request.form.get("password", "")
ip = request.remote_addr or "?"
if THROTTLE.is_locked(username, ip):
flash("Too many failed attempts. Please wait a few minutes and try again.", "error")
return render_template("login.html", next_url=next_url), 429
try:
# Accounts freshly added / reset by an admin have no password yet:
# send them to set one instead of failing the login.
if USERS.needs_password(username):
return redirect(url_for("set_password", username=username, next=next_url))
ok = USERS.verify(username, password)
except UserStoreError as exc:
app.logger.error("User store unavailable: %s", exc)
flash("Login is temporarily unavailable \u2014 contact the administrator.", "error")
return render_template("login.html", next_url=next_url), 503
if ok:
THROTTLE.reset(username, ip)
session.clear()
session["username"] = username
return redirect(next_url or url_for("index"))
THROTTLE.record_failure(username, ip)
flash("Invalid username or password.", "error")
return render_template("login.html", next_url=next_url)
@app.route("/set-password", methods=["GET", "POST"])
def set_password():
"""First-time / post-reset password setup for an account awaiting one."""
if session.get("username"):
return redirect(url_for("index"))
username = request.values.get("username", "").strip()
next_url = request.values.get("next", "")
if not _is_safe_next(next_url):
next_url = ""
try:
awaiting = USERS.needs_password(username)
except UserStoreError:
awaiting = False
if not username or not awaiting:
flash("That account is not awaiting a password (or does not exist).", "info")
return redirect(url_for("login"))
if request.method == "POST":
pw1 = request.form.get("password", "")
pw2 = request.form.get("password2", "")
if len(pw1) < 6:
flash("Password must be at least 6 characters.", "error")
return render_template("set_password.html", username=username, next_url=next_url)
if pw1 != pw2:
flash("Passwords do not match.", "error")
return render_template("set_password.html", username=username, next_url=next_url)
try:
USERS.set_password(username, pw1)
except UserStoreError as exc:
flash(f"Could not set password: {exc}", "error")
return render_template("set_password.html", username=username, next_url=next_url)
session.clear()
session["username"] = username
flash("Password set — you're signed in.", "info")
return redirect(next_url or url_for("index"))
return render_template("set_password.html", username=username, next_url=next_url)
def _require_admin() -> bool:
u = session.get("username")
try:
return bool(u) and USERS.is_admin(u)
except Exception: # noqa: BLE001
return False
@app.route("/admin")
def admin():
if not _require_admin():
flash("Administrator access is required for that page.", "error")
return redirect(url_for("index"))
return render_template("admin.html", users=USERS.list_users())
@app.route("/admin/add", methods=["POST"])
def admin_add():
if not _require_admin():
flash("Administrator access is required.", "error")
return redirect(url_for("index"))
username = request.form.get("username", "").strip()
password = request.form.get("password", "")
make_admin = request.form.get("is_admin") == "1"
if not re.match(r"^[A-Za-z0-9._-]{2,40}$", username):
flash("Username must be 2\u201340 characters: letters, digits, '.', '_' or '-'.", "error")
return redirect(url_for("admin"))
try:
USERS.add_user(username, password or None, admin=make_admin)
except UserStoreError as exc:
flash(str(exc), "error")
return redirect(url_for("admin"))
if password:
flash(f"Added user '{username}'.", "info")
else:
flash(f"Added user '{username}'. They will set their password on first sign-in.", "info")
return redirect(url_for("admin"))
@app.route("/admin/reset", methods=["POST"])
def admin_reset():
if not _require_admin():
flash("Administrator access is required.", "error")
return redirect(url_for("index"))
username = request.form.get("username", "").strip()
try:
USERS.reset_password(username)
except UserStoreError as exc:
flash(str(exc), "error")
return redirect(url_for("admin"))
flash(f"Password reset for '{username}'. They will choose a new password on next sign-in.", "info")
return redirect(url_for("admin"))
@app.route("/admin/delete", methods=["POST"])
def admin_delete():
if not _require_admin():
flash("Administrator access is required.", "error")
return redirect(url_for("index"))
username = request.form.get("username", "").strip()
if username == session.get("username"):
flash("You cannot remove your own account.", "error")
return redirect(url_for("admin"))
USERS.delete_user(username)
flash(f"Removed user '{username}'.", "info")
return redirect(url_for("admin"))
@app.route("/logout")
def logout():
sid = session.get("sid")
if sid:
prev = _SESSIONS.pop(sid, None)
if prev and os.path.isdir(prev["dir"]):
shutil.rmtree(prev["dir"], ignore_errors=True)
session.clear()
flash("Signed out.", "info")
return redirect(url_for("login"))
APP_VERSION = "1.0"
@app.route("/about")
def about():
"""Public, shareable overview of everything the tool can do."""
return render_template("about.html", version=APP_VERSION)
@app.route("/")
def index():
username = session["username"]
try:
workspaces = WORKSPACES.list_workspaces(username)
used = WORKSPACES.usage(username)
except WorkspaceError as exc:
app.logger.warning("Workspace listing failed for %s: %s", username, exc)
workspaces, used = [], 0
for w in workspaces:
w["size_h"] = _human_size(w.get("size", 0))
shared = []
try:
shared = WORKSPACES.list_shared_with_me(username)
except Exception as exc: # noqa: BLE001
app.logger.warning("Shared-workspace listing failed for %s: %s", username, exc)
for w in shared:
w["size_h"] = _human_size(w.get("size", 0))
all_users = []
try:
all_users = [u["username"] for u in USERS.list_users()
if u["username"] != username]
except Exception as exc: # noqa: BLE001
app.logger.warning("User listing failed for %s: %s", username, exc)
sid = _get_session_id()
state = _current(sid)
sources = list(state["sources"].values()) if state else []
sources.sort(key=lambda s: s.source_id)
pct = min(100, round(used * 100 / USER_QUOTA)) if USER_QUOTA else 0
return render_template(
"home.html", workspaces=workspaces, shared=shared, sources=sources,
all_users=all_users,
used=used, quota=USER_QUOTA, used_h=_human_size(used),
quota_h=_human_size(USER_QUOTA), pct=pct)
@app.route("/upload", methods=["GET", "POST"])
def upload():
if request.method == "GET":
sid = _get_session_id()
state = _current(sid)
sources = list(state["sources"].values()) if state else []
sources.sort(key=lambda s: s.source_id)
return render_template("index.html", sources=sources)
sid = _get_session_id()
uploaded = request.files.getlist("files")
uploaded = [f for f in uploaded if f and f.filename]
path_input = request.form.get("path", "").strip()
if not uploaded and not path_input:
flash("Select files to upload or enter a server-side path.", "error")
return redirect(url_for("index"))
workdir = _reset_workdir(sid)
raw_dir = os.path.join(workdir, "raw")
os.makedirs(raw_dir, exist_ok=True)
collected: list[str] = []
try:
# 1) Uploaded files (saved into the workdir; archives extracted).
for storage in uploaded:
fname = secure_filename(storage.filename) or "upload.bin"
saved = os.path.join(raw_dir, fname)
storage.save(saved)
if ingest.is_archive(fname):
extract_dir = os.path.join(workdir, "extracted", fname)
os.makedirs(extract_dir, exist_ok=True)
collected.extend(ingest.extract_archive(saved, extract_dir))
else:
collected.append(saved)
# 2) Server-side path (folder or file), read in place.
if path_input:
collected.extend(_collect_from_path(path_input, workdir))
except ingest.IngestError as exc:
flash(f"Rejected: {exc}", "error")
return redirect(url_for("index"))
return _finalize_collected(sid, collected)
@app.route("/select", methods=["GET"])
def select():
sid = _get_session_id()
state = _current(sid)
pending = state.get("pending") if state else None
if not pending:
flash("Upload an archive first.", "info")
return redirect(url_for("index"))
return render_template("select.html", archives=pending["archives"],
has_plain=bool(pending.get("plain")))
@app.route("/select", methods=["POST"])
def select_post():
sid = _get_session_id()
state = _current(sid)
pending = state.get("pending") if state else None
if not pending:
flash("Upload an archive first.", "info")
return redirect(url_for("index"))
chosen = set(request.form.getlist("archive", type=int))
if not chosen:
flash("Select at least one log bundle to analyze.", "error")
return redirect(url_for("select"))
workdir = state["dir"]
by_id = {a["id"]: a for a in pending["archives"]}
groups: list[tuple] = []
try:
for aid in sorted(chosen):
arc = by_id.get(aid)
if not arc:
continue
bundle_dir = os.path.join(workdir, "bundles", str(aid))
os.makedirs(bundle_dir, exist_ok=True)
files = ingest.extract_archive(arc["path"], bundle_dir)
inner = [f for f in files if ingest.is_archive(os.path.basename(f))]
flat = [f for f in files if f not in set(inner)]
if flat:
groups.append((arc["label"], bundle_dir, flat))
# Auto-extract incidental archives inside the bundle (e.g. dhd_*.tar.gz).
groups.extend(_expand_deep_archives(inner, bundle_dir))
except ingest.IngestError as exc:
flash(f"Bundle rejected: {exc}", "error")
return redirect(url_for("select"))
# Carry any plain (non-archive) files found alongside the bundles.
plain = pending.get("plain") or []
if plain:
proot = os.path.commonpath(plain) if len(plain) > 1 else os.path.dirname(plain[0])
groups.append(("files", proot, plain))
if not groups:
flash("No log files were found in the selected bundle(s).", "error")
return redirect(url_for("select"))
_register_source_groups(sid, groups)
_SESSIONS[sid].pop("pending", None)
logs, others = _split_counts(sid)
msg = f"Loaded {logs} log file(s) from {len(chosen)} bundle(s)."
if others:
msg += f" {others} non-log file(s) set aside."
flash(msg, "info")
return redirect(url_for("view"))
def _resolve_selection(state, args, flash_errors=True):
"""Resolve the selected sources and parsed filters from request args.
Shared by the view and export routes so both honour the same preset,
source selection, timestamp range, and text query. Returns a dict.
"""
all_sources = sorted(state["sources"].values(), key=lambda s: s.source_id)
existing_ids = {s.source_id for s in all_sources}
# Split log files from non-log files and group the latter by type (conf,
# xml, db, pid, …). The default view is the logs; a category filter (?cat=)
# opens just that non-log group, shown separately rather than merged.
log_ids = {s.source_id for s in all_sources if getattr(s, "is_log", True)}
other_ids = existing_ids - log_ids
cat_of = {s.source_id: getattr(s, "category", "log") for s in all_sources}
cat_counts = {}
for _c in cat_of.values():
if _c != "log":
cat_counts[_c] = cat_counts.get(_c, 0) + 1
cat = args.get("cat", "").strip().lower()
if cat in cat_counts:
universe = {sid for sid, c in cat_of.items() if c == cat}
show_others = True
else:
cat = "log"
universe = log_ids or existing_ids
show_others = False
explicit_preset = args.get("preset", "").strip()
want_all = args.get("all") == "1"
excl_ids = set(args.getlist("excl", type=int)) # excluded ids when want_all
has_src = bool(args.getlist("src", type=int))
# lgset: the persisted "legend candidate" source ids (comma-separated) so a
# manual selection keeps showing excluded sources as re-includable chips.
# Its presence also signals the controls form has been submitted at least
# once (the user has interacted), so we don't snap back to the default preset.
interacted = "lgset" in args
lgset_raw = args.get("lgset", "").strip()
lgset_ids = [int(x) for x in lgset_raw.split(",") if x.strip().isdigit()]
# Default to the WiFi Analysis preset only on a truly fresh log view (no
# explicit choice / interaction, and not while viewing the non-log bundle).
preset_key = explicit_preset
if (not preset_key and not has_src and not want_all and not interacted
and not show_others and "wifi" in PRESETS):
preset_key = "wifi"
preset = PRESETS.get(preset_key) if not show_others else None
if preset:
wanted = preset["files"]
selected_ids = {
s.source_id for s in all_sources
if s.source_id in log_ids and _preset_matches(s.name, wanted)
}
if not selected_ids:
# Only warn when the user explicitly asked for a preset.
if flash_errors and explicit_preset:
flash(f"No logs matching the {preset['label']} preset were found "
f"in this upload.", "info")
selected_ids = set(universe)
preset = None
preset_key = ""
else:
sel = args.getlist("src", type=int)
if want_all:
selected_ids = universe - excl_ids
elif sel:
selected_ids = set(sel)
elif interacted:
selected_ids = set() # user explicitly deselected everything
else:
selected_ids = set(universe)
selected = [s for s in all_sources if s.source_id in selected_ids]
# Legend candidate ids (the toggle bar above the logs):
# - a preset -> that preset's matched sources (so excluded ones show too)
# - lgset -> the persisted manual working set
# - otherwise -> the currently selected sources
if show_others:
legend_ids = [s.source_id for s in all_sources if s.source_id in universe]
elif preset:
legend_ids = [s.source_id for s in all_sources
if s.source_id in log_ids and _preset_matches(s.name, preset["files"])]
elif lgset_ids:
legend_ids = [i for i in lgset_ids if i in existing_ids]
else:
legend_ids = [s.source_id for s in selected]
mode = args.get("mode", "merge")
if show_others:
mode = "separate" # non-log files are shown per-file, never merged
start_raw = args.get("start", "").strip()
end_raw = args.get("end", "").strip()
q_raw = args.get("q", "").strip()
qmode = args.get("qmode", "any").strip().lower()
if qmode not in ("any", "all"):
qmode = "any"
start = parse_filter_bound(start_raw)
end = parse_filter_bound(end_raw)
if flash_errors and start_raw and start is None:
flash(f"Could not parse start time: {start_raw!r}", "error")
if flash_errors and end_raw and end is None:
flash(f"Could not parse end time: {end_raw!r}", "error")
return {
"all_sources": all_sources, "selected_ids": selected_ids,
"selected": selected, "preset_key": preset_key if preset else "",
"legend_ids": legend_ids,
"show_others": show_others, "active_cat": cat, "cat_counts": cat_counts,
"log_count": len(log_ids), "other_count": len(other_ids),
"universe_ids": universe,
"mode": mode, "start_raw": start_raw, "end_raw": end_raw, "q_raw": q_raw,
"qmode": qmode,
"start": start, "end": end,
}
@app.route("/view")
def view():
sid = _get_session_id()
state = _current(sid)
if state and state.get("pending") and not state.get("sources"):
return redirect(url_for("select"))
if not state or not state["sources"]:
flash("Upload some logs first.", "info")
return redirect(url_for("index"))
sel = _resolve_selection(state, request.args)
all_sources = sel["all_sources"]
selected_ids = sel["selected_ids"]
selected = sel["selected"]
preset_key = sel["preset_key"]
legend_ids = sel["legend_ids"]
mode = sel["mode"]
start_raw, end_raw, q_raw = sel["start_raw"], sel["end_raw"], sel["q_raw"]
qmode = sel["qmode"]
start, end = sel["start"], sel["end"]
show_others = sel["show_others"]
other_count = sel["other_count"]
log_count = sel["log_count"]
universe_ids = sel["universe_ids"]
active_cat = sel["active_cat"]
cat_counts = sel["cat_counts"]
# Candidate sources for the clickable legend/toggle bar above the logs,
# ordered per legend_ids; each may be included (selected) or excluded.
by_id = state["sources"]
legend_candidates = [by_id[i] for i in legend_ids if i in by_id]
# Highlight a preset chip whenever the current selection equals that preset's
# matched set (regardless of how it was chosen).
active_preset = preset_key
if not active_preset:
for k, p in PRESETS.items():
matched = {s.source_id for s in all_sources
if _preset_matches(s.name, p["files"])}
if matched and matched == selected_ids:
active_preset = k
break
# Compact selection for links so hundreds of sources don't overflow URLs:
# enumerate whichever set is smaller (included vs. excluded), relative to the
# current universe (logs, or the non-log bundle when others=1).
if len(selected_ids) * 2 > len(universe_ids):
sel_kwargs = {"all": 1, "excl": sorted(universe_ids - selected_ids)}
else:
sel_kwargs = {"src": sorted(selected_ids)}
if show_others:
sel_kwargs["cat"] = active_cat
# Only persist an interactive legend set (<=40); larger falls back to a
# static capped legend, so the hidden field stays small.
legend_ids_str = ",".join(str(i) for i in legend_ids) if len(legend_ids) <= 40 else ""
# Pagination is optional. When disabled, page_size=None => one page of all.
if PAGINATE:
page = request.args.get("page", 1, type=int)
page_size = request.args.get("page_size", DEFAULT_PAGE_SIZE, type=int)
page_size = max(50, min(page_size, 5000))
else:
page = 1
page_size = None
color_map = {s.source_id: s.color for s in all_sources}
name_map = {s.source_id: s.name for s in all_sources}
def _base(name):
return name.split("/")[-1] if name else name
# Investigation bookmarks: pinned-line keys (basename, seq) + count,
# scoped to the currently loaded log folder / workspace.
username = session["username"]
bm_scope = _bookmark_scope(state)
user_bookmarks = BOOKMARKS.list(_notes_owner(state), bm_scope)
# New bookmarks identify a line by its unique source_id; legacy ones only
# carry a (possibly duplicate) basename. Track both: exact for new, best-
# effort for old.
pinned_ids = set()
pinned_names = set()
def _index_pin(rec):
try:
seq_ = int(rec.get("seq", -1))
except (TypeError, ValueError):
return
sid_ = rec.get("srcid")
if sid_ is not None:
try:
pinned_ids.add((int(sid_), seq_))
return
except (TypeError, ValueError):
pass
pinned_names.add((rec.get("source", ""), seq_))
for _b in user_bookmarks:
_index_pin(_b)