NetworkReader.cs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403
  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. public static bool ReadBool(this NetworkReader reader) => reader.ReadByte() != 0;
  115. public static short ReadShort(this NetworkReader reader) => (short)reader.ReadUShort();
  116. public static ushort ReadUShort(this NetworkReader reader)
  117. {
  118. ushort value = 0;
  119. value |= reader.ReadByte();
  120. value |= (ushort)(reader.ReadByte() << 8);
  121. return value;
  122. }
  123. public static int ReadInt(this NetworkReader reader) => (int)reader.ReadUInt();
  124. public static uint ReadUInt(this NetworkReader reader)
  125. {
  126. uint value = 0;
  127. value |= reader.ReadByte();
  128. value |= (uint)(reader.ReadByte() << 8);
  129. value |= (uint)(reader.ReadByte() << 16);
  130. value |= (uint)(reader.ReadByte() << 24);
  131. return value;
  132. }
  133. public static long ReadLong(this NetworkReader reader) => (long)reader.ReadULong();
  134. public static ulong ReadULong(this NetworkReader reader)
  135. {
  136. ulong value = 0;
  137. value |= reader.ReadByte();
  138. value |= ((ulong)reader.ReadByte()) << 8;
  139. value |= ((ulong)reader.ReadByte()) << 16;
  140. value |= ((ulong)reader.ReadByte()) << 24;
  141. value |= ((ulong)reader.ReadByte()) << 32;
  142. value |= ((ulong)reader.ReadByte()) << 40;
  143. value |= ((ulong)reader.ReadByte()) << 48;
  144. value |= ((ulong)reader.ReadByte()) << 56;
  145. return value;
  146. }
  147. public static float ReadFloat(this NetworkReader reader)
  148. {
  149. UIntFloat converter = new UIntFloat();
  150. converter.intValue = reader.ReadUInt();
  151. return converter.floatValue;
  152. }
  153. public static double ReadDouble(this NetworkReader reader)
  154. {
  155. UIntDouble converter = new UIntDouble();
  156. converter.longValue = reader.ReadULong();
  157. return converter.doubleValue;
  158. }
  159. public static decimal ReadDecimal(this NetworkReader reader)
  160. {
  161. UIntDecimal converter = new UIntDecimal();
  162. converter.longValue1 = reader.ReadULong();
  163. converter.longValue2 = reader.ReadULong();
  164. return converter.decimalValue;
  165. }
  166. /// <exception cref="T:System.ArgumentException">if an invalid utf8 string is sent</exception>
  167. public static string ReadString(this NetworkReader reader)
  168. {
  169. // read number of bytes
  170. ushort size = reader.ReadUShort();
  171. // null support, see NetworkWriter
  172. if (size == 0)
  173. return null;
  174. int realSize = size - 1;
  175. // make sure it's within limits to avoid allocation attacks etc.
  176. if (realSize >= NetworkWriter.MaxStringLength)
  177. {
  178. throw new EndOfStreamException($"ReadString too long: {realSize}. Limit is: {NetworkWriter.MaxStringLength}");
  179. }
  180. ArraySegment<byte> data = reader.ReadBytesSegment(realSize);
  181. // convert directly from buffer to string via encoding
  182. return encoding.GetString(data.Array, data.Offset, data.Count);
  183. }
  184. /// <exception cref="T:OverflowException">if count is invalid</exception>
  185. public static byte[] ReadBytesAndSize(this NetworkReader reader)
  186. {
  187. // count = 0 means the array was null
  188. // otherwise count -1 is the length of the array
  189. uint count = reader.ReadUInt();
  190. // Use checked() to force it to throw OverflowException if data is invalid
  191. return count == 0 ? null : reader.ReadBytes(checked((int)(count - 1u)));
  192. }
  193. /// <exception cref="T:OverflowException">if count is invalid</exception>
  194. public static ArraySegment<byte> ReadBytesAndSizeSegment(this NetworkReader reader)
  195. {
  196. // count = 0 means the array was null
  197. // otherwise count - 1 is the length of the array
  198. uint count = reader.ReadUInt();
  199. // Use checked() to force it to throw OverflowException if data is invalid
  200. return count == 0 ? default : reader.ReadBytesSegment(checked((int)(count - 1u)));
  201. }
  202. public static Vector2 ReadVector2(this NetworkReader reader) => new Vector2(reader.ReadFloat(), reader.ReadFloat());
  203. public static Vector3 ReadVector3(this NetworkReader reader) => new Vector3(reader.ReadFloat(), reader.ReadFloat(), reader.ReadFloat());
  204. // TODO add nullable support to weaver instead
  205. public static Vector3? ReadVector3Nullable(this NetworkReader reader) => reader.ReadBool() ? ReadVector3(reader) : default;
  206. public static Vector4 ReadVector4(this NetworkReader reader) => new Vector4(reader.ReadFloat(), reader.ReadFloat(), reader.ReadFloat(), reader.ReadFloat());
  207. public static Vector2Int ReadVector2Int(this NetworkReader reader) => new Vector2Int(reader.ReadInt(), reader.ReadInt());
  208. public static Vector3Int ReadVector3Int(this NetworkReader reader) => new Vector3Int(reader.ReadInt(), reader.ReadInt(), reader.ReadInt());
  209. public static Color ReadColor(this NetworkReader reader) => new Color(reader.ReadFloat(), reader.ReadFloat(), reader.ReadFloat(), reader.ReadFloat());
  210. // TODO add nullable support to weaver instead
  211. public static Color? ReadColorNullable(this NetworkReader reader) => reader.ReadBool() ? new Color(reader.ReadFloat(), reader.ReadFloat(), reader.ReadFloat(), reader.ReadFloat()) : default;
  212. public static Color32 ReadColor32(this NetworkReader reader) => new Color32(reader.ReadByte(), reader.ReadByte(), reader.ReadByte(), reader.ReadByte());
  213. // TODO add nullable support to weaver instead
  214. public static Color32? ReadColor32Nullable(this NetworkReader reader) => reader.ReadBool() ? new Color32(reader.ReadByte(), reader.ReadByte(), reader.ReadByte(), reader.ReadByte()) : default;
  215. public static Quaternion ReadQuaternion(this NetworkReader reader) => new Quaternion(reader.ReadFloat(), reader.ReadFloat(), reader.ReadFloat(), reader.ReadFloat());
  216. // TODO add nullable support to weaver instead
  217. public static Quaternion? ReadQuaternionNullable(this NetworkReader reader) => reader.ReadBool() ? ReadQuaternion(reader) : default;
  218. public static Rect ReadRect(this NetworkReader reader) => new Rect(reader.ReadFloat(), reader.ReadFloat(), reader.ReadFloat(), reader.ReadFloat());
  219. public static Plane ReadPlane(this NetworkReader reader) => new Plane(reader.ReadVector3(), reader.ReadFloat());
  220. public static Ray ReadRay(this NetworkReader reader) => new Ray(reader.ReadVector3(), reader.ReadVector3());
  221. public static Matrix4x4 ReadMatrix4x4(this NetworkReader reader)
  222. {
  223. return new Matrix4x4
  224. {
  225. m00 = reader.ReadFloat(),
  226. m01 = reader.ReadFloat(),
  227. m02 = reader.ReadFloat(),
  228. m03 = reader.ReadFloat(),
  229. m10 = reader.ReadFloat(),
  230. m11 = reader.ReadFloat(),
  231. m12 = reader.ReadFloat(),
  232. m13 = reader.ReadFloat(),
  233. m20 = reader.ReadFloat(),
  234. m21 = reader.ReadFloat(),
  235. m22 = reader.ReadFloat(),
  236. m23 = reader.ReadFloat(),
  237. m30 = reader.ReadFloat(),
  238. m31 = reader.ReadFloat(),
  239. m32 = reader.ReadFloat(),
  240. m33 = reader.ReadFloat()
  241. };
  242. }
  243. public static byte[] ReadBytes(this NetworkReader reader, int count)
  244. {
  245. byte[] bytes = new byte[count];
  246. reader.ReadBytes(bytes, count);
  247. return bytes;
  248. }
  249. public static Guid ReadGuid(this NetworkReader reader) => new Guid(reader.ReadBytes(16));
  250. public static Transform ReadTransform(this NetworkReader reader)
  251. {
  252. // Don't use null propagation here as it could lead to MissingReferenceException
  253. NetworkIdentity networkIdentity = reader.ReadNetworkIdentity();
  254. return networkIdentity != null ? networkIdentity.transform : null;
  255. }
  256. public static GameObject ReadGameObject(this NetworkReader reader)
  257. {
  258. // Don't use null propagation here as it could lead to MissingReferenceException
  259. NetworkIdentity networkIdentity = reader.ReadNetworkIdentity();
  260. return networkIdentity != null ? networkIdentity.gameObject : null;
  261. }
  262. public static NetworkIdentity ReadNetworkIdentity(this NetworkReader reader)
  263. {
  264. uint netId = reader.ReadUInt();
  265. if (netId == 0)
  266. return null;
  267. // look in server spawned
  268. if (NetworkServer.active &&
  269. NetworkServer.spawned.TryGetValue(netId, out NetworkIdentity serverIdentity))
  270. return serverIdentity;
  271. // look in client spawned
  272. if (NetworkClient.active &&
  273. NetworkClient.spawned.TryGetValue(netId, out NetworkIdentity clientIdentity))
  274. return clientIdentity;
  275. // a netId not being in spawned is common.
  276. // for example, "[SyncVar] NetworkIdentity target" netId would not
  277. // be known on client if the monster walks out of proximity for a
  278. // moment. no need to log any error or warning here.
  279. return null;
  280. }
  281. public static NetworkBehaviour ReadNetworkBehaviour(this NetworkReader reader)
  282. {
  283. // reuse ReadNetworkIdentity, get the component at index
  284. NetworkIdentity identity = ReadNetworkIdentity(reader);
  285. // a netId not being in spawned is common.
  286. // for example, "[SyncVar] NetworkBehaviour target" netId would not
  287. // be known on client if the monster walks out of proximity for a
  288. // moment. no need to log any error or warning here.
  289. if (identity == null)
  290. return null;
  291. // if identity isn't null, then index is also sent to read before returning
  292. byte componentIndex = reader.ReadByte();
  293. return identity.NetworkBehaviours[componentIndex];
  294. }
  295. public static T ReadNetworkBehaviour<T>(this NetworkReader reader) where T : NetworkBehaviour
  296. {
  297. return reader.ReadNetworkBehaviour() as T;
  298. }
  299. public static NetworkBehaviour.NetworkBehaviourSyncVar ReadNetworkBehaviourSyncVar(this NetworkReader reader)
  300. {
  301. uint netId = reader.ReadUInt();
  302. byte componentIndex = default;
  303. // if netId is not 0, then index is also sent to read before returning
  304. if (netId != 0)
  305. {
  306. componentIndex = reader.ReadByte();
  307. }
  308. return new NetworkBehaviour.NetworkBehaviourSyncVar(netId, componentIndex);
  309. }
  310. public static List<T> ReadList<T>(this NetworkReader reader)
  311. {
  312. int length = reader.ReadInt();
  313. if (length < 0)
  314. return null;
  315. List<T> result = new List<T>(length);
  316. for (int i = 0; i < length; i++)
  317. {
  318. result.Add(reader.Read<T>());
  319. }
  320. return result;
  321. }
  322. public static T[] ReadArray<T>(this NetworkReader reader)
  323. {
  324. int length = reader.ReadInt();
  325. // we write -1 for null
  326. if (length < 0)
  327. return null;
  328. // todo throw an exception for other negative values (we never write them, likely to be attacker)
  329. // this assumes that a reader for T reads at least 1 bytes
  330. // we can't know the exact size of T because it could have a user created reader
  331. // NOTE: don't add to length as it could overflow if value is int.max
  332. if (length > reader.Length - reader.Position)
  333. {
  334. throw new EndOfStreamException($"Received array that is too large: {length}");
  335. }
  336. T[] result = new T[length];
  337. for (int i = 0; i < length; i++)
  338. {
  339. result[i] = reader.Read<T>();
  340. }
  341. return result;
  342. }
  343. public static Uri ReadUri(this NetworkReader reader)
  344. {
  345. string uriString = reader.ReadString();
  346. return (string.IsNullOrEmpty(uriString) ? null : new Uri(uriString));
  347. }
  348. }
  349. }