// ServeDNS implements the plugin.Handle interface.
552682
func (t *trace) ServeDNS(ctx context.Context, w dns.ResponseWriter, r *dns.Msg) (int, error) {
	trace := false
	if t.every > 0 {
		queryNr := atomic.AddUint64(&t.count, 1)

		if queryNr%t.every == 0 {
			trace = true
		}
	}
	if span := ot.SpanFromContext(ctx); span == nil && trace {
		span := t.Tracer().StartSpan("servedns")
		defer span.Finish()
		ctx = ot.ContextWithSpan(ctx, span)
	}
	return plugin.NextOrFailure(t.Name(), t.Next, ctx, w, r)
}
1332346
func (middlewares Middlewares) ServeNext(next http.Handler) http.Handler {
	return middlewares.BuildHandler(next)
}
195308
func (s *Server) ServeDNS(ctx context.Context, w dns.ResponseWriter, r *dns.Msg) {
	// The default dns.Mux checks the question section size, but we have our
	// own mux here. Check if we have a question section. If not drop them here.
	if r == nil || len(r.Question) == 0 {
		errorAndMetricsFunc(s.Addr, w, r, dns.RcodeServerFailure)
		return
	}

	if !s.debug {
		defer func() {
			// In case the user doesn't enable error plugin, we still
			// need to make sure that we stay alive up here
			if rec := recover(); rec != nil {
				vars.Panic.Inc()
				errorAndMetricsFunc(s.Addr, w, r, dns.RcodeServerFailure)
			}
		}()
	}

	if !s.classChaos && r.Question[0].Qclass != dns.ClassINET {
		errorAndMetricsFunc(s.Addr, w, r, dns.RcodeRefused)
		return
	}

	if m, err := edns.Version(r); err != nil { // Wrong EDNS version, return at once.
		w.WriteMsg(m)
		return
	}

	q := r.Question[0].Name
	b := make([]byte, len(q))
	var off int
	var end bool

	var dshandler *Config

	// Wrap the response writer in a ScrubWriter so we automatically make the reply fit in the client's buffer.
	w = request.NewScrubWriter(r, w)

	for {
		l := len(q[off:])
		for i := 0; i < l; i++ {
			b[i] = q[off+i]
			// normalize the name for the lookup
			if b[i] >= 'A' && b[i] <= 'Z' {
				b[i] |= ('a' - 'A')
			}
		}

		if h, ok := s.zones[string(b[:l])]; ok {
			if r.Question[0].Qtype != dns.TypeDS {
				if h.FilterFunc == nil {
					rcode, _ := h.pluginChain.ServeDNS(ctx, w, r)
					if !plugin.ClientWrite(rcode) {
						errorFunc(s.Addr, w, r, rcode)
					}
					return
				}
				// FilterFunc is set, call it to see if we should use this handler.
				// This is given to full query name.
				if h.FilterFunc(q) {
					rcode, _ := h.pluginChain.ServeDNS(ctx, w, r)
					if !plugin.ClientWrite(rcode) {
						errorFunc(s.Addr, w, r, rcode)
					}
					return
				}
			}
			// The type is DS, keep the handler, but keep on searching as maybe we are serving
			// the parent as well and the DS should be routed to it - this will probably *misroute* DS
			// queries to a possibly grand parent, but there is no way for us to know at this point
			// if there is an actually delegation from grandparent -> parent -> zone.
			// In all fairness: direct DS queries should not be needed.
			dshandler = h
		}
		off, end = dns.NextLabel(q, off)
		if end {
			break
		}
	}

	if r.Question[0].Qtype == dns.TypeDS && dshandler != nil && dshandler.pluginChain != nil {
		// DS request, and we found a zone, use the handler for the query.
		rcode, _ := dshandler.pluginChain.ServeDNS(ctx, w, r)
		if !plugin.ClientWrite(rcode) {
			errorFunc(s.Addr, w, r, rcode)
		}
		return
	}

	// Wildcard match, if we have found nothing try the root zone as a last resort.
	if h, ok := s.zones["."]; ok && h.pluginChain != nil {
		rcode, _ := h.pluginChain.ServeDNS(ctx, w, r)
		if !plugin.ClientWrite(rcode) {
			errorFunc(s.Addr, w, r, rcode)
		}
		return
	}

	// Still here? Error out with REFUSED.
	errorAndMetricsFunc(s.Addr, w, r, dns.RcodeRefused)
}
59457
func (l Logger) ServeDNS(ctx context.Context, w dns.ResponseWriter, r *dns.Msg) (int, error) {
	state := request.Request{W: w, Req: r}
	for _, rule := range l.Rules {
		if !plugin.Name(rule.NameScope).Matches(state.Name()) {
			continue
		}

		rrw := dnstest.NewRecorder(w)
		rc, err := plugin.NextOrFailure(l.Name(), l.Next, ctx, rrw, r)

		tpe, _ := response.Typify(rrw.Msg, time.Now().UTC())
		class := response.Classify(tpe)
		// If we don't set up a class in config, the default "all" will be added
		// and we shouldn't have an empty rule.Class.
		_, ok := rule.Class[response.All]
		_, ok1 := rule.Class[class]
		if ok || ok1 {
			logstr := l.repl.Replace(ctx, state, rrw, rule.Format)
			clog.Infof(logstr)
		}

		return rc, err

	}
	return plugin.NextOrFailure(l.Name(), l.Next, ctx, w, r)
}
719507
func (f AnnotationsHandlerFunc) ServeAnnotations(ctx context.Context, res AnnotationsResponse, req *AnnotationsRequest) error {
	return f(ctx, res, req)
}
515285
func (c *ServicedCli) hosts() (data []string) {
	hosts, err := c.driver.GetHosts()
	if err != nil || hosts == nil || len(hosts) == 0 {
		return
	}

	data = make([]string, len(hosts))
	for i, h := range hosts {
		data[i] = h.ID
	}

	return
}
363114
func (rw Rewrite) ServeDNS(ctx context.Context, w dns.ResponseWriter, r *dns.Msg) (int, error) {
	wr := NewResponseReverter(w, r)
	for _, rule := range rw.Rules {
		switch result := rule.Rewrite(w, r); result {
		case RewriteDone:
			if rule.Mode() == Stop {
				if rw.noRevert {
					return plugin.NextOrFailure(rw.Name(), rw.Next, ctx, w, r)
				}
				return plugin.NextOrFailure(rw.Name(), rw.Next, ctx, wr, r)
			}
		case RewriteIgnored:
			break
		case RewriteStatus:
			// only valid for complex rules.
			// if cRule, ok := rule.(*ComplexRule); ok && cRule.Status != 0 {
			// return cRule.Status, nil
			// }
		}
	}
	return plugin.NextOrFailure(rw.Name(), rw.Next, ctx, w, r)
}
209926
func (e *External) ServeDNS(ctx context.Context, w dns.ResponseWriter, r *dns.Msg) (int, error) {
	state := request.Request{W: w, Req: r}

	zone := plugin.Zones(e.Zones).Matches(state.Name())
	if zone == "" {
		return plugin.NextOrFailure(e.Name(), e.Next, ctx, w, r)
	}

	if e.externalFunc == nil {
		return plugin.NextOrFailure(e.Name(), e.Next, ctx, w, r)
	}

	state.Zone = zone
	for _, z := range e.Zones {
		// TODO(miek): save this in the External struct.
		if state.Name() == z { // apex query
			ret, err := e.serveApex(state)
			return ret, err
		}
		if dns.IsSubDomain(e.apex+"."+z, state.Name()) {
			// dns subdomain test for ns. and dns. queries
			ret, err := e.serveSubApex(state)
			return ret, err
		}
	}

	svc, rcode := e.externalFunc(state)

	m := new(dns.Msg)
	m.SetReply(state.Req)

	if len(svc) == 0 {
		m.Rcode = rcode
		m.Ns = []dns.RR{e.soa(state)}
		w.WriteMsg(m)
		return 0, nil
	}

	switch state.QType() {
	case dns.TypeA:
		m.Answer = e.a(svc, state)
	case dns.TypeAAAA:
		m.Answer = e.aaaa(svc, state)
	case dns.TypeSRV:
		m.Answer, m.Extra = e.srv(svc, state)
	default:
		m.Ns = []dns.RR{e.soa(state)}
	}

	// If we did have records, but queried for the wrong qtype return a nodata response.
	if len(m.Answer) == 0 {
		m.Ns = []dns.RR{e.soa(state)}
	}

	w.WriteMsg(m)
	return 0, nil
}
67409
func (re Reverse) ServeDNS(ctx context.Context, w dns.ResponseWriter, r *dns.Msg) (int, error) {
	var rr dns.RR

	state := request.Request{W: w, Req: r}
	m := new(dns.Msg)
	m.SetReply(r)
	m.Authoritative, m.RecursionAvailable, m.Compress = true, true, true

	switch state.QType() {
	case dns.TypePTR:
		address := dnsutil.ExtractAddressFromReverse(state.Name())

		if address == "" {
			// Not an reverse lookup, but can still be an pointer for an domain
			break
		}

		ip := net.ParseIP(address)
		// loop through the configured networks
		for _, n := range re.Networks {
			if n.IPnet.Contains(ip) {
				rr = &dns.PTR{
					Hdr: dns.RR_Header{Name: state.QName(), Rrtype: dns.TypePTR, Class: dns.ClassINET, Ttl: n.TTL},
					Ptr: n.ipToHostname(ip),
				}
				break
			}
		}

	case dns.TypeA:
		for _, n := range re.Networks {
			if dns.IsSubDomain(n.Zone, state.Name()) {

				// skip if requesting an v4 address and network is not v4
				if n.IPnet.IP.To4() == nil {
					continue
				}

				result := n.hostnameToIP(state.Name())
				if result != nil {
					rr = &dns.A{
						Hdr: dns.RR_Header{Name: state.QName(), Rrtype: dns.TypeA, Class: dns.ClassINET, Ttl: n.TTL},
						A:   result,
					}
					break
				}
			}
		}

	case dns.TypeAAAA:
		for _, n := range re.Networks {
			if dns.IsSubDomain(n.Zone, state.Name()) {

				// Do not use To16 which tries to make v4 in v6
				if n.IPnet.IP.To4() != nil {
					continue
				}

				result := n.hostnameToIP(state.Name())
				if result != nil {
					rr = &dns.AAAA{
						Hdr:  dns.RR_Header{Name: state.QName(), Rrtype: dns.TypeAAAA, Class: dns.ClassINET, Ttl: n.TTL},
						AAAA: result,
					}
					break
				}
			}
		}

	}

	if rr != nil {
		m.Answer = append(m.Answer, rr)
		state.SizeAndDo(m)
		w.WriteMsg(m)
		return dns.RcodeSuccess, nil
	}

	if re.Fallthrough {
		return plugin.NextOrFailure(re.Name(), re.Next, ctx, w, r)
	}
	return dns.RcodeServerFailure, nil
}
340337
func (f *Federation) ServeDNS(ctx context.Context, w dns.ResponseWriter, r *dns.Msg) (int, error) {
	if f.Federations == nil {
		return plugin.NextOrFailure(f.Name(), f.Next, ctx, w, r)
	}

	state := request.Request{W: w, Req: r}

	zone := plugin.Zones(f.zones).Matches(state.Name())
	if zone == "" {
		return plugin.NextOrFailure(f.Name(), f.Next, ctx, w, r)
	}

	state.Zone = zone

	// Remove the federation label from the qname to see if something exists.
	without, label := f.isNameFederation(state.Name(), state.Zone)
	if without == "" {
		return plugin.NextOrFailure(f.Name(), f.Next, ctx, w, r)
	}

	qname := r.Question[0].Name
	r.Question[0].Name = without
	state.Clear()

	// Start the next plugin, but with a nowriter, capture the result, if NXDOMAIN
	// perform federation, otherwise just write the result.
	nw := nonwriter.New(w)
	ret, err := plugin.NextOrFailure(f.Name(), f.Next, ctx, nw, r)

	if !plugin.ClientWrite(ret) {
		// something went wrong
		r.Question[0].Name = qname
		return ret, err
	}

	if m := nw.Msg; m.Rcode != dns.RcodeNameError {
		// If positive answer we need to substitute the original qname in the answer.
		m.Question[0].Name = qname
		for _, a := range m.Answer {
			a.Header().Name = qname
		}

		w.WriteMsg(m)

		return dns.RcodeSuccess, nil
	}

	// Still here, we've seen NXDOMAIN and need to perform federation.
	service, err := f.Federations(state, label, f.f[label]) // state references Req which has updated qname
	if err != nil {
		r.Question[0].Name = qname
		return dns.RcodeServerFailure, err
	}

	r.Question[0].Name = qname

	m := new(dns.Msg)
	m.SetReply(r)
	m.Authoritative = true

	m.Answer = []dns.RR{service.NewCNAME(state.QName(), service.Host)}

	if f.Upstream != nil {
		aRecord, err := f.Upstream.Lookup(ctx, state, service.Host, state.QType())
		if err == nil && aRecord != nil && len(aRecord.Answer) > 0 {
			m.Answer = append(m.Answer, aRecord.Answer...)
		}
	}

	w.WriteMsg(m)
	return dns.RcodeSuccess, nil
}
1143215
func (f HandlerFunc) ServeHTTP(ctx context.Context, w http.ResponseWriter, r *http.Request) {
	f(ctx, w, r)
}
1104890
func (kl *Kubelet) ServeLogs(w http.ResponseWriter, req *http.Request) {
	// TODO: whitelist logs we are willing to serve
	kl.logServer.ServeHTTP(w, req)
}
245647
func (f QueryHandlerFunc) ServeQuery(ctx context.Context, res QueryResponse, req *QueryRequest) error {
	return f(ctx, res, req)
}
67607
func (h *HandlerFunc) ServeHTTP(w http.ResponseWriter, req *http.Request) {
	ip, err := HTTPRequestLookup(req)
	if err != nil {
		log.Printf("failed to lookup request address: %v", err)
		status := http.StatusInternalServerError
		http.Error(w, http.StatusText(status), status)
		return
	}

	if h.whitelist.Permitted(ip) {
		h.allow(w, req)
	} else {
		if h.deny == nil {
			status := http.StatusUnauthorized
			http.Error(w, http.StatusText(status), status)
		} else {
			h.deny(w, req)
		}
	}
}
283591
func (c *Cache) ServeDNS(ctx context.Context, w dns.ResponseWriter, r *dns.Msg) (int, error) {
	state := request.Request{W: w, Req: r}

	qname := state.Name()
	qtype := state.QType()
	zone := plugin.Zones(c.Zones).Matches(qname)
	if zone == "" {
		return plugin.NextOrFailure(c.Name(), c.Next, ctx, w, r)
	}

	do := state.Do() // TODO(): might need more from OPT record? Like the actual bufsize?

	now := time.Now().UTC()

	i, ttl := c.get(now, qname, qtype, do)
	if i != nil && ttl > 0 {
		resp := i.toMsg(r)

		state.SizeAndDo(resp)
		resp, _ = state.Scrub(resp)
		w.WriteMsg(resp)

		if c.prefetch > 0 {
			i.Freq.Update(c.duration, now)
		}

		pct := 100
		if i.origTTL != 0 { // you'll never know
			pct = int(float64(ttl) / float64(i.origTTL) * 100)
		}

		if c.prefetch > 0 && i.Freq.Hits() > c.prefetch && pct < c.percentage {
			// When prefetching we loose the item i, and with it the frequency
			// that we've gathered sofar. See we copy the frequencies info back
			// into the new item that was stored in the cache.
			prr := &ResponseWriter{ResponseWriter: w, Cache: c, prefetch: true}
			plugin.NextOrFailure(c.Name(), c.Next, ctx, prr, r)

			if i1, _ := c.get(now, qname, qtype, do); i1 != nil {
				i1.Freq.Reset(now, i.Freq.Hits())
			}
		}

		return dns.RcodeSuccess, nil
	}

	crr := &ResponseWriter{ResponseWriter: w, Cache: c}
	return plugin.NextOrFailure(c.Name(), c.Next, ctx, crr, r)
}
759748
func (f WriteHandlerFunc) ServeWrite(r Request, data []byte) byte {
	return f(r, data)
}
180376
func (e *Erratic) ServeDNS(ctx context.Context, w dns.ResponseWriter, r *dns.Msg) (int, error) {
	state := request.Request{W: w, Req: r}
	drop := false
	delay := false
	trunc := false

	queryNr := atomic.LoadUint64(&e.q)
	atomic.AddUint64(&e.q, 1)

	if e.drop > 0 && queryNr%e.drop == 0 {
		drop = true
	}
	if e.delay > 0 && queryNr%e.delay == 0 {
		delay = true
	}
	if e.truncate > 0 && queryNr&e.truncate == 0 {
		trunc = true
	}

	m := new(dns.Msg)
	m.SetReply(r)
	m.Authoritative = true
	if trunc {
		m.Truncated = true
	}

	// small dance to copy rrA or rrAAAA into a non-pointer var that allows us to overwrite the ownername
	// in a non-racy way.
	switch state.QType() {
	case dns.TypeA:
		rr := *(rrA.(*dns.A))
		rr.Header().Name = state.QName()
		m.Answer = append(m.Answer, &rr)
		if e.large {
			for i := 0; i < 29; i++ {
				m.Answer = append(m.Answer, &rr)
			}
		}
	case dns.TypeAAAA:
		rr := *(rrAAAA.(*dns.AAAA))
		rr.Header().Name = state.QName()
		m.Answer = append(m.Answer, &rr)
	case dns.TypeAXFR:
		if drop {
			return 0, nil
		}
		if delay {
			time.Sleep(e.duration)
		}

		xfr(state, trunc)
		return 0, nil

	default:
		if drop {
			return 0, nil
		}
		if delay {
			time.Sleep(e.duration)
		}
		// coredns will return error.
		return dns.RcodeServerFailure, nil
	}

	if drop {
		return 0, nil
	}

	if delay {
		time.Sleep(e.duration)
	}

	w.WriteMsg(m)

	return 0, nil
}