NetworkReaderExtensions.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using UnityEngine;
  5. namespace Mirror
  6. {
  7. // Mirror's Weaver automatically detects all NetworkReader function types,
  8. // but they do all need to be extensions.
  9. public static class NetworkReaderExtensions
  10. {
  11. public static byte ReadByte(this NetworkReader reader) => reader.ReadBlittable<byte>();
  12. public static byte? ReadByteNullable(this NetworkReader reader) => reader.ReadBlittableNullable<byte>();
  13. public static sbyte ReadSByte(this NetworkReader reader) => reader.ReadBlittable<sbyte>();
  14. public static sbyte? ReadSByteNullable(this NetworkReader reader) => reader.ReadBlittableNullable<sbyte>();
  15. // bool is not blittable. read as ushort.
  16. public static char ReadChar(this NetworkReader reader) => (char)reader.ReadBlittable<ushort>();
  17. public static char? ReadCharNullable(this NetworkReader reader) => (char?)reader.ReadBlittableNullable<ushort>();
  18. // bool is not blittable. read as byte.
  19. public static bool ReadBool(this NetworkReader reader) => reader.ReadBlittable<byte>() != 0;
  20. public static bool? ReadBoolNullable(this NetworkReader reader)
  21. {
  22. byte? value = reader.ReadBlittableNullable<byte>();
  23. return value.HasValue ? (value.Value != 0) : default(bool?);
  24. }
  25. public static short ReadShort(this NetworkReader reader) => (short)reader.ReadUShort();
  26. public static short? ReadShortNullable(this NetworkReader reader) => reader.ReadBlittableNullable<short>();
  27. public static ushort ReadUShort(this NetworkReader reader) => reader.ReadBlittable<ushort>();
  28. public static ushort? ReadUShortNullable(this NetworkReader reader) => reader.ReadBlittableNullable<ushort>();
  29. public static int ReadInt(this NetworkReader reader) => reader.ReadBlittable<int>();
  30. public static int? ReadIntNullable(this NetworkReader reader) => reader.ReadBlittableNullable<int>();
  31. public static uint ReadUInt(this NetworkReader reader) => reader.ReadBlittable<uint>();
  32. public static uint? ReadUIntNullable(this NetworkReader reader) => reader.ReadBlittableNullable<uint>();
  33. public static long ReadLong(this NetworkReader reader) => reader.ReadBlittable<long>();
  34. public static long? ReadLongNullable(this NetworkReader reader) => reader.ReadBlittableNullable<long>();
  35. public static ulong ReadULong(this NetworkReader reader) => reader.ReadBlittable<ulong>();
  36. public static ulong? ReadULongNullable(this NetworkReader reader) => reader.ReadBlittableNullable<ulong>();
  37. public static float ReadFloat(this NetworkReader reader) => reader.ReadBlittable<float>();
  38. public static float? ReadFloatNullable(this NetworkReader reader) => reader.ReadBlittableNullable<float>();
  39. public static double ReadDouble(this NetworkReader reader) => reader.ReadBlittable<double>();
  40. public static double? ReadDoubleNullable(this NetworkReader reader) => reader.ReadBlittableNullable<double>();
  41. public static decimal ReadDecimal(this NetworkReader reader) => reader.ReadBlittable<decimal>();
  42. public static decimal? ReadDecimalNullable(this NetworkReader reader) => reader.ReadBlittableNullable<decimal>();
  43. /// <exception cref="T:System.ArgumentException">if an invalid utf8 string is sent</exception>
  44. public static string ReadString(this NetworkReader reader)
  45. {
  46. // read number of bytes
  47. ushort size = reader.ReadUShort();
  48. // null support, see NetworkWriter
  49. if (size == 0)
  50. return null;
  51. int realSize = size - 1;
  52. // make sure it's within limits to avoid allocation attacks etc.
  53. if (realSize >= NetworkWriter.MaxStringLength)
  54. {
  55. throw new EndOfStreamException($"ReadString too long: {realSize}. Limit is: {NetworkWriter.MaxStringLength}");
  56. }
  57. ArraySegment<byte> data = reader.ReadBytesSegment(realSize);
  58. // convert directly from buffer to string via encoding
  59. // throws in case of invalid utf8.
  60. // see test: ReadString_InvalidUTF8()
  61. return reader.encoding.GetString(data.Array, data.Offset, data.Count);
  62. }
  63. /// <exception cref="T:OverflowException">if count is invalid</exception>
  64. public static byte[] ReadBytesAndSize(this NetworkReader reader)
  65. {
  66. // count = 0 means the array was null
  67. // otherwise count -1 is the length of the array
  68. uint count = reader.ReadUInt();
  69. // Use checked() to force it to throw OverflowException if data is invalid
  70. return count == 0 ? null : reader.ReadBytes(checked((int)(count - 1u)));
  71. }
  72. public static byte[] ReadBytes(this NetworkReader reader, int count)
  73. {
  74. byte[] bytes = new byte[count];
  75. reader.ReadBytes(bytes, count);
  76. return bytes;
  77. }
  78. /// <exception cref="T:OverflowException">if count is invalid</exception>
  79. public static ArraySegment<byte> ReadBytesAndSizeSegment(this NetworkReader reader)
  80. {
  81. // count = 0 means the array was null
  82. // otherwise count - 1 is the length of the array
  83. uint count = reader.ReadUInt();
  84. // Use checked() to force it to throw OverflowException if data is invalid
  85. return count == 0 ? default : reader.ReadBytesSegment(checked((int)(count - 1u)));
  86. }
  87. public static Vector2 ReadVector2(this NetworkReader reader) => reader.ReadBlittable<Vector2>();
  88. public static Vector2? ReadVector2Nullable(this NetworkReader reader) => reader.ReadBlittableNullable<Vector2>();
  89. public static Vector3 ReadVector3(this NetworkReader reader) => reader.ReadBlittable<Vector3>();
  90. public static Vector3? ReadVector3Nullable(this NetworkReader reader) => reader.ReadBlittableNullable<Vector3>();
  91. public static Vector4 ReadVector4(this NetworkReader reader) => reader.ReadBlittable<Vector4>();
  92. public static Vector4? ReadVector4Nullable(this NetworkReader reader) => reader.ReadBlittableNullable<Vector4>();
  93. public static Vector2Int ReadVector2Int(this NetworkReader reader) => reader.ReadBlittable<Vector2Int>();
  94. public static Vector2Int? ReadVector2IntNullable(this NetworkReader reader) => reader.ReadBlittableNullable<Vector2Int>();
  95. public static Vector3Int ReadVector3Int(this NetworkReader reader) => reader.ReadBlittable<Vector3Int>();
  96. public static Vector3Int? ReadVector3IntNullable(this NetworkReader reader) => reader.ReadBlittableNullable<Vector3Int>();
  97. public static Color ReadColor(this NetworkReader reader) => reader.ReadBlittable<Color>();
  98. public static Color? ReadColorNullable(this NetworkReader reader) => reader.ReadBlittableNullable<Color>();
  99. public static Color32 ReadColor32(this NetworkReader reader) => reader.ReadBlittable<Color32>();
  100. public static Color32? ReadColor32Nullable(this NetworkReader reader) => reader.ReadBlittableNullable<Color32>();
  101. public static Quaternion ReadQuaternion(this NetworkReader reader) => reader.ReadBlittable<Quaternion>();
  102. public static Quaternion? ReadQuaternionNullable(this NetworkReader reader) => reader.ReadBlittableNullable<Quaternion>();
  103. public static Rect ReadRect(this NetworkReader reader) => reader.ReadBlittable<Rect>();
  104. public static Rect? ReadRectNullable(this NetworkReader reader) => reader.ReadBlittableNullable<Rect>();
  105. public static Plane ReadPlane(this NetworkReader reader) => reader.ReadBlittable<Plane>();
  106. public static Plane? ReadPlaneNullable(this NetworkReader reader) => reader.ReadBlittableNullable<Plane>();
  107. public static Ray ReadRay(this NetworkReader reader) => reader.ReadBlittable<Ray>();
  108. public static Ray? ReadRayNullable(this NetworkReader reader) => reader.ReadBlittableNullable<Ray>();
  109. public static Matrix4x4 ReadMatrix4x4(this NetworkReader reader) => reader.ReadBlittable<Matrix4x4>();
  110. public static Matrix4x4? ReadMatrix4x4Nullable(this NetworkReader reader) => reader.ReadBlittableNullable<Matrix4x4>();
  111. public static Guid ReadGuid(this NetworkReader reader)
  112. {
  113. #if !UNITY_2021_3_OR_NEWER
  114. // Unity 2019 doesn't have Span yet
  115. return new Guid(reader.ReadBytes(16));
  116. #else
  117. // ReadBlittable(Guid) isn't safe. see ReadBlittable comments.
  118. // Guid is Sequential, but we can't guarantee packing.
  119. if (reader.Remaining >= 16)
  120. {
  121. ReadOnlySpan<byte> span = new ReadOnlySpan<byte>(reader.buffer.Array, reader.buffer.Offset + reader.Position, 16);
  122. reader.Position += 16;
  123. return new Guid(span);
  124. }
  125. throw new EndOfStreamException($"ReadGuid out of range: {reader}");
  126. #endif
  127. }
  128. public static Guid? ReadGuidNullable(this NetworkReader reader) => reader.ReadBool() ? ReadGuid(reader) : default(Guid?);
  129. public static NetworkIdentity ReadNetworkIdentity(this NetworkReader reader)
  130. {
  131. uint netId = reader.ReadUInt();
  132. if (netId == 0)
  133. return null;
  134. // NOTE: a netId not being in spawned is common.
  135. // for example, "[SyncVar] NetworkIdentity target" netId would not
  136. // be known on client if the monster walks out of proximity for a
  137. // moment. no need to log any error or warning here.
  138. return Utils.GetSpawnedInServerOrClient(netId);
  139. }
  140. public static NetworkBehaviour ReadNetworkBehaviour(this NetworkReader reader)
  141. {
  142. // read netId first.
  143. //
  144. // IMPORTANT: if netId != 0, writer always writes componentIndex.
  145. // reusing ReadNetworkIdentity() might return a null NetworkIdentity
  146. // even if netId was != 0 but the identity disappeared on the client,
  147. // resulting in unequal amounts of data being written / read.
  148. // https://github.com/vis2k/Mirror/issues/2972
  149. uint netId = reader.ReadUInt();
  150. if (netId == 0)
  151. return null;
  152. // read component index in any case, BEFORE searching the spawned
  153. // NetworkIdentity by netId.
  154. byte componentIndex = reader.ReadByte();
  155. // NOTE: a netId not being in spawned is common.
  156. // for example, "[SyncVar] NetworkIdentity target" netId would not
  157. // be known on client if the monster walks out of proximity for a
  158. // moment. no need to log any error or warning here.
  159. NetworkIdentity identity = Utils.GetSpawnedInServerOrClient(netId);
  160. return identity != null
  161. ? identity.NetworkBehaviours[componentIndex]
  162. : null;
  163. }
  164. public static T ReadNetworkBehaviour<T>(this NetworkReader reader) where T : NetworkBehaviour
  165. {
  166. return reader.ReadNetworkBehaviour() as T;
  167. }
  168. public static NetworkBehaviourSyncVar ReadNetworkBehaviourSyncVar(this NetworkReader reader)
  169. {
  170. uint netId = reader.ReadUInt();
  171. byte componentIndex = default;
  172. // if netId is not 0, then index is also sent to read before returning
  173. if (netId != 0)
  174. {
  175. componentIndex = reader.ReadByte();
  176. }
  177. return new NetworkBehaviourSyncVar(netId, componentIndex);
  178. }
  179. public static Transform ReadTransform(this NetworkReader reader)
  180. {
  181. // Don't use null propagation here as it could lead to MissingReferenceException
  182. NetworkIdentity networkIdentity = reader.ReadNetworkIdentity();
  183. return networkIdentity != null ? networkIdentity.transform : null;
  184. }
  185. public static GameObject ReadGameObject(this NetworkReader reader)
  186. {
  187. // Don't use null propagation here as it could lead to MissingReferenceException
  188. NetworkIdentity networkIdentity = reader.ReadNetworkIdentity();
  189. return networkIdentity != null ? networkIdentity.gameObject : null;
  190. }
  191. public static List<T> ReadList<T>(this NetworkReader reader)
  192. {
  193. int length = reader.ReadInt();
  194. if (length < 0)
  195. return null;
  196. List<T> result = new List<T>(length);
  197. for (int i = 0; i < length; i++)
  198. {
  199. result.Add(reader.Read<T>());
  200. }
  201. return result;
  202. }
  203. public static T[] ReadArray<T>(this NetworkReader reader)
  204. {
  205. int length = reader.ReadInt();
  206. // we write -1 for null
  207. if (length < 0)
  208. return null;
  209. // todo throw an exception for other negative values (we never write them, likely to be attacker)
  210. // this assumes that a reader for T reads at least 1 bytes
  211. // we can't know the exact size of T because it could have a user created reader
  212. // NOTE: don't add to length as it could overflow if value is int.max
  213. if (length > reader.Remaining)
  214. {
  215. throw new EndOfStreamException($"Received array that is too large: {length}");
  216. }
  217. T[] result = new T[length];
  218. for (int i = 0; i < length; i++)
  219. {
  220. result[i] = reader.Read<T>();
  221. }
  222. return result;
  223. }
  224. public static Uri ReadUri(this NetworkReader reader)
  225. {
  226. string uriString = reader.ReadString();
  227. return (string.IsNullOrWhiteSpace(uriString) ? null : new Uri(uriString));
  228. }
  229. public static Texture2D ReadTexture2D(this NetworkReader reader)
  230. {
  231. // TODO allocation protection when sending textures to server.
  232. // currently can allocate 32k x 32k x 4 byte = 3.8 GB
  233. // support 'null' textures for [SyncVar]s etc.
  234. // https://github.com/vis2k/Mirror/issues/3144
  235. short width = reader.ReadShort();
  236. if (width == -1) return null;
  237. // read height
  238. short height = reader.ReadShort();
  239. Texture2D texture2D = new Texture2D(width, height);
  240. // read pixel content
  241. Color32[] pixels = reader.ReadArray<Color32>();
  242. texture2D.SetPixels32(pixels);
  243. texture2D.Apply();
  244. return texture2D;
  245. }
  246. public static Sprite ReadSprite(this NetworkReader reader)
  247. {
  248. // support 'null' textures for [SyncVar]s etc.
  249. // https://github.com/vis2k/Mirror/issues/3144
  250. Texture2D texture = reader.ReadTexture2D();
  251. if (texture == null) return null;
  252. // otherwise create a valid sprite
  253. return Sprite.Create(texture, reader.ReadRect(), reader.ReadVector2());
  254. }
  255. }
  256. }