NetworkReader.cs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Text;
  5. using UnityEngine;
  6. namespace Mirror
  7. {
  8. /// <summary>Helper class that weaver populates with all reader types.</summary>
  9. // Note that c# creates a different static variable for each type
  10. // -> Weaver.ReaderWriterProcessor.InitializeReaderAndWriters() populates it
  11. public static class Reader<T>
  12. {
  13. public static Func<NetworkReader, T> read;
  14. }
  15. /// <summary>Network Reader for most simple types like floats, ints, buffers, structs, etc. Use NetworkReaderPool.GetReader() to avoid allocations.</summary>
  16. // Note: This class is intended to be extremely pedantic,
  17. // and throw exceptions whenever stuff is going slightly wrong.
  18. // The exceptions will be handled in NetworkServer/NetworkClient.
  19. public class NetworkReader
  20. {
  21. // internal buffer
  22. // byte[] pointer would work, but we use ArraySegment to also support
  23. // the ArraySegment constructor
  24. ArraySegment<byte> buffer;
  25. /// <summary>Next position to read from the buffer</summary>
  26. // 'int' is the best type for .Position. 'short' is too small if we send >32kb which would result in negative .Position
  27. // -> converting long to int is fine until 2GB of data (MAX_INT), so we don't have to worry about overflows here
  28. public int Position;
  29. /// <summary>Total number of bytes to read from buffer</summary>
  30. public int Length => buffer.Count;
  31. /// <summary>Remaining bytes that can be read, for convenience.</summary>
  32. public int Remaining => Length - Position;
  33. public NetworkReader(byte[] bytes)
  34. {
  35. buffer = new ArraySegment<byte>(bytes);
  36. }
  37. public NetworkReader(ArraySegment<byte> segment)
  38. {
  39. buffer = segment;
  40. }
  41. // sometimes it's useful to point a reader on another buffer instead of
  42. // allocating a new reader (e.g. NetworkReaderPool)
  43. public void SetBuffer(byte[] bytes)
  44. {
  45. buffer = new ArraySegment<byte>(bytes);
  46. Position = 0;
  47. }
  48. public void SetBuffer(ArraySegment<byte> segment)
  49. {
  50. buffer = segment;
  51. Position = 0;
  52. }
  53. public byte ReadByte()
  54. {
  55. if (Position + 1 > buffer.Count)
  56. {
  57. throw new EndOfStreamException("ReadByte out of range:" + ToString());
  58. }
  59. return buffer.Array[buffer.Offset + Position++];
  60. }
  61. /// <summary>Read 'count' bytes into the bytes array</summary>
  62. // TODO why does this also return bytes[]???
  63. public byte[] ReadBytes(byte[] bytes, int count)
  64. {
  65. // check if passed byte array is big enough
  66. if (count > bytes.Length)
  67. {
  68. throw new EndOfStreamException("ReadBytes can't read " + count + " + bytes because the passed byte[] only has length " + bytes.Length);
  69. }
  70. ArraySegment<byte> data = ReadBytesSegment(count);
  71. Array.Copy(data.Array, data.Offset, bytes, 0, count);
  72. return bytes;
  73. }
  74. /// <summary>Read 'count' bytes allocation-free as ArraySegment that points to the internal array.</summary>
  75. public ArraySegment<byte> ReadBytesSegment(int count)
  76. {
  77. // check if within buffer limits
  78. if (Position + count > buffer.Count)
  79. {
  80. throw new EndOfStreamException("ReadBytesSegment can't read " + count + " bytes because it would read past the end of the stream. " + ToString());
  81. }
  82. // return the segment
  83. ArraySegment<byte> result = new ArraySegment<byte>(buffer.Array, buffer.Offset + Position, count);
  84. Position += count;
  85. return result;
  86. }
  87. public override string ToString()
  88. {
  89. return $"NetworkReader pos={Position} len={Length} buffer={BitConverter.ToString(buffer.Array, buffer.Offset, buffer.Count)}";
  90. }
  91. /// <summary>Reads any data type that mirror supports. Uses weaver populated Reader(T).read</summary>
  92. public T Read<T>()
  93. {
  94. Func<NetworkReader, T> readerDelegate = Reader<T>.read;
  95. if (readerDelegate == null)
  96. {
  97. Debug.LogError($"No reader found for {typeof(T)}. Use a type supported by Mirror or define a custom reader");
  98. return default;
  99. }
  100. return readerDelegate(this);
  101. }
  102. }
  103. // Mirror's Weaver automatically detects all NetworkReader function types,
  104. // but they do all need to be extensions.
  105. public static class NetworkReaderExtensions
  106. {
  107. // cache encoding instead of creating it each time
  108. // 1000 readers before: 1MB GC, 30ms
  109. // 1000 readers after: 0.8MB GC, 18ms
  110. static readonly UTF8Encoding encoding = new UTF8Encoding(false, true);
  111. public static byte ReadByte(this NetworkReader reader) => reader.ReadByte();
  112. public static sbyte ReadSByte(this NetworkReader reader) => (sbyte)reader.ReadByte();
  113. public static char ReadChar(this NetworkReader reader) => (char)reader.ReadUShort();
  114. // Deprecated 2021-05-18
  115. [Obsolete("We've cleaned up the API. Use ReadBool instead.")]
  116. public static bool ReadBoolean(this NetworkReader reader) => reader.ReadBool();
  117. public static bool ReadBool(this NetworkReader reader) => reader.ReadByte() != 0;
  118. // Deprecated 2021-05-18
  119. [Obsolete("We've cleaned up the API. Use ReadShort instead.")]
  120. public static short ReadInt16(this NetworkReader reader) => reader.ReadShort();
  121. public static short ReadShort(this NetworkReader reader) => (short)reader.ReadUShort();
  122. // Deprecated 2021-05-18
  123. [Obsolete("We've cleaned up the API. Use ReadUShort instead.")]
  124. public static ushort ReadUInt16(this NetworkReader reader) => reader.ReadUShort();
  125. public static ushort ReadUShort(this NetworkReader reader)
  126. {
  127. ushort value = 0;
  128. value |= reader.ReadByte();
  129. value |= (ushort)(reader.ReadByte() << 8);
  130. return value;
  131. }
  132. // Deprecated 2021-05-18
  133. [Obsolete("We've cleaned up the API. Use ReadInt instead.")]
  134. public static int ReadInt32(this NetworkReader reader) => reader.ReadInt();
  135. public static int ReadInt(this NetworkReader reader) => (int)reader.ReadUInt();
  136. // Deprecated 2021-05-18
  137. [Obsolete("We've cleaned up the API. Use ReadUInt instead.")]
  138. public static uint ReadUInt32(this NetworkReader reader) => reader.ReadUInt();
  139. public static uint ReadUInt(this NetworkReader reader)
  140. {
  141. uint value = 0;
  142. value |= reader.ReadByte();
  143. value |= (uint)(reader.ReadByte() << 8);
  144. value |= (uint)(reader.ReadByte() << 16);
  145. value |= (uint)(reader.ReadByte() << 24);
  146. return value;
  147. }
  148. // Deprecated 2021-05-18
  149. [Obsolete("We've cleaned up the API. Use ReadLong instead.")]
  150. public static long ReadInt64(this NetworkReader reader) => reader.ReadLong();
  151. public static long ReadLong(this NetworkReader reader) => (long)reader.ReadULong();
  152. // Deprecated 2021-05-18
  153. [Obsolete("We've cleaned up the API. Use ReadULong instead.")]
  154. public static ulong ReadUInt64(this NetworkReader reader) => reader.ReadULong();
  155. public static ulong ReadULong(this NetworkReader reader)
  156. {
  157. ulong value = 0;
  158. value |= reader.ReadByte();
  159. value |= ((ulong)reader.ReadByte()) << 8;
  160. value |= ((ulong)reader.ReadByte()) << 16;
  161. value |= ((ulong)reader.ReadByte()) << 24;
  162. value |= ((ulong)reader.ReadByte()) << 32;
  163. value |= ((ulong)reader.ReadByte()) << 40;
  164. value |= ((ulong)reader.ReadByte()) << 48;
  165. value |= ((ulong)reader.ReadByte()) << 56;
  166. return value;
  167. }
  168. // Deprecated 2021-05-18
  169. [Obsolete("We've cleaned up the API. Use ReadFloat instead.")]
  170. public static float ReadSingle(this NetworkReader reader) => reader.ReadFloat();
  171. public static float ReadFloat(this NetworkReader reader)
  172. {
  173. UIntFloat converter = new UIntFloat();
  174. converter.intValue = reader.ReadUInt();
  175. return converter.floatValue;
  176. }
  177. public static double ReadDouble(this NetworkReader reader)
  178. {
  179. UIntDouble converter = new UIntDouble();
  180. converter.longValue = reader.ReadULong();
  181. return converter.doubleValue;
  182. }
  183. public static decimal ReadDecimal(this NetworkReader reader)
  184. {
  185. UIntDecimal converter = new UIntDecimal();
  186. converter.longValue1 = reader.ReadULong();
  187. converter.longValue2 = reader.ReadULong();
  188. return converter.decimalValue;
  189. }
  190. /// <exception cref="T:System.ArgumentException">if an invalid utf8 string is sent</exception>
  191. public static string ReadString(this NetworkReader reader)
  192. {
  193. // read number of bytes
  194. ushort size = reader.ReadUShort();
  195. // null support, see NetworkWriter
  196. if (size == 0)
  197. return null;
  198. int realSize = size - 1;
  199. // make sure it's within limits to avoid allocation attacks etc.
  200. if (realSize >= NetworkWriter.MaxStringLength)
  201. {
  202. throw new EndOfStreamException("ReadString too long: " + realSize + ". Limit is: " + NetworkWriter.MaxStringLength);
  203. }
  204. ArraySegment<byte> data = reader.ReadBytesSegment(realSize);
  205. // convert directly from buffer to string via encoding
  206. return encoding.GetString(data.Array, data.Offset, data.Count);
  207. }
  208. /// <exception cref="T:OverflowException">if count is invalid</exception>
  209. public static byte[] ReadBytesAndSize(this NetworkReader reader)
  210. {
  211. // count = 0 means the array was null
  212. // otherwise count -1 is the length of the array
  213. uint count = reader.ReadUInt();
  214. // Use checked() to force it to throw OverflowException if data is invalid
  215. return count == 0 ? null : reader.ReadBytes(checked((int)(count - 1u)));
  216. }
  217. /// <exception cref="T:OverflowException">if count is invalid</exception>
  218. public static ArraySegment<byte> ReadBytesAndSizeSegment(this NetworkReader reader)
  219. {
  220. // count = 0 means the array was null
  221. // otherwise count - 1 is the length of the array
  222. uint count = reader.ReadUInt();
  223. // Use checked() to force it to throw OverflowException if data is invalid
  224. return count == 0 ? default : reader.ReadBytesSegment(checked((int)(count - 1u)));
  225. }
  226. public static Vector2 ReadVector2(this NetworkReader reader) => new Vector2(reader.ReadFloat(), reader.ReadFloat());
  227. public static Vector3 ReadVector3(this NetworkReader reader) => new Vector3(reader.ReadFloat(), reader.ReadFloat(), reader.ReadFloat());
  228. // TODO add nullable support to weaver instead
  229. public static Vector3? ReadVector3Nullable(this NetworkReader reader) => reader.ReadBool() ? ReadVector3(reader) : default;
  230. public static Vector4 ReadVector4(this NetworkReader reader) => new Vector4(reader.ReadFloat(), reader.ReadFloat(), reader.ReadFloat(), reader.ReadFloat());
  231. public static Vector2Int ReadVector2Int(this NetworkReader reader) => new Vector2Int(reader.ReadInt(), reader.ReadInt());
  232. public static Vector3Int ReadVector3Int(this NetworkReader reader) => new Vector3Int(reader.ReadInt(), reader.ReadInt(), reader.ReadInt());
  233. public static Color ReadColor(this NetworkReader reader) => new Color(reader.ReadFloat(), reader.ReadFloat(), reader.ReadFloat(), reader.ReadFloat());
  234. public static Color32 ReadColor32(this NetworkReader reader) => new Color32(reader.ReadByte(), reader.ReadByte(), reader.ReadByte(), reader.ReadByte());
  235. public static Quaternion ReadQuaternion(this NetworkReader reader) => new Quaternion(reader.ReadFloat(), reader.ReadFloat(), reader.ReadFloat(), reader.ReadFloat());
  236. // TODO add nullable support to weaver instead
  237. public static Quaternion? ReadQuaternionNullable(this NetworkReader reader) => reader.ReadBool() ? ReadQuaternion(reader) : default;
  238. public static Rect ReadRect(this NetworkReader reader) => new Rect(reader.ReadFloat(), reader.ReadFloat(), reader.ReadFloat(), reader.ReadFloat());
  239. public static Plane ReadPlane(this NetworkReader reader) => new Plane(reader.ReadVector3(), reader.ReadFloat());
  240. public static Ray ReadRay(this NetworkReader reader) => new Ray(reader.ReadVector3(), reader.ReadVector3());
  241. public static Matrix4x4 ReadMatrix4x4(this NetworkReader reader)
  242. {
  243. return new Matrix4x4
  244. {
  245. m00 = reader.ReadFloat(),
  246. m01 = reader.ReadFloat(),
  247. m02 = reader.ReadFloat(),
  248. m03 = reader.ReadFloat(),
  249. m10 = reader.ReadFloat(),
  250. m11 = reader.ReadFloat(),
  251. m12 = reader.ReadFloat(),
  252. m13 = reader.ReadFloat(),
  253. m20 = reader.ReadFloat(),
  254. m21 = reader.ReadFloat(),
  255. m22 = reader.ReadFloat(),
  256. m23 = reader.ReadFloat(),
  257. m30 = reader.ReadFloat(),
  258. m31 = reader.ReadFloat(),
  259. m32 = reader.ReadFloat(),
  260. m33 = reader.ReadFloat()
  261. };
  262. }
  263. public static byte[] ReadBytes(this NetworkReader reader, int count)
  264. {
  265. byte[] bytes = new byte[count];
  266. reader.ReadBytes(bytes, count);
  267. return bytes;
  268. }
  269. public static Guid ReadGuid(this NetworkReader reader) => new Guid(reader.ReadBytes(16));
  270. public static Transform ReadTransform(this NetworkReader reader)
  271. {
  272. // Don't use null propagation here as it could lead to MissingReferenceException
  273. NetworkIdentity networkIdentity = reader.ReadNetworkIdentity();
  274. return networkIdentity != null ? networkIdentity.transform : null;
  275. }
  276. public static GameObject ReadGameObject(this NetworkReader reader)
  277. {
  278. // Don't use null propagation here as it could lead to MissingReferenceException
  279. NetworkIdentity networkIdentity = reader.ReadNetworkIdentity();
  280. return networkIdentity != null ? networkIdentity.gameObject : null;
  281. }
  282. public static NetworkIdentity ReadNetworkIdentity(this NetworkReader reader)
  283. {
  284. uint netId = reader.ReadUInt();
  285. if (netId == 0)
  286. return null;
  287. if (NetworkIdentity.spawned.TryGetValue(netId, out NetworkIdentity identity))
  288. {
  289. return identity;
  290. }
  291. // a netId not being in spawned is common.
  292. // for example, "[SyncVar] NetworkIdentity target" netId would not
  293. // be known on client if the monster walks out of proximity for a
  294. // moment. no need to log any error or warning here.
  295. return null;
  296. }
  297. public static NetworkBehaviour ReadNetworkBehaviour(this NetworkReader reader)
  298. {
  299. uint netId = reader.ReadUInt();
  300. if (netId == 0)
  301. return null;
  302. // if netId is not 0, then index is also sent to read before returning
  303. byte componentIndex = reader.ReadByte();
  304. if (NetworkIdentity.spawned.TryGetValue(netId, out NetworkIdentity identity))
  305. {
  306. return identity.NetworkBehaviours[componentIndex];
  307. }
  308. // a netId not being in spawned is common.
  309. // for example, "[SyncVar] NetworkBehaviour target" netId would not
  310. // be known on client if the monster walks out of proximity for a
  311. // moment. no need to log any error or warning here.
  312. return null;
  313. }
  314. public static T ReadNetworkBehaviour<T>(this NetworkReader reader) where T : NetworkBehaviour
  315. {
  316. return reader.ReadNetworkBehaviour() as T;
  317. }
  318. public static NetworkBehaviour.NetworkBehaviourSyncVar ReadNetworkBehaviourSyncVar(this NetworkReader reader)
  319. {
  320. uint netId = reader.ReadUInt();
  321. byte componentIndex = default;
  322. // if netId is not 0, then index is also sent to read before returning
  323. if (netId != 0)
  324. {
  325. componentIndex = reader.ReadByte();
  326. }
  327. return new NetworkBehaviour.NetworkBehaviourSyncVar(netId, componentIndex);
  328. }
  329. public static List<T> ReadList<T>(this NetworkReader reader)
  330. {
  331. int length = reader.ReadInt();
  332. if (length < 0)
  333. return null;
  334. List<T> result = new List<T>(length);
  335. for (int i = 0; i < length; i++)
  336. {
  337. result.Add(reader.Read<T>());
  338. }
  339. return result;
  340. }
  341. public static T[] ReadArray<T>(this NetworkReader reader)
  342. {
  343. int length = reader.ReadInt();
  344. // we write -1 for null
  345. if (length < 0)
  346. return null;
  347. // todo throw an exception for other negative values (we never write them, likely to be attacker)
  348. // this assumes that a reader for T reads at least 1 bytes
  349. // we can't know the exact size of T because it could have a user created reader
  350. // NOTE: don't add to length as it could overflow if value is int.max
  351. if (length > reader.Length - reader.Position)
  352. {
  353. throw new EndOfStreamException($"Received array that is too large: {length}");
  354. }
  355. T[] result = new T[length];
  356. for (int i = 0; i < length; i++)
  357. {
  358. result[i] = reader.Read<T>();
  359. }
  360. return result;
  361. }
  362. public static Uri ReadUri(this NetworkReader reader)
  363. {
  364. string uriString = reader.ReadString();
  365. return (string.IsNullOrEmpty(uriString) ? null : new Uri(uriString));
  366. }
  367. }
  368. }