1
0

geoloader.go 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. package geodb
  2. import (
  3. "bytes"
  4. "encoding/csv"
  5. "io"
  6. "net"
  7. "strings"
  8. )
  9. func (s *Store) search(ip string) string {
  10. if strings.Contains(ip, ",") {
  11. //This is a CF proxied request. We only need the front part
  12. //Example 219.71.102.145, 172.71.139.178
  13. ip = strings.Split(ip, ",")[0]
  14. ip = strings.TrimSpace(ip)
  15. }
  16. //See if there are cached country code for this ip
  17. /*
  18. ccc, ok := s.geoipCache.Load(ip)
  19. if ok {
  20. return ccc.(string)
  21. }
  22. */
  23. //Search in geotrie tree
  24. cc := ""
  25. if IsIPv6(ip) {
  26. cc = s.geotrieIpv6.search(ip)
  27. } else {
  28. cc = s.geotrie.search(ip)
  29. }
  30. /*
  31. if cc != "" {
  32. s.geoipCache.Store(ip, cc)
  33. }
  34. */
  35. return cc
  36. }
  37. // Construct the trie data structure for quick lookup
  38. func constrctTrieTree(data [][]string) *trie {
  39. tt := newTrie()
  40. for _, entry := range data {
  41. startIp := entry[0]
  42. endIp := entry[1]
  43. cc := entry[2]
  44. tt.insert(startIp, cc)
  45. tt.insert(endIp, cc)
  46. }
  47. return tt
  48. }
  49. // Parse the embedded csv as ipstart, ipend and country code entries
  50. func parseCSV(content []byte) ([][]string, error) {
  51. var records [][]string
  52. r := csv.NewReader(bytes.NewReader(content))
  53. for {
  54. record, err := r.Read()
  55. if err == io.EOF {
  56. break
  57. }
  58. if err != nil {
  59. return nil, err
  60. }
  61. records = append(records, record)
  62. }
  63. return records, nil
  64. }
  65. // Check if a ip string is within the range of two others
  66. func isIPInRange(ip, start, end string) bool {
  67. ipAddr := net.ParseIP(ip)
  68. if ipAddr == nil {
  69. return false
  70. }
  71. startAddr := net.ParseIP(start)
  72. if startAddr == nil {
  73. return false
  74. }
  75. endAddr := net.ParseIP(end)
  76. if endAddr == nil {
  77. return false
  78. }
  79. if ipAddr.To4() == nil || startAddr.To4() == nil || endAddr.To4() == nil {
  80. return false
  81. }
  82. return bytes.Compare(ipAddr.To4(), startAddr.To4()) >= 0 && bytes.Compare(ipAddr.To4(), endAddr.To4()) <= 0
  83. }