|
| 1 | +package datahub |
| 2 | + |
| 3 | +import ( |
| 4 | + "net" |
| 5 | + "strconv" |
| 6 | + "time" |
| 7 | + |
| 8 | + "github.com/coredns/coredns/plugin/dnstap/msg" |
| 9 | + "github.com/coredns/coredns/request" |
| 10 | + |
| 11 | + tap "github.com/dnstap/golang-dnstap" |
| 12 | + "github.com/miekg/dns" |
| 13 | +) |
| 14 | + |
| 15 | +// toDnstap will send the forward and received message to the dnstap plugin. |
| 16 | +func (dh *Datahub) ToDnstap(host string, state *request.Request, reply *dns.Msg, start time.Time) { |
| 17 | + if tapPlugin == nil { |
| 18 | + return |
| 19 | + } |
| 20 | + // Query |
| 21 | + q := new(tap.Message) |
| 22 | + msg.SetQueryTime(q, start) |
| 23 | + h, p, _ := net.SplitHostPort(host) // this is preparsed and can't err here |
| 24 | + port, _ := strconv.ParseUint(p, 10, 32) // same here |
| 25 | + ip := net.ParseIP(h) |
| 26 | + |
| 27 | + var ta net.Addr = &net.UDPAddr{IP: ip, Port: int(port)} |
| 28 | + t := state.Proto() |
| 29 | + if t == "tcp" { |
| 30 | + ta = &net.TCPAddr{IP: ip, Port: int(port)} |
| 31 | + } |
| 32 | + |
| 33 | + // Forwarder dnstap messages are from the perspective of the downstream server |
| 34 | + // (upstream is the forward server) |
| 35 | + msg.SetQueryAddress(q, state.W.RemoteAddr()) |
| 36 | + msg.SetResponseAddress(q, ta) |
| 37 | + |
| 38 | + if tapPlugin.IncludeRawMessage { |
| 39 | + buf, _ := state.Req.Pack() |
| 40 | + q.QueryMessage = buf |
| 41 | + } |
| 42 | + msg.SetType(q, tap.Message_FORWARDER_QUERY) |
| 43 | + tapPlugin.TapMessage(q) |
| 44 | + |
| 45 | + // Response |
| 46 | + if reply != nil { |
| 47 | + r := new(tap.Message) |
| 48 | + if tapPlugin.IncludeRawMessage { |
| 49 | + buf, _ := reply.Pack() |
| 50 | + r.ResponseMessage = buf |
| 51 | + } |
| 52 | + msg.SetQueryTime(r, start) |
| 53 | + msg.SetQueryAddress(r, state.W.RemoteAddr()) |
| 54 | + msg.SetResponseAddress(r, ta) |
| 55 | + msg.SetResponseTime(r, time.Now()) |
| 56 | + msg.SetType(r, tap.Message_FORWARDER_RESPONSE) |
| 57 | + tapPlugin.TapMessage(r) |
| 58 | + } |
| 59 | +} |
0 commit comments