@cto.af/pcap-ng-parser 3.0.1 → 3.0.3

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