TJSONProtocol.php 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807
  1. <?php
  2. /*
  3. * Licensed to the Apache Software Foundation (ASF) under one
  4. * or more contributor license agreements. See the NOTICE file
  5. * distributed with this work for additional information
  6. * regarding copyright ownership. The ASF licenses this file
  7. * to you under the Apache License, Version 2.0 (the
  8. * "License"); you may not use this file except in compliance
  9. * with the License. You may obtain a copy of the License at
  10. *
  11. * http://www.apache.org/licenses/LICENSE-2.0
  12. *
  13. * Unless required by applicable law or agreed to in writing,
  14. * software distributed under the License is distributed on an
  15. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  16. * KIND, either express or implied. See the License for the
  17. * specific language governing permissions and limitations
  18. * under the License.
  19. *
  20. * @package thrift.protocol
  21. */
  22. namespace Thrift\Protocol;
  23. use Thrift\Type\TType;
  24. use Thrift\Exception\TProtocolException;
  25. use Thrift\Protocol\JSON\BaseContext;
  26. use Thrift\Protocol\JSON\LookaheadReader;
  27. use Thrift\Protocol\JSON\PairContext;
  28. use Thrift\Protocol\JSON\ListContext;
  29. /**
  30. * JSON implementation of thrift protocol, ported from Java.
  31. */
  32. class TJSONProtocol extends TProtocol
  33. {
  34. const COMMA = ',';
  35. const COLON = ':';
  36. const LBRACE = '{';
  37. const RBRACE = '}';
  38. const LBRACKET = '[';
  39. const RBRACKET = ']';
  40. const QUOTE = '"';
  41. const BACKSLASH = '\\';
  42. const ZERO = '0';
  43. const ESCSEQ = '\\';
  44. const DOUBLEESC = '__DOUBLE_ESCAPE_SEQUENCE__';
  45. const VERSION = 1;
  46. public static $JSON_CHAR_TABLE = array(
  47. /* 0 1 2 3 4 5 6 7 8 9 A B C D E F */
  48. 0, 0, 0, 0, 0, 0, 0, 0, 'b', 't', 'n', 0, 'f', 'r', 0, 0, // 0
  49. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 1
  50. 1, 1, '"', 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 2
  51. );
  52. public static $ESCAPE_CHARS = array('"', '\\', '/', "b", "f", "n", "r", "t");
  53. public static $ESCAPE_CHAR_VALS = array(
  54. '"', '\\', '/', "\x08", "\f", "\n", "\r", "\t",
  55. );
  56. const NAME_BOOL = "tf";
  57. const NAME_BYTE = "i8";
  58. const NAME_I16 = "i16";
  59. const NAME_I32 = "i32";
  60. const NAME_I64 = "i64";
  61. const NAME_DOUBLE = "dbl";
  62. const NAME_STRUCT = "rec";
  63. const NAME_STRING = "str";
  64. const NAME_MAP = "map";
  65. const NAME_LIST = "lst";
  66. const NAME_SET = "set";
  67. private function getTypeNameForTypeID($typeID)
  68. {
  69. switch ($typeID) {
  70. case TType::BOOL:
  71. return self::NAME_BOOL;
  72. case TType::BYTE:
  73. return self::NAME_BYTE;
  74. case TType::I16:
  75. return self::NAME_I16;
  76. case TType::I32:
  77. return self::NAME_I32;
  78. case TType::I64:
  79. return self::NAME_I64;
  80. case TType::DOUBLE:
  81. return self::NAME_DOUBLE;
  82. case TType::STRING:
  83. return self::NAME_STRING;
  84. case TType::STRUCT:
  85. return self::NAME_STRUCT;
  86. case TType::MAP:
  87. return self::NAME_MAP;
  88. case TType::SET:
  89. return self::NAME_SET;
  90. case TType::LST:
  91. return self::NAME_LIST;
  92. default:
  93. throw new TProtocolException("Unrecognized type", TProtocolException::UNKNOWN);
  94. }
  95. }
  96. private function getTypeIDForTypeName($name)
  97. {
  98. $result = TType::STOP;
  99. if (strlen($name) > 1) {
  100. switch (substr($name, 0, 1)) {
  101. case 'd':
  102. $result = TType::DOUBLE;
  103. break;
  104. case 'i':
  105. switch (substr($name, 1, 1)) {
  106. case '8':
  107. $result = TType::BYTE;
  108. break;
  109. case '1':
  110. $result = TType::I16;
  111. break;
  112. case '3':
  113. $result = TType::I32;
  114. break;
  115. case '6':
  116. $result = TType::I64;
  117. break;
  118. }
  119. break;
  120. case 'l':
  121. $result = TType::LST;
  122. break;
  123. case 'm':
  124. $result = TType::MAP;
  125. break;
  126. case 'r':
  127. $result = TType::STRUCT;
  128. break;
  129. case 's':
  130. if (substr($name, 1, 1) == 't') {
  131. $result = TType::STRING;
  132. } elseif (substr($name, 1, 1) == 'e') {
  133. $result = TType::SET;
  134. }
  135. break;
  136. case 't':
  137. $result = TType::BOOL;
  138. break;
  139. }
  140. }
  141. if ($result == TType::STOP) {
  142. throw new TProtocolException("Unrecognized type", TProtocolException::INVALID_DATA);
  143. }
  144. return $result;
  145. }
  146. public $contextStack_ = array();
  147. public $context_;
  148. public $reader_;
  149. private function pushContext($c)
  150. {
  151. array_push($this->contextStack_, $this->context_);
  152. $this->context_ = $c;
  153. }
  154. private function popContext()
  155. {
  156. $this->context_ = array_pop($this->contextStack_);
  157. }
  158. public function __construct($trans)
  159. {
  160. parent::__construct($trans);
  161. $this->context_ = new BaseContext();
  162. $this->reader_ = new LookaheadReader($this);
  163. }
  164. public function reset()
  165. {
  166. $this->contextStack_ = array();
  167. $this->context_ = new BaseContext();
  168. $this->reader_ = new LookaheadReader($this);
  169. }
  170. private $tmpbuf_ = array(4);
  171. public function readJSONSyntaxChar($b)
  172. {
  173. $ch = $this->reader_->read();
  174. if (substr($ch, 0, 1) != $b) {
  175. throw new TProtocolException("Unexpected character: " . $ch, TProtocolException::INVALID_DATA);
  176. }
  177. }
  178. private function hexVal($s)
  179. {
  180. for ($i = 0; $i < strlen($s); $i++) {
  181. $ch = substr($s, $i, 1);
  182. if (!($ch >= "a" && $ch <= "f") && !($ch >= "0" && $ch <= "9")) {
  183. throw new TProtocolException("Expected hex character " . $ch, TProtocolException::INVALID_DATA);
  184. }
  185. }
  186. return hexdec($s);
  187. }
  188. private function hexChar($val)
  189. {
  190. return dechex($val);
  191. }
  192. private function hasJSONUnescapedUnicode()
  193. {
  194. if (PHP_MAJOR_VERSION > 5
  195. || (PHP_MAJOR_VERSION == 5 && PHP_MINOR_VERSION >= 4))
  196. return true;
  197. return false;
  198. }
  199. private function unescapedUnicode($str)
  200. {
  201. if ($this->hasJSONUnescapedUnicode()) {
  202. return json_encode($str, JSON_UNESCAPED_UNICODE);
  203. }
  204. $json = json_encode($str);
  205. /*
  206. * Unescaped character outside the Basic Multilingual Plane
  207. * High surrogate: 0xD800 - 0xDBFF
  208. * Low surrogate: 0xDC00 - 0xDFFF
  209. */
  210. $json = preg_replace_callback('/\\\\u(d[89ab][0-9a-f]{2})\\\\u(d[cdef][0-9a-f]{2})/i',
  211. function ($matches) {
  212. return mb_convert_encoding(pack('H*', $matches[1].$matches[2]), 'UTF-8', 'UTF-16BE');
  213. }, $json);
  214. /*
  215. * Unescaped characters within the Basic Multilingual Plane
  216. */
  217. $json = preg_replace_callback('/\\\\u([0-9a-f]{4})/i',
  218. function ($matches) {
  219. return mb_convert_encoding(pack('H*', $matches[1]), 'UTF-8', 'UTF-16BE');
  220. }, $json);
  221. return $json;
  222. }
  223. private function writeJSONString($b)
  224. {
  225. $this->context_->write();
  226. if (is_numeric($b) && $this->context_->escapeNum()) {
  227. $this->trans_->write(self::QUOTE);
  228. }
  229. $this->trans_->write($this->unescapedUnicode($b));
  230. if (is_numeric($b) && $this->context_->escapeNum()) {
  231. $this->trans_->write(self::QUOTE);
  232. }
  233. }
  234. private function writeJSONInteger($num)
  235. {
  236. $this->context_->write();
  237. if ($this->context_->escapeNum()) {
  238. $this->trans_->write(self::QUOTE);
  239. }
  240. $this->trans_->write($num);
  241. if ($this->context_->escapeNum()) {
  242. $this->trans_->write(self::QUOTE);
  243. }
  244. }
  245. private function writeJSONDouble($num)
  246. {
  247. $this->context_->write();
  248. if ($this->context_->escapeNum()) {
  249. $this->trans_->write(self::QUOTE);
  250. }
  251. $this->trans_->write(json_encode($num));
  252. if ($this->context_->escapeNum()) {
  253. $this->trans_->write(self::QUOTE);
  254. }
  255. }
  256. private function writeJSONBase64($data)
  257. {
  258. $this->context_->write();
  259. $this->trans_->write(self::QUOTE);
  260. $this->trans_->write(json_encode(base64_encode($data)));
  261. $this->trans_->write(self::QUOTE);
  262. }
  263. private function writeJSONObjectStart()
  264. {
  265. $this->context_->write();
  266. $this->trans_->write(self::LBRACE);
  267. $this->pushContext(new PairContext($this));
  268. }
  269. private function writeJSONObjectEnd()
  270. {
  271. $this->popContext();
  272. $this->trans_->write(self::RBRACE);
  273. }
  274. private function writeJSONArrayStart()
  275. {
  276. $this->context_->write();
  277. $this->trans_->write(self::LBRACKET);
  278. $this->pushContext(new ListContext($this));
  279. }
  280. private function writeJSONArrayEnd()
  281. {
  282. $this->popContext();
  283. $this->trans_->write(self::RBRACKET);
  284. }
  285. private function readJSONString($skipContext)
  286. {
  287. if (!$skipContext) {
  288. $this->context_->read();
  289. }
  290. $jsonString = '';
  291. $lastChar = null;
  292. while (true) {
  293. $ch = $this->reader_->read();
  294. $jsonString .= $ch;
  295. if ($ch == self::QUOTE &&
  296. $lastChar !== NULL &&
  297. $lastChar !== self::ESCSEQ) {
  298. break;
  299. }
  300. if ($ch == self::ESCSEQ && $lastChar == self::ESCSEQ) {
  301. $lastChar = self::DOUBLEESC;
  302. } else {
  303. $lastChar = $ch;
  304. }
  305. }
  306. return json_decode($jsonString);
  307. }
  308. private function isJSONNumeric($b)
  309. {
  310. switch ($b) {
  311. case '+':
  312. case '-':
  313. case '.':
  314. case '0':
  315. case '1':
  316. case '2':
  317. case '3':
  318. case '4':
  319. case '5':
  320. case '6':
  321. case '7':
  322. case '8':
  323. case '9':
  324. case 'E':
  325. case 'e':
  326. return true;
  327. }
  328. return false;
  329. }
  330. private function readJSONNumericChars()
  331. {
  332. $strbld = array();
  333. while (true) {
  334. $ch = $this->reader_->peek();
  335. if (!$this->isJSONNumeric($ch)) {
  336. break;
  337. }
  338. $strbld[] = $this->reader_->read();
  339. }
  340. return implode("", $strbld);
  341. }
  342. private function readJSONInteger()
  343. {
  344. $this->context_->read();
  345. if ($this->context_->escapeNum()) {
  346. $this->readJSONSyntaxChar(self::QUOTE);
  347. }
  348. $str = $this->readJSONNumericChars();
  349. if ($this->context_->escapeNum()) {
  350. $this->readJSONSyntaxChar(self::QUOTE);
  351. }
  352. if (!is_numeric($str)) {
  353. throw new TProtocolException("Invalid data in numeric: " . $str, TProtocolException::INVALID_DATA);
  354. }
  355. return intval($str);
  356. }
  357. /**
  358. * Identical to readJSONInteger but without the final cast.
  359. * Needed for proper handling of i64 on 32 bit machines. Why a
  360. * separate function? So we don't have to force the rest of the
  361. * use cases through the extra conditional.
  362. */
  363. private function readJSONIntegerAsString()
  364. {
  365. $this->context_->read();
  366. if ($this->context_->escapeNum()) {
  367. $this->readJSONSyntaxChar(self::QUOTE);
  368. }
  369. $str = $this->readJSONNumericChars();
  370. if ($this->context_->escapeNum()) {
  371. $this->readJSONSyntaxChar(self::QUOTE);
  372. }
  373. if (!is_numeric($str)) {
  374. throw new TProtocolException("Invalid data in numeric: " . $str, TProtocolException::INVALID_DATA);
  375. }
  376. return $str;
  377. }
  378. private function readJSONDouble()
  379. {
  380. $this->context_->read();
  381. if (substr($this->reader_->peek(), 0, 1) == self::QUOTE) {
  382. $arr = $this->readJSONString(true);
  383. if ($arr == "NaN") {
  384. return NAN;
  385. } elseif ($arr == "Infinity") {
  386. return INF;
  387. } elseif (!$this->context_->escapeNum()) {
  388. throw new TProtocolException("Numeric data unexpectedly quoted " . $arr,
  389. TProtocolException::INVALID_DATA);
  390. }
  391. return floatval($arr);
  392. } else {
  393. if ($this->context_->escapeNum()) {
  394. $this->readJSONSyntaxChar(self::QUOTE);
  395. }
  396. return floatval($this->readJSONNumericChars());
  397. }
  398. }
  399. private function readJSONBase64()
  400. {
  401. $arr = $this->readJSONString(false);
  402. $data = base64_decode($arr, true);
  403. if ($data === false) {
  404. throw new TProtocolException("Invalid base64 data " . $arr, TProtocolException::INVALID_DATA);
  405. }
  406. return $data;
  407. }
  408. private function readJSONObjectStart()
  409. {
  410. $this->context_->read();
  411. $this->readJSONSyntaxChar(self::LBRACE);
  412. $this->pushContext(new PairContext($this));
  413. }
  414. private function readJSONObjectEnd()
  415. {
  416. $this->readJSONSyntaxChar(self::RBRACE);
  417. $this->popContext();
  418. }
  419. private function readJSONArrayStart()
  420. {
  421. $this->context_->read();
  422. $this->readJSONSyntaxChar(self::LBRACKET);
  423. $this->pushContext(new ListContext($this));
  424. }
  425. private function readJSONArrayEnd()
  426. {
  427. $this->readJSONSyntaxChar(self::RBRACKET);
  428. $this->popContext();
  429. }
  430. /**
  431. * Writes the message header
  432. *
  433. * @param string $name Function name
  434. * @param int $type message type TMessageType::CALL or TMessageType::REPLY
  435. * @param int $seqid The sequence id of this message
  436. */
  437. public function writeMessageBegin($name, $type, $seqid)
  438. {
  439. $this->writeJSONArrayStart();
  440. $this->writeJSONInteger(self::VERSION);
  441. $this->writeJSONString($name);
  442. $this->writeJSONInteger($type);
  443. $this->writeJSONInteger($seqid);
  444. }
  445. /**
  446. * Close the message
  447. */
  448. public function writeMessageEnd()
  449. {
  450. $this->writeJSONArrayEnd();
  451. }
  452. /**
  453. * Writes a struct header.
  454. *
  455. * @param string $name Struct name
  456. * @throws TException on write error
  457. * @return int How many bytes written
  458. */
  459. public function writeStructBegin($name)
  460. {
  461. $this->writeJSONObjectStart();
  462. }
  463. /**
  464. * Close a struct.
  465. *
  466. * @throws TException on write error
  467. * @return int How many bytes written
  468. */
  469. public function writeStructEnd()
  470. {
  471. $this->writeJSONObjectEnd();
  472. }
  473. public function writeFieldBegin($fieldName, $fieldType, $fieldId)
  474. {
  475. $this->writeJSONInteger($fieldId);
  476. $this->writeJSONObjectStart();
  477. $this->writeJSONString($this->getTypeNameForTypeID($fieldType));
  478. }
  479. public function writeFieldEnd()
  480. {
  481. $this->writeJsonObjectEnd();
  482. }
  483. public function writeFieldStop()
  484. {
  485. }
  486. public function writeMapBegin($keyType, $valType, $size)
  487. {
  488. $this->writeJSONArrayStart();
  489. $this->writeJSONString($this->getTypeNameForTypeID($keyType));
  490. $this->writeJSONString($this->getTypeNameForTypeID($valType));
  491. $this->writeJSONInteger($size);
  492. $this->writeJSONObjectStart();
  493. }
  494. public function writeMapEnd()
  495. {
  496. $this->writeJSONObjectEnd();
  497. $this->writeJSONArrayEnd();
  498. }
  499. public function writeListBegin($elemType, $size)
  500. {
  501. $this->writeJSONArrayStart();
  502. $this->writeJSONString($this->getTypeNameForTypeID($elemType));
  503. $this->writeJSONInteger($size);
  504. }
  505. public function writeListEnd()
  506. {
  507. $this->writeJSONArrayEnd();
  508. }
  509. public function writeSetBegin($elemType, $size)
  510. {
  511. $this->writeJSONArrayStart();
  512. $this->writeJSONString($this->getTypeNameForTypeID($elemType));
  513. $this->writeJSONInteger($size);
  514. }
  515. public function writeSetEnd()
  516. {
  517. $this->writeJSONArrayEnd();
  518. }
  519. public function writeBool($bool)
  520. {
  521. $this->writeJSONInteger($bool ? 1 : 0);
  522. }
  523. public function writeByte($byte)
  524. {
  525. $this->writeJSONInteger($byte);
  526. }
  527. public function writeI16($i16)
  528. {
  529. $this->writeJSONInteger($i16);
  530. }
  531. public function writeI32($i32)
  532. {
  533. $this->writeJSONInteger($i32);
  534. }
  535. public function writeI64($i64)
  536. {
  537. $this->writeJSONInteger($i64);
  538. }
  539. public function writeDouble($dub)
  540. {
  541. $this->writeJSONDouble($dub);
  542. }
  543. public function writeString($str)
  544. {
  545. $this->writeJSONString($str);
  546. }
  547. /**
  548. * Reads the message header
  549. *
  550. * @param string $name Function name
  551. * @param int $type message type TMessageType::CALL or TMessageType::REPLY
  552. * @parem int $seqid The sequence id of this message
  553. */
  554. public function readMessageBegin(&$name, &$type, &$seqid)
  555. {
  556. $this->readJSONArrayStart();
  557. if ($this->readJSONInteger() != self::VERSION) {
  558. throw new TProtocolException("Message contained bad version", TProtocolException::BAD_VERSION);
  559. }
  560. $name = $this->readJSONString(false);
  561. $type = $this->readJSONInteger();
  562. $seqid = $this->readJSONInteger();
  563. return true;
  564. }
  565. /**
  566. * Read the close of message
  567. */
  568. public function readMessageEnd()
  569. {
  570. $this->readJSONArrayEnd();
  571. }
  572. public function readStructBegin(&$name)
  573. {
  574. $this->readJSONObjectStart();
  575. return 0;
  576. }
  577. public function readStructEnd()
  578. {
  579. $this->readJSONObjectEnd();
  580. }
  581. public function readFieldBegin(&$name, &$fieldType, &$fieldId)
  582. {
  583. $ch = $this->reader_->peek();
  584. $name = "";
  585. if (substr($ch, 0, 1) == self::RBRACE) {
  586. $fieldType = TType::STOP;
  587. } else {
  588. $fieldId = $this->readJSONInteger();
  589. $this->readJSONObjectStart();
  590. $fieldType = $this->getTypeIDForTypeName($this->readJSONString(false));
  591. }
  592. }
  593. public function readFieldEnd()
  594. {
  595. $this->readJSONObjectEnd();
  596. }
  597. public function readMapBegin(&$keyType, &$valType, &$size)
  598. {
  599. $this->readJSONArrayStart();
  600. $keyType = $this->getTypeIDForTypeName($this->readJSONString(false));
  601. $valType = $this->getTypeIDForTypeName($this->readJSONString(false));
  602. $size = $this->readJSONInteger();
  603. $this->readJSONObjectStart();
  604. }
  605. public function readMapEnd()
  606. {
  607. $this->readJSONObjectEnd();
  608. $this->readJSONArrayEnd();
  609. }
  610. public function readListBegin(&$elemType, &$size)
  611. {
  612. $this->readJSONArrayStart();
  613. $elemType = $this->getTypeIDForTypeName($this->readJSONString(false));
  614. $size = $this->readJSONInteger();
  615. return true;
  616. }
  617. public function readListEnd()
  618. {
  619. $this->readJSONArrayEnd();
  620. }
  621. public function readSetBegin(&$elemType, &$size)
  622. {
  623. $this->readJSONArrayStart();
  624. $elemType = $this->getTypeIDForTypeName($this->readJSONString(false));
  625. $size = $this->readJSONInteger();
  626. return true;
  627. }
  628. public function readSetEnd()
  629. {
  630. $this->readJSONArrayEnd();
  631. }
  632. public function readBool(&$bool)
  633. {
  634. $bool = $this->readJSONInteger() == 0 ? false : true;
  635. return true;
  636. }
  637. public function readByte(&$byte)
  638. {
  639. $byte = $this->readJSONInteger();
  640. return true;
  641. }
  642. public function readI16(&$i16)
  643. {
  644. $i16 = $this->readJSONInteger();
  645. return true;
  646. }
  647. public function readI32(&$i32)
  648. {
  649. $i32 = $this->readJSONInteger();
  650. return true;
  651. }
  652. public function readI64(&$i64)
  653. {
  654. if (PHP_INT_SIZE === 4) {
  655. $i64 = $this->readJSONIntegerAsString();
  656. } else {
  657. $i64 = $this->readJSONInteger();
  658. }
  659. return true;
  660. }
  661. public function readDouble(&$dub)
  662. {
  663. $dub = $this->readJSONDouble();
  664. return true;
  665. }
  666. public function readString(&$str)
  667. {
  668. $str = $this->readJSONString(false);
  669. return true;
  670. }
  671. }