ProcessPipes.php 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360
  1. <?php
  2. /*
  3. * This file is part of the Symfony package.
  4. *
  5. * (c) Fabien Potencier <fabien@symfony.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 Symfony\Component\Process;
  11. use Symfony\Component\Process\Exception\RuntimeException;
  12. /**
  13. * ProcessPipes manages descriptors and pipes for the use of proc_open.
  14. */
  15. class ProcessPipes
  16. {
  17. /** @var array */
  18. public $pipes = array();
  19. /** @var array */
  20. private $files = array();
  21. /** @var array */
  22. private $fileHandles = array();
  23. /** @var array */
  24. private $readBytes = array();
  25. /** @var bool */
  26. private $useFiles;
  27. /** @var bool */
  28. private $ttyMode;
  29. const CHUNK_SIZE = 16384;
  30. public function __construct($useFiles, $ttyMode)
  31. {
  32. $this->useFiles = (bool) $useFiles;
  33. $this->ttyMode = (bool) $ttyMode;
  34. // Fix for PHP bug #51800: reading from STDOUT pipe hangs forever on Windows if the output is too big.
  35. // Workaround for this problem is to use temporary files instead of pipes on Windows platform.
  36. //
  37. // @see https://bugs.php.net/bug.php?id=51800
  38. if ($this->useFiles) {
  39. $this->files = array(
  40. Process::STDOUT => tempnam(sys_get_temp_dir(), 'sf_proc_stdout'),
  41. Process::STDERR => tempnam(sys_get_temp_dir(), 'sf_proc_stderr'),
  42. );
  43. foreach ($this->files as $offset => $file) {
  44. $this->fileHandles[$offset] = fopen($this->files[$offset], 'rb');
  45. if (false === $this->fileHandles[$offset]) {
  46. throw new RuntimeException('A temporary file could not be opened to write the process output to, verify that your TEMP environment variable is writable');
  47. }
  48. }
  49. $this->readBytes = array(
  50. Process::STDOUT => 0,
  51. Process::STDERR => 0,
  52. );
  53. }
  54. }
  55. public function __destruct()
  56. {
  57. $this->close();
  58. $this->removeFiles();
  59. }
  60. /**
  61. * Sets non-blocking mode on pipes.
  62. */
  63. public function unblock()
  64. {
  65. foreach ($this->pipes as $pipe) {
  66. stream_set_blocking($pipe, 0);
  67. }
  68. }
  69. /**
  70. * Closes file handles and pipes.
  71. */
  72. public function close()
  73. {
  74. $this->closeUnixPipes();
  75. foreach ($this->fileHandles as $handle) {
  76. fclose($handle);
  77. }
  78. $this->fileHandles = array();
  79. }
  80. /**
  81. * Closes Unix pipes.
  82. *
  83. * Nothing happens in case file handles are used.
  84. */
  85. public function closeUnixPipes()
  86. {
  87. foreach ($this->pipes as $pipe) {
  88. fclose($pipe);
  89. }
  90. $this->pipes = array();
  91. }
  92. /**
  93. * Returns an array of descriptors for the use of proc_open.
  94. *
  95. * @return array
  96. */
  97. public function getDescriptors()
  98. {
  99. if ($this->useFiles) {
  100. // We're not using pipe on Windows platform as it hangs (https://bugs.php.net/bug.php?id=51800)
  101. // We're not using file handles as it can produce corrupted output https://bugs.php.net/bug.php?id=65650
  102. // So we redirect output within the commandline and pass the nul device to the process
  103. return array(
  104. array('pipe', 'r'),
  105. array('file', 'NUL', 'w'),
  106. array('file', 'NUL', 'w'),
  107. );
  108. }
  109. if ($this->ttyMode) {
  110. return array(
  111. array('file', '/dev/tty', 'r'),
  112. array('file', '/dev/tty', 'w'),
  113. array('file', '/dev/tty', 'w'),
  114. );
  115. }
  116. return array(
  117. array('pipe', 'r'), // stdin
  118. array('pipe', 'w'), // stdout
  119. array('pipe', 'w'), // stderr
  120. );
  121. }
  122. /**
  123. * Returns an array of filenames indexed by their related stream in case these pipes use temporary files.
  124. *
  125. * @return array
  126. */
  127. public function getFiles()
  128. {
  129. if ($this->useFiles) {
  130. return $this->files;
  131. }
  132. return array();
  133. }
  134. /**
  135. * Reads data in file handles and pipes.
  136. *
  137. * @param bool $blocking Whether to use blocking calls or not.
  138. *
  139. * @return array An array of read data indexed by their fd.
  140. */
  141. public function read($blocking)
  142. {
  143. return array_replace($this->readStreams($blocking), $this->readFileHandles());
  144. }
  145. /**
  146. * Reads data in file handles and pipes, closes them if EOF is reached.
  147. *
  148. * @param bool $blocking Whether to use blocking calls or not.
  149. *
  150. * @return array An array of read data indexed by their fd.
  151. */
  152. public function readAndCloseHandles($blocking)
  153. {
  154. return array_replace($this->readStreams($blocking, true), $this->readFileHandles(true));
  155. }
  156. /**
  157. * Returns if the current state has open file handles or pipes.
  158. *
  159. * @return bool
  160. */
  161. public function hasOpenHandles()
  162. {
  163. if (!$this->useFiles) {
  164. return (bool) $this->pipes;
  165. }
  166. return (bool) $this->pipes && (bool) $this->fileHandles;
  167. }
  168. /**
  169. * Writes stdin data.
  170. *
  171. * @param bool $blocking Whether to use blocking calls or not.
  172. * @param string|null $stdin The data to write.
  173. */
  174. public function write($blocking, $stdin)
  175. {
  176. if (null === $stdin) {
  177. fclose($this->pipes[0]);
  178. unset($this->pipes[0]);
  179. return;
  180. }
  181. $writePipes = array($this->pipes[0]);
  182. unset($this->pipes[0]);
  183. $stdinLen = strlen($stdin);
  184. $stdinOffset = 0;
  185. while ($writePipes) {
  186. $r = null;
  187. $w = $writePipes;
  188. $e = null;
  189. if (false === $n = @stream_select($r, $w, $e, 0, $blocking ? ceil(Process::TIMEOUT_PRECISION * 1E6) : 0)) {
  190. // if a system call has been interrupted, forget about it, let's try again
  191. if ($this->hasSystemCallBeenInterrupted()) {
  192. continue;
  193. }
  194. break;
  195. }
  196. // nothing has changed, let's wait until the process is ready
  197. if (0 === $n) {
  198. continue;
  199. }
  200. if ($w) {
  201. $written = fwrite($writePipes[0], (binary) substr($stdin, $stdinOffset), 8192);
  202. if (false !== $written) {
  203. $stdinOffset += $written;
  204. }
  205. if ($stdinOffset >= $stdinLen) {
  206. fclose($writePipes[0]);
  207. $writePipes = null;
  208. }
  209. }
  210. }
  211. }
  212. /**
  213. * Reads data in file handles.
  214. *
  215. * @param bool $close Whether to close file handles or not.
  216. *
  217. * @return array An array of read data indexed by their fd.
  218. */
  219. private function readFileHandles($close = false)
  220. {
  221. $read = array();
  222. $fh = $this->fileHandles;
  223. foreach ($fh as $type => $fileHandle) {
  224. if (0 !== fseek($fileHandle, $this->readBytes[$type])) {
  225. continue;
  226. }
  227. $data = '';
  228. $dataread = null;
  229. while (!feof($fileHandle)) {
  230. if (false !== $dataread = fread($fileHandle, self::CHUNK_SIZE)) {
  231. $data .= $dataread;
  232. }
  233. }
  234. if (0 < $length = strlen($data)) {
  235. $this->readBytes[$type] += $length;
  236. $read[$type] = $data;
  237. }
  238. if (false === $dataread || (true === $close && feof($fileHandle) && '' === $data)) {
  239. fclose($this->fileHandles[$type]);
  240. unset($this->fileHandles[$type]);
  241. }
  242. }
  243. return $read;
  244. }
  245. /**
  246. * Reads data in file pipes streams.
  247. *
  248. * @param bool $blocking Whether to use blocking calls or not.
  249. * @param bool $close Whether to close file handles or not.
  250. *
  251. * @return array An array of read data indexed by their fd.
  252. */
  253. private function readStreams($blocking, $close = false)
  254. {
  255. if (empty($this->pipes)) {
  256. usleep(Process::TIMEOUT_PRECISION * 1E4);
  257. return array();
  258. }
  259. $read = array();
  260. $r = $this->pipes;
  261. $w = null;
  262. $e = null;
  263. // let's have a look if something changed in streams
  264. if (false === $n = @stream_select($r, $w, $e, 0, $blocking ? ceil(Process::TIMEOUT_PRECISION * 1E6) : 0)) {
  265. // if a system call has been interrupted, forget about it, let's try again
  266. // otherwise, an error occurred, let's reset pipes
  267. if (!$this->hasSystemCallBeenInterrupted()) {
  268. $this->pipes = array();
  269. }
  270. return $read;
  271. }
  272. // nothing has changed
  273. if (0 === $n) {
  274. return $read;
  275. }
  276. foreach ($r as $pipe) {
  277. $type = array_search($pipe, $this->pipes);
  278. $data = '';
  279. while ('' !== $dataread = (string) fread($pipe, self::CHUNK_SIZE)) {
  280. $data .= $dataread;
  281. }
  282. if ('' !== $data) {
  283. $read[$type] = $data;
  284. }
  285. if (false === $data || (true === $close && feof($pipe) && '' === $data)) {
  286. fclose($this->pipes[$type]);
  287. unset($this->pipes[$type]);
  288. }
  289. }
  290. return $read;
  291. }
  292. /**
  293. * Returns true if a system call has been interrupted.
  294. *
  295. * @return bool
  296. */
  297. private function hasSystemCallBeenInterrupted()
  298. {
  299. $lastError = error_get_last();
  300. // stream_select returns false when the `select` system call is interrupted by an incoming signal
  301. return isset($lastError['message']) && false !== stripos($lastError['message'], 'interrupted system call');
  302. }
  303. /**
  304. * Removes temporary files
  305. */
  306. private function removeFiles()
  307. {
  308. foreach ($this->files as $filename) {
  309. if (file_exists($filename)) {
  310. @unlink($filename);
  311. }
  312. }
  313. $this->files = array();
  314. }
  315. }