CodedInputStreamTest.cs 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961
  1. #region Copyright notice and license
  2. // Protocol Buffers - Google's data interchange format
  3. // Copyright 2008 Google Inc. All rights reserved.
  4. // https://developers.google.com/protocol-buffers/
  5. //
  6. // Redistribution and use in source and binary forms, with or without
  7. // modification, are permitted provided that the following conditions are
  8. // met:
  9. //
  10. // * Redistributions of source code must retain the above copyright
  11. // notice, this list of conditions and the following disclaimer.
  12. // * Redistributions in binary form must reproduce the above
  13. // copyright notice, this list of conditions and the following disclaimer
  14. // in the documentation and/or other materials provided with the
  15. // distribution.
  16. // * Neither the name of Google Inc. nor the names of its
  17. // contributors may be used to endorse or promote products derived from
  18. // this software without specific prior written permission.
  19. //
  20. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  21. // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  22. // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  23. // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  24. // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  25. // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  26. // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  27. // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  28. // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  29. // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  30. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  31. #endregion
  32. using System;
  33. using System.Buffers;
  34. using System.IO;
  35. using Google.Protobuf.TestProtos;
  36. using Proto2 = Google.Protobuf.TestProtos.Proto2;
  37. using NUnit.Framework;
  38. namespace Google.Protobuf
  39. {
  40. public class CodedInputStreamTest
  41. {
  42. /// <summary>
  43. /// Helper to construct a byte array from a bunch of bytes. The inputs are
  44. /// actually ints so that I can use hex notation and not get stupid errors
  45. /// about precision.
  46. /// </summary>
  47. private static byte[] Bytes(params int[] bytesAsInts)
  48. {
  49. byte[] bytes = new byte[bytesAsInts.Length];
  50. for (int i = 0; i < bytesAsInts.Length; i++)
  51. {
  52. bytes[i] = (byte) bytesAsInts[i];
  53. }
  54. return bytes;
  55. }
  56. /// <summary>
  57. /// Parses the given bytes using ReadRawVarint32() and ReadRawVarint64()
  58. /// </summary>
  59. private static void AssertReadVarint(byte[] data, ulong value)
  60. {
  61. CodedInputStream input = new CodedInputStream(data);
  62. Assert.AreEqual((uint) value, input.ReadRawVarint32());
  63. Assert.IsTrue(input.IsAtEnd);
  64. input = new CodedInputStream(data);
  65. Assert.AreEqual(value, input.ReadRawVarint64());
  66. Assert.IsTrue(input.IsAtEnd);
  67. AssertReadFromParseContext(new ReadOnlySequence<byte>(data), (ref ParseContext ctx) =>
  68. {
  69. Assert.AreEqual((uint) value, ctx.ReadUInt32());
  70. }, true);
  71. AssertReadFromParseContext(new ReadOnlySequence<byte>(data), (ref ParseContext ctx) =>
  72. {
  73. Assert.AreEqual(value, ctx.ReadUInt64());
  74. }, true);
  75. // Try different block sizes.
  76. for (int bufferSize = 1; bufferSize <= 16; bufferSize *= 2)
  77. {
  78. input = new CodedInputStream(new SmallBlockInputStream(data, bufferSize));
  79. Assert.AreEqual((uint) value, input.ReadRawVarint32());
  80. input = new CodedInputStream(new SmallBlockInputStream(data, bufferSize));
  81. Assert.AreEqual(value, input.ReadRawVarint64());
  82. Assert.IsTrue(input.IsAtEnd);
  83. AssertReadFromParseContext(ReadOnlySequenceFactory.CreateWithContent(data, bufferSize), (ref ParseContext ctx) =>
  84. {
  85. Assert.AreEqual((uint) value, ctx.ReadUInt32());
  86. }, true);
  87. AssertReadFromParseContext(ReadOnlySequenceFactory.CreateWithContent(data, bufferSize), (ref ParseContext ctx) =>
  88. {
  89. Assert.AreEqual(value, ctx.ReadUInt64());
  90. }, true);
  91. }
  92. // Try reading directly from a MemoryStream. We want to verify that it
  93. // doesn't read past the end of the input, so write an extra byte - this
  94. // lets us test the position at the end.
  95. MemoryStream memoryStream = new MemoryStream();
  96. memoryStream.Write(data, 0, data.Length);
  97. memoryStream.WriteByte(0);
  98. memoryStream.Position = 0;
  99. Assert.AreEqual((uint) value, CodedInputStream.ReadRawVarint32(memoryStream));
  100. Assert.AreEqual(data.Length, memoryStream.Position);
  101. }
  102. /// <summary>
  103. /// Parses the given bytes using ReadRawVarint32() and ReadRawVarint64() and
  104. /// expects them to fail with an InvalidProtocolBufferException whose
  105. /// description matches the given one.
  106. /// </summary>
  107. private static void AssertReadVarintFailure(InvalidProtocolBufferException expected, byte[] data)
  108. {
  109. CodedInputStream input = new CodedInputStream(data);
  110. var exception = Assert.Throws<InvalidProtocolBufferException>(() => input.ReadRawVarint32());
  111. Assert.AreEqual(expected.Message, exception.Message);
  112. input = new CodedInputStream(data);
  113. exception = Assert.Throws<InvalidProtocolBufferException>(() => input.ReadRawVarint64());
  114. Assert.AreEqual(expected.Message, exception.Message);
  115. AssertReadFromParseContext(new ReadOnlySequence<byte>(data), (ref ParseContext ctx) =>
  116. {
  117. try
  118. {
  119. ctx.ReadUInt32();
  120. Assert.Fail();
  121. }
  122. catch (InvalidProtocolBufferException ex)
  123. {
  124. Assert.AreEqual(expected.Message, ex.Message);
  125. }
  126. }, false);
  127. AssertReadFromParseContext(new ReadOnlySequence<byte>(data), (ref ParseContext ctx) =>
  128. {
  129. try
  130. {
  131. ctx.ReadUInt64();
  132. Assert.Fail();
  133. }
  134. catch (InvalidProtocolBufferException ex)
  135. {
  136. Assert.AreEqual(expected.Message, ex.Message);
  137. }
  138. }, false);
  139. // Make sure we get the same error when reading directly from a Stream.
  140. exception = Assert.Throws<InvalidProtocolBufferException>(() => CodedInputStream.ReadRawVarint32(new MemoryStream(data)));
  141. Assert.AreEqual(expected.Message, exception.Message);
  142. }
  143. private delegate void ParseContextAssertAction(ref ParseContext ctx);
  144. private static void AssertReadFromParseContext(ReadOnlySequence<byte> input, ParseContextAssertAction assertAction, bool assertIsAtEnd)
  145. {
  146. ParseContext.Initialize(input, out ParseContext parseCtx);
  147. assertAction(ref parseCtx);
  148. if (assertIsAtEnd)
  149. {
  150. Assert.IsTrue(SegmentedBufferHelper.IsAtEnd(ref parseCtx.buffer, ref parseCtx.state));
  151. }
  152. }
  153. [Test]
  154. public void ReadVarint()
  155. {
  156. AssertReadVarint(Bytes(0x00), 0);
  157. AssertReadVarint(Bytes(0x01), 1);
  158. AssertReadVarint(Bytes(0x7f), 127);
  159. // 14882
  160. AssertReadVarint(Bytes(0xa2, 0x74), (0x22 << 0) | (0x74 << 7));
  161. // 2961488830
  162. AssertReadVarint(Bytes(0xbe, 0xf7, 0x92, 0x84, 0x0b),
  163. (0x3e << 0) | (0x77 << 7) | (0x12 << 14) | (0x04 << 21) |
  164. (0x0bL << 28));
  165. // 64-bit
  166. // 7256456126
  167. AssertReadVarint(Bytes(0xbe, 0xf7, 0x92, 0x84, 0x1b),
  168. (0x3e << 0) | (0x77 << 7) | (0x12 << 14) | (0x04 << 21) |
  169. (0x1bL << 28));
  170. // 41256202580718336
  171. AssertReadVarint(Bytes(0x80, 0xe6, 0xeb, 0x9c, 0xc3, 0xc9, 0xa4, 0x49),
  172. (0x00 << 0) | (0x66 << 7) | (0x6b << 14) | (0x1c << 21) |
  173. (0x43L << 28) | (0x49L << 35) | (0x24L << 42) | (0x49L << 49));
  174. // 11964378330978735131
  175. AssertReadVarint(Bytes(0x9b, 0xa8, 0xf9, 0xc2, 0xbb, 0xd6, 0x80, 0x85, 0xa6, 0x01),
  176. (0x1b << 0) | (0x28 << 7) | (0x79 << 14) | (0x42 << 21) |
  177. (0x3bUL << 28) | (0x56UL << 35) | (0x00UL << 42) |
  178. (0x05UL << 49) | (0x26UL << 56) | (0x01UL << 63));
  179. // Failures
  180. AssertReadVarintFailure(
  181. InvalidProtocolBufferException.MalformedVarint(),
  182. Bytes(0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80,
  183. 0x00));
  184. AssertReadVarintFailure(
  185. InvalidProtocolBufferException.TruncatedMessage(),
  186. Bytes(0x80));
  187. }
  188. /// <summary>
  189. /// Parses the given bytes using ReadRawLittleEndian32() and checks
  190. /// that the result matches the given value.
  191. /// </summary>
  192. private static void AssertReadLittleEndian32(byte[] data, uint value)
  193. {
  194. CodedInputStream input = new CodedInputStream(data);
  195. Assert.AreEqual(value, input.ReadRawLittleEndian32());
  196. Assert.IsTrue(input.IsAtEnd);
  197. AssertReadFromParseContext(new ReadOnlySequence<byte>(data), (ref ParseContext ctx) =>
  198. {
  199. Assert.AreEqual(value, ctx.ReadFixed32());
  200. }, true);
  201. // Try different block sizes.
  202. for (int blockSize = 1; blockSize <= 16; blockSize *= 2)
  203. {
  204. input = new CodedInputStream(
  205. new SmallBlockInputStream(data, blockSize));
  206. Assert.AreEqual(value, input.ReadRawLittleEndian32());
  207. Assert.IsTrue(input.IsAtEnd);
  208. AssertReadFromParseContext(ReadOnlySequenceFactory.CreateWithContent(data, blockSize), (ref ParseContext ctx) =>
  209. {
  210. Assert.AreEqual(value, ctx.ReadFixed32());
  211. }, true);
  212. }
  213. }
  214. /// <summary>
  215. /// Parses the given bytes using ReadRawLittleEndian64() and checks
  216. /// that the result matches the given value.
  217. /// </summary>
  218. private static void AssertReadLittleEndian64(byte[] data, ulong value)
  219. {
  220. CodedInputStream input = new CodedInputStream(data);
  221. Assert.AreEqual(value, input.ReadRawLittleEndian64());
  222. Assert.IsTrue(input.IsAtEnd);
  223. AssertReadFromParseContext(new ReadOnlySequence<byte>(data), (ref ParseContext ctx) =>
  224. {
  225. Assert.AreEqual(value, ctx.ReadFixed64());
  226. }, true);
  227. // Try different block sizes.
  228. for (int blockSize = 1; blockSize <= 16; blockSize *= 2)
  229. {
  230. input = new CodedInputStream(
  231. new SmallBlockInputStream(data, blockSize));
  232. Assert.AreEqual(value, input.ReadRawLittleEndian64());
  233. Assert.IsTrue(input.IsAtEnd);
  234. AssertReadFromParseContext(ReadOnlySequenceFactory.CreateWithContent(data, blockSize), (ref ParseContext ctx) =>
  235. {
  236. Assert.AreEqual(value, ctx.ReadFixed64());
  237. }, true);
  238. }
  239. }
  240. [Test]
  241. public void ReadLittleEndian()
  242. {
  243. AssertReadLittleEndian32(Bytes(0x78, 0x56, 0x34, 0x12), 0x12345678);
  244. AssertReadLittleEndian32(Bytes(0xf0, 0xde, 0xbc, 0x9a), 0x9abcdef0);
  245. AssertReadLittleEndian64(Bytes(0xf0, 0xde, 0xbc, 0x9a, 0x78, 0x56, 0x34, 0x12),
  246. 0x123456789abcdef0L);
  247. AssertReadLittleEndian64(
  248. Bytes(0x78, 0x56, 0x34, 0x12, 0xf0, 0xde, 0xbc, 0x9a), 0x9abcdef012345678UL);
  249. }
  250. [Test]
  251. public void DecodeZigZag32()
  252. {
  253. Assert.AreEqual(0, ParsingPrimitives.DecodeZigZag32(0));
  254. Assert.AreEqual(-1, ParsingPrimitives.DecodeZigZag32(1));
  255. Assert.AreEqual(1, ParsingPrimitives.DecodeZigZag32(2));
  256. Assert.AreEqual(-2, ParsingPrimitives.DecodeZigZag32(3));
  257. Assert.AreEqual(0x3FFFFFFF, ParsingPrimitives.DecodeZigZag32(0x7FFFFFFE));
  258. Assert.AreEqual(unchecked((int) 0xC0000000), ParsingPrimitives.DecodeZigZag32(0x7FFFFFFF));
  259. Assert.AreEqual(0x7FFFFFFF, ParsingPrimitives.DecodeZigZag32(0xFFFFFFFE));
  260. Assert.AreEqual(unchecked((int) 0x80000000), ParsingPrimitives.DecodeZigZag32(0xFFFFFFFF));
  261. }
  262. [Test]
  263. public void DecodeZigZag64()
  264. {
  265. Assert.AreEqual(0, ParsingPrimitives.DecodeZigZag64(0));
  266. Assert.AreEqual(-1, ParsingPrimitives.DecodeZigZag64(1));
  267. Assert.AreEqual(1, ParsingPrimitives.DecodeZigZag64(2));
  268. Assert.AreEqual(-2, ParsingPrimitives.DecodeZigZag64(3));
  269. Assert.AreEqual(0x000000003FFFFFFFL, ParsingPrimitives.DecodeZigZag64(0x000000007FFFFFFEL));
  270. Assert.AreEqual(unchecked((long) 0xFFFFFFFFC0000000L), ParsingPrimitives.DecodeZigZag64(0x000000007FFFFFFFL));
  271. Assert.AreEqual(0x000000007FFFFFFFL, ParsingPrimitives.DecodeZigZag64(0x00000000FFFFFFFEL));
  272. Assert.AreEqual(unchecked((long) 0xFFFFFFFF80000000L), ParsingPrimitives.DecodeZigZag64(0x00000000FFFFFFFFL));
  273. Assert.AreEqual(0x7FFFFFFFFFFFFFFFL, ParsingPrimitives.DecodeZigZag64(0xFFFFFFFFFFFFFFFEL));
  274. Assert.AreEqual(unchecked((long) 0x8000000000000000L), ParsingPrimitives.DecodeZigZag64(0xFFFFFFFFFFFFFFFFL));
  275. }
  276. [Test]
  277. public void ReadWholeMessage_VaryingBlockSizes()
  278. {
  279. TestAllTypes message = SampleMessages.CreateFullTestAllTypes();
  280. byte[] rawBytes = message.ToByteArray();
  281. Assert.AreEqual(rawBytes.Length, message.CalculateSize());
  282. TestAllTypes message2 = TestAllTypes.Parser.ParseFrom(rawBytes);
  283. Assert.AreEqual(message, message2);
  284. // Try different block sizes.
  285. for (int blockSize = 1; blockSize < 256; blockSize *= 2)
  286. {
  287. message2 = TestAllTypes.Parser.ParseFrom(new SmallBlockInputStream(rawBytes, blockSize));
  288. Assert.AreEqual(message, message2);
  289. }
  290. }
  291. [Test]
  292. public void ReadWholeMessage_VaryingBlockSizes_FromSequence()
  293. {
  294. TestAllTypes message = SampleMessages.CreateFullTestAllTypes();
  295. byte[] rawBytes = message.ToByteArray();
  296. Assert.AreEqual(rawBytes.Length, message.CalculateSize());
  297. TestAllTypes message2 = TestAllTypes.Parser.ParseFrom(rawBytes);
  298. Assert.AreEqual(message, message2);
  299. // Try different block sizes.
  300. for (int blockSize = 1; blockSize < 256; blockSize *= 2)
  301. {
  302. message2 = TestAllTypes.Parser.ParseFrom(ReadOnlySequenceFactory.CreateWithContent(rawBytes, blockSize));
  303. Assert.AreEqual(message, message2);
  304. }
  305. }
  306. [Test]
  307. public void ReadHugeBlob()
  308. {
  309. // Allocate and initialize a 1MB blob.
  310. byte[] blob = new byte[1 << 20];
  311. for (int i = 0; i < blob.Length; i++)
  312. {
  313. blob[i] = (byte) i;
  314. }
  315. // Make a message containing it.
  316. var message = new TestAllTypes { SingleBytes = ByteString.CopyFrom(blob) };
  317. // Serialize and parse it. Make sure to parse from an InputStream, not
  318. // directly from a ByteString, so that CodedInputStream uses buffered
  319. // reading.
  320. TestAllTypes message2 = TestAllTypes.Parser.ParseFrom(message.ToByteString());
  321. Assert.AreEqual(message, message2);
  322. }
  323. [Test]
  324. public void ReadMaliciouslyLargeBlob()
  325. {
  326. MemoryStream ms = new MemoryStream();
  327. CodedOutputStream output = new CodedOutputStream(ms);
  328. uint tag = WireFormat.MakeTag(1, WireFormat.WireType.LengthDelimited);
  329. output.WriteRawVarint32(tag);
  330. output.WriteRawVarint32(0x7FFFFFFF);
  331. output.WriteRawBytes(new byte[32]); // Pad with a few random bytes.
  332. output.Flush();
  333. ms.Position = 0;
  334. CodedInputStream input = new CodedInputStream(ms);
  335. Assert.AreEqual(tag, input.ReadTag());
  336. Assert.Throws<InvalidProtocolBufferException>(() => input.ReadBytes());
  337. }
  338. [Test]
  339. public void ReadBlobGreaterThanCurrentLimit()
  340. {
  341. MemoryStream ms = new MemoryStream();
  342. CodedOutputStream output = new CodedOutputStream(ms);
  343. uint tag = WireFormat.MakeTag(1, WireFormat.WireType.LengthDelimited);
  344. output.WriteRawVarint32(tag);
  345. output.WriteRawVarint32(4);
  346. output.WriteRawBytes(new byte[4]); // Pad with a few random bytes.
  347. output.Flush();
  348. ms.Position = 0;
  349. CodedInputStream input = new CodedInputStream(ms);
  350. Assert.AreEqual(tag, input.ReadTag());
  351. // Specify limit smaller than data length
  352. input.PushLimit(3);
  353. Assert.Throws<InvalidProtocolBufferException>(() => input.ReadBytes());
  354. AssertReadFromParseContext(new ReadOnlySequence<byte>(ms.ToArray()), (ref ParseContext ctx) =>
  355. {
  356. Assert.AreEqual(tag, ctx.ReadTag());
  357. SegmentedBufferHelper.PushLimit(ref ctx.state, 3);
  358. try
  359. {
  360. ctx.ReadBytes();
  361. Assert.Fail();
  362. }
  363. catch (InvalidProtocolBufferException) {}
  364. }, true);
  365. }
  366. [Test]
  367. public void ReadStringGreaterThanCurrentLimit()
  368. {
  369. MemoryStream ms = new MemoryStream();
  370. CodedOutputStream output = new CodedOutputStream(ms);
  371. uint tag = WireFormat.MakeTag(1, WireFormat.WireType.LengthDelimited);
  372. output.WriteRawVarint32(tag);
  373. output.WriteRawVarint32(4);
  374. output.WriteRawBytes(new byte[4]); // Pad with a few random bytes.
  375. output.Flush();
  376. ms.Position = 0;
  377. CodedInputStream input = new CodedInputStream(ms.ToArray());
  378. Assert.AreEqual(tag, input.ReadTag());
  379. // Specify limit smaller than data length
  380. input.PushLimit(3);
  381. Assert.Throws<InvalidProtocolBufferException>(() => input.ReadString());
  382. AssertReadFromParseContext(new ReadOnlySequence<byte>(ms.ToArray()), (ref ParseContext ctx) =>
  383. {
  384. Assert.AreEqual(tag, ctx.ReadTag());
  385. SegmentedBufferHelper.PushLimit(ref ctx.state, 3);
  386. try
  387. {
  388. ctx.ReadString();
  389. Assert.Fail();
  390. }
  391. catch (InvalidProtocolBufferException) { }
  392. }, true);
  393. }
  394. // Representations of a tag for field 0 with various wire types
  395. [Test]
  396. [TestCase(0)]
  397. [TestCase(1)]
  398. [TestCase(2)]
  399. [TestCase(3)]
  400. [TestCase(4)]
  401. [TestCase(5)]
  402. public void ReadTag_ZeroFieldRejected(byte tag)
  403. {
  404. CodedInputStream cis = new CodedInputStream(new byte[] { tag });
  405. Assert.Throws<InvalidProtocolBufferException>(() => cis.ReadTag());
  406. }
  407. internal static TestRecursiveMessage MakeRecursiveMessage(int depth)
  408. {
  409. if (depth == 0)
  410. {
  411. return new TestRecursiveMessage { I = 5 };
  412. }
  413. else
  414. {
  415. return new TestRecursiveMessage { A = MakeRecursiveMessage(depth - 1) };
  416. }
  417. }
  418. internal static void AssertMessageDepth(TestRecursiveMessage message, int depth)
  419. {
  420. if (depth == 0)
  421. {
  422. Assert.IsNull(message.A);
  423. Assert.AreEqual(5, message.I);
  424. }
  425. else
  426. {
  427. Assert.IsNotNull(message.A);
  428. AssertMessageDepth(message.A, depth - 1);
  429. }
  430. }
  431. [Test]
  432. public void MaliciousRecursion()
  433. {
  434. ByteString atRecursiveLimit = MakeRecursiveMessage(CodedInputStream.DefaultRecursionLimit).ToByteString();
  435. ByteString beyondRecursiveLimit = MakeRecursiveMessage(CodedInputStream.DefaultRecursionLimit + 1).ToByteString();
  436. AssertMessageDepth(TestRecursiveMessage.Parser.ParseFrom(atRecursiveLimit), CodedInputStream.DefaultRecursionLimit);
  437. Assert.Throws<InvalidProtocolBufferException>(() => TestRecursiveMessage.Parser.ParseFrom(beyondRecursiveLimit));
  438. CodedInputStream input = CodedInputStream.CreateWithLimits(new MemoryStream(atRecursiveLimit.ToByteArray()), 1000000, CodedInputStream.DefaultRecursionLimit - 1);
  439. Assert.Throws<InvalidProtocolBufferException>(() => TestRecursiveMessage.Parser.ParseFrom(input));
  440. }
  441. private static byte[] MakeMaliciousRecursionUnknownFieldsPayload(int recursionDepth)
  442. {
  443. // generate recursively nested groups that will be parsed as unknown fields
  444. int unknownFieldNumber = 14; // an unused field number
  445. MemoryStream ms = new MemoryStream();
  446. CodedOutputStream output = new CodedOutputStream(ms);
  447. for (int i = 0; i < recursionDepth; i++)
  448. {
  449. output.WriteTag(WireFormat.MakeTag(unknownFieldNumber, WireFormat.WireType.StartGroup));
  450. }
  451. for (int i = 0; i < recursionDepth; i++)
  452. {
  453. output.WriteTag(WireFormat.MakeTag(unknownFieldNumber, WireFormat.WireType.EndGroup));
  454. }
  455. output.Flush();
  456. return ms.ToArray();
  457. }
  458. [Test]
  459. public void MaliciousRecursion_UnknownFields()
  460. {
  461. byte[] payloadAtRecursiveLimit = MakeMaliciousRecursionUnknownFieldsPayload(CodedInputStream.DefaultRecursionLimit);
  462. byte[] payloadBeyondRecursiveLimit = MakeMaliciousRecursionUnknownFieldsPayload(CodedInputStream.DefaultRecursionLimit + 1);
  463. Assert.DoesNotThrow(() => TestRecursiveMessage.Parser.ParseFrom(payloadAtRecursiveLimit));
  464. Assert.Throws<InvalidProtocolBufferException>(() => TestRecursiveMessage.Parser.ParseFrom(payloadBeyondRecursiveLimit));
  465. }
  466. [Test]
  467. public void ReadGroup_WrongEndGroupTag()
  468. {
  469. int groupFieldNumber = Proto2.TestAllTypes.OptionalGroupFieldNumber;
  470. // write Proto2.TestAllTypes with "optional_group" set, but use wrong EndGroup closing tag
  471. MemoryStream ms = new MemoryStream();
  472. CodedOutputStream output = new CodedOutputStream(ms);
  473. output.WriteTag(WireFormat.MakeTag(groupFieldNumber, WireFormat.WireType.StartGroup));
  474. output.WriteGroup(new Proto2.TestAllTypes.Types.OptionalGroup { A = 12345 });
  475. // end group with different field number
  476. output.WriteTag(WireFormat.MakeTag(groupFieldNumber + 1, WireFormat.WireType.EndGroup));
  477. output.Flush();
  478. var payload = ms.ToArray();
  479. Assert.Throws<InvalidProtocolBufferException>(() => Proto2.TestAllTypes.Parser.ParseFrom(payload));
  480. }
  481. [Test]
  482. public void ReadGroup_UnknownFields_WrongEndGroupTag()
  483. {
  484. MemoryStream ms = new MemoryStream();
  485. CodedOutputStream output = new CodedOutputStream(ms);
  486. output.WriteTag(WireFormat.MakeTag(14, WireFormat.WireType.StartGroup));
  487. // end group with different field number
  488. output.WriteTag(WireFormat.MakeTag(15, WireFormat.WireType.EndGroup));
  489. output.Flush();
  490. var payload = ms.ToArray();
  491. Assert.Throws<InvalidProtocolBufferException>(() => TestRecursiveMessage.Parser.ParseFrom(payload));
  492. }
  493. [Test]
  494. public void SizeLimit()
  495. {
  496. // Have to use a Stream rather than ByteString.CreateCodedInput as SizeLimit doesn't
  497. // apply to the latter case.
  498. MemoryStream ms = new MemoryStream(SampleMessages.CreateFullTestAllTypes().ToByteArray());
  499. CodedInputStream input = CodedInputStream.CreateWithLimits(ms, 16, 100);
  500. Assert.Throws<InvalidProtocolBufferException>(() => TestAllTypes.Parser.ParseFrom(input));
  501. }
  502. /// <summary>
  503. /// Tests that if we read an string that contains invalid UTF-8, no exception
  504. /// is thrown. Instead, the invalid bytes are replaced with the Unicode
  505. /// "replacement character" U+FFFD.
  506. /// </summary>
  507. [Test]
  508. public void ReadInvalidUtf8()
  509. {
  510. MemoryStream ms = new MemoryStream();
  511. CodedOutputStream output = new CodedOutputStream(ms);
  512. uint tag = WireFormat.MakeTag(1, WireFormat.WireType.LengthDelimited);
  513. output.WriteRawVarint32(tag);
  514. output.WriteRawVarint32(1);
  515. output.WriteRawBytes(new byte[] {0x80});
  516. output.Flush();
  517. ms.Position = 0;
  518. CodedInputStream input = new CodedInputStream(ms);
  519. Assert.AreEqual(tag, input.ReadTag());
  520. string text = input.ReadString();
  521. Assert.AreEqual('\ufffd', text[0]);
  522. }
  523. [Test]
  524. public void ReadNegativeSizedStringThrowsInvalidProtocolBufferException()
  525. {
  526. MemoryStream ms = new MemoryStream();
  527. CodedOutputStream output = new CodedOutputStream(ms);
  528. uint tag = WireFormat.MakeTag(1, WireFormat.WireType.LengthDelimited);
  529. output.WriteRawVarint32(tag);
  530. output.WriteLength(-1);
  531. output.Flush();
  532. ms.Position = 0;
  533. CodedInputStream input = new CodedInputStream(ms);
  534. Assert.AreEqual(tag, input.ReadTag());
  535. Assert.Throws<InvalidProtocolBufferException>(() => input.ReadString());
  536. }
  537. [Test]
  538. public void ReadNegativeSizedBytesThrowsInvalidProtocolBufferException()
  539. {
  540. MemoryStream ms = new MemoryStream();
  541. CodedOutputStream output = new CodedOutputStream(ms);
  542. uint tag = WireFormat.MakeTag(1, WireFormat.WireType.LengthDelimited);
  543. output.WriteRawVarint32(tag);
  544. output.WriteLength(-1);
  545. output.Flush();
  546. ms.Position = 0;
  547. CodedInputStream input = new CodedInputStream(ms);
  548. Assert.AreEqual(tag, input.ReadTag());
  549. Assert.Throws<InvalidProtocolBufferException>(() => input.ReadBytes());
  550. }
  551. /// <summary>
  552. /// A stream which limits the number of bytes it reads at a time.
  553. /// We use this to make sure that CodedInputStream doesn't screw up when
  554. /// reading in small blocks.
  555. /// </summary>
  556. private sealed class SmallBlockInputStream : MemoryStream
  557. {
  558. private readonly int blockSize;
  559. public SmallBlockInputStream(byte[] data, int blockSize)
  560. : base(data)
  561. {
  562. this.blockSize = blockSize;
  563. }
  564. public override int Read(byte[] buffer, int offset, int count)
  565. {
  566. return base.Read(buffer, offset, Math.Min(count, blockSize));
  567. }
  568. }
  569. [Test]
  570. public void TestNegativeEnum()
  571. {
  572. byte[] bytes = { 0xFE, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01 };
  573. CodedInputStream input = new CodedInputStream(bytes);
  574. Assert.AreEqual((int)SampleEnum.NegativeValue, input.ReadEnum());
  575. Assert.IsTrue(input.IsAtEnd);
  576. }
  577. //Issue 71: CodedInputStream.ReadBytes go to slow path unnecessarily
  578. [Test]
  579. public void TestSlowPathAvoidance()
  580. {
  581. using (var ms = new MemoryStream())
  582. {
  583. CodedOutputStream output = new CodedOutputStream(ms);
  584. output.WriteTag(1, WireFormat.WireType.LengthDelimited);
  585. output.WriteBytes(ByteString.CopyFrom(new byte[100]));
  586. output.WriteTag(2, WireFormat.WireType.LengthDelimited);
  587. output.WriteBytes(ByteString.CopyFrom(new byte[100]));
  588. output.Flush();
  589. ms.Position = 0;
  590. CodedInputStream input = new CodedInputStream(ms, new byte[ms.Length / 2], 0, 0, false);
  591. uint tag = input.ReadTag();
  592. Assert.AreEqual(1, WireFormat.GetTagFieldNumber(tag));
  593. Assert.AreEqual(100, input.ReadBytes().Length);
  594. tag = input.ReadTag();
  595. Assert.AreEqual(2, WireFormat.GetTagFieldNumber(tag));
  596. Assert.AreEqual(100, input.ReadBytes().Length);
  597. }
  598. }
  599. [Test]
  600. public void Tag0Throws()
  601. {
  602. var input = new CodedInputStream(new byte[] { 0 });
  603. Assert.Throws<InvalidProtocolBufferException>(() => input.ReadTag());
  604. }
  605. [Test]
  606. public void SkipGroup()
  607. {
  608. // Create an output stream with a group in:
  609. // Field 1: string "field 1"
  610. // Field 2: group containing:
  611. // Field 1: fixed int32 value 100
  612. // Field 2: string "ignore me"
  613. // Field 3: nested group containing
  614. // Field 1: fixed int64 value 1000
  615. // Field 3: string "field 3"
  616. var stream = new MemoryStream();
  617. var output = new CodedOutputStream(stream);
  618. output.WriteTag(1, WireFormat.WireType.LengthDelimited);
  619. output.WriteString("field 1");
  620. // The outer group...
  621. output.WriteTag(2, WireFormat.WireType.StartGroup);
  622. output.WriteTag(1, WireFormat.WireType.Fixed32);
  623. output.WriteFixed32(100);
  624. output.WriteTag(2, WireFormat.WireType.LengthDelimited);
  625. output.WriteString("ignore me");
  626. // The nested group...
  627. output.WriteTag(3, WireFormat.WireType.StartGroup);
  628. output.WriteTag(1, WireFormat.WireType.Fixed64);
  629. output.WriteFixed64(1000);
  630. // Note: Not sure the field number is relevant for end group...
  631. output.WriteTag(3, WireFormat.WireType.EndGroup);
  632. // End the outer group
  633. output.WriteTag(2, WireFormat.WireType.EndGroup);
  634. output.WriteTag(3, WireFormat.WireType.LengthDelimited);
  635. output.WriteString("field 3");
  636. output.Flush();
  637. stream.Position = 0;
  638. // Now act like a generated client
  639. var input = new CodedInputStream(stream);
  640. Assert.AreEqual(WireFormat.MakeTag(1, WireFormat.WireType.LengthDelimited), input.ReadTag());
  641. Assert.AreEqual("field 1", input.ReadString());
  642. Assert.AreEqual(WireFormat.MakeTag(2, WireFormat.WireType.StartGroup), input.ReadTag());
  643. input.SkipLastField(); // Should consume the whole group, including the nested one.
  644. Assert.AreEqual(WireFormat.MakeTag(3, WireFormat.WireType.LengthDelimited), input.ReadTag());
  645. Assert.AreEqual("field 3", input.ReadString());
  646. }
  647. [Test]
  648. public void SkipGroup_WrongEndGroupTag()
  649. {
  650. // Create an output stream with:
  651. // Field 1: string "field 1"
  652. // Start group 2
  653. // Field 3: fixed int32
  654. // End group 4 (should give an error)
  655. var stream = new MemoryStream();
  656. var output = new CodedOutputStream(stream);
  657. output.WriteTag(1, WireFormat.WireType.LengthDelimited);
  658. output.WriteString("field 1");
  659. // The outer group...
  660. output.WriteTag(2, WireFormat.WireType.StartGroup);
  661. output.WriteTag(3, WireFormat.WireType.Fixed32);
  662. output.WriteFixed32(100);
  663. output.WriteTag(4, WireFormat.WireType.EndGroup);
  664. output.Flush();
  665. stream.Position = 0;
  666. // Now act like a generated client
  667. var input = new CodedInputStream(stream);
  668. Assert.AreEqual(WireFormat.MakeTag(1, WireFormat.WireType.LengthDelimited), input.ReadTag());
  669. Assert.AreEqual("field 1", input.ReadString());
  670. Assert.AreEqual(WireFormat.MakeTag(2, WireFormat.WireType.StartGroup), input.ReadTag());
  671. Assert.Throws<InvalidProtocolBufferException>(input.SkipLastField);
  672. }
  673. [Test]
  674. public void RogueEndGroupTag()
  675. {
  676. // If we have an end-group tag without a leading start-group tag, generated
  677. // code will just call SkipLastField... so that should fail.
  678. var stream = new MemoryStream();
  679. var output = new CodedOutputStream(stream);
  680. output.WriteTag(1, WireFormat.WireType.EndGroup);
  681. output.Flush();
  682. stream.Position = 0;
  683. var input = new CodedInputStream(stream);
  684. Assert.AreEqual(WireFormat.MakeTag(1, WireFormat.WireType.EndGroup), input.ReadTag());
  685. Assert.Throws<InvalidProtocolBufferException>(input.SkipLastField);
  686. }
  687. [Test]
  688. public void EndOfStreamReachedWhileSkippingGroup()
  689. {
  690. var stream = new MemoryStream();
  691. var output = new CodedOutputStream(stream);
  692. output.WriteTag(1, WireFormat.WireType.StartGroup);
  693. output.WriteTag(2, WireFormat.WireType.StartGroup);
  694. output.WriteTag(2, WireFormat.WireType.EndGroup);
  695. output.Flush();
  696. stream.Position = 0;
  697. // Now act like a generated client
  698. var input = new CodedInputStream(stream);
  699. input.ReadTag();
  700. Assert.Throws<InvalidProtocolBufferException>(input.SkipLastField);
  701. }
  702. [Test]
  703. public void RecursionLimitAppliedWhileSkippingGroup()
  704. {
  705. var stream = new MemoryStream();
  706. var output = new CodedOutputStream(stream);
  707. for (int i = 0; i < CodedInputStream.DefaultRecursionLimit + 1; i++)
  708. {
  709. output.WriteTag(1, WireFormat.WireType.StartGroup);
  710. }
  711. for (int i = 0; i < CodedInputStream.DefaultRecursionLimit + 1; i++)
  712. {
  713. output.WriteTag(1, WireFormat.WireType.EndGroup);
  714. }
  715. output.Flush();
  716. stream.Position = 0;
  717. // Now act like a generated client
  718. var input = new CodedInputStream(stream);
  719. Assert.AreEqual(WireFormat.MakeTag(1, WireFormat.WireType.StartGroup), input.ReadTag());
  720. Assert.Throws<InvalidProtocolBufferException>(input.SkipLastField);
  721. }
  722. [Test]
  723. public void Construction_Invalid()
  724. {
  725. Assert.Throws<ArgumentNullException>(() => new CodedInputStream((byte[]) null));
  726. Assert.Throws<ArgumentNullException>(() => new CodedInputStream(null, 0, 0));
  727. Assert.Throws<ArgumentNullException>(() => new CodedInputStream((Stream) null));
  728. Assert.Throws<ArgumentOutOfRangeException>(() => new CodedInputStream(new byte[10], 100, 0));
  729. Assert.Throws<ArgumentOutOfRangeException>(() => new CodedInputStream(new byte[10], 5, 10));
  730. }
  731. [Test]
  732. public void CreateWithLimits_InvalidLimits()
  733. {
  734. var stream = new MemoryStream();
  735. Assert.Throws<ArgumentOutOfRangeException>(() => CodedInputStream.CreateWithLimits(stream, 0, 1));
  736. Assert.Throws<ArgumentOutOfRangeException>(() => CodedInputStream.CreateWithLimits(stream, 1, 0));
  737. }
  738. [Test]
  739. public void Dispose_DisposesUnderlyingStream()
  740. {
  741. var memoryStream = new MemoryStream();
  742. Assert.IsTrue(memoryStream.CanRead);
  743. using (var cis = new CodedInputStream(memoryStream))
  744. {
  745. }
  746. Assert.IsFalse(memoryStream.CanRead); // Disposed
  747. }
  748. [Test]
  749. public void Dispose_WithLeaveOpen()
  750. {
  751. var memoryStream = new MemoryStream();
  752. Assert.IsTrue(memoryStream.CanRead);
  753. using (var cis = new CodedInputStream(memoryStream, true))
  754. {
  755. }
  756. Assert.IsTrue(memoryStream.CanRead); // We left the stream open
  757. }
  758. [Test]
  759. public void Dispose_FromByteArray()
  760. {
  761. var stream = new CodedInputStream(new byte[10]);
  762. stream.Dispose();
  763. }
  764. [Test]
  765. public void TestParseMessagesCloseTo2G()
  766. {
  767. byte[] serializedMessage = GenerateBigSerializedMessage();
  768. // How many of these big messages do we need to take us near our 2GB limit?
  769. int count = Int32.MaxValue / serializedMessage.Length;
  770. // Now make a MemoryStream that will fake a near-2GB stream of messages by returning
  771. // our big serialized message 'count' times.
  772. using (RepeatingMemoryStream stream = new RepeatingMemoryStream(serializedMessage, count))
  773. {
  774. Assert.DoesNotThrow(()=>TestAllTypes.Parser.ParseFrom(stream));
  775. }
  776. }
  777. [Test]
  778. public void TestParseMessagesOver2G()
  779. {
  780. byte[] serializedMessage = GenerateBigSerializedMessage();
  781. // How many of these big messages do we need to take us near our 2GB limit?
  782. int count = Int32.MaxValue / serializedMessage.Length;
  783. // Now add one to take us over the 2GB limit
  784. count++;
  785. // Now make a MemoryStream that will fake a near-2GB stream of messages by returning
  786. // our big serialized message 'count' times.
  787. using (RepeatingMemoryStream stream = new RepeatingMemoryStream(serializedMessage, count))
  788. {
  789. Assert.Throws<InvalidProtocolBufferException>(() => TestAllTypes.Parser.ParseFrom(stream),
  790. "Protocol message was too large. May be malicious. " +
  791. "Use CodedInputStream.SetSizeLimit() to increase the size limit.");
  792. }
  793. }
  794. /// <returns>A serialized big message</returns>
  795. private static byte[] GenerateBigSerializedMessage()
  796. {
  797. byte[] value = new byte[16 * 1024 * 1024];
  798. TestAllTypes message = SampleMessages.CreateFullTestAllTypes();
  799. message.SingleBytes = ByteString.CopyFrom(value);
  800. return message.ToByteArray();
  801. }
  802. /// <summary>
  803. /// A MemoryStream that repeats a byte arrays' content a number of times.
  804. /// Simulates really large input without consuming loads of memory. Used above
  805. /// to test the parsing behavior when the input size exceeds 2GB or close to it.
  806. /// </summary>
  807. private class RepeatingMemoryStream: MemoryStream
  808. {
  809. private readonly byte[] bytes;
  810. private readonly int maxIterations;
  811. private int index = 0;
  812. public RepeatingMemoryStream(byte[] bytes, int maxIterations)
  813. {
  814. this.bytes = bytes;
  815. this.maxIterations = maxIterations;
  816. }
  817. public override int Read(byte[] buffer, int offset, int count)
  818. {
  819. if (bytes.Length == 0)
  820. {
  821. return 0;
  822. }
  823. int numBytesCopiedTotal = 0;
  824. while (numBytesCopiedTotal < count && index < maxIterations)
  825. {
  826. int numBytesToCopy = Math.Min(bytes.Length - (int)Position, count);
  827. Array.Copy(bytes, (int)Position, buffer, offset, numBytesToCopy);
  828. numBytesCopiedTotal += numBytesToCopy;
  829. offset += numBytesToCopy;
  830. count -= numBytesCopiedTotal;
  831. Position += numBytesToCopy;
  832. if (Position >= bytes.Length)
  833. {
  834. Position = 0;
  835. index++;
  836. }
  837. }
  838. return numBytesCopiedTotal;
  839. }
  840. }
  841. }
  842. }