opticflow 0.1.0__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.
opticflow/__init__.py ADDED
@@ -0,0 +1,3 @@
1
+ """opticflow: watch one device's network flows live, from flow snapshots."""
2
+
3
+ __version__ = "0.1.0"
opticflow/__main__.py ADDED
@@ -0,0 +1,6 @@
1
+ import sys
2
+
3
+ from opticflow.cli import main
4
+
5
+ if __name__ == "__main__":
6
+ sys.exit(main())
opticflow/app.py ADDED
@@ -0,0 +1,470 @@
1
+ """The main loop: wait on the snapshot source and the keyboard, print tables."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import os
6
+ import select
7
+ import signal
8
+ import sys
9
+ import time
10
+ from dataclasses import dataclass
11
+ from typing import TextIO
12
+
13
+ from opticflow import __version__
14
+ from opticflow.capture import Capture, CaptureError, LogFiles, capture_filter, check_interface
15
+ from opticflow.filters import Address, Filters, involves, parse_age, parse_terms
16
+ from opticflow.formatting import byte_unit, clock, day
17
+ from opticflow.prompt import APPLY, CANCEL, KeyReader, LineEditor
18
+ from opticflow.snapshot import FormatError, Snapshot, SnapshotError, check_format, decode, parse
19
+ from opticflow.sources import Ended, Line, Notice, Overlong, Source, SourceError, open_source
20
+ from opticflow.table import Style, Symbols, TableView, plain, render, rows_for
21
+ from opticflow.terminal import Keyboard, Screen, Suspension
22
+
23
+ TICK = 0.5
24
+ QUIET_SNAPSHOTS = 3
25
+ STALE_INTERVALS = 3
26
+
27
+ FILTER_LABEL = "filter (any of, comma-separated; empty clears): "
28
+ AGE_LABEL = "max age in seconds (empty clears): "
29
+ HELP = [
30
+ "keys:",
31
+ " f filter: values separated by commas; a flow shows if any appears in any column",
32
+ " a max age: only flows at most this many seconds old",
33
+ " c clear both filters",
34
+ " ? this help",
35
+ " q quit (Ctrl-C also quits)",
36
+ "in a prompt: Enter applies, Esc cancels, Backspace deletes, Ctrl-U clears;",
37
+ "empty input clears that filter",
38
+ ]
39
+
40
+
41
+ class Stop(Exception):
42
+ """Leave the loop with this exit status."""
43
+
44
+ def __init__(self, status: int) -> None:
45
+ super().__init__(status)
46
+ self.status = status
47
+
48
+
49
+ class Fatal(Exception):
50
+ """An error that ends the program with status 1."""
51
+
52
+
53
+ @dataclass
54
+ class Options:
55
+ address: Address
56
+ source: str | None = None
57
+ log: str | None = None
58
+ interface: str | None = None
59
+ color: str = "auto"
60
+
61
+
62
+ def _signal_stop(signum: int, frame: object) -> None:
63
+ raise Stop(128 + signum)
64
+
65
+
66
+ class App:
67
+ def __init__(self, options: Options, out: TextIO, err: TextIO, stdin: TextIO | None) -> None:
68
+ self.options = options
69
+ self.out = out
70
+ self.err = err
71
+ self.stdin = stdin
72
+ self.device = str(options.address)
73
+ interactive = _isatty(out)
74
+ if options.color == "auto":
75
+ colour = interactive and not os.environ.get("NO_COLOR")
76
+ else:
77
+ colour = options.color == "always"
78
+ encoding = (getattr(out, "encoding", None) or "").lower().replace("-", "")
79
+ self.unicode = encoding in ("utf8", "utf8sig")
80
+ self.style = Style(colour)
81
+ self.symbols = Symbols.for_output(self.unicode)
82
+ self.screen = Screen(out, interactive)
83
+ self.keyboard: Keyboard | None = None
84
+ self.keys = KeyReader()
85
+ self.editor: LineEditor | None = None
86
+ self.editing: str | None = None
87
+ self.filters = Filters()
88
+ self.source: Source | None = None
89
+ self.logs: LogFiles | None = None
90
+ self.capture: Capture | None = None
91
+ self.latest: Snapshot | None = None
92
+ self.last_source = None
93
+ self.last_day: str | None = None
94
+ self.last_arrival = time.monotonic()
95
+ self.stale_noticed = False
96
+ self.seen_device = False
97
+ self.quiet = 0
98
+ self.narrow_hinted = False
99
+ self.failed = False
100
+ self.started = False
101
+ self.pending: list = [] # items read but not yet handled
102
+
103
+ # Output ------------------------------------------------------------------
104
+
105
+ def emit(self, screen_lines: list[str], log_lines: list[str] | None = None) -> None:
106
+ """Lines for the history: on screen, and in NAME.txt (plain text)."""
107
+ self.screen.write_lines(screen_lines)
108
+ if self.logs is not None:
109
+ self.logs.write_text(log_lines if log_lines is not None else screen_lines)
110
+
111
+ def say(self, text: str, kind: str | None = None) -> None:
112
+ line = [(kind, text)]
113
+ self.emit([self.style.line(line)], [text])
114
+
115
+ def error(self, text: str) -> None:
116
+ self.screen.clear_last()
117
+ self.err.write(f"opticflow: {text}\n")
118
+ self.err.flush()
119
+ if self.logs is not None:
120
+ self.logs.write_text([f"opticflow: {text}"])
121
+
122
+ def status(self, text: str) -> None:
123
+ """A short-lived last line, never kept in the history or the log."""
124
+ if self.editor is None:
125
+ self.screen.set_last(text[: max(1, (self.screen.width() or 80) - 1)])
126
+
127
+ # Start -------------------------------------------------------------------
128
+
129
+ def run(self) -> int:
130
+ previous = {
131
+ sig: signal.signal(sig, _signal_stop) for sig in (signal.SIGTERM, signal.SIGHUP)
132
+ }
133
+ suspension = None
134
+ status = 0
135
+ try:
136
+ if self.options.log:
137
+ self.logs = LogFiles.for_name(self.options.log)
138
+ self.logs.check_free()
139
+ self.source = open_source(self.options.source)
140
+ if self.screen.interactive:
141
+ self.keyboard = Keyboard.open(self.stdin)
142
+ if self.keyboard is not None:
143
+ self.keyboard.start()
144
+ suspension = Suspension(self.keyboard, self.screen)
145
+ suspension.install()
146
+ first = self.wait_for_first()
147
+ self.screen.clear_last() # the "waiting for the first snapshot" line
148
+ if self.logs is not None:
149
+ self.start_capture(first)
150
+ self.started = True
151
+ self.print_start(first)
152
+ if self.keyboard is None and self.screen.interactive:
153
+ self.say("no terminal to read keys from: keys are off")
154
+ self.show(first)
155
+ self.loop()
156
+ except Stop as stop:
157
+ status = stop.status
158
+ except KeyboardInterrupt:
159
+ status = 130
160
+ except (Fatal, SourceError, CaptureError, FormatError) as problem:
161
+ self.error(str(problem))
162
+ status = 1
163
+ finally:
164
+ self.screen.clear_last()
165
+ if suspension is not None:
166
+ suspension.uninstall()
167
+ if self.keyboard is not None:
168
+ self.keyboard.close()
169
+ status = self.finish(status)
170
+ if self.source is not None:
171
+ self.source.close()
172
+ for sig, handler in previous.items():
173
+ signal.signal(sig, handler)
174
+ return status
175
+
176
+ def wait_for_first(self) -> Snapshot:
177
+ assert self.source is not None
178
+ first_line = True
179
+ self.status(f"waiting for the first snapshot from {self.source.name} ...")
180
+ while True:
181
+ items = self.wait()
182
+ while items:
183
+ item = items.pop(0)
184
+ if isinstance(item, Ended):
185
+ raise Fatal(f"{self.source.name} ended before any snapshot arrived")
186
+ if isinstance(item, Notice):
187
+ self.status(item.text)
188
+ continue
189
+ if isinstance(item, Overlong):
190
+ if first_line:
191
+ raise Fatal(f"{self.source.name} does not look like a snapshot stream")
192
+ continue
193
+ try:
194
+ data = decode(item.data)
195
+ except SnapshotError:
196
+ if first_line:
197
+ raise Fatal(
198
+ f"{self.source.name} does not look like a snapshot stream "
199
+ "(the first line is not a JSON object)"
200
+ ) from None
201
+ continue
202
+ first_line = False
203
+ check_format(data)
204
+ try:
205
+ snapshot = parse(item.data)
206
+ except SnapshotError as problem:
207
+ self.status(f"skipped a damaged snapshot: {problem}")
208
+ continue
209
+ self.pending = items # the rest of this read, handled by the loop
210
+ return snapshot
211
+
212
+ def start_capture(self, first: Snapshot) -> None:
213
+ assert self.logs is not None
214
+ interface = self.options.interface or first.source.interface
215
+ if not interface:
216
+ raise Fatal("the snapshots name no interface; give one with --interface for -log")
217
+ check_interface(interface)
218
+ self.logs.create()
219
+ try:
220
+ self.status(f"starting the capture on {interface} ...")
221
+ assert self.logs.pcap_fd is not None
222
+ self.capture = Capture(self.logs.pcap_fd, interface, self.device)
223
+ self.capture.start()
224
+ except BaseException:
225
+ self.capture = None
226
+ self.logs.remove()
227
+ self.logs = None
228
+ raise
229
+ self.screen.clear_last()
230
+
231
+ def print_start(self, snapshot: Snapshot) -> None:
232
+ source = snapshot.source
233
+ dot = self.symbols.dot
234
+ parts = [
235
+ f"opticflow {__version__}",
236
+ f"device {self.device}",
237
+ f"from {self.source.name if self.source else '?'}",
238
+ f"{source.engine} {source.engine_version}",
239
+ f"labels by {source.labeler}",
240
+ f"bytes counted as {byte_unit(source.bytes)}",
241
+ ]
242
+ self.say(dot.join(parts), "title")
243
+ if self.logs is not None and self.capture is not None:
244
+ self.say(
245
+ f"saving {self.logs.text_path} and {self.logs.pcap_path} "
246
+ f"(dumpcap on {self.capture.interface}, {capture_filter(self.device)})",
247
+ "title",
248
+ )
249
+ if self.keyboard is not None:
250
+ self.say(f"keys: f filter{dot}a max age{dot}c clear{dot}? help{dot}q quit", "rule")
251
+ self.last_source = source
252
+
253
+ # Loop --------------------------------------------------------------------
254
+
255
+ def wait(self) -> list:
256
+ """Wait up to one tick for the source or the keyboard, and handle keys."""
257
+ assert self.source is not None
258
+ descriptors = []
259
+ source_fd = self.source.fileno()
260
+ if source_fd is not None:
261
+ descriptors.append(source_fd)
262
+ if self.keyboard is not None:
263
+ descriptors.append(self.keyboard.fd)
264
+ # select(), not poll() or the default selector: on macOS only select()
265
+ # accepts /dev/tty (see DECISIONS.md).
266
+ timeout = 0 if self.pending else TICK
267
+ try:
268
+ ready, _, _ = select.select(descriptors, [], [], timeout)
269
+ except InterruptedError: # pragma: no cover - retried by Python since 3.5
270
+ ready = []
271
+ if self.keyboard is not None and self.keyboard.fd in ready:
272
+ self.handle_keys(self.keyboard.read())
273
+ items, self.pending = self.pending + self.source.poll(), []
274
+ return items
275
+
276
+ def loop(self) -> None:
277
+ while True:
278
+ for item in self.wait():
279
+ if isinstance(item, Line):
280
+ self.handle_line(item.data)
281
+ elif isinstance(item, Overlong):
282
+ self.say("skipped a line longer than 64 MiB", "note")
283
+ elif isinstance(item, Notice):
284
+ self.say(item.text, "note")
285
+ elif isinstance(item, Ended):
286
+ raise Stop(1 if self.failed else 0)
287
+ self.check_health()
288
+
289
+ def handle_line(self, data: bytes) -> None:
290
+ try:
291
+ snapshot = parse(data)
292
+ except SnapshotError as problem:
293
+ self.say(f"skipped a damaged snapshot: {problem}", "note")
294
+ return
295
+ if snapshot.source != self.last_source:
296
+ self.print_start(snapshot)
297
+ self.show(snapshot)
298
+
299
+ def check_health(self) -> None:
300
+ if self.latest is not None and not self.stale_noticed:
301
+ silent = time.monotonic() - self.last_arrival
302
+ if silent > STALE_INTERVALS * max(self.latest.interval, 1.0):
303
+ self.say(f"no snapshot for {int(silent)} s", "note")
304
+ self.stale_noticed = True
305
+ if self.capture is not None:
306
+ problem = self.capture.problem()
307
+ if problem:
308
+ self.failed = True
309
+ self.say(problem + "; the text log continues", "note")
310
+
311
+ # Tables ------------------------------------------------------------------
312
+
313
+ def show(self, snapshot: Snapshot, again: bool = False) -> None:
314
+ if not again:
315
+ self.latest = snapshot
316
+ self.last_arrival = time.monotonic()
317
+ self.stale_noticed = False
318
+ mine = [flow for flow in snapshot.flows if involves(flow, self.options.address)]
319
+ mine.sort(key=lambda flow: (-flow.start, flow.id))
320
+ shown = [flow for flow in mine if self.filters.passes(flow)]
321
+ start_of_interval = snapshot.time - snapshot.interval
322
+ today = day(snapshot.time)
323
+ view = TableView(
324
+ when=clock(snapshot.time, with_date=today != self.last_day),
325
+ device=self.device,
326
+ rows=rows_for(shown),
327
+ device_flows=len(mine),
328
+ new=sum(1 for flow in shown if flow.start >= start_of_interval),
329
+ ended=sum(1 for flow in shown if flow.ended),
330
+ again=again,
331
+ filters=self.filters.describe(self.unicode),
332
+ notes=self.notes(snapshot),
333
+ )
334
+ self.last_day = today
335
+ screen_lines, layout = render(view, self.screen.width(), self.symbols)
336
+ if layout.too_narrow and not self.narrow_hinted:
337
+ self.say(f"widen the window to {layout.full_width} columns to see every column", "note")
338
+ self.narrow_hinted = True
339
+ elif not layout.too_narrow:
340
+ self.narrow_hinted = False
341
+ log_lines = None
342
+ if self.logs is not None:
343
+ log_lines = [plain(line) for line in render(view, None, self.symbols)[0]]
344
+ self.emit([""] + [self.style.line(line) for line in screen_lines], [""] + (log_lines or []))
345
+ if not again:
346
+ self.track_device(bool(mine))
347
+
348
+ def notes(self, snapshot: Snapshot) -> list[str]:
349
+ notes = []
350
+ if snapshot.dropped:
351
+ notes.append(f"{snapshot.dropped} packets dropped by the capture: counts too low")
352
+ if snapshot.untracked:
353
+ notes.append(
354
+ f"{snapshot.untracked} packets not counted (the engine's flow table was full)"
355
+ )
356
+ return notes
357
+
358
+ def track_device(self, present: bool) -> None:
359
+ if present:
360
+ self.seen_device = True
361
+ self.quiet = 0
362
+ return
363
+ if not self.seen_device:
364
+ return
365
+ self.quiet += 1
366
+ if self.quiet == QUIET_SNAPSHOTS:
367
+ self.say(
368
+ f"no flows for {self.device} in the last {QUIET_SNAPSHOTS} snapshots: "
369
+ "the device may be quiet, or have a new address",
370
+ "note",
371
+ )
372
+
373
+ # Keys --------------------------------------------------------------------
374
+
375
+ def handle_keys(self, data: bytes) -> None:
376
+ for key in self.keys.feed(data):
377
+ if self.editor is not None:
378
+ self.edit(key)
379
+ elif key == "q":
380
+ raise Stop(1 if self.failed else 0)
381
+ elif key == "f":
382
+ self.open_editor("filter", FILTER_LABEL, self.filters.terms_text())
383
+ elif key == "a":
384
+ self.open_editor("age", AGE_LABEL, self.filters.age_text())
385
+ elif key == "c":
386
+ if self.filters.active:
387
+ self.filters = Filters()
388
+ self.reshow()
389
+ else:
390
+ self.say("no filters to clear")
391
+ elif key == "?":
392
+ self.emit(HELP)
393
+
394
+ def open_editor(self, what: str, label: str, text: str) -> None:
395
+ self.editing = what
396
+ self.editor = LineEditor(label, text)
397
+ self.screen.set_last(self.editor.display(self.screen.width()))
398
+
399
+ def edit(self, key: str) -> None:
400
+ assert self.editor is not None
401
+ result = self.editor.key(key)
402
+ if result is None:
403
+ return
404
+ if result == CANCEL:
405
+ self.close_editor()
406
+ return
407
+ if result != APPLY:
408
+ self.screen.set_last(self.editor.display(self.screen.width()))
409
+ return
410
+ text, what = self.editor.text, self.editing
411
+ self.close_editor()
412
+ if what == "filter":
413
+ changed = Filters(parse_terms(text), self.filters.max_age)
414
+ else:
415
+ try:
416
+ changed = Filters(self.filters.terms, parse_age(text))
417
+ except ValueError as problem:
418
+ self.say(f"{problem}; the age filter is unchanged", "note")
419
+ return
420
+ if changed != self.filters:
421
+ self.filters = changed
422
+ self.reshow()
423
+
424
+ def close_editor(self) -> None:
425
+ self.editor = None
426
+ self.editing = None
427
+ self.screen.clear_last()
428
+
429
+ def reshow(self) -> None:
430
+ if self.latest is not None:
431
+ self.show(self.latest, again=True)
432
+
433
+ # End ---------------------------------------------------------------------
434
+
435
+ def finish(self, status: int) -> int:
436
+ if self.capture is not None:
437
+ summary = self.capture.stop()
438
+ self.capture = None
439
+ details = []
440
+ if summary.captured is not None:
441
+ details.append(_packets(summary.captured))
442
+ if summary.dropped:
443
+ details.append(f"{summary.dropped} dropped by the capture")
444
+ message = f"saved {self.logs.text_path} and {self.logs.pcap_path}" if self.logs else ""
445
+ if details:
446
+ message += " (" + ", ".join(details) + ")"
447
+ if summary.problem:
448
+ self.failed = True
449
+ message += f"; {summary.problem}"
450
+ self.say(message, "note" if summary.problem else "title")
451
+ if self.logs is not None:
452
+ self.logs.close()
453
+ if self.failed and status == 0:
454
+ return 1
455
+ return status
456
+
457
+
458
+ def _packets(count: int) -> str:
459
+ return f"{count} packet" if count == 1 else f"{count} packets"
460
+
461
+
462
+ def _isatty(stream: TextIO) -> bool:
463
+ try:
464
+ return stream.isatty()
465
+ except (AttributeError, ValueError):
466
+ return False
467
+
468
+
469
+ def run(options: Options) -> int:
470
+ return App(options, sys.stdout, sys.stderr, sys.stdin).run()