schc

package module
v0.2.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 11, 2026 License: Apache-2.0 Imports: 16 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

schc

Static Context Header Compression and fragmentation (SCHC, RFC 8724) for IPv6, UDP, ICMPv6 and CoAP (RFC 8824, with OSCORE), the LoRaWAN profile (RFC 9011), Compound ACK (RFC 9441), rules in the RFC 9363 YANG model as JSON or CORECONF CBOR, and V.44 data compression (packet, multi-packet and stream methods), in pure Go.

Go Reference test Go

No cgo. The schc and schc/v44 packages use only the Go standard library; schc/coreconf adds github.com/fxamacker/cbor/v2. Written for SigmaM2M, a oneM2M platform, where it carries DLMS/COSEM meter traffic over LoRaWAN.

Features

Feature Status
Compression: matching operators equal, ignore, MSB(x), match-mapping; actions not-sent, value-sent, mapping-sent, LSB, compute, DevIID, AppIID; variable-length residues Implemented
Fields: IPv6 (Traffic Class whole or as DSCP and ECN), UDP, ICMPv6 Echo (type, code, checksum, identifier, sequence, as openschc labels them), IEC 62056-4-7 wrapper header Implemented
Fields: CoAP (RFC 8824): version, type, TKL, code (whole or as class and detail), MID, token with the tkl length function, every option by number (named for the options of RFC 7252, 7641, 7959, 7967, 8613, 8768, 9175, 9177 and 9668, coap.option.N for any other), payload marker; several Uri-Path or Uri-Query elements in one entry (5.3) Implemented
CoAP layouts: one rule from IPv6 to CoAP, CoAP alone (end-to-end, then IPv6/UDP in a second stage), OSCORE (RFC 8613 option as flags, piv, kidctx and kid; inner rules on the plaintext, outer rules on the protected message) Implemented
Fragmentation: No-ACK, ACK-Always, ACK-on-Error (fixed tiles, or tiles that fill each fragment as an RFC 9363 rule without tile-size means), bitmap compression Implemented, as clock-driven sender and receiver state machines without I/O
SCHC Compound ACK (RFC 9441) Implemented (compoundAck in a rule)
RCS algorithms: CRC32 (RFC 8724), CRC-32C, CRC-16 of HDLC, CRC-8, and any a profile registers with RegisterRCS Implemented
LoRaWAN profile (RFC 9011): uplink ACK-on-Error, downlink ACK-Always, multicast No-ACK, class timers, FPort mapping, AES-CMAC interface identifier Implemented
Rules in the RFC 9363 data model: RFC 7951 JSON read and written (ParseYANG, MarshalYANG), with the RFC 9441 augment; CORECONF form, CBOR with SIDs (RFC 9254), in schc/coreconf Implemented. RFC 9363 assigned no SIDs: the defaults are openschc's assignment for ietf-schc, others load from SID files
Rules in this module's own JSON Implemented (the form all features have; RFC 9363 cannot express every-option FIDs or grouped entries)
V.44 packet method (annex B.1) Implemented
V.44 multi-packet (annex B.2) and stream methods, with transparent mode, ESCAPE, compressibility monitoring and parameter mode Implemented; V.44 gives no vectors for them, so they are tested by round trip and the appendix II.1 sequence continued across a FLUSH
V.44 negotiation: Table 10 parameters in an XID user data subfield (annex A) or in parameter mode, and the agreement rules of 7.4 and annex B Implemented; the V.42 LAPM procedures that carry the XID frame are not

Not implemented: implicit rules (RuleID length 0), the extended token lengths of RFC 8974 (such messages go under the no-compression rule), and the Sigfox and other technology profiles (RFC 9442 and later). Standards and clause references are listed in PROVENANCE.md.

Choosing a SCHC implementation

No other Go implementation of SCHC was found (GitHub and the Go module proxy, October 2026). The other open implementations are in Python and C; compared from their repositories at the versions named. Check the projects themselves before relying on a row.

