StreamConnection.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386
  1. <?php
  2. /*
  3. * This file is part of the Predis package.
  4. *
  5. * (c) Daniele Alessandri <suppakilla@gmail.com>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Predis\Connection;
  11. use Predis\Command\CommandInterface;
  12. use Predis\Response\Error as ErrorResponse;
  13. use Predis\Response\Status as StatusResponse;
  14. /**
  15. * Standard connection to Redis servers implemented on top of PHP's streams.
  16. * The connection parameters supported by this class are:.
  17. *
  18. * - scheme: it can be either 'redis', 'tcp', 'rediss', 'tls' or 'unix'.
  19. * - host: hostname or IP address of the server.
  20. * - port: TCP port of the server.
  21. * - path: path of a UNIX domain socket when scheme is 'unix'.
  22. * - timeout: timeout to perform the connection (default is 5 seconds).
  23. * - read_write_timeout: timeout of read / write operations.
  24. * - async_connect: performs the connection asynchronously.
  25. * - tcp_nodelay: enables or disables Nagle's algorithm for coalescing.
  26. * - persistent: the connection is left intact after a GC collection.
  27. * - ssl: context options array (see http://php.net/manual/en/context.ssl.php)
  28. *
  29. * @author Daniele Alessandri <suppakilla@gmail.com>
  30. */
  31. class StreamConnection extends AbstractConnection
  32. {
  33. /**
  34. * Disconnects from the server and destroys the underlying resource when the
  35. * garbage collector kicks in only if the connection has not been marked as
  36. * persistent.
  37. */
  38. public function __destruct()
  39. {
  40. if (isset($this->parameters->persistent) && $this->parameters->persistent) {
  41. return;
  42. }
  43. $this->disconnect();
  44. }
  45. /**
  46. * {@inheritdoc}
  47. */
  48. protected function assertParameters(ParametersInterface $parameters)
  49. {
  50. switch ($parameters->scheme) {
  51. case 'tcp':
  52. case 'redis':
  53. case 'unix':
  54. break;
  55. case 'tls':
  56. case 'rediss':
  57. $this->assertSslSupport($parameters);
  58. break;
  59. default:
  60. throw new \InvalidArgumentException("Invalid scheme: '$parameters->scheme'.");
  61. }
  62. return $parameters;
  63. }
  64. /**
  65. * Checks needed conditions for SSL-encrypted connections.
  66. *
  67. * @param ParametersInterface $parameters Initialization parameters for the connection.
  68. *
  69. * @throws \InvalidArgumentException
  70. */
  71. protected function assertSslSupport(ParametersInterface $parameters)
  72. {
  73. if (
  74. filter_var($parameters->persistent, FILTER_VALIDATE_BOOLEAN) &&
  75. version_compare(PHP_VERSION, '7.0.0beta') < 0
  76. ) {
  77. throw new \InvalidArgumentException('Persistent SSL connections require PHP >= 7.0.0.');
  78. }
  79. }
  80. /**
  81. * {@inheritdoc}
  82. */
  83. protected function createResource()
  84. {
  85. switch ($this->parameters->scheme) {
  86. case 'tcp':
  87. case 'redis':
  88. return $this->tcpStreamInitializer($this->parameters);
  89. case 'unix':
  90. return $this->unixStreamInitializer($this->parameters);
  91. case 'tls':
  92. case 'rediss':
  93. return $this->tlsStreamInitializer($this->parameters);
  94. default:
  95. throw new \InvalidArgumentException("Invalid scheme: '{$this->parameters->scheme}'.");
  96. }
  97. }
  98. /**
  99. * Creates a connected stream socket resource.
  100. *
  101. * @param ParametersInterface $parameters Connection parameters.
  102. * @param string $address Address for stream_socket_client().
  103. * @param int $flags Flags for stream_socket_client().
  104. *
  105. * @return resource
  106. */
  107. protected function createStreamSocket(ParametersInterface $parameters, $address, $flags)
  108. {
  109. $timeout = (isset($parameters->timeout) ? (float) $parameters->timeout : 5.0);
  110. if (!$resource = @stream_socket_client($address, $errno, $errstr, $timeout, $flags)) {
  111. $this->onConnectionError(trim($errstr), $errno);
  112. }
  113. if (isset($parameters->read_write_timeout)) {
  114. $rwtimeout = (float) $parameters->read_write_timeout;
  115. $rwtimeout = $rwtimeout > 0 ? $rwtimeout : -1;
  116. $timeoutSeconds = floor($rwtimeout);
  117. $timeoutUSeconds = ($rwtimeout - $timeoutSeconds) * 1000000;
  118. stream_set_timeout($resource, $timeoutSeconds, $timeoutUSeconds);
  119. }
  120. if (isset($parameters->tcp_nodelay) && function_exists('socket_import_stream')) {
  121. $socket = socket_import_stream($resource);
  122. socket_set_option($socket, SOL_TCP, TCP_NODELAY, (int) $parameters->tcp_nodelay);
  123. }
  124. return $resource;
  125. }
  126. /**
  127. * Initializes a TCP stream resource.
  128. *
  129. * @param ParametersInterface $parameters Initialization parameters for the connection.
  130. *
  131. * @return resource
  132. */
  133. protected function tcpStreamInitializer(ParametersInterface $parameters)
  134. {
  135. $address = "tcp://[$parameters->host]:$parameters->port";
  136. $flags = STREAM_CLIENT_CONNECT;
  137. if (isset($parameters->async_connect) && $parameters->async_connect) {
  138. $flags |= STREAM_CLIENT_ASYNC_CONNECT;
  139. }
  140. if (isset($parameters->persistent)) {
  141. if (false !== $persistent = filter_var($parameters->persistent, FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE)) {
  142. $flags |= STREAM_CLIENT_PERSISTENT;
  143. if ($persistent === null) {
  144. $address = "{$address}/{$parameters->persistent}";
  145. }
  146. }
  147. }
  148. $resource = $this->createStreamSocket($parameters, $address, $flags);
  149. return $resource;
  150. }
  151. /**
  152. * Initializes a UNIX stream resource.
  153. *
  154. * @param ParametersInterface $parameters Initialization parameters for the connection.
  155. *
  156. * @return resource
  157. */
  158. protected function unixStreamInitializer(ParametersInterface $parameters)
  159. {
  160. if (!isset($parameters->path)) {
  161. throw new \InvalidArgumentException('Missing UNIX domain socket path.');
  162. }
  163. $flags = STREAM_CLIENT_CONNECT;
  164. if (isset($parameters->persistent)) {
  165. if (false !== $persistent = filter_var($parameters->persistent, FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE)) {
  166. $flags |= STREAM_CLIENT_PERSISTENT;
  167. if ($persistent === null) {
  168. throw new \InvalidArgumentException(
  169. 'Persistent connection IDs are not supported when using UNIX domain sockets.'
  170. );
  171. }
  172. }
  173. }
  174. $resource = $this->createStreamSocket($parameters, "unix://{$parameters->path}", $flags);
  175. return $resource;
  176. }
  177. /**
  178. * Initializes a SSL-encrypted TCP stream resource.
  179. *
  180. * @param ParametersInterface $parameters Initialization parameters for the connection.
  181. *
  182. * @return resource
  183. */
  184. protected function tlsStreamInitializer(ParametersInterface $parameters)
  185. {
  186. $resource = $this->tcpStreamInitializer($parameters);
  187. $metadata = stream_get_meta_data($resource);
  188. // Detect if crypto mode is already enabled for this stream (PHP >= 7.0.0).
  189. if (isset($metadata['crypto'])) {
  190. return $resource;
  191. }
  192. if (is_array($parameters->ssl)) {
  193. $options = $parameters->ssl;
  194. } else {
  195. $options = array();
  196. }
  197. if (!isset($options['crypto_type'])) {
  198. $options['crypto_type'] = STREAM_CRYPTO_METHOD_TLS_CLIENT;
  199. }
  200. if (!stream_context_set_option($resource, array('ssl' => $options))) {
  201. $this->onConnectionError('Error while setting SSL context options');
  202. }
  203. if (!stream_socket_enable_crypto($resource, true, $options['crypto_type'])) {
  204. $this->onConnectionError('Error while switching to encrypted communication');
  205. }
  206. return $resource;
  207. }
  208. /**
  209. * {@inheritdoc}
  210. */
  211. public function connect()
  212. {
  213. if (parent::connect() && $this->initCommands) {
  214. foreach ($this->initCommands as $command) {
  215. $this->executeCommand($command);
  216. }
  217. }
  218. }
  219. /**
  220. * {@inheritdoc}
  221. */
  222. public function disconnect()
  223. {
  224. if ($this->isConnected()) {
  225. fclose($this->getResource());
  226. parent::disconnect();
  227. }
  228. }
  229. /**
  230. * Performs a write operation over the stream of the buffer containing a
  231. * command serialized with the Redis wire protocol.
  232. *
  233. * @param string $buffer Representation of a command in the Redis wire protocol.
  234. */
  235. protected function write($buffer)
  236. {
  237. $socket = $this->getResource();
  238. while (($length = strlen($buffer)) > 0) {
  239. $written = @fwrite($socket, $buffer);
  240. if ($length === $written) {
  241. return;
  242. }
  243. if ($written === false || $written === 0) {
  244. $this->onConnectionError('Error while writing bytes to the server.');
  245. }
  246. $buffer = substr($buffer, $written);
  247. }
  248. }
  249. /**
  250. * {@inheritdoc}
  251. */
  252. public function read()
  253. {
  254. $socket = $this->getResource();
  255. $chunk = fgets($socket);
  256. if ($chunk === false || $chunk === '') {
  257. $this->onConnectionError('Error while reading line from the server.');
  258. }
  259. $prefix = $chunk[0];
  260. $payload = substr($chunk, 1, -2);
  261. switch ($prefix) {
  262. case '+':
  263. return StatusResponse::get($payload);
  264. case '$':
  265. $size = (int) $payload;
  266. if ($size === -1) {
  267. return;
  268. }
  269. $bulkData = '';
  270. $bytesLeft = ($size += 2);
  271. do {
  272. $chunk = fread($socket, min($bytesLeft, 4096));
  273. if ($chunk === false || $chunk === '') {
  274. $this->onConnectionError('Error while reading bytes from the server.');
  275. }
  276. $bulkData .= $chunk;
  277. $bytesLeft = $size - strlen($bulkData);
  278. } while ($bytesLeft > 0);
  279. return substr($bulkData, 0, -2);
  280. case '*':
  281. $count = (int) $payload;
  282. if ($count === -1) {
  283. return;
  284. }
  285. $multibulk = array();
  286. for ($i = 0; $i < $count; ++$i) {
  287. $multibulk[$i] = $this->read();
  288. }
  289. return $multibulk;
  290. case ':':
  291. return (int) $payload;
  292. case '-':
  293. return new ErrorResponse($payload);
  294. default:
  295. $this->onProtocolError("Unknown response prefix: '$prefix'.");
  296. return;
  297. }
  298. }
  299. /**
  300. * {@inheritdoc}
  301. */
  302. public function writeRequest(CommandInterface $command)
  303. {
  304. $commandID = $command->getId();
  305. $arguments = $command->getArguments();
  306. $cmdlen = strlen($commandID);
  307. $reqlen = count($arguments) + 1;
  308. $buffer = "*{$reqlen}\r\n\${$cmdlen}\r\n{$commandID}\r\n";
  309. for ($i = 0, $reqlen--; $i < $reqlen; ++$i) {
  310. $argument = $arguments[$i];
  311. $arglen = strlen($argument);
  312. $buffer .= "\${$arglen}\r\n{$argument}\r\n";
  313. }
  314. $this->write($buffer);
  315. }
  316. }