// ServeDNS implements the middleware.Handler interface.
345671
func (pf *pfdns) ServeDNS(ctx context.Context, w dns.ResponseWriter, r *dns.Msg) (int, error) {

	pf.RefreshPfconfig(ctx)

	state := request.Request{W: w, Req: r}
	a := new(dns.Msg)
	a.SetReply(r)
	a.Compress = true
	a.Authoritative = true
	var rr dns.RR

	pffilter := filter_client.NewClient()

	var ipVersion int
	srcIP := state.IP()
	bIP := net.ParseIP(srcIP)
	if bIP.To4() == nil {
		ipVersion = 6
	} else {
		ipVersion = 4
	}

	mac, err := pf.Ip2Mac(ctx, srcIP, ipVersion)
	if err != nil {
		log.LoggerWContext(ctx).Error(fmt.Sprintf("ERROR cannot find mac for ip %s\n", srcIP))
		mac = "00:00:00:00:00:00"
	}

	var status = "unreg"
	var category string
	err = pf.Nodedb.QueryRow(mac, 1).Scan(&status, &category)
	if err != nil {
		log.LoggerWContext(ctx).Error(fmt.Sprintf("error getting node status %s %s\n", mac, err))
	}

	var PortalDetection bool
	PortalDetection = false
	if pf.checkDetectionMechanisms(ctx, state.QName()) {
		PortalDetection = true
		log.LoggerWContext(ctx).Debug("Portal Detection Mechanisms detected " + state.QName())
	}

	// Domain bypass
	for k, v := range pf.FqdnDomainPort {
		if k.MatchString(state.QName()) {
			answer, err := pf.LocalResolver(state)
			if err != nil {
				log.LoggerWContext(ctx).Error("Local resolver error for fqdn" + state.QName() + " with the following error" + err.Error())
			} else {
				for _, ans := range append(answer.Answer, answer.Extra...) {
					switch ansb := ans.(type) {
					case *dns.A:
						for _, valeur := range v {
							if err := pf.SetPassthrough(ctx, "passthrough", ansb.A.String(), valeur, true); err != nil {
								log.LoggerWContext(ctx).Error(fmt.Sprintf("Not able to contact localhost for setPassthrough %s", err))
							}
						}
					}
				}
				log.LoggerWContext(ctx).Debug(srcIP + " : " + mac + " Domain bypass for fqdn " + state.QName())
				w.WriteMsg(answer)
			}
			return 0, nil
		}
	}

	security_event := pf.HasSecurityEvents(ctx, mac)
	if security_event {
		// Passthrough bypass
		if !(PortalDetection) {

			for k, v := range pf.FqdnIsolationPort {
				if k.MatchString(state.QName()) {
					answer, err := pf.LocalResolver(state)
					if err != nil {
						log.LoggerWContext(ctx).Error("Local resolver error for fqdn" + state.QName() + " with the following error" + err.Error())
					} else {
						for _, ans := range append(answer.Answer, answer.Extra...) {
							switch ansb := ans.(type) {
							case *dns.A:
								for _, valeur := range v {
									if err := pf.SetPassthrough(ctx, "passthrough_isolation", ansb.A.String(), valeur, false); err != nil {
										log.LoggerWContext(ctx).Error(fmt.Sprintf("Not able to contact Unified API to adjust passthroughs: %s", err))
									}
								}
							}
						}
						log.LoggerWContext(ctx).Debug(srcIP + " : " + mac + " isolation passthrough  for fqdn " + state.QName())
						w.WriteMsg(answer)
					}
					return 0, nil
				}
			}
		}
	}
	// Passthrough bypass
	if !(PortalDetection) {
		for k, v := range pf.FqdnPort {
			if k.MatchString(state.QName()) {
				answer, err := pf.LocalResolver(state)
				if err != nil {
					log.LoggerWContext(ctx).Error("Local resolver error for fqdn" + state.QName() + " with the following error" + err.Error())
				} else {
					for _, ans := range append(answer.Answer, answer.Extra...) {
						switch ansb := ans.(type) {
						case *dns.A:
							for _, valeur := range v {
								if err := pf.SetPassthrough(ctx, "passthrough", ansb.A.String(), valeur, false); err != nil {
									log.LoggerWContext(ctx).Error(fmt.Sprintf("Not able to contact Unified API to adjust passthroughs %s", err))
								}
							}
						}

					}
					w.WriteMsg(answer)
					log.LoggerWContext(ctx).Debug(srcIP + " : " + mac + " passthrough for fqdn " + state.QName())
				}
				return 0, nil
			}
		}
	}

	// DNS Filter code
	var Type string

	for k, v := range pf.NetworkType {
		switch v {
		case "inlinel2":
			Type = "inline"

		case "inlinel3":
			Type = "inline"

		case "vlan-isolation":
			Type = "isolation"

		case "vlan-registration":
			Type = "registration"
		case "dns-enforcement":
			Type = "dnsenforcement"
		}

		if k.Contains(bIP) {
			// Register and inline or dns enforcement then resolv
			switch Type {
			case "dnsenforcement", "inline":
				var status = "unreg"

				err = pf.Nodedb.QueryRow(mac, 1).Scan(&status, &category)
				if err != nil {
					log.LoggerWContext(ctx).Error(fmt.Sprintf("error getting node status %s %s\n", mac, err))
				}
				// Defer to the proxy middleware if the device is registered
				if status == "reg" && !security_event && category != "REJECT" {
					log.LoggerWContext(ctx).Debug(srcIP + " : " + mac + " serve dns " + state.QName())
					return pf.Next.ServeDNS(ctx, w, r)
				} else if status == "reg" && category == "REJECT" {
					rr, _ = dns.NewRR("30 IN A 127.0.0.1")
					a.Answer = []dns.RR{rr}
					log.LoggerWContext(ctx).Debug("REJECT " + mac + " IP " + srcIP + " Query " + state.QName())
					state.SizeAndDo(a)
					w.WriteMsg(a)
					return 0, nil
				}
			}
			cacheKey := pf.MakeKeyCache(mac, category, security_event, state.QName())
			answer, found := pf.DNSFilter.Get(cacheKey)
			if found && answer != "null" {
				log.LoggerWContext(ctx).Debug("Get answer from the cache for " + state.QName())
				rr, _ = dns.NewRR(answer.(string))
			} else {
				info, err := pffilter.FilterDns(Type, map[string]interface{}{
					"qname":    state.QName(),
					"peerhost": state.RemoteAddr(),
					"qtype":    state.QType(),
					"mac":      mac,
				})
				if err != nil {
					pf.DNSFilter.Set(cacheKey, "null", cache.DefaultExpiration)
					break
				}
				var answer string
				for a, b := range info.(map[string]interface{}) {
					if a == "answer" {
						answer = b.(string)
						break
					}
				}
				log.LoggerWContext(ctx).Debug("Get answer from pffilter for " + state.QName())
				pf.DNSFilter.Set(cacheKey, answer, cache.DefaultExpiration)
				rr, _ = dns.NewRR(answer)
			}

			a.Answer = []dns.RR{rr}
			log.LoggerWContext(ctx).Debug("DNS Filter matched for MAC " + mac + " IP " + srcIP + " Query " + state.QName())
			state.SizeAndDo(a)
			w.WriteMsg(a)
			return 0, nil
		}
	}

	switch state.Family() {
	case 1:
		rr = new(dns.A)
		var found bool
		found = false
		for i := 0; i <= len(pf.PortalFQDN); i++ {
			if found {
				break
			}
			for c, d := range pf.PortalFQDN[i] {
				if c.Contains(bIP) {
					if d.MatchString(state.QName()) {
						rr.(*dns.A).Hdr = dns.RR_Header{Name: state.QName(), Rrtype: dns.TypeA, Class: state.QClass(), Ttl: 60}
					} else {
						rr.(*dns.A).Hdr = dns.RR_Header{Name: state.QName(), Rrtype: dns.TypeA, Class: state.QClass(), Ttl: 15}
					}
					found = true
					break
				}
			}
		}
		for k, v := range pf.Network {
			if k.Contains(bIP) {
				returnedIP := append([]byte(nil), v.To4()...)
				rr.(*dns.A).A = returnedIP
				break
			} else {
				rr.(*dns.A).A = pf.RedirectIP.To4()
			}
		}
	case 2:
		rr = new(dns.AAAA)
		var found bool
		found = false
		for i := 0; i <= len(pf.PortalFQDN); i++ {
			if found {
				break
			}
			for c, d := range pf.PortalFQDN[i] {
				if c.Contains(bIP) {
					if d.MatchString(state.QName()) {
						rr.(*dns.AAAA).Hdr = dns.RR_Header{Name: state.QName(), Rrtype: dns.TypeAAAA, Class: state.QClass(), Ttl: 60}
					} else {
						rr.(*dns.AAAA).Hdr = dns.RR_Header{Name: state.QName(), Rrtype: dns.TypeAAAA, Class: state.QClass(), Ttl: 15}
					}
					found = true
					break
				}
			}
		}
		for k, v := range pf.Network {
			if k.Contains(bIP) {
				returnedIP := append([]byte(nil), v.To16()...)
				rr.(*dns.AAAA).AAAA = returnedIP
				break
			} else {
				rr.(*dns.AAAA).AAAA = pf.RedirectIP.To16()
			}
		}
	}

	a.Answer = []dns.RR{rr}
	log.LoggerWContext(ctx).Debug("Returned portal for MAC " + mac + " with IP " + srcIP + "for fqdn " + state.QName())
	state.SizeAndDo(a)
	w.WriteMsg(a)

	return 0, nil
}
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
}
1327952
func (h Handler) ServeDNS(ctx context.Context, w dns.ResponseWriter, r *dns.Msg) (int, error) {
	state := request.Request{W: w, Req: r}

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

	for _, template := range h.Templates {
		data, match, fthrough := template.match(state, zone)
		if !match {
			if !fthrough {
				return dns.RcodeNameError, nil
			}
			continue
		}

		templateMatchesCount.WithLabelValues(metrics.WithServer(ctx), data.Zone, data.Class, data.Type).Inc()

		if template.rcode == dns.RcodeServerFailure {
			return template.rcode, nil
		}

		msg := new(dns.Msg)
		msg.SetReply(r)
		msg.Authoritative = true
		msg.Rcode = template.rcode

		for _, answer := range template.answer {
			rr, err := executeRRTemplate(metrics.WithServer(ctx), "answer", answer, data)
			if err != nil {
				return dns.RcodeServerFailure, err
			}
			msg.Answer = append(msg.Answer, rr)
			if template.upstream != nil && (state.QType() == dns.TypeA || state.QType() == dns.TypeAAAA) && rr.Header().Rrtype == dns.TypeCNAME {
				up, _ := template.upstream.Lookup(ctx, state, rr.(*dns.CNAME).Target, state.QType())
				msg.Answer = append(msg.Answer, up.Answer...)
			}
		}
		for _, additional := range template.additional {
			rr, err := executeRRTemplate(metrics.WithServer(ctx), "additional", additional, data)
			if err != nil {
				return dns.RcodeServerFailure, err
			}
			msg.Extra = append(msg.Extra, rr)
		}
		for _, authority := range template.authority {
			rr, err := executeRRTemplate(metrics.WithServer(ctx), "authority", authority, data)
			if err != nil {
				return dns.RcodeServerFailure, err
			}
			msg.Ns = append(msg.Ns, rr)
		}

		w.WriteMsg(msg)
		return template.rcode, nil
	}

	return h.Next.ServeDNS(ctx, w, r)
}
972184
func (r *Router) ServeFiles(path string, root http.FileSystem) {
	r.Router.ServeFiles(path, root)
}
1144186
func (s *middlewareLister) Middlewares(namespace string) MiddlewareNamespaceLister {
	return middlewareNamespaceLister{indexer: s.indexer, namespace: namespace}
}
719507
func (f AnnotationsHandlerFunc) ServeAnnotations(ctx context.Context, res AnnotationsResponse, req *AnnotationsRequest) error {
	return f(ctx, res, req)
}
1167185
func (mw MiddlewareFunc) Middleware(handler http.Handler) http.Handler {
	return mw(handler)
}
878973
func (c Chaos) ServeDNS(ctx context.Context, w dns.ResponseWriter, r *dns.Msg) (int, error) {
	state := request.Request{W: w, Req: r}
	if state.QClass() != dns.ClassCHAOS || state.QType() != dns.TypeTXT {
		return plugin.NextOrFailure(c.Name(), c.Next, ctx, w, r)
	}

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

	hdr := dns.RR_Header{Name: state.QName(), Rrtype: dns.TypeTXT, Class: dns.ClassCHAOS, Ttl: 0}
	switch state.Name() {
	default:
		return c.Next.ServeDNS(ctx, w, r)
	case "authors.bind.":
		for a := range c.Authors {
			m.Answer = append(m.Answer, &dns.TXT{Hdr: hdr, Txt: []string{trim(a)}})
		}
	case "version.bind.", "version.server.":
		m.Answer = []dns.RR{&dns.TXT{Hdr: hdr, Txt: []string{trim(c.Version)}}}
	case "hostname.bind.", "id.server.":
		hostname, err := os.Hostname()
		if err != nil {
			hostname = "localhost"
		}
		m.Answer = []dns.RR{&dns.TXT{Hdr: hdr, Txt: []string{trim(hostname)}}}
	}
	state.SizeAndDo(m)
	w.WriteMsg(m)
	return 0, nil
}
456924
func (s *handler) ServeDNS(w dns.ResponseWriter, r *dns.Msg) {
	m := new(dns.Msg)
	m.SetReply(r)
	m.Compress = false

	fakeDNS := os.Getenv("DOCKER_HOST_IP")
	if fakeDNS == "" {
		fakeDNS = "127.0.0.1"
	}
	for _, q := range r.Question {
		log.Infof("Query -- [%s] %s", q.Name, dns.TypeToString[q.Qtype])

		switch q.Qtype {
		case dns.TypeA:
			record := new(dns.A)
			record.Hdr = dns.RR_Header{
				Name:   q.Name,
				Rrtype: dns.TypeA,
				Class:  dns.ClassINET,
				Ttl:    0,
			}
			record.A = net.ParseIP(fakeDNS)

			m.Answer = append(m.Answer, record)
		case dns.TypeCAA:
			addCAARecord := true

			var value string
			switch q.Name {
			case "bad-caa-reserved.com.":
				value = "sad-hacker-ca.invalid"
			case "good-caa-reserved.com.":
				value = "happy-hacker-ca.invalid"
			case "accounturi.good-caa-reserved.com.":
				uri := os.Getenv("ACCOUNT_URI")
				value = fmt.Sprintf("happy-hacker-ca.invalid; accounturi=%s", uri)
			case "recheck.good-caa-reserved.com.":
				// Allow issuance when we're running in the past
				// (under FAKECLOCK), otherwise deny issuance.
				if os.Getenv("FAKECLOCK") != "" {
					value = "happy-hacker-ca.invalid"
				} else {
					value = "sad-hacker-ca.invalid"
				}
			case "dns-01-only.good-caa-reserved.com.":
				value = "happy-hacker-ca.invalid; validationmethods=dns-01"
			case "http-01-only.good-caa-reserved.com.":
				value = "happy-hacker-ca.invalid; validationmethods=http-01"
			case "dns-01-or-http-01.good-caa-reserved.com.":
				value = "happy-hacker-ca.invalid; validationmethods=dns-01,http-01"
			default:
				addCAARecord = false
			}
			if addCAARecord {
				record := new(dns.CAA)
				record.Hdr = dns.RR_Header{
					Name:   q.Name,
					Rrtype: dns.TypeCAA,
					Class:  dns.ClassINET,
					Ttl:    0,
				}
				record.Tag = "issue"
				record.Value = value
				m.Answer = append(m.Answer, record)
			}
		}
	}

	auth := new(dns.SOA)
	auth.Hdr = dns.RR_Header{Name: "boulder.invalid.", Rrtype: dns.TypeSOA, Class: dns.ClassINET, Ttl: 0}
	auth.Ns = "ns.boulder.invalid."
	auth.Mbox = "master.boulder.invalid."
	auth.Serial = 1
	auth.Refresh = 1
	auth.Retry = 1
	auth.Expire = 1
	auth.Minttl = 1
	m.Ns = append(m.Ns, auth)

	if err := w.WriteMsg(m); err != nil {
		log.Fatalf("Failed to write message %v", err)
	}
}
728084
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)

		if rc > 0 {
			// There was an error up the chain, but no response has been written yet.
			// The error must be handled here so the log entry will record the response size.
			if l.ErrorFunc != nil {
				l.ErrorFunc(rrw, r, rc)
			} else {
				answer := new(dns.Msg)
				answer.SetRcode(r, rc)
				state.SizeAndDo(answer)

				vars.Report(state, vars.Dropped, rcode.ToString(rc), answer.Len(), time.Now())

				w.WriteMsg(answer)
			}
			rc = 0
		}

		tpe, _ := response.Typify(rrw.Msg, time.Now().UTC())
		class := response.Classify(tpe)
		if rule.Class == response.All || rule.Class == class {
			rep := replacer.New(r, rrw, CommonLogEmptyValue)
			rule.Log.Println(rep.Replace(rule.Format))
		}

		return rc, err

	}
	return plugin.NextOrFailure(l.Name(), l.Next, ctx, w, r)
}
1110009
func (h Dnstap) ServeDNS(ctx context.Context, w dns.ResponseWriter, r *dns.Msg) (int, error) {

	// Add send option into context so other plugin can decide on which DNSTap
	// message to be sent out
	sendOption := taprw.SendOption{Cq: true, Cr: true}
	newCtx := context.WithValue(ctx, DnstapSendOption, &sendOption)
	newCtx = ContextWithTapper(newCtx, h)

	rw := &taprw.ResponseWriter{
		ResponseWriter: w,
		Tapper:         &h,
		Query:          r,
		Send:           &sendOption,
		QueryEpoch:     time.Now(),
	}

	code, err := plugin.NextOrFailure(h.Name(), h.Next, newCtx, rw, r)
	if err != nil {
		// ignore dnstap errors
		return code, err
	}

	if err = rw.DnstapError(); err != nil {
		return code, plugin.Error("dnstap", err)
	}

	return code, nil
}
684052
func (m *ServeMux) Middleware(f MiddlewareFunc) {
	m.middlewares = append(m.middlewares, f)
}
250227
func (nc *Conn) Servers() []string {
	nc.mu.RLock()
	defer nc.mu.RUnlock()
	return nc.getServers(false)
}
635013
func (h *Handler) serveDeleteInstance(w http.ResponseWriter, r *http.Request, params httprouter.Params) {
	// Retrieve path parameters.
	service := params.ByName("service")
	instanceID := params.ByName("instance_id")

	// Remove instance from the store.
	if err := h.Store.RemoveInstance(service, instanceID); err == ErrNotLeader {
		h.redirectToLeader(w, r)
		return
	} else if IsNotFound(err) {
		hh.ObjectNotFoundError(w, err.Error())
		return
	} else if err != nil {
		hh.Error(w, err)
		return
	}
}
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)
}
503382
func Serve(l net.Listener, h Handler, appname, hostname string) (err error) {
  serv := Server{
    Appname: appname,
    Hostname: hostname,
    Handler: h,
  }
  return serv.Serve(l)
}
808273
func (m MiddlewareFunc) ServeNext(next http.Handler) http.Handler {
	return m(next)
}