this module openschc (Python) microSCHC 0.22.0 (Python) libschc (C)
Version looked at v0.2.0 master, last commit 2025-12-16 (PyPI 0.0.3 is from 2022) PyPI, 2026-03-02 master, last commit 2023-04-28
Licence Apache-2.0 MIT MIT GPL-3.0, or a commercial licence
Compression of IPv6 and UDP yes, and ICMPv6 Echo yes, and ICMPv6 Echo yes, and IPv4, SCTP yes
CoAP fields (RFC 8824) yes, with OSCORE inner and outer rules yes yes yes
IEC 62056-4-7 wrapper (DLMS/COSEM) fields yes no no no
Fragmentation: No-ACK, ACK-Always, ACK-on-Error yes yes no yes
Compound ACK (RFC 9441) yes not found in its source (its YANG files mention it) no not found in its source
LoRaWAN the RFC 9011 profile: FPort mapping, timers, AES-CMAC interface identifier examples carry the rule ID in FPort; no AES-CMAC identifier found no a LoRaWAN profile in its rule headers; no AES-CMAC identifier found
Rules as YANG / CORECONF yes: RFC 9363 JSON and CORECONF CBOR, reads openschc's example rule file yes no (own data model) no (C headers)
V.44 compression yes no no no
Runs in a Go program without cgo yes no no no

Pick this module for a Go program: a server or gateway that compresses CoAP, UDP/IPv6 or DLMS/COSEM traffic for LoRaWAN or another LPWAN, or that manages rules in the RFC 9363 model. Pick openschc when you want its network simulator or work in Python; microSCHC for compression alone on MicroPython; libschc on a microcontroller, if GPL-3.0 or its commercial licence suits you.

Install

go get github.com/cB-Sigma/schc@latest

Requires Go 1.24 or later.

Quick start

Compress a CoAP request and its response with one rule that describes both directions (RFC 8824 7.3, table 6; from ExampleRuleSet_Compress_coap):

import "github.com/cB-Sigma/schc"

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"}]}]}`))
stack, _ := schc.ParseStack("coap") // "ipv6/udp/coap" for one rule over the whole packet
get, _ := hex.DecodeString("4101000182bb74656d7065726174757265")
msg, rule, err := rules.Compress(stack, get, schc.Up, schc.Context{})
msg.Pad(8) // GET /temperature, 17 bytes, becomes 01 14
back, _, err := rules.Decompress(stack, msg, schc.Up, schc.Context{})

The same rules as RFC 9363 instance data, and in CBOR:

y, err := rules.MarshalYANG()          // RFC 7951 JSON of ietf-schc
again, err := schc.ParseYANG(y)
c, err := coreconf.Marshal(rules, nil) // import "github.com/cB-Sigma/schc/coreconf"

Fragmentation: NewSender and NewReceiver take a fragmentation rule. The caller carries the sender's fragments to the receiver (Start, Receive) and the receiver's acknowledgements back, and calls Tick at each Deadline. ExampleNewSender fragments a 300-byte packet with the RFC 9011 uplink rule and reassembles it; ExampleRuleSet_Compress compresses an IEC 62056-4-7 wrapper header; v44.ExampleCompress and v44.ExampleNewEncoder compress with the packet and multi-packet methods.

Documentation

Reference: pkg.go.dev/github.com/cB-Sigma/schc.

Package Contents
schc (module root) Rules as our JSON or RFC 9363 JSON; compression and decompression of IPv6, UDP, ICMPv6, CoAP (with OSCORE) and IEC 62056-4-7 wrapper headers; fragmentation sender and receiver with Compound ACK and pluggable RCS; the RFC 9011 LoRaWAN rules, FPort mapping and interface identifier
schc/coreconf RFC 9363 rule sets in CBOR with SIDs (RFC 9254); SID files in the RFC 9595 format or openschc's
schc/v44 ITU-T V.44: packet method (dictionary reset per packet, FLUSH at the end, annex B indicator for packets sent uncompressed); multi-packet and stream methods (Encoder, Decoder); negotiation parameters, XID subfield and agreement

