InputStream.php 11 KB

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