package dns

import (
	
	
	
)

// Envelope is used when doing a zone transfer with a remote server.
type Envelope struct {
	RR    []RR  // The set of RRs in the answer section of the xfr reply message.
	Error error // If something went wrong, this contains the error.
}

// A Transfer defines parameters that are used during a zone transfer.
type Transfer struct {
	*Conn
	DialTimeout    time.Duration     // net.DialTimeout, defaults to 2 seconds
	ReadTimeout    time.Duration     // net.Conn.SetReadTimeout value for connections, defaults to 2 seconds
	WriteTimeout   time.Duration     // net.Conn.SetWriteTimeout value for connections, defaults to 2 seconds
	TsigProvider   TsigProvider      // An implementation of the TsigProvider interface. If defined it replaces TsigSecret and is used for all TSIG operations.
	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)
	tsigTimersOnly bool
	TLS            *tls.Config // TLS config. If Xfr over TLS will be attempted
}

func ( *Transfer) () TsigProvider {
	if .TsigProvider != nil {
		return .TsigProvider
	}
	if .TsigSecret != nil {
		return tsigSecretProvider(.TsigSecret)
	}
	return nil
}

// TODO: Think we need to away to stop the transfer

// In performs an incoming transfer with the server in a.
// If you would like to set the source IP, or some other attribute
// of a Dialer for a Transfer, you can do so by specifying the attributes
// in the Transfer.Conn:
//
//	d := net.Dialer{LocalAddr: transfer_source}
//	con, err := d.Dial("tcp", master)
//	dnscon := &dns.Conn{Conn:con}
//	transfer = &dns.Transfer{Conn: dnscon}
//	channel, err := transfer.In(message, master)
func ( *Transfer) ( *Msg,  string) ( chan *Envelope,  error) {
	switch .Question[0].Qtype {
	case TypeAXFR, TypeIXFR:
	default:
		return nil, &Error{"unsupported question type"}
	}

	 := dnsTimeout
	if .DialTimeout != 0 {
		 = .DialTimeout
	}

	if .Conn == nil {
		if .TLS != nil {
			.Conn,  = DialTimeoutWithTLS("tcp-tls", , .TLS, )
		} else {
			.Conn,  = DialTimeout("tcp", , )
		}
		if  != nil {
			return nil, 
		}
	}

	if  := .WriteMsg();  != nil {
		return nil, 
	}

	 = make(chan *Envelope)
	switch .Question[0].Qtype {
	case TypeAXFR:
		go .inAxfr(, )
	case TypeIXFR:
		go .inIxfr(, )
	}

	return , nil
}

func ( *Transfer) ( *Msg,  chan *Envelope) {
	 := true
	defer func() {
		// First close the connection, then the channel. This allows functions blocked on
		// the channel to assume that the connection is closed and no further operations are
		// pending when they resume.
		.Close()
		close()
	}()
	 := dnsTimeout
	if .ReadTimeout != 0 {
		 = .ReadTimeout
	}
	for {
		.Conn.SetReadDeadline(time.Now().Add())
		,  := .ReadMsg()
		if  != nil {
			 <- &Envelope{nil, }
			return
		}
		if .Id != .Id {
			 <- &Envelope{.Answer, ErrId}
			return
		}
		if  {
			if .Rcode != RcodeSuccess {
				 <- &Envelope{.Answer, &Error{err: fmt.Sprintf(errXFR, .Rcode)}}
				return
			}
			if !isSOAFirst() {
				 <- &Envelope{.Answer, ErrSoa}
				return
			}
			 = !
			// only one answer that is SOA, receive more
			if len(.Answer) == 1 {
				.tsigTimersOnly = true
				 <- &Envelope{.Answer, nil}
				continue
			}
		}

		if ! {
			.tsigTimersOnly = true // Subsequent envelopes use this.
			if isSOALast() {
				 <- &Envelope{.Answer, nil}
				return
			}
			 <- &Envelope{.Answer, nil}
		}
	}
}

