@netkitty/codec 2.0.0 → 2.1.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 (87) hide show
  1. package/CHANGELOG.md +136 -0
  2. package/README.md +10 -6
  3. package/README.zh-CN.md +9 -6
  4. package/dist/Codec.js +4 -1
  5. package/dist/abstracts/BaseHeader.d.ts +26 -0
  6. package/dist/abstracts/BaseHeader.js +53 -0
  7. package/dist/headers/AH.js +3 -2
  8. package/dist/headers/BFD.d.ts +2 -1
  9. package/dist/headers/BFD.js +30 -4
  10. package/dist/headers/BGP.js +5 -1
  11. package/dist/headers/C37118.d.ts +3 -2
  12. package/dist/headers/C37118.js +34 -15
  13. package/dist/headers/CDP.d.ts +3 -3
  14. package/dist/headers/CDP.js +46 -10
  15. package/dist/headers/CMS.js +25 -10
  16. package/dist/headers/COTP.js +2 -3
  17. package/dist/headers/CoAP.js +20 -2
  18. package/dist/headers/DCCP.d.ts +3 -2
  19. package/dist/headers/DCCP.js +60 -8
  20. package/dist/headers/DNP3.d.ts +5 -3
  21. package/dist/headers/DNP3.js +62 -7
  22. package/dist/headers/EIGRP.d.ts +3 -2
  23. package/dist/headers/EIGRP.js +31 -5
  24. package/dist/headers/EthernetII.js +1 -0
  25. package/dist/headers/GELF.js +1 -0
  26. package/dist/headers/GENEVE.js +1 -0
  27. package/dist/headers/GRE.js +1 -0
  28. package/dist/headers/GTPv2C.js +1 -0
  29. package/dist/headers/Goose.js +4 -4
  30. package/dist/headers/HSR.js +1 -0
  31. package/dist/headers/HTTP2.js +1 -0
  32. package/dist/headers/ICMP.js +2 -1
  33. package/dist/headers/ICMPv6.js +10 -16
  34. package/dist/headers/IEC104_I_Frame.js +189 -160
  35. package/dist/headers/IEC104_S_Frame.js +19 -1
  36. package/dist/headers/IEC104_U_Frame.js +19 -1
  37. package/dist/headers/IEC61850SampledValues.js +4 -4
  38. package/dist/headers/IGMP.d.ts +8 -7
  39. package/dist/headers/IGMP.js +57 -19
  40. package/dist/headers/IPFIX.js +1 -1
  41. package/dist/headers/IPv4.js +26 -23
  42. package/dist/headers/IPv6.js +4 -1
  43. package/dist/headers/IPv6HopByHopOptions.js +3 -1
  44. package/dist/headers/ISAKMP.js +1 -0
  45. package/dist/headers/Kerberos.js +1 -0
  46. package/dist/headers/L2TP.js +1 -0
  47. package/dist/headers/LDAP.js +1 -1
  48. package/dist/headers/LLC.js +1 -0
  49. package/dist/headers/NHRP.d.ts +1 -1
  50. package/dist/headers/NHRP.js +29 -4
  51. package/dist/headers/OSPF.d.ts +3 -3
  52. package/dist/headers/OSPF.js +72 -7
  53. package/dist/headers/PIM.d.ts +3 -3
  54. package/dist/headers/PIM.js +55 -6
  55. package/dist/headers/PPPoEDiscovery.js +2 -0
  56. package/dist/headers/PTP.js +5 -1
  57. package/dist/headers/RDP.js +2 -0
  58. package/dist/headers/RGoose.js +2 -0
  59. package/dist/headers/RSVP.d.ts +3 -3
  60. package/dist/headers/RSVP.js +56 -42
  61. package/dist/headers/RTCP.js +1 -0
  62. package/dist/headers/SCTP.d.ts +2 -2
  63. package/dist/headers/SCTP.js +29 -5
  64. package/dist/headers/SNAP.js +2 -2
  65. package/dist/headers/SNMP.js +2 -2
  66. package/dist/headers/STUN.js +1 -1
  67. package/dist/headers/SercosIII.d.ts +3 -2
  68. package/dist/headers/SercosIII.js +41 -5
  69. package/dist/headers/TCP.js +13 -58
  70. package/dist/headers/TLS_Alert.js +20 -2
  71. package/dist/headers/TLS_ApplicationData.d.ts +3 -3
  72. package/dist/headers/TLS_ApplicationData.js +25 -6
  73. package/dist/headers/TLS_ChangeCipherSpec.d.ts +2 -2
  74. package/dist/headers/TLS_ChangeCipherSpec.js +24 -4
  75. package/dist/headers/TLS_Handshake.js +39 -6
  76. package/dist/headers/TLS_Heartbeat.d.ts +4 -3
  77. package/dist/headers/TLS_Heartbeat.js +40 -7
  78. package/dist/headers/TPKT.js +1 -1
  79. package/dist/headers/UDP.js +17 -61
  80. package/dist/headers/VLAN_802dot1Q.js +1 -0
  81. package/dist/headers/VRRP.d.ts +2 -1
  82. package/dist/headers/VRRP.js +45 -9
  83. package/dist/helper/Checksum.d.ts +15 -0
  84. package/dist/helper/Checksum.js +56 -0
  85. package/dist/helper/Crc.d.ts +18 -0
  86. package/dist/helper/Crc.js +58 -0
  87. package/package.json +2 -2
package/CHANGELOG.md CHANGED
@@ -3,6 +3,142 @@
3
3
  All notable changes to this project will be documented in this file.
4
4
  See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
5
5
 
