NetworkReaderExtensions.cs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388
  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. ushort realSize = (ushort)(size - 1);
  52. // make sure it's within limits to avoid allocation attacks etc.
  53. if (realSize > NetworkWriter.MaxStringLength)
  54. throw new EndOfStreamException($"NetworkReader.ReadString - Value too long: {realSize} bytes. Limit is: {NetworkWriter.MaxStringLength} bytes");
  55. ArraySegment<byte> data = reader.ReadBytesSegment(realSize);
  56. // convert directly from buffer to string via encoding
  57. // throws in case of invalid utf8.
  58. // see test: ReadString_InvalidUTF8()
  59. return reader.encoding.GetString(data.Array, data.Offset, data.Count);
  60. }
  61. public static byte[] ReadBytes(this NetworkReader reader, int count)
  62. {
  63. // prevent allocation attacks with a reasonable limit.
  64. // server shouldn't allocate too much on client devices.
  65. // client shouldn't allocate too much on server in ClientToServer [SyncVar]s.
  66. if (count > NetworkReader.AllocationLimit)
  67. {
  68. // throw EndOfStream for consistency with ReadBlittable when out of data
  69. throw new EndOfStreamException($"NetworkReader attempted to allocate {count} bytes, which is larger than the allowed limit of {NetworkReader.AllocationLimit} bytes.");
  70. }
  71. byte[] bytes = new byte[count];
  72. reader.ReadBytes(bytes, count);
  73. return bytes;
  74. }
  75. /// <exception cref="T:OverflowException">if count is invalid</exception>
  76. public static byte[] ReadBytesAndSize(this NetworkReader reader)
  77. {
  78. // count = 0 means the array was null
  79. // otherwise count -1 is the length of the array
  80. uint count = reader.ReadUInt();
  81. // Use checked() to force it to throw OverflowException if data is invalid
  82. return count == 0 ? null : reader.ReadBytes(checked((int)(count - 1u)));
  83. }
  84. // Reads ArraySegment and size header
  85. /// <exception cref="T:OverflowException">if count is invalid</exception>
  86. public static ArraySegment<byte> ReadArraySegmentAndSize(this NetworkReader reader)
  87. {
  88. // count = 0 means the array was null
  89. // otherwise count - 1 is the length of the array
  90. uint count = reader.ReadUInt();
  91. // Use checked() to force it to throw OverflowException if data is invalid
  92. return count == 0 ? default : reader.ReadBytesSegment(checked((int)(count - 1u)));
  93. }
  94. public static Vector2 ReadVector2(this NetworkReader reader) => reader.ReadBlittable<Vector2>();
  95. public static Vector2? ReadVector2Nullable(this NetworkReader reader) => reader.ReadBlittableNullable<Vector2>();
  96. public static Vector3 ReadVector3(this NetworkReader reader) => reader.ReadBlittable<Vector3>();
  97. public static Vector3? ReadVector3Nullable(this NetworkReader reader) => reader.ReadBlittableNullable<Vector3>();
  98. public static Vector4 ReadVector4(this NetworkReader reader) => reader.ReadBlittable<Vector4>();
  99. public static Vector4? ReadVector4Nullable(this NetworkReader reader) => reader.ReadBlittableNullable<Vector4>();
  100. public static Vector2Int ReadVector2Int(this NetworkReader reader) => reader.ReadBlittable<Vector2Int>();
  101. public static Vector2Int? ReadVector2IntNullable(this NetworkReader reader) => reader.ReadBlittableNullable<Vector2Int>();
  102. public static Vector3Int ReadVector3Int(this NetworkReader reader) => reader.ReadBlittable<Vector3Int>();
  103. public static Vector3Int? ReadVector3IntNullable(this NetworkReader reader) => reader.ReadBlittableNullable<Vector3Int>();
  104. public static Color ReadColor(this NetworkReader reader) => reader.ReadBlittable<Color>();
  105. public static Color? ReadColorNullable(this NetworkReader reader) => reader.ReadBlittableNullable<Color>();
  106. public static Color32 ReadColor32(this NetworkReader reader) => reader.ReadBlittable<Color32>();
  107. public static Color32? ReadColor32Nullable(this NetworkReader reader) => reader.ReadBlittableNullable<Color32>();
  108. public static Quaternion ReadQuaternion(this NetworkReader reader) => reader.ReadBlittable<Quaternion>();
  109. public static Quaternion? ReadQuaternionNullable(this NetworkReader reader) => reader.ReadBlittableNullable<Quaternion>();
  110. // Rect is a struct with properties instead of fields
  111. public static Rect ReadRect(this NetworkReader reader) => new Rect(reader.ReadVector2(), reader.ReadVector2());
  112. public static Rect? ReadRectNullable(this NetworkReader reader) => reader.ReadBool() ? ReadRect(reader) : default(Rect?);
  113. // Plane is a struct with properties instead of fields
  114. public static Plane ReadPlane(this NetworkReader reader) => new Plane(reader.ReadVector3(), reader.ReadFloat());
  115. public static Plane? ReadPlaneNullable(this NetworkReader reader) => reader.ReadBool() ? ReadPlane(reader) : default(Plane?);
  116. // Ray is a struct with properties instead of fields
  117. public static Ray ReadRay(this NetworkReader reader) => new Ray(reader.ReadVector3(), reader.ReadVector3());
  118. public static Ray? ReadRayNullable(this NetworkReader reader) => reader.ReadBool() ? ReadRay(reader) : default(Ray?);
  119. // LayerMask is a struct with properties instead of fields
  120. public static LayerMask ReadLayerMask(this NetworkReader reader)
  121. {
  122. // LayerMask doesn't have a constructor that takes an initial value.
  123. // 32 layers as a flags enum, max value of 496, we only need a UShort.
  124. LayerMask layerMask = default;
  125. layerMask.value = reader.ReadUShort();
  126. return layerMask;
  127. }
  128. public static LayerMask? ReadLayerMaskNullable(this NetworkReader reader) => reader.ReadBool() ? ReadLayerMask(reader) : default(LayerMask?);
  129. public static Matrix4x4 ReadMatrix4x4(this NetworkReader reader) => reader.ReadBlittable<Matrix4x4>();
  130. public static Matrix4x4? ReadMatrix4x4Nullable(this NetworkReader reader) => reader.ReadBlittableNullable<Matrix4x4>();
  131. public static Guid ReadGuid(this NetworkReader reader)
  132. {
  133. #if !UNITY_2021_3_OR_NEWER
  134. // Unity 2019 doesn't have Span yet
  135. return new Guid(reader.ReadBytes(16));
  136. #else
  137. // ReadBlittable(Guid) isn't safe. see ReadBlittable comments.
  138. // Guid is Sequential, but we can't guarantee packing.
  139. if (reader.Remaining >= 16)
  140. {
  141. ReadOnlySpan<byte> span = new ReadOnlySpan<byte>(reader.buffer.Array, reader.buffer.Offset + reader.Position, 16);
  142. reader.Position += 16;
  143. return new Guid(span);
  144. }
  145. throw new EndOfStreamException($"ReadGuid out of range: {reader}");
  146. #endif
  147. }
  148. public static Guid? ReadGuidNullable(this NetworkReader reader) => reader.ReadBool() ? ReadGuid(reader) : default(Guid?);
  149. public static NetworkIdentity ReadNetworkIdentity(this NetworkReader reader)
  150. {
  151. uint netId = reader.ReadUInt();
  152. if (netId == 0)
  153. return null;
  154. // NOTE: a netId not being in spawned is common.
  155. // for example, "[SyncVar] NetworkIdentity target" netId would not
  156. // be known on client if the monster walks out of proximity for a
  157. // moment. no need to log any error or warning here.
  158. return Utils.GetSpawnedInServerOrClient(netId);
  159. }
  160. public static NetworkBehaviour ReadNetworkBehaviour(this NetworkReader reader)
  161. {
  162. // read netId first.
  163. //
  164. // IMPORTANT: if netId != 0, writer always writes componentIndex.
  165. // reusing ReadNetworkIdentity() might return a null NetworkIdentity
  166. // even if netId was != 0 but the identity disappeared on the client,
  167. // resulting in unequal amounts of data being written / read.
  168. // https://github.com/vis2k/Mirror/issues/2972
  169. uint netId = reader.ReadUInt();
  170. if (netId == 0)
  171. return null;
  172. // read component index in any case, BEFORE searching the spawned
  173. // NetworkIdentity by netId.
  174. byte componentIndex = reader.ReadByte();
  175. // NOTE: a netId not being in spawned is common.
  176. // for example, "[SyncVar] NetworkIdentity target" netId would not
  177. // be known on client if the monster walks out of proximity for a
  178. // moment. no need to log any error or warning here.
  179. NetworkIdentity identity = Utils.GetSpawnedInServerOrClient(netId);
  180. return identity != null
  181. ? identity.NetworkBehaviours[componentIndex]
  182. : null;
  183. }
  184. public static T ReadNetworkBehaviour<T>(this NetworkReader reader) where T : NetworkBehaviour
  185. {
  186. return reader.ReadNetworkBehaviour() as T;
  187. }
  188. public static NetworkBehaviourSyncVar ReadNetworkBehaviourSyncVar(this NetworkReader reader)
  189. {
  190. uint netId = reader.ReadUInt();
  191. byte componentIndex = default;
  192. // if netId is not 0, then index is also sent to read before returning
  193. if (netId != 0)
  194. {
  195. componentIndex = reader.ReadByte();
  196. }
  197. return new NetworkBehaviourSyncVar(netId, componentIndex);
  198. }
  199. public static Transform ReadTransform(this NetworkReader reader)
  200. {
  201. // Don't use null propagation here as it could lead to MissingReferenceException
  202. NetworkIdentity networkIdentity = reader.ReadNetworkIdentity();
  203. return networkIdentity != null ? networkIdentity.transform : null;
  204. }
  205. public static GameObject ReadGameObject(this NetworkReader reader)
  206. {
  207. // Don't use null propagation here as it could lead to MissingReferenceException
  208. NetworkIdentity networkIdentity = reader.ReadNetworkIdentity();
  209. return networkIdentity != null ? networkIdentity.gameObject : null;
  210. }
  211. // while SyncList<T> is recommended for NetworkBehaviours,
  212. // structs may have .List<T> members which weaver needs to be able to
  213. // fully serialize for NetworkMessages etc.
  214. // note that Weaver/Readers/GenerateReader() handles this manually.
  215. public static List<T> ReadList<T>(this NetworkReader reader)
  216. {
  217. int length = reader.ReadInt();
  218. // 'null' is encoded as '-1'
  219. if (length < 0) return null;
  220. // prevent allocation attacks with a reasonable limit.
  221. // server shouldn't allocate too much on client devices.
  222. // client shouldn't allocate too much on server in ClientToServer [SyncVar]s.
  223. if (length > NetworkReader.AllocationLimit)
  224. {
  225. // throw EndOfStream for consistency with ReadBlittable when out of data
  226. throw new EndOfStreamException($"NetworkReader attempted to allocate a List<{typeof(T)}> {length} elements, which is larger than the allowed limit of {NetworkReader.AllocationLimit}.");
  227. }
  228. List<T> result = new List<T>(length);
  229. for (int i = 0; i < length; i++)
  230. {
  231. result.Add(reader.Read<T>());
  232. }
  233. return result;
  234. }
  235. // while SyncSet<T> is recommended for NetworkBehaviours,
  236. // structs may have .Set<T> members which weaver needs to be able to
  237. // fully serialize for NetworkMessages etc.
  238. // note that Weaver/Readers/GenerateReader() handles this manually.
  239. // TODO writer not found. need to adjust weaver first. see tests.
  240. /*
  241. public static HashSet<T> ReadHashSet<T>(this NetworkReader reader)
  242. {
  243. int length = reader.ReadInt();
  244. if (length < 0)
  245. return null;
  246. HashSet<T> result = new HashSet<T>();
  247. for (int i = 0; i < length; i++)
  248. {
  249. result.Add(reader.Read<T>());
  250. }
  251. return result;
  252. }
  253. */
  254. public static T[] ReadArray<T>(this NetworkReader reader)
  255. {
  256. int length = reader.ReadInt();
  257. // 'null' is encoded as '-1'
  258. if (length < 0) return null;
  259. // prevent allocation attacks with a reasonable limit.
  260. // server shouldn't allocate too much on client devices.
  261. // client shouldn't allocate too much on server in ClientToServer [SyncVar]s.
  262. if (length > NetworkReader.AllocationLimit)
  263. {
  264. // throw EndOfStream for consistency with ReadBlittable when out of data
  265. throw new EndOfStreamException($"NetworkReader attempted to allocate an Array<{typeof(T)}> with {length} elements, which is larger than the allowed limit of {NetworkReader.AllocationLimit}.");
  266. }
  267. // we can't check if reader.Remaining < length,
  268. // because we don't know sizeof(T) since it's a managed type.
  269. // if (length > reader.Remaining) throw new EndOfStreamException($"Received array that is too large: {length}");
  270. T[] result = new T[length];
  271. for (int i = 0; i < length; i++)
  272. {
  273. result[i] = reader.Read<T>();
  274. }
  275. return result;
  276. }
  277. public static Uri ReadUri(this NetworkReader reader)
  278. {
  279. string uriString = reader.ReadString();
  280. return (string.IsNullOrWhiteSpace(uriString) ? null : new Uri(uriString));
  281. }
  282. public static Texture2D ReadTexture2D(this NetworkReader reader)
  283. {
  284. // support 'null' textures for [SyncVar]s etc.
  285. // https://github.com/vis2k/Mirror/issues/3144
  286. short width = reader.ReadShort();
  287. if (width == -1) return null;
  288. // read height
  289. short height = reader.ReadShort();
  290. // prevent allocation attacks with a reasonable limit.
  291. // server shouldn't allocate too much on client devices.
  292. // client shouldn't allocate too much on server in ClientToServer [SyncVar]s.
  293. // log an error and return default.
  294. // we don't want attackers to be able to trigger exceptions.
  295. int totalSize = width * height;
  296. if (totalSize > NetworkReader.AllocationLimit)
  297. {
  298. Debug.LogWarning($"NetworkReader attempted to allocate a Texture2D with total size (width * height) of {totalSize}, which is larger than the allowed limit of {NetworkReader.AllocationLimit}.");
  299. return null;
  300. }
  301. Texture2D texture2D = new Texture2D(width, height);
  302. // read pixel content
  303. Color32[] pixels = reader.ReadArray<Color32>();
  304. texture2D.SetPixels32(pixels);
  305. texture2D.Apply();
  306. return texture2D;
  307. }
  308. public static Sprite ReadSprite(this NetworkReader reader)
  309. {
  310. // support 'null' textures for [SyncVar]s etc.
  311. // https://github.com/vis2k/Mirror/issues/3144
  312. Texture2D texture = reader.ReadTexture2D();
  313. if (texture == null) return null;
  314. // otherwise create a valid sprite
  315. return Sprite.Create(texture, reader.ReadRect(), reader.ReadVector2());
  316. }
  317. public static DateTime ReadDateTime(this NetworkReader reader) => DateTime.FromOADate(reader.ReadDouble());
  318. public static DateTime? ReadDateTimeNullable(this NetworkReader reader) => reader.ReadBool() ? ReadDateTime(reader) : default(DateTime?);
  319. }
  320. }