The YANG module yang/cb-sigma-schc@2026-10-11.yang defines the identities this module writes where ietf-schc has none (the wrapper fields, CoAP options registered after RFC 9363, variable lengths in bits, the extra RCS algorithms).

Testing

go test -race ./...

The tests re-enact the RFC 8724 appendix B and RFC 9011 appendix A example exchanges message by message, the RFC 8824 examples of tables 1 to 6 (the GET and Content exchange with and without OSCORE, the inner and outer rules, the CORECONF path) as our own hex, the RFC 9441 Compound ACK sequence and message layout, and the V.44 appendix II examples; sources are listed in PROVENANCE.md, with the defects found in those examples. There are fuzz tests for SCHC message decoding, decompression, CoAP parsing, RFC 9363 JSON, CORECONF CBOR and the V.44 decoders. // Covers: SIG-... comments in tests are requirement IDs of the SigmaM2M project's compliance report and have no meaning outside it.

Interop tested against
  • openschc's example rule set in RFC 9363 JSON (examples/datamodel/schc.json at commit 58293f71, MIT licence, in testdata/openschc): every rule loads (its two ACK-on-Error rules have no tile-size, so their tiles fill each fragment), its CoAP and ICMPv6 rules compress packets to the residues the rules describe, and it converts to CORECONF CBOR and back.

No packets have been exchanged with openschc or libschc, no LoRaWAN network server and no meter that uses V.44 has been tested against this module, and no other V.44 implementation was available to check the multi-packet and stream methods.

This module has no simulator. Its LoRaWAN fragmentation is exercised by SigmaM2M's DLMS/COSEM tests.

Status

v0.x. The API may change before v1; v0.2.0 only adds to v0.1.

Contributing

See CONTRIBUTING.md.

Security

See SECURITY.md for how to report a vulnerability.

Licence

Apache-2.0 (see LICENSE and NOTICE). Copyright 2026 Abhinav Gautam.

Documentation

Overview

Package schc is Static Context Header Compression and fragmentation (RFC 8724) for IPv6, UDP, ICMPv6 and CoAP (RFC 8824), with the LoRaWAN profile of RFC 9011, the Compound ACK of RFC 9441 and rules in the RFC 9363 data model.

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).

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

Examples

Constants

View Source
const (
	FCoAPVersion    = "coap.version"    // 2 bits
	FCoAPType       = "coap.type"       // 2 bits
	FCoAPTKL        = "coap.tkl"        // 4 bits
	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.

View Source
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"
)

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.

View Source
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.

View Source
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).

View Source
const (
	ClassA = "A"
	ClassB = "B"
	ClassC = "C"
)

LoRaWAN device classes (RFC 9011 4.1).

View Source
const (
	MOEqual        = "equal"
	MOIgnore       = "ignore"
	MOMSB          = "msb"
	MOMatchMapping = "match-mapping"
)

Matching operators (RFC 8724 7.3).

View Source
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).

View Source
const (
	KindCompression   = "compression"
	KindNoCompression = "no-compression"
	KindFragmentation = "fragmentation"
)

Rule kinds.

View Source
const (
	NoAck      = "no-ack"
	AckAlways  = "ack-always"
	AckOnError = "ack-on-error"
)

Fragmentation modes (RFC 8724 8.4).

View Source
const (
	LastTileRegular = "regular"
	LastTileAll1    = "all1"
	LastTileEither  = "either"
)

Where an ACK-on-Error sender puts the last tile (RFC 8724 8.4.3).

View Source
const (
	YANGModule    = "ietf-schc"
	YANGExtModule = "cb-sigma-schc"
)

YANGModule is the module name of RFC 9363 and YANGExtModule ours.

