Debian Codegraph @

client.go

raw symbols SCIP
1 package dns
2
3 // A client implementation.
4
5 import (
6 "context"
7 "crypto/tls"
8 "encoding/binary"
9 "io"
10 "net"
11 "strings"
12 "time"
13 )
14
15 const (
16 dnsTimeout time.Duration = 2 * time.Second
17 tcpIdleTimeout time.Duration = 8 * time.Second
18 )
19
20 func isPacketConn(c net.Conn) bool {
21 if _, ok := c.(net.PacketConn); !ok {
22 return false
23 }
24
25 if ua, ok := c.LocalAddr().(*net.UnixAddr); ok {
26 return ua.Net == "unixgram" || ua.Net == "unixpacket"
27 }
28
29 return true
30 }
31
32 // A Conn represents a connection to a DNS server.
33 type Conn struct {
34 net.Conn // a net.Conn holding the connection
35 UDPSize uint16 // minimum receive buffer for UDP messages
36 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)
37 TsigProvider TsigProvider // An implementation of the TsigProvider interface. If defined it replaces TsigSecret and is used for all TSIG operations.
38 tsigRequestMAC string
39 }
40
41 func (co *Conn) tsigProvider() TsigProvider {
42 if co.TsigProvider != nil {
43 return co.TsigProvider
44 }
45 // tsigSecretProvider will return ErrSecret if co.TsigSecret is nil.
46 return tsigSecretProvider(co.TsigSecret)
47 }
48
49 // A Client defines parameters for a DNS client.
50 type Client struct {
51 Net string // if "tcp" or "tcp-tls" (DNS over TLS) a TCP query will be initiated, otherwise an UDP one (default is "" for UDP)
52 UDPSize uint16 // minimum receive buffer for UDP messages
53 TLSConfig *tls.Config // TLS connection configuration
54 Dialer *net.Dialer // a net.Dialer used to set local address, timeouts and more
55 // Timeout is a cumulative timeout for dial, write and read, defaults to 0 (disabled) - overrides DialTimeout, ReadTimeout,
56 // WriteTimeout when non-zero. Can be overridden with net.Dialer.Timeout (see Client.ExchangeWithDialer and
57 // Client.Dialer) or context.Context.Deadline (see ExchangeContext)
58 Timeout time.Duration
59 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
60 ReadTimeout time.Duration // net.Conn.SetReadDeadline value for connections, defaults to 2 seconds - overridden by Timeout when that value is non-zero
61 WriteTimeout time.Duration // net.Conn.SetWriteDeadline value for connections, defaults to 2 seconds - overridden by Timeout when that value is non-zero
62 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)
63 TsigProvider TsigProvider // An implementation of the TsigProvider interface. If defined it replaces TsigSecret and is used for all TSIG operations.
64
65 // SingleInflight previously serialised multiple concurrent queries for the
66 // same Qname, Qtype and Qclass to ensure only one would be in flight at a
67 // time.
68 //
69 // Deprecated: This is a no-op. Callers should implement their own in flight
70 // query caching if needed. See github.com/miekg/dns/issues/1449.
71 SingleInflight bool
72 }
73
74 // Exchange performs a synchronous UDP query. It sends the message m to the address
75 // contained in a and waits for a reply. Exchange does not retry a failed query, nor
76 // will it fall back to TCP in case of truncation.
77 // See client.Exchange for more information on setting larger buffer sizes.
78 func Exchange(m *Msg, a string) (r *Msg, err error) {
79 client := Client{Net: "udp"}
80 r, _, err = client.Exchange(m, a)
81 return r, err
82 }
83
84 func (c *Client) dialTimeout() time.Duration {
85 if c.Timeout != 0 {
86 return c.Timeout
87 }
88 if c.DialTimeout != 0 {
89 return c.DialTimeout
90 }
91 return dnsTimeout
92 }
93
94 func (c *Client) readTimeout() time.Duration {
95 if c.Timeout != 0 {
96 return c.Timeout
97 }
98 if c.ReadTimeout != 0 {
99 return c.ReadTimeout
100 }
101 return dnsTimeout
102 }
103
104 func (c *Client) writeTimeout() time.Duration {
105 if c.Timeout != 0 {
106 return c.Timeout
107 }
108 if c.WriteTimeout != 0 {
109 return c.WriteTimeout
110 }
111 return dnsTimeout
112 }
113
114 // Dial connects to the address on the named network.
115 func (c *Client) Dial(address string) (conn *Conn, err error) {
116 return c.DialContext(context.Background(), address)
117 }
118
119 // DialContext connects to the address on the named network, with a context.Context.
120 func (c *Client) DialContext(ctx context.Context, address string) (conn *Conn, err error) {
121 // create a new dialer with the appropriate timeout
122 var d net.Dialer
123 if c.Dialer == nil {
124 d = net.Dialer{Timeout: c.getTimeoutForRequest(c.dialTimeout())}
125 } else {
126 d = *c.Dialer
127 }
128
129 network := c.Net
130 if network == "" {
131 network = "udp"
132 }
133
134 useTLS := strings.HasPrefix(network, "tcp") && strings.HasSuffix(network, "-tls")
135
136 conn = new(Conn)
137 if useTLS {
138 network = strings.TrimSuffix(network, "-tls")
139
140 tlsDialer := tls.Dialer{
141 NetDialer: &d,
142 Config: c.TLSConfig,
143 }
144 conn.Conn, err = tlsDialer.DialContext(ctx, network, address)
145 } else {
146 conn.Conn, err = d.DialContext(ctx, network, address)
147 }
148 if err != nil {
149 return nil, err
150 }
151 conn.UDPSize = c.UDPSize
152 return conn, nil
153 }
154
155 // Exchange performs a synchronous query. It sends the message m to the address
156 // contained in a and waits for a reply. Basic use pattern with a *dns.Client:
157 //
158 // c := new(dns.Client)
159 // in, rtt, err := c.Exchange(message, "127.0.0.1:53")
160 //
161 // Exchange does not retry a failed query, nor will it fall back to TCP in
162 // case of truncation.
163 // It is up to the caller to create a message that allows for larger responses to be
164 // returned. Specifically this means adding an EDNS0 OPT RR that will advertise a larger
165 // buffer, see SetEdns0. Messages without an OPT RR will fallback to the historic limit
166 // of 512 bytes
167 // To specify a local address or a timeout, the caller has to set the `Client.Dialer`
168 // attribute appropriately
169 func (c *Client) Exchange(m *Msg, address string) (r *Msg, rtt time.Duration, err error) {
170 co, err := c.Dial(address)
171
172 if err != nil {
173 return nil, 0, err
174 }
175 defer co.Close()
176 return c.ExchangeWithConn(m, co)
177 }
178
179 // ExchangeWithConn has the same behavior as Exchange, just with a predetermined connection
180 // that will be used instead of creating a new one.
181 // Usage pattern with a *dns.Client:
182 //
183 // c := new(dns.Client)
184 // // connection management logic goes here
185 //
186 // conn := c.Dial(address)
187 // in, rtt, err := c.ExchangeWithConn(message, conn)
188 //
189 // This allows users of the library to implement their own connection management,
190 // as opposed to Exchange, which will always use new connections and incur the added overhead
191 // that entails when using "tcp" and especially "tcp-tls" clients.
192 func (c *Client) ExchangeWithConn(m *Msg, conn *Conn) (r *Msg, rtt time.Duration, err error) {
193 return c.ExchangeWithConnContext(context.Background(), m, conn)
194 }
195
196 // ExchangeWithConnContext has the same behaviour as ExchangeWithConn and
197 // additionally obeys deadlines from the passed Context.
198 func (c *Client) ExchangeWithConnContext(ctx context.Context, m *Msg, co *Conn) (r *Msg, rtt time.Duration, err error) {
199 opt := m.IsEdns0()
200 // If EDNS0 is used use that for size.
201 if opt != nil && opt.UDPSize() >= MinMsgSize {
202 co.UDPSize = opt.UDPSize()
203 }
204 // Otherwise use the client's configured UDP size.
205 if opt == nil && c.UDPSize >= MinMsgSize {
206 co.UDPSize = c.UDPSize
207 }
208
209 // write with the appropriate write timeout
210 t := time.Now()
211 writeDeadline := t.Add(c.getTimeoutForRequest(c.writeTimeout()))
212 readDeadline := t.Add(c.getTimeoutForRequest(c.readTimeout()))
213 if deadline, ok := ctx.Deadline(); ok {
214 if deadline.Before(writeDeadline) {
215 writeDeadline = deadline
216 }
217 if deadline.Before(readDeadline) {
218 readDeadline = deadline
219 }
220 }
221 co.SetWriteDeadline(writeDeadline)
222 co.SetReadDeadline(readDeadline)
223
224 co.TsigSecret, co.TsigProvider = c.TsigSecret, c.TsigProvider
225
226 if err = co.WriteMsg(m); err != nil {
227 return nil, 0, err
228 }
229
230 if isPacketConn(co.Conn) {
231 for {
232 r, err = co.ReadMsg()
233 // Ignore replies with mismatched IDs because they might be
234 // responses to earlier queries that timed out.
235 if err != nil || r.Id == m.Id {
236 break
237 }
238 }
239 } else {
240 r, err = co.ReadMsg()
241 if err == nil && r.Id != m.Id {
242 err = ErrId
243 }
244 }
245 rtt = time.Since(t)
246 return r, rtt, err
247 }
248
249 // ReadMsg reads a message from the connection co.
250 // If the received message contains a TSIG record the transaction signature
251 // is verified. This method always tries to return the message, however if an
252 // error is returned there are no guarantees that the returned message is a
253 // valid representation of the packet read.
254 func (co *Conn) ReadMsg() (*Msg, error) {
255 p, err := co.ReadMsgHeader(nil)
256 if err != nil {
257 return nil, err
258 }
259
260 m := new(Msg)
261 if err := m.Unpack(p); err != nil {
262 // If an error was returned, we still want to allow the user to use
263 // the message, but naively they can just check err if they don't want
264 // to use an erroneous message
265 return m, err
266 }
267 if t := m.IsTsig(); t != nil {
268 // Need to work on the original message p, as that was used to calculate the tsig.
269 err = TsigVerifyWithProvider(p, co.tsigProvider(), co.tsigRequestMAC, false)
270 }
271 return m, err
272 }
273
274 // ReadMsgHeader reads a DNS message, parses and populates hdr (when hdr is not nil).
275 // Returns message as a byte slice to be parsed with Msg.Unpack later on.
276 // Note that error handling on the message body is not possible as only the header is parsed.
277 func (co *Conn) ReadMsgHeader(hdr *Header) ([]byte, error) {
278 var (
279 p []byte
280 n int
281 err error
282 )
283
284 if isPacketConn(co.Conn) {
285 if co.UDPSize > MinMsgSize {
286 p = make([]byte, co.UDPSize)
287 } else {
288 p = make([]byte, MinMsgSize)
289 }
290 n, err = co.Read(p)
291 } else {
292 var length uint16
293 if err := binary.Read(co.Conn, binary.BigEndian, &length); err != nil {
294 return nil, err
295 }
296
297 p = make([]byte, length)
298 n, err = io.ReadFull(co.Conn, p)
299 }
300
301 if err != nil {
302 return nil, err
303 } else if n < headerSize {
304 return nil, ErrShortRead
305 }
306
307 p = p[:n]
308 if hdr != nil {
309 dh, _, err := unpackMsgHdr(p, 0)
310 if err != nil {
311 return nil, err
312 }
313 *hdr = dh
314 }
315 return p, err
316 }
317
318 // Read implements the net.Conn read method.
319 func (co *Conn) Read(p []byte) (n int, err error) {
320 if co.Conn == nil {
321 return 0, ErrConnEmpty
322 }
323
324 if isPacketConn(co.Conn) {
325 // UDP connection
326 return co.Conn.Read(p)
327 }
328
329 var length uint16
330 if err := binary.Read(co.Conn, binary.BigEndian, &length); err != nil {
331 return 0, err
332 }
333 if int(length) > len(p) {
334 return 0, io.ErrShortBuffer
335 }
336
337 return io.ReadFull(co.Conn, p[:length])
338 }
339
340 // WriteMsg sends a message through the connection co.
341 // If the message m contains a TSIG record the transaction
342 // signature is calculated.
343 func (co *Conn) WriteMsg(m *Msg) (err error) {
344 var out []byte
345 if t := m.IsTsig(); t != nil {
346 // Set tsigRequestMAC for the next read, although only used in zone transfers.
347 out, co.tsigRequestMAC, err = TsigGenerateWithProvider(m, co.tsigProvider(), co.tsigRequestMAC, false)
348 } else {
349 out, err = m.Pack()
350 }
351 if err != nil {
352 return err
353 }
354 _, err = co.Write(out)
355 return err
356 }
357
358 // Write implements the net.Conn Write method.
359 func (co *Conn) Write(p []byte) (int, error) {
360 if len(p) > MaxMsgSize {
361 return 0, &Error{err: "message too large"}
362 }
363
364 if isPacketConn(co.Conn) {
365 return co.Conn.Write(p)
366 }
367
368 msg := make([]byte, 2+len(p))
369 binary.BigEndian.PutUint16(msg, uint16(len(p)))
370 copy(msg[2:], p)
371 return co.Conn.Write(msg)
372 }
373
374 // Return the appropriate timeout for a specific request
375 func (c *Client) getTimeoutForRequest(timeout time.Duration) time.Duration {
376 var requestTimeout time.Duration
377 if c.Timeout != 0 {
378 requestTimeout = c.Timeout
379 } else {
380 requestTimeout = timeout
381 }
382 // net.Dialer.Timeout has priority if smaller than the timeouts computed so
383 // far
384 if c.Dialer != nil && c.Dialer.Timeout != 0 {
385 if c.Dialer.Timeout < requestTimeout {
386 requestTimeout = c.Dialer.Timeout
387 }
388 }
389 return requestTimeout
390 }
391
392 // Dial connects to the address on the named network.
393 func Dial(network, address string) (conn *Conn, err error) {
394 conn = new(Conn)
395 conn.Conn, err = net.Dial(network, address)
396 if err != nil {
397 return nil, err
398 }
399 return conn, nil
400 }
401
402 // ExchangeContext performs a synchronous UDP query, like Exchange. It
403 // additionally obeys deadlines from the passed Context.
404 func ExchangeContext(ctx context.Context, m *Msg, a string) (r *Msg, err error) {
405 client := Client{Net: "udp"}
406 r, _, err = client.ExchangeContext(ctx, m, a)
407 // ignoring rtt to leave the original ExchangeContext API unchanged, but
408 // this function will go away
409 return r, err
410 }
411
412 // ExchangeConn performs a synchronous query. It sends the message m via the connection
413 // c and waits for a reply. The connection c is not closed by ExchangeConn.
414 // Deprecated: This function is going away, but can easily be mimicked:
415 //
416 // co := &dns.Conn{Conn: c} // c is your net.Conn
417 // co.WriteMsg(m)
418 // in, _ := co.ReadMsg()
419 // co.Close()
420 func ExchangeConn(c net.Conn, m *Msg) (r *Msg, err error) {
421 println("dns: ExchangeConn: this function is deprecated")
422 co := new(Conn)
423 co.Conn = c
424 if err = co.WriteMsg(m); err != nil {
425 return nil, err
426 }
427 r, err = co.ReadMsg()
428 if err == nil && r.Id != m.Id {
429 err = ErrId
430 }
431 return r, err
432 }
433
434 // DialTimeout acts like Dial but takes a timeout.
435 func DialTimeout(network, address string, timeout time.Duration) (conn *Conn, err error) {
436 client := Client{Net: network, Dialer: &net.Dialer{Timeout: timeout}}
437 return client.Dial(address)
438 }
439
440 // DialWithTLS connects to the address on the named network with TLS.
441 func DialWithTLS(network, address string, tlsConfig *tls.Config) (conn *Conn, err error) {
442 if !strings.HasSuffix(network, "-tls") {
443 network += "-tls"
444 }
445 client := Client{Net: network, TLSConfig: tlsConfig}
446 return client.Dial(address)
447 }
448
449 // DialTimeoutWithTLS acts like DialWithTLS but takes a timeout.
450 func DialTimeoutWithTLS(network, address string, tlsConfig *tls.Config, timeout time.Duration) (conn *Conn, err error) {
451 if !strings.HasSuffix(network, "-tls") {
452 network += "-tls"
453 }
454 client := Client{Net: network, Dialer: &net.Dialer{Timeout: timeout}, TLSConfig: tlsConfig}
455 return client.Dial(address)
456 }
457
458 // ExchangeContext acts like Exchange, but honors the deadline on the provided
459 // context, if present. If there is both a context deadline and a configured
460 // timeout on the client, the earliest of the two takes effect.
461 func (c *Client) ExchangeContext(ctx context.Context, m *Msg, a string) (r *Msg, rtt time.Duration, err error) {
462 conn, err := c.DialContext(ctx, a)
463 if err != nil {
464 return nil, 0, err
465 }
466 defer conn.Close()
467
468 return c.ExchangeWithConnContext(ctx, m, conn)
469 }