本文整理汇总了Golang中github.com/miekg/dns.ResponseWriter类的典型用法代码示例。如果您正苦于以下问题:Golang ResponseWriter类的具体用法?Golang ResponseWriter怎么用?Golang ResponseWriter使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了ResponseWriter类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: handleRequest
// Handles an incoming DNS request packet. This function decides whether
// the hostname listed in the DNS packet is worthy of manipulation, or
// not. The IP addresses listed in the reply to the user for a target
// hostname are added to the routing table at this time before a
// reply is sent back to the user, otherwise the user agent of the client
// might connect faster than the routing changes can be made.
func handleRequest(w dns.ResponseWriter, req *dns.Msg) {
var m *dns.Msg
// check if the the hostname in the request matches the target
if len(req.Question) > 0 && isTargetZone(req.Question[0].Name) {
// handle `A` and `AAAA` types accordingly
// other record types will be forwarded without manipulation
switch req.Question[0].Qtype {
case dns.TypeA:
m = handleV4Hijack(w, req)
case dns.TypeAAAA:
m = handleV6Hijack(w, req)
}
}
// if no reply was previously set, forward it
if m == nil {
m = getServerReply(w, req)
}
// send reply back to user
w.WriteMsg(m)
}
示例2: handleTest
// handleTest is used to handle DNS queries in the ".consul." domain
func (d *DNSServer) handleTest(resp dns.ResponseWriter, req *dns.Msg) {
q := req.Question[0]
defer func(s time.Time) {
d.logger.Printf("[DEBUG] dns: request for %v (%v)", q, time.Now().Sub(s))
}(time.Now())
if !(q.Qtype == dns.TypeANY || q.Qtype == dns.TypeTXT) {
return
}
if q.Name != testQuery {
return
}
// Always respond with TXT "ok"
m := new(dns.Msg)
m.SetReply(req)
m.Authoritative = true
m.RecursionAvailable = true
header := dns.RR_Header{Name: q.Name, Rrtype: dns.TypeTXT, Class: dns.ClassINET, Ttl: 0}
txt := &dns.TXT{header, []string{"ok"}}
m.Answer = append(m.Answer, txt)
d.addSOA(consulDomain, m)
if err := resp.WriteMsg(m); err != nil {
d.logger.Printf("[WARN] dns: failed to respond: %v", err)
}
}
示例3: 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)
}
示例4: handleQuery
// handleQUery is used to handle DNS queries in the configured domain
func (d *DNSServer) handleQuery(resp dns.ResponseWriter, req *dns.Msg) {
q := req.Question[0]
defer func(s time.Time) {
d.logger.Printf("[DEBUG] dns: request for %v (%v)", q, time.Now().Sub(s))
}(time.Now())
// Switch to TCP if the client is
network := "udp"
if _, ok := resp.RemoteAddr().(*net.TCPAddr); ok {
network = "tcp"
}
// Setup the message response
m := new(dns.Msg)
m.SetReply(req)
m.Authoritative = true
m.RecursionAvailable = (len(d.recursors) > 0)
// Only add the SOA if requested
if req.Question[0].Qtype == dns.TypeSOA {
d.addSOA(d.domain, m)
}
// Dispatch the correct handler
d.dispatch(network, req, m)
// Write out the complete response
if err := resp.WriteMsg(m); err != nil {
d.logger.Printf("[WARN] dns: failed to respond: %v", err)
}
}
示例5: resolver
// resolver responds to all DNS A record requests with an address from addrpool,
// maintaining a mapping to the domain's actual IP address.
func resolver(w dns.ResponseWriter, req *dns.Msg) {
msg, err := dns.Exchange(req, dnsserver)
if err != nil {
log.Printf("Couldn't query: %v", err)
// TODO return error Msg
return
}
for _, rr := range msg.Answer {
// TODO do this for only one record, delete the others.
if rr.Header().Rrtype == dns.TypeA {
a := rr.(*dns.A)
addrpool.Lock()
addr, ok := addrpool.domains[a.Hdr.Name]
// Maybe we should also Get it on ok to push it up the LRU cache.
if !ok {
addrpool.pool.RemoveOldest()
addrpool.pool.Add(ip4touint32(addrpool.freeaddr), a.Hdr.Name)
log.Printf("Adding %v -> %s", addrpool.freeaddr, a.Hdr.Name)
addr = addrpool.freeaddr
addrpool.domains[a.Hdr.Name] = addr
}
addrpool.Unlock()
log.Println("Type A:", a.A)
a.A = addr
a.Hdr.Ttl = 1
}
}
w.WriteMsg(msg)
}
示例6: TransferHandler
func (s *soa) TransferHandler(w dns.ResponseWriter, req *dns.Msg) {
m := new(dns.Msg)
m.SetReply(req)
m.Answer = make([]dns.RR, 1)
m.Answer[0] = test.SOA(fmt.Sprintf("%s IN SOA bla. bla. %d 0 0 0 0 ", testZone, s.serial))
w.WriteMsg(m)
}
示例7: 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
}
示例8: forwardQueryStart
func (r *resolver) forwardQueryStart(w dns.ResponseWriter, msg *dns.Msg, queryID uint16) bool {
proto := w.LocalAddr().Network()
dnsID := uint16(rand.Intn(maxDNSID))
cc := clientConn{
dnsID: queryID,
respWriter: w,
}
r.queryLock.Lock()
defer r.queryLock.Unlock()
if r.count == maxConcurrent {
return false
}
r.count++
switch proto {
case "tcp":
break
case "udp":
for ok := true; ok == true; dnsID = uint16(rand.Intn(maxDNSID)) {
_, ok = r.client[dnsID]
}
log.Debugf("client dns id %v, changed id %v", queryID, dnsID)
r.client[dnsID] = cc
msg.Id = dnsID
default:
log.Errorf("Invalid protocol..")
return false
}
return true
}
示例9: forwardQueryEnd
func (r *resolver) forwardQueryEnd(w dns.ResponseWriter, msg *dns.Msg) dns.ResponseWriter {
var (
cc clientConn
ok bool
)
proto := w.LocalAddr().Network()
r.queryLock.Lock()
defer r.queryLock.Unlock()
if r.count == 0 {
log.Errorf("Invalid concurrent query count")
} else {
r.count--
}
switch proto {
case "tcp":
break
case "udp":
if cc, ok = r.client[msg.Id]; ok == false {
log.Debugf("Can't retrieve client context for dns id %v", msg.Id)
return nil
}
log.Debugf("dns msg id %v, client id %v", msg.Id, cc.dnsID)
delete(r.client, msg.Id)
msg.Id = cc.dnsID
w = cc.respWriter
default:
log.Errorf("Invalid protocol")
return nil
}
return w
}
示例10: handleDNSExternal
func (s *DNS) handleDNSExternal(w dns.ResponseWriter, req *dns.Msg) {
network := "udp"
if _, ok := w.RemoteAddr().(*net.TCPAddr); ok {
network = "tcp"
}
c := &dns.Client{Net: network}
var r *dns.Msg
var err error
for _, recursor := range s.recursors {
if recursor == "" {
log.Printf("Found empty recursor")
continue
}
log.Printf("Forwarding request to external recursor for: %s", req.Question[0].Name)
r, _, err = c.Exchange(req, recursor)
if err == nil {
if err := w.WriteMsg(r); err != nil {
log.Printf("DNS lookup failed %v", err)
}
return
}
}
dns.HandleFailed(w, req)
}
示例11: handleDnsRequest
func handleDnsRequest(w dns.ResponseWriter, r *dns.Msg) {
m := new(dns.Msg)
m.SetReply(r)
records := make([]dns.RR, 0)
q := r.Question[0]
if q.Qtype == dns.TypeA && strings.HasSuffix(q.Name, ".docker.") {
docker, _ := dockerclient.NewDockerClient("unix:///var/run/docker.sock", &tls.Config{})
name := strings.SplitN(q.Name, ".", 2)[0]
containers, err := docker.ListContainers(false, false, fmt.Sprintf("{\"name\":[\"%s\"]}", name))
if err != nil {
log.Fatal(err)
}
for _, c := range containers {
info, _ := docker.InspectContainer(c.Id)
log.Printf("Container %s[%6s] has ip %s\n", name, info.Id, info.NetworkSettings.IPAddress)
records = append(records,
&dns.A{
Hdr: dns.RR_Header{
Name: q.Name,
Rrtype: dns.TypeA,
Class: dns.ClassINET,
Ttl: 60},
A: net.ParseIP(info.NetworkSettings.IPAddress),
})
}
}
m.Answer = append(m.Answer, records...)
defer w.WriteMsg(m)
}
示例12: handleDNSInternal
func (s *DNS) handleDNSInternal(w dns.ResponseWriter, req *dns.Msg) {
q := req.Question[0]
if q.Qtype == dns.TypeA && q.Qclass == dns.ClassINET {
if record, ok := s.cache.Get(q.Name); ok {
log.Printf("Found internal record for %s", q.Name)
m := new(dns.Msg)
m.SetReply(req)
rr_header := dns.RR_Header{
Name: q.Name,
Rrtype: dns.TypeA,
Class: dns.ClassINET,
Ttl: 0,
}
a := &dns.A{rr_header, net.ParseIP(record.ip)}
m.Answer = append(m.Answer, a)
w.WriteMsg(m)
return
}
log.Printf("No internal record found for %s", q.Name)
dns.HandleFailed(w, req)
}
log.Printf("Only handling type A requests, skipping")
dns.HandleFailed(w, req)
}
示例13: handleReverseDNSLookup
func (s *DNS) handleReverseDNSLookup(w dns.ResponseWriter, req *dns.Msg) {
q := req.Question[0]
if q.Qtype == dns.TypePTR && q.Qclass == dns.ClassINET {
if record, ok := s.cache.Get(q.Name); ok {
log.Printf("Found internal record for %s", q.Name)
m := new(dns.Msg)
m.SetReply(req)
rr_header := dns.RR_Header{
Name: q.Name,
Rrtype: dns.TypePTR,
Class: dns.ClassINET,
Ttl: 0,
}
a := &dns.PTR{rr_header, record.fqdn}
m.Answer = append(m.Answer, a)
w.WriteMsg(m)
return
}
log.Printf("Forwarding request to external recursor for: %s", q.Name)
// Forward the request
s.handleDNSExternal(w, req)
}
dns.HandleFailed(w, req)
}
示例14: getServerReply
// Forwards a DNS request to the specified nameservers. On success, the
// original reply packet will be returned to the caller. On failure, a
// new packet will be returned with `RCODE` set to `SERVFAIL`.
// Even though the original `ResponseWriter` object is taken as an argument,
// this function does not send a reply to the client. Instead, the
// packet is returned for further processing by the caller.
func getServerReply(w dns.ResponseWriter, req *dns.Msg) *dns.Msg {
if *verbose {
log.Print("Forwarding ", req.Question[0].Name, "/", dns.Type(req.Question[0].Qtype).String())
}
// create a new DNS client
client := &dns.Client{Net: "udp", ReadTimeout: 4 * time.Second, WriteTimeout: 4 * time.Second, SingleInflight: true}
if _, tcp := w.RemoteAddr().(*net.TCPAddr); tcp {
client.Net = "tcp"
}
var r *dns.Msg
var err error
// loop through the specified nameservers and forward them the request
// the request ID is used as a starting point in order to introduce at least
// some element of randomness, instead of always hitting the first nameserver
for i := 0; i < len(nameservers); i++ {
r, _, err = client.Exchange(req, nameservers[(int(req.Id)+i)%len(nameservers)])
if err == nil {
r.Compress = true
return r
}
}
log.Print("Failed to forward request.", err)
return getEmptyMsg(w, req, dns.RcodeServerFailure)
}
示例15: handleQuery
func (h *Handler) handleQuery(w dns.ResponseWriter, r *dns.Msg) {
q := r.Question[0]
m := &dns.Msg{}
m.SetReply(r)
switch q.Qtype {
case dns.TypePTR:
if q.Name == h.reverse {
rr := &dns.PTR{}
rr.Hdr = dns.RR_Header{Name: q.Name, Rrtype: dns.TypePTR, Class: dns.ClassINET, Ttl: 0}
rr.Ptr = h.name
m.Answer = append(m.Answer, rr)
}
case dns.TypeA:
if q.Name == h.name {
rr := &dns.A{}
rr.Hdr = dns.RR_Header{Name: q.Name, Rrtype: dns.TypeA, Class: dns.ClassINET, Ttl: 0}
rr.A = h.ip
m.Answer = append(m.Answer, rr)
}
}
w.WriteMsg(m)
}