@netkitty/codec 2.1.0 → 2.3.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.
Files changed (83) hide show
  1. package/CHANGELOG.md +249 -0
  2. package/README.md +30 -1
  3. package/README.zh-CN.md +26 -1
  4. package/dist/Codec.d.ts +25 -7
  5. package/dist/Codec.js +151 -18
  6. package/dist/PacketHeaders.d.ts +2 -0
  7. package/dist/PacketHeaders.js +8 -4
  8. package/dist/abstracts/BaseHeader.d.ts +34 -0
  9. package/dist/abstracts/BaseHeader.js +43 -0
  10. package/dist/headers/ARP.d.ts +3 -1
  11. package/dist/headers/ARP.js +8 -1
  12. package/dist/headers/BACnetIP.js +2 -1
  13. package/dist/headers/BGP.js +3 -2
  14. package/dist/headers/Babel.js +1 -1
  15. package/dist/headers/Codesys.js +3 -2
  16. package/dist/headers/DHCP.js +2 -1
  17. package/dist/headers/DNP3.d.ts +12 -7
  18. package/dist/headers/DNP3.js +98 -18
  19. package/dist/headers/DTLS.js +5 -3
  20. package/dist/headers/Diameter.js +2 -1
  21. package/dist/headers/Elasticsearch.js +3 -2
  22. package/dist/headers/EthernetII.d.ts +1 -0
  23. package/dist/headers/EthernetII.js +3 -0
  24. package/dist/headers/Goose.d.ts +31 -7
  25. package/dist/headers/Goose.js +409 -168
  26. package/dist/headers/HARTIP.js +2 -2
  27. package/dist/headers/ICMP.d.ts +1 -0
  28. package/dist/headers/ICMP.js +9 -1
  29. package/dist/headers/ICMPv6.d.ts +1 -0
  30. package/dist/headers/ICMPv6.js +1 -0
  31. package/dist/headers/IEC104_I_Frame.d.ts +28 -0
  32. package/dist/headers/IEC104_I_Frame.js +246 -160
  33. package/dist/headers/IEC104_S_Frame.js +3 -3
  34. package/dist/headers/IEC104_U_Frame.js +5 -3
  35. package/dist/headers/IEC61850SampledValues.d.ts +1 -0
  36. package/dist/headers/IEC61850SampledValues.js +16 -1
  37. package/dist/headers/IPFIX.js +2 -1
  38. package/dist/headers/IPv4.d.ts +1 -0
  39. package/dist/headers/IPv4.js +6 -0
  40. package/dist/headers/IPv6.d.ts +1 -0
  41. package/dist/headers/IPv6.js +6 -0
  42. package/dist/headers/IPv6HopByHopOptions.d.ts +2 -0
  43. package/dist/headers/IPv6HopByHopOptions.js +11 -0
  44. package/dist/headers/KNXnetIP.js +3 -2
  45. package/dist/headers/LACP.js +2 -1
  46. package/dist/headers/LDP.js +2 -2
  47. package/dist/headers/MQTT.js +3 -1
  48. package/dist/headers/MarkerProtocol.js +2 -1
  49. package/dist/headers/NHRP.js +7 -15
  50. package/dist/headers/NetFlowV5.js +2 -1
  51. package/dist/headers/OPCUA.js +4 -0
  52. package/dist/headers/OSPF.d.ts +2 -2
  53. package/dist/headers/OSPF.js +32 -20
  54. package/dist/headers/OSPFv3.d.ts +38 -0
  55. package/dist/headers/OSPFv3.js +316 -0
  56. package/dist/headers/PPTP.js +2 -2
  57. package/dist/headers/QUIC.js +8 -3
  58. package/dist/headers/RGoose.js +2 -1
  59. package/dist/headers/RIP.js +3 -2
  60. package/dist/headers/RIPng.js +3 -2
  61. package/dist/headers/RTCP.js +3 -2
  62. package/dist/headers/RTP.js +3 -2
  63. package/dist/headers/SFlow.js +4 -2
  64. package/dist/headers/SLMP.js +2 -1
  65. package/dist/headers/SLP.js +2 -1
  66. package/dist/headers/SLPv1.js +2 -1
  67. package/dist/headers/SMB1.js +3 -2
  68. package/dist/headers/SMB2.js +3 -2
  69. package/dist/headers/STUN.js +2 -1
  70. package/dist/headers/TLS_Handshake.d.ts +6 -0
  71. package/dist/headers/TLS_Handshake.js +28 -3
  72. package/dist/headers/TacacsPlus.js +3 -1
  73. package/dist/headers/Trailer.d.ts +30 -0
  74. package/dist/headers/Trailer.js +63 -0
  75. package/dist/headers/VLAN_802dot1Q.d.ts +1 -0
  76. package/dist/headers/VLAN_802dot1Q.js +3 -0
  77. package/dist/headers/WakeOnLAN.js +2 -1
  78. package/dist/headers/WireGuard.js +3 -2
  79. package/dist/headers/Zabbix.js +2 -2
  80. package/dist/lib/BERElement.d.ts +51 -0
  81. package/dist/lib/BERElement.js +125 -0
  82. package/dist/types/LayerGraph.d.ts +10 -5
  83. package/package.json +2 -2
