client.go 12 KB

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