6
+ # [2.1.0](https://github.com/myq1991/netkitty/compare/@netkitty/codec@2.0.0...@netkitty/codec@2.1.0) (2026-11-26)
7
+
8
+
9
+ ### Bug Fixes
10
+
11
+ * **codec:** annotate inferred and computed fields, declare constant fallbacks as defaults ([c7953e3](https://github.com/myq1991/netkitty/commit/c7953e3fac0ac8fa687872d044b2cd81e624ab74))
12
+ * **codec:** build the IGMPv3 query from its own fields and compute the IGMP checksum ([07bc9a7](https://github.com/myq1991/netkitty/commit/07bc9a75581fe0269ee77051de22a8d206c71bea))
13
+ * **codec:** compute auto fields only when left out, and find the IP layer for pseudo-headers ([f3b2571](https://github.com/myq1991/netkitty/commit/f3b25717506353ed47f9178dbbf760924409e88e))
14
+ * **codec:** compute PIM, EIGRP, NHRP, VRRP and OSPF checksums when left out ([5d82eda](https://github.com/myq1991/netkitty/commit/5d82eda00616f9b4abe105c2051c5248f4382a8e))
15
+ * **codec:** compute RSVP and CDP checksums, write their explicit lengths as given ([3f0c6fa](https://github.com/myq1991/netkitty/commit/3f0c6faa7a609d00a503331f2da76906bcfd0fe5))
16
+ * **codec:** compute the BFD, CMS, CoAP and IEC 104 lengths when left out ([59be323](https://github.com/myq1991/netkitty/commit/59be32306a0d40e21e7162ef5c9105603230fd4c))
17
+ * **codec:** compute the SCTP CRC32c and the DCCP checksum when left out ([58311cb](https://github.com/myq1991/netkitty/commit/58311cbfb951786e87fa2e218fce39074786ed5d))
18
+ * **codec:** compute the Sercos III, DNP3 and C37.118 checks when left out ([a73343b](https://github.com/myq1991/netkitty/commit/a73343b68a4e6db4bba0aab3bbb72cfe8ab51824))
19
+ * **codec:** compute TLS record lengths when left out ([2183575](https://github.com/myq1991/netkitty/commit/21835752dc1140808dc9f0e1b1a5c74d60b5ca11))
20
+ * **codec:** leave the IPv4 pseudo-header out of the VRRP v3 checksum (RFC 9568) ([3a0487e](https://github.com/myq1991/netkitty/commit/3a0487e64fa54cb4284cd4c87d3d2dc0ac50b990))
21
+ * **codec:** let every decoded IEC 104 I-frame tree pass encode validation ([abac0b8](https://github.com/myq1991/netkitty/commit/abac0b886971274d531c3b2e83c285282d8770d2))
22
+ * **codec:** zero-fill a DCCP header up to the Data Offset computed for it ([a521722](https://github.com/myq1991/netkitty/commit/a521722ab35c654935a4f58962ddb71f76ee01e7))
23
+
24
+
25
+ ### Upgrade note
26
+
27
+ Encode now computes a length, count or checksum only when the field is left out: a caller that passes
28
+ `0` to mean "compute it" (as `ipv4.checksum: 0` / `udp.length: 0` used to allow) must leave the field
29
+ out instead. Read "Behaviour changes" below before upgrading.
30
+
31
+ ### Behaviour changes (check before upgrading)
32
+
33
+ #### An explicit value is never recomputed
34
+ - An `autoCalculated` field is computed only when it is **left out** of the input. Any value you give,
35
+ **0 included**, is written as given. Before, many fields treated 0 as "compute": `ipv4.hdrLen` /
36
+ `length` / `checksum`, `ipv6.plen`, `ipv6-hopopt.len`, `tcp.hdrLen` / `checksum`, `udp.length` /
37
+ `checksum`, `icmp.checksum`, `icmpv6.checksum`, `ah.payloadLen`, `tpkt.length`, `cotp.li`,
38
+ `stun.messageLength`, `ipfix.length`, `goose.length`, `sv.length`. Code that passes `0` to mean
39
+ "calculate it" now sends 0; leave the field out instead.
40
+ - On an integer field, `null` is coerced to 0 (so it counts as a given 0) and `''` fails validation. On
41
+ a hex string field, `''` and `null` count as left out.
42
+ - A captured UDP datagram with checksum 0 ("no checksum", RFC 768) now re-encodes to its own bytes
43
+ (it used to get a computed checksum).
44
+ - `bgp.length` minimum 19 → 0 and `ptp.messageLength` minimum 34 → 0: a shorter value is written as given
45
+ with a warning (`Length should be at least 19` / `Message length should be at least 34`) instead of
46
+ failing validation.
47
+
48
+ #### encode() no longer changes its input
49
+ - `encode()` validates a deep copy (`structuredClone`, Node.js 17+) of each input, so Ajv defaults
50
+ (`tpkt.version`, `cotp.pduType`, …) and type coercion (`'102'` → `102`) no longer appear in the objects
51
+ you passed. Code that read defaults back from its own input after encoding must read the decoded
52
+ result instead.
53
+
54
+ #### Checksums over the right IP layer
55
+ - TCP, UDP and ICMPv6 take their pseudo-header from the nearest IPv4/IPv6 layer beneath, so a checksum
56
+ behind AH or an IPv6 extension header is now correct (it was 0 behind AH). With no IP layer beneath, a
57
+ warning is recorded (`Cannot compute … checksum: no IP layer beneath …`). ICMPv6 inside an
58
+ IPv6-in-IPv6 tunnel now uses the inner header.
59
+
60
+ #### Newly computed fields (when left out; all now `autoCalculated`)
61
+ Before, each of these was written as 0 when left out.
62
+ - Internet checksums: `igmp.checksum` (the IGMP message), `pim.checksum` (whole message; a Register
63
+ covers its first 8 bytes; over IPv6 with the pseudo-header, next header 103), `eigrp.checksum`,
64
+ `rsvp.checksum`, `nhrp.checksum`, `vrrp.checksum` (v2 and v3 over IPv4 over the message, RFC 9568;
65
+ v3 over IPv6 with the pseudo-header, protocol 112), `ospf.checksum` (OSPFv2: the packet without the
66
+ 64-bit authentication field; 0 for cryptographic authentication, RFC 2328 D.4.3), `dccp.checksum`
67
+ (pseudo-header protocol 33, header, and the data CsCov selects), `cdp.checksum` (the Internet checksum
68
+ as Cisco computes it for an odd length, matching Wireshark).
69
+ - CRCs: `sctp.checksum` (CRC32c over the packet, least significant byte first), `sercos3.crc32`
70
+ (CRC-32 over the Ethernet header and Sercos bytes 0–1, little-endian; needs an Ethernet layer
71
+ directly beneath, else 0 with an error), `dnp3.headerCrc` (CRC-16/DNP over octets 0–7),
72
+ `c37118.chk` (CRC-16/CCITT-FALSE over the frame before CHK).
73
+ - Lengths: `ospf.packetLength`, `bfd.length` (24 + authentication section), `cms.frameLength` (bytes
74
+ after the 4-byte header), `dnp3.length` (5 + user-data octets, excluding block CRCs), `coap.tokenLength`,
75
+ `length` of tls-alert / tls-appdata / tls-ccsp / tls-handshake / tls-heartbeat (this record only),
76
+ `tls-handshake.handshakeLength`, `tls-heartbeat.payloadLength`, `apduLength` of IEC 104 I, S and U
77
+ frames.
78
+ - `c37118.framesize` left out now counts the 2-byte CHK when CHK is also left out (it added 0).
79
+
80
+ #### Other encode changes in these protocols
81
+ - IGMPv3 Query: its body is emitted from its own fields (type 0x11 with any of `resvSQRV`,
82
+ `qqic`, `numSources`, `sources` given), not from the IP Total Length, so a left-out `ipv4.length` no
83
+ longer drops the sources. A type 0x11 message with no v3 field is an 8-byte v2 query, whatever the IP
84
+ length says.
85
+ - `rsvp.length` is written as given (below 8 is flagged; it used to be raised to 8); left out it is
86
+ the bytes actually written, not the sum of the object lengths. `rsvp.objects[].length` and
87
+ `cdp.tlvs[].length` given as 0 are written as 0 (they were recomputed).
88
+ - DCCP with `dataOffset` left out: the header is zero-filled up to the computed Data Offset (a crafted
89
+ header that was not a multiple of 4 octets grows to the next one).
90
+ - IEC 104 I-frame with `apduLength` left out: information objects are spaced by the size of the first
91
+ object written (they were spaced by the given APDU length).
92
+ - A left-out TLS `appData` or heartbeat `payloadMessage` writes nothing (it wrote one 0x00 octet).
93
+ - Layers built from empty data (plus the discriminator `allowedNextLayers` gives) now re-decode as
94
+ themselves: dnp3, coap, c37118, every tls-* record, IEC 104 I and S frames.
95
+
96
+ #### Schema representation (`CODEC_SCHEMAS`)
97
+ - `autoCalculated: true` added to the demux fields encode infers from the next layer
98
+ (`eth` / `vlan` / `hsr` / `snap` `etherType`, `gre` / `geneve` `protocolType`, `ipv4.protocol`,
99
+ `ipv6.nxt`, `ipv6-hopopt.nxt`, `ah.nxt`), to `snap.oui` (derived from `ouiProtocol`) and to
100
+ `rdp.length` (always 8 for the Negotiation structure).
101
+ - `default` added where encode already fell back to a protocol constant, so editors can show it:
102
+ `ipv4.version` 4, `ipv6.version` 6, `ipv4.flags.df` 1, `gelf.magic` `'1e0f'`, `http2.preface` (the
103
+ connection preface), `llc.control` `'03'`, `gtpv2.flags.version` 2, `isakmp.version.major` 2,
104
+ `l2tp.flags.version` 2, `pppoe-disc.type` 1 / `version` 1, `r-session.commonHeaderId` 0x80 /
105
+ `version` 1, `rtcp.version` 2, `kerberos.msgType` 0x6a, `ldap.protocolOpTag` 0x60, `snmp.pduType`
106
+ 0xa0, `snmp.variableBindings[].valueType` 0x05, `pim.version` 2, `rsvp.version` 1, `vrrp.version` 2 /
107
+ `type` 1 / `adverInt` 1, `bfd.version` 1, `c37118.sync.version` 1, `cms.protocolType` 1. Encoded
108
+ bytes are unchanged; a field filled from its default is no longer reported as `'Not Found'`.
109
+ - Protocol signatures now have a `default`, so a layer built from empty data is recognised again:
110
+ `dnp3.start` `'0564'`, `c37118.leadIn` `'aa'`, `coap.version` 1, the TLS records' `contentType`
111
+ (21 alert, 23 appdata, 20 ccsp, 22 handshake, 24 heartbeat) and `version` `'TLS1.2'`,
112
+ `tls-ccsp.change_cipher_spec_message` `'01'`, `startByte` 104 on IEC 104 I / S / U frames.
113
+
114
+ #### IEC 104 I-frame item schemas (decoded trees now always pass encode validation)
115
+ - Item variants that disagreed with what decode fills are corrected: type 40 (M_EP_TF_1) no longer
116
+ requires SIE/SIF (type 39's fields); type 38 (M_EP_TD_1) uses `Milliseconds_16` / `Milliseconds_56`
117
+ instead of `Milliseconds`; type 70 (M_EI_NA_1) uses `COI_R` / `COI_I` instead of `COI` / `LPC`; type 101
118
+ (C_CI_NA_1) uses `RQT` instead of `RQI`. Inputs written against the old names fail validation.
119
+ - Time fields of the 21 time-tagged variants accept their full wire range (milliseconds 0–65535, minutes
120
+ 0–63, hours 0–31, day 0–31, month 0–15, year 0–127); a captured out-of-calendar time (day or month 0)
121
+ re-encodes instead of throwing.
122
+
123
+ ### Additions
124
+ - `BaseHeader` (for custom codecs): protected `isLeftOut(field)` (the left-out test every computed field
125
+ uses), `nearestIPModule()` and `ipPseudoHeader(protocol, upperLayerLength)`.
126
+
127
+ ### Known limitations
128
+ - Not computed: OSPFv3 checksums, the DNP3 per-block data CRCs (kept verbatim in `payload`), IEC 104
129
+ `numberOfObject` (not derived from the item count). tls-handshake still writes its 6-byte hello
130
+ skeleton when `messagedata` is left out. A tcp → IEC 104 U-frame built from empty data does not
131
+ re-decode as a U-frame.
132
+ - IPv4 does not bound its payload by Total Length, and Ethernet padding after an 802.3 / LLC payload
133
+ decodes as a trailing layer; a left-out length or checksum then counts the padding.
134
+ - Where a given length positions what follows (QUIC connection IDs, S7comm parameter/data, Diameter AVPs,
135
+ AMQP frame end, …), an explicit length that disagrees with the data reshapes the packet the way decode
136
+ would read it.
137
+
138
+
139
+
140
+
141
+
6
142
  # [2.0.0](https://github.com/myq1991/netkitty/compare/@netkitty/codec@1.2.1...@netkitty/codec@2.0.0) (2026-11-26)
7
143
 
8
144
 
package/README.md CHANGED
@@ -61,9 +61,13 @@ rebuilt.equals(packet) // true for a well-formed packet — decode/encode roun
61
61
 
62
62
  Build a packet from scratch by handing `encode` an array of `{id, data}` inputs in outer-to-inner
63
63
  order; any field you omit is filled from the schema's defaults, and form-string values are coerced.
64
- A parent's demux field you leave out — an EtherType (`eth`/`vlan`/`hsr`/`gre`/`geneve`/`snap`), the
65
- IPv4 `protocol`, the IPv6 `nxt` — is filled from the layer that follows (eth before LLC gets the IEEE
66
- 802.3 length instead); a value you do supply is always written as given:
64
+ Lengths, counts and checksums you leave out are computed, and a parent's demux field you leave out — an
65
+ EtherType (`eth`/`vlan`/`hsr`/`gre`/`geneve`/`snap`), the IPv4 `protocol`, the IPv6 `nxt` — is filled
66
+ from the layer that follows (eth before LLC gets the IEEE 802.3 length instead). A value you do supply,
67
+ 0 included, is always written as given, so a wrong checksum or length can be crafted on purpose. Leave a
68
+ field out to have it computed: on an integer field `null` is coerced to 0 (and written as 0) and `''`
69
+ fails validation, while on a hex field `''` and `null` count as left out. `encode` works on copies: the
70
+ input objects you pass are never changed.
67
71
 
68
72
  ```ts
69
73
  const {packet} = await codec.encode([
@@ -127,9 +131,9 @@ declaration plays four parts at once:
127
131
  projections such as HTTP `method`/`statusCode` or CMS `serviceDataDecoded`, decoded from a
128
132
  verbatim field that is the real encode authority; also values encode always derives itself). On an
129
133
  object/array it covers every descendant.
130
- - `autoCalculated: true` — encode computes the value (length, checksum, count, offset…) from the
131
- rest of the packet when it is left out (or 0 where that is the field's convention); an explicit
132
- value is still written as given. E.g. `ipv4.length`, `ipv4.checksum`, `tcp.hdrLen`.
134
+ - `autoCalculated: true` — encode computes the value (length, checksum, count, offset, or the demux
135
+ field inferred from the next layer) when it is left out; any value given, 0 included, is written
136
+ as given. E.g. `ipv4.length`, `ipv4.checksum`, `tcp.hdrLen`, `ipv4.protocol`.
133
137
  - `byteAlignment: N` — encode zero-pads the field to a multiple of N bytes, e.g. `ipv4.options`
134
138
  (4) and `tcp.options` (4).
135
139
 
package/README.zh-CN.md CHANGED
@@ -58,9 +58,12 @@ rebuilt.equals(packet) // 对于结构完好的报文为 true —— 解码/
58
58
  ```
59
59
 
60
60
  想从零构造一个报文,只要按从外到内的顺序给 `encode` 传一组 `{id, data}` 输入即可;没填的字段会用
61
- schema 里的默认值补齐,表单传来的字符串也会被自动转换成对应类型。上一层用来区分下一层的字段如果没填
62
- (`eth`/`vlan`/`hsr`/`gre`/`geneve`/`snap` 的 EtherType、IPv4 的 `protocol`、IPv6 的 `nxt`),会按
63
- 后面那一层自动填写(eth 后面接 LLC 时填 IEEE 802.3 长度);显式填写的值总是原样写出:
61
+ schema 里的默认值补齐,表单传来的字符串也会被自动转换成对应类型。没填的长度、计数和校验和会自动计算;
62
+ 上一层用来区分下一层的字段如果没填(`eth`/`vlan`/`hsr`/`gre`/`geneve`/`snap` 的 EtherType、IPv4 的
63
+ `protocol`、IPv6 的 `nxt`),会按后面那一层自动填写(eth 后面接 LLC 时填 IEEE 802.3 长度)。显式填写的值
64
+ (包括 0)总是原样写出,所以可以有意构造错误的校验和或长度。想让某个字段自动计算,就不要传它:整数字段传
65
+ `null` 会被转换成 0 并照写,传 `''` 会校验失败;十六进制字段传 `''` 或 `null` 则等同于不填。`encode` 在
66
+ 副本上工作,不会修改传入的对象:
64
67
 
65
68
  ```ts
66
69
  const {packet} = await codec.encode([
@@ -122,9 +125,9 @@ type CodecErrorInfo = {
122
125
  - `readOnly: true`——encode 忽略该值,修改它永远不会改变编码字节(例如 HTTP `method`/`statusCode`、
123
126
  CMS `serviceDataDecoded` 这类从逐字节保留的字段解出、仅供展示的投影——真正的编码依据是那个逐字节
124
127
  字段;以及 encode 总是自行推导的值)。标在对象/数组上时覆盖其全部子孙字段。
125
- - `autoCalculated: true`——输入缺省该字段(或按该字段约定给 0)时,encode 会根据报文其余部分自动
126
- 计算(长度、校验和、计数、偏移等);显式给出的值仍按原样写入。例如 `ipv4.length`、`ipv4.checksum`、
127
- `tcp.hdrLen`。
128
+ - `autoCalculated: true`——输入缺省该字段时,encode 会自动计算(长度、校验和、计数、偏移,或按下一层
129
+ 推断的分发字段);给出的任何值(包括 0)都按原样写入。例如 `ipv4.length`、`ipv4.checksum`、
130
+ `tcp.hdrLen`、`ipv4.protocol`。
128
131
  - `byteAlignment: N`——encode 会用 0 把该字段补齐到 N 字节的整数倍,例如 `ipv4.options`(4)、
129
132
  `tcp.options`(4)。
130
133
 
package/dist/Codec.js CHANGED
@@ -362,7 +362,10 @@ class Codec {
362
362
  const codecModule = codecModuleConstructor.CREATE_INSTANCE(codecData, codecModules);
363
363
  let validated;
364
364
  try {
365
- validated = codecModule.validate(input.data);
365
+ //Ajv fills schema defaults into, and coerces types in, the object it validates. Work on
366
+ //a deep copy so the caller's input is never changed (re-encoding it later must not
367
+ //replay those defaults as explicit values).
368
+ validated = codecModule.validate(structuredClone(input.data));
366
369
  }
367
370
  catch (e) {
368
371
  //Name the input layer by position too, so a caller can bind the error to its form.
@@ -295,6 +295,32 @@ export declare abstract class BaseHeader {
295
295
  * @protected
296
296
  */
297
297
  protected encodeOmittedEtherType(field: FlexibleObject, offset: number): void;
298
+ /**
299
+ * True when `field` was left out of the encode input, which is what asks encode to calculate an
300
+ * autoCalculated length, count or checksum. Any value given, 0 included, is written as given, so a
301
+ * deliberately wrong value can still be crafted. An empty string counts as left out (a hex field
302
+ * has no bytes to write then). Read it at the top of the field's encode closure, before the closure
303
+ * writes a placeholder into the same node.
304
+ * @param field
305
+ * @protected
306
+ */
307
+ protected isLeftOut(field: FlexibleObject): boolean;
308
+ /**
309
+ * The nearest IPv4 or IPv6 layer beneath this one, skipping whatever sits in between (AH, IPv6
310
+ * extension headers, …); undefined when there is none.
311
+ * @protected
312
+ */
313
+ protected nearestIPModule(): CodecModule | undefined;
314
+ /**
315
+ * The pseudo-header an upper-layer checksum covers, built from the nearest IP layer beneath: for
316
+ * IPv4 source, destination, zero, protocol and the 16-bit upper-layer length (RFC 768 / 793); for
317
+ * IPv6 source, destination, the 32-bit length, three zero octets and the next header (RFC 8200
318
+ * section 8.1). undefined when no IP layer is beneath or its addresses are unusable.
319
+ * @param protocol the upper-layer protocol number (6 TCP, 17 UDP, …)
320
+ * @param upperLayerLength byte count the checksum covers above the pseudo-header
321
+ * @protected
322
+ */
323
+ protected ipPseudoHeader(protocol: number, upperLayerLength: number): Buffer | undefined;
298
324
  /**
299
325
  * Record encode/decode error
300
326
  * @param path
@@ -606,6 +606,59 @@ class BaseHeader {
606
606
  this.writeBytes(offset, (0, NumberToBuffer_1.UInt16ToBuffer)(Math.min(length, 0xffff)));
607
607
  });
608
608
  }
609
+ /**
610
+ * True when `field` was left out of the encode input, which is what asks encode to calculate an
611
+ * autoCalculated length, count or checksum. Any value given, 0 included, is written as given, so a
612
+ * deliberately wrong value can still be crafted. An empty string counts as left out (a hex field
613
+ * has no bytes to write then). Read it at the top of the field's encode closure, before the closure
614
+ * writes a placeholder into the same node.
615
+ * @param field
616
+ * @protected
617
+ */
618
+ isLeftOut(field) {
619
+ const value = field.getValue();
620
+ return value === undefined || value === null || value === '';
621
+ }
622
+ /**
623
+ * The nearest IPv4 or IPv6 layer beneath this one, skipping whatever sits in between (AH, IPv6
624
+ * extension headers, …); undefined when there is none.
625
+ * @protected
626
+ */
627
+ nearestIPModule() {
628
+ for (let i = this.prevCodecModules.length - 1; i >= 0; i--) {
629
+ const id = this.prevCodecModules[i].id;
630
+ if (id === 'ipv4' || id === 'ipv6')
631
+ return this.prevCodecModules[i];
632
+ }
633
+ return undefined;
634
+ }
635
+ /**
636
+ * The pseudo-header an upper-layer checksum covers, built from the nearest IP layer beneath: for
637
+ * IPv4 source, destination, zero, protocol and the 16-bit upper-layer length (RFC 768 / 793); for
638
+ * IPv6 source, destination, the 32-bit length, three zero octets and the next header (RFC 8200
639
+ * section 8.1). undefined when no IP layer is beneath or its addresses are unusable.
640
+ * @param protocol the upper-layer protocol number (6 TCP, 17 UDP, …)
641
+ * @param upperLayerLength byte count the checksum covers above the pseudo-header
642
+ * @protected
643
+ */
644
+ ipPseudoHeader(protocol, upperLayerLength) {
645
+ const ip = this.nearestIPModule();
646
+ if (!ip)
647
+ return undefined;
648
+ const sourceIp = ip.instance.sip.getValue();
649
+ const destinationIp = ip.instance.dip.getValue();
650
+ if (typeof sourceIp !== 'string' || typeof destinationIp !== 'string')
651
+ return undefined;
652
+ try {
653
+ if (ip.id === 'ipv4') {
654
+ return Buffer.concat([(0, IPToBuffer_1.IPv4ToBuffer)(sourceIp), (0, IPToBuffer_1.IPv4ToBuffer)(destinationIp), (0, NumberToBuffer_1.UInt8ToBuffer)(0), (0, NumberToBuffer_1.UInt8ToBuffer)(protocol), (0, NumberToBuffer_1.UInt16ToBuffer)(upperLayerLength)]);
655
+ }
656
+ return Buffer.concat([(0, IPToBuffer_1.IPv6ToBuffer)(sourceIp), (0, IPToBuffer_1.IPv6ToBuffer)(destinationIp), (0, NumberToBuffer_1.UInt32ToBuffer)(upperLayerLength), Buffer.alloc(3, 0), (0, NumberToBuffer_1.UInt8ToBuffer)(protocol)]);
657
+ }
658
+ catch (e) {
659
+ return undefined;
660
+ }
661
+ }
609
662
  /**
610
663
  * Dotted path of the index-th field codec in the same walk order getFieldCodecs uses. Cold path only
611
664
  * (a field closure threw): rebuilds the path list on demand so the hot loop carries no per-field
@@ -69,7 +69,7 @@ class AH extends BaseHeader_1.BaseHeader {
69
69
  //Next Header is an IP-protocol number (the type of the protected payload); stored as
70
70
  //`nxt` — the field name IPv6 extension headers use — so the `ipproto` demux routes the
71
71
  //inner layer and TCP/UDP's `nxt`-aware match() accepts AH as a parent.
72
- nxt: this.fieldUInt('nxt', 0, 1, 'Next Header'),
72
+ nxt: { ...this.fieldUInt('nxt', 0, 1, 'Next Header'), autoCalculated: true },
73
73
  //AH total length in 4-octet words minus 2. Honored-else-derived: a supplied value is
74
74
  //kept verbatim, an absent (0) one is recomputed from the encoded ICV length.
75
75
  payloadLen: {
@@ -82,10 +82,11 @@ class AH extends BaseHeader_1.BaseHeader {
82
82
  this.instance.payloadLen.setValue((0, BufferToNumber_1.BufferToUInt8)(this.readBytes(1, 1)));
83
83
  },
84
84
  encode: function () {
85
+ const leftOut = this.isLeftOut(this.instance.payloadLen);
85
86
  const payloadLen = this.instance.payloadLen.getValue(0);
86
87
  this.instance.payloadLen.setValue(payloadLen);
87
88
  this.writeBytes(1, (0, NumberToBuffer_1.UInt8ToBuffer)(payloadLen));
88
- if (!payloadLen) {
89
+ if (leftOut) {
89
90
  this.addPostSelfEncodeHandler(() => {
90
91
  //Fixed prefix is 12 octets (3 words); total = 12 + ICV octets, and
91
92
  //Payload Len = totalWords - 2 = (12 + icvBytes)/4 - 2 = icvBytes/4 + 1.
@@ -13,7 +13,8 @@ import { DemuxProducer } from '../types/DemuxProducer';
13
13
  * If the A (Authentication Present) flag is set an optional Authentication Section follows the
14
14
  * mandatory 24 bytes (Auth Type, Auth Len, then type-specific auth data). It is kept verbatim as
15
15
  * `authSection` hex so any auth variant round-trips byte-for-byte; when A is clear it is empty. The
16
- * Length field is honoured verbatim (not recomputed) so a captured packet re-encodes byte-for-byte.
16
+ * Length field is written as given (so a captured packet re-encodes byte-for-byte); left out, it is the
17
+ * 24 mandatory bytes plus the authentication section.
17
18
  * BFD Control is a leaf — nothing rides on top of it.
18
19
  */
19
20
  export declare class BFD extends BaseHeader {
@@ -5,6 +5,8 @@ const BaseHeader_1 = require("../abstracts/BaseHeader");
5
5
  const BufferToHex_1 = require("../helper/BufferToHex");
6
6
  const HexToBuffer_1 = require("../helper/HexToBuffer");
7
7
  const StringContentEncodingEnum_1 = require("../lib/StringContentEncodingEnum");
8
+ const BufferToNumber_1 = require("../helper/BufferToNumber");
9
+ const NumberToBuffer_1 = require("../helper/NumberToBuffer");
8
10
  /**
9
11
  * BFD — Bidirectional Forwarding Detection Control (RFC 5880), UDP port 3784 (single-hop) and 4784
10
12
  * (multi-hop). The mandatory section is 24 bytes: a first byte carrying Version[3] (= 1) and a 5-bit
@@ -17,7 +19,8 @@ const StringContentEncodingEnum_1 = require("../lib/StringContentEncodingEnum");
17
19
  * If the A (Authentication Present) flag is set an optional Authentication Section follows the
18
20
  * mandatory 24 bytes (Auth Type, Auth Len, then type-specific auth data). It is kept verbatim as
19
21
  * `authSection` hex so any auth variant round-trips byte-for-byte; when A is clear it is empty. The
20
- * Length field is honoured verbatim (not recomputed) so a captured packet re-encodes byte-for-byte.
22
+ * Length field is written as given (so a captured packet re-encodes byte-for-byte); left out, it is the
23
+ * 24 mandatory bytes plus the authentication section.
21
24
  * BFD Control is a leaf — nothing rides on top of it.
22
25
  */
23
26
  class BFD extends BaseHeader_1.BaseHeader {
@@ -70,11 +73,13 @@ class BFD extends BaseHeader_1.BaseHeader {
70
73
  properties: {
71
74
  //Byte 0: Version (top 3 bits, = 1 for RFC 5880) + Diagnostic (low 5 bits). MSB-first,
72
75
  //so version is bitOffset 0..2 and diagnostic bitOffset 3..7 of a 1-octet window.
76
+ //Default 1: the RFC 5880 version, which encode writes when it is left out.
73
77
  version: {
74
78
  type: 'integer',
75
79
  label: 'Version',
76
80
  minimum: 0,
77
81
  maximum: 7,
82
+ default: 1,
78
83
  decode: function () { this.instance.version.setValue(this.readBits(0, 1, 0, 3)); },
79
84
  encode: function () { this.writeBits(0, 1, 0, 3, this.instance.version.getValue(1)); }
80
85
  },
@@ -108,9 +113,30 @@ class BFD extends BaseHeader_1.BaseHeader {
108
113
  }
109
114
  },
110
115
  detectMult: this.fieldUInt('detectMult', 2, 1, 'Detect Mult'),
111
- //Length of the entire BFD Control packet in bytes. Honoured verbatim (a real no-auth
112
- //packet carries 24) — not recomputed, so a captured packet re-encodes byte-for-byte.
113
- length: this.fieldUInt('length', 3, 1, 'Length'),
116
+ //Length of the entire BFD Control packet in bytes (a real no-auth packet carries 24).
117
+ length: {
118
+ type: 'integer',
119
+ autoCalculated: true,
120
+ label: 'Length',
121
+ minimum: 0,
122
+ maximum: 255,
123
+ decode: function () {
124
+ this.instance.length.setValue((0, BufferToNumber_1.BufferToUInt8)(this.readBytes(3, 1)));
125
+ },
126
+ encode: function () {
127
+ if (!this.isLeftOut(this.instance.length)) {
128
+ this.writeBytes(3, (0, NumberToBuffer_1.UInt8ToBuffer)(this.instance.length.getValue(0)));
129
+ return;
130
+ }
131
+ let length = 24 + (0, HexToBuffer_1.HexToBuffer)(this.instance.authSection.getValue('')).length;
132
+ if (length > 255) {
133
+ this.recordError(this.instance.length.getPath(), 'Maximum value is 255');
134
+ length = 255;
135
+ }
136
+ this.instance.length.setValue(length);
137
+ this.writeBytes(3, (0, NumberToBuffer_1.UInt8ToBuffer)(length));
138
+ }
139
+ },
114
140
  myDiscriminator: this.fieldUInt('myDiscriminator', 4, 4, 'My Discriminator'),
115
141
  yourDiscriminator: this.fieldUInt('yourDiscriminator', 8, 4, 'Your Discriminator'),
116
142
  desiredMinTxInterval: this.fieldUInt('desiredMinTxInterval', 12, 4, 'Desired Min TX Interval'),
@@ -47,7 +47,9 @@ class BGP extends BaseHeader_1.BaseHeader {
47
47
  type: 'integer',
48
48
  autoCalculated: true,
49
49
  label: 'Length',
50
- minimum: 19,
50
+ //The field floor, not the 19-byte minimum message: a given value is written as
51
+ //given (flagged when too short) so a malformed message can be crafted.
52
+ minimum: 0,
51
53
  maximum: 65535,
52
54
  decode: function () {
53
55
  this.instance.length.setValue((0, BufferToNumber_1.BufferToUInt16)(this.readBytes(16, 2)));
@@ -63,6 +65,8 @@ class BGP extends BaseHeader_1.BaseHeader {
63
65
  this.recordError(this.instance.length.getPath(), 'Maximum value is 65535');
64
66
  value = 65535;
65
67
  }
68
+ if (value < 19)
69
+ this.recordError(this.instance.length.getPath(), 'Length should be at least 19');
66
70
  this.instance.length.setValue(value);
67
71
  this.writeBytes(16, (0, NumberToBuffer_1.UInt16ToBuffer)(value));
68
72
  }
@@ -11,8 +11,9 @@ import { DemuxProducer } from '../types/DemuxProducer';
11
11
  *
12
12
  * The frame body between the header and the CHK is frame-type-specific (a configuration frame defines
13
13
  * the data layout for the data frames that follow — cross-frame state, not a single-packet concern), so
14
- * this codec keeps the body verbatim as `body` hex, bounded by FRAMESIZE, and keeps the CHK verbatim
15
- * (never recomputed). A well-formed frame round-trips byte-for-byte.
14
+ * this codec keeps the body verbatim as `body` hex, bounded by FRAMESIZE. FRAMESIZE and CHK are written
15
+ * as given; left out, FRAMESIZE is the actual frame length and CHK the CRC-CCITT (CRC-16/CCITT-FALSE:
16
+ * polynomial 0x1021, initial 0xFFFF) of every octet before it. A well-formed frame round-trips byte-for-byte.
16
17
  */
17
18
  export declare class C37118 extends BaseHeader {
18
19
  #private;
@@ -7,6 +7,7 @@ const HexToBuffer_1 = require("../helper/HexToBuffer");
7
7
  const BufferToNumber_1 = require("../helper/BufferToNumber");
8
8
  const NumberToBuffer_1 = require("../helper/NumberToBuffer");
9
9
  const StringContentEncodingEnum_1 = require("../lib/StringContentEncodingEnum");
10
+ const Crc_1 = require("../helper/Crc");
10
11
  /**
11
12
  * C37.118 — IEEE Std C37.118.2 synchrophasor data transfer (PMU/PDC), typically TCP port 4712 and UDP
12
13
  * port 4713. Every frame shares a 14-byte common header: SYNC (a 0xAA lead-in byte, then a byte holding
@@ -17,8 +18,9 @@ const StringContentEncodingEnum_1 = require("../lib/StringContentEncodingEnum");
17
18
  *
18
19
  * The frame body between the header and the CHK is frame-type-specific (a configuration frame defines
19
20
  * the data layout for the data frames that follow — cross-frame state, not a single-packet concern), so
20
- * this codec keeps the body verbatim as `body` hex, bounded by FRAMESIZE, and keeps the CHK verbatim
21
- * (never recomputed). A well-formed frame round-trips byte-for-byte.
21
+ * this codec keeps the body verbatim as `body` hex, bounded by FRAMESIZE. FRAMESIZE and CHK are written
22
+ * as given; left out, FRAMESIZE is the actual frame length and CHK the CRC-CCITT (CRC-16/CCITT-FALSE:
23
+ * polynomial 0x1021, initial 0xFFFF) of every octet before it. A well-formed frame round-trips byte-for-byte.
22
24
  */
23
25
  class C37118 extends BaseHeader_1.BaseHeader {
24
26
  constructor() {
@@ -40,7 +42,8 @@ class C37118 extends BaseHeader_1.BaseHeader {
40
42
  type: 'object',
41
43
  summary: 'C37.118 type=${sync.frameType} id=${idcode}',
42
44
  properties: {
43
- leadIn: this.fieldHex('leadIn', 0, 1, 'Lead-in (0xAA)'),
45
+ //Default 0xAA: the SYNC lead-in every frame begins with, and what match() requires.
46
+ leadIn: { ...this.fieldHex('leadIn', 0, 1, 'Lead-in (0xAA)'), default: 'aa' },
44
47
  //SYNC byte 1 (MSB first): reserved bit, 3-bit Frame Type, 4-bit Version.
45
48
  sync: {
46
49
  type: 'object',
@@ -56,8 +59,9 @@ class C37118 extends BaseHeader_1.BaseHeader {
56
59
  decode: function () { this.instance.sync.frameType.setValue(this.readBits(1, 1, 1, 3)); },
57
60
  encode: function () { this.writeBits(1, 1, 1, 3, this.instance.sync.frameType.getValue(0)); }
58
61
  },
62
+ //Default 1 (IEEE C37.118-2005), the version encode writes when it is left out.
59
63
  version: {
60
- type: 'integer', label: 'Version', minimum: 0, maximum: 15,
64
+ type: 'integer', label: 'Version', minimum: 0, maximum: 15, default: 1,
61
65
  decode: function () { this.instance.sync.version.setValue(this.readBits(1, 1, 4, 4)); },
62
66
  encode: function () { this.writeBits(1, 1, 4, 4, this.instance.sync.version.getValue(1)); }
63
67
  }
@@ -74,11 +78,20 @@ class C37118 extends BaseHeader_1.BaseHeader {
74
78
  },
75
79
  encode: function () {
76
80
  //Honored when supplied (a crafted frame may lie); else derived from the actual
77
- //body + CHK (FRAMESIZE is the total frame length: 14-byte header + body + CHK).
78
- const provided = this.instance.framesize.getValue();
79
- const value = (provided !== undefined && provided !== null)
80
- ? provided
81
- : 14 + (0, HexToBuffer_1.HexToBuffer)(this.instance.body.getValue('')).length + (0, HexToBuffer_1.HexToBuffer)(this.instance.chk.getValue('')).length;
81
+ //body + CHK (FRAMESIZE is the total frame length: 14-byte header + body + CHK, the
82
+ //CHK being 2 bytes when it is left out to be computed).
83
+ let value;
84
+ if (!this.isLeftOut(this.instance.framesize)) {
85
+ value = this.instance.framesize.getValue(0);
86
+ }
87
+ else {
88
+ const chkLength = this.isLeftOut(this.instance.chk) ? 2 : (0, HexToBuffer_1.HexToBuffer)(this.instance.chk.getValue('')).length;
89
+ value = 14 + (0, HexToBuffer_1.HexToBuffer)(this.instance.body.getValue('')).length + chkLength;
90
+ if (value > 65535) {
91
+ this.recordError(this.instance.framesize.getPath(), 'Maximum value is 65535');
92
+ value = 65535;
93
+ }
94
+ }
82
95
  this.instance.framesize.setValue(value);
83
96
  this.writeBytes(2, (0, NumberToBuffer_1.UInt16ToBuffer)(value));
84
97
  }
@@ -122,14 +135,20 @@ class C37118 extends BaseHeader_1.BaseHeader {
122
135
  const bodyBuffer = (0, HexToBuffer_1.HexToBuffer)(body);
123
136
  if (bodyBuffer.length)
124
137
  this.writeBytes(14, bodyBuffer);
125
- const chk = this.instance.chk.getValue('');
126
- if (chk)
127
- this.writeBytes(14 + bodyBuffer.length, (0, HexToBuffer_1.HexToBuffer)(chk));
138
+ const chkOffset = 14 + bodyBuffer.length;
139
+ if (!this.isLeftOut(this.instance.chk)) {
140
+ this.writeBytes(chkOffset, (0, HexToBuffer_1.HexToBuffer)(this.instance.chk.getValue('')));
141
+ return;
142
+ }
143
+ //Every octet before the CHK (header, FRAMESIZE included, and body) is written by now.
144
+ const chk = (0, NumberToBuffer_1.UInt16ToBuffer)((0, Crc_1.Crc16CcittFalse)(this.readBytes(0, chkOffset)));
145
+ this.instance.chk.setValue((0, BufferToHex_1.BufferToHex)(chk));
146
+ this.writeBytes(chkOffset, chk);
128
147
  }
129
148
  },
130
- //The check word (CRC-CCITT), honored verbatim (never recomputed) — populated by the body
131
- //master since its offset (FRAMESIZE - 2) is frame-length dependent.
132
- chk: { type: 'string', label: 'Check', contentEncoding: StringContentEncodingEnum_1.StringContentEncodingEnum.HEX }
149
+ //The check word (CRC-CCITT, big-endian) — encoded by the body master since its offset
150
+ //(FRAMESIZE - 2) is frame-length dependent; computed there when left out.
151
+ chk: { type: 'string', autoCalculated: true, label: 'Check', contentEncoding: StringContentEncodingEnum_1.StringContentEncodingEnum.HEX }
133
152
  }
134
153
  };
135
154
  }
@@ -9,9 +9,9 @@ import { DemuxProducer } from '../types/DemuxProducer';
9
9
  * Capabilities, 0x0005 Software Version, 0x0006 Platform.
10
10
  *
11
11
  * The TLV values are kept verbatim as hex (device names, address lists and capability bitmaps need no
12
- * form structure), the Checksum is honored verbatim (never recomputed), and the TLV walk is bounded by
13
- * the captured bytes so a corrupt Length can't run past the frame. A well-formed CDP frame round-trips
14
- * byte-for-byte.
12
+ * form structure), and the TLV walk is bounded by the captured bytes so a corrupt Length can't run past
13
+ * the frame. The Checksum and each TLV Length are computed on encode when left out and written as given
14
+ * otherwise. A well-formed CDP frame round-trips byte-for-byte.
15
15
  */
16
16
  export declare class CDP extends BaseHeader {
17
17
  #private;