connection.h 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833
  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 "networkprotocol.h"
  26. #include <iostream>
  27. #include <fstream>
  28. #include <list>
  29. #include <map>
  30. class NetworkPacket;
  31. namespace con
  32. {
  33. class ConnectionReceiveThread;
  34. class ConnectionSendThread;
  35. typedef enum MTProtocols {
  36. MTP_PRIMARY,
  37. MTP_UDP,
  38. MTP_MINETEST_RELIABLE_UDP
  39. } MTProtocols;
  40. #define MAX_UDP_PEERS 65535
  41. #define SEQNUM_MAX 65535
  42. inline bool seqnum_higher(u16 totest, u16 base)
  43. {
  44. if (totest > base)
  45. {
  46. if ((totest - base) > (SEQNUM_MAX/2))
  47. return false;
  48. return true;
  49. }
  50. if ((base - totest) > (SEQNUM_MAX/2))
  51. return true;
  52. return false;
  53. }
  54. inline bool seqnum_in_window(u16 seqnum, u16 next,u16 window_size)
  55. {
  56. u16 window_start = next;
  57. u16 window_end = ( next + window_size ) % (SEQNUM_MAX+1);
  58. if (window_start < window_end) {
  59. return ((seqnum >= window_start) && (seqnum < window_end));
  60. }
  61. return ((seqnum < window_end) || (seqnum >= window_start));
  62. }
  63. static inline float CALC_DTIME(u64 lasttime, u64 curtime)
  64. {
  65. float value = ( curtime - lasttime) / 1000.0;
  66. return MYMAX(MYMIN(value,0.1),0.0);
  67. }
  68. struct BufferedPacket
  69. {
  70. BufferedPacket(u8 *a_data, u32 a_size):
  71. data(a_data, a_size)
  72. {}
  73. BufferedPacket(u32 a_size):
  74. data(a_size)
  75. {}
  76. Buffer<u8> data; // Data of the packet, including headers
  77. float time = 0.0f; // Seconds from buffering the packet or re-sending
  78. float totaltime = 0.0f; // Seconds from buffering the packet
  79. u64 absolute_send_time = -1;
  80. Address address; // Sender or destination
  81. unsigned int resend_count = 0;
  82. };
  83. // This adds the base headers to the data and makes a packet out of it
  84. BufferedPacket makePacket(Address &address, const SharedBuffer<u8> &data,
  85. u32 protocol_id, session_t sender_peer_id, u8 channel);
  86. // Depending on size, make a TYPE_ORIGINAL or TYPE_SPLIT packet
  87. // Increments split_seqnum if a split packet is made
  88. void makeAutoSplitPacket(const SharedBuffer<u8> &data, u32 chunksize_max,
  89. u16 &split_seqnum, std::list<SharedBuffer<u8>> *list);
  90. // Add the TYPE_RELIABLE header to the data
  91. SharedBuffer<u8> makeReliablePacket(const SharedBuffer<u8> &data, u16 seqnum);
  92. struct IncomingSplitPacket
  93. {
  94. IncomingSplitPacket(u32 cc, bool r):
  95. chunk_count(cc), reliable(r) {}
  96. IncomingSplitPacket() = delete;
  97. float time = 0.0f; // Seconds from adding
  98. u32 chunk_count;
  99. bool reliable; // If true, isn't deleted on timeout
  100. bool allReceived() const
  101. {
  102. return (chunks.size() == chunk_count);
  103. }
  104. bool insert(u32 chunk_num, SharedBuffer<u8> &chunkdata);
  105. SharedBuffer<u8> reassemble();
  106. private:
  107. // Key is chunk number, value is data without headers
  108. std::map<u16, SharedBuffer<u8>> chunks;
  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] session_t 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] session_t 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. /*
  152. ORIGINAL: This is a plain packet with no control and no error
  153. checking at all.
  154. - When this is processed, it is directly handed to the user.
  155. Header (1 byte):
  156. [0] u8 type
  157. */
  158. //#define TYPE_ORIGINAL 1
  159. #define ORIGINAL_HEADER_SIZE 1
  160. /*
  161. SPLIT: These are sequences of packets forming one bigger piece of
  162. data.
  163. - When processed and all the packet_nums 0...packet_count-1 are
  164. present (this should be buffered), the resulting data shall be
  165. directly handed to the user.
  166. - If the data fails to come up in a reasonable time, the buffer shall
  167. be silently discarded.
  168. - These can be sent as-is or atop of a RELIABLE packet stream.
  169. Header (7 bytes):
  170. [0] u8 type
  171. [1] u16 seqnum
  172. [3] u16 chunk_count
  173. [5] u16 chunk_num
  174. */
  175. //#define TYPE_SPLIT 2
  176. /*
  177. RELIABLE: Delivery of all RELIABLE packets shall be forced by ACKs,
  178. and they shall be delivered in the same order as sent. This is done
  179. with a buffer in the receiving and transmitting end.
  180. - When this is processed, the contents of each packet is recursively
  181. processed as packets.
  182. Header (3 bytes):
  183. [0] u8 type
  184. [1] u16 seqnum
  185. */
  186. //#define TYPE_RELIABLE 3
  187. #define RELIABLE_HEADER_SIZE 3
  188. #define SEQNUM_INITIAL 65500
  189. enum PacketType: u8 {
  190. PACKET_TYPE_CONTROL = 0,
  191. PACKET_TYPE_ORIGINAL = 1,
  192. PACKET_TYPE_SPLIT = 2,
  193. PACKET_TYPE_RELIABLE = 3,
  194. PACKET_TYPE_MAX
  195. };
  196. /*
  197. A buffer which stores reliable packets and sorts them internally
  198. for fast access to the smallest one.
  199. */
  200. typedef std::list<BufferedPacket>::iterator RPBSearchResult;
  201. class ReliablePacketBuffer
  202. {
  203. public:
  204. ReliablePacketBuffer() = default;
  205. bool getFirstSeqnum(u16& result);
  206. BufferedPacket popFirst();
  207. BufferedPacket popSeqnum(u16 seqnum);
  208. void insert(BufferedPacket &p, u16 next_expected);
  209. void incrementTimeouts(float dtime);
  210. std::list<BufferedPacket> getTimedOuts(float timeout,
  211. unsigned int max_packets);
  212. void print();
  213. bool empty();
  214. RPBSearchResult notFound();
  215. u32 size();
  216. private:
  217. RPBSearchResult findPacket(u16 seqnum); // does not perform locking
  218. std::list<BufferedPacket> m_list;
  219. u16 m_oldest_non_answered_ack;
  220. std::mutex m_list_mutex;
  221. };
  222. /*
  223. A buffer for reconstructing split packets
  224. */
  225. class IncomingSplitBuffer
  226. {
  227. public:
  228. ~IncomingSplitBuffer();
  229. /*
  230. Returns a reference counted buffer of length != 0 when a full split
  231. packet is constructed. If not, returns one of length 0.
  232. */
  233. SharedBuffer<u8> insert(const BufferedPacket &p, bool reliable);
  234. void removeUnreliableTimedOuts(float dtime, float timeout);
  235. private:
  236. // Key is seqnum
  237. std::map<u16, IncomingSplitPacket*> m_buf;
  238. std::mutex m_map_mutex;
  239. };
  240. struct OutgoingPacket
  241. {
  242. session_t peer_id;
  243. u8 channelnum;
  244. SharedBuffer<u8> data;
  245. bool reliable;
  246. bool ack;
  247. OutgoingPacket(session_t peer_id_, u8 channelnum_, const SharedBuffer<u8> &data_,
  248. bool reliable_,bool ack_=false):
  249. peer_id(peer_id_),
  250. channelnum(channelnum_),
  251. data(data_),
  252. reliable(reliable_),
  253. ack(ack_)
  254. {
  255. }
  256. };
  257. enum ConnectionCommandType{
  258. CONNCMD_NONE,
  259. CONNCMD_SERVE,
  260. CONNCMD_CONNECT,
  261. CONNCMD_DISCONNECT,
  262. CONNCMD_DISCONNECT_PEER,
  263. CONNCMD_SEND,
  264. CONNCMD_SEND_TO_ALL,
  265. CONCMD_ACK,
  266. CONCMD_CREATE_PEER
  267. };
  268. struct ConnectionCommand
  269. {
  270. enum ConnectionCommandType type = CONNCMD_NONE;
  271. Address address;
  272. session_t peer_id = PEER_ID_INEXISTENT;
  273. u8 channelnum = 0;
  274. Buffer<u8> data;
  275. bool reliable = false;
  276. bool raw = false;
  277. ConnectionCommand() = default;
  278. ConnectionCommand &operator=(const ConnectionCommand &other)
  279. {
  280. type = other.type;
  281. address = other.address;
  282. peer_id = other.peer_id;
  283. channelnum = other.channelnum;
  284. // We must copy the buffer here to prevent race condition
  285. data = SharedBuffer<u8>(*other.data, other.data.getSize());
  286. reliable = other.reliable;
  287. raw = other.raw;
  288. return *this;
  289. }
  290. void serve(Address address_)
  291. {
  292. type = CONNCMD_SERVE;
  293. address = address_;
  294. }
  295. void connect(Address address_)
  296. {
  297. type = CONNCMD_CONNECT;
  298. address = address_;
  299. }
  300. void disconnect()
  301. {
  302. type = CONNCMD_DISCONNECT;
  303. }
  304. void disconnect_peer(session_t peer_id_)
  305. {
  306. type = CONNCMD_DISCONNECT_PEER;
  307. peer_id = peer_id_;
  308. }
  309. void send(session_t peer_id_, u8 channelnum_, NetworkPacket *pkt, bool reliable_);
  310. void ack(session_t peer_id_, u8 channelnum_, const SharedBuffer<u8> &data_)
  311. {
  312. type = CONCMD_ACK;
  313. peer_id = peer_id_;
  314. channelnum = channelnum_;
  315. data = data_;
  316. reliable = false;
  317. }
  318. void createPeer(session_t peer_id_, const SharedBuffer<u8> &data_)
  319. {
  320. type = CONCMD_CREATE_PEER;
  321. peer_id = peer_id_;
  322. data = data_;
  323. channelnum = 0;
  324. reliable = true;
  325. raw = true;
  326. }
  327. };
  328. /* maximum window size to use, 0xFFFF is theoretical maximum don't think about
  329. * touching it, the less you're away from it the more likely data corruption
  330. * will occur
  331. */
  332. #define MAX_RELIABLE_WINDOW_SIZE 0x8000
  333. /* starting value for window size */
  334. #define MIN_RELIABLE_WINDOW_SIZE 0x40
  335. class Channel
  336. {
  337. public:
  338. u16 readNextIncomingSeqNum();
  339. u16 incNextIncomingSeqNum();
  340. u16 getOutgoingSequenceNumber(bool& successfull);
  341. u16 readOutgoingSequenceNumber();
  342. bool putBackSequenceNumber(u16);
  343. u16 readNextSplitSeqNum();
  344. void setNextSplitSeqNum(u16 seqnum);
  345. // This is for buffering the incoming packets that are coming in
  346. // the wrong order
  347. ReliablePacketBuffer incoming_reliables;
  348. // This is for buffering the sent packets so that the sender can
  349. // re-send them if no ACK is received
  350. ReliablePacketBuffer outgoing_reliables_sent;
  351. //queued reliable packets
  352. std::queue<BufferedPacket> queued_reliables;
  353. //queue commands prior splitting to packets
  354. std::deque<ConnectionCommand> queued_commands;
  355. IncomingSplitBuffer incoming_splits;
  356. Channel() = default;
  357. ~Channel() = default;
  358. void UpdatePacketLossCounter(unsigned int count);
  359. void UpdatePacketTooLateCounter();
  360. void UpdateBytesSent(unsigned int bytes,unsigned int packages=1);
  361. void UpdateBytesLost(unsigned int bytes);
  362. void UpdateBytesReceived(unsigned int bytes);
  363. void UpdateTimers(float dtime);
  364. const float getCurrentDownloadRateKB()
  365. { MutexAutoLock lock(m_internal_mutex); return cur_kbps; };
  366. const float getMaxDownloadRateKB()
  367. { MutexAutoLock lock(m_internal_mutex); return max_kbps; };
  368. const float getCurrentLossRateKB()
  369. { MutexAutoLock lock(m_internal_mutex); return cur_kbps_lost; };
  370. const float getMaxLossRateKB()
  371. { MutexAutoLock lock(m_internal_mutex); return max_kbps_lost; };
  372. const float getCurrentIncomingRateKB()
  373. { MutexAutoLock lock(m_internal_mutex); return cur_incoming_kbps; };
  374. const float getMaxIncomingRateKB()
  375. { MutexAutoLock lock(m_internal_mutex); return max_incoming_kbps; };
  376. const float getAvgDownloadRateKB()
  377. { MutexAutoLock lock(m_internal_mutex); return avg_kbps; };
  378. const float getAvgLossRateKB()
  379. { MutexAutoLock lock(m_internal_mutex); return avg_kbps_lost; };
  380. const float getAvgIncomingRateKB()
  381. { MutexAutoLock lock(m_internal_mutex); return avg_incoming_kbps; };
  382. const unsigned int getWindowSize() const { return window_size; };
  383. void setWindowSize(unsigned int size) { window_size = size; };
  384. private:
  385. std::mutex m_internal_mutex;
  386. int window_size = MIN_RELIABLE_WINDOW_SIZE;
  387. u16 next_incoming_seqnum = SEQNUM_INITIAL;
  388. u16 next_outgoing_seqnum = SEQNUM_INITIAL;
  389. u16 next_outgoing_split_seqnum = SEQNUM_INITIAL;
  390. unsigned int current_packet_loss = 0;
  391. unsigned int current_packet_too_late = 0;
  392. unsigned int current_packet_successful = 0;
  393. float packet_loss_counter = 0.0f;
  394. unsigned int current_bytes_transfered = 0;
  395. unsigned int current_bytes_received = 0;
  396. unsigned int current_bytes_lost = 0;
  397. float max_kbps = 0.0f;
  398. float cur_kbps = 0.0f;
  399. float avg_kbps = 0.0f;
  400. float max_incoming_kbps = 0.0f;
  401. float cur_incoming_kbps = 0.0f;
  402. float avg_incoming_kbps = 0.0f;
  403. float max_kbps_lost = 0.0f;
  404. float cur_kbps_lost = 0.0f;
  405. float avg_kbps_lost = 0.0f;
  406. float bpm_counter = 0.0f;
  407. unsigned int rate_samples = 0;
  408. };
  409. class Peer;
  410. class PeerHelper
  411. {
  412. public:
  413. PeerHelper() = default;
  414. PeerHelper(Peer* peer);
  415. ~PeerHelper();
  416. PeerHelper& operator=(Peer* peer);
  417. Peer* operator->() const;
  418. bool operator!();
  419. Peer* operator&() const;
  420. bool operator!=(void* ptr);
  421. private:
  422. Peer *m_peer = nullptr;
  423. };
  424. class Connection;
  425. typedef enum {
  426. CUR_DL_RATE,
  427. AVG_DL_RATE,
  428. CUR_INC_RATE,
  429. AVG_INC_RATE,
  430. CUR_LOSS_RATE,
  431. AVG_LOSS_RATE,
  432. } rate_stat_type;
  433. class Peer {
  434. public:
  435. friend class PeerHelper;
  436. Peer(Address address_,u16 id_,Connection* connection) :
  437. id(id_),
  438. m_connection(connection),
  439. address(address_),
  440. m_last_timeout_check(porting::getTimeMs())
  441. {
  442. };
  443. virtual ~Peer() {
  444. MutexAutoLock usage_lock(m_exclusive_access_mutex);
  445. FATAL_ERROR_IF(m_usage != 0, "Reference counting failure");
  446. };
  447. // Unique id of the peer
  448. u16 id;
  449. void Drop();
  450. virtual void PutReliableSendCommand(ConnectionCommand &c,
  451. unsigned int max_packet_size) {};
  452. virtual bool getAddress(MTProtocols type, Address& toset) = 0;
  453. bool isPendingDeletion()
  454. { MutexAutoLock lock(m_exclusive_access_mutex); return m_pending_deletion; };
  455. void ResetTimeout()
  456. {MutexAutoLock lock(m_exclusive_access_mutex); m_timeout_counter = 0.0; };
  457. bool isTimedOut(float timeout);
  458. unsigned int m_increment_packets_remaining = 9;
  459. unsigned int m_increment_bytes_remaining = 0;
  460. virtual u16 getNextSplitSequenceNumber(u8 channel) { return 0; };
  461. virtual void setNextSplitSequenceNumber(u8 channel, u16 seqnum) {};
  462. virtual SharedBuffer<u8> addSplitPacket(u8 channel, const BufferedPacket &toadd,
  463. bool reliable)
  464. {
  465. fprintf(stderr,"Peer: addSplitPacket called, this is supposed to be never called!\n");
  466. return SharedBuffer<u8>(0);
  467. };
  468. virtual bool Ping(float dtime, SharedBuffer<u8>& data) { return false; };
  469. virtual float getStat(rtt_stat_type type) const {
  470. switch (type) {
  471. case MIN_RTT:
  472. return m_rtt.min_rtt;
  473. case MAX_RTT:
  474. return m_rtt.max_rtt;
  475. case AVG_RTT:
  476. return m_rtt.avg_rtt;
  477. case MIN_JITTER:
  478. return m_rtt.jitter_min;
  479. case MAX_JITTER:
  480. return m_rtt.jitter_max;
  481. case AVG_JITTER:
  482. return m_rtt.jitter_avg;
  483. }
  484. return -1;
  485. }
  486. protected:
  487. virtual void reportRTT(float rtt) {};
  488. void RTTStatistics(float rtt,
  489. const std::string &profiler_id = "",
  490. unsigned int num_samples = 1000);
  491. bool IncUseCount();
  492. void DecUseCount();
  493. std::mutex m_exclusive_access_mutex;
  494. bool m_pending_deletion = false;
  495. Connection* m_connection;
  496. // Address of the peer
  497. Address address;
  498. // Ping timer
  499. float m_ping_timer = 0.0f;
  500. private:
  501. struct rttstats {
  502. float jitter_min = FLT_MAX;
  503. float jitter_max = 0.0f;
  504. float jitter_avg = -1.0f;
  505. float min_rtt = FLT_MAX;
  506. float max_rtt = 0.0f;
  507. float avg_rtt = -1.0f;
  508. rttstats() = default;
  509. };
  510. rttstats m_rtt;
  511. float m_last_rtt = -1.0f;
  512. // current usage count
  513. unsigned int m_usage = 0;
  514. // Seconds from last receive
  515. float m_timeout_counter = 0.0f;
  516. u64 m_last_timeout_check;
  517. };
  518. class UDPPeer : public Peer
  519. {
  520. public:
  521. friend class PeerHelper;
  522. friend class ConnectionReceiveThread;
  523. friend class ConnectionSendThread;
  524. friend class Connection;
  525. UDPPeer(u16 a_id, Address a_address, Connection* connection);
  526. virtual ~UDPPeer() = default;
  527. void PutReliableSendCommand(ConnectionCommand &c,
  528. unsigned int max_packet_size);
  529. bool getAddress(MTProtocols type, Address& toset);
  530. u16 getNextSplitSequenceNumber(u8 channel);
  531. void setNextSplitSequenceNumber(u8 channel, u16 seqnum);
  532. SharedBuffer<u8> addSplitPacket(u8 channel, const BufferedPacket &toadd,
  533. bool reliable);
  534. protected:
  535. /*
  536. Calculates avg_rtt and resend_timeout.
  537. rtt=-1 only recalculates resend_timeout
  538. */
  539. void reportRTT(float rtt);
  540. void RunCommandQueues(
  541. unsigned int max_packet_size,
  542. unsigned int maxcommands,
  543. unsigned int maxtransfer);
  544. float getResendTimeout()
  545. { MutexAutoLock lock(m_exclusive_access_mutex); return resend_timeout; }
  546. void setResendTimeout(float timeout)
  547. { MutexAutoLock lock(m_exclusive_access_mutex); resend_timeout = timeout; }
  548. bool Ping(float dtime,SharedBuffer<u8>& data);
  549. Channel channels[CHANNEL_COUNT];
  550. bool m_pending_disconnect = false;
  551. private:
  552. // This is changed dynamically
  553. float resend_timeout = 0.5;
  554. bool processReliableSendCommand(
  555. ConnectionCommand &c,
  556. unsigned int max_packet_size);
  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. session_t 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(session_t peer_id_, const SharedBuffer<u8> &data_)
  593. {
  594. type = CONNEVENT_DATA_RECEIVED;
  595. peer_id = peer_id_;
  596. data = data_;
  597. }
  598. void peerAdded(session_t peer_id_, Address address_)
  599. {
  600. type = CONNEVENT_PEER_ADDED;
  601. peer_id = peer_id_;
  602. address = address_;
  603. }
  604. void peerRemoved(session_t 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 PeerHandler;
  617. class Connection
  618. {
  619. public:
  620. friend class ConnectionSendThread;
  621. friend class ConnectionReceiveThread;
  622. Connection(u32 protocol_id, u32 max_packet_size, float timeout, bool ipv6,
  623. PeerHandler *peerhandler);
  624. ~Connection();
  625. /* Interface */
  626. ConnectionEvent waitEvent(u32 timeout_ms);
  627. void putCommand(ConnectionCommand &c);
  628. void SetTimeoutMs(u32 timeout) { m_bc_receive_timeout = timeout; }
  629. void Serve(Address bind_addr);
  630. void Connect(Address address);
  631. bool Connected();
  632. void Disconnect();
  633. void Receive(NetworkPacket* pkt);
  634. void Send(session_t peer_id, u8 channelnum, NetworkPacket *pkt, bool reliable);
  635. session_t GetPeerID() const { return m_peer_id; }
  636. Address GetPeerAddress(session_t peer_id);
  637. float getPeerStat(session_t peer_id, rtt_stat_type type);
  638. float getLocalStat(rate_stat_type type);
  639. const u32 GetProtocolID() const { return m_protocol_id; };
  640. const std::string getDesc();
  641. void DisconnectPeer(session_t peer_id);
  642. protected:
  643. PeerHelper getPeerNoEx(session_t peer_id);
  644. u16 lookupPeer(Address& sender);
  645. u16 createPeer(Address& sender, MTProtocols protocol, int fd);
  646. UDPPeer* createServerPeer(Address& sender);
  647. bool deletePeer(session_t peer_id, bool timeout);
  648. void SetPeerID(session_t id) { m_peer_id = id; }
  649. void sendAck(session_t peer_id, u8 channelnum, u16 seqnum);
  650. void PrintInfo(std::ostream &out);
  651. std::list<session_t> getPeerIDs()
  652. {
  653. MutexAutoLock peerlock(m_peers_mutex);
  654. return m_peer_ids;
  655. }
  656. UDPSocket m_udpSocket;
  657. MutexedQueue<ConnectionCommand> m_command_queue;
  658. void putEvent(ConnectionEvent &e);
  659. void TriggerSend();
  660. private:
  661. MutexedQueue<ConnectionEvent> m_event_queue;
  662. session_t m_peer_id = 0;
  663. u32 m_protocol_id;
  664. std::map<session_t, Peer *> m_peers;
  665. std::list<session_t> m_peer_ids;
  666. std::mutex m_peers_mutex;
  667. std::unique_ptr<ConnectionSendThread> m_sendThread;
  668. std::unique_ptr<ConnectionReceiveThread> m_receiveThread;
  669. std::mutex m_info_mutex;
  670. // Backwards compatibility
  671. PeerHandler *m_bc_peerhandler;
  672. u32 m_bc_receive_timeout = 0;
  673. bool m_shutting_down = false;
  674. session_t m_next_remote_peer_id = 2;
  675. };
  676. } // namespace