| 1 | // DNS server implementation. |
| 2 | |
| 3 | package dns |
| 4 | |
| 5 | import ( |
| 6 | "context" |
| 7 | "crypto/tls" |
| 8 | "encoding/binary" |
| 9 | "errors" |
| 10 | "io" |
| 11 | "net" |
| 12 | "strings" |
| 13 | "sync" |
| 14 | "time" |
| 15 | ) |
| 16 | |
| 17 | // Default maximum number of TCP queries before we close the socket. |
| 18 | const maxTCPQueries = 128 |
| 19 | |
| 20 | // aLongTimeAgo is a non-zero time, far in the past, used for |
| 21 | // immediate cancellation of network operations. |
| 22 | var aLongTimeAgo = time.Unix(1, 0) |
| 23 | |
| 24 | // Handler is implemented by any value that implements ServeDNS. |
| 25 | type Handler interface { |
| 26 | ServeDNS(w ResponseWriter, r *Msg) |
| 27 | } |
| 28 | |
| 29 | // The HandlerFunc type is an adapter to allow the use of |
| 30 | // ordinary functions as DNS handlers. If f is a function |
| 31 | // with the appropriate signature, HandlerFunc(f) is a |
| 32 | // Handler object that calls f. |
| 33 | type HandlerFunc func(ResponseWriter, *Msg) |
| 34 | |
| 35 | // ServeDNS calls f(w, r). |
| 36 | func (f HandlerFunc) ServeDNS(w ResponseWriter, r *Msg) { |
| 37 | f(w, r) |
| 38 | } |
| 39 | |
| 40 | // A ResponseWriter interface is used by an DNS handler to |
| 41 | // construct an DNS response. |
| 42 | type ResponseWriter interface { |
| 43 | // LocalAddr returns the net.Addr of the server |
| 44 | LocalAddr() net.Addr |
| 45 | // RemoteAddr returns the net.Addr of the client that sent the current request. |
| 46 | RemoteAddr() net.Addr |
| 47 | // WriteMsg writes a reply back to the client. |
| 48 | WriteMsg(*Msg) error |
| 49 | // Write writes a raw buffer back to the client. |
| 50 | Write([]byte) (int, error) |
| 51 | // Close closes the connection. |
| 52 | Close() error |
| 53 | // TsigStatus returns the status of the Tsig. |
| 54 | TsigStatus() error |
| 55 | // TsigTimersOnly sets the tsig timers only boolean. |
| 56 | TsigTimersOnly(bool) |
| 57 | // Hijack lets the caller take over the connection. |
| 58 | // After a call to Hijack(), the DNS package will not do anything with the connection. |
| 59 | Hijack() |
| 60 | } |
| 61 | |
| 62 | // A ConnectionStater interface is used by a DNS Handler to access TLS connection state |
| 63 | // when available. |
| 64 | type ConnectionStater interface { |
| 65 | ConnectionState() *tls.ConnectionState |
| 66 | } |
| 67 | |
| 68 | type response struct { |
| 69 | closed bool // connection has been closed |
| 70 | hijacked bool // connection has been hijacked by handler |
| 71 | tsigTimersOnly bool |
| 72 | tsigStatus error |
| 73 | tsigRequestMAC string |
| 74 | tsigProvider TsigProvider |
| 75 | udp net.PacketConn // i/o connection if UDP was used |
| 76 | tcp net.Conn // i/o connection if TCP was used |
| 77 | udpSession *SessionUDP // oob data to get egress interface right |
| 78 | pcSession net.Addr // address to use when writing to a generic net.PacketConn |
| 79 | writer Writer // writer to output the raw DNS bits |
| 80 | } |
| 81 | |
| 82 | // handleRefused returns a HandlerFunc that returns REFUSED for every request it gets. |
| 83 | func handleRefused(w ResponseWriter, r *Msg) { |
| 84 | m := new(Msg) |
| 85 | m.SetRcode(r, RcodeRefused) |
| 86 | w.WriteMsg(m) |
| 87 | } |
| 88 | |
| 89 | // HandleFailed returns a HandlerFunc that returns SERVFAIL for every request it gets. |
| 90 | // Deprecated: This function is going away. |
| 91 | func HandleFailed(w ResponseWriter, r *Msg) { |
| 92 | m := new(Msg) |
| 93 | m.SetRcode(r, RcodeServerFailure) |
| 94 | // does not matter if this write fails |
| 95 | w.WriteMsg(m) |
| 96 | } |
| 97 | |
| 98 | // ListenAndServe Starts a server on address and network specified Invoke handler |
| 99 | // for incoming queries. |
| 100 | func ListenAndServe(addr string, network string, handler Handler) error { |
| 101 | server := &Server{Addr: addr, Net: network, Handler: handler} |
| 102 | return server.ListenAndServe() |
| 103 | } |
| 104 | |
| 105 | // ListenAndServeTLS acts like http.ListenAndServeTLS, more information in |
| 106 | // http://golang.org/pkg/net/http/#ListenAndServeTLS |
| 107 | func ListenAndServeTLS(addr, certFile, keyFile string, handler Handler) error { |
| 108 | cert, err := tls.LoadX509KeyPair(certFile, keyFile) |
| 109 | if err != nil { |
| 110 | return err |
| 111 | } |
| 112 | |
| 113 | config := tls.Config{ |
| 114 | Certificates: []tls.Certificate{cert}, |
| 115 | } |
| 116 | |
| 117 | server := &Server{ |
| 118 | Addr: addr, |
| 119 | Net: "tcp-tls", |
| 120 | TLSConfig: &config, |
| 121 | Handler: handler, |
| 122 | } |
| 123 | |
| 124 | return server.ListenAndServe() |
| 125 | } |
| 126 | |
| 127 | // ActivateAndServe activates a server with a listener from systemd, |
| 128 | // l and p should not both be non-nil. |
| 129 | // If both l and p are not nil only p will be used. |
| 130 | // Invoke handler for incoming queries. |
| 131 | func ActivateAndServe(l net.Listener, p net.PacketConn, handler Handler) error { |
| 132 | server := &Server{Listener: l, PacketConn: p, Handler: handler} |
| 133 | return server.ActivateAndServe() |
| 134 | } |
| 135 | |
| 136 | // Writer writes raw DNS messages; each call to Write should send an entire message. |
| 137 | type Writer interface { |
| 138 | io.Writer |
| 139 | } |
| 140 | |
| 141 | // Reader reads raw DNS messages; each call to ReadTCP or ReadUDP should return an entire message. |
| 142 | type Reader interface { |
| 143 | // ReadTCP reads a raw message from a TCP connection. Implementations may alter |
| 144 | // connection properties, for example the read-deadline. |
| 145 | ReadTCP(conn net.Conn, timeout time.Duration) ([]byte, error) |
| 146 | // ReadUDP reads a raw message from a UDP connection. Implementations may alter |
| 147 | // connection properties, for example the read-deadline. |
| 148 | ReadUDP(conn *net.UDPConn, timeout time.Duration) ([]byte, *SessionUDP, error) |
| 149 | } |
| 150 | |
| 151 | // PacketConnReader is an optional interface that Readers can implement to support using generic net.PacketConns. |
| 152 | type PacketConnReader interface { |
| 153 | Reader |
| 154 | |
| 155 | // ReadPacketConn reads a raw message from a generic net.PacketConn UDP connection. Implementations may |
| 156 | // alter connection properties, for example the read-deadline. |
| 157 | ReadPacketConn(conn net.PacketConn, timeout time.Duration) ([]byte, net.Addr, error) |
| 158 | } |
| 159 | |
| 160 | // defaultReader is an adapter for the Server struct that implements the Reader and |
| 161 | // PacketConnReader interfaces using the readTCP, readUDP and readPacketConn funcs |
| 162 | // of the embedded Server. |
| 163 | type defaultReader struct { |
| 164 | *Server |
| 165 | } |
| 166 | |
| 167 | var _ PacketConnReader = defaultReader{} |
| 168 | |
| 169 | func (dr defaultReader) ReadTCP(conn net.Conn, timeout time.Duration) ([]byte, error) { |
| 170 | return dr.readTCP(conn, timeout) |
| 171 | } |
| 172 | |
| 173 | func (dr defaultReader) ReadUDP(conn *net.UDPConn, timeout time.Duration) ([]byte, *SessionUDP, error) { |
| 174 | return dr.readUDP(conn, timeout) |
| 175 | } |
| 176 | |
| 177 | func (dr defaultReader) ReadPacketConn(conn net.PacketConn, timeout time.Duration) ([]byte, net.Addr, error) { |
| 178 | return dr.readPacketConn(conn, timeout) |
| 179 | } |
| 180 | |
| 181 | // DecorateReader is a decorator hook for extending or supplanting the functionality of a Reader. |
| 182 | // Implementations should never return a nil Reader. |
| 183 | // Readers should also implement the optional PacketConnReader interface. |
| 184 | // PacketConnReader is required to use a generic net.PacketConn. |
| 185 | type DecorateReader func(Reader) Reader |
| 186 | |
| 187 | // DecorateWriter is a decorator hook for extending or supplanting the functionality of a Writer. |
| 188 | // Implementations should never return a nil Writer. |
| 189 | type DecorateWriter func(Writer) Writer |
| 190 | |
| 191 | // MsgInvalidFunc is a listener hook for observing incoming messages that were discarded |
| 192 | // because they could not be parsed. |
| 193 | // Every message that is read by a Reader will eventually be provided to the Handler, |
| 194 | // rejected (or ignored) by the MsgAcceptFunc, or passed to this function. |
| 195 | type MsgInvalidFunc func(m []byte, err error) |
| 196 | |
| 197 | var DefaultMsgInvalidFunc MsgInvalidFunc = defaultMsgInvalidFunc |
| 198 | |
| 199 | func defaultMsgInvalidFunc(m []byte, err error) {} |
| 200 | |
| 201 | // A Server defines parameters for running an DNS server. |
| 202 | type Server struct { |
| 203 | // Address to listen on, ":dns" if empty. |
| 204 | Addr string |
| 205 | // if "tcp" or "tcp-tls" (DNS over TLS) it will invoke a TCP listener, otherwise an UDP one |
| 206 | Net string |
| 207 | // TCP Listener to use, this is to aid in systemd's socket activation. |
| 208 | Listener net.Listener |
| 209 | // TLS connection configuration |
| 210 | TLSConfig *tls.Config |
| 211 | // UDP "Listener" to use, this is to aid in systemd's socket activation. |
| 212 | PacketConn net.PacketConn |
| 213 | // Handler to invoke, dns.DefaultServeMux if nil. |
| 214 | Handler Handler |
| 215 | // Default buffer size to use to read incoming UDP messages. If not set |
| 216 | // it defaults to MinMsgSize (512 B). |
| 217 | UDPSize int |
| 218 | // The net.Conn.SetReadTimeout value for new connections, defaults to 2 * time.Second. |
| 219 | ReadTimeout time.Duration |
| 220 | // The net.Conn.SetWriteTimeout value for new connections, defaults to 2 * time.Second. |
| 221 | WriteTimeout time.Duration |
| 222 | // TCP idle timeout for multiple queries, if nil, defaults to 8 * time.Second (RFC 5966). |
| 223 | IdleTimeout func() time.Duration |
| 224 | // An implementation of the TsigProvider interface. If defined it replaces TsigSecret and is used for all TSIG operations. |
| 225 | TsigProvider TsigProvider |
| 226 | // Secret(s) for Tsig map[<zonename>]<base64 secret>. The zonename must be in canonical form (lowercase, fqdn, see RFC 4034 Section 6.2). |
| 227 | TsigSecret map[string]string |
| 228 | // If NotifyStartedFunc is set it is called once the server has started listening. |
| 229 | NotifyStartedFunc func() |
| 230 | // DecorateReader is optional, allows customization of the process that reads raw DNS messages. |
| 231 | // The decorated reader must not mutate the data read from the conn. |
| 232 | DecorateReader DecorateReader |
| 233 | // DecorateWriter is optional, allows customization of the process that writes raw DNS messages. |
| 234 | DecorateWriter DecorateWriter |
| 235 | // Maximum number of TCP queries before we close the socket. Default is maxTCPQueries (unlimited if -1). |
| 236 | MaxTCPQueries int |
| 237 | // Whether to set the SO_REUSEPORT socket option, allowing multiple listeners to be bound to a single address. |
| 238 | // It is only supported on certain GOOSes and when using ListenAndServe. |
| 239 | ReusePort bool |
| 240 | // Whether to set the SO_REUSEADDR socket option, allowing multiple listeners to be bound to a single address. |
| 241 | // Crucially this allows binding when an existing server is listening on `0.0.0.0` or `::`. |
| 242 | // It is only supported on certain GOOSes and when using ListenAndServe. |
| 243 | ReuseAddr bool |
| 244 | // AcceptMsgFunc will check the incoming message and will reject it early in the process. |
| 245 | // By default DefaultMsgAcceptFunc will be used. |
| 246 | MsgAcceptFunc MsgAcceptFunc |
| 247 | // MsgInvalidFunc is optional, will be called if a message is received but cannot be parsed. |
| 248 | MsgInvalidFunc MsgInvalidFunc |
| 249 | |
| 250 | // Shutdown handling |
| 251 | lock sync.RWMutex |
| 252 | started bool |
| 253 | shutdown chan struct{} |
| 254 | conns map[net.Conn]struct{} |
| 255 | |
| 256 | // A pool for UDP message buffers. |
| 257 | udpPool sync.Pool |
| 258 | } |
| 259 | |
| 260 | func (srv *Server) tsigProvider() TsigProvider { |
| 261 | if srv.TsigProvider != nil { |
| 262 | return srv.TsigProvider |
| 263 | } |
| 264 | if srv.TsigSecret != nil { |
| 265 | return tsigSecretProvider(srv.TsigSecret) |
| 266 | } |
| 267 | return nil |
| 268 | } |
| 269 | |
| 270 | func (srv *Server) isStarted() bool { |
| 271 | srv.lock.RLock() |
| 272 | started := srv.started |
| 273 | srv.lock.RUnlock() |
| 274 | return started |
| 275 | } |
| 276 | |
| 277 | func makeUDPBuffer(size int) func() interface{} { |
| 278 | return func() interface{} { |
| 279 | return make([]byte, size) |
| 280 | } |
| 281 | } |
| 282 | |
| 283 | func (srv *Server) init() { |
| 284 | srv.shutdown = make(chan struct{}) |
| 285 | srv.conns = make(map[net.Conn]struct{}) |
| 286 | |
| 287 | if srv.UDPSize == 0 { |
| 288 | srv.UDPSize = MinMsgSize |
| 289 | } |
| 290 | if srv.MsgAcceptFunc == nil { |
| 291 | srv.MsgAcceptFunc = DefaultMsgAcceptFunc |
| 292 | } |
| 293 | if srv.MsgInvalidFunc == nil { |
| 294 | srv.MsgInvalidFunc = DefaultMsgInvalidFunc |
| 295 | } |
| 296 | if srv.Handler == nil { |
| 297 | srv.Handler = DefaultServeMux |
| 298 | } |
| 299 | |
| 300 | srv.udpPool.New = makeUDPBuffer(srv.UDPSize) |
| 301 | } |
| 302 | |
| 303 | func unlockOnce(l sync.Locker) func() { |
| 304 | var once sync.Once |
| 305 | return func() { once.Do(l.Unlock) } |
| 306 | } |
| 307 | |
| 308 | // ListenAndServe starts a nameserver on the configured address in *Server. |
| 309 | func (srv *Server) ListenAndServe() error { |
| 310 | unlock := unlockOnce(&srv.lock) |
| 311 | srv.lock.Lock() |
| 312 | defer unlock() |
| 313 | |
| 314 | if srv.started { |
| 315 | return &Error{err: "server already started"} |
| 316 | } |
| 317 | |
| 318 | addr := srv.Addr |
| 319 | if addr == "" { |
| 320 | addr = ":domain" |
| 321 | } |
| 322 | |
| 323 | srv.init() |
| 324 | |
| 325 | switch srv.Net { |
| 326 | case "tcp", "tcp4", "tcp6": |
| 327 | l, err := listenTCP(srv.Net, addr, srv.ReusePort, srv.ReuseAddr) |
| 328 | if err != nil { |
| 329 | return err |
| 330 | } |
| 331 | srv.Listener = l |
| 332 | srv.started = true |
| 333 | unlock() |
| 334 | return srv.serveTCP(l) |
| 335 | case "tcp-tls", "tcp4-tls", "tcp6-tls": |
| 336 | if srv.TLSConfig == nil || (len(srv.TLSConfig.Certificates) == 0 && srv.TLSConfig.GetCertificate == nil) { |
| 337 | return errors.New("neither Certificates nor GetCertificate set in config") |
| 338 | } |
| 339 | network := strings.TrimSuffix(srv.Net, "-tls") |
| 340 | l, err := listenTCP(network, addr, srv.ReusePort, srv.ReuseAddr) |
| 341 | if err != nil { |
| 342 | return err |
| 343 | } |
| 344 | l = tls.NewListener(l, srv.TLSConfig) |
| 345 | srv.Listener = l |
| 346 | srv.started = true |
| 347 | unlock() |
| 348 | return srv.serveTCP(l) |
| 349 | case "udp", "udp4", "udp6": |
| 350 | l, err := listenUDP(srv.Net, addr, srv.ReusePort, srv.ReuseAddr) |
| 351 | if err != nil { |
| 352 | return err |
| 353 | } |
| 354 | u := l.(*net.UDPConn) |
| 355 | if e := setUDPSocketOptions(u); e != nil { |
| 356 | u.Close() |
| 357 | return e |
| 358 | } |
| 359 | srv.PacketConn = l |
| 360 | srv.started = true |
| 361 | unlock() |
| 362 | return srv.serveUDP(u) |
| 363 | } |
| 364 | return &Error{err: "bad network"} |
| 365 | } |
| 366 | |
| 367 | // ActivateAndServe starts a nameserver with the PacketConn or Listener |
| 368 | // configured in *Server. Its main use is to start a server from systemd. |
| 369 | func (srv *Server) ActivateAndServe() error { |
| 370 | unlock := unlockOnce(&srv.lock) |
| 371 | srv.lock.Lock() |
| 372 | defer unlock() |
| 373 | |
| 374 | if srv.started { |
| 375 | return &Error{err: "server already started"} |
| 376 | } |
| 377 | |
| 378 | srv.init() |
| 379 | |
| 380 | if srv.PacketConn != nil { |
| 381 | // Check PacketConn interface's type is valid and value |
| 382 | // is not nil |
| 383 | if t, ok := srv.PacketConn.(*net.UDPConn); ok && t != nil { |
| 384 | if e := setUDPSocketOptions(t); e != nil { |
| 385 | return e |
| 386 | } |
| 387 | } |
| 388 | srv.started = true |
| 389 | unlock() |
| 390 | return srv.serveUDP(srv.PacketConn) |
| 391 | } |
| 392 | if srv.Listener != nil { |
| 393 | srv.started = true |
| 394 | unlock() |
| 395 | return srv.serveTCP(srv.Listener) |
| 396 | } |
| 397 | return &Error{err: "bad listeners"} |
| 398 | } |
| 399 | |
| 400 | // Shutdown shuts down a server. After a call to Shutdown, ListenAndServe and |
| 401 | // ActivateAndServe will return. |
| 402 | func (srv *Server) Shutdown() error { |
| 403 | return srv.ShutdownContext(context.Background()) |
| 404 | } |
| 405 | |
| 406 | // ShutdownContext shuts down a server. After a call to ShutdownContext, |
| 407 | // ListenAndServe and ActivateAndServe will return. |
| 408 | // |
| 409 | // A context.Context may be passed to limit how long to wait for connections |
| 410 | // to terminate. |
| 411 | func (srv *Server) ShutdownContext(ctx context.Context) error { |
| 412 | srv.lock.Lock() |
| 413 | if !srv.started { |
| 414 | srv.lock.Unlock() |
| 415 | return &Error{err: "server not started"} |
| 416 | } |
| 417 | |
| 418 | srv.started = false |
| 419 | |
| 420 | if srv.PacketConn != nil { |
| 421 | srv.PacketConn.SetReadDeadline(aLongTimeAgo) // Unblock reads |
| 422 | } |
| 423 | |
| 424 | if srv.Listener != nil { |
| 425 | srv.Listener.Close() |
| 426 | } |
| 427 | |
| 428 | for rw := range srv.conns { |
| 429 | rw.SetReadDeadline(aLongTimeAgo) // Unblock reads |
| 430 | } |
| 431 | |
| 432 | srv.lock.Unlock() |
| 433 | |
| 434 | if testShutdownNotify != nil { |
| 435 | testShutdownNotify.Broadcast() |
| 436 | } |
| 437 | |
| 438 | var ctxErr error |
| 439 | select { |
| 440 | case <-srv.shutdown: |
| 441 | case <-ctx.Done(): |
| 442 | ctxErr = ctx.Err() |
| 443 | } |
| 444 | |
| 445 | if srv.PacketConn != nil { |
| 446 | srv.PacketConn.Close() |
| 447 | } |
| 448 | |
| 449 | return ctxErr |
| 450 | } |
| 451 | |
| 452 | var testShutdownNotify *sync.Cond |
| 453 | |
| 454 | // getReadTimeout is a helper func to use system timeout if server did not intend to change it. |
| 455 | func (srv *Server) getReadTimeout() time.Duration { |
| 456 | if srv.ReadTimeout != 0 { |
| 457 | return srv.ReadTimeout |
| 458 | } |
| 459 | return dnsTimeout |
| 460 | } |
| 461 | |
| 462 | // serveTCP starts a TCP listener for the server. |
| 463 | func (srv *Server) serveTCP(l net.Listener) error { |
| 464 | defer l.Close() |
| 465 | |
| 466 | if srv.NotifyStartedFunc != nil { |
| 467 | srv.NotifyStartedFunc() |
| 468 | } |
| 469 | |
| 470 | var wg sync.WaitGroup |
| 471 | defer func() { |
| 472 | wg.Wait() |
| 473 | close(srv.shutdown) |
| 474 | }() |
| 475 | |
| 476 | for srv.isStarted() { |
| 477 | rw, err := l.Accept() |
| 478 | if err != nil { |
| 479 | if !srv.isStarted() { |
| 480 | return nil |
| 481 | } |
| 482 | if neterr, ok := err.(net.Error); ok && neterr.Temporary() { |
| 483 | continue |
| 484 | } |
| 485 | return err |
| 486 | } |
| 487 | srv.lock.Lock() |
| 488 | // Track the connection to allow unblocking reads on shutdown. |
| 489 | srv.conns[rw] = struct{}{} |
| 490 | srv.lock.Unlock() |
| 491 | wg.Add(1) |
| 492 | go srv.serveTCPConn(&wg, rw) |
| 493 | } |
| 494 | |
| 495 | return nil |
| 496 | } |
| 497 | |
| 498 | // serveUDP starts a UDP listener for the server. |
| 499 | func (srv *Server) serveUDP(l net.PacketConn) error { |
| 500 | defer l.Close() |
| 501 | |
| 502 | reader := Reader(defaultReader{srv}) |
| 503 | if srv.DecorateReader != nil { |
| 504 | reader = srv.DecorateReader(reader) |
| 505 | } |
| 506 | |
| 507 | lUDP, isUDP := l.(*net.UDPConn) |
| 508 | readerPC, canPacketConn := reader.(PacketConnReader) |
| 509 | if !isUDP && !canPacketConn { |
| 510 | return &Error{err: "PacketConnReader was not implemented on Reader returned from DecorateReader but is required for net.PacketConn"} |
| 511 | } |
| 512 | |
| 513 | if srv.NotifyStartedFunc != nil { |
| 514 | srv.NotifyStartedFunc() |
| 515 | } |
| 516 | |
| 517 | var wg sync.WaitGroup |
| 518 | defer func() { |
| 519 | wg.Wait() |
| 520 | close(srv.shutdown) |
| 521 | }() |
| 522 | |
| 523 | rtimeout := srv.getReadTimeout() |
| 524 | // deadline is not used here |
| 525 | for srv.isStarted() { |
| 526 | var ( |
| 527 | m []byte |
| 528 | sPC net.Addr |
| 529 | sUDP *SessionUDP |
| 530 | err error |
| 531 | ) |
| 532 | if isUDP { |
| 533 | m, sUDP, err = reader.ReadUDP(lUDP, rtimeout) |
| 534 | } else { |
| 535 | m, sPC, err = readerPC.ReadPacketConn(l, rtimeout) |
| 536 | } |
| 537 | if err != nil { |
| 538 | if !srv.isStarted() { |
| 539 | return nil |
| 540 | } |
| 541 | if netErr, ok := err.(net.Error); ok && netErr.Temporary() { |
| 542 | continue |
| 543 | } |
| 544 | return err |
| 545 | } |
| 546 | if len(m) < headerSize { |
| 547 | if cap(m) == srv.UDPSize { |
| 548 | srv.udpPool.Put(m[:srv.UDPSize]) |
| 549 | } |
| 550 | srv.MsgInvalidFunc(m, ErrShortRead) |
| 551 | continue |
| 552 | } |
| 553 | wg.Add(1) |
| 554 | go srv.serveUDPPacket(&wg, m, l, sUDP, sPC) |
| 555 | } |
| 556 | |
| 557 | return nil |
| 558 | } |
| 559 | |
| 560 | // Serve a new TCP connection. |
| 561 | func (srv *Server) serveTCPConn(wg *sync.WaitGroup, rw net.Conn) { |
| 562 | w := &response{tsigProvider: srv.tsigProvider(), tcp: rw} |
| 563 | if srv.DecorateWriter != nil { |
| 564 | w.writer = srv.DecorateWriter(w) |
| 565 | } else { |
| 566 | w.writer = w |
| 567 | } |
| 568 | |
| 569 | reader := Reader(defaultReader{srv}) |
| 570 | if srv.DecorateReader != nil { |
| 571 | reader = srv.DecorateReader(reader) |
| 572 | } |
| 573 | |
| 574 | idleTimeout := tcpIdleTimeout |
| 575 | if srv.IdleTimeout != nil { |
| 576 | idleTimeout = srv.IdleTimeout() |
| 577 | } |
| 578 | |
| 579 | timeout := srv.getReadTimeout() |
| 580 | |
| 581 | limit := srv.MaxTCPQueries |
| 582 | if limit == 0 { |
| 583 | limit = maxTCPQueries |
| 584 | } |
| 585 | |
| 586 | for q := 0; (q < limit || limit == -1) && srv.isStarted(); q++ { |
| 587 | m, err := reader.ReadTCP(w.tcp, timeout) |
| 588 | if err != nil { |
| 589 | // TODO(tmthrgd): handle error |
| 590 | break |
| 591 | } |
| 592 | srv.serveDNS(m, w) |
| 593 | if w.closed { |
| 594 | break // Close() was called |
| 595 | } |
| 596 | if w.hijacked { |
| 597 | break // client will call Close() themselves |
| 598 | } |
| 599 | // The first read uses the read timeout, the rest use the |
| 600 | // idle timeout. |
| 601 | timeout = idleTimeout |
| 602 | } |
| 603 | |
| 604 | if !w.hijacked { |
| 605 | w.Close() |
| 606 | } |
| 607 | |
| 608 | srv.lock.Lock() |
| 609 | delete(srv.conns, w.tcp) |
| 610 | srv.lock.Unlock() |
| 611 | |
| 612 | wg.Done() |
| 613 | } |
| 614 | |
| 615 | // Serve a new UDP request. |
| 616 | func (srv *Server) serveUDPPacket(wg *sync.WaitGroup, m []byte, u net.PacketConn, udpSession *SessionUDP, pcSession net.Addr) { |
| 617 | w := &response{tsigProvider: srv.tsigProvider(), udp: u, udpSession: udpSession, pcSession: pcSession} |
| 618 | if srv.DecorateWriter != nil { |
| 619 | w.writer = srv.DecorateWriter(w) |
| 620 | } else { |
| 621 | w.writer = w |
| 622 | } |
| 623 | |
| 624 | srv.serveDNS(m, w) |
| 625 | wg.Done() |
| 626 | } |
| 627 | |
| 628 | func (srv *Server) serveDNS(m []byte, w *response) { |
| 629 | dh, off, err := unpackMsgHdr(m, 0) |
| 630 | if err != nil { |
| 631 | srv.MsgInvalidFunc(m, err) |
| 632 | // Let client hang, they are sending crap; any reply can be used to amplify. |
| 633 | return |
| 634 | } |
| 635 | |
| 636 | req := new(Msg) |
| 637 | req.setHdr(dh) |
| 638 | |
| 639 | switch action := srv.MsgAcceptFunc(dh); action { |
| 640 | case MsgAccept: |
| 641 | err := req.unpack(dh, m, off) |
| 642 | if err == nil { |
| 643 | break |
| 644 | } |
| 645 | |
| 646 | srv.MsgInvalidFunc(m, err) |
| 647 | fallthrough |
| 648 | case MsgReject, MsgRejectNotImplemented: |
| 649 | opcode := req.Opcode |
| 650 | req.SetRcodeFormatError(req) |
| 651 | req.Zero = false |
| 652 | if action == MsgRejectNotImplemented { |
| 653 | req.Opcode = opcode |
| 654 | req.Rcode = RcodeNotImplemented |
| 655 | } |
| 656 | |
| 657 | // Are we allowed to delete any OPT records here? |
| 658 | req.Ns, req.Answer, req.Extra = nil, nil, nil |
| 659 | |
| 660 | w.WriteMsg(req) |
| 661 | fallthrough |
| 662 | case MsgIgnore: |
| 663 | if w.udp != nil && cap(m) == srv.UDPSize { |
| 664 | srv.udpPool.Put(m[:srv.UDPSize]) |
| 665 | } |
| 666 | |
| 667 | return |
| 668 | } |
| 669 | |
| 670 | w.tsigStatus = nil |
| 671 | if w.tsigProvider != nil { |
| 672 | if t := req.IsTsig(); t != nil { |
| 673 | w.tsigStatus = TsigVerifyWithProvider(m, w.tsigProvider, "", false) |
| 674 | w.tsigTimersOnly = false |
| 675 | w.tsigRequestMAC = t.MAC |
| 676 | } |
| 677 | } |
| 678 | |
| 679 | if w.udp != nil && cap(m) == srv.UDPSize { |
| 680 | srv.udpPool.Put(m[:srv.UDPSize]) |
| 681 | } |
| 682 | |
| 683 | srv.Handler.ServeDNS(w, req) // Writes back to the client |
| 684 | } |
| 685 | |
| 686 | func (srv *Server) readTCP(conn net.Conn, timeout time.Duration) ([]byte, error) { |
| 687 | // If we race with ShutdownContext, the read deadline may |
| 688 | // have been set in the distant past to unblock the read |
| 689 | // below. We must not override it, otherwise we may block |
| 690 | // ShutdownContext. |
| 691 | srv.lock.RLock() |
| 692 | if srv.started { |
| 693 | conn.SetReadDeadline(time.Now().Add(timeout)) |
| 694 | } |
| 695 | srv.lock.RUnlock() |
| 696 | |
| 697 | var length uint16 |
| 698 | if err := binary.Read(conn, binary.BigEndian, &length); err != nil { |
| 699 | return nil, err |
| 700 | } |
| 701 | |
| 702 | m := make([]byte, length) |
| 703 | if _, err := io.ReadFull(conn, m); err != nil { |
| 704 | return nil, err |
| 705 | } |
| 706 | |
| 707 | return m, nil |
| 708 | } |
| 709 | |
| 710 | func (srv *Server) readUDP(conn *net.UDPConn, timeout time.Duration) ([]byte, *SessionUDP, error) { |
| 711 | srv.lock.RLock() |
| 712 | if srv.started { |
| 713 | // See the comment in readTCP above. |
| 714 | conn.SetReadDeadline(time.Now().Add(timeout)) |
| 715 | } |
| 716 | srv.lock.RUnlock() |
| 717 | |
| 718 | m := srv.udpPool.Get().([]byte) |
| 719 | n, s, err := ReadFromSessionUDP(conn, m) |
| 720 | if err != nil { |
| 721 | srv.udpPool.Put(m) |
| 722 | return nil, nil, err |
| 723 | } |
| 724 | m = m[:n] |
| 725 | return m, s, nil |
| 726 | } |
| 727 | |
| 728 | func (srv *Server) readPacketConn(conn net.PacketConn, timeout time.Duration) ([]byte, net.Addr, error) { |
| 729 | srv.lock.RLock() |
| 730 | if srv.started { |
| 731 | // See the comment in readTCP above. |
| 732 | conn.SetReadDeadline(time.Now().Add(timeout)) |
| 733 | } |
| 734 | srv.lock.RUnlock() |
| 735 | |
| 736 | m := srv.udpPool.Get().([]byte) |
| 737 | n, addr, err := conn.ReadFrom(m) |
| 738 | if err != nil { |
| 739 | srv.udpPool.Put(m) |
| 740 | return nil, nil, err |
| 741 | } |
| 742 | m = m[:n] |
| 743 | return m, addr, nil |
| 744 | } |
| 745 | |
| 746 | // WriteMsg implements the ResponseWriter.WriteMsg method. |
| 747 | func (w *response) WriteMsg(m *Msg) (err error) { |
| 748 | if w.closed { |
| 749 | return &Error{err: "WriteMsg called after Close"} |
| 750 | } |
| 751 | |
| 752 | var data []byte |
| 753 | if w.tsigProvider != nil { // if no provider, dont check for the tsig (which is a longer check) |
| 754 | if t := m.IsTsig(); t != nil { |
| 755 | data, w.tsigRequestMAC, err = TsigGenerateWithProvider(m, w.tsigProvider, w.tsigRequestMAC, w.tsigTimersOnly) |
| 756 | if err != nil { |
| 757 | return err |
| 758 | } |
| 759 | _, err = w.writer.Write(data) |
| 760 | return err |
| 761 | } |
| 762 | } |
| 763 | data, err = m.Pack() |
| 764 | if err != nil { |
| 765 | return err |
| 766 | } |
| 767 | _, err = w.writer.Write(data) |
| 768 | return err |
| 769 | } |
| 770 | |
| 771 | // Write implements the ResponseWriter.Write method. |
| 772 | func (w *response) Write(m []byte) (int, error) { |
| 773 | if w.closed { |
| 774 | return 0, &Error{err: "Write called after Close"} |
| 775 | } |
| 776 | |
| 777 | switch { |
| 778 | case w.udp != nil: |
| 779 | if u, ok := w.udp.(*net.UDPConn); ok { |
| 780 | return WriteToSessionUDP(u, m, w.udpSession) |
| 781 | } |
| 782 | return w.udp.WriteTo(m, w.pcSession) |
| 783 | case w.tcp != nil: |
| 784 | if len(m) > MaxMsgSize { |
| 785 | return 0, &Error{err: "message too large"} |
| 786 | } |
| 787 | |
| 788 | msg := make([]byte, 2+len(m)) |
| 789 | binary.BigEndian.PutUint16(msg, uint16(len(m))) |
| 790 | copy(msg[2:], m) |
| 791 | return w.tcp.Write(msg) |
| 792 | default: |
| 793 | panic("dns: internal error: udp and tcp both nil") |
| 794 | } |
| 795 | } |
| 796 | |
| 797 | // LocalAddr implements the ResponseWriter.LocalAddr method. |
| 798 | func (w *response) LocalAddr() net.Addr { |
| 799 | switch { |
| 800 | case w.udp != nil: |
| 801 | return w.udp.LocalAddr() |
| 802 | case w.tcp != nil: |
| 803 | return w.tcp.LocalAddr() |
| 804 | default: |
| 805 | panic("dns: internal error: udp and tcp both nil") |
| 806 | } |
| 807 | } |
| 808 | |
| 809 | // RemoteAddr implements the ResponseWriter.RemoteAddr method. |
| 810 | func (w *response) RemoteAddr() net.Addr { |
| 811 | switch { |
| 812 | case w.udpSession != nil: |
| 813 | return w.udpSession.RemoteAddr() |
| 814 | case w.pcSession != nil: |
| 815 | return w.pcSession |
| 816 | case w.tcp != nil: |
| 817 | return w.tcp.RemoteAddr() |
| 818 | default: |
| 819 | panic("dns: internal error: udpSession, pcSession and tcp are all nil") |
| 820 | } |
| 821 | } |
| 822 | |
| 823 | // TsigStatus implements the ResponseWriter.TsigStatus method. |
| 824 | func (w *response) TsigStatus() error { return w.tsigStatus } |
| 825 | |
| 826 | // TsigTimersOnly implements the ResponseWriter.TsigTimersOnly method. |
| 827 | func (w *response) TsigTimersOnly(b bool) { w.tsigTimersOnly = b } |
| 828 | |
| 829 | // Hijack implements the ResponseWriter.Hijack method. |
| 830 | func (w *response) Hijack() { w.hijacked = true } |
| 831 | |
| 832 | // Close implements the ResponseWriter.Close method |
| 833 | func (w *response) Close() error { |
| 834 | if w.closed { |
| 835 | return &Error{err: "connection already closed"} |
| 836 | } |
| 837 | w.closed = true |
| 838 | |
| 839 | switch { |
| 840 | case w.udp != nil: |
| 841 | // Can't close the udp conn, as that is actually the listener. |
| 842 | return nil |
| 843 | case w.tcp != nil: |
| 844 | return w.tcp.Close() |
| 845 | default: |
| 846 | panic("dns: internal error: udp and tcp both nil") |
| 847 | } |
| 848 | } |
| 849 | |
| 850 | // ConnectionState() implements the ConnectionStater.ConnectionState() interface. |
| 851 | func (w *response) ConnectionState() *tls.ConnectionState { |
| 852 | type tlsConnectionStater interface { |
| 853 | ConnectionState() tls.ConnectionState |
| 854 | } |
| 855 | if v, ok := w.tcp.(tlsConnectionStater); ok { |
| 856 | t := v.ConnectionState() |
| 857 | return &t |
| 858 | } |
| 859 | return nil |
| 860 | } |