Process.php 56 KB

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