github.com/imannamdari/v2ray-core/v5@v5.0.5/app/dns/nameserver_quic.go (about) 1 package dns 2 3 import ( 4 "bytes" 5 "context" 6 "encoding/binary" 7 "net/url" 8 "sync" 9 "sync/atomic" 10 "time" 11 12 "github.com/imannamdari/quic-go" 13 "golang.org/x/net/dns/dnsmessage" 14 "golang.org/x/net/http2" 15 16 "github.com/imannamdari/v2ray-core/v5/common" 17 "github.com/imannamdari/v2ray-core/v5/common/buf" 18 "github.com/imannamdari/v2ray-core/v5/common/net" 19 "github.com/imannamdari/v2ray-core/v5/common/protocol/dns" 20 "github.com/imannamdari/v2ray-core/v5/common/session" 21 "github.com/imannamdari/v2ray-core/v5/common/signal/pubsub" 22 "github.com/imannamdari/v2ray-core/v5/common/task" 23 dns_feature "github.com/imannamdari/v2ray-core/v5/features/dns" 24 "github.com/imannamdari/v2ray-core/v5/transport/internet/tls" 25 ) 26 27 // NextProtoDQ - During connection establishment, DNS/QUIC support is indicated 28 // by selecting the ALPN token "dq" in the crypto handshake. 29 const NextProtoDQ = "doq" 30 31 const handshakeIdleTimeout = time.Second * 8 32 33 // QUICNameServer implemented DNS over QUIC 34 type QUICNameServer struct { 35 sync.RWMutex 36 ips map[string]record 37 pub *pubsub.Service 38 cleanup *task.Periodic 39 reqID uint32 40 name string 41 destination net.Destination 42 connection quic.Connection 43 } 44 45 // NewQUICNameServer creates DNS-over-QUIC client object for local resolving 46 func NewQUICNameServer(url *url.URL) (*QUICNameServer, error) { 47 newError("DNS: created Local DNS-over-QUIC client for ", url.String()).AtInfo().WriteToLog() 48 49 var err error 50 port := net.Port(853) 51 if url.Port() != "" { 52 port, err = net.PortFromString(url.Port()) 53 if err != nil { 54 return nil, err 55 } 56 } 57 dest := net.UDPDestination(net.ParseAddress(url.Hostname()), port) 58 59 s := &QUICNameServer{ 60 ips: make(map[string]record), 61 pub: pubsub.NewService(), 62 name: url.String(), 63 destination: dest, 64 } 65 s.cleanup = &task.Periodic{ 66 Interval: time.Minute, 67 Execute: s.Cleanup, 68 } 69 70 return s, nil 71 } 72 73 // Name returns client name 74 func (s *QUICNameServer) Name() string { 75 return s.name 76 } 77 78 // Cleanup clears expired items from cache 79 func (s *QUICNameServer) Cleanup() error { 80 now := time.Now() 81 s.Lock() 82 defer s.Unlock() 83 84 if len(s.ips) == 0 { 85 return newError("nothing to do. stopping...") 86 } 87 88 for domain, record := range s.ips { 89 if record.A != nil && record.A.Expire.Before(now) { 90 record.A = nil 91 } 92 if record.AAAA != nil && record.AAAA.Expire.Before(now) { 93 record.AAAA = nil 94 } 95 96 if record.A == nil && record.AAAA == nil { 97 newError(s.name, " cleanup ", domain).AtDebug().WriteToLog() 98 delete(s.ips, domain) 99 } else { 100 s.ips[domain] = record 101 } 102 } 103 104 if len(s.ips) == 0 { 105 s.ips = make(map[string]record) 106 } 107 108 return nil 109 } 110 111 func (s *QUICNameServer) updateIP(req *dnsRequest, ipRec *IPRecord) { 112 elapsed := time.Since(req.start) 113 114 s.Lock() 115 rec := s.ips[req.domain] 116 updated := false 117 118 switch req.reqType { 119 case dnsmessage.TypeA: 120 if isNewer(rec.A, ipRec) { 121 rec.A = ipRec 122 updated = true 123 } 124 case dnsmessage.TypeAAAA: 125 addr := make([]net.Address, 0) 126 for _, ip := range ipRec.IP { 127 if len(ip.IP()) == net.IPv6len { 128 addr = append(addr, ip) 129 } 130 } 131 ipRec.IP = addr 132 if isNewer(rec.AAAA, ipRec) { 133 rec.AAAA = ipRec 134 updated = true 135 } 136 } 137 newError(s.name, " got answer: ", req.domain, " ", req.reqType, " -> ", ipRec.IP, " ", elapsed).AtInfo().WriteToLog() 138 139 if updated { 140 s.ips[req.domain] = rec 141 } 142 switch req.reqType { 143 case dnsmessage.TypeA: 144 s.pub.Publish(req.domain+"4", nil) 145 case dnsmessage.TypeAAAA: 146 s.pub.Publish(req.domain+"6", nil) 147 } 148 s.Unlock() 149 common.Must(s.cleanup.Start()) 150 } 151 152 func (s *QUICNameServer) newReqID() uint16 { 153 return uint16(atomic.AddUint32(&s.reqID, 1)) 154 } 155 156 func (s *QUICNameServer) sendQuery(ctx context.Context, domain string, clientIP net.IP, option dns_feature.IPOption) { 157 newError(s.name, " querying: ", domain).AtInfo().WriteToLog(session.ExportIDToError(ctx)) 158 159 reqs := buildReqMsgs(domain, option, s.newReqID, genEDNS0Options(clientIP)) 160 161 var deadline time.Time 162 if d, ok := ctx.Deadline(); ok { 163 deadline = d 164 } else { 165 deadline = time.Now().Add(time.Second * 5) 166 } 167 168 for _, req := range reqs { 169 go func(r *dnsRequest) { 170 // generate new context for each req, using same context 171 // may cause reqs all aborted if any one encounter an error 172 dnsCtx := ctx 173 174 // reserve internal dns server requested Inbound 175 if inbound := session.InboundFromContext(ctx); inbound != nil { 176 dnsCtx = session.ContextWithInbound(dnsCtx, inbound) 177 } 178 179 dnsCtx = session.ContextWithContent(dnsCtx, &session.Content{ 180 Protocol: "quic", 181 SkipDNSResolve: true, 182 }) 183 184 var cancel context.CancelFunc 185 dnsCtx, cancel = context.WithDeadline(dnsCtx, deadline) 186 defer cancel() 187 188 b, err := dns.PackMessage(r.msg) 189 if err != nil { 190 newError("failed to pack dns query").Base(err).AtError().WriteToLog() 191 return 192 } 193 194 dnsReqBuf := buf.New() 195 binary.Write(dnsReqBuf, binary.BigEndian, uint16(b.Len())) 196 dnsReqBuf.Write(b.Bytes()) 197 b.Release() 198 199 conn, err := s.openStream(dnsCtx) 200 if err != nil { 201 newError("failed to open quic connection").Base(err).AtError().WriteToLog() 202 return 203 } 204 205 _, err = conn.Write(dnsReqBuf.Bytes()) 206 if err != nil { 207 newError("failed to send query").Base(err).AtError().WriteToLog() 208 return 209 } 210 211 _ = conn.Close() 212 213 respBuf := buf.New() 214 defer respBuf.Release() 215 n, err := respBuf.ReadFullFrom(conn, 2) 216 if err != nil && n == 0 { 217 newError("failed to read response length").Base(err).AtError().WriteToLog() 218 return 219 } 220 var length int16 221 err = binary.Read(bytes.NewReader(respBuf.Bytes()), binary.BigEndian, &length) 222 if err != nil { 223 newError("failed to parse response length").Base(err).AtError().WriteToLog() 224 return 225 } 226 respBuf.Clear() 227 n, err = respBuf.ReadFullFrom(conn, int32(length)) 228 if err != nil && n == 0 { 229 newError("failed to read response length").Base(err).AtError().WriteToLog() 230 return 231 } 232 233 rec, err := parseResponse(respBuf.Bytes()) 234 if err != nil { 235 newError("failed to handle response").Base(err).AtError().WriteToLog() 236 return 237 } 238 s.updateIP(r, rec) 239 }(req) 240 } 241 } 242 243 func (s *QUICNameServer) findIPsForDomain(domain string, option dns_feature.IPOption) ([]net.IP, error) { 244 s.RLock() 245 record, found := s.ips[domain] 246 s.RUnlock() 247 248 if !found { 249 return nil, errRecordNotFound 250 } 251 252 var ips []net.Address 253 var lastErr error 254 if option.IPv4Enable { 255 a, err := record.A.getIPs() 256 if err != nil { 257 lastErr = err 258 } 259 ips = append(ips, a...) 260 } 261 262 if option.IPv6Enable { 263 aaaa, err := record.AAAA.getIPs() 264 if err != nil { 265 lastErr = err 266 } 267 ips = append(ips, aaaa...) 268 } 269 270 if len(ips) > 0 { 271 return toNetIP(ips) 272 } 273 274 if lastErr != nil { 275 return nil, lastErr 276 } 277 278 return nil, dns_feature.ErrEmptyResponse 279 } 280 281 // QueryIP is called from dns.Server->queryIPTimeout 282 func (s *QUICNameServer) QueryIP(ctx context.Context, domain string, clientIP net.IP, option dns_feature.IPOption, disableCache bool) ([]net.IP, error) { 283 fqdn := Fqdn(domain) 284 285 if disableCache { 286 newError("DNS cache is disabled. Querying IP for ", domain, " at ", s.name).AtDebug().WriteToLog() 287 } else { 288 ips, err := s.findIPsForDomain(fqdn, option) 289 if err != errRecordNotFound { 290 newError(s.name, " cache HIT ", domain, " -> ", ips).Base(err).AtDebug().WriteToLog() 291 return ips, err 292 } 293 } 294 295 // ipv4 and ipv6 belong to different subscription groups 296 var sub4, sub6 *pubsub.Subscriber 297 if option.IPv4Enable { 298 sub4 = s.pub.Subscribe(fqdn + "4") 299 defer sub4.Close() 300 } 301 if option.IPv6Enable { 302 sub6 = s.pub.Subscribe(fqdn + "6") 303 defer sub6.Close() 304 } 305 done := make(chan interface{}) 306 go func() { 307 if sub4 != nil { 308 select { 309 case <-sub4.Wait(): 310 case <-ctx.Done(): 311 } 312 } 313 if sub6 != nil { 314 select { 315 case <-sub6.Wait(): 316 case <-ctx.Done(): 317 } 318 } 319 close(done) 320 }() 321 s.sendQuery(ctx, fqdn, clientIP, option) 322 323 for { 324 ips, err := s.findIPsForDomain(fqdn, option) 325 if err != errRecordNotFound { 326 return ips, err 327 } 328 329 select { 330 case <-ctx.Done(): 331 return nil, ctx.Err() 332 case <-done: 333 } 334 } 335 } 336 337 func isActive(s quic.Connection) bool { 338 select { 339 case <-s.Context().Done(): 340 return false 341 default: 342 return true 343 } 344 } 345 346 func (s *QUICNameServer) getConnection(ctx context.Context) (quic.Connection, error) { 347 var conn quic.Connection 348 s.RLock() 349 conn = s.connection 350 if conn != nil && isActive(conn) { 351 s.RUnlock() 352 return conn, nil 353 } 354 if conn != nil { 355 // we're recreating the connection, let's create a new one 356 _ = conn.CloseWithError(0, "") 357 } 358 s.RUnlock() 359 360 s.Lock() 361 defer s.Unlock() 362 363 var err error 364 conn, err = s.openConnection(ctx) 365 if err != nil { 366 // This does not look too nice, but QUIC (or maybe quic-go) 367 // doesn't seem stable enough. 368 // Maybe retransmissions aren't fully implemented in quic-go? 369 // Anyways, the simple solution is to make a second try when 370 // it fails to open the QUIC connection. 371 conn, err = s.openConnection(ctx) 372 if err != nil { 373 return nil, err 374 } 375 } 376 s.connection = conn 377 return conn, nil 378 } 379 380 func (s *QUICNameServer) openConnection(ctx context.Context) (quic.Connection, error) { 381 tlsConfig := tls.Config{} 382 quicConfig := &quic.Config{ 383 HandshakeIdleTimeout: handshakeIdleTimeout, 384 } 385 386 conn, err := quic.DialAddrContext(ctx, s.destination.NetAddr(), tlsConfig.GetTLSConfig(tls.WithNextProto("http/1.1", http2.NextProtoTLS, NextProtoDQ)), quicConfig) 387 if err != nil { 388 return nil, err 389 } 390 391 return conn, nil 392 } 393 394 func (s *QUICNameServer) openStream(ctx context.Context) (quic.Stream, error) { 395 conn, err := s.getConnection(ctx) 396 if err != nil { 397 return nil, err 398 } 399 400 // open a new stream 401 return conn.OpenStreamSync(ctx) 402 }