client.go 11 KB

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