ip.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356
  1. /**************************************************************************/
  2. /* ip.cpp */
  3. /**************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /**************************************************************************/
  8. /* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
  9. /* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
  10. /* */
  11. /* Permission is hereby granted, free of charge, to any person obtaining */
  12. /* a copy of this software and associated documentation files (the */
  13. /* "Software"), to deal in the Software without restriction, including */
  14. /* without limitation the rights to use, copy, modify, merge, publish, */
  15. /* distribute, sublicense, and/or sell copies of the Software, and to */
  16. /* permit persons to whom the Software is furnished to do so, subject to */
  17. /* the following conditions: */
  18. /* */
  19. /* The above copyright notice and this permission notice shall be */
  20. /* included in all copies or substantial portions of the Software. */
  21. /* */
  22. /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
  23. /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
  24. /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */
  25. /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
  26. /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
  27. /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
  28. /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
  29. /**************************************************************************/
  30. #include "ip.h"
  31. #include "core/hash_map.h"
  32. #include "core/os/semaphore.h"
  33. #include "core/os/thread.h"
  34. VARIANT_ENUM_CAST(IP::ResolverStatus);
  35. /************* RESOLVER ******************/
  36. struct _IP_ResolverPrivate {
  37. struct QueueItem {
  38. SafeNumeric<IP::ResolverStatus> status;
  39. List<IP_Address> response;
  40. String hostname;
  41. IP::Type type;
  42. void clear() {
  43. status.set(IP::RESOLVER_STATUS_NONE);
  44. response.clear();
  45. type = IP::TYPE_NONE;
  46. hostname = "";
  47. };
  48. QueueItem() {
  49. clear();
  50. };
  51. };
  52. QueueItem queue[IP::RESOLVER_MAX_QUERIES];
  53. IP::ResolverID find_empty_id() const {
  54. for (int i = 0; i < IP::RESOLVER_MAX_QUERIES; i++) {
  55. if (queue[i].status.get() == IP::RESOLVER_STATUS_NONE) {
  56. return i;
  57. }
  58. }
  59. return IP::RESOLVER_INVALID_ID;
  60. }
  61. Mutex mutex;
  62. Semaphore sem;
  63. Thread thread;
  64. //Semaphore* semaphore;
  65. bool thread_abort;
  66. void resolve_queues() {
  67. for (int i = 0; i < IP::RESOLVER_MAX_QUERIES; i++) {
  68. if (queue[i].status.get() != IP::RESOLVER_STATUS_WAITING) {
  69. continue;
  70. }
  71. mutex.lock();
  72. List<IP_Address> response;
  73. String hostname = queue[i].hostname;
  74. IP::Type type = queue[i].type;
  75. mutex.unlock();
  76. // We should not lock while resolving the hostname,
  77. // only when modifying the queue.
  78. IP::get_singleton()->_resolve_hostname(response, hostname, type);
  79. MutexLock lock(mutex);
  80. // Could have been completed by another function, or deleted.
  81. if (queue[i].status.get() != IP::RESOLVER_STATUS_WAITING) {
  82. continue;
  83. }
  84. // We might be overriding another result, but we don't care as long as the result is valid.
  85. if (response.size()) {
  86. String key = get_cache_key(hostname, type);
  87. cache[key] = response;
  88. }
  89. queue[i].response = response;
  90. queue[i].status.set(response.empty() ? IP::RESOLVER_STATUS_ERROR : IP::RESOLVER_STATUS_DONE);
  91. }
  92. }
  93. static void _thread_function(void *self) {
  94. _IP_ResolverPrivate *ipr = (_IP_ResolverPrivate *)self;
  95. while (!ipr->thread_abort) {
  96. ipr->sem.wait();
  97. ipr->resolve_queues();
  98. }
  99. }
  100. HashMap<String, List<IP_Address>> cache;
  101. static String get_cache_key(String p_hostname, IP::Type p_type) {
  102. return itos(p_type) + p_hostname;
  103. }
  104. };
  105. IP_Address IP::resolve_hostname(const String &p_hostname, IP::Type p_type) {
  106. const Array addresses = resolve_hostname_addresses(p_hostname, p_type);
  107. return addresses.size() ? addresses[0].operator IP_Address() : IP_Address();
  108. }
  109. Array IP::resolve_hostname_addresses(const String &p_hostname, Type p_type) {
  110. List<IP_Address> res;
  111. String key = _IP_ResolverPrivate::get_cache_key(p_hostname, p_type);
  112. resolver->mutex.lock();
  113. if (resolver->cache.has(key)) {
  114. res = resolver->cache[key];
  115. } else {
  116. // This should be run unlocked so the resolver thread can keep resolving
  117. // other requests.
  118. resolver->mutex.unlock();
  119. _resolve_hostname(res, p_hostname, p_type);
  120. resolver->mutex.lock();
  121. // We might be overriding another result, but we don't care as long as the result is valid.
  122. if (res.size()) {
  123. resolver->cache[key] = res;
  124. }
  125. }
  126. resolver->mutex.unlock();
  127. Array result;
  128. for (int i = 0; i < res.size(); ++i) {
  129. result.push_back(String(res[i]));
  130. }
  131. return result;
  132. }
  133. IP::ResolverID IP::resolve_hostname_queue_item(const String &p_hostname, IP::Type p_type) {
  134. MutexLock lock(resolver->mutex);
  135. ResolverID id = resolver->find_empty_id();
  136. if (id == RESOLVER_INVALID_ID) {
  137. WARN_PRINT("Out of resolver queries");
  138. return id;
  139. }
  140. String key = _IP_ResolverPrivate::get_cache_key(p_hostname, p_type);
  141. resolver->queue[id].hostname = p_hostname;
  142. resolver->queue[id].type = p_type;
  143. if (resolver->cache.has(key)) {
  144. resolver->queue[id].response = resolver->cache[key];
  145. resolver->queue[id].status.set(IP::RESOLVER_STATUS_DONE);
  146. } else {
  147. resolver->queue[id].response = List<IP_Address>();
  148. resolver->queue[id].status.set(IP::RESOLVER_STATUS_WAITING);
  149. if (resolver->thread.is_started()) {
  150. resolver->sem.post();
  151. } else {
  152. resolver->resolve_queues();
  153. }
  154. }
  155. return id;
  156. }
  157. IP::ResolverStatus IP::get_resolve_item_status(ResolverID p_id) const {
  158. ERR_FAIL_INDEX_V_MSG(p_id, IP::RESOLVER_MAX_QUERIES, IP::RESOLVER_STATUS_NONE, vformat("Too many concurrent DNS resolver queries (%d, but should be %d at most). Try performing less network requests at once.", p_id, IP::RESOLVER_MAX_QUERIES));
  159. IP::ResolverStatus res = resolver->queue[p_id].status.get();
  160. if (res == IP::RESOLVER_STATUS_NONE) {
  161. ERR_PRINT("Condition status == IP::RESOLVER_STATUS_NONE");
  162. return IP::RESOLVER_STATUS_NONE;
  163. }
  164. return res;
  165. }
  166. IP_Address IP::get_resolve_item_address(ResolverID p_id) const {
  167. ERR_FAIL_INDEX_V_MSG(p_id, IP::RESOLVER_MAX_QUERIES, IP_Address(), vformat("Too many concurrent DNS resolver queries (%d, but should be %d at most). Try performing less network requests at once.", p_id, IP::RESOLVER_MAX_QUERIES));
  168. MutexLock lock(resolver->mutex);
  169. if (resolver->queue[p_id].status.get() != IP::RESOLVER_STATUS_DONE) {
  170. ERR_PRINT("Resolve of '" + resolver->queue[p_id].hostname + "'' didn't complete yet.");
  171. return IP_Address();
  172. }
  173. List<IP_Address> res = resolver->queue[p_id].response;
  174. for (int i = 0; i < res.size(); ++i) {
  175. if (res[i].is_valid()) {
  176. return res[i];
  177. }
  178. }
  179. return IP_Address();
  180. }
  181. Array IP::get_resolve_item_addresses(ResolverID p_id) const {
  182. ERR_FAIL_INDEX_V_MSG(p_id, IP::RESOLVER_MAX_QUERIES, Array(), vformat("Too many concurrent DNS resolver queries (%d, but should be %d at most). Try performing less network requests at once.", p_id, IP::RESOLVER_MAX_QUERIES));
  183. MutexLock lock(resolver->mutex);
  184. if (resolver->queue[p_id].status.get() != IP::RESOLVER_STATUS_DONE) {
  185. ERR_PRINT("Resolve of '" + resolver->queue[p_id].hostname + "'' didn't complete yet.");
  186. return Array();
  187. }
  188. List<IP_Address> res = resolver->queue[p_id].response;
  189. Array result;
  190. for (int i = 0; i < res.size(); ++i) {
  191. if (res[i].is_valid()) {
  192. result.push_back(String(res[i]));
  193. }
  194. }
  195. return result;
  196. }
  197. void IP::erase_resolve_item(ResolverID p_id) {
  198. ERR_FAIL_INDEX_MSG(p_id, IP::RESOLVER_MAX_QUERIES, vformat("Too many concurrent DNS resolver queries (%d, but should be %d at most). Try performing less network requests at once.", p_id, IP::RESOLVER_MAX_QUERIES));
  199. resolver->queue[p_id].status.set(IP::RESOLVER_STATUS_NONE);
  200. }
  201. void IP::clear_cache(const String &p_hostname) {
  202. MutexLock lock(resolver->mutex);
  203. if (p_hostname.empty()) {
  204. resolver->cache.clear();
  205. } else {
  206. resolver->cache.erase(_IP_ResolverPrivate::get_cache_key(p_hostname, IP::TYPE_NONE));
  207. resolver->cache.erase(_IP_ResolverPrivate::get_cache_key(p_hostname, IP::TYPE_IPV4));
  208. resolver->cache.erase(_IP_ResolverPrivate::get_cache_key(p_hostname, IP::TYPE_IPV6));
  209. resolver->cache.erase(_IP_ResolverPrivate::get_cache_key(p_hostname, IP::TYPE_ANY));
  210. }
  211. }
  212. Array IP::_get_local_addresses() const {
  213. Array addresses;
  214. List<IP_Address> ip_addresses;
  215. get_local_addresses(&ip_addresses);
  216. for (List<IP_Address>::Element *E = ip_addresses.front(); E; E = E->next()) {
  217. addresses.push_back(E->get());
  218. }
  219. return addresses;
  220. }
  221. Array IP::_get_local_interfaces() const {
  222. Array results;
  223. Map<String, Interface_Info> interfaces;
  224. get_local_interfaces(&interfaces);
  225. for (Map<String, Interface_Info>::Element *E = interfaces.front(); E; E = E->next()) {
  226. Interface_Info &c = E->get();
  227. Dictionary rc;
  228. rc["name"] = c.name;
  229. rc["friendly"] = c.name_friendly;
  230. rc["index"] = c.index;
  231. Array ips;
  232. for (const List<IP_Address>::Element *F = c.ip_addresses.front(); F; F = F->next()) {
  233. ips.push_front(F->get());
  234. }
  235. rc["addresses"] = ips;
  236. results.push_front(rc);
  237. }
  238. return results;
  239. }
  240. void IP::get_local_addresses(List<IP_Address> *r_addresses) const {
  241. Map<String, Interface_Info> interfaces;
  242. get_local_interfaces(&interfaces);
  243. for (Map<String, Interface_Info>::Element *E = interfaces.front(); E; E = E->next()) {
  244. for (const List<IP_Address>::Element *F = E->get().ip_addresses.front(); F; F = F->next()) {
  245. r_addresses->push_front(F->get());
  246. }
  247. }
  248. }
  249. void IP::_bind_methods() {
  250. ClassDB::bind_method(D_METHOD("resolve_hostname", "host", "ip_type"), &IP::resolve_hostname, DEFVAL(IP::TYPE_ANY));
  251. ClassDB::bind_method(D_METHOD("resolve_hostname_addresses", "host", "ip_type"), &IP::resolve_hostname_addresses, DEFVAL(IP::TYPE_ANY));
  252. ClassDB::bind_method(D_METHOD("resolve_hostname_queue_item", "host", "ip_type"), &IP::resolve_hostname_queue_item, DEFVAL(IP::TYPE_ANY));
  253. ClassDB::bind_method(D_METHOD("get_resolve_item_status", "id"), &IP::get_resolve_item_status);
  254. ClassDB::bind_method(D_METHOD("get_resolve_item_address", "id"), &IP::get_resolve_item_address);
  255. ClassDB::bind_method(D_METHOD("get_resolve_item_addresses", "id"), &IP::get_resolve_item_addresses);
  256. ClassDB::bind_method(D_METHOD("erase_resolve_item", "id"), &IP::erase_resolve_item);
  257. ClassDB::bind_method(D_METHOD("get_local_addresses"), &IP::_get_local_addresses);
  258. ClassDB::bind_method(D_METHOD("get_local_interfaces"), &IP::_get_local_interfaces);
  259. ClassDB::bind_method(D_METHOD("clear_cache", "hostname"), &IP::clear_cache, DEFVAL(""));
  260. BIND_ENUM_CONSTANT(RESOLVER_STATUS_NONE);
  261. BIND_ENUM_CONSTANT(RESOLVER_STATUS_WAITING);
  262. BIND_ENUM_CONSTANT(RESOLVER_STATUS_DONE);
  263. BIND_ENUM_CONSTANT(RESOLVER_STATUS_ERROR);
  264. BIND_CONSTANT(RESOLVER_MAX_QUERIES);
  265. BIND_CONSTANT(RESOLVER_INVALID_ID);
  266. BIND_ENUM_CONSTANT(TYPE_NONE);
  267. BIND_ENUM_CONSTANT(TYPE_IPV4);
  268. BIND_ENUM_CONSTANT(TYPE_IPV6);
  269. BIND_ENUM_CONSTANT(TYPE_ANY);
  270. }
  271. IP *IP::singleton = nullptr;
  272. IP *IP::get_singleton() {
  273. return singleton;
  274. }
  275. IP *(*IP::_create)() = nullptr;
  276. IP *IP::create() {
  277. ERR_FAIL_COND_V_MSG(singleton, nullptr, "IP singleton already exist.");
  278. ERR_FAIL_COND_V(!_create, nullptr);
  279. return _create();
  280. }
  281. IP::IP() {
  282. singleton = this;
  283. resolver = memnew(_IP_ResolverPrivate);
  284. resolver->thread_abort = false;
  285. resolver->thread.start(_IP_ResolverPrivate::_thread_function, resolver);
  286. }
  287. IP::~IP() {
  288. resolver->thread_abort = true;
  289. resolver->sem.post();
  290. resolver->thread.wait_to_finish();
  291. memdelete(resolver);
  292. }