// ServeDNS implements the plugin.Handler.ServeDNS.
771429
func (h *Route53) ServeDNS(ctx context.Context, w dns.ResponseWriter, r *dns.Msg) (int, error) {
	state := request.Request{W: w, Req: r}
	qname := state.Name()

	zName := plugin.Zones(h.zoneNames).Matches(qname)
	if zName == "" {
		return plugin.NextOrFailure(h.Name(), h.Next, ctx, w, r)
	}
	z, ok := h.zones[zName]
	if !ok || z == nil {
		return dns.RcodeServerFailure, nil
	}

	m := new(dns.Msg)
	m.SetReply(r)
	m.Authoritative = true
	var result file.Result
	for _, hostedZone := range z {
		h.zMu.RLock()
		m.Answer, m.Ns, m.Extra, result = hostedZone.z.Lookup(ctx, state, qname)
		h.zMu.RUnlock()

		// Take the answer if it's non-empty OR if there is another
		// record type exists for this name (NODATA).
		if len(m.Answer) != 0 || result == file.NoData {
			break
		}
	}

	if len(m.Answer) == 0 && result != file.NoData && h.Fall.Through(qname) {
		return plugin.NextOrFailure(h.Name(), h.Next, ctx, w, r)
	}

	switch result {
	case file.Success:
	case file.NoData:
	case file.NameError:
		m.Rcode = dns.RcodeNameError
	case file.Delegation:
		m.Authoritative = false
	case file.ServerFailure:
		return dns.RcodeServerFailure, nil
	}

	w.WriteMsg(m)
	return dns.RcodeSuccess, nil
}
561394
func (client *Client) SetBackendServers(loadBalancerId string, backendServers []BackendServerType) (result []BackendServerType, err error) {
	bytes, _ := json.Marshal(backendServers)

	args := &SetBackendServersArgs{
		LoadBalancerId: loadBalancerId,
		BackendServers: string(bytes),
	}
	response := &SetBackendServersResponse{}

	err = client.Invoke("SetBackendServers", args, response)
	if err != nil {
		return nil, err
	}
	return response.BackendServers.BackendServer, err
}
527943
func hostedZoneNameServers(id string, conn *route53.Route53) ([]string, error) {
	req := &route53.GetHostedZoneInput{}
	req.Id = aws.String(id)

	resp, err := conn.GetHostedZone(req)
	if err != nil {
		return []string{}, err
	}

	if resp.DelegationSet == nil {
		return []string{}, nil
	}

	servers := []string{}
	for _, server := range resp.DelegationSet.NameServers {
		if server != nil {
			servers = append(servers, *server)
		}
	}
	return servers, nil
}
566730
func ServeJS(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Content-Type", "application/javascript")
	w.Write(liveReloadJS())
}
796959
func (l *Loop) ServeDNS(ctx context.Context, w dns.ResponseWriter, r *dns.Msg) (int, error) {
	if r.Question[0].Qtype != dns.TypeHINFO {
		return plugin.NextOrFailure(l.Name(), l.Next, ctx, w, r)
	}
	if l.disabled() {
		return plugin.NextOrFailure(l.Name(), l.Next, ctx, w, r)
	}

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

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

	if state.Name() == l.qname {
		l.inc()
	}

	if l.seen() > 2 {
		log.Fatalf(`Loop (%s -> %s) detected for zone %q, see https://coredns.io/plugins/loop#troubleshooting. Query: "HINFO %s"`, state.RemoteAddr(), l.address(), l.zone, l.qname)
	}

	return plugin.NextOrFailure(l.Name(), l.Next, ctx, w, r)
}
554257
func (client *Client) AddBackendServers(loadBalancerId string, backendServers []BackendServerType) (result []BackendServerType, err error) {

	bytes, _ := json.Marshal(backendServers)

	args := &AddBackendServersArgs{
		LoadBalancerId: loadBalancerId,
		BackendServers: string(bytes),
	}
	response := &AddBackendServersResponse{}

	err = client.Invoke("AddBackendServers", args, response)
	if err != nil {
		return nil, err
	}
	return response.BackendServers.BackendServer, err
}
874365
func (r *Router) ServeFiles(base string, root http.FileSystem) {
	if strings.ContainsAny(base, ":*") {
		panic("Lion: ServeFiles cannot have url parameters")
	}

	pattern := path.Join(base, "/*")
	fileServer := http.StripPrefix(base, http.FileServer(root))

	r.Get(pattern, fileServer)
	r.Head(pattern, fileServer)
}
561977
func (ctxt *Context) ServeJSON(data interface{}) {
	encoded, err := json.Marshal(data)
	if err != nil {
		panic(err)
	}
	ctxt.Header().Set("Content-Type", "application/json")
	ctxt.Write(encoded)
}
794621
func (a *AutoPath) ServeDNS(ctx context.Context, w dns.ResponseWriter, r *dns.Msg) (int, error) {
	state := request.Request{W: w, Req: r}

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

	// Check if autopath should be done, searchFunc takes precedence over the local configured search path.
	var err error
	searchpath := a.search

	if a.searchFunc != nil {
		searchpath = a.searchFunc(state)
	}

	if len(searchpath) == 0 {
		return plugin.NextOrFailure(a.Name(), a.Next, ctx, w, r)
	}

	if !firstInSearchPath(state.Name(), searchpath) {
		return plugin.NextOrFailure(a.Name(), a.Next, ctx, w, r)
	}

	origQName := state.QName()

	// Establish base name of the query. I.e what was originally asked.
	base, err := dnsutil.TrimZone(state.QName(), searchpath[0])
	if err != nil {
		return dns.RcodeServerFailure, err
	}

	firstReply := new(dns.Msg)
	firstRcode := 0
	var firstErr error

	ar := r.Copy()
	// Walk the search path and see if we can get a non-nxdomain - if they all fail we return the first
	// query we've done and return that as-is. This means the client will do the search path walk again...
	for i, s := range searchpath {
		newQName := base + "." + s
		ar.Question[0].Name = newQName
		nw := nonwriter.New(w)

		rcode, err := plugin.NextOrFailure(a.Name(), a.Next, ctx, nw, ar)
		if err != nil {
			// Return now - not sure if this is the best. We should also check if the write has happened.
			return rcode, err
		}
		if i == 0 {
			firstReply = nw.Msg
			firstRcode = rcode
			firstErr = err
		}

		if !plugin.ClientWrite(rcode) {
			continue
		}

		if nw.Msg.Rcode == dns.RcodeNameError {
			continue
		}

		msg := nw.Msg
		cnamer(msg, origQName)

		// Write whatever non-nxdomain answer we've found.
		w.WriteMsg(msg)
		autoPathCount.WithLabelValues(metrics.WithServer(ctx)).Add(1)
		return rcode, err

	}
	if plugin.ClientWrite(firstRcode) {
		w.WriteMsg(firstReply)
	}
	return firstRcode, firstErr
}
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)
}
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
}
1169148
func (k Kubernetes) ServeDNS(ctx context.Context, w dns.ResponseWriter, r *dns.Msg) (int, error) {
	state := request.Request{W: w, Req: r}

	qname := state.QName()
	zone := plugin.Zones(k.Zones).Matches(qname)
	if zone == "" {
		return plugin.NextOrFailure(k.Name(), k.Next, ctx, w, r)
	}
	zone = qname[len(qname)-len(zone):] // maintain case of original query
	state.Zone = zone

	var (
		records []dns.RR
		extra   []dns.RR
		err     error
	)

	switch state.QType() {
	case dns.TypeA:
		records, err = plugin.A(ctx, &k, zone, state, nil, plugin.Options{})
	case dns.TypeAAAA:
		records, err = plugin.AAAA(ctx, &k, zone, state, nil, plugin.Options{})
	case dns.TypeTXT:
		records, err = plugin.TXT(ctx, &k, zone, state, plugin.Options{})
	case dns.TypeCNAME:
		records, err = plugin.CNAME(ctx, &k, zone, state, plugin.Options{})
	case dns.TypePTR:
		records, err = plugin.PTR(ctx, &k, zone, state, plugin.Options{})
	case dns.TypeMX:
		records, extra, err = plugin.MX(ctx, &k, zone, state, plugin.Options{})
	case dns.TypeSRV:
		records, extra, err = plugin.SRV(ctx, &k, zone, state, plugin.Options{})
	case dns.TypeSOA:
		records, err = plugin.SOA(ctx, &k, zone, state, plugin.Options{})
	case dns.TypeNS:
		if state.Name() == zone {
			records, extra, err = plugin.NS(ctx, &k, zone, state, plugin.Options{})
			break
		}
		fallthrough
	case dns.TypeAXFR, dns.TypeIXFR:
		k.Transfer(ctx, state)
	default:
		// Do a fake A lookup, so we can distinguish between NODATA and NXDOMAIN
		_, err = plugin.A(ctx, &k, zone, state, nil, plugin.Options{})
	}

	if k.IsNameError(err) {
		if k.Fall.Through(state.Name()) {
			return plugin.NextOrFailure(k.Name(), k.Next, ctx, w, r)
		}
		if !k.APIConn.HasSynced() {
			// If we haven't synchronized with the kubernetes cluster, return server failure
			return plugin.BackendError(ctx, &k, zone, dns.RcodeServerFailure, state, nil /* err */, plugin.Options{})
		}
		return plugin.BackendError(ctx, &k, zone, dns.RcodeNameError, state, nil /* err */, plugin.Options{})
	}
	if err != nil {
		return dns.RcodeServerFailure, err
	}

	if len(records) == 0 {
		return plugin.BackendError(ctx, &k, zone, dns.RcodeSuccess, state, nil, plugin.Options{})
	}

	m := new(dns.Msg)
	m.SetReply(r)
	m.Authoritative = true
	m.Answer = append(m.Answer, records...)
	m.Extra = append(m.Extra, extra...)

	w.WriteMsg(m)
	return dns.RcodeSuccess, 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)
	}
}
1367474
func (a Auto) ServeDNS(ctx context.Context, w dns.ResponseWriter, r *dns.Msg) (int, error) {
	state := request.Request{W: w, Req: r}
	qname := state.Name()

	// Precheck with the origins, i.e. are we allowed to look here?
	zone := plugin.Zones(a.Zones.Origins()).Matches(qname)
	if zone == "" {
		return plugin.NextOrFailure(a.Name(), a.Next, ctx, w, r)
	}

	// Now the real zone.
	zone = plugin.Zones(a.Zones.Names()).Matches(qname)

	a.Zones.RLock()
	z, ok := a.Zones.Z[zone]
	a.Zones.RUnlock()

	if !ok || z == nil {
		return dns.RcodeServerFailure, nil
	}

	if state.QType() == dns.TypeAXFR || state.QType() == dns.TypeIXFR {
		xfr := file.Xfr{Zone: z}
		return xfr.ServeDNS(ctx, w, r)
	}

	answer, ns, extra, result := z.Lookup(ctx, state, qname)

	m := new(dns.Msg)
	m.SetReply(r)
	m.Authoritative = true
	m.Answer, m.Ns, m.Extra = answer, ns, extra

	switch result {
	case file.Success:
	case file.NoData:
	case file.NameError:
		m.Rcode = dns.RcodeNameError
	case file.Delegation:
		m.Authoritative = false
	case file.ServerFailure:
		return dns.RcodeServerFailure, nil
	}

	w.WriteMsg(m)
	return dns.RcodeSuccess, nil
}
331330
func (m *ServeMux) Prepare() {
	for _, plugin := range m.plugins {
		used := false
		if sc := plugin.HandlersScanner(); sc != nil {
			err := sc.HandlersScannerProcess(m, m.router.handlers)
			if err != nil {
				panic(err)
			}
			used = true
		}
		if !used {
			panic(fmt.Sprintf("unused plugin: %#v", plugin))
		}
	}
}
827695
func (r *Router) ServeFiles(path string, root http.FileSystem) {
	if len(path) < 10 || path[len(path)-10:] != "/*filepath" {
		panic("path must end with /*filepath")
	}

	fileServer := http.FileServer(root)

	var h Handler = func(w http.ResponseWriter, req *Request) error {
		req.URL.Path = req.Params.ByName("filepath")
		fileServer.ServeHTTP(w, req.Request)
		return nil
	}
	r.GET(path, h)
}
617611
func parseDNS(dns *structs.QueryDNSOptions) error {
	if dns.TTL != "" {
		ttl, err := time.ParseDuration(dns.TTL)
		if err != nil {
			return fmt.Errorf("Bad DNS TTL '%s': %v", dns.TTL, err)
		}

		if ttl < 0 {
			return fmt.Errorf("DNS TTL '%d', must be >=0", ttl)
		}
	}

	return nil
}