@cto.af/pcap-ng-parser 2.1.0 → 3.0.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/src/index.ts ADDED
@@ -0,0 +1,931 @@
1
+ import * as blocks from './blocks.ts';
2
+ import {
3
+ CUSTOM_COPY,
4
+ CUSTOM_NOCOPY,
5
+ DECRYPTION_SECRETS,
6
+ ENHANCED_PACKET,
7
+ INTERFACE_DESCRIPTION,
8
+ INTERFACE_STATISTICS,
9
+ NAME_RESOLUTION,
10
+ OPTION_NAMES,
11
+ type OptionType,
12
+ SECTION_HEADER,
13
+ SIMPLE_PACKET,
14
+ } from './options.ts';
15
+ import {
16
+ type CustomBlock,
17
+ type DecryptionSecrets,
18
+ EPB_FLAGS_DIRECTIONS,
19
+ EPB_FLAGS_LINK_LAYER_ERRORS,
20
+ EPB_FLAGS_RECEPTION,
21
+ type EUI48ResolutionRecord,
22
+ type EUI64ResolutionRecord,
23
+ type Endianess,
24
+ ErrorEvent,
25
+ type GenericOption,
26
+ type IPv4ResolutionRecord,
27
+ type IPv6ResolutionRecord,
28
+ type Interface,
29
+ type InterfaceStatistics,
30
+ type NameResolution,
31
+ type NameResolutionRecord,
32
+ type Option,
33
+ type Packet,
34
+ type PacketFlags,
35
+ type PrivateEnterpriseNumber,
36
+ type SectionHeader,
37
+ } from './events.ts';
38
+ import {DataViewReader, DataViewWritableStream, TruncationError} from 'dataview-stream';
39
+ import {colons, pad4} from './utils.ts';
40
+ import {LINK_TYPE_NAMES} from './linkTypes.ts';
41
+ import {assert} from '@cto.af/utils';
42
+ import {decode as ipDecode} from '@leichtgewicht/ip-codec';
43
+
44
+ export type {
45
+ CustomBlock,
46
+ DecryptionSecrets,
47
+ EUI48ResolutionRecord,
48
+ EUI64ResolutionRecord,
49
+ GenericOption,
50
+ Endianess,
51
+ Interface,
52
+ IPv4ResolutionRecord,
53
+ IPv6ResolutionRecord,
54
+ InterfaceStatistics,
55
+ NameResolution,
56
+ NameResolutionRecord,
57
+ Option,
58
+ OptionType,
59
+ Packet,
60
+ PacketFlags,
61
+ PrivateEnterpriseNumber,
62
+ SectionHeader,
63
+ };
64
+
65
+ const PCAP_MAGIC_MICRO = 0xA1B2C3D4;
66
+ const PCAP_MAGIC_NANO = 0xA1B23C4D;
67
+ const PCAP_MAGIC_MICRO_LE = 0xD4C3B2A1;
68
+ const PCAP_MAGIC_NANO_LE = 0x4D3CB2A1;
69
+
70
+ const TD = new TextDecoder();
71
+
72
+ // #region Types
73
+
74
+ export type EventCallback<T> =
75
+ ((evt: T) => void) |
76
+ {handleEvent(evt: T): void} |
77
+ null;
78
+
79
+ /**
80
+ * An error has occured when parsing inside a block. This error can be
81
+ * ignored and parsing can continue within the next block safely.
82
+ */
83
+ export class RecoverableError extends Error {
84
+ public constructor(err: unknown) {
85
+ super(err instanceof Error ? err.message : 'Recoverable Error', {cause: err});
86
+ }
87
+ }
88
+
89
+ export interface ParseEvents {
90
+ close: Event;
91
+ custom: CustomEvent<CustomBlock>;
92
+ error: ErrorEvent;
93
+ interface: CustomEvent<Interface>;
94
+ names: CustomEvent<NameResolution>;
95
+ data: CustomEvent<Packet>;
96
+ section: CustomEvent<SectionHeader>;
97
+ secrets: CustomEvent<DecryptionSecrets>;
98
+ stats: CustomEvent<InterfaceStatistics>;
99
+ unknown: CustomEvent<number>;
100
+ }
101
+
102
+ export type ParseEventsDetail<K extends keyof ParseEvents> =
103
+ ParseEvents[K] extends CustomEvent<infer T> ? T :
104
+ ParseEvents[K] extends ErrorEvent ? any :
105
+ // Only for the close event
106
+ // eslint-disable-next-line @typescript-eslint/no-invalid-void-type
107
+ void;
108
+
109
+ export interface ParserOptions {
110
+ /** If true, don't allow old PCAP format. */
111
+ rejectOld?: boolean;
112
+
113
+ /** If true, don't allow new PCAPng format. */
114
+ rejectNG?: boolean;
115
+ }
116
+
117
+ interface Block {
118
+ blockType: number;
119
+ blockTotalLength: number;
120
+ data: DataViewReader;
121
+ }
122
+
123
+ // #region WritableStream
124
+
125
+ /**
126
+ * Parse a PCAPng or old-style PCAP file from a stream.
127
+ *
128
+ * @example
129
+ * ```js
130
+ * import fs from 'node:fs/promises';
131
+ * import {PCAPNGParser} from '@cto.af/pcap-ng-parser';
132
+ *
133
+ * const parser = new PCAPNGParser();
134
+ * parser.on('data', pkt => console.log(pkt.data)); // Uint8Array
135
+ * const file = await fs.open('examples/res/myfile.pcapng');
136
+ * file.readableWebStream().pipeTo(parser);
137
+ * ```
138
+ */
139
+ export class PCAPNGParser
140
+ extends WritableStream<Uint8Array>
141
+ implements EventTarget {
142
+ /**
143
+ * Interface information receieved for the current section, in order of
144
+ * reception.
145
+ */
146
+ public interfaces: Interface[] = [];
147
+
148
+ // This is a weak map since the wrapper is holding a reference to the
149
+ // original listener, and #et is holding a reference to the wrapper.
150
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-function-type
151
+ #listeners = new WeakMap<Function, (ev: Event) => void>();
152
+ #et = new EventTarget();
153
+ #dv: DataViewWritableStream;
154
+ #ng = true; // Is this the -ng format, or the older format?
155
+ #opts: Required<ParserOptions>;
156
+
157
+ public constructor(opts: ParserOptions = {}) {
158
+ const dv = new DataViewWritableStream();
159
+ const writer = dv.getWriter();
160
+
161
+ let self: PCAPNGParser | undefined = undefined;
162
+
163
+ super({
164
+ write(chunk) {
165
+ return writer.write(chunk);
166
+ },
167
+ async abort(reason) {
168
+ await writer.abort(reason);
169
+ self?.dispatchEvent(new ErrorEvent('error', {
170
+ error: reason,
171
+ }));
172
+ },
173
+ async close() {
174
+ await writer.close();
175
+ },
176
+ });
177
+ // eslint-disable-next-line @typescript-eslint/no-this-alias
178
+ self = this;
179
+ this.#opts = {
180
+ rejectOld: false,
181
+ rejectNG: false,
182
+ ...opts,
183
+ };
184
+
185
+ this.#dv = dv;
186
+ this.#readFile();
187
+ }
188
+
189
+ /**
190
+ * Is this file in the pcap-ng format?
191
+ */
192
+ public get ng(): boolean {
193
+ return this.#ng;
194
+ }
195
+
196
+ /**
197
+ * Endianness of the current section.
198
+ * Little-endian => LE.
199
+ * Big-endian => BE.
200
+ */
201
+ public get endianess(): Endianess {
202
+ return this.#dv.littleEndian ? 'LE' : 'BE';
203
+ }
204
+
205
+ // #region EventTarget
206
+
207
+ /**
208
+ * The **`addEventListener()`** method of the EventTarget interface sets up
209
+ * a function that will be called whenever the specified event is delivered
210
+ * to the target.
211
+ *
212
+ * @see https://developer.mozilla.org/docs/Web/API/EventTarget/addEventListener
213
+ */
214
+ public addEventListener<E extends keyof ParseEvents>(
215
+ type: E,
216
+ callback: EventCallback<ParseEvents[E]>,
217
+ options?: AddEventListenerOptions | boolean
218
+ ): void;
219
+ public addEventListener(
220
+ type: string,
221
+ callback: EventListenerOrEventListenerObject | null,
222
+ options?: AddEventListenerOptions | boolean
223
+ ): void {
224
+ this.#et.addEventListener(type, callback, options);
225
+ }
226
+
227
+ /**
228
+ * The **`dispatchEvent()`** method of the EventTarget sends an Event to the
229
+ * object, (synchronously) invoking the affected event listeners in the
230
+ * appropriate order.
231
+ *
232
+ * @see https://developer.mozilla.org/docs/Web/API/EventTarget/dispatchEvent
233
+ */
234
+ public dispatchEvent(
235
+ event: ParseEvents[keyof ParseEvents]
236
+ ): boolean;
237
+ public dispatchEvent(event: Event): boolean {
238
+ return this.#et.dispatchEvent(event);
239
+ }
240
+
241
+ /**
242
+ * The **`removeEventListener()`** method of the EventTarget interface
243
+ * removes an event listener previously registered with
244
+ * EventTarget.addEventListener() from the target.
245
+ *
246
+ * @see https://developer.mozilla.org/docs/Web/API/EventTarget/removeEventListener
247
+ */
248
+ public removeEventListener<E extends keyof ParseEvents>(
249
+ event: E,
250
+ calback: EventCallback<ParseEvents[E]>,
251
+ options?: EventListenerOptions | boolean
252
+ ): void;
253
+ public removeEventListener(
254
+ type: string,
255
+ callback: EventListenerOrEventListenerObject | null,
256
+ options?: EventListenerOptions | boolean
257
+ ): void {
258
+ this.#et.removeEventListener(type, callback, options);
259
+ }
260
+
261
+ /**
262
+ * Listen for an event, unwrapping the detailor error in the event so that
263
+ * it is easier to process.
264
+ *
265
+ * @param eventName Event name.
266
+ * @param listener Handler.
267
+ * @returns This, for chaining.
268
+ */
269
+ public on<E extends keyof ParseEvents>(
270
+ eventName: E,
271
+ listener: (detail: ParseEventsDetail<E>) => void
272
+ ): this {
273
+ const wrapper = (ev: Event): void => {
274
+ if (eventName === 'close') {
275
+ // @ts-expect-error This should be inferred as correct.
276
+ listener();
277
+ }
278
+ if (ev instanceof CustomEvent) {
279
+ listener(ev.detail);
280
+ } else if (ev instanceof ErrorEvent) {
281
+ listener(ev.error);
282
+ }
283
+ };
284
+ this.#listeners.set(listener, wrapper);
285
+ this.addEventListener(eventName, wrapper);
286
+ return this;
287
+ }
288
+
289
+ /**
290
+ * Listen for the first occurence of a given event. Does the same
291
+ * unwrapping as `on`.
292
+ *
293
+ * @param eventName Event name.
294
+ * @param listener Handler.
295
+ * @returns This, for chaining.
296
+ */
297
+ public once<E extends keyof ParseEvents>(
298
+ eventName: E,
299
+ listener: (detail: ParseEventsDetail<E>) => void
300
+ ): this {
301
+ const wrapper = (ev: Event): void => {
302
+ this.#listeners.delete(listener);
303
+ if (eventName === 'close') {
304
+ // @ts-expect-error This should be inferred as correct.
305
+ listener();
306
+ }
307
+ if (ev instanceof CustomEvent) {
308
+ listener(ev.detail);
309
+ } else if (ev instanceof ErrorEvent) {
310
+ listener(ev.error);
311
+ }
312
+ };
313
+ this.#listeners.set(listener, wrapper);
314
+ this.addEventListener(eventName, wrapper, {once: true});
315
+ return this;
316
+ }
317
+
318
+ /**
319
+ * Stop listening for the given event.
320
+ *
321
+ * @param eventName Event name.
322
+ * @param listener Handler to remove.
323
+ * @returns This, for chaining.
324
+ * @throws On unknown listener.
325
+ */
326
+ public off<E extends keyof ParseEvents>(
327
+ eventName: E,
328
+ listener: (detail: ParseEventsDetail<E>) => void
329
+ ): this {
330
+ const wrapper = this.#listeners.get(listener);
331
+ if (!wrapper) {
332
+ throw new Error('Unknown listener');
333
+ }
334
+ this.removeEventListener(eventName, wrapper);
335
+ this.#listeners.delete(listener);
336
+ return this;
337
+ }
338
+
339
+ // #region utilities
340
+
341
+ #timestamp(stampHigh: number, stampLow: number, interfaceId: number): Date {
342
+ // Don't read as bigint, since each half could be LE.
343
+ const stamp = (BigInt(stampHigh) << 32n) | BigInt(stampLow);
344
+ const int = this.interfaces[interfaceId];
345
+ assert(int, 'Interface always checked before calling');
346
+
347
+ const off = int.tsoffset + (stamp / int.tsresol);
348
+ return new Date(Number(off));
349
+ }
350
+
351
+ #dvr(bytes: Uint8Array): DataViewReader {
352
+ return new DataViewReader(bytes, {littleEndian: this.#dv.littleEndian});
353
+ }
354
+
355
+ // #region Top-level
356
+
357
+ /**
358
+ * Read the whole file, once data has started to flow.
359
+ */
360
+ async #readFile(): Promise<void> {
361
+ try {
362
+ // Mostly, we're going to re-peek the first 8 bits in readBlock, so
363
+ // optimize ever-so-slightly.
364
+ const magicBuf = await this.#dv.peek(8);
365
+ const magic = this.#dvr(magicBuf).u32();
366
+ if (magic === SECTION_HEADER) {
367
+ await this.#readSections();
368
+ } else if (magic === PCAP_MAGIC_MICRO) {
369
+ await this.#readPCAP(false, false);
370
+ } else if (magic === PCAP_MAGIC_MICRO_LE) {
371
+ await this.#readPCAP(true, false);
372
+ } else if (magic === PCAP_MAGIC_NANO) {
373
+ await this.#readPCAP(false, true);
374
+ } else if (magic === PCAP_MAGIC_NANO_LE) {
375
+ await this.#readPCAP(true, true);
376
+ } else {
377
+ throw new Error(`Invalid file format: magic = ${magic}`);
378
+ }
379
+ } catch (error) {
380
+ this.dispatchEvent(new ErrorEvent('error', {error}));
381
+ }
382
+ this.dispatchEvent(new Event('close'));
383
+ }
384
+
385
+ /**
386
+ * Read an old-style PCAP file.
387
+ *
388
+ * @param littleEndian If true, littleEndian, else false.
389
+ * @param nano If true, nanosecond precision, else microsecond.
390
+ * @see https://www.ietf.org/archive/id/draft-ietf-opsawg-pcap-06.html
391
+ */
392
+ async #readPCAP(littleEndian: boolean, nano: boolean): Promise<void> {
393
+ if (this.#opts.rejectOld) {
394
+ throw new Error('Old PCAP format detected and rejected');
395
+ }
396
+
397
+ if (littleEndian) {
398
+ this.#dv.littleEndian = !this.#dv.littleEndian;
399
+ }
400
+ this.#ng = false;
401
+ const {linkType, snapLen} = await this.#dv.struct(
402
+ blocks.pcapHeaderFormat
403
+ );
404
+
405
+ const tsresol = nano ? 1000000n : 1000n;
406
+
407
+ const int: Interface = {
408
+ linkType: linkType & 0xffff,
409
+ snapLen,
410
+ tsresol,
411
+ tsoffset: 0n,
412
+ options: [],
413
+ };
414
+ const ltName = LINK_TYPE_NAMES.get(int.linkType);
415
+ if (ltName) {
416
+ int.linkTypeName = ltName;
417
+ }
418
+ const fcsPresent = Boolean(linkType & 0x04000000);
419
+ if (fcsPresent) {
420
+ const FCSlen = linkType >> 28; // 16 bit words
421
+ int.options.push({
422
+ optionType: 13,
423
+ name: 'if_fcslen',
424
+ data: new Uint8Array([FCSlen * 16]), // Bits
425
+ });
426
+ }
427
+ this.interfaces.push(int);
428
+ this.dispatchEvent(new CustomEvent('interface', {detail: int}));
429
+
430
+ while (true) {
431
+ try {
432
+ await this.#dv.waitFor(4);
433
+ } catch (er) {
434
+ if (er instanceof TruncationError && er.requested === 4) {
435
+ return;
436
+ }
437
+ throw er;
438
+ }
439
+ const {
440
+ timestampHigh, timestampLow, capturedPacketLength, originalPacketLength,
441
+ } = await this.#dv.struct(blocks.pcapPacketFormat);
442
+
443
+ const data = await this.#dv.bytes(capturedPacketLength);
444
+
445
+ const pkt: Packet = {
446
+ interfaceId: 0,
447
+ timestamp: new Date(
448
+ (timestampHigh * 1000) + (timestampLow / Number(tsresol))
449
+ ),
450
+ originalPacketLength,
451
+ data,
452
+ options: [],
453
+ };
454
+
455
+ this.dispatchEvent(new CustomEvent('data', {
456
+ detail: pkt,
457
+ }));
458
+ }
459
+ }
460
+
461
+ async #readSections(): Promise<void> {
462
+ if (this.#opts.rejectNG) {
463
+ throw new Error('PCAPng format detected and rejected');
464
+ }
465
+
466
+ while (true) {
467
+ const block = await this.#readBlock();
468
+ if (!block) {
469
+ break;
470
+ }
471
+ try {
472
+ switch (block.blockType) {
473
+ case SECTION_HEADER:
474
+ await this.#processSectionHeader(block);
475
+ break;
476
+ case INTERFACE_DESCRIPTION:
477
+ await this.#processInterface(block);
478
+ break;
479
+ case SIMPLE_PACKET:
480
+ await this.#processSimplePacket(block);
481
+ break;
482
+ case NAME_RESOLUTION:
483
+ await this.#processNameResolution(block);
484
+ break;
485
+ case INTERFACE_STATISTICS:
486
+ await this.#processInterfaceStatistics(block);
487
+ break;
488
+ case ENHANCED_PACKET:
489
+ await this.#processEnhancedPacket(block);
490
+ break;
491
+ case DECRYPTION_SECRETS:
492
+ await this.#processDecryptionSecrets(block);
493
+ break;
494
+ case CUSTOM_COPY:
495
+ case CUSTOM_NOCOPY:
496
+ await this.#processCustom(block);
497
+ break;
498
+ default:
499
+ this.dispatchEvent(new CustomEvent('unknown', {detail: block.blockType}));
500
+ break;
501
+ }
502
+ } catch (error) {
503
+ this.dispatchEvent(new ErrorEvent('error', {
504
+ error: new RecoverableError(error),
505
+ }));
506
+ }
507
+ }
508
+ }
509
+
510
+ // #region Blocks
511
+
512
+ /**
513
+ * Read a block.
514
+ */
515
+ async #readBlock(): Promise<Block | undefined> {
516
+ let blockType = undefined;
517
+ try {
518
+ blockType = await this.#dv.u32();
519
+ } catch (er) {
520
+ assert(er instanceof TruncationError);
521
+ assert(er.requested === 4);
522
+ return undefined;
523
+ }
524
+
525
+ if (blockType === SECTION_HEADER) {
526
+ // Peek at the byte order first.
527
+ const prelude = await this.#dv.peek(8);
528
+ const dv = this.#dvr(prelude);
529
+ dv.skip(4); // Ignore length for now
530
+ const bom = dv.u32();
531
+ if (bom === 0x1A2B3C4D) {
532
+ // No-op
533
+ } else if (bom === 0x4D3C2B1A) {
534
+ this.#dv.littleEndian = !this.#dv.littleEndian;
535
+ } else {
536
+ throw new Error(`Unable to determine endian from 0x${bom.toString(16)}`);
537
+ }
538
+ }
539
+
540
+ const blockTotalLength = await this.#dv.u32();
541
+ const dataLen = blockTotalLength - 12;
542
+ const data = await this.#dv.bytes(dataLen);
543
+ const block = {
544
+ blockType,
545
+ blockTotalLength,
546
+ data: this.#dvr(data),
547
+ };
548
+ // Padding
549
+ await this.#dv.bytes(pad4(dataLen));
550
+ const endTotalLength = await this.#dv.u32();
551
+ if (endTotalLength !== blockTotalLength) {
552
+ throw new Error(`Length mismatch, ${endTotalLength} != ${blockTotalLength}`);
553
+ }
554
+ return block;
555
+ }
556
+
557
+ #readOptions(block: Block, interfaceId?: number): Option[] {
558
+ let foundEndOption = false;
559
+
560
+ const options: Option[] = [];
561
+ while (!block.data.finished && !foundEndOption) {
562
+ const rb = block.data.struct(blocks.optionBlock);
563
+ if (rb.optionType === 0) {
564
+ foundEndOption = true;
565
+ } else {
566
+ let pen: PrivateEnterpriseNumber | undefined = undefined;
567
+ let name = undefined;
568
+ let optLen = rb.dataLength;
569
+ let typ: OptionType | undefined = undefined;
570
+
571
+ const desc = OPTION_NAMES.get(block.blockType)?.get(rb.optionType);
572
+ if (desc) {
573
+ name = {name: desc[0]};
574
+ // eslint-disable-next-line @typescript-eslint/prefer-destructuring
575
+ typ = desc[1];
576
+ if (desc[2]) {
577
+ pen = {
578
+ pen: block.data.u32(),
579
+ };
580
+ optLen -= 4;
581
+ }
582
+ }
583
+
584
+ const opt: Option = {
585
+ optionType: rb.optionType,
586
+ ...name,
587
+ ...pen,
588
+ };
589
+
590
+ if (rb.optionType & 0x8000) {
591
+ opt.private = true;
592
+ }
593
+ switch (typ) {
594
+ case 'string': {
595
+ const left = block.data.bytes(optLen);
596
+ opt.str = TD
597
+ .decode(left)
598
+ .replaceAll('\0', '')
599
+ .trim();
600
+ break;
601
+ }
602
+ case 'ipv4':
603
+ case 'ipv6':
604
+ opt.str = ipDecode(block.data.bytes(rb.dataLength));
605
+ break;
606
+ case 'ipv4mask':
607
+ if (rb.dataLength !== 8) {
608
+ throw new Error('Invalid ipv4mask option');
609
+ }
610
+ opt.str = `${ipDecode(block.data.bytes(4))}/${ipDecode(block.data.bytes(4))}`;
611
+ break;
612
+ case 'ipv6prefix':
613
+ if (rb.dataLength !== 17) {
614
+ throw new Error('Invalid ipv6prefix option');
615
+ }
616
+ opt.str = `${ipDecode(block.data.bytes(16))}/${block.data.u8()}`;
617
+ break;
618
+ case 'eui':
619
+ opt.str = colons(block.data.bytes(rb.dataLength));
620
+ break;
621
+ case 'u32':
622
+ opt.bigint = BigInt(block.data.u32());
623
+ break;
624
+ case 'u64':
625
+ opt.bigint = block.data.u64();
626
+ break;
627
+ case 'timestamp': {
628
+ const {timestampHigh, timestampLow} =
629
+ block.data.struct(blocks.timestampFormat);
630
+ opt.date = this.#timestamp(
631
+ timestampHigh, timestampLow, interfaceId as number
632
+ );
633
+ break;
634
+ }
635
+ default:
636
+ opt.data = block.data.bytes(rb.dataLength);
637
+ break;
638
+ }
639
+
640
+ // Skip padding
641
+ block.data.skip(pad4(rb.dataLength));
642
+ options.push(opt);
643
+ }
644
+ }
645
+ return options;
646
+ }
647
+
648
+ // #region Block types
649
+
650
+ #processSectionHeader(block: Block): void {
651
+ const hdr = block.data.struct(blocks.sectionHeaderBlock);
652
+
653
+ const detail: SectionHeader = {
654
+ ...hdr,
655
+ endianess: this.endianess,
656
+ options: this.#readOptions(block),
657
+ };
658
+
659
+ this.interfaces = []; // Reset interfaces in each section.
660
+ this.dispatchEvent(new CustomEvent('section', {detail}));
661
+ }
662
+
663
+ /**
664
+ * Interface Description Block.
665
+ *
666
+ * @param block Block.
667
+ * @see https://www.ietf.org/archive/id/draft-ietf-opsawg-pcapng-04.html#name-interface-description-block
668
+ */
669
+ #processInterface(block: Block): void {
670
+ const idRes = block.data.struct(
671
+ blocks.interfaceDescriptionBlockFormat
672
+ );
673
+
674
+ const iData: Interface = {
675
+ linkType: idRes.linkType,
676
+ snapLen: idRes.snapLen,
677
+ tsoffset: 0n,
678
+ tsresol: 1000n,
679
+ options: this.#readOptions(block),
680
+ };
681
+ for (const opt of iData.options) {
682
+ switch (opt.optionType) {
683
+ case 2:
684
+ iData.name = opt.str as string;
685
+ break;
686
+ case 14: {
687
+ iData.tsoffset = (opt.bigint as bigint) * 1000n;
688
+ break;
689
+ }
690
+ case 9: {
691
+ const tsresol = (opt.data as Uint8Array)[0] as number;
692
+ if (tsresol & 0x80) {
693
+ // This is going to lose precision. Hope nobody does this in
694
+ // practice.
695
+ iData.tsresol = (1n << BigInt(tsresol & 0x7F)) / 1000n;
696
+ } else {
697
+ iData.tsresol = 10n ** (BigInt(tsresol) - 3n);
698
+ }
699
+ break;
700
+ }
701
+ }
702
+ }
703
+
704
+ this.interfaces.push(iData);
705
+ this.dispatchEvent(new CustomEvent('interface', {detail: iData}));
706
+ }
707
+
708
+ /**
709
+ * Simple Packet Block.
710
+ *
711
+ * @param block Block.
712
+ * @throws Invalid interface.
713
+ * @see https://www.ietf.org/archive/id/draft-ietf-opsawg-pcapng-04.html#name-simple-packet-block
714
+ */
715
+ #processSimplePacket(block: Block): void {
716
+ const [int] = this.interfaces;
717
+ if (!int) {
718
+ throw new Error('No interface for simple packet');
719
+ }
720
+ const originalPacketLength = block.data.u32();
721
+ const len = Math.min(originalPacketLength, int.snapLen);
722
+ const data = block.data.bytes(len);
723
+
724
+ const pkt: Packet = {
725
+ interfaceId: 0,
726
+ originalPacketLength,
727
+ data,
728
+ options: [],
729
+ };
730
+
731
+ this.dispatchEvent(new CustomEvent('data', {
732
+ detail: pkt,
733
+ }));
734
+ }
735
+
736
+ /**
737
+ * Name Resolution Block.
738
+ *
739
+ * @param block Block.
740
+ * @throws Invalid size.
741
+ * @see https://www.ietf.org/archive/id/draft-ietf-opsawg-pcapng-04.html#name-name-resolution-block
742
+ */
743
+ #processNameResolution(block: Block): void {
744
+ const res: NameResolution = {
745
+ records: [],
746
+ options: [],
747
+ };
748
+ while (true) {
749
+ const {recordType, recordValueLength} =
750
+ block.data.struct(blocks.nameResolutionFormat);
751
+ if (recordType === 0) {
752
+ break;
753
+ }
754
+ const val = block.data.bytes(recordValueLength);
755
+ block.data.skip(pad4(recordValueLength));
756
+ switch (recordType) {
757
+ case 0x0001:
758
+ if (recordValueLength < 6) {
759
+ throw new Error('Invalid nrb_record_ipv4 record');
760
+ }
761
+ res.records.push({
762
+ name: 'nrb_record_ipv4',
763
+ ipv4: ipDecode(val.subarray(0, 4)),
764
+ entries: TD.decode(val.subarray(4))
765
+ .split('\x00')
766
+ .slice(0, -1),
767
+ });
768
+ break;
769
+ case 0x0002:
770
+ if (recordValueLength < 18) {
771
+ throw new Error('Invalid nrb_record_ipv6 record');
772
+ }
773
+ res.records.push({
774
+ name: 'nrb_record_ipv6',
775
+ ipv6: ipDecode(val.subarray(0, 16)),
776
+ entries: TD.decode(val.subarray(16))
777
+ .split('\x00')
778
+ .slice(0, -1),
779
+ });
780
+ break;
781
+ case 0x0003:
782
+ if (recordValueLength < 8) {
783
+ throw new Error('Invalid nrb_record_eui48 record');
784
+ }
785
+ res.records.push({
786
+ name: 'nrb_record_eui48',
787
+ eui48: colons(val.subarray(0, 6)),
788
+ entries: TD.decode(val.subarray(6))
789
+ .split('\x00')
790
+ .slice(0, -1),
791
+ });
792
+ break;
793
+ case 0x0004:
794
+ if (recordValueLength < 10) {
795
+ throw new Error('Invalid nrb_record_eui64 record');
796
+ }
797
+ res.records.push({
798
+ name: 'nrb_record_eui64',
799
+ eui64: colons(val.subarray(0, 8)),
800
+ entries: TD.decode(val.subarray(8))
801
+ .split('\x00')
802
+ .slice(0, -1),
803
+ });
804
+ break;
805
+ }
806
+ }
807
+ res.options = this.#readOptions(block);
808
+ this.dispatchEvent(new CustomEvent('names', {detail: res}));
809
+ }
810
+
811
+ /**
812
+ * Interface Statistics block.
813
+ *
814
+ * @param block Block.
815
+ * @throws Invalid interface.
816
+ * @see https://www.ietf.org/archive/id/draft-ietf-opsawg-pcapng-04.html#name-interface-statistics-block
817
+ */
818
+ #processInterfaceStatistics(block: Block): void {
819
+ const {interfaceId, timestampHigh, timestampLow} =
820
+ block.data.struct(blocks.interfaceStatisticsFormat);
821
+ if (interfaceId >= this.interfaces.length) {
822
+ throw new Error(`Invalid interface id: ${interfaceId}`);
823
+ }
824
+
825
+ const stats: InterfaceStatistics = {
826
+ interfaceId,
827
+ timestamp: this.#timestamp(timestampHigh, timestampLow, interfaceId),
828
+ options: this.#readOptions(block, interfaceId),
829
+ };
830
+ this.dispatchEvent(new CustomEvent('stats', {detail: stats}));
831
+ }
832
+
833
+ /**
834
+ * Enhanced Packet Block.
835
+ *
836
+ * @param block Block.
837
+ * @throws Invalid interface.
838
+ * @see https://www.ietf.org/archive/id/draft-ietf-opsawg-pcapng-04.html#name-enhanced-packet-block
839
+ */
840
+ #processEnhancedPacket(block: Block): void {
841
+ const {
842
+ interfaceId,
843
+ timestampHigh,
844
+ timestampLow,
845
+ capturedPacketLength,
846
+ originalPacketLength,
847
+ } = block.data.struct(blocks.enhancedPacketBlockFormat);
848
+
849
+ if (interfaceId >= this.interfaces.length) {
850
+ throw new Error(`Invalid interface ID: ${interfaceId} >= ${this.interfaces.length}`);
851
+ }
852
+
853
+ const data = block.data.bytes(capturedPacketLength);
854
+
855
+ const pkt: Packet = {
856
+ interfaceId,
857
+ timestamp: this.#timestamp(timestampHigh, timestampLow, interfaceId),
858
+ originalPacketLength,
859
+ data,
860
+ options: [],
861
+ };
862
+
863
+ block.data.skip(pad4(capturedPacketLength));
864
+ pkt.options = this.#readOptions(block, interfaceId);
865
+ for (const o of pkt.options) {
866
+ if (o.optionType === 2) { // Type epb_flags
867
+ assert(o.data);
868
+ let flags = this.#dvr(o.data).u32();
869
+ pkt.flags = {
870
+ direction: EPB_FLAGS_DIRECTIONS[flags & 0x3] as
871
+ typeof EPB_FLAGS_DIRECTIONS[number],
872
+ reception: EPB_FLAGS_RECEPTION[(flags >> 2) & 0x7] as
873
+ typeof EPB_FLAGS_RECEPTION[number],
874
+ FCSlen: (flags >> 5) & 0xF,
875
+ noChecksum: Boolean((flags >> 9) & 0x1),
876
+ checksumValid: Boolean((flags >> 10) & 0x1),
877
+ TCPsegmentationOffload: Boolean((flags >> 11) & 0x1),
878
+ linkLayerErrors: [],
879
+ };
880
+ flags >>= 16;
881
+ for (let i = 0; i < 8; i++) {
882
+ if (flags & 0x1) {
883
+ pkt.flags.linkLayerErrors?.push(EPB_FLAGS_LINK_LAYER_ERRORS[i] as
884
+ typeof EPB_FLAGS_LINK_LAYER_ERRORS[number]);
885
+ }
886
+ flags >>= 1;
887
+ }
888
+ }
889
+ }
890
+ this.dispatchEvent(new CustomEvent('data', {
891
+ detail: pkt,
892
+ }));
893
+ }
894
+
895
+ /**
896
+ * Decryption Secrets block.
897
+ *
898
+ * @param block Block.
899
+ * @see https://www.ietf.org/archive/id/draft-ietf-opsawg-pcapng-04.html#name-decryption-secrets-block
900
+ */
901
+ #processDecryptionSecrets(block: Block): void {
902
+ // TODO(@hildjj): parse the keying information for each of the spec'd
903
+ // secret types.
904
+ const {secretsType, secretsLength} =
905
+ block.data.struct(blocks.decryptionSecretsFormat);
906
+
907
+ const detail: DecryptionSecrets = {
908
+ secretsType,
909
+ data: block.data.bytes(secretsLength),
910
+ options: [],
911
+ };
912
+ block.data.skip(pad4(secretsLength));
913
+ detail.options = this.#readOptions(block);
914
+ this.dispatchEvent(new CustomEvent('secrets', {detail}));
915
+ }
916
+
917
+ #processCustom(block: Block): void {
918
+ const pen = block.data.u32();
919
+
920
+ // For options, see:
921
+ // https://github.com/IETF-OPSAWG-WG/draft-ietf-opsawg-pcap/issues/125
922
+ const detail: CustomBlock = {
923
+ pen,
924
+ data: block.data.unused(),
925
+ copy: (block.blockType === CUSTOM_COPY),
926
+ };
927
+ this.dispatchEvent(new CustomEvent('custom', {detail}));
928
+ }
929
+ }
930
+
931
+ export default PCAPNGParser;