serve.go 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280
  1. package server
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "log"
  6. "net"
  7. "os"
  8. "strconv"
  9. "strings"
  10. "time"
  11. "github.com/abh/geodns/applog"
  12. "github.com/abh/geodns/querylog"
  13. "github.com/abh/geodns/zones"
  14. "github.com/miekg/dns"
  15. "github.com/rcrowley/go-metrics"
  16. )
  17. func getQuestionName(z *zones.Zone, req *dns.Msg) string {
  18. lx := dns.SplitDomainName(req.Question[0].Name)
  19. ql := lx[0 : len(lx)-z.LabelCount]
  20. return strings.ToLower(strings.Join(ql, "."))
  21. }
  22. func (srv *Server) serve(w dns.ResponseWriter, req *dns.Msg, z *zones.Zone) {
  23. qname := req.Question[0].Name
  24. qtype := req.Question[0].Qtype
  25. var qle *querylog.Entry
  26. if srv.queryLogger != nil {
  27. qle = &querylog.Entry{
  28. Time: time.Now().UnixNano(),
  29. Origin: z.Origin,
  30. Name: qname,
  31. Qtype: qtype,
  32. }
  33. defer srv.queryLogger.Write(qle)
  34. }
  35. applog.Printf("[zone %s] incoming %s %s (id %d) from %s\n", z.Origin, qname,
  36. dns.TypeToString[qtype], req.Id, w.RemoteAddr())
  37. // Global meter
  38. metrics.Get("queries").(metrics.Meter).Mark(1)
  39. // Zone meter
  40. z.Metrics.Queries.Mark(1)
  41. applog.Println("Got request", req)
  42. label := getQuestionName(z, req)
  43. z.Metrics.LabelStats.Add(label)
  44. // IP that's talking to us (not EDNS CLIENT SUBNET)
  45. var realIP net.IP
  46. if addr, ok := w.RemoteAddr().(*net.UDPAddr); ok {
  47. realIP = make(net.IP, len(addr.IP))
  48. copy(realIP, addr.IP)
  49. } else if addr, ok := w.RemoteAddr().(*net.TCPAddr); ok {
  50. realIP = make(net.IP, len(addr.IP))
  51. copy(realIP, addr.IP)
  52. }
  53. if qle != nil {
  54. qle.RemoteAddr = realIP.String()
  55. }
  56. z.Metrics.ClientStats.Add(realIP.String())
  57. var ip net.IP // EDNS or real IP
  58. var edns *dns.EDNS0_SUBNET
  59. var opt_rr *dns.OPT
  60. for _, extra := range req.Extra {
  61. switch extra.(type) {
  62. case *dns.OPT:
  63. for _, o := range extra.(*dns.OPT).Option {
  64. opt_rr = extra.(*dns.OPT)
  65. switch e := o.(type) {
  66. case *dns.EDNS0_NSID:
  67. // do stuff with e.Nsid
  68. case *dns.EDNS0_SUBNET:
  69. z.Metrics.EdnsQueries.Mark(1)
  70. applog.Println("Got edns", e.Address, e.Family, e.SourceNetmask, e.SourceScope)
  71. if e.Address != nil {
  72. edns = e
  73. ip = e.Address
  74. if qle != nil {
  75. qle.HasECS = true
  76. qle.ClientAddr = fmt.Sprintf("%s/%d", ip, e.SourceNetmask)
  77. }
  78. }
  79. }
  80. }
  81. }
  82. }
  83. if len(ip) == 0 { // no edns subnet
  84. ip = realIP
  85. if qle != nil {
  86. qle.ClientAddr = fmt.Sprintf("%s/%d", ip, len(ip)*8)
  87. }
  88. }
  89. targets, netmask, location := z.Options.Targeting.GetTargets(ip, z.HasClosest)
  90. if qle != nil {
  91. qle.Targets = targets
  92. }
  93. m := new(dns.Msg)
  94. if qle != nil {
  95. defer func() {
  96. qle.Rcode = m.Rcode
  97. qle.Answers = len(m.Answer)
  98. }()
  99. }
  100. m.SetReply(req)
  101. if e := m.IsEdns0(); e != nil {
  102. m.SetEdns0(4096, e.Do())
  103. }
  104. m.Authoritative = true
  105. // TODO: set scope to 0 if there are no alternate responses
  106. if edns != nil {
  107. if edns.Family != 0 {
  108. if netmask < 16 {
  109. netmask = 16
  110. }
  111. edns.SourceScope = uint8(netmask)
  112. m.Extra = append(m.Extra, opt_rr)
  113. }
  114. }
  115. labels, labelQtype := z.FindLabels(label, targets, []uint16{dns.TypeMF, dns.TypeCNAME, qtype})
  116. if labelQtype == 0 {
  117. labelQtype = qtype
  118. }
  119. if labels == nil {
  120. permitDebug := srv.PublicDebugQueries || (realIP != nil && realIP.IsLoopback())
  121. firstLabel := (strings.Split(label, "."))[0]
  122. if qle != nil {
  123. qle.LabelName = firstLabel
  124. }
  125. if permitDebug && firstLabel == "_status" {
  126. if qtype == dns.TypeANY || qtype == dns.TypeTXT {
  127. m.Answer = srv.statusRR(label + "." + z.Origin + ".")
  128. } else {
  129. m.Ns = append(m.Ns, z.SoaRR())
  130. }
  131. m.Authoritative = true
  132. w.WriteMsg(m)
  133. return
  134. }
  135. if permitDebug && firstLabel == "_health" {
  136. if qtype == dns.TypeANY || qtype == dns.TypeTXT {
  137. baseLabel := strings.Join((strings.Split(label, "."))[1:], ".")
  138. m.Answer = z.HealthRR(label+"."+z.Origin+".", baseLabel)
  139. m.Authoritative = true
  140. w.WriteMsg(m)
  141. return
  142. }
  143. m.Ns = append(m.Ns, z.SoaRR())
  144. m.Authoritative = true
  145. w.WriteMsg(m)
  146. return
  147. }
  148. if firstLabel == "_country" {
  149. if qtype == dns.TypeANY || qtype == dns.TypeTXT {
  150. h := dns.RR_Header{Ttl: 1, Class: dns.ClassINET, Rrtype: dns.TypeTXT}
  151. h.Name = label + "." + z.Origin + "."
  152. txt := []string{
  153. w.RemoteAddr().String(),
  154. ip.String(),
  155. }
  156. targets, netmask, location := z.Options.Targeting.GetTargets(ip, z.HasClosest)
  157. txt = append(txt, strings.Join(targets, " "))
  158. txt = append(txt, fmt.Sprintf("/%d", netmask), srv.info.ID, srv.info.IP)
  159. if location != nil {
  160. txt = append(txt, fmt.Sprintf("(%.3f,%.3f)", location.Latitude, location.Longitude))
  161. } else {
  162. txt = append(txt, "(?,?)")
  163. }
  164. m.Answer = []dns.RR{&dns.TXT{Hdr: h,
  165. Txt: txt,
  166. }}
  167. } else {
  168. m.Ns = append(m.Ns, z.SoaRR())
  169. }
  170. m.Authoritative = true
  171. w.WriteMsg(m)
  172. return
  173. }
  174. // return NXDOMAIN
  175. m.SetRcode(req, dns.RcodeNameError)
  176. m.Authoritative = true
  177. m.Ns = []dns.RR{z.SoaRR()}
  178. w.WriteMsg(m)
  179. return
  180. }
  181. if !labels.Closest {
  182. location = nil
  183. }
  184. if servers := labels.Picker(labelQtype, labels.MaxHosts, location); servers != nil {
  185. var rrs []dns.RR
  186. for _, record := range servers {
  187. rr := dns.Copy(record.RR)
  188. rr.Header().Name = qname
  189. rrs = append(rrs, rr)
  190. }
  191. m.Answer = rrs
  192. }
  193. if len(m.Answer) == 0 {
  194. // Return a SOA so the NOERROR answer gets cached
  195. m.Ns = append(m.Ns, z.SoaRR())
  196. }
  197. applog.Println(m)
  198. if qle != nil {
  199. qle.LabelName = labels.Label
  200. qle.Answers = len(m.Answer)
  201. qle.Rcode = m.Rcode
  202. }
  203. err := w.WriteMsg(m)
  204. if err != nil {
  205. // if Pack'ing fails the Write fails. Return SERVFAIL.
  206. log.Println("Error writing packet", m)
  207. dns.HandleFailed(w, req)
  208. }
  209. return
  210. }
  211. func (srv *Server) statusRR(label string) []dns.RR {
  212. h := dns.RR_Header{Ttl: 1, Class: dns.ClassINET, Rrtype: dns.TypeTXT}
  213. h.Name = label
  214. status := map[string]string{"v": srv.info.Version, "id": srv.info.ID}
  215. hostname, err := os.Hostname()
  216. if err == nil {
  217. status["h"] = hostname
  218. }
  219. qCounter := metrics.Get("queries").(metrics.Meter)
  220. status["up"] = strconv.Itoa(int(time.Since(srv.info.Started).Seconds()))
  221. status["qs"] = strconv.FormatInt(qCounter.Count(), 10)
  222. status["qps1"] = fmt.Sprintf("%.4f", qCounter.Rate1())
  223. js, err := json.Marshal(status)
  224. return []dns.RR{&dns.TXT{Hdr: h, Txt: []string{string(js)}}}
  225. }