geoloader.go 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. package geodb
  2. import (
  3. "bytes"
  4. "encoding/csv"
  5. "io"
  6. "strings"
  7. "imuslab.com/zoraxy/mod/netutils"
  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. ccc, ok := s.geoipCache.Load(ip)
  18. if ok {
  19. return ccc.(string)
  20. }
  21. //Search in geotrie tree
  22. cc := ""
  23. if netutils.IsIPv6(ip) {
  24. if s.geotrieIpv6 == nil {
  25. cc = s.slowSearchIpv6(ip)
  26. } else {
  27. cc = s.geotrieIpv6.search(ip)
  28. }
  29. } else {
  30. if s.geotrie == nil {
  31. cc = s.slowSearchIpv4(ip)
  32. } else {
  33. cc = s.geotrie.search(ip)
  34. }
  35. }
  36. /*
  37. if cc != "" {
  38. s.geoipCache.Store(ip, cc)
  39. }
  40. */
  41. return cc
  42. }
  43. // Construct the trie data structure for quick lookup
  44. func constrctTrieTree(data [][]string) *trie {
  45. tt := newTrie()
  46. for _, entry := range data {
  47. startIp := entry[0]
  48. endIp := entry[1]
  49. cc := entry[2]
  50. tt.insert(startIp, cc)
  51. tt.insert(endIp, cc)
  52. }
  53. return tt
  54. }
  55. // Parse the embedded csv as ipstart, ipend and country code entries
  56. func parseCSV(content []byte) ([][]string, error) {
  57. var records [][]string
  58. r := csv.NewReader(bytes.NewReader(content))
  59. for {
  60. record, err := r.Read()
  61. if err == io.EOF {
  62. break
  63. }
  64. if err != nil {
  65. return nil, err
  66. }
  67. records = append(records, record)
  68. }
  69. return records, nil
  70. }