/
msg.go
1086 lines (1035 loc) · 28.9 KB
/
msg.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2009 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// This is not (yet) optimized for speed.
// DNS packet assembly, see RFC 1035. Converting from - Unpack() -
// and to - Pack() - wire format.
// All the packers and unpackers take a (msg []byte, off int)
// and return (off1 int, ok bool). If they return ok==false, they
// also return off1==len(msg), so that the next unpacker will
// also fail. This lets us avoid checks of ok until the end of a
// packing sequence.
package dns
import (
"os"
// "fmt"
"reflect"
"net"
"rand"
"time"
"strconv"
"encoding/base64"
"encoding/base32"
"encoding/hex"
)
var (
ErrUnpack os.Error = &Error{Error: "unpacking failed"}
ErrPack os.Error = &Error{Error: "packing failed"}
ErrId os.Error = &Error{Error: "id mismatch"}
ErrShortRead os.Error = &Error{Error: "short read"}
ErrConn os.Error = &Error{Error: "conn holds both UDP and TCP connection"}
ErrConnEmpy os.Error = &Error{Error: "conn has no connection"}
ErrServ os.Error = &Error{Error: "no servers could be reached"}
ErrKey os.Error = &Error{Error: "bad key"}
ErrPrivKey os.Error = &Error{Error: "bad private key"}
ErrKeySize os.Error = &Error{Error: "bad key size"}
ErrAlg os.Error = &Error{Error: "bad algorithm"}
ErrTime os.Error = &Error{Error: "bad time"}
ErrNoSig os.Error = &Error{Error: "no signature found"}
ErrSig os.Error = &Error{Error: "bad signature"}
ErrSigGen os.Error = &Error{Error: "bad signature generation"}
ErrAuth os.Error = &Error{Error: "bad authentication"}
ErrXfrSoa os.Error = &Error{Error: "no SOA seen"}
ErrHandle os.Error = &Error{Error: "handle is nil"}
ErrChan os.Error = &Error{Error: "channel is nil"}
)
// A manually-unpacked version of (id, bits).
// This is in its own struct for easy printing.
type MsgHdr struct {
Id uint16
Response bool
Opcode int
Authoritative bool
Truncated bool
RecursionDesired bool
RecursionAvailable bool
Zero bool
AuthenticatedData bool
CheckingDisabled bool
Rcode int
}
// The layout of a DNS message.
type Msg struct {
MsgHdr
Question []Question
Answer []RR
Ns []RR
Extra []RR
}
// Map of strings for each RR wire type.
var Rr_str = map[uint16]string{
TypeCNAME: "CNAME",
TypeHINFO: "HINFO",
TypeMB: "MB",
TypeMG: "MG",
TypeMINFO: "MINFO",
TypeMR: "MR",
TypeMX: "MX",
TypeNS: "NS",
TypePTR: "PTR",
TypeSOA: "SOA",
TypeTXT: "TXT",
TypeSRV: "SRV",
TypeNAPTR: "NAPTR",
TypeKX: "KX",
TypeCERT: "CERT",
TypeDNAME: "DNAME",
TypeA: "A",
TypeAAAA: "AAAA",
TypeLOC: "LOC",
TypeOPT: "OPT",
TypeDS: "DS",
TypeDHCID: "DHCID",
TypeIPSECKEY: "IPSECKEY",
TypeSSHFP: "SSHFP",
TypeRRSIG: "RRSIG",
TypeNSEC: "NSEC",
TypeDNSKEY: "DNSKEY",
TypeNSEC3: "NSEC3",
TypeNSEC3PARAM: "NSEC3PARAM",
TypeTALINK: "TALINK",
TypeSPF: "SPF",
TypeTKEY: "TKEY", // Meta RR
TypeTSIG: "TSIG", // Meta RR
TypeAXFR: "AXFR", // Meta RR
TypeIXFR: "IXFR", // Meta RR
TypeALL: "ANY", // Meta RR
TypeURI: "URI",
TypeTA: "TA",
TypeDLV: "DLV",
}
// Reverse of Rr_str (needed for string parsing).
var Str_rr = reverse(Rr_str)
// Map of strings for each CLASS wire type.
var Class_str = map[uint16]string{
ClassINET: "IN",
ClassCSNET: "CS",
ClassCHAOS: "CH",
ClassHESIOD: "HS",
ClassANY: "ANY",
}
// Map of strings for opcodes.
var opcode_str = map[int]string{
OpcodeQuery: "QUERY",
OpcodeIQuery: "IQUERY",
OpcodeStatus: "STATUS",
OpcodeNotify: "NOTIFY",
OpcodeUpdate: "UPDATE",
}
// Map of strings for rcodes.
var rcode_str = map[int]string{
RcodeSuccess: "NOERROR",
RcodeFormatError: "FORMERR",
RcodeServerFailure: "SERVFAIL",
RcodeNameError: "NXDOMAIN",
RcodeNotImplemented: "NOTIMPL",
RcodeRefused: "REFUSED",
RcodeYXDomain: "YXDOMAIN", // From RFC 2136
RcodeYXRrset: "YXRRSET",
RcodeNXRrset: "NXRRSET",
RcodeNotAuth: "NOTAUTH",
RcodeNotZone: "NOTZONE",
}
// Rather than write the usual handful of routines to pack and
// unpack every message that can appear on the wire, we use
// reflection to write a generic pack/unpack for structs and then
// use it. Thus, if in the future we need to define new message
// structs, no new pack/unpack/printing code needs to be written.
// Pack a domain name s into msg[off:].
// Domain names are a sequence of counted strings
// split at the dots. They end with a zero-length string.
func packDomainName(s string, msg []byte, off int) (off1 int, ok bool) {
// Add trailing dot to canonicalize name.
if n := len(s); n == 0 || s[n-1] != '.' {
s += "."
}
// Each dot ends a segment of the name.
// We trade each dot byte for a length byte.
// Except for escaped dots (\.), which are normal dots.
// There is also a trailing zero.
// Check that we have all the space we need.
tot := len(s) + 1
if off+tot > len(msg) {
return len(msg), false
}
// Emit sequence of counted strings, chopping at dots.
begin := 0
bs := []byte(s)
ls := len(bs)
for i := 0; i < ls; i++ {
if bs[i] == '\\' {
for j := i; j < len(s)-1; j++ {
bs[j] = bs[j+1]
}
ls--
continue
}
if bs[i] == '.' {
if i-begin >= 1<<6 { // top two bits of length must be clear
return len(msg), false
}
msg[off] = byte(i - begin)
off++
for j := begin; j < i; j++ {
msg[off] = bs[j]
off++
}
begin = i + 1
}
}
// Root label is special
if string(bs) == "." {
return off, true
}
msg[off] = 0
off++
return off, true
}
// Unpack a domain name.
// In addition to the simple sequences of counted strings above,
// domain names are allowed to refer to strings elsewhere in the
// packet, to avoid repeating common suffixes when returning
// many entries in a single domain. The pointers are marked
// by a length byte with the top two bits set. Ignoring those
// two bits, that byte and the next give a 14 bit offset from msg[0]
// where we should pick up the trail.
// Note that if we jump elsewhere in the packet,
// we return off1 == the offset after the first pointer we found,
// which is where the next record will start.
// In theory, the pointers are only allowed to jump backward.
// We let them jump anywhere and stop jumping after a while.
func unpackDomainName(msg []byte, off int) (s string, off1 int, ok bool) {
s = ""
ptr := 0 // number of pointers followed
Loop:
for {
if off >= len(msg) {
return "", len(msg), false
}
c := int(msg[off])
off++
switch c & 0xC0 {
case 0x00:
if c == 0x00 {
// end of name
break Loop
}
// literal string
if off+c > len(msg) {
return "", len(msg), false
}
for j := off; j < off+c; j++ {
if msg[j] == '.' {
// literal dot, escape it
s += "\\."
} else {
s += string(msg[j])
}
}
s += "."
off += c
case 0xC0:
// pointer to somewhere else in msg.
// remember location after first ptr,
// since that's how many bytes we consumed.
// also, don't follow too many pointers --
// maybe there's a loop.
if off >= len(msg) {
return "", len(msg), false
}
c1 := msg[off]
off++
if ptr == 0 {
off1 = off
}
if ptr++; ptr > 10 {
return "", len(msg), false
}
off = (c^0xC0)<<8 | int(c1)
default:
// 0x80 and 0x40 are reserved
return "", len(msg), false
}
}
if ptr == 0 {
off1 = off
}
return s, off1, true
}
// Pack a reflect.StructValue into msg. Struct members can only be uint8, uint16, uint32, string,
// slices and other (often anonymous) structs.
func packStructValue(val reflect.Value, msg []byte, off int) (off1 int, ok bool) {
for i := 0; i < val.NumField(); i++ {
f := val.Type().Field(i)
switch fv := val.Field(i); fv.Kind() {
default:
BadType:
//fmt.Fprintf(os.Stderr, "dns: unknown packing type %v\n", f.Type)
return len(msg), false
case reflect.Slice:
switch f.Tag {
default:
//fmt.Fprintf(os.Stderr, "dns: unknown packing slice tag %v\n", f.Tag)
return len(msg), false
case "OPT": // edns
for j := 0; j < val.Field(i).Len(); j++ {
element := val.Field(i).Index(j)
code := uint16(element.Field(0).Uint())
// for each code we should do something else
h, e := hex.DecodeString(string(element.Field(1).String()))
if e != nil {
//fmt.Fprintf(os.Stderr, "dns: failure packing OTP")
return len(msg), false
}
data := string(h)
// Option Code
msg[off] = byte(code >> 8)
msg[off+1] = byte(code)
// Length
msg[off+2] = byte(len(data) >> 8)
msg[off+3] = byte(len(data))
off += 4
copy(msg[off:off+len(data)], []byte(data))
off += len(data)
}
case "A":
// It must be a slice of 4, even if it is 16, we encode
// only the first 4
if off+net.IPv4len > len(msg) {
//fmt.Fprintf(os.Stderr, "dns: overflow packing A")
return len(msg), false
}
if fv.Len() == net.IPv6len {
msg[off] = byte(fv.Index(12).Uint())
msg[off+1] = byte(fv.Index(13).Uint())
msg[off+2] = byte(fv.Index(14).Uint())
msg[off+3] = byte(fv.Index(15).Uint())
} else {
msg[off] = byte(fv.Index(0).Uint())
msg[off+1] = byte(fv.Index(1).Uint())
msg[off+2] = byte(fv.Index(2).Uint())
msg[off+3] = byte(fv.Index(3).Uint())
}
off += net.IPv4len
case "AAAA":
if fv.Len() > net.IPv6len || off+fv.Len() > len(msg) {
//fmt.Fprintf(os.Stderr, "dns: overflow packing AAAA")
return len(msg), false
}
for j := 0; j < net.IPv6len; j++ {
msg[off] = byte(fv.Index(j).Uint())
off++
}
case "NSEC": // NSEC/NSEC3
for j := 0; j < val.Field(i).Len(); j++ {
var _ = byte(fv.Index(j).Uint())
}
// handle type bit maps
// TODO(mg)
}
case reflect.Struct:
off, ok = packStructValue(fv, msg, off)
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
i := fv.Uint()
switch fv.Type().Kind() {
default:
goto BadType
case reflect.Uint8:
if off+1 > len(msg) {
//fmt.Fprintf(os.Stderr, "dns: overflow packing uint8")
return len(msg), false
}
msg[off] = byte(i)
off++
case reflect.Uint16:
if off+2 > len(msg) {
//fmt.Fprintf(os.Stderr, "dns: overflow packing uint16")
return len(msg), false
}
msg[off] = byte(i >> 8)
msg[off+1] = byte(i)
off += 2
case reflect.Uint32:
if off+4 > len(msg) {
//fmt.Fprintf(os.Stderr, "dns: overflow packing uint32")
return len(msg), false
}
msg[off] = byte(i >> 24)
msg[off+1] = byte(i >> 16)
msg[off+2] = byte(i >> 8)
msg[off+3] = byte(i)
off += 4
case reflect.Uint64:
// Only used in TSIG, where it stops at 48 bits, so we discard the upper 16
if off+6 > len(msg) {
//fmt.Fprintf(os.Stderr, "dns: overflow packing uint64")
return len(msg), false
}
msg[off] = byte(i >> 40)
msg[off+1] = byte(i >> 32)
msg[off+2] = byte(i >> 24)
msg[off+3] = byte(i >> 16)
msg[off+4] = byte(i >> 8)
msg[off+5] = byte(i)
off += 6
}
case reflect.String:
// There are multiple string encodings.
// The tag distinguishes ordinary strings from domain names.
s := fv.String()
switch f.Tag {
default:
//fmt.Fprintf(os.Stderr, "dns: unknown packing string tag %v", f.Tag)
return len(msg), false
case "base32":
b32, err := packBase32([]byte(s))
if err != nil {
//fmt.Fprintf(os.Stderr, "dns: overflow packing base32")
return len(msg), false
}
copy(msg[off:off+len(b32)], b32)
off += len(b32)
case "base64":
b64, err := packBase64([]byte(s))
if err != nil {
//fmt.Fprintf(os.Stderr, "dns: overflow packing base64")
return len(msg), false
}
copy(msg[off:off+len(b64)], b64)
off += len(b64)
case "domain-name":
off, ok = packDomainName(s, msg, off)
if !ok {
//fmt.Fprintf(os.Stderr, "dns: overflow packing domain-name")
return len(msg), false
}
case "size-hex":
fallthrough
case "hex":
// There is no length encoded here
h, e := hex.DecodeString(s)
if e != nil {
//fmt.Fprintf(os.Stderr, "dns: overflow packing (size-)hex string")
return len(msg), false
}
copy(msg[off:off+hex.DecodedLen(len(s))], h)
off += hex.DecodedLen(len(s))
case "size":
// the size is already encoded in the RR, we can safely use the
// length of string. String is RAW (not encoded in hex, nor base64)
copy(msg[off:off+len(s)], s)
off += len(s)
case "txt":
// Counted string: 1 byte length, but the string may be longer
// than 255, in that case it should be multiple strings, for now:
fallthrough
case "":
// Counted string: 1 byte length.
if len(s) > 255 || off+1+len(s) > len(msg) {
//fmt.Fprintf(os.Stderr, "dns: overflow packing string")
return len(msg), false
}
msg[off] = byte(len(s))
off++
for i := 0; i < len(s); i++ {
msg[off+i] = s[i]
}
off += len(s)
}
}
}
return off, true
}
func structValue(any interface{}) reflect.Value {
return reflect.ValueOf(any).Elem()
}
func packStruct(any interface{}, msg []byte, off int) (off1 int, ok bool) {
off, ok = packStructValue(structValue(any), msg, off)
return off, ok
}
// Unpack a reflect.StructValue from msg.
// Same restrictions as packStructValue.
func unpackStructValue(val reflect.Value, msg []byte, off int) (off1 int, ok bool) {
for i := 0; i < val.NumField(); i++ {
f := val.Type().Field(i)
switch fv := val.Field(i); fv.Kind() {
default:
BadType:
//fmt.Fprintf(os.Stderr, "dns: unknown unpacking type %v", f.Type)
return len(msg), false
case reflect.Slice:
switch f.Tag {
default:
//fmt.Fprintf(os.Stderr, "dns: unknown unpacking slice tag %v", f.Tag)
return len(msg), false
case "A":
if off+net.IPv4len > len(msg) {
//fmt.Fprintf(os.Stderr, "dns: overflow unpacking A")
return len(msg), false
}
b := net.IPv4(msg[off], msg[off+1], msg[off+2], msg[off+3])
fv.Set(reflect.ValueOf(b))
off += net.IPv4len
case "AAAA":
if off+net.IPv6len > len(msg) {
//fmt.Fprintf(os.Stderr, "dns: overflow unpacking AAAA")
return len(msg), false
}
p := make(net.IP, net.IPv6len)
copy(p, msg[off:off+net.IPv6len])
b := net.IP(p)
fv.Set(reflect.ValueOf(b))
off += net.IPv6len
case "OPT": // EDNS
if off+2 > len(msg) {
//fmt.Fprintf(os.Stderr, "dns: overflow unpacking OPT")
// No room for anything else
break
}
opt := make([]Option, 1)
opt[0].Code, off = unpackUint16(msg, off)
optlen, off1 := unpackUint16(msg, off)
if off1+int(optlen) > len(msg) {
//fmt.Fprintf(os.Stderr, "dns: overflow unpacking OPT")
return len(msg), false
}
opt[0].Data = hex.EncodeToString(msg[off1 : off1+int(optlen)])
fv.Set(reflect.ValueOf(opt))
off = off1 + int(optlen)
case "NSEC": // NSEC/NSEC3
if off+1 > len(msg) {
//fmt.Fprintf(os.Stderr, "dns: overflow unpacking NSEC")
return len(msg), false
}
// Fix multple windows TODO(mg)
nsec := make([]uint16, 256) // use append TODO(mg)
ni := 0
window := int(msg[off])
blocks := int(msg[off+1])
if off+blocks > len(msg) {
//fmt.Fprintf(os.Stderr, "dns: overflow unpacking NSEC")
return len(msg), false
}
if blocks == 0 {
// Nothing encoded in this window
// Kinda lame to alloc above and to clear it here
nsec = nsec[:ni]
fv.Set(reflect.ValueOf(nsec))
break
}
off += 2
for j := 0; j < blocks; j++ {
b := msg[off+j]
// Check the bits one by one, and set the type
if b&0x80 == 0x80 {
nsec[ni] = uint16(window*256 + j*8 + 0)
ni++
}
if b&0x40 == 0x40 {
nsec[ni] = uint16(window*256 + j*8 + 1)
ni++
}
if b&0x20 == 0x20 {
nsec[ni] = uint16(window*256 + j*8 + 2)
ni++
}
if b&0x10 == 0x10 {
nsec[ni] = uint16(window*256 + j*8 + 3)
ni++
}
if b&0x8 == 0x8 {
nsec[ni] = uint16(window*256 + j*8 + 4)
ni++
}
if b&0x4 == 0x4 {
nsec[ni] = uint16(window*256 + j*8 + 5)
ni++
}
if b&0x2 == 0x2 {
nsec[ni] = uint16(window*256 + j*8 + 6)
ni++
}
if b&0x1 == 0x1 {
nsec[ni] = uint16(window*256 + j*8 + 7)
ni++
}
}
nsec = nsec[:ni]
fv.Set(reflect.ValueOf(nsec))
off += blocks
}
case reflect.Struct:
off, ok = unpackStructValue(fv, msg, off)
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
switch fv.Type().Kind() {
default:
goto BadType
case reflect.Uint8:
if off+1 > len(msg) {
//fmt.Fprintf(os.Stderr, "dns: overflow unpacking uint8")
return len(msg), false
}
i := uint8(msg[off])
fv.SetUint(uint64(i))
off++
case reflect.Uint16:
var i uint16
if off+2 > len(msg) {
//fmt.Fprintf(os.Stderr, "dns: overflow unpacking uint16")
return len(msg), false
}
i, off = unpackUint16(msg, off)
fv.SetUint(uint64(i))
case reflect.Uint32:
if off+4 > len(msg) {
//fmt.Fprintf(os.Stderr, "dns: overflow unpacking uint32")
return len(msg), false
}
i := uint32(msg[off])<<24 | uint32(msg[off+1])<<16 | uint32(msg[off+2])<<8 | uint32(msg[off+3])
fv.SetUint(uint64(i))
off += 4
case reflect.Uint64:
// This is *only* used in TSIG where the last 48 bits are occupied
// So for now, assume a uint48 (6 bytes)
if off+6 > len(msg) {
//fmt.Fprintf(os.Stderr, "dns: overflow unpacking uint64")
return len(msg), false
}
i := uint64(msg[off])<<40 | uint64(msg[off+1])<<32 | uint64(msg[off+2])<<24 | uint64(msg[off+3])<<16 |
uint64(msg[off+4])<<8 | uint64(msg[off+5])
fv.SetUint(uint64(i))
off += 6
}
case reflect.String:
var s string
switch f.Tag {
default:
//fmt.Fprintf(os.Stderr, "dns: unknown unpacking string tag %v", f.Tag)
return len(msg), false
case "hex":
// Rest of the RR is hex encoded, network order an issue here?
rdlength := int(val.FieldByName("Hdr").FieldByName("Rdlength").Uint())
var consumed int
switch val.Type().Name() {
case "RR_DS":
consumed = 4 // KeyTag(2) + Algorithm(1) + DigestType(1)
case "RR_SSHFP":
consumed = 2 // Algorithm(1) + Type(1)
case "RR_NSEC3PARAM":
consumed = 5 // Hash(1) + Flags(1) + Iterations(2) + SaltLength(1)
case "RR_RFC3597":
fallthrough // Rest is the unknown data
default:
consumed = 0 // return len(msg), false?
}
s = hex.EncodeToString(msg[off : off+rdlength-consumed])
off += rdlength - consumed
case "base64":
// Rest of the RR is base64 encoded value
rdlength := int(val.FieldByName("Hdr").FieldByName("Rdlength").Uint())
// Need to know how much of rdlength is already consumed, in this packet
var consumed int
switch val.Type().Name() {
case "RR_DNSKEY":
consumed = 4 // Flags(2) + Protocol(1) + Algorithm(1)
case "RR_RRSIG":
consumed = 18 // TypeCovered(2) + Algorithm(1) + Labels(1) +
// OrigTTL(4) + SigExpir(4) + SigIncep(4) + KeyTag(2) + len(signername)
// Should already be set in the sequence of parsing (comes before)
// Work because of rfc4034, section 3.17
consumed += len(val.FieldByName("SignerName").String()) + 1
default:
consumed = 0 // TODO
}
s = unpackBase64(msg[off : off+rdlength-consumed])
off += rdlength - consumed
case "domain-name":
s, off, ok = unpackDomainName(msg, off)
if !ok {
//fmt.Fprintf(os.Stderr, "dns: failure unpacking domain-name")
return len(msg), false
}
case "size-base32":
var size int
switch val.Type().Name() {
case "RR_NSEC3":
switch f.Name {
case "NextDomain":
name := val.FieldByName("HashLength")
size = int(name.Uint())
}
}
if off+size > len(msg) {
//fmt.Fprintf(os.Stderr, "dns: failure unpacking size-base32 string")
return len(msg), false
}
s = unpackBase32(msg[off : off+size])
off += size
case "size-hex":
// a "size" string, but it must be encoded in hex in the string
var size int
switch val.Type().Name() {
case "RR_NSEC3":
switch f.Name {
case "Salt":
name := val.FieldByName("SaltLength")
size = int(name.Uint())
case "NextDomain":
name := val.FieldByName("HashLength")
size = int(name.Uint())
}
case "RR_TSIG":
switch f.Name {
case "MAC":
name := val.FieldByName("MACSize")
size = int(name.Uint())
case "OtherData":
name := val.FieldByName("OtherLen")
size = int(name.Uint())
}
}
if off+size > len(msg) {
//fmt.Fprintf(os.Stderr, "dns: failure unpacking size-hex string")
return len(msg), false
}
s = hex.EncodeToString(msg[off : off+size])
off += size
case "txt":
// 1 or multiple txt pieces
rdlength := int(val.FieldByName("Hdr").FieldByName("Rdlength").Uint())
Txt:
if off >= len(msg) || off+1+int(msg[off]) > len(msg) {
//fmt.Fprintf(os.Stderr, "dns: failure unpacking txt string")
return len(msg), false
}
n := int(msg[off])
off++
b := make([]byte, n)
for i := 0; i < n; i++ {
b[i] = msg[off+i]
}
off += n
s += string(b)
if off < rdlength {
// More to come
goto Txt
}
case "":
if off >= len(msg) || off+1+int(msg[off]) > len(msg) {
//fmt.Fprintf(os.Stderr, "dns: failure unpacking string")
return len(msg), false
}
n := int(msg[off])
off++
b := make([]byte, n)
for i := 0; i < n; i++ {
b[i] = msg[off+i]
}
off += n
s = string(b)
}
fv.SetString(s)
}
}
return off, true
}
// Helper function for unpacking
func unpackUint16(msg []byte, off int) (v uint16, off1 int) {
v = uint16(msg[off])<<8 | uint16(msg[off+1])
off1 = off + 2
return
}
func unpackStruct(any interface{}, msg []byte, off int) (off1 int, ok bool) {
off, ok = unpackStructValue(structValue(any), msg, off)
return off, ok
}
func unpackBase32(b []byte) string {
b32 := make([]byte, base32.HexEncoding.EncodedLen(len(b)))
base32.HexEncoding.Encode(b32, b)
return string(b32)
}
func unpackBase64(b []byte) string {
b64 := make([]byte, base64.StdEncoding.EncodedLen(len(b)))
base64.StdEncoding.Encode(b64, b)
return string(b64)
}
// Helper function for packing, mostly used in dnssec.go
func packUint16(i uint16) (byte, byte) {
return byte(i >> 8), byte(i)
}
func packBase64(s []byte) ([]byte, os.Error) {
b64len := base64.StdEncoding.DecodedLen(len(s))
buf := make([]byte, b64len)
n, err := base64.StdEncoding.Decode(buf, []byte(s))
if err != nil {
return nil, err
}
buf = buf[:n]
return buf, nil
}
// Helper function for packing, mostly used in dnssec.go
func packBase32(s []byte) ([]byte, os.Error) {
b32len := base32.HexEncoding.DecodedLen(len(s))
buf := make([]byte, b32len)
n, err := base32.HexEncoding.Decode(buf, []byte(s))
if err != nil {
return nil, err
}
buf = buf[:n]
return buf, nil
}
// Resource record packer.
func packRR(rr RR, msg []byte, off int) (off2 int, ok bool) {
if rr == nil {
return len(msg), false
}
var off1 int
// pack twice, once to find end of header
// and again to find end of packet.
// a bit inefficient but this doesn't need to be fast.
// off1 is end of header
// off2 is end of rr
off1, ok = packStruct(rr.Header(), msg, off)
off2, ok = packStruct(rr, msg, off)
if !ok {
return len(msg), false
}
// TODO make this quicker?
// pack a third time; redo header with correct data length
rr.Header().Rdlength = uint16(off2 - off1)
packStruct(rr.Header(), msg, off)
return off2, true
}
// Resource record unpacker.
func unpackRR(msg []byte, off int) (rr RR, off1 int, ok bool) {
// unpack just the header, to find the rr type and length
var h RR_Header
off0 := off
if off, ok = unpackStruct(&h, msg, off); !ok {
return nil, len(msg), false
}
end := off + int(h.Rdlength)
// make an rr of that type and re-unpack.
// again inefficient but doesn't need to be fast.
mk, known := rr_mk[int(h.Rrtype)]
if !known {
rr = new(RR_RFC3597)
} else {
rr = mk()
}
off, ok = unpackStruct(rr, msg, off0)
if off != end {
return &h, end, true
}
return rr, off, ok
}
// Reverse a map
func reverse(m map[uint16]string) map[string]uint16 {
n := make(map[string]uint16)
for u, s := range m {
n[s] = u
}
return n
}
// Convert a MsgHdr to a string, mimic the way Dig displays headers:
//;; opcode: QUERY, status: NOERROR, id: 48404
//;; flags: qr aa rd ra;
func (h *MsgHdr) String() string {
if h == nil {
return "<nil> MsgHdr"
}
s := ";; opcode: " + opcode_str[h.Opcode]
s += ", status: " + rcode_str[h.Rcode]
s += ", id: " + strconv.Itoa(int(h.Id)) + "\n"
s += ";; flags:"
if h.Response {
s += " qr"
}
if h.Authoritative {
s += " aa"
}
if h.Truncated {
s += " tc"
}
if h.RecursionDesired {
s += " rd"
}
if h.RecursionAvailable {
s += " ra"
}
if h.Zero { // Hmm
s += " z"
}
if h.AuthenticatedData {
s += " ad"
}
if h.CheckingDisabled {
s += " cd"
}
s += ";"
return s
}
// Pack a msg: convert it to wire format.
func (dns *Msg) Pack() (msg []byte, ok bool) {
var dh Header
// Convert convenient Msg into wire-like Header.
dh.Id = dns.Id
dh.Bits = uint16(dns.Opcode)<<11 | uint16(dns.Rcode)
if dns.Response {
dh.Bits |= _QR
}
if dns.Authoritative {
dh.Bits |= _AA
}
if dns.Truncated {
dh.Bits |= _TC
}
if dns.RecursionDesired {
dh.Bits |= _RD
}
if dns.RecursionAvailable {
dh.Bits |= _RA
}
if dns.Zero {
dh.Bits |= _Z
}
if dns.AuthenticatedData {
dh.Bits |= _AD
}
if dns.CheckingDisabled {
dh.Bits |= _CD
}
// Prepare variable sized arrays.
question := dns.Question
answer := dns.Answer
ns := dns.Ns
extra := dns.Extra
dh.Qdcount = uint16(len(question))
dh.Ancount = uint16(len(answer))
dh.Nscount = uint16(len(ns))
dh.Arcount = uint16(len(extra))
// Could work harder to calculate message size,
// but this is far more than we need and not
// big enough to hurt the allocator.
msg = make([]byte, DefaultMsgSize) // TODO, calculate REAL size
// Pack it in: header and then the pieces.
off := 0
off, ok = packStruct(&dh, msg, off)
for i := 0; i < len(question); i++ {
off, ok = packStruct(&question[i], msg, off)
}
for i := 0; i < len(answer); i++ {
off, ok = packRR(answer[i], msg, off)
}
for i := 0; i < len(ns); i++ {
off, ok = packRR(ns[i], msg, off)
}
for i := 0; i < len(extra); i++ {
off, ok = packRR(extra[i], msg, off)
}
if !ok {
return nil, false
}
return msg[:off], true
}
// Unpack a binary message to a Msg structure.
func (dns *Msg) Unpack(msg []byte) bool {
// Header.
var dh Header
off := 0
var ok bool
if off, ok = unpackStruct(&dh, msg, off); !ok {
return false
}