getinfo_geoip.c 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. #include "core/or/or.h"
  2. #include "core/mainloop/connection.h"
  3. #include "feature/control/control.h"
  4. #include "feature/control/getinfo_geoip.h"
  5. #include "lib/geoip/geoip.h"
  6. /** Helper used to implement GETINFO ip-to-country/... controller command. */
  7. int
  8. getinfo_helper_geoip(control_connection_t *control_conn,
  9. const char *question, char **answer,
  10. const char **errmsg)
  11. {
  12. (void)control_conn;
  13. if (!strcmpstart(question, "ip-to-country/")) {
  14. int c;
  15. sa_family_t family;
  16. tor_addr_t addr;
  17. question += strlen("ip-to-country/");
  18. if (!strcmp(question, "ipv4-available") ||
  19. !strcmp(question, "ipv6-available")) {
  20. family = !strcmp(question, "ipv4-available") ? AF_INET : AF_INET6;
  21. const int available = geoip_is_loaded(family);
  22. tor_asprintf(answer, "%d", !! available);
  23. return 0;
  24. }
  25. family = tor_addr_parse(&addr, question);
  26. if (family != AF_INET && family != AF_INET6) {
  27. *errmsg = "Invalid address family";
  28. return -1;
  29. }
  30. if (!geoip_is_loaded(family)) {
  31. *errmsg = "GeoIP data not loaded";
  32. return -1;
  33. }
  34. if (family == AF_INET)
  35. c = geoip_get_country_by_ipv4(tor_addr_to_ipv4h(&addr));
  36. else /* AF_INET6 */
  37. c = geoip_get_country_by_ipv6(tor_addr_to_in6(&addr));
  38. *answer = tor_strdup(geoip_get_country_name(c));
  39. }
  40. return 0;
  41. }