client.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477
  1. package dns
  2. // A client implementation.
  3. import (
  4. "bytes"
  5. "context"
  6. "crypto/tls"
  7. "encoding/binary"
  8. "io"
  9. "net"
  10. "strings"
  11. "time"
  12. )
  13. const (
  14. dnsTimeout time.Duration = 2 * time.Second
  15. tcpIdleTimeout time.Duration = 8 * time.Second
  16. )
  17. // A Conn represents a connection to a DNS server.
  18. type Conn struct {
  19. net.Conn // a net.Conn holding the connection
  20. UDPSize uint16 // minimum receive buffer for UDP messages
  21. TsigSecret map[string]string // secret(s) for Tsig map[<zonename>]<base64 secret>, zonename must be in canonical form (lowercase, fqdn, see RFC 4034 Section 6.2)
  22. tsigRequestMAC string
  23. }
  24. // A Client defines parameters for a DNS client.
  25. type Client struct {
  26. Net string // if "tcp" or "tcp-tls" (DNS over TLS) a TCP query will be initiated, otherwise an UDP one (default is "" for UDP)
  27. UDPSize uint16 // minimum receive buffer for UDP messages
  28. TLSConfig *tls.Config // TLS connection configuration
  29. Dialer *net.Dialer // a net.Dialer used to set local address, timeouts and more
  30. // Timeout is a cumulative timeout for dial, write and read, defaults to 0 (disabled) - overrides DialTimeout, ReadTimeout,
  31. // WriteTimeout when non-zero. Can be overridden with net.Dialer.Timeout (see Client.ExchangeWithDialer and
  32. // Client.Dialer) or context.Context.Deadline (see the deprecated ExchangeContext)
  33. Timeout time.Duration
  34. DialTimeout time.Duration // net.DialTimeout, defaults to 2 seconds, or net.Dialer.Timeout if expiring earlier - overridden by Timeout when that value is non-zero
  35. ReadTimeout time.Duration // net.Conn.SetReadTimeout value for connections, defaults to 2 seconds - overridden by Timeout when that value is non-zero
  36. WriteTimeout time.Duration // net.Conn.SetWriteTimeout value for connections, defaults to 2 seconds - overridden by Timeout when that value is non-zero
  37. TsigSecret map[string]string // secret(s) for Tsig map[<zonename>]<base64 secret>, zonename must be in canonical form (lowercase, fqdn, see RFC 4034 Section 6.2)
  38. SingleInflight bool // if true suppress multiple outstanding queries for the same Qname, Qtype and Qclass
  39. group singleflight
  40. }
  41. // Exchange performs a synchronous UDP query. It sends the message m to the address
  42. // contained in a and waits for a reply. Exchange does not retry a failed query, nor
  43. // will it fall back to TCP in case of truncation.
  44. // See client.Exchange for more information on setting larger buffer sizes.
  45. func Exchange(m *Msg, a string) (r *Msg, err error) {
  46. client := Client{Net: "udp"}
  47. r, _, err = client.Exchange(m, a)
  48. return r, err
  49. }
  50. func (c *Client) dialTimeout() time.Duration {
  51. if c.Timeout != 0 {
  52. return c.Timeout
  53. }
  54. if c.DialTimeout != 0 {
  55. return c.DialTimeout
  56. }
  57. return dnsTimeout
  58. }
  59. func (c *Client) readTimeout() time.Duration {
  60. if c.ReadTimeout != 0 {
  61. return c.ReadTimeout
  62. }
  63. return dnsTimeout
  64. }
  65. func (c *Client) writeTimeout() time.Duration {
  66. if c.WriteTimeout != 0 {
  67. return c.WriteTimeout
  68. }
  69. return dnsTimeout
  70. }
  71. // Dial connects to the address on the named network.
  72. func (c *Client) Dial(address string) (conn *Conn, err error) {
  73. // create a new dialer with the appropriate timeout
  74. var d net.Dialer
  75. if c.Dialer == nil {
  76. d = net.Dialer{Timeout: c.getTimeoutForRequest(c.dialTimeout())}
  77. } else {
  78. d = *c.Dialer
  79. }
  80. network := c.Net
  81. if network == "" {
  82. network = "udp"
  83. }
  84. useTLS := strings.HasPrefix(network, "tcp") && strings.HasSuffix(network, "-tls")
  85. conn = new(Conn)
  86. if useTLS {
  87. network = strings.TrimSuffix(network, "-tls")
  88. conn.Conn, err = tls.DialWithDialer(&d, network, address, c.TLSConfig)
  89. } else {
  90. conn.Conn, err = d.Dial(network, address)
  91. }
  92. if err != nil {
  93. return nil, err
  94. }
  95. return conn, nil
  96. }
  97. // Exchange performs a synchronous query. It sends the message m to the address
  98. // contained in a and waits for a reply. Basic use pattern with a *dns.Client:
  99. //
  100. // c := new(dns.Client)
  101. // in, rtt, err := c.Exchange(message, "127.0.0.1:53")
  102. //
  103. // Exchange does not retry a failed query, nor will it fall back to TCP in
  104. // case of truncation.
  105. // It is up to the caller to create a message that allows for larger responses to be
  106. // returned. Specifically this means adding an EDNS0 OPT RR that will advertise a larger
  107. // buffer, see SetEdns0. Messages without an OPT RR will fallback to the historic limit
  108. // of 512 bytes
  109. // To specify a local address or a timeout, the caller has to set the `Client.Dialer`
  110. // attribute appropriately
  111. func (c *Client) Exchange(m *Msg, address string) (r *Msg, rtt time.Duration, err error) {
  112. if !c.SingleInflight {
  113. return c.exchange(m, address)
  114. }
  115. t := "nop"
  116. if t1, ok := TypeToString[m.Question[0].Qtype]; ok {
  117. t = t1
  118. }
  119. cl := "nop"
  120. if cl1, ok := ClassToString[m.Question[0].Qclass]; ok {
  121. cl = cl1
  122. }
  123. r, rtt, err, shared := c.group.Do(m.Question[0].Name+t+cl, func() (*Msg, time.Duration, error) {
  124. return c.exchange(m, address)
  125. })
  126. if r != nil && shared {
  127. r = r.Copy()
  128. }
  129. return r, rtt, err
  130. }
  131. func (c *Client) exchange(m *Msg, a string) (r *Msg, rtt time.Duration, err error) {
  132. var co *Conn
  133. co, err = c.Dial(a)
  134. if err != nil {
  135. return nil, 0, err
  136. }
  137. defer co.Close()
  138. opt := m.IsEdns0()
  139. // If EDNS0 is used use that for size.
  140. if opt != nil && opt.UDPSize() >= MinMsgSize {
  141. co.UDPSize = opt.UDPSize()
  142. }
  143. // Otherwise use the client's configured UDP size.
  144. if opt == nil && c.UDPSize >= MinMsgSize {
  145. co.UDPSize = c.UDPSize
  146. }
  147. co.TsigSecret = c.TsigSecret
  148. t := time.Now()
  149. // write with the appropriate write timeout
  150. co.SetWriteDeadline(t.Add(c.getTimeoutForRequest(c.writeTimeout())))
  151. if err = co.WriteMsg(m); err != nil {
  152. return nil, 0, err
  153. }
  154. co.SetReadDeadline(time.Now().Add(c.getTimeoutForRequest(c.readTimeout())))
  155. r, err = co.ReadMsg()
  156. if err == nil && r.Id != m.Id {
  157. err = ErrId
  158. }
  159. rtt = time.Since(t)
  160. return r, rtt, err
  161. }
  162. // ReadMsg reads a message from the connection co.
  163. // If the received message contains a TSIG record the transaction signature
  164. // is verified. This method always tries to return the message, however if an
  165. // error is returned there are no guarantees that the returned message is a
  166. // valid representation of the packet read.
  167. func (co *Conn) ReadMsg() (*Msg, error) {
  168. p, err := co.ReadMsgHeader(nil)
  169. if err != nil {
  170. return nil, err
  171. }
  172. m := new(Msg)
  173. if err := m.Unpack(p); err != nil {
  174. // If an error was returned, we still want to allow the user to use
  175. // the message, but naively they can just check err if they don't want
  176. // to use an erroneous message
  177. return m, err
  178. }
  179. if t := m.IsTsig(); t != nil {
  180. if _, ok := co.TsigSecret[t.Hdr.Name]; !ok {
  181. return m, ErrSecret
  182. }
  183. // Need to work on the original message p, as that was used to calculate the tsig.
  184. err = TsigVerify(p, co.TsigSecret[t.Hdr.Name], co.tsigRequestMAC, false)
  185. }
  186. return m, err
  187. }
  188. // ReadMsgHeader reads a DNS message, parses and populates hdr (when hdr is not nil).
  189. // Returns message as a byte slice to be parsed with Msg.Unpack later on.
  190. // Note that error handling on the message body is not possible as only the header is parsed.
  191. func (co *Conn) ReadMsgHeader(hdr *Header) ([]byte, error) {
  192. var (
  193. p []byte
  194. n int
  195. err error
  196. )
  197. switch t := co.Conn.(type) {
  198. case *net.TCPConn, *tls.Conn:
  199. r := t.(io.Reader)
  200. // First two bytes specify the length of the entire message.
  201. l, err := tcpMsgLen(r)
  202. if err != nil {
  203. return nil, err
  204. }
  205. p = make([]byte, l)
  206. n, err = tcpRead(r, p)
  207. default:
  208. if co.UDPSize > MinMsgSize {
  209. p = make([]byte, co.UDPSize)
  210. } else {
  211. p = make([]byte, MinMsgSize)
  212. }
  213. n, err = co.Read(p)
  214. }
  215. if err != nil {
  216. return nil, err
  217. } else if n < headerSize {
  218. return nil, ErrShortRead
  219. }
  220. p = p[:n]
  221. if hdr != nil {
  222. dh, _, err := unpackMsgHdr(p, 0)
  223. if err != nil {
  224. return nil, err
  225. }
  226. *hdr = dh
  227. }
  228. return p, err
  229. }
  230. // tcpMsgLen is a helper func to read first two bytes of stream as uint16 packet length.
  231. func tcpMsgLen(t io.Reader) (int, error) {
  232. p := []byte{0, 0}
  233. n, err := t.Read(p)
  234. if err != nil {
  235. return 0, err
  236. }
  237. // As seen with my local router/switch, returns 1 byte on the above read,
  238. // resulting a a ShortRead. Just write it out (instead of loop) and read the
  239. // other byte.
  240. if n == 1 {
  241. n1, err := t.Read(p[1:])
  242. if err != nil {
  243. return 0, err
  244. }
  245. n += n1
  246. }
  247. if n != 2 {
  248. return 0, ErrShortRead
  249. }
  250. l := binary.BigEndian.Uint16(p)
  251. if l == 0 {
  252. return 0, ErrShortRead
  253. }
  254. return int(l), nil
  255. }
  256. // tcpRead calls TCPConn.Read enough times to fill allocated buffer.
  257. func tcpRead(t io.Reader, p []byte) (int, error) {
  258. n, err := t.Read(p)
  259. if err != nil {
  260. return n, err
  261. }
  262. for n < len(p) {
  263. j, err := t.Read(p[n:])
  264. if err != nil {
  265. return n, err
  266. }
  267. n += j
  268. }
  269. return n, err
  270. }
  271. // Read implements the net.Conn read method.
  272. func (co *Conn) Read(p []byte) (n int, err error) {
  273. if co.Conn == nil {
  274. return 0, ErrConnEmpty
  275. }
  276. if len(p) < 2 {
  277. return 0, io.ErrShortBuffer
  278. }
  279. switch t := co.Conn.(type) {
  280. case *net.TCPConn, *tls.Conn:
  281. r := t.(io.Reader)
  282. l, err := tcpMsgLen(r)
  283. if err != nil {
  284. return 0, err
  285. }
  286. if l > len(p) {
  287. return l, io.ErrShortBuffer
  288. }
  289. return tcpRead(r, p[:l])
  290. }
  291. // UDP connection
  292. return co.Conn.Read(p)
  293. }
  294. // WriteMsg sends a message through the connection co.
  295. // If the message m contains a TSIG record the transaction
  296. // signature is calculated.
  297. func (co *Conn) WriteMsg(m *Msg) (err error) {
  298. var out []byte
  299. if t := m.IsTsig(); t != nil {
  300. mac := ""
  301. if _, ok := co.TsigSecret[t.Hdr.Name]; !ok {
  302. return ErrSecret
  303. }
  304. out, mac, err = TsigGenerate(m, co.TsigSecret[t.Hdr.Name], co.tsigRequestMAC, false)
  305. // Set for the next read, although only used in zone transfers
  306. co.tsigRequestMAC = mac
  307. } else {
  308. out, err = m.Pack()
  309. }
  310. if err != nil {
  311. return err
  312. }
  313. _, err = co.Write(out)
  314. return err
  315. }
  316. // Write implements the net.Conn Write method.
  317. func (co *Conn) Write(p []byte) (n int, err error) {
  318. switch t := co.Conn.(type) {
  319. case *net.TCPConn, *tls.Conn:
  320. w := t.(io.Writer)
  321. lp := len(p)
  322. if lp < 2 {
  323. return 0, io.ErrShortBuffer
  324. }
  325. if lp > MaxMsgSize {
  326. return 0, &Error{err: "message too large"}
  327. }
  328. l := make([]byte, 2, lp+2)
  329. binary.BigEndian.PutUint16(l, uint16(lp))
  330. p = append(l, p...)
  331. n, err := io.Copy(w, bytes.NewReader(p))
  332. return int(n), err
  333. }
  334. return co.Conn.Write(p)
  335. }
  336. // Return the appropriate timeout for a specific request
  337. func (c *Client) getTimeoutForRequest(timeout time.Duration) time.Duration {
  338. var requestTimeout time.Duration
  339. if c.Timeout != 0 {
  340. requestTimeout = c.Timeout
  341. } else {
  342. requestTimeout = timeout
  343. }
  344. // net.Dialer.Timeout has priority if smaller than the timeouts computed so
  345. // far
  346. if c.Dialer != nil && c.Dialer.Timeout != 0 {
  347. if c.Dialer.Timeout < requestTimeout {
  348. requestTimeout = c.Dialer.Timeout
  349. }
  350. }
  351. return requestTimeout
  352. }
  353. // Dial connects to the address on the named network.
  354. func Dial(network, address string) (conn *Conn, err error) {
  355. conn = new(Conn)
  356. conn.Conn, err = net.Dial(network, address)
  357. if err != nil {
  358. return nil, err
  359. }
  360. return conn, nil
  361. }
  362. // ExchangeContext performs a synchronous UDP query, like Exchange. It
  363. // additionally obeys deadlines from the passed Context.
  364. func ExchangeContext(ctx context.Context, m *Msg, a string) (r *Msg, err error) {
  365. client := Client{Net: "udp"}
  366. r, _, err = client.ExchangeContext(ctx, m, a)
  367. // ignorint rtt to leave the original ExchangeContext API unchanged, but
  368. // this function will go away
  369. return r, err
  370. }
  371. // ExchangeConn performs a synchronous query. It sends the message m via the connection
  372. // c and waits for a reply. The connection c is not closed by ExchangeConn.
  373. // This function is going away, but can easily be mimicked:
  374. //
  375. // co := &dns.Conn{Conn: c} // c is your net.Conn
  376. // co.WriteMsg(m)
  377. // in, _ := co.ReadMsg()
  378. // co.Close()
  379. //
  380. func ExchangeConn(c net.Conn, m *Msg) (r *Msg, err error) {
  381. println("dns: ExchangeConn: this function is deprecated")
  382. co := new(Conn)
  383. co.Conn = c
  384. if err = co.WriteMsg(m); err != nil {
  385. return nil, err
  386. }
  387. r, err = co.ReadMsg()
  388. if err == nil && r.Id != m.Id {
  389. err = ErrId
  390. }
  391. return r, err
  392. }
  393. // DialTimeout acts like Dial but takes a timeout.
  394. func DialTimeout(network, address string, timeout time.Duration) (conn *Conn, err error) {
  395. client := Client{Net: network, Dialer: &net.Dialer{Timeout: timeout}}
  396. return client.Dial(address)
  397. }
  398. // DialWithTLS connects to the address on the named network with TLS.
  399. func DialWithTLS(network, address string, tlsConfig *tls.Config) (conn *Conn, err error) {
  400. if !strings.HasSuffix(network, "-tls") {
  401. network += "-tls"
  402. }
  403. client := Client{Net: network, TLSConfig: tlsConfig}
  404. return client.Dial(address)
  405. }
  406. // DialTimeoutWithTLS acts like DialWithTLS but takes a timeout.
  407. func DialTimeoutWithTLS(network, address string, tlsConfig *tls.Config, timeout time.Duration) (conn *Conn, err error) {
  408. if !strings.HasSuffix(network, "-tls") {
  409. network += "-tls"
  410. }
  411. client := Client{Net: network, Dialer: &net.Dialer{Timeout: timeout}, TLSConfig: tlsConfig}
  412. return client.Dial(address)
  413. }
  414. // ExchangeContext acts like Exchange, but honors the deadline on the provided
  415. // context, if present. If there is both a context deadline and a configured
  416. // timeout on the client, the earliest of the two takes effect.
  417. func (c *Client) ExchangeContext(ctx context.Context, m *Msg, a string) (r *Msg, rtt time.Duration, err error) {
  418. var timeout time.Duration
  419. if deadline, ok := ctx.Deadline(); !ok {
  420. timeout = 0
  421. } else {
  422. timeout = time.Until(deadline)
  423. }
  424. // not passing the context to the underlying calls, as the API does not support
  425. // context. For timeouts you should set up Client.Dialer and call Client.Exchange.
  426. // TODO(tmthrgd,miekg): this is a race condition.
  427. c.Dialer = &net.Dialer{Timeout: timeout}
  428. return c.Exchange(m, a)
  429. }