CodedInputStream.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378
  1. <?php
  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. namespace Google\Protobuf\Internal;
  32. use Google\Protobuf\Internal\Uint64;
  33. class CodedInputStream
  34. {
  35. private $buffer;
  36. private $buffer_size_after_limit;
  37. private $buffer_end;
  38. private $current;
  39. private $current_limit;
  40. private $legitimate_message_end;
  41. private $recursion_budget;
  42. private $recursion_limit;
  43. private $total_bytes_limit;
  44. private $total_bytes_read;
  45. const MAX_VARINT_BYTES = 10;
  46. const DEFAULT_RECURSION_LIMIT = 100;
  47. const DEFAULT_TOTAL_BYTES_LIMIT = 33554432; // 32 << 20, 32MB
  48. public function __construct($buffer)
  49. {
  50. $start = 0;
  51. $end = strlen($buffer);
  52. $this->buffer = $buffer;
  53. $this->buffer_size_after_limit = 0;
  54. $this->buffer_end = $end;
  55. $this->current = $start;
  56. $this->current_limit = $end;
  57. $this->legitimate_message_end = false;
  58. $this->recursion_budget = self::DEFAULT_RECURSION_LIMIT;
  59. $this->recursion_limit = self::DEFAULT_RECURSION_LIMIT;
  60. $this->total_bytes_limit = self::DEFAULT_TOTAL_BYTES_LIMIT;
  61. $this->total_bytes_read = $end - $start;
  62. }
  63. private function advance($amount)
  64. {
  65. $this->current += $amount;
  66. }
  67. public function bufferSize()
  68. {
  69. return $this->buffer_end - $this->current;
  70. }
  71. public function current()
  72. {
  73. return $this->total_bytes_read -
  74. ($this->buffer_end - $this->current +
  75. $this->buffer_size_after_limit);
  76. }
  77. public function substr($start, $end)
  78. {
  79. return substr($this->buffer, $start, $end - $start);
  80. }
  81. private function recomputeBufferLimits()
  82. {
  83. $this->buffer_end += $this->buffer_size_after_limit;
  84. $closest_limit = min($this->current_limit, $this->total_bytes_limit);
  85. if ($closest_limit < $this->total_bytes_read) {
  86. // The limit position is in the current buffer. We must adjust the
  87. // buffer size accordingly.
  88. $this->buffer_size_after_limit = $this->total_bytes_read -
  89. $closest_limit;
  90. $this->buffer_end -= $this->buffer_size_after_limit;
  91. } else {
  92. $this->buffer_size_after_limit = 0;
  93. }
  94. }
  95. private function consumedEntireMessage()
  96. {
  97. return $this->legitimate_message_end;
  98. }
  99. /**
  100. * Read uint32 into $var. Advance buffer with consumed bytes. If the
  101. * contained varint is larger than 32 bits, discard the high order bits.
  102. * @param $var.
  103. */
  104. public function readVarint32(&$var)
  105. {
  106. if (!$this->readVarint64($var)) {
  107. return false;
  108. }
  109. if (PHP_INT_SIZE == 4) {
  110. $var = bcmod($var, 4294967296);
  111. } else {
  112. $var &= 0xFFFFFFFF;
  113. }
  114. // Convert large uint32 to int32.
  115. if ($var > 0x7FFFFFFF) {
  116. if (PHP_INT_SIZE === 8) {
  117. $var = $var | (0xFFFFFFFF << 32);
  118. } else {
  119. $var = bcsub($var, 4294967296);
  120. }
  121. }
  122. $var = intval($var);
  123. return true;
  124. }
  125. /**
  126. * Read Uint64 into $var. Advance buffer with consumed bytes.
  127. * @param $var.
  128. */
  129. public function readVarint64(&$var)
  130. {
  131. $count = 0;
  132. if (PHP_INT_SIZE == 4) {
  133. $high = 0;
  134. $low = 0;
  135. $b = 0;
  136. do {
  137. if ($this->current === $this->buffer_end) {
  138. return false;
  139. }
  140. if ($count === self::MAX_VARINT_BYTES) {
  141. return false;
  142. }
  143. $b = ord($this->buffer[$this->current]);
  144. $bits = 7 * $count;
  145. if ($bits >= 32) {
  146. $high |= (($b & 0x7F) << ($bits - 32));
  147. } else if ($bits > 25){
  148. // $bits is 28 in this case.
  149. $low |= (($b & 0x7F) << 28);
  150. $high = ($b & 0x7F) >> 4;
  151. } else {
  152. $low |= (($b & 0x7F) << $bits);
  153. }
  154. $this->advance(1);
  155. $count += 1;
  156. } while ($b & 0x80);
  157. $var = GPBUtil::combineInt32ToInt64($high, $low);
  158. if (bccomp($var, 0) < 0) {
  159. $var = bcadd($var, "18446744073709551616");
  160. }
  161. } else {
  162. $result = 0;
  163. $shift = 0;
  164. do {
  165. if ($this->current === $this->buffer_end) {
  166. return false;
  167. }
  168. if ($count === self::MAX_VARINT_BYTES) {
  169. return false;
  170. }
  171. $byte = ord($this->buffer[$this->current]);
  172. $result |= ($byte & 0x7f) << $shift;
  173. $shift += 7;
  174. $this->advance(1);
  175. $count += 1;
  176. } while ($byte > 0x7f);
  177. $var = $result;
  178. }
  179. return true;
  180. }
  181. /**
  182. * Read int into $var. If the result is larger than the largest integer, $var
  183. * will be -1. Advance buffer with consumed bytes.
  184. * @param $var.
  185. */
  186. public function readVarintSizeAsInt(&$var)
  187. {
  188. if (!$this->readVarint64($var)) {
  189. return false;
  190. }
  191. $var = (int)$var;
  192. return true;
  193. }
  194. /**
  195. * Read 32-bit unsiged integer to $var. If the buffer has less than 4 bytes,
  196. * return false. Advance buffer with consumed bytes.
  197. * @param $var.
  198. */
  199. public function readLittleEndian32(&$var)
  200. {
  201. $data = null;
  202. if (!$this->readRaw(4, $data)) {
  203. return false;
  204. }
  205. $var = unpack('V', $data);
  206. $var = $var[1];
  207. return true;
  208. }
  209. /**
  210. * Read 64-bit unsiged integer to $var. If the buffer has less than 8 bytes,
  211. * return false. Advance buffer with consumed bytes.
  212. * @param $var.
  213. */
  214. public function readLittleEndian64(&$var)
  215. {
  216. $data = null;
  217. if (!$this->readRaw(4, $data)) {
  218. return false;
  219. }
  220. $low = unpack('V', $data)[1];
  221. if (!$this->readRaw(4, $data)) {
  222. return false;
  223. }
  224. $high = unpack('V', $data)[1];
  225. if (PHP_INT_SIZE == 4) {
  226. $var = GPBUtil::combineInt32ToInt64($high, $low);
  227. } else {
  228. $var = ($high << 32) | $low;
  229. }
  230. return true;
  231. }
  232. /**
  233. * Read tag into $var. Advance buffer with consumed bytes.
  234. * @param $var.
  235. */
  236. public function readTag()
  237. {
  238. if ($this->current === $this->buffer_end) {
  239. // Make sure that it failed due to EOF, not because we hit
  240. // total_bytes_limit, which, unlike normal limits, is not a valid
  241. // place to end a message.
  242. $current_position = $this->total_bytes_read -
  243. $this->buffer_size_after_limit;
  244. if ($current_position >= $this->total_bytes_limit) {
  245. // Hit total_bytes_limit_. But if we also hit the normal limit,
  246. // we're still OK.
  247. $this->legitimate_message_end =
  248. ($this->current_limit === $this->total_bytes_limit);
  249. } else {
  250. $this->legitimate_message_end = true;
  251. }
  252. return 0;
  253. }
  254. $result = 0;
  255. // The larget tag is 2^29 - 1, which can be represented by int32.
  256. $success = $this->readVarint32($result);
  257. if ($success) {
  258. return $result;
  259. } else {
  260. return 0;
  261. }
  262. }
  263. public function readRaw($size, &$buffer)
  264. {
  265. $current_buffer_size = 0;
  266. if ($this->bufferSize() < $size) {
  267. return false;
  268. }
  269. $buffer = substr($this->buffer, $this->current, $size);
  270. $this->advance($size);
  271. return true;
  272. }
  273. /* Places a limit on the number of bytes that the stream may read, starting
  274. * from the current position. Once the stream hits this limit, it will act
  275. * like the end of the input has been reached until popLimit() is called.
  276. *
  277. * As the names imply, the stream conceptually has a stack of limits. The
  278. * shortest limit on the stack is always enforced, even if it is not the top
  279. * limit.
  280. *
  281. * The value returned by pushLimit() is opaque to the caller, and must be
  282. * passed unchanged to the corresponding call to popLimit().
  283. *
  284. * @param integer $byte_limit
  285. * @throws \Exception Fail to push limit.
  286. */
  287. public function pushLimit($byte_limit)
  288. {
  289. // Current position relative to the beginning of the stream.
  290. $current_position = $this->current();
  291. $old_limit = $this->current_limit;
  292. // security: byte_limit is possibly evil, so check for negative values
  293. // and overflow.
  294. if ($byte_limit >= 0 &&
  295. $byte_limit <= PHP_INT_MAX - $current_position &&
  296. $byte_limit <= $this->current_limit - $current_position) {
  297. $this->current_limit = $current_position + $byte_limit;
  298. $this->recomputeBufferLimits();
  299. } else {
  300. throw new GPBDecodeException("Fail to push limit.");
  301. }
  302. return $old_limit;
  303. }
  304. /* The limit passed in is actually the *old* limit, which we returned from
  305. * PushLimit().
  306. *
  307. * @param integer $byte_limit
  308. */
  309. public function popLimit($byte_limit)
  310. {
  311. $this->current_limit = $byte_limit;
  312. $this->recomputeBufferLimits();
  313. // We may no longer be at a legitimate message end. ReadTag() needs to
  314. // be called again to find out.
  315. $this->legitimate_message_end = false;
  316. }
  317. public function incrementRecursionDepthAndPushLimit(
  318. $byte_limit, &$old_limit, &$recursion_budget)
  319. {
  320. $old_limit = $this->pushLimit($byte_limit);
  321. $recursion_limit = --$this->recursion_limit;
  322. }
  323. public function decrementRecursionDepthAndPopLimit($byte_limit)
  324. {
  325. $result = $this->consumedEntireMessage();
  326. $this->popLimit($byte_limit);
  327. ++$this->recursion_budget;
  328. return $result;
  329. }
  330. public function bytesUntilLimit()
  331. {
  332. if ($this->current_limit === PHP_INT_MAX) {
  333. return -1;
  334. }
  335. return $this->current_limit - $this->current;
  336. }
  337. }