github.com/Uhtred009/v2ray-core-1@v4.31.2+incompatible/app/dns/udpns.go (about) 1 // +build !confonly 2 3 package dns 4 5 import ( 6 "context" 7 "strings" 8 "sync" 9 "sync/atomic" 10 "time" 11 12 "golang.org/x/net/dns/dnsmessage" 13 "v2ray.com/core/common" 14 "v2ray.com/core/common/net" 15 "v2ray.com/core/common/protocol/dns" 16 udp_proto "v2ray.com/core/common/protocol/udp" 17 "v2ray.com/core/common/session" 18 "v2ray.com/core/common/signal/pubsub" 19 "v2ray.com/core/common/task" 20 dns_feature "v2ray.com/core/features/dns" 21 "v2ray.com/core/features/routing" 22 "v2ray.com/core/transport/internet/udp" 23 ) 24 25 type ClassicNameServer struct { 26 sync.RWMutex 27 name string 28 address net.Destination 29 ips map[string]record 30 requests map[uint16]dnsRequest 31 pub *pubsub.Service 32 udpServer *udp.Dispatcher 33 cleanup *task.Periodic 34 reqID uint32 35 clientIP net.IP 36 } 37 38 func NewClassicNameServer(address net.Destination, dispatcher routing.Dispatcher, clientIP net.IP) *ClassicNameServer { 39 40 // default to 53 if unspecific 41 if address.Port == 0 { 42 address.Port = net.Port(53) 43 } 44 45 s := &ClassicNameServer{ 46 address: address, 47 ips: make(map[string]record), 48 requests: make(map[uint16]dnsRequest), 49 clientIP: clientIP, 50 pub: pubsub.NewService(), 51 name: strings.ToUpper(address.String()), 52 } 53 s.cleanup = &task.Periodic{ 54 Interval: time.Minute, 55 Execute: s.Cleanup, 56 } 57 s.udpServer = udp.NewDispatcher(dispatcher, s.HandleResponse) 58 newError("DNS: created udp client inited for ", address.NetAddr()).AtInfo().WriteToLog() 59 return s 60 } 61 62 func (s *ClassicNameServer) Name() string { 63 return s.name 64 } 65 66 func (s *ClassicNameServer) Cleanup() error { 67 now := time.Now() 68 s.Lock() 69 defer s.Unlock() 70 71 if len(s.ips) == 0 && len(s.requests) == 0 { 72 return newError(s.name, " nothing to do. stopping...") 73 } 74 75 for domain, record := range s.ips { 76 if record.A != nil && record.A.Expire.Before(now) { 77 record.A = nil 78 } 79 if record.AAAA != nil && record.AAAA.Expire.Before(now) { 80 record.AAAA = nil 81 } 82 83 if record.A == nil && record.AAAA == nil { 84 delete(s.ips, domain) 85 } else { 86 s.ips[domain] = record 87 } 88 } 89 90 if len(s.ips) == 0 { 91 s.ips = make(map[string]record) 92 } 93 94 for id, req := range s.requests { 95 if req.expire.Before(now) { 96 delete(s.requests, id) 97 } 98 } 99 100 if len(s.requests) == 0 { 101 s.requests = make(map[uint16]dnsRequest) 102 } 103 104 return nil 105 } 106 107 func (s *ClassicNameServer) HandleResponse(ctx context.Context, packet *udp_proto.Packet) { 108 109 ipRec, err := parseResponse(packet.Payload.Bytes()) 110 if err != nil { 111 newError(s.name, " fail to parse responded DNS udp").AtError().WriteToLog() 112 return 113 } 114 115 s.Lock() 116 id := ipRec.ReqID 117 req, ok := s.requests[id] 118 if ok { 119 // remove the pending request 120 delete(s.requests, id) 121 } 122 s.Unlock() 123 if !ok { 124 newError(s.name, " cannot find the pending request").AtError().WriteToLog() 125 return 126 } 127 128 var rec record 129 switch req.reqType { 130 case dnsmessage.TypeA: 131 rec.A = ipRec 132 case dnsmessage.TypeAAAA: 133 rec.AAAA = ipRec 134 } 135 136 elapsed := time.Since(req.start) 137 newError(s.name, " got answer: ", req.domain, " ", req.reqType, " -> ", ipRec.IP, " ", elapsed).AtInfo().WriteToLog() 138 if len(req.domain) > 0 && (rec.A != nil || rec.AAAA != nil) { 139 s.updateIP(req.domain, rec) 140 } 141 } 142 143 func (s *ClassicNameServer) updateIP(domain string, newRec record) { 144 s.Lock() 145 146 newError(s.name, " updating IP records for domain:", domain).AtDebug().WriteToLog() 147 rec := s.ips[domain] 148 149 updated := false 150 if isNewer(rec.A, newRec.A) { 151 rec.A = newRec.A 152 updated = true 153 } 154 if isNewer(rec.AAAA, newRec.AAAA) { 155 rec.AAAA = newRec.AAAA 156 updated = true 157 } 158 159 if updated { 160 s.ips[domain] = rec 161 } 162 if newRec.A != nil { 163 s.pub.Publish(domain+"4", nil) 164 } 165 if newRec.AAAA != nil { 166 s.pub.Publish(domain+"6", nil) 167 } 168 s.Unlock() 169 common.Must(s.cleanup.Start()) 170 } 171 172 func (s *ClassicNameServer) newReqID() uint16 { 173 return uint16(atomic.AddUint32(&s.reqID, 1)) 174 } 175 176 func (s *ClassicNameServer) addPendingRequest(req *dnsRequest) { 177 s.Lock() 178 defer s.Unlock() 179 180 id := req.msg.ID 181 req.expire = time.Now().Add(time.Second * 8) 182 s.requests[id] = *req 183 } 184 185 func (s *ClassicNameServer) sendQuery(ctx context.Context, domain string, option IPOption) { 186 newError(s.name, " querying DNS for: ", domain).AtDebug().WriteToLog(session.ExportIDToError(ctx)) 187 188 reqs := buildReqMsgs(domain, option, s.newReqID, genEDNS0Options(s.clientIP)) 189 190 for _, req := range reqs { 191 s.addPendingRequest(req) 192 b, _ := dns.PackMessage(req.msg) 193 udpCtx := context.Background() 194 if inbound := session.InboundFromContext(ctx); inbound != nil { 195 udpCtx = session.ContextWithInbound(udpCtx, inbound) 196 } 197 udpCtx = session.ContextWithContent(udpCtx, &session.Content{ 198 Protocol: "dns", 199 }) 200 s.udpServer.Dispatch(udpCtx, s.address, b) 201 } 202 } 203 204 func (s *ClassicNameServer) findIPsForDomain(domain string, option IPOption) ([]net.IP, error) { 205 s.RLock() 206 record, found := s.ips[domain] 207 s.RUnlock() 208 209 if !found { 210 return nil, errRecordNotFound 211 } 212 213 var ips []net.Address 214 var lastErr error 215 if option.IPv4Enable { 216 a, err := record.A.getIPs() 217 if err != nil { 218 lastErr = err 219 } 220 ips = append(ips, a...) 221 } 222 223 if option.IPv6Enable { 224 aaaa, err := record.AAAA.getIPs() 225 if err != nil { 226 lastErr = err 227 } 228 ips = append(ips, aaaa...) 229 } 230 231 if len(ips) > 0 { 232 return toNetIP(ips), nil 233 } 234 235 if lastErr != nil { 236 return nil, lastErr 237 } 238 239 return nil, dns_feature.ErrEmptyResponse 240 } 241 242 func (s *ClassicNameServer) QueryIP(ctx context.Context, domain string, option IPOption) ([]net.IP, error) { 243 244 fqdn := Fqdn(domain) 245 246 ips, err := s.findIPsForDomain(fqdn, option) 247 if err != errRecordNotFound { 248 newError(s.name, " cache HIT ", domain, " -> ", ips).Base(err).AtDebug().WriteToLog() 249 return ips, err 250 } 251 252 // ipv4 and ipv6 belong to different subscription groups 253 var sub4, sub6 *pubsub.Subscriber 254 if option.IPv4Enable { 255 sub4 = s.pub.Subscribe(fqdn + "4") 256 defer sub4.Close() 257 } 258 if option.IPv6Enable { 259 sub6 = s.pub.Subscribe(fqdn + "6") 260 defer sub6.Close() 261 } 262 done := make(chan interface{}) 263 go func() { 264 if sub4 != nil { 265 select { 266 case <-sub4.Wait(): 267 case <-ctx.Done(): 268 } 269 } 270 if sub6 != nil { 271 select { 272 case <-sub6.Wait(): 273 case <-ctx.Done(): 274 } 275 } 276 close(done) 277 }() 278 s.sendQuery(ctx, fqdn, option) 279 280 for { 281 ips, err := s.findIPsForDomain(fqdn, option) 282 if err != errRecordNotFound { 283 return ips, err 284 } 285 286 select { 287 case <-ctx.Done(): 288 return nil, ctx.Err() 289 case <-done: 290 } 291 } 292 }