3 Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com>
5 This program is free software; you can redistribute it and/or modify
6 it under the terms of the GNU Lesser General Public License as published by
7 the Free Software Foundation; either version 2.1 of the License, or
8 (at your option) any later version.
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 GNU Lesser General Public License for more details.
15 You should have received a copy of the GNU Lesser General Public License along
16 with this program; if not, write to the Free Software Foundation, Inc.,
17 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
20 #ifndef CONNECTION_HEADER
21 #define CONNECTION_HEADER
23 #include "irrlichttypes_bloated.h"
25 #include "exceptions.h"
26 #include "constants.h"
27 #include "util/pointer.h"
28 #include "util/container.h"
29 #include "util/thread.h"
30 #include "util/numeric.h"
42 class NotFoundException : public BaseException
45 NotFoundException(const char *s):
50 class PeerNotFoundException : public BaseException
53 PeerNotFoundException(const char *s):
58 class ConnectionException : public BaseException
61 ConnectionException(const char *s):
66 class ConnectionBindFailed : public BaseException
69 ConnectionBindFailed(const char *s):
74 class InvalidIncomingDataException : public BaseException
77 InvalidIncomingDataException(const char *s):
82 class InvalidOutgoingDataException : public BaseException
85 InvalidOutgoingDataException(const char *s):
90 class NoIncomingDataException : public BaseException
93 NoIncomingDataException(const char *s):
98 class ProcessedSilentlyException : public BaseException
101 ProcessedSilentlyException(const char *s):
106 class ProcessedQueued : public BaseException
109 ProcessedQueued(const char *s):
114 class IncomingDataCorruption : public BaseException
117 IncomingDataCorruption(const char *s):
122 typedef enum MTProtocols {
125 MINETEST_RELIABLE_UDP
128 #define SEQNUM_MAX 65535
129 inline bool seqnum_higher(u16 totest, u16 base)
133 if((totest - base) > (SEQNUM_MAX/2))
140 if((base - totest) > (SEQNUM_MAX/2))
147 inline bool seqnum_in_window(u16 seqnum, u16 next,u16 window_size)
149 u16 window_start = next;
150 u16 window_end = ( next + window_size ) % (SEQNUM_MAX+1);
152 if (window_start < window_end)
154 return ((seqnum >= window_start) && (seqnum < window_end));
158 return ((seqnum < window_end) || (seqnum >= window_start));
162 struct BufferedPacket
164 BufferedPacket(u8 *a_data, u32 a_size):
165 data(a_data, a_size), time(0.0), totaltime(0.0), absolute_send_time(-1)
167 BufferedPacket(u32 a_size):
168 data(a_size), time(0.0), totaltime(0.0), absolute_send_time(-1)
170 SharedBuffer<u8> data; // Data of the packet, including headers
171 float time; // Seconds from buffering the packet or re-sending
172 float totaltime; // Seconds from buffering the packet
173 unsigned int absolute_send_time;
174 Address address; // Sender or destination
177 // This adds the base headers to the data and makes a packet out of it
178 BufferedPacket makePacket(Address &address, u8 *data, u32 datasize,
179 u32 protocol_id, u16 sender_peer_id, u8 channel);
180 BufferedPacket makePacket(Address &address, SharedBuffer<u8> &data,
181 u32 protocol_id, u16 sender_peer_id, u8 channel);
183 // Add the TYPE_ORIGINAL header to the data
184 SharedBuffer<u8> makeOriginalPacket(
185 SharedBuffer<u8> data);
187 // Split data in chunks and add TYPE_SPLIT headers to them
188 std::list<SharedBuffer<u8> > makeSplitPacket(
189 SharedBuffer<u8> data,
193 // Depending on size, make a TYPE_ORIGINAL or TYPE_SPLIT packet
194 // Increments split_seqnum if a split packet is made
195 std::list<SharedBuffer<u8> > makeAutoSplitPacket(
196 SharedBuffer<u8> data,
200 // Add the TYPE_RELIABLE header to the data
201 SharedBuffer<u8> makeReliablePacket(
202 SharedBuffer<u8> data,
205 struct IncomingSplitPacket
207 IncomingSplitPacket()
212 // Key is chunk number, value is data without headers
213 std::map<u16, SharedBuffer<u8> > chunks;
215 float time; // Seconds from adding
216 bool reliable; // If true, isn't deleted on timeout
220 return (chunks.size() == chunk_count);
227 A packet is sent through a channel to a peer with a basic header:
228 TODO: Should we have a receiver_peer_id also?
231 [4] u16 sender_peer_id
235 value 0 (PEER_ID_INEXISTENT) is reserved for making new connections
236 value 1 (PEER_ID_SERVER) is reserved for server
237 these constants are defined in constants.h
239 The lower the number, the higher the priority is.
240 Only channels 0, 1 and 2 exist.
242 #define BASE_HEADER_SIZE 7
243 #define CHANNEL_COUNT 3
247 CONTROL: This is a packet used by the protocol.
248 - When this is processed, nothing is handed to the user.
252 controltype and data description:
255 CONTROLTYPE_SET_PEER_ID
258 - There is no actual reply, but this can be sent in a reliable
259 packet to get a reply
262 #define TYPE_CONTROL 0
263 #define CONTROLTYPE_ACK 0
264 #define CONTROLTYPE_SET_PEER_ID 1
265 #define CONTROLTYPE_PING 2
266 #define CONTROLTYPE_DISCO 3
267 #define CONTROLTYPE_ENABLE_BIG_SEND_WINDOW 4
270 ORIGINAL: This is a plain packet with no control and no error
272 - When this is processed, it is directly handed to the user.
276 #define TYPE_ORIGINAL 1
277 #define ORIGINAL_HEADER_SIZE 1
279 SPLIT: These are sequences of packets forming one bigger piece of
281 - When processed and all the packet_nums 0...packet_count-1 are
282 present (this should be buffered), the resulting data shall be
283 directly handed to the user.
284 - If the data fails to come up in a reasonable time, the buffer shall
285 be silently discarded.
286 - These can be sent as-is or atop of a RELIABLE packet stream.
295 RELIABLE: Delivery of all RELIABLE packets shall be forced by ACKs,
296 and they shall be delivered in the same order as sent. This is done
297 with a buffer in the receiving and transmitting end.
298 - When this is processed, the contents of each packet is recursively
299 processed as packets.
305 #define TYPE_RELIABLE 3
306 #define RELIABLE_HEADER_SIZE 3
307 #define SEQNUM_INITIAL 65500
310 A buffer which stores reliable packets and sorts them internally
311 for fast access to the smallest one.
314 typedef std::list<BufferedPacket>::iterator RPBSearchResult;
316 class ReliablePacketBuffer
319 ReliablePacketBuffer();
321 bool getFirstSeqnum(u16& result);
323 BufferedPacket popFirst();
324 BufferedPacket popSeqnum(u16 seqnum);
325 void insert(BufferedPacket &p,u16 next_expected);
327 void incrementTimeouts(float dtime);
328 std::list<BufferedPacket> getTimedOuts(float timeout,
329 unsigned int max_packets);
333 bool containsPacket(u16 seqnum);
334 RPBSearchResult notFound();
339 RPBSearchResult findPacket(u16 seqnum);
341 std::list<BufferedPacket> m_list;
344 u16 m_oldest_non_answered_ack;
348 unsigned int writeptr;
352 A buffer for reconstructing split packets
355 class IncomingSplitBuffer
358 ~IncomingSplitBuffer();
360 Returns a reference counted buffer of length != 0 when a full split
361 packet is constructed. If not, returns one of length 0.
363 SharedBuffer<u8> insert(BufferedPacket &p, bool reliable);
365 void removeUnreliableTimedOuts(float dtime, float timeout);
369 std::map<u16, IncomingSplitPacket*> m_buf;
374 struct OutgoingPacket
378 SharedBuffer<u8> data;
382 OutgoingPacket(u16 peer_id_, u8 channelnum_, SharedBuffer<u8> data_,
383 bool reliable_,bool ack_=false):
385 channelnum(channelnum_),
393 enum ConnectionCommandType{
398 CONNCMD_DISCONNECT_PEER,
403 CONCMD_DISABLE_LEGACY
406 struct ConnectionCommand
408 enum ConnectionCommandType type;
417 ConnectionCommand(): type(CONNCMD_NONE), peer_id(PEER_ID_INEXISTENT), reliable(false), raw(false) {}
419 void serve(u16 port_)
421 type = CONNCMD_SERVE;
424 void connect(Address address_)
426 type = CONNCMD_CONNECT;
431 type = CONNCMD_DISCONNECT;
433 void disconnect_peer(u16 peer_id_)
435 type = CONNCMD_DISCONNECT_PEER;
438 void send(u16 peer_id_, u8 channelnum_,
439 SharedBuffer<u8> data_, bool reliable_)
443 channelnum = channelnum_;
445 reliable = reliable_;
447 void sendToAll(u8 channelnum_, SharedBuffer<u8> data_, bool reliable_)
449 type = CONNCMD_SEND_TO_ALL;
450 channelnum = channelnum_;
452 reliable = reliable_;
455 void ack(u16 peer_id_, u8 channelnum_, SharedBuffer<u8> data_)
459 channelnum = channelnum_;
464 void createPeer(u16 peer_id_, SharedBuffer<u8> data_)
466 type = CONCMD_CREATE_PEER;
474 void disableLegacy(u16 peer_id_, SharedBuffer<u8> data_)
476 type = CONCMD_DISABLE_LEGACY;
489 u16 readNextIncomingSeqNum();
490 u16 incNextIncomingSeqNum();
492 u16 getOutgoingSequenceNumber(bool& successfull);
493 u16 readOutgoingSequenceNumber();
494 bool putBackSequenceNumber(u16);
496 u16 readNextSplitSeqNum();
497 void setNextSplitSeqNum(u16 seqnum);
499 // This is for buffering the incoming packets that are coming in
501 ReliablePacketBuffer incoming_reliables;
502 // This is for buffering the sent packets so that the sender can
503 // re-send them if no ACK is received
504 ReliablePacketBuffer outgoing_reliables_sent;
506 //queued reliable packets
507 Queue<BufferedPacket> queued_reliables;
509 //queue commands prior splitting to packets
510 Queue<ConnectionCommand> queued_commands;
512 IncomingSplitBuffer incoming_splits;
517 void UpdatePacketLossCounter(unsigned int count);
518 void UpdatePacketTooLateCounter();
519 void UpdateBytesSent(unsigned int bytes,unsigned int packages=1);
520 void UpdateBytesLost(unsigned int bytes);
522 void UpdateTimers(float dtime);
524 const float getCurrentDownloadRateKB()
525 { JMutexAutoLock lock(m_internal_mutex); return cur_kbps; };
526 const float getMaxDownloadRateKB()
527 { JMutexAutoLock lock(m_internal_mutex); return max_kbps; };
529 const float getCurrentLossRateKB()
530 { JMutexAutoLock lock(m_internal_mutex); return cur_kbps_lost; };
531 const float getMaxLossRateKB()
532 { JMutexAutoLock lock(m_internal_mutex); return max_kbps_lost; };
534 const float getAvgDownloadRateKB()
535 { JMutexAutoLock lock(m_internal_mutex); return avg_kbps; };
536 const float getAvgLossRateKB()
537 { JMutexAutoLock lock(m_internal_mutex); return avg_kbps_lost; };
539 const unsigned int getWindowSize() const { return window_size; };
541 void setWindowSize(unsigned int size) { window_size = size; };
543 JMutex m_internal_mutex;
544 unsigned int window_size;
546 u16 next_incoming_seqnum;
548 u16 next_outgoing_seqnum;
549 u16 next_outgoing_split_seqnum;
551 unsigned int current_packet_loss;
552 unsigned int current_packet_too_late;
553 unsigned int current_packet_successfull;
554 float packet_loss_counter;
556 unsigned int current_bytes_transfered;
557 unsigned int current_bytes_lost;
588 virtual ~PeerHandler()
593 This is called after the Peer has been inserted into the
594 Connection's peer container.
596 virtual void peerAdded(Peer *peer) = 0;
598 This is called before the Peer has been removed from the
599 Connection's peer container.
601 virtual void deletingPeer(Peer *peer, bool timeout) = 0;
608 PeerHelper(Peer* peer);
611 PeerHelper& operator=(Peer* peer);
612 Peer* operator->() const;
614 Peer* operator&() const;
615 bool operator!=(void* ptr);
623 typedef enum rtt_stat_type {
634 friend class PeerHelper;
636 Peer(Address address_,u16 id_,Connection* connection) :
638 m_increment_packets_remaining(9),
639 m_increment_bytes_remaining(0),
640 m_pending_deletion(false),
641 m_connection(connection),
646 m_timeout_counter(0.0),
647 m_last_timeout_check(porting::getTimeMs()),
648 m_has_sent_with_id(false)
650 m_rtt.avg_rtt = -1.0;
651 m_rtt.jitter_avg = -1.0;
652 m_rtt.jitter_max = 0.0;
654 m_rtt.jitter_min = FLT_MAX;
655 m_rtt.min_rtt = FLT_MAX;
659 JMutexAutoLock usage_lock(m_exclusive_access_mutex);
660 assert(m_usage == 0);
663 // Unique id of the peer
668 virtual void PutReliableSendCommand(ConnectionCommand &c,
669 unsigned int max_packet_size) {};
671 virtual bool isActive() { return false; };
673 virtual bool getAddress(MTProtocols type, Address& toset) = 0;
676 {JMutexAutoLock lock(m_exclusive_access_mutex); m_timeout_counter=0.0; };
678 bool isTimedOut(float timeout);
681 { JMutexAutoLock lock(m_exclusive_access_mutex); m_has_sent_with_id = true; };
684 { JMutexAutoLock lock(m_exclusive_access_mutex); return m_has_sent_with_id; };
686 unsigned int m_increment_packets_remaining;
687 unsigned int m_increment_bytes_remaining;
689 virtual u16 getNextSplitSequenceNumber(u8 channel) { return 0; };
690 virtual void setNextSplitSequenceNumber(u8 channel, u16 seqnum) {};
691 virtual SharedBuffer<u8> addSpiltPacket(u8 channel,
692 BufferedPacket toadd,
695 fprintf(stderr,"Peer: addSplitPacket called, this is supposed to be never called!\n");
696 return SharedBuffer<u8>(0);
699 virtual bool Ping(float dtime, SharedBuffer<u8>& data) { return false; };
701 virtual float getStat(rtt_stat_type type) const {
704 return m_rtt.min_rtt;
706 return m_rtt.max_rtt;
708 return m_rtt.avg_rtt;
710 return m_rtt.jitter_min;
712 return m_rtt.jitter_max;
714 return m_rtt.jitter_avg;
719 virtual void reportRTT(float rtt) {};
721 void RTTStatistics(float rtt,
722 std::string profiler_id="",
723 unsigned int num_samples=1000);
728 JMutex m_exclusive_access_mutex;
730 bool m_pending_deletion;
732 Connection* m_connection;
734 // Address of the peer
753 // current usage count
754 unsigned int m_usage;
756 // Seconds from last receive
757 float m_timeout_counter;
759 u32 m_last_timeout_check;
761 bool m_has_sent_with_id;
764 class UDPPeer : public Peer
768 friend class PeerHelper;
769 friend class ConnectionReceiveThread;
770 friend class ConnectionSendThread;
772 UDPPeer(u16 a_id, Address a_address, Connection* connection);
773 virtual ~UDPPeer() {};
775 void PutReliableSendCommand(ConnectionCommand &c,
776 unsigned int max_packet_size);
779 { return ((hasSentWithID()) && (!m_pending_deletion)); };
781 bool getAddress(MTProtocols type, Address& toset);
783 void setNonLegacyPeer();
786 { return m_legacy_peer; }
788 u16 getNextSplitSequenceNumber(u8 channel);
789 void setNextSplitSequenceNumber(u8 channel, u16 seqnum);
791 SharedBuffer<u8> addSpiltPacket(u8 channel,
792 BufferedPacket toadd,
798 Calculates avg_rtt and resend_timeout.
799 rtt=-1 only recalculates resend_timeout
801 void reportRTT(float rtt);
803 void RunCommandQueues(
804 unsigned int max_packet_size,
805 unsigned int maxcommands,
806 unsigned int maxtransfer);
808 float getResendTimeout()
809 { JMutexAutoLock lock(m_exclusive_access_mutex); return resend_timeout; }
811 void setResendTimeout(float timeout)
812 { JMutexAutoLock lock(m_exclusive_access_mutex); resend_timeout = timeout; }
813 bool Ping(float dtime,SharedBuffer<u8>& data);
815 Channel channels[CHANNEL_COUNT];
816 bool m_pending_disconnect;
818 // This is changed dynamically
819 float resend_timeout;
821 bool processReliableSendCommand(
822 ConnectionCommand &c,
823 unsigned int max_packet_size);
832 enum ConnectionEventType{
834 CONNEVENT_DATA_RECEIVED,
835 CONNEVENT_PEER_ADDED,
836 CONNEVENT_PEER_REMOVED,
837 CONNEVENT_BIND_FAILED,
840 struct ConnectionEvent
842 enum ConnectionEventType type;
848 ConnectionEvent(): type(CONNEVENT_NONE) {}
850 std::string describe()
854 return "CONNEVENT_NONE";
855 case CONNEVENT_DATA_RECEIVED:
856 return "CONNEVENT_DATA_RECEIVED";
857 case CONNEVENT_PEER_ADDED:
858 return "CONNEVENT_PEER_ADDED";
859 case CONNEVENT_PEER_REMOVED:
860 return "CONNEVENT_PEER_REMOVED";
861 case CONNEVENT_BIND_FAILED:
862 return "CONNEVENT_BIND_FAILED";
864 return "Invalid ConnectionEvent";
867 void dataReceived(u16 peer_id_, SharedBuffer<u8> data_)
869 type = CONNEVENT_DATA_RECEIVED;
873 void peerAdded(u16 peer_id_, Address address_)
875 type = CONNEVENT_PEER_ADDED;
879 void peerRemoved(u16 peer_id_, bool timeout_, Address address_)
881 type = CONNEVENT_PEER_REMOVED;
888 type = CONNEVENT_BIND_FAILED;
892 class ConnectionSendThread : public JThread {
895 friend class UDPPeer;
897 ConnectionSendThread(Connection* parent,
898 unsigned int max_packet_size, float timeout);
904 void setPeerTimeout(float peer_timeout)
905 { m_timeout = peer_timeout; }
908 void runTimeouts (float dtime);
909 void rawSend (const BufferedPacket &packet);
910 bool rawSendAsPacket(u16 peer_id, u8 channelnum,
911 SharedBuffer<u8> data, bool reliable);
913 void processReliableCommand (ConnectionCommand &c);
914 void processNonReliableCommand (ConnectionCommand &c);
915 void serve (u16 port);
916 void connect (Address address);
918 void disconnect_peer(u16 peer_id);
919 void send (u16 peer_id, u8 channelnum,
920 SharedBuffer<u8> data);
921 void sendReliable (ConnectionCommand &c);
922 void sendToAll (u8 channelnum,
923 SharedBuffer<u8> data);
924 void sendToAllReliable(ConnectionCommand &c);
926 void sendPackets (float dtime);
928 void sendAsPacket (u16 peer_id, u8 channelnum,
929 SharedBuffer<u8> data,bool ack=false);
931 void sendAsPacketReliable(BufferedPacket& p, Channel* channel);
933 bool packetsQueued();
935 Connection* m_connection;
936 unsigned int m_max_packet_size;
938 Queue<OutgoingPacket> m_outgoing_queue;
939 JSemaphore m_send_sleep_semaphore;
941 unsigned int m_iteration_packets_avaialble;
942 unsigned int m_max_commands_per_iteration;
943 unsigned int m_max_data_packets_per_iteration;
944 unsigned int m_max_packets_requeued;
947 class ConnectionReceiveThread : public JThread {
949 ConnectionReceiveThread(Connection* parent,
950 unsigned int max_packet_size);
957 // Returns next data from a buffer if possible
958 // If found, returns true; if not, false.
959 // If found, sets peer_id and dst
960 bool getFromBuffers (u16 &peer_id, SharedBuffer<u8> &dst);
962 bool checkIncomingBuffers(Channel *channel, u16 &peer_id,
963 SharedBuffer<u8> &dst);
966 Processes a packet with the basic header stripped out.
968 packetdata: Data in packet (with no base headers)
969 peer_id: peer id of the sender of the packet in question
970 channelnum: channel on which the packet was sent
971 reliable: true if recursing into a reliable packet
973 SharedBuffer<u8> processPacket(Channel *channel,
974 SharedBuffer<u8> packetdata, u16 peer_id,
975 u8 channelnum, bool reliable);
978 Connection* m_connection;
979 unsigned int m_max_packet_size;
985 friend class ConnectionSendThread;
986 friend class ConnectionReceiveThread;
988 Connection(u32 protocol_id, u32 max_packet_size, float timeout, bool ipv6);
989 Connection(u32 protocol_id, u32 max_packet_size, float timeout, bool ipv6,
990 PeerHandler *peerhandler);
994 ConnectionEvent getEvent();
995 ConnectionEvent waitEvent(u32 timeout_ms);
996 void putCommand(ConnectionCommand &c);
998 void SetTimeoutMs(int timeout){ m_bc_receive_timeout = timeout; }
999 void Serve(unsigned short port);
1000 void Connect(Address address);
1003 u32 Receive(u16 &peer_id, SharedBuffer<u8> &data);
1004 void SendToAll(u8 channelnum, SharedBuffer<u8> data, bool reliable);
1005 void Send(u16 peer_id, u8 channelnum, SharedBuffer<u8> data, bool reliable);
1006 u16 GetPeerID(){ return m_peer_id; }
1007 Address GetPeerAddress(u16 peer_id);
1008 float GetPeerAvgRTT(u16 peer_id);
1009 const u32 GetProtocolID() const { return m_protocol_id; };
1010 const std::string getDesc();
1011 void DisconnectPeer(u16 peer_id);
1014 PeerHelper getPeer(u16 peer_id);
1015 PeerHelper getPeerNoEx(u16 peer_id);
1016 u16 lookupPeer(Address& sender);
1018 u16 createPeer(Address& sender, MTProtocols protocol, int fd);
1019 UDPPeer* createServerPeer(Address& sender);
1020 bool deletePeer(u16 peer_id, bool timeout);
1022 void SetPeerID(u16 id){ m_peer_id = id; }
1024 void sendAck(u16 peer_id, u8 channelnum, u16 seqnum);
1026 void PrintInfo(std::ostream &out);
1029 std::list<u16> getPeerIDs();
1031 UDPSocket m_udpSocket;
1032 MutexedQueue<ConnectionCommand> m_command_queue;
1034 void putEvent(ConnectionEvent &e);
1037 { m_sendThread.Trigger(); }
1039 std::list<Peer*> getPeers();
1041 MutexedQueue<ConnectionEvent> m_event_queue;
1046 std::map<u16, Peer*> m_peers;
1047 JMutex m_peers_mutex;
1049 ConnectionSendThread m_sendThread;
1050 ConnectionReceiveThread m_receiveThread;
1052 JMutex m_info_mutex;
1054 // Backwards compatibility
1055 PeerHandler *m_bc_peerhandler;
1056 int m_bc_receive_timeout;
1058 bool m_shutting_down;
1060 u16 m_next_remote_peer_id;