本文整理汇总了Golang中github.com/miekg/dns.Msg类的典型用法代码示例。如果您正苦于以下问题:Golang Msg类的具体用法?Golang Msg怎么用?Golang Msg使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Msg类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: get_serial
func get_serial(zone_name, query_dest string) (uint32, error) {
var in *dns.Msg
m := new(dns.Msg)
m.SetQuestion(zone_name, dns.TypeSOA)
if conf.Transfer_source != nil {
d := net.Dialer{LocalAddr: conf.Transfer_source}
c, err := d.Dial("tcp", query_dest)
if err != nil {
logger.Error(fmt.Sprintf("QUERY ERROR : problem dialing query_dest %s", query_dest))
return 0, err
}
co := &dns.Conn{Conn: c}
co.WriteMsg(m)
in, err = co.ReadMsg()
if err != nil {
logger.Error(fmt.Sprintf("QUERY ERROR : problem querying query_dest %s", query_dest))
return 0, err
}
co.Close()
} else {
c := &dns.Client{DialTimeout: conf.Query_timeout, ReadTimeout: conf.Query_timeout}
if conf.All_tcp == true {
c.Net = "tcp"
}
// _ is query time, might be useful later
var err error
in, _, err = c.Exchange(m, query_dest)
if err != nil {
logger.Error(fmt.Sprintf("QUERY ERROR : problem querying query_dest %s", query_dest))
return 0, err
}
}
return serial_query_parse(in), nil
}
示例2: handleSRV
func (res *Resolver) handleSRV(rs *records.RecordGenerator, name string, m, r *dns.Msg) error {
var errs multiError
added := map[string]struct{}{} // track the A RR's we've already added, avoid dups
for srv := range rs.SRVs[name] {
srvRR, err := res.formatSRV(r.Question[0].Name, srv)
if err != nil {
errs.Add(err)
continue
}
m.Answer = append(m.Answer, srvRR)
host := strings.Split(srv, ":")[0]
if _, found := added[host]; found {
// avoid dups
continue
}
if len(rs.As[host]) == 0 {
continue
}
if a, ok := rs.As.First(host); ok {
aRR, err := res.formatA(host, a)
if err != nil {
errs.Add(err)
continue
}
m.Extra = append(m.Extra, aRR)
added[host] = struct{}{}
}
}
return errs
}
示例3: handlePTRQuery
func (r *resolver) handlePTRQuery(ptr string, query *dns.Msg) (*dns.Msg, error) {
parts := []string{}
if strings.HasSuffix(ptr, ptrIPv4domain) {
parts = strings.Split(ptr, ptrIPv4domain)
} else if strings.HasSuffix(ptr, ptrIPv6domain) {
parts = strings.Split(ptr, ptrIPv6domain)
} else {
return nil, fmt.Errorf("invalid PTR query, %v", ptr)
}
host := r.backend.ResolveIP(parts[0])
if len(host) == 0 {
return nil, nil
}
logrus.Debugf("Lookup for IP %s: name %s", parts[0], host)
fqdn := dns.Fqdn(host)
resp := new(dns.Msg)
resp.SetReply(query)
setCommonFlags(resp)
rr := new(dns.PTR)
rr.Hdr = dns.RR_Header{Name: ptr, Rrtype: dns.TypePTR, Class: dns.ClassINET, Ttl: respTTL}
rr.Ptr = fqdn
resp.Answer = append(resp.Answer, rr)
return resp, nil
}
示例4: handleDNS
// handleDNS is a handler function to actualy perform the dns querey response
func (c *CatchAll) handleDNS(w dns.ResponseWriter, r *dns.Msg) {
defer w.Close()
var rr dns.RR
domainSpoof := r.Question[0].Name
msgResp := new(dns.Msg)
msgResp.SetReply(r)
msgResp.Compress = false
rr = new(dns.A)
if c.SpoofDomain {
rr.(*dns.A).Hdr = dns.RR_Header{Name: domainSpoof, Rrtype: dns.TypeA, Class: dns.ClassINET, Ttl: 0}
} else {
rr.(*dns.A).Hdr = dns.RR_Header{Name: c.Domain, Rrtype: dns.TypeA, Class: dns.ClassINET, Ttl: 0}
}
rr.(*dns.A).A = c.IP
switch r.Question[0].Qtype {
case dns.TypeA:
msgResp.Answer = append(msgResp.Answer, rr)
default:
log.Warnf("Unknown dns type %T", r.Question[0].Qtype)
return
}
w.WriteMsg(msgResp)
}
示例5: resolve
// Perform DNS resolution
func resolve(w http.ResponseWriter, r *http.Request, server string, domain string, querytype uint16) {
m := new(dns.Msg)
m.SetQuestion(domain, querytype)
m.MsgHdr.RecursionDesired = true
w.Header().Set("Content-Type", "application/json")
w.Header().Set("Access-Control-Allow-Origin", "*")
c := new(dns.Client)
Redo:
if in, _, err := c.Exchange(m, server); err == nil { // Second return value is RTT, not used for now
if in.MsgHdr.Truncated {
c.Net = "tcp"
goto Redo
}
switch in.MsgHdr.Rcode {
case dns.RcodeServerFailure:
error(w, 500, 502, "The name server encountered an internal failure while processing this request (SERVFAIL)")
case dns.RcodeNameError:
error(w, 500, 503, "Some name that ought to exist, does not exist (NXDOMAIN)")
case dns.RcodeRefused:
error(w, 500, 505, "The name server refuses to perform the specified operation for policy or security reasons (REFUSED)")
default:
jsonify(w, r, in.Question, in.Answer, in.Ns, in.Extra)
}
} else {
error(w, 500, 501, "DNS server could not be reached")
}
}
示例6: TestDNS_CaseInsensitiveNodeLookup
func TestDNS_CaseInsensitiveNodeLookup(t *testing.T) {
dir, srv := makeDNSServer(t)
defer os.RemoveAll(dir)
defer srv.agent.Shutdown()
testutil.WaitForLeader(t, srv.agent.RPC, "dc1")
// Register node
args := &structs.RegisterRequest{
Datacenter: "dc1",
Node: "Foo",
Address: "127.0.0.1",
}
var out struct{}
if err := srv.agent.RPC("Catalog.Register", args, &out); err != nil {
t.Fatalf("err: %v", err)
}
m := new(dns.Msg)
m.SetQuestion("fOO.node.dc1.consul.", dns.TypeANY)
c := new(dns.Client)
addr, _ := srv.agent.config.ClientListener("", srv.agent.config.Ports.DNS)
in, _, err := c.Exchange(m, addr.String())
if err != nil {
t.Fatalf("err: %v", err)
}
if len(in.Answer) != 1 {
t.Fatalf("empty lookup: %#v", in)
}
}
示例7: TestDNS_Recurse
func TestDNS_Recurse(t *testing.T) {
recursor := makeRecursor(t, []dns.RR{dnsA("apple.com", "1.2.3.4")})
defer recursor.Shutdown()
dir, srv := makeDNSServerConfig(t, func(c *Config) {
c.DNSRecursor = recursor.Addr
}, nil)
defer os.RemoveAll(dir)
defer srv.agent.Shutdown()
m := new(dns.Msg)
m.SetQuestion("apple.com.", dns.TypeANY)
c := new(dns.Client)
addr, _ := srv.agent.config.ClientListener("", srv.agent.config.Ports.DNS)
in, _, err := c.Exchange(m, addr.String())
if err != nil {
t.Fatalf("err: %v", err)
}
if len(in.Answer) == 0 {
t.Fatalf("Bad: %#v", in)
}
if in.Rcode != dns.RcodeSuccess {
t.Fatalf("Bad: %#v", in)
}
}
示例8: TestMsgOverflow
func TestMsgOverflow(t *testing.T) {
if testing.Short() {
t.Skip("skipping test in short mode.")
}
s := newTestServer(t, false)
defer s.Stop()
c := new(dns.Client)
m := new(dns.Msg)
// TODO(miek): rethink how to enable metrics in tests.
if !metricsDone {
Metrics()
}
for i := 0; i < 2000; i++ {
is := strconv.Itoa(i)
m := &msg.Service{
Host: "2001::" + is, Key: "machine" + is + ".machines.skydns.test.",
}
addService(t, s, m.Key, 0, m)
defer delService(t, s, m.Key)
}
m.SetQuestion("machines.skydns.test.", dns.TypeSRV)
resp, _, err := c.Exchange(m, "127.0.0.1:"+StrPort)
if err != nil {
t.Fatal(err)
}
t.Logf("%s", resp)
if resp.Rcode != dns.RcodeServerFailure {
t.Fatalf("expecting server failure, got %d", resp.Rcode)
}
}
示例9: handlePTRRequest
func (s *DNSServer) handlePTRRequest(r *dns.Msg, m *dns.Msg) {
m.Answer = make([]dns.RR, 0, 2)
query := r.Question[0].Name
if query[len(query)-1] == '.' {
query = query[:len(query)-1]
}
for service := range s.queryIp(query) {
var ttl int
if service.Ttl != -1 {
ttl = service.Ttl
} else {
ttl = s.config.ttl
}
for domain := range s.listDomains(service) {
rr := new(dns.PTR)
rr.Hdr = dns.RR_Header{
Name: r.Question[0].Name,
Rrtype: dns.TypePTR,
Class: dns.ClassINET,
Ttl: uint32(ttl),
}
rr.Ptr = domain
m.Answer = append(m.Answer, rr)
}
}
}
示例10: ParseDnsFrame
func ParseDnsFrame(f Frame, req *dns.Msg) (addrs []net.IP, err error) {
ft, ok := f.(*FrameDns)
if !ok {
return nil, ErrDnsMsgIllegal
}
res := new(dns.Msg)
err = res.Unpack(ft.Data)
if err != nil || !res.Response || res.Id != req.Id {
return nil, ErrDnsMsgIllegal
}
if DEBUGDNS {
DebugDNS(res, req.Question[0].Name)
}
for _, a := range res.Answer {
switch ta := a.(type) {
case *dns.A:
addrs = append(addrs, ta.A)
case *dns.AAAA:
addrs = append(addrs, ta.AAAA)
}
}
return
}
示例11: TestShuffleAnswers
func TestShuffleAnswers(t *testing.T) {
var res Resolver
m := new(dns.Msg)
for i := 0; i < 10; i++ {
name := "10.0.0." + strconv.Itoa(i)
rr, err := res.formatA("blah.com", name)
if err != nil {
t.Error(err)
}
m.Answer = append(m.Answer, rr)
}
n := new(dns.Msg)
c := make([]dns.RR, len(m.Answer))
copy(c, m.Answer)
n.Answer = c
_ = shuffleAnswers(m.Answer)
sflag := false
// 10! chance of failing here
for i := 0; i < 10; i++ {
if n.Answer[i] != m.Answer[i] {
sflag = true
break
}
}
if !sflag {
t.Error("not shuffling")
}
}
示例12: handle
func handle(writer dns.ResponseWriter, request *dns.Msg) {
message := new(dns.Msg)
message.SetReply(request)
message.SetRcode(message, dns.RcodeSuccess)
question := request.Question[0]
switch request.Opcode {
case dns.OpcodeNotify:
log.Println(fmt.Sprintf("Recieved NOTIFY for %s", question.Name))
message = handle_notify(question, message, writer)
case dns.OpcodeQuery:
log.Println(fmt.Sprintf("Recieved QUERY for %s", question.Name))
message = handle_query(question, message, writer)
default:
message = handle_error(message, writer, "REFUSED")
}
// Apparently this dns library takes the question out on
// certain RCodes, like REFUSED, which is not right. So we reinsert it.
message.Question[0].Name = question.Name
message.Question[0].Qtype = question.Qtype
message.Question[0].Qclass = question.Qclass
message.MsgHdr.Opcode = request.Opcode
// Send an authoritative answer
message.MsgHdr.Authoritative = true
writer.WriteMsg(message)
}
示例13: metazone
// Create DNS packet with the config in line with the meta zone
// paper from Vixie
func metazone(w dns.ResponseWriter, req *dns.Msg, c *Config) {
logPrintf("metazone command")
// Only called when the class is CHAOS
// PTR zone. -> get a list of zone names
// Top level zone stuff -- list them
if strings.ToUpper(req.Question[0].Name) == "ZONE." {
m := new(dns.Msg)
m.SetReply(req)
for _, z := range c.Zones {
ptr, _ := dns.NewRR("zone. 0 CH PTR " + z.Origin)
m.Answer = append(m.Answer, ptr)
}
w.WriteMsg(m)
return
}
// Top level user stuff -- list them
if strings.ToUpper(req.Question[0].Name) == "USER." {
}
// <zone>.ZONE.
formerr(w, req)
return
}
示例14: handleExplanation
func (p *Parser) handleExplanation() string {
resolvedDomain, err := ParseMacroToken(p, p.Explanation)
if err != nil || isEmpty(&resolvedDomain) {
// TODO(zaccone): Should we return some internal error
return ""
}
resolvedDomain = NormalizeHost(resolvedDomain)
query := new(dns.Msg)
query.SetQuestion(resolvedDomain, dns.TypeTXT)
c := new(dns.Client)
response, _, err := c.Exchange(query, Nameserver)
if err != nil || (response != nil && response.Rcode != dns.RcodeSuccess) {
return ""
}
explanation := make([]string, 0, len(response.Answer))
for _, answer := range response.Answer {
if q, ok := answer.(*dns.TXT); ok {
for _, txt := range q.Txt {
explanation = append(explanation, txt)
}
}
}
// RFC 7208, section 6.2 specifies that result string should be
// concatenated with no spaces.
parsedExplanation, err := ParseMacro(p, strings.Join(explanation, ""))
if err != nil {
return ""
}
return parsedExplanation
}
示例15: TestPrune
// Check that we can prune an answer
func TestPrune(t *testing.T) {
InitDefaultLogging(testing.Verbose())
Info.Println("TestPrune starting")
questionMsg := new(dns.Msg)
questionMsg.SetQuestion("name", dns.TypeA)
questionMsg.RecursionDesired = true
question := &questionMsg.Question[0]
records := []ZoneRecord{
Record{"name", net.ParseIP("10.0.1.1"), 0, 0, 0},
Record{"name", net.ParseIP("10.0.1.2"), 0, 0, 0},
Record{"name", net.ParseIP("10.0.1.3"), 0, 0, 0},
Record{"name", net.ParseIP("10.0.1.4"), 0, 0, 0},
}
reply := makeAddressReply(questionMsg, question, records, DefaultLocalTTL)
reply.Answer[0].Header().Ttl = DefaultLocalTTL
pruned := pruneAnswers(reply.Answer, 1)
require.Equal(t, 1, len(pruned), "wrong number of answers")
pruned = pruneAnswers(reply.Answer, 2)
require.Equal(t, 2, len(pruned), "wrong number of answers")
pruned = pruneAnswers(reply.Answer, 0)
require.Equal(t, len(records), len(pruned), "wrong number of answers")
}