@torrent-tv/proxy 2.55.14 → 2.57.0
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.
- package/CHANGELOG.md +1169 -1150
- package/bin/cli.js +494 -478
- package/package.json +1 -1
- package/routes/api/subtitles/get.js +13 -4
- package/services/container-index/matroska-subtitles.js +6 -0
- package/services/container-index/mp4-subtitles.js +25 -1
- package/services/data-channel-handler.js +1133 -949
- package/services/delivery-probe.js +338 -255
- package/services/packet-witness.js +784 -406
- package/services/torrent-worker/client.js +2 -1
- package/services/torrent-worker/subtitle-cues.js +182 -21
- package/services/torrent-worker/worker.js +28 -2
- package/test/delivery-probe.test.js +124 -78
- package/test/packet-witness-ring.test.js +236 -0
- package/test/packet-witness.test.js +148 -120
- package/test/subtitle-track-numbering.test.js +262 -0
- package/test/wedge-certainty.test.js +131 -0
|
@@ -1,406 +1,784 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* @file
|
|
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
|
-
export
|
|
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
|
-
* @param {
|
|
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
|
-
const
|
|
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
|
-
}
|
|
1
|
+
/**
|
|
2
|
+
* @file Packet witness for the delivery freeze: a ring that is always running,
|
|
3
|
+
* and a tail that outlasts the sender's own retransmission timeout.
|
|
4
|
+
*
|
|
5
|
+
* Roadmap item 11. Two captures taken by the earlier version of this file, read
|
|
6
|
+
* on 2026-08-26 (`research/delivery-freeze-sender-silent-2026-08-26.md`), place
|
|
7
|
+
* the failure: while a channel held 67 MB, the proxy put NO packet larger than
|
|
8
|
+
* 89 bytes of UDP payload on the wire for 28 s, twice, in two separate
|
|
9
|
+
* episodes. The receiver never had anything to drop, the path carried STUN and
|
|
10
|
+
* the browser's own requests throughout, and `usrsctp_sendv` refused every byte
|
|
11
|
+
* for 54 minutes. What those captures could NOT show is what happened at the
|
|
12
|
+
* ONSET, because they began 30 s after the queue was already declared stuck,
|
|
13
|
+
* and what happens beyond 28 s, because that is where they stopped.
|
|
14
|
+
*
|
|
15
|
+
* So the capture is in two halves now.
|
|
16
|
+
*
|
|
17
|
+
* The RING runs the whole time a data channel is open, size-bounded and
|
|
18
|
+
* wrapping, filtered to the WebRTC UDP port. It costs a rotating file on disk
|
|
19
|
+
* and nothing else, and it means the seconds BEFORE a freeze are already
|
|
20
|
+
* recorded when the freeze is noticed. On a wedge its files are copied aside
|
|
21
|
+
* before the wrap can reach them.
|
|
22
|
+
*
|
|
23
|
+
* The TAIL then records the wedged session's own 5-tuple for
|
|
24
|
+
* {@linkcode WITNESS_TAIL_SECONDS}, which is three times usrsctp's maximum
|
|
25
|
+
* retransmission timeout. That length is what turns "no zero-window probe in
|
|
26
|
+
* the 28 s we watched" into a statement about the sender: a stalled SCTP sender
|
|
27
|
+
* whose peer advertises a zero window MUST probe once per timeout, and the
|
|
28
|
+
* timeout cannot exceed {@linkcode WITNESS_RTO_CEILING_SECONDS}. Silence across
|
|
29
|
+
* three of those is not a sampling gap.
|
|
30
|
+
*
|
|
31
|
+
* Bounded so it can never cost more than an episode is worth: the ring is
|
|
32
|
+
* capped in bytes and deleted when the last channel closes, the tail process is
|
|
33
|
+
* killed after its window plus grace, one tail runs at a time with a cooldown,
|
|
34
|
+
* and old captures are pruned at startup like core dumps.
|
|
35
|
+
*/
|
|
36
|
+
|
|
37
|
+
import { spawn } from "node:child_process";
|
|
38
|
+
import { copyFile, readdir, rename, rm, stat } from "node:fs/promises";
|
|
39
|
+
import os from "node:os";
|
|
40
|
+
import path from "node:path";
|
|
41
|
+
|
|
42
|
+
import { dumpsToRemove } from "./core-dumps.js";
|
|
43
|
+
|
|
44
|
+
/** Per-packet capture length. Small: headers are what the signatures need. */
|
|
45
|
+
export const WITNESS_SNAPLEN_BYTES = 128;
|
|
46
|
+
|
|
47
|
+
/**
|
|
48
|
+
* usrsctp's maximum retransmission timeout, seconds (its `RTO.max` default).
|
|
49
|
+
*
|
|
50
|
+
* Not ours to choose: it is the longest a stalled SCTP sender may wait before
|
|
51
|
+
* it must try again, so it is the shortest window in which silence means
|
|
52
|
+
* anything at all.
|
|
53
|
+
*/
|
|
54
|
+
export const WITNESS_RTO_CEILING_SECONDS = 60;
|
|
55
|
+
|
|
56
|
+
/**
|
|
57
|
+
* How long the tail capture records the wedged session, seconds.
|
|
58
|
+
*
|
|
59
|
+
* Three retransmission timeouts. One would leave the answer to a single
|
|
60
|
+
* scheduling accident; three is silence that has had three chances to break.
|
|
61
|
+
*/
|
|
62
|
+
export const WITNESS_TAIL_SECONDS = WITNESS_RTO_CEILING_SECONDS * 3;
|
|
63
|
+
|
|
64
|
+
/** Megabytes per ring file before tcpdump rotates to the next. */
|
|
65
|
+
export const WITNESS_RING_FILE_MB = 16;
|
|
66
|
+
|
|
67
|
+
/** How many ring files wrap around (16 MB × 4 = 64 MB of history). */
|
|
68
|
+
export const WITNESS_RING_FILES = 4;
|
|
69
|
+
|
|
70
|
+
/** Megabytes per tail file. A wedged session emits a few packets a second. */
|
|
71
|
+
export const WITNESS_TAIL_FILE_MB = 8;
|
|
72
|
+
|
|
73
|
+
/** How many tail files may be written before tcpdump stops on its own. */
|
|
74
|
+
export const WITNESS_TAIL_FILES = 2;
|
|
75
|
+
|
|
76
|
+
/** Extra time before the SIGKILL fallback lands on a hanging tcpdump. */
|
|
77
|
+
export const WITNESS_KILL_GRACE_MS = 5_000;
|
|
78
|
+
|
|
79
|
+
/** Minimum spacing between tail captures, whatever the reason for them. */
|
|
80
|
+
export const WITNESS_COOLDOWN_MS = 10 * 60_000;
|
|
81
|
+
|
|
82
|
+
/** How many old captures survive at startup, newest first. */
|
|
83
|
+
export const WITNESS_CAPTURES_KEPT = 8;
|
|
84
|
+
|
|
85
|
+
/** Base name of the rolling ring, before tcpdump appends its file number. */
|
|
86
|
+
export const WITNESS_RING_BASENAME = "packet-witness-ring.pcap";
|
|
87
|
+
|
|
88
|
+
/**
|
|
89
|
+
* The remote endpoint of a transport snapshot, already structured.
|
|
90
|
+
*
|
|
91
|
+
* @typedef {Object} WitnessRemoteEndpoint
|
|
92
|
+
* @property {string} address - IP literal (may carry a `%zone` suffix).
|
|
93
|
+
* @property {number} port
|
|
94
|
+
*/
|
|
95
|
+
|
|
96
|
+
/**
|
|
97
|
+
* What the watcher hands over when a wedge crosses the capture threshold.
|
|
98
|
+
*
|
|
99
|
+
* @typedef {Object} WitnessTrigger
|
|
100
|
+
* @property {string} sessionId
|
|
101
|
+
* @property {string} tag - Session id, first 8 characters.
|
|
102
|
+
* @property {string} label - Data channel label ("proxy", "proxy-control").
|
|
103
|
+
* @property {WitnessRemoteEndpoint | null} remote
|
|
104
|
+
* @property {number} queuedBytes
|
|
105
|
+
* @property {number} stuckForMs
|
|
106
|
+
*/
|
|
107
|
+
|
|
108
|
+
/**
|
|
109
|
+
* Strip a zone suffix and keep only IPv4/IPv6 literals.
|
|
110
|
+
*
|
|
111
|
+
* The address travels into a tcpdump BPF filter argument. The child is spawned
|
|
112
|
+
* as an argv array (no shell), so injection is not reachable, but a garbage or
|
|
113
|
+
* hostname value would produce a capture of nothing — rejected instead, so the
|
|
114
|
+
* log can say why nothing was written.
|
|
115
|
+
*
|
|
116
|
+
* @param {unknown} raw - Address as libdatachannel reports it.
|
|
117
|
+
* @returns {string | null} A clean literal, or null when not usable.
|
|
118
|
+
*/
|
|
119
|
+
export function normalizeRemoteAddress(raw) {
|
|
120
|
+
if (typeof raw !== "string") {
|
|
121
|
+
return null;
|
|
122
|
+
}
|
|
123
|
+
const zoneFree = raw.replace(/%.*$/, "");
|
|
124
|
+
if (zoneFree.length === 0 || zoneFree.length > 45) {
|
|
125
|
+
return null;
|
|
126
|
+
}
|
|
127
|
+
const ipv4 = /^(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}$/;
|
|
128
|
+
// Hex groups and at most one "::" compression — enough to keep hostnames,
|
|
129
|
+
// decimal-octet junk and shell metacharacters out of the filter.
|
|
130
|
+
const ipv6 = /^(?:[0-9A-Fa-f]{0,4}:){2,7}[0-9A-Fa-f]{0,4}$/;
|
|
131
|
+
if (ipv4.test(zoneFree) || (zoneFree.includes(":") && ipv6.test(zoneFree))) {
|
|
132
|
+
return zoneFree;
|
|
133
|
+
}
|
|
134
|
+
return null;
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
/**
|
|
138
|
+
* The tcpdump command line for a size-rotated capture.
|
|
139
|
+
*
|
|
140
|
+
* `-i any` covers hosts where the UDP mux socket is not on a named interface;
|
|
141
|
+
* `-n` keeps DNS out of the hot path; `-S` prints absolute sequence numbers so
|
|
142
|
+
* duplicate SACKs across file rotations compare equal by eye.
|
|
143
|
+
*
|
|
144
|
+
* Rotation is by SIZE, not by time, and that is a correction rather than a
|
|
145
|
+
* preference. `-G <seconds>` with `-W <count>` and a file name carrying no
|
|
146
|
+
* strftime field makes every rotation write the SAME name: the four files the
|
|
147
|
+
* previous version believed it was keeping were one file overwritten four
|
|
148
|
+
* times, which is why both field captures hold 28 s and not the intended 120.
|
|
149
|
+
* `-C <megabytes>` with `-W <count>` appends a number to the name and wraps
|
|
150
|
+
* around, which is the ring this needs — and a byte bound is the right bound
|
|
151
|
+
* anyway, because the rate varies by two orders of magnitude between a wedged
|
|
152
|
+
* session and a healthy burst.
|
|
153
|
+
*
|
|
154
|
+
* @param {Object} parts
|
|
155
|
+
* @param {string} [parts.host] - Validated IP literal; omitted captures every peer.
|
|
156
|
+
* @param {number} parts.port - The WebRTC UDP port.
|
|
157
|
+
* @param {string} parts.filePrefix - Path prefix; tcpdump appends the file number.
|
|
158
|
+
* @param {number} [parts.snaplen] - Bytes per packet to store.
|
|
159
|
+
* @param {number} [parts.fileMegabytes]
|
|
160
|
+
* @param {number} [parts.files]
|
|
161
|
+
* @returns {string[]}
|
|
162
|
+
*/
|
|
163
|
+
export function buildTcpdumpArgs({
|
|
164
|
+
host = "",
|
|
165
|
+
port,
|
|
166
|
+
filePrefix,
|
|
167
|
+
snaplen = WITNESS_SNAPLEN_BYTES,
|
|
168
|
+
fileMegabytes = WITNESS_RING_FILE_MB,
|
|
169
|
+
files = WITNESS_RING_FILES
|
|
170
|
+
}) {
|
|
171
|
+
const filter = ["udp", "and", "port", String(port)];
|
|
172
|
+
if (host) {
|
|
173
|
+
filter.push("and", "host", host);
|
|
174
|
+
}
|
|
175
|
+
return [
|
|
176
|
+
"-n",
|
|
177
|
+
"-S",
|
|
178
|
+
"-s",
|
|
179
|
+
String(snaplen),
|
|
180
|
+
"-i",
|
|
181
|
+
"any",
|
|
182
|
+
"-w",
|
|
183
|
+
filePrefix,
|
|
184
|
+
"-C",
|
|
185
|
+
String(fileMegabytes),
|
|
186
|
+
"-W",
|
|
187
|
+
String(files),
|
|
188
|
+
...filter
|
|
189
|
+
];
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
/**
|
|
193
|
+
* Whether a new capture may start right now.
|
|
194
|
+
*
|
|
195
|
+
* Pure, so the gating rule is testable without clocks or processes: never two
|
|
196
|
+
* at once, and none within the cooldown of the previous one. `lastStartedAt`
|
|
197
|
+
* of 0 means this process has not captured yet.
|
|
198
|
+
*
|
|
199
|
+
* @param {{ running: boolean, lastStartedAt: number, now?: number, cooldownMs?: number }} state
|
|
200
|
+
* @returns {boolean}
|
|
201
|
+
*/
|
|
202
|
+
export function shouldStartCapture({ running, lastStartedAt, now = Date.now(), cooldownMs = WITNESS_COOLDOWN_MS }) {
|
|
203
|
+
if (running) {
|
|
204
|
+
return false;
|
|
205
|
+
}
|
|
206
|
+
return lastStartedAt <= 0 || now - lastStartedAt >= cooldownMs;
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
/**
|
|
210
|
+
* Whether a file name is a capture this module wrote (including the
|
|
211
|
+
* timestamp-suffixed rotations tcpdump appends under `-G`).
|
|
212
|
+
*
|
|
213
|
+
* @param {string} name
|
|
214
|
+
* @returns {boolean}
|
|
215
|
+
*/
|
|
216
|
+
export function isWitnessCapture(name) {
|
|
217
|
+
return typeof name === "string" && /^packet-witness\.[^/\\]+\.pcap/.test(name);
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
/**
|
|
221
|
+
* Whether a file name is one of the rolling ring's own files.
|
|
222
|
+
*
|
|
223
|
+
* The ring is scratch, not evidence: it wraps, and it is deleted when the last
|
|
224
|
+
* channel closes. Only the copies taken at a wedge are kept, and those are
|
|
225
|
+
* named so that {@link isWitnessCapture} — and therefore the pruner — sees
|
|
226
|
+
* them and the ring's own files are left alone.
|
|
227
|
+
*
|
|
228
|
+
* @param {string} name
|
|
229
|
+
* @returns {boolean}
|
|
230
|
+
*/
|
|
231
|
+
export function isWitnessRingFile(name) {
|
|
232
|
+
return typeof name === "string" && name.startsWith(WITNESS_RING_BASENAME) && !name.includes("/") && !name.includes("\\");
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
/**
|
|
236
|
+
* Delete all but the newest few captures in `dir`.
|
|
237
|
+
*
|
|
238
|
+
* Mirrors `pruneCoreDumps`: best-effort, never fatal, one summary line.
|
|
239
|
+
*
|
|
240
|
+
* @param {string} dir
|
|
241
|
+
* @param {number} [keep]
|
|
242
|
+
* @returns {Promise<void>}
|
|
243
|
+
*/
|
|
244
|
+
export async function pruneWitnessCaptures(dir, keep = WITNESS_CAPTURES_KEPT) {
|
|
245
|
+
if (typeof dir !== "string" || dir.length === 0) {
|
|
246
|
+
return;
|
|
247
|
+
}
|
|
248
|
+
/** @type {Array<{ name: string, writtenAt: number, bytes: number }>} */
|
|
249
|
+
const captures = [];
|
|
250
|
+
try {
|
|
251
|
+
for (const name of await readdir(dir)) {
|
|
252
|
+
if (!isWitnessCapture(name)) {
|
|
253
|
+
continue;
|
|
254
|
+
}
|
|
255
|
+
try {
|
|
256
|
+
const info = await stat(path.join(dir, name));
|
|
257
|
+
if (info.isFile()) {
|
|
258
|
+
captures.push({ name, writtenAt: info.mtimeMs, bytes: info.size });
|
|
259
|
+
}
|
|
260
|
+
} catch {
|
|
261
|
+
// silent-ok: vanished between listing and reading.
|
|
262
|
+
}
|
|
263
|
+
}
|
|
264
|
+
} catch {
|
|
265
|
+
return; // No such directory, or unreadable. Nothing to tidy.
|
|
266
|
+
}
|
|
267
|
+
if (captures.length === 0) {
|
|
268
|
+
return;
|
|
269
|
+
}
|
|
270
|
+
const doomed = dumpsToRemove(captures, keep);
|
|
271
|
+
const freed = captures
|
|
272
|
+
.filter((capture) => doomed.includes(capture.name))
|
|
273
|
+
.reduce((total, capture) => total + capture.bytes, 0);
|
|
274
|
+
for (const name of doomed) {
|
|
275
|
+
try {
|
|
276
|
+
await rm(path.join(dir, name), { force: true });
|
|
277
|
+
} catch {
|
|
278
|
+
// silent-ok: best effort, retried at the next start.
|
|
279
|
+
}
|
|
280
|
+
}
|
|
281
|
+
const keptBytes = captures
|
|
282
|
+
.filter((capture) => !doomed.includes(capture.name))
|
|
283
|
+
.reduce((total, capture) => total + capture.bytes, 0);
|
|
284
|
+
if (freed > 0 || captures.length > keep) {
|
|
285
|
+
logLine(
|
|
286
|
+
`packet witness: ${captures.length} capture(s) present, keeping the newest ${Math.min(keep, captures.length)}, ` +
|
|
287
|
+
`removed ${doomed.length} (${(freed / 1024).toFixed(1)} KB), keeping ${(keptBytes / 1024).toFixed(1)} KB`
|
|
288
|
+
);
|
|
289
|
+
}
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
/**
|
|
293
|
+
* Turn ring files left by a previous process into evidence, at startup.
|
|
294
|
+
*
|
|
295
|
+
* The ring is scratch while a process lives, but a process that was KILLED —
|
|
296
|
+
* which the crash family of roadmap item 1 does regularly, seven times in a
|
|
297
|
+
* fortnight — leaves behind the last seconds it recorded, and those seconds
|
|
298
|
+
* contain the death. Renaming them under a name the pruner recognises keeps
|
|
299
|
+
* them; without this the next viewer's first channel would delete them before
|
|
300
|
+
* anyone had looked.
|
|
301
|
+
*
|
|
302
|
+
* @param {string} dir
|
|
303
|
+
* @returns {Promise<string[]>} Names of the files adopted.
|
|
304
|
+
*/
|
|
305
|
+
export async function adoptOrphanRingFiles(dir) {
|
|
306
|
+
if (typeof dir !== "string" || dir.length === 0) {
|
|
307
|
+
return [];
|
|
308
|
+
}
|
|
309
|
+
/** @type {string[]} */
|
|
310
|
+
const adopted = [];
|
|
311
|
+
let names;
|
|
312
|
+
try {
|
|
313
|
+
names = (await readdir(dir)).filter((name) => isWitnessRingFile(name)).sort();
|
|
314
|
+
} catch {
|
|
315
|
+
return adopted;
|
|
316
|
+
}
|
|
317
|
+
if (names.length === 0) {
|
|
318
|
+
return adopted;
|
|
319
|
+
}
|
|
320
|
+
const stampSeconds = Math.floor(Date.now() / 1000);
|
|
321
|
+
for (const name of names) {
|
|
322
|
+
const suffix = name.slice(WITNESS_RING_BASENAME.length) || "0";
|
|
323
|
+
const target = `packet-witness.orphan.${stampSeconds}.before${suffix}.pcap`;
|
|
324
|
+
try {
|
|
325
|
+
await rename(path.join(dir, name), path.join(dir, target));
|
|
326
|
+
adopted.push(target);
|
|
327
|
+
} catch {
|
|
328
|
+
// silent-ok: unreadable or already gone.
|
|
329
|
+
}
|
|
330
|
+
}
|
|
331
|
+
if (adopted.length > 0) {
|
|
332
|
+
logLine(
|
|
333
|
+
`packet witness: ${adopted.length} ring file(s) survived the previous process and were kept ` +
|
|
334
|
+
`as ${adopted.join(", ")} — whatever ended it is in them`
|
|
335
|
+
);
|
|
336
|
+
}
|
|
337
|
+
return adopted;
|
|
338
|
+
}
|
|
339
|
+
|
|
340
|
+
/**
|
|
341
|
+
* The logger handed to {@linkcode createPacketWitness}; module-level so the
|
|
342
|
+
* pruner can speak without an options bag threaded everywhere.
|
|
343
|
+
*
|
|
344
|
+
* @type {(message: string) => void}
|
|
345
|
+
*/
|
|
346
|
+
let logLine = () => {};
|
|
347
|
+
|
|
348
|
+
/**
|
|
349
|
+
* Create the witness.
|
|
350
|
+
*
|
|
351
|
+
* @param {Object} options
|
|
352
|
+
* @param {(message: string) => void} options.log - Log sink (the shared logger).
|
|
353
|
+
* @param {string} [options.dir] - Where captures go; empty means os.tmpdir().
|
|
354
|
+
* @param {number} options.port - The WebRTC UDP port to filter on.
|
|
355
|
+
* @param {typeof spawn} [options.spawnProcess] - Seam for tests; defaults to node's spawn.
|
|
356
|
+
* @returns {{
|
|
357
|
+
* dir: string,
|
|
358
|
+
* maybeCapture: (trigger: WitnessTrigger) => boolean,
|
|
359
|
+
* holdRing: () => void,
|
|
360
|
+
* releaseRing: () => void
|
|
361
|
+
* }}
|
|
362
|
+
*/
|
|
363
|
+
export function createPacketWitness({ log, dir = "", port, spawnProcess = spawn }) {
|
|
364
|
+
logLine = typeof log === "function" ? log : logLine;
|
|
365
|
+
const resolvedDir = typeof dir === "string" && dir.length > 0 ? dir : os.tmpdir();
|
|
366
|
+
|
|
367
|
+
/** @type {{ running: boolean, lastStartedAt: number, availability: "unknown" | "yes" | "no" }} */
|
|
368
|
+
const state = { running: false, lastStartedAt: 0, availability: "unknown" };
|
|
369
|
+
|
|
370
|
+
/**
|
|
371
|
+
* Ask whether tcpdump exists at all — once per process, whichever way it
|
|
372
|
+
* answers. A host without it gets exactly one log line, ever.
|
|
373
|
+
*
|
|
374
|
+
* @returns {Promise<boolean>}
|
|
375
|
+
*/
|
|
376
|
+
const probeAvailability = () =>
|
|
377
|
+
new Promise((resolve) => {
|
|
378
|
+
let settled = false;
|
|
379
|
+
const done = (value) => {
|
|
380
|
+
if (!settled) {
|
|
381
|
+
settled = true;
|
|
382
|
+
resolve(value);
|
|
383
|
+
}
|
|
384
|
+
};
|
|
385
|
+
try {
|
|
386
|
+
const probe = spawnProcess("tcpdump", ["--version"], { stdio: "ignore" });
|
|
387
|
+
probe.on("error", () => done(false));
|
|
388
|
+
probe.on("spawn", () => done(true));
|
|
389
|
+
probe.on("close", () => done(true));
|
|
390
|
+
} catch {
|
|
391
|
+
done(false);
|
|
392
|
+
}
|
|
393
|
+
});
|
|
394
|
+
|
|
395
|
+
/**
|
|
396
|
+
* Keep the ring's history: stop it, copy its files, start it again.
|
|
397
|
+
*
|
|
398
|
+
* This is the half of the evidence the earlier version never had — the
|
|
399
|
+
* seconds BEFORE the freeze. Stopping first is not tidiness: tcpdump buffers,
|
|
400
|
+
* so the newest packets are only on disk once it has been asked to finish,
|
|
401
|
+
* and the file it is currently writing is the one that holds the onset. The
|
|
402
|
+
* gap this leaves is a fraction of a second, and the tail capture that
|
|
403
|
+
* follows covers everything after it.
|
|
404
|
+
*
|
|
405
|
+
* @param {WitnessTrigger} trigger
|
|
406
|
+
* @param {number} stampSeconds - Shared with the tail, so the pair sorts together.
|
|
407
|
+
* @returns {Promise<string[]>} Names of the copies that landed.
|
|
408
|
+
*/
|
|
409
|
+
const preserveRing = async (trigger, stampSeconds) => {
|
|
410
|
+
/** @type {string[]} */
|
|
411
|
+
const kept = [];
|
|
412
|
+
ring.preserving = true;
|
|
413
|
+
try {
|
|
414
|
+
await stopRingProcess();
|
|
415
|
+
let names;
|
|
416
|
+
try {
|
|
417
|
+
names = (await readdir(resolvedDir)).filter((name) => isWitnessRingFile(name)).sort();
|
|
418
|
+
} catch {
|
|
419
|
+
return kept;
|
|
420
|
+
}
|
|
421
|
+
for (const name of names) {
|
|
422
|
+
const suffix = name.slice(WITNESS_RING_BASENAME.length) || "0";
|
|
423
|
+
const target = `packet-witness.${trigger.tag}.${stampSeconds}.before${suffix}.pcap`;
|
|
424
|
+
try {
|
|
425
|
+
await copyFile(path.join(resolvedDir, name), path.join(resolvedDir, target));
|
|
426
|
+
kept.push(target);
|
|
427
|
+
} catch {
|
|
428
|
+
// silent-ok: nothing to copy, or it vanished under us.
|
|
429
|
+
}
|
|
430
|
+
}
|
|
431
|
+
return kept;
|
|
432
|
+
} finally {
|
|
433
|
+
ring.preserving = false;
|
|
434
|
+
// Back to recording, unless everyone has gone in the meantime.
|
|
435
|
+
if (ring.holders > 0) {
|
|
436
|
+
await startRingProcess();
|
|
437
|
+
} else {
|
|
438
|
+
await clearRingFiles();
|
|
439
|
+
}
|
|
440
|
+
}
|
|
441
|
+
};
|
|
442
|
+
|
|
443
|
+
/**
|
|
444
|
+
* Run one bounded capture and report what it wrote.
|
|
445
|
+
*
|
|
446
|
+
* @param {WitnessTrigger} trigger
|
|
447
|
+
* @param {string} address - Validated remote IP literal.
|
|
448
|
+
* @param {number} stampSeconds
|
|
449
|
+
* @returns {Promise<void>}
|
|
450
|
+
*/
|
|
451
|
+
const runCapture = async (trigger, address, stampSeconds) => {
|
|
452
|
+
const prefix = path.join(
|
|
453
|
+
resolvedDir,
|
|
454
|
+
`packet-witness.${trigger.tag}.${stampSeconds}.tail.pcap`
|
|
455
|
+
);
|
|
456
|
+
const args = buildTcpdumpArgs({
|
|
457
|
+
host: address,
|
|
458
|
+
port,
|
|
459
|
+
filePrefix: prefix,
|
|
460
|
+
fileMegabytes: WITNESS_TAIL_FILE_MB,
|
|
461
|
+
files: WITNESS_TAIL_FILES
|
|
462
|
+
});
|
|
463
|
+
logLine(
|
|
464
|
+
`packet witness: capturing ${WITNESS_TAIL_SECONDS}s of udp port ${port} ↔ ${address} ` +
|
|
465
|
+
`(session ${trigger.tag}, "${trigger.label}" queue ${trigger.queuedBytes}B wedged ` +
|
|
466
|
+
`${Math.round(trigger.stuckForMs / 1000)}s; ${WITNESS_TAIL_SECONDS}s is three times ` +
|
|
467
|
+
`usrsctp's ${WITNESS_RTO_CEILING_SECONDS}s retransmission ceiling, so a zero-window ` +
|
|
468
|
+
`probe cannot hide inside it) → ${prefix}`
|
|
469
|
+
);
|
|
470
|
+
await new Promise((resolve) => {
|
|
471
|
+
/** @type {ReturnType<typeof setTimeout> | null} */
|
|
472
|
+
let killer = null;
|
|
473
|
+
/** @type {NodeJS.Timeout | null} */
|
|
474
|
+
let hardKill = null;
|
|
475
|
+
let child;
|
|
476
|
+
try {
|
|
477
|
+
child = spawnProcess("tcpdump", args, { stdio: "ignore" });
|
|
478
|
+
} catch (error) {
|
|
479
|
+
logLine(`packet witness: could not start tcpdump: ${error?.message ?? error}`);
|
|
480
|
+
resolve();
|
|
481
|
+
return;
|
|
482
|
+
}
|
|
483
|
+
const finish = () => {
|
|
484
|
+
if (killer) {
|
|
485
|
+
clearTimeout(killer);
|
|
486
|
+
killer = null;
|
|
487
|
+
}
|
|
488
|
+
if (hardKill) {
|
|
489
|
+
clearTimeout(hardKill);
|
|
490
|
+
hardKill = null;
|
|
491
|
+
}
|
|
492
|
+
resolve();
|
|
493
|
+
};
|
|
494
|
+
child.on("error", (error) => {
|
|
495
|
+
state.availability = "no";
|
|
496
|
+
logLine(`packet witness: tcpdump failed to run: ${error?.message ?? error}`);
|
|
497
|
+
finish();
|
|
498
|
+
});
|
|
499
|
+
child.on("close", (code, signal) => {
|
|
500
|
+
logLine(
|
|
501
|
+
`packet witness: capture ended${signal ? ` (${signal})` : ` (exit ${code ?? "?"})`}`
|
|
502
|
+
);
|
|
503
|
+
finish();
|
|
504
|
+
});
|
|
505
|
+
killer = setTimeout(() => {
|
|
506
|
+
try { child.kill("SIGTERM"); } catch { /* already gone */ }
|
|
507
|
+
hardKill = setTimeout(() => {
|
|
508
|
+
try { child.kill("SIGKILL"); } catch { /* already gone */ }
|
|
509
|
+
}, WITNESS_KILL_GRACE_MS);
|
|
510
|
+
}, WITNESS_TAIL_SECONDS * 1000);
|
|
511
|
+
});
|
|
512
|
+
// Say what landed on disk, so whoever reads the log later knows whether
|
|
513
|
+
// the evidence exists without listing the directory themselves.
|
|
514
|
+
try {
|
|
515
|
+
const names = (await readdir(resolvedDir)).filter((name) => isWitnessCapture(name));
|
|
516
|
+
const mine = [];
|
|
517
|
+
for (const name of names) {
|
|
518
|
+
if (!name.startsWith(path.basename(prefix))) {
|
|
519
|
+
continue;
|
|
520
|
+
}
|
|
521
|
+
try {
|
|
522
|
+
const info = await stat(path.join(resolvedDir, name));
|
|
523
|
+
mine.push(`${name} ${(info.size / 1024).toFixed(1)} KB`);
|
|
524
|
+
} catch { /* gone between listing and reading */ }
|
|
525
|
+
}
|
|
526
|
+
logLine(`packet witness: wrote ${mine.length} file(s): ${mine.join(", ") || "none"}`);
|
|
527
|
+
} catch {
|
|
528
|
+
logLine("packet witness: could not list the capture directory");
|
|
529
|
+
}
|
|
530
|
+
};
|
|
531
|
+
|
|
532
|
+
/**
|
|
533
|
+
* Start a capture for this trigger, if the rules allow one.
|
|
534
|
+
*
|
|
535
|
+
* @param {WitnessTrigger} trigger
|
|
536
|
+
* @returns {boolean} True when a capture actually started.
|
|
537
|
+
*/
|
|
538
|
+
const maybeCapture = (trigger) => {
|
|
539
|
+
const address = normalizeRemoteAddress(trigger?.remote?.address);
|
|
540
|
+
const portNumber = trigger?.remote?.port;
|
|
541
|
+
if (!address || !Number.isInteger(portNumber) || portNumber < 1 || portNumber > 65535) {
|
|
542
|
+
return false;
|
|
543
|
+
}
|
|
544
|
+
if (!shouldStartCapture(state)) {
|
|
545
|
+
return false;
|
|
546
|
+
}
|
|
547
|
+
state.running = true;
|
|
548
|
+
state.lastStartedAt = Date.now();
|
|
549
|
+
const startedAt = state.lastStartedAt;
|
|
550
|
+
void (async () => {
|
|
551
|
+
try {
|
|
552
|
+
if (state.availability === "unknown") {
|
|
553
|
+
state.availability = (await probeAvailability()) ? "yes" : "no";
|
|
554
|
+
}
|
|
555
|
+
if (state.availability === "no") {
|
|
556
|
+
logLine(
|
|
557
|
+
"packet witness: unavailable — no tcpdump on this host; " +
|
|
558
|
+
"the stuck-queue log lines remain the only evidence here"
|
|
559
|
+
);
|
|
560
|
+
return;
|
|
561
|
+
}
|
|
562
|
+
const stampSeconds = Math.floor(Date.now() / 1000);
|
|
563
|
+
const before = await preserveRing(trigger, stampSeconds);
|
|
564
|
+
logLine(
|
|
565
|
+
before.length > 0
|
|
566
|
+
? `packet witness: kept ${before.length} ring file(s) from before the wedge: ${before.join(", ")}`
|
|
567
|
+
: "packet witness: no ring history to keep — the ring was not running"
|
|
568
|
+
);
|
|
569
|
+
await runCapture(trigger, address, stampSeconds);
|
|
570
|
+
// The disk bound has to hold between restarts too: one episode writes
|
|
571
|
+
// up to four ring copies and two tail files, and the cooldown allows
|
|
572
|
+
// six episodes an hour. Pruning only at startup let that accumulate.
|
|
573
|
+
await pruneWitnessCaptures(resolvedDir);
|
|
574
|
+
} finally {
|
|
575
|
+
state.running = false;
|
|
576
|
+
// Keep the requested spacing honest even when the capture ended early.
|
|
577
|
+
const earliestNext = startedAt + WITNESS_COOLDOWN_MS;
|
|
578
|
+
if (state.lastStartedAt < earliestNext) {
|
|
579
|
+
state.lastStartedAt = earliestNext;
|
|
580
|
+
}
|
|
581
|
+
}
|
|
582
|
+
})();
|
|
583
|
+
return true;
|
|
584
|
+
};
|
|
585
|
+
|
|
586
|
+
/**
|
|
587
|
+
* The rolling ring: one tcpdump, reference-counted by open data channels.
|
|
588
|
+
*
|
|
589
|
+
* @type {{
|
|
590
|
+
* child: import('node:child_process').ChildProcess | null,
|
|
591
|
+
* holders: number,
|
|
592
|
+
* starting: boolean,
|
|
593
|
+
* preserving: boolean,
|
|
594
|
+
* failed: boolean
|
|
595
|
+
* }}
|
|
596
|
+
*/
|
|
597
|
+
const ring = { child: null, holders: 0, starting: false, preserving: false, failed: false };
|
|
598
|
+
|
|
599
|
+
/**
|
|
600
|
+
* Delete the ring's own files.
|
|
601
|
+
*
|
|
602
|
+
* Refused while a wedge is copying them out: the copies are the only reason
|
|
603
|
+
* the ring exists, and the viewer closing the tab is exactly when both happen
|
|
604
|
+
* at once. Deferred until the copy is done instead.
|
|
605
|
+
*
|
|
606
|
+
* @returns {Promise<void>}
|
|
607
|
+
*/
|
|
608
|
+
const clearRingFiles = async () => {
|
|
609
|
+
if (ring.preserving) {
|
|
610
|
+
return;
|
|
611
|
+
}
|
|
612
|
+
try {
|
|
613
|
+
for (const name of await readdir(resolvedDir)) {
|
|
614
|
+
if (isWitnessRingFile(name)) {
|
|
615
|
+
await rm(path.join(resolvedDir, name), { force: true });
|
|
616
|
+
}
|
|
617
|
+
}
|
|
618
|
+
} catch {
|
|
619
|
+
// silent-ok: best effort, retried when the ring next stops.
|
|
620
|
+
}
|
|
621
|
+
};
|
|
622
|
+
|
|
623
|
+
/**
|
|
624
|
+
* Stop the ring's tcpdump and wait for it to flush and exit.
|
|
625
|
+
*
|
|
626
|
+
* The wait matters. tcpdump buffers its output, so the newest packets — the
|
|
627
|
+
* ONSET, which is the whole reason the ring runs — sit in that buffer until
|
|
628
|
+
* the process is asked to finish. `-U` would flush per packet instead, at one
|
|
629
|
+
* write syscall per packet, and at the measured 150 Mbps that is twelve
|
|
630
|
+
* thousand a second on a machine whose spare capacity is already the binding
|
|
631
|
+
* constraint. Stopping costs nothing while nothing is wrong.
|
|
632
|
+
*
|
|
633
|
+
* @returns {Promise<void>}
|
|
634
|
+
*/
|
|
635
|
+
const stopRingProcess = () => {
|
|
636
|
+
const child = ring.child;
|
|
637
|
+
ring.child = null;
|
|
638
|
+
if (!child) {
|
|
639
|
+
return Promise.resolve();
|
|
640
|
+
}
|
|
641
|
+
return new Promise((resolve) => {
|
|
642
|
+
let settled = false;
|
|
643
|
+
const done = () => {
|
|
644
|
+
if (!settled) {
|
|
645
|
+
settled = true;
|
|
646
|
+
clearTimeout(hardKill);
|
|
647
|
+
resolve();
|
|
648
|
+
}
|
|
649
|
+
};
|
|
650
|
+
const hardKill = setTimeout(() => {
|
|
651
|
+
try { child.kill("SIGKILL"); } catch { /* already gone */ }
|
|
652
|
+
done();
|
|
653
|
+
}, WITNESS_KILL_GRACE_MS);
|
|
654
|
+
if (typeof hardKill.unref === "function") {
|
|
655
|
+
hardKill.unref();
|
|
656
|
+
}
|
|
657
|
+
child.on("close", done);
|
|
658
|
+
child.on("error", done);
|
|
659
|
+
try {
|
|
660
|
+
child.kill("SIGTERM");
|
|
661
|
+
} catch {
|
|
662
|
+
done();
|
|
663
|
+
}
|
|
664
|
+
});
|
|
665
|
+
};
|
|
666
|
+
|
|
667
|
+
/**
|
|
668
|
+
* Start the ring's tcpdump, if it is wanted and not already running.
|
|
669
|
+
*
|
|
670
|
+
* @returns {Promise<void>}
|
|
671
|
+
*/
|
|
672
|
+
const startRingProcess = async () => {
|
|
673
|
+
if (ring.child !== null || ring.starting || ring.holders === 0) {
|
|
674
|
+
return;
|
|
675
|
+
}
|
|
676
|
+
ring.starting = true;
|
|
677
|
+
try {
|
|
678
|
+
if (state.availability === "unknown") {
|
|
679
|
+
state.availability = (await probeAvailability()) ? "yes" : "no";
|
|
680
|
+
}
|
|
681
|
+
// Everything above suspended; the last channel may have closed meanwhile.
|
|
682
|
+
// Without this second look the ring starts with nobody holding it and
|
|
683
|
+
// nobody left to stop it.
|
|
684
|
+
if (state.availability === "no" || ring.holders === 0) {
|
|
685
|
+
return;
|
|
686
|
+
}
|
|
687
|
+
const prefix = path.join(resolvedDir, WITNESS_RING_BASENAME);
|
|
688
|
+
const args = buildTcpdumpArgs({ port, filePrefix: prefix });
|
|
689
|
+
let child;
|
|
690
|
+
try {
|
|
691
|
+
child = spawnProcess("tcpdump", args, { stdio: "ignore" });
|
|
692
|
+
} catch (error) {
|
|
693
|
+
ring.failed = true;
|
|
694
|
+
logLine(`packet witness: the ring could not start: ${error?.message ?? error}`);
|
|
695
|
+
return;
|
|
696
|
+
}
|
|
697
|
+
ring.child = child;
|
|
698
|
+
child.on("error", (error) => {
|
|
699
|
+
ring.failed = true;
|
|
700
|
+
if (ring.child === child) {
|
|
701
|
+
ring.child = null;
|
|
702
|
+
}
|
|
703
|
+
logLine(`packet witness: the ring stopped: ${error?.message ?? error}`);
|
|
704
|
+
});
|
|
705
|
+
child.on("close", (code, signal) => {
|
|
706
|
+
if (ring.child !== child) {
|
|
707
|
+
return; // An orderly stop; it has already said what it needed to.
|
|
708
|
+
}
|
|
709
|
+
ring.child = null;
|
|
710
|
+
ring.failed = true;
|
|
711
|
+
// Ending on its own means it never recorded what it claimed to. A host
|
|
712
|
+
// with tcpdump installed but without the capability to capture answers
|
|
713
|
+
// `--version` happily and dies here, which would otherwise leave a
|
|
714
|
+
// "ring recording" line in the log and no history behind it.
|
|
715
|
+
logLine(
|
|
716
|
+
`packet witness: the ring ended on its own${signal ? ` (${signal})` : ` (exit ${code ?? "?"})`}` +
|
|
717
|
+
`${ring.holders > 0 ? " while a viewer was still being served — no history is being kept" : ""}`
|
|
718
|
+
);
|
|
719
|
+
});
|
|
720
|
+
logLine(
|
|
721
|
+
`packet witness: ring recording udp port ${port}, ` +
|
|
722
|
+
`${WITNESS_RING_FILES} × ${WITNESS_RING_FILE_MB} MB wrapping — ` +
|
|
723
|
+
"the seconds before a freeze, kept in advance"
|
|
724
|
+
);
|
|
725
|
+
} finally {
|
|
726
|
+
ring.starting = false;
|
|
727
|
+
// Holders may have gone while the probe or the spawn was in flight.
|
|
728
|
+
if (ring.holders === 0 && ring.child !== null) {
|
|
729
|
+
await stopRingProcess();
|
|
730
|
+
await clearRingFiles();
|
|
731
|
+
}
|
|
732
|
+
}
|
|
733
|
+
};
|
|
734
|
+
|
|
735
|
+
/**
|
|
736
|
+
* Begin recording, or note one more reason to keep recording.
|
|
737
|
+
*
|
|
738
|
+
* Reference-counted by open data channels, so the ring runs exactly while a
|
|
739
|
+
* viewer is being served and costs nothing on an idle proxy. Starting it is
|
|
740
|
+
* what makes the ONSET of a freeze readable: by the time a wedge is declared,
|
|
741
|
+
* the seconds before it are already on disk.
|
|
742
|
+
*
|
|
743
|
+
* @returns {void}
|
|
744
|
+
*/
|
|
745
|
+
const holdRing = () => {
|
|
746
|
+
ring.holders += 1;
|
|
747
|
+
if (ring.holders !== 1) {
|
|
748
|
+
return;
|
|
749
|
+
}
|
|
750
|
+
void startRingProcess();
|
|
751
|
+
};
|
|
752
|
+
|
|
753
|
+
/**
|
|
754
|
+
* Release one reason to keep recording; the last one stops the ring.
|
|
755
|
+
*
|
|
756
|
+
* @returns {void}
|
|
757
|
+
*/
|
|
758
|
+
const releaseRing = () => {
|
|
759
|
+
if (ring.holders > 0) {
|
|
760
|
+
ring.holders -= 1;
|
|
761
|
+
}
|
|
762
|
+
if (ring.holders > 0 || ring.starting) {
|
|
763
|
+
return;
|
|
764
|
+
}
|
|
765
|
+
void (async () => {
|
|
766
|
+
await stopRingProcess();
|
|
767
|
+
await clearRingFiles();
|
|
768
|
+
})();
|
|
769
|
+
};
|
|
770
|
+
|
|
771
|
+
/**
|
|
772
|
+
* Stop everything this witness owns. For process shutdown.
|
|
773
|
+
*
|
|
774
|
+
* @returns {Promise<void>}
|
|
775
|
+
*/
|
|
776
|
+
const dispose = async () => {
|
|
777
|
+
ring.holders = 0;
|
|
778
|
+
await stopRingProcess();
|
|
779
|
+
await clearRingFiles();
|
|
780
|
+
};
|
|
781
|
+
|
|
782
|
+
return { dir: resolvedDir, maybeCapture, holdRing, releaseRing, dispose, ring };
|
|
783
|
+
|
|
784
|
+
}
|