Debian Codegraph @

internal/jump/jump.go

raw
1 // Package jump contain mini pack function that quick jumping through a binary message.
2 package jump
3
4 import "encoding/binary"
5
6 // Main use is to find the last RR in a message for TSIG.
7
8 // Name jumps the name that should start msgBuf[off].
9 func Name(msgBuf []byte, off int) int {
10 for off < len(msgBuf) {
11 c := msgBuf[off]
12 off++
13
14 switch c & 0xC0 {
15 case 0x00:
16 if c == 0 {
17 return off
18 }
19 off += int(c)
20 case 0xC0:
21 return off + 1
22 }
23 }
24 return 0
25 }
26
27 // Question jumps the question section that should start at msgBuf[off].
28 func Question(msgBuf []byte, off int) int {
29 off = Name(msgBuf, off)
30 if off+4 >= len(msgBuf) || off == 0 {
31 return 0
32 }
33 return off + 4 // type + class
34 }
35
36 // RR jumps the RR that starts at msgBuf[off].
37 func RR(msgBuf []byte, off int) int {
38 off = Name(msgBuf, off)
39 if off >= len(msgBuf) || off == 0 {
40 return 0
41 }
42 off += 8 // type + class + ttl
43 if off+2 >= len(msgBuf) { // not enough room to read rdlength
44 return 0
45 }
46 rdlength := binary.BigEndian.Uint16(msgBuf[off:])
47 off = off + 2 + int(rdlength)
48 return off
49 }
50
51 // To jumps to the start of the i-th RR in the message, that starts at msgBuf[0]. This counts from 0 which
52 // returns the RR *after* a possible question section. When we jump over the entire message, 0 is returned. The
53 // supported number of "RR"s in the question section is zero or one. The zero check is done by checking the
54 // Qdcount *in the buffer* as there is no other way of doing so.
55 func To(i int, msgBuf []byte) int {
56 off := 12
57 if off >= len(msgBuf) {
58 return 0
59 }
60 qdcount := binary.BigEndian.Uint16(msgBuf[4:])
61 if qdcount > 0 {
62 off = Question(msgBuf, off)
63 if off >= len(msgBuf) {
64 return 0
65 }
66 }
67 for range i {
68 off = RR(msgBuf, off)
69 if off >= len(msgBuf) {
70 return 0
71 }
72 }
73 return off
74 }