func ( *Transfer) ( *Msg,  chan *Envelope) {
	var  uint32 // The first serial seen is the current server serial
	 := true
	 := 0
	 := .Ns[0].(*SOA).Serial
	defer func() {
		// First close the connection, then the channel. This allows functions blocked on
		// the channel to assume that the connection is closed and no further operations are
		// pending when they resume.
		.Close()
		close()
	}()
	 := dnsTimeout
	if .ReadTimeout != 0 {
		 = .ReadTimeout
	}
	for {
		.SetReadDeadline(time.Now().Add())
		,  := .ReadMsg()
		if  != nil {
			 <- &Envelope{nil, }
			return
		}
		if .Id != .Id {
			 <- &Envelope{.Answer, ErrId}
			return
		}
		if .Rcode != RcodeSuccess {
			 <- &Envelope{.Answer, &Error{err: fmt.Sprintf(errXFR, .Rcode)}}
			return
		}
		if  == 0 {
			// Check if the returned answer is ok
			if !isSOAFirst() {
				 <- &Envelope{.Answer, ErrSoa}
				return
			}
			// This serial is important
			 = .Answer[0].(*SOA).Serial
			// Check if there are no changes in zone
			if  >=  {
				 <- &Envelope{.Answer, nil}
				return
			}
		}
		// Now we need to check each message for SOA records, to see what we need to do
		.tsigTimersOnly = true
		for ,  := range .Answer {
			if ,  := .(*SOA);  {
				if .Serial ==  {
					++
					// quit if it's a full axfr or the servers' SOA is repeated the third time
					if  &&  == 2 ||  == 3 {
						 <- &Envelope{.Answer, nil}
						return
					}
				} else if  {
					// it's an ixfr
					 = false
				}
			}
		}
		 <- &Envelope{.Answer, nil}
	}
}

// Out performs an outgoing transfer with the client connecting in w.
// Basic use pattern:
//
//	ch := make(chan *dns.Envelope)
//	tr := new(dns.Transfer)
//	var wg sync.WaitGroup
//	wg.Add(1)
//	go func() {
//		tr.Out(w, r, ch)
//		wg.Done()
//	}()
//	ch <- &dns.Envelope{RR: []dns.RR{soa, rr1, rr2, rr3, soa}}
//	close(ch)
//	wg.Wait() // wait until everything is written out
//	w.Close() // close connection
//
// The server is responsible for sending the correct sequence of RRs through the channel ch.
func ( *Transfer) ( ResponseWriter,  *Msg,  chan *Envelope) error {
	for  := range  {
		 := new(Msg)
		// Compress?
		.SetReply()
		.Authoritative = true
		// assume it fits TODO(miek): fix
		.Answer = append(.Answer, .RR...)
		if  := .IsTsig();  != nil && .TsigStatus() == nil {
			.SetTsig(.Hdr.Name, .Algorithm, .Fudge, time.Now().Unix())
		}
		if  := .WriteMsg();  != nil {
			return 
		}
		.TsigTimersOnly(true)
	}
	return nil
}

// ReadMsg reads a message from the transfer connection t.
func ( *Transfer) () (*Msg, error) {
	 := new(Msg)
	 := make([]byte, MaxMsgSize)
	,  := .Read()
	if  != nil &&  == 0 {
		return nil, 
	}
	 = [:]
	if  := .Unpack();  != nil {
		return nil, 
	}

	if  := .tsigProvider();  != nil {
		// Need to work on the original message p, as that was used to calculate the tsig.
		 = TsigVerifyWithProvider(, , .tsigRequestMAC, .tsigTimersOnly)
		if  := .IsTsig();  != nil {
			.tsigRequestMAC = .MAC
		}
	}
	return , 
}

// WriteMsg writes a message through the transfer connection t.
func ( *Transfer) ( *Msg) ( error) {
	var  []byte
	if ,  := .IsTsig(), .tsigProvider();  != nil &&  != nil {
		, .tsigRequestMAC,  = TsigGenerateWithProvider(, , .tsigRequestMAC, .tsigTimersOnly)
	} else {
		,  = .Pack()
	}
	if  != nil {
		return 
	}
	_,  = .Write()
	return 
}

func isSOAFirst( *Msg) bool {
	return len(.Answer) > 0 &&
		.Answer[0].Header().Rrtype == TypeSOA
}

func isSOALast( *Msg) bool {
	return len(.Answer) > 0 &&
		.Answer[len(.Answer)-1].Header().Rrtype == TypeSOA
}

const errXFR = "bad xfr rcode: %d"