View Source
const OptionOSCORE = 9

OptionOSCORE is the OSCORE option number (RFC 8613 2).

View Source
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).

View Source
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

View Source
var ErrAborted = errors.New("schc: the receiver aborted the transfer")

ErrAborted is the error of a transfer the other end aborted.

View Source
var ErrInactive = errors.New("schc: the transfer was inactive for too long")

ErrInactive is the error of a transfer that timed out.

View Source
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.

View Source
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

func CoAPOptionFID(n uint32) string

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

func CoAPOptionNumber(fid string) (uint32, bool)

CoAPOptionNumber is the option number of a CoAP option FID, including "coap.option.n" and the four OSCORE parts.

func LoRaWANIID

func LoRaWANIID(appSKey, devEUI []byte) ([]byte, error)

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.

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 BitsOf

func BitsOf(b []byte, n int) Bits

BitsOf is the first n bits of b (b is not copied).

func BytesOf

func BytesOf(b []byte) Bits

BytesOf is every bit of b.

func FromLoRaWAN

func FromLoRaWAN(fport uint8, payload []byte) Bits

FromLoRaWAN joins FPort and FRMPayload into the SCHC Message (RFC 9011 5.1, 5.5).

func IPv6Value

func IPv6Value(s string) (Bits, error)

IPv6Value reads an IPv6 prefix ("fe80::/64") or interface identifier ("::1") as the 64 bits of a prefix or IID field.

func ParseBits

func ParseBits(s string) (Bits, error)

ParseBits reads a string of 0 and 1 (spaces ignored), for tests.

func Uint

func Uint(v uint64, n int) Bits

Uint is v in n bits (n up to 64).

func (*Bits) Append

func (x *Bits) Append(y Bits)

Append appends y.

func (*Bits) AppendBit

func (x *Bits) AppendBit(v uint8)

AppendBit appends one bit.

func (*Bits) AppendBytes

func (x *Bits) AppendBytes(b []byte)

AppendBytes appends every bit of b.

func (*Bits) AppendUint

func (x *Bits) AppendUint(v uint64, n int)

AppendUint appends the n low bits of v, most significant first.

func (Bits) Bit

func (x Bits) Bit(i int) uint8

Bit is bit i (0 or 1).

func (Bits) Bytes

func (x Bits) Bytes() []byte

Bytes returns the bits zero-extended to whole bytes (a copy).

func (Bits) Clone

func (x Bits) Clone() Bits

Clone copies x.

func (Bits) Equal

func (x Bits) Equal(y Bits) bool

Equal reports whether x and y hold the same bits.

func (Bits) Len

func (x Bits) Len() int

Len is the number of bits.

func (*Bits) Pad

func (x *Bits) Pad(word int) int

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).

func (Bits) Slice

func (x Bits) Slice(from, to int) Bits

Slice is bits [from, to) (a copy).

func (Bits) String

func (x Bits) String() string

String shows the bits as 0 and 1, for tests and logs.

func (Bits) UintAt

func (x Bits) UintAt(from, n int) uint64

UintAt reads n bits (up to 64) at bit offset from.

type Context

type Context struct {
	DevIID []byte
	AppIID []byte
}

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).

const (
	Up   Direction = "up"
	Down Direction = "dw"
	Bi   Direction = "bi"
)

Directions.

type Duration

type Duration time.Duration

Duration is a JSON duration: "12h", "30s" or a number of seconds.

func (Duration) D

func (d Duration) D() time.Duration

D is the duration.

func (Duration) MarshalJSON

func (d Duration) MarshalJSON() ([]byte, error)

MarshalJSON writes a duration string.

func (*Duration) UnmarshalJSON

func (d *Duration) UnmarshalJSON(b []byte) error

UnmarshalJSON reads "12h" or seconds.

type Field

type Field struct {
	FID   string
	Pos   int // occurrence, from 1
	Value Bits
}

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

