-
Notifications
You must be signed in to change notification settings - Fork 301
/
ecs.go
101 lines (90 loc) · 2.64 KB
/
ecs.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
// Copyright (C) 2020-2021, IrineSistiana
//
// This file is part of mosdns.
//
// mosdns is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// mosdns is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
package dnsutils
import (
"github.com/miekg/dns"
"net"
)
func GetMsgECS(m *dns.Msg) (e *dns.EDNS0_SUBNET) {
opt := m.IsEdns0()
if opt == nil { // no opt, no ecs
return nil
}
// find ecs in opt
for o := range opt.Option {
if opt.Option[o].Option() == dns.EDNS0SUBNET {
return opt.Option[o].(*dns.EDNS0_SUBNET)
}
}
return nil
}
func RemoveECS(m *dns.Msg) (removedECS *dns.EDNS0_SUBNET) {
opt := m.IsEdns0()
if opt == nil { // no opt, no ecs
return nil
}
for i := range opt.Option {
if opt.Option[i].Option() == dns.EDNS0SUBNET {
removedECS = opt.Option[i].(*dns.EDNS0_SUBNET)
opt.Option = append(opt.Option[:i], opt.Option[i+1:]...)
return
}
}
return nil
}
func AppendECS(m *dns.Msg, ecs *dns.EDNS0_SUBNET) *dns.Msg {
opt := m.IsEdns0()
if opt == nil { // No OPT record.
o := new(dns.OPT)
o.SetUDPSize(dns.MinMsgSize)
o.Hdr.Name = "."
o.Hdr.Rrtype = dns.TypeOPT
o.Option = []dns.EDNS0{ecs}
m.Extra = append(m.Extra, o)
return m
}
// If m has an OPT record, search ecs section.
for o := range opt.Option {
if opt.Option[o].Option() == dns.EDNS0SUBNET { // overwrite
opt.Option[o] = ecs
return m
}
}
// no ecs section, append it
opt.Option = append(opt.Option, ecs)
return m
}
func NewEDNS0Subnet(ip net.IP, mask uint8, v6 bool) *dns.EDNS0_SUBNET {
edns0Subnet := new(dns.EDNS0_SUBNET)
// edns family: https://www.iana.org/assignments/address-family-numbers/address-family-numbers.xhtml
// ipv4 = 1
// ipv6 = 2
if !v6 { // ipv4
edns0Subnet.Family = 1
} else { // ipv6
edns0Subnet.Family = 2
}
edns0Subnet.SourceNetmask = mask
edns0Subnet.Code = dns.EDNS0SUBNET
edns0Subnet.Address = ip
// SCOPE PREFIX-LENGTH, an unsigned octet representing the leftmost
// number of significant bits of ADDRESS that the response covers.
// In queries, it MUST be set to 0.
// https://tools.ietf.org/html/rfc7871
edns0Subnet.SourceScope = 0
return edns0Subnet
}