DiagnoseCommand.php 21 KB

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