serve.go 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361
  1. package server
  2. import (
  3. "encoding/hex"
  4. "encoding/json"
  5. "fmt"
  6. "log"
  7. "net"
  8. "net/netip"
  9. "os"
  10. "strconv"
  11. "strings"
  12. "time"
  13. "github.com/abh/geodns/v3/applog"
  14. "github.com/abh/geodns/v3/edns"
  15. "github.com/abh/geodns/v3/querylog"
  16. "github.com/abh/geodns/v3/zones"
  17. "github.com/miekg/dns"
  18. "github.com/prometheus/client_golang/prometheus"
  19. )
  20. func getQuestionName(z *zones.Zone, fqdn string) string {
  21. lx := dns.SplitDomainName(fqdn)
  22. ql := lx[0 : len(lx)-z.LabelCount]
  23. return strings.ToLower(strings.Join(ql, "."))
  24. }
  25. func (srv *Server) serve(w dns.ResponseWriter, req *dns.Msg, z *zones.Zone) {
  26. qnamefqdn := req.Question[0].Name
  27. qtype := req.Question[0].Qtype
  28. var qle *querylog.Entry
  29. if srv.queryLogger != nil {
  30. var isTcp bool
  31. if net := w.LocalAddr().Network(); net == "tcp" {
  32. isTcp = true
  33. }
  34. qle = &querylog.Entry{
  35. Time: time.Now().UnixNano(),
  36. Origin: z.Origin,
  37. Name: strings.ToLower(qnamefqdn),
  38. Qtype: qtype,
  39. Version: srv.info.Version,
  40. IsTCP: isTcp,
  41. }
  42. defer srv.queryLogger.Write(qle)
  43. }
  44. applog.Printf("[zone %s] incoming %s %s (id %d) from %s\n", z.Origin, qnamefqdn,
  45. dns.TypeToString[qtype], req.Id, w.RemoteAddr())
  46. applog.Println("Got request", req)
  47. // qlabel is the qname without the zone origin suffix
  48. qlabel := getQuestionName(z, qnamefqdn)
  49. z.Metrics.LabelStats.Add(qlabel)
  50. // IP that's talking to us (not EDNS CLIENT SUBNET)
  51. var realIP net.IP
  52. if addr, ok := w.RemoteAddr().(*net.UDPAddr); ok {
  53. realIP = make(net.IP, len(addr.IP))
  54. copy(realIP, addr.IP)
  55. } else if addr, ok := w.RemoteAddr().(*net.TCPAddr); ok {
  56. realIP = make(net.IP, len(addr.IP))
  57. copy(realIP, addr.IP)
  58. }
  59. if qle != nil {
  60. qle.RemoteAddr = realIP.String()
  61. }
  62. z.Metrics.ClientStats.Add(realIP.String())
  63. var ip net.IP // EDNS CLIENT SUBNET or real IP
  64. var ecs *dns.EDNS0_SUBNET
  65. if option := req.IsEdns0(); option != nil {
  66. for _, s := range option.Option {
  67. switch e := s.(type) {
  68. case *dns.EDNS0_SUBNET:
  69. applog.Println("Got edns-client-subnet", e.Address, e.Family, e.SourceNetmask, e.SourceScope)
  70. if e.Address != nil {
  71. ecs = e
  72. if ecsip, ok := netip.AddrFromSlice(e.Address); ok {
  73. if ecsip.IsGlobalUnicast() &&
  74. !(ecsip.IsPrivate() ||
  75. ecsip.IsLinkLocalMulticast() ||
  76. ecsip.IsInterfaceLocalMulticast()) {
  77. ip = ecsip.AsSlice()
  78. }
  79. }
  80. if qle != nil {
  81. qle.HasECS = true
  82. qle.ClientAddr = fmt.Sprintf("%s/%d", ip, e.SourceNetmask)
  83. }
  84. }
  85. }
  86. }
  87. }
  88. if len(ip) == 0 { // no edns client subnet
  89. ip = realIP
  90. if qle != nil {
  91. qle.ClientAddr = fmt.Sprintf("%s/%d", ip, len(ip)*8)
  92. }
  93. }
  94. targets, netmask, location := z.Options.Targeting.GetTargets(ip, z.HasClosest)
  95. // if the ECS IP didn't get targets, try the real IP instead
  96. if l := len(targets); (l == 0 || l == 1 && targets[0] == "@") && !ip.Equal(realIP) {
  97. targets, netmask, location = z.Options.Targeting.GetTargets(realIP, z.HasClosest)
  98. }
  99. m := &dns.Msg{}
  100. // setup logging of answers and rcode
  101. if qle != nil {
  102. qle.Targets = targets
  103. defer func() {
  104. qle.Rcode = m.Rcode
  105. qle.AnswerCount = len(m.Answer)
  106. for _, rr := range m.Answer {
  107. var s string
  108. switch a := rr.(type) {
  109. case *dns.A:
  110. s = a.A.String()
  111. case *dns.AAAA:
  112. s = a.AAAA.String()
  113. case *dns.CNAME:
  114. s = a.Target
  115. case *dns.MX:
  116. s = a.Mx
  117. case *dns.NS:
  118. s = a.Ns
  119. case *dns.SRV:
  120. s = a.Target
  121. case *dns.TXT:
  122. s = strings.Join(a.Txt, " ")
  123. }
  124. if len(s) > 0 {
  125. qle.AnswerData = append(qle.AnswerData, s)
  126. }
  127. }
  128. }()
  129. }
  130. mv, err := edns.Version(req)
  131. if err != nil {
  132. m = mv
  133. err := w.WriteMsg(m)
  134. if err != nil {
  135. applog.Printf("could not write response: %s", err)
  136. }
  137. return
  138. }
  139. m.SetReply(req)
  140. if option := edns.SetSizeAndDo(req, m); option != nil {
  141. for _, s := range option.Option {
  142. switch e := s.(type) {
  143. case *dns.EDNS0_NSID:
  144. e.Code = dns.EDNS0NSID
  145. e.Nsid = hex.EncodeToString([]byte(srv.info.ID))
  146. case *dns.EDNS0_SUBNET:
  147. // access e.Family, e.Address, etc.
  148. // TODO: set scope to 0 if there are no alternate responses
  149. if ecs.Family != 0 {
  150. if netmask < 16 {
  151. netmask = 16
  152. }
  153. e.SourceScope = uint8(netmask)
  154. }
  155. }
  156. }
  157. }
  158. m.Authoritative = true
  159. labelMatches := z.FindLabels(qlabel, targets, []uint16{dns.TypeMF, dns.TypeCNAME, qtype})
  160. if len(labelMatches) == 0 {
  161. permitDebug := srv.PublicDebugQueries || (realIP != nil && realIP.IsLoopback())
  162. firstLabel := (strings.Split(qlabel, "."))[0]
  163. if qle != nil {
  164. qle.LabelName = firstLabel
  165. }
  166. if permitDebug && firstLabel == "_status" {
  167. if qtype == dns.TypeANY || qtype == dns.TypeTXT {
  168. m.Answer = srv.statusRR(qlabel + "." + z.Origin + ".")
  169. } else {
  170. m.Ns = append(m.Ns, z.SoaRR())
  171. }
  172. m.Authoritative = true
  173. w.WriteMsg(m)
  174. return
  175. }
  176. if permitDebug && firstLabel == "_health" {
  177. if qtype == dns.TypeANY || qtype == dns.TypeTXT {
  178. baseLabel := strings.Join((strings.Split(qlabel, "."))[1:], ".")
  179. m.Answer = z.HealthRR(qlabel+"."+z.Origin+".", baseLabel)
  180. m.Authoritative = true
  181. w.WriteMsg(m)
  182. return
  183. }
  184. m.Ns = append(m.Ns, z.SoaRR())
  185. m.Authoritative = true
  186. w.WriteMsg(m)
  187. return
  188. }
  189. if firstLabel == "_country" {
  190. if qtype == dns.TypeANY || qtype == dns.TypeTXT {
  191. h := dns.RR_Header{Ttl: 1, Class: dns.ClassINET, Rrtype: dns.TypeTXT}
  192. h.Name = qnamefqdn
  193. txt := []string{
  194. w.RemoteAddr().String(),
  195. ip.String(),
  196. }
  197. targets, netmask, location := z.Options.Targeting.GetTargets(ip, z.HasClosest)
  198. txt = append(txt, strings.Join(targets, " "))
  199. txt = append(txt, fmt.Sprintf("/%d", netmask), srv.info.ID, srv.info.IP)
  200. if location != nil {
  201. txt = append(txt, fmt.Sprintf("(%.3f,%.3f)", location.Latitude, location.Longitude))
  202. } else {
  203. txt = append(txt, "()")
  204. }
  205. m.Answer = []dns.RR{&dns.TXT{Hdr: h,
  206. Txt: txt,
  207. }}
  208. } else {
  209. m.Ns = append(m.Ns, z.SoaRR())
  210. }
  211. m.Authoritative = true
  212. w.WriteMsg(m)
  213. return
  214. }
  215. // return NXDOMAIN
  216. m.SetRcode(req, dns.RcodeNameError)
  217. srv.metrics.Queries.With(
  218. prometheus.Labels{
  219. "zone": z.Origin,
  220. "qtype": dns.TypeToString[qtype],
  221. "qname": "_error",
  222. "rcode": dns.RcodeToString[m.Rcode],
  223. }).Inc()
  224. m.Authoritative = true
  225. m.Ns = []dns.RR{z.SoaRR()}
  226. w.WriteMsg(m)
  227. return
  228. }
  229. for _, match := range labelMatches {
  230. label := match.Label
  231. labelQtype := match.Type
  232. if !label.Closest {
  233. location = nil
  234. }
  235. if servers := z.Picker(label, labelQtype, label.MaxHosts, location); servers != nil {
  236. var rrs []dns.RR
  237. for _, record := range servers {
  238. rr := dns.Copy(record.RR)
  239. rr.Header().Name = qnamefqdn
  240. rrs = append(rrs, rr)
  241. }
  242. m.Answer = rrs
  243. }
  244. if len(m.Answer) > 0 {
  245. // maxHosts only matter within a "targeting group"; at least that's
  246. // how it has been working, so we stop looking for answers as soon
  247. // as we have some.
  248. if qle != nil {
  249. qle.LabelName = label.Label
  250. qle.AnswerCount = len(m.Answer)
  251. }
  252. break
  253. }
  254. }
  255. if len(m.Answer) == 0 {
  256. // Return a SOA so the NOERROR answer gets cached
  257. m.Ns = append(m.Ns, z.SoaRR())
  258. }
  259. qlabelMetric := "_"
  260. if srv.DetailedMetrics {
  261. qlabelMetric = qlabel
  262. }
  263. srv.metrics.Queries.With(
  264. prometheus.Labels{
  265. "zone": z.Origin,
  266. "qtype": dns.TypeToString[qtype],
  267. "qname": qlabelMetric,
  268. "rcode": dns.RcodeToString[m.Rcode],
  269. }).Inc()
  270. applog.Println(m)
  271. if qle != nil {
  272. // should this be in the match loop above?
  273. qle.Rcode = m.Rcode
  274. }
  275. err = w.WriteMsg(m)
  276. if err != nil {
  277. // if Pack'ing fails the Write fails. Return SERVFAIL.
  278. applog.Printf("Error writing packet: %q, %s", err, m)
  279. dns.HandleFailed(w, req)
  280. }
  281. }
  282. func (srv *Server) statusRR(label string) []dns.RR {
  283. h := dns.RR_Header{Ttl: 1, Class: dns.ClassINET, Rrtype: dns.TypeTXT}
  284. h.Name = label
  285. status := map[string]string{"v": srv.info.Version, "id": srv.info.ID}
  286. hostname, err := os.Hostname()
  287. if err == nil {
  288. status["h"] = hostname
  289. }
  290. status["up"] = strconv.Itoa(int(time.Since(srv.info.Started).Seconds()))
  291. js, err := json.Marshal(status)
  292. if err != nil {
  293. log.Printf("error marshaling json status: %s", err)
  294. }
  295. return []dns.RR{&dns.TXT{Hdr: h, Txt: []string{string(js)}}}
  296. }