@@ -1,4 +1,5 @@
1
1
  "use strict";
2
+ var _a;
2
3
  Object.defineProperty(exports, "__esModule", { value: true });
3
4
  exports.DNP3 = void 0;
4
5
  const BaseHeader_1 = require("../abstracts/BaseHeader");
@@ -16,13 +17,18 @@ const Crc_1 = require("../helper/Crc");
16
17
  * Source address, and a header CRC. The user data that follows is carried in blocks of up to 16 octets
17
18
  * each with its own trailing 2-byte CRC.
18
19
  *
19
- * This codec decodes the link header structurally and keeps the data-block region (transport header +
20
- * application data + the per-block CRCs) verbatim as `payload` hex — de-blocking those CRCs to recover
21
- * the transport/application layer is a cross-frame reassembly concern, not a single-packet one. The block
22
- * CRCs stay inside `payload` exactly as given. Length and the header CRC are written as given; left out,
23
- * Length counts the payload's data octets (its block CRCs excluded) and the header CRC is computed
24
- * (CRC-16/DNP over the first 8 octets). A well-formed frame round-trips byte-for-byte; the frame's extent is
25
- * derived from the Length field so a pipelined/trailing frame is left to RawData.
20
+ * This codec decodes the link header structurally and carries the data-block region in one of two hex
21
+ * fields. `userData` is the user data with the block CRCs removed (transport header + application data,
22
+ * not decoded further: reassembling the transport/application layer is a cross-frame concern); `payload`
23
+ * is the region verbatim, block CRCs included. Decode emits exactly one of them: `userData` when the
24
+ * region is complete and every block CRC verifies, otherwise `payload` plus a warning naming each bad or
25
+ * truncated block. On encode a given `payload` wins and is written as given (how a frame with a wrong
26
+ * block CRC is crafted; a `userData` given alongside it is ignored with a warning); otherwise `userData`
27
+ * is split into 16-octet blocks, each followed by its CRC-16/DNP, low octet first. Length and the header
28
+ * CRC are written as given; left out, Length counts the user data octets (the block CRCs excluded) and
29
+ * the header CRC is computed (CRC-16/DNP over the first 8 octets). A frame round-trips byte-for-byte
30
+ * either way; the frame's extent is derived from the Length field so a pipelined/trailing frame is left
31
+ * to RawData.
26
32
  */
