DiagnoseCommand.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460
  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\Command;
  12. use Composer\Composer;
  13. use Composer\Factory;
  14. use Composer\Downloader\TransportException;
  15. use Composer\Plugin\CommandEvent;
  16. use Composer\Plugin\PluginEvents;
  17. use Composer\Util\ConfigValidator;
  18. use Composer\Util\ProcessExecutor;
  19. use Composer\Util\RemoteFilesystem;
  20. use Composer\Util\StreamContextFactory;
  21. use Symfony\Component\Console\Input\InputInterface;
  22. use Symfony\Component\Console\Output\OutputInterface;
  23. /**
  24. * @author Jordi Boggiano <j.boggiano@seld.be>
  25. */
  26. class DiagnoseCommand extends Command
  27. {
  28. /** @var RemoteFileSystem */
  29. protected $rfs;
  30. /** @var ProcessExecutor */
  31. protected $process;
  32. /** @var int */
  33. protected $failures = 0;
  34. protected function configure()
  35. {
  36. $this
  37. ->setName('diagnose')
  38. ->setDescription('Diagnoses the system to identify common errors.')
  39. ->setHelp(<<<EOT
  40. The <info>diagnose</info> command checks common errors to help debugging problems.
  41. EOT
  42. )
  43. ;
  44. }
  45. protected function execute(InputInterface $input, OutputInterface $output)
  46. {
  47. $composer = $this->getComposer(false);
  48. if ($composer) {
  49. $commandEvent = new CommandEvent(PluginEvents::COMMAND, 'diagnose', $input, $output);
  50. $composer->getEventDispatcher()->dispatch($commandEvent->getName(), $commandEvent);
  51. $output->write('Checking composer.json: ');
  52. $this->outputResult($output, $this->checkComposerSchema());
  53. }
  54. if ($composer) {
  55. $config = $composer->getConfig();
  56. } else {
  57. $config = Factory::createConfig();
  58. }
  59. $this->rfs = new RemoteFilesystem($this->getIO(), $config);
  60. $this->process = new ProcessExecutor($this->getIO());
  61. $output->write('Checking platform settings: ');
  62. $this->outputResult($output, $this->checkPlatform());
  63. $output->write('Checking git settings: ');
  64. $this->outputResult($output, $this->checkGit());
  65. $output->write('Checking http connectivity: ');
  66. $this->outputResult($output, $this->checkHttp());
  67. $opts = stream_context_get_options(StreamContextFactory::getContext('http://example.org'));
  68. if (!empty($opts['http']['proxy'])) {
  69. $output->write('Checking HTTP proxy: ');
  70. $this->outputResult($output, $this->checkHttpProxy());
  71. $output->write('Checking HTTP proxy support for request_fulluri: ');
  72. $this->outputResult($output, $this->checkHttpProxyFullUriRequestParam());
  73. $output->write('Checking HTTPS proxy support for request_fulluri: ');
  74. $this->outputResult($output, $this->checkHttpsProxyFullUriRequestParam());
  75. }
  76. if ($oauth = $config->get('github-oauth')) {
  77. foreach ($oauth as $domain => $token) {
  78. $output->write('Checking '.$domain.' oauth access: ');
  79. $this->outputResult($output, $this->checkGithubOauth($domain, $token));
  80. }
  81. } else {
  82. $output->write('Checking github.com rate limit: ');
  83. $rate = $this->getGithubRateLimit('github.com');
  84. if (10 > $rate['remaining']) {
  85. $output->writeln('<warning>WARNING</warning>');
  86. $output->writeln(sprintf(
  87. '<comment>Github has a rate limit on their API. '
  88. . 'You currently have <options=bold>%u</options=bold> '
  89. . 'out of <options=bold>%u</options=bold> requests left.' . PHP_EOL
  90. . 'See https://developer.github.com/v3/#rate-limiting and also' . PHP_EOL
  91. . ' https://getcomposer.org/doc/articles/troubleshooting.md#api-rate-limit-and-oauth-tokens</comment>',
  92. $rate['remaining'],
  93. $rate['limit']
  94. ));
  95. } else {
  96. $output->writeln('<info>OK</info>');
  97. }
  98. }
  99. $output->write('Checking disk free space: ');
  100. $this->outputResult($output, $this->checkDiskSpace($config));
  101. $output->write('Checking composer version: ');
  102. $this->outputResult($output, $this->checkVersion());
  103. return $this->failures;
  104. }
  105. private function checkComposerSchema()
  106. {
  107. $validator = new ConfigValidator($this->getIO());
  108. list($errors, $publishErrors, $warnings) = $validator->validate(Factory::getComposerFile());
  109. if ($errors || $publishErrors || $warnings) {
  110. $messages = array(
  111. 'error' => array_merge($errors, $publishErrors),
  112. 'warning' => $warnings,
  113. );
  114. $output = '';
  115. foreach ($messages as $style => $msgs) {
  116. foreach ($msgs as $msg) {
  117. $output .= '<' . $style . '>' . $msg . '</' . $style . '>' . PHP_EOL;
  118. }
  119. }
  120. return rtrim($output);
  121. }
  122. return true;
  123. }
  124. private function checkGit()
  125. {
  126. $this->process->execute('git config color.ui', $output);
  127. if (strtolower(trim($output)) === 'always') {
  128. return '<comment>Your git color.ui setting is set to always, this is known to create issues. Use "git config --global color.ui true" to set it correctly.</comment>';
  129. }
  130. return true;
  131. }
  132. private function checkHttp()
  133. {
  134. $protocol = extension_loaded('openssl') ? 'https' : 'http';
  135. try {
  136. $this->rfs->getContents('packagist.org', $protocol . '://packagist.org/packages.json', false);
  137. } catch (\Exception $e) {
  138. return $e;
  139. }
  140. return true;
  141. }
  142. private function checkHttpProxy()
  143. {
  144. $protocol = extension_loaded('openssl') ? 'https' : 'http';
  145. try {
  146. $json = json_decode($this->rfs->getContents('packagist.org', $protocol . '://packagist.org/packages.json', false), true);
  147. $hash = reset($json['provider-includes']);
  148. $hash = $hash['sha256'];
  149. $path = str_replace('%hash%', $hash, key($json['provider-includes']));
  150. $provider = $this->rfs->getContents('packagist.org', $protocol . '://packagist.org/'.$path, false);
  151. if (hash('sha256', $provider) !== $hash) {
  152. return 'It seems that your proxy is modifying http traffic on the fly';
  153. }
  154. } catch (\Exception $e) {
  155. return $e;
  156. }
  157. return true;
  158. }
  159. /**
  160. * Due to various proxy servers configurations, some servers can't handle non-standard HTTP "http_proxy_request_fulluri" parameter,
  161. * and will return error 500/501 (as not implemented), see discussion @ https://github.com/composer/composer/pull/1825.
  162. * This method will test, if you need to disable this parameter via setting extra environment variable in your system.
  163. *
  164. * @return bool|string
  165. */
  166. private function checkHttpProxyFullUriRequestParam()
  167. {
  168. $url = 'http://packagist.org/packages.json';
  169. try {
  170. $this->rfs->getContents('packagist.org', $url, false);
  171. } catch (TransportException $e) {
  172. try {
  173. $this->rfs->getContents('packagist.org', $url, false, array('http' => array('request_fulluri' => false)));
  174. } catch (TransportException $e) {
  175. return 'Unable to assess the situation, maybe packagist.org is down ('.$e->getMessage().')';
  176. }
  177. return 'It seems there is a problem with your proxy server, try setting the "HTTP_PROXY_REQUEST_FULLURI" and "HTTPS_PROXY_REQUEST_FULLURI" environment variables to "false"';
  178. }
  179. return true;
  180. }
  181. /**
  182. * Due to various proxy servers configurations, some servers can't handle non-standard HTTP "http_proxy_request_fulluri" parameter,
  183. * and will return error 500/501 (as not implemented), see discussion @ https://github.com/composer/composer/pull/1825.
  184. * This method will test, if you need to disable this parameter via setting extra environment variable in your system.
  185. *
  186. * @return bool|string
  187. */
  188. private function checkHttpsProxyFullUriRequestParam()
  189. {
  190. if (!extension_loaded('openssl')) {
  191. return 'You need the openssl extension installed for this check';
  192. }
  193. $url = 'https://api.github.com/repos/Seldaek/jsonlint/zipball/1.0.0';
  194. try {
  195. $this->rfs->getContents('github.com', $url, false);
  196. } catch (TransportException $e) {
  197. try {
  198. $this->rfs->getContents('github.com', $url, false, array('http' => array('request_fulluri' => false)));
  199. } catch (TransportException $e) {
  200. return 'Unable to assess the situation, maybe github is down ('.$e->getMessage().')';
  201. }
  202. return 'It seems there is a problem with your proxy server, try setting the "HTTPS_PROXY_REQUEST_FULLURI" environment variable to "false"';
  203. }
  204. return true;
  205. }
  206. private function checkGithubOauth($domain, $token)
  207. {
  208. $this->getIO()->setAuthentication($domain, $token, 'x-oauth-basic');
  209. try {
  210. $url = $domain === 'github.com' ? 'https://api.'.$domain.'/user/repos' : 'https://'.$domain.'/api/v3/user/repos';
  211. return $this->rfs->getContents($domain, $url, false, array(
  212. 'retry-auth-failure' => false
  213. )) ? true : 'Unexpected error';
  214. } catch (\Exception $e) {
  215. if ($e instanceof TransportException && $e->getCode() === 401) {
  216. return '<comment>The oauth token for '.$domain.' seems invalid, run "composer config --global --unset github-oauth.'.$domain.'" to remove it</comment>';
  217. }
  218. return $e;
  219. }
  220. }
  221. private function getGithubRateLimit($domain, $token = null)
  222. {
  223. if ($token) {
  224. $this->getIO()->setAuthentication($domain, $token, 'x-oauth-basic');
  225. }
  226. try {
  227. $url = $domain === 'github.com' ? 'https://api.'.$domain.'/rate_limit' : 'https://'.$domain.'/api/rate_limit';
  228. $json = $this->rfs->getContents($domain, $url, array('retry-auth-failure' => false));
  229. $data = json_decode($json, true);
  230. return $data['rate'];
  231. } catch (\Exception $e) {
  232. if ($e instanceof TransportException && $e->getCode() === 401) {
  233. return '<comment>The oauth token for '.$domain.' seems invalid, run "composer config --global --unset github-oauth.'.$domain.'" to remove it</comment>';
  234. }
  235. return $e;
  236. }
  237. }
  238. private function checkDiskSpace($config)
  239. {
  240. $minSpaceFree = 1024*1024;
  241. if ((($df = @disk_free_space($dir = $config->get('home'))) !== false && $df < $minSpaceFree)
  242. || (($df = @disk_free_space($dir = $config->get('vendor-dir'))) !== false && $df < $minSpaceFree)
  243. ) {
  244. return '<error>The disk hosting '.$dir.' is full</error>';
  245. }
  246. return true;
  247. }
  248. private function checkVersion()
  249. {
  250. $protocol = extension_loaded('openssl') ? 'https' : 'http';
  251. $latest = trim($this->rfs->getContents('getcomposer.org', $protocol . '://getcomposer.org/version', false));
  252. if (Composer::VERSION !== $latest && Composer::VERSION !== '@package_version@') {
  253. return '<comment>You are not running the latest version</comment>';
  254. }
  255. return true;
  256. }
  257. private function outputResult(OutputInterface $output, $result)
  258. {
  259. if (true === $result) {
  260. $output->writeln('<info>OK</info>');
  261. } else {
  262. $this->failures++;
  263. $output->writeln('<error>FAIL</error>');
  264. if ($result instanceof \Exception) {
  265. $output->writeln('['.get_class($result).'] '.$result->getMessage());
  266. } elseif ($result) {
  267. $output->writeln(trim($result));
  268. }
  269. }
  270. }
  271. private function checkPlatform()
  272. {
  273. $output = '';
  274. $out = function ($msg, $style) use (&$output) {
  275. $output .= '<'.$style.'>'.$msg.'</'.$style.'>'.PHP_EOL;
  276. };
  277. // code below taken from getcomposer.org/installer, any changes should be made there and replicated here
  278. $errors = array();
  279. $warnings = array();
  280. $iniPath = php_ini_loaded_file();
  281. $displayIniMessage = false;
  282. if ($iniPath) {
  283. $iniMessage = PHP_EOL.PHP_EOL.'The php.ini used by your command-line PHP is: ' . $iniPath;
  284. } else {
  285. $iniMessage = PHP_EOL.PHP_EOL.'A php.ini file does not exist. You will have to create one.';
  286. }
  287. $iniMessage .= PHP_EOL.'If you can not modify the ini file, you can also run `php -d option=value` to modify ini values on the fly. You can use -d multiple times.';
  288. if (!ini_get('allow_url_fopen')) {
  289. $errors['allow_url_fopen'] = true;
  290. }
  291. if (version_compare(PHP_VERSION, '5.3.2', '<')) {
  292. $errors['php'] = PHP_VERSION;
  293. }
  294. if (!isset($errors['php']) && version_compare(PHP_VERSION, '5.3.4', '<')) {
  295. $warnings['php'] = PHP_VERSION;
  296. }
  297. if (!extension_loaded('openssl')) {
  298. $warnings['openssl'] = true;
  299. }
  300. if (!defined('HHVM_VERSION') && !extension_loaded('apcu') && ini_get('apc.enable_cli')) {
  301. $warnings['apc_cli'] = true;
  302. }
  303. if (ini_get('xdebug.profiler_enabled')) {
  304. $warnings['xdebug_profile'] = true;
  305. } elseif (extension_loaded('xdebug')) {
  306. $warnings['xdebug_loaded'] = true;
  307. }
  308. ob_start();
  309. phpinfo(INFO_GENERAL);
  310. $phpinfo = ob_get_clean();
  311. if (preg_match('{Configure Command(?: *</td><td class="v">| *=> *)(.*?)(?:</td>|$)}m', $phpinfo, $match)) {
  312. $configure = $match[1];
  313. if (false !== strpos($configure, '--enable-sigchild')) {
  314. $warnings['sigchild'] = true;
  315. }
  316. if (false !== strpos($configure, '--with-curlwrappers')) {
  317. $warnings['curlwrappers'] = true;
  318. }
  319. }
  320. if (!empty($errors)) {
  321. foreach ($errors as $error => $current) {
  322. switch ($error) {
  323. case 'php':
  324. $text = "- Your PHP ({$current}) is too old, you must upgrade to PHP 5.3.2 or higher.";
  325. break;
  326. case 'allow_url_fopen':
  327. $text = "The allow_url_fopen setting is incorrect.".PHP_EOL;
  328. $text .= "Add the following to the end of your `php.ini`:".PHP_EOL;
  329. $text .= " allow_url_fopen = On";
  330. $displayIniMessage = true;
  331. break;
  332. }
  333. $out($text, 'error');
  334. }
  335. $output .= PHP_EOL;
  336. }
  337. if (!empty($warnings)) {
  338. foreach ($warnings as $warning => $current) {
  339. switch ($warning) {
  340. case 'apc_cli':
  341. $text = "The apc.enable_cli setting is incorrect.".PHP_EOL;
  342. $text .= "Add the following to the end of your `php.ini`:".PHP_EOL;
  343. $text .= " apc.enable_cli = Off";
  344. $displayIniMessage = true;
  345. break;
  346. case 'sigchild':
  347. $text = "PHP was compiled with --enable-sigchild which can cause issues on some platforms.".PHP_EOL;
  348. $text .= "Recompile it without this flag if possible, see also:".PHP_EOL;
  349. $text .= " https://bugs.php.net/bug.php?id=22999";
  350. break;
  351. case 'curlwrappers':
  352. $text = "PHP was compiled with --with-curlwrappers which will cause issues with HTTP authentication and GitHub.".PHP_EOL;
  353. $text .= " Recompile it without this flag if possible";
  354. break;
  355. case 'openssl':
  356. $text = "The openssl extension is missing, which will reduce the security and stability of Composer.".PHP_EOL;
  357. $text .= " If possible you should enable it or recompile php with --with-openssl";
  358. break;
  359. case 'php':
  360. $text = "Your PHP ({$current}) is quite old, upgrading to PHP 5.3.4 or higher is recommended.".PHP_EOL;
  361. $text .= " Composer works with 5.3.2+ for most people, but there might be edge case issues.";
  362. break;
  363. case 'xdebug_loaded':
  364. $text = "The xdebug extension is loaded, this can slow down Composer a little.".PHP_EOL;
  365. $text .= " Disabling it when using Composer is recommended.";
  366. break;
  367. case 'xdebug_profile':
  368. $text = "The xdebug.profiler_enabled setting is enabled, this can slow down Composer a lot.".PHP_EOL;
  369. $text .= "Add the following to the end of your `php.ini` to disable it:".PHP_EOL;
  370. $text .= " xdebug.profiler_enabled = 0";
  371. $displayIniMessage = true;
  372. break;
  373. }
  374. $out($text, 'comment');
  375. }
  376. }
  377. if ($displayIniMessage) {
  378. $out($iniMessage, 'comment');
  379. }
  380. return !$warnings && !$errors ? true : $output;
  381. }
  382. }