You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

Responder.php 9.9KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379
  1. <?php
  2. /**
  3. * Hoa
  4. *
  5. *
  6. * @license
  7. *
  8. * New BSD License
  9. *
  10. * Copyright © 2007-2017, Hoa community. All rights reserved.
  11. *
  12. * Redistribution and use in source and binary forms, with or without
  13. * modification, are permitted provided that the following conditions are met:
  14. * * Redistributions of source code must retain the above copyright
  15. * notice, this list of conditions and the following disclaimer.
  16. * * Redistributions in binary form must reproduce the above copyright
  17. * notice, this list of conditions and the following disclaimer in the
  18. * documentation and/or other materials provided with the distribution.
  19. * * Neither the name of the Hoa nor the names of its contributors may be
  20. * used to endorse or promote products derived from this software without
  21. * specific prior written permission.
  22. *
  23. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  24. * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  25. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  26. * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS AND CONTRIBUTORS BE
  27. * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
  28. * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
  29. * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
  30. * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
  31. * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  32. * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
  33. * POSSIBILITY OF SUCH DAMAGE.
  34. */
  35. namespace Hoa\Fastcgi;
  36. use Hoa\Socket;
  37. /**
  38. * Class \Hoa\Fastcgi\Responder.
  39. *
  40. * A FastCGI client with a responder role.
  41. * Inspired by PHP SAPI code: php://sapi/cgi/fastcgi.*.
  42. *
  43. * @copyright Copyright © 2007-2017 Hoa community
  44. * @license New BSD License
  45. */
  46. class Responder extends Connection
  47. {
  48. /**
  49. * Request: begin.
  50. *
  51. * @const int
  52. */
  53. const REQUEST_BEGIN = 1;
  54. /**
  55. * Request: abord.
  56. *
  57. * @const int
  58. */
  59. const REQUEST_ABORD = 2;
  60. /**
  61. * Request: end.
  62. *
  63. * @const int
  64. */
  65. const REQUEST_END = 3;
  66. /**
  67. * Request: parameters.
  68. *
  69. * @const int
  70. */
  71. const REQUEST_PARAMETERS = 4;
  72. /**
  73. * Stream: stdin.
  74. *
  75. * @const int
  76. */
  77. const STREAM_STDIN = 5;
  78. /**
  79. * Stream: stdout.
  80. *
  81. * @const int
  82. */
  83. const STREAM_STDOUT = 6;
  84. /**
  85. * Stream: stderr.
  86. *
  87. * @const int
  88. */
  89. const STREAM_STDERR = 7;
  90. /**
  91. * Request status: normal en of request.
  92. *
  93. * @const int
  94. */
  95. const STATUS_COMPLETE = 0;
  96. /**
  97. * Request status: rejecting a new request; this happens when a Web server
  98. * sends concurrent requests over one connection to an application that is
  99. * designed to process one request at a time per connection.
  100. *
  101. * @const int
  102. */
  103. const STATUS_CANNOT_MULTIPLEX = 1;
  104. /**
  105. * Request status: rejecting a new request; this happens when the
  106. * application runs out of some resource, e.g. database connections.
  107. *
  108. * @const int
  109. */
  110. const STATUS_OVERLOADED = 2;
  111. /**
  112. * Request status: rejecting a new request; this happens when the Web server
  113. * has specificied a role that is unknown to the application.
  114. *
  115. * @const int
  116. */
  117. const STATUS_UNKNOWN_ROLE = 3;
  118. /**
  119. * Client socket connection.
  120. *
  121. * @var \Hoa\Socket\Client
  122. */
  123. protected $_client = null;
  124. /**
  125. * Response's output.
  126. *
  127. * @var string
  128. */
  129. protected $_responseOutput = null;
  130. /**
  131. * Response's error.
  132. *
  133. * @var string
  134. */
  135. protected $_responseError = null;
  136. /**
  137. * Response's headers.
  138. *
  139. * @var array
  140. */
  141. protected $_responseHeaders = [];
  142. /**
  143. * Constructor.
  144. *
  145. * @param \Hoa\Socket\Client $client Client connection.
  146. */
  147. public function __construct(Socket\Client $client)
  148. {
  149. $this->setClient($client);
  150. return;
  151. }
  152. /**
  153. * Send data on a FastCGI.
  154. *
  155. * @param array $headers Headers.
  156. * @param string $content Content (e.g. key=value for POST).
  157. * @return string
  158. * @throws \Hoa\Socket\Exception
  159. * @throws \Hoa\Fastcgi\Exception
  160. * @throws \Hoa\Fastcgi\Exception\CannotMultiplex
  161. * @throws \Hoa\Fastcgi\Exception\Overloaded
  162. * @throws \Hoa\Fastcgi\Exception\UnknownRole
  163. * @throws \Hoa\Fastcgi\Exception\UnknownStatus
  164. */
  165. public function send(array $headers, $content = null)
  166. {
  167. $this->_responseOutput = null;
  168. $this->_responseError = null;
  169. $this->_responseHeaders = [];
  170. $client = $this->getClient();
  171. $client->connect();
  172. $client->setStreamBlocking(true);
  173. $parameters = null;
  174. $responseOutput = null;
  175. $request = $this->pack(
  176. self::REQUEST_BEGIN,
  177. // ┌───────────────────┐
  178. // │ “I'm a responder” │
  179. // └─────────⌵─────────┘
  180. chr(0) . chr(1) . chr((int) $client->isPersistent()) .
  181. chr(0) . chr(0) . chr(0) . chr(0) . chr(0)
  182. );
  183. $parameters .= $this->packPairs($headers);
  184. if (null !== $parameters) {
  185. $request .= $this->pack(self::REQUEST_PARAMETERS, $parameters);
  186. }
  187. $request .= $this->pack(self::REQUEST_PARAMETERS, '');
  188. if (null !== $content) {
  189. // The maximum length of each record is 65535 bytes.
  190. // Pack multiple records if the length is larger than the
  191. // 65535 bytes.
  192. foreach (str_split($content, 65535) as $chunk) {
  193. $request .= $this->pack(self::STREAM_STDIN, $chunk);
  194. }
  195. }
  196. $request .= $this->pack(self::STREAM_STDIN, '');
  197. $client->writeAll($request);
  198. $handle = null;
  199. do {
  200. if (false === $handle = $this->readPack()) {
  201. throw new Exception(
  202. 'Bad request (not a well-formed FastCGI request).',
  203. 0
  204. );
  205. }
  206. if (self::STREAM_STDOUT === $handle[parent::HEADER_TYPE]) {
  207. $responseOutput .= $handle[parent::HEADER_CONTENT];
  208. } elseif (self::STREAM_STDERR === $handle[parent::HEADER_TYPE]) {
  209. $this->_responseError .= $handle[parent::HEADER_CONTENT];
  210. }
  211. } while (self::REQUEST_END !== $handle[parent::HEADER_TYPE]);
  212. $client->disconnect();
  213. $status = ord($handle[parent::HEADER_CONTENT][4]);
  214. switch ($status) {
  215. case self::STATUS_CANNOT_MULTIPLEX:
  216. throw new Exception\CannotMultiplex(
  217. 'Application %s that you are trying to reach does not ' .
  218. 'support multiplexing.',
  219. 1,
  220. $this->getClient()->getSocket()->__toString()
  221. );
  222. break;
  223. case self::STATUS_OVERLOADED:
  224. throw new Exception\Overloaded(
  225. 'Application %s is too busy and rejects your request.',
  226. 2,
  227. $this->getClient()->getSocket()->__toString()
  228. );
  229. break;
  230. case self::STATUS_UNKNOWN_ROLE:
  231. throw new Exception\UnknownRole(
  232. 'Server for the application %s returns an unknown role.',
  233. 3,
  234. $this->getClient()->getSocket()->__toString()
  235. );
  236. break;
  237. case self::STATUS_COMPLETE:
  238. break;
  239. default:
  240. throw new Exception\UnknownStatus(
  241. 'Server for the application %s returns an unknown status: %d.',
  242. 4,
  243. [
  244. $this->getClient()->getSocket()->__toString(),
  245. $status
  246. ]
  247. );
  248. }
  249. $pos = strpos($responseOutput, "\r\n\r\n");
  250. $this->buildResponseHeaders(substr($responseOutput, 0, $pos));
  251. return $this->_responseOutput = substr($responseOutput, $pos + 4);
  252. }
  253. /**
  254. * Build the response header array.
  255. *
  256. * @param string $headers The response header string
  257. * @return void
  258. */
  259. protected function buildResponseHeaders($headers)
  260. {
  261. foreach (explode("\r\n", $headers) as $header) {
  262. $semicolon = strpos($header, ':');
  263. $this->_responseHeaders[strtolower(trim(substr($header, 0, $semicolon)))]
  264. = trim(substr($header, $semicolon + 1));
  265. }
  266. }
  267. /**
  268. * Get response content.
  269. *
  270. * @return ?string
  271. */
  272. public function getResponseContent()
  273. {
  274. return $this->_responseOutput;
  275. }
  276. /**
  277. * Get response error if any.
  278. *
  279. * @return ?string
  280. */
  281. public function getResponseError()
  282. {
  283. return $this->_responseError;
  284. }
  285. /**
  286. * Get response headers.
  287. *
  288. * @return array
  289. */
  290. public function getResponseHeaders()
  291. {
  292. return $this->_responseHeaders;
  293. }
  294. /**
  295. * Read data.
  296. *
  297. * @param int $length Length of data to read.
  298. * @return string
  299. */
  300. protected function read($length)
  301. {
  302. return $this->getClient()->read($length);
  303. }
  304. /**
  305. * Set client.
  306. *
  307. * @param \Hoa\Socket\Client $client Client.
  308. * @return \Hoa\Socket\Client
  309. */
  310. public function setClient(Socket\Client $client)
  311. {
  312. $old = $this->_client;
  313. $this->_client = $client;
  314. return $old;
  315. }
  316. /**
  317. * Get client.
  318. *
  319. * @return \Hoa\Socket\Client
  320. */
  321. public function getClient()
  322. {
  323. return $this->_client;
  324. }
  325. }