Process.php 51 KB

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