godot.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600
  1. /**************************************************************************/
  2. /* godot.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. /**
  31. @file godot.cpp
  32. @brief ENet Godot specific functions
  33. */
  34. #include "core/io/dtls_server.h"
  35. #include "core/io/ip.h"
  36. #include "core/io/net_socket.h"
  37. #include "core/io/packet_peer_dtls.h"
  38. #include "core/io/udp_server.h"
  39. #include "core/os/os.h"
  40. // This must be last for windows to compile (tested with MinGW)
  41. #include "enet/enet.h"
  42. /// Abstract ENet interface for UDP/DTLS.
  43. class ENetGodotSocket {
  44. public:
  45. virtual Error bind(IPAddress p_ip, uint16_t p_port) = 0;
  46. virtual Error get_socket_address(IPAddress *r_ip, uint16_t *r_port) = 0;
  47. virtual Error sendto(const uint8_t *p_buffer, int p_len, int &r_sent, IPAddress p_ip, uint16_t p_port) = 0;
  48. virtual Error recvfrom(uint8_t *p_buffer, int p_len, int &r_read, IPAddress &r_ip, uint16_t &r_port) = 0;
  49. virtual int set_option(ENetSocketOption p_option, int p_value) = 0;
  50. virtual void close() = 0;
  51. virtual void set_refuse_new_connections(bool p_enable) {} /* Only used by dtls server */
  52. virtual bool can_upgrade() { return false; } /* Only true in ENetUDP */
  53. virtual ~ENetGodotSocket() {}
  54. };
  55. class ENetDTLSClient;
  56. class ENetDTLSServer;
  57. /// NetSocket interface
  58. class ENetUDP : public ENetGodotSocket {
  59. friend class ENetDTLSClient;
  60. friend class ENetDTLSServer;
  61. private:
  62. Ref<NetSocket> sock;
  63. IPAddress local_address;
  64. bool bound = false;
  65. public:
  66. ENetUDP() {
  67. sock = Ref<NetSocket>(NetSocket::create());
  68. IP::Type ip_type = IP::TYPE_ANY;
  69. sock->open(NetSocket::TYPE_UDP, ip_type);
  70. }
  71. ~ENetUDP() {
  72. sock->close();
  73. }
  74. bool can_upgrade() {
  75. return true;
  76. }
  77. Error bind(IPAddress p_ip, uint16_t p_port) {
  78. local_address = p_ip;
  79. bound = true;
  80. return sock->bind(p_ip, p_port);
  81. }
  82. Error get_socket_address(IPAddress *r_ip, uint16_t *r_port) {
  83. Error err = sock->get_socket_address(r_ip, r_port);
  84. if (bound) {
  85. *r_ip = local_address;
  86. }
  87. return err;
  88. }
  89. Error sendto(const uint8_t *p_buffer, int p_len, int &r_sent, IPAddress p_ip, uint16_t p_port) {
  90. return sock->sendto(p_buffer, p_len, r_sent, p_ip, p_port);
  91. }
  92. Error recvfrom(uint8_t *p_buffer, int p_len, int &r_read, IPAddress &r_ip, uint16_t &r_port) {
  93. Error err = sock->poll(NetSocket::POLL_TYPE_IN, 0);
  94. if (err != OK) {
  95. return err;
  96. }
  97. return sock->recvfrom(p_buffer, p_len, r_read, r_ip, r_port);
  98. }
  99. int set_option(ENetSocketOption p_option, int p_value) {
  100. switch (p_option) {
  101. case ENET_SOCKOPT_NONBLOCK: {
  102. sock->set_blocking_enabled(p_value ? false : true);
  103. return 0;
  104. } break;
  105. case ENET_SOCKOPT_BROADCAST: {
  106. sock->set_broadcasting_enabled(p_value ? true : false);
  107. return 0;
  108. } break;
  109. case ENET_SOCKOPT_REUSEADDR: {
  110. sock->set_reuse_address_enabled(p_value ? true : false);
  111. return 0;
  112. } break;
  113. case ENET_SOCKOPT_RCVBUF: {
  114. return -1;
  115. } break;
  116. case ENET_SOCKOPT_SNDBUF: {
  117. return -1;
  118. } break;
  119. case ENET_SOCKOPT_RCVTIMEO: {
  120. return -1;
  121. } break;
  122. case ENET_SOCKOPT_SNDTIMEO: {
  123. return -1;
  124. } break;
  125. case ENET_SOCKOPT_NODELAY: {
  126. sock->set_tcp_no_delay_enabled(p_value ? true : false);
  127. return 0;
  128. } break;
  129. }
  130. return -1;
  131. }
  132. void close() {
  133. sock->close();
  134. local_address.clear();
  135. }
  136. };
  137. /// DTLS Client ENet interface
  138. class ENetDTLSClient : public ENetGodotSocket {
  139. bool connected = false;
  140. Ref<PacketPeerUDP> udp;
  141. Ref<PacketPeerDTLS> dtls;
  142. Ref<TLSOptions> tls_options;
  143. String for_hostname;
  144. IPAddress local_address;
  145. public:
  146. ENetDTLSClient(ENetUDP *p_base, String p_for_hostname, Ref<TLSOptions> p_options) {
  147. for_hostname = p_for_hostname;
  148. tls_options = p_options;
  149. udp.instantiate();
  150. dtls = Ref<PacketPeerDTLS>(PacketPeerDTLS::create());
  151. if (p_base->bound) {
  152. uint16_t port;
  153. p_base->get_socket_address(&local_address, &port);
  154. p_base->close();
  155. bind(local_address, port);
  156. }
  157. }
  158. ~ENetDTLSClient() {
  159. close();
  160. }
  161. Error bind(IPAddress p_ip, uint16_t p_port) {
  162. local_address = p_ip;
  163. return udp->bind(p_port, p_ip);
  164. }
  165. Error get_socket_address(IPAddress *r_ip, uint16_t *r_port) {
  166. if (!udp->is_bound()) {
  167. return ERR_UNCONFIGURED;
  168. }
  169. *r_ip = local_address;
  170. *r_port = udp->get_local_port();
  171. return OK;
  172. }
  173. Error sendto(const uint8_t *p_buffer, int p_len, int &r_sent, IPAddress p_ip, uint16_t p_port) {
  174. if (!connected) {
  175. udp->connect_to_host(p_ip, p_port);
  176. if (dtls->connect_to_peer(udp, for_hostname, tls_options)) {
  177. return FAILED;
  178. }
  179. connected = true;
  180. }
  181. dtls->poll();
  182. if (dtls->get_status() == PacketPeerDTLS::STATUS_HANDSHAKING) {
  183. return ERR_BUSY;
  184. } else if (dtls->get_status() != PacketPeerDTLS::STATUS_CONNECTED) {
  185. return FAILED;
  186. }
  187. r_sent = p_len;
  188. return dtls->put_packet(p_buffer, p_len);
  189. }
  190. Error recvfrom(uint8_t *p_buffer, int p_len, int &r_read, IPAddress &r_ip, uint16_t &r_port) {
  191. dtls->poll();
  192. if (dtls->get_status() == PacketPeerDTLS::STATUS_HANDSHAKING) {
  193. return ERR_BUSY;
  194. }
  195. if (dtls->get_status() != PacketPeerDTLS::STATUS_CONNECTED) {
  196. return FAILED;
  197. }
  198. int pc = dtls->get_available_packet_count();
  199. if (pc == 0) {
  200. return ERR_BUSY;
  201. } else if (pc < 0) {
  202. return FAILED;
  203. }
  204. const uint8_t *buffer;
  205. Error err = dtls->get_packet(&buffer, r_read);
  206. ERR_FAIL_COND_V(err != OK, err);
  207. ERR_FAIL_COND_V(p_len < r_read, ERR_OUT_OF_MEMORY);
  208. memcpy(p_buffer, buffer, r_read);
  209. r_ip = udp->get_packet_address();
  210. r_port = udp->get_packet_port();
  211. return err;
  212. }
  213. int set_option(ENetSocketOption p_option, int p_value) {
  214. return -1;
  215. }
  216. void close() {
  217. dtls->disconnect_from_peer();
  218. udp->close();
  219. }
  220. };
  221. /// DTLSServer - ENet interface
  222. class ENetDTLSServer : public ENetGodotSocket {
  223. Ref<DTLSServer> server;
  224. Ref<UDPServer> udp_server;
  225. HashMap<String, Ref<PacketPeerDTLS>> peers;
  226. int last_service = 0;
  227. IPAddress local_address;
  228. public:
  229. ENetDTLSServer(ENetUDP *p_base, Ref<TLSOptions> p_options) {
  230. udp_server.instantiate();
  231. if (p_base->bound) {
  232. uint16_t port;
  233. p_base->get_socket_address(&local_address, &port);
  234. p_base->close();
  235. bind(local_address, port);
  236. }
  237. server = Ref<DTLSServer>(DTLSServer::create());
  238. server->setup(p_options);
  239. }
  240. ~ENetDTLSServer() {
  241. close();
  242. }
  243. void set_refuse_new_connections(bool p_refuse) {
  244. udp_server->set_max_pending_connections(p_refuse ? 0 : 16);
  245. }
  246. Error bind(IPAddress p_ip, uint16_t p_port) {
  247. local_address = p_ip;
  248. return udp_server->listen(p_port, p_ip);
  249. }
  250. Error get_socket_address(IPAddress *r_ip, uint16_t *r_port) {
  251. if (!udp_server->is_listening()) {
  252. return ERR_UNCONFIGURED;
  253. }
  254. *r_ip = local_address;
  255. *r_port = udp_server->get_local_port();
  256. return OK;
  257. }
  258. Error sendto(const uint8_t *p_buffer, int p_len, int &r_sent, IPAddress p_ip, uint16_t p_port) {
  259. String key = String(p_ip) + ":" + itos(p_port);
  260. ERR_FAIL_COND_V(!peers.has(key), ERR_UNAVAILABLE);
  261. Ref<PacketPeerDTLS> peer = peers[key];
  262. Error err = peer->put_packet(p_buffer, p_len);
  263. if (err == OK) {
  264. r_sent = p_len;
  265. } else if (err == ERR_BUSY) {
  266. r_sent = 0;
  267. } else {
  268. r_sent = -1;
  269. }
  270. return err;
  271. }
  272. Error recvfrom(uint8_t *p_buffer, int p_len, int &r_read, IPAddress &r_ip, uint16_t &r_port) {
  273. udp_server->poll();
  274. // TODO limits? Maybe we can better enforce allowed connections!
  275. if (udp_server->is_connection_available()) {
  276. Ref<PacketPeerUDP> udp = udp_server->take_connection();
  277. IPAddress peer_ip = udp->get_packet_address();
  278. int peer_port = udp->get_packet_port();
  279. Ref<PacketPeerDTLS> peer = server->take_connection(udp);
  280. PacketPeerDTLS::Status status = peer->get_status();
  281. if (status == PacketPeerDTLS::STATUS_HANDSHAKING || status == PacketPeerDTLS::STATUS_CONNECTED) {
  282. String key = String(peer_ip) + ":" + itos(peer_port);
  283. peers[key] = peer;
  284. }
  285. }
  286. List<String> remove;
  287. Error err = ERR_BUSY;
  288. // TODO this needs to be fair!
  289. for (KeyValue<String, Ref<PacketPeerDTLS>> & E : peers) {
  290. Ref<PacketPeerDTLS> peer = E.value;
  291. peer->poll();
  292. if (peer->get_status() == PacketPeerDTLS::STATUS_HANDSHAKING) {
  293. continue;
  294. } else if (peer->get_status() != PacketPeerDTLS::STATUS_CONNECTED) {
  295. // Peer disconnected, removing it.
  296. remove.push_back(E.key);
  297. continue;
  298. }
  299. if (peer->get_available_packet_count() > 0) {
  300. const uint8_t *buffer;
  301. err = peer->get_packet(&buffer, r_read);
  302. if (err != OK || p_len < r_read) {
  303. // Something wrong with this peer, removing it.
  304. remove.push_back(E.key);
  305. err = FAILED;
  306. continue;
  307. }
  308. Vector<String> s = E.key.rsplit(":", false, 1);
  309. ERR_CONTINUE(s.size() != 2); // BUG!
  310. memcpy(p_buffer, buffer, r_read);
  311. r_ip = s[0];
  312. r_port = s[1].to_int();
  313. break; // err = OK
  314. }
  315. }
  316. // Remove disconnected peers from map.
  317. for (String &E : remove) {
  318. peers.erase(E);
  319. }
  320. return err; // OK, ERR_BUSY, or possibly an error.
  321. }
  322. int set_option(ENetSocketOption p_option, int p_value) {
  323. return -1;
  324. }
  325. void close() {
  326. for (KeyValue<String, Ref<PacketPeerDTLS>> &E : peers) {
  327. E.value->disconnect_from_peer();
  328. }
  329. peers.clear();
  330. udp_server->stop();
  331. server->stop();
  332. local_address.clear();
  333. }
  334. };
  335. static enet_uint32 timeBase = 0;
  336. int enet_initialize(void) {
  337. return 0;
  338. }
  339. void enet_deinitialize(void) {
  340. }
  341. enet_uint32 enet_host_random_seed(void) {
  342. return (enet_uint32)OS::get_singleton()->get_unix_time();
  343. }
  344. enet_uint32 enet_time_get(void) {
  345. return OS::get_singleton()->get_ticks_msec() - timeBase;
  346. }
  347. void enet_time_set(enet_uint32 newTimeBase) {
  348. timeBase = OS::get_singleton()->get_ticks_msec() - newTimeBase;
  349. }
  350. int enet_address_set_host(ENetAddress *address, const char *name) {
  351. IPAddress ip = IP::get_singleton()->resolve_hostname(name);
  352. ERR_FAIL_COND_V(!ip.is_valid(), -1);
  353. enet_address_set_ip(address, ip.get_ipv6(), 16);
  354. return 0;
  355. }
  356. void enet_address_set_ip(ENetAddress *address, const uint8_t *ip, size_t size) {
  357. int len = size > 16 ? 16 : size;
  358. memset(address->host, 0, 16);
  359. memcpy(address->host, ip, len);
  360. }
  361. int enet_address_get_host_ip(const ENetAddress *address, char *name, size_t nameLength) {
  362. return -1;
  363. }
  364. int enet_address_get_host(const ENetAddress *address, char *name, size_t nameLength) {
  365. return -1;
  366. }
  367. ENetSocket enet_socket_create(ENetSocketType type) {
  368. ENetUDP *socket = memnew(ENetUDP);
  369. return socket;
  370. }
  371. int enet_host_dtls_server_setup(ENetHost *host, void *p_options) {
  372. ERR_FAIL_COND_V_MSG(!DTLSServer::is_available(), -1, "DTLS server is not available in this build.");
  373. ENetGodotSocket *sock = (ENetGodotSocket *)host->socket;
  374. if (!sock->can_upgrade()) {
  375. return -1;
  376. }
  377. host->socket = memnew(ENetDTLSServer(static_cast<ENetUDP *>(sock), Ref<TLSOptions>(static_cast<TLSOptions *>(p_options))));
  378. memdelete(sock);
  379. return 0;
  380. }
  381. int enet_host_dtls_client_setup(ENetHost *host, const char *p_for_hostname, void *p_options) {
  382. ERR_FAIL_COND_V_MSG(!PacketPeerDTLS::is_available(), -1, "DTLS is not available in this build.");
  383. ENetGodotSocket *sock = (ENetGodotSocket *)host->socket;
  384. if (!sock->can_upgrade()) {
  385. return -1;
  386. }
  387. host->socket = memnew(ENetDTLSClient(static_cast<ENetUDP *>(sock), String::utf8(p_for_hostname), Ref<TLSOptions>(static_cast<TLSOptions *>(p_options))));
  388. memdelete(sock);
  389. return 0;
  390. }
  391. void enet_host_refuse_new_connections(ENetHost *host, int p_refuse) {
  392. ERR_FAIL_COND(!host->socket);
  393. ((ENetGodotSocket *)host->socket)->set_refuse_new_connections(p_refuse);
  394. }
  395. int enet_socket_bind(ENetSocket socket, const ENetAddress *address) {
  396. IPAddress ip;
  397. if (address->wildcard) {
  398. ip = IPAddress("*");
  399. } else {
  400. ip.set_ipv6(address->host);
  401. }
  402. ENetGodotSocket *sock = (ENetGodotSocket *)socket;
  403. if (sock->bind(ip, address->port) != OK) {
  404. return -1;
  405. }
  406. return 0;
  407. }
  408. void enet_socket_destroy(ENetSocket socket) {
  409. ENetGodotSocket *sock = (ENetGodotSocket *)socket;
  410. sock->close();
  411. memdelete(sock);
  412. }
  413. int enet_socket_send(ENetSocket socket, const ENetAddress *address, const ENetBuffer *buffers, size_t bufferCount) {
  414. ERR_FAIL_COND_V(address == nullptr, -1);
  415. ENetGodotSocket *sock = (ENetGodotSocket *)socket;
  416. IPAddress dest;
  417. Error err;
  418. size_t i = 0;
  419. dest.set_ipv6(address->host);
  420. // Create a single packet.
  421. Vector<uint8_t> out;
  422. uint8_t *w;
  423. int size = 0;
  424. int pos = 0;
  425. for (i = 0; i < bufferCount; i++) {
  426. size += buffers[i].dataLength;
  427. }
  428. out.resize(size);
  429. w = out.ptrw();
  430. for (i = 0; i < bufferCount; i++) {
  431. memcpy(&w[pos], buffers[i].data, buffers[i].dataLength);
  432. pos += buffers[i].dataLength;
  433. }
  434. int sent = 0;
  435. err = sock->sendto((const uint8_t *)&w[0], size, sent, dest, address->port);
  436. if (err != OK) {
  437. if (err == ERR_BUSY) { // Blocking call
  438. return 0;
  439. }
  440. WARN_PRINT("Sending failed!");
  441. return -1;
  442. }
  443. return sent;
  444. }
  445. int enet_socket_receive(ENetSocket socket, ENetAddress *address, ENetBuffer *buffers, size_t bufferCount) {
  446. ERR_FAIL_COND_V(bufferCount != 1, -1);
  447. ENetGodotSocket *sock = (ENetGodotSocket *)socket;
  448. int read;
  449. IPAddress ip;
  450. Error err = sock->recvfrom((uint8_t *)buffers[0].data, buffers[0].dataLength, read, ip, address->port);
  451. if (err == ERR_BUSY) {
  452. return 0;
  453. }
  454. if (err == ERR_OUT_OF_MEMORY) {
  455. // A packet above the ENET_PROTOCOL_MAXIMUM_MTU was received.
  456. return -2;
  457. }
  458. if (err != OK) {
  459. return -1;
  460. }
  461. enet_address_set_ip(address, ip.get_ipv6(), 16);
  462. return read;
  463. }
  464. int enet_socket_get_address (ENetSocket socket, ENetAddress * address) {
  465. IPAddress ip;
  466. uint16_t port;
  467. ENetGodotSocket *sock = (ENetGodotSocket *)socket;
  468. if (sock->get_socket_address(&ip, &port) != OK) {
  469. return -1;
  470. }
  471. enet_address_set_ip(address, ip.get_ipv6(), 16);
  472. address->port = port;
  473. return 0;
  474. }
  475. // Not implemented
  476. int enet_socket_wait(ENetSocket socket, enet_uint32 *condition, enet_uint32 timeout) {
  477. return 0; // do we need this function?
  478. }
  479. int enet_socketset_select(ENetSocket maxSocket, ENetSocketSet *readSet, ENetSocketSet *writeSet, enet_uint32 timeout) {
  480. return -1;
  481. }
  482. int enet_socket_listen(ENetSocket socket, int backlog) {
  483. return -1;
  484. }
  485. int enet_socket_set_option(ENetSocket socket, ENetSocketOption option, int value) {
  486. ENetGodotSocket *sock = (ENetGodotSocket *)socket;
  487. return sock->set_option(option, value);
  488. }
  489. int enet_socket_get_option(ENetSocket socket, ENetSocketOption option, int *value) {
  490. return -1;
  491. }
  492. int enet_socket_connect(ENetSocket socket, const ENetAddress *address) {
  493. return -1;
  494. }
  495. ENetSocket enet_socket_accept(ENetSocket socket, ENetAddress *address) {
  496. return nullptr;
  497. }
  498. int enet_socket_shutdown(ENetSocket socket, ENetSocketShutdown how) {
  499. return -1;
  500. }