ProcessPipes.php 10.0 KB

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