networked_multiplayer_enet.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659
  1. #include "os/os.h"
  2. #include "io/marshalls.h"
  3. #include "networked_multiplayer_enet.h"
  4. void NetworkedMultiplayerENet::set_transfer_mode(TransferMode p_mode) {
  5. transfer_mode=p_mode;
  6. }
  7. void NetworkedMultiplayerENet::set_target_peer(int p_peer){
  8. target_peer=p_peer;
  9. }
  10. int NetworkedMultiplayerENet::get_packet_peer() const{
  11. ERR_FAIL_COND_V(!active,1);
  12. ERR_FAIL_COND_V(incoming_packets.size()==0,1);
  13. return incoming_packets.front()->get().from;
  14. }
  15. Error NetworkedMultiplayerENet::create_server(int p_port, int p_max_clients, int p_in_bandwidth, int p_out_bandwidth){
  16. ERR_FAIL_COND_V(active,ERR_ALREADY_IN_USE);
  17. ENetAddress address;
  18. address.host = bind_ip;
  19. address.port = p_port;
  20. host = enet_host_create (& address /* the address to bind the server host to */,
  21. p_max_clients /* allow up to 32 clients and/or outgoing connections */,
  22. SYSCH_MAX /* allow up to SYSCH_MAX channels to be used */,
  23. p_in_bandwidth /* assume any amount of incoming bandwidth */,
  24. p_out_bandwidth /* assume any amount of outgoing bandwidth */);
  25. ERR_FAIL_COND_V(!host,ERR_CANT_CREATE);
  26. _setup_compressor();
  27. active=true;
  28. server=true;
  29. refuse_connections=false;
  30. unique_id=1;
  31. connection_status=CONNECTION_CONNECTED;
  32. return OK;
  33. }
  34. Error NetworkedMultiplayerENet::create_client(const IP_Address& p_ip, int p_port, int p_in_bandwidth, int p_out_bandwidth){
  35. ERR_FAIL_COND_V(active,ERR_ALREADY_IN_USE);
  36. host = enet_host_create (NULL /* create a client host */,
  37. 1 /* only allow 1 outgoing connection */,
  38. SYSCH_MAX /* allow up to SYSCH_MAX channels to be used */,
  39. p_in_bandwidth /* 56K modem with 56 Kbps downstream bandwidth */,
  40. p_out_bandwidth /* 56K modem with 14 Kbps upstream bandwidth */);
  41. ERR_FAIL_COND_V(!host,ERR_CANT_CREATE);
  42. _setup_compressor();
  43. ENetAddress address;
  44. address.host=p_ip.host;
  45. address.port=p_port;
  46. //enet_address_set_host (& address, "localhost");
  47. //address.port = p_port;
  48. unique_id=_gen_unique_id();
  49. /* Initiate the connection, allocating the enough channels */
  50. ENetPeer *peer = enet_host_connect (host, & address, SYSCH_MAX, unique_id);
  51. if (peer == NULL) {
  52. enet_host_destroy(host);
  53. ERR_FAIL_COND_V(!peer,ERR_CANT_CREATE);
  54. }
  55. //technically safe to ignore the peer or anything else.
  56. connection_status=CONNECTION_CONNECTING;
  57. active=true;
  58. server=false;
  59. refuse_connections=false;
  60. return OK;
  61. }
  62. void NetworkedMultiplayerENet::poll(){
  63. ERR_FAIL_COND(!active);
  64. _pop_current_packet();
  65. ENetEvent event;
  66. /* Wait up to 1000 milliseconds for an event. */
  67. while (true) {
  68. if (!host || !active) //might have been disconnected while emitting a notification
  69. return;
  70. int ret = enet_host_service (host, & event, 1);
  71. if (ret<0) {
  72. //error, do something?
  73. break;
  74. } else if (ret==0) {
  75. break;
  76. }
  77. switch (event.type)
  78. {
  79. case ENET_EVENT_TYPE_CONNECT: {
  80. /* Store any relevant client information here. */
  81. if (server && refuse_connections) {
  82. enet_peer_reset(event.peer);
  83. break;
  84. }
  85. IP_Address ip;
  86. ip.host=event.peer -> address.host;
  87. int *new_id = memnew( int );
  88. *new_id = event.data;
  89. if (*new_id==0) { //data zero is sent by server (enet won't let you configure this). Server is always 1
  90. *new_id=1;
  91. }
  92. event.peer->data=new_id;
  93. peer_map[*new_id]=event.peer;
  94. connection_status=CONNECTION_CONNECTED; //if connecting, this means it connected t something!
  95. emit_signal("peer_connected",*new_id);
  96. if (server) {
  97. //someone connected, let it know of all the peers available
  98. for (Map<int,ENetPeer*>::Element *E=peer_map.front();E;E=E->next()) {
  99. if (E->key()==*new_id)
  100. continue;
  101. //send existing peers to new peer
  102. ENetPacket * packet = enet_packet_create (NULL,8,ENET_PACKET_FLAG_RELIABLE);
  103. encode_uint32(SYSMSG_ADD_PEER,&packet->data[0]);
  104. encode_uint32(E->key(),&packet->data[4]);
  105. enet_peer_send(event.peer,SYSCH_CONFIG,packet);
  106. //send the new peer to existing peers
  107. packet = enet_packet_create (NULL,8,ENET_PACKET_FLAG_RELIABLE);
  108. encode_uint32(SYSMSG_ADD_PEER,&packet->data[0]);
  109. encode_uint32(*new_id,&packet->data[4]);
  110. enet_peer_send(E->get(),SYSCH_CONFIG,packet);
  111. }
  112. } else {
  113. emit_signal("connection_succeeded");
  114. }
  115. } break;
  116. case ENET_EVENT_TYPE_DISCONNECT: {
  117. /* Reset the peer's client information. */
  118. int *id = (int*)event.peer -> data;
  119. if (!id) {
  120. if (!server) {
  121. emit_signal("connection_failed");
  122. }
  123. } else {
  124. if (server) {
  125. //someone disconnected, let it know to everyone else
  126. for (Map<int,ENetPeer*>::Element *E=peer_map.front();E;E=E->next()) {
  127. if (E->key()==*id)
  128. continue;
  129. //send the new peer to existing peers
  130. ENetPacket* packet = enet_packet_create (NULL,8,ENET_PACKET_FLAG_RELIABLE);
  131. encode_uint32(SYSMSG_REMOVE_PEER,&packet->data[0]);
  132. encode_uint32(*id,&packet->data[4]);
  133. enet_peer_send(E->get(),SYSCH_CONFIG,packet);
  134. }
  135. } else if (!server) {
  136. emit_signal("server_disconnected");
  137. close_connection();
  138. return;
  139. }
  140. emit_signal("peer_disconnected",*id);
  141. peer_map.erase(*id);
  142. memdelete( id );
  143. }
  144. } break;
  145. case ENET_EVENT_TYPE_RECEIVE: {
  146. if (event.channelID==SYSCH_CONFIG) {
  147. //some config message
  148. ERR_CONTINUE( event.packet->dataLength < 8);
  149. // Only server can send config messages
  150. ERR_CONTINUE( server );
  151. int msg = decode_uint32(&event.packet->data[0]);
  152. int id = decode_uint32(&event.packet->data[4]);
  153. switch(msg) {
  154. case SYSMSG_ADD_PEER: {
  155. peer_map[id]=NULL;
  156. emit_signal("peer_connected",id);
  157. } break;
  158. case SYSMSG_REMOVE_PEER: {
  159. peer_map.erase(id);
  160. emit_signal("peer_disconnected",id);
  161. } break;
  162. }
  163. enet_packet_destroy(event.packet);
  164. } else if (event.channelID < SYSCH_MAX){
  165. Packet packet;
  166. packet.packet = event.packet;
  167. uint32_t *id = (uint32_t*)event.peer->data;
  168. ERR_CONTINUE(event.packet->dataLength<12)
  169. uint32_t source = decode_uint32(&event.packet->data[0]);
  170. int target = decode_uint32(&event.packet->data[4]);
  171. uint32_t flags = decode_uint32(&event.packet->data[8]);
  172. packet.from=source;
  173. if (server) {
  174. // Someone is cheating and trying to fake the source!
  175. ERR_CONTINUE(source!=*id);
  176. packet.from=*id;
  177. if (target==0) {
  178. //re-send the everyone but sender :|
  179. incoming_packets.push_back(packet);
  180. //and make copies for sending
  181. for (Map<int,ENetPeer*>::Element *E=peer_map.front();E;E=E->next()) {
  182. if (uint32_t(E->key())==source) //do not resend to self
  183. continue;
  184. ENetPacket* packet2 = enet_packet_create (packet.packet->data,packet.packet->dataLength,flags);
  185. enet_peer_send(E->get(),event.channelID,packet2);
  186. }
  187. } else if (target<0) {
  188. //to all but one
  189. //and make copies for sending
  190. for (Map<int,ENetPeer*>::Element *E=peer_map.front();E;E=E->next()) {
  191. if (uint32_t(E->key())==source || E->key()==-target) //do not resend to self, also do not send to excluded
  192. continue;
  193. ENetPacket* packet2 = enet_packet_create (packet.packet->data,packet.packet->dataLength,flags);
  194. enet_peer_send(E->get(),event.channelID,packet2);
  195. }
  196. if (-target != 1) {
  197. //server is not excluded
  198. incoming_packets.push_back(packet);
  199. } else {
  200. //server is excluded, erase packet
  201. enet_packet_destroy(packet.packet);
  202. }
  203. } else if (target==1) {
  204. //to myself and only myself
  205. incoming_packets.push_back(packet);
  206. } else {
  207. //to someone else, specifically
  208. ERR_CONTINUE(!peer_map.has(target));
  209. enet_peer_send(peer_map[target],event.channelID,packet.packet);
  210. }
  211. } else {
  212. incoming_packets.push_back(packet);
  213. }
  214. //destroy packet later..
  215. } else {
  216. ERR_CONTINUE(true);
  217. }
  218. }break;
  219. case ENET_EVENT_TYPE_NONE: {
  220. //do nothing
  221. } break;
  222. }
  223. }
  224. }
  225. bool NetworkedMultiplayerENet::is_server() const {
  226. ERR_FAIL_COND_V(!active,false);
  227. return server;
  228. }
  229. void NetworkedMultiplayerENet::close_connection() {
  230. if (!active)
  231. return;
  232. _pop_current_packet();
  233. bool peers_disconnected=false;
  234. for (Map<int,ENetPeer*>::Element *E=peer_map.front();E;E=E->next()) {
  235. if (E->get()) {
  236. enet_peer_disconnect_now(E->get(),unique_id);
  237. peers_disconnected=true;
  238. }
  239. }
  240. if (peers_disconnected) {
  241. enet_host_flush(host);
  242. OS::get_singleton()->delay_usec(100); //wait 100ms for disconnection packets to send
  243. }
  244. enet_host_destroy(host);
  245. active=false;
  246. incoming_packets.clear();
  247. unique_id=1; //server is 1
  248. connection_status=CONNECTION_DISCONNECTED;
  249. }
  250. int NetworkedMultiplayerENet::get_available_packet_count() const {
  251. return incoming_packets.size();
  252. }
  253. Error NetworkedMultiplayerENet::get_packet(const uint8_t **r_buffer,int &r_buffer_size) const{
  254. ERR_FAIL_COND_V(incoming_packets.size()==0,ERR_UNAVAILABLE);
  255. _pop_current_packet();
  256. current_packet = incoming_packets.front()->get();
  257. incoming_packets.pop_front();
  258. *r_buffer=(const uint8_t*)(&current_packet.packet->data[12]);
  259. r_buffer_size=current_packet.packet->dataLength-12;
  260. return OK;
  261. }
  262. Error NetworkedMultiplayerENet::put_packet(const uint8_t *p_buffer,int p_buffer_size){
  263. ERR_FAIL_COND_V(!active,ERR_UNCONFIGURED);
  264. ERR_FAIL_COND_V(connection_status!=CONNECTION_CONNECTED,ERR_UNCONFIGURED);
  265. int packet_flags=0;
  266. int channel=SYSCH_RELIABLE;
  267. switch(transfer_mode) {
  268. case TRANSFER_MODE_UNRELIABLE: {
  269. packet_flags=ENET_PACKET_FLAG_UNSEQUENCED;
  270. channel=SYSCH_UNRELIABLE;
  271. } break;
  272. case TRANSFER_MODE_UNRELIABLE_ORDERED: {
  273. packet_flags=0;
  274. channel=SYSCH_UNRELIABLE;
  275. } break;
  276. case TRANSFER_MODE_RELIABLE: {
  277. packet_flags=ENET_PACKET_FLAG_RELIABLE;
  278. channel=SYSCH_RELIABLE;
  279. } break;
  280. }
  281. Map<int,ENetPeer*>::Element *E=NULL;
  282. if (target_peer!=0) {
  283. E = peer_map.find(ABS(target_peer));
  284. if (!E) {
  285. ERR_EXPLAIN("Invalid Target Peer: "+itos(target_peer));
  286. ERR_FAIL_V(ERR_INVALID_PARAMETER);
  287. }
  288. }
  289. ENetPacket * packet = enet_packet_create (NULL,p_buffer_size+12,packet_flags);
  290. encode_uint32(unique_id,&packet->data[0]); //source ID
  291. encode_uint32(target_peer,&packet->data[4]); //dest ID
  292. encode_uint32(packet_flags,&packet->data[8]); //dest ID
  293. copymem(&packet->data[12],p_buffer,p_buffer_size);
  294. if (server) {
  295. if (target_peer==0) {
  296. enet_host_broadcast(host,channel,packet);
  297. } else if (target_peer<0) {
  298. //send to all but one
  299. //and make copies for sending
  300. int exclude=-target_peer;
  301. for (Map<int,ENetPeer*>::Element *F=peer_map.front();F;F=F->next()) {
  302. if (F->key()==exclude) // exclude packet
  303. continue;
  304. ENetPacket* packet2 = enet_packet_create (packet->data,packet->dataLength,packet_flags);
  305. enet_peer_send(F->get(),channel,packet2);
  306. }
  307. enet_packet_destroy(packet); //original packet no longer needed
  308. } else {
  309. enet_peer_send (E->get(), channel, packet);
  310. }
  311. } else {
  312. ERR_FAIL_COND_V(!peer_map.has(1),ERR_BUG);
  313. enet_peer_send (peer_map[1], channel, packet); //send to server for broadcast..
  314. }
  315. enet_host_flush(host);
  316. return OK;
  317. }
  318. int NetworkedMultiplayerENet::get_max_packet_size() const {
  319. return 1<<24; //anything is good
  320. }
  321. void NetworkedMultiplayerENet::_pop_current_packet() const {
  322. if (current_packet.packet) {
  323. enet_packet_destroy(current_packet.packet);
  324. current_packet.packet=NULL;
  325. current_packet.from=0;
  326. }
  327. }
  328. NetworkedMultiplayerPeer::ConnectionStatus NetworkedMultiplayerENet::get_connection_status() const {
  329. return connection_status;
  330. }
  331. uint32_t NetworkedMultiplayerENet::_gen_unique_id() const {
  332. uint32_t hash = 0;
  333. while (hash==0 || hash==1) {
  334. hash = hash_djb2_one_32(
  335. (uint32_t)OS::get_singleton()->get_ticks_usec() );
  336. hash = hash_djb2_one_32(
  337. (uint32_t)OS::get_singleton()->get_unix_time(), hash );
  338. hash = hash_djb2_one_32(
  339. (uint32_t)OS::get_singleton()->get_data_dir().hash64(), hash );
  340. //hash = hash_djb2_one_32(
  341. // (uint32_t)OS::get_singleton()->get_unique_ID().hash64(), hash );
  342. hash = hash_djb2_one_32(
  343. (uint32_t)((uint64_t)this), hash ); //rely on aslr heap
  344. hash = hash_djb2_one_32(
  345. (uint32_t)((uint64_t)&hash), hash ); //rely on aslr stack
  346. hash=hash&0x7FFFFFFF; // make it compatible with unsigned, since negatie id is used for exclusion
  347. }
  348. return hash;
  349. }
  350. int NetworkedMultiplayerENet::get_unique_id() const {
  351. ERR_FAIL_COND_V(!active,0);
  352. return unique_id;
  353. }
  354. void NetworkedMultiplayerENet::set_refuse_new_connections(bool p_enable) {
  355. refuse_connections=p_enable;
  356. }
  357. bool NetworkedMultiplayerENet::is_refusing_new_connections() const {
  358. return refuse_connections;
  359. }
  360. void NetworkedMultiplayerENet::set_compression_mode(CompressionMode p_mode) {
  361. compression_mode=p_mode;
  362. }
  363. NetworkedMultiplayerENet::CompressionMode NetworkedMultiplayerENet::get_compression_mode() const{
  364. return compression_mode;
  365. }
  366. size_t NetworkedMultiplayerENet::enet_compress(void * context, const ENetBuffer * inBuffers, size_t inBufferCount, size_t inLimit, enet_uint8 * outData, size_t outLimit) {
  367. NetworkedMultiplayerENet *enet = (NetworkedMultiplayerENet*)(context);
  368. if (size_t(enet->src_compressor_mem.size())<inLimit) {
  369. enet->src_compressor_mem.resize( inLimit );
  370. }
  371. int total = inLimit;
  372. int ofs=0;
  373. while(total) {
  374. for(size_t i=0;i<inBufferCount;i++) {
  375. int to_copy = MIN(total,int(inBuffers[i].dataLength));
  376. copymem(&enet->src_compressor_mem[ofs],inBuffers[i].data,to_copy);
  377. ofs+=to_copy;
  378. total-=to_copy;
  379. }
  380. }
  381. Compression::Mode mode;
  382. switch(enet->compression_mode) {
  383. case COMPRESS_FASTLZ: {
  384. mode=Compression::MODE_FASTLZ;
  385. } break;
  386. case COMPRESS_ZLIB: {
  387. mode=Compression::MODE_DEFLATE;
  388. } break;
  389. default: { ERR_FAIL_V(0); }
  390. }
  391. int req_size = Compression::get_max_compressed_buffer_size(ofs,mode);
  392. if (enet->dst_compressor_mem.size()<req_size) {
  393. enet->dst_compressor_mem.resize(req_size);
  394. }
  395. int ret=Compression::compress(enet->dst_compressor_mem.ptr(),enet->src_compressor_mem.ptr(),ofs,mode);
  396. if (ret<0)
  397. return 0;
  398. if (ret>int(outLimit))
  399. return 0; //do not bother
  400. copymem(outData,enet->dst_compressor_mem.ptr(),ret);
  401. return ret;
  402. }
  403. size_t NetworkedMultiplayerENet::enet_decompress (void * context, const enet_uint8 * inData, size_t inLimit, enet_uint8 * outData, size_t outLimit){
  404. NetworkedMultiplayerENet *enet = (NetworkedMultiplayerENet*)(context);
  405. int ret = -1;
  406. switch(enet->compression_mode) {
  407. case COMPRESS_FASTLZ: {
  408. ret=Compression::decompress(outData,outLimit,inData,inLimit,Compression::MODE_FASTLZ);
  409. } break;
  410. case COMPRESS_ZLIB: {
  411. ret=Compression::decompress(outData,outLimit,inData,inLimit,Compression::MODE_DEFLATE);
  412. } break;
  413. default: {}
  414. }
  415. if (ret<0) {
  416. return 0;
  417. } else {
  418. return ret;
  419. }
  420. }
  421. void NetworkedMultiplayerENet::_setup_compressor() {
  422. switch(compression_mode) {
  423. case COMPRESS_NONE: {
  424. enet_host_compress(host,NULL);
  425. } break;
  426. case COMPRESS_RANGE_CODER: {
  427. enet_host_compress_with_range_coder(host);
  428. } break;
  429. case COMPRESS_FASTLZ:
  430. case COMPRESS_ZLIB: {
  431. enet_host_compress(host,&enet_compressor);
  432. } break;
  433. }
  434. }
  435. void NetworkedMultiplayerENet::enet_compressor_destroy(void * context){
  436. //do none
  437. }
  438. void NetworkedMultiplayerENet::_bind_methods() {
  439. ObjectTypeDB::bind_method(_MD("create_server","port","max_clients","in_bandwidth","out_bandwidth"),&NetworkedMultiplayerENet::create_server,DEFVAL(32),DEFVAL(0),DEFVAL(0));
  440. ObjectTypeDB::bind_method(_MD("create_client","ip","port","in_bandwidth","out_bandwidth"),&NetworkedMultiplayerENet::create_client,DEFVAL(0),DEFVAL(0));
  441. ObjectTypeDB::bind_method(_MD("close_connection"),&NetworkedMultiplayerENet::close_connection);
  442. ObjectTypeDB::bind_method(_MD("set_compression_mode","mode"),&NetworkedMultiplayerENet::set_compression_mode);
  443. ObjectTypeDB::bind_method(_MD("get_compression_mode"),&NetworkedMultiplayerENet::get_compression_mode);
  444. ObjectTypeDB::bind_method(_MD("set_bind_ip", "ip"),&NetworkedMultiplayerENet::set_bind_ip);
  445. BIND_CONSTANT( COMPRESS_NONE );
  446. BIND_CONSTANT( COMPRESS_RANGE_CODER );
  447. BIND_CONSTANT( COMPRESS_FASTLZ );
  448. BIND_CONSTANT( COMPRESS_ZLIB );
  449. }
  450. NetworkedMultiplayerENet::NetworkedMultiplayerENet(){
  451. active=false;
  452. server=false;
  453. refuse_connections=false;
  454. unique_id=0;
  455. target_peer=0;
  456. current_packet.packet=NULL;
  457. transfer_mode=TRANSFER_MODE_RELIABLE;
  458. connection_status=CONNECTION_DISCONNECTED;
  459. compression_mode=COMPRESS_NONE;
  460. enet_compressor.context=this;
  461. enet_compressor.compress=enet_compress;
  462. enet_compressor.decompress=enet_decompress;
  463. enet_compressor.destroy=enet_compressor_destroy;
  464. bind_ip=ENET_HOST_ANY;
  465. }
  466. NetworkedMultiplayerENet::~NetworkedMultiplayerENet(){
  467. close_connection();
  468. }
  469. // sets IP for ENet to bind when using create_server
  470. // if no IP is set, then ENet bind to ENET_HOST_ANY
  471. void NetworkedMultiplayerENet::set_bind_ip(const IP_Address& p_ip){
  472. bind_ip=p_ip.host;
  473. }