XdebugHandler.php 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345
  1. <?php
  2. /*
  3. * This file is part of Composer.
  4. *
  5. * (c) Nils Adermann <naderman@naderman.de>
  6. * Jordi Boggiano <j.boggiano@seld.be>
  7. *
  8. * For the full copyright and license information, please view the LICENSE
  9. * file that was distributed with this source code.
  10. */
  11. namespace Composer;
  12. use Symfony\Component\Console\Output\OutputInterface;
  13. /**
  14. * @author John Stevenson <john-stevenson@blueyonder.co.uk>
  15. */
  16. class XdebugHandler
  17. {
  18. const ENV_ALLOW = 'COMPOSER_ALLOW_XDEBUG';
  19. const RESTART_ID = 'internal';
  20. private $output;
  21. private $loaded;
  22. private $envScanDir;
  23. /**
  24. * Constructor
  25. */
  26. public function __construct(OutputInterface $output)
  27. {
  28. $this->output = $output;
  29. $this->loaded = extension_loaded('xdebug');
  30. $this->envScanDir = getenv('PHP_INI_SCAN_DIR');
  31. }
  32. /**
  33. * Checks if xdebug is loaded and composer needs to be restarted
  34. *
  35. * If so, then a tmp ini is created with the xdebug ini entry commented out.
  36. * If additional inis have been loaded, these are combined into the tmp ini
  37. * and PHP_INI_SCAN_DIR is set to an empty value.
  38. *
  39. * This behaviour can be disabled by setting the COMPOSER_ALLOW_XDEBUG
  40. * environment variable to 1. This variable is used internally so that the
  41. * restarted process is created only once and PHP_INI_SCAN_DIR can be
  42. * restored to its original value.
  43. */
  44. public function check()
  45. {
  46. $args = explode('|', strval(getenv(self::ENV_ALLOW)), 2);
  47. if ($this->needsRestart($args[0])) {
  48. $this->prepareRestart($command) && $this->restart($command);
  49. return;
  50. }
  51. // Restore environment variables if we are restarting
  52. if (self::RESTART_ID === $args[0]) {
  53. putenv(self::ENV_ALLOW);
  54. if (false !== $this->envScanDir) {
  55. // $args[1] contains the original value
  56. if (isset($args[1])) {
  57. putenv('PHP_INI_SCAN_DIR='.$args[1]);
  58. } else {
  59. putenv('PHP_INI_SCAN_DIR');
  60. }
  61. }
  62. }
  63. }
  64. /**
  65. * Executes the restarted command
  66. *
  67. * @param string $command
  68. */
  69. protected function restart($command)
  70. {
  71. passthru($command, $exitCode);
  72. exit($exitCode);
  73. }
  74. /**
  75. * Returns true if a restart is needed
  76. *
  77. * @param string $allow Environment value
  78. *
  79. * @return bool
  80. */
  81. private function needsRestart($allow)
  82. {
  83. if (PHP_SAPI !== 'cli' || !defined('PHP_BINARY')) {
  84. return false;
  85. }
  86. return empty($allow) && $this->loaded;
  87. }
  88. /**
  89. * Returns true if everything was written for the restart
  90. *
  91. * If any of the following fails (however unlikely) we must return false to
  92. * stop potential recursion:
  93. * - tmp ini file creation
  94. * - environment variable creation
  95. *
  96. * @param null|string $command The command to run, set by method
  97. *
  98. * @return bool
  99. */
  100. private function prepareRestart(&$command)
  101. {
  102. $iniFiles = array();
  103. if ($loadedIni = php_ini_loaded_file()) {
  104. $iniFiles[] = $loadedIni;
  105. }
  106. $additional = $this->getAdditionalInis($iniFiles, $replace);
  107. $tmpIni = $this->writeTmpIni($iniFiles, $replace);
  108. if (false !== $tmpIni) {
  109. $command = $this->getCommand($tmpIni);
  110. return $this->setEnvironment($additional);
  111. }
  112. return false;
  113. }
  114. /**
  115. * Writes the tmp ini file and returns its filename
  116. *
  117. * The filename is passed as the -c option when the process restarts. On
  118. * non-Windows platforms the filename is prefixed with the username to
  119. * avoid any multi-user conflict. Windows always uses the user temp dir.
  120. *
  121. * @param array $iniFiles The php.ini locations
  122. * @param bool $replace Whether we need to modify the files
  123. *
  124. * @return bool|string False if the tmp ini could not be created
  125. */
  126. private function writeTmpIni(array $iniFiles, $replace)
  127. {
  128. if (empty($iniFiles)) {
  129. // Unlikely, maybe xdebug was loaded through a command line option.
  130. return '';
  131. }
  132. if (function_exists('posix_getpwuid')) {
  133. $user = posix_getpwuid(posix_getuid());
  134. }
  135. $prefix = !empty($user) ? $user['name'].'-' : '';
  136. $tmpIni = sys_get_temp_dir().'/'.$prefix.'composer-php.ini';
  137. $content = $this->getIniHeader($iniFiles);
  138. foreach ($iniFiles as $file) {
  139. $content .= $this->getIniData($file, $replace);
  140. }
  141. return @file_put_contents($tmpIni, $content) ? $tmpIni : false;
  142. }
  143. /**
  144. * Returns true if additional inis were loaded
  145. *
  146. * @param array $iniFiles Populated by method
  147. * @param bool $replace Whether we need to modify the files
  148. *
  149. * @return bool
  150. */
  151. private function getAdditionalInis(array &$iniFiles, &$replace)
  152. {
  153. $replace = true;
  154. if ($scanned = php_ini_scanned_files()) {
  155. $list = explode(',', $scanned);
  156. foreach ($list as $file) {
  157. $file = trim($file);
  158. if (preg_match('/xdebug.ini$/', $file)) {
  159. // Skip the file, no need for regex replacing
  160. $replace = false;
  161. } else {
  162. $iniFiles[] = $file;
  163. }
  164. }
  165. }
  166. return !empty($scanned);
  167. }
  168. /**
  169. * Returns formatted ini file data
  170. *
  171. * @param string $iniFile The location of the ini file
  172. * @param bool $replace Whether to regex replace content
  173. *
  174. * @return string The ini data
  175. */
  176. private function getIniData($iniFile, $replace)
  177. {
  178. $data = str_repeat(PHP_EOL, 3);
  179. $data .= sprintf('; %s%s', $iniFile, PHP_EOL);
  180. $contents = file_get_contents($iniFile);
  181. if ($replace) {
  182. // Comment out xdebug config
  183. $regex = '/^\s*(zend_extension\s*=.*xdebug.*)$/mi';
  184. $data .= preg_replace($regex, ';$1', $contents);
  185. } else {
  186. $data .= $contents;
  187. }
  188. return $data;
  189. }
  190. /**
  191. * Returns the restart command line
  192. *
  193. * @param string $tmpIni The temporary ini file location
  194. *
  195. * @return string
  196. */
  197. private function getCommand($tmpIni)
  198. {
  199. $phpArgs = array(PHP_BINARY, '-c', $tmpIni);
  200. $params = array_merge($phpArgs, $this->getScriptArgs($_SERVER['argv']));
  201. return implode(' ', array_map(array($this, 'escape'), $params));
  202. }
  203. /**
  204. * Returns true if the restart environment variables were set
  205. *
  206. * @param bool $additional Whether additional inis were loaded
  207. *
  208. * @return bool
  209. */
  210. private function setEnvironment($additional)
  211. {
  212. $args = array(self::RESTART_ID);
  213. if (false !== $this->envScanDir) {
  214. // Save current PHP_INI_SCAN_DIR
  215. $args[] = $this->envScanDir;
  216. }
  217. if ($additional && !putenv('PHP_INI_SCAN_DIR=')) {
  218. return false;
  219. }
  220. return putenv(self::ENV_ALLOW.'='.implode('|', $args));
  221. }
  222. /**
  223. * Returns the restart script arguments, adding --ansi if required
  224. *
  225. * If we are a terminal with color support we must ensure that the --ansi
  226. * option is set, because the restarted output is piped.
  227. *
  228. * @param array $args The argv array
  229. *
  230. * @return array
  231. */
  232. private function getScriptArgs(array $args)
  233. {
  234. if (in_array('--no-ansi', $args) || in_array('--ansi', $args)) {
  235. return $args;
  236. }
  237. if ($this->output->isDecorated()) {
  238. $offset = count($args) > 1 ? 2: 1;
  239. array_splice($args, $offset, 0, '--ansi');
  240. }
  241. return $args;
  242. }
  243. /**
  244. * Escapes a string to be used as a shell argument.
  245. *
  246. * From https://github.com/johnstevenson/winbox-args
  247. * MIT Licensed (c) John Stevenson <john-stevenson@blueyonder.co.uk>
  248. *
  249. * @param string $arg The argument to be escaped
  250. * @param bool $meta Additionally escape cmd.exe meta characters
  251. *
  252. * @return string The escaped argument
  253. */
  254. private function escape($arg, $meta = true)
  255. {
  256. if (!defined('PHP_WINDOWS_VERSION_BUILD')) {
  257. return escapeshellarg($arg);
  258. }
  259. $quote = strpbrk($arg, " \t") !== false || $arg === '';
  260. $arg = preg_replace('/(\\\\*)"/', '$1$1\\"', $arg, -1, $dquotes);
  261. if ($meta) {
  262. $meta = $dquotes || preg_match('/%[^%]+%/', $arg);
  263. if (!$meta && !$quote) {
  264. $quote = strpbrk($arg, '^&|<>()') !== false;
  265. }
  266. }
  267. if ($quote) {
  268. $arg = preg_replace('/(\\\\*)$/', '$1$1', $arg);
  269. $arg = '"'.$arg.'"';
  270. }
  271. if ($meta) {
  272. $arg = preg_replace('/(["^&|<>()%])/', '^$1', $arg);
  273. }
  274. return $arg;
  275. }
  276. /**
  277. * Returns the location of the original ini data used.
  278. *
  279. * @param array $iniFiles loaded php.ini locations
  280. *
  281. * @return string
  282. */
  283. private function getIniHeader($iniFiles)
  284. {
  285. $ini = implode(PHP_EOL.'; ', $iniFiles);
  286. $header = <<<EOD
  287. ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
  288. ; This file was automatically generated by Composer and can now be deleted.
  289. ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
  290. ; It is a modified copy of your php.ini configuration, found at:
  291. ; {$ini}
  292. ; Make any changes there because this data will not be used again.
  293. EOD;
  294. $header .= str_repeat(PHP_EOL, 50);
  295. return $header;
  296. }
  297. }