Process.php 52 KB

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