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/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. MutexLock lock(mutex);
  71. List<IPAddress> response;
  72. String hostname = queue[i].hostname;
  73. IP::Type type = queue[i].type;
  74. lock.temp_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. lock.temp_relock();
  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(const 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. {
  112. MutexLock lock(resolver->mutex);
  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. lock.temp_unlock();
  119. _resolve_hostname(res, p_hostname, p_type);
  120. lock.temp_relock();
  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. }
  127. PackedStringArray result;
  128. for (const IPAddress &E : res) {
  129. result.push_back(String(E));
  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<IPAddress>();
  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. IPAddress IP::get_resolve_item_address(ResolverID p_id) const {
  167. 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));
  168. MutexLock lock(resolver->mutex);
  169. if (resolver->queue[p_id].status.get() != IP::RESOLVER_STATUS_DONE) {
  170. ERR_PRINT(vformat("Resolve of '%s' didn't complete yet.", resolver->queue[p_id].hostname));
  171. return IPAddress();
  172. }
  173. List<IPAddress> res = resolver->queue[p_id].response;
  174. for (const IPAddress &E : res) {
  175. if (E.is_valid()) {
  176. return E;
  177. }
  178. }
  179. return IPAddress();
  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(vformat("Resolve of '%s' didn't complete yet.", resolver->queue[p_id].hostname));
  186. return Array();
  187. }
  188. List<IPAddress> res = resolver->queue[p_id].response;
  189. Array result;
  190. for (const IPAddress &E : res) {
  191. if (E.is_valid()) {
  192. result.push_back(String(E));
  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.is_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. PackedStringArray IP::_get_local_addresses() const {
  213. PackedStringArray addresses;
  214. List<IPAddress> ip_addresses;
  215. get_local_addresses(&ip_addresses);
  216. for (const IPAddress &E : ip_addresses) {
  217. addresses.push_back(E);
  218. }
  219. return addresses;
  220. }
  221. TypedArray<Dictionary> IP::_get_local_interfaces() const {
  222. TypedArray<Dictionary> results;
  223. HashMap<String, Interface_Info> interfaces;
  224. get_local_interfaces(&interfaces);
  225. for (KeyValue<String, Interface_Info> &E : interfaces) {
  226. Interface_Info &c = E.value;
  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 IPAddress &F : c.ip_addresses) {
  233. ips.push_front(F);
  234. }
  235. rc["addresses"] = ips;
  236. results.push_front(rc);
  237. }
  238. return results;
  239. }
  240. void IP::get_local_addresses(List<IPAddress> *r_addresses) const {
  241. HashMap<String, Interface_Info> interfaces;
  242. get_local_interfaces(&interfaces);
  243. for (const KeyValue<String, Interface_Info> &E : interfaces) {
  244. for (const IPAddress &F : E.value.ip_addresses) {
  245. r_addresses->push_front(F);
  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_NULL_V(_create, nullptr);
  279. return _create();
  280. }
  281. IP::IP() {
  282. singleton = this;
  283. resolver = memnew(_IP_ResolverPrivate);
  284. resolver->thread_abort.clear();
  285. resolver->thread.start(_IP_ResolverPrivate::_thread_function, resolver);
  286. }
  287. IP::~IP() {
  288. resolver->thread_abort.set();
  289. resolver->sem.post();
  290. resolver->thread.wait_to_finish();
  291. memdelete(resolver);
  292. }