server.go 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782
  1. // DNS server implementation.
  2. package dns
  3. import (
  4. "bytes"
  5. "crypto/tls"
  6. "encoding/binary"
  7. "io"
  8. "net"
  9. "sync"
  10. "sync/atomic"
  11. "time"
  12. )
  13. // Default maximum number of TCP queries before we close the socket.
  14. const maxTCPQueries = 128
  15. // Interval for stop worker if no load
  16. const idleWorkerTimeout = 10 * time.Second
  17. // Maximum number of workers
  18. const maxWorkersCount = 10000
  19. // Handler is implemented by any value that implements ServeDNS.
  20. type Handler interface {
  21. ServeDNS(w ResponseWriter, r *Msg)
  22. }
  23. // A ResponseWriter interface is used by an DNS handler to
  24. // construct an DNS response.
  25. type ResponseWriter interface {
  26. // LocalAddr returns the net.Addr of the server
  27. LocalAddr() net.Addr
  28. // RemoteAddr returns the net.Addr of the client that sent the current request.
  29. RemoteAddr() net.Addr
  30. // WriteMsg writes a reply back to the client.
  31. WriteMsg(*Msg) error
  32. // Write writes a raw buffer back to the client.
  33. Write([]byte) (int, error)
  34. // Close closes the connection.
  35. Close() error
  36. // TsigStatus returns the status of the Tsig.
  37. TsigStatus() error
  38. // TsigTimersOnly sets the tsig timers only boolean.
  39. TsigTimersOnly(bool)
  40. // Hijack lets the caller take over the connection.
  41. // After a call to Hijack(), the DNS package will not do anything with the connection.
  42. Hijack()
  43. }
  44. type response struct {
  45. msg []byte
  46. hijacked bool // connection has been hijacked by handler
  47. tsigStatus error
  48. tsigTimersOnly bool
  49. tsigRequestMAC string
  50. tsigSecret map[string]string // the tsig secrets
  51. udp *net.UDPConn // i/o connection if UDP was used
  52. tcp net.Conn // i/o connection if TCP was used
  53. udpSession *SessionUDP // oob data to get egress interface right
  54. writer Writer // writer to output the raw DNS bits
  55. }
  56. // ServeMux is an DNS request multiplexer. It matches the
  57. // zone name of each incoming request against a list of
  58. // registered patterns add calls the handler for the pattern
  59. // that most closely matches the zone name. ServeMux is DNSSEC aware, meaning
  60. // that queries for the DS record are redirected to the parent zone (if that
  61. // is also registered), otherwise the child gets the query.
  62. // ServeMux is also safe for concurrent access from multiple goroutines.
  63. type ServeMux struct {
  64. z map[string]Handler
  65. m *sync.RWMutex
  66. }
  67. // NewServeMux allocates and returns a new ServeMux.
  68. func NewServeMux() *ServeMux { return &ServeMux{z: make(map[string]Handler), m: new(sync.RWMutex)} }
  69. // DefaultServeMux is the default ServeMux used by Serve.
  70. var DefaultServeMux = NewServeMux()
  71. // The HandlerFunc type is an adapter to allow the use of
  72. // ordinary functions as DNS handlers. If f is a function
  73. // with the appropriate signature, HandlerFunc(f) is a
  74. // Handler object that calls f.
  75. type HandlerFunc func(ResponseWriter, *Msg)
  76. // ServeDNS calls f(w, r).
  77. func (f HandlerFunc) ServeDNS(w ResponseWriter, r *Msg) {
  78. f(w, r)
  79. }
  80. // HandleFailed returns a HandlerFunc that returns SERVFAIL for every request it gets.
  81. func HandleFailed(w ResponseWriter, r *Msg) {
  82. m := new(Msg)
  83. m.SetRcode(r, RcodeServerFailure)
  84. // does not matter if this write fails
  85. w.WriteMsg(m)
  86. }
  87. func failedHandler() Handler { return HandlerFunc(HandleFailed) }
  88. // ListenAndServe Starts a server on address and network specified Invoke handler
  89. // for incoming queries.
  90. func ListenAndServe(addr string, network string, handler Handler) error {
  91. server := &Server{Addr: addr, Net: network, Handler: handler}
  92. return server.ListenAndServe()
  93. }
  94. // ListenAndServeTLS acts like http.ListenAndServeTLS, more information in
  95. // http://golang.org/pkg/net/http/#ListenAndServeTLS
  96. func ListenAndServeTLS(addr, certFile, keyFile string, handler Handler) error {
  97. cert, err := tls.LoadX509KeyPair(certFile, keyFile)
  98. if err != nil {
  99. return err
  100. }
  101. config := tls.Config{
  102. Certificates: []tls.Certificate{cert},
  103. }
  104. server := &Server{
  105. Addr: addr,
  106. Net: "tcp-tls",
  107. TLSConfig: &config,
  108. Handler: handler,
  109. }
  110. return server.ListenAndServe()
  111. }
  112. // ActivateAndServe activates a server with a listener from systemd,
  113. // l and p should not both be non-nil.
  114. // If both l and p are not nil only p will be used.
  115. // Invoke handler for incoming queries.
  116. func ActivateAndServe(l net.Listener, p net.PacketConn, handler Handler) error {
  117. server := &Server{Listener: l, PacketConn: p, Handler: handler}
  118. return server.ActivateAndServe()
  119. }
  120. func (mux *ServeMux) match(q string, t uint16) Handler {
  121. mux.m.RLock()
  122. defer mux.m.RUnlock()
  123. var handler Handler
  124. b := make([]byte, len(q)) // worst case, one label of length q
  125. off := 0
  126. end := false
  127. for {
  128. l := len(q[off:])
  129. for i := 0; i < l; i++ {
  130. b[i] = q[off+i]
  131. if b[i] >= 'A' && b[i] <= 'Z' {
  132. b[i] |= ('a' - 'A')
  133. }
  134. }
  135. if h, ok := mux.z[string(b[:l])]; ok { // causes garbage, might want to change the map key
  136. if t != TypeDS {
  137. return h
  138. }
  139. // Continue for DS to see if we have a parent too, if so delegeate to the parent
  140. handler = h
  141. }
  142. off, end = NextLabel(q, off)
  143. if end {
  144. break
  145. }
  146. }
  147. // Wildcard match, if we have found nothing try the root zone as a last resort.
  148. if h, ok := mux.z["."]; ok {
  149. return h
  150. }
  151. return handler
  152. }
  153. // Handle adds a handler to the ServeMux for pattern.
  154. func (mux *ServeMux) Handle(pattern string, handler Handler) {
  155. if pattern == "" {
  156. panic("dns: invalid pattern " + pattern)
  157. }
  158. mux.m.Lock()
  159. mux.z[Fqdn(pattern)] = handler
  160. mux.m.Unlock()
  161. }
  162. // HandleFunc adds a handler function to the ServeMux for pattern.
  163. func (mux *ServeMux) HandleFunc(pattern string, handler func(ResponseWriter, *Msg)) {
  164. mux.Handle(pattern, HandlerFunc(handler))
  165. }
  166. // HandleRemove deregistrars the handler specific for pattern from the ServeMux.
  167. func (mux *ServeMux) HandleRemove(pattern string) {
  168. if pattern == "" {
  169. panic("dns: invalid pattern " + pattern)
  170. }
  171. mux.m.Lock()
  172. delete(mux.z, Fqdn(pattern))
  173. mux.m.Unlock()
  174. }
  175. // ServeDNS dispatches the request to the handler whose
  176. // pattern most closely matches the request message. If DefaultServeMux
  177. // is used the correct thing for DS queries is done: a possible parent
  178. // is sought.
  179. // If no handler is found a standard SERVFAIL message is returned
  180. // If the request message does not have exactly one question in the
  181. // question section a SERVFAIL is returned, unlesss Unsafe is true.
  182. func (mux *ServeMux) ServeDNS(w ResponseWriter, request *Msg) {
  183. var h Handler
  184. if len(request.Question) < 1 { // allow more than one question
  185. h = failedHandler()
  186. } else {
  187. if h = mux.match(request.Question[0].Name, request.Question[0].Qtype); h == nil {
  188. h = failedHandler()
  189. }
  190. }
  191. h.ServeDNS(w, request)
  192. }
  193. // Handle registers the handler with the given pattern
  194. // in the DefaultServeMux. The documentation for
  195. // ServeMux explains how patterns are matched.
  196. func Handle(pattern string, handler Handler) { DefaultServeMux.Handle(pattern, handler) }
  197. // HandleRemove deregisters the handle with the given pattern
  198. // in the DefaultServeMux.
  199. func HandleRemove(pattern string) { DefaultServeMux.HandleRemove(pattern) }
  200. // HandleFunc registers the handler function with the given pattern
  201. // in the DefaultServeMux.
  202. func HandleFunc(pattern string, handler func(ResponseWriter, *Msg)) {
  203. DefaultServeMux.HandleFunc(pattern, handler)
  204. }
  205. // Writer writes raw DNS messages; each call to Write should send an entire message.
  206. type Writer interface {
  207. io.Writer
  208. }
  209. // Reader reads raw DNS messages; each call to ReadTCP or ReadUDP should return an entire message.
  210. type Reader interface {
  211. // ReadTCP reads a raw message from a TCP connection. Implementations may alter
  212. // connection properties, for example the read-deadline.
  213. ReadTCP(conn net.Conn, timeout time.Duration) ([]byte, error)
  214. // ReadUDP reads a raw message from a UDP connection. Implementations may alter
  215. // connection properties, for example the read-deadline.
  216. ReadUDP(conn *net.UDPConn, timeout time.Duration) ([]byte, *SessionUDP, error)
  217. }
  218. // defaultReader is an adapter for the Server struct that implements the Reader interface
  219. // using the readTCP and readUDP func of the embedded Server.
  220. type defaultReader struct {
  221. *Server
  222. }
  223. func (dr *defaultReader) ReadTCP(conn net.Conn, timeout time.Duration) ([]byte, error) {
  224. return dr.readTCP(conn, timeout)
  225. }
  226. func (dr *defaultReader) ReadUDP(conn *net.UDPConn, timeout time.Duration) ([]byte, *SessionUDP, error) {
  227. return dr.readUDP(conn, timeout)
  228. }
  229. // DecorateReader is a decorator hook for extending or supplanting the functionality of a Reader.
  230. // Implementations should never return a nil Reader.
  231. type DecorateReader func(Reader) Reader
  232. // DecorateWriter is a decorator hook for extending or supplanting the functionality of a Writer.
  233. // Implementations should never return a nil Writer.
  234. type DecorateWriter func(Writer) Writer
  235. // A Server defines parameters for running an DNS server.
  236. type Server struct {
  237. // Address to listen on, ":dns" if empty.
  238. Addr string
  239. // if "tcp" or "tcp-tls" (DNS over TLS) it will invoke a TCP listener, otherwise an UDP one
  240. Net string
  241. // TCP Listener to use, this is to aid in systemd's socket activation.
  242. Listener net.Listener
  243. // TLS connection configuration
  244. TLSConfig *tls.Config
  245. // UDP "Listener" to use, this is to aid in systemd's socket activation.
  246. PacketConn net.PacketConn
  247. // Handler to invoke, dns.DefaultServeMux if nil.
  248. Handler Handler
  249. // Default buffer size to use to read incoming UDP messages. If not set
  250. // it defaults to MinMsgSize (512 B).
  251. UDPSize int
  252. // The net.Conn.SetReadTimeout value for new connections, defaults to 2 * time.Second.
  253. ReadTimeout time.Duration
  254. // The net.Conn.SetWriteTimeout value for new connections, defaults to 2 * time.Second.
  255. WriteTimeout time.Duration
  256. // TCP idle timeout for multiple queries, if nil, defaults to 8 * time.Second (RFC 5966).
  257. IdleTimeout func() time.Duration
  258. // Secret(s) for Tsig map[<zonename>]<base64 secret>. The zonename must be in canonical form (lowercase, fqdn, see RFC 4034 Section 6.2).
  259. TsigSecret map[string]string
  260. // Unsafe instructs the server to disregard any sanity checks and directly hand the message to
  261. // the handler. It will specifically not check if the query has the QR bit not set.
  262. Unsafe bool
  263. // If NotifyStartedFunc is set it is called once the server has started listening.
  264. NotifyStartedFunc func()
  265. // DecorateReader is optional, allows customization of the process that reads raw DNS messages.
  266. DecorateReader DecorateReader
  267. // DecorateWriter is optional, allows customization of the process that writes raw DNS messages.
  268. DecorateWriter DecorateWriter
  269. // Maximum number of TCP queries before we close the socket. Default is maxTCPQueries (unlimited if -1).
  270. MaxTCPQueries int
  271. // UDP packet or TCP connection queue
  272. queue chan *response
  273. // Workers count
  274. workersCount int32
  275. // Shutdown handling
  276. lock sync.RWMutex
  277. started bool
  278. }
  279. func (srv *Server) worker(w *response) {
  280. srv.serve(w)
  281. for {
  282. count := atomic.LoadInt32(&srv.workersCount)
  283. if count > maxWorkersCount {
  284. return
  285. }
  286. if atomic.CompareAndSwapInt32(&srv.workersCount, count, count+1) {
  287. break
  288. }
  289. }
  290. defer atomic.AddInt32(&srv.workersCount, -1)
  291. inUse := false
  292. timeout := time.NewTimer(idleWorkerTimeout)
  293. defer timeout.Stop()
  294. LOOP:
  295. for {
  296. select {
  297. case w, ok := <-srv.queue:
  298. if !ok {
  299. break LOOP
  300. }
  301. inUse = true
  302. srv.serve(w)
  303. case <-timeout.C:
  304. if !inUse {
  305. break LOOP
  306. }
  307. inUse = false
  308. timeout.Reset(idleWorkerTimeout)
  309. }
  310. }
  311. }
  312. func (srv *Server) spawnWorker(w *response) {
  313. select {
  314. case srv.queue <- w:
  315. default:
  316. go srv.worker(w)
  317. }
  318. }
  319. // ListenAndServe starts a nameserver on the configured address in *Server.
  320. func (srv *Server) ListenAndServe() error {
  321. srv.lock.Lock()
  322. defer srv.lock.Unlock()
  323. if srv.started {
  324. return &Error{err: "server already started"}
  325. }
  326. addr := srv.Addr
  327. if addr == "" {
  328. addr = ":domain"
  329. }
  330. if srv.UDPSize == 0 {
  331. srv.UDPSize = MinMsgSize
  332. }
  333. srv.queue = make(chan *response)
  334. defer close(srv.queue)
  335. switch srv.Net {
  336. case "tcp", "tcp4", "tcp6":
  337. a, err := net.ResolveTCPAddr(srv.Net, addr)
  338. if err != nil {
  339. return err
  340. }
  341. l, err := net.ListenTCP(srv.Net, a)
  342. if err != nil {
  343. return err
  344. }
  345. srv.Listener = l
  346. srv.started = true
  347. srv.lock.Unlock()
  348. err = srv.serveTCP(l)
  349. srv.lock.Lock() // to satisfy the defer at the top
  350. return err
  351. case "tcp-tls", "tcp4-tls", "tcp6-tls":
  352. network := "tcp"
  353. if srv.Net == "tcp4-tls" {
  354. network = "tcp4"
  355. } else if srv.Net == "tcp6-tls" {
  356. network = "tcp6"
  357. }
  358. l, err := tls.Listen(network, addr, srv.TLSConfig)
  359. if err != nil {
  360. return err
  361. }
  362. srv.Listener = l
  363. srv.started = true
  364. srv.lock.Unlock()
  365. err = srv.serveTCP(l)
  366. srv.lock.Lock() // to satisfy the defer at the top
  367. return err
  368. case "udp", "udp4", "udp6":
  369. a, err := net.ResolveUDPAddr(srv.Net, addr)
  370. if err != nil {
  371. return err
  372. }
  373. l, err := net.ListenUDP(srv.Net, a)
  374. if err != nil {
  375. return err
  376. }
  377. if e := setUDPSocketOptions(l); e != nil {
  378. return e
  379. }
  380. srv.PacketConn = l
  381. srv.started = true
  382. srv.lock.Unlock()
  383. err = srv.serveUDP(l)
  384. srv.lock.Lock() // to satisfy the defer at the top
  385. return err
  386. }
  387. return &Error{err: "bad network"}
  388. }
  389. // ActivateAndServe starts a nameserver with the PacketConn or Listener
  390. // configured in *Server. Its main use is to start a server from systemd.
  391. func (srv *Server) ActivateAndServe() error {
  392. srv.lock.Lock()
  393. defer srv.lock.Unlock()
  394. if srv.started {
  395. return &Error{err: "server already started"}
  396. }
  397. pConn := srv.PacketConn
  398. l := srv.Listener
  399. srv.queue = make(chan *response)
  400. defer close(srv.queue)
  401. if pConn != nil {
  402. if srv.UDPSize == 0 {
  403. srv.UDPSize = MinMsgSize
  404. }
  405. // Check PacketConn interface's type is valid and value
  406. // is not nil
  407. if t, ok := pConn.(*net.UDPConn); ok && t != nil {
  408. if e := setUDPSocketOptions(t); e != nil {
  409. return e
  410. }
  411. srv.started = true
  412. srv.lock.Unlock()
  413. e := srv.serveUDP(t)
  414. srv.lock.Lock() // to satisfy the defer at the top
  415. return e
  416. }
  417. }
  418. if l != nil {
  419. srv.started = true
  420. srv.lock.Unlock()
  421. e := srv.serveTCP(l)
  422. srv.lock.Lock() // to satisfy the defer at the top
  423. return e
  424. }
  425. return &Error{err: "bad listeners"}
  426. }
  427. // Shutdown shuts down a server. After a call to Shutdown, ListenAndServe and
  428. // ActivateAndServe will return.
  429. func (srv *Server) Shutdown() error {
  430. srv.lock.Lock()
  431. if !srv.started {
  432. srv.lock.Unlock()
  433. return &Error{err: "server not started"}
  434. }
  435. srv.started = false
  436. srv.lock.Unlock()
  437. if srv.PacketConn != nil {
  438. srv.PacketConn.Close()
  439. }
  440. if srv.Listener != nil {
  441. srv.Listener.Close()
  442. }
  443. return nil
  444. }
  445. // getReadTimeout is a helper func to use system timeout if server did not intend to change it.
  446. func (srv *Server) getReadTimeout() time.Duration {
  447. rtimeout := dnsTimeout
  448. if srv.ReadTimeout != 0 {
  449. rtimeout = srv.ReadTimeout
  450. }
  451. return rtimeout
  452. }
  453. // serveTCP starts a TCP listener for the server.
  454. func (srv *Server) serveTCP(l net.Listener) error {
  455. defer l.Close()
  456. if srv.NotifyStartedFunc != nil {
  457. srv.NotifyStartedFunc()
  458. }
  459. for {
  460. rw, err := l.Accept()
  461. srv.lock.RLock()
  462. if !srv.started {
  463. srv.lock.RUnlock()
  464. return nil
  465. }
  466. srv.lock.RUnlock()
  467. if err != nil {
  468. if neterr, ok := err.(net.Error); ok && neterr.Temporary() {
  469. continue
  470. }
  471. return err
  472. }
  473. srv.spawnWorker(&response{tsigSecret: srv.TsigSecret, tcp: rw})
  474. }
  475. }
  476. // serveUDP starts a UDP listener for the server.
  477. func (srv *Server) serveUDP(l *net.UDPConn) error {
  478. defer l.Close()
  479. if srv.NotifyStartedFunc != nil {
  480. srv.NotifyStartedFunc()
  481. }
  482. reader := Reader(&defaultReader{srv})
  483. if srv.DecorateReader != nil {
  484. reader = srv.DecorateReader(reader)
  485. }
  486. rtimeout := srv.getReadTimeout()
  487. // deadline is not used here
  488. for {
  489. m, s, err := reader.ReadUDP(l, rtimeout)
  490. srv.lock.RLock()
  491. if !srv.started {
  492. srv.lock.RUnlock()
  493. return nil
  494. }
  495. srv.lock.RUnlock()
  496. if err != nil {
  497. if netErr, ok := err.(net.Error); ok && netErr.Temporary() {
  498. continue
  499. }
  500. return err
  501. }
  502. if len(m) < headerSize {
  503. continue
  504. }
  505. srv.spawnWorker(&response{msg: m, tsigSecret: srv.TsigSecret, udp: l, udpSession: s})
  506. }
  507. }
  508. func (srv *Server) serve(w *response) {
  509. if srv.DecorateWriter != nil {
  510. w.writer = srv.DecorateWriter(w)
  511. } else {
  512. w.writer = w
  513. }
  514. if w.udp != nil {
  515. // serve UDP
  516. srv.serveDNS(w)
  517. return
  518. }
  519. reader := Reader(&defaultReader{srv})
  520. if srv.DecorateReader != nil {
  521. reader = srv.DecorateReader(reader)
  522. }
  523. defer func() {
  524. if !w.hijacked {
  525. w.Close()
  526. }
  527. }()
  528. idleTimeout := tcpIdleTimeout
  529. if srv.IdleTimeout != nil {
  530. idleTimeout = srv.IdleTimeout()
  531. }
  532. timeout := srv.getReadTimeout()
  533. limit := srv.MaxTCPQueries
  534. if limit == 0 {
  535. limit = maxTCPQueries
  536. }
  537. for q := 0; q < limit || limit == -1; q++ {
  538. var err error
  539. w.msg, err = reader.ReadTCP(w.tcp, timeout)
  540. if err != nil {
  541. // TODO(tmthrgd): handle error
  542. break
  543. }
  544. srv.serveDNS(w)
  545. if w.tcp == nil {
  546. break // Close() was called
  547. }
  548. if w.hijacked {
  549. break // client will call Close() themselves
  550. }
  551. // The first read uses the read timeout, the rest use the
  552. // idle timeout.
  553. timeout = idleTimeout
  554. }
  555. }
  556. func (srv *Server) serveDNS(w *response) {
  557. req := new(Msg)
  558. err := req.Unpack(w.msg)
  559. if err != nil { // Send a FormatError back
  560. x := new(Msg)
  561. x.SetRcodeFormatError(req)
  562. w.WriteMsg(x)
  563. return
  564. }
  565. if !srv.Unsafe && req.Response {
  566. return
  567. }
  568. w.tsigStatus = nil
  569. if w.tsigSecret != nil {
  570. if t := req.IsTsig(); t != nil {
  571. if secret, ok := w.tsigSecret[t.Hdr.Name]; ok {
  572. w.tsigStatus = TsigVerify(w.msg, secret, "", false)
  573. } else {
  574. w.tsigStatus = ErrSecret
  575. }
  576. w.tsigTimersOnly = false
  577. w.tsigRequestMAC = req.Extra[len(req.Extra)-1].(*TSIG).MAC
  578. }
  579. }
  580. handler := srv.Handler
  581. if handler == nil {
  582. handler = DefaultServeMux
  583. }
  584. handler.ServeDNS(w, req) // Writes back to the client
  585. }
  586. func (srv *Server) readTCP(conn net.Conn, timeout time.Duration) ([]byte, error) {
  587. conn.SetReadDeadline(time.Now().Add(timeout))
  588. l := make([]byte, 2)
  589. n, err := conn.Read(l)
  590. if err != nil || n != 2 {
  591. if err != nil {
  592. return nil, err
  593. }
  594. return nil, ErrShortRead
  595. }
  596. length := binary.BigEndian.Uint16(l)
  597. if length == 0 {
  598. return nil, ErrShortRead
  599. }
  600. m := make([]byte, int(length))
  601. n, err = conn.Read(m[:int(length)])
  602. if err != nil || n == 0 {
  603. if err != nil {
  604. return nil, err
  605. }
  606. return nil, ErrShortRead
  607. }
  608. i := n
  609. for i < int(length) {
  610. j, err := conn.Read(m[i:int(length)])
  611. if err != nil {
  612. return nil, err
  613. }
  614. i += j
  615. }
  616. n = i
  617. m = m[:n]
  618. return m, nil
  619. }
  620. func (srv *Server) readUDP(conn *net.UDPConn, timeout time.Duration) ([]byte, *SessionUDP, error) {
  621. conn.SetReadDeadline(time.Now().Add(timeout))
  622. m := make([]byte, srv.UDPSize)
  623. n, s, err := ReadFromSessionUDP(conn, m)
  624. if err != nil {
  625. return nil, nil, err
  626. }
  627. m = m[:n]
  628. return m, s, nil
  629. }
  630. // WriteMsg implements the ResponseWriter.WriteMsg method.
  631. func (w *response) WriteMsg(m *Msg) (err error) {
  632. var data []byte
  633. if w.tsigSecret != nil { // if no secrets, dont check for the tsig (which is a longer check)
  634. if t := m.IsTsig(); t != nil {
  635. data, w.tsigRequestMAC, err = TsigGenerate(m, w.tsigSecret[t.Hdr.Name], w.tsigRequestMAC, w.tsigTimersOnly)
  636. if err != nil {
  637. return err
  638. }
  639. _, err = w.writer.Write(data)
  640. return err
  641. }
  642. }
  643. data, err = m.Pack()
  644. if err != nil {
  645. return err
  646. }
  647. _, err = w.writer.Write(data)
  648. return err
  649. }
  650. // Write implements the ResponseWriter.Write method.
  651. func (w *response) Write(m []byte) (int, error) {
  652. switch {
  653. case w.udp != nil:
  654. n, err := WriteToSessionUDP(w.udp, m, w.udpSession)
  655. return n, err
  656. case w.tcp != nil:
  657. lm := len(m)
  658. if lm < 2 {
  659. return 0, io.ErrShortBuffer
  660. }
  661. if lm > MaxMsgSize {
  662. return 0, &Error{err: "message too large"}
  663. }
  664. l := make([]byte, 2, 2+lm)
  665. binary.BigEndian.PutUint16(l, uint16(lm))
  666. m = append(l, m...)
  667. n, err := io.Copy(w.tcp, bytes.NewReader(m))
  668. return int(n), err
  669. }
  670. panic("not reached")
  671. }
  672. // LocalAddr implements the ResponseWriter.LocalAddr method.
  673. func (w *response) LocalAddr() net.Addr {
  674. if w.tcp != nil {
  675. return w.tcp.LocalAddr()
  676. }
  677. return w.udp.LocalAddr()
  678. }
  679. // RemoteAddr implements the ResponseWriter.RemoteAddr method.
  680. func (w *response) RemoteAddr() net.Addr {
  681. if w.tcp != nil {
  682. return w.tcp.RemoteAddr()
  683. }
  684. return w.udpSession.RemoteAddr()
  685. }
  686. // TsigStatus implements the ResponseWriter.TsigStatus method.
  687. func (w *response) TsigStatus() error { return w.tsigStatus }
  688. // TsigTimersOnly implements the ResponseWriter.TsigTimersOnly method.
  689. func (w *response) TsigTimersOnly(b bool) { w.tsigTimersOnly = b }
  690. // Hijack implements the ResponseWriter.Hijack method.
  691. func (w *response) Hijack() { w.hijacked = true }
  692. // Close implements the ResponseWriter.Close method
  693. func (w *response) Close() error {
  694. // Can't close the udp conn, as that is actually the listener.
  695. if w.tcp != nil {
  696. e := w.tcp.Close()
  697. w.tcp = nil
  698. return e
  699. }
  700. return nil
  701. }