DiagnoseCommand.php 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595
  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\Config;
  15. use Composer\Downloader\TransportException;
  16. use Composer\Plugin\CommandEvent;
  17. use Composer\Plugin\PluginEvents;
  18. use Composer\Util\ConfigValidator;
  19. use Composer\Util\ProcessExecutor;
  20. use Composer\Util\RemoteFilesystem;
  21. use Composer\Util\StreamContextFactory;
  22. use Composer\Util\Keys;
  23. use Symfony\Component\Console\Input\InputInterface;
  24. use Symfony\Component\Console\Output\OutputInterface;
  25. /**
  26. * @author Jordi Boggiano <j.boggiano@seld.be>
  27. */
  28. class DiagnoseCommand extends Command
  29. {
  30. /** @var RemoteFileSystem */
  31. protected $rfs;
  32. /** @var ProcessExecutor */
  33. protected $process;
  34. /** @var int */
  35. protected $failures = 0;
  36. protected function configure()
  37. {
  38. $this
  39. ->setName('diagnose')
  40. ->setDescription('Diagnoses the system to identify common errors.')
  41. ->setHelp(<<<EOT
  42. The <info>diagnose</info> command checks common errors to help debugging problems.
  43. EOT
  44. )
  45. ;
  46. }
  47. /**
  48. * {@inheritdoc}
  49. */
  50. protected function execute(InputInterface $input, OutputInterface $output)
  51. {
  52. $composer = $this->getComposer(false);
  53. $io = $this->getIO();
  54. if ($composer) {
  55. $commandEvent = new CommandEvent(PluginEvents::COMMAND, 'diagnose', $input, $output);
  56. $composer->getEventDispatcher()->dispatch($commandEvent->getName(), $commandEvent);
  57. $io->write('Checking composer.json: ', false);
  58. $this->outputResult($this->checkComposerSchema());
  59. }
  60. if ($composer) {
  61. $config = $composer->getConfig();
  62. } else {
  63. $config = Factory::createConfig();
  64. }
  65. $this->rfs = Factory::createRemoteFilesystem($io, $config);
  66. $this->process = new ProcessExecutor($io);
  67. $io->write('Checking platform settings: ', false);
  68. $this->outputResult($this->checkPlatform());
  69. $io->write('Checking git settings: ', false);
  70. $this->outputResult($this->checkGit());
  71. $io->write('Checking http connectivity to packagist: ', false);
  72. $this->outputResult($this->checkHttp('http', $config));
  73. $io->write('Checking https connectivity to packagist: ', false);
  74. $this->outputResult($this->checkHttp('https', $config));
  75. $opts = stream_context_get_options(StreamContextFactory::getContext('http://example.org'));
  76. if (!empty($opts['http']['proxy'])) {
  77. $io->write('Checking HTTP proxy: ', false);
  78. $this->outputResult($this->checkHttpProxy());
  79. $io->write('Checking HTTP proxy support for request_fulluri: ', false);
  80. $this->outputResult($this->checkHttpProxyFullUriRequestParam());
  81. $io->write('Checking HTTPS proxy support for request_fulluri: ', false);
  82. $this->outputResult($this->checkHttpsProxyFullUriRequestParam());
  83. }
  84. if ($oauth = $config->get('github-oauth')) {
  85. foreach ($oauth as $domain => $token) {
  86. $io->write('Checking '.$domain.' oauth access: ', false);
  87. $this->outputResult($this->checkGithubOauth($domain, $token));
  88. }
  89. } else {
  90. $io->write('Checking github.com rate limit: ', false);
  91. try {
  92. $rate = $this->getGithubRateLimit('github.com');
  93. $this->outputResult(true);
  94. if (10 > $rate['remaining']) {
  95. $io->write('<warning>WARNING</warning>');
  96. $io->write(sprintf(
  97. '<comment>Github has a rate limit on their API. '
  98. . 'You currently have <options=bold>%u</options=bold> '
  99. . 'out of <options=bold>%u</options=bold> requests left.' . PHP_EOL
  100. . 'See https://developer.github.com/v3/#rate-limiting and also' . PHP_EOL
  101. . ' https://getcomposer.org/doc/articles/troubleshooting.md#api-rate-limit-and-oauth-tokens</comment>',
  102. $rate['remaining'],
  103. $rate['limit']
  104. ));
  105. }
  106. } catch (\Exception $e) {
  107. if ($e instanceof TransportException && $e->getCode() === 401) {
  108. $this->outputResult('<comment>The oauth token for github.com seems invalid, run "composer config --global --unset github-oauth.github.com" to remove it</comment>');
  109. } else {
  110. $this->outputResult($e);
  111. }
  112. }
  113. }
  114. $io->write('Checking disk free space: ', false);
  115. $this->outputResult($this->checkDiskSpace($config));
  116. $io->write('Checking pubkeys: ', false);
  117. $this->outputResult($this->checkPubKeys($config));
  118. $io->write('Checking composer version: ', false);
  119. $this->outputResult($this->checkVersion());
  120. return $this->failures;
  121. }
  122. private function checkComposerSchema()
  123. {
  124. $validator = new ConfigValidator($this->getIO());
  125. list($errors, , $warnings) = $validator->validate(Factory::getComposerFile());
  126. if ($errors || $warnings) {
  127. $messages = array(
  128. 'error' => $errors,
  129. 'warning' => $warnings,
  130. );
  131. $output = '';
  132. foreach ($messages as $style => $msgs) {
  133. foreach ($msgs as $msg) {
  134. $output .= '<' . $style . '>' . $msg . '</' . $style . '>' . PHP_EOL;
  135. }
  136. }
  137. return rtrim($output);
  138. }
  139. return true;
  140. }
  141. private function checkGit()
  142. {
  143. $this->process->execute('git config color.ui', $output);
  144. if (strtolower(trim($output)) === 'always') {
  145. 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>';
  146. }
  147. return true;
  148. }
  149. private function checkHttp($proto, Config $config)
  150. {
  151. $disableTls = false;
  152. $result = array();
  153. if ($proto === 'https' && $config->get('disable-tls') === true) {
  154. $disableTls = true;
  155. $result[] = '<warning>Composer is configured to disable SSL/TLS protection. This will leave remote HTTPS requests vulnerable to Man-In-The-Middle attacks.</warning>';
  156. }
  157. if ($proto === 'https' && !extension_loaded('openssl') && !$disableTls) {
  158. $result[] = '<error>Composer is configured to use SSL/TLS protection but the openssl extension is not available.</error>';
  159. }
  160. try {
  161. $this->rfs->getContents('packagist.org', $proto . '://packagist.org/packages.json', false);
  162. } catch (TransportException $e) {
  163. if (false !== strpos($e->getMessage(), 'cafile')) {
  164. $result[] = '<error>[' . get_class($e) . '] ' . $e->getMessage() . '</error>';
  165. $result[] = '<error>Unable to locate a valid CA certificate file. You must set a valid \'cafile\' option.</error>';
  166. $result[] = '<error>You can alternatively disable this error, at your own risk, by enabling the \'disable-tls\' option.</error>';
  167. } else {
  168. array_unshift($result, '[' . get_class($e) . '] ' . $e->getMessage());
  169. }
  170. }
  171. if (count($result) > 0) {
  172. return $result;
  173. }
  174. return true;
  175. }
  176. private function checkHttpProxy()
  177. {
  178. $protocol = extension_loaded('openssl') ? 'https' : 'http';
  179. try {
  180. $json = json_decode($this->rfs->getContents('packagist.org', $protocol . '://packagist.org/packages.json', false), true);
  181. $hash = reset($json['provider-includes']);
  182. $hash = $hash['sha256'];
  183. $path = str_replace('%hash%', $hash, key($json['provider-includes']));
  184. $provider = $this->rfs->getContents('packagist.org', $protocol . '://packagist.org/'.$path, false);
  185. if (hash('sha256', $provider) !== $hash) {
  186. return 'It seems that your proxy is modifying http traffic on the fly';
  187. }
  188. } catch (\Exception $e) {
  189. return $e;
  190. }
  191. return true;
  192. }
  193. /**
  194. * Due to various proxy servers configurations, some servers can't handle non-standard HTTP "http_proxy_request_fulluri" parameter,
  195. * and will return error 500/501 (as not implemented), see discussion @ https://github.com/composer/composer/pull/1825.
  196. * This method will test, if you need to disable this parameter via setting extra environment variable in your system.
  197. *
  198. * @return bool|string
  199. */
  200. private function checkHttpProxyFullUriRequestParam()
  201. {
  202. $url = 'http://packagist.org/packages.json';
  203. try {
  204. $this->rfs->getContents('packagist.org', $url, false);
  205. } catch (TransportException $e) {
  206. try {
  207. $this->rfs->getContents('packagist.org', $url, false, array('http' => array('request_fulluri' => false)));
  208. } catch (TransportException $e) {
  209. return 'Unable to assess the situation, maybe packagist.org is down ('.$e->getMessage().')';
  210. }
  211. 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"';
  212. }
  213. return true;
  214. }
  215. /**
  216. * Due to various proxy servers configurations, some servers can't handle non-standard HTTP "http_proxy_request_fulluri" parameter,
  217. * and will return error 500/501 (as not implemented), see discussion @ https://github.com/composer/composer/pull/1825.
  218. * This method will test, if you need to disable this parameter via setting extra environment variable in your system.
  219. *
  220. * @return bool|string
  221. */
  222. private function checkHttpsProxyFullUriRequestParam()
  223. {
  224. if (!extension_loaded('openssl')) {
  225. return 'You need the openssl extension installed for this check';
  226. }
  227. $url = 'https://api.github.com/repos/Seldaek/jsonlint/zipball/1.0.0';
  228. try {
  229. $this->rfs->getContents('github.com', $url, false);
  230. } catch (TransportException $e) {
  231. try {
  232. $this->rfs->getContents('github.com', $url, false, array('http' => array('request_fulluri' => false)));
  233. } catch (TransportException $e) {
  234. return 'Unable to assess the situation, maybe github is down ('.$e->getMessage().')';
  235. }
  236. return 'It seems there is a problem with your proxy server, try setting the "HTTPS_PROXY_REQUEST_FULLURI" environment variable to "false"';
  237. }
  238. return true;
  239. }
  240. private function checkGithubOauth($domain, $token)
  241. {
  242. $this->getIO()->setAuthentication($domain, $token, 'x-oauth-basic');
  243. try {
  244. $url = $domain === 'github.com' ? 'https://api.'.$domain.'/user/repos' : 'https://'.$domain.'/api/v3/user/repos';
  245. return $this->rfs->getContents($domain, $url, false, array(
  246. 'retry-auth-failure' => false,
  247. )) ? true : 'Unexpected error';
  248. } catch (\Exception $e) {
  249. if ($e instanceof TransportException && $e->getCode() === 401) {
  250. return '<comment>The oauth token for '.$domain.' seems invalid, run "composer config --global --unset github-oauth.'.$domain.'" to remove it</comment>';
  251. }
  252. return $e;
  253. }
  254. }
  255. /**
  256. * @param string $domain
  257. * @param string $token
  258. * @throws TransportException
  259. * @return array
  260. */
  261. private function getGithubRateLimit($domain, $token = null)
  262. {
  263. if ($token) {
  264. $this->getIO()->setAuthentication($domain, $token, 'x-oauth-basic');
  265. }
  266. $url = $domain === 'github.com' ? 'https://api.'.$domain.'/rate_limit' : 'https://'.$domain.'/api/rate_limit';
  267. $json = $this->rfs->getContents($domain, $url, false, array('retry-auth-failure' => false));
  268. $data = json_decode($json, true);
  269. return $data['resources']['core'];
  270. }
  271. private function checkDiskSpace($config)
  272. {
  273. $minSpaceFree = 1024 * 1024;
  274. if ((($df = @disk_free_space($dir = $config->get('home'))) !== false && $df < $minSpaceFree)
  275. || (($df = @disk_free_space($dir = $config->get('vendor-dir'))) !== false && $df < $minSpaceFree)
  276. ) {
  277. return '<error>The disk hosting '.$dir.' is full</error>';
  278. }
  279. return true;
  280. }
  281. private function checkPubKeys($config)
  282. {
  283. $home = $config->get('home');
  284. $errors = [];
  285. $io = $this->getIO();
  286. if (file_exists($home.'/keys.tags.pub') && file_exists($home.'/keys.dev.pub')) {
  287. $io->write('');
  288. }
  289. if (file_exists($home.'/keys.tags.pub')) {
  290. $io->write('Tags Public Key Fingerprint: ' . Keys::fingerprint($home.'/keys.tags.pub'));
  291. } else {
  292. $errors[] = '<error>Missing pubkey for tags verification</error>';
  293. }
  294. if (file_exists($home.'/keys.dev.pub')) {
  295. $io->write('Dev Public Key Fingerprint: ' . Keys::fingerprint($home.'/keys.dev.pub'));
  296. } else {
  297. $errors[] = '<error>Missing pubkey for dev verification</error>';
  298. }
  299. if ($errors) {
  300. $errors[] = '<error>Run composer self-update --update-keys to set them up</error>';
  301. }
  302. return $errors ?: true;
  303. }
  304. private function checkVersion()
  305. {
  306. $protocol = extension_loaded('openssl') ? 'https' : 'http';
  307. $latest = trim($this->rfs->getContents('getcomposer.org', $protocol . '://getcomposer.org/version', false));
  308. if (Composer::VERSION !== $latest && Composer::VERSION !== '@package_version@') {
  309. return '<comment>You are not running the latest version, run `composer self-update` to update</comment>';
  310. }
  311. return true;
  312. }
  313. /**
  314. * @param bool|string|\Exception $result
  315. */
  316. private function outputResult($result)
  317. {
  318. $io = $this->getIO();
  319. if (true === $result) {
  320. $io->write('<info>OK</info>');
  321. } else {
  322. $this->failures++;
  323. $io->write('<error>FAIL</error>');
  324. if ($result instanceof \Exception) {
  325. $io->write('['.get_class($result).'] '.$result->getMessage());
  326. } elseif ($result) {
  327. if (is_array($result)) {
  328. foreach ($result as $message) {
  329. $io->write($message);
  330. }
  331. } else {
  332. $io->write($result);
  333. }
  334. }
  335. }
  336. }
  337. private function checkPlatform()
  338. {
  339. $output = '';
  340. $out = function ($msg, $style) use (&$output) {
  341. $output .= '<'.$style.'>'.$msg.'</'.$style.'>'.PHP_EOL;
  342. };
  343. // code below taken from getcomposer.org/installer, any changes should be made there and replicated here
  344. $errors = array();
  345. $warnings = array();
  346. $iniPath = php_ini_loaded_file();
  347. $displayIniMessage = false;
  348. if ($iniPath) {
  349. $iniMessage = PHP_EOL.PHP_EOL.'The php.ini used by your command-line PHP is: ' . $iniPath;
  350. } else {
  351. $iniMessage = PHP_EOL.PHP_EOL.'A php.ini file does not exist. You will have to create one.';
  352. }
  353. $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.';
  354. if (!function_exists('json_decode')) {
  355. $errors['json'] = true;
  356. }
  357. if (!extension_loaded('Phar')) {
  358. $errors['phar'] = true;
  359. }
  360. if (!extension_loaded('filter')) {
  361. $errors['filter'] = true;
  362. }
  363. if (!extension_loaded('hash')) {
  364. $errors['hash'] = true;
  365. }
  366. if (!ini_get('allow_url_fopen')) {
  367. $errors['allow_url_fopen'] = true;
  368. }
  369. if (extension_loaded('ionCube Loader') && ioncube_loader_iversion() < 40009) {
  370. $errors['ioncube'] = ioncube_loader_version();
  371. }
  372. if (PHP_VERSION_ID < 50302) {
  373. $errors['php'] = PHP_VERSION;
  374. }
  375. if (!isset($errors['php']) && PHP_VERSION_ID < 50304) {
  376. $warnings['php'] = PHP_VERSION;
  377. }
  378. if (!extension_loaded('openssl')) {
  379. $errors['openssl'] = true;
  380. }
  381. if (!defined('HHVM_VERSION') && !extension_loaded('apcu') && ini_get('apc.enable_cli')) {
  382. $warnings['apc_cli'] = true;
  383. }
  384. ob_start();
  385. phpinfo(INFO_GENERAL);
  386. $phpinfo = ob_get_clean();
  387. if (preg_match('{Configure Command(?: *</td><td class="v">| *=> *)(.*?)(?:</td>|$)}m', $phpinfo, $match)) {
  388. $configure = $match[1];
  389. if (false !== strpos($configure, '--enable-sigchild')) {
  390. $warnings['sigchild'] = true;
  391. }
  392. if (false !== strpos($configure, '--with-curlwrappers')) {
  393. $warnings['curlwrappers'] = true;
  394. }
  395. }
  396. if (ini_get('xdebug.profiler_enabled')) {
  397. $warnings['xdebug_profile'] = true;
  398. } elseif (extension_loaded('xdebug')) {
  399. $warnings['xdebug_loaded'] = true;
  400. }
  401. if (!empty($errors)) {
  402. foreach ($errors as $error => $current) {
  403. switch ($error) {
  404. case 'json':
  405. $text = PHP_EOL."The json extension is missing.".PHP_EOL;
  406. $text .= "Install it or recompile php without --disable-json";
  407. break;
  408. case 'phar':
  409. $text = PHP_EOL."The phar extension is missing.".PHP_EOL;
  410. $text .= "Install it or recompile php without --disable-phar";
  411. break;
  412. case 'filter':
  413. $text = PHP_EOL."The filter extension is missing.".PHP_EOL;
  414. $text .= "Install it or recompile php without --disable-filter";
  415. break;
  416. case 'hash':
  417. $text = PHP_EOL."The hash extension is missing.".PHP_EOL;
  418. $text .= "Install it or recompile php without --disable-hash";
  419. break;
  420. case 'unicode':
  421. $text = PHP_EOL."The detect_unicode setting must be disabled.".PHP_EOL;
  422. $text .= "Add the following to the end of your `php.ini`:".PHP_EOL;
  423. $text .= " detect_unicode = Off";
  424. $displayIniMessage = true;
  425. break;
  426. case 'suhosin':
  427. $text = PHP_EOL."The suhosin.executor.include.whitelist setting is incorrect.".PHP_EOL;
  428. $text .= "Add the following to the end of your `php.ini` or suhosin.ini (Example path [for Debian]: /etc/php5/cli/conf.d/suhosin.ini):".PHP_EOL;
  429. $text .= " suhosin.executor.include.whitelist = phar ".$current;
  430. $displayIniMessage = true;
  431. break;
  432. case 'php':
  433. $text = PHP_EOL."Your PHP ({$current}) is too old, you must upgrade to PHP 5.3.2 or higher.";
  434. break;
  435. case 'allow_url_fopen':
  436. $text = PHP_EOL."The allow_url_fopen setting is incorrect.".PHP_EOL;
  437. $text .= "Add the following to the end of your `php.ini`:".PHP_EOL;
  438. $text .= " allow_url_fopen = On";
  439. $displayIniMessage = true;
  440. break;
  441. case 'ioncube':
  442. $text = PHP_EOL."Your ionCube Loader extension ($current) is incompatible with Phar files.".PHP_EOL;
  443. $text .= "Upgrade to ionCube 4.0.9 or higher or remove this line (path may be different) from your `php.ini` to disable it:".PHP_EOL;
  444. $text .= " zend_extension = /usr/lib/php5/20090626+lfs/ioncube_loader_lin_5.3.so";
  445. $displayIniMessage = true;
  446. break;
  447. case 'openssl':
  448. $text = PHP_EOL."The openssl extension is missing, which means that secure HTTPS transfers are impossible.".PHP_EOL;
  449. $text .= "If possible you should enable it or recompile php with --with-openssl";
  450. break;
  451. }
  452. $out($text, 'error');
  453. }
  454. $output .= PHP_EOL;
  455. }
  456. if (!empty($warnings)) {
  457. foreach ($warnings as $warning => $current) {
  458. switch ($warning) {
  459. case 'apc_cli':
  460. $text = "The apc.enable_cli setting is incorrect.".PHP_EOL;
  461. $text .= "Add the following to the end of your `php.ini`:".PHP_EOL;
  462. $text .= " apc.enable_cli = Off";
  463. $displayIniMessage = true;
  464. break;
  465. case 'sigchild':
  466. $text = "PHP was compiled with --enable-sigchild which can cause issues on some platforms.".PHP_EOL;
  467. $text .= "Recompile it without this flag if possible, see also:".PHP_EOL;
  468. $text .= " https://bugs.php.net/bug.php?id=22999";
  469. break;
  470. case 'curlwrappers':
  471. $text = "PHP was compiled with --with-curlwrappers which will cause issues with HTTP authentication and GitHub.".PHP_EOL;
  472. $text .= " Recompile it without this flag if possible";
  473. break;
  474. case 'php':
  475. $text = "Your PHP ({$current}) is quite old, upgrading to PHP 5.3.4 or higher is recommended.".PHP_EOL;
  476. $text .= " Composer works with 5.3.2+ for most people, but there might be edge case issues.";
  477. break;
  478. case 'xdebug_loaded':
  479. $text = "The xdebug extension is loaded, this can slow down Composer a little.".PHP_EOL;
  480. $text .= " Disabling it when using Composer is recommended.";
  481. break;
  482. case 'xdebug_profile':
  483. $text = "The xdebug.profiler_enabled setting is enabled, this can slow down Composer a lot.".PHP_EOL;
  484. $text .= "Add the following to the end of your `php.ini` to disable it:".PHP_EOL;
  485. $text .= " xdebug.profiler_enabled = 0";
  486. $displayIniMessage = true;
  487. break;
  488. }
  489. $out($text, 'comment');
  490. }
  491. }
  492. if ($displayIniMessage) {
  493. $out($iniMessage, 'comment');
  494. }
  495. return !$warnings && !$errors ? true : $output;
  496. }
  497. }