ProcessPipes.php 11 KB

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