RakNetTypes.h 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507
  1. /*
  2. * Copyright (c) 2014, Oculus VR, Inc.
  3. * All rights reserved.
  4. *
  5. * This source code is licensed under the BSD-style license found in the
  6. * LICENSE file in the root directory of this source tree. An additional grant
  7. * of patent rights can be found in the PATENTS file in the same directory.
  8. *
  9. */
  10. /// \file
  11. /// \brief Types used by RakNet, most of which involve user code.
  12. ///
  13. #ifndef __NETWORK_TYPES_H
  14. #define __NETWORK_TYPES_H
  15. #include "RakNetDefines.h"
  16. #include "NativeTypes.h"
  17. #include "RakNetTime.h"
  18. #include "Export.h"
  19. #include "WindowsIncludes.h"
  20. #include "XBox360Includes.h"
  21. #include "SocketIncludes.h"
  22. namespace RakNet {
  23. /// Forward declarations
  24. class RakPeerInterface;
  25. class BitStream;
  26. struct Packet;
  27. enum StartupResult
  28. {
  29. RAKNET_STARTED,
  30. RAKNET_ALREADY_STARTED,
  31. INVALID_SOCKET_DESCRIPTORS,
  32. INVALID_MAX_CONNECTIONS,
  33. SOCKET_FAMILY_NOT_SUPPORTED,
  34. SOCKET_PORT_ALREADY_IN_USE,
  35. SOCKET_FAILED_TO_BIND,
  36. SOCKET_FAILED_TEST_SEND,
  37. PORT_CANNOT_BE_ZERO,
  38. FAILED_TO_CREATE_NETWORK_THREAD,
  39. COULD_NOT_GENERATE_GUID,
  40. STARTUP_OTHER_FAILURE
  41. };
  42. enum ConnectionAttemptResult
  43. {
  44. CONNECTION_ATTEMPT_STARTED,
  45. INVALID_PARAMETER,
  46. CANNOT_RESOLVE_DOMAIN_NAME,
  47. ALREADY_CONNECTED_TO_ENDPOINT,
  48. CONNECTION_ATTEMPT_ALREADY_IN_PROGRESS,
  49. SECURITY_INITIALIZATION_FAILED
  50. };
  51. /// Returned from RakPeerInterface::GetConnectionState()
  52. enum ConnectionState
  53. {
  54. /// Connect() was called, but the process hasn't started yet
  55. IS_PENDING,
  56. /// Processing the connection attempt
  57. IS_CONNECTING,
  58. /// Is connected and able to communicate
  59. IS_CONNECTED,
  60. /// Was connected, but will disconnect as soon as the remaining messages are delivered
  61. IS_DISCONNECTING,
  62. /// A connection attempt failed and will be aborted
  63. IS_SILENTLY_DISCONNECTING,
  64. /// No longer connected
  65. IS_DISCONNECTED,
  66. /// Was never connected, or else was disconnected long enough ago that the entry has been discarded
  67. IS_NOT_CONNECTED
  68. };
  69. /// Given a number of bits, return how many bytes are needed to represent that.
  70. #define BITS_TO_BYTES(x) (((x)+7)>>3)
  71. #define BYTES_TO_BITS(x) ((x)<<3)
  72. /// \sa NetworkIDObject.h
  73. typedef unsigned char UniqueIDType;
  74. typedef unsigned short SystemIndex;
  75. typedef unsigned char RPCIndex;
  76. const int MAX_RPC_MAP_SIZE=((RPCIndex)-1)-1;
  77. const int UNDEFINED_RPC_INDEX=((RPCIndex)-1);
  78. /// First byte of a network message
  79. typedef unsigned char MessageID;
  80. typedef uint32_t BitSize_t;
  81. #if defined(_MSC_VER) && _MSC_VER > 0
  82. #define PRINTF_64_BIT_MODIFIER "I64"
  83. #else
  84. #define PRINTF_64_BIT_MODIFIER "ll"
  85. #endif
  86. /// Used with the PublicKey structure
  87. enum PublicKeyMode
  88. {
  89. /// The connection is insecure. You can also just pass 0 for the pointer to PublicKey in RakPeerInterface::Connect()
  90. PKM_INSECURE_CONNECTION,
  91. /// Accept whatever public key the server gives us. This is vulnerable to man in the middle, but does not require
  92. /// distribution of the public key in advance of connecting.
  93. PKM_ACCEPT_ANY_PUBLIC_KEY,
  94. /// Use a known remote server public key. PublicKey::remoteServerPublicKey must be non-zero.
  95. /// This is the recommended mode for secure connections.
  96. PKM_USE_KNOWN_PUBLIC_KEY,
  97. /// Use a known remote server public key AND provide a public key for the connecting client.
  98. /// PublicKey::remoteServerPublicKey, myPublicKey and myPrivateKey must be all be non-zero.
  99. /// The server must cooperate for this mode to work.
  100. /// I recommend not using this mode except for server-to-server communication as it significantly increases the CPU requirements during connections for both sides.
  101. /// Furthermore, when it is used, a connection password should be used as well to avoid DoS attacks.
  102. PKM_USE_TWO_WAY_AUTHENTICATION
  103. };
  104. /// Passed to RakPeerInterface::Connect()
  105. struct RAK_DLL_EXPORT PublicKey
  106. {
  107. /// How to interpret the public key, see above
  108. PublicKeyMode publicKeyMode;
  109. /// Pointer to a public key of length cat::EasyHandshake::PUBLIC_KEY_BYTES. See the Encryption sample.
  110. char *remoteServerPublicKey;
  111. /// (Optional) Pointer to a public key of length cat::EasyHandshake::PUBLIC_KEY_BYTES
  112. char *myPublicKey;
  113. /// (Optional) Pointer to a private key of length cat::EasyHandshake::PRIVATE_KEY_BYTES
  114. char *myPrivateKey;
  115. };
  116. /// Describes the local socket to use for RakPeer::Startup
  117. struct RAK_DLL_EXPORT SocketDescriptor
  118. {
  119. SocketDescriptor();
  120. SocketDescriptor(unsigned short _port, const char *_hostAddress);
  121. /// The local port to bind to. Pass 0 to have the OS autoassign a port.
  122. unsigned short port;
  123. /// The local network card address to bind to, such as "127.0.0.1". Pass an empty string to use INADDR_ANY.
  124. char hostAddress[32];
  125. /// IP version: For IPV4, use AF_INET (default). For IPV6, use AF_INET6. To autoselect, use AF_UNSPEC.
  126. /// IPV6 is the newer internet protocol. Instead of addresses such as natpunch.jenkinssoftware.com, you may have an address such as fe80::7c:31f7:fec4:27de%14.
  127. /// Encoding takes 16 bytes instead of 4, so IPV6 is less efficient for bandwidth.
  128. /// On the positive side, NAT Punchthrough is not needed and should not be used with IPV6 because there are enough addresses that routers do not need to create address mappings.
  129. /// RakPeer::Startup() will fail if this IP version is not supported.
  130. /// \pre RAKNET_SUPPORT_IPV6 must be set to 1 in RakNetDefines.h for AF_INET6
  131. short socketFamily;
  132. unsigned short remotePortRakNetWasStartedOn_PS3_PSP2;
  133. // Required for Google chrome
  134. _PP_Instance_ chromeInstance;
  135. // Set to true to use a blocking socket (default, do not change unless you have a reason to)
  136. bool blockingSocket;
  137. /// XBOX only: set IPPROTO_VDP if you want to use VDP. If enabled, this socket does not support broadcast to 255.255.255.255
  138. unsigned int extraSocketOptions;
  139. };
  140. extern bool NonNumericHostString( const char *host );
  141. /// \brief Network address for a system
  142. /// \details Corresponds to a network address<BR>
  143. /// This is not necessarily a unique identifier. For example, if a system has both LAN and internet connections, the system may be identified by either one, depending on who is communicating<BR>
  144. /// Therefore, you should not transmit the SystemAddress over the network and expect it to identify a system, or use it to connect to that system, except in the case where that system is not behind a NAT (such as with a dedciated server)
  145. /// Use RakNetGUID for a unique per-instance of RakPeer to identify systems
  146. struct RAK_DLL_EXPORT SystemAddress
  147. {
  148. /// Constructors
  149. SystemAddress();
  150. SystemAddress(const char *str);
  151. SystemAddress(const char *str, unsigned short port);
  152. /// SystemAddress, with RAKNET_SUPPORT_IPV6 defined, holds both an sockaddr_in6 and a sockaddr_in
  153. union// In6OrIn4
  154. {
  155. #if RAKNET_SUPPORT_IPV6==1
  156. struct sockaddr_storage sa_stor;
  157. sockaddr_in6 addr6;
  158. #endif
  159. sockaddr_in addr4;
  160. } address;
  161. /// This is not used internally, but holds a copy of the port held in the address union, so for debugging it's easier to check what port is being held
  162. unsigned short debugPort;
  163. /// \internal Return the size to write to a bitStream
  164. static int size(void);
  165. /// Hash the system address
  166. static unsigned long ToInteger( const SystemAddress &sa );
  167. /// Return the IP version, either IPV4 or IPV6
  168. /// \return Either 4 or 6
  169. unsigned char GetIPVersion(void) const;
  170. /// \internal Returns either IPPROTO_IP or IPPROTO_IPV6
  171. /// \sa GetIPVersion
  172. unsigned int GetIPPROTO(void) const;
  173. /// Call SetToLoopback(), with whatever IP version is currently held. Defaults to IPV4
  174. void SetToLoopback(void);
  175. /// Call SetToLoopback() with a specific IP version
  176. /// \param[in] ipVersion Either 4 for IPV4 or 6 for IPV6
  177. void SetToLoopback(unsigned char ipVersion);
  178. /// \return If was set to 127.0.0.1 or ::1
  179. bool IsLoopback(void) const;
  180. // Return the systemAddress as a string in the format <IP>|<Port>
  181. // Returns a static string
  182. // NOT THREADSAFE
  183. // portDelineator should not be '.', ':', '%', '-', '/', a number, or a-f
  184. const char *ToString(bool writePort=true, char portDelineator='|') const;
  185. // Return the systemAddress as a string in the format <IP>|<Port>
  186. // dest must be large enough to hold the output
  187. // portDelineator should not be '.', ':', '%', '-', '/', a number, or a-f
  188. // THREADSAFE
  189. void ToString(bool writePort, char *dest, char portDelineator='|') const;
  190. /// Set the system address from a printable IP string, for example "192.0.2.1" or "2001:db8:63b3:1::3490"
  191. /// You can write the port as well, using the portDelineator, for example "192.0.2.1|1234"
  192. /// \param[in] str A printable IP string, for example "192.0.2.1" or "2001:db8:63b3:1::3490". Pass 0 for \a str to set to UNASSIGNED_SYSTEM_ADDRESS
  193. /// \param[in] portDelineator if \a str contains a port, delineate the port with this character. portDelineator should not be '.', ':', '%', '-', '/', a number, or a-f
  194. /// \param[in] ipVersion Only used if str is a pre-defined address in the wrong format, such as 127.0.0.1 but you want ip version 6, so you can pass 6 here to do the conversion
  195. /// \note The current port is unchanged if a port is not specified in \a str
  196. /// \return True on success, false on ipVersion does not match type of passed string
  197. bool FromString(const char *str, char portDelineator='|', int ipVersion=0);
  198. /// Same as FromString(), but you explicitly set a port at the same time
  199. bool FromStringExplicitPort(const char *str, unsigned short port, int ipVersion=0);
  200. /// Copy the port from another SystemAddress structure
  201. void CopyPort( const SystemAddress& right );
  202. /// Returns if two system addresses have the same IP (port is not checked)
  203. bool EqualsExcludingPort( const SystemAddress& right ) const;
  204. /// Returns the port in host order (this is what you normally use)
  205. unsigned short GetPort(void) const;
  206. /// \internal Returns the port in network order
  207. unsigned short GetPortNetworkOrder(void) const;
  208. /// Sets the port. The port value should be in host order (this is what you normally use)
  209. /// Renamed from SetPort because of winspool.h http://edn.embarcadero.com/article/21494
  210. void SetPortHostOrder(unsigned short s);
  211. /// \internal Sets the port. The port value should already be in network order.
  212. void SetPortNetworkOrder(unsigned short s);
  213. /// Old version, for crap platforms that don't support newer socket functions
  214. bool SetBinaryAddress(const char *str, char portDelineator=':');
  215. /// Old version, for crap platforms that don't support newer socket functions
  216. void ToString_Old(bool writePort, char *dest, char portDelineator=':') const;
  217. /// \internal sockaddr_in6 requires extra data beyond just the IP and port. Copy that extra data from an existing SystemAddress that already has it
  218. void FixForIPVersion(const SystemAddress &boundAddressToSocket);
  219. bool IsLANAddress(void);
  220. SystemAddress& operator = ( const SystemAddress& input );
  221. bool operator==( const SystemAddress& right ) const;
  222. bool operator!=( const SystemAddress& right ) const;
  223. bool operator > ( const SystemAddress& right ) const;
  224. bool operator < ( const SystemAddress& right ) const;
  225. /// \internal Used internally for fast lookup. Optional (use -1 to do regular lookup). Don't transmit this.
  226. SystemIndex systemIndex;
  227. private:
  228. #if RAKNET_SUPPORT_IPV6==1
  229. void ToString_New(bool writePort, char *dest, char portDelineator) const;
  230. #endif
  231. };
  232. /// Uniquely identifies an instance of RakPeer. Use RakPeer::GetGuidFromSystemAddress() and RakPeer::GetSystemAddressFromGuid() to go between SystemAddress and RakNetGUID
  233. /// Use RakPeer::GetGuidFromSystemAddress(UNASSIGNED_SYSTEM_ADDRESS) to get your own GUID
  234. struct RAK_DLL_EXPORT RakNetGUID
  235. {
  236. RakNetGUID();
  237. explicit RakNetGUID(uint64_t _g) {g=_g; systemIndex=(SystemIndex)-1;}
  238. // uint32_t g[6];
  239. uint64_t g;
  240. // Return the GUID as a string
  241. // Returns a static string
  242. // NOT THREADSAFE
  243. const char *ToString(void) const;
  244. // Return the GUID as a string
  245. // dest must be large enough to hold the output
  246. // THREADSAFE
  247. void ToString(char *dest) const;
  248. bool FromString(const char *source);
  249. static unsigned long ToUint32( const RakNetGUID &g );
  250. RakNetGUID& operator = ( const RakNetGUID& input )
  251. {
  252. g=input.g;
  253. systemIndex=input.systemIndex;
  254. return *this;
  255. }
  256. // Used internally for fast lookup. Optional (use -1 to do regular lookup). Don't transmit this.
  257. SystemIndex systemIndex;
  258. static int size() {return (int) sizeof(uint64_t);}
  259. bool operator==( const RakNetGUID& right ) const;
  260. bool operator!=( const RakNetGUID& right ) const;
  261. bool operator > ( const RakNetGUID& right ) const;
  262. bool operator < ( const RakNetGUID& right ) const;
  263. };
  264. /// Index of an invalid SystemAddress
  265. //const SystemAddress UNASSIGNED_SYSTEM_ADDRESS =
  266. //{
  267. // 0xFFFFFFFF, 0xFFFF
  268. //};
  269. #ifndef SWIG
  270. const SystemAddress UNASSIGNED_SYSTEM_ADDRESS;
  271. const RakNetGUID UNASSIGNED_RAKNET_GUID((uint64_t)-1);
  272. #endif
  273. //{
  274. // {0xFFFFFFFF,0xFFFFFFFF,0xFFFFFFFF,0xFFFFFFFF,0xFFFFFFFF,0xFFFFFFFF}
  275. // 0xFFFFFFFFFFFFFFFF
  276. //};
  277. struct RAK_DLL_EXPORT AddressOrGUID
  278. {
  279. RakNetGUID rakNetGuid;
  280. SystemAddress systemAddress;
  281. SystemIndex GetSystemIndex(void) const {if (rakNetGuid!=UNASSIGNED_RAKNET_GUID) return rakNetGuid.systemIndex; else return systemAddress.systemIndex;}
  282. bool IsUndefined(void) const {return rakNetGuid==UNASSIGNED_RAKNET_GUID && systemAddress==UNASSIGNED_SYSTEM_ADDRESS;}
  283. void SetUndefined(void) {rakNetGuid=UNASSIGNED_RAKNET_GUID; systemAddress=UNASSIGNED_SYSTEM_ADDRESS;}
  284. static unsigned long ToInteger( const AddressOrGUID &aog );
  285. const char *ToString(bool writePort=true) const;
  286. void ToString(bool writePort, char *dest) const;
  287. AddressOrGUID() {}
  288. AddressOrGUID( const AddressOrGUID& input )
  289. {
  290. rakNetGuid=input.rakNetGuid;
  291. systemAddress=input.systemAddress;
  292. }
  293. AddressOrGUID( const SystemAddress& input )
  294. {
  295. rakNetGuid=UNASSIGNED_RAKNET_GUID;
  296. systemAddress=input;
  297. }
  298. AddressOrGUID( Packet *packet );
  299. AddressOrGUID( const RakNetGUID& input )
  300. {
  301. rakNetGuid=input;
  302. systemAddress=UNASSIGNED_SYSTEM_ADDRESS;
  303. }
  304. AddressOrGUID& operator = ( const AddressOrGUID& input )
  305. {
  306. rakNetGuid=input.rakNetGuid;
  307. systemAddress=input.systemAddress;
  308. return *this;
  309. }
  310. AddressOrGUID& operator = ( const SystemAddress& input )
  311. {
  312. rakNetGuid=UNASSIGNED_RAKNET_GUID;
  313. systemAddress=input;
  314. return *this;
  315. }
  316. AddressOrGUID& operator = ( const RakNetGUID& input )
  317. {
  318. rakNetGuid=input;
  319. systemAddress=UNASSIGNED_SYSTEM_ADDRESS;
  320. return *this;
  321. }
  322. inline bool operator==( const AddressOrGUID& right ) const {return (rakNetGuid!=UNASSIGNED_RAKNET_GUID && rakNetGuid==right.rakNetGuid) || (systemAddress!=UNASSIGNED_SYSTEM_ADDRESS && systemAddress==right.systemAddress);}
  323. };
  324. typedef uint64_t NetworkID;
  325. /// This represents a user message from another system.
  326. struct Packet
  327. {
  328. /// The system that send this packet.
  329. SystemAddress systemAddress;
  330. /// A unique identifier for the system that sent this packet, regardless of IP address (internal / external / remote system)
  331. /// Only valid once a connection has been established (ID_CONNECTION_REQUEST_ACCEPTED, or ID_NEW_INCOMING_CONNECTION)
  332. /// Until that time, will be UNASSIGNED_RAKNET_GUID
  333. RakNetGUID guid;
  334. /// The length of the data in bytes
  335. unsigned int length;
  336. /// The length of the data in bits
  337. BitSize_t bitSize;
  338. /// The data from the sender
  339. unsigned char* data;
  340. /// @internal
  341. /// Indicates whether to delete the data, or to simply delete the packet.
  342. bool deleteData;
  343. /// @internal
  344. /// If true, this message is meant for the user, not for the plugins, so do not process it through plugins
  345. bool wasGeneratedLocally;
  346. };
  347. /// Index of an unassigned player
  348. const SystemIndex UNASSIGNED_PLAYER_INDEX = 65535;
  349. /// Unassigned object ID
  350. const NetworkID UNASSIGNED_NETWORK_ID = (uint64_t) -1;
  351. const int PING_TIMES_ARRAY_SIZE = 5;
  352. struct RAK_DLL_EXPORT uint24_t
  353. {
  354. uint32_t val;
  355. uint24_t() {}
  356. inline operator uint32_t() { return val; }
  357. inline operator uint32_t() const { return val; }
  358. inline uint24_t(const uint24_t& a) {val=a.val;}
  359. inline uint24_t operator++() {++val; val&=0x00FFFFFF; return *this;}
  360. inline uint24_t operator--() {--val; val&=0x00FFFFFF; return *this;}
  361. inline uint24_t operator++(int) {uint24_t temp(val); ++val; val&=0x00FFFFFF; return temp;}
  362. inline uint24_t operator--(int) {uint24_t temp(val); --val; val&=0x00FFFFFF; return temp;}
  363. inline uint24_t operator&(const uint24_t& a) {return uint24_t(val&a.val);}
  364. inline uint24_t& operator=(const uint24_t& a) { val=a.val; return *this; }
  365. inline uint24_t& operator+=(const uint24_t& a) { val+=a.val; val&=0x00FFFFFF; return *this; }
  366. inline uint24_t& operator-=(const uint24_t& a) { val-=a.val; val&=0x00FFFFFF; return *this; }
  367. inline bool operator==( const uint24_t& right ) const {return val==right.val;}
  368. inline bool operator!=( const uint24_t& right ) const {return val!=right.val;}
  369. inline bool operator > ( const uint24_t& right ) const {return val>right.val;}
  370. inline bool operator < ( const uint24_t& right ) const {return val<right.val;}
  371. inline const uint24_t operator+( const uint24_t &other ) const { return uint24_t(val+other.val); }
  372. inline const uint24_t operator-( const uint24_t &other ) const { return uint24_t(val-other.val); }
  373. inline const uint24_t operator/( const uint24_t &other ) const { return uint24_t(val/other.val); }
  374. inline const uint24_t operator*( const uint24_t &other ) const { return uint24_t(val*other.val); }
  375. inline uint24_t(const uint32_t& a) {val=a; val&=0x00FFFFFF;}
  376. inline uint24_t operator&(const uint32_t& a) {return uint24_t(val&a);}
  377. inline uint24_t& operator=(const uint32_t& a) { val=a; val&=0x00FFFFFF; return *this; }
  378. inline uint24_t& operator+=(const uint32_t& a) { val+=a; val&=0x00FFFFFF; return *this; }
  379. inline uint24_t& operator-=(const uint32_t& a) { val-=a; val&=0x00FFFFFF; return *this; }
  380. inline bool operator==( const uint32_t& right ) const {return val==(right&0x00FFFFFF);}
  381. inline bool operator!=( const uint32_t& right ) const {return val!=(right&0x00FFFFFF);}
  382. inline bool operator > ( const uint32_t& right ) const {return val>(right&0x00FFFFFF);}
  383. inline bool operator < ( const uint32_t& right ) const {return val<(right&0x00FFFFFF);}
  384. inline const uint24_t operator+( const uint32_t &other ) const { return uint24_t(val+other); }
  385. inline const uint24_t operator-( const uint32_t &other ) const { return uint24_t(val-other); }
  386. inline const uint24_t operator/( const uint32_t &other ) const { return uint24_t(val/other); }
  387. inline const uint24_t operator*( const uint32_t &other ) const { return uint24_t(val*other); }
  388. };
  389. } // namespace RakNet
  390. #endif
粤ICP备19079148号