CodedInputStream.cs 46 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293
  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 Google.Protobuf.Collections;
  33. using System;
  34. using System.Collections.Generic;
  35. using System.IO;
  36. namespace Google.Protobuf
  37. {
  38. /// <summary>
  39. /// Reads and decodes protocol message fields.
  40. /// </summary>
  41. /// <remarks>
  42. /// <para>
  43. /// This class is generally used by generated code to read appropriate
  44. /// primitives from the stream. It effectively encapsulates the lowest
  45. /// levels of protocol buffer format.
  46. /// </para>
  47. /// <para>
  48. /// Repeated fields and map fields are not handled by this class; use <see cref="RepeatedField{T}"/>
  49. /// and <see cref="MapField{TKey, TValue}"/> to serialize such fields.
  50. /// </para>
  51. /// </remarks>
  52. public sealed class CodedInputStream : IDisposable
  53. {
  54. /// <summary>
  55. /// Whether to leave the underlying stream open when disposing of this stream.
  56. /// This is always true when there's no stream.
  57. /// </summary>
  58. private bool leaveOpen;
  59. /// <summary>
  60. /// Buffer of data read from the stream or provided at construction time.
  61. /// </summary>
  62. private byte[] buffer;
  63. /// <summary>
  64. /// The index of the buffer at which we need to refill from the stream (if there is one).
  65. /// </summary>
  66. private int bufferSize;
  67. private int bufferSizeAfterLimit = 0;
  68. /// <summary>
  69. /// The position within the current buffer (i.e. the next byte to read)
  70. /// </summary>
  71. private int bufferPos = 0;
  72. /// <summary>
  73. /// The stream to read further input from, or null if the byte array buffer was provided
  74. /// directly on construction, with no further data available.
  75. /// </summary>
  76. private readonly Stream input;
  77. /// <summary>
  78. /// The last tag we read. 0 indicates we've read to the end of the stream
  79. /// (or haven't read anything yet).
  80. /// </summary>
  81. private uint lastTag = 0;
  82. /// <summary>
  83. /// The next tag, used to store the value read by PeekTag.
  84. /// </summary>
  85. private uint nextTag = 0;
  86. private bool hasNextTag = false;
  87. internal const int DefaultRecursionLimit = 64;
  88. internal const int DefaultSizeLimit = 64 << 20; // 64MB
  89. internal const int BufferSize = 4096;
  90. /// <summary>
  91. /// The total number of bytes read before the current buffer. The
  92. /// total bytes read up to the current position can be computed as
  93. /// totalBytesRetired + bufferPos.
  94. /// </summary>
  95. private int totalBytesRetired = 0;
  96. /// <summary>
  97. /// The absolute position of the end of the current message.
  98. /// </summary>
  99. private int currentLimit = int.MaxValue;
  100. private int recursionDepth = 0;
  101. private int recursionLimit;
  102. private int sizeLimit;
  103. #region Construction
  104. // Note that the checks are performed such that we don't end up checking obviously-valid things
  105. // like non-null references for arrays we've just created.
  106. /// <summary>
  107. /// Creates a new CodedInputStream reading data from the given byte array.
  108. /// </summary>
  109. public CodedInputStream(byte[] buffer) : this(null, ProtoPreconditions.CheckNotNull(buffer, "buffer"), 0, buffer.Length, true)
  110. {
  111. }
  112. /// <summary>
  113. /// Creates a new <see cref="CodedInputStream"/> that reads from the given byte array slice.
  114. /// </summary>
  115. public CodedInputStream(byte[] buffer, int offset, int length)
  116. : this(null, ProtoPreconditions.CheckNotNull(buffer, "buffer"), offset, offset + length, true)
  117. {
  118. if (offset < 0 || offset > buffer.Length)
  119. {
  120. throw new ArgumentOutOfRangeException("offset", "Offset must be within the buffer");
  121. }
  122. if (length < 0 || offset + length > buffer.Length)
  123. {
  124. throw new ArgumentOutOfRangeException("length", "Length must be non-negative and within the buffer");
  125. }
  126. }
  127. /// <summary>
  128. /// Creates a new <see cref="CodedInputStream"/> reading data from the given stream, which will be disposed
  129. /// when the returned object is disposed.
  130. /// </summary>
  131. /// <param name="input">The stream to read from.</param>
  132. public CodedInputStream(Stream input) : this(input, false)
  133. {
  134. }
  135. /// <summary>
  136. /// Creates a new <see cref="CodedInputStream"/> reading data from the given stream.
  137. /// </summary>
  138. /// <param name="input">The stream to read from.</param>
  139. /// <param name="leaveOpen"><c>true</c> to leave <paramref name="input"/> open when the returned
  140. /// <c cref="CodedInputStream"/> is disposed; <c>false</c> to dispose of the given stream when the
  141. /// returned object is disposed.</param>
  142. public CodedInputStream(Stream input, bool leaveOpen)
  143. : this(ProtoPreconditions.CheckNotNull(input, "input"), new byte[BufferSize], 0, 0, leaveOpen)
  144. {
  145. }
  146. /// <summary>
  147. /// Creates a new CodedInputStream reading data from the given
  148. /// stream and buffer, using the default limits.
  149. /// </summary>
  150. internal CodedInputStream(Stream input, byte[] buffer, int bufferPos, int bufferSize, bool leaveOpen)
  151. {
  152. this.input = input;
  153. this.buffer = buffer;
  154. this.bufferPos = bufferPos;
  155. this.bufferSize = bufferSize;
  156. this.sizeLimit = DefaultSizeLimit;
  157. this.recursionLimit = DefaultRecursionLimit;
  158. this.leaveOpen = leaveOpen;
  159. }
  160. public void Reset(byte[] buf, int offset, int length)
  161. {
  162. this.buffer = buf;
  163. this.bufferPos = offset;
  164. this.bufferSize = length;
  165. this.sizeLimit = DefaultSizeLimit;
  166. this.recursionLimit = DefaultRecursionLimit;
  167. this.leaveOpen = true;
  168. bufferSizeAfterLimit = 0;
  169. lastTag = 0;
  170. nextTag = 0;
  171. hasNextTag = false;
  172. totalBytesRetired = 0;
  173. currentLimit = int.MaxValue;
  174. sizeLimit = 0;
  175. recursionDepth = 0;
  176. }
  177. /// <summary>
  178. /// Creates a new CodedInputStream reading data from the given
  179. /// stream and buffer, using the specified limits.
  180. /// </summary>
  181. /// <remarks>
  182. /// This chains to the version with the default limits instead of vice versa to avoid
  183. /// having to check that the default values are valid every time.
  184. /// </remarks>
  185. internal CodedInputStream(Stream input, byte[] buffer, int bufferPos, int bufferSize, int sizeLimit, int recursionLimit, bool leaveOpen)
  186. : this(input, buffer, bufferPos, bufferSize, leaveOpen)
  187. {
  188. if (sizeLimit <= 0)
  189. {
  190. throw new ArgumentOutOfRangeException("sizeLimit", "Size limit must be positive");
  191. }
  192. if (recursionLimit <= 0)
  193. {
  194. throw new ArgumentOutOfRangeException("recursionLimit!", "Recursion limit must be positive");
  195. }
  196. this.sizeLimit = sizeLimit;
  197. this.recursionLimit = recursionLimit;
  198. }
  199. #endregion
  200. /// <summary>
  201. /// Creates a <see cref="CodedInputStream"/> with the specified size and recursion limits, reading
  202. /// from an input stream.
  203. /// </summary>
  204. /// <remarks>
  205. /// This method exists separately from the constructor to reduce the number of constructor overloads.
  206. /// It is likely to be used considerably less frequently than the constructors, as the default limits
  207. /// are suitable for most use cases.
  208. /// </remarks>
  209. /// <param name="input">The input stream to read from</param>
  210. /// <param name="sizeLimit">The total limit of data to read from the stream.</param>
  211. /// <param name="recursionLimit">The maximum recursion depth to allow while reading.</param>
  212. /// <returns>A <c>CodedInputStream</c> reading from <paramref name="input"/> with the specified size
  213. /// and recursion limits.</returns>
  214. public static CodedInputStream CreateWithLimits(Stream input, int sizeLimit, int recursionLimit)
  215. {
  216. // Note: we may want an overload accepting leaveOpen
  217. return new CodedInputStream(input, new byte[BufferSize], 0, 0, sizeLimit, recursionLimit, false);
  218. }
  219. /// <summary>
  220. /// Returns the current position in the input stream, or the position in the input buffer
  221. /// </summary>
  222. public long Position
  223. {
  224. get
  225. {
  226. if (input != null)
  227. {
  228. return input.Position - ((bufferSize + bufferSizeAfterLimit) - bufferPos);
  229. }
  230. return bufferPos;
  231. }
  232. }
  233. /// <summary>
  234. /// Returns the last tag read, or 0 if no tags have been read or we've read beyond
  235. /// the end of the stream.
  236. /// </summary>
  237. internal uint LastTag { get { return lastTag; } }
  238. /// <summary>
  239. /// Returns the size limit for this stream.
  240. /// </summary>
  241. /// <remarks>
  242. /// This limit is applied when reading from the underlying stream, as a sanity check. It is
  243. /// not applied when reading from a byte array data source without an underlying stream.
  244. /// The default value is 64MB.
  245. /// </remarks>
  246. /// <value>
  247. /// The size limit.
  248. /// </value>
  249. public int SizeLimit { get { return sizeLimit; } }
  250. /// <summary>
  251. /// Returns the recursion limit for this stream. This limit is applied whilst reading messages,
  252. /// to avoid maliciously-recursive data.
  253. /// </summary>
  254. /// <remarks>
  255. /// The default limit is 64.
  256. /// </remarks>
  257. /// <value>
  258. /// The recursion limit for this stream.
  259. /// </value>
  260. public int RecursionLimit { get { return recursionLimit; } }
  261. /// <summary>
  262. /// Disposes of this instance, potentially closing any underlying stream.
  263. /// </summary>
  264. /// <remarks>
  265. /// As there is no flushing to perform here, disposing of a <see cref="CodedInputStream"/> which
  266. /// was constructed with the <c>leaveOpen</c> option parameter set to <c>true</c> (or one which
  267. /// was constructed to read from a byte array) has no effect.
  268. /// </remarks>
  269. public void Dispose()
  270. {
  271. if (!leaveOpen)
  272. {
  273. input.Dispose();
  274. }
  275. }
  276. #region Validation
  277. /// <summary>
  278. /// Verifies that the last call to ReadTag() returned tag 0 - in other words,
  279. /// we've reached the end of the stream when we expected to.
  280. /// </summary>
  281. /// <exception cref="InvalidProtocolBufferException">The
  282. /// tag read was not the one specified</exception>
  283. internal void CheckReadEndOfStreamTag()
  284. {
  285. if (lastTag != 0)
  286. {
  287. throw InvalidProtocolBufferException.MoreDataAvailable();
  288. }
  289. }
  290. #endregion
  291. #region Reading of tags etc
  292. /// <summary>
  293. /// Peeks at the next field tag. This is like calling <see cref="ReadTag"/>, but the
  294. /// tag is not consumed. (So a subsequent call to <see cref="ReadTag"/> will return the
  295. /// same value.)
  296. /// </summary>
  297. public uint PeekTag()
  298. {
  299. if (hasNextTag)
  300. {
  301. return nextTag;
  302. }
  303. uint savedLast = lastTag;
  304. nextTag = ReadTag();
  305. hasNextTag = true;
  306. lastTag = savedLast; // Undo the side effect of ReadTag
  307. return nextTag;
  308. }
  309. /// <summary>
  310. /// Reads a field tag, returning the tag of 0 for "end of stream".
  311. /// </summary>
  312. /// <remarks>
  313. /// If this method returns 0, it doesn't necessarily mean the end of all
  314. /// the data in this CodedInputStream; it may be the end of the logical stream
  315. /// for an embedded message, for example.
  316. /// </remarks>
  317. /// <returns>The next field tag, or 0 for end of stream. (0 is never a valid tag.)</returns>
  318. public uint ReadTag()
  319. {
  320. if (hasNextTag)
  321. {
  322. lastTag = nextTag;
  323. hasNextTag = false;
  324. return lastTag;
  325. }
  326. // Optimize for the incredibly common case of having at least two bytes left in the buffer,
  327. // and those two bytes being enough to get the tag. This will be true for fields up to 4095.
  328. if (bufferPos + 2 <= bufferSize)
  329. {
  330. int tmp = buffer[bufferPos++];
  331. if (tmp < 128)
  332. {
  333. lastTag = (uint)tmp;
  334. }
  335. else
  336. {
  337. int result = tmp & 0x7f;
  338. if ((tmp = buffer[bufferPos++]) < 128)
  339. {
  340. result |= tmp << 7;
  341. lastTag = (uint) result;
  342. }
  343. else
  344. {
  345. // Nope, rewind and go the potentially slow route.
  346. bufferPos -= 2;
  347. lastTag = ReadRawVarint32();
  348. }
  349. }
  350. }
  351. else
  352. {
  353. if (IsAtEnd)
  354. {
  355. lastTag = 0;
  356. return 0; // This is the only case in which we return 0.
  357. }
  358. lastTag = ReadRawVarint32();
  359. }
  360. if (lastTag == 0)
  361. {
  362. // If we actually read zero, that's not a valid tag.
  363. throw InvalidProtocolBufferException.InvalidTag();
  364. }
  365. return lastTag;
  366. }
  367. /// <summary>
  368. /// Skips the data for the field with the tag we've just read.
  369. /// This should be called directly after <see cref="ReadTag"/>, when
  370. /// the caller wishes to skip an unknown field.
  371. /// </summary>
  372. /// <remarks>
  373. /// This method throws <see cref="InvalidProtocolBufferException"/> if the last-read tag was an end-group tag.
  374. /// If a caller wishes to skip a group, they should skip the whole group, by calling this method after reading the
  375. /// start-group tag. This behavior allows callers to call this method on any field they don't understand, correctly
  376. /// resulting in an error if an end-group tag has not been paired with an earlier start-group tag.
  377. /// </remarks>
  378. /// <exception cref="InvalidProtocolBufferException">The last tag was an end-group tag</exception>
  379. /// <exception cref="InvalidOperationException">The last read operation read to the end of the logical stream</exception>
  380. public void SkipLastField()
  381. {
  382. if (lastTag == 0)
  383. {
  384. throw new InvalidOperationException("SkipLastField cannot be called at the end of a stream");
  385. }
  386. switch (WireFormat.GetTagWireType(lastTag))
  387. {
  388. case WireFormat.WireType.StartGroup:
  389. SkipGroup(lastTag);
  390. break;
  391. case WireFormat.WireType.EndGroup:
  392. throw new InvalidProtocolBufferException("SkipLastField called on an end-group tag, indicating that the corresponding start-group was missing");
  393. case WireFormat.WireType.Fixed32:
  394. ReadFixed32();
  395. break;
  396. case WireFormat.WireType.Fixed64:
  397. ReadFixed64();
  398. break;
  399. case WireFormat.WireType.LengthDelimited:
  400. var length = ReadLength();
  401. SkipRawBytes(length);
  402. break;
  403. case WireFormat.WireType.Varint:
  404. ReadRawVarint32();
  405. break;
  406. }
  407. }
  408. private void SkipGroup(uint startGroupTag)
  409. {
  410. // Note: Currently we expect this to be the way that groups are read. We could put the recursion
  411. // depth changes into the ReadTag method instead, potentially...
  412. recursionDepth++;
  413. if (recursionDepth >= recursionLimit)
  414. {
  415. throw InvalidProtocolBufferException.RecursionLimitExceeded();
  416. }
  417. uint tag;
  418. while (true)
  419. {
  420. tag = ReadTag();
  421. if (tag == 0)
  422. {
  423. throw InvalidProtocolBufferException.TruncatedMessage();
  424. }
  425. // Can't call SkipLastField for this case- that would throw.
  426. if (WireFormat.GetTagWireType(tag) == WireFormat.WireType.EndGroup)
  427. {
  428. break;
  429. }
  430. // This recursion will allow us to handle nested groups.
  431. SkipLastField();
  432. }
  433. int startField = WireFormat.GetTagFieldNumber(startGroupTag);
  434. int endField = WireFormat.GetTagFieldNumber(tag);
  435. if (startField != endField)
  436. {
  437. throw new InvalidProtocolBufferException("Mismatched end-group tag. Started with field " + startField + "; ended with field " + endField);
  438. }
  439. recursionDepth--;
  440. }
  441. /// <summary>
  442. /// Reads a double field from the stream.
  443. /// </summary>
  444. public double ReadDouble()
  445. {
  446. return BitConverter.Int64BitsToDouble((long) ReadRawLittleEndian64());
  447. }
  448. /// <summary>
  449. /// Reads a float field from the stream.
  450. /// </summary>
  451. public float ReadFloat()
  452. {
  453. if (BitConverter.IsLittleEndian && 4 <= bufferSize - bufferPos)
  454. {
  455. float ret = BitConverter.ToSingle(buffer, bufferPos);
  456. bufferPos += 4;
  457. return ret;
  458. }
  459. else
  460. {
  461. byte[] rawBytes = ReadRawBytes(4);
  462. if (!BitConverter.IsLittleEndian)
  463. {
  464. ByteArray.Reverse(rawBytes);
  465. }
  466. return BitConverter.ToSingle(rawBytes, 0);
  467. }
  468. }
  469. /// <summary>
  470. /// Reads a uint64 field from the stream.
  471. /// </summary>
  472. public ulong ReadUInt64()
  473. {
  474. return ReadRawVarint64();
  475. }
  476. /// <summary>
  477. /// Reads an int64 field from the stream.
  478. /// </summary>
  479. public long ReadInt64()
  480. {
  481. return (long) ReadRawVarint64();
  482. }
  483. /// <summary>
  484. /// Reads an int32 field from the stream.
  485. /// </summary>
  486. public int ReadInt32()
  487. {
  488. return (int) ReadRawVarint32();
  489. }
  490. /// <summary>
  491. /// Reads a fixed64 field from the stream.
  492. /// </summary>
  493. public ulong ReadFixed64()
  494. {
  495. return ReadRawLittleEndian64();
  496. }
  497. /// <summary>
  498. /// Reads a fixed32 field from the stream.
  499. /// </summary>
  500. public uint ReadFixed32()
  501. {
  502. return ReadRawLittleEndian32();
  503. }
  504. /// <summary>
  505. /// Reads a bool field from the stream.
  506. /// </summary>
  507. public bool ReadBool()
  508. {
  509. return ReadRawVarint32() != 0;
  510. }
  511. /// <summary>
  512. /// Reads a string field from the stream.
  513. /// </summary>
  514. public string ReadString()
  515. {
  516. int length = ReadLength();
  517. // No need to read any data for an empty string.
  518. if (length == 0)
  519. {
  520. return "";
  521. }
  522. if (length <= bufferSize - bufferPos)
  523. {
  524. // Fast path: We already have the bytes in a contiguous buffer, so
  525. // just copy directly from it.
  526. String result = CodedOutputStream.Utf8Encoding.GetString(buffer, bufferPos, length);
  527. bufferPos += length;
  528. return result;
  529. }
  530. // Slow path: Build a byte array first then copy it.
  531. return CodedOutputStream.Utf8Encoding.GetString(ReadRawBytes(length), 0, length);
  532. }
  533. /// <summary>
  534. /// Reads an embedded message field value from the stream.
  535. /// </summary>
  536. public void ReadMessage(IMessage builder)
  537. {
  538. int length = ReadLength();
  539. if (recursionDepth >= recursionLimit)
  540. {
  541. throw InvalidProtocolBufferException.RecursionLimitExceeded();
  542. }
  543. int oldLimit = PushLimit(length);
  544. ++recursionDepth;
  545. builder.MergeFrom(this);
  546. CheckReadEndOfStreamTag();
  547. // Check that we've read exactly as much data as expected.
  548. if (!ReachedLimit)
  549. {
  550. throw InvalidProtocolBufferException.TruncatedMessage();
  551. }
  552. --recursionDepth;
  553. PopLimit(oldLimit);
  554. }
  555. /// <summary>
  556. /// Reads a bytes field value from the stream.
  557. /// </summary>
  558. public ByteString ReadBytes()
  559. {
  560. int length = ReadLength();
  561. if (length <= bufferSize - bufferPos && length > 0)
  562. {
  563. // Fast path: We already have the bytes in a contiguous buffer, so
  564. // just copy directly from it.
  565. ByteString result = ByteString.CopyFrom(buffer, bufferPos, length);
  566. bufferPos += length;
  567. return result;
  568. }
  569. else
  570. {
  571. // Slow path: Build a byte array and attach it to a new ByteString.
  572. return ByteString.AttachBytes(ReadRawBytes(length));
  573. }
  574. }
  575. /// <summary>
  576. /// Reads a uint32 field value from the stream.
  577. /// </summary>
  578. public uint ReadUInt32()
  579. {
  580. return ReadRawVarint32();
  581. }
  582. /// <summary>
  583. /// Reads an enum field value from the stream.
  584. /// </summary>
  585. public int ReadEnum()
  586. {
  587. // Currently just a pass-through, but it's nice to separate it logically from WriteInt32.
  588. return (int) ReadRawVarint32();
  589. }
  590. /// <summary>
  591. /// Reads an sfixed32 field value from the stream.
  592. /// </summary>
  593. public int ReadSFixed32()
  594. {
  595. return (int) ReadRawLittleEndian32();
  596. }
  597. /// <summary>
  598. /// Reads an sfixed64 field value from the stream.
  599. /// </summary>
  600. public long ReadSFixed64()
  601. {
  602. return (long) ReadRawLittleEndian64();
  603. }
  604. /// <summary>
  605. /// Reads an sint32 field value from the stream.
  606. /// </summary>
  607. public int ReadSInt32()
  608. {
  609. return DecodeZigZag32(ReadRawVarint32());
  610. }
  611. /// <summary>
  612. /// Reads an sint64 field value from the stream.
  613. /// </summary>
  614. public long ReadSInt64()
  615. {
  616. return DecodeZigZag64(ReadRawVarint64());
  617. }
  618. /// <summary>
  619. /// Reads a length for length-delimited data.
  620. /// </summary>
  621. /// <remarks>
  622. /// This is internally just reading a varint, but this method exists
  623. /// to make the calling code clearer.
  624. /// </remarks>
  625. public int ReadLength()
  626. {
  627. return (int) ReadRawVarint32();
  628. }
  629. /// <summary>
  630. /// Peeks at the next tag in the stream. If it matches <paramref name="tag"/>,
  631. /// the tag is consumed and the method returns <c>true</c>; otherwise, the
  632. /// stream is left in the original position and the method returns <c>false</c>.
  633. /// </summary>
  634. public bool MaybeConsumeTag(uint tag)
  635. {
  636. if (PeekTag() == tag)
  637. {
  638. hasNextTag = false;
  639. return true;
  640. }
  641. return false;
  642. }
  643. #endregion
  644. #region Underlying reading primitives
  645. /// <summary>
  646. /// Same code as ReadRawVarint32, but read each byte individually, checking for
  647. /// buffer overflow.
  648. /// </summary>
  649. private uint SlowReadRawVarint32()
  650. {
  651. int tmp = ReadRawByte();
  652. if (tmp < 128)
  653. {
  654. return (uint) tmp;
  655. }
  656. int result = tmp & 0x7f;
  657. if ((tmp = ReadRawByte()) < 128)
  658. {
  659. result |= tmp << 7;
  660. }
  661. else
  662. {
  663. result |= (tmp & 0x7f) << 7;
  664. if ((tmp = ReadRawByte()) < 128)
  665. {
  666. result |= tmp << 14;
  667. }
  668. else
  669. {
  670. result |= (tmp & 0x7f) << 14;
  671. if ((tmp = ReadRawByte()) < 128)
  672. {
  673. result |= tmp << 21;
  674. }
  675. else
  676. {
  677. result |= (tmp & 0x7f) << 21;
  678. result |= (tmp = ReadRawByte()) << 28;
  679. if (tmp >= 128)
  680. {
  681. // Discard upper 32 bits.
  682. for (int i = 0; i < 5; i++)
  683. {
  684. if (ReadRawByte() < 128)
  685. {
  686. return (uint) result;
  687. }
  688. }
  689. throw InvalidProtocolBufferException.MalformedVarint();
  690. }
  691. }
  692. }
  693. }
  694. return (uint) result;
  695. }
  696. /// <summary>
  697. /// Reads a raw Varint from the stream. If larger than 32 bits, discard the upper bits.
  698. /// This method is optimised for the case where we've got lots of data in the buffer.
  699. /// That means we can check the size just once, then just read directly from the buffer
  700. /// without constant rechecking of the buffer length.
  701. /// </summary>
  702. internal uint ReadRawVarint32()
  703. {
  704. if (bufferPos + 5 > bufferSize)
  705. {
  706. return SlowReadRawVarint32();
  707. }
  708. int tmp = buffer[bufferPos++];
  709. if (tmp < 128)
  710. {
  711. return (uint) tmp;
  712. }
  713. int result = tmp & 0x7f;
  714. if ((tmp = buffer[bufferPos++]) < 128)
  715. {
  716. result |= tmp << 7;
  717. }
  718. else
  719. {
  720. result |= (tmp & 0x7f) << 7;
  721. if ((tmp = buffer[bufferPos++]) < 128)
  722. {
  723. result |= tmp << 14;
  724. }
  725. else
  726. {
  727. result |= (tmp & 0x7f) << 14;
  728. if ((tmp = buffer[bufferPos++]) < 128)
  729. {
  730. result |= tmp << 21;
  731. }
  732. else
  733. {
  734. result |= (tmp & 0x7f) << 21;
  735. result |= (tmp = buffer[bufferPos++]) << 28;
  736. if (tmp >= 128)
  737. {
  738. // Discard upper 32 bits.
  739. // Note that this has to use ReadRawByte() as we only ensure we've
  740. // got at least 5 bytes at the start of the method. This lets us
  741. // use the fast path in more cases, and we rarely hit this section of code.
  742. for (int i = 0; i < 5; i++)
  743. {
  744. if (ReadRawByte() < 128)
  745. {
  746. return (uint) result;
  747. }
  748. }
  749. throw InvalidProtocolBufferException.MalformedVarint();
  750. }
  751. }
  752. }
  753. }
  754. return (uint) result;
  755. }
  756. /// <summary>
  757. /// Reads a varint from the input one byte at a time, so that it does not
  758. /// read any bytes after the end of the varint. If you simply wrapped the
  759. /// stream in a CodedInputStream and used ReadRawVarint32(Stream)
  760. /// then you would probably end up reading past the end of the varint since
  761. /// CodedInputStream buffers its input.
  762. /// </summary>
  763. /// <param name="input"></param>
  764. /// <returns></returns>
  765. internal static uint ReadRawVarint32(Stream input)
  766. {
  767. int result = 0;
  768. int offset = 0;
  769. for (; offset < 32; offset += 7)
  770. {
  771. int b = input.ReadByte();
  772. if (b == -1)
  773. {
  774. throw InvalidProtocolBufferException.TruncatedMessage();
  775. }
  776. result |= (b & 0x7f) << offset;
  777. if ((b & 0x80) == 0)
  778. {
  779. return (uint) result;
  780. }
  781. }
  782. // Keep reading up to 64 bits.
  783. for (; offset < 64; offset += 7)
  784. {
  785. int b = input.ReadByte();
  786. if (b == -1)
  787. {
  788. throw InvalidProtocolBufferException.TruncatedMessage();
  789. }
  790. if ((b & 0x80) == 0)
  791. {
  792. return (uint) result;
  793. }
  794. }
  795. throw InvalidProtocolBufferException.MalformedVarint();
  796. }
  797. /// <summary>
  798. /// Reads a raw varint from the stream.
  799. /// </summary>
  800. internal ulong ReadRawVarint64()
  801. {
  802. int shift = 0;
  803. ulong result = 0;
  804. while (shift < 64)
  805. {
  806. byte b = ReadRawByte();
  807. result |= (ulong) (b & 0x7F) << shift;
  808. if ((b & 0x80) == 0)
  809. {
  810. return result;
  811. }
  812. shift += 7;
  813. }
  814. throw InvalidProtocolBufferException.MalformedVarint();
  815. }
  816. /// <summary>
  817. /// Reads a 32-bit little-endian integer from the stream.
  818. /// </summary>
  819. internal uint ReadRawLittleEndian32()
  820. {
  821. uint b1 = ReadRawByte();
  822. uint b2 = ReadRawByte();
  823. uint b3 = ReadRawByte();
  824. uint b4 = ReadRawByte();
  825. return b1 | (b2 << 8) | (b3 << 16) | (b4 << 24);
  826. }
  827. /// <summary>
  828. /// Reads a 64-bit little-endian integer from the stream.
  829. /// </summary>
  830. internal ulong ReadRawLittleEndian64()
  831. {
  832. ulong b1 = ReadRawByte();
  833. ulong b2 = ReadRawByte();
  834. ulong b3 = ReadRawByte();
  835. ulong b4 = ReadRawByte();
  836. ulong b5 = ReadRawByte();
  837. ulong b6 = ReadRawByte();
  838. ulong b7 = ReadRawByte();
  839. ulong b8 = ReadRawByte();
  840. return b1 | (b2 << 8) | (b3 << 16) | (b4 << 24)
  841. | (b5 << 32) | (b6 << 40) | (b7 << 48) | (b8 << 56);
  842. }
  843. /// <summary>
  844. /// Decode a 32-bit value with ZigZag encoding.
  845. /// </summary>
  846. /// <remarks>
  847. /// ZigZag encodes signed integers into values that can be efficiently
  848. /// encoded with varint. (Otherwise, negative values must be
  849. /// sign-extended to 64 bits to be varint encoded, thus always taking
  850. /// 10 bytes on the wire.)
  851. /// </remarks>
  852. internal static int DecodeZigZag32(uint n)
  853. {
  854. return (int)(n >> 1) ^ -(int)(n & 1);
  855. }
  856. /// <summary>
  857. /// Decode a 32-bit value with ZigZag encoding.
  858. /// </summary>
  859. /// <remarks>
  860. /// ZigZag encodes signed integers into values that can be efficiently
  861. /// encoded with varint. (Otherwise, negative values must be
  862. /// sign-extended to 64 bits to be varint encoded, thus always taking
  863. /// 10 bytes on the wire.)
  864. /// </remarks>
  865. internal static long DecodeZigZag64(ulong n)
  866. {
  867. return (long)(n >> 1) ^ -(long)(n & 1);
  868. }
  869. #endregion
  870. #region Internal reading and buffer management
  871. /// <summary>
  872. /// Sets currentLimit to (current position) + byteLimit. This is called
  873. /// when descending into a length-delimited embedded message. The previous
  874. /// limit is returned.
  875. /// </summary>
  876. /// <returns>The old limit.</returns>
  877. internal int PushLimit(int byteLimit)
  878. {
  879. if (byteLimit < 0)
  880. {
  881. throw InvalidProtocolBufferException.NegativeSize();
  882. }
  883. byteLimit += totalBytesRetired + bufferPos;
  884. int oldLimit = currentLimit;
  885. if (byteLimit > oldLimit)
  886. {
  887. throw InvalidProtocolBufferException.TruncatedMessage();
  888. }
  889. currentLimit = byteLimit;
  890. RecomputeBufferSizeAfterLimit();
  891. return oldLimit;
  892. }
  893. private void RecomputeBufferSizeAfterLimit()
  894. {
  895. bufferSize += bufferSizeAfterLimit;
  896. int bufferEnd = totalBytesRetired + bufferSize;
  897. if (bufferEnd > currentLimit)
  898. {
  899. // Limit is in current buffer.
  900. bufferSizeAfterLimit = bufferEnd - currentLimit;
  901. bufferSize -= bufferSizeAfterLimit;
  902. }
  903. else
  904. {
  905. bufferSizeAfterLimit = 0;
  906. }
  907. }
  908. /// <summary>
  909. /// Discards the current limit, returning the previous limit.
  910. /// </summary>
  911. internal void PopLimit(int oldLimit)
  912. {
  913. currentLimit = oldLimit;
  914. RecomputeBufferSizeAfterLimit();
  915. }
  916. /// <summary>
  917. /// Returns whether or not all the data before the limit has been read.
  918. /// </summary>
  919. /// <returns></returns>
  920. internal bool ReachedLimit
  921. {
  922. get
  923. {
  924. if (currentLimit == int.MaxValue)
  925. {
  926. return false;
  927. }
  928. int currentAbsolutePosition = totalBytesRetired + bufferPos;
  929. return currentAbsolutePosition >= currentLimit;
  930. }
  931. }
  932. /// <summary>
  933. /// Returns true if the stream has reached the end of the input. This is the
  934. /// case if either the end of the underlying input source has been reached or
  935. /// the stream has reached a limit created using PushLimit.
  936. /// </summary>
  937. public bool IsAtEnd
  938. {
  939. get { return bufferPos == bufferSize && !RefillBuffer(false); }
  940. }
  941. /// <summary>
  942. /// Called when buffer is empty to read more bytes from the
  943. /// input. If <paramref name="mustSucceed"/> is true, RefillBuffer() gurantees that
  944. /// either there will be at least one byte in the buffer when it returns
  945. /// or it will throw an exception. If <paramref name="mustSucceed"/> is false,
  946. /// RefillBuffer() returns false if no more bytes were available.
  947. /// </summary>
  948. /// <param name="mustSucceed"></param>
  949. /// <returns></returns>
  950. private bool RefillBuffer(bool mustSucceed)
  951. {
  952. if (bufferPos < bufferSize)
  953. {
  954. throw new InvalidOperationException("RefillBuffer() called when buffer wasn't empty.");
  955. }
  956. if (totalBytesRetired + bufferSize == currentLimit)
  957. {
  958. // Oops, we hit a limit.
  959. if (mustSucceed)
  960. {
  961. throw InvalidProtocolBufferException.TruncatedMessage();
  962. }
  963. else
  964. {
  965. return false;
  966. }
  967. }
  968. totalBytesRetired += bufferSize;
  969. bufferPos = 0;
  970. bufferSize = (input == null) ? 0 : input.Read(buffer, 0, buffer.Length);
  971. if (bufferSize < 0)
  972. {
  973. throw new InvalidOperationException("Stream.Read returned a negative count");
  974. }
  975. if (bufferSize == 0)
  976. {
  977. if (mustSucceed)
  978. {
  979. throw InvalidProtocolBufferException.TruncatedMessage();
  980. }
  981. else
  982. {
  983. return false;
  984. }
  985. }
  986. else
  987. {
  988. RecomputeBufferSizeAfterLimit();
  989. int totalBytesRead =
  990. totalBytesRetired + bufferSize + bufferSizeAfterLimit;
  991. if (totalBytesRead > sizeLimit || totalBytesRead < 0)
  992. {
  993. throw InvalidProtocolBufferException.SizeLimitExceeded();
  994. }
  995. return true;
  996. }
  997. }
  998. /// <summary>
  999. /// Read one byte from the input.
  1000. /// </summary>
  1001. /// <exception cref="InvalidProtocolBufferException">
  1002. /// the end of the stream or the current limit was reached
  1003. /// </exception>
  1004. internal byte ReadRawByte()
  1005. {
  1006. if (bufferPos == bufferSize)
  1007. {
  1008. RefillBuffer(true);
  1009. }
  1010. return buffer[bufferPos++];
  1011. }
  1012. /// <summary>
  1013. /// Reads a fixed size of bytes from the input.
  1014. /// </summary>
  1015. /// <exception cref="InvalidProtocolBufferException">
  1016. /// the end of the stream or the current limit was reached
  1017. /// </exception>
  1018. internal byte[] ReadRawBytes(int size)
  1019. {
  1020. if (size < 0)
  1021. {
  1022. throw InvalidProtocolBufferException.NegativeSize();
  1023. }
  1024. if (totalBytesRetired + bufferPos + size > currentLimit)
  1025. {
  1026. // Read to the end of the stream (up to the current limit) anyway.
  1027. SkipRawBytes(currentLimit - totalBytesRetired - bufferPos);
  1028. // Then fail.
  1029. throw InvalidProtocolBufferException.TruncatedMessage();
  1030. }
  1031. if (size <= bufferSize - bufferPos)
  1032. {
  1033. // We have all the bytes we need already.
  1034. byte[] bytes = new byte[size];
  1035. ByteArray.Copy(buffer, bufferPos, bytes, 0, size);
  1036. bufferPos += size;
  1037. return bytes;
  1038. }
  1039. else if (size < buffer.Length)
  1040. {
  1041. // Reading more bytes than are in the buffer, but not an excessive number
  1042. // of bytes. We can safely allocate the resulting array ahead of time.
  1043. // First copy what we have.
  1044. byte[] bytes = new byte[size];
  1045. int pos = bufferSize - bufferPos;
  1046. ByteArray.Copy(buffer, bufferPos, bytes, 0, pos);
  1047. bufferPos = bufferSize;
  1048. // We want to use RefillBuffer() and then copy from the buffer into our
  1049. // byte array rather than reading directly into our byte array because
  1050. // the input may be unbuffered.
  1051. RefillBuffer(true);
  1052. while (size - pos > bufferSize)
  1053. {
  1054. Buffer.BlockCopy(buffer, 0, bytes, pos, bufferSize);
  1055. pos += bufferSize;
  1056. bufferPos = bufferSize;
  1057. RefillBuffer(true);
  1058. }
  1059. ByteArray.Copy(buffer, 0, bytes, pos, size - pos);
  1060. bufferPos = size - pos;
  1061. return bytes;
  1062. }
  1063. else
  1064. {
  1065. // The size is very large. For security reasons, we can't allocate the
  1066. // entire byte array yet. The size comes directly from the input, so a
  1067. // maliciously-crafted message could provide a bogus very large size in
  1068. // order to trick the app into allocating a lot of memory. We avoid this
  1069. // by allocating and reading only a small chunk at a time, so that the
  1070. // malicious message must actually *be* extremely large to cause
  1071. // problems. Meanwhile, we limit the allowed size of a message elsewhere.
  1072. // Remember the buffer markers since we'll have to copy the bytes out of
  1073. // it later.
  1074. int originalBufferPos = bufferPos;
  1075. int originalBufferSize = bufferSize;
  1076. // Mark the current buffer consumed.
  1077. totalBytesRetired += bufferSize;
  1078. bufferPos = 0;
  1079. bufferSize = 0;
  1080. // Read all the rest of the bytes we need.
  1081. int sizeLeft = size - (originalBufferSize - originalBufferPos);
  1082. List<byte[]> chunks = new List<byte[]>();
  1083. while (sizeLeft > 0)
  1084. {
  1085. byte[] chunk = new byte[Math.Min(sizeLeft, buffer.Length)];
  1086. int pos = 0;
  1087. while (pos < chunk.Length)
  1088. {
  1089. int n = (input == null) ? -1 : input.Read(chunk, pos, chunk.Length - pos);
  1090. if (n <= 0)
  1091. {
  1092. throw InvalidProtocolBufferException.TruncatedMessage();
  1093. }
  1094. totalBytesRetired += n;
  1095. pos += n;
  1096. }
  1097. sizeLeft -= chunk.Length;
  1098. chunks.Add(chunk);
  1099. }
  1100. // OK, got everything. Now concatenate it all into one buffer.
  1101. byte[] bytes = new byte[size];
  1102. // Start by copying the leftover bytes from this.buffer.
  1103. int newPos = originalBufferSize - originalBufferPos;
  1104. ByteArray.Copy(buffer, originalBufferPos, bytes, 0, newPos);
  1105. // And now all the chunks.
  1106. foreach (byte[] chunk in chunks)
  1107. {
  1108. Buffer.BlockCopy(chunk, 0, bytes, newPos, chunk.Length);
  1109. newPos += chunk.Length;
  1110. }
  1111. // Done.
  1112. return bytes;
  1113. }
  1114. }
  1115. /// <summary>
  1116. /// Reads and discards <paramref name="size"/> bytes.
  1117. /// </summary>
  1118. /// <exception cref="InvalidProtocolBufferException">the end of the stream
  1119. /// or the current limit was reached</exception>
  1120. private void SkipRawBytes(int size)
  1121. {
  1122. if (size < 0)
  1123. {
  1124. throw InvalidProtocolBufferException.NegativeSize();
  1125. }
  1126. if (totalBytesRetired + bufferPos + size > currentLimit)
  1127. {
  1128. // Read to the end of the stream anyway.
  1129. SkipRawBytes(currentLimit - totalBytesRetired - bufferPos);
  1130. // Then fail.
  1131. throw InvalidProtocolBufferException.TruncatedMessage();
  1132. }
  1133. if (size <= bufferSize - bufferPos)
  1134. {
  1135. // We have all the bytes we need already.
  1136. bufferPos += size;
  1137. }
  1138. else
  1139. {
  1140. // Skipping more bytes than are in the buffer. First skip what we have.
  1141. int pos = bufferSize - bufferPos;
  1142. // ROK 5/7/2013 Issue #54: should retire all bytes in buffer (bufferSize)
  1143. // totalBytesRetired += pos;
  1144. totalBytesRetired += bufferSize;
  1145. bufferPos = 0;
  1146. bufferSize = 0;
  1147. // Then skip directly from the InputStream for the rest.
  1148. if (pos < size)
  1149. {
  1150. if (input == null)
  1151. {
  1152. throw InvalidProtocolBufferException.TruncatedMessage();
  1153. }
  1154. SkipImpl(size - pos);
  1155. totalBytesRetired += size - pos;
  1156. }
  1157. }
  1158. }
  1159. /// <summary>
  1160. /// Abstraction of skipping to cope with streams which can't really skip.
  1161. /// </summary>
  1162. private void SkipImpl(int amountToSkip)
  1163. {
  1164. if (input.CanSeek)
  1165. {
  1166. long previousPosition = input.Position;
  1167. input.Position += amountToSkip;
  1168. if (input.Position != previousPosition + amountToSkip)
  1169. {
  1170. throw InvalidProtocolBufferException.TruncatedMessage();
  1171. }
  1172. }
  1173. else
  1174. {
  1175. byte[] skipBuffer = new byte[Math.Min(1024, amountToSkip)];
  1176. while (amountToSkip > 0)
  1177. {
  1178. int bytesRead = input.Read(skipBuffer, 0, Math.Min(skipBuffer.Length, amountToSkip));
  1179. if (bytesRead <= 0)
  1180. {
  1181. throw InvalidProtocolBufferException.TruncatedMessage();
  1182. }
  1183. amountToSkip -= bytesRead;
  1184. }
  1185. }
  1186. }
  1187. #endregion
  1188. }
  1189. }