func DecodeAtReceiver(r *Rule, msg Bits, word int) (*FragMsg, error)

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

func DecodeAtSender(r *Rule, msg Bits, word int) (*FragMsg, error)

DecodeAtSender reads a message a fragment sender gets: an ACK or a Receiver-Abort (RFC 8724 8.3.2, 8.3.5).

func (*FragMsg) Encode

func (m *FragMsg) Encode(word int) Bits

Encode writes the message with padding to the L2 Word (RFC 8724 8.3, clause 9).

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"`
	// contains filtered or unexported fields
}

FragParams are a fragmentation rule's parameters (RFC 8724 8.2.4, 8.4 and appendix D).

type LoRaWANFrame

type LoRaWANFrame struct {
	FPort   uint8
	Payload []byte
}

LoRaWANFrame is a SCHC Message as it travels on LoRaWAN: the FPort and the FRMPayload.

func ToLoRaWAN

func ToLoRaWAN(msg Bits) (LoRaWANFrame, error)

ToLoRaWAN splits a SCHC Message (8-bit RuleID first) into FPort and payload, padding with zeros to whole bytes (RFC 9011 5.1, 5.4).

type MsgKind

type MsgKind int

MsgKind is a SCHC F/R message type (RFC 8724 8.2.1, 8.3).

const (
	MsgFragment      MsgKind = iota // Regular SCHC Fragment (including All-0)
	MsgAll1                         // All-1 SCHC Fragment
	MsgAckReq                       // SCHC ACK REQ
	MsgSenderAbort                  // SCHC Sender-Abort
	MsgAck                          // SCHC ACK
	MsgReceiverAbort                // SCHC Receiver-Abort
)

Message types.

func (MsgKind) String

func (k MsgKind) String() string

String is the message type's short name, such as "ack-req".

type Packet

type Packet struct {
	Fields  []Field
	Payload []byte
}

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

func NewReceiver(r *Rule, word int, dtag uint32, maxBytes int, now time.Time) *Receiver

NewReceiver starts reassembly for a fragmentation rule and DTag. maxBytes bounds the reassembled packet (0: 4096).

func (*Receiver) Deadline

func (rv *Receiver) Deadline() time.Time

Deadline is when the inactivity timer expires.

func (*Receiver) Done

func (rv *Receiver) Done() bool

Done reports whether the packet was reassembled or the transfer ended.

func (*Receiver) Err

func (rv *Receiver) Err() error

Err is why reassembly failed.

func (*Receiver) Packet

func (rv *Receiver) Packet() (Bits, bool)

Packet is the reassembled SCHC Packet (with the padding bits of the fragment that carried the last tile, which decompression drops).

func (*Receiver) Receive

func (rv *Receiver) Receive(now time.Time, msg Bits) ([]Bits, error)

Receive handles a message; it returns the messages to send back.

func (*Receiver) Tick

func (rv *Receiver) Tick(now time.Time) []Bits

Tick runs the inactivity timer: on expiry reassembly ends (with a Receiver-Abort outside No-ACK). After success it just ends the clean-up.

type Rule

type Rule struct {
	ID       uint32 `json:"ruleId"`
	IDLength int    `json:"ruleIdLength,omitempty"` // bits, default 8
	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

func LoRaWANDownlinkRule(fport uint8, class string, pingSlot time.Duration) Rule

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

func LoRaWANMulticastRule(fport uint8) Rule

LoRaWANMulticastRule is the multicast downlink rule of RFC 9011 5.6.3: No-ACK, T=0, N=1.

func LoRaWANUplinkRule

func LoRaWANUplinkRule(fport uint8, tileBytes int, ackEveryWindow bool) Rule

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).

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

func ParseRuleSet(b []byte) (*RuleSet, error)

ParseRuleSet reads and checks a rule set from JSON.

func ParseYANG added in v0.2.0

func ParseYANG(b []byte) (*RuleSet, error)

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) ByID

