Debian Codegraph @

transfer.go

raw
1 package dns
2
3 import (
4 "context"
5 "fmt"
6 "io"
7 "net"
8 "time"
9 )
10
11 // Envelope is used when doing a zone transfer with a remote server.
12 type Envelope struct {
13 Answer []RR // The RRs as returned by the remote server, or the ones to be send to the remote.
14 Error error // If something went wrong, this contains the error.
15 }
16
17 // TransferIn performs a zone transfer with address over network, the message m is used to ask for the transfer and
18 // should have an [AXFR] or [IXFR] RR in the question section. For doing an IXFR a SOA record needs to be
19 // present in the [Ns] section of the [Msg], see RFC 1995.
20 //
21 // If the pseudo section contains a (stub) TSIG or in the future.
22 // SIG0 record, TSIG or SIG0 signing is performed, see [NewTSIG] and [NewSIG0] on how create such RRs. For
23 // this the client also need a [TSIGSigner] or [SIG0Signer].
24 //
25 // On the returned channel the received RRs are returned (and a non-nil erorr in case of an error). These RRs
26 // are as they were found, i.e. including the starting and ending SOA RRs.
27 //
28 // If m's buffer is empty TransferIn will call m.Pack(). If the clients's transport is nil [NewDefaultTransport] will
29 // be set and used.
30 //
31 // Setting up a transfer is done as follows:
32 //
33 // c := dns.NewClient()
34 // c.Transfer = &dns.Transfer{TSIGSigner: dns.HmacTSIG{[]byte("secret")}} // optionally set up TSIG with hmac
35 // m := dns.NewMsg("example.org.", dns.TypeAXFR)
36 // env, err := c.TransferIn(context.TODO(), m, "tcp", addr)
37 // if err != nil {
38 // return fmt.Errorf("failed to setup zone transfer in", err)
39 // }
40 //
41 // for e := range env {
42 // if e.Error != nil {
43 // // ...
44 // }
45 // // do things with e.Answer
46 // }
47 func (c *Client) TransferIn(ctx context.Context, m *Msg, network, address string) (<-chan *Envelope, error) {
48 if c.Transport == nil {
49 c.Transport = NewTransport()
50 }
51 conn, err := c.dial(ctx, network, address)
52 if err != nil {
53 return nil, err
54 }
55 return c.TransferInWithConn(ctx, m, conn)
56 }
57
58 // TransferInWithConn behaves like [client.TransferIn], but with a supplied connection.
59 func (c *Client) TransferInWithConn(ctx context.Context, m *Msg, conn net.Conn) (<-chan *Envelope, error) {
60 _, axfr := m.Question[0].(*AXFR)
61 _, ixfr := m.Question[0].(*IXFR)
62 if !axfr && !ixfr {
63 return nil, &Error{err: "unsupported transfer type"}
64 }
65 if ixfr {
66 if len(m.Ns) == 0 {
67 return nil, fmt.Errorf("%w: %s", ErrSOA, "empty Ns")
68 }
69 if _, ok := m.Ns[0].(*SOA); !ok {
70 return nil, fmt.Errorf("%w: %s", ErrSOA, "bad Ns")
71 }
72 }
73
74 if len(m.Data) == 0 {
75 if err := m.Pack(); err != nil {
76 return nil, err
77 }
78 }
79
80 if c.Transfer != nil && c.TSIGSigner != nil && hasTSIG(m) != nil {
81 if err := TSIGSign(m, c.TSIGSigner, &TSIGOption{}); err != nil {
82 return nil, err
83 }
84 }
85 // if.SIG0Signer != nil {} // TODO(miek): implement the whole SIG0 dance
86
87 remote := &response{conn: conn} // for Session() call in msg.go#L926
88 if _, err := io.Copy(remote, m); err != nil {
89 return nil, err
90 }
91
92 ch := make(chan *Envelope)
93 if axfr {
94 go c.transferInAXFR(ctx, m, ch, conn)
95 }
96 if ixfr {
97 go c.transferInIXFR(ctx, m, ch, conn)
98 }
99 return ch, nil
100 }
101
102 func (c *Client) transferInAXFR(ctx context.Context, m *Msg, ch chan<- *Envelope, conn net.Conn) {
103 defer func() {
104 // First close the connection, then the channel. This allows functions blocked on the channel to
105 // assume that the connection is closed and no further operations are pending when they resume.
106 conn.Close()
107 close(ch)
108 }()
109
110 options := TSIGOption{}
111 t := hasTSIG(m)
112 if t != nil {
113 options.RequestMAC = t.MAC
114 }
115
116 r := &Msg{}
117 for {
118 r.Options = MsgOptionUnpackHeader
119 conn.SetReadDeadline(time.Now().Add(c.ReadTimeout))
120 if _, err := io.Copy(r, conn); err != nil {
121 // the response writer or actual conn is closed, just return, or some other error, we may
122 // not be sure someone is still listening on this channel.
123 return
124 }
125 if err := ctx.Err(); err != nil {
126 ch <- &Envelope{Error: err}
127 return
128 }
129
130 if err := r.Unpack(); err != nil {
131 ch <- &Envelope{Error: err}
132 return
133 }
134
135 if m.ID != r.ID {
136 ch <- &Envelope{Error: fmt.Errorf("%w: %d != %d", ErrID, m.ID, r.ID)}
137 return
138 }
139
140 if r.Rcode != RcodeSuccess {
141 ch <- &Envelope{Error: fmt.Errorf("%w: %s", ErrRcode, rcodeToString(r.Rcode))}
142 return
143 }
144
145 r.Options = MsgOptionUnpack
146 err := r.Unpack()
147 if err != nil {
148 ch <- &Envelope{Answer: r.Answer, Error: err}
149 return
150 }
151
152 // On first loop first be need to see a SOA RR.
153 if !options.TimersOnly {
154 if len(r.Answer) == 0 {
155 ch <- &Envelope{Error: fmt.Errorf("%w: %s", ErrSOA, "empty answer")}
156 return
157 }
158 if _, ok := r.Answer[0].(*SOA); !ok {
159 ch <- &Envelope{Error: ErrSOA}
160 return
161 }
162 }
163
164 if c.Transfer != nil && c.TSIGSigner != nil && t != nil { // original request had tsig, so we need to check that.
165 if err := TSIGVerify(r, c.TSIGSigner, &options); err != nil {
166 ch <- &Envelope{Answer: r.Answer, Error: err}
167 return
168 }
169 }
170
171 ch <- &Envelope{Answer: r.Answer}
172
173 // If there is a SOA RR as the last we're done
174 if options.TimersOnly {
175 if len(r.Answer) > 0 {
176 if _, ok := r.Answer[len(r.Answer)-1].(*SOA); ok {
177 return
178 }
179 }
180 }
181
182 options.TimersOnly = true
183 if t != nil {
184 // r must have tsig, otherwise errored out above
185 options.RequestMAC = hasTSIG(r).MAC
186 }
187 }
188 }
189
190 // ixfr is similar, but different enough to warrant its own function. Doing this in the axfr-loop is possible,
191 // but make that more brittle. Although ifxr also needs to support axfr...
192 func (c *Client) transferInIXFR(ctx context.Context, m *Msg, ch chan<- *Envelope, conn net.Conn) {
193 defer func() {
194 conn.Close()
195 close(ch)
196 }()
197
198 options := TSIGOption{}
199 t := hasTSIG(m)
200 if t != nil {
201 options.RequestMAC = t.MAC
202 }
203 // serial is the serial of the first SOA, it used to determine when we seen all the RRs.
204 serial := uint32(0)
205 // assume incremental transfer, which implies seeing the 2n SOA with serial 'serial',
206 expectSOA := 1 // we ignore the first one and assume we get an axfr instead of ixfr, if the first msg indicates we do ifxr with +1 this.
207
208 r := &Msg{}
209 for {
210 r.Options = MsgOptionUnpackHeader
211 conn.SetReadDeadline(time.Now().Add(c.ReadTimeout))
212 if _, err := io.Copy(r, conn); err != nil {
213 // the response writer or actual conn is closed, just return, or some other error, we may
214 // not be sure someone is still listening on this channel.
215 return
216 }
217 if err := ctx.Err(); err != nil {
218 ch <- &Envelope{Error: err}
219 return
220 }
221
222 if err := r.Unpack(); err != nil {
223 ch <- &Envelope{Error: err}
224 return
225 }
226
227 if m.ID != r.ID {
228 ch <- &Envelope{Error: fmt.Errorf("%w: %d != %d", ErrID, m.ID, r.ID)}
229 return
230 }
231
232 if r.Rcode != RcodeSuccess {
233 ch <- &Envelope{Error: fmt.Errorf("%w: %s", ErrRcode, rcodeToString(r.Rcode))}
234 return
235 }
236
237 r.Options = MsgOptionUnpack
238 err := r.Unpack()
239 if err != nil {
240 ch <- &Envelope{Answer: r.Answer, Error: err}
241 return
242 }
243
244 // On first loop first be need to see a SOA RR and check that with the request serial.
245 if !options.TimersOnly {
246 if len(r.Answer) == 0 {
247 ch <- &Envelope{Error: fmt.Errorf("%w: %s", ErrSOA, "empty answer")}
248 return
249 }
250 if _, ok := r.Answer[0].(*SOA); !ok {
251 ch <- &Envelope{Error: ErrSOA}
252 return
253 }
254 serial = r.Answer[0].(*SOA).Serial
255 // If client serial >= server serial per RFC 1982, we are already up to date.
256 if CompareSerial(m.Ns[0].(*SOA).Serial, serial) >= 0 {
257 ch <- &Envelope{Answer: []RR{r.Answer[0]}}
258 return
259 }
260 if len(r.Answer) > 2 {
261 if _, ok := r.Answer[1].(*SOA); ok {
262 expectSOA++
263 }
264 }
265 }
266
267 if c.Transfer != nil && c.TSIGSigner != nil && t != nil { // original request had tsig, so we need to check that.
268 if err := TSIGVerify(r, c.TSIGSigner, &options); err != nil {
269 ch <- &Envelope{Answer: r.Answer, Error: err}
270 return
271 }
272 }
273
274 ch <- &Envelope{Answer: r.Answer}
275
276 // If we see the first SOA's serial expectSOA times we need to stop.
277 if options.TimersOnly {
278 for i := range r.Answer {
279 if s, ok := r.Answer[i].(*SOA); ok && s.Serial == serial {
280 expectSOA--
281 if expectSOA == 0 {
282 return
283 }
284 }
285 }
286 }
287
288 options.TimersOnly = true
289 if t != nil {
290 // r must have tsig, otherwise errored out above
291 options.RequestMAC = hasTSIG(r).MAC
292 }
293 }
294 }
295
296 // TransferOut performs an outgoing transfer with the client connecting in w, r is the request
297 // that initiates the transfer and is used for TSIG/SIG0.
298 //
299 // Example setup from within a dns.HandleFunc:
300 //
301 // r.Unpack()
302 // w.Hijack() // hijack the connection as we should close when done
303 // env := make(chan *dns.Envelope)
304 // c := dns.NewClient()
305 // var wg sync.WaitGroup
306 // wg.Go(func() {
307 // c.TransferOut(w, r, env)
308 // w.Close()
309 // })
310 // env <- &dns.Envelope{Answer: []dns.RR{...}}
311 // close(env)
312 //
313 // The server is responsible for sending the correct sequence of RRs through the channel env.
314 // If the clients's transport is nil [NewDefaultTransport] will be set and used.
315 func (c *Client) TransferOut(w ResponseWriter, r *Msg, env <-chan *Envelope) (err error) {
316 if c.Transport == nil {
317 c.Transport = NewTransport()
318 }
319 defer func() {
320 // drain channel reads
321 for range env {
322 }
323 }()
324
325 options := TSIGOption{}
326 t := hasTSIG(r)
327 if t != nil {
328 options.RequestMAC = t.MAC
329 }
330 for e := range env {
331 m := new(Msg) // TODO(miek): Msg can be lifted out of for loop?
332 m.Authoritative = true
333
334 // dnsutil.SetReply as used here, but led to all kinds of cyclic imports, just use that very static code here.
335 m.ID, m.Rcode = r.ID, RcodeSuccess
336 m.Response, m.Opcode = true, r.Opcode
337 m.RecursionDesired = r.RecursionDesired
338 m.CheckingDisabled = r.CheckingDisabled
339 m.Security = r.Security
340 m.Question = r.Question
341 m.Answer, m.Ns, m.Extra, m.Pseudo = nil, nil, nil, nil
342
343 m.Answer = e.Answer
344 if t != nil {
345 m.Pseudo = []RR{t} // will overwrite the bits that matter
346 }
347 if err = m.Pack(); err != nil {
348 return err
349 }
350 if c.Transfer != nil && c.TSIGSigner != nil && t != nil {
351 if err = TSIGSign(m, c.TSIGSigner, &options); err != nil {
352 return err
353 }
354 }
355
356 if _, err = io.Copy(w, m); err != nil {
357 return err
358 }
359
360 options.TimersOnly = true
361 if t != nil {
362 // m must have tsig, otherwise errored out above
363 options.RequestMAC = hasTSIG(m).MAC
364 }
365 }
366 return nil
367 }