本文整理汇总了Golang中github.com/miekg/dns.Msg.Rcode方法的典型用法代码示例。如果您正苦于以下问题:Golang Msg.Rcode方法的具体用法?Golang Msg.Rcode怎么用?Golang Msg.Rcode使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类github.com/miekg/dns.Msg
的用法示例。
在下文中一共展示了Msg.Rcode方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: handleEmpty
func (res *Resolver) handleEmpty(rs *records.RecordGenerator, name string, m, r *dns.Msg) error {
qType := r.Question[0].Qtype
switch qType {
case dns.TypeSOA, dns.TypeNS, dns.TypeSRV:
logging.CurLog.MesosSuccess.Inc()
return nil
}
m.Rcode = dns.RcodeNameError
if qType == dns.TypeAAAA && len(rs.SRVs[name])+len(rs.As[name]) > 0 {
m.Rcode = dns.RcodeSuccess
}
logging.CurLog.MesosNXDomain.Inc()
logging.VeryVerbose.Println("total A rrs:\t" + strconv.Itoa(len(rs.As)))
logging.VeryVerbose.Println("failed looking for " + r.Question[0].String())
rr, err := res.formatSOA(r.Question[0].Name)
if err != nil {
return err
}
m.Ns = append(m.Ns, rr)
return nil
}
示例2: leaderResponse
func (h *dnsHandler) leaderResponse(name string, q dns.Question, res *dns.Msg) {
if q.Qtype != dns.TypeA {
return
}
zone := strings.Replace(name, "leader.", "", 1)
if zone != h.zone {
servers, err := h.store.getServers(zone)
if err != nil {
res.Rcode = dns.RcodeServerFailure
return
}
if len(servers) == 0 {
res.Rcode = dns.RcodeNameError
return
}
referral(res, fmt.Sprintf("%s.%s", zone, h.domain), servers)
return
}
leader, err := h.store.getLeader()
if err != nil {
res.Rcode = dns.RcodeServerFailure
return
}
res.Answer = append(res.Answer, newRR(q, leader))
}
示例3: handlerFunc
// handlerFunc receives requests, looks up the result and returns what is found.
func handlerFunc(res dns.ResponseWriter, req *dns.Msg) {
message := new(dns.Msg)
switch req.Opcode {
case dns.OpcodeQuery:
message.SetReply(req)
message.Compress = false
message.Answer = make([]dns.RR, 0)
for _, question := range message.Question {
answers := answerQuestion(strings.ToLower(question.Name), question.Qtype)
if len(answers) > 0 {
for i := range answers {
message.Answer = append(message.Answer, answers[i])
}
} else {
// If there are no records, go back through and search for SOA records
for _, question := range message.Question {
answers := answerQuestion(strings.ToLower(question.Name), dns.TypeSOA)
for i := range answers {
message.Ns = append(message.Ns, answers[i])
}
}
}
}
if len(message.Answer) == 0 && len(message.Ns) == 0 {
message.Rcode = dns.RcodeNameError
}
default:
message = message.SetRcode(req, dns.RcodeNotImplemented)
}
res.WriteMsg(message)
}
示例4: makeDNSFailResponse
func makeDNSFailResponse(r *dns.Msg) *dns.Msg {
m := new(dns.Msg)
m.SetReply(r)
m.RecursionAvailable = true
m.Rcode = dns.RcodeNameError
return m
}
示例5: ServeDNS
func (t *UsageTracker) ServeDNS(w dns.ResponseWriter, r *dns.Msg) {
var latest *usage.ProjectVersion
var event *TrackingEvent
m := new(dns.Msg)
m.SetReply(r)
q := r.Question[0].Name
pv, err := usage.ParseV1(q)
if err != nil {
log.Printf("error parsing %s (%s): %s", q, w.RemoteAddr().(*net.UDPAddr).IP, err)
// m.Rcode = dns.RcodeRefused
m.Rcode = dns.RcodeNameError
goto response
}
latest, err = t.GetLatest(pv)
if err != nil {
// TODO if format is right, but project is missing,
// return an NXDOMAIN error
log.Printf("error fetching latest for %v: %s", pv, err)
m.Rcode = dns.RcodeNameError
goto response
}
// do this after getting the version so we don't track results for
// projects that aren't found
event = &TrackingEvent{*pv, ""}
if addr, ok := w.RemoteAddr().(*net.UDPAddr); ok {
event.ClientAddress = addr.IP.String()
}
if err = t.Track(event); err != nil {
log.Printf("error tracking %v: %s", event, err)
// tracking error is not fatal, so still return the results
}
m.Answer = append(m.Answer, PtrRecord(latest))
response:
err = w.WriteMsg(m)
if err != nil {
log.Printf("error writing response %v: %s", m, err)
}
}
示例6: prepareFailureMsg
func prepareFailureMsg(req *dns.Msg) *dns.Msg {
failMsg := new(dns.Msg)
failMsg.Id = req.Id
failMsg.Response = true
failMsg.Authoritative = true
failMsg.Question = req.Question
failMsg.Rcode = dns.RcodeNameError
return failMsg
}
示例7: prepareAnswerMsg
func prepareAnswerMsg(req *dns.Msg, answers []dns.RR) *dns.Msg {
answerMsg := new(dns.Msg)
answerMsg.Id = req.Id
answerMsg.Response = true
answerMsg.Authoritative = true
answerMsg.Question = req.Question
answerMsg.Answer = answers
answerMsg.Rcode = dns.RcodeSuccess
answerMsg.Extra = []dns.RR{}
return answerMsg
}
示例8: errorResponse
func (d *DNSServer) errorResponse(r *dns.Msg, code int, w dns.ResponseWriter) {
m := dns.Msg{}
m.SetReply(r)
m.RecursionAvailable = true
m.Rcode = code
d.ns.debugf("error response: %+v", m)
if err := w.WriteMsg(&m); err != nil {
d.ns.infof("error responding: %v", err)
}
}
示例9: serviceResponse
func (h *dnsHandler) serviceResponse(name string, q dns.Question, res *dns.Msg) {
if q.Qtype != dns.TypeA && q.Qtype != dns.TypeSRV {
return
}
all := strings.Count(name, ".") == 5 && strings.HasPrefix(name, allPrefix)
if all {
name = name[len(allPrefix):]
}
srv, err := infoFromAddr(name)
if err != nil {
res.Rcode = dns.RcodeNameError
return
}
var instances instances
if all {
instances, err = h.store.getAllInstances(srv)
} else {
instances, err = h.store.getHealthyInstances(srv)
}
if err != nil {
// TODO(ts): Maybe return NoError for registered service without
// instances.
if isNoInstances(err) {
res.Rcode = dns.RcodeNameError
return
}
res.Rcode = dns.RcodeServerFailure
return
}
for _, i := range instances {
res.Answer = append(res.Answer, newRR(q, i))
}
}
示例10: serverResponse
func (h *dnsHandler) serverResponse(name string, q dns.Question, res *dns.Msg) {
if q.Qtype != dns.TypeA && q.Qtype != dns.TypeNS {
return
}
ns, zone := parseServerQuestion(name)
if ns != "" && q.Qtype == dns.TypeNS {
return
}
servers, err := h.store.getServers(zone)
if err != nil && !isNoInstances(err) {
res.Rcode = dns.RcodeServerFailure
return
}
sort.Sort(servers)
// return list of all nameservers
if ns == "" {
for i, server := range servers {
server.host = fmt.Sprintf("ns%d.%s", i, q.Name)
res.Answer = append(res.Answer, newRR(q, server))
}
return
}
// return requested nameserver
index, err := strconv.Atoi(ns[2:])
if err != nil {
res.Rcode = dns.RcodeNameError
return
}
if len(servers) <= index {
return
}
res.Answer = append(res.Answer, newRR(q, servers[index]))
}
示例11: handleEmpty
func (res *Resolver) handleEmpty(rs *records.RecordGenerator, name string, m, r *dns.Msg) error {
qType := r.Question[0].Qtype
switch qType {
case dns.TypeSOA, dns.TypeNS, dns.TypeSRV:
logging.CurLog.MesosSuccess.Inc()
return nil
}
m.Rcode = dns.RcodeNameError
// Because we don't implement AAAA records, AAAA queries will always
// go via this path
// Unfortunately, we don't implement AAAA queries in Mesos-DNS,
// and although the 'Not Implemented' error code seems more suitable,
// RFCs do not recommend it: https://tools.ietf.org/html/rfc4074
// Therefore we always return success, which is synonymous with NODATA
// to get a positive cache on no records AAAA
// Further information:
// PR: https://github.com/mesosphere/mesos-dns/pull/366
// Issue: https://github.com/mesosphere/mesos-dns/issues/363
// The second component is just a matter of returning NODATA if we have
// SRV or A records for the given name, but no neccessarily the given query
if (qType == dns.TypeAAAA) || (len(rs.SRVs[name])+len(rs.As[name]) > 0) {
m.Rcode = dns.RcodeSuccess
}
logging.CurLog.MesosNXDomain.Inc()
logging.VeryVerbose.Println("total A rrs:\t" + strconv.Itoa(len(rs.As)))
logging.VeryVerbose.Println("failed looking for " + r.Question[0].String())
m.Ns = append(m.Ns, res.formatSOA(r.Question[0].Name))
return nil
}
示例12: handleRequest
func handleRequest(w dns.ResponseWriter, r *dns.Msg) {
q := r.Question[0]
info := fmt.Sprintf("Question: Type=%s Class=%s Name=%s", dns.TypeToString[q.Qtype], dns.ClassToString[q.Qclass], q.Name)
if q.Qtype == dns.TypeA && q.Qclass == dns.ClassINET {
m := new(dns.Msg)
m.SetReply(r)
a := new(dns.A)
a.Hdr = dns.RR_Header{Name: q.Name, Rrtype: dns.TypeA, Class: dns.ClassINET, Ttl: 600}
a.A = resolveIP
m.Answer = []dns.RR{a}
w.WriteMsg(m)
log.Printf("%s (RESOLVED)\n", info)
} else {
m := new(dns.Msg)
m.SetReply(r)
m.Rcode = dns.RcodeNameError // NXDOMAIN
w.WriteMsg(m)
log.Printf("%s (NXDOMAIN)\n", info)
}
}
示例13: ServeDNS
func (f File) ServeDNS(ctx context.Context, w dns.ResponseWriter, r *dns.Msg) (int, error) {
state := middleware.State{W: w, Req: r}
if state.QClass() != dns.ClassINET {
return dns.RcodeServerFailure, errors.New("can only deal with ClassINET")
}
qname := state.Name()
zone := middleware.Zones(f.Zones.Names).Matches(qname)
if zone == "" {
if f.Next != nil {
return f.Next.ServeDNS(ctx, w, r)
}
return dns.RcodeServerFailure, errors.New("no next middleware found")
}
z, ok := f.Zones.Z[zone]
if !ok {
return f.Next.ServeDNS(ctx, w, r)
}
if z == nil {
return dns.RcodeServerFailure, nil
}
if r.Opcode == dns.OpcodeNotify {
if z.isNotify(state) {
m := new(dns.Msg)
m.SetReply(r)
m.Authoritative, m.RecursionAvailable, m.Compress = true, true, true
state.SizeAndDo(m)
w.WriteMsg(m)
log.Printf("[INFO] Notify from %s for %s: checking transfer", state.IP(), zone)
ok, err := z.shouldTransfer()
if ok {
z.TransferIn()
} else {
log.Printf("[INFO] Notify from %s for %s: no serial increase seen", state.IP(), zone)
}
if err != nil {
log.Printf("[WARNING] Notify from %s for %s: failed primary check: %s", state.IP(), zone, err)
}
return dns.RcodeSuccess, nil
}
log.Printf("[INFO] Dropping notify from %s for %s", state.IP(), zone)
return dns.RcodeSuccess, nil
}
if z.Expired != nil && *z.Expired {
log.Printf("[ERROR] Zone %s is expired", zone)
return dns.RcodeServerFailure, nil
}
if state.QType() == dns.TypeAXFR || state.QType() == dns.TypeIXFR {
xfr := Xfr{z}
return xfr.ServeDNS(ctx, w, r)
}
answer, ns, extra, result := z.Lookup(qname, state.QType(), state.Do())
m := new(dns.Msg)
m.SetReply(r)
m.Authoritative, m.RecursionAvailable, m.Compress = true, true, true
m.Answer, m.Ns, m.Extra = answer, ns, extra
switch result {
case Success:
case NoData:
case NameError:
m.Rcode = dns.RcodeNameError
case Delegation:
m.Authoritative = false
case ServerFailure:
return dns.RcodeServerFailure, nil
}
state.SizeAndDo(m)
m, _ = state.Scrub(m)
w.WriteMsg(m)
return dns.RcodeSuccess, nil
}
示例14: ServeDNS
// ServeDNS is the handler for DNS requests, responsible for parsing DNS request, possibly forwarding
// it to a real dns server and returning a response.
func (s *server) ServeDNS(w dns.ResponseWriter, req *dns.Msg) {
m := new(dns.Msg)
m.SetReply(req)
m.Authoritative = true
m.RecursionAvailable = true
m.Compress = true
bufsize := uint16(512)
dnssec := false
tcp := false
start := time.Now()
if req.Question[0].Qtype == dns.TypeANY {
m.Authoritative = false
m.Rcode = dns.RcodeRefused
m.RecursionAvailable = false
m.RecursionDesired = false
m.Compress = false
// if write fails don't care
w.WriteMsg(m)
promErrorCount.WithLabelValues("refused").Inc()
return
}
if o := req.IsEdns0(); o != nil {
bufsize = o.UDPSize()
dnssec = o.Do()
}
if bufsize < 512 {
bufsize = 512
}
// with TCP we can send 64K
if tcp = isTCP(w); tcp {
bufsize = dns.MaxMsgSize - 1
promRequestCount.WithLabelValues("tcp").Inc()
} else {
promRequestCount.WithLabelValues("udp").Inc()
}
StatsRequestCount.Inc(1)
if dnssec {
StatsDnssecOkCount.Inc(1)
promDnssecOkCount.Inc()
}
defer func() {
promCacheSize.WithLabelValues("response").Set(float64(s.rcache.Size()))
}()
// Check cache first.
key := cache.QuestionKey(req.Question[0], dnssec)
m1, exp, hit := s.rcache.Search(key)
if hit {
// Cache hit! \o/
if time.Since(exp) < 0 {
m1.Id = m.Id
m1.Compress = true
m1.Truncated = false
if dnssec {
// The key for DNS/DNSSEC in cache is different, no
// need to do Denial/Sign here.
//if s.config.PubKey != nil {
//s.Denial(m1) // not needed for cache hits
//s.Sign(m1, bufsize)
//}
}
if m1.Len() > int(bufsize) && !tcp {
promErrorCount.WithLabelValues("truncated").Inc()
m1.Truncated = true
}
// Still round-robin even with hits from the cache.
// Only shuffle A and AAAA records with each other.
if req.Question[0].Qtype == dns.TypeA || req.Question[0].Qtype == dns.TypeAAAA {
s.RoundRobin(m1.Answer)
}
if err := w.WriteMsg(m1); err != nil {
log.Printf("skydns: failure to return reply %q", err)
}
metricSizeAndDuration(m1, start, tcp)
return
}
// Expired! /o\
s.rcache.Remove(key)
}
q := req.Question[0]
name := strings.ToLower(q.Name)
if s.config.Verbose {
log.Printf("skydns: received DNS Request for %q from %q with type %d", q.Name, w.RemoteAddr(), q.Qtype)
}
for zone, ns := range *s.config.stub {
if strings.HasSuffix(name, zone) {
resp := s.ServeDNSStubForward(w, req, ns)
//.........这里部分代码省略.........
示例15: TestUDPDNSServer
func TestUDPDNSServer(t *testing.T) {
setupForTest(t)
const (
successTestName = "test1.weave.local."
failTestName = "fail.weave.local."
nonLocalName = "weave.works."
testAddr1 = "10.2.2.1"
containerID = "somecontainer"
)
testCIDR1 := testAddr1 + "/24"
InitDefaultLogging(testing.Verbose())
Info.Println("TestUDPDNSServer starting")
zone, err := NewZoneDb(ZoneConfig{})
require.NoError(t, err)
err = zone.Start()
require.NoError(t, err)
defer zone.Stop()
ip, _, _ := net.ParseCIDR(testCIDR1)
zone.AddRecord(containerID, successTestName, ip)
fallbackHandler := func(w dns.ResponseWriter, req *dns.Msg) {
if len(req.Question) == 0 {
return // ignore empty queries (sent when shutting down the server)
}
m := new(dns.Msg)
m.SetReply(req)
q := req.Question[0]
if q.Name == nonLocalName && q.Qtype == dns.TypeMX {
m.Answer = make([]dns.RR, 1)
m.Answer[0] = &dns.MX{Hdr: dns.RR_Header{Name: m.Question[0].Name, Rrtype: dns.TypeMX, Class: dns.ClassINET, Ttl: 0}, Mx: "mail." + nonLocalName}
} else if q.Name == nonLocalName && q.Qtype == dns.TypeANY {
m.Answer = make([]dns.RR, 512/len("mailn."+nonLocalName)+1)
for i := range m.Answer {
m.Answer[i] = &dns.MX{Hdr: dns.RR_Header{Name: m.Question[0].Name, Rrtype: dns.TypeMX, Class: dns.ClassINET, Ttl: 0}, Mx: fmt.Sprintf("mail%d.%s", i, nonLocalName)}
}
} else if q.Name == testRDNSnonlocal && q.Qtype == dns.TypePTR {
m.Answer = make([]dns.RR, 1)
m.Answer[0] = &dns.PTR{Hdr: dns.RR_Header{Name: m.Question[0].Name, Rrtype: dns.TypePTR, Class: dns.ClassINET, Ttl: 0}, Ptr: "ns1.google.com."}
} else if q.Name == testRDNSfail && q.Qtype == dns.TypePTR {
m.Rcode = dns.RcodeNameError
}
w.WriteMsg(m)
}
// Run another DNS server for fallback
fallback, err := newMockedFallback(fallbackHandler, nil)
require.NoError(t, err)
fallback.Start()
defer fallback.Stop()
srv, err := NewDNSServer(DNSServerConfig{
Zone: zone,
UpstreamCfg: fallback.CliConfig,
CacheDisabled: true,
ListenReadTimeout: testSocketTimeout,
})
require.NoError(t, err)
err = srv.Start()
require.NoError(t, err)
go srv.ActivateAndServe()
defer srv.Stop()
time.Sleep(100 * time.Millisecond) // Allow sever goroutine to start
var r *dns.Msg
testPort, err := srv.GetPort()
require.NoError(t, err)
require.NotEqual(t, 0, testPort, "invalid listen port")
_, r = assertExchange(t, successTestName, dns.TypeA, testPort, 1, 1, 0)
require.IsType(t, (*dns.A)(nil), r.Answer[0], "DNS record")
require.Equal(t, testAddr1, r.Answer[0].(*dns.A).A.String(), "IP address")
assertExchange(t, failTestName, dns.TypeA, testPort, 0, 0, dns.RcodeNameError)
_, r = assertExchange(t, testRDNSsuccess, dns.TypePTR, testPort, 1, 1, 0)
require.IsType(t, (*dns.PTR)(nil), r.Answer[0], "DNS record")
require.Equal(t, successTestName, r.Answer[0].(*dns.PTR).Ptr, "IP address")
assertExchange(t, testRDNSfail, dns.TypePTR, testPort, 0, 0, dns.RcodeNameError)
// This should fail because we don't handle MX records
assertExchange(t, successTestName, dns.TypeMX, testPort, 0, 0, dns.RcodeNameError)
// This non-local query for an MX record should succeed by being
// passed on to the fallback server
assertExchange(t, nonLocalName, dns.TypeMX, testPort, 1, -1, 0)
// Now ask a query that we expect to return a lot of data.
assertExchange(t, nonLocalName, dns.TypeANY, testPort, 5, -1, 0)
assertExchange(t, testRDNSnonlocal, dns.TypePTR, testPort, 1, -1, 0)
// Not testing MDNS functionality of server here (yet), since it
// needs two servers, each listening on its own address
}