StreamConnection.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391
  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. if (!filter_var($parameters->host, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6)) {
  136. $address = "tcp://$parameters->host:$parameters->port";
  137. } else {
  138. $address = "tcp://[$parameters->host]:$parameters->port";
  139. }
  140. $flags = STREAM_CLIENT_CONNECT;
  141. if (isset($parameters->async_connect) && $parameters->async_connect) {
  142. $flags |= STREAM_CLIENT_ASYNC_CONNECT;
  143. }
  144. if (isset($parameters->persistent)) {
  145. if (false !== $persistent = filter_var($parameters->persistent, FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE)) {
  146. $flags |= STREAM_CLIENT_PERSISTENT;
  147. if ($persistent === null) {
  148. $address = "{$address}/{$parameters->persistent}";
  149. }
  150. }
  151. }
  152. $resource = $this->createStreamSocket($parameters, $address, $flags);
  153. return $resource;
  154. }
  155. /**
  156. * Initializes a UNIX stream resource.
  157. *
  158. * @param ParametersInterface $parameters Initialization parameters for the connection.
  159. *
  160. * @return resource
  161. */
  162. protected function unixStreamInitializer(ParametersInterface $parameters)
  163. {
  164. if (!isset($parameters->path)) {
  165. throw new \InvalidArgumentException('Missing UNIX domain socket path.');
  166. }
  167. $flags = STREAM_CLIENT_CONNECT;
  168. if (isset($parameters->persistent)) {
  169. if (false !== $persistent = filter_var($parameters->persistent, FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE)) {
  170. $flags |= STREAM_CLIENT_PERSISTENT;
  171. if ($persistent === null) {
  172. throw new \InvalidArgumentException(
  173. 'Persistent connection IDs are not supported when using UNIX domain sockets.'
  174. );
  175. }
  176. }
  177. }
  178. $resource = $this->createStreamSocket($parameters, "unix://{$parameters->path}", $flags);
  179. return $resource;
  180. }
  181. /**
  182. * Initializes a SSL-encrypted TCP stream resource.
  183. *
  184. * @param ParametersInterface $parameters Initialization parameters for the connection.
  185. *
  186. * @return resource
  187. */
  188. protected function tlsStreamInitializer(ParametersInterface $parameters)
  189. {
  190. $resource = $this->tcpStreamInitializer($parameters);
  191. $metadata = stream_get_meta_data($resource);
  192. // Detect if crypto mode is already enabled for this stream (PHP >= 7.0.0).
  193. if (isset($metadata['crypto'])) {
  194. return $resource;
  195. }
  196. if (is_array($parameters->ssl)) {
  197. $options = $parameters->ssl;
  198. } else {
  199. $options = array();
  200. }
  201. if (!isset($options['crypto_type'])) {
  202. $options['crypto_type'] = STREAM_CRYPTO_METHOD_TLS_CLIENT;
  203. }
  204. if (!stream_context_set_option($resource, array('ssl' => $options))) {
  205. $this->onConnectionError('Error while setting SSL context options');
  206. }
  207. if (!stream_socket_enable_crypto($resource, true, $options['crypto_type'])) {
  208. $this->onConnectionError('Error while switching to encrypted communication');
  209. }
  210. return $resource;
  211. }
  212. /**
  213. * {@inheritdoc}
  214. */
  215. public function connect()
  216. {
  217. if (parent::connect() && $this->initCommands) {
  218. foreach ($this->initCommands as $command) {
  219. $this->executeCommand($command);
  220. }
  221. }
  222. }
  223. /**
  224. * {@inheritdoc}
  225. */
  226. public function disconnect()
  227. {
  228. if ($this->isConnected()) {
  229. fclose($this->getResource());
  230. parent::disconnect();
  231. }
  232. }
  233. /**
  234. * Performs a write operation over the stream of the buffer containing a
  235. * command serialized with the Redis wire protocol.
  236. *
  237. * @param string $buffer Representation of a command in the Redis wire protocol.
  238. */
  239. protected function write($buffer)
  240. {
  241. $socket = $this->getResource();
  242. while (($length = strlen($buffer)) > 0) {
  243. $written = @fwrite($socket, $buffer);
  244. if ($length === $written) {
  245. return;
  246. }
  247. if ($written === false || $written === 0) {
  248. $this->onConnectionError('Error while writing bytes to the server.');
  249. }
  250. $buffer = substr($buffer, $written);
  251. }
  252. }
  253. /**
  254. * {@inheritdoc}
  255. */
  256. public function read()
  257. {
  258. $socket = $this->getResource();
  259. $chunk = fgets($socket);
  260. if ($chunk === false || $chunk === '') {
  261. $this->onConnectionError('Error while reading line from the server.');
  262. }
  263. $prefix = $chunk[0];
  264. $payload = substr($chunk, 1, -2);
  265. switch ($prefix) {
  266. case '+':
  267. return StatusResponse::get($payload);
  268. case '$':
  269. $size = (int) $payload;
  270. if ($size === -1) {
  271. return;
  272. }
  273. $bulkData = '';
  274. $bytesLeft = ($size += 2);
  275. do {
  276. $chunk = fread($socket, min($bytesLeft, 4096));
  277. if ($chunk === false || $chunk === '') {
  278. $this->onConnectionError('Error while reading bytes from the server.');
  279. }
  280. $bulkData .= $chunk;
  281. $bytesLeft = $size - strlen($bulkData);
  282. } while ($bytesLeft > 0);
  283. return substr($bulkData, 0, -2);
  284. case '*':
  285. $count = (int) $payload;
  286. if ($count === -1) {
  287. return;
  288. }
  289. $multibulk = array();
  290. for ($i = 0; $i < $count; ++$i) {
  291. $multibulk[$i] = $this->read();
  292. }
  293. return $multibulk;
  294. case ':':
  295. return (int) $payload;
  296. case '-':
  297. return new ErrorResponse($payload);
  298. default:
  299. $this->onProtocolError("Unknown response prefix: '$prefix'.");
  300. return;
  301. }
  302. }
  303. /**
  304. * {@inheritdoc}
  305. */
  306. public function writeRequest(CommandInterface $command)
  307. {
  308. $commandID = $command->getId();
  309. $arguments = $command->getArguments();
  310. $cmdlen = strlen($commandID);
  311. $reqlen = count($arguments) + 1;
  312. $buffer = "*{$reqlen}\r\n\${$cmdlen}\r\n{$commandID}\r\n";
  313. for ($i = 0, $reqlen--; $i < $reqlen; ++$i) {
  314. $argument = $arguments[$i];
  315. $arglen = strlen($argument);
  316. $buffer .= "\${$arglen}\r\n{$argument}\r\n";
  317. }
  318. $this->write($buffer);
  319. }
  320. }