ClusterGeoIpService.cpp 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235
  1. /*
  2. * ZeroTier One - Network Virtualization Everywhere
  3. * Copyright (C) 2011-2016 ZeroTier, Inc. https://www.zerotier.com/
  4. *
  5. * This program is free software: you can redistribute it and/or modify
  6. * it under the terms of the GNU General Public License as published by
  7. * the Free Software Foundation, either version 3 of the License, or
  8. * (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU General Public License
  16. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  17. */
  18. #ifdef ZT_ENABLE_CLUSTER
  19. #include <math.h>
  20. #include <cmath>
  21. #include "ClusterGeoIpService.hpp"
  22. #include "../node/Utils.hpp"
  23. #include "../osdep/OSUtils.hpp"
  24. #define ZT_CLUSTERGEOIPSERVICE_FILE_MODIFICATION_CHECK_EVERY 10000
  25. namespace ZeroTier {
  26. ClusterGeoIpService::ClusterGeoIpService() :
  27. _pathToCsv(),
  28. _ipStartColumn(-1),
  29. _ipEndColumn(-1),
  30. _latitudeColumn(-1),
  31. _longitudeColumn(-1),
  32. _lastFileCheckTime(0),
  33. _csvModificationTime(0),
  34. _csvFileSize(0)
  35. {
  36. }
  37. ClusterGeoIpService::~ClusterGeoIpService()
  38. {
  39. }
  40. bool ClusterGeoIpService::locate(const InetAddress &ip,int &x,int &y,int &z)
  41. {
  42. Mutex::Lock _l(_lock);
  43. if ((_pathToCsv.length() > 0)&&((OSUtils::now() - _lastFileCheckTime) > ZT_CLUSTERGEOIPSERVICE_FILE_MODIFICATION_CHECK_EVERY)) {
  44. _lastFileCheckTime = OSUtils::now();
  45. if ((_csvFileSize != OSUtils::getFileSize(_pathToCsv.c_str()))||(_csvModificationTime != OSUtils::getLastModified(_pathToCsv.c_str())))
  46. _load(_pathToCsv.c_str(),_ipStartColumn,_ipEndColumn,_latitudeColumn,_longitudeColumn);
  47. }
  48. /* We search by looking up the upper bound of the sorted vXdb vectors
  49. * and then iterating down for a matching IP range. We stop when we hit
  50. * the beginning or an entry whose start and end are before the IP we
  51. * are searching. */
  52. if ((ip.ss_family == AF_INET)&&(_v4db.size() > 0)) {
  53. _V4E key;
  54. key.start = Utils::ntoh((uint32_t)(reinterpret_cast<const struct sockaddr_in *>(&ip)->sin_addr.s_addr));
  55. std::vector<_V4E>::const_iterator i(std::upper_bound(_v4db.begin(),_v4db.end(),key));
  56. while (i != _v4db.begin()) {
  57. --i;
  58. if ((key.start >= i->start)&&(key.start <= i->end)) {
  59. x = i->x;
  60. y = i->y;
  61. z = i->z;
  62. //printf("%s : %f,%f %d,%d,%d\n",ip.toIpString().c_str(),i->lat,i->lon,x,y,z);
  63. return true;
  64. } else if ((key.start > i->start)&&(key.start > i->end))
  65. break;
  66. }
  67. } else if ((ip.ss_family == AF_INET6)&&(_v6db.size() > 0)) {
  68. _V6E key;
  69. memcpy(key.start,reinterpret_cast<const struct sockaddr_in6 *>(&ip)->sin6_addr.s6_addr,16);
  70. std::vector<_V6E>::const_iterator i(std::upper_bound(_v6db.begin(),_v6db.end(),key));
  71. while (i != _v6db.begin()) {
  72. --i;
  73. const int s_vs_s = memcmp(key.start,i->start,16);
  74. const int s_vs_e = memcmp(key.start,i->end,16);
  75. if ((s_vs_s >= 0)&&(s_vs_e <= 0)) {
  76. x = i->x;
  77. y = i->y;
  78. z = i->z;
  79. //printf("%s : %f,%f %d,%d,%d\n",ip.toIpString().c_str(),i->lat,i->lon,x,y,z);
  80. return true;
  81. } else if ((s_vs_s > 0)&&(s_vs_e > 0))
  82. break;
  83. }
  84. }
  85. return false;
  86. }
  87. void ClusterGeoIpService::_parseLine(const char *line,std::vector<_V4E> &v4db,std::vector<_V6E> &v6db,int ipStartColumn,int ipEndColumn,int latitudeColumn,int longitudeColumn)
  88. {
  89. std::vector<std::string> ls(Utils::split(line,",\t","\\","\"'"));
  90. if ( ((ipStartColumn >= 0)&&(ipStartColumn < (int)ls.size()))&&
  91. ((ipEndColumn >= 0)&&(ipEndColumn < (int)ls.size()))&&
  92. ((latitudeColumn >= 0)&&(latitudeColumn < (int)ls.size()))&&
  93. ((longitudeColumn >= 0)&&(longitudeColumn < (int)ls.size())) ) {
  94. InetAddress ipStart(ls[ipStartColumn].c_str(),0);
  95. InetAddress ipEnd(ls[ipEndColumn].c_str(),0);
  96. const double lat = strtod(ls[latitudeColumn].c_str(),(char **)0);
  97. const double lon = strtod(ls[longitudeColumn].c_str(),(char **)0);
  98. if ((ipStart.ss_family == ipEnd.ss_family)&&(ipStart)&&(ipEnd)&&(std::isfinite(lat))&&(std::isfinite(lon))) {
  99. const double latRadians = lat * 0.01745329251994; // PI / 180
  100. const double lonRadians = lon * 0.01745329251994; // PI / 180
  101. const double cosLat = cos(latRadians);
  102. const int x = (int)round((-6371.0) * cosLat * cos(lonRadians)); // 6371 == Earth's approximate radius in kilometers
  103. const int y = (int)round(6371.0 * sin(latRadians));
  104. const int z = (int)round(6371.0 * cosLat * sin(lonRadians));
  105. if (ipStart.ss_family == AF_INET) {
  106. v4db.push_back(_V4E());
  107. v4db.back().start = Utils::ntoh((uint32_t)(reinterpret_cast<const struct sockaddr_in *>(&ipStart)->sin_addr.s_addr));
  108. v4db.back().end = Utils::ntoh((uint32_t)(reinterpret_cast<const struct sockaddr_in *>(&ipEnd)->sin_addr.s_addr));
  109. v4db.back().lat = (float)lat;
  110. v4db.back().lon = (float)lon;
  111. v4db.back().x = x;
  112. v4db.back().y = y;
  113. v4db.back().z = z;
  114. //printf("%s - %s : %d,%d,%d\n",ipStart.toIpString().c_str(),ipEnd.toIpString().c_str(),x,y,z);
  115. } else if (ipStart.ss_family == AF_INET6) {
  116. v6db.push_back(_V6E());
  117. memcpy(v6db.back().start,reinterpret_cast<const struct sockaddr_in6 *>(&ipStart)->sin6_addr.s6_addr,16);
  118. memcpy(v6db.back().end,reinterpret_cast<const struct sockaddr_in6 *>(&ipEnd)->sin6_addr.s6_addr,16);
  119. v6db.back().lat = (float)lat;
  120. v6db.back().lon = (float)lon;
  121. v6db.back().x = x;
  122. v6db.back().y = y;
  123. v6db.back().z = z;
  124. //printf("%s - %s : %d,%d,%d\n",ipStart.toIpString().c_str(),ipEnd.toIpString().c_str(),x,y,z);
  125. }
  126. }
  127. }
  128. }
  129. long ClusterGeoIpService::_load(const char *pathToCsv,int ipStartColumn,int ipEndColumn,int latitudeColumn,int longitudeColumn)
  130. {
  131. // assumes _lock is locked
  132. FILE *f = fopen(pathToCsv,"rb");
  133. if (!f)
  134. return -1;
  135. std::vector<_V4E> v4db;
  136. std::vector<_V6E> v6db;
  137. v4db.reserve(16777216);
  138. v6db.reserve(16777216);
  139. char buf[4096];
  140. char linebuf[1024];
  141. unsigned int lineptr = 0;
  142. for(;;) {
  143. int n = (int)fread(buf,1,sizeof(buf),f);
  144. if (n <= 0)
  145. break;
  146. for(int i=0;i<n;++i) {
  147. if ((buf[i] == '\r')||(buf[i] == '\n')||(buf[i] == (char)0)) {
  148. if (lineptr) {
  149. linebuf[lineptr] = (char)0;
  150. _parseLine(linebuf,v4db,v6db,ipStartColumn,ipEndColumn,latitudeColumn,longitudeColumn);
  151. }
  152. lineptr = 0;
  153. } else if (lineptr < (unsigned int)sizeof(linebuf))
  154. linebuf[lineptr++] = buf[i];
  155. }
  156. }
  157. if (lineptr) {
  158. linebuf[lineptr] = (char)0;
  159. _parseLine(linebuf,v4db,v6db,ipStartColumn,ipEndColumn,latitudeColumn,longitudeColumn);
  160. }
  161. fclose(f);
  162. if ((v4db.size() > 0)||(v6db.size() > 0)) {
  163. std::sort(v4db.begin(),v4db.end());
  164. std::sort(v6db.begin(),v6db.end());
  165. _pathToCsv = pathToCsv;
  166. _ipStartColumn = ipStartColumn;
  167. _ipEndColumn = ipEndColumn;
  168. _latitudeColumn = latitudeColumn;
  169. _longitudeColumn = longitudeColumn;
  170. _lastFileCheckTime = OSUtils::now();
  171. _csvModificationTime = OSUtils::getLastModified(pathToCsv);
  172. _csvFileSize = OSUtils::getFileSize(pathToCsv);
  173. _v4db.swap(v4db);
  174. _v6db.swap(v6db);
  175. return (long)(_v4db.size() + _v6db.size());
  176. } else {
  177. return 0;
  178. }
  179. }
  180. } // namespace ZeroTier
  181. #endif // ZT_ENABLE_CLUSTER
  182. /*
  183. int main(int argc,char **argv)
  184. {
  185. char buf[1024];
  186. ZeroTier::ClusterGeoIpService gip;
  187. printf("loading...\n");
  188. gip.load("/Users/api/Code/ZeroTier/Infrastructure/root-servers/zerotier-one/cluster-geoip.csv",0,1,5,6);
  189. printf("... done!\n"); fflush(stdout);
  190. while (gets(buf)) { // unsafe, testing only
  191. ZeroTier::InetAddress addr(buf,0);
  192. printf("looking up: %s\n",addr.toString().c_str()); fflush(stdout);
  193. int x = 0,y = 0,z = 0;
  194. if (gip.locate(addr,x,y,z)) {
  195. //printf("%s: %d,%d,%d\n",addr.toString().c_str(),x,y,z); fflush(stdout);
  196. } else {
  197. printf("%s: not found!\n",addr.toString().c_str()); fflush(stdout);
  198. }
  199. }
  200. return 0;
  201. }
  202. */