func (rs *RuleSet) ByID(id uint32) *Rule

ByID returns the rule with an ID (of any length), or nil.

func (*RuleSet) Compile

func (rs *RuleSet) Compile() error

Compile fills in defaults and checks the rules; it must run before use.

func (*RuleSet) Compress

func (rs *RuleSet) Compress(st Stack, raw []byte, dir Direction, ctx Context) (Bits, *Rule, error)

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

func (rs *RuleSet) CompressPacket(p Packet, dir Direction, ctx Context) (Bits, *Rule, error)

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

func (rs *RuleSet) DecompressPacket(msg Bits, dir Direction, ctx Context) (Packet, *Rule, error)

DecompressPacket reads a SCHC Packet into labelled fields and payload without a stack (compute fields come back empty).

func (*RuleSet) Fragmentation

func (rs *RuleSet) Fragmentation(dir Direction) []*Rule

Fragmentation returns the fragmentation rules for a direction, in ID order.

func (*RuleSet) MarshalYANG added in v0.2.0

func (rs *RuleSet) MarshalYANG() ([]byte, error)

MarshalYANG writes the rule set as RFC 9363 instance data in RFC 7951 JSON. The rule set must be compiled (ParseRuleSet does it).

func (*RuleSet) YANG added in v0.2.0

func (rs *RuleSet) YANG() (*YANGDocument, error)

YANG converts the rule set to the RFC 9363 tree.

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

func NewSender(r *Rule, word int, dtag uint32, packet Bits) (*Sender, error)

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) Deadline

func (s *Sender) Deadline() time.Time

Deadline is when Tick next has work (the retransmission timer), or zero.

func (*Sender) Done

func (s *Sender) Done() bool

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).

func (*Sender) Err

func (s *Sender) Err() error

Err is why the transfer failed.

func (*Sender) Receive

func (s *Sender) Receive(now time.Time, msg Bits, mtu int) ([]Bits, error)

Receive handles an ACK or Receiver-Abort.

func (*Sender) Start

func (s *Sender) Start(now time.Time, mtu int) ([]Bits, error)

Start sends the first messages: every fragment in No-ACK, the first window otherwise.

func (*Sender) Tick

func (s *Sender) Tick(now time.Time) ([]Bits, error)

Tick runs the retransmission timer: an ACK REQ (ACK-Always) or the All-1 again (ACK-on-Error), up to MAX_ACK_REQUESTS, then a Sender-Abort.

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

func ParseStack(s string) (Stack, error)

ParseStack reads "ipv6/udp/coap", "coap", "coap-inner", "ipv6/udp/wrapper", "wrapper", "ipv6/udp", "ipv6/icmpv6", "none" or "".

func (Stack) Build

func (st Stack) Build(vals map[string]Bits, payload []byte, dir Direction) ([]byte, error)

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

func (st Stack) BuildFields(fields []Field, payload []byte, dir Direction) ([]byte, error)

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.

func (Stack) Parse

func (st Stack) Parse(raw []byte, dir Direction) (Packet, error)

Parse labels a packet's header fields. dir tells the Dev end from the App end (source is the Dev going up).

func (Stack) String

func (st Stack) String() string

String is the stack as ParseStack reads it.

type WindowBitmap added in v0.2.0

type WindowBitmap struct {
	W      uint32
	Bitmap []bool
}

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.

type YANGTimer added in v0.2.0

type YANGTimer struct {
	TicksDuration *uint8  `json:"ticks-duration,omitempty"`
	TicksNumbers  *uint16 `json:"ticks-numbers,omitempty"`
}

YANGTimer is a timer in ticks of 2^TicksDuration microseconds.

type YANGValue added in v0.2.0

type YANGValue struct {
	Index uint16 `json:"index"`
	Value []byte `json:"value"`
}

YANGValue is a tv-struct: an index and a binary value (base64 in JSON).

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).

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL