Process.php 52 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686
  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 $useFileHandles = false;
  66. /** @var PipesInterface */
  67. private $processPipes;
  68. private $latestSignal;
  69. private static $sigchild;
  70. /**
  71. * Exit codes translation table.
  72. *
  73. * User-defined errors must use exit codes in the 64-113 range.
  74. */
  75. public static $exitCodes = [
  76. 0 => 'OK',
  77. 1 => 'General error',
  78. 2 => 'Misuse of shell builtins',
  79. 126 => 'Invoked command cannot execute',
  80. 127 => 'Command not found',
  81. 128 => 'Invalid exit argument',
  82. // signals
  83. 129 => 'Hangup',
  84. 130 => 'Interrupt',
  85. 131 => 'Quit and dump core',
  86. 132 => 'Illegal instruction',
  87. 133 => 'Trace/breakpoint trap',
  88. 134 => 'Process aborted',
  89. 135 => 'Bus error: "access to undefined portion of memory object"',
  90. 136 => 'Floating point exception: "erroneous arithmetic operation"',
  91. 137 => 'Kill (terminate immediately)',
  92. 138 => 'User-defined 1',
  93. 139 => 'Segmentation violation',
  94. 140 => 'User-defined 2',
  95. 141 => 'Write to pipe with no one reading',
  96. 142 => 'Signal raised by alarm',
  97. 143 => 'Termination (request to terminate)',
  98. // 144 - not defined
  99. 145 => 'Child process terminated, stopped (or continued*)',
  100. 146 => 'Continue if stopped',
  101. 147 => 'Stop executing temporarily',
  102. 148 => 'Terminal stop signal',
  103. 149 => 'Background process attempting to read from tty ("in")',
  104. 150 => 'Background process attempting to write to tty ("out")',
  105. 151 => 'Urgent data available on socket',
  106. 152 => 'CPU time limit exceeded',
  107. 153 => 'File size limit exceeded',
  108. 154 => 'Signal raised by timer counting virtual time: "virtual timer expired"',
  109. 155 => 'Profiling timer expired',
  110. // 156 - not defined
  111. 157 => 'Pollable event',
  112. // 158 - not defined
  113. 159 => 'Bad syscall',
  114. ];
  115. /**
  116. * @param array $command The command to run and its arguments listed as separate entries
  117. * @param string|null $cwd The working directory or null to use the working dir of the current PHP process
  118. * @param array|null $env The environment variables or null to use the same environment as the current PHP process
  119. * @param mixed $input The input as stream resource, scalar or \Traversable, or null for no input
  120. * @param int|float|null $timeout The timeout in seconds or null to disable
  121. *
  122. * @throws LogicException When proc_open is not installed
  123. */
  124. public function __construct($command, string $cwd = null, array $env = null, $input = null, ?float $timeout = 60)
  125. {
  126. if (!\function_exists('proc_open')) {
  127. throw new LogicException('The Process class relies on proc_open, which is not available on your PHP installation.');
  128. }
  129. if (!\is_array($command)) {
  130. @trigger_error(sprintf('Passing a command as string when creating a "%s" instance is deprecated since Symfony 4.2, pass it as an array of its arguments instead, or use the "Process::fromShellCommandline()" constructor if you need features provided by the shell.', __CLASS__), \E_USER_DEPRECATED);
  131. }
  132. $this->commandline = $command;
  133. $this->cwd = $cwd;
  134. // on Windows, if the cwd changed via chdir(), proc_open defaults to the dir where PHP was started
  135. // on Gnu/Linux, PHP builds with --enable-maintainer-zts are also affected
  136. // @see : https://bugs.php.net/51800
  137. // @see : https://bugs.php.net/50524
  138. if (null === $this->cwd && (\defined('ZEND_THREAD_SAFE') || '\\' === \DIRECTORY_SEPARATOR)) {
  139. $this->cwd = getcwd();
  140. }
  141. if (null !== $env) {
  142. $this->setEnv($env);
  143. }
  144. $this->setInput($input);
  145. $this->setTimeout($timeout);
  146. $this->useFileHandles = '\\' === \DIRECTORY_SEPARATOR;
  147. $this->pty = false;
  148. }
  149. /**
  150. * Creates a Process instance as a command-line to be run in a shell wrapper.
  151. *
  152. * Command-lines are parsed by the shell of your OS (/bin/sh on Unix-like, cmd.exe on Windows.)
  153. * This allows using e.g. pipes or conditional execution. In this mode, signals are sent to the
  154. * shell wrapper and not to your commands.
  155. *
  156. * In order to inject dynamic values into command-lines, we strongly recommend using placeholders.
  157. * This will save escaping values, which is not portable nor secure anyway:
  158. *
  159. * $process = Process::fromShellCommandline('my_command "$MY_VAR"');
  160. * $process->run(null, ['MY_VAR' => $theValue]);
  161. *
  162. * @param string $command The command line to pass to the shell of the OS
  163. * @param string|null $cwd The working directory or null to use the working dir of the current PHP process
  164. * @param array|null $env The environment variables or null to use the same environment as the current PHP process
  165. * @param mixed $input The input as stream resource, scalar or \Traversable, or null for no input
  166. * @param int|float|null $timeout The timeout in seconds or null to disable
  167. *
  168. * @return static
  169. *
  170. * @throws LogicException When proc_open is not installed
  171. */
  172. public static function fromShellCommandline(string $command, string $cwd = null, array $env = null, $input = null, ?float $timeout = 60)
  173. {
  174. $process = new static([], $cwd, $env, $input, $timeout);
  175. $process->commandline = $command;
  176. return $process;
  177. }
  178. public function __sleep()
  179. {
  180. throw new \BadMethodCallException('Cannot serialize '.__CLASS__);
  181. }
  182. public function __wakeup()
  183. {
  184. throw new \BadMethodCallException('Cannot unserialize '.__CLASS__);
  185. }
  186. public function __destruct()
  187. {
  188. $this->stop(0);
  189. }
  190. public function __clone()
  191. {
  192. $this->resetProcessData();
  193. }
  194. /**
  195. * Runs the process.
  196. *
  197. * The callback receives the type of output (out or err) and
  198. * some bytes from the output in real-time. It allows to have feedback
  199. * from the independent process during execution.
  200. *
  201. * The STDOUT and STDERR are also available after the process is finished
  202. * via the getOutput() and getErrorOutput() methods.
  203. *
  204. * @param callable|null $callback A PHP callback to run whenever there is some
  205. * output available on STDOUT or STDERR
  206. *
  207. * @return int The exit status code
  208. *
  209. * @throws RuntimeException When process can't be launched
  210. * @throws RuntimeException When process is already running
  211. * @throws ProcessTimedOutException When process timed out
  212. * @throws ProcessSignaledException When process stopped after receiving signal
  213. * @throws LogicException In case a callback is provided and output has been disabled
  214. *
  215. * @final
  216. */
  217. public function run(callable $callback = null, array $env = []): int
  218. {
  219. $this->start($callback, $env);
  220. return $this->wait();
  221. }
  222. /**
  223. * Runs the process.
  224. *
  225. * This is identical to run() except that an exception is thrown if the process
  226. * exits with a non-zero exit code.
  227. *
  228. * @return $this
  229. *
  230. * @throws ProcessFailedException if the process didn't terminate successfully
  231. *
  232. * @final
  233. */
  234. public function mustRun(callable $callback = null, array $env = []): self
  235. {
  236. if (0 !== $this->run($callback, $env)) {
  237. throw new ProcessFailedException($this);
  238. }
  239. return $this;
  240. }
  241. /**
  242. * Starts the process and returns after writing the input to STDIN.
  243. *
  244. * This method blocks until all STDIN data is sent to the process then it
  245. * returns while the process runs in the background.
  246. *
  247. * The termination of the process can be awaited with wait().
  248. *
  249. * The callback receives the type of output (out or err) and some bytes from
  250. * the output in real-time while writing the standard input to the process.
  251. * It allows to have feedback from the independent process during execution.
  252. *
  253. * @param callable|null $callback A PHP callback to run whenever there is some
  254. * output available on STDOUT or STDERR
  255. *
  256. * @throws RuntimeException When process can't be launched
  257. * @throws RuntimeException When process is already running
  258. * @throws LogicException In case a callback is provided and output has been disabled
  259. */
  260. public function start(callable $callback = null, array $env = [])
  261. {
  262. if ($this->isRunning()) {
  263. throw new RuntimeException('Process is already running.');
  264. }
  265. $this->resetProcessData();
  266. $this->starttime = $this->lastOutputTime = microtime(true);
  267. $this->callback = $this->buildCallback($callback);
  268. $this->hasCallback = null !== $callback;
  269. $descriptors = $this->getDescriptors();
  270. if ($this->env) {
  271. $env += $this->env;
  272. }
  273. $env += $this->getDefaultEnv();
  274. if (\is_array($commandline = $this->commandline)) {
  275. $commandline = implode(' ', array_map([$this, 'escapeArgument'], $commandline));
  276. if ('\\' !== \DIRECTORY_SEPARATOR) {
  277. // exec is mandatory to deal with sending a signal to the process
  278. $commandline = 'exec '.$commandline;
  279. }
  280. } else {
  281. $commandline = $this->replacePlaceholders($commandline, $env);
  282. }
  283. $options = ['suppress_errors' => true];
  284. if ('\\' === \DIRECTORY_SEPARATOR) {
  285. $options['bypass_shell'] = true;
  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, $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($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($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($timeout = 10, $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. * Sets the command line to be executed.
  858. *
  859. * @param string|array $commandline The command to execute
  860. *
  861. * @return $this
  862. *
  863. * @deprecated since Symfony 4.2.
  864. */
  865. public function setCommandLine($commandline)
  866. {
  867. @trigger_error(sprintf('The "%s()" method is deprecated since Symfony 4.2.', __METHOD__), \E_USER_DEPRECATED);
  868. $this->commandline = $commandline;
  869. return $this;
  870. }
  871. /**
  872. * Gets the process timeout (max. runtime).
  873. *
  874. * @return float|null The timeout in seconds or null if it's disabled
  875. */
  876. public function getTimeout()
  877. {
  878. return $this->timeout;
  879. }
  880. /**
  881. * Gets the process idle timeout (max. time since last output).
  882. *
  883. * @return float|null The timeout in seconds or null if it's disabled
  884. */
  885. public function getIdleTimeout()
  886. {
  887. return $this->idleTimeout;
  888. }
  889. /**
  890. * Sets the process timeout (max. runtime) in seconds.
  891. *
  892. * To disable the timeout, set this value to null.
  893. *
  894. * @param int|float|null $timeout The timeout in seconds
  895. *
  896. * @return $this
  897. *
  898. * @throws InvalidArgumentException if the timeout is negative
  899. */
  900. public function setTimeout($timeout)
  901. {
  902. $this->timeout = $this->validateTimeout($timeout);
  903. return $this;
  904. }
  905. /**
  906. * Sets the process idle timeout (max. time since last output).
  907. *
  908. * To disable the timeout, set this value to null.
  909. *
  910. * @param int|float|null $timeout The timeout in seconds
  911. *
  912. * @return $this
  913. *
  914. * @throws LogicException if the output is disabled
  915. * @throws InvalidArgumentException if the timeout is negative
  916. */
  917. public function setIdleTimeout($timeout)
  918. {
  919. if (null !== $timeout && $this->outputDisabled) {
  920. throw new LogicException('Idle timeout can not be set while the output is disabled.');
  921. }
  922. $this->idleTimeout = $this->validateTimeout($timeout);
  923. return $this;
  924. }
  925. /**
  926. * Enables or disables the TTY mode.
  927. *
  928. * @param bool $tty True to enabled and false to disable
  929. *
  930. * @return $this
  931. *
  932. * @throws RuntimeException In case the TTY mode is not supported
  933. */
  934. public function setTty($tty)
  935. {
  936. if ('\\' === \DIRECTORY_SEPARATOR && $tty) {
  937. throw new RuntimeException('TTY mode is not supported on Windows platform.');
  938. }
  939. if ($tty && !self::isTtySupported()) {
  940. throw new RuntimeException('TTY mode requires /dev/tty to be read/writable.');
  941. }
  942. $this->tty = (bool) $tty;
  943. return $this;
  944. }
  945. /**
  946. * Checks if the TTY mode is enabled.
  947. *
  948. * @return bool true if the TTY mode is enabled, false otherwise
  949. */
  950. public function isTty()
  951. {
  952. return $this->tty;
  953. }
  954. /**
  955. * Sets PTY mode.
  956. *
  957. * @param bool $bool
  958. *
  959. * @return $this
  960. */
  961. public function setPty($bool)
  962. {
  963. $this->pty = (bool) $bool;
  964. return $this;
  965. }
  966. /**
  967. * Returns PTY state.
  968. *
  969. * @return bool
  970. */
  971. public function isPty()
  972. {
  973. return $this->pty;
  974. }
  975. /**
  976. * Gets the working directory.
  977. *
  978. * @return string|null The current working directory or null on failure
  979. */
  980. public function getWorkingDirectory()
  981. {
  982. if (null === $this->cwd) {
  983. // getcwd() will return false if any one of the parent directories does not have
  984. // the readable or search mode set, even if the current directory does
  985. return getcwd() ?: null;
  986. }
  987. return $this->cwd;
  988. }
  989. /**
  990. * Sets the current working directory.
  991. *
  992. * @param string $cwd The new working directory
  993. *
  994. * @return $this
  995. */
  996. public function setWorkingDirectory($cwd)
  997. {
  998. $this->cwd = $cwd;
  999. return $this;
  1000. }
  1001. /**
  1002. * Gets the environment variables.
  1003. *
  1004. * @return array The current environment variables
  1005. */
  1006. public function getEnv()
  1007. {
  1008. return $this->env;
  1009. }
  1010. /**
  1011. * Sets the environment variables.
  1012. *
  1013. * Each environment variable value should be a string.
  1014. * If it is an array, the variable is ignored.
  1015. * If it is false or null, it will be removed when
  1016. * env vars are otherwise inherited.
  1017. *
  1018. * That happens in PHP when 'argv' is registered into
  1019. * the $_ENV array for instance.
  1020. *
  1021. * @param array $env The new environment variables
  1022. *
  1023. * @return $this
  1024. */
  1025. public function setEnv(array $env)
  1026. {
  1027. // Process can not handle env values that are arrays
  1028. $env = array_filter($env, function ($value) {
  1029. return !\is_array($value);
  1030. });
  1031. $this->env = $env;
  1032. return $this;
  1033. }
  1034. /**
  1035. * Gets the Process input.
  1036. *
  1037. * @return resource|string|\Iterator|null The Process input
  1038. */
  1039. public function getInput()
  1040. {
  1041. return $this->input;
  1042. }
  1043. /**
  1044. * Sets the input.
  1045. *
  1046. * This content will be passed to the underlying process standard input.
  1047. *
  1048. * @param string|int|float|bool|resource|\Traversable|null $input The content
  1049. *
  1050. * @return $this
  1051. *
  1052. * @throws LogicException In case the process is running
  1053. */
  1054. public function setInput($input)
  1055. {
  1056. if ($this->isRunning()) {
  1057. throw new LogicException('Input can not be set while the process is running.');
  1058. }
  1059. $this->input = ProcessUtils::validateInput(__METHOD__, $input);
  1060. return $this;
  1061. }
  1062. /**
  1063. * Sets whether environment variables will be inherited or not.
  1064. *
  1065. * @param bool $inheritEnv
  1066. *
  1067. * @return $this
  1068. *
  1069. * @deprecated since Symfony 4.4, env variables are always inherited
  1070. */
  1071. public function inheritEnvironmentVariables($inheritEnv = true)
  1072. {
  1073. @trigger_error(sprintf('The "%s()" method is deprecated since Symfony 4.4, env variables are always inherited.', __METHOD__), \E_USER_DEPRECATED);
  1074. if (!$inheritEnv) {
  1075. throw new InvalidArgumentException('Not inheriting environment variables is not supported.');
  1076. }
  1077. return $this;
  1078. }
  1079. /**
  1080. * Performs a check between the timeout definition and the time the process started.
  1081. *
  1082. * In case you run a background process (with the start method), you should
  1083. * trigger this method regularly to ensure the process timeout
  1084. *
  1085. * @throws ProcessTimedOutException In case the timeout was reached
  1086. */
  1087. public function checkTimeout()
  1088. {
  1089. if (self::STATUS_STARTED !== $this->status) {
  1090. return;
  1091. }
  1092. if (null !== $this->timeout && $this->timeout < microtime(true) - $this->starttime) {
  1093. $this->stop(0);
  1094. throw new ProcessTimedOutException($this, ProcessTimedOutException::TYPE_GENERAL);
  1095. }
  1096. if (null !== $this->idleTimeout && $this->idleTimeout < microtime(true) - $this->lastOutputTime) {
  1097. $this->stop(0);
  1098. throw new ProcessTimedOutException($this, ProcessTimedOutException::TYPE_IDLE);
  1099. }
  1100. }
  1101. /**
  1102. * Returns whether TTY is supported on the current operating system.
  1103. */
  1104. public static function isTtySupported(): bool
  1105. {
  1106. static $isTtySupported;
  1107. if (null === $isTtySupported) {
  1108. $isTtySupported = (bool) @proc_open('echo 1 >/dev/null', [['file', '/dev/tty', 'r'], ['file', '/dev/tty', 'w'], ['file', '/dev/tty', 'w']], $pipes);
  1109. }
  1110. return $isTtySupported;
  1111. }
  1112. /**
  1113. * Returns whether PTY is supported on the current operating system.
  1114. *
  1115. * @return bool
  1116. */
  1117. public static function isPtySupported()
  1118. {
  1119. static $result;
  1120. if (null !== $result) {
  1121. return $result;
  1122. }
  1123. if ('\\' === \DIRECTORY_SEPARATOR) {
  1124. return $result = false;
  1125. }
  1126. return $result = (bool) @proc_open('echo 1 >/dev/null', [['pty'], ['pty'], ['pty']], $pipes);
  1127. }
  1128. /**
  1129. * Creates the descriptors needed by the proc_open.
  1130. */
  1131. private function getDescriptors(): array
  1132. {
  1133. if ($this->input instanceof \Iterator) {
  1134. $this->input->rewind();
  1135. }
  1136. if ('\\' === \DIRECTORY_SEPARATOR) {
  1137. $this->processPipes = new WindowsPipes($this->input, !$this->outputDisabled || $this->hasCallback);
  1138. } else {
  1139. $this->processPipes = new UnixPipes($this->isTty(), $this->isPty(), $this->input, !$this->outputDisabled || $this->hasCallback);
  1140. }
  1141. return $this->processPipes->getDescriptors();
  1142. }
  1143. /**
  1144. * Builds up the callback used by wait().
  1145. *
  1146. * The callbacks adds all occurred output to the specific buffer and calls
  1147. * the user callback (if present) with the received output.
  1148. *
  1149. * @param callable|null $callback The user defined PHP callback
  1150. *
  1151. * @return \Closure A PHP closure
  1152. */
  1153. protected function buildCallback(callable $callback = null)
  1154. {
  1155. if ($this->outputDisabled) {
  1156. return function ($type, $data) use ($callback): bool {
  1157. return null !== $callback && $callback($type, $data);
  1158. };
  1159. }
  1160. $out = self::OUT;
  1161. return function ($type, $data) use ($callback, $out): bool {
  1162. if ($out == $type) {
  1163. $this->addOutput($data);
  1164. } else {
  1165. $this->addErrorOutput($data);
  1166. }
  1167. return null !== $callback && $callback($type, $data);
  1168. };
  1169. }
  1170. /**
  1171. * Updates the status of the process, reads pipes.
  1172. *
  1173. * @param bool $blocking Whether to use a blocking read call
  1174. */
  1175. protected function updateStatus($blocking)
  1176. {
  1177. if (self::STATUS_STARTED !== $this->status) {
  1178. return;
  1179. }
  1180. $this->processInformation = proc_get_status($this->process);
  1181. $running = $this->processInformation['running'];
  1182. $this->readPipes($running && $blocking, '\\' !== \DIRECTORY_SEPARATOR || !$running);
  1183. if ($this->fallbackStatus && $this->isSigchildEnabled()) {
  1184. $this->processInformation = $this->fallbackStatus + $this->processInformation;
  1185. }
  1186. if (!$running) {
  1187. $this->close();
  1188. }
  1189. }
  1190. /**
  1191. * Returns whether PHP has been compiled with the '--enable-sigchild' option or not.
  1192. *
  1193. * @return bool
  1194. */
  1195. protected function isSigchildEnabled()
  1196. {
  1197. if (null !== self::$sigchild) {
  1198. return self::$sigchild;
  1199. }
  1200. if (!\function_exists('phpinfo')) {
  1201. return self::$sigchild = false;
  1202. }
  1203. ob_start();
  1204. phpinfo(\INFO_GENERAL);
  1205. return self::$sigchild = false !== strpos(ob_get_clean(), '--enable-sigchild');
  1206. }
  1207. /**
  1208. * Reads pipes for the freshest output.
  1209. *
  1210. * @param string $caller The name of the method that needs fresh outputs
  1211. * @param bool $blocking Whether to use blocking calls or not
  1212. *
  1213. * @throws LogicException in case output has been disabled or process is not started
  1214. */
  1215. private function readPipesForOutput(string $caller, bool $blocking = false)
  1216. {
  1217. if ($this->outputDisabled) {
  1218. throw new LogicException('Output has been disabled.');
  1219. }
  1220. $this->requireProcessIsStarted($caller);
  1221. $this->updateStatus($blocking);
  1222. }
  1223. /**
  1224. * Validates and returns the filtered timeout.
  1225. *
  1226. * @throws InvalidArgumentException if the given timeout is a negative number
  1227. */
  1228. private function validateTimeout(?float $timeout): ?float
  1229. {
  1230. $timeout = (float) $timeout;
  1231. if (0.0 === $timeout) {
  1232. $timeout = null;
  1233. } elseif ($timeout < 0) {
  1234. throw new InvalidArgumentException('The timeout value must be a valid positive integer or float number.');
  1235. }
  1236. return $timeout;
  1237. }
  1238. /**
  1239. * Reads pipes, executes callback.
  1240. *
  1241. * @param bool $blocking Whether to use blocking calls or not
  1242. * @param bool $close Whether to close file handles or not
  1243. */
  1244. private function readPipes(bool $blocking, bool $close)
  1245. {
  1246. $result = $this->processPipes->readAndWrite($blocking, $close);
  1247. $callback = $this->callback;
  1248. foreach ($result as $type => $data) {
  1249. if (3 !== $type) {
  1250. $callback(self::STDOUT === $type ? self::OUT : self::ERR, $data);
  1251. } elseif (!isset($this->fallbackStatus['signaled'])) {
  1252. $this->fallbackStatus['exitcode'] = (int) $data;
  1253. }
  1254. }
  1255. }
  1256. /**
  1257. * Closes process resource, closes file handles, sets the exitcode.
  1258. *
  1259. * @return int The exitcode
  1260. */
  1261. private function close(): int
  1262. {
  1263. $this->processPipes->close();
  1264. if (\is_resource($this->process)) {
  1265. proc_close($this->process);
  1266. }
  1267. $this->exitcode = $this->processInformation['exitcode'];
  1268. $this->status = self::STATUS_TERMINATED;
  1269. if (-1 === $this->exitcode) {
  1270. if ($this->processInformation['signaled'] && 0 < $this->processInformation['termsig']) {
  1271. // if process has been signaled, no exitcode but a valid termsig, apply Unix convention
  1272. $this->exitcode = 128 + $this->processInformation['termsig'];
  1273. } elseif ($this->isSigchildEnabled()) {
  1274. $this->processInformation['signaled'] = true;
  1275. $this->processInformation['termsig'] = -1;
  1276. }
  1277. }
  1278. // Free memory from self-reference callback created by buildCallback
  1279. // Doing so in other contexts like __destruct or by garbage collector is ineffective
  1280. // Now pipes are closed, so the callback is no longer necessary
  1281. $this->callback = null;
  1282. return $this->exitcode;
  1283. }
  1284. /**
  1285. * Resets data related to the latest run of the process.
  1286. */
  1287. private function resetProcessData()
  1288. {
  1289. $this->starttime = null;
  1290. $this->callback = null;
  1291. $this->exitcode = null;
  1292. $this->fallbackStatus = [];
  1293. $this->processInformation = null;
  1294. $this->stdout = fopen('php://temp/maxmemory:'.(1024 * 1024), 'w+');
  1295. $this->stderr = fopen('php://temp/maxmemory:'.(1024 * 1024), 'w+');
  1296. $this->process = null;
  1297. $this->latestSignal = null;
  1298. $this->status = self::STATUS_READY;
  1299. $this->incrementalOutputOffset = 0;
  1300. $this->incrementalErrorOutputOffset = 0;
  1301. }
  1302. /**
  1303. * Sends a POSIX signal to the process.
  1304. *
  1305. * @param int $signal A valid POSIX signal (see https://php.net/pcntl.constants)
  1306. * @param bool $throwException Whether to throw exception in case signal failed
  1307. *
  1308. * @return bool True if the signal was sent successfully, false otherwise
  1309. *
  1310. * @throws LogicException In case the process is not running
  1311. * @throws RuntimeException In case --enable-sigchild is activated and the process can't be killed
  1312. * @throws RuntimeException In case of failure
  1313. */
  1314. private function doSignal(int $signal, bool $throwException): bool
  1315. {
  1316. if (null === $pid = $this->getPid()) {
  1317. if ($throwException) {
  1318. throw new LogicException('Can not send signal on a non running process.');
  1319. }
  1320. return false;
  1321. }
  1322. if ('\\' === \DIRECTORY_SEPARATOR) {
  1323. exec(sprintf('taskkill /F /T /PID %d 2>&1', $pid), $output, $exitCode);
  1324. if ($exitCode && $this->isRunning()) {
  1325. if ($throwException) {
  1326. throw new RuntimeException(sprintf('Unable to kill the process (%s).', implode(' ', $output)));
  1327. }
  1328. return false;
  1329. }
  1330. } else {
  1331. if (!$this->isSigchildEnabled()) {
  1332. $ok = @proc_terminate($this->process, $signal);
  1333. } elseif (\function_exists('posix_kill')) {
  1334. $ok = @posix_kill($pid, $signal);
  1335. } elseif ($ok = proc_open(sprintf('kill -%d %d', $signal, $pid), [2 => ['pipe', 'w']], $pipes)) {
  1336. $ok = false === fgets($pipes[2]);
  1337. }
  1338. if (!$ok) {
  1339. if ($throwException) {
  1340. throw new RuntimeException(sprintf('Error while sending signal "%s".', $signal));
  1341. }
  1342. return false;
  1343. }
  1344. }
  1345. $this->latestSignal = $signal;
  1346. $this->fallbackStatus['signaled'] = true;
  1347. $this->fallbackStatus['exitcode'] = -1;
  1348. $this->fallbackStatus['termsig'] = $this->latestSignal;
  1349. return true;
  1350. }
  1351. private function prepareWindowsCommandLine(string $cmd, array &$env): string
  1352. {
  1353. $uid = uniqid('', true);
  1354. $varCount = 0;
  1355. $varCache = [];
  1356. $cmd = preg_replace_callback(
  1357. '/"(?:(
  1358. [^"%!^]*+
  1359. (?:
  1360. (?: !LF! | "(?:\^[%!^])?+" )
  1361. [^"%!^]*+
  1362. )++
  1363. ) | [^"]*+ )"/x',
  1364. function ($m) use (&$env, &$varCache, &$varCount, $uid) {
  1365. if (!isset($m[1])) {
  1366. return $m[0];
  1367. }
  1368. if (isset($varCache[$m[0]])) {
  1369. return $varCache[$m[0]];
  1370. }
  1371. if (false !== strpos($value = $m[1], "\0")) {
  1372. $value = str_replace("\0", '?', $value);
  1373. }
  1374. if (false === strpbrk($value, "\"%!\n")) {
  1375. return '"'.$value.'"';
  1376. }
  1377. $value = str_replace(['!LF!', '"^!"', '"^%"', '"^^"', '""'], ["\n", '!', '%', '^', '"'], $value);
  1378. $value = '"'.preg_replace('/(\\\\*)"/', '$1$1\\"', $value).'"';
  1379. $var = $uid.++$varCount;
  1380. $env[$var] = $value;
  1381. return $varCache[$m[0]] = '!'.$var.'!';
  1382. },
  1383. $cmd
  1384. );
  1385. $cmd = 'cmd /V:ON /E:ON /D /C ('.str_replace("\n", ' ', $cmd).')';
  1386. foreach ($this->processPipes->getFiles() as $offset => $filename) {
  1387. $cmd .= ' '.$offset.'>"'.$filename.'"';
  1388. }
  1389. return $cmd;
  1390. }
  1391. /**
  1392. * Ensures the process is running or terminated, throws a LogicException if the process has a not started.
  1393. *
  1394. * @throws LogicException if the process has not run
  1395. */
  1396. private function requireProcessIsStarted(string $functionName)
  1397. {
  1398. if (!$this->isStarted()) {
  1399. throw new LogicException(sprintf('Process must be started before calling "%s()".', $functionName));
  1400. }
  1401. }
  1402. /**
  1403. * Ensures the process is terminated, throws a LogicException if the process has a status different than "terminated".
  1404. *
  1405. * @throws LogicException if the process is not yet terminated
  1406. */
  1407. private function requireProcessIsTerminated(string $functionName)
  1408. {
  1409. if (!$this->isTerminated()) {
  1410. throw new LogicException(sprintf('Process must be terminated before calling "%s()".', $functionName));
  1411. }
  1412. }
  1413. /**
  1414. * Escapes a string to be used as a shell argument.
  1415. */
  1416. private function escapeArgument(?string $argument): string
  1417. {
  1418. if ('' === $argument || null === $argument) {
  1419. return '""';
  1420. }
  1421. if ('\\' !== \DIRECTORY_SEPARATOR) {
  1422. return "'".str_replace("'", "'\\''", $argument)."'";
  1423. }
  1424. if (false !== strpos($argument, "\0")) {
  1425. $argument = str_replace("\0", '?', $argument);
  1426. }
  1427. if (!preg_match('/[\/()%!^"<>&|\s]/', $argument)) {
  1428. return $argument;
  1429. }
  1430. $argument = preg_replace('/(\\\\+)$/', '$1$1', $argument);
  1431. return '"'.str_replace(['"', '^', '%', '!', "\n"], ['""', '"^^"', '"^%"', '"^!"', '!LF!'], $argument).'"';
  1432. }
  1433. private function replacePlaceholders(string $commandline, array $env)
  1434. {
  1435. return preg_replace_callback('/"\$\{:([_a-zA-Z]++[_a-zA-Z0-9]*+)\}"/', function ($matches) use ($commandline, $env) {
  1436. if (!isset($env[$matches[1]]) || false === $env[$matches[1]]) {
  1437. throw new InvalidArgumentException(sprintf('Command line is missing a value for parameter "%s": ', $matches[1]).$commandline);
  1438. }
  1439. return $this->escapeArgument($env[$matches[1]]);
  1440. }, $commandline);
  1441. }
  1442. private function getDefaultEnv(): array
  1443. {
  1444. $env = [];
  1445. foreach ($_SERVER as $k => $v) {
  1446. if (\is_string($v) && false !== $v = getenv($k)) {
  1447. $env[$k] = $v;
  1448. }
  1449. }
  1450. foreach ($_ENV as $k => $v) {
  1451. if (\is_string($v)) {
  1452. $env[$k] = $v;
  1453. }
  1454. }
  1455. return $env;
  1456. }
  1457. }