00001
00002
00003
00004
00005
00006
00007
00008
00009 #ifndef __RAK_PEER_H
00010 #define __RAK_PEER_H
00011
00012 #include "ReliabilityLayer.h"
00013 #include "RakPeerInterface.h"
00014 #include "RPCNode.h"
00015 #include "RSACrypt.h"
00016 #include "BitStream.h"
00017 #include "SingleProducerConsumer.h"
00018 #include "RPCMap.h"
00019 #include "SimpleMutex.h"
00020 #include "DS_OrderedList.h"
00021 #include "Export.h"
00022 #include "RakString.h"
00023 #include "RakThread.h"
00024 #include "RakNetSocket.h"
00025 #include "RakNetSmartPtr.h"
00026 #include "DS_ThreadsafeAllocatingQueue.h"
00027 #include "SignaledEvent.h"
00028
00029 class HuffmanEncodingTree;
00030 class PluginInterface2;
00031
00032
00033
00034 struct RemoteSystemIndex{unsigned index; RemoteSystemIndex *next;};
00035
00036
00037
00038
00046 class RAK_DLL_EXPORT RakPeer : public RakPeerInterface
00047 {
00048 public:
00050 RakPeer();
00051
00053 virtual ~RakPeer();
00054
00055
00068 bool Startup( unsigned short maxConnections, int _threadSleepTimer, SocketDescriptor *socketDescriptors, unsigned socketDescriptorCount, int threadPriority=-99999 );
00069
00080 void InitializeSecurity(const char *pubKeyE, const char *pubKeyN, const char *privKeyP, const char *privKeyQ );
00081
00084 void DisableSecurity( void );
00085
00091 void AddToSecurityExceptionList(const char *ip);
00092
00095 void RemoveFromSecurityExceptionList(const char *ip);
00096
00100 bool IsInSecurityExceptionList(const char *ip);
00101
00109 void SetMaximumIncomingConnections( unsigned short numberAllowed );
00110
00113 unsigned short GetMaximumIncomingConnections( void ) const;
00114
00117 unsigned short NumberOfConnections(void) const;
00118
00125 void SetIncomingPassword( const char* passwordData, int passwordDataLength );
00126
00130 void GetIncomingPassword( char* passwordData, int *passwordDataLength );
00131
00152 bool Connect( const char* host, unsigned short remotePort, const char *passwordData, int passwordDataLength, unsigned connectionSocketIndex=0, unsigned sendConnectionAttemptCount=12, unsigned timeBetweenSendConnectionAttemptsMS=500, RakNetTime timeoutTime=0 );
00153
00165 virtual bool ConnectWithSocket(const char* host, unsigned short remotePort, const char *passwordData, int passwordDataLength, RakNetSmartPtr<RakNetSocket> socket, unsigned sendConnectionAttemptCount=12, unsigned timeBetweenSendConnectionAttemptsMS=500, RakNetTime timeoutTime=0);
00166
00167
00172
00173
00179 void Shutdown( unsigned int blockDuration, unsigned char orderingChannel=0, PacketPriority disconnectionNotificationPriority=LOW_PRIORITY );
00180
00183 bool IsActive( void ) const;
00184
00188 bool GetConnectionList( SystemAddress *remoteSystems, unsigned short *numberOfSystems ) const;
00189
00193 virtual uint32_t GetNextSendReceipt(void);
00194
00198 virtual uint32_t IncrementNextSendReceipt(void);
00199
00212 uint32_t Send( const char *data, const int length, PacketPriority priority, PacketReliability reliability, char orderingChannel, const AddressOrGUID systemIdentifier, bool broadcast, uint32_t forceReceipt=0 );
00213
00220 void SendLoopback( const char *data, const int length );
00221
00234 uint32_t Send( const RakNet::BitStream * bitStream, PacketPriority priority, PacketReliability reliability, char orderingChannel, const AddressOrGUID systemIdentifier, bool broadcast, uint32_t forceReceipt=0 );
00235
00257 uint32_t SendList( const char **data, const int *lengths, const int numParameters, PacketPriority priority, PacketReliability reliability, char orderingChannel, const AddressOrGUID systemIdentifier, bool broadcast, uint32_t forceReceipt=0 );
00258
00265 Packet* Receive( void );
00266
00269 void DeallocatePacket( Packet *packet );
00270
00273 unsigned short GetMaximumNumberOfPeers( void ) const;
00274
00275
00281 void RegisterAsRemoteProcedureCall( const char* uniqueID, void ( *functionPointer ) ( RPCParameters *rpcParms ) );
00282
00289 void RegisterClassMemberRPC( const char* uniqueID, void *functionPointer );
00290
00295 void UnregisterAsRemoteProcedureCall( const char* uniqueID );
00296
00301 void SetNetworkIDManager( NetworkIDManager *manager );
00302
00304 NetworkIDManager *GetNetworkIDManager(void) const;
00305
00324 bool RPC( const char* uniqueID, const char *data, BitSize_t bitLength, PacketPriority priority, PacketReliability reliability, char orderingChannel, const AddressOrGUID systemIdentifier, bool broadcast, RakNetTime *includedTimestamp, NetworkID networkID, RakNet::BitStream *replyFromTarget );
00325
00333
00347
00348
00349
00356
00357
00361
00362
00365
00366
00373
00374
00380
00381
00387
00388
00392
00393
00398
00399
00404
00405
00408
00409
00411
00412
00416
00417
00421
00422
00423
00427
00428
00437
00438
00442
00443
00447
00448
00452
00453
00458
00459
00460
00466
00467
00472
00473
00474
00479
00480
00483
00484
00491
00492
00498
00499
00504
00505
00509
00510
00511
00523
00527
00528
00531
00532
00536
00537
00542
00543
00547
00548
00558
00559
00565
00566
00569
00570
00575
00576
00584
00585
00586
00592
00593
00600
00601
00612
00613
00620
00621
00625
00626
00630
00631
00632
00636
00637
00641
00642
00643
00648
00649
00653
00655
00656
00659
00660
00661
00666
00667
00672
00673
00679
00680
00684
00685
00687
00688
00692
00693
00694
00703
00704
00709
00710
00713
00714
00715
00716
00723
00726
00727
00729
00730
00731
00733
00734
00736
00737
00738
00739
00742
00743
00744
00745
00746
00747
00750
00751
00752
00753
00754
00755
00756
00757
00758
00759
00760
00761
00762
00763
00764
00765
00766
00767
00768
00769
00770
00771
00772
00773
00774
00775
00776
00777
00778
00779
00780
00781
00782
00783
00784
00785
00786
00787
00788
00789
00790
00791
00792
00793
00794
00795
00796 friend void ProcessPortUnreachable( const unsigned int binaryAddress, const unsigned short port, RakPeer *rakPeer );
00797 friend bool ProcessOfflineNetworkPacket( const SystemAddress systemAddress, const char *data, const int length, RakPeer *rakPeer, RakNetSmartPtr<RakNetSocket> rakNetSocket, bool *isOfflineMessage, RakNetTimeUS timeRead );
00798 friend void ProcessNetworkPacket( const SystemAddress systemAddress, const char *data, const int length, RakPeer *rakPeer, RakNetSmartPtr<RakNetSocket> rakNetSocket, RakNetTimeUS timeRead );
00799 friend void ProcessNetworkPacket( const SystemAddress systemAddress, const char *data, const int length, RakPeer *rakPeer, RakNetTimeUS timeRead );
00800
00801
00802 Packet* ReceiveIgnoreRPC( void );
00803
00804 int GetIndexFromSystemAddress( const SystemAddress systemAddress, bool calledFromNetworkThread ) const;
00805 int GetIndexFromGuid( const RakNetGUID guid );
00806
00807
00808
00809 bool SendConnectionRequest( const char* host, unsigned short remotePort, const char *passwordData, int passwordDataLength, unsigned connectionSocketIndex, unsigned int extraData, unsigned sendConnectionAttemptCount, unsigned timeBetweenSendConnectionAttemptsMS, RakNetTime timeoutTime, RakNetSmartPtr<RakNetSocket> socket );
00810 bool SendConnectionRequest( const char* host, unsigned short remotePort, const char *passwordData, int passwordDataLength, unsigned connectionSocketIndex, unsigned int extraData, unsigned sendConnectionAttemptCount, unsigned timeBetweenSendConnectionAttemptsMS, RakNetTime timeoutTime );
00814 RemoteSystemStruct *GetRemoteSystemFromSystemAddress( const SystemAddress systemAddress, bool calledFromNetworkThread, bool onlyActive ) const;
00815 RakPeer::RemoteSystemStruct *GetRemoteSystem( const AddressOrGUID systemIdentifier, bool calledFromNetworkThread, bool onlyActive ) const;
00816 void ValidateRemoteSystemLookup(void) const;
00817 RemoteSystemStruct *GetRemoteSystemFromGUID( const RakNetGUID guid, bool onlyActive ) const;
00819 void ParseConnectionRequestPacket( RakPeer::RemoteSystemStruct *remoteSystem, SystemAddress systemAddress, const char *data, int byteSize);
00821 void OnConnectionRequest( RakPeer::RemoteSystemStruct *remoteSystem, unsigned char *AESKey, bool setAESKey, RakNetTime incomingTimestamp );
00822 void SendConnectionRequestAccepted(RakPeer::RemoteSystemStruct *remoteSystem, RakNetTime incomingTimestamp);
00824 void NotifyAndFlagForShutdown( const SystemAddress systemAddress, bool performImmediate, unsigned char orderingChannel, PacketPriority disconnectionNotificationPriority );
00826 unsigned short GetNumberOfRemoteInitiatedConnections( void ) const;
00835 RemoteSystemStruct * AssignSystemAddressToRemoteSystemList( const SystemAddress systemAddress, RemoteSystemStruct::ConnectMode connectionMode, RakNetSmartPtr<RakNetSocket> incomingRakNetSocket, bool *thisIPConnectedRecently, SystemAddress bindingAddress, int incomingMTU, RakNetGUID guid );
00839 void ShiftIncomingTimestamp( unsigned char *data, SystemAddress systemAddress ) const;
00843 RakNetTime GetBestClockDifferential( const SystemAddress systemAddress ) const;
00844
00845
00851 bool HandleRPCPacket( const char *data, int length, SystemAddress systemAddress );
00852
00857 void HandleRPCReplyPacket( const char *data, int length, SystemAddress systemAddress );
00858
00859 bool IsLoopbackAddress(const AddressOrGUID &systemIdentifier, bool matchPort) const;
00860 SystemAddress GetLoopbackAddress(void) const;
00861
00863 volatile bool endThreads;
00865 volatile bool isMainLoopThreadActive,isRecvFromLoopThreadActive;
00866 bool occasionalPing;
00867
00868 unsigned short maximumNumberOfPeers;
00869
00871
00873 unsigned short maximumIncomingConnections;
00874 RakNet::BitStream offlinePingResponse;
00876 SystemAddress mySystemAddress[MAXIMUM_NUMBER_OF_INTERNAL_IDS];
00877 char incomingPassword[256];
00878 unsigned char incomingPasswordLength;
00879
00884 RemoteSystemStruct* remoteSystemList;
00885
00886
00887 RemoteSystemIndex **remoteSystemLookup;
00888 unsigned int RemoteSystemLookupHashIndex(SystemAddress sa) const;
00889 void ReferenceRemoteSystem(SystemAddress sa, unsigned int remoteSystemListIndex);
00890 void DereferenceRemoteSystem(SystemAddress sa);
00891 RemoteSystemStruct* GetRemoteSystem(SystemAddress sa) const;
00892 unsigned int GetRemoteSystemIndex(SystemAddress sa) const;
00893 void ClearRemoteSystemLookup(void);
00894 DataStructures::MemoryPool<RemoteSystemIndex> remoteSystemIndexPool;
00895
00896
00897
00898
00899
00900 enum
00901 {
00902
00903 #ifdef _RAKNET_THREADSAFE
00904 requestedConnectionList_Mutex,
00905 #endif
00906 offlinePingResponse_Mutex,
00907 NUMBER_OF_RAKPEER_MUTEXES
00908 };
00909 SimpleMutex rakPeerMutexes[ NUMBER_OF_RAKPEER_MUTEXES ];
00911
00912 bool updateCycleIsRunning;
00914
00915
00917
00918 unsigned int bytesSentPerSecond, bytesReceivedPerSecond;
00919
00920
00921 unsigned int validationInteger;
00922 SimpleMutex incomingQueueMutex, banListMutex;
00923
00924
00925
00926 struct BanStruct
00927 {
00928 char *IP;
00929 RakNetTime timeout;
00930 };
00931
00932 struct RequestedConnectionStruct
00933 {
00934 SystemAddress systemAddress;
00935 RakNetTime nextRequestTime;
00936 unsigned char requestsMade;
00937 char *data;
00938 unsigned short dataLength;
00939 char outgoingPassword[256];
00940 unsigned char outgoingPasswordLength;
00941 unsigned socketIndex;
00942 unsigned int extraData;
00943 unsigned sendConnectionAttemptCount;
00944 unsigned timeBetweenSendConnectionAttemptsMS;
00945 RakNetTime timeoutTime;
00946 RakNetSmartPtr<RakNetSocket> socket;
00947 enum {CONNECT=1, } actionToTake;
00948 };
00949
00950
00951 DataStructures::List<BanStruct*> banList;
00952 DataStructures::List<PluginInterface2*> messageHandlerList;
00953
00954 DataStructures::Queue<RequestedConnectionStruct*> requestedConnectionQueue;
00955 SimpleMutex requestedConnectionQueueMutex;
00956
00958 unsigned int frequencyTable[ 256 ];
00959 HuffmanEncodingTree *inputTree, *outputTree;
00960 unsigned int rawBytesSent, rawBytesReceived, compressedBytesSent, compressedBytesReceived;
00961
00962
00963 void GenerateSYNCookieRandomNumber( void );
00964 void SecuredConnectionResponse( const SystemAddress systemAddress );
00965 void SecuredConnectionConfirmation( RakPeer::RemoteSystemStruct * remoteSystem, char* data );
00966 bool RunUpdateCycle( void );
00967
00968
00969 struct BufferedCommandStruct
00970 {
00971 BitSize_t numberOfBitsToSend;
00972 PacketPriority priority;
00973 PacketReliability reliability;
00974 char orderingChannel;
00975 AddressOrGUID systemIdentifier;
00976 bool broadcast;
00977 RemoteSystemStruct::ConnectMode connectionMode;
00978 NetworkID networkID;
00979 bool blockingCommand;
00980 char *data;
00981 bool haveRakNetCloseSocket;
00982 unsigned connectionSocketIndex;
00983 unsigned short remotePortRakNetWasStartedOn_PS3;
00984 SOCKET socket;
00985 unsigned short port;
00986 uint32_t receipt;
00987 enum {BCS_SEND, BCS_CLOSE_CONNECTION, BCS_GET_SOCKET, BCS_CHANGE_SYSTEM_ADDRESS, BCS_DO_NOTHING} command;
00988 };
00989
00990
00991
00992
00993 #ifndef _RAKNET_THREADSAFE
00994 DataStructures::SingleProducerConsumer<BufferedCommandStruct> bufferedCommands;
00995 #else
00996 DataStructures::ThreadsafeAllocatingQueue<BufferedCommandStruct> bufferedCommands;
00997 #endif
00998
00999
01000 struct RecvFromStruct
01001 {
01002 #if (defined(_XBOX) || defined(_X360)) && defined(RAKNET_USE_VDP)
01003 char data[MAXIMUM_MTU_SIZE*2];
01004 #else
01005 char data[MAXIMUM_MTU_SIZE];
01006 #endif
01007 int bytesRead;
01008 SystemAddress systemAddress;
01009 RakNetTimeUS timeRead;
01010 SOCKET s;
01011 unsigned short remotePortRakNetWasStartedOn_PS3;
01012 };
01013
01014 #ifndef _RAKNET_THREADSAFE
01015 DataStructures::SingleProducerConsumer<RecvFromStruct> bufferedPackets;
01016 #else
01017 DataStructures::ThreadsafeAllocatingQueue<RecvFromStruct> bufferedPackets;
01018 #endif
01019
01020 struct SocketQueryOutput
01021 {
01022 SocketQueryOutput() {}
01023 ~SocketQueryOutput() {}
01024 DataStructures::List<RakNetSmartPtr<RakNetSocket> > sockets;
01025 };
01026 #ifndef _RAKNET_THREADSAFE
01027 DataStructures::SingleProducerConsumer< SocketQueryOutput > socketQueryOutput;
01028 #else
01029 DataStructures::ThreadsafeAllocatingQueue<SocketQueryOutput> socketQueryOutput;
01030 #endif
01031
01032 bool AllowIncomingConnections(void) const;
01033
01034 void PingInternal( const SystemAddress target, bool performImmediate, PacketReliability reliability );
01035 bool ValidSendTarget(SystemAddress systemAddress, bool broadcast);
01036
01037 void CloseConnectionInternal( const AddressOrGUID& systemIdentifier, bool sendDisconnectionNotification, bool performImmediate, unsigned char orderingChannel, PacketPriority disconnectionNotificationPriority );
01038 void SendBuffered( const char *data, BitSize_t numberOfBitsToSend, PacketPriority priority, PacketReliability reliability, char orderingChannel, const AddressOrGUID systemIdentifier, bool broadcast, RemoteSystemStruct::ConnectMode connectionMode, uint32_t receipt );
01039 void SendBufferedList( const char **data, const int *lengths, const int numParameters, PacketPriority priority, PacketReliability reliability, char orderingChannel, const AddressOrGUID systemIdentifier, bool broadcast, RemoteSystemStruct::ConnectMode connectionMode, uint32_t receipt );
01040 bool SendImmediate( char *data, BitSize_t numberOfBitsToSend, PacketPriority priority, PacketReliability reliability, char orderingChannel, const AddressOrGUID systemIdentifier, bool broadcast, bool useCallerDataAllocation, RakNetTimeUS currentTime, uint32_t receipt );
01041
01042 void ClearBufferedCommands(void);
01043 void ClearBufferedPackets(void);
01044 void ClearSocketQueryOutput(void);
01045 void ClearRequestedConnectionList(void);
01046 void AddPacketToProducer(Packet *p);
01047 unsigned int GenerateSeedFromGuid(void);
01048 SimpleMutex securityExceptionMutex;
01049
01050
01051 RPCMap rpcMap;
01052 int defaultMTUSize;
01053 bool trackFrequencyTable;
01054 int threadSleepTimer;
01055
01056
01057 DataStructures::List<RakNetSmartPtr<RakNetSocket> > socketList;
01058 void DerefAllSockets(void);
01059 unsigned int GetRakNetSocketFromUserConnectionSocketIndex(unsigned int userIndex) const;
01060
01061 RakNet::BitStream *replyFromTargetBS;
01062 SystemAddress replyFromTargetPlayer;
01063 bool replyFromTargetBroadcast;
01064
01065 RakNetTime defaultTimeoutTime;
01066
01067
01068
01069
01070
01071 bool blockOnRPCReply;
01072
01073
01074 RouterInterface *router;
01075
01076
01077 void GenerateGUID(void);
01078 unsigned int GetSystemIndexFromGuid( const RakNetGUID input ) const;
01079 RakNetGUID myGuid;
01080
01081 unsigned maxOutgoingBPS;
01082
01083
01084 #ifdef _DEBUG
01085 double _packetloss;
01086 unsigned short _minExtraPing, _extraPingVariance;
01087 #endif
01088
01089 #if !defined(_XBOX) && !defined(_WIN32_WCE) && !defined(X360)
01090
01091 RSACrypt rsacrypt;
01092 uint32_t publicKeyE;
01093 uint32_t publicKeyN[RAKNET_RSA_FACTOR_LIMBS];
01094 bool keysLocallyGenerated, usingSecurity;
01095 RakNetTime randomNumberExpirationTime;
01096 unsigned char newRandomNumber[ 20 ], oldRandomNumber[ 20 ];
01097
01098
01099
01100
01101
01102
01103
01104
01105
01106
01107 #endif
01108
01110
01112 bool allowConnectionResponseIPMigration;
01113
01114 SystemAddress firstExternalID;
01115 int splitMessageProgressInterval;
01116 RakNetTime unreliableTimeout;
01117
01118
01119
01120 NetworkIDManager *networkIDManager;
01121
01122 DataStructures::List<RakNet::RakString> securityExceptionList;
01123
01124 char ipList[ MAXIMUM_NUMBER_OF_INTERNAL_IDS ][ 16 ];
01125 unsigned int binaryAddresses[MAXIMUM_NUMBER_OF_INTERNAL_IDS];
01126
01127 bool allowInternalRouting;
01128
01129 void (*userUpdateThreadPtr)(RakPeerInterface *, void *);
01130 void *userUpdateThreadData;
01131
01132
01133 SignaledEvent quitAndDataEvents;
01134 bool limitConnectionFrequencyFromTheSameIP;
01135
01136 SimpleMutex packetAllocationPoolMutex;
01137 DataStructures::MemoryPool<Packet> packetAllocationPool;
01138
01139 SimpleMutex packetReturnMutex;
01140 DataStructures::Queue<Packet*> packetReturnQueue;
01141 Packet *AllocPacket(unsigned dataSize, const char *file, unsigned int line);
01142 Packet *AllocPacket(unsigned dataSize, unsigned char *data, const char *file, unsigned int line);
01143
01147 SimpleMutex sendReceiptSerialMutex;
01148 uint32_t sendReceiptSerial;
01149 void ResetSendReceipt(void);
01150
01151 void OnConnectedPong(RakNetTime sendPingTime, RakNetTime sendPongTime, RemoteSystemStruct *remoteSystem);
01152 };
01153
01154 #endif