serve.go 7.5 KB

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