client.go 11 KB

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