connection.h 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936
  1. /*
  2. Minetest
  3. Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com>
  4. This program is free software; you can redistribute it and/or modify
  5. it under the terms of the GNU Lesser General Public License as published by
  6. the Free Software Foundation; either version 2.1 of the License, or
  7. (at your option) any later version.
  8. This program is distributed in the hope that it will be useful,
  9. but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. GNU Lesser General Public License for more details.
  12. You should have received a copy of the GNU Lesser General Public License along
  13. with this program; if not, write to the Free Software Foundation, Inc.,
  14. 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
  15. */
  16. #pragma once
  17. #include "irrlichttypes_bloated.h"
  18. #include "peerhandler.h"
  19. #include "socket.h"
  20. #include "constants.h"
  21. #include "util/pointer.h"
  22. #include "util/container.h"
  23. #include "util/thread.h"
  24. #include "util/numeric.h"
  25. #include <iostream>
  26. #include <fstream>
  27. #include <list>
  28. #include <map>
  29. class NetworkPacket;
  30. namespace con
  31. {
  32. typedef enum MTProtocols {
  33. MTP_PRIMARY,
  34. MTP_UDP,
  35. MTP_MINETEST_RELIABLE_UDP
  36. } MTProtocols;
  37. #define SEQNUM_MAX 65535
  38. inline bool seqnum_higher(u16 totest, u16 base)
  39. {
  40. if (totest > base)
  41. {
  42. if ((totest - base) > (SEQNUM_MAX/2))
  43. return false;
  44. return true;
  45. }
  46. if ((base - totest) > (SEQNUM_MAX/2))
  47. return true;
  48. return false;
  49. }
  50. inline bool seqnum_in_window(u16 seqnum, u16 next,u16 window_size)
  51. {
  52. u16 window_start = next;
  53. u16 window_end = ( next + window_size ) % (SEQNUM_MAX+1);
  54. if (window_start < window_end) {
  55. return ((seqnum >= window_start) && (seqnum < window_end));
  56. }
  57. return ((seqnum < window_end) || (seqnum >= window_start));
  58. }
  59. struct BufferedPacket
  60. {
  61. BufferedPacket(u8 *a_data, u32 a_size):
  62. data(a_data, a_size)
  63. {}
  64. BufferedPacket(u32 a_size):
  65. data(a_size)
  66. {}
  67. Buffer<u8> data; // Data of the packet, including headers
  68. float time = 0.0f; // Seconds from buffering the packet or re-sending
  69. float totaltime = 0.0f; // Seconds from buffering the packet
  70. u64 absolute_send_time = -1;
  71. Address address; // Sender or destination
  72. unsigned int resend_count = 0;
  73. };
  74. // This adds the base headers to the data and makes a packet out of it
  75. BufferedPacket makePacket(Address &address, u8 *data, u32 datasize,
  76. u32 protocol_id, u16 sender_peer_id, u8 channel);
  77. BufferedPacket makePacket(Address &address, SharedBuffer<u8> &data,
  78. u32 protocol_id, u16 sender_peer_id, u8 channel);
  79. // Add the TYPE_ORIGINAL header to the data
  80. SharedBuffer<u8> makeOriginalPacket(
  81. SharedBuffer<u8> data);
  82. // Split data in chunks and add TYPE_SPLIT headers to them
  83. std::list<SharedBuffer<u8> > makeSplitPacket(
  84. SharedBuffer<u8> data,
  85. u32 chunksize_max,
  86. u16 seqnum);
  87. // Depending on size, make a TYPE_ORIGINAL or TYPE_SPLIT packet
  88. // Increments split_seqnum if a split packet is made
  89. std::list<SharedBuffer<u8> > makeAutoSplitPacket(
  90. SharedBuffer<u8> data,
  91. u32 chunksize_max,
  92. u16 &split_seqnum);
  93. // Add the TYPE_RELIABLE header to the data
  94. SharedBuffer<u8> makeReliablePacket(
  95. const SharedBuffer<u8> &data,
  96. u16 seqnum);
  97. struct IncomingSplitPacket
  98. {
  99. IncomingSplitPacket() = default;
  100. // Key is chunk number, value is data without headers
  101. std::map<u16, SharedBuffer<u8> > chunks;
  102. u32 chunk_count;
  103. float time = 0.0f; // Seconds from adding
  104. bool reliable = false; // If true, isn't deleted on timeout
  105. bool allReceived()
  106. {
  107. return (chunks.size() == chunk_count);
  108. }
  109. };
  110. /*
  111. === NOTES ===
  112. A packet is sent through a channel to a peer with a basic header:
  113. TODO: Should we have a receiver_peer_id also?
  114. Header (7 bytes):
  115. [0] u32 protocol_id
  116. [4] u16 sender_peer_id
  117. [6] u8 channel
  118. sender_peer_id:
  119. Unique to each peer.
  120. value 0 (PEER_ID_INEXISTENT) is reserved for making new connections
  121. value 1 (PEER_ID_SERVER) is reserved for server
  122. these constants are defined in constants.h
  123. channel:
  124. The lower the number, the higher the priority is.
  125. Only channels 0, 1 and 2 exist.
  126. */
  127. #define BASE_HEADER_SIZE 7
  128. #define CHANNEL_COUNT 3
  129. /*
  130. Packet types:
  131. CONTROL: This is a packet used by the protocol.
  132. - When this is processed, nothing is handed to the user.
  133. Header (2 byte):
  134. [0] u8 type
  135. [1] u8 controltype
  136. controltype and data description:
  137. CONTROLTYPE_ACK
  138. [2] u16 seqnum
  139. CONTROLTYPE_SET_PEER_ID
  140. [2] u16 peer_id_new
  141. CONTROLTYPE_PING
  142. - There is no actual reply, but this can be sent in a reliable
  143. packet to get a reply
  144. CONTROLTYPE_DISCO
  145. */
  146. #define TYPE_CONTROL 0
  147. #define CONTROLTYPE_ACK 0
  148. #define CONTROLTYPE_SET_PEER_ID 1
  149. #define CONTROLTYPE_PING 2
  150. #define CONTROLTYPE_DISCO 3
  151. #define CONTROLTYPE_ENABLE_BIG_SEND_WINDOW 4
  152. /*
  153. ORIGINAL: This is a plain packet with no control and no error
  154. checking at all.
  155. - When this is processed, it is directly handed to the user.
  156. Header (1 byte):
  157. [0] u8 type
  158. */
  159. #define TYPE_ORIGINAL 1
  160. #define ORIGINAL_HEADER_SIZE 1
  161. /*
  162. SPLIT: These are sequences of packets forming one bigger piece of
  163. data.
  164. - When processed and all the packet_nums 0...packet_count-1 are
  165. present (this should be buffered), the resulting data shall be
  166. directly handed to the user.
  167. - If the data fails to come up in a reasonable time, the buffer shall
  168. be silently discarded.
  169. - These can be sent as-is or atop of a RELIABLE packet stream.
  170. Header (7 bytes):
  171. [0] u8 type
  172. [1] u16 seqnum
  173. [3] u16 chunk_count
  174. [5] u16 chunk_num
  175. */
  176. #define TYPE_SPLIT 2
  177. /*
  178. RELIABLE: Delivery of all RELIABLE packets shall be forced by ACKs,
  179. and they shall be delivered in the same order as sent. This is done
  180. with a buffer in the receiving and transmitting end.
  181. - When this is processed, the contents of each packet is recursively
  182. processed as packets.
  183. Header (3 bytes):
  184. [0] u8 type
  185. [1] u16 seqnum
  186. */
  187. #define TYPE_RELIABLE 3
  188. #define RELIABLE_HEADER_SIZE 3
  189. #define SEQNUM_INITIAL 65500
  190. /*
  191. A buffer which stores reliable packets and sorts them internally
  192. for fast access to the smallest one.
  193. */
  194. typedef std::list<BufferedPacket>::iterator RPBSearchResult;
  195. class ReliablePacketBuffer
  196. {
  197. public:
  198. ReliablePacketBuffer() = default;
  199. bool getFirstSeqnum(u16& result);
  200. BufferedPacket popFirst();
  201. BufferedPacket popSeqnum(u16 seqnum);
  202. void insert(BufferedPacket &p,u16 next_expected);
  203. void incrementTimeouts(float dtime);
  204. std::list<BufferedPacket> getTimedOuts(float timeout,
  205. unsigned int max_packets);
  206. void print();
  207. bool empty();
  208. bool containsPacket(u16 seqnum);
  209. RPBSearchResult notFound();
  210. u32 size();
  211. private:
  212. RPBSearchResult findPacket(u16 seqnum);
  213. std::list<BufferedPacket> m_list;
  214. u32 m_list_size = 0;
  215. u16 m_oldest_non_answered_ack;
  216. std::mutex m_list_mutex;
  217. };
  218. /*
  219. A buffer for reconstructing split packets
  220. */
  221. class IncomingSplitBuffer
  222. {
  223. public:
  224. ~IncomingSplitBuffer();
  225. /*
  226. Returns a reference counted buffer of length != 0 when a full split
  227. packet is constructed. If not, returns one of length 0.
  228. */
  229. SharedBuffer<u8> insert(BufferedPacket &p, bool reliable);
  230. void removeUnreliableTimedOuts(float dtime, float timeout);
  231. private:
  232. // Key is seqnum
  233. std::map<u16, IncomingSplitPacket*> m_buf;
  234. std::mutex m_map_mutex;
  235. };
  236. struct OutgoingPacket
  237. {
  238. u16 peer_id;
  239. u8 channelnum;
  240. SharedBuffer<u8> data;
  241. bool reliable;
  242. bool ack;
  243. OutgoingPacket(u16 peer_id_, u8 channelnum_, const SharedBuffer<u8> &data_,
  244. bool reliable_,bool ack_=false):
  245. peer_id(peer_id_),
  246. channelnum(channelnum_),
  247. data(data_),
  248. reliable(reliable_),
  249. ack(ack_)
  250. {
  251. }
  252. };
  253. enum ConnectionCommandType{
  254. CONNCMD_NONE,
  255. CONNCMD_SERVE,
  256. CONNCMD_CONNECT,
  257. CONNCMD_DISCONNECT,
  258. CONNCMD_DISCONNECT_PEER,
  259. CONNCMD_SEND,
  260. CONNCMD_SEND_TO_ALL,
  261. CONCMD_ACK,
  262. CONCMD_CREATE_PEER,
  263. CONCMD_DISABLE_LEGACY
  264. };
  265. struct ConnectionCommand
  266. {
  267. enum ConnectionCommandType type = CONNCMD_NONE;
  268. Address address;
  269. u16 peer_id = PEER_ID_INEXISTENT;
  270. u8 channelnum;
  271. Buffer<u8> data;
  272. bool reliable = false;
  273. bool raw = false;
  274. ConnectionCommand() = default;
  275. void serve(Address address_)
  276. {
  277. type = CONNCMD_SERVE;
  278. address = address_;
  279. }
  280. void connect(Address address_)
  281. {
  282. type = CONNCMD_CONNECT;
  283. address = address_;
  284. }
  285. void disconnect()
  286. {
  287. type = CONNCMD_DISCONNECT;
  288. }
  289. void disconnect_peer(u16 peer_id_)
  290. {
  291. type = CONNCMD_DISCONNECT_PEER;
  292. peer_id = peer_id_;
  293. }
  294. void send(u16 peer_id_, u8 channelnum_, NetworkPacket* pkt, bool reliable_);
  295. void ack(u16 peer_id_, u8 channelnum_, const SharedBuffer<u8> &data_)
  296. {
  297. type = CONCMD_ACK;
  298. peer_id = peer_id_;
  299. channelnum = channelnum_;
  300. data = data_;
  301. reliable = false;
  302. }
  303. void createPeer(u16 peer_id_, const SharedBuffer<u8> &data_)
  304. {
  305. type = CONCMD_CREATE_PEER;
  306. peer_id = peer_id_;
  307. data = data_;
  308. channelnum = 0;
  309. reliable = true;
  310. raw = true;
  311. }
  312. void disableLegacy(u16 peer_id_, const SharedBuffer<u8> &data_)
  313. {
  314. type = CONCMD_DISABLE_LEGACY;
  315. peer_id = peer_id_;
  316. data = data_;
  317. channelnum = 0;
  318. reliable = true;
  319. raw = true;
  320. }
  321. };
  322. /* maximum window size to use, 0xFFFF is theoretical maximum don't think about
  323. * touching it, the less you're away from it the more likely data corruption
  324. * will occur
  325. */
  326. #define MAX_RELIABLE_WINDOW_SIZE 0x8000
  327. /* starting value for window size */
  328. #define MIN_RELIABLE_WINDOW_SIZE 0x40
  329. class Channel
  330. {
  331. public:
  332. u16 readNextIncomingSeqNum();
  333. u16 incNextIncomingSeqNum();
  334. u16 getOutgoingSequenceNumber(bool& successfull);
  335. u16 readOutgoingSequenceNumber();
  336. bool putBackSequenceNumber(u16);
  337. u16 readNextSplitSeqNum();
  338. void setNextSplitSeqNum(u16 seqnum);
  339. // This is for buffering the incoming packets that are coming in
  340. // the wrong order
  341. ReliablePacketBuffer incoming_reliables;
  342. // This is for buffering the sent packets so that the sender can
  343. // re-send them if no ACK is received
  344. ReliablePacketBuffer outgoing_reliables_sent;
  345. //queued reliable packets
  346. std::queue<BufferedPacket> queued_reliables;
  347. //queue commands prior splitting to packets
  348. std::deque<ConnectionCommand> queued_commands;
  349. IncomingSplitBuffer incoming_splits;
  350. Channel() = default;
  351. ~Channel() = default;
  352. void UpdatePacketLossCounter(unsigned int count);
  353. void UpdatePacketTooLateCounter();
  354. void UpdateBytesSent(unsigned int bytes,unsigned int packages=1);
  355. void UpdateBytesLost(unsigned int bytes);
  356. void UpdateBytesReceived(unsigned int bytes);
  357. void UpdateTimers(float dtime, bool legacy_peer);
  358. const float getCurrentDownloadRateKB()
  359. { MutexAutoLock lock(m_internal_mutex); return cur_kbps; };
  360. const float getMaxDownloadRateKB()
  361. { MutexAutoLock lock(m_internal_mutex); return max_kbps; };
  362. const float getCurrentLossRateKB()
  363. { MutexAutoLock lock(m_internal_mutex); return cur_kbps_lost; };
  364. const float getMaxLossRateKB()
  365. { MutexAutoLock lock(m_internal_mutex); return max_kbps_lost; };
  366. const float getCurrentIncomingRateKB()
  367. { MutexAutoLock lock(m_internal_mutex); return cur_incoming_kbps; };
  368. const float getMaxIncomingRateKB()
  369. { MutexAutoLock lock(m_internal_mutex); return max_incoming_kbps; };
  370. const float getAvgDownloadRateKB()
  371. { MutexAutoLock lock(m_internal_mutex); return avg_kbps; };
  372. const float getAvgLossRateKB()
  373. { MutexAutoLock lock(m_internal_mutex); return avg_kbps_lost; };
  374. const float getAvgIncomingRateKB()
  375. { MutexAutoLock lock(m_internal_mutex); return avg_incoming_kbps; };
  376. const unsigned int getWindowSize() const { return window_size; };
  377. void setWindowSize(unsigned int size) { window_size = size; };
  378. private:
  379. std::mutex m_internal_mutex;
  380. int window_size = MIN_RELIABLE_WINDOW_SIZE;
  381. u16 next_incoming_seqnum = SEQNUM_INITIAL;
  382. u16 next_outgoing_seqnum = SEQNUM_INITIAL;
  383. u16 next_outgoing_split_seqnum = SEQNUM_INITIAL;
  384. unsigned int current_packet_loss = 0;
  385. unsigned int current_packet_too_late = 0;
  386. unsigned int current_packet_successfull = 0;
  387. float packet_loss_counter = 0.0f;
  388. unsigned int current_bytes_transfered = 0;
  389. unsigned int current_bytes_received = 0;
  390. unsigned int current_bytes_lost = 0;
  391. float max_kbps = 0.0f;
  392. float cur_kbps = 0.0f;
  393. float avg_kbps = 0.0f;
  394. float max_incoming_kbps = 0.0f;
  395. float cur_incoming_kbps = 0.0f;
  396. float avg_incoming_kbps = 0.0f;
  397. float max_kbps_lost = 0.0f;
  398. float cur_kbps_lost = 0.0f;
  399. float avg_kbps_lost = 0.0f;
  400. float bpm_counter = 0.0f;
  401. unsigned int rate_samples = 0;
  402. };
  403. class Peer;
  404. class PeerHelper
  405. {
  406. public:
  407. PeerHelper() = default;
  408. PeerHelper(Peer* peer);
  409. ~PeerHelper();
  410. PeerHelper& operator=(Peer* peer);
  411. Peer* operator->() const;
  412. bool operator!();
  413. Peer* operator&() const;
  414. bool operator!=(void* ptr);
  415. private:
  416. Peer *m_peer = nullptr;
  417. };
  418. class Connection;
  419. typedef enum {
  420. CUR_DL_RATE,
  421. AVG_DL_RATE,
  422. CUR_INC_RATE,
  423. AVG_INC_RATE,
  424. CUR_LOSS_RATE,
  425. AVG_LOSS_RATE,
  426. } rate_stat_type;
  427. class Peer {
  428. public:
  429. friend class PeerHelper;
  430. Peer(Address address_,u16 id_,Connection* connection) :
  431. id(id_),
  432. m_connection(connection),
  433. address(address_),
  434. m_last_timeout_check(porting::getTimeMs())
  435. {
  436. };
  437. virtual ~Peer() {
  438. MutexAutoLock usage_lock(m_exclusive_access_mutex);
  439. FATAL_ERROR_IF(m_usage != 0, "Reference counting failure");
  440. };
  441. // Unique id of the peer
  442. u16 id;
  443. void Drop();
  444. virtual void PutReliableSendCommand(ConnectionCommand &c,
  445. unsigned int max_packet_size) {};
  446. virtual bool getAddress(MTProtocols type, Address& toset) = 0;
  447. bool isPendingDeletion()
  448. { MutexAutoLock lock(m_exclusive_access_mutex); return m_pending_deletion; };
  449. void ResetTimeout()
  450. {MutexAutoLock lock(m_exclusive_access_mutex); m_timeout_counter = 0.0; };
  451. bool isTimedOut(float timeout);
  452. unsigned int m_increment_packets_remaining = 9;
  453. unsigned int m_increment_bytes_remaining = 0;
  454. virtual u16 getNextSplitSequenceNumber(u8 channel) { return 0; };
  455. virtual void setNextSplitSequenceNumber(u8 channel, u16 seqnum) {};
  456. virtual SharedBuffer<u8> addSpiltPacket(u8 channel,
  457. BufferedPacket toadd,
  458. bool reliable)
  459. {
  460. fprintf(stderr,"Peer: addSplitPacket called, this is supposed to be never called!\n");
  461. return SharedBuffer<u8>(0);
  462. };
  463. virtual bool Ping(float dtime, SharedBuffer<u8>& data) { return false; };
  464. virtual float getStat(rtt_stat_type type) const {
  465. switch (type) {
  466. case MIN_RTT:
  467. return m_rtt.min_rtt;
  468. case MAX_RTT:
  469. return m_rtt.max_rtt;
  470. case AVG_RTT:
  471. return m_rtt.avg_rtt;
  472. case MIN_JITTER:
  473. return m_rtt.jitter_min;
  474. case MAX_JITTER:
  475. return m_rtt.jitter_max;
  476. case AVG_JITTER:
  477. return m_rtt.jitter_avg;
  478. }
  479. return -1;
  480. }
  481. protected:
  482. virtual void reportRTT(float rtt) {};
  483. void RTTStatistics(float rtt,
  484. const std::string &profiler_id = "",
  485. unsigned int num_samples = 1000);
  486. bool IncUseCount();
  487. void DecUseCount();
  488. std::mutex m_exclusive_access_mutex;
  489. bool m_pending_deletion = false;
  490. Connection* m_connection;
  491. // Address of the peer
  492. Address address;
  493. // Ping timer
  494. float m_ping_timer = 0.0f;
  495. private:
  496. struct rttstats {
  497. float jitter_min = FLT_MAX;
  498. float jitter_max = 0.0f;
  499. float jitter_avg = -1.0f;
  500. float min_rtt = FLT_MAX;
  501. float max_rtt = 0.0f;
  502. float avg_rtt = -1.0f;
  503. rttstats() = default;
  504. };
  505. rttstats m_rtt;
  506. float m_last_rtt = -1.0f;
  507. // current usage count
  508. unsigned int m_usage = 0;
  509. // Seconds from last receive
  510. float m_timeout_counter = 0.0f;
  511. u64 m_last_timeout_check;
  512. };
  513. class UDPPeer : public Peer
  514. {
  515. public:
  516. friend class PeerHelper;
  517. friend class ConnectionReceiveThread;
  518. friend class ConnectionSendThread;
  519. friend class Connection;
  520. UDPPeer(u16 a_id, Address a_address, Connection* connection);
  521. virtual ~UDPPeer() = default;
  522. void PutReliableSendCommand(ConnectionCommand &c,
  523. unsigned int max_packet_size);
  524. bool getAddress(MTProtocols type, Address& toset);
  525. void setNonLegacyPeer();
  526. bool getLegacyPeer()
  527. { return m_legacy_peer; }
  528. u16 getNextSplitSequenceNumber(u8 channel);
  529. void setNextSplitSequenceNumber(u8 channel, u16 seqnum);
  530. SharedBuffer<u8> addSpiltPacket(u8 channel,
  531. BufferedPacket toadd,
  532. bool reliable);
  533. protected:
  534. /*
  535. Calculates avg_rtt and resend_timeout.
  536. rtt=-1 only recalculates resend_timeout
  537. */
  538. void reportRTT(float rtt);
  539. void RunCommandQueues(
  540. unsigned int max_packet_size,
  541. unsigned int maxcommands,
  542. unsigned int maxtransfer);
  543. float getResendTimeout()
  544. { MutexAutoLock lock(m_exclusive_access_mutex); return resend_timeout; }
  545. void setResendTimeout(float timeout)
  546. { MutexAutoLock lock(m_exclusive_access_mutex); resend_timeout = timeout; }
  547. bool Ping(float dtime,SharedBuffer<u8>& data);
  548. Channel channels[CHANNEL_COUNT];
  549. bool m_pending_disconnect = false;
  550. private:
  551. // This is changed dynamically
  552. float resend_timeout = 0.5;
  553. bool processReliableSendCommand(
  554. ConnectionCommand &c,
  555. unsigned int max_packet_size);
  556. bool m_legacy_peer = true;
  557. };
  558. /*
  559. Connection
  560. */
  561. enum ConnectionEventType{
  562. CONNEVENT_NONE,
  563. CONNEVENT_DATA_RECEIVED,
  564. CONNEVENT_PEER_ADDED,
  565. CONNEVENT_PEER_REMOVED,
  566. CONNEVENT_BIND_FAILED,
  567. };
  568. struct ConnectionEvent
  569. {
  570. enum ConnectionEventType type = CONNEVENT_NONE;
  571. u16 peer_id = 0;
  572. Buffer<u8> data;
  573. bool timeout = false;
  574. Address address;
  575. ConnectionEvent() = default;
  576. std::string describe()
  577. {
  578. switch(type) {
  579. case CONNEVENT_NONE:
  580. return "CONNEVENT_NONE";
  581. case CONNEVENT_DATA_RECEIVED:
  582. return "CONNEVENT_DATA_RECEIVED";
  583. case CONNEVENT_PEER_ADDED:
  584. return "CONNEVENT_PEER_ADDED";
  585. case CONNEVENT_PEER_REMOVED:
  586. return "CONNEVENT_PEER_REMOVED";
  587. case CONNEVENT_BIND_FAILED:
  588. return "CONNEVENT_BIND_FAILED";
  589. }
  590. return "Invalid ConnectionEvent";
  591. }
  592. void dataReceived(u16 peer_id_, const SharedBuffer<u8> &data_)
  593. {
  594. type = CONNEVENT_DATA_RECEIVED;
  595. peer_id = peer_id_;
  596. data = data_;
  597. }
  598. void peerAdded(u16 peer_id_, Address address_)
  599. {
  600. type = CONNEVENT_PEER_ADDED;
  601. peer_id = peer_id_;
  602. address = address_;
  603. }
  604. void peerRemoved(u16 peer_id_, bool timeout_, Address address_)
  605. {
  606. type = CONNEVENT_PEER_REMOVED;
  607. peer_id = peer_id_;
  608. timeout = timeout_;
  609. address = address_;
  610. }
  611. void bindFailed()
  612. {
  613. type = CONNEVENT_BIND_FAILED;
  614. }
  615. };
  616. class ConnectionSendThread : public Thread {
  617. public:
  618. friend class UDPPeer;
  619. ConnectionSendThread(unsigned int max_packet_size, float timeout);
  620. void *run();
  621. void Trigger();
  622. void setParent(Connection* parent) {
  623. assert(parent != NULL); // Pre-condition
  624. m_connection = parent;
  625. }
  626. void setPeerTimeout(float peer_timeout)
  627. { m_timeout = peer_timeout; }
  628. private:
  629. void runTimeouts (float dtime);
  630. void rawSend (const BufferedPacket &packet);
  631. bool rawSendAsPacket(u16 peer_id, u8 channelnum,
  632. SharedBuffer<u8> data, bool reliable);
  633. void processReliableCommand (ConnectionCommand &c);
  634. void processNonReliableCommand (ConnectionCommand &c);
  635. void serve (Address bind_address);
  636. void connect (Address address);
  637. void disconnect ();
  638. void disconnect_peer(u16 peer_id);
  639. void send (u16 peer_id, u8 channelnum,
  640. SharedBuffer<u8> data);
  641. void sendReliable (ConnectionCommand &c);
  642. void sendToAll (u8 channelnum,
  643. SharedBuffer<u8> data);
  644. void sendToAllReliable(ConnectionCommand &c);
  645. void sendPackets (float dtime);
  646. void sendAsPacket (u16 peer_id, u8 channelnum,
  647. SharedBuffer<u8> data,bool ack=false);
  648. void sendAsPacketReliable(BufferedPacket& p, Channel* channel);
  649. bool packetsQueued();
  650. Connection *m_connection = nullptr;
  651. unsigned int m_max_packet_size;
  652. float m_timeout;
  653. std::queue<OutgoingPacket> m_outgoing_queue;
  654. Semaphore m_send_sleep_semaphore;
  655. unsigned int m_iteration_packets_avaialble;
  656. unsigned int m_max_commands_per_iteration = 1;
  657. unsigned int m_max_data_packets_per_iteration;
  658. unsigned int m_max_packets_requeued = 256;
  659. };
  660. class ConnectionReceiveThread : public Thread {
  661. public:
  662. ConnectionReceiveThread(unsigned int max_packet_size);
  663. void *run();
  664. void setParent(Connection *parent) {
  665. assert(parent); // Pre-condition
  666. m_connection = parent;
  667. }
  668. private:
  669. void receive();
  670. // Returns next data from a buffer if possible
  671. // If found, returns true; if not, false.
  672. // If found, sets peer_id and dst
  673. bool getFromBuffers(u16 &peer_id, SharedBuffer<u8> &dst);
  674. bool checkIncomingBuffers(Channel *channel, u16 &peer_id,
  675. SharedBuffer<u8> &dst);
  676. /*
  677. Processes a packet with the basic header stripped out.
  678. Parameters:
  679. packetdata: Data in packet (with no base headers)
  680. peer_id: peer id of the sender of the packet in question
  681. channelnum: channel on which the packet was sent
  682. reliable: true if recursing into a reliable packet
  683. */
  684. SharedBuffer<u8> processPacket(Channel *channel,
  685. SharedBuffer<u8> packetdata, u16 peer_id,
  686. u8 channelnum, bool reliable);
  687. Connection *m_connection = nullptr;
  688. };
  689. class PeerHandler;
  690. class Connection
  691. {
  692. public:
  693. friend class ConnectionSendThread;
  694. friend class ConnectionReceiveThread;
  695. Connection(u32 protocol_id, u32 max_packet_size, float timeout, bool ipv6,
  696. PeerHandler *peerhandler);
  697. ~Connection();
  698. /* Interface */
  699. ConnectionEvent waitEvent(u32 timeout_ms);
  700. void putCommand(ConnectionCommand &c);
  701. void SetTimeoutMs(int timeout) { m_bc_receive_timeout = timeout; }
  702. void Serve(Address bind_addr);
  703. void Connect(Address address);
  704. bool Connected();
  705. void Disconnect();
  706. void Receive(NetworkPacket* pkt);
  707. void Send(u16 peer_id, u8 channelnum, NetworkPacket* pkt, bool reliable);
  708. u16 GetPeerID() { return m_peer_id; }
  709. Address GetPeerAddress(u16 peer_id);
  710. float getPeerStat(u16 peer_id, rtt_stat_type type);
  711. float getLocalStat(rate_stat_type type);
  712. const u32 GetProtocolID() const { return m_protocol_id; };
  713. const std::string getDesc();
  714. void DisconnectPeer(u16 peer_id);
  715. protected:
  716. PeerHelper getPeer(u16 peer_id);
  717. PeerHelper getPeerNoEx(u16 peer_id);
  718. u16 lookupPeer(Address& sender);
  719. u16 createPeer(Address& sender, MTProtocols protocol, int fd);
  720. UDPPeer* createServerPeer(Address& sender);
  721. bool deletePeer(u16 peer_id, bool timeout);
  722. void SetPeerID(u16 id) { m_peer_id = id; }
  723. void sendAck(u16 peer_id, u8 channelnum, u16 seqnum);
  724. void PrintInfo(std::ostream &out);
  725. void PrintInfo();
  726. std::list<u16> getPeerIDs()
  727. {
  728. MutexAutoLock peerlock(m_peers_mutex);
  729. return m_peer_ids;
  730. }
  731. UDPSocket m_udpSocket;
  732. MutexedQueue<ConnectionCommand> m_command_queue;
  733. void putEvent(ConnectionEvent &e);
  734. void TriggerSend()
  735. { m_sendThread.Trigger(); }
  736. private:
  737. std::list<Peer*> getPeers();
  738. MutexedQueue<ConnectionEvent> m_event_queue;
  739. u16 m_peer_id = 0;
  740. u32 m_protocol_id;
  741. std::map<u16, Peer*> m_peers;
  742. std::list<u16> m_peer_ids;
  743. std::mutex m_peers_mutex;
  744. ConnectionSendThread m_sendThread;
  745. ConnectionReceiveThread m_receiveThread;
  746. std::mutex m_info_mutex;
  747. // Backwards compatibility
  748. PeerHandler *m_bc_peerhandler;
  749. int m_bc_receive_timeout = 0;
  750. bool m_shutting_down = false;
  751. u16 m_next_remote_peer_id = 2;
  752. };
  753. } // namespace