@netkitty/codec 1.2.1 → 2.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.
Files changed (176) hide show
  1. package/CHANGELOG.md +159 -0
  2. package/README.md +58 -10
  3. package/README.zh-CN.md +52 -9
  4. package/dist/Codec.d.ts +3 -2
  5. package/dist/Codec.js +106 -10
  6. package/dist/abstracts/BaseHeader.d.ts +28 -2
  7. package/dist/abstracts/BaseHeader.js +132 -43
  8. package/dist/errors/CodecSchemaValidateError.d.ts +34 -1
  9. package/dist/errors/CodecSchemaValidateError.js +26 -3
  10. package/dist/headers/ADSAMS.js +2 -0
  11. package/dist/headers/AH.js +1 -0
  12. package/dist/headers/AMQP.js +2 -1
  13. package/dist/headers/ARP.js +16 -10
  14. package/dist/headers/BACnetIP.js +1 -0
  15. package/dist/headers/BGP.js +1 -0
  16. package/dist/headers/Babel.js +2 -1
  17. package/dist/headers/BitTorrent.d.ts +2 -0
  18. package/dist/headers/BitTorrent.js +4 -2
  19. package/dist/headers/C37118.js +1 -0
  20. package/dist/headers/CAPWAP.js +1 -0
  21. package/dist/headers/CDP.js +1 -1
  22. package/dist/headers/CMS.js +2 -2
  23. package/dist/headers/COTP.d.ts +2 -0
  24. package/dist/headers/COTP.js +6 -1
  25. package/dist/headers/CassandraCQL.js +1 -0
  26. package/dist/headers/Codesys.js +1 -0
  27. package/dist/headers/Collectd.js +1 -1
  28. package/dist/headers/DCCP.js +1 -0
  29. package/dist/headers/DHCPFailover.js +1 -0
  30. package/dist/headers/DNS.js +3 -3
  31. package/dist/headers/DTLS.js +1 -0
  32. package/dist/headers/Diameter.js +3 -2
  33. package/dist/headers/EAPOL.js +1 -1
  34. package/dist/headers/EIGRP.js +1 -1
  35. package/dist/headers/ENIP.js +1 -0
  36. package/dist/headers/Elasticsearch.js +1 -0
  37. package/dist/headers/EtherCAT.js +1 -0
  38. package/dist/headers/EthernetII.js +6 -0
  39. package/dist/headers/FTP.js +6 -6
  40. package/dist/headers/Finger.js +3 -3
  41. package/dist/headers/FoundationFieldbusHSE.js +1 -0
  42. package/dist/headers/GELF.js +7 -1
  43. package/dist/headers/GENEVE.js +1 -1
  44. package/dist/headers/GLBP.js +1 -1
  45. package/dist/headers/GTPU.js +1 -0
  46. package/dist/headers/GTPv2C.js +1 -0
  47. package/dist/headers/GitProtocol.js +2 -2
  48. package/dist/headers/Goose.js +20 -8
  49. package/dist/headers/Gopher.js +6 -6
  50. package/dist/headers/HARTIP.js +1 -0
  51. package/dist/headers/HSR.js +2 -0
  52. package/dist/headers/HTTP.js +6 -6
  53. package/dist/headers/HTTP2.js +1 -0
  54. package/dist/headers/ICMP.js +1 -0
  55. package/dist/headers/ICMPv6.js +1 -0
  56. package/dist/headers/IEC104_I_Frame.js +26 -3
  57. package/dist/headers/IEC104_S_Frame.js +7 -2
  58. package/dist/headers/IEC104_U_Frame.js +14 -3
  59. package/dist/headers/IEC61850SampledValues.js +2 -1
  60. package/dist/headers/IGMP.js +1 -0
  61. package/dist/headers/IMAP.js +5 -5
  62. package/dist/headers/IPFIX.js +2 -1
  63. package/dist/headers/IPv4.js +18 -1
  64. package/dist/headers/IPv6.js +1 -0
  65. package/dist/headers/IPv6HopByHopOptions.js +12 -11
  66. package/dist/headers/IRC.js +4 -4
  67. package/dist/headers/ISAKMP.js +2 -1
  68. package/dist/headers/ISCSI.js +2 -0
  69. package/dist/headers/ISIS.js +2 -1
  70. package/dist/headers/ISOSession.d.ts +2 -0
  71. package/dist/headers/ISOSession.js +14 -10
  72. package/dist/headers/Ident.js +8 -8
  73. package/dist/headers/KNXnetIP.js +1 -0
  74. package/dist/headers/Kafka.js +1 -0
  75. package/dist/headers/Kerberos.js +1 -0
  76. package/dist/headers/L2TP.js +2 -2
  77. package/dist/headers/LACP.js +1 -1
  78. package/dist/headers/LDAP.js +2 -3
  79. package/dist/headers/LDP.js +1 -0
  80. package/dist/headers/LLC.d.ts +2 -0
  81. package/dist/headers/LLC.js +2 -0
  82. package/dist/headers/LPD.js +3 -3
  83. package/dist/headers/MGCP.js +7 -7
  84. package/dist/headers/MMS.d.ts +2 -0
  85. package/dist/headers/MMS.js +10 -6
  86. package/dist/headers/MQTT.js +1 -0
  87. package/dist/headers/MQTTSN.js +1 -0
  88. package/dist/headers/MarkerProtocol.js +1 -1
  89. package/dist/headers/Megaco.js +3 -3
  90. package/dist/headers/Memcached.js +3 -2
  91. package/dist/headers/ModbusTCP.js +1 -0
  92. package/dist/headers/ModbusUDP.js +1 -0
  93. package/dist/headers/MongoDB.js +1 -0
  94. package/dist/headers/MySQL.js +1 -0
  95. package/dist/headers/NATS.js +2 -2
  96. package/dist/headers/NBDS.js +1 -0
  97. package/dist/headers/NBSS.js +1 -0
  98. package/dist/headers/NFS.js +1 -0
  99. package/dist/headers/NHRP.js +1 -0
  100. package/dist/headers/NNTP.js +6 -6
  101. package/dist/headers/NetFlowV5.js +1 -0
  102. package/dist/headers/OLSR.js +2 -1
  103. package/dist/headers/OPCUA.js +1 -0
  104. package/dist/headers/OpenFlow.js +1 -0
  105. package/dist/headers/OpenVPN.js +1 -0
  106. package/dist/headers/PCWorx.js +1 -0
  107. package/dist/headers/POP3.js +5 -5
  108. package/dist/headers/PPPoEDiscovery.js +2 -1
  109. package/dist/headers/PPPoESession.js +1 -0
  110. package/dist/headers/PPTP.js +1 -0
  111. package/dist/headers/PTP.js +1 -0
  112. package/dist/headers/PostgreSQL.js +2 -0
  113. package/dist/headers/QUIC.js +2 -0
  114. package/dist/headers/RADIUS.js +1 -0
  115. package/dist/headers/RDP.d.ts +2 -0
  116. package/dist/headers/RDP.js +4 -1
  117. package/dist/headers/RFB.js +4 -4
  118. package/dist/headers/RGoose.js +6 -1
  119. package/dist/headers/RSVP.js +3 -2
  120. package/dist/headers/RTCP.js +1 -0
  121. package/dist/headers/RTP.js +2 -1
  122. package/dist/headers/RTPS.d.ts +2 -0
  123. package/dist/headers/RTPS.js +4 -1
  124. package/dist/headers/RTSP.js +7 -7
  125. package/dist/headers/RawData.js +1 -1
  126. package/dist/headers/Redis.js +4 -4
  127. package/dist/headers/Rlogin.js +5 -5
  128. package/dist/headers/Rsync.js +2 -2
  129. package/dist/headers/S7comm.d.ts +2 -0
  130. package/dist/headers/S7comm.js +5 -1
  131. package/dist/headers/SCTP.js +2 -2
  132. package/dist/headers/SFlow.js +2 -1
  133. package/dist/headers/SIP.js +6 -6
  134. package/dist/headers/SLMP.js +1 -0
  135. package/dist/headers/SLP.js +2 -0
  136. package/dist/headers/SLPv1.js +1 -0
  137. package/dist/headers/SMB1.js +1 -0
  138. package/dist/headers/SMB2.js +1 -0
  139. package/dist/headers/SMPP.js +1 -0
  140. package/dist/headers/SMTP.js +6 -6
  141. package/dist/headers/SNAP.js +18 -5
  142. package/dist/headers/SNMP.js +4 -4
  143. package/dist/headers/SOCKS4.js +11 -5
  144. package/dist/headers/SSDP.js +7 -7
  145. package/dist/headers/SSH.js +5 -4
  146. package/dist/headers/STOMP.js +5 -5
  147. package/dist/headers/STUN.js +2 -0
  148. package/dist/headers/Skinny.js +1 -0
  149. package/dist/headers/StatsD.js +4 -4
  150. package/dist/headers/SunRPC.js +1 -0
  151. package/dist/headers/Syslog.js +2 -2
  152. package/dist/headers/TCP.js +18 -6
  153. package/dist/headers/TLS_Alert.js +23 -11
  154. package/dist/headers/TLS_ApplicationData.js +9 -4
  155. package/dist/headers/TLS_ChangeCipherSpec.js +10 -5
  156. package/dist/headers/TLS_Handshake.js +41 -26
  157. package/dist/headers/TLS_Heartbeat.js +10 -1
  158. package/dist/headers/TPKT.js +3 -1
  159. package/dist/headers/TacacsPlus.js +1 -0
  160. package/dist/headers/Telnet.js +2 -1
  161. package/dist/headers/Teredo.js +2 -2
  162. package/dist/headers/UDP.js +8 -0
  163. package/dist/headers/VLAN_802dot1Q.js +7 -0
  164. package/dist/headers/WCCP.js +1 -0
  165. package/dist/headers/WHOIS.js +3 -3
  166. package/dist/headers/WSDiscovery.js +2 -2
  167. package/dist/headers/XMPP.js +3 -3
  168. package/dist/headers/Zabbix.js +1 -0
  169. package/dist/index.d.ts +3 -3
  170. package/dist/lib/SchemaValidator.d.ts +31 -0
  171. package/dist/lib/SchemaValidator.js +137 -0
  172. package/dist/schema/ProtocolFieldJSONSchema.d.ts +4 -1
  173. package/dist/schema/ProtocolJSONSchema.d.ts +1 -1
  174. package/dist/types/CodecErrorInfo.d.ts +11 -0
  175. package/dist/types/LayerGraph.d.ts +14 -1
  176. package/package.json +2 -2