27
33
  class DNP3 extends BaseHeader_1.BaseHeader {
28
34
  constructor() {
@@ -31,12 +37,12 @@ class DNP3 extends BaseHeader_1.BaseHeader {
31
37
  this.name = 'Distributed Network Protocol 3';
32
38
  this.nickname = 'DNP3';
33
39
  this.matchKeys = ['tcpport:20000', 'udpport:20000'];
34
- //A leaf header — the transport/application layers require de-blocking (a reassembly concern).
40
+ //A leaf header — the transport/application layers require reassembly across frames.
35
41
  this.demuxProducers = [];
36
42
  }
37
43
  static #schemaCache;
38
44
  get SCHEMA() {
39
- return (DNP3.#schemaCache ??= DNP3.#buildSchema());
45
+ return (_a.#schemaCache ??= _a.#buildSchema());
40
46
  }
41
47
  /** A single bit of the Control octet (byte 3, bit 0 = MSB). */
42
48
  static #flagBit(name, bitOffset, label) {
@@ -68,6 +74,50 @@ class DNP3 extends BaseHeader_1.BaseHeader {
68
74
  const rest = payloadOctets % 18;
69
75
  return Math.floor(payloadOctets / 18) * 16 + (rest > 2 ? rest - 2 : 0);
70
76
  }
77
+ /** A block CRC-16/DNP as it goes on the wire, low octet first. */
78
+ static #blockCrc(data) {
79
+ const crc = (0, Crc_1.Crc16Dnp)(data);
80
+ return Buffer.from([crc & 0xff, (crc >> 8) & 0xff]);
81
+ }
82
+ /** `userData` split into 16-octet blocks, each followed by its CRC. */
83
+ static #toDataBlocks(userData) {
84
+ const blocks = [];
85
+ for (let offset = 0; offset < userData.length; offset += 16) {
86
+ const data = userData.subarray(offset, offset + 16);
87
+ blocks.push(data, _a.#blockCrc(data));
88
+ }
89
+ return Buffer.concat(blocks);
90
+ }
91
+ /**
92
+ * Read the data-block region (bounded by the Length-derived frame extent and the captured bytes) and
93
+ * de-block it along the block sizes the Length field implies. `faults` names every block whose CRC
94
+ * does not verify and a block the capture cuts short; `userData` (the data octets, CRCs removed) is
95
+ * only meaningful when there are none.
96
+ */
97
+ #dataBlocks() {
98
+ const frameLength = this.#frameLength();
99
+ const remaining = this.packet.length - this.startPos;
100
+ const end = frameLength > remaining ? remaining : frameLength;
101
+ const region = end > 10 ? this.readBytes(10, end - 10) : Buffer.alloc(0);
102
+ const data = [];
103
+ const faults = [];
104
+ let offset = 0;
105
+ for (let block = 1; offset < frameLength - 10; block++) {
106
+ const size = Math.min(18, frameLength - 10 - offset);
107
+ if (offset + size > region.length) {
108
+ faults.push(`Data block ${block} is truncated: ${region.length - offset} of ${size} octets`);
109
+ break;
110
+ }
111
+ const blockData = region.subarray(offset, offset + size - 2);
112
+ const crc = (0, BufferToHex_1.BufferToHex)(region.subarray(offset + size - 2, offset + size));
113
+ const expected = (0, BufferToHex_1.BufferToHex)(_a.#blockCrc(blockData));
114
+ if (crc !== expected)
115
+ faults.push(`Data block ${block} CRC ${crc} does not match the computed ${expected}`);
116
+ data.push(blockData);
117
+ offset += size;
118
+ }
119
+ return { region: region, userData: Buffer.concat(data), faults: faults };
120
+ }
71
121
  static #buildSchema() {
72
122
  return {
73
123
  type: 'object',
@@ -75,7 +125,8 @@ class DNP3 extends BaseHeader_1.BaseHeader {
75
125
  properties: {
76
126
  //Default 0x0564: the start octets every DNP3 frame begins with, and what match() requires.
77
127
  start: { ...this.fieldHex('start', 0, 2, 'Start'), default: '0564' },
78
- //Octets from Control through the user data, the block CRCs excluded: 5 + user data octets.
128
+ //Octets from Control through the user data, the block CRCs excluded: 5 + user data octets,
129
+ //counted from whichever of payload / userData is written.
79
130
  length: {
80
131
  type: 'integer',
81
132
  autoCalculated: true,
@@ -90,7 +141,10 @@ class DNP3 extends BaseHeader_1.BaseHeader {
90
141
  this.writeBytes(2, (0, NumberToBuffer_1.UInt8ToBuffer)(this.instance.length.getValue(0)));
91
142
  return;
92
143
  }
93
- let length = 5 + DNP3.#userDataOctets((0, HexToBuffer_1.HexToBuffer)(this.instance.payload.getValue('')).length);
144
+ const userDataOctets = this.isLeftOut(this.instance.payload)
145
+ ? (0, HexToBuffer_1.HexToBuffer)(this.instance.userData.getValue('')).length
146
+ : _a.#userDataOctets((0, HexToBuffer_1.HexToBuffer)(this.instance.payload.getValue('')).length);
147
+ let length = 5 + userDataOctets;
94
148
  if (length > 255) {
95
149
  this.recordError(this.instance.length.getPath(), 'Maximum value is 255');
96
150
  length = 255;
@@ -168,18 +222,43 @@ class DNP3 extends BaseHeader_1.BaseHeader {
168
222
  this.writeBytes(8, crcBuffer);
169
223
  }
170
224
  },
171
- //The data-block region: transport header + application data + per-block CRCs, kept verbatim.
172
- //Bounded by the Length-derived frame extent so a pipelined/trailing frame is left to raw.
225
+ //The user data (transport header + application data) with the block CRCs removed. Decoded
226
+ //when the data-block region is complete and every block CRC verifies; encoded into 16-octet
227
+ //blocks, each followed by its CRC, unless a payload is given.
228
+ userData: {
229
+ type: 'string',
230
+ label: 'User Data',
231
+ contentEncoding: StringContentEncodingEnum_1.StringContentEncodingEnum.HEX,
232
+ decode: function () {
233
+ const blocks = this.#dataBlocks();
234
+ if (!blocks.faults.length)
235
+ this.instance.userData.setValue((0, BufferToHex_1.BufferToHex)(blocks.userData));
236
+ },
237
+ encode: function () {
238
+ if (this.isLeftOut(this.instance.userData))
239
+ return;
240
+ if (!this.isLeftOut(this.instance.payload)) {
241
+ this.recordError(this.instance.userData.getPath(), 'Ignored: payload is given and is written verbatim instead');
242
+ return;
243
+ }
244
+ this.writeBytes(10, _a.#toDataBlocks((0, HexToBuffer_1.HexToBuffer)(this.instance.userData.getValue(''))));
245
+ }
246
+ },
247
+ //The data-block region verbatim: transport header + application data + per-block CRCs.
248
+ //Decoded instead of userData when a block CRC is wrong or the capture cuts a block short;
249
+ //given on encode, it is written as given. Bounded by the Length-derived frame extent so a
250
+ //pipelined/trailing frame is left to raw.
173
251
  payload: {
174
252
  type: 'string',
175
253
  label: 'Payload',
176
254
  contentEncoding: StringContentEncodingEnum_1.StringContentEncodingEnum.HEX,
177
255
  decode: function () {
178
- const remaining = this.packet.length - this.startPos;
179
- let end = this.#frameLength();
180
- if (end > remaining)
181
- end = remaining;
182
- this.instance.payload.setValue(end > 10 ? (0, BufferToHex_1.BufferToHex)(this.readBytes(10, end - 10)) : '');
256
+ if (!this.instance.userData.isUndefined())
257
+ return;
258
+ const blocks = this.#dataBlocks();
259
+ this.instance.payload.setValue((0, BufferToHex_1.BufferToHex)(blocks.region));
260
+ for (const fault of blocks.faults)
261
+ this.recordError(this.instance.payload.getPath(), `${fault}; the data blocks are kept verbatim as payload`, 'warning');
183
262
  },
184
263
  encode: function () {
185
264
  const payload = this.instance.payload.getValue('');
@@ -203,3 +282,4 @@ class DNP3 extends BaseHeader_1.BaseHeader {
203
282
  }
204
283
  }
205
284
  exports.DNP3 = DNP3;
285
+ _a = DNP3;
@@ -64,11 +64,13 @@ class DTLS extends BaseHeader_1.BaseHeader {
64
64
  summary: 'DTLS type=${contentType} len=${length}',
65
65
  properties: {
66
66
  //ContentType (20 change_cipher_spec, 21 alert, 22 handshake, 23 application_data,
67
- //24 heartbeat). Kept as an integer — the record header is otherwise opaque here.
68
- contentType: this.fieldUInt('contentType', 0, 1, 'Content Type'),
67
+ //24 heartbeat). Kept as an integer — the record header is otherwise opaque here. Default
68
+ //22 (handshake): match() requires a type in 20..25.
69
+ contentType: { ...this.fieldUInt('contentType', 0, 1, 'Content Type'), default: 22 },
69
70
  //Version — 0xfeff DTLS 1.0 / 0xfefd DTLS 1.2. Stored as a lower-case hex string so any
70
71
  //value round-trips verbatim (the match gate restricts real selection to feff/fefd).
71
- version: this.fieldHex('version', 1, 2, 'Version'),
72
+ //Default fefd (DTLS 1.2).
73
+ version: { ...this.fieldHex('version', 1, 2, 'Version'), default: 'fefd' },
72
74
  epoch: this.fieldUInt('epoch', 3, 2, 'Epoch'),
73
75
  //48-bit per-epoch sequence number, kept verbatim as hex (exceeds the 32-bit fieldUInt path).
74
76
  sequenceNumber: this.fieldHex('sequenceNumber', 5, 6, 'Sequence Number'),
@@ -65,7 +65,8 @@ class Diameter extends BaseHeader_1.BaseHeader {
65
65
  type: 'object',
66
66
  summary: 'Diameter cmd=${commandCode}',
67
67
  properties: {
68
- version: this.fieldUInt('version', 0, 1, 'Version'),
68
+ //Default 1: the only Diameter version (RFC 6733 §3), and what match() requires.
69
+ version: { ...this.fieldUInt('version', 0, 1, 'Version'), default: 1 },
69
70
  messageLength: {
70
71
  type: 'integer',
71
72
  autoCalculated: true,
@@ -43,8 +43,9 @@ class Elasticsearch extends BaseHeader_1.BaseHeader {
43
43
  type: 'object',
44
44
  summary: 'Elasticsearch reqId=${requestId} len=${messageLength}',
45
45
  properties: {
46
- //The 'ES' magic (0x4553) — kept verbatim as hex so any prefix still round-trips.
47
- magic: this.fieldHex('magic', 0, 2, 'Magic'),
46
+ //The 'ES' magic (0x4553) — kept verbatim as hex so any prefix still round-trips. Default
47
+ //'ES': what match() requires.
48
+ magic: { ...this.fieldHex('magic', 0, 2, 'Magic'), default: '4553' },
48
49
  messageLength: {
49
50
  type: 'integer',
50
51
  autoCalculated: true,
@@ -24,5 +24,6 @@ export declare class EthernetII extends BaseHeader {
24
24
  readonly demuxProducers: DemuxProducer[];
25
25
  readonly matchKeys: string[];
26
26
  readonly heuristicFallback: boolean;
27
+ payloadEnd(): number | undefined;
27
28
  match(): boolean;
28
29
  }
@@ -101,6 +101,9 @@ class EthernetII extends BaseHeader_1.BaseHeader {
101
101
  }
102
102
  };
103
103
  }
104
+ payloadEnd() {
105
+ return this.ieee802dot3PayloadEnd(this.instance.etherType);
106
+ }
104
107
  match() {
105
108
  //Fewer bytes than the 14-octet header cannot be reproduced by these fields (encode always writes
106
109
  //a whole header): leave them to raw so they round-trip byte-exact.
@@ -1,6 +1,6 @@
1
1
  import { ProtocolJSONSchema } from '../schema/ProtocolJSONSchema';
2
2
  import { BaseHeader } from '../abstracts/BaseHeader';
3
- import TLV from 'node-tlv';
3
+ import { BERElement } from '../lib/BERElement';
4
4
  declare enum ItemDataType {
5
5
  Boolean = "Boolean",
6
6
  INT8 = "INT8",
@@ -78,10 +78,21 @@ type StructureDataItem = {
78
78
  dataType: ItemDataType.Structure;
79
79
  value: DataItem[];
80
80
  };
81
- type DataItem = BooleanDataItem | INT8DataItem | INT16DataItem | INT32DataItem | INT64DataItem | INT8UDataItem | INT16UDataItem | INT32UDataItem | FLOAT32DataItem | CODEDENUMDataItem | OCTETSTRINGDataItem | VISIBLESTRINGDataItem | TimeStampDataItem | QualityDataItem | StructureDataItem;
81
+ /**
82
+ * How a goosePdu element was encoded on the wire, where that differs from the form encode writes by
83
+ * default (the minimal BER length, the minimal INTEGER content). Decode records it only for such
84
+ * elements, so a tree without it encodes exactly as before; encode follows it while the value fits.
85
+ */
86
+ type ElementEncoding = {
87
+ lengthOctets?: number;
88
+ width?: number;
89
+ content?: string;
90
+ };
91
+ type DataItem = (BooleanDataItem | INT8DataItem | INT16DataItem | INT32DataItem | INT64DataItem | INT8UDataItem | INT16UDataItem | INT32UDataItem | FLOAT32DataItem | CODEDENUMDataItem | OCTETSTRINGDataItem | VISIBLESTRINGDataItem | TimeStampDataItem | QualityDataItem | StructureDataItem) & {
92
+ encoding?: ElementEncoding;
93
+ };
82
94
  export declare class Goose extends BaseHeader {
83
- protected TLVInstance: TLV;
84
- protected TLVChild: TLV[];
95
+ #private;
85
96
  /**
86
97
  * True when at least one structured goosePdu field decoded/was supplied. Used to
87
98
  * decide whether the raw-passthrough fallback applies.
@@ -96,10 +107,11 @@ export declare class Goose extends BaseHeader {
96
107
  SCHEMA: ProtocolJSONSchema;
97
108
  /**
98
109
  * Decode data TLV items
99
- * @param dataTLVs
110
+ * @param dataElements
111
+ * @param path
100
112
  * @protected
101
113
  */
102
- protected decodeDataTLVItem(dataTLVs: TLV[], path: string): DataItem[];
114
+ protected decodeDataTLVItem(dataElements: BERElement[], path: string): DataItem[];
103
115
  /**
104
116
  * Decode a BIT STRING (tag 0x84) data item
105
117
  * CODED-ENUM is 2 octets and Quality 3 octets (the leading unused-bits octet included in the
@@ -130,16 +142,28 @@ export declare class Goose extends BaseHeader {
130
142
  * @protected
131
143
  */
132
144
  protected decodeUnsignedIntegerItem(value: Buffer, path: string): DataItem;
145
+ /**
146
+ * Decode a FLOATING-POINT (tag 0x87) data item
147
+ * The first content octet is the exponent width, not part of the number: IEC 61850-8-1 encodes a
148
+ * FLOAT32 as 08 followed by the 4 octets of an IEEE 754 single. A FLOAT64 (exponent width 11, 8
149
+ * octets) keeps its value; other forms read as 0. Either way the item re-encodes as captured until
150
+ * its value changes.
151
+ * @param value
152
+ * @param path
153
+ * @protected
154
+ */
155
+ protected decodeFloatingPointItem(value: Buffer, path: string): DataItem;
133
156
  /**
134
157
  * Encode data TLV items
135
158
  * @param dataItems
136
159
  * @protected
137
160
  */
138
- protected encodeDataTLVItem(dataItems: DataItem[]): TLV[];
161
+ protected encodeDataTLVItem(dataItems: DataItem[]): Buffer[];
139
162
  readonly id: string;
140
163
  readonly matchKeys: string[];
141
164
  readonly name: string;
142
165
  readonly nickname: string;
143
166
  match(): boolean;
167
+ payloadEnd(): number | undefined;
144
168
  }
145
169
  export {};