A Discrete-Event Network Simulator
API
Loading...
Searching...
No Matches
sixlowpan-ghc.cc
Go to the documentation of this file.
1/*
2 * Copyright (c) 2026 SRM Institute of Science and Technology
3 *
4 * SPDX-License-Identifier: GPL-2.0-only
5 *
6 * Author: Usham Roy <ushamroy80@gmail.com>
7 *
8 * 6LoWPAN-GHC: Generic Header Compression - RFC 7400
9 *
10 * Source: original implementation following RFC 7400 (Bormann, November 2014).
11 */
12
13#include "sixlowpan-ghc.h"
14
15#include "ns3/abort.h"
16#include "ns3/assert.h"
17#include "ns3/log.h"
18
19#include <algorithm>
20#include <array>
21#include <cstring>
22#include <vector>
23
24namespace ns3
25{
26
27NS_LOG_COMPONENT_DEFINE("SixLowPanGhc");
28
29// ============================================================================
30// GHC Compression/Decompression Engine
31// ============================================================================
32
33void
35 const Ipv6Address& srcAddr,
36 const Ipv6Address& dstAddr)
37{
38 // Bytes 0-15: Source IPv6 address
39 srcAddr.GetBytes(dict);
40
41 // Bytes 16-31: Destination IPv6 address
42 dstAddr.GetBytes(dict + 16);
43
44 // Bytes 32-47: static dictionary (RFC 7400 Section 3.1)
45 static constexpr std::array<uint8_t, 16> staticDict = {0x16,
46 0xfe,
47 0xfd,
48 0x17,
49 0xfe,
50 0xfd,
51 0x00,
52 0x01,
53 0x00,
54 0x00,
55 0x00,
56 0x00,
57 0x00,
58 0x01,
59 0x00,
60 0x00};
61 std::copy(staticDict.begin(), staticDict.end(), dict + 32);
62}
63
66{
67 if ((byte & 0x80) == 0)
68 {
69 // 0kkkkkkk - Literal copy
71 }
72 else if ((byte & 0xF0) == 0x80)
73 {
74 // 1000nnnn - Zero insertion: emits nnnn+2 zero bytes (RFC 7400 Section 3).
76 }
77 else if (byte == 0x90)
78 {
79 // 10010000 - Stop code
81 }
82 else if ((byte & 0xE0) == 0xA0)
83 {
84 // 101nssss - Extended arguments
86 }
87 else if ((byte & 0xC0) == 0xC0)
88 {
89 // 11nnnkkk - Backreference
91 }
92 else
93 {
94 // 1001nnnn (nnnn > 0) and 011xxxxx - Reserved per RFC 7400 Section 3.
96 }
97}
98
101 const Ipv6Address& dstAddr,
102 const uint8_t* compressed,
103 uint32_t compressedLen,
104 uint8_t* output,
105 uint32_t outputMaxLen,
106 bool useStopCode)
107{
108 NS_LOG_FUNCTION(srcAddr << dstAddr << compressedLen << outputMaxLen << useStopCode);
109
110 // Working buffer: dictionary followed by the decompressed output.
111 // Sized from the caller's limit so any link MTU is supported.
112 const uint32_t bufferSize = DICTIONARY_SIZE + outputMaxLen;
113 std::vector<uint8_t> buffer(bufferSize);
114
115 // Initialize dictionary in buffer[0..47]
116 InitDictionary(buffer.data(), srcAddr, dstAddr);
117
118 uint32_t outputPos = DICTIONARY_SIZE; // Current write position in buffer
119 uint32_t inputPos = 0; // Current read position in compressed
120 uint32_t sa = 0; // Start adjust accumulator
121 uint32_t na = 0; // Number adjust accumulator
122 bool stopCodeFound = false;
123
124 while (inputPos < compressedLen && !stopCodeFound)
125 {
126 uint8_t codeByte = compressed[inputPos++];
127 GhcBytecodeType type = ClassifyBytecode(codeByte);
128
129 switch (type)
130 {
132 // 0kkkkkkk: copy k literal bytes from bytecode stream
133 uint32_t k = codeByte & 0x7F;
134
135 if (k == 0)
136 {
137 // No-op
138 break;
139 }
140 if (k > MAX_LITERAL_RUN)
141 {
142 NS_LOG_WARN("GHC: Literal count k=" << k << " is reserved");
143 return 0;
144 }
145 if (inputPos + k > compressedLen)
146 {
147 NS_LOG_WARN("GHC: Literal overruns compressed data");
148 return 0;
149 }
150 if (outputPos + k > bufferSize)
151 {
152 NS_LOG_WARN("GHC: Literal would exceed buffer");
153 return 0;
154 }
155
156 std::memcpy(buffer.data() + outputPos, compressed + inputPos, k);
157 outputPos += k;
158 inputPos += k;
159 break;
160 }
161
163 // 1000nnnn: insert (n+2) zero bytes
164 uint32_t n = (codeByte & 0x0F) + 2;
165
166 if (outputPos + n > bufferSize)
167 {
168 NS_LOG_WARN("GHC: Zero insert would exceed buffer");
169 return 0;
170 }
171
172 std::memset(buffer.data() + outputPos, 0, n);
173 outputPos += n;
174 break;
175 }
176
178 // 10010000: terminate decompression (extension headers only)
179 if (!useStopCode)
180 {
181 NS_LOG_WARN("GHC: Unexpected stop code in non-extension context");
182 return 0;
183 }
184 NS_LOG_DEBUG("GHC: Stop code encountered");
185 stopCodeFound = true;
186 break;
187 }
188
190 // 101nssss: sa += ssss << 3, na += n << 3
191 // bit layout: 101[n][ssss]
192 // n = bit 4 (one bit)
193 // ssss = bits 0-3
194 uint32_t ssss = codeByte & 0x0F;
195 uint32_t nBit = (codeByte >> 4) & 0x01;
196
197 sa += (ssss << 3);
198 na += (nBit << 3);
199
200 NS_LOG_DEBUG("GHC: ExtArgs sa=" << sa << " na=" << na);
201 break;
202 }
203
205 // 11nnnkkk: copy n bytes from s bytes back
206 // n = na + (nnn) + 2
207 // s = (kkk) + sa + n
208 uint32_t nnn = (codeByte >> 3) & 0x07;
209 uint32_t kkk = codeByte & 0x07;
210
211 uint32_t copyLen = na + nnn + 2;
212 uint32_t offset = kkk + sa + copyLen;
213
214 // Reset extended arg accumulators
215 sa = 0;
216 na = 0;
217
218 if (offset > outputPos)
219 {
220 NS_LOG_WARN("GHC: Backref offset " << offset << " exceeds buffer position "
221 << outputPos);
222 return 0;
223 }
224 if (outputPos + copyLen > bufferSize)
225 {
226 NS_LOG_WARN("GHC: Backref would exceed buffer");
227 return 0;
228 }
229
230 // Copy byte-by-byte (overlapping copies are valid in LZ77)
231 uint32_t srcPos = outputPos - offset;
232 for (uint32_t i = 0; i < copyLen; i++)
233 {
234 buffer[outputPos + i] = buffer[srcPos + i];
235 }
236 outputPos += copyLen;
237 break;
238 }
239
241 NS_LOG_WARN("GHC: Reserved bytecode 0x" << std::hex << +codeByte);
242 return 0;
243 }
244 }
245
246 // Output is everything after the dictionary. The per-bytecode buffer
247 // checks above already guarantee decompressedLen <= outputMaxLen.
248 uint32_t decompressedLen = outputPos - DICTIONARY_SIZE;
249
250 std::memcpy(output, buffer.data() + DICTIONARY_SIZE, decompressedLen);
251
252 NS_LOG_DEBUG("GHC: Decompressed " << compressedLen << " bytes to " << decompressedLen
253 << " bytes");
254
255 return decompressedLen;
256}
257
259SixLowPanGhcEngine::CountZeros(const uint8_t* input, uint32_t remaining)
260{
261 uint32_t count = 0;
262 while (count < remaining && input[count] == 0)
263 {
264 count++;
265 }
266 return count;
267}
268
271{
272 // Backref encoding 11nnnkkk: n = na + nnn + 2, s = kkk + sa + n, with
273 // nnn and kkk in [0,7]. Work out the extended-args accumulators needed,
274 // rounded up to their unit of 8 (see EmitBackref).
275 uint32_t nBase = matchLength - 2;
276 uint32_t kBase = matchOffset - matchLength;
277
278 uint32_t na = (nBase > 7) ? ((nBase - 7 + 7) / 8) * 8 : 0;
279 uint32_t sa = (kBase > 7) ? ((kBase - 7 + 7) / 8) * 8 : 0;
280
281 // Each 101nssss byte carries up to ssss(15)*8 = 120 of sa and 8 of na.
282 uint32_t bytes = 0;
283 while (sa > 0 || na > 0)
284 {
285 bytes++;
286 sa -= std::min<uint32_t>(sa, 15 * 8);
287 na -= std::min<uint32_t>(na, 8);
288 }
289 return bytes;
290}
291
292bool
294 uint32_t bufLen,
295 const uint8_t* input,
296 uint32_t inputRemaining,
297 uint32_t& matchOffset,
298 uint32_t& matchLength)
299{
300 matchOffset = 0;
301 matchLength = 0;
302
303 // Simple exhaustive (brute-force) LZ77 search: for every backward distance
304 // we compare against the input and keep the longest match. GHC operates on
305 // header-scale data, so the O(window * matchLen) cost is negligible and
306 // no hash chains or suffix structures are needed.
307
308 uint32_t maxMatchLen = std::min<uint32_t>(inputRemaining, MAX_BACKREF_LEN);
309
310 // Search the whole buffer: extended-args bytes let a backref address any
311 // offset (each one adds up to 120), so the dictionary at the start of the
312 // buffer stays reachable even for long payloads. The cost check below
313 // rejects matches whose extended-args overhead would exceed the bytes
314 // they save.
315 for (uint32_t back = 2; back <= bufLen; back++)
316 {
317 uint32_t searchPos = bufLen - back;
318 uint32_t len = 0;
319
320 while (len < maxMatchLen && buffer[searchPos + len] == input[len])
321 {
322 len++;
323 }
324
325 // The encoding requires offset >= length; clamp overlapping matches
326 // to what can actually be emitted.
327 len = std::min(len, back);
328
329 if (len < 2 || len <= matchLength)
330 {
331 continue;
332 }
333
334 // Emit a backref only when it is no larger than the literal bytes
335 // it replaces: 1 opcode byte + extended-args bytes vs len bytes.
336 if (1 + CountBackrefExtArgBytes(len, back) > len)
337 {
338 continue;
339 }
340
341 matchLength = len;
342 matchOffset = back;
343
344 if (matchLength == maxMatchLen)
345 {
346 break; // Can't do better
347 }
348 }
349
350 return (matchLength >= 2);
351}
352
353bool
355 uint32_t& outPos,
356 uint32_t outputMaxLen,
357 uint32_t matchLength,
358 uint32_t matchOffset)
359{
360 NS_ASSERT(matchLength >= 2);
361 // GHC bytecode 11nnnkkk requires offset >= length;
362 // caller (Compress) clamps overlapping matches before calling us.
363
364 // Backref encoding: 11nnnkkk
365 // n = na + nnn + 2 => nnn = n - na - 2
366 // s = kkk + sa + n => kkk = s - sa - n (where s = matchOffset)
367 //
368 // We need: nnn in [0,7], kkk in [0,7]
369 // If they don't fit, we need Extended Args (101nssss) to add to sa/na.
370
371 uint32_t n = matchLength; // Total copy length
372 uint32_t s = matchOffset; // Total offset
373
374 // Determine how much sa and na we need
375 // nnn = n - na - 2, must be in [0,7] => na = n - 2 - nnn
376 // kkk = s - sa - n, must be in [0,7] => sa = s - n - kkk
377
378 // First try without extended args
379 uint32_t nBase = n - 2; // Need nnn = nBase - na
380 uint32_t kBase = s - n; // Need kkk = kBase - sa
381
382 uint32_t na = 0;
383 uint32_t sa = 0;
384
385 // Calculate required na (to make nnn fit in [0,7])
386 if (nBase > 7)
387 {
388 na = nBase - 7; // Minimum na to make nnn <= 7
389 // na must be a multiple of 8 (since extended args add in units of 8)
390 na = ((na + 7) / 8) * 8;
391 }
392
393 // Calculate required sa (to make kkk fit in [0,7])
394 if (kBase > 7)
395 {
396 sa = kBase - 7;
397 sa = ((sa + 7) / 8) * 8;
398 }
399
400 // Verify encoding is feasible
401 uint32_t nnn = nBase - na;
402 uint32_t kkk = kBase - sa;
403
404 if (nnn > 7 || kkk > 7)
405 {
406 NS_LOG_WARN("GHC: Cannot encode backref len=" << n << " offset=" << s);
407 return false;
408 }
409
410 // Check output space: extended-args bytes + 1 (backref byte)
411 uint32_t extArgBytes = CountBackrefExtArgBytes(matchLength, matchOffset);
412 if (outPos + extArgBytes + 1 > outputMaxLen)
413 {
414 return false;
415 }
416
417 // Emit extended args
418 uint32_t remainingSa = sa;
419 uint32_t remainingNa = na;
420
421 while (remainingSa > 0 || remainingNa > 0)
422 {
423 // Extended arg: 101[n][ssss]
424 // adds ssss*8 to sa, n*8 to na
425 uint32_t ssss = std::min<uint32_t>(remainingSa / 8, 15);
426 uint32_t nBit = (remainingNa >= 8) ? 1 : 0;
427
428 uint8_t extByte = 0xA0 | (nBit << 4) | (ssss & 0x0F);
429 output[outPos++] = extByte;
430
431 remainingSa -= ssss * 8;
432 if (nBit)
433 {
434 remainingNa -= 8;
435 }
436 }
437
438 // Emit backref: 11nnnkkk
439 uint8_t backrefByte = 0xC0 | ((nnn & 0x07) << 3) | (kkk & 0x07);
440 output[outPos++] = backrefByte;
441
442 return true;
443}
444
447 const Ipv6Address& dstAddr,
448 const uint8_t* input,
449 uint32_t inputLen,
450 uint8_t* output,
451 uint32_t outputMaxLen,
452 bool emitStopCode)
453{
454 NS_LOG_FUNCTION(srcAddr << dstAddr << inputLen << outputMaxLen << emitStopCode);
455
456 if (inputLen == 0)
457 {
458 return 0;
459 }
460
461 // Working buffer: dictionary followed by the input bytes consumed so far
462 // (bufPos advances in lockstep with inPos, so this size is exact).
463 std::vector<uint8_t> buffer(DICTIONARY_SIZE + inputLen);
464 InitDictionary(buffer.data(), srcAddr, dstAddr);
465
466 uint32_t bufPos = DICTIONARY_SIZE; // Next write position in buffer
467 uint32_t inPos = 0; // Current position in input
468 uint32_t outPos = 0; // Current position in output
469
470 // Accumulate literal bytes to emit as a group
471 std::vector<uint8_t> literalBuf;
472
473 // Lambda to flush accumulated literals
474 auto flushLiterals = [&]() -> bool {
475 while (!literalBuf.empty())
476 {
477 uint32_t chunk = std::min<uint32_t>(literalBuf.size(), MAX_LITERAL_RUN);
478
479 // Need 1 byte (count) + chunk bytes (data)
480 if (outPos + 1 + chunk > outputMaxLen)
481 {
482 return false;
483 }
484
485 output[outPos++] = static_cast<uint8_t>(chunk); // 0kkkkkkk where k < 96
486 std::memcpy(output + outPos, literalBuf.data(), chunk);
487 outPos += chunk;
488
489 literalBuf.erase(literalBuf.begin(), literalBuf.begin() + chunk);
490 }
491 return true;
492 };
493
494 while (inPos < inputLen)
495 {
496 // Evaluate both ZERO_INSERT and BACKREF at this position and pick the
497 // one that consumes more input bytes. A backref that covers the zero
498 // run PLUS following non-zero bytes (e.g., matching the "00 00 00 00
499 // 01" pattern in the static dictionary) is strictly better than a
500 // zero-insert that stops at the zero prefix, because it consumes the
501 // trailing bytes in the same opcode budget instead of forcing them
502 // into a separate literal run. This is the case flagged by Tommaso
503 // Pecorella on MR !2802 for Fig.13 (suboptimal "82 03 01" vs optimal
504 // "de 02").
505 uint32_t zeros = CountZeros(input + inPos, inputLen - inPos);
506
507 uint32_t matchOffset = 0;
508 uint32_t matchLength = 0;
509 bool haveMatch = FindLongestMatch(buffer.data(),
510 bufPos,
511 input + inPos,
512 inputLen - inPos,
513 matchOffset,
514 matchLength);
515
516 // Prefer BACKREF if it strictly covers more input than ZERO_INSERT
517 // (or if no zero run is available). Ties go to ZERO_INSERT since its
518 // encoding is simpler (no offset math, no extended args).
519 const bool preferBackref = haveMatch && (zeros < 2 || matchLength > zeros);
520
521 if (preferBackref)
522 {
523 if (!flushLiterals())
524 {
525 return 0;
526 }
527
528 uint32_t savedOutPos = outPos;
529 if (EmitBackref(output, outPos, outputMaxLen, matchLength, matchOffset))
530 {
531 // Advance buffer with matched data
532 std::memcpy(buffer.data() + bufPos, input + inPos, matchLength);
533 bufPos += matchLength;
534 inPos += matchLength;
535 continue;
536 }
537 // Backref encoding failed (e.g., offset too large even with
538 // extended args); rewind and fall back to zero-insert or literal.
539 outPos = savedOutPos;
540 }
541
542 if (zeros >= 2)
543 {
544 if (!flushLiterals())
545 {
546 return 0;
547 }
548
549 // Emit zero insertion instructions
550 while (zeros >= 2)
551 {
552 uint32_t emit = std::min<uint32_t>(zeros, MAX_ZERO_RUN);
553 if (outPos + 1 > outputMaxLen)
554 {
555 return 0;
556 }
557
558 // 1000nnnn where n = emit - 2
559 output[outPos++] = 0x80 | ((emit - 2) & 0x0F);
560
561 // Also advance the buffer (for future backreferences)
562 std::memset(buffer.data() + bufPos, 0, emit);
563 bufPos += emit;
564 inPos += emit;
565 zeros -= emit;
566 }
567 continue;
568 }
569
570 // Strategy 3: Accumulate as literal
571 literalBuf.push_back(input[inPos]);
572 buffer[bufPos++] = input[inPos];
573 inPos++;
574 }
575
576 // Flush remaining literals
577 if (!flushLiterals())
578 {
579 return 0;
580 }
581
582 // Emit stop code if requested (for extension headers)
583 if (emitStopCode)
584 {
585 if (outPos + 1 > outputMaxLen)
586 {
587 return 0;
588 }
589 output[outPos++] = 0x90; // Stop code
590 }
591
592 // Only return compressed data if it's actually smaller
593 uint32_t overhead = emitStopCode ? 1 : 0;
594 if (outPos >= inputLen + overhead)
595 {
596 NS_LOG_DEBUG("GHC: No compression benefit (" << outPos << " >= " << inputLen << ")");
597 return 0; // No compression benefit
598 }
599
600 NS_LOG_DEBUG("GHC: Compressed " << inputLen << " bytes to " << outPos << " bytes (ratio "
601 << static_cast<float>(inputLen) / outPos << "x)");
602
603 return outPos;
604}
605
606// ============================================================================
607// SixLowPanGhcExtension Implementation
608// ============================================================================
609
611
614 m_nextHeader(0),
615 m_blobLength(0)
616{
617 std::memset(m_blob, 0, sizeof(m_blob));
618}
619
620TypeId
622{
623 static TypeId tid = TypeId("ns3::SixLowPanGhcExtension")
624 .SetParent<Header>()
625 .SetGroupName("SixLowPan")
626 .AddConstructor<SixLowPanGhcExtension>();
627 return tid;
628}
629
630TypeId
635
636void
637SixLowPanGhcExtension::Print(std::ostream& os) const
638{
639 os << "GHC Ext Header: EID=" << GetEid() << " NH=" << GetNh() << " blob[" << +m_blobLength
640 << "]";
641}
642
645{
646 // 1 byte NHC + optional 1 byte Next Header + blob length
647 uint32_t size = 1; // NHC byte
648 if (!GetNh())
649 {
650 size += 1; // Next header inline
651 }
652 size += m_blobLength;
653 return size;
654}
655
656void
658{
659 start.WriteU8(m_nhcByte);
660 if (!GetNh())
661 {
662 start.WriteU8(m_nextHeader);
663 }
664 start.Write(m_blob, m_blobLength);
665}
666
669{
670 m_nhcByte = start.ReadU8();
671 if (!GetNh())
672 {
673 m_nextHeader = start.ReadU8();
674 }
675
676 // For GHC extension headers, we need to scan for Stop Code to find blob end.
677 // The deserializer must read bytecodes until Stop Code is found.
678 m_blobLength = 0;
679 while (start.GetRemainingSize() > 0 && m_blobLength < 255)
680 {
681 uint8_t byte = start.ReadU8();
682 m_blob[m_blobLength++] = byte;
683
684 if (byte == 0x90) // Stop code
685 {
686 break;
687 }
688
689 // If it's a literal (0kkkkkkk), skip k bytes
690 if ((byte & 0x80) == 0)
691 {
692 uint32_t k = byte & 0x7F;
693 for (uint32_t i = 0; i < k && start.GetRemainingSize() > 0 && m_blobLength < 255; i++)
694 {
695 m_blob[m_blobLength++] = start.ReadU8();
696 }
697 }
698 }
699
700 return GetSerializedSize();
701}
702
708
709void
711{
712 m_nhcByte = GHC_EXT_BASE | ((static_cast<uint8_t>(eid) & 0x07) << 1) | (m_nhcByte & NH_MASK);
713}
714
717{
718 return static_cast<Eid_e>((m_nhcByte & EID_MASK) >> 1);
719}
720
721void
723{
724 m_nextHeader = nextHeader;
725}
726
727uint8_t
732
733void
735{
736 if (nhField)
737 {
739 }
740 else
741 {
743 }
744}
745
746bool
748{
749 return (m_nhcByte & NH_MASK) != 0;
750}
751
752void
753SixLowPanGhcExtension::SetBlob(const uint8_t* blob, uint32_t size)
754{
755 NS_ASSERT(size <= MAX_BLOB_SIZE);
756 m_blobLength = size;
757 std::memcpy(m_blob, blob, size);
758}
759
762{
763 uint32_t copyLen = std::min<uint32_t>(m_blobLength, size);
764 std::memcpy(blob, m_blob, copyLen);
765 return copyLen;
766}
767
773
774std::ostream&
775operator<<(std::ostream& os, const SixLowPanGhcExtension& header)
776{
777 header.Print(os);
778 return os;
779}
780
781// ============================================================================
782// SixLowPanGhcUdp Implementation
783// ============================================================================
784
785NS_OBJECT_ENSURE_REGISTERED(SixLowPanGhcUdp);
786
794
795TypeId
797{
798 static TypeId tid = TypeId("ns3::SixLowPanGhcUdp")
799 .SetParent<Header>()
800 .SetGroupName("SixLowPan")
801 .AddConstructor<SixLowPanGhcUdp>();
802 return tid;
803}
804
805TypeId
807{
808 return GetTypeId();
809}
810
811void
812SixLowPanGhcUdp::Print(std::ostream& os) const
813{
814 os << "GHC UDP: src=" << m_srcPort << " dst=" << m_dstPort << " C=" << GetC()
815 << " P=" << GetPorts();
816}
817
820{
821 uint32_t size = 1; // NHC byte
822
823 switch (GetPorts())
824 {
825 case PORTS_INLINE:
826 size += 4; // 2 + 2
827 break;
830 size += 3; // 2 + 1 or 1 + 2
831 break;
833 size += 1; // 4-bit + 4-bit packed
834 break;
835 }
836
837 if (!GetC())
838 {
839 size += 2; // Checksum inline
840 }
841
842 return size;
843}
844
845void
847{
848 start.WriteU8(m_baseFormat);
849
850 switch (GetPorts())
851 {
852 case PORTS_INLINE:
853 start.WriteHtonU16(m_srcPort);
854 start.WriteHtonU16(m_dstPort);
855 break;
857 start.WriteHtonU16(m_srcPort);
858 start.WriteU8(m_dstPort & 0xFF);
859 break;
861 start.WriteU8(m_srcPort & 0xFF);
862 start.WriteHtonU16(m_dstPort);
863 break;
865 start.WriteU8(((m_srcPort & 0x0F) << 4) | (m_dstPort & 0x0F));
866 break;
867 }
868
869 if (!GetC())
870 {
871 start.WriteHtonU16(m_checksum);
872 }
873}
874
877{
878 m_baseFormat = start.ReadU8();
879
880 switch (GetPorts())
881 {
882 case PORTS_INLINE:
883 m_srcPort = start.ReadNtohU16();
884 m_dstPort = start.ReadNtohU16();
885 break;
887 m_srcPort = start.ReadNtohU16();
888 m_dstPort = 0xF000 | start.ReadU8();
889 break;
891 m_srcPort = 0xF000 | start.ReadU8();
892 m_dstPort = start.ReadNtohU16();
893 break;
895 uint8_t packed = start.ReadU8();
896 m_srcPort = 0xF0B0 | ((packed >> 4) & 0x0F);
897 m_dstPort = 0xF0B0 | (packed & 0x0F);
898 break;
899 }
900 }
901
902 if (!GetC())
903 {
904 m_checksum = start.ReadNtohU16();
905 }
906
907 return GetSerializedSize();
908}
909
915
916void
921
924{
925 return static_cast<Ports_e>(m_baseFormat & P_MASK);
926}
927
928void
933
934uint16_t
936{
937 return m_srcPort;
938}
939
940void
945
946uint16_t
948{
949 return m_dstPort;
950}
951
952void
954{
955 if (cField)
956 {
958 }
959 else
960 {
962 }
963}
964
965bool
967{
968 return (m_baseFormat & C_MASK) != 0;
969}
970
971void
973{
974 m_checksum = checksum;
975}
976
977uint16_t
979{
980 return m_checksum;
981}
982
983std::ostream&
984operator<<(std::ostream& os, const SixLowPanGhcUdp& header)
985{
986 header.Print(os);
987 return os;
988}
989
990// ============================================================================
991// SixLowPanGhcIcmpv6 Implementation
992// ============================================================================
993
994NS_OBJECT_ENSURE_REGISTERED(SixLowPanGhcIcmpv6);
995
997 : m_blobLength(0)
998{
999 std::memset(m_blob, 0, sizeof(m_blob));
1000}
1001
1002TypeId
1004{
1005 static TypeId tid = TypeId("ns3::SixLowPanGhcIcmpv6")
1006 .SetParent<Header>()
1007 .SetGroupName("SixLowPan")
1008 .AddConstructor<SixLowPanGhcIcmpv6>();
1009 return tid;
1010}
1011
1012TypeId
1014{
1015 return GetTypeId();
1016}
1017
1018void
1019SixLowPanGhcIcmpv6::Print(std::ostream& os) const
1020{
1021 os << "GHC ICMPv6: blob[" << +m_blobLength << "]";
1022}
1023
1026{
1027 return 1 + m_blobLength; // NHC byte + compressed ICMPv6 body
1028}
1029
1030void
1032{
1033 start.WriteU8(GHC_ICMPV6_NHC);
1034 start.Write(m_blob, m_blobLength);
1035}
1036
1039{
1040 NS_FATAL_ERROR("The two-iterator Deserialize must be used for this variable-sized header");
1041 return 0;
1042}
1043
1046{
1047 uint8_t nhc = start.ReadU8();
1048 NS_ASSERT(nhc == GHC_ICMPV6_NHC);
1049
1050 // The wire format has no length field: the bytecode blob runs to the
1051 // end of the packet (RFC 7400 Section 3), which the caller passes as
1052 // the end iterator.
1053 uint32_t blobLen = start.GetDistanceFrom(end);
1054 NS_ASSERT(blobLen <= MAX_BLOB_SIZE);
1055 m_blobLength = static_cast<uint8_t>(blobLen);
1056 start.Read(m_blob, m_blobLength);
1057
1058 return GetSerializedSize();
1059}
1060
1066
1067void
1068SixLowPanGhcIcmpv6::SetBlob(const uint8_t* blob, uint32_t size)
1069{
1070 NS_ASSERT(size <= MAX_BLOB_SIZE);
1071 m_blobLength = size;
1072 std::memcpy(m_blob, blob, size);
1073}
1074
1076SixLowPanGhcIcmpv6::CopyBlob(uint8_t* blob, uint32_t size) const
1077{
1078 uint32_t copyLen = std::min<uint32_t>(m_blobLength, size);
1079 std::memcpy(blob, m_blob, copyLen);
1080 return copyLen;
1081}
1082
1085{
1086 return m_blobLength;
1087}
1088
1089std::ostream&
1090operator<<(std::ostream& os, const SixLowPanGhcIcmpv6& header)
1091{
1092 header.Print(os);
1093 return os;
1094}
1095
1096// ============================================================================
1097// SixLowPan6Cio Implementation
1098// ============================================================================
1099
1100NS_OBJECT_ENSURE_REGISTERED(SixLowPan6Cio);
1101
1106
1107TypeId
1109{
1110 static TypeId tid = TypeId("ns3::SixLowPan6Cio")
1111 .SetParent<Header>()
1112 .SetGroupName("SixLowPan")
1113 .AddConstructor<SixLowPan6Cio>();
1114 return tid;
1115}
1116
1117TypeId
1119{
1120 return GetTypeId();
1121}
1122
1123void
1124SixLowPan6Cio::Print(std::ostream& os) const
1125{
1126 os << "6CIO: GHC=" << GetGhcCapable() << " flags=0x" << std::hex << m_flags << std::dec;
1127}
1128
1131{
1132 // Type(1) + Length(1) + Flags(4 bytes = 32 bits)
1133 // Length field = 1 (in 8-octet units) => total 8 bytes
1134 // But we use minimum 6 bytes (Type + Len + 4 flag bytes)
1135 return 8; // Padded to 8-octet boundary per ND option rules
1136}
1137
1138void
1140{
1141 start.WriteU8(SIXLOWPAN_6CIO_TYPE);
1142 start.WriteU8(SIXLOWPAN_6CIO_LEN);
1143 start.WriteHtonU32(m_flags);
1144 start.WriteU16(0); // Padding to 8-byte boundary
1145}
1146
1149{
1150 uint8_t type = start.ReadU8();
1152 uint8_t len = start.ReadU8();
1153 m_flags = start.ReadNtohU32();
1154
1155 // Skip remaining bytes based on length field
1156 uint32_t remaining = (len * 8) - 6; // Total - (type + len + 4 flag bytes)
1157 for (uint32_t i = 0; i < remaining; i++)
1158 {
1159 start.ReadU8();
1160 }
1161
1162 return len * 8;
1163}
1164
1165void
1167{
1168 if (ghcCapable)
1169 {
1171 }
1172 else
1173 {
1175 }
1176}
1177
1178bool
1180{
1181 return (m_flags & GHC_FLAG_BIT) != 0;
1182}
1183
1184std::ostream&
1185operator<<(std::ostream& os, const SixLowPan6Cio& header)
1186{
1187 header.Print(os);
1188 return os;
1189}
1190
1191} // namespace ns3
iterator in a Buffer instance
Definition buffer.h:109
Protocol header serialization and deserialization.
Definition header.h:36
Describes an IPv6 address.
void GetBytes(uint8_t buf[ADDRESS_LENGTH]) const
Get the bytes corresponding to the address.
6LoWPAN Capability Indication Option (6CIO) - RFC 7400 Section 6.
static constexpr uint8_t SIXLOWPAN_6CIO_TYPE
ND Option Type.
uint32_t GetSerializedSize() const override
void Serialize(Buffer::Iterator start) const override
TypeId GetInstanceTypeId() const override
Get the most derived TypeId for this Object.
static TypeId GetTypeId()
Get the type ID.
void Print(std::ostream &os) const override
static constexpr uint8_t SIXLOWPAN_6CIO_LEN
Length in 8-octet units.
void SetGhcCapable(bool ghcCapable)
Set the GHC capability flag.
bool GetGhcCapable() const
Get the GHC capability flag.
uint32_t Deserialize(Buffer::Iterator start) override
static constexpr uint32_t GHC_FLAG_BIT
G bit position.
uint32_t m_flags
Flags field (variable, up to 48 bits per RFC).
NhcDispatch_e
Dispatch values for Next Header compression.
static uint32_t Decompress(const Ipv6Address &srcAddr, const Ipv6Address &dstAddr, const uint8_t *compressed, uint32_t compressedLen, uint8_t *output, uint32_t outputMaxLen, bool useStopCode=false)
Decompress a GHC-compressed byte stream.
static uint32_t CountBackrefExtArgBytes(uint32_t matchLength, uint32_t matchOffset)
Count the extended-args bytes a backreference encoding needs.
static GhcBytecodeType ClassifyBytecode(uint8_t byte)
Classify a GHC bytecode instruction.
static uint32_t CountZeros(const uint8_t *input, uint32_t remaining)
Count consecutive zero bytes in input.
static void InitDictionary(uint8_t *dict, const Ipv6Address &srcAddr, const Ipv6Address &dstAddr)
Initialize the 48-byte decompression dictionary.
static uint32_t Compress(const Ipv6Address &srcAddr, const Ipv6Address &dstAddr, const uint8_t *input, uint32_t inputLen, uint8_t *output, uint32_t outputMaxLen, bool emitStopCode=false)
Compress a byte stream using the GHC LZ77 algorithm.
static constexpr uint32_t MAX_LITERAL_RUN
Maximum bytes copied by one 0kkkkkkk literal bytecode.
static constexpr uint32_t MAX_BACKREF_LEN
Maximum copy length of one 11nnnkkk backreference.
static bool EmitBackref(uint8_t *output, uint32_t &outPos, uint32_t outputMaxLen, uint32_t matchLength, uint32_t matchOffset)
Emit a backreference bytecode (with optional extended args).
static constexpr uint32_t MAX_ZERO_RUN
Maximum zeros inserted by one 1000nnnn bytecode: n+2 with n <= 15.
static constexpr uint32_t DICTIONARY_SIZE
Predefined dictionary size (48 bytes).
static bool FindLongestMatch(const uint8_t *buffer, uint32_t bufLen, const uint8_t *input, uint32_t inputRemaining, uint32_t &matchOffset, uint32_t &matchLength)
Find the longest match in the buffer for LZ77 compression.
GHC NHC Extension Header - see RFC 7400 Section 5.
uint8_t m_nhcByte
NHC header byte: 1011EID[NH].
void Serialize(Buffer::Iterator start) const override
static constexpr uint32_t MAX_BLOB_SIZE
Maximum blob size: the blob length field is 8 bits.
static constexpr uint8_t GHC_EXT_BASE
Base NHC byte pattern for GHC extension: 10110000 = 0xB0.
uint8_t m_blobLength
Length of GHC compressed data.
Eid_e GetEid() const
Get the Extension Header Type.
static TypeId GetTypeId()
Get the type ID.
bool GetNh() const
Get the NH field.
uint8_t GetNextHeader() const
Get the Next Header field value.
uint32_t GetSerializedSize() const override
void SetNh(bool nhField)
Set the NH field (next header compressed flag).
static constexpr uint8_t EID_MASK
Mask for EID field extraction (bits 1-3).
uint8_t m_blob[MAX_BLOB_SIZE+1]
GHC compressed bytecodes.
Eid_e
Extension Header ID (same encoding as RFC 6282).
uint32_t CopyBlob(uint8_t *blob, uint32_t size) const
Copy the GHC-compressed bytecode blob.
void Print(std::ostream &os) const override
TypeId GetInstanceTypeId() const override
Get the most derived TypeId for this Object.
SixLowPanDispatch::NhcDispatch_e GetNhcDispatchType() const
Get the NhcDispatch type.
void SetBlob(const uint8_t *blob, uint32_t size)
Set the GHC-compressed bytecode blob.
uint32_t Deserialize(Buffer::Iterator start) override
void SetEid(Eid_e eid)
Set the Extension Header Type.
uint8_t m_nextHeader
Next Header value (if NH=0).
void SetNextHeader(uint8_t nextHeader)
Set the Next Header field value.
static constexpr uint8_t NH_MASK
Mask for NH flag extraction (bit 0).
uint32_t GetBlobLength() const
Get the blob length.
GHC ICMPv6 NHC Header - see RFC 7400 Section 5.
uint32_t GetBlobLength() const
Get the blob length.
SixLowPanDispatch::NhcDispatch_e GetNhcDispatchType() const
Get the NhcDispatch type.
uint32_t CopyBlob(uint8_t *blob, uint32_t size) const
Copy the GHC-compressed bytecode blob.
uint32_t Deserialize(Buffer::Iterator start) override
uint8_t m_blobLength
Length of GHC compressed ICMPv6 body.
void Print(std::ostream &os) const override
uint8_t m_blob[MAX_BLOB_SIZE+1]
GHC compressed bytecodes.
TypeId GetInstanceTypeId() const override
Get the most derived TypeId for this Object.
void SetBlob(const uint8_t *blob, uint32_t size)
Set the GHC-compressed bytecode blob for the ICMPv6 body.
static constexpr uint8_t GHC_ICMPV6_NHC
Fixed: 11011111.
void Serialize(Buffer::Iterator start) const override
static constexpr uint32_t MAX_BLOB_SIZE
Maximum blob size: the blob length field is 8 bits.
uint32_t GetSerializedSize() const override
static TypeId GetTypeId()
Get the type ID.
GHC UDP NHC Header - see RFC 7400 Section 5.
void SetSrcPort(uint16_t port)
Set the source port.
static constexpr uint8_t GHC_UDP_BASE
11010000
uint32_t Deserialize(Buffer::Iterator start) override
static constexpr uint8_t C_MASK
Checksum flag mask.
uint8_t m_baseFormat
NHC byte: 11010CPP.
uint16_t m_dstPort
Destination port.
void SetPorts(Ports_e port)
Set the port compression mode.
static constexpr uint8_t P_MASK
Port compression mask.
void Print(std::ostream &os) const override
TypeId GetInstanceTypeId() const override
Get the most derived TypeId for this Object.
uint16_t GetDstPort() const
Get the destination port.
void SetChecksum(uint16_t checksum)
Set the UDP checksum.
void SetDstPort(uint16_t port)
Set the destination port.
uint16_t GetChecksum() const
Get the UDP checksum.
static TypeId GetTypeId()
Get the type ID.
uint16_t m_checksum
UDP checksum.
void SetC(bool cField)
Set the checksum elision flag (C bit).
Ports_e
Port compression modes (same as RFC 6282 UDP NHC).
void Serialize(Buffer::Iterator start) const override
SixLowPanDispatch::NhcDispatch_e GetNhcDispatchType() const
Get the NhcDispatch type.
uint16_t m_srcPort
Source port.
Ports_e GetPorts() const
Get the port compression mode.
uint32_t GetSerializedSize() const override
bool GetC() const
Get the checksum elision flag (C bit).
uint16_t GetSrcPort() const
Get the source port.
a unique identifier for an interface.
Definition type-id.h:50
TypeId SetParent(TypeId tid)
Set the parent TypeId.
Definition type-id.cc:1003
uint16_t port
Definition dsdv-manet.cc:33
#define NS_ASSERT(condition)
At runtime, in debugging builds, if this condition is not true, the program prints the source file,...
Definition assert.h:55
#define NS_FATAL_ERROR(msg)
Report a fatal error with a message and terminate.
#define NS_LOG_COMPONENT_DEFINE(name)
Define a Log component with a specific name.
Definition log.h:201
#define NS_LOG_DEBUG(msg)
Use NS_LOG to output a message of level LOG_DEBUG.
Definition log.h:267
#define NS_LOG_FUNCTION(parameters)
If log level LOG_FUNCTION is enabled, this macro will output all input parameters separated by ",...
#define NS_LOG_WARN(msg)
Use NS_LOG to output a message of level LOG_WARN.
Definition log.h:260
#define NS_OBJECT_ENSURE_REGISTERED(type)
Register an Object subclass with the TypeId system.
Definition object-base.h:35
GhcBytecodeType
GHC bytecode instruction types per RFC 7400 Section 3.
@ STOP_CODE
10010000: terminate decompression
@ RESERVED
Reserved/invalid pattern.
@ BACKREF
11nnnkkk: backreference copy
@ LITERAL
0kkkkkkk: copy k literal bytes
@ ZERO_INSERT
1000nnnn: insert (n+2) zero bytes
@ EXTENDED_ARGS
101nssss: extend backreference
Every class exported by the ns3 library is enclosed in the ns3 namespace.
std::ostream & operator<<(std::ostream &os, const Angles &a)
Definition angles.cc:148