Documentation
¶
Overview ¶
Package schc is Static Context Header Compression and fragmentation (RFC 8724) for IPv6, IPv4, UDP, SCTP, ICMPv6 and CoAP (RFC 8824, with the extended token lengths of RFC 8974), with the LoRaWAN profile of RFC 9011, the Sigfox profile of RFC 9442, the Compound ACK of RFC 9441 and rules in the RFC 9363 data model, implicit rules included.
Compression (compress.go): rules of field descriptors (FID, FL, FP, DI, TV, MO, CDA) matched as clause 7.2 says; the matching operators equal, ignore, MSB(x) and match-mapping; the actions not-sent, value-sent, mapping-sent, LSB, compute, DevIID and AppIID; variable-length residues with their 4/12/28-bit sizes. Fields are labelled by our parsers for IPv6 and UDP (clause 10, addresses and ports by Dev/App role), ICMPv6 Echo, the IEC 62056-4-7 wrapper header (fields.go) and CoAP (coap.go); compute rebuilds the IPv6 and UDP lengths, the UDP and ICMPv6 checksums and the wrapper length, and a compute or DevIID field is elided only when the other end rebuilds the same value. A rule may describe the IPv6 Traffic Class as DSCP and ECN and the CoAP code as class and detail (RFC 9363's subfield identities).
CoAP (coap.go, RFC 8824): the header fields, the token with the "tkl" length function (4.5), every option by number with the OSCORE option cut into flags, piv, kidctx and kid (6.4), and entries that group several Uri-Path or Uri-Query elements (5.3). The stack "coap" is a whole CoAP message, alone or as "ipv6/udp/coap" in one rule; the stack "coap-inner" is an OSCORE plaintext, for the inner rules of 7.2, whose encrypted result an outer rule compresses as the payload of the protected message. OSCORE protection itself is the caller's.
Fragmentation (frag.go, sender.go, receiver.go): the message formats of clause 8.3 with bitmap compression, the RCS of 8.2.3 (CRC32 by default, others through RegisterRCS, rcs.go), and the sender and receiver of No-ACK, ACK-Always and ACK-on-Error (8.4) as clock-driven state machines without I/O. With a rule's CompoundAck the ACK-on-Error receiver reports every window with missing tiles in one SCHC Compound ACK and the sender reads it (RFC 9441).
IPv4 (RFC 791, options as one field) and the SCTP common header (RFC 9260) are labelled too; compute rebuilds IHL, Total Length, the header checksum, the UDP checksum over IPv4 and the SCTP CRC32c.
Sigfox (sigfox.go, RFC 9442): the uplink No-ACK rule, the three uplink ACK-on-Error header layouts with the Compound ACK in 8-byte downlinks, and the downlink ACK-Always rule, built from profile options any rule may use (FragParams: HeaderPadded, the fragment-count RCS, FCNCountdown, FullFragments, NoAckReq, BitmapUncompressed, AckMaxBits).
LoRaWAN (lorawan.go): RuleID in the FPort, the uplink ACK-on-Error and downlink ACK-Always rules with their parameters and class timers, the multicast No-ACK rule, and the AES-CMAC IID of RFC 9011 5.3.
Rules (rule.go, yang.go): our own JSON, which every feature has, and the RFC 9363 data model in RFC 7951 JSON (ParseYANG, MarshalYANG) with the RFC 9441 augment; package coreconf carries the latter in CBOR with SIDs.
Index ¶
- Constants
- Variables
- func CoAPOptionFID(n uint32) string
- func CoAPOptionNumber(fid string) (uint32, bool)
- func LoRaWANIID(appSKey, devEUI []byte) ([]byte, error)
- func RCSAlgorithms() []string
- func RegisterRCS(a RCSAlgorithm) error
- func SigfoxDownlinkPayload(msg Bits) ([]byte, error)
- type Bits
- func (x *Bits) Append(y Bits)
- func (x *Bits) AppendBit(v uint8)
- func (x *Bits) AppendBytes(b []byte)
- func (x *Bits) AppendUint(v uint64, n int)
- func (x Bits) Bit(i int) uint8
- func (x Bits) Bytes() []byte
- func (x Bits) Clone() Bits
- func (x Bits) Equal(y Bits) bool
- func (x Bits) Len() int
- func (x *Bits) Pad(word int) int
- func (x Bits) Slice(from, to int) Bits
- func (x Bits) String() string
- func (x Bits) UintAt(from, n int) uint64
- type Context
- type Direction
- type Duration
- type Field
- type FieldDescriptor
- type FragMsg
- type FragParams
- type LoRaWANFrame
- type MsgKind
- type Packet
- type RCSAlgorithm
- type Receiver
- type Rule
- func LoRaWANDownlinkRule(fport uint8, class string, pingSlot time.Duration) Rule
- func LoRaWANMulticastRule(fport uint8) Rule
- func LoRaWANUplinkRule(fport uint8, tileBytes int, ackEveryWindow bool) Rule
- func SigfoxDownlinkRule(id uint32) (Rule, error)
- func SigfoxUplinkNoAckRule(id uint32) (Rule, error)
- func SigfoxUplinkRule(id uint32, h SigfoxHeader) (Rule, error)
- type RuleSet
- func (rs *RuleSet) ByID(id uint32) *Rule
- func (rs *RuleSet) Compile() error
- func (rs *RuleSet) Compress(st Stack, raw []byte, dir Direction, ctx Context) (Bits, *Rule, error)
- func (rs *RuleSet) CompressPacket(p Packet, dir Direction, ctx Context) (Bits, *Rule, error)
- func (rs *RuleSet) Decompress(st Stack, msg Bits, dir Direction, ctx Context) ([]byte, *Rule, error)
- func (rs *RuleSet) DecompressPacket(msg Bits, dir Direction, ctx Context) (Packet, *Rule, error)
- func (rs *RuleSet) Fragmentation(dir Direction) []*Rule
- func (rs *RuleSet) MarshalYANG() ([]byte, error)
- func (rs *RuleSet) YANG() (*YANGDocument, error)
- type Sender
- type SigfoxHeader
- type Stack
- type WindowBitmap
- type YANGDocument
- type YANGEntry
- type YANGOptions
- type YANGRule
- type YANGSCHC
- type YANGTimer
- type YANGValue
Examples ¶
Constants ¶
const ( FCoAPVersion = "coap.version" // 2 bits FCoAPType = "coap.type" // 2 bits FCoAPTKL = "coap.tkl" // 4 bits, or 12 or 20 with the extended length of RFC 8974 FCoAPCode = "coap.code" // 8 bits FCoAPCodeClass = "coap.codeClass" // first 3 bits of the code, when a rule describes them apart FCoAPCodeDetail = "coap.codeDetail" // last 5 bits of the code FCoAPMID = "coap.mid" // 16 bits FCoAPToken = "coap.token" // TKL bytes (fl "tkl" in a rule) FCoAPIfMatch = "coap.ifMatch" // 1, RFC 7252 FCoAPUriHost = "coap.uriHost" // 3 FCoAPETag = "coap.etag" // 4 FCoAPIfNoneMatch = "coap.ifNoneMatch" // 5 FCoAPObserve = "coap.observe" // 6, RFC 7641 FCoAPUriPort = "coap.uriPort" // 7 FCoAPLocationPath = "coap.locationPath" // 8 FCoAPUriPath = "coap.uriPath" // 11 FCoAPContentFormat = "coap.contentFormat" // 12 FCoAPMaxAge = "coap.maxAge" // 14 FCoAPUriQuery = "coap.uriQuery" // 15 FCoAPHopLimit = "coap.hopLimit" // 16, RFC 8768 FCoAPAccept = "coap.accept" // 17 FCoAPQBlock1 = "coap.qBlock1" // 19, RFC 9177 FCoAPLocationQuery = "coap.locationQuery" // 20 FCoAPEDHOC = "coap.edhoc" // 21, RFC 9668 FCoAPBlock2 = "coap.block2" // 23, RFC 7959 FCoAPBlock1 = "coap.block1" // 27, RFC 7959 FCoAPSize2 = "coap.size2" // 28, RFC 7959 FCoAPQBlock2 = "coap.qBlock2" // 31, RFC 9177 FCoAPProxyURI = "coap.proxyUri" // 35 FCoAPProxyScheme = "coap.proxyScheme" // 39 FCoAPSize1 = "coap.size1" // 60 FCoAPEcho = "coap.echo" // 252, RFC 9175 FCoAPNoResponse = "coap.noResponse" // 258, RFC 7967 FCoAPRequestTag = "coap.requestTag" // 292, RFC 9175 FCoAPOCFAcceptCFVer = "coap.ocfAcceptContentFormatVersion" // 2049 FCoAPOCFCFVer = "coap.ocfContentFormatVersion" // 2053 FOSCOREFlags = "coap.oscore.flags" // option 9 (RFC 8613), its first byte (RFC 8824 6.4) FOSCOREPIV = "coap.oscore.piv" // the Partial IV, n bytes FOSCOREKIDCtx = "coap.oscore.kidctx" // the s byte and the kid context FOSCOREKID = "coap.oscore.kid" // the kid, the rest of the value )
CoAP field IDs (RFC 8824). The header fields are labelled in header order; every option instance gets the FID of its option number, with Pos counting the instances of that option from 1, and its value as the field (the option's delta and length are not fields: they are rebuilt from the option number and the value). The payload marker is not a field either: it is sent when, and only when, the payload is not empty, as RFC 7252 3 requires.
The OSCORE option (RFC 8613 6.1) is labelled as the four fields of RFC 8824 6.4: flags (the first byte), piv, kidctx (the s byte and the kid context) and kid. Each is empty when its part is absent; an empty OSCORE option gives four empty fields.
const ( FIPv6Version = "ipv6.version" FIPv6TrafficClass = "ipv6.trafficClass" FIPv6FlowLabel = "ipv6.flowLabel" FIPv6PayloadLength = "ipv6.payloadLength" FIPv6NextHeader = "ipv6.nextHeader" FIPv6HopLimit = "ipv6.hopLimit" FIPv6DevPrefix = "ipv6.devPrefix" FIPv6DevIID = "ipv6.devIID" FIPv6AppPrefix = "ipv6.appPrefix" FIPv6AppIID = "ipv6.appIID" FUDPDevPort = "udp.devPort" FUDPAppPort = "udp.appPort" FUDPLength = "udp.length" FUDPChecksum = "udp.checksum" FWrapperVersion = "wrapper.version" FWrapperDevWPort = "wrapper.devWPort" FWrapperAppWPort = "wrapper.appWPort" FWrapperLength = "wrapper.length" // ICMPv6 (RFC 4443) for the ping of RFC 8724's OAM use, as openschc // labels it; identifier and sequence only in Echo Request and Reply. FICMPv6Type = "icmpv6.type" FICMPv6Code = "icmpv6.code" FICMPv6Checksum = "icmpv6.checksum" FICMPv6Identifier = "icmpv6.identifier" FICMPv6Sequence = "icmpv6.sequence" // IPv4 (RFC 791), addresses by role as for IPv6; the ToS byte may be // described as DSCP and ECN (RFC 2474, 3168); options, when IHL is // over 5, are one field of whole 32-bit words. FIPv4Version = "ipv4.version" FIPv4IHL = "ipv4.ihl" FIPv4ToS = "ipv4.tos" FIPv4DS = "ipv4.ds" FIPv4ECN = "ipv4.ecn" FIPv4TotalLength = "ipv4.totalLength" FIPv4Identification = "ipv4.identification" FIPv4Flags = "ipv4.flags" FIPv4FragmentOffset = "ipv4.fragmentOffset" FIPv4TTL = "ipv4.ttl" FIPv4Protocol = "ipv4.protocol" FIPv4Checksum = "ipv4.checksum" FIPv4DevAddress = "ipv4.devAddress" FIPv4AppAddress = "ipv4.appAddress" FIPv4Options = "ipv4.options" // SCTP common header (RFC 9260 3.1); the chunks are the payload. FSCTPDevPort = "sctp.devPort" FSCTPAppPort = "sctp.appPort" FSCTPVerificationTag = "sctp.verificationTag" FSCTPChecksum = "sctp.checksum" )
Field IDs our parsers label. IPv6 and UDP follow RFC 8724 clause 10, naming addresses and ports by role (Dev, App) rather than position (10.7, 10.9). The wrapper fields are the IEC 62056-4-7 wrapper header, also named by role: the meter's wPort is devWPort.
const ( FIPv6DS = "ipv6.ds" // first 6 bits of the Traffic Class FIPv6ECN = "ipv6.ecn" // last 2 bits )
Subfields a rule may describe in place of their field (RFC 9363 derives their identities from the field's): the IPv6 Traffic Class as DSCP and ECN (RFC 2474, RFC 3168), the CoAP Code as class and detail (RFC 7252 3). The parsers label the whole field; a rule that names a subfield gets the field cut into its subfields before matching, and decompression joins them again.
const ( // FPortUp is the recommended uplink fragmentation RuleID (5.2). FPortUp = 20 // FPortDown is the recommended downlink fragmentation RuleID. FPortDown = 21 // FPortNoCompression is the recommended RuleID for a packet no rule // compresses. FPortNoCompression = 22 )
SCHC over LoRaWAN (RFC 9011). The RuleID is 8 bits carried in the LoRaWAN FPort; the SCHC Message is FPort then FRMPayload (5.1, 5.2). The L2 Word is a byte and padding is zeros (5.4, 5.6).
const ( ClassA = "A" ClassB = "B" ClassC = "C" )
LoRaWAN device classes (RFC 9011 4.1).
const ( MOEqual = "equal" MOIgnore = "ignore" MOMSB = "msb" MOMatchMapping = "match-mapping" )
Matching operators (RFC 8724 7.3).
const ( CDANotSent = "not-sent" CDAValueSent = "value-sent" CDAMappingSent = "mapping-sent" CDALSB = "lsb" CDACompute = "compute" CDADevIID = "deviid" CDAAppIID = "appiid" )
Compression/decompression actions (RFC 8724 7.4).
const ( KindCompression = "compression" KindNoCompression = "no-compression" KindFragmentation = "fragmentation" )
Rule kinds.
const ( NoAck = "no-ack" AckAlways = "ack-always" AckOnError = "ack-on-error" )
Fragmentation modes (RFC 8724 8.4).
const ( LastTileRegular = "regular" LastTileAll1 = "all1" LastTileEither = "either" )
Where an ACK-on-Error sender puts the last tile (RFC 8724 8.4.3).
const ( SigfoxUplinkMTU = 96 // bits SigfoxDownlinkMTU = 64 // bits, every downlink frame )
SCHC over Sigfox (RFC 9442). Uplink frames carry 0 to 12 bytes, downlink frames exactly 8; the L2 Word is a byte (3.2, 3.3, 3.7). The RuleID is the first bits of the SCHC header (3.4); uplink fragmentation RuleIDs are 3 bits, or 6 bits starting 111, or 8 bits starting 111111 (4.1).
const ( YANGModule = "ietf-schc" YANGExtModule = "cb-sigma-schc" )
YANGModule is the module name of RFC 9363 and YANGExtModule ours.
const OptionOSCORE = 9
OptionOSCORE is the OSCORE option number (RFC 8613 2).
const RCSCRC32 = "crc32"
RCSCRC32 is the default algorithm: CRC32 with the reflected polynomial EDB88320h (RFC 8724 8.2.3, as Ethernet and ISO/IEC 3309 use it).
const RCSFragmentCount = "fragment-count"
RCSFragmentCount is the RCS of the Sigfox profile (RFC 9442 3.5.1.5): the field carries the number of fragments of the All-1's window, the All-1 included (for No-ACK, of the whole packet), modulo 2^rcsSize, so the receiver knows how many tiles the last window has. It checks no content. The RFC does not say how the count is formed; this follows the implementation of the RFC's authors (github.com/schc-over-sigfox, MIT, Fragmenter.generate_fragment), see PROVENANCE.md. A rule naming it gives its size in rcsSize.
const VarTKL = "tkl"
VarTKL is the field length function of the CoAP token (RFC 8824 4.5): the token is as long as the TKL says, and no size goes in the residue.
Variables ¶
var ErrAborted = errors.New("schc: the receiver aborted the transfer")
ErrAborted is the error of a transfer the other end aborted.
var ErrInactive = errors.New("schc: the transfer was inactive for too long")
ErrInactive is the error of a transfer that timed out.
var ErrNoRule = errors.New("schc: no rule compresses this packet and there is no no-compression rule")
ErrNoRule is returned when no compression rule fits and the rule set has no no-compression rule.
var ErrSenderAborted = errors.New("schc: the sender aborted the transfer")
ErrSenderAborted is the error of a transfer the sender aborted.
Functions ¶
func CoAPOptionFID ¶ added in v0.2.0
CoAPOptionFID is the field ID of a CoAP option number (the OSCORE option is labelled as its four parts; this returns "coap.oscore").
func CoAPOptionNumber ¶ added in v0.2.0
CoAPOptionNumber is the option number of a CoAP option FID, including "coap.option.n" and the four OSCORE parts.
func LoRaWANIID ¶
LoRaWANIID is the Dev IPv6 interface identifier of RFC 9011 5.3: the first 8 bytes of AES128-CMAC(AppSKey, DevEUI).
func RCSAlgorithms ¶ added in v0.2.0
func RCSAlgorithms() []string
RCSAlgorithms lists the registered algorithm names, sorted.
func RegisterRCS ¶ added in v0.2.0
func RegisterRCS(a RCSAlgorithm) error
RegisterRCS adds an RCS algorithm a profile defines, for rules to name. A name already registered is an error.
func SigfoxDownlinkPayload ¶ added in v0.3.0
SigfoxDownlinkPayload pads a SCHC message with zeros to the 8 bytes of a Sigfox downlink frame (RFC 9442 3.7): every ACK and every downlink fragment travels so.
A downlink All-1's padding cannot be told from tile bytes; RFC 9442 leaves the length of the last tile to the receiver, and reassembly here keeps the padding as part of it (see PROVENANCE.md).
Types ¶
type Bits ¶
type Bits struct {
// contains filtered or unexported fields
}
Bits is a string of bits, most significant bit of the first byte first. SCHC works on bits, not bytes (RFC 8724 clause 9): residues, headers and tiles need not be whole bytes.
func FromLoRaWAN ¶
FromLoRaWAN joins FPort and FRMPayload into the SCHC Message (RFC 9011 5.1, 5.5).
func IPv6Value ¶
IPv6Value reads an IPv6 prefix ("fe80::/64") or interface identifier ("::1") as the 64 bits of a prefix or IID field.
func (*Bits) AppendUint ¶
AppendUint appends the n low bits of v, most significant first.
func (*Bits) Pad ¶
Pad appends zero bits up to a multiple of word bits and returns how many were added (RFC 8724 clause 9: fewer than one L2 Word; RFC 9011 5.4: always zero).
type Context ¶
Context is what the decompressor learns from the L2 (RFC 8724 7.4.7): the Dev's and the App's interface identifiers, 8 bytes each when known.
type Direction ¶
type Direction string
Direction is a field descriptor's Direction Indicator, or a packet's direction (RFC 8724 7.1): up (from the device), dw (to the device) or bi (both, descriptors only).
type Duration ¶
Duration is a JSON duration: "12h", "30s" or a number of seconds.
func (Duration) MarshalJSON ¶
MarshalJSON writes a duration string.
func (*Duration) UnmarshalJSON ¶
UnmarshalJSON reads "12h" or seconds.
type Field ¶
Field is one header field a parser labelled (RFC 8724 7.1: rules do not say how fields are found; a parser alongside SCHC labels them).
type FieldDescriptor ¶
type FieldDescriptor struct {
FID string `json:"fid"`
// FL is the field length in bits; 0 with Var set is a variable-length
// field measured in Var units ("bits" or "bytes", RFC 8724 7.4.2), or
// the CoAP token whose length is its TKL ("tkl", RFC 8824 4.5).
FL int `json:"fl,omitempty"`
Var string `json:"var,omitempty"`
// FP is the field position, default 1; 0 is "don't care" (RFC 8724
// 7.2).
FP *int `json:"fp,omitempty"`
DI Direction `json:"di,omitempty"` // default bi
// TV is a number, a hex string ("0x…" or bare hex), an IPv6 prefix or
// address (for 64-bit prefix and IID fields), {"text": "…"} for UTF-8
// bytes, {"hex": "…"}, or a list of these for match-mapping. For the
// CoAP options that hold text (Uri-Host, Uri-Path, Uri-Query,
// Location-Path, Location-Query, Proxy-Uri, Proxy-Scheme) a plain
// string is the text. A number for a variable-length field is its
// shortest big-endian form, as CoAP uint options are (0 is empty).
TV json.RawMessage `json:"tv,omitempty"`
MO string `json:"mo"`
MOArg int `json:"moArg,omitempty"` // x of MSB(x)
CDA string `json:"cda"`
// contains filtered or unexported fields
}
FieldDescriptor is one line of a compression rule (RFC 8724 7.1).
type FragMsg ¶
type FragMsg struct {
Kind MsgKind
Rule *Rule
DTag uint32
W uint32
FCN uint32 // fragments
RCS uint32 // All-1
// Payload is a fragment's payload bits (for an All-1 including its
// padding, which cannot be told from tile bits, RFC 8724 8.4.3.2).
Payload Bits
C bool // ACK
Bitmap []bool // ACK with C=0: the window's bitmap, leftmost tile (WINDOW_SIZE-1) first, uncompressed
// More are the further windows of a SCHC Compound ACK (RFC 9441), in
// increasing window order after W; only with a rule's CompoundAck.
More []WindowBitmap
}
FragMsg is one SCHC F/R message, decoded.
func DecodeAtReceiver ¶
DecodeAtReceiver reads a message a fragment receiver gets: a fragment, All-1, ACK REQ or Sender-Abort (RFC 8724 8.3.1, 8.3.3, 8.3.4; they are told apart by FCN and size).
func DecodeAtSender ¶
DecodeAtSender reads a message a fragment sender gets: an ACK or a Receiver-Abort (RFC 8724 8.3.2, 8.3.5).
type FragParams ¶
type FragParams struct {
Mode string `json:"mode"`
Direction Direction `json:"direction,omitempty"` // up or dw: which way the fragments go
DTagSize int `json:"dtagSize,omitempty"` // T
WSize int `json:"wSize,omitempty"` // M
FCNSize int `json:"fcnSize"` // N
WindowSize int `json:"windowSize,omitempty"`
// TileSize is the regular tile size in bits for ACK-on-Error; in
// JSON tileBytes (bytes) or tileBits. 0 makes each tile fill its
// fragment at the MTU the sender starts with, one tile per fragment
// (RFC 9363's tile-size left out).
TileSize int `json:"tileBits,omitempty"`
TileBytes int `json:"tileBytes,omitempty"`
// RCS names the Reassembly Check Sequence algorithm (default "crc32",
// RFC 8724 8.2.3; see RegisterRCS) and RCSSize its size in bits (by
// default the algorithm's).
RCS string `json:"rcs,omitempty"`
RCSSize int `json:"rcsSize,omitempty"`
MaxAckRequests int `json:"maxAckRequests,omitempty"`
Retransmission Duration `json:"retransmissionTimer,omitempty"`
Inactivity Duration `json:"inactivityTimer,omitempty"`
LastTile string `json:"lastTile,omitempty"` // ACK-on-Error: regular, all1 or either (default either)
PenultimateShort bool `json:"penultimateShort,omitempty"` // ACK-on-Error: penultimate tile may be one L2 Word short
// AckEveryWindow: the ACK-on-Error receiver acknowledges every window
// and the sender waits for it before the next (RFC 9011 5.6.2).
AckEveryWindow bool `json:"ackEveryWindow,omitempty"`
// CompoundAck: the ACK-on-Error receiver reports every window with
// missing tiles in one SCHC Compound ACK, and the sender reads them
// (RFC 9441); LastBitmapUncompressed sends its last bitmap whole.
CompoundAck bool `json:"compoundAck,omitempty"`
LastBitmapUncompressed bool `json:"lastBitmapUncompressed,omitempty"`
// Options of technology profiles (all off by default; the Sigfox
// rules of RFC 9442 set them, see SigfoxUplinkRule):
//
// HeaderPadded pads every fragment header (an All-1's with its RCS)
// to an L2 Word before the payload. BitmapUncompressed sends every ACK bitmap
// whole (for a Compound ACK, as LastBitmapUncompressed). NoAckReq has
// the sender ask for an ACK by sending the All-1 again, never an ACK
// REQ. FCNCountdown numbers No-ACK fragments from the number of
// fragments less one down to 1, the last being the All-1.
// FullFragments (No-ACK and ACK-Always) fills every regular fragment
// to the MTU, so no regular fragment needs padding; a remainder too
// long for the All-1 goes in one more regular fragment and the All-1
// follows empty.
HeaderPadded bool `json:"headerPadded,omitempty"`
BitmapUncompressed bool `json:"bitmapUncompressed,omitempty"`
NoAckReq bool `json:"noAckReq,omitempty"`
FCNCountdown bool `json:"fcnCountdown,omitempty"`
FullFragments bool `json:"fullFragments,omitempty"`
// AckMaxBits bounds the receiver's SCHC ACK (the frame it travels in,
// 64 bits on a Sigfox downlink): a Compound ACK reports as many
// windows with tiles missing as fit, lowest first. 0 is no bound.
AckMaxBits int `json:"ackMaxBits,omitempty"`
// contains filtered or unexported fields
}
FragParams are a fragmentation rule's parameters (RFC 8724 8.2.4, 8.4 and appendix D).
type LoRaWANFrame ¶
LoRaWANFrame is a SCHC Message as it travels on LoRaWAN: the FPort and the FRMPayload.
type MsgKind ¶
type MsgKind int
MsgKind is a SCHC F/R message type (RFC 8724 8.2.1, 8.3).
type Packet ¶
Packet is a parsed packet: its labelled header fields in header order and the payload that follows them.
type RCSAlgorithm ¶ added in v0.2.0
type RCSAlgorithm struct {
// Name is how rules name it, such as "crc32".
Name string
// Bits is the size of the RCS field, 1 to 32.
Bits int
// Sum computes the RCS of the packet bytes; only its low Bits bits are
// sent.
Sum func(packet []byte) uint32
}
RCSAlgorithm is a Reassembly Check Sequence algorithm (RFC 8724 8.2.3): a check over the reassembled packet, zero-extended to whole bytes, sent in the All-1 fragment. RFC 8724 defines CRC32 and leaves others to profiles; a fragmentation rule names its algorithm ("rcs" in JSON, rcs-algorithm in RFC 9363).
func LookupRCS ¶ added in v0.2.0
func LookupRCS(name string) (RCSAlgorithm, bool)
LookupRCS returns a registered RCS algorithm.
type Receiver ¶
type Receiver struct {
// contains filtered or unexported fields
}
Receiver reassembles one fragmented SCHC Packet (one RuleID and DTag) and runs the receiver side of its mode (RFC 8724 8.4.1.2, 8.4.2.2, 8.4.3.2). Like Sender it does no I/O: it returns the messages to send back and, once the integrity check passes, the SCHC Packet.
func NewReceiver ¶
NewReceiver starts reassembly for a fragmentation rule and DTag. maxBytes bounds the reassembled packet (0: 4096).
func (*Receiver) Packet ¶
Packet is the reassembled SCHC Packet (with the padding bits of the fragment that carried the last tile, which decompression drops).
type Rule ¶
type Rule struct {
ID uint32 `json:"ruleId"`
IDLength int `json:"ruleIdLength,omitempty"` // bits, default 8
// Implicit is a rule whose RuleID is not sent (length 0): the context
// says which rule applies, as when the rule set holds one rule or the
// L2 tells rules apart (RFC 9363's rule-id-length 0). Its ID is 0, and
// it must be the only rule of its rule set, since an empty RuleID
// starts every other.
Implicit bool `json:"implicit,omitempty"`
Kind string `json:"kind,omitempty"` // default compression, or fragmentation when fragmentation is set
// Name is a label for logs and the console.
Name string `json:"name,omitempty"`
Fields []FieldDescriptor `json:"fields,omitempty"`
Fragmentation *FragParams `json:"fragmentation,omitempty"`
// contains filtered or unexported fields
}
Rule is one rule: compression, no-compression or fragmentation.
func LoRaWANDownlinkRule ¶
LoRaWANDownlinkRule is the unicast downlink fragmentation rule of RFC 9011 5.6.3: ACK-Always, T=0, M=1, N=1, WINDOW_SIZE 1, CRC32 RCS, MAX_ACK_REQUESTS 8, with the timers of the device class (5.6.3.5): class A inactivity 36 h and retransmission inactivity/(MAX+1); class B three ping slot periods; class C 30 s; B and C inactivity 12 h.
func LoRaWANMulticastRule ¶
LoRaWANMulticastRule is the multicast downlink rule of RFC 9011 5.6.3: No-ACK, T=0, N=1.
func LoRaWANUplinkRule ¶
LoRaWANUplinkRule is the uplink fragmentation rule of RFC 9011 5.6.2: ACK-on-Error, T=0, M=2, N=6, WINDOW_SIZE 63, 10-byte tiles, CRC32 RCS, MAX_ACK_REQUESTS 8, 12-hour timers, last tile in either fragment, regular penultimate tile. ackEveryWindow is the per-rule choice 5.6.2 adds (recommended for battery devices).
func SigfoxDownlinkRule ¶ added in v0.3.0
SigfoxDownlinkRule is the downlink ACK-Always rule of RFC 9442 3.5.2: RuleID 3 bits (0 to 7), no DTag or W (one window), a 5-bit FCN, WINDOW_SIZE 31, 7-byte tiles filling each 8-byte frame, a 5-bit RCS and whole bitmaps in the device's ACK.
func SigfoxUplinkNoAckRule ¶ added in v0.3.0
SigfoxUplinkNoAckRule is the uplink No-ACK rule of RFC 9442 3.5.1.3.1: RuleID 3 bits (0 to 6), no DTag or W, a 5-bit FCN counting down to 1 with the All-1 last, 11-byte tiles, a 5-bit RCS, at most 340 bytes.
func SigfoxUplinkRule ¶ added in v0.3.0
func SigfoxUplinkRule(id uint32, h SigfoxHeader) (Rule, error)
SigfoxUplinkRule is an uplink ACK-on-Error rule of RFC 9442 in one of the three header layouts, with the SCHC Compound ACK (RFC 9441) its receiver must send, bitmaps whole, and the last tile in the All-1 when it fits there (else the All-1 follows it alone).
type RuleSet ¶
type RuleSet struct {
// L2Word is the L2 Word size in bits (default 8, the LoRaWAN value of
// RFC 9011 5.6).
L2Word int `json:"l2Word,omitempty"`
Rules []Rule `json:"rules"`
// MaxPacketSize bounds a decompressed or reassembled packet in bytes
// (RFC 8724 appendix D, clause 12; default 4096).
MaxPacketSize int `json:"maxPacketSize,omitempty"`
}
RuleSet is a SCHC context: the rules both ends hold (RFC 8724 7.1). In JSON it is our own form; ParseYANG and MarshalYANG use RFC 9363's.
func FromYANG ¶ added in v0.2.0
func FromYANG(doc *YANGDocument, opt YANGOptions) (*RuleSet, []error, error)
FromYANG builds and compiles a rule set from the RFC 9363 tree.
func ParseRuleSet ¶
ParseRuleSet reads and checks a rule set from JSON.
func ParseYANG ¶ added in v0.2.0
ParseYANG reads RFC 9363 instance data in RFC 7951 JSON and compiles it.
func ParseYANGWith ¶ added in v0.2.0
func ParseYANGWith(b []byte, opt YANGOptions) (rs *RuleSet, skipped []error, err error)
ParseYANGWith is ParseYANG with options; skipped lists the rules left out under SkipBadRules and why.
func (*RuleSet) Compress ¶
Compress parses raw with st and compresses it with the first rule that fits (RFC 8724 7.2), or sends it whole under the no-compression rule. The result is the SCHC Packet: RuleID, residue, payload (not padded).
Example ¶
Compress an IEC 62056-4-7 wrapper header (8 bytes) to a few bits with a rule that elides the constant fields and computes the length, then rebuild the frame on the other side from the same rules.
package main
import (
"bytes"
"fmt"
"github.com/cB-Sigma/schc"
)
func main() {
rules, err := schc.ParseRuleSet([]byte(`{"rules":[
{"ruleId":1,"fields":[
{"fid":"wrapper.version","fl":16,"tv":1,"mo":"equal","cda":"not-sent"},
{"fid":"wrapper.devWPort","fl":16,"tv":1,"mo":"equal","cda":"not-sent"},
{"fid":"wrapper.appWPort","fl":16,"tv":[16,32,48,64,80,96,102,1],"mo":"match-mapping","cda":"mapping-sent"},
{"fid":"wrapper.length","fl":16,"mo":"ignore","cda":"compute"}]},
{"ruleId":22,"kind":"no-compression"}]}`))
if err != nil {
panic(err)
}
stack, _ := schc.ParseStack("wrapper")
apdu := []byte{0xC0, 0x01, 0xC1, 0x00, 0x03}
frame := append([]byte{0x00, 0x01, 0x00, 0x01, 0x00, 0x10, 0x00, byte(len(apdu))}, apdu...)
msg, rule, err := rules.Compress(stack, frame, schc.Up, schc.Context{})
if err != nil {
panic(err)
}
fmt.Println("rule", rule.ID, "header and payload in", msg.Len(), "bits instead of", 8*len(frame))
msg.Pad(8)
back, _, err := rules.Decompress(stack, msg, schc.Up, schc.Context{})
fmt.Println(bytes.Equal(back, frame), err)
}
Output: rule 1 header and payload in 51 bits instead of 104 true <nil>
Example (Coap) ¶
Compress a CoAP GET and its response with one rule that describes both directions (RFC 8824 7.3, table 6): the request to 2 bytes, the response's header to 1 byte before its payload.
package main
import (
"bytes"
"encoding/hex"
"fmt"
"github.com/cB-Sigma/schc"
)
func main() {
rules, err := schc.ParseRuleSet([]byte(`{"rules":[{"ruleId":1,"fields":[
{"fid":"coap.version","fl":2,"tv":1,"mo":"equal","cda":"not-sent"},
{"fid":"coap.type","fl":2,"di":"up","tv":0,"mo":"equal","cda":"not-sent"},
{"fid":"coap.type","fl":2,"di":"dw","tv":2,"mo":"equal","cda":"not-sent"},
{"fid":"coap.tkl","fl":4,"tv":1,"mo":"equal","cda":"not-sent"},
{"fid":"coap.code","fl":8,"di":"up","tv":1,"mo":"equal","cda":"not-sent"},
{"fid":"coap.code","fl":8,"di":"dw","tv":[69,132],"mo":"match-mapping","cda":"mapping-sent"},
{"fid":"coap.mid","fl":16,"tv":0,"mo":"msb(12)","cda":"lsb"},
{"fid":"coap.token","var":"tkl","tv":"80","mo":"msb(5)","cda":"lsb"},
{"fid":"coap.uriPath","var":"bytes","di":"up","tv":"temperature","mo":"equal","cda":"not-sent"}]}]}`))
if err != nil {
panic(err)
}
stack, _ := schc.ParseStack("coap") // or "ipv6/udp/coap" for one rule over the whole packet
get, _ := hex.DecodeString("4101000182bb74656d7065726174757265")
content, _ := hex.DecodeString("6145000182ff32332043")
for _, m := range []struct {
dir schc.Direction
msg []byte
}{{schc.Up, get}, {schc.Down, content}} {
c, _, err := rules.Compress(stack, m.msg, m.dir, schc.Context{})
if err != nil {
panic(err)
}
c.Pad(8)
back, _, err := rules.Decompress(stack, c, m.dir, schc.Context{})
fmt.Printf("%s: %d bytes to %x, back %v %v\n", m.dir, len(m.msg), c.Bytes(), bytes.Equal(back, m.msg), err)
}
}
Output: up: 17 bytes to 0114, back true <nil> dw: 10 bytes to 010a32332043, back true <nil>
func (*RuleSet) CompressPacket ¶
CompressPacket compresses fields a caller labelled itself (no stack: compute CDAs are not checked) with the first rule that fits.
func (*RuleSet) Decompress ¶
func (rs *RuleSet) Decompress(st Stack, msg Bits, dir Direction, ctx Context) ([]byte, *Rule, error)
Decompress reads a SCHC Packet (possibly followed by padding of less than one L2 Word) and rebuilds the original packet with st (RFC 8724 7.2).
func (*RuleSet) DecompressPacket ¶
DecompressPacket reads a SCHC Packet into labelled fields and payload without a stack (compute fields come back empty).
func (*RuleSet) Fragmentation ¶
Fragmentation returns the fragmentation rules for a direction, in ID order.
func (*RuleSet) MarshalYANG ¶ added in v0.2.0
MarshalYANG writes the rule set as RFC 9363 instance data in RFC 7951 JSON. The rule set must be compiled (ParseRuleSet does it).
type Sender ¶
type Sender struct {
// NextMTU, when set, gives the MTU of each new fragment in place of
// the mtu argument (an L2 whose MTU varies, RFC 8724 figure 32).
NextMTU func() int
// contains filtered or unexported fields
}
Sender fragments one SCHC Packet under a fragmentation rule and runs the sender side of its mode (RFC 8724 8.4.1.1, 8.4.2.1, 8.4.3.1). It does no I/O: its methods return the encoded messages to transmit, and the caller runs the clock (Tick) and says how many bits the next message may have (mtu, the whole SCHC message including the RuleID).
func NewSender ¶
NewSender starts fragmenting packet under rule r with DTag dtag.
Example ¶
Fragment a 300-byte packet for LoRaWAN with the RFC 9011 uplink rule (ACK-on-Error) and reassemble it. Sender and Receiver are state machines without I/O: the caller carries their messages and drives their timers.
package main
import (
"bytes"
"fmt"
"time"
"github.com/cB-Sigma/schc"
)
func main() {
rules := schc.RuleSet{Rules: []schc.Rule{schc.LoRaWANUplinkRule(schc.FPortUp, 10, false)}}
if err := rules.Compile(); err != nil {
panic(err)
}
rule := &rules.Rules[0]
packet := schc.BytesOf(bytes.Repeat([]byte("sensor data "), 25))
now := time.Now()
sender, err := schc.NewSender(rule, 8, 0, packet)
if err != nil {
panic(err)
}
receiver := schc.NewReceiver(rule, 8, 0, 0, now)
frags, err := sender.Start(now, 8+8*51) // FPort plus 51 bytes of LoRaWAN payload
if err != nil {
panic(err)
}
var acks []schc.Bits
for _, f := range frags {
lf, _ := schc.ToLoRaWAN(f) // what goes on the radio: FPort and payload
a, err := receiver.Receive(now, schc.FromLoRaWAN(lf.FPort, lf.Payload))
if err != nil {
panic(err)
}
acks = append(acks, a...)
}
for _, a := range acks {
if _, err := sender.Receive(now, a, 8+8*51); err != nil {
panic(err)
}
}
got, ok := receiver.Packet()
same := ok && bytes.Equal(got.Slice(0, packet.Len()).Bytes(), packet.Bytes())
fmt.Printf("%d fragments, reassembled %v, sender done %v\n", len(frags), same, sender.Done())
}
Output: 7 fragments, reassembled true, sender done true
func (*Sender) Done ¶
Done reports whether the transfer ended; Err is its error (nil when the receiver confirmed the packet, or for No-ACK once everything was sent).
type SigfoxHeader ¶ added in v0.3.0
type SigfoxHeader int
SigfoxHeader is one of the uplink ACK-on-Error header layouts of RFC 9442 3.5.1.3.2 and 3.5.1.4.
const ( // SigfoxSingleByte: RuleID 3 bits, W 2, FCN 3, WINDOW_SIZE 7, tiles // of 11 bytes, a 3-bit RCS (3.5.1.3.2); RuleIDs 0 to 6. SigfoxSingleByte SigfoxHeader = iota // SigfoxTwoByte1: RuleID 6 bits, W 2, FCN 4, WINDOW_SIZE 12, tiles of // 10 bytes, a 4-bit RCS (3.5.1.4.1); RuleIDs 56 to 62 (111000 to // 111110). SigfoxTwoByte1 // SigfoxTwoByte2: RuleID 8 bits, W 3, FCN 5, WINDOW_SIZE 31, tiles of // 10 bytes, a 5-bit RCS (3.5.1.4.2); RuleIDs 252 to 255. SigfoxTwoByte2 )
The uplink ACK-on-Error layouts.
type Stack ¶
type Stack []string
Stack is the protocol layers a packet's header is made of, outermost first: any of ipv6, udp, and then one of coap, coap-inner and wrapper, in that order, or ipv6/icmpv6. An empty stack has no header: the whole packet is payload.
coap is a whole CoAP message (RFC 7252 3), alone or over ipv6/udp in one rule (RFC 8824 figures 1 and 2); coap-inner is an OSCORE plaintext (RFC 8613 5.3: the code, the Class E options and the payload), for the inner rules of RFC 8824 7.2, whose result is encrypted and carried in an outer CoAP message that the outer rules compress with coap or ipv6/udp/coap.
func ParseStack ¶
ParseStack reads "ipv6/udp/coap", "coap", "coap-inner", "ipv6/udp/wrapper", "wrapper", "ipv6/udp", "ipv6/icmpv6", "none" or "".
func (Stack) Build ¶
Build writes a packet from its field values (by FID; fields missing from vals are computed) and payload. It is the inverse of Parse for headers whose fields appear once; use BuildFields for CoAP messages with repeated options.
func (Stack) BuildFields ¶ added in v0.2.0
BuildFields writes a packet from its labelled fields (fields missing are computed) and payload. It is the inverse of Parse: CoAP options are written in option-number order, repeated ones by position.
type WindowBitmap ¶ added in v0.2.0
WindowBitmap is one window's bitmap in a SCHC Compound ACK.
type YANGDocument ¶ added in v0.2.0
type YANGDocument struct {
SCHC YANGSCHC `json:"ietf-schc:schc"`
}
YANGDocument is the top of RFC 9363 instance data in JSON.
type YANGEntry ¶ added in v0.2.0
type YANGEntry struct {
FieldID string `json:"field-id,omitempty"`
FieldLength json.RawMessage `json:"field-length,omitempty"`
FieldPosition *uint8 `json:"field-position,omitempty"`
DirectionIndicator string `json:"direction-indicator,omitempty"`
TargetValue []YANGValue `json:"target-value,omitempty"`
MatchingOperator string `json:"matching-operator,omitempty"`
MatchingOperatorValue []YANGValue `json:"matching-operator-value,omitempty"`
CompDecompAction string `json:"comp-decomp-action,omitempty"`
CompDecompActionValue []YANGValue `json:"comp-decomp-action-value,omitempty"`
}
YANGEntry is one field descriptor of a compression rule. FieldLength is a number or an identity.
type YANGOptions ¶ added in v0.2.0
type YANGOptions struct {
// SkipBadRules leaves out the rules that cannot be read (an unknown
// field ID, a missing mandatory leaf, a value that does not fit)
// instead of failing; ParseYANGWith reports each one.
SkipBadRules bool
// TileBits is a tile size for ACK-on-Error rules without tile-size,
// for peers that expect one. 0 keeps RFC 9363's meaning: tiles fill
// each fragment (FragParams.TileSize 0).
TileBits int
}
YANGOptions say how ParseYANG treats what this module cannot use.
type YANGRule ¶ added in v0.2.0
type YANGRule struct {
RuleIDValue *uint32 `json:"rule-id-value,omitempty"`
RuleIDLength *uint8 `json:"rule-id-length,omitempty"`
RuleNature string `json:"rule-nature,omitempty"`
Entry []YANGEntry `json:"entry,omitempty"`
FragmentationMode string `json:"fragmentation-mode,omitempty"`
L2WordSize *uint8 `json:"l2-word-size,omitempty"`
Direction string `json:"direction,omitempty"`
DTagSize *uint8 `json:"dtag-size,omitempty"`
WSize *uint8 `json:"w-size,omitempty"`
FCNSize *uint8 `json:"fcn-size,omitempty"`
RCSAlgorithm string `json:"rcs-algorithm,omitempty"`
MaximumPacketSize *uint16 `json:"maximum-packet-size,omitempty"`
WindowSize *uint16 `json:"window-size,omitempty"`
MaxInterleavedFrames *uint8 `json:"max-interleaved-frames,omitempty"`
InactivityTimer *YANGTimer `json:"inactivity-timer,omitempty"`
RetransmissionTimer *YANGTimer `json:"retransmission-timer,omitempty"`
MaxAckRequests *uint8 `json:"max-ack-requests,omitempty"`
TileSize *uint8 `json:"tile-size,omitempty"`
TileInAll1 string `json:"tile-in-all-1,omitempty"`
AckBehavior string `json:"ack-behavior,omitempty"`
// The RFC 9441 augment (module ietf-schc-compound-ack).
BitmapFormat string `json:"ietf-schc-compound-ack:bitmap-format,omitempty"`
LastBitmapCompression *bool `json:"ietf-schc-compound-ack:last-bitmap-compression,omitempty"`
}
YANGRule is one rule of any nature.
type YANGSCHC ¶ added in v0.2.0
type YANGSCHC struct {
Rule []YANGRule `json:"rule"`
}
YANGSCHC is the schc container.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
Package coreconf carries SCHC rule sets in the CORECONF form: RFC 9363 instance data encoded in CBOR with YANG Schema Item iDentifiers (SIDs), as RFC 9254 specifies, for rule management over CoAP (CORECONF).
|
Package coreconf carries SCHC rule sets in the CORECONF form: RFC 9363 instance data encoded in CBOR with YANG Schema Item iDentifiers (SIDs), as RFC 9254 specifies, for rule management over CoAP (CORECONF). |
|
Package v44 is the ITU-T V.44 (11/2000, with Corrigendum 1 of 03/2002) data compression algorithm in pure Go: the packet method (annex B.1, Compress and Decompress), the multi-packet method (annex B.2) and the stream method of the main body (Encoder and Decoder), and the negotiation of annex A and 7.4 (Proposal, MarshalXID, ParseXID, Agree, parameter mode).
|
Package v44 is the ITU-T V.44 (11/2000, with Corrigendum 1 of 03/2002) data compression algorithm in pure Go: the packet method (annex B.1, Compress and Decompress), the multi-packet method (annex B.2) and the stream method of the main body (Encoder and Decoder), and the negotiation of annex A and 7.4 (Proposal, MarshalXID, ParseXID, Agree, parameter mode). |