godot.cpp 15 KB

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