connection.h 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785
  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.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 <vector>
  28. #include <map>
  29. #define MAX_UDP_PEERS 65535
  30. /*
  31. === NOTES ===
  32. A packet is sent through a channel to a peer with a basic header:
  33. Header (7 bytes):
  34. [0] u32 protocol_id
  35. [4] session_t sender_peer_id
  36. [6] u8 channel
  37. sender_peer_id:
  38. Unique to each peer.
  39. value 0 (PEER_ID_INEXISTENT) is reserved for making new connections
  40. value 1 (PEER_ID_SERVER) is reserved for server
  41. these constants are defined in constants.h
  42. channel:
  43. Channel numbers have no intrinsic meaning. Currently only 0, 1, 2 exist.
  44. */
  45. #define BASE_HEADER_SIZE 7
  46. #define CHANNEL_COUNT 3
  47. /*
  48. Packet types:
  49. CONTROL: This is a packet used by the protocol.
  50. - When this is processed, nothing is handed to the user.
  51. Header (2 byte):
  52. [0] u8 type
  53. [1] u8 controltype
  54. controltype and data description:
  55. CONTROLTYPE_ACK
  56. [2] u16 seqnum
  57. CONTROLTYPE_SET_PEER_ID
  58. [2] session_t peer_id_new
  59. CONTROLTYPE_PING
  60. - There is no actual reply, but this can be sent in a reliable
  61. packet to get a reply
  62. CONTROLTYPE_DISCO
  63. */
  64. enum ControlType : u8 {
  65. CONTROLTYPE_ACK = 0,
  66. CONTROLTYPE_SET_PEER_ID = 1,
  67. CONTROLTYPE_PING = 2,
  68. CONTROLTYPE_DISCO = 3,
  69. };
  70. /*
  71. ORIGINAL: This is a plain packet with no control and no error
  72. checking at all.
  73. - When this is processed, it is directly handed to the user.
  74. Header (1 byte):
  75. [0] u8 type
  76. */
  77. //#define TYPE_ORIGINAL 1
  78. #define ORIGINAL_HEADER_SIZE 1
  79. /*
  80. SPLIT: These are sequences of packets forming one bigger piece of
  81. data.
  82. - When processed and all the packet_nums 0...packet_count-1 are
  83. present (this should be buffered), the resulting data shall be
  84. directly handed to the user.
  85. - If the data fails to come up in a reasonable time, the buffer shall
  86. be silently discarded.
  87. - These can be sent as-is or atop of a RELIABLE packet stream.
  88. Header (7 bytes):
  89. [0] u8 type
  90. [1] u16 seqnum
  91. [3] u16 chunk_count
  92. [5] u16 chunk_num
  93. */
  94. //#define TYPE_SPLIT 2
  95. /*
  96. RELIABLE: Delivery of all RELIABLE packets shall be forced by ACKs,
  97. and they shall be delivered in the same order as sent. This is done
  98. with a buffer in the receiving and transmitting end.
  99. - When this is processed, the contents of each packet is recursively
  100. processed as packets.
  101. Header (3 bytes):
  102. [0] u8 type
  103. [1] u16 seqnum
  104. */
  105. //#define TYPE_RELIABLE 3
  106. #define RELIABLE_HEADER_SIZE 3
  107. #define SEQNUM_INITIAL 65500
  108. #define SEQNUM_MAX 65535
  109. class NetworkPacket;
  110. namespace con
  111. {
  112. class ConnectionReceiveThread;
  113. class ConnectionSendThread;
  114. typedef enum MTProtocols {
  115. MTP_PRIMARY,
  116. MTP_UDP,
  117. MTP_MINETEST_RELIABLE_UDP
  118. } MTProtocols;
  119. enum PacketType : u8 {
  120. PACKET_TYPE_CONTROL = 0,
  121. PACKET_TYPE_ORIGINAL = 1,
  122. PACKET_TYPE_SPLIT = 2,
  123. PACKET_TYPE_RELIABLE = 3,
  124. PACKET_TYPE_MAX
  125. };
  126. inline bool seqnum_higher(u16 totest, u16 base)
  127. {
  128. if (totest > base)
  129. {
  130. if ((totest - base) > (SEQNUM_MAX/2))
  131. return false;
  132. return true;
  133. }
  134. if ((base - totest) > (SEQNUM_MAX/2))
  135. return true;
  136. return false;
  137. }
  138. inline bool seqnum_in_window(u16 seqnum, u16 next,u16 window_size)
  139. {
  140. u16 window_start = next;
  141. u16 window_end = ( next + window_size ) % (SEQNUM_MAX+1);
  142. if (window_start < window_end) {
  143. return ((seqnum >= window_start) && (seqnum < window_end));
  144. }
  145. return ((seqnum < window_end) || (seqnum >= window_start));
  146. }
  147. static inline float CALC_DTIME(u64 lasttime, u64 curtime)
  148. {
  149. float value = ( curtime - lasttime) / 1000.0;
  150. return MYMAX(MYMIN(value,0.1),0.0);
  151. }
  152. /*
  153. Struct for all kinds of packets. Includes following data:
  154. BASE_HEADER
  155. u8[] packet data (usually copied from SharedBuffer<u8>)
  156. */
  157. struct BufferedPacket {
  158. BufferedPacket(u32 a_size)
  159. {
  160. m_data.resize(a_size);
  161. data = &m_data[0];
  162. }
  163. DISABLE_CLASS_COPY(BufferedPacket)
  164. u16 getSeqnum() const;
  165. inline size_t size() const { return m_data.size(); }
  166. u8 *data; // Direct memory access
  167. float time = 0.0f; // Seconds from buffering the packet or re-sending
  168. float totaltime = 0.0f; // Seconds from buffering the packet
  169. u64 absolute_send_time = -1;
  170. Address address; // Sender or destination
  171. unsigned int resend_count = 0;
  172. private:
  173. std::vector<u8> m_data; // Data of the packet, including headers
  174. };
  175. typedef std::shared_ptr<BufferedPacket> BufferedPacketPtr;
  176. // This adds the base headers to the data and makes a packet out of it
  177. BufferedPacketPtr makePacket(Address &address, const SharedBuffer<u8> &data,
  178. u32 protocol_id, session_t sender_peer_id, u8 channel);
  179. // Depending on size, make a TYPE_ORIGINAL or TYPE_SPLIT packet
  180. // Increments split_seqnum if a split packet is made
  181. void makeAutoSplitPacket(const SharedBuffer<u8> &data, u32 chunksize_max,
  182. u16 &split_seqnum, std::list<SharedBuffer<u8>> *list);
  183. // Add the TYPE_RELIABLE header to the data
  184. SharedBuffer<u8> makeReliablePacket(const SharedBuffer<u8> &data, u16 seqnum);
  185. struct IncomingSplitPacket
  186. {
  187. IncomingSplitPacket(u32 cc, bool r):
  188. chunk_count(cc), reliable(r) {}
  189. IncomingSplitPacket() = delete;
  190. float time = 0.0f; // Seconds from adding
  191. u32 chunk_count;
  192. bool reliable; // If true, isn't deleted on timeout
  193. bool allReceived() const
  194. {
  195. return (chunks.size() == chunk_count);
  196. }
  197. bool insert(u32 chunk_num, SharedBuffer<u8> &chunkdata);
  198. SharedBuffer<u8> reassemble();
  199. private:
  200. // Key is chunk number, value is data without headers
  201. std::map<u16, SharedBuffer<u8>> chunks;
  202. };
  203. /*
  204. A buffer which stores reliable packets and sorts them internally
  205. for fast access to the smallest one.
  206. */
  207. typedef std::list<BufferedPacketPtr>::iterator RPBSearchResult;
  208. class ReliablePacketBuffer
  209. {
  210. public:
  211. ReliablePacketBuffer() = default;
  212. bool getFirstSeqnum(u16& result);
  213. BufferedPacketPtr popFirst();
  214. BufferedPacketPtr popSeqnum(u16 seqnum);
  215. void insert(BufferedPacketPtr &p_ptr, u16 next_expected);
  216. void incrementTimeouts(float dtime);
  217. std::list<ConstSharedPtr<BufferedPacket>> getTimedOuts(float timeout, u32 max_packets);
  218. void print();
  219. bool empty();
  220. u32 size();
  221. private:
  222. RPBSearchResult findPacketNoLock(u16 seqnum);
  223. std::list<BufferedPacketPtr> m_list;
  224. u16 m_oldest_non_answered_ack;
  225. std::mutex m_list_mutex;
  226. };
  227. /*
  228. A buffer for reconstructing split packets
  229. */
  230. class IncomingSplitBuffer
  231. {
  232. public:
  233. ~IncomingSplitBuffer();
  234. /*
  235. Returns a reference counted buffer of length != 0 when a full split
  236. packet is constructed. If not, returns one of length 0.
  237. */
  238. SharedBuffer<u8> insert(BufferedPacketPtr &p_ptr, bool reliable);
  239. void removeUnreliableTimedOuts(float dtime, float timeout);
  240. private:
  241. // Key is seqnum
  242. std::map<u16, IncomingSplitPacket*> m_buf;
  243. std::mutex m_map_mutex;
  244. };
  245. enum ConnectionCommandType{
  246. CONNCMD_NONE,
  247. CONNCMD_SERVE,
  248. CONNCMD_CONNECT,
  249. CONNCMD_DISCONNECT,
  250. CONNCMD_DISCONNECT_PEER,
  251. CONNCMD_SEND,
  252. CONNCMD_SEND_TO_ALL,
  253. CONCMD_ACK,
  254. CONCMD_CREATE_PEER
  255. };
  256. struct ConnectionCommand;
  257. typedef std::shared_ptr<ConnectionCommand> ConnectionCommandPtr;
  258. // This is very similar to ConnectionEvent
  259. struct ConnectionCommand
  260. {
  261. const ConnectionCommandType type;
  262. Address address;
  263. session_t peer_id = PEER_ID_INEXISTENT;
  264. u8 channelnum = 0;
  265. Buffer<u8> data;
  266. bool reliable = false;
  267. bool raw = false;
  268. DISABLE_CLASS_COPY(ConnectionCommand);
  269. static ConnectionCommandPtr serve(Address address);
  270. static ConnectionCommandPtr connect(Address address);
  271. static ConnectionCommandPtr disconnect();
  272. static ConnectionCommandPtr disconnect_peer(session_t peer_id);
  273. static ConnectionCommandPtr send(session_t peer_id, u8 channelnum, NetworkPacket *pkt, bool reliable);
  274. static ConnectionCommandPtr ack(session_t peer_id, u8 channelnum, const Buffer<u8> &data);
  275. static ConnectionCommandPtr createPeer(session_t peer_id, const Buffer<u8> &data);
  276. private:
  277. ConnectionCommand(ConnectionCommandType type_) :
  278. type(type_) {}
  279. static ConnectionCommandPtr create(ConnectionCommandType type);
  280. };
  281. /* maximum window size to use, 0xFFFF is theoretical maximum. don't think about
  282. * touching it, the less you're away from it the more likely data corruption
  283. * will occur
  284. */
  285. #define MAX_RELIABLE_WINDOW_SIZE 0x8000
  286. /* starting value for window size */
  287. #define START_RELIABLE_WINDOW_SIZE 0x400
  288. /* minimum value for window size */
  289. #define MIN_RELIABLE_WINDOW_SIZE 0x40
  290. class Channel
  291. {
  292. public:
  293. u16 readNextIncomingSeqNum();
  294. u16 incNextIncomingSeqNum();
  295. u16 getOutgoingSequenceNumber(bool& successful);
  296. u16 readOutgoingSequenceNumber();
  297. bool putBackSequenceNumber(u16);
  298. u16 readNextSplitSeqNum();
  299. void setNextSplitSeqNum(u16 seqnum);
  300. // This is for buffering the incoming packets that are coming in
  301. // the wrong order
  302. ReliablePacketBuffer incoming_reliables;
  303. // This is for buffering the sent packets so that the sender can
  304. // re-send them if no ACK is received
  305. ReliablePacketBuffer outgoing_reliables_sent;
  306. //queued reliable packets
  307. std::queue<BufferedPacketPtr> queued_reliables;
  308. //queue commands prior splitting to packets
  309. std::deque<ConnectionCommandPtr> queued_commands;
  310. IncomingSplitBuffer incoming_splits;
  311. Channel() = default;
  312. ~Channel() = default;
  313. void UpdatePacketLossCounter(unsigned int count);
  314. void UpdatePacketTooLateCounter();
  315. void UpdateBytesSent(unsigned int bytes,unsigned int packages=1);
  316. void UpdateBytesLost(unsigned int bytes);
  317. void UpdateBytesReceived(unsigned int bytes);
  318. void UpdateTimers(float dtime);
  319. float getCurrentDownloadRateKB()
  320. { MutexAutoLock lock(m_internal_mutex); return cur_kbps; };
  321. float getMaxDownloadRateKB()
  322. { MutexAutoLock lock(m_internal_mutex); return max_kbps; };
  323. float getCurrentLossRateKB()
  324. { MutexAutoLock lock(m_internal_mutex); return cur_kbps_lost; };
  325. float getMaxLossRateKB()
  326. { MutexAutoLock lock(m_internal_mutex); return max_kbps_lost; };
  327. float getCurrentIncomingRateKB()
  328. { MutexAutoLock lock(m_internal_mutex); return cur_incoming_kbps; };
  329. float getMaxIncomingRateKB()
  330. { MutexAutoLock lock(m_internal_mutex); return max_incoming_kbps; };
  331. float getAvgDownloadRateKB()
  332. { MutexAutoLock lock(m_internal_mutex); return avg_kbps; };
  333. float getAvgLossRateKB()
  334. { MutexAutoLock lock(m_internal_mutex); return avg_kbps_lost; };
  335. float getAvgIncomingRateKB()
  336. { MutexAutoLock lock(m_internal_mutex); return avg_incoming_kbps; };
  337. u16 getWindowSize() const { return m_window_size; };
  338. void setWindowSize(long size)
  339. {
  340. m_window_size = (u16)rangelim(size, MIN_RELIABLE_WINDOW_SIZE, MAX_RELIABLE_WINDOW_SIZE);
  341. }
  342. private:
  343. std::mutex m_internal_mutex;
  344. u16 m_window_size = MIN_RELIABLE_WINDOW_SIZE;
  345. u16 next_incoming_seqnum = SEQNUM_INITIAL;
  346. u16 next_outgoing_seqnum = SEQNUM_INITIAL;
  347. u16 next_outgoing_split_seqnum = SEQNUM_INITIAL;
  348. unsigned int current_packet_loss = 0;
  349. unsigned int current_packet_too_late = 0;
  350. unsigned int current_packet_successful = 0;
  351. float packet_loss_counter = 0.0f;
  352. unsigned int current_bytes_transfered = 0;
  353. unsigned int current_bytes_received = 0;
  354. unsigned int current_bytes_lost = 0;
  355. float max_kbps = 0.0f;
  356. float cur_kbps = 0.0f;
  357. float avg_kbps = 0.0f;
  358. float max_incoming_kbps = 0.0f;
  359. float cur_incoming_kbps = 0.0f;
  360. float avg_incoming_kbps = 0.0f;
  361. float max_kbps_lost = 0.0f;
  362. float cur_kbps_lost = 0.0f;
  363. float avg_kbps_lost = 0.0f;
  364. float bpm_counter = 0.0f;
  365. unsigned int rate_samples = 0;
  366. };
  367. class Peer;
  368. class PeerHelper
  369. {
  370. public:
  371. PeerHelper() = default;
  372. PeerHelper(Peer* peer);
  373. ~PeerHelper();
  374. PeerHelper& operator=(Peer* peer);
  375. Peer* operator->() const;
  376. bool operator!();
  377. Peer* operator&() const;
  378. bool operator!=(void* ptr);
  379. private:
  380. Peer *m_peer = nullptr;
  381. };
  382. class Connection;
  383. typedef enum {
  384. CUR_DL_RATE,
  385. AVG_DL_RATE,
  386. CUR_INC_RATE,
  387. AVG_INC_RATE,
  388. CUR_LOSS_RATE,
  389. AVG_LOSS_RATE,
  390. } rate_stat_type;
  391. class Peer {
  392. public:
  393. friend class PeerHelper;
  394. Peer(Address address_,session_t id_,Connection* connection) :
  395. id(id_),
  396. m_connection(connection),
  397. address(address_),
  398. m_last_timeout_check(porting::getTimeMs())
  399. {
  400. };
  401. virtual ~Peer() {
  402. MutexAutoLock usage_lock(m_exclusive_access_mutex);
  403. FATAL_ERROR_IF(m_usage != 0, "Reference counting failure");
  404. };
  405. // Unique id of the peer
  406. const session_t id;
  407. void Drop();
  408. virtual void PutReliableSendCommand(ConnectionCommandPtr &c,
  409. unsigned int max_packet_size) {};
  410. virtual bool getAddress(MTProtocols type, Address& toset) = 0;
  411. bool isPendingDeletion()
  412. { MutexAutoLock lock(m_exclusive_access_mutex); return m_pending_deletion; };
  413. void ResetTimeout()
  414. {MutexAutoLock lock(m_exclusive_access_mutex); m_timeout_counter = 0.0; };
  415. bool isTimedOut(float timeout);
  416. unsigned int m_increment_packets_remaining = 0;
  417. virtual u16 getNextSplitSequenceNumber(u8 channel) { return 0; };
  418. virtual void setNextSplitSequenceNumber(u8 channel, u16 seqnum) {};
  419. virtual SharedBuffer<u8> addSplitPacket(u8 channel, BufferedPacketPtr &toadd,
  420. bool reliable)
  421. {
  422. errorstream << "Peer::addSplitPacket called,"
  423. << " this is supposed to be never called!" << std::endl;
  424. return SharedBuffer<u8>(0);
  425. };
  426. virtual bool Ping(float dtime, SharedBuffer<u8>& data) { return false; };
  427. virtual float getStat(rtt_stat_type type) const {
  428. switch (type) {
  429. case MIN_RTT:
  430. return m_rtt.min_rtt;
  431. case MAX_RTT:
  432. return m_rtt.max_rtt;
  433. case AVG_RTT:
  434. return m_rtt.avg_rtt;
  435. case MIN_JITTER:
  436. return m_rtt.jitter_min;
  437. case MAX_JITTER:
  438. return m_rtt.jitter_max;
  439. case AVG_JITTER:
  440. return m_rtt.jitter_avg;
  441. }
  442. return -1;
  443. }
  444. protected:
  445. virtual void reportRTT(float rtt) {};
  446. void RTTStatistics(float rtt,
  447. const std::string &profiler_id = "",
  448. unsigned int num_samples = 1000);
  449. bool IncUseCount();
  450. void DecUseCount();
  451. mutable std::mutex m_exclusive_access_mutex;
  452. bool m_pending_deletion = false;
  453. Connection* m_connection;
  454. // Address of the peer
  455. Address address;
  456. // Ping timer
  457. float m_ping_timer = 0.0f;
  458. private:
  459. struct rttstats {
  460. float jitter_min = FLT_MAX;
  461. float jitter_max = 0.0f;
  462. float jitter_avg = -1.0f;
  463. float min_rtt = FLT_MAX;
  464. float max_rtt = 0.0f;
  465. float avg_rtt = -1.0f;
  466. rttstats() = default;
  467. };
  468. rttstats m_rtt;
  469. float m_last_rtt = -1.0f;
  470. // current usage count
  471. unsigned int m_usage = 0;
  472. // Seconds from last receive
  473. float m_timeout_counter = 0.0f;
  474. u64 m_last_timeout_check;
  475. };
  476. class UDPPeer : public Peer
  477. {
  478. public:
  479. friend class PeerHelper;
  480. friend class ConnectionReceiveThread;
  481. friend class ConnectionSendThread;
  482. friend class Connection;
  483. UDPPeer(u16 a_id, Address a_address, Connection* connection);
  484. virtual ~UDPPeer() = default;
  485. void PutReliableSendCommand(ConnectionCommandPtr &c,
  486. unsigned int max_packet_size);
  487. bool getAddress(MTProtocols type, Address& toset);
  488. u16 getNextSplitSequenceNumber(u8 channel);
  489. void setNextSplitSequenceNumber(u8 channel, u16 seqnum);
  490. SharedBuffer<u8> addSplitPacket(u8 channel, BufferedPacketPtr &toadd,
  491. bool reliable);
  492. protected:
  493. /*
  494. Calculates avg_rtt and resend_timeout.
  495. rtt=-1 only recalculates resend_timeout
  496. */
  497. void reportRTT(float rtt);
  498. void RunCommandQueues(
  499. unsigned int max_packet_size,
  500. unsigned int maxcommands,
  501. unsigned int maxtransfer);
  502. float getResendTimeout()
  503. { MutexAutoLock lock(m_exclusive_access_mutex); return resend_timeout; }
  504. void setResendTimeout(float timeout)
  505. { MutexAutoLock lock(m_exclusive_access_mutex); resend_timeout = timeout; }
  506. bool Ping(float dtime,SharedBuffer<u8>& data);
  507. Channel channels[CHANNEL_COUNT];
  508. bool m_pending_disconnect = false;
  509. private:
  510. // This is changed dynamically
  511. float resend_timeout = 0.5;
  512. bool processReliableSendCommand(
  513. ConnectionCommandPtr &c_ptr,
  514. unsigned int max_packet_size);
  515. };
  516. /*
  517. Connection
  518. */
  519. enum ConnectionEventType {
  520. CONNEVENT_NONE,
  521. CONNEVENT_DATA_RECEIVED,
  522. CONNEVENT_PEER_ADDED,
  523. CONNEVENT_PEER_REMOVED,
  524. CONNEVENT_BIND_FAILED,
  525. };
  526. struct ConnectionEvent;
  527. typedef std::shared_ptr<ConnectionEvent> ConnectionEventPtr;
  528. // This is very similar to ConnectionCommand
  529. struct ConnectionEvent
  530. {
  531. const ConnectionEventType type;
  532. session_t peer_id = 0;
  533. Buffer<u8> data;
  534. bool timeout = false;
  535. Address address;
  536. // We don't want to copy "data"
  537. DISABLE_CLASS_COPY(ConnectionEvent);
  538. static ConnectionEventPtr create(ConnectionEventType type);
  539. static ConnectionEventPtr dataReceived(session_t peer_id, const Buffer<u8> &data);
  540. static ConnectionEventPtr peerAdded(session_t peer_id, Address address);
  541. static ConnectionEventPtr peerRemoved(session_t peer_id, bool is_timeout, Address address);
  542. static ConnectionEventPtr bindFailed();
  543. const char *describe() const;
  544. private:
  545. ConnectionEvent(ConnectionEventType type_) :
  546. type(type_) {}
  547. };
  548. class PeerHandler;
  549. class Connection
  550. {
  551. public:
  552. friend class ConnectionSendThread;
  553. friend class ConnectionReceiveThread;
  554. Connection(u32 protocol_id, u32 max_packet_size, float timeout, bool ipv6,
  555. PeerHandler *peerhandler);
  556. ~Connection();
  557. /* Interface */
  558. ConnectionEventPtr waitEvent(u32 timeout_ms);
  559. void putCommand(ConnectionCommandPtr c);
  560. void SetTimeoutMs(u32 timeout) { m_bc_receive_timeout = timeout; }
  561. void Serve(Address bind_addr);
  562. void Connect(Address address);
  563. bool Connected();
  564. void Disconnect();
  565. void Receive(NetworkPacket* pkt);
  566. bool TryReceive(NetworkPacket *pkt);
  567. void Send(session_t peer_id, u8 channelnum, NetworkPacket *pkt, bool reliable);
  568. session_t GetPeerID() const { return m_peer_id; }
  569. Address GetPeerAddress(session_t peer_id);
  570. float getPeerStat(session_t peer_id, rtt_stat_type type);
  571. float getLocalStat(rate_stat_type type);
  572. u32 GetProtocolID() const { return m_protocol_id; };
  573. const std::string getDesc();
  574. void DisconnectPeer(session_t peer_id);
  575. protected:
  576. PeerHelper getPeerNoEx(session_t peer_id);
  577. u16 lookupPeer(Address& sender);
  578. u16 createPeer(Address& sender, MTProtocols protocol, int fd);
  579. UDPPeer* createServerPeer(Address& sender);
  580. bool deletePeer(session_t peer_id, bool timeout);
  581. void SetPeerID(session_t id) { m_peer_id = id; }
  582. void sendAck(session_t peer_id, u8 channelnum, u16 seqnum);
  583. std::vector<session_t> getPeerIDs()
  584. {
  585. MutexAutoLock peerlock(m_peers_mutex);
  586. return m_peer_ids;
  587. }
  588. UDPSocket m_udpSocket;
  589. // Command queue: user -> SendThread
  590. MutexedQueue<ConnectionCommandPtr> m_command_queue;
  591. bool Receive(NetworkPacket *pkt, u32 timeout);
  592. void putEvent(ConnectionEventPtr e);
  593. void TriggerSend();
  594. bool ConnectedToServer()
  595. {
  596. return getPeerNoEx(PEER_ID_SERVER) != nullptr;
  597. }
  598. private:
  599. // Event queue: ReceiveThread -> user
  600. MutexedQueue<ConnectionEventPtr> m_event_queue;
  601. session_t m_peer_id = 0;
  602. u32 m_protocol_id;
  603. std::map<session_t, Peer *> m_peers;
  604. std::vector<session_t> m_peer_ids;
  605. std::mutex m_peers_mutex;
  606. std::unique_ptr<ConnectionSendThread> m_sendThread;
  607. std::unique_ptr<ConnectionReceiveThread> m_receiveThread;
  608. mutable std::mutex m_info_mutex;
  609. // Backwards compatibility
  610. PeerHandler *m_bc_peerhandler;
  611. u32 m_bc_receive_timeout = 0;
  612. bool m_shutting_down = false;
  613. session_t m_next_remote_peer_id = 2;
  614. };
  615. } // namespace