@@ -1,10 +1,11 @@
1
1
  import { ProtocolJSONSchema } from '../schema/ProtocolJSONSchema';
2
2
  import { CodecModule } from '../types/CodecModule';
3
3
  import { ProtocolFieldJSONSchema } from '../schema/ProtocolFieldJSONSchema';
4
- import { CodecErrorInfo } from '../types/CodecErrorInfo';
4
+ import { CodecErrorInfo, CodecErrorSeverity } from '../types/CodecErrorInfo';
5
5
  import { PostHandlerItem } from '../types/PostHandlerItem';
6
6
  import { CodecData } from '../types/CodecData';
7
7
  import { DemuxProducer } from '../types/DemuxProducer';
8
+ import { HeuristicParent } from '../types/LayerGraph';
8
9
  import { FlexibleObject } from '../lib/FlexibleObject';
9
10
  import { HeaderTreeNode } from '../types/HeaderTreeNode';
10
11
  /** Absolute byte span a field occupies in the packet, collected during a dissect pass. */
@@ -54,6 +55,8 @@ export declare abstract class BaseHeader {
54
55
  * false: matchKeys → bucket only; no matchKeys → heuristic only.
55
56
  */
56
57
  static get HEURISTIC_FALLBACK(): boolean;
58
+ /** Parent layer ids a content-heuristic header can follow (see the instance field heuristicParents). */
59
+ static get HEURISTIC_PARENTS(): HeuristicParent[];
57
60
  /** Higher is tried first within a demux bucket and within the heuristic chain; ties keep registration order. */
58
61
  static get MATCH_PRIORITY(): number;
59
62
  static get PROTOCOL_SCHEMA(): ProtocolJSONSchema;
@@ -101,6 +104,15 @@ export declare abstract class BaseHeader {
101
104
  readonly heuristicFallback: boolean;
102
105
  /** Selection priority within a bucket / the heuristic chain (higher first; ties keep registration order). */
103
106
  readonly matchPriority: number;
107
+ /**
108
+ * Editor graph only (never used to select a codec on decode): the parent layer ids this header can
109
+ * follow when it is matched by content rather than by a demux key (no matchKeys, or reachable off its
110
+ * parent only via heuristicFallback) — e.g. LLC after eth/vlan (802.3 length), COTP after TPKT.
111
+ * allowedNextLayers(parent) lists such a child with a null discriminator — there is no parent field
112
+ * to set, the child's own bytes (or a value encode derives, like the 802.3 length) route it — or,
113
+ * for an entry {parent, discriminator}, with that parent field value the child needs.
114
+ */
115
+ readonly heuristicParents: HeuristicParent[];
104
116
  /**
105
117
  * Encode/Decode error info objects
106
118
  */
@@ -272,13 +284,27 @@ export declare abstract class BaseHeader {
272
284
  * @protected
273
285
  */
274
286
  protected getFieldCodecs(schema: ProtocolFieldJSONSchema, codecName: string, execBeforeSubCodecs: boolean, codecs?: (() => void | Promise<void>)[], paths?: string[] | null, pathPrefix?: string): (() => void | Promise<void>)[];
287
+ /**
288
+ * Encode an EtherType field the input left out (eth/vlan). The codec has already filled it from the
289
+ * next layer when that layer is routed by EtherType, so reaching here means it is not: when the next
290
+ * encoded layer is LLC the field carries the IEEE 802.3 length (byte count of everything after this
291
+ * header), otherwise it stays 0x0000 and is reported as 'Not Found'. Decided once every layer is
292
+ * encoded, since the length is only known then.
293
+ * @param field the EtherType field node
294
+ * @param offset its header-relative byte offset
295
+ * @protected
296
+ */
297
+ protected encodeOmittedEtherType(field: FlexibleObject, offset: number): void;
275
298
  /**
276
299
  * Record encode/decode error
277
300
  * @param path
278
301
  * @param message
302
+ * @param severity defaults by phase: every decode error is 'error'; on encode, a missing field that
303
+ * fell back to its default ('Not Found') is 'info', an internal exception is 'error', and anything
304
+ * else recorded while still writing the layer (clamped values, odd-but-encodable values) is 'warning'
279
305
  * @protected
280
306
  */
281
- protected recordError(path: string, message: string): void;
307
+ protected recordError(path: string, message: string, severity?: CodecErrorSeverity): void;
282
308
  /**
283
309
  * Register post encode handler for current codec
284
310
  * @param handler
@@ -3,8 +3,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.BaseHeader = void 0;
4
4
  const SortPostHandlers_1 = require("../lib/SortPostHandlers");
5
5
  const FlexibleObject_1 = require("../lib/FlexibleObject");
6
- const ajv_1 = require("ajv");
7
- const CodecSchemaValidateError_1 = require("../errors/CodecSchemaValidateError");
6
+ const SchemaValidator_1 = require("../lib/SchemaValidator");
8
7
  const BufferToNumber_1 = require("../helper/BufferToNumber");
9
8
  const NumberToBuffer_1 = require("../helper/NumberToBuffer");
10
9
  const BufferToHex_1 = require("../helper/BufferToHex");
@@ -12,7 +11,7 @@ const HexToBuffer_1 = require("../helper/HexToBuffer");
12
11
  const BufferToIP_1 = require("../helper/BufferToIP");
13
12
  const IPToBuffer_1 = require("../helper/IPToBuffer");
14
13
  const StringContentEncodingEnum_1 = require("../lib/StringContentEncodingEnum");
15
- const CONSTRUCTOR_VALIDATE_KEY = '__validate';
14
+ const NumberToHex_1 = require("../helper/NumberToHex");
16
15
  //Per-codec-class cached MATCH probe. Content-heuristic selection calls MATCH() on many candidates
17
16
  //per layer; each used to build a whole fresh instance (rebuilding the SCHEMA) just to run match().
18
17
  //Since match() only inspects the previous layer and the raw buffer, one reusable probe per class
@@ -73,25 +72,20 @@ class BaseHeader {
73
72
  static get HEURISTIC_FALLBACK() {
74
73
  return this.CODEC_INSTANCE.heuristicFallback;
75
74
  }
75
+ /** Parent layer ids a content-heuristic header can follow (see the instance field heuristicParents). */
76
+ static get HEURISTIC_PARENTS() {
77
+ return this.CODEC_INSTANCE.heuristicParents;
78
+ }
76
79
  /** Higher is tried first within a demux bucket and within the heuristic chain; ties keep registration order. */
77
80
  static get MATCH_PRIORITY() {
78
81
  return this.CODEC_INSTANCE.matchPriority;
79
82
  }
83
+ //The JSON round-trip strips the decode/encode closures, leaving the declarative shell (plus the
84
+ //format/pattern each contentEncoding implies, see DeriveContentConstraints). The Ajv
85
+ //validator is no longer compiled here (it was, for every protocol, at `new Codec()`); validate()
86
+ //compiles it on first encode of that protocol.
80
87
  static get PROTOCOL_SCHEMA() {
81
- const schema = JSON.parse(JSON.stringify(this.CODEC_INSTANCE.SCHEMA));
82
- if (!Object.hasOwn(this, CONSTRUCTOR_VALIDATE_KEY)) {
83
- const validate = new ajv_1.Ajv({
84
- strict: false,
85
- useDefaults: true,
86
- coerceTypes: true
87
- }).compile(schema);
88
- Object.defineProperty(this, CONSTRUCTOR_VALIDATE_KEY, {
89
- enumerable: false,
90
- configurable: false,
91
- value: validate
92
- });
93
- }
94
- return schema;
88
+ return (0, SchemaValidator_1.DeriveContentConstraints)(JSON.parse(JSON.stringify(this.CODEC_INSTANCE.SCHEMA)));
95
89
  }
96
90
  static MATCH(codecData, codecModules) {
97
91
  //Reuse one cached probe instance per codec class instead of rebuilding a full instance (and its
@@ -114,6 +108,14 @@ class BaseHeader {
114
108
  //the hot path is untouched. See enableByteRangeTracking() / getByteRanges().
115
109
  #byteRanges;
116
110
  #currentFieldPath;
111
+ //Index (in getFieldCodecs walk order) of the field closure currently running, and its phase. A
112
+ //post handler registered from inside that closure captures them, so an exception it throws later
113
+ //is attributed to the field that registered it. -1 outside the field loop.
114
+ #activeFieldIndex;
115
+ #activeFieldPhase;
116
+ //Whether this instance is decoding or encoding; picks the default severity of recorded errors.
117
+ //Stays set after encode()/decode() return, so packet-level post handlers (which run later) inherit it.
118
+ #phase;
117
119
  /**
118
120
  * Turn on byte-range collection for a dissect pass (call before decode()). Additive and
119
121
  * read-only: it changes nothing about the decoded values, only records where each field lives.
@@ -191,6 +193,15 @@ class BaseHeader {
191
193
  this.heuristicFallback = false;
192
194
  /** Selection priority within a bucket / the heuristic chain (higher first; ties keep registration order). */
193
195
  this.matchPriority = 0;
196
+ /**
197
+ * Editor graph only (never used to select a codec on decode): the parent layer ids this header can
198
+ * follow when it is matched by content rather than by a demux key (no matchKeys, or reachable off its
199
+ * parent only via heuristicFallback) — e.g. LLC after eth/vlan (802.3 length), COTP after TPKT.
200
+ * allowedNextLayers(parent) lists such a child with a null discriminator — there is no parent field
201
+ * to set, the child's own bytes (or a value encode derives, like the 802.3 length) route it — or,
202
+ * for an entry {parent, discriminator}, with that parent field value the child needs.
203
+ */
204
+ this.heuristicParents = [];
194
205
  /**
195
206
  * Encode/Decode error info objects
196
207
  */
@@ -204,6 +215,14 @@ class BaseHeader {
204
215
  //the hot path is untouched. See enableByteRangeTracking() / getByteRanges().
205
216
  this.#byteRanges = null;
206
217
  this.#currentFieldPath = '';
218
+ //Index (in getFieldCodecs walk order) of the field closure currently running, and its phase. A
219
+ //post handler registered from inside that closure captures them, so an exception it throws later
220
+ //is attributed to the field that registered it. -1 outside the field loop.
221
+ this.#activeFieldIndex = -1;
222
+ this.#activeFieldPhase = 'decode';
223
+ //Whether this instance is decoding or encoding; picks the default severity of recorded errors.
224
+ //Stays set after encode()/decode() return, so packet-level post handlers (which run later) inherit it.
225
+ this.#phase = 'decode';
207
226
  /**
208
227
  * The start position of this header in the entire packet's buffer
209
228
  */
@@ -559,19 +578,70 @@ class BaseHeader {
559
578
  }
560
579
  return codecs;
561
580
  }
581
+ /**
582
+ * Encode an EtherType field the input left out (eth/vlan). The codec has already filled it from the
583
+ * next layer when that layer is routed by EtherType, so reaching here means it is not: when the next
584
+ * encoded layer is LLC the field carries the IEEE 802.3 length (byte count of everything after this
585
+ * header), otherwise it stays 0x0000 and is reported as 'Not Found'. Decided once every layer is
586
+ * encoded, since the length is only known then.
587
+ * @param field the EtherType field node
588
+ * @param offset its header-relative byte offset
589
+ * @protected
590
+ */
591
+ encodeOmittedEtherType(field, offset) {
592
+ this.writeBytes(offset, Buffer.alloc(2, 0));
593
+ this.addPostPacketEncodeHandler(() => {
594
+ const index = this.codecModules.indexOf(this);
595
+ const next = index >= 0 ? this.codecModules[index + 1] : undefined;
596
+ if (!next || next.id !== 'llc') {
597
+ this.recordError(field.getPath(), 'Not Found');
598
+ return;
599
+ }
600
+ let length = 0;
601
+ for (let i = index + 1; i < this.codecModules.length; i++)
602
+ length += this.codecModules[i].length;
603
+ if (length > 0x05dc)
604
+ this.recordError(field.getPath(), `802.3 length ${length} exceeds 1500, the frame will not decode as LLC`);
605
+ field.setValue((0, NumberToHex_1.UInt16ToHex)(Math.min(length, 0xffff)));
606
+ this.writeBytes(offset, (0, NumberToBuffer_1.UInt16ToBuffer)(Math.min(length, 0xffff)));
607
+ });
608
+ }
609
+ /**
610
+ * Dotted path of the index-th field codec in the same walk order getFieldCodecs uses. Cold path only
611
+ * (a field closure threw): rebuilds the path list on demand so the hot loop carries no per-field
612
+ * path bookkeeping, yet the recorded error still names the field that failed instead of ''.
613
+ */
614
+ #fieldPathAt(codecName, execBeforeSubCodecs, index) {
615
+ const paths = [];
616
+ this.getFieldCodecs(this.SCHEMA, codecName, execBeforeSubCodecs, [], paths);
617
+ return paths[index] ?? '';
618
+ }
562
619
  /**
563
620
  * Record encode/decode error
564
621
  * @param path
565
622
  * @param message
623
+ * @param severity defaults by phase: every decode error is 'error'; on encode, a missing field that
624
+ * fell back to its default ('Not Found') is 'info', an internal exception is 'error', and anything
625
+ * else recorded while still writing the layer (clamped values, odd-but-encodable values) is 'warning'
566
626
  * @protected
567
627
  */
568
- recordError(path, message) {
628
+ recordError(path, message, severity) {
569
629
  this.errors.push({
570
630
  id: this.id,
571
631
  path: path,
572
- message: message
632
+ message: message,
633
+ severity: severity ? severity : this.#defaultSeverity(message)
573
634
  });
574
635
  }
636
+ #defaultSeverity(message) {
637
+ if (this.#phase === 'decode')
638
+ return 'error';
639
+ if (message === 'Not Found')
640
+ return 'info';
641
+ if (message.startsWith('Encode error:'))
642
+ return 'error';
643
+ return 'warning';
644
+ }
575
645
  /**
576
646
  * Register post encode handler for current codec
577
647
  * @param handler
@@ -581,7 +651,7 @@ class BaseHeader {
581
651
  addPostSelfEncodeHandler(handler, priority = 0) {
582
652
  this.postSelfEncodeHandlers.push({
583
653
  priority: priority,
584
- handler: handler
654
+ handler: this.#guardPostHandler(handler)
585
655
  });
586
656
  }
587
657
  /**
@@ -593,7 +663,7 @@ class BaseHeader {
593
663
  addPostSelfDecodeHandler(handler, priority = 0) {
594
664
  this.postSelfDecodeHandlers.push({
595
665
  priority: priority,
596
- handler: handler
666
+ handler: this.#guardPostHandler(handler)
597
667
  });
598
668
  }
599
669
  /**
@@ -606,7 +676,7 @@ class BaseHeader {
606
676
  addPostPacketEncodeHandler(handler, priority = 0) {
607
677
  this.postPacketHandlers.push({
608
678
  priority: priority,
609
- handler: handler
679
+ handler: this.#guardPostHandler(handler)
610
680
  });
611
681
  }
612
682
  /**
@@ -619,37 +689,48 @@ class BaseHeader {
619
689
  addPostPacketDecodeHandler(handler, priority = 0) {
620
690
  this.postPacketHandlers.push({
621
691
  priority: priority,
622
- handler: handler
692
+ handler: this.#guardPostHandler(handler)
623
693
  });
624
694
  }
695
+ /**
696
+ * Wrap a post handler so an exception it throws (sync or async) is contained as a recorded error,
697
+ * the same contract as a field closure: encode/decode never crash on an edge-case input (e.g. a
698
+ * UDP layer encoded without an IP parent for its checksum pseudo-header). The error is attributed
699
+ * to the field whose closure registered the handler, when there is one.
700
+ */
701
+ #guardPostHandler(handler) {
702
+ const fieldIndex = this.#activeFieldIndex;
703
+ const phase = this.#activeFieldPhase;
704
+ const record = (e) => {
705
+ const path = fieldIndex >= 0 ? this.#fieldPathAt(phase, phase === 'decode', fieldIndex) : '';
706
+ this.recordError(path, `${phase === 'encode' ? 'Encode' : 'Decode'} error: ${e.message}`);
707
+ };
708
+ return () => {
709
+ try {
710
+ const result = handler();
711
+ if (result && typeof result.then === 'function')
712
+ return result.catch(record);
713
+ }
714
+ catch (e) {
715
+ record(e);
716
+ }
717
+ };
718
+ }
625
719
  /**
626
720
  * Validate input json node is valid
627
721
  * @param headerTreeNode
628
722
  */
629
723
  validate(headerTreeNode) {
630
- let validate = this.constructor[CONSTRUCTOR_VALIDATE_KEY];
631
- if (!validate) {
632
- validate = new ajv_1.Ajv({
633
- strict: false,
634
- useDefaults: true,
635
- coerceTypes: true
636
- }).compile(this.SCHEMA);
637
- this.constructor[CONSTRUCTOR_VALIDATE_KEY] = validate;
638
- }
639
- const isValid = validate(headerTreeNode);
640
- if (!isValid) {
641
- let errorObject;
642
- if (validate.errors)
643
- errorObject = validate.errors[0];
644
- const errorMessage = errorObject?.message ? errorObject.message : 'Unknown Error';
645
- throw new CodecSchemaValidateError_1.CodecSchemaValidateError(errorMessage);
646
- }
724
+ const validate = (0, SchemaValidator_1.SchemaValidatorOf)(this.constructor, this.SCHEMA);
725
+ if (!validate(headerTreeNode))
726
+ throw (0, SchemaValidator_1.SchemaValidateErrorOf)(this.id, validate.errors);
647
727
  return headerTreeNode;
648
728
  }
649
729
  /**
650
730
  * Decode packet header field by field
651
731
  */
652
732
  async decode() {
733
+ this.#phase = 'decode';
653
734
  const paths = this.#byteRanges ? [] : null;
654
735
  const decodes = this.getFieldCodecs(this.SCHEMA, 'decode', true, [], paths);
655
736
  for (let i = 0; i < decodes.length; i++) {
@@ -660,6 +741,8 @@ class BaseHeader {
660
741
  //closures are synchronous, so this avoids a promise allocation + scheduler turn per field.
661
742
  if (paths)
662
743
  this.#currentFieldPath = paths[i];
744
+ this.#activeFieldIndex = i;
745
+ this.#activeFieldPhase = 'decode';
663
746
  try {
664
747
  //Invoke with the current instance as `this`. Arrow closures (headers not yet migrated)
665
748
  //ignore the binding and use their captured lexical this — the same instance — so this is
@@ -670,12 +753,13 @@ class BaseHeader {
670
753
  await result;
671
754
  }
672
755
  catch (e) {
673
- this.recordError('', `Decode error: ${e.message}`);
756
+ this.recordError(paths ? paths[i] : this.#fieldPathAt('decode', true, i), `Decode error: ${e.message}`);
674
757
  }
675
758
  }
676
759
  //Post-handler reads (cross-field/cross-layer fixups) are not a single field's bytes — clear
677
760
  //the tracked path so they are not attributed to whichever field decoded last.
678
761
  this.#currentFieldPath = '';
762
+ this.#activeFieldIndex = -1;
679
763
  const postSelfDecodeHandlers = (0, SortPostHandlers_1.SortPostHandlers)(this.postSelfDecodeHandlers);
680
764
  let postDecodeHandler = postSelfDecodeHandlers.shift();
681
765
  while (postDecodeHandler) {
@@ -692,8 +776,12 @@ class BaseHeader {
692
776
  * Encode packet header field by field
693
777
  */
694
778
  async encode() {
779
+ this.#phase = 'encode';
695
780
  const encodes = this.getFieldCodecs(this.SCHEMA, 'encode', false);
696
- for (const encode of encodes) {
781
+ for (let i = 0; i < encodes.length; i++) {
782
+ const encode = encodes[i];
783
+ this.#activeFieldIndex = i;
784
+ this.#activeFieldPhase = 'encode';
697
785
  //Shape validation is the deliberate fast-fail at the encode entry point (Ajv, in
698
786
  //Codec.#encode); it runs before we get here. Past that, a field's encode closure must
699
787
  //not crash the whole encode on an edge-case value — contain it to a recorded error so
@@ -706,9 +794,10 @@ class BaseHeader {
706
794
  await result;
707
795
  }
708
796
  catch (e) {
709
- this.recordError('', `Encode error: ${e.message}`);
797
+ this.recordError(this.#fieldPathAt('encode', false, i), `Encode error: ${e.message}`);
710
798
  }
711
799
  }
800
+ this.#activeFieldIndex = -1;
712
801
  const postSelfEncodeHandlers = (0, SortPostHandlers_1.SortPostHandlers)(this.postSelfEncodeHandlers);
713
802
  let postEncodeHandler = postSelfEncodeHandlers.shift();
714
803
  while (postEncodeHandler) {
@@ -1,6 +1,39 @@
1
1
  import { NetKittyError } from '@netkitty/errors';
2
- /** Thrown at the encode entry point when an input fails Ajv shape validation against the header schema. */
2
+ /** One Ajv validation failure, plus the dotted field path the codec uses for its other errors. */
3
+ export type CodecSchemaValidationIssue = {
4
+ /** Ajv JSON Pointer to the offending value inside the layer's data, e.g. '/flags/rb'. */
5
+ instancePath: string;
6
+ /** Ajv JSON Pointer to the failing keyword inside the schema. */
7
+ schemaPath: string;
8
+ /** The failing JSON Schema keyword, e.g. 'minLength', 'enum', 'format'. */
9
+ keyword: string;
10
+ /** Keyword-specific details from Ajv, e.g. {limit: 7}. */
11
+ params: Record<string, unknown>;
12
+ message: string;
13
+ /** Dotted field path inside the layer, e.g. 'flags.rb' or 'options[0].kind'. */
14
+ path: string;
15
+ };
16
+ /**
17
+ * Thrown at the encode entry point when an input fails Ajv shape validation against the header schema.
18
+ * `layerId` / `layerIndex` name the input layer, `path` the field inside it (same dotted form as
19
+ * `result.errors[].path`), and `errors` carries Ajv's own error objects. `message` is Ajv's message for
20
+ * the first failure.
21
+ */
3
22
  export declare class CodecSchemaValidateError extends NetKittyError {
4
23
  errno: number;
5
24
  code: string;
25
+ /** PROTOCOL_ID of the input layer that failed validation, e.g. 'ipv4'. */
26
+ layerId: string;
27
+ /** Index of that layer in the encode() input array; -1 when validate() was called directly. */
28
+ layerIndex: number;
29
+ /** Dotted path of the failing field inside the layer, e.g. 'sip'. '' when the layer data itself failed. */
30
+ path: string;
31
+ /** Every Ajv error reported for this layer (validation stops at the first failing keyword). */
32
+ errors: CodecSchemaValidationIssue[];
33
+ constructor(message?: string, details?: {
34
+ layerId?: string;
35
+ layerIndex?: number;
36
+ path?: string;
37
+ errors?: CodecSchemaValidationIssue[];
38
+ });
6
39
  }
@@ -2,12 +2,35 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.CodecSchemaValidateError = void 0;
4
4
  const errors_1 = require("@netkitty/errors");
5
- /** Thrown at the encode entry point when an input fails Ajv shape validation against the header schema. */
5
+ /**
6
+ * Thrown at the encode entry point when an input fails Ajv shape validation against the header schema.
7
+ * `layerId` / `layerIndex` name the input layer, `path` the field inside it (same dotted form as
8
+ * `result.errors[].path`), and `errors` carries Ajv's own error objects. `message` is Ajv's message for
9
+ * the first failure.
10
+ */
6
11
  class CodecSchemaValidateError extends errors_1.NetKittyError {
7
- constructor() {
8
- super(...arguments);
12
+ constructor(message, details) {
13
+ super(message);
9
14
  this.errno = errors_1.ErrorCode.E_CODEC_SCHEMA_VALIDATE.errno;
10
15
  this.code = errors_1.ErrorCode.E_CODEC_SCHEMA_VALIDATE.code;
16
+ /** PROTOCOL_ID of the input layer that failed validation, e.g. 'ipv4'. */
17
+ this.layerId = '';
18
+ /** Index of that layer in the encode() input array; -1 when validate() was called directly. */
19
+ this.layerIndex = -1;
20
+ /** Dotted path of the failing field inside the layer, e.g. 'sip'. '' when the layer data itself failed. */
21
+ this.path = '';
22
+ /** Every Ajv error reported for this layer (validation stops at the first failing keyword). */
23
+ this.errors = [];
24
+ if (details) {
25
+ if (details.layerId !== undefined)
26
+ this.layerId = details.layerId;
27
+ if (details.layerIndex !== undefined)
28
+ this.layerIndex = details.layerIndex;
29
+ if (details.path !== undefined)
30
+ this.path = details.path;
31
+ if (details.errors !== undefined)
32
+ this.errors = details.errors;
33
+ }
11
34
  }
12
35
  }
13
36
  exports.CodecSchemaValidateError = CodecSchemaValidateError;
@@ -103,6 +103,7 @@ class ADSAMS extends BaseHeader_1.BaseHeader {
103
103
  reserved: this.fieldHex('reserved', 0, 2, 'Reserved'),
104
104
  length: {
105
105
  type: 'integer',
106
+ autoCalculated: true,
106
107
  label: 'AMS/TCP Length',
107
108
  minimum: 0,
108
109
  maximum: 4294967295,
@@ -142,6 +143,7 @@ class ADSAMS extends BaseHeader_1.BaseHeader {
142
143
  stateFlags: this.#fieldUInt16LE('stateFlags', 24, 'State Flags'),
143
144
  dataLength: {
144
145
  type: 'integer',
146
+ autoCalculated: true,
145
147
  label: 'Data Length',
146
148
  minimum: 0,
147
149
  maximum: 4294967295,
@@ -74,6 +74,7 @@ class AH extends BaseHeader_1.BaseHeader {
74
74
  //kept verbatim, an absent (0) one is recomputed from the encoded ICV length.
75
75
  payloadLen: {
76
76
  type: 'integer',
77
+ autoCalculated: true,
77
78
  label: 'Payload Length',
78
79
  minimum: 0,
79
80
  maximum: 255,
@@ -115,7 +115,7 @@ class AMQP extends BaseHeader_1.BaseHeader {
115
115
  },
116
116
  //Decode-only display string for the Info summary (populated above); carries no encode, so
117
117
  //it never affects the emitted bytes.
118
- info: { type: 'string', label: 'Info' },
118
+ info: { type: 'string', label: 'Info', readOnly: true },
119
119
  // ===== Protocol-header handshake form ("AMQP" + four version octets) =====
120
120
  protocol: {
121
121
  type: 'string',
@@ -208,6 +208,7 @@ class AMQP extends BaseHeader_1.BaseHeader {
208
208
  //recorded), and a well-formed frame (Length == payload bytes) never triggers it.
209
209
  length: {
210
210
  type: 'integer',
211
+ autoCalculated: true,
211
212
  label: 'Length',
212
213
  minimum: 0,
213
214
  maximum: 4294967295,
@@ -133,9 +133,12 @@ class ARP extends BaseHeader_1.BaseHeader {
133
133
  }
134
134
  },
135
135
  opcode: {
136
- type: 'number',
136
+ type: 'integer',
137
137
  label: 'Opcode',
138
- enum: [1, 2, 3, 4],
138
+ //A value field (any 16-bit opcode can be decoded and must re-encode); 1–4 are the
139
+ //request/reply/RARP codes, anything else is flagged, not rejected.
140
+ minimum: 0,
141
+ maximum: 65535,
139
142
  decode: () => {
140
143
  this.instance.opcode.setValue((0, BufferToNumber_1.BufferToUInt16)(this.readBytes(6, 2)));
141
144
  if (![1, 2, 3, 4].includes(this.instance.opcode.getValue()))
@@ -158,13 +161,13 @@ class ARP extends BaseHeader_1.BaseHeader {
158
161
  label: 'MAC address',
159
162
  minLength: 17,
160
163
  maxLength: 17,
161
- contentEncoding: StringContentEncodingEnum_1.StringContentEncodingEnum.UTF8,
164
+ contentEncoding: StringContentEncodingEnum_1.StringContentEncodingEnum.MAC,
162
165
  decode: () => {
163
166
  const macAddrBuffer = Buffer.alloc(6, this.readBytes(8, 6));
164
167
  this.instance.sender.mac.setValue(Array.from(macAddrBuffer).map((value) => (0, NumberToHex_1.UInt8ToHex)(value)).join(':'));
165
168
  },
166
169
  encode: () => {
167
- const macStr = this.instance.sender.mac.getValue();
170
+ const macStr = this.instance.sender.mac.getValue('00:00:00:00:00:00', (nodePath) => this.recordError(nodePath, 'Not Found'));
168
171
  const rawMacBuffer = Buffer.from(macStr.split(':').map((value) => parseInt(value, 16)).map((value) => value ? value : 0));
169
172
  if (rawMacBuffer.length !== 6)
170
173
  this.recordError(this.instance.sender.mac.getPath(), 'Invalid MAC address length');
@@ -176,13 +179,13 @@ class ARP extends BaseHeader_1.BaseHeader {
176
179
  label: 'IP address',
177
180
  minLength: 7,
178
181
  maxLength: 15,
179
- contentEncoding: StringContentEncodingEnum_1.StringContentEncodingEnum.UTF8,
182
+ contentEncoding: StringContentEncodingEnum_1.StringContentEncodingEnum.IPv4,
180
183
  decode: () => {
181
184
  const ipv4Buffer = Buffer.alloc(4, this.readBytes(14, 4));
182
185
  this.instance.sender.ipv4.setValue((0, BufferToIP_1.BufferToIPv4)(ipv4Buffer));
183
186
  },
184
187
  encode: () => {
185
- const ipv4Str = this.instance.sender.ipv4.getValue();
188
+ const ipv4Str = this.instance.sender.ipv4.getValue('0.0.0.0', (nodePath) => this.recordError(nodePath, 'Not Found'));
186
189
  this.writeBytes(14, (0, IPToBuffer_1.IPv4ToBuffer)(ipv4Str));
187
190
  }
188
191
  }
@@ -197,13 +200,13 @@ class ARP extends BaseHeader_1.BaseHeader {
197
200
  label: 'MAC address',
198
201
  minLength: 17,
199
202
  maxLength: 17,
200
- contentEncoding: StringContentEncodingEnum_1.StringContentEncodingEnum.UTF8,
203
+ contentEncoding: StringContentEncodingEnum_1.StringContentEncodingEnum.MAC,
201
204
  decode: () => {
202
205
  const macAddrBuffer = Buffer.alloc(6, this.readBytes(18, 6));
203
206
  this.instance.target.mac.setValue(Array.from(macAddrBuffer).map((value) => (0, NumberToHex_1.UInt8ToHex)(value)).join(':'));
204
207
  },
205
208
  encode: () => {
206
- const macStr = this.instance.target.mac.getValue();
209
+ const macStr = this.instance.target.mac.getValue('00:00:00:00:00:00', (nodePath) => this.recordError(nodePath, 'Not Found'));
207
210
  const rawMacBuffer = Buffer.from(macStr.split(':').map((value) => parseInt(value, 16)).map((value) => value ? value : 0));
208
211
  if (rawMacBuffer.length !== 6)
209
212
  this.recordError(this.instance.target.mac.getPath(), 'Invalid MAC address length');
@@ -215,13 +218,13 @@ class ARP extends BaseHeader_1.BaseHeader {
215
218
  label: 'IP address',
216
219
  minLength: 7,
217
220
  maxLength: 15,
218
- contentEncoding: StringContentEncodingEnum_1.StringContentEncodingEnum.UTF8,
221
+ contentEncoding: StringContentEncodingEnum_1.StringContentEncodingEnum.IPv4,
219
222
  decode: () => {
220
223
  const ipv4Buffer = Buffer.alloc(4, this.readBytes(24, 4));
221
224
  this.instance.target.ipv4.setValue((0, BufferToIP_1.BufferToIPv4)(ipv4Buffer));
222
225
  },
223
226
  encode: () => {
224
- const ipv4Str = this.instance.target.ipv4.getValue();
227
+ const ipv4Str = this.instance.target.ipv4.getValue('0.0.0.0', (nodePath) => this.recordError(nodePath, 'Not Found'));
225
228
  this.writeBytes(24, (0, IPToBuffer_1.IPv4ToBuffer)(ipv4Str));
226
229
  }
227
230
  }
@@ -237,6 +240,9 @@ class ARP extends BaseHeader_1.BaseHeader {
237
240
  match() {
238
241
  if (!this.prevCodecModule)
239
242
  return false;
243
+ //The fields model the 28-octet Ethernet/IPv4 ARP packet; a shorter one is left to raw (byte-exact).
244
+ if (this.packet.length - this.startPos < 28)
245
+ return false;
240
246
  return this.prevCodecModule.instance.etherType.getValue() === (0, NumberToHex_1.UInt16ToHex)(0x0806);
241
247
  }
242
248
  }
@@ -44,6 +44,7 @@ class BACnetIP extends BaseHeader_1.BaseHeader {
44
44
  'function': this.fieldUInt('function', 1, 1, 'Function'),
45
45
  length: {
46
46
  type: 'integer',
47
+ autoCalculated: true,
47
48
  label: 'Length',
48
49
  minimum: 0,
49
50
  maximum: 65535,
@@ -45,6 +45,7 @@ class BGP extends BaseHeader_1.BaseHeader {
45
45
  marker: this.fieldHex('marker', 0, 16, 'Marker'),
46
46
  length: {
47
47
  type: 'integer',
48
+ autoCalculated: true,
48
49
  label: 'Length',
49
50
  minimum: 19,
50
51
  maximum: 65535,
@@ -70,6 +70,7 @@ class Babel extends BaseHeader_1.BaseHeader {
70
70
  //correct even though it encodes before the `tlvs` field writes them.
71
71
  bodyLength: {
72
72
  type: 'integer',
73
+ autoCalculated: true,
73
74
  label: 'Body Length',
74
75
  minimum: 0,
75
76
  maximum: 65535,
@@ -119,7 +120,7 @@ class Babel extends BaseHeader_1.BaseHeader {
119
120
  label: 'TLV',
120
121
  properties: {
121
122
  type: { type: 'integer', label: 'Type', minimum: 0, maximum: 255 },
122
- length: { type: 'integer', label: 'Length', minimum: 0, maximum: 255 },
123
+ length: { type: 'integer', label: 'Length', autoCalculated: true, minimum: 0, maximum: 255 },
123
124
  value: { type: 'string', label: 'Value', contentEncoding: StringContentEncodingEnum_1.StringContentEncodingEnum.HEX }
124
125
  }
125
126
  },
@@ -1,4 +1,5 @@
1
1
  import { BaseHeader } from '../abstracts/BaseHeader';
2
+ import { HeuristicParent } from '../types/LayerGraph';
2
3
  import { ProtocolJSONSchema } from '../schema/ProtocolJSONSchema';
3
4
  import { DemuxProducer } from '../types/DemuxProducer';
4
5
  /**
@@ -22,6 +23,7 @@ export declare class BitTorrent extends BaseHeader {
22
23
  readonly name: string;
23
24
  readonly nickname: string;
24
25
  readonly matchKeys: string[];
26
+ readonly heuristicParents: HeuristicParent[];
25
27
  readonly heuristicFallback: boolean;
26
28
  match(): boolean;
27
29
  readonly demuxProducers: DemuxProducer[];