DiagnoseCommand.php 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563
  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 Symfony\Component\Console\Input\InputInterface;
  23. use Symfony\Component\Console\Output\OutputInterface;
  24. use Symfony\Component\Console\Input\InputOption;
  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 composer version: ', false);
  117. $this->outputResult($this->checkVersion());
  118. return $this->failures;
  119. }
  120. private function checkComposerSchema()
  121. {
  122. $validator = new ConfigValidator($this->getIO());
  123. list($errors, , $warnings) = $validator->validate(Factory::getComposerFile());
  124. if ($errors || $warnings) {
  125. $messages = array(
  126. 'error' => $errors,
  127. 'warning' => $warnings,
  128. );
  129. $output = '';
  130. foreach ($messages as $style => $msgs) {
  131. foreach ($msgs as $msg) {
  132. $output .= '<' . $style . '>' . $msg . '</' . $style . '>' . PHP_EOL;
  133. }
  134. }
  135. return rtrim($output);
  136. }
  137. return true;
  138. }
  139. private function checkGit()
  140. {
  141. $this->process->execute('git config color.ui', $output);
  142. if (strtolower(trim($output)) === 'always') {
  143. 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>';
  144. }
  145. return true;
  146. }
  147. private function checkHttp($proto, Config $config)
  148. {
  149. $disableTls = false;
  150. $result = array();
  151. if ($proto === 'https' && $config->get('disable-tls') === true) {
  152. $disableTls = true;
  153. $result[] = '<warning>Composer is configured to disable SSL/TLS protection. This will leave remote HTTPS requests vulnerable to Man-In-The-Middle attacks.</warning>';
  154. }
  155. if ($proto === 'https' && !extension_loaded('openssl') && !$disableTls) {
  156. $result[] = '<error>Composer is configured to use SSL/TLS protection but the openssl extension is not available.</error>';
  157. }
  158. try {
  159. $this->rfs->getContents('packagist.org', $proto . '://packagist.org/packages.json', false);
  160. } catch (TransportException $e) {
  161. if (preg_match('|cafile|', $e->getMessage())) {
  162. $result[] = '<error>[' . get_class($e) . '] ' . $e->getMessage() . '</error>';
  163. $result[] = '<error>Unable to locate a valid CA certificate file. You must set a valid \'cafile\' option.</error>';
  164. $result[] = '<error>You can alternatively disable this error, at your own risk, by enabling the \'disable-tls\' option.</error>';
  165. } else {
  166. array_unshift($result, '[' . get_class($e) . '] ' . $e->getMessage());
  167. }
  168. }
  169. if (count($result) > 0) {
  170. return $result;
  171. }
  172. return true;
  173. }
  174. private function checkHttpProxy()
  175. {
  176. $protocol = extension_loaded('openssl') ? 'https' : 'http';
  177. try {
  178. $json = json_decode($this->rfs->getContents('packagist.org', $protocol . '://packagist.org/packages.json', false), true);
  179. $hash = reset($json['provider-includes']);
  180. $hash = $hash['sha256'];
  181. $path = str_replace('%hash%', $hash, key($json['provider-includes']));
  182. $provider = $this->rfs->getContents('packagist.org', $protocol . '://packagist.org/'.$path, false);
  183. if (hash('sha256', $provider) !== $hash) {
  184. return 'It seems that your proxy is modifying http traffic on the fly';
  185. }
  186. } catch (\Exception $e) {
  187. return $e;
  188. }
  189. return true;
  190. }
  191. /**
  192. * Due to various proxy servers configurations, some servers can't handle non-standard HTTP "http_proxy_request_fulluri" parameter,
  193. * and will return error 500/501 (as not implemented), see discussion @ https://github.com/composer/composer/pull/1825.
  194. * This method will test, if you need to disable this parameter via setting extra environment variable in your system.
  195. *
  196. * @return bool|string
  197. */
  198. private function checkHttpProxyFullUriRequestParam()
  199. {
  200. $url = 'http://packagist.org/packages.json';
  201. try {
  202. $this->rfs->getContents('packagist.org', $url, false);
  203. } catch (TransportException $e) {
  204. try {
  205. $this->rfs->getContents('packagist.org', $url, false, array('http' => array('request_fulluri' => false)));
  206. } catch (TransportException $e) {
  207. return 'Unable to assess the situation, maybe packagist.org is down ('.$e->getMessage().')';
  208. }
  209. 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"';
  210. }
  211. return true;
  212. }
  213. /**
  214. * Due to various proxy servers configurations, some servers can't handle non-standard HTTP "http_proxy_request_fulluri" parameter,
  215. * and will return error 500/501 (as not implemented), see discussion @ https://github.com/composer/composer/pull/1825.
  216. * This method will test, if you need to disable this parameter via setting extra environment variable in your system.
  217. *
  218. * @return bool|string
  219. */
  220. private function checkHttpsProxyFullUriRequestParam()
  221. {
  222. if (!extension_loaded('openssl')) {
  223. return 'You need the openssl extension installed for this check';
  224. }
  225. $url = 'https://api.github.com/repos/Seldaek/jsonlint/zipball/1.0.0';
  226. try {
  227. $this->rfs->getContents('github.com', $url, false);
  228. } catch (TransportException $e) {
  229. try {
  230. $this->rfs->getContents('github.com', $url, false, array('http' => array('request_fulluri' => false)));
  231. } catch (TransportException $e) {
  232. return 'Unable to assess the situation, maybe github is down ('.$e->getMessage().')';
  233. }
  234. return 'It seems there is a problem with your proxy server, try setting the "HTTPS_PROXY_REQUEST_FULLURI" environment variable to "false"';
  235. }
  236. return true;
  237. }
  238. private function checkGithubOauth($domain, $token)
  239. {
  240. $this->getIO()->setAuthentication($domain, $token, 'x-oauth-basic');
  241. try {
  242. $url = $domain === 'github.com' ? 'https://api.'.$domain.'/user/repos' : 'https://'.$domain.'/api/v3/user/repos';
  243. return $this->rfs->getContents($domain, $url, false, array(
  244. 'retry-auth-failure' => false,
  245. )) ? true : 'Unexpected error';
  246. } catch (\Exception $e) {
  247. if ($e instanceof TransportException && $e->getCode() === 401) {
  248. return '<comment>The oauth token for '.$domain.' seems invalid, run "composer config --global --unset github-oauth.'.$domain.'" to remove it</comment>';
  249. }
  250. return $e;
  251. }
  252. }
  253. /**
  254. * @param string $domain
  255. * @param string $token
  256. * @throws TransportException
  257. * @return array
  258. */
  259. private function getGithubRateLimit($domain, $token = null)
  260. {
  261. if ($token) {
  262. $this->getIO()->setAuthentication($domain, $token, 'x-oauth-basic');
  263. }
  264. $url = $domain === 'github.com' ? 'https://api.'.$domain.'/rate_limit' : 'https://'.$domain.'/api/rate_limit';
  265. $json = $this->rfs->getContents($domain, $url, false, array('retry-auth-failure' => false));
  266. $data = json_decode($json, true);
  267. return $data['resources']['core'];
  268. }
  269. private function checkDiskSpace($config)
  270. {
  271. $minSpaceFree = 1024 * 1024;
  272. if ((($df = @disk_free_space($dir = $config->get('home'))) !== false && $df < $minSpaceFree)
  273. || (($df = @disk_free_space($dir = $config->get('vendor-dir'))) !== false && $df < $minSpaceFree)
  274. ) {
  275. return '<error>The disk hosting '.$dir.' is full</error>';
  276. }
  277. return true;
  278. }
  279. private function checkVersion()
  280. {
  281. $protocol = extension_loaded('openssl') ? 'https' : 'http';
  282. $latest = trim($this->rfs->getContents('getcomposer.org', $protocol . '://getcomposer.org/version', false));
  283. if (Composer::VERSION !== $latest && Composer::VERSION !== '@package_version@') {
  284. return '<comment>You are not running the latest version, run `composer self-update` to update</comment>';
  285. }
  286. return true;
  287. }
  288. /**
  289. * @param bool|string|\Exception $result
  290. */
  291. private function outputResult($result)
  292. {
  293. $io = $this->getIO();
  294. if (true === $result) {
  295. $io->write('<info>OK</info>');
  296. } else {
  297. $this->failures++;
  298. $io->write('<error>FAIL</error>');
  299. if ($result instanceof \Exception) {
  300. $io->write('['.get_class($result).'] '.$result->getMessage());
  301. } elseif ($result) {
  302. if (is_array($result)) {
  303. foreach ($result as $message) {
  304. $io->write($message);
  305. }
  306. } else {
  307. $io->write($result);
  308. }
  309. }
  310. }
  311. }
  312. private function checkPlatform()
  313. {
  314. $output = '';
  315. $out = function ($msg, $style) use (&$output) {
  316. $output .= '<'.$style.'>'.$msg.'</'.$style.'>'.PHP_EOL;
  317. };
  318. // code below taken from getcomposer.org/installer, any changes should be made there and replicated here
  319. $errors = array();
  320. $warnings = array();
  321. $iniPath = php_ini_loaded_file();
  322. $displayIniMessage = false;
  323. if ($iniPath) {
  324. $iniMessage = PHP_EOL.PHP_EOL.'The php.ini used by your command-line PHP is: ' . $iniPath;
  325. } else {
  326. $iniMessage = PHP_EOL.PHP_EOL.'A php.ini file does not exist. You will have to create one.';
  327. }
  328. $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.';
  329. if (!function_exists('json_decode')) {
  330. $errors['json'] = true;
  331. }
  332. if (!extension_loaded('Phar')) {
  333. $errors['phar'] = true;
  334. }
  335. if (!extension_loaded('filter')) {
  336. $errors['filter'] = true;
  337. }
  338. if (!extension_loaded('hash')) {
  339. $errors['hash'] = true;
  340. }
  341. if (!ini_get('allow_url_fopen')) {
  342. $errors['allow_url_fopen'] = true;
  343. }
  344. if (extension_loaded('ionCube Loader') && ioncube_loader_iversion() < 40009) {
  345. $errors['ioncube'] = ioncube_loader_version();
  346. }
  347. if (PHP_VERSION_ID < 50302) {
  348. $errors['php'] = PHP_VERSION;
  349. }
  350. if (!isset($errors['php']) && PHP_VERSION_ID < 50304) {
  351. $warnings['php'] = PHP_VERSION;
  352. }
  353. if (!extension_loaded('openssl')) {
  354. $errors['openssl'] = true;
  355. }
  356. if (!defined('HHVM_VERSION') && !extension_loaded('apcu') && ini_get('apc.enable_cli')) {
  357. $warnings['apc_cli'] = true;
  358. }
  359. ob_start();
  360. phpinfo(INFO_GENERAL);
  361. $phpinfo = ob_get_clean();
  362. if (preg_match('{Configure Command(?: *</td><td class="v">| *=> *)(.*?)(?:</td>|$)}m', $phpinfo, $match)) {
  363. $configure = $match[1];
  364. if (false !== strpos($configure, '--enable-sigchild')) {
  365. $warnings['sigchild'] = true;
  366. }
  367. if (false !== strpos($configure, '--with-curlwrappers')) {
  368. $warnings['curlwrappers'] = true;
  369. }
  370. }
  371. if (ini_get('xdebug.profiler_enabled')) {
  372. $warnings['xdebug_profile'] = true;
  373. } elseif (extension_loaded('xdebug')) {
  374. $warnings['xdebug_loaded'] = true;
  375. }
  376. if (!empty($errors)) {
  377. foreach ($errors as $error => $current) {
  378. switch ($error) {
  379. case 'json':
  380. $text = PHP_EOL."The json extension is missing.".PHP_EOL;
  381. $text .= "Install it or recompile php without --disable-json";
  382. break;
  383. case 'phar':
  384. $text = PHP_EOL."The phar extension is missing.".PHP_EOL;
  385. $text .= "Install it or recompile php without --disable-phar";
  386. break;
  387. case 'filter':
  388. $text = PHP_EOL."The filter extension is missing.".PHP_EOL;
  389. $text .= "Install it or recompile php without --disable-filter";
  390. break;
  391. case 'hash':
  392. $text = PHP_EOL."The hash extension is missing.".PHP_EOL;
  393. $text .= "Install it or recompile php without --disable-hash";
  394. break;
  395. case 'unicode':
  396. $text = PHP_EOL."The detect_unicode setting must be disabled.".PHP_EOL;
  397. $text .= "Add the following to the end of your `php.ini`:".PHP_EOL;
  398. $text .= " detect_unicode = Off";
  399. $displayIniMessage = true;
  400. break;
  401. case 'suhosin':
  402. $text = PHP_EOL."The suhosin.executor.include.whitelist setting is incorrect.".PHP_EOL;
  403. $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;
  404. $text .= " suhosin.executor.include.whitelist = phar ".$current;
  405. $displayIniMessage = true;
  406. break;
  407. case 'php':
  408. $text = PHP_EOL."Your PHP ({$current}) is too old, you must upgrade to PHP 5.3.2 or higher.";
  409. break;
  410. case 'allow_url_fopen':
  411. $text = PHP_EOL."The allow_url_fopen setting is incorrect.".PHP_EOL;
  412. $text .= "Add the following to the end of your `php.ini`:".PHP_EOL;
  413. $text .= " allow_url_fopen = On";
  414. $displayIniMessage = true;
  415. break;
  416. case 'ioncube':
  417. $text = PHP_EOL."Your ionCube Loader extension ($current) is incompatible with Phar files.".PHP_EOL;
  418. $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;
  419. $text .= " zend_extension = /usr/lib/php5/20090626+lfs/ioncube_loader_lin_5.3.so";
  420. $displayIniMessage = true;
  421. break;
  422. case 'openssl':
  423. $text = PHP_EOL."The openssl extension is missing, which means that secure HTTPS transfers are impossible.".PHP_EOL;
  424. $text .= "If possible you should enable it or recompile php with --with-openssl";
  425. break;
  426. }
  427. $out($text, 'error');
  428. }
  429. $output .= PHP_EOL;
  430. }
  431. if (!empty($warnings)) {
  432. foreach ($warnings as $warning => $current) {
  433. switch ($warning) {
  434. case 'apc_cli':
  435. $text = "The apc.enable_cli setting is incorrect.".PHP_EOL;
  436. $text .= "Add the following to the end of your `php.ini`:".PHP_EOL;
  437. $text .= " apc.enable_cli = Off";
  438. $displayIniMessage = true;
  439. break;
  440. case 'sigchild':
  441. $text = "PHP was compiled with --enable-sigchild which can cause issues on some platforms.".PHP_EOL;
  442. $text .= "Recompile it without this flag if possible, see also:".PHP_EOL;
  443. $text .= " https://bugs.php.net/bug.php?id=22999";
  444. break;
  445. case 'curlwrappers':
  446. $text = "PHP was compiled with --with-curlwrappers which will cause issues with HTTP authentication and GitHub.".PHP_EOL;
  447. $text .= " Recompile it without this flag if possible";
  448. break;
  449. case 'php':
  450. $text = "Your PHP ({$current}) is quite old, upgrading to PHP 5.3.4 or higher is recommended.".PHP_EOL;
  451. $text .= " Composer works with 5.3.2+ for most people, but there might be edge case issues.";
  452. break;
  453. case 'xdebug_loaded':
  454. $text = "The xdebug extension is loaded, this can slow down Composer a little.".PHP_EOL;
  455. $text .= " Disabling it when using Composer is recommended.";
  456. break;
  457. case 'xdebug_profile':
  458. $text = "The xdebug.profiler_enabled setting is enabled, this can slow down Composer a lot.".PHP_EOL;
  459. $text .= "Add the following to the end of your `php.ini` to disable it:".PHP_EOL;
  460. $text .= " xdebug.profiler_enabled = 0";
  461. $displayIniMessage = true;
  462. break;
  463. }
  464. $out($text, 'comment');
  465. }
  466. }
  467. if ($displayIniMessage) {
  468. $out($iniMessage, 'comment');
  469. }
  470. return !$warnings && !$errors ? true : $output;
  471. }
  472. }