Process.php 47 KB

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