dns/client.go

446 lines
11 KiB
Go
Raw Normal View History

2011-04-13 05:44:56 +10:00
package dns
// A concurrent client implementation.
// Client sends query to a channel which
// will then handle the query. Returned replys
// are return on another channel. Ready for handling --- same
// setup for server - a HANDLER function that gets run
// when the query returns.
import (
2011-04-16 07:55:27 +10:00
"io"
"net"
2011-04-13 05:44:56 +10:00
)
2011-08-09 23:01:29 +10:00
// Incoming (just as in os.Signal)
2011-04-13 05:44:56 +10:00
type QueryHandler interface {
2011-04-13 06:21:09 +10:00
QueryDNS(w RequestWriter, q *Msg)
2011-04-13 05:44:56 +10:00
}
2011-08-01 21:15:15 +10:00
// The RequestWriter interface is used by a DNS query handler to
// construct a DNS request.
2011-04-13 05:44:56 +10:00
type RequestWriter interface {
2011-04-16 07:55:27 +10:00
Write(*Msg)
2011-11-03 09:06:54 +11:00
Send(*Msg) error
Receive() (*Msg, error)
Close() error
Dial() error
2011-04-13 06:21:09 +10:00
}
// hijacked connections...?
2011-04-13 06:39:38 +10:00
type reply struct {
2011-04-19 06:08:12 +10:00
client *Client
addr string
req *Msg
conn net.Conn
2011-04-23 00:37:26 +10:00
tsigRequestMAC string
2011-04-19 06:08:12 +10:00
tsigTimersOnly bool
}
2011-08-01 21:15:15 +10:00
// A Request is a incoming message from a Client
type Request struct {
Request *Msg
Addr string
Client *Client
2011-04-13 06:21:09 +10:00
}
2011-04-13 05:44:56 +10:00
// QueryMux is an DNS request multiplexer. It matches the
// zone name of each incoming request against a list of
// registered patterns add calls the handler for the pattern
// that most closely matches the zone name.
type QueryMux struct {
2011-04-13 06:21:09 +10:00
m map[string]QueryHandler
2011-04-13 05:44:56 +10:00
}
// NewQueryMux allocates and returns a new QueryMux.
func NewQueryMux() *QueryMux { return &QueryMux{make(map[string]QueryHandler)} }
// DefaultQueryMux is the default QueryMux used by Query.
var DefaultQueryMux = NewQueryMux()
func newQueryChanSlice() chan *Exchange { return make(chan *Exchange) }
func newQueryChan() chan *Request { return make(chan *Request) }
2011-04-14 04:41:16 +10:00
2011-07-06 05:08:22 +10:00
// Default channels to use for the resolver
var (
// DefaultReplyChan is the channel on which the replies are
// coming back. Is it a channel of *Exchange, so that the original
// question is included with the answer.
DefaultReplyChan = newQueryChanSlice()
// DefaultQueryChan is the channel were you can send the questions to.
DefaultQueryChan = newQueryChan()
)
2011-04-14 04:41:16 +10:00
2011-04-13 05:44:56 +10:00
// The HandlerQueryFunc type is an adapter to allow the use of
// ordinary functions as DNS query handlers. If f is a function
// with the appropriate signature, HandlerQueryFunc(f) is a
// QueryHandler object that calls f.
2011-04-13 05:44:56 +10:00
type HandlerQueryFunc func(RequestWriter, *Msg)
// QueryDNS calls f(w, reg)
func (f HandlerQueryFunc) QueryDNS(w RequestWriter, r *Msg) {
go f(w, r)
}
func HandleQueryFunc(pattern string, handler func(RequestWriter, *Msg)) {
DefaultQueryMux.HandleQueryFunc(pattern, handler)
2011-04-13 05:44:56 +10:00
}
// reusing zoneMatch from server.go
func (mux *QueryMux) match(zone string) QueryHandler {
2011-04-13 06:21:09 +10:00
var h QueryHandler
var n = 0
for k, v := range mux.m {
if !zoneMatch(k, zone) {
continue
}
if h == nil || len(k) > n {
n = len(k)
h = v
}
}
return h
2011-04-13 05:44:56 +10:00
}
func (mux *QueryMux) Handle(pattern string, handler QueryHandler) {
2011-04-13 06:21:09 +10:00
if pattern == "" {
panic("dns: invalid pattern " + pattern)
}
2011-07-05 06:27:23 +10:00
mux.m[pattern] = handler
2011-04-13 05:44:56 +10:00
}
func (mux *QueryMux) HandleQueryFunc(pattern string, handler func(RequestWriter, *Msg)) {
2011-04-13 06:21:09 +10:00
mux.Handle(pattern, HandlerQueryFunc(handler))
2011-04-13 05:44:56 +10:00
}
func (mux *QueryMux) QueryDNS(w RequestWriter, r *Msg) {
h := mux.match(r.Question[0].Name)
2011-04-13 06:21:09 +10:00
if h == nil {
2011-07-24 07:43:43 +10:00
panic("dns: no handler found for " + r.Question[0].Name)
2011-04-13 06:21:09 +10:00
}
h.QueryDNS(w, r)
2011-04-13 05:44:56 +10:00
}
type Client struct {
2011-04-19 06:08:12 +10:00
Net string // if "tcp" a TCP query will be initiated, otherwise an UDP one
Attempts int // number of attempts
Retry bool // retry with TCP
2011-11-03 09:06:54 +11:00
QueryChan chan *Request // read DNS request from this channel
ReplyChan chan *Exchange // write the reply (together with the DNS request) to this channel
2011-09-21 01:40:13 +10:00
ReadTimeout int64 // the net.Conn.SetReadTimeout value for new connections (ns)
WriteTimeout int64 // the net.Conn.SetWriteTimeout value for new connections (ns)
2011-04-19 06:08:12 +10:00
TsigSecret map[string]string // secret(s) for Tsig map[<zonename>]<base64 secret>
Hijacked net.Conn // if set the calling code takes care of the connection
2011-07-24 07:43:43 +10:00
// LocalAddr string // Local address to use
}
2011-07-31 22:33:13 +10:00
// NewClient creates a new client, with Net set to "udp" and Attempts to 1.
2011-09-11 08:31:03 +10:00
// The client's ReplyChan is set to DefaultReplyChan and QueryChan
// to DefaultQueryChan.
func NewClient() *Client {
c := new(Client)
c.Net = "udp"
c.Attempts = 1
2011-11-03 09:06:54 +11:00
c.ReplyChan = DefaultReplyChan
c.QueryChan = DefaultQueryChan
2011-09-21 22:22:43 +10:00
c.ReadTimeout = 1 * 1e9
c.WriteTimeout = 1 * 1e9
return c
}
type Query struct {
QueryChan chan *Request // read DNS request from this channel
2011-11-03 09:06:54 +11:00
Handler QueryHandler // handler to invoke, dns.DefaultQueryMux if nil
}
2011-11-03 09:06:54 +11:00
func (q *Query) Query() error {
handler := q.Handler
2011-04-13 06:21:09 +10:00
if handler == nil {
handler = DefaultQueryMux
}
2011-07-24 07:43:43 +10:00
//forever:
for {
select {
case in := <-q.QueryChan:
w := new(reply)
w.req = in.Request
w.addr = in.Addr
w.client = in.Client
handler.QueryDNS(w, in.Request)
}
}
2011-04-13 06:21:09 +10:00
return nil
2011-04-13 05:44:56 +10:00
}
2011-11-03 09:06:54 +11:00
func (q *Query) ListenAndQuery() error {
if q.QueryChan == nil {
q.QueryChan = DefaultQueryChan
}
return q.Query()
}
// ListenAndQuery starts the listener for firing off the queries. If
2011-07-05 06:27:23 +10:00
// c is nil DefaultQueryChan is used. If handler is nil
// DefaultQueryMux is used.
func ListenAndQuery(request chan *Request, handler QueryHandler) {
q := &Query{QueryChan: request, Handler: handler}
go q.ListenAndQuery()
}
2011-09-11 08:31:03 +10:00
// Write returns the original question and the answer on the
// reply channel of the client.
func (w *reply) Write(m *Msg) {
w.Client().ReplyChan <- &Exchange{Request: w.req, Reply: m}
}
2011-07-05 05:38:50 +10:00
// Do performs an asynchronous query. The result is returned on the
// QueryChan channel set in the Client c.
func (c *Client) Do(m *Msg, a string) {
2011-11-03 09:06:54 +11:00
c.QueryChan <- &Request{Client: c, Addr: a, Request: m}
}
// ExchangeBuffer performs a synchronous query. It sends the buffer m to the
2011-12-17 05:35:37 +11:00
// address contained in a.
2011-11-03 09:06:54 +11:00
func (c *Client) ExchangeBuffer(inbuf []byte, a string, outbuf []byte) (n int, err error) {
2011-04-18 17:28:56 +10:00
w := new(reply)
w.client = c
w.addr = a
if c.Hijacked == nil {
if err = w.Dial(); err != nil {
return 0, err
}
2011-08-09 00:29:13 +10:00
defer w.Close()
2011-08-08 21:10:35 +10:00
}
if c.Hijacked != nil {
w.conn = c.Hijacked
}
2011-08-08 21:10:35 +10:00
if n, err = w.writeClient(inbuf); err != nil {
return 0, err
2011-04-18 17:28:56 +10:00
}
2012-01-16 01:30:12 +11:00
//Why cant we set the buf here?? TODO(MG)
2011-08-08 21:10:35 +10:00
if n, err = w.readClient(outbuf); err != nil {
return n, err
2011-04-18 17:28:56 +10:00
}
2011-08-08 21:10:35 +10:00
return n, nil
2011-08-04 19:27:56 +10:00
}
// Exchange performs an synchronous query. It sends the message m to the address
// contained in a and waits for an reply.
2011-11-03 09:06:54 +11:00
func (c *Client) Exchange(m *Msg, a string) (r *Msg, err error) {
2011-08-08 21:10:35 +10:00
var n int
2011-08-04 19:27:56 +10:00
out, ok := m.Pack()
if !ok {
2012-01-13 08:49:26 +11:00
return nil, ErrPack
2011-08-04 19:27:56 +10:00
}
var in []byte
switch c.Net {
case "tcp":
in = make([]byte, MaxMsgSize)
case "udp":
in = make([]byte, DefaultMsgSize)
}
2012-01-13 08:49:26 +11:00
//TODO(mg): look at the buffer size here
2011-08-08 21:10:35 +10:00
if n, err = c.ExchangeBuffer(out, a, in); err != nil {
return nil, err
}
r = new(Msg)
if ok := r.Unpack(in[:n]); !ok {
return nil, ErrUnpack
}
2011-08-08 21:10:35 +10:00
return r, nil
}
// Dial connects to the address addr for the network set in c.Net
2011-11-03 09:06:54 +11:00
func (w *reply) Dial() error {
2011-08-08 21:10:35 +10:00
conn, err := net.Dial(w.Client().Net, w.addr)
if err != nil {
return err
}
w.conn = conn
return nil
}
// UDP/TCP stuff big TODO
2011-11-03 09:06:54 +11:00
func (w *reply) Close() (err error) {
2011-08-08 21:10:35 +10:00
return w.conn.Close()
}
func (w *reply) Client() *Client {
return w.client
2011-04-17 18:54:34 +10:00
}
func (w *reply) Request() *Msg {
return w.req
}
2011-11-03 09:06:54 +11:00
func (w *reply) Receive() (*Msg, error) {
var p []byte
m := new(Msg)
switch w.Client().Net {
2011-07-06 04:55:05 +10:00
case "tcp", "tcp4", "tcp6":
2011-04-19 02:29:46 +10:00
p = make([]byte, MaxMsgSize)
2011-07-06 04:55:05 +10:00
case "udp", "udp4", "udp6":
p = make([]byte, DefaultMsgSize)
2011-04-19 06:08:12 +10:00
}
n, err := w.readClient(p)
if err != nil {
return nil, err
}
p = p[:n]
if ok := m.Unpack(p); !ok {
return nil, ErrUnpack
}
2011-04-23 00:37:26 +10:00
// Tsig
if m.IsTsig() {
secret := m.Extra[len(m.Extra)-1].(*RR_TSIG).Hdr.Name
_, ok := w.Client().TsigSecret[secret]
if !ok {
return m, ErrSecret
2011-04-23 00:37:26 +10:00
}
2011-11-03 09:06:54 +11:00
// Need to work on the original message p, as that was used
// to calculate the tsig.
err := TsigVerify(p, w.Client().TsigSecret[secret], w.tsigRequestMAC, w.tsigTimersOnly)
if err != nil {
2011-04-23 00:37:26 +10:00
return m, err
}
}
return m, nil
}
2011-04-16 07:55:27 +10:00
2011-11-03 09:06:54 +11:00
func (w *reply) readClient(p []byte) (n int, err error) {
if w.conn == nil {
2011-11-03 09:06:54 +11:00
return 0, ErrConnEmpty
//panic("no connection")
}
switch w.Client().Net {
2011-07-06 04:55:05 +10:00
case "tcp", "tcp4", "tcp6":
2011-04-19 02:27:59 +10:00
if len(p) < 1 {
2011-04-19 06:08:12 +10:00
return 0, io.ErrShortBuffer
}
n, err = w.conn.(*net.TCPConn).Read(p[0:2])
if err != nil || n != 2 {
return n, err
}
l, _ := unpackUint16(p[0:2], 0)
if l == 0 {
return 0, ErrShortRead
}
if int(l) > len(p) {
return int(l), io.ErrShortBuffer
}
n, err = w.conn.(*net.TCPConn).Read(p[:l])
if err != nil {
return n, err
}
i := n
for i < int(l) {
j, err := w.conn.(*net.TCPConn).Read(p[i:int(l)])
if err != nil {
return i, err
}
i += j
}
n = i
2011-07-06 04:55:05 +10:00
case "udp", "udp4", "udp6":
n, _, err = w.conn.(*net.UDPConn).ReadFromUDP(p)
2011-04-17 18:54:34 +10:00
if err != nil {
return n, err
}
}
return
2011-04-16 07:55:27 +10:00
}
// Send sends a dns msg to the address specified in w.
2011-04-19 06:08:12 +10:00
// If the message m contains a TSIG record the transaction
// signature is calculated.
2011-11-03 09:06:54 +11:00
func (w *reply) Send(m *Msg) error {
2011-04-19 06:08:12 +10:00
if m.IsTsig() {
2011-04-23 00:37:26 +10:00
secret := m.Extra[len(m.Extra)-1].(*RR_TSIG).Hdr.Name
_, ok := w.Client().TsigSecret[secret]
if !ok {
return ErrSecret
2011-04-23 00:37:26 +10:00
}
2012-01-13 08:49:26 +11:00
// Compressie maakt dit stuk
2011-11-03 09:06:54 +11:00
if err := TsigGenerate(m, w.Client().TsigSecret[secret], w.tsigRequestMAC, w.tsigTimersOnly); err != nil {
return err
}
w.tsigRequestMAC = m.Extra[len(m.Extra)-1].(*RR_TSIG).MAC // Save the requestMAC for the next packet
2011-04-19 06:08:12 +10:00
}
2011-04-16 07:55:27 +10:00
out, ok := m.Pack()
if !ok {
return ErrPack
}
_, err := w.writeClient(out)
2011-04-16 07:55:27 +10:00
if err != nil {
return err
}
return nil
}
2011-11-03 09:06:54 +11:00
func (w *reply) writeClient(p []byte) (n int, err error) {
2011-08-04 21:49:40 +10:00
if w.Client().Attempts == 0 {
panic("c.Attempts 0")
}
2011-08-04 21:49:40 +10:00
if w.Client().Net == "" {
panic("c.Net empty")
}
2011-08-09 00:29:13 +10:00
if w.Client().Hijacked == nil {
2011-08-08 21:10:35 +10:00
if err = w.Dial(); err != nil {
return 0, err
}
2011-11-03 09:06:54 +11:00
w.conn.SetWriteTimeout(w.Client().WriteTimeout)
w.conn.SetReadTimeout(w.Client().ReadTimeout)
2011-09-21 01:40:13 +10:00
2011-04-16 07:55:27 +10:00
}
2011-08-04 21:49:40 +10:00
switch w.Client().Net {
2011-07-06 04:55:05 +10:00
case "tcp", "tcp4", "tcp6":
2011-04-16 07:55:27 +10:00
if len(p) < 2 {
return 0, io.ErrShortBuffer
}
2011-08-04 21:49:40 +10:00
for a := 0; a < w.Client().Attempts; a++ {
2011-08-09 21:15:25 +10:00
a, b := packUint16(uint16(len(p)))
n, err = w.conn.Write([]byte{a, b})
2011-04-16 07:55:27 +10:00
if err != nil {
if e, ok := err.(net.Error); ok && e.Timeout() {
continue
}
return n, err
}
if n != 2 {
return n, io.ErrShortWrite
}
2011-08-08 21:10:35 +10:00
n, err = w.conn.Write(p)
2011-04-16 07:55:27 +10:00
if err != nil {
if e, ok := err.(net.Error); ok && e.Timeout() {
continue
}
return n, err
}
i := n
if i < len(p) {
2011-08-08 21:10:35 +10:00
j, err := w.conn.Write(p[i:len(p)])
2011-04-16 07:55:27 +10:00
if err != nil {
if e, ok := err.(net.Error); ok && e.Timeout() {
// We are half way in our write...
continue
}
return i, err
}
i += j
}
n = i
}
2011-07-06 04:55:05 +10:00
case "udp", "udp4", "udp6":
2011-08-04 21:49:40 +10:00
for a := 0; a < w.Client().Attempts; a++ {
2011-08-08 21:10:35 +10:00
n, err = w.conn.(*net.UDPConn).WriteTo(p, w.conn.RemoteAddr())
2011-04-16 07:55:27 +10:00
if err != nil {
if e, ok := err.(net.Error); ok && e.Timeout() {
continue
}
return 0, err
}
}
}
return 0, nil
}