Process.php 55 KB

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