ip.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355
  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/os/semaphore.h"
  32. #include "core/os/thread.h"
  33. #include "core/templates/hash_map.h"
  34. #include "core/variant/typed_array.h"
  35. /************* RESOLVER ******************/
  36. struct _IP_ResolverPrivate {
  37. struct QueueItem {
  38. SafeNumeric<IP::ResolverStatus> status;
  39. List<IPAddress> 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. SafeFlag thread_abort;
  65. void resolve_queues() {
  66. for (int i = 0; i < IP::RESOLVER_MAX_QUERIES; i++) {
  67. if (queue[i].status.get() != IP::RESOLVER_STATUS_WAITING) {
  68. continue;
  69. }
  70. mutex.lock();
  71. List<IPAddress> response;
  72. String hostname = queue[i].hostname;
  73. IP::Type type = queue[i].type;
  74. mutex.unlock();
  75. // We should not lock while resolving the hostname,
  76. // only when modifying the queue.
  77. IP::get_singleton()->_resolve_hostname(response, hostname, type);
  78. MutexLock lock(mutex);
  79. // Could have been completed by another function, or deleted.
  80. if (queue[i].status.get() != IP::RESOLVER_STATUS_WAITING) {
  81. continue;
  82. }
  83. // We might be overriding another result, but we don't care as long as the result is valid.
  84. if (response.size()) {
  85. String key = get_cache_key(hostname, type);
  86. cache[key] = response;
  87. }
  88. queue[i].response = response;
  89. queue[i].status.set(response.is_empty() ? IP::RESOLVER_STATUS_ERROR : IP::RESOLVER_STATUS_DONE);
  90. }
  91. }
  92. static void _thread_function(void *self) {
  93. _IP_ResolverPrivate *ipr = static_cast<_IP_ResolverPrivate *>(self);
  94. while (!ipr->thread_abort.is_set()) {
  95. ipr->sem.wait();
  96. ipr->resolve_queues();
  97. }
  98. }
  99. HashMap<String, List<IPAddress>> cache;
  100. static String get_cache_key(String p_hostname, IP::Type p_type) {
  101. return itos(p_type) + p_hostname;
  102. }
  103. };
  104. IPAddress IP::resolve_hostname(const String &p_hostname, IP::Type p_type) {
  105. const PackedStringArray addresses = resolve_hostname_addresses(p_hostname, p_type);
  106. return addresses.size() ? (IPAddress)addresses[0] : IPAddress();
  107. }
  108. PackedStringArray IP::resolve_hostname_addresses(const String &p_hostname, Type p_type) {
  109. List<IPAddress> res;
  110. String key = _IP_ResolverPrivate::get_cache_key(p_hostname, p_type);
  111. resolver->mutex.lock();
  112. if (resolver->cache.has(key)) {
  113. res = resolver->cache[key];
  114. } else {
  115. // This should be run unlocked so the resolver thread can keep resolving
  116. // other requests.
  117. resolver->mutex.unlock();
  118. _resolve_hostname(res, p_hostname, p_type);
  119. resolver->mutex.lock();
  120. // We might be overriding another result, but we don't care as long as the result is valid.
  121. if (res.size()) {
  122. resolver->cache[key] = res;
  123. }
  124. }
  125. resolver->mutex.unlock();
  126. PackedStringArray result;
  127. for (int i = 0; i < res.size(); ++i) {
  128. result.push_back(String(res[i]));
  129. }
  130. return result;
  131. }
  132. IP::ResolverID IP::resolve_hostname_queue_item(const String &p_hostname, IP::Type p_type) {
  133. MutexLock lock(resolver->mutex);
  134. ResolverID id = resolver->find_empty_id();
  135. if (id == RESOLVER_INVALID_ID) {
  136. WARN_PRINT("Out of resolver queries");
  137. return id;
  138. }
  139. String key = _IP_ResolverPrivate::get_cache_key(p_hostname, p_type);
  140. resolver->queue[id].hostname = p_hostname;
  141. resolver->queue[id].type = p_type;
  142. if (resolver->cache.has(key)) {
  143. resolver->queue[id].response = resolver->cache[key];
  144. resolver->queue[id].status.set(IP::RESOLVER_STATUS_DONE);
  145. } else {
  146. resolver->queue[id].response = List<IPAddress>();
  147. resolver->queue[id].status.set(IP::RESOLVER_STATUS_WAITING);
  148. if (resolver->thread.is_started()) {
  149. resolver->sem.post();
  150. } else {
  151. resolver->resolve_queues();
  152. }
  153. }
  154. return id;
  155. }
  156. IP::ResolverStatus IP::get_resolve_item_status(ResolverID p_id) const {
  157. 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));
  158. IP::ResolverStatus res = resolver->queue[p_id].status.get();
  159. if (res == IP::RESOLVER_STATUS_NONE) {
  160. ERR_PRINT("Condition status == IP::RESOLVER_STATUS_NONE");
  161. return IP::RESOLVER_STATUS_NONE;
  162. }
  163. return res;
  164. }
  165. IPAddress IP::get_resolve_item_address(ResolverID p_id) const {
  166. ERR_FAIL_INDEX_V_MSG(p_id, IP::RESOLVER_MAX_QUERIES, IPAddress(), 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));
  167. MutexLock lock(resolver->mutex);
  168. if (resolver->queue[p_id].status.get() != IP::RESOLVER_STATUS_DONE) {
  169. ERR_PRINT("Resolve of '" + resolver->queue[p_id].hostname + "'' didn't complete yet.");
  170. return IPAddress();
  171. }
  172. List<IPAddress> res = resolver->queue[p_id].response;
  173. for (int i = 0; i < res.size(); ++i) {
  174. if (res[i].is_valid()) {
  175. return res[i];
  176. }
  177. }
  178. return IPAddress();
  179. }
  180. Array IP::get_resolve_item_addresses(ResolverID p_id) const {
  181. 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));
  182. MutexLock lock(resolver->mutex);
  183. if (resolver->queue[p_id].status.get() != IP::RESOLVER_STATUS_DONE) {
  184. ERR_PRINT("Resolve of '" + resolver->queue[p_id].hostname + "'' didn't complete yet.");
  185. return Array();
  186. }
  187. List<IPAddress> res = resolver->queue[p_id].response;
  188. Array result;
  189. for (int i = 0; i < res.size(); ++i) {
  190. if (res[i].is_valid()) {
  191. result.push_back(String(res[i]));
  192. }
  193. }
  194. return result;
  195. }
  196. void IP::erase_resolve_item(ResolverID p_id) {
  197. 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));
  198. resolver->queue[p_id].status.set(IP::RESOLVER_STATUS_NONE);
  199. }
  200. void IP::clear_cache(const String &p_hostname) {
  201. MutexLock lock(resolver->mutex);
  202. if (p_hostname.is_empty()) {
  203. resolver->cache.clear();
  204. } else {
  205. resolver->cache.erase(_IP_ResolverPrivate::get_cache_key(p_hostname, IP::TYPE_NONE));
  206. resolver->cache.erase(_IP_ResolverPrivate::get_cache_key(p_hostname, IP::TYPE_IPV4));
  207. resolver->cache.erase(_IP_ResolverPrivate::get_cache_key(p_hostname, IP::TYPE_IPV6));
  208. resolver->cache.erase(_IP_ResolverPrivate::get_cache_key(p_hostname, IP::TYPE_ANY));
  209. }
  210. }
  211. PackedStringArray IP::_get_local_addresses() const {
  212. PackedStringArray addresses;
  213. List<IPAddress> ip_addresses;
  214. get_local_addresses(&ip_addresses);
  215. for (const IPAddress &E : ip_addresses) {
  216. addresses.push_back(E);
  217. }
  218. return addresses;
  219. }
  220. TypedArray<Dictionary> IP::_get_local_interfaces() const {
  221. TypedArray<Dictionary> results;
  222. HashMap<String, Interface_Info> interfaces;
  223. get_local_interfaces(&interfaces);
  224. for (KeyValue<String, Interface_Info> &E : interfaces) {
  225. Interface_Info &c = E.value;
  226. Dictionary rc;
  227. rc["name"] = c.name;
  228. rc["friendly"] = c.name_friendly;
  229. rc["index"] = c.index;
  230. Array ips;
  231. for (const IPAddress &F : c.ip_addresses) {
  232. ips.push_front(F);
  233. }
  234. rc["addresses"] = ips;
  235. results.push_front(rc);
  236. }
  237. return results;
  238. }
  239. void IP::get_local_addresses(List<IPAddress> *r_addresses) const {
  240. HashMap<String, Interface_Info> interfaces;
  241. get_local_interfaces(&interfaces);
  242. for (const KeyValue<String, Interface_Info> &E : interfaces) {
  243. for (const IPAddress &F : E.value.ip_addresses) {
  244. r_addresses->push_front(F);
  245. }
  246. }
  247. }
  248. void IP::_bind_methods() {
  249. ClassDB::bind_method(D_METHOD("resolve_hostname", "host", "ip_type"), &IP::resolve_hostname, DEFVAL(IP::TYPE_ANY));
  250. ClassDB::bind_method(D_METHOD("resolve_hostname_addresses", "host", "ip_type"), &IP::resolve_hostname_addresses, DEFVAL(IP::TYPE_ANY));
  251. ClassDB::bind_method(D_METHOD("resolve_hostname_queue_item", "host", "ip_type"), &IP::resolve_hostname_queue_item, DEFVAL(IP::TYPE_ANY));
  252. ClassDB::bind_method(D_METHOD("get_resolve_item_status", "id"), &IP::get_resolve_item_status);
  253. ClassDB::bind_method(D_METHOD("get_resolve_item_address", "id"), &IP::get_resolve_item_address);
  254. ClassDB::bind_method(D_METHOD("get_resolve_item_addresses", "id"), &IP::get_resolve_item_addresses);
  255. ClassDB::bind_method(D_METHOD("erase_resolve_item", "id"), &IP::erase_resolve_item);
  256. ClassDB::bind_method(D_METHOD("get_local_addresses"), &IP::_get_local_addresses);
  257. ClassDB::bind_method(D_METHOD("get_local_interfaces"), &IP::_get_local_interfaces);
  258. ClassDB::bind_method(D_METHOD("clear_cache", "hostname"), &IP::clear_cache, DEFVAL(""));
  259. BIND_ENUM_CONSTANT(RESOLVER_STATUS_NONE);
  260. BIND_ENUM_CONSTANT(RESOLVER_STATUS_WAITING);
  261. BIND_ENUM_CONSTANT(RESOLVER_STATUS_DONE);
  262. BIND_ENUM_CONSTANT(RESOLVER_STATUS_ERROR);
  263. BIND_CONSTANT(RESOLVER_MAX_QUERIES);
  264. BIND_CONSTANT(RESOLVER_INVALID_ID);
  265. BIND_ENUM_CONSTANT(TYPE_NONE);
  266. BIND_ENUM_CONSTANT(TYPE_IPV4);
  267. BIND_ENUM_CONSTANT(TYPE_IPV6);
  268. BIND_ENUM_CONSTANT(TYPE_ANY);
  269. }
  270. IP *IP::singleton = nullptr;
  271. IP *IP::get_singleton() {
  272. return singleton;
  273. }
  274. IP *(*IP::_create)() = nullptr;
  275. IP *IP::create() {
  276. ERR_FAIL_COND_V_MSG(singleton, nullptr, "IP singleton already exist.");
  277. ERR_FAIL_NULL_V(_create, nullptr);
  278. return _create();
  279. }
  280. IP::IP() {
  281. singleton = this;
  282. resolver = memnew(_IP_ResolverPrivate);
  283. resolver->thread_abort.clear();
  284. resolver->thread.start(_IP_ResolverPrivate::_thread_function, resolver);
  285. }
  286. IP::~IP() {
  287. resolver->thread_abort.set();
  288. resolver->sem.post();
  289. resolver->thread.wait_to_finish();
  290. memdelete(resolver);
  291. }