You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1674 lines
52 KiB

3 years ago
  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\InvalidArgumentException;
  12. use Symfony\Component\Process\Exception\LogicException;
  13. use Symfony\Component\Process\Exception\ProcessFailedException;
  14. use Symfony\Component\Process\Exception\ProcessSignaledException;
  15. use Symfony\Component\Process\Exception\ProcessTimedOutException;
  16. use Symfony\Component\Process\Exception\RuntimeException;
  17. use Symfony\Component\Process\Pipes\PipesInterface;
  18. use Symfony\Component\Process\Pipes\UnixPipes;
  19. use Symfony\Component\Process\Pipes\WindowsPipes;
  20. /**
  21. * Process is a thin wrapper around proc_* functions to easily
  22. * start independent PHP processes.
  23. *
  24. * @author Fabien Potencier <fabien@symfony.com>
  25. * @author Romain Neutron <imprec@gmail.com>
  26. */
  27. class Process implements \IteratorAggregate
  28. {
  29. public const ERR = 'err';
  30. public const OUT = 'out';
  31. public const STATUS_READY = 'ready';
  32. public const STATUS_STARTED = 'started';
  33. public const STATUS_TERMINATED = 'terminated';
  34. public const STDIN = 0;
  35. public const STDOUT = 1;
  36. public const STDERR = 2;
  37. // Timeout Precision in seconds.
  38. public const TIMEOUT_PRECISION = 0.2;
  39. public const ITER_NON_BLOCKING = 1; // By default, iterating over outputs is a blocking call, use this flag to make it non-blocking
  40. public const ITER_KEEP_OUTPUT = 2; // By default, outputs are cleared while iterating, use this flag to keep them in memory
  41. public const ITER_SKIP_OUT = 4; // Use this flag to skip STDOUT while iterating
  42. public const ITER_SKIP_ERR = 8; // Use this flag to skip STDERR while iterating
  43. private $callback;
  44. private $hasCallback = false;
  45. private $commandline;
  46. private $cwd;
  47. private $env;
  48. private $input;
  49. private $starttime;
  50. private $lastOutputTime;
  51. private $timeout;
  52. private $idleTimeout;
  53. private $exitcode;
  54. private $fallbackStatus = [];
  55. private $processInformation;
  56. private $outputDisabled = false;
  57. private $stdout;
  58. private $stderr;
  59. private $process;
  60. private $status = self::STATUS_READY;
  61. private $incrementalOutputOffset = 0;
  62. private $incrementalErrorOutputOffset = 0;
  63. private $tty = false;
  64. private $pty;
  65. private $options = ['suppress_errors' => true, 'bypass_shell' => true];
  66. private $useFileHandles = false;
  67. /** @var PipesInterface */
  68. private $processPipes;
  69. private $latestSignal;
  70. private static $sigchild;
  71. /**
  72. * Exit codes translation table.
  73. *
  74. * User-defined errors must use exit codes in the 64-113 range.
  75. */
  76. public static $exitCodes = [
  77. 0 => 'OK',
  78. 1 => 'General error',
  79. 2 => 'Misuse of shell builtins',
  80. 126 => 'Invoked command cannot execute',
  81. 127 => 'Command not found',
  82. 128 => 'Invalid exit argument',
  83. // signals
  84. 129 => 'Hangup',
  85. 130 => 'Interrupt',
  86. 131 => 'Quit and dump core',
  87. 132 => 'Illegal instruction',
  88. 133 => 'Trace/breakpoint trap',
  89. 134 => 'Process aborted',
  90. 135 => 'Bus error: "access to undefined portion of memory object"',
  91. 136 => 'Floating point exception: "erroneous arithmetic operation"',
  92. 137 => 'Kill (terminate immediately)',
  93. 138 => 'User-defined 1',
  94. 139 => 'Segmentation violation',
  95. 140 => 'User-defined 2',
  96. 141 => 'Write to pipe with no one reading',
  97. 142 => 'Signal raised by alarm',
  98. 143 => 'Termination (request to terminate)',
  99. // 144 - not defined
  100. 145 => 'Child process terminated, stopped (or continued*)',
  101. 146 => 'Continue if stopped',
  102. 147 => 'Stop executing temporarily',
  103. 148 => 'Terminal stop signal',
  104. 149 => 'Background process attempting to read from tty ("in")',
  105. 150 => 'Background process attempting to write to tty ("out")',
  106. 151 => 'Urgent data available on socket',
  107. 152 => 'CPU time limit exceeded',
  108. 153 => 'File size limit exceeded',
  109. 154 => 'Signal raised by timer counting virtual time: "virtual timer expired"',
  110. 155 => 'Profiling timer expired',
  111. // 156 - not defined
  112. 157 => 'Pollable event',
  113. // 158 - not defined
  114. 159 => 'Bad syscall',
  115. ];
  116. /**
  117. * @param array $command The command to run and its arguments listed as separate entries
  118. * @param string|null $cwd The working directory or null to use the working dir of the current PHP process
  119. * @param array|null $env The environment variables or null to use the same environment as the current PHP process
  120. * @param mixed $input The input as stream resource, scalar or \Traversable, or null for no input
  121. * @param int|float|null $timeout The timeout in seconds or null to disable
  122. *
  123. * @throws LogicException When proc_open is not installed
  124. */
  125. public function __construct(array $command, string $cwd = null, array $env = null, $input = null, ?float $timeout = 60)
  126. {
  127. if (!\function_exists('proc_open')) {
  128. throw new LogicException('The Process class relies on proc_open, which is not available on your PHP installation.');
  129. }
  130. $this->commandline = $command;
  131. $this->cwd = $cwd;
  132. // on Windows, if the cwd changed via chdir(), proc_open defaults to the dir where PHP was started
  133. // on Gnu/Linux, PHP builds with --enable-maintainer-zts are also affected
  134. // @see : https://bugs.php.net/51800
  135. // @see : https://bugs.php.net/50524
  136. if (null === $this->cwd && (\defined('ZEND_THREAD_SAFE') || '\\' === \DIRECTORY_SEPARATOR)) {
  137. $this->cwd = getcwd();
  138. }
  139. if (null !== $env) {
  140. $this->setEnv($env);
  141. }
  142. $this->setInput($input);
  143. $this->setTimeout($timeout);
  144. $this->useFileHandles = '\\' === \DIRECTORY_SEPARATOR;
  145. $this->pty = false;
  146. }
  147. /**
  148. * Creates a Process instance as a command-line to be run in a shell wrapper.
  149. *
  150. * Command-lines are parsed by the shell of your OS (/bin/sh on Unix-like, cmd.exe on Windows.)
  151. * This allows using e.g. pipes or conditional execution. In this mode, signals are sent to the
  152. * shell wrapper and not to your commands.
  153. *
  154. * In order to inject dynamic values into command-lines, we strongly recommend using placeholders.
  155. * This will save escaping values, which is not portable nor secure anyway:
  156. *
  157. * $process = Process::fromShellCommandline('my_command "$MY_VAR"');
  158. * $process->run(null, ['MY_VAR' => $theValue]);
  159. *
  160. * @param string $command The command line to pass to the shell of the OS
  161. * @param string|null $cwd The working directory or null to use the working dir of the current PHP process
  162. * @param array|null $env The environment variables or null to use the same environment as the current PHP process
  163. * @param mixed $input The input as stream resource, scalar or \Traversable, or null for no input
  164. * @param int|float|null $timeout The timeout in seconds or null to disable
  165. *
  166. * @return static
  167. *
  168. * @throws LogicException When proc_open is not installed
  169. */
  170. public static function fromShellCommandline(string $command, string $cwd = null, array $env = null, $input = null, ?float $timeout = 60)
  171. {
  172. $process = new static([], $cwd, $env, $input, $timeout);
  173. $process->commandline = $command;
  174. return $process;
  175. }
  176. public function __sleep()
  177. {
  178. throw new \BadMethodCallException('Cannot serialize '.__CLASS__);
  179. }
  180. public function __wakeup()
  181. {
  182. throw new \BadMethodCallException('Cannot unserialize '.__CLASS__);
  183. }
  184. public function __destruct()
  185. {
  186. if ($this->options['create_new_console'] ?? false) {
  187. $this->processPipes->close();
  188. } else {
  189. $this->stop(0);
  190. }
  191. }
  192. public function __clone()
  193. {
  194. $this->resetProcessData();
  195. }
  196. /**
  197. * Runs the process.
  198. *
  199. * The callback receives the type of output (out or err) and
  200. * some bytes from the output in real-time. It allows to have feedback
  201. * from the independent process during execution.
  202. *
  203. * The STDOUT and STDERR are also available after the process is finished
  204. * via the getOutput() and getErrorOutput() methods.
  205. *
  206. * @param callable|null $callback A PHP callback to run whenever there is some
  207. * output available on STDOUT or STDERR
  208. *
  209. * @return int The exit status code
  210. *
  211. * @throws RuntimeException When process can't be launched
  212. * @throws RuntimeException When process is already running
  213. * @throws ProcessTimedOutException When process timed out
  214. * @throws ProcessSignaledException When process stopped after receiving signal
  215. * @throws LogicException In case a callback is provided and output has been disabled
  216. *
  217. * @final
  218. */
  219. public function run(callable $callback = null, array $env = []): int
  220. {
  221. $this->start($callback, $env);
  222. return $this->wait();
  223. }
  224. /**
  225. * Runs the process.
  226. *
  227. * This is identical to run() except that an exception is thrown if the process
  228. * exits with a non-zero exit code.
  229. *
  230. * @return $this
  231. *
  232. * @throws ProcessFailedException if the process didn't terminate successfully
  233. *
  234. * @final
  235. */
  236. public function mustRun(callable $callback = null, array $env = []): self
  237. {
  238. if (0 !== $this->run($callback, $env)) {
  239. throw new ProcessFailedException($this);
  240. }
  241. return $this;
  242. }
  243. /**
  244. * Starts the process and returns after writing the input to STDIN.
  245. *
  246. * This method blocks until all STDIN data is sent to the process then it
  247. * returns while the process runs in the background.
  248. *
  249. * The termination of the process can be awaited with wait().
  250. *
  251. * The callback receives the type of output (out or err) and some bytes from
  252. * the output in real-time while writing the standard input to the process.
  253. * It allows to have feedback from the independent process during execution.
  254. *
  255. * @param callable|null $callback A PHP callback to run whenever there is some
  256. * output available on STDOUT or STDERR
  257. *
  258. * @throws RuntimeException When process can't be launched
  259. * @throws RuntimeException When process is already running
  260. * @throws LogicException In case a callback is provided and output has been disabled
  261. */
  262. public function start(callable $callback = null, array $env = [])
  263. {
  264. if ($this->isRunning()) {
  265. throw new RuntimeException('Process is already running.');
  266. }
  267. $this->resetProcessData();
  268. $this->starttime = $this->lastOutputTime = microtime(true);
  269. $this->callback = $this->buildCallback($callback);
  270. $this->hasCallback = null !== $callback;
  271. $descriptors = $this->getDescriptors();
  272. if ($this->env) {
  273. $env += $this->env;
  274. }
  275. $env += $this->getDefaultEnv();
  276. if (\is_array($commandline = $this->commandline)) {
  277. $commandline = implode(' ', array_map([$this, 'escapeArgument'], $commandline));
  278. if ('\\' !== \DIRECTORY_SEPARATOR) {
  279. // exec is mandatory to deal with sending a signal to the process
  280. $commandline = 'exec '.$commandline;
  281. }
  282. } else {
  283. $commandline = $this->replacePlaceholders($commandline, $env);
  284. }
  285. if ('\\' === \DIRECTORY_SEPARATOR) {
  286. $commandline = $this->prepareWindowsCommandLine($commandline, $env);
  287. } elseif (!$this->useFileHandles && $this->isSigchildEnabled()) {
  288. // last exit code is output on the fourth pipe and caught to work around --enable-sigchild
  289. $descriptors[3] = ['pipe', 'w'];
  290. // See https://unix.stackexchange.com/questions/71205/background-process-pipe-input
  291. $commandline = '{ ('.$commandline.') <&3 3<&- 3>/dev/null & } 3<&0;';
  292. $commandline .= 'pid=$!; echo $pid >&3; wait $pid; code=$?; echo $code >&3; exit $code';
  293. // Workaround for the bug, when PTS functionality is enabled.
  294. // @see : https://bugs.php.net/69442
  295. $ptsWorkaround = fopen(__FILE__, 'r');
  296. }
  297. $envPairs = [];
  298. foreach ($env as $k => $v) {
  299. if (false !== $v) {
  300. $envPairs[] = $k.'='.$v;
  301. }
  302. }
  303. if (!is_dir($this->cwd)) {
  304. throw new RuntimeException(sprintf('The provided cwd "%s" does not exist.', $this->cwd));
  305. }
  306. $this->process = @proc_open($commandline, $descriptors, $this->processPipes->pipes, $this->cwd, $envPairs, $this->options);
  307. if (!\is_resource($this->process)) {
  308. throw new RuntimeException('Unable to launch a new process.');
  309. }
  310. $this->status = self::STATUS_STARTED;
  311. if (isset($descriptors[3])) {
  312. $this->fallbackStatus['pid'] = (int) fgets($this->processPipes->pipes[3]);
  313. }
  314. if ($this->tty) {
  315. return;
  316. }
  317. $this->updateStatus(false);
  318. $this->checkTimeout();
  319. }
  320. /**
  321. * Restarts the process.
  322. *
  323. * Be warned that the process is cloned before being started.
  324. *
  325. * @param callable|null $callback A PHP callback to run whenever there is some
  326. * output available on STDOUT or STDERR
  327. *
  328. * @return static
  329. *
  330. * @throws RuntimeException When process can't be launched
  331. * @throws RuntimeException When process is already running
  332. *
  333. * @see start()
  334. *
  335. * @final
  336. */
  337. public function restart(callable $callback = null, array $env = []): self
  338. {
  339. if ($this->isRunning()) {
  340. throw new RuntimeException('Process is already running.');
  341. }
  342. $process = clone $this;
  343. $process->start($callback, $env);
  344. return $process;
  345. }
  346. /**
  347. * Waits for the process to terminate.
  348. *
  349. * The callback receives the type of output (out or err) and some bytes
  350. * from the output in real-time while writing the standard input to the process.
  351. * It allows to have feedback from the independent process during execution.
  352. *
  353. * @param callable|null $callback A valid PHP callback
  354. *
  355. * @return int The exitcode of the process
  356. *
  357. * @throws ProcessTimedOutException When process timed out
  358. * @throws ProcessSignaledException When process stopped after receiving signal
  359. * @throws LogicException When process is not yet started
  360. */
  361. public function wait(callable $callback = null)
  362. {
  363. $this->requireProcessIsStarted(__FUNCTION__);
  364. $this->updateStatus(false);
  365. if (null !== $callback) {
  366. if (!$this->processPipes->haveReadSupport()) {
  367. $this->stop(0);
  368. throw new LogicException('Pass the callback to the "Process::start" method or call enableOutput to use a callback with "Process::wait".');
  369. }
  370. $this->callback = $this->buildCallback($callback);
  371. }
  372. do {
  373. $this->checkTimeout();
  374. $running = '\\' === \DIRECTORY_SEPARATOR ? $this->isRunning() : $this->processPipes->areOpen();
  375. $this->readPipes($running, '\\' !== \DIRECTORY_SEPARATOR || !$running);
  376. } while ($running);
  377. while ($this->isRunning()) {
  378. $this->checkTimeout();
  379. usleep(1000);
  380. }
  381. if ($this->processInformation['signaled'] && $this->processInformation['termsig'] !== $this->latestSignal) {
  382. throw new ProcessSignaledException($this);
  383. }
  384. return $this->exitcode;
  385. }
  386. /**
  387. * Waits until the callback returns true.
  388. *
  389. * The callback receives the type of output (out or err) and some bytes
  390. * from the output in real-time while writing the standard input to the process.
  391. * It allows to have feedback from the independent process during execution.
  392. *
  393. * @throws RuntimeException When process timed out
  394. * @throws LogicException When process is not yet started
  395. * @throws ProcessTimedOutException In case the timeout was reached
  396. */
  397. public function waitUntil(callable $callback): bool
  398. {
  399. $this->requireProcessIsStarted(__FUNCTION__);
  400. $this->updateStatus(false);
  401. if (!$this->processPipes->haveReadSupport()) {
  402. $this->stop(0);
  403. throw new LogicException('Pass the callback to the "Process::start" method or call enableOutput to use a callback with "Process::waitUntil".');
  404. }
  405. $callback = $this->buildCallback($callback);
  406. $ready = false;
  407. while (true) {
  408. $this->checkTimeout();
  409. $running = '\\' === \DIRECTORY_SEPARATOR ? $this->isRunning() : $this->processPipes->areOpen();
  410. $output = $this->processPipes->readAndWrite($running, '\\' !== \DIRECTORY_SEPARATOR || !$running);
  411. foreach ($output as $type => $data) {
  412. if (3 !== $type) {
  413. $ready = $callback(self::STDOUT === $type ? self::OUT : self::ERR, $data) || $ready;
  414. } elseif (!isset($this->fallbackStatus['signaled'])) {
  415. $this->fallbackStatus['exitcode'] = (int) $data;
  416. }
  417. }
  418. if ($ready) {
  419. return true;
  420. }
  421. if (!$running) {
  422. return false;
  423. }
  424. usleep(1000);
  425. }
  426. }
  427. /**
  428. * Returns the Pid (process identifier), if applicable.
  429. *
  430. * @return int|null The process id if running, null otherwise
  431. */
  432. public function getPid()
  433. {
  434. return $this->isRunning() ? $this->processInformation['pid'] : null;
  435. }
  436. /**
  437. * Sends a POSIX signal to the process.
  438. *
  439. * @param int $signal A valid POSIX signal (see https://php.net/pcntl.constants)
  440. *
  441. * @return $this
  442. *
  443. * @throws LogicException In case the process is not running
  444. * @throws RuntimeException In case --enable-sigchild is activated and the process can't be killed
  445. * @throws RuntimeException In case of failure
  446. */
  447. public function signal(int $signal)
  448. {
  449. $this->doSignal($signal, true);
  450. return $this;
  451. }
  452. /**
  453. * Disables fetching output and error output from the underlying process.
  454. *
  455. * @return $this
  456. *
  457. * @throws RuntimeException In case the process is already running
  458. * @throws LogicException if an idle timeout is set
  459. */
  460. public function disableOutput()
  461. {
  462. if ($this->isRunning()) {
  463. throw new RuntimeException('Disabling output while the process is running is not possible.');
  464. }
  465. if (null !== $this->idleTimeout) {
  466. throw new LogicException('Output can not be disabled while an idle timeout is set.');
  467. }
  468. $this->outputDisabled = true;
  469. return $this;
  470. }
  471. /**
  472. * Enables fetching output and error output from the underlying process.
  473. *
  474. * @return $this
  475. *
  476. * @throws RuntimeException In case the process is already running
  477. */
  478. public function enableOutput()
  479. {
  480. if ($this->isRunning()) {
  481. throw new RuntimeException('Enabling output while the process is running is not possible.');
  482. }
  483. $this->outputDisabled = false;
  484. return $this;
  485. }
  486. /**
  487. * Returns true in case the output is disabled, false otherwise.
  488. *
  489. * @return bool
  490. */
  491. public function isOutputDisabled()
  492. {
  493. return $this->outputDisabled;
  494. }
  495. /**
  496. * Returns the current output of the process (STDOUT).
  497. *
  498. * @return string The process output
  499. *
  500. * @throws LogicException in case the output has been disabled
  501. * @throws LogicException In case the process is not started
  502. */
  503. public function getOutput()
  504. {
  505. $this->readPipesForOutput(__FUNCTION__);
  506. if (false === $ret = stream_get_contents($this->stdout, -1, 0)) {
  507. return '';
  508. }
  509. return $ret;
  510. }
  511. /**
  512. * Returns the output incrementally.
  513. *
  514. * In comparison with the getOutput method which always return the whole
  515. * output, this one returns the new output since the last call.
  516. *
  517. * @return string The process output since the last call
  518. *
  519. * @throws LogicException in case the output has been disabled
  520. * @throws LogicException In case the process is not started
  521. */
  522. public function getIncrementalOutput()
  523. {
  524. $this->readPipesForOutput(__FUNCTION__);
  525. $latest = stream_get_contents($this->stdout, -1, $this->incrementalOutputOffset);
  526. $this->incrementalOutputOffset = ftell($this->stdout);
  527. if (false === $latest) {
  528. return '';
  529. }
  530. return $latest;
  531. }
  532. /**
  533. * Returns an iterator to the output of the process, with the output type as keys (Process::OUT/ERR).
  534. *
  535. * @param int $flags A bit field of Process::ITER_* flags
  536. *
  537. * @throws LogicException in case the output has been disabled
  538. * @throws LogicException In case the process is not started
  539. *
  540. * @return \Generator
  541. */
  542. public function getIterator(int $flags = 0)
  543. {
  544. $this->readPipesForOutput(__FUNCTION__, false);
  545. $clearOutput = !(self::ITER_KEEP_OUTPUT & $flags);
  546. $blocking = !(self::ITER_NON_BLOCKING & $flags);
  547. $yieldOut = !(self::ITER_SKIP_OUT & $flags);
  548. $yieldErr = !(self::ITER_SKIP_ERR & $flags);
  549. while (null !== $this->callback || ($yieldOut && !feof($this->stdout)) || ($yieldErr && !feof($this->stderr))) {
  550. if ($yieldOut) {
  551. $out = stream_get_contents($this->stdout, -1, $this->incrementalOutputOffset);
  552. if (isset($out[0])) {
  553. if ($clearOutput) {
  554. $this->clearOutput();
  555. } else {
  556. $this->incrementalOutputOffset = ftell($this->stdout);
  557. }
  558. yield self::OUT => $out;
  559. }
  560. }
  561. if ($yieldErr) {
  562. $err = stream_get_contents($this->stderr, -1, $this->incrementalErrorOutputOffset);
  563. if (isset($err[0])) {
  564. if ($clearOutput) {
  565. $this->clearErrorOutput();
  566. } else {
  567. $this->incrementalErrorOutputOffset = ftell($this->stderr);
  568. }
  569. yield self::ERR => $err;
  570. }
  571. }
  572. if (!$blocking && !isset($out[0]) && !isset($err[0])) {
  573. yield self::OUT => '';
  574. }
  575. $this->checkTimeout();
  576. $this->readPipesForOutput(__FUNCTION__, $blocking);
  577. }
  578. }
  579. /**
  580. * Clears the process output.
  581. *
  582. * @return $this
  583. */
  584. public function clearOutput()
  585. {
  586. ftruncate($this->stdout, 0);
  587. fseek($this->stdout, 0);
  588. $this->incrementalOutputOffset = 0;
  589. return $this;
  590. }
  591. /**
  592. * Returns the current error output of the process (STDERR).
  593. *
  594. * @return string The process error output
  595. *
  596. * @throws LogicException in case the output has been disabled
  597. * @throws LogicException In case the process is not started
  598. */
  599. public function getErrorOutput()
  600. {
  601. $this->readPipesForOutput(__FUNCTION__);
  602. if (false === $ret = stream_get_contents($this->stderr, -1, 0)) {
  603. return '';
  604. }
  605. return $ret;
  606. }
  607. /**
  608. * Returns the errorOutput incrementally.
  609. *
  610. * In comparison with the getErrorOutput method which always return the
  611. * whole error output, this one returns the new error output since the last
  612. * call.
  613. *
  614. * @return string The process error output since the last call
  615. *
  616. * @throws LogicException in case the output has been disabled
  617. * @throws LogicException In case the process is not started
  618. */
  619. public function getIncrementalErrorOutput()
  620. {
  621. $this->readPipesForOutput(__FUNCTION__);
  622. $latest = stream_get_contents($this->stderr, -1, $this->incrementalErrorOutputOffset);
  623. $this->incrementalErrorOutputOffset = ftell($this->stderr);
  624. if (false === $latest) {
  625. return '';
  626. }
  627. return $latest;
  628. }
  629. /**
  630. * Clears the process output.
  631. *
  632. * @return $this
  633. */
  634. public function clearErrorOutput()
  635. {
  636. ftruncate($this->stderr, 0);
  637. fseek($this->stderr, 0);
  638. $this->incrementalErrorOutputOffset = 0;
  639. return $this;
  640. }
  641. /**
  642. * Returns the exit code returned by the process.
  643. *
  644. * @return int|null The exit status code, null if the Process is not terminated
  645. */
  646. public function getExitCode()
  647. {
  648. $this->updateStatus(false);
  649. return $this->exitcode;
  650. }
  651. /**
  652. * Returns a string representation for the exit code returned by the process.
  653. *
  654. * This method relies on the Unix exit code status standardization
  655. * and might not be relevant for other operating systems.
  656. *
  657. * @return string|null A string representation for the exit status code, null if the Process is not terminated
  658. *
  659. * @see http://tldp.org/LDP/abs/html/exitcodes.html
  660. * @see http://en.wikipedia.org/wiki/Unix_signal
  661. */
  662. public function getExitCodeText()
  663. {
  664. if (null === $exitcode = $this->getExitCode()) {
  665. return null;
  666. }
  667. return self::$exitCodes[$exitcode] ?? 'Unknown error';
  668. }
  669. /**
  670. * Checks if the process ended successfully.
  671. *
  672. * @return bool true if the process ended successfully, false otherwise
  673. */
  674. public function isSuccessful()
  675. {
  676. return 0 === $this->getExitCode();
  677. }
  678. /**
  679. * Returns true if the child process has been terminated by an uncaught signal.
  680. *
  681. * It always returns false on Windows.
  682. *
  683. * @return bool
  684. *
  685. * @throws LogicException In case the process is not terminated
  686. */
  687. public function hasBeenSignaled()
  688. {
  689. $this->requireProcessIsTerminated(__FUNCTION__);
  690. return $this->processInformation['signaled'];
  691. }
  692. /**
  693. * Returns the number of the signal that caused the child process to terminate its execution.
  694. *
  695. * It is only meaningful if hasBeenSignaled() returns true.
  696. *
  697. * @return int
  698. *
  699. * @throws RuntimeException In case --enable-sigchild is activated
  700. * @throws LogicException In case the process is not terminated
  701. */
  702. public function getTermSignal()
  703. {
  704. $this->requireProcessIsTerminated(__FUNCTION__);
  705. if ($this->isSigchildEnabled() && -1 === $this->processInformation['termsig']) {
  706. throw new RuntimeException('This PHP has been compiled with --enable-sigchild. Term signal can not be retrieved.');
  707. }
  708. return $this->processInformation['termsig'];
  709. }
  710. /**
  711. * Returns true if the child process has been stopped by a signal.
  712. *
  713. * It always returns false on Windows.
  714. *
  715. * @return bool
  716. *
  717. * @throws LogicException In case the process is not terminated
  718. */
  719. public function hasBeenStopped()
  720. {
  721. $this->requireProcessIsTerminated(__FUNCTION__);
  722. return $this->processInformation['stopped'];
  723. }
  724. /**
  725. * Returns the number of the signal that caused the child process to stop its execution.
  726. *
  727. * It is only meaningful if hasBeenStopped() returns true.
  728. *
  729. * @return int
  730. *
  731. * @throws LogicException In case the process is not terminated
  732. */
  733. public function getStopSignal()
  734. {
  735. $this->requireProcessIsTerminated(__FUNCTION__);
  736. return $this->processInformation['stopsig'];
  737. }
  738. /**
  739. * Checks if the process is currently running.
  740. *
  741. * @return bool true if the process is currently running, false otherwise
  742. */
  743. public function isRunning()
  744. {
  745. if (self::STATUS_STARTED !== $this->status) {
  746. return false;
  747. }
  748. $this->updateStatus(false);
  749. return $this->processInformation['running'];
  750. }
  751. /**
  752. * Checks if the process has been started with no regard to the current state.
  753. *
  754. * @return bool true if status is ready, false otherwise
  755. */
  756. public function isStarted()
  757. {
  758. return self::STATUS_READY != $this->status;
  759. }
  760. /**
  761. * Checks if the process is terminated.
  762. *
  763. * @return bool true if process is terminated, false otherwise
  764. */
  765. public function isTerminated()
  766. {
  767. $this->updateStatus(false);
  768. return self::STATUS_TERMINATED == $this->status;
  769. }
  770. /**
  771. * Gets the process status.
  772. *
  773. * The status is one of: ready, started, terminated.
  774. *
  775. * @return string The current process status
  776. */
  777. public function getStatus()
  778. {
  779. $this->updateStatus(false);
  780. return $this->status;
  781. }
  782. /**
  783. * Stops the process.
  784. *
  785. * @param int|float $timeout The timeout in seconds
  786. * @param int $signal A POSIX signal to send in case the process has not stop at timeout, default is SIGKILL (9)
  787. *
  788. * @return int|null The exit-code of the process or null if it's not running
  789. */
  790. public function stop(float $timeout = 10, int $signal = null)
  791. {
  792. $timeoutMicro = microtime(true) + $timeout;
  793. if ($this->isRunning()) {
  794. // given SIGTERM may not be defined and that "proc_terminate" uses the constant value and not the constant itself, we use the same here
  795. $this->doSignal(15, false);
  796. do {
  797. usleep(1000);
  798. } while ($this->isRunning() && microtime(true) < $timeoutMicro);
  799. if ($this->isRunning()) {
  800. // Avoid exception here: process is supposed to be running, but it might have stopped just
  801. // after this line. In any case, let's silently discard the error, we cannot do anything.
  802. $this->doSignal($signal ?: 9, false);
  803. }
  804. }
  805. if ($this->isRunning()) {
  806. if (isset($this->fallbackStatus['pid'])) {
  807. unset($this->fallbackStatus['pid']);
  808. return $this->stop(0, $signal);
  809. }
  810. $this->close();
  811. }
  812. return $this->exitcode;
  813. }
  814. /**
  815. * Adds a line to the STDOUT stream.
  816. *
  817. * @internal
  818. */
  819. public function addOutput(string $line)
  820. {
  821. $this->lastOutputTime = microtime(true);
  822. fseek($this->stdout, 0, \SEEK_END);
  823. fwrite($this->stdout, $line);
  824. fseek($this->stdout, $this->incrementalOutputOffset);
  825. }
  826. /**
  827. * Adds a line to the STDERR stream.
  828. *
  829. * @internal
  830. */
  831. public function addErrorOutput(string $line)
  832. {
  833. $this->lastOutputTime = microtime(true);
  834. fseek($this->stderr, 0, \SEEK_END);
  835. fwrite($this->stderr, $line);
  836. fseek($this->stderr, $this->incrementalErrorOutputOffset);
  837. }
  838. /**
  839. * Gets the last output time in seconds.
  840. *
  841. * @return float|null The last output time in seconds or null if it isn't started
  842. */
  843. public function getLastOutputTime(): ?float
  844. {
  845. return $this->lastOutputTime;
  846. }
  847. /**
  848. * Gets the command line to be executed.
  849. *
  850. * @return string The command to execute
  851. */
  852. public function getCommandLine()
  853. {
  854. return \is_array($this->commandline) ? implode(' ', array_map([$this, 'escapeArgument'], $this->commandline)) : $this->commandline;
  855. }
  856. /**
  857. * Gets the process timeout (max. runtime).
  858. *
  859. * @return float|null The timeout in seconds or null if it's disabled
  860. */
  861. public function getTimeout()
  862. {
  863. return $this->timeout;
  864. }
  865. /**
  866. * Gets the process idle timeout (max. time since last output).
  867. *
  868. * @return float|null The timeout in seconds or null if it's disabled
  869. */
  870. public function getIdleTimeout()
  871. {
  872. return $this->idleTimeout;
  873. }
  874. /**
  875. * Sets the process timeout (max. runtime) in seconds.
  876. *
  877. * To disable the timeout, set this value to null.
  878. *
  879. * @return $this
  880. *
  881. * @throws InvalidArgumentException if the timeout is negative
  882. */
  883. public function setTimeout(?float $timeout)
  884. {
  885. $this->timeout = $this->validateTimeout($timeout);
  886. return $this;
  887. }
  888. /**
  889. * Sets the process idle timeout (max. time since last output) in seconds.
  890. *
  891. * To disable the timeout, set this value to null.
  892. *
  893. * @return $this
  894. *
  895. * @throws LogicException if the output is disabled
  896. * @throws InvalidArgumentException if the timeout is negative
  897. */
  898. public function setIdleTimeout(?float $timeout)
  899. {
  900. if (null !== $timeout && $this->outputDisabled) {
  901. throw new LogicException('Idle timeout can not be set while the output is disabled.');
  902. }
  903. $this->idleTimeout = $this->validateTimeout($timeout);
  904. return $this;
  905. }
  906. /**
  907. * Enables or disables the TTY mode.
  908. *
  909. * @return $this
  910. *
  911. * @throws RuntimeException In case the TTY mode is not supported
  912. */
  913. public function setTty(bool $tty)
  914. {
  915. if ('\\' === \DIRECTORY_SEPARATOR && $tty) {
  916. throw new RuntimeException('TTY mode is not supported on Windows platform.');
  917. }
  918. if ($tty && !self::isTtySupported()) {
  919. throw new RuntimeException('TTY mode requires /dev/tty to be read/writable.');
  920. }
  921. $this->tty = $tty;
  922. return $this;
  923. }
  924. /**
  925. * Checks if the TTY mode is enabled.
  926. *
  927. * @return bool true if the TTY mode is enabled, false otherwise
  928. */
  929. public function isTty()
  930. {
  931. return $this->tty;
  932. }
  933. /**
  934. * Sets PTY mode.
  935. *
  936. * @return $this
  937. */
  938. public function setPty(bool $bool)
  939. {
  940. $this->pty = $bool;
  941. return $this;
  942. }
  943. /**
  944. * Returns PTY state.
  945. *
  946. * @return bool
  947. */
  948. public function isPty()
  949. {
  950. return $this->pty;
  951. }
  952. /**
  953. * Gets the working directory.
  954. *
  955. * @return string|null The current working directory or null on failure
  956. */
  957. public function getWorkingDirectory()
  958. {
  959. if (null === $this->cwd) {
  960. // getcwd() will return false if any one of the parent directories does not have
  961. // the readable or search mode set, even if the current directory does
  962. return getcwd() ?: null;
  963. }
  964. return $this->cwd;
  965. }
  966. /**
  967. * Sets the current working directory.
  968. *
  969. * @return $this
  970. */
  971. public function setWorkingDirectory(string $cwd)
  972. {
  973. $this->cwd = $cwd;
  974. return $this;
  975. }
  976. /**
  977. * Gets the environment variables.
  978. *
  979. * @return array The current environment variables
  980. */
  981. public function getEnv()
  982. {
  983. return $this->env;
  984. }
  985. /**
  986. * Sets the environment variables.
  987. *
  988. * Each environment variable value should be a string.
  989. * If it is an array, the variable is ignored.
  990. * If it is false or null, it will be removed when
  991. * env vars are otherwise inherited.
  992. *
  993. * That happens in PHP when 'argv' is registered into
  994. * the $_ENV array for instance.
  995. *
  996. * @param array $env The new environment variables
  997. *
  998. * @return $this
  999. */
  1000. public function setEnv(array $env)
  1001. {
  1002. // Process can not handle env values that are arrays
  1003. $env = array_filter($env, function ($value) {
  1004. return !\is_array($value);
  1005. });
  1006. $this->env = $env;
  1007. return $this;
  1008. }
  1009. /**
  1010. * Gets the Process input.
  1011. *
  1012. * @return resource|string|\Iterator|null The Process input
  1013. */
  1014. public function getInput()
  1015. {
  1016. return $this->input;
  1017. }
  1018. /**
  1019. * Sets the input.
  1020. *
  1021. * This content will be passed to the underlying process standard input.
  1022. *
  1023. * @param string|int|float|bool|resource|\Traversable|null $input The content
  1024. *
  1025. * @return $this
  1026. *
  1027. * @throws LogicException In case the process is running
  1028. */
  1029. public function setInput($input)
  1030. {
  1031. if ($this->isRunning()) {
  1032. throw new LogicException('Input can not be set while the process is running.');
  1033. }
  1034. $this->input = ProcessUtils::validateInput(__METHOD__, $input);
  1035. return $this;
  1036. }
  1037. /**
  1038. * Performs a check between the timeout definition and the time the process started.
  1039. *
  1040. * In case you run a background process (with the start method), you should
  1041. * trigger this method regularly to ensure the process timeout
  1042. *
  1043. * @throws ProcessTimedOutException In case the timeout was reached
  1044. */
  1045. public function checkTimeout()
  1046. {
  1047. if (self::STATUS_STARTED !== $this->status) {
  1048. return;
  1049. }
  1050. if (null !== $this->timeout && $this->timeout < microtime(true) - $this->starttime) {
  1051. $this->stop(0);
  1052. throw new ProcessTimedOutException($this, ProcessTimedOutException::TYPE_GENERAL);
  1053. }
  1054. if (null !== $this->idleTimeout && $this->idleTimeout < microtime(true) - $this->lastOutputTime) {
  1055. $this->stop(0);
  1056. throw new ProcessTimedOutException($this, ProcessTimedOutException::TYPE_IDLE);
  1057. }
  1058. }
  1059. /**
  1060. * @throws LogicException in case process is not started
  1061. */
  1062. public function getStartTime(): float
  1063. {
  1064. if (!$this->isStarted()) {
  1065. throw new LogicException('Start time is only available after process start.');
  1066. }
  1067. return $this->starttime;
  1068. }
  1069. /**
  1070. * Defines options to pass to the underlying proc_open().
  1071. *
  1072. * @see https://php.net/proc_open for the options supported by PHP.
  1073. *
  1074. * Enabling the "create_new_console" option allows a subprocess to continue
  1075. * to run after the main process exited, on both Windows and *nix
  1076. */
  1077. public function setOptions(array $options)
  1078. {
  1079. if ($this->isRunning()) {
  1080. throw new RuntimeException('Setting options while the process is running is not possible.');
  1081. }
  1082. $defaultOptions = $this->options;
  1083. $existingOptions = ['blocking_pipes', 'create_process_group', 'create_new_console'];
  1084. foreach ($options as $key => $value) {
  1085. if (!\in_array($key, $existingOptions)) {
  1086. $this->options = $defaultOptions;
  1087. throw new LogicException(sprintf('Invalid option "%s" passed to "%s()". Supported options are "%s".', $key, __METHOD__, implode('", "', $existingOptions)));
  1088. }
  1089. $this->options[$key] = $value;
  1090. }
  1091. }
  1092. /**
  1093. * Returns whether TTY is supported on the current operating system.
  1094. */
  1095. public static function isTtySupported(): bool
  1096. {
  1097. static $isTtySupported;
  1098. if (null === $isTtySupported) {
  1099. $isTtySupported = (bool) @proc_open('echo 1 >/dev/null', [['file', '/dev/tty', 'r'], ['file', '/dev/tty', 'w'], ['file', '/dev/tty', 'w']], $pipes);
  1100. }
  1101. return $isTtySupported;
  1102. }
  1103. /**
  1104. * Returns whether PTY is supported on the current operating system.
  1105. *
  1106. * @return bool
  1107. */
  1108. public static function isPtySupported()
  1109. {
  1110. static $result;
  1111. if (null !== $result) {
  1112. return $result;
  1113. }
  1114. if ('\\' === \DIRECTORY_SEPARATOR) {
  1115. return $result = false;
  1116. }
  1117. return $result = (bool) @proc_open('echo 1 >/dev/null', [['pty'], ['pty'], ['pty']], $pipes);
  1118. }
  1119. /**
  1120. * Creates the descriptors needed by the proc_open.
  1121. */
  1122. private function getDescriptors(): array
  1123. {
  1124. if ($this->input instanceof \Iterator) {
  1125. $this->input->rewind();
  1126. }
  1127. if ('\\' === \DIRECTORY_SEPARATOR) {
  1128. $this->processPipes = new WindowsPipes($this->input, !$this->outputDisabled || $this->hasCallback);
  1129. } else {
  1130. $this->processPipes = new UnixPipes($this->isTty(), $this->isPty(), $this->input, !$this->outputDisabled || $this->hasCallback);
  1131. }
  1132. return $this->processPipes->getDescriptors();
  1133. }
  1134. /**
  1135. * Builds up the callback used by wait().
  1136. *
  1137. * The callbacks adds all occurred output to the specific buffer and calls
  1138. * the user callback (if present) with the received output.
  1139. *
  1140. * @param callable|null $callback The user defined PHP callback
  1141. *
  1142. * @return \Closure A PHP closure
  1143. */
  1144. protected function buildCallback(callable $callback = null)
  1145. {
  1146. if ($this->outputDisabled) {
  1147. return function ($type, $data) use ($callback): bool {
  1148. return null !== $callback && $callback($type, $data);
  1149. };
  1150. }
  1151. $out = self::OUT;
  1152. return function ($type, $data) use ($callback, $out): bool {
  1153. if ($out == $type) {
  1154. $this->addOutput($data);
  1155. } else {
  1156. $this->addErrorOutput($data);
  1157. }
  1158. return null !== $callback && $callback($type, $data);
  1159. };
  1160. }
  1161. /**
  1162. * Updates the status of the process, reads pipes.
  1163. *
  1164. * @param bool $blocking Whether to use a blocking read call
  1165. */
  1166. protected function updateStatus(bool $blocking)
  1167. {
  1168. if (self::STATUS_STARTED !== $this->status) {
  1169. return;
  1170. }
  1171. $this->processInformation = proc_get_status($this->process);
  1172. $running = $this->processInformation['running'];
  1173. $this->readPipes($running && $blocking, '\\' !== \DIRECTORY_SEPARATOR || !$running);
  1174. if ($this->fallbackStatus && $this->isSigchildEnabled()) {
  1175. $this->processInformation = $this->fallbackStatus + $this->processInformation;
  1176. }
  1177. if (!$running) {
  1178. $this->close();
  1179. }
  1180. }
  1181. /**
  1182. * Returns whether PHP has been compiled with the '--enable-sigchild' option or not.
  1183. *
  1184. * @return bool
  1185. */
  1186. protected function isSigchildEnabled()
  1187. {
  1188. if (null !== self::$sigchild) {
  1189. return self::$sigchild;
  1190. }
  1191. if (!\function_exists('phpinfo')) {
  1192. return self::$sigchild = false;
  1193. }
  1194. ob_start();
  1195. phpinfo(\INFO_GENERAL);
  1196. return self::$sigchild = false !== strpos(ob_get_clean(), '--enable-sigchild');
  1197. }
  1198. /**
  1199. * Reads pipes for the freshest output.
  1200. *
  1201. * @param string $caller The name of the method that needs fresh outputs
  1202. * @param bool $blocking Whether to use blocking calls or not
  1203. *
  1204. * @throws LogicException in case output has been disabled or process is not started
  1205. */
  1206. private function readPipesForOutput(string $caller, bool $blocking = false)
  1207. {
  1208. if ($this->outputDisabled) {
  1209. throw new LogicException('Output has been disabled.');
  1210. }
  1211. $this->requireProcessIsStarted($caller);
  1212. $this->updateStatus($blocking);
  1213. }
  1214. /**
  1215. * Validates and returns the filtered timeout.
  1216. *
  1217. * @throws InvalidArgumentException if the given timeout is a negative number
  1218. */
  1219. private function validateTimeout(?float $timeout): ?float
  1220. {
  1221. $timeout = (float) $timeout;
  1222. if (0.0 === $timeout) {
  1223. $timeout = null;
  1224. } elseif ($timeout < 0) {
  1225. throw new InvalidArgumentException('The timeout value must be a valid positive integer or float number.');
  1226. }
  1227. return $timeout;
  1228. }
  1229. /**
  1230. * Reads pipes, executes callback.
  1231. *
  1232. * @param bool $blocking Whether to use blocking calls or not
  1233. * @param bool $close Whether to close file handles or not
  1234. */
  1235. private function readPipes(bool $blocking, bool $close)
  1236. {
  1237. $result = $this->processPipes->readAndWrite($blocking, $close);
  1238. $callback = $this->callback;
  1239. foreach ($result as $type => $data) {
  1240. if (3 !== $type) {
  1241. $callback(self::STDOUT === $type ? self::OUT : self::ERR, $data);
  1242. } elseif (!isset($this->fallbackStatus['signaled'])) {
  1243. $this->fallbackStatus['exitcode'] = (int) $data;
  1244. }
  1245. }
  1246. }
  1247. /**
  1248. * Closes process resource, closes file handles, sets the exitcode.
  1249. *
  1250. * @return int The exitcode
  1251. */
  1252. private function close(): int
  1253. {
  1254. $this->processPipes->close();
  1255. if (\is_resource($this->process)) {
  1256. proc_close($this->process);
  1257. }
  1258. $this->exitcode = $this->processInformation['exitcode'];
  1259. $this->status = self::STATUS_TERMINATED;
  1260. if (-1 === $this->exitcode) {
  1261. if ($this->processInformation['signaled'] && 0 < $this->processInformation['termsig']) {
  1262. // if process has been signaled, no exitcode but a valid termsig, apply Unix convention
  1263. $this->exitcode = 128 + $this->processInformation['termsig'];
  1264. } elseif ($this->isSigchildEnabled()) {
  1265. $this->processInformation['signaled'] = true;
  1266. $this->processInformation['termsig'] = -1;
  1267. }
  1268. }
  1269. // Free memory from self-reference callback created by buildCallback
  1270. // Doing so in other contexts like __destruct or by garbage collector is ineffective
  1271. // Now pipes are closed, so the callback is no longer necessary
  1272. $this->callback = null;
  1273. return $this->exitcode;
  1274. }
  1275. /**
  1276. * Resets data related to the latest run of the process.
  1277. */
  1278. private function resetProcessData()
  1279. {
  1280. $this->starttime = null;
  1281. $this->callback = null;
  1282. $this->exitcode = null;
  1283. $this->fallbackStatus = [];
  1284. $this->processInformation = null;
  1285. $this->stdout = fopen('php://temp/maxmemory:'.(1024 * 1024), 'w+');
  1286. $this->stderr = fopen('php://temp/maxmemory:'.(1024 * 1024), 'w+');
  1287. $this->process = null;
  1288. $this->latestSignal = null;
  1289. $this->status = self::STATUS_READY;
  1290. $this->incrementalOutputOffset = 0;
  1291. $this->incrementalErrorOutputOffset = 0;
  1292. }
  1293. /**
  1294. * Sends a POSIX signal to the process.
  1295. *
  1296. * @param int $signal A valid POSIX signal (see https://php.net/pcntl.constants)
  1297. * @param bool $throwException Whether to throw exception in case signal failed
  1298. *
  1299. * @return bool True if the signal was sent successfully, false otherwise
  1300. *
  1301. * @throws LogicException In case the process is not running
  1302. * @throws RuntimeException In case --enable-sigchild is activated and the process can't be killed
  1303. * @throws RuntimeException In case of failure
  1304. */
  1305. private function doSignal(int $signal, bool $throwException): bool
  1306. {
  1307. if (null === $pid = $this->getPid()) {
  1308. if ($throwException) {
  1309. throw new LogicException('Can not send signal on a non running process.');
  1310. }
  1311. return false;
  1312. }
  1313. if ('\\' === \DIRECTORY_SEPARATOR) {
  1314. exec(sprintf('taskkill /F /T /PID %d 2>&1', $pid), $output, $exitCode);
  1315. if ($exitCode && $this->isRunning()) {
  1316. if ($throwException) {
  1317. throw new RuntimeException(sprintf('Unable to kill the process (%s).', implode(' ', $output)));
  1318. }
  1319. return false;
  1320. }
  1321. } else {
  1322. if (!$this->isSigchildEnabled()) {
  1323. $ok = @proc_terminate($this->process, $signal);
  1324. } elseif (\function_exists('posix_kill')) {
  1325. $ok = @posix_kill($pid, $signal);
  1326. } elseif ($ok = proc_open(sprintf('kill -%d %d', $signal, $pid), [2 => ['pipe', 'w']], $pipes)) {
  1327. $ok = false === fgets($pipes[2]);
  1328. }
  1329. if (!$ok) {
  1330. if ($throwException) {
  1331. throw new RuntimeException(sprintf('Error while sending signal "%s".', $signal));
  1332. }
  1333. return false;
  1334. }
  1335. }
  1336. $this->latestSignal = $signal;
  1337. $this->fallbackStatus['signaled'] = true;
  1338. $this->fallbackStatus['exitcode'] = -1;
  1339. $this->fallbackStatus['termsig'] = $this->latestSignal;
  1340. return true;
  1341. }
  1342. private function prepareWindowsCommandLine(string $cmd, array &$env): string
  1343. {
  1344. $uid = uniqid('', true);
  1345. $varCount = 0;
  1346. $varCache = [];
  1347. $cmd = preg_replace_callback(
  1348. '/"(?:(
  1349. [^"%!^]*+
  1350. (?:
  1351. (?: !LF! | "(?:\^[%!^])?+" )
  1352. [^"%!^]*+
  1353. )++
  1354. ) | [^"]*+ )"/x',
  1355. function ($m) use (&$env, &$varCache, &$varCount, $uid) {
  1356. if (!isset($m[1])) {
  1357. return $m[0];
  1358. }
  1359. if (isset($varCache[$m[0]])) {
  1360. return $varCache[$m[0]];
  1361. }
  1362. if (false !== strpos($value = $m[1], "\0")) {
  1363. $value = str_replace("\0", '?', $value);
  1364. }
  1365. if (false === strpbrk($value, "\"%!\n")) {
  1366. return '"'.$value.'"';
  1367. }
  1368. $value = str_replace(['!LF!', '"^!"', '"^%"', '"^^"', '""'], ["\n", '!', '%', '^', '"'], $value);
  1369. $value = '"'.preg_replace('/(\\\\*)"/', '$1$1\\"', $value).'"';
  1370. $var = $uid.++$varCount;
  1371. $env[$var] = $value;
  1372. return $varCache[$m[0]] = '!'.$var.'!';
  1373. },
  1374. $cmd
  1375. );
  1376. $cmd = 'cmd /V:ON /E:ON /D /C ('.str_replace("\n", ' ', $cmd).')';
  1377. foreach ($this->processPipes->getFiles() as $offset => $filename) {
  1378. $cmd .= ' '.$offset.'>"'.$filename.'"';
  1379. }
  1380. return $cmd;
  1381. }
  1382. /**
  1383. * Ensures the process is running or terminated, throws a LogicException if the process has a not started.
  1384. *
  1385. * @throws LogicException if the process has not run
  1386. */
  1387. private function requireProcessIsStarted(string $functionName)
  1388. {
  1389. if (!$this->isStarted()) {
  1390. throw new LogicException(sprintf('Process must be started before calling "%s()".', $functionName));
  1391. }
  1392. }
  1393. /**
  1394. * Ensures the process is terminated, throws a LogicException if the process has a status different than "terminated".
  1395. *
  1396. * @throws LogicException if the process is not yet terminated
  1397. */
  1398. private function requireProcessIsTerminated(string $functionName)
  1399. {
  1400. if (!$this->isTerminated()) {
  1401. throw new LogicException(sprintf('Process must be terminated before calling "%s()".', $functionName));
  1402. }
  1403. }
  1404. /**
  1405. * Escapes a string to be used as a shell argument.
  1406. */
  1407. private function escapeArgument(?string $argument): string
  1408. {
  1409. if ('' === $argument || null === $argument) {
  1410. return '""';
  1411. }
  1412. if ('\\' !== \DIRECTORY_SEPARATOR) {
  1413. return "'".str_replace("'", "'\\''", $argument)."'";
  1414. }
  1415. if (false !== strpos($argument, "\0")) {
  1416. $argument = str_replace("\0", '?', $argument);
  1417. }
  1418. if (!preg_match('/[\/()%!^"<>&|\s]/', $argument)) {
  1419. return $argument;
  1420. }
  1421. $argument = preg_replace('/(\\\\+)$/', '$1$1', $argument);
  1422. return '"'.str_replace(['"', '^', '%', '!', "\n"], ['""', '"^^"', '"^%"', '"^!"', '!LF!'], $argument).'"';
  1423. }
  1424. private function replacePlaceholders(string $commandline, array $env)
  1425. {
  1426. return preg_replace_callback('/"\$\{:([_a-zA-Z]++[_a-zA-Z0-9]*+)\}"/', function ($matches) use ($commandline, $env) {
  1427. if (!isset($env[$matches[1]]) || false === $env[$matches[1]]) {
  1428. throw new InvalidArgumentException(sprintf('Command line is missing a value for parameter "%s": ', $matches[1]).$commandline);
  1429. }
  1430. return $this->escapeArgument($env[$matches[1]]);
  1431. }, $commandline);
  1432. }
  1433. private function getDefaultEnv(): array
  1434. {
  1435. $env = [];
  1436. foreach ($_SERVER as $k => $v) {
  1437. if (\is_string($v) && false !== $v = getenv($k)) {
  1438. $env[$k] = $v;
  1439. }
  1440. }
  1441. foreach ($_ENV as $k => $v) {
  1442. if (\is_string($v)) {
  1443. $env[$k] = $v;
  1444. }
  1445. }
  1446. return $env;
  1447. }
  1448. }