PageRenderTime 58ms CodeModel.GetById 23ms RepoModel.GetById 0ms app.codeStats 0ms

/drush/composer/vendor/composer/composer/src/Composer/Util/RemoteFilesystem.php

https://bitbucket.org/kbasarab/kbasarab_vim
PHP | 1043 lines | 670 code | 145 blank | 228 comment | 170 complexity | 54e27727f05cc34721f45a27b4966700 MD5 | raw file
Possible License(s): MIT
  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\Util;
  12. use Composer\Config;
  13. use Composer\IO\IOInterface;
  14. use Composer\Downloader\TransportException;
  15. /**
  16. * @author François Pluchino <francois.pluchino@opendisplay.com>
  17. * @author Jordi Boggiano <j.boggiano@seld.be>
  18. * @author Nils Adermann <naderman@naderman.de>
  19. */
  20. class RemoteFilesystem
  21. {
  22. private $io;
  23. private $config;
  24. private $scheme;
  25. private $bytesMax;
  26. private $originUrl;
  27. private $fileUrl;
  28. private $fileName;
  29. private $retry;
  30. private $progress;
  31. private $lastProgress;
  32. private $options = array();
  33. private $peerCertificateMap = array();
  34. private $disableTls = false;
  35. private $retryAuthFailure;
  36. private $lastHeaders;
  37. private $storeAuth;
  38. private $degradedMode = false;
  39. private $redirects;
  40. private $maxRedirects = 20;
  41. /**
  42. * Constructor.
  43. *
  44. * @param IOInterface $io The IO instance
  45. * @param Config $config The config
  46. * @param array $options The options
  47. * @param bool $disableTls
  48. */
  49. public function __construct(IOInterface $io, Config $config = null, array $options = array(), $disableTls = false)
  50. {
  51. $this->io = $io;
  52. // Setup TLS options
  53. // The cafile option can be set via config.json
  54. if ($disableTls === false) {
  55. $this->options = $this->getTlsDefaults($options);
  56. } else {
  57. $this->disableTls = true;
  58. }
  59. // handle the other externally set options normally.
  60. $this->options = array_replace_recursive($this->options, $options);
  61. $this->config = $config;
  62. }
  63. /**
  64. * Copy the remote file in local.
  65. *
  66. * @param string $originUrl The origin URL
  67. * @param string $fileUrl The file URL
  68. * @param string $fileName the local filename
  69. * @param bool $progress Display the progression
  70. * @param array $options Additional context options
  71. *
  72. * @return bool true
  73. */
  74. public function copy($originUrl, $fileUrl, $fileName, $progress = true, $options = array())
  75. {
  76. return $this->get($originUrl, $fileUrl, $options, $fileName, $progress);
  77. }
  78. /**
  79. * Get the content.
  80. *
  81. * @param string $originUrl The origin URL
  82. * @param string $fileUrl The file URL
  83. * @param bool $progress Display the progression
  84. * @param array $options Additional context options
  85. *
  86. * @return bool|string The content
  87. */
  88. public function getContents($originUrl, $fileUrl, $progress = true, $options = array())
  89. {
  90. return $this->get($originUrl, $fileUrl, $options, null, $progress);
  91. }
  92. /**
  93. * Retrieve the options set in the constructor
  94. *
  95. * @return array Options
  96. */
  97. public function getOptions()
  98. {
  99. return $this->options;
  100. }
  101. /**
  102. * Merges new options
  103. *
  104. * @return array $options
  105. */
  106. public function setOptions(array $options)
  107. {
  108. $this->options = array_replace_recursive($this->options, $options);
  109. }
  110. public function isTlsDisabled()
  111. {
  112. return $this->disableTls === true;
  113. }
  114. /**
  115. * Returns the headers of the last request
  116. *
  117. * @return array
  118. */
  119. public function getLastHeaders()
  120. {
  121. return $this->lastHeaders;
  122. }
  123. /**
  124. * @param array $headers array of returned headers like from getLastHeaders()
  125. * @param string $name header name (case insensitive)
  126. * @return string|null
  127. */
  128. public function findHeaderValue(array $headers, $name)
  129. {
  130. $value = null;
  131. foreach ($headers as $header) {
  132. if (preg_match('{^'.$name.':\s*(.+?)\s*$}i', $header, $match)) {
  133. $value = $match[1];
  134. } elseif (preg_match('{^HTTP/}i', $header)) {
  135. // In case of redirects, http_response_headers contains the headers of all responses
  136. // so we reset the flag when a new response is being parsed as we are only interested in the last response
  137. $value = null;
  138. }
  139. }
  140. return $value;
  141. }
  142. /**
  143. * @param array $headers array of returned headers like from getLastHeaders()
  144. * @return int|null
  145. */
  146. public function findStatusCode(array $headers)
  147. {
  148. $value = null;
  149. foreach ($headers as $header) {
  150. if (preg_match('{^HTTP/\S+ (\d+)}i', $header, $match)) {
  151. // In case of redirects, http_response_headers contains the headers of all responses
  152. // so we can not return directly and need to keep iterating
  153. $value = (int) $match[1];
  154. }
  155. }
  156. return $value;
  157. }
  158. /**
  159. * Get file content or copy action.
  160. *
  161. * @param string $originUrl The origin URL
  162. * @param string $fileUrl The file URL
  163. * @param array $additionalOptions context options
  164. * @param string $fileName the local filename
  165. * @param bool $progress Display the progression
  166. *
  167. * @throws TransportException|\Exception
  168. * @throws TransportException When the file could not be downloaded
  169. *
  170. * @return bool|string
  171. */
  172. protected function get($originUrl, $fileUrl, $additionalOptions = array(), $fileName = null, $progress = true)
  173. {
  174. if (strpos($originUrl, '.github.com') === (strlen($originUrl) - 11)) {
  175. $originUrl = 'github.com';
  176. }
  177. $this->scheme = parse_url($fileUrl, PHP_URL_SCHEME);
  178. $this->bytesMax = 0;
  179. $this->originUrl = $originUrl;
  180. $this->fileUrl = $fileUrl;
  181. $this->fileName = $fileName;
  182. $this->progress = $progress;
  183. $this->lastProgress = null;
  184. $this->retryAuthFailure = true;
  185. $this->lastHeaders = array();
  186. $this->redirects = 1; // The first request counts.
  187. // capture username/password from URL if there is one
  188. if (preg_match('{^https?://(.+):(.+)@([^/]+)}i', $fileUrl, $match)) {
  189. $this->io->setAuthentication($originUrl, urldecode($match[1]), urldecode($match[2]));
  190. }
  191. $tempAdditionalOptions = $additionalOptions;
  192. if (isset($tempAdditionalOptions['retry-auth-failure'])) {
  193. $this->retryAuthFailure = (bool) $tempAdditionalOptions['retry-auth-failure'];
  194. unset($tempAdditionalOptions['retry-auth-failure']);
  195. }
  196. $isRedirect = false;
  197. if (isset($tempAdditionalOptions['redirects'])) {
  198. $this->redirects = $tempAdditionalOptions['redirects'];
  199. $isRedirect = true;
  200. unset($tempAdditionalOptions['redirects']);
  201. }
  202. $options = $this->getOptionsForUrl($originUrl, $tempAdditionalOptions);
  203. unset($tempAdditionalOptions);
  204. $userlandFollow = isset($options['http']['follow_location']) && !$options['http']['follow_location'];
  205. $origFileUrl = $fileUrl;
  206. if (isset($options['github-token'])) {
  207. $fileUrl .= (false === strpos($fileUrl, '?') ? '?' : '&') . 'access_token='.$options['github-token'];
  208. unset($options['github-token']);
  209. }
  210. if (isset($options['gitlab-token'])) {
  211. $fileUrl .= (false === strpos($fileUrl, '?') ? '?' : '&') . 'access_token='.$options['gitlab-token'];
  212. unset($options['gitlab-token']);
  213. }
  214. if (isset($options['http'])) {
  215. $options['http']['ignore_errors'] = true;
  216. }
  217. if ($this->degradedMode && substr($fileUrl, 0, 21) === 'http://packagist.org/') {
  218. // access packagist using the resolved IPv4 instead of the hostname to force IPv4 protocol
  219. $fileUrl = 'http://' . gethostbyname('packagist.org') . substr($fileUrl, 20);
  220. }
  221. $ctx = StreamContextFactory::getContext($fileUrl, $options, array('notification' => array($this, 'callbackGet')));
  222. $actualContextOptions = stream_context_get_options($ctx);
  223. $usingProxy = !empty($actualContextOptions['http']['proxy']) ? ' using proxy ' . $actualContextOptions['http']['proxy'] : '';
  224. $this->io->writeError((substr($origFileUrl, 0, 4) === 'http' ? 'Downloading ' : 'Reading ') . $origFileUrl . $usingProxy, true, IOInterface::DEBUG);
  225. unset($origFileUrl, $actualContextOptions);
  226. if ($this->progress && !$isRedirect) {
  227. $this->io->writeError(" Downloading: <comment>Connecting...</comment>", false);
  228. }
  229. // Check for secure HTTP, but allow insecure Packagist calls to $hashed providers as file integrity is verified with sha256
  230. if ((substr($fileUrl, 0, 23) !== 'http://packagist.org/p/' || (false === strpos($fileUrl, '$') && false === strpos($fileUrl, '%24'))) && $this->config) {
  231. $this->config->prohibitUrlByConfig($fileUrl);
  232. }
  233. $errorMessage = '';
  234. $errorCode = 0;
  235. $result = false;
  236. set_error_handler(function ($code, $msg) use (&$errorMessage) {
  237. if ($errorMessage) {
  238. $errorMessage .= "\n";
  239. }
  240. $errorMessage .= preg_replace('{^file_get_contents\(.*?\): }', '', $msg);
  241. });
  242. try {
  243. $result = file_get_contents($fileUrl, false, $ctx);
  244. if (PHP_VERSION_ID < 50600 && !empty($options['ssl']['peer_fingerprint'])) {
  245. // Emulate fingerprint validation on PHP < 5.6
  246. $params = stream_context_get_params($ctx);
  247. $expectedPeerFingerprint = $options['ssl']['peer_fingerprint'];
  248. $peerFingerprint = TlsHelper::getCertificateFingerprint($params['options']['ssl']['peer_certificate']);
  249. // Constant time compare??!
  250. if ($expectedPeerFingerprint !== $peerFingerprint) {
  251. throw new TransportException('Peer fingerprint did not match');
  252. }
  253. }
  254. } catch (\Exception $e) {
  255. if ($e instanceof TransportException && !empty($http_response_header[0])) {
  256. $e->setHeaders($http_response_header);
  257. $e->setStatusCode($this->findStatusCode($http_response_header));
  258. }
  259. if ($e instanceof TransportException && $result !== false) {
  260. $e->setResponse($result);
  261. }
  262. $result = false;
  263. }
  264. if ($errorMessage && !ini_get('allow_url_fopen')) {
  265. $errorMessage = 'allow_url_fopen must be enabled in php.ini ('.$errorMessage.')';
  266. }
  267. restore_error_handler();
  268. if (isset($e) && !$this->retry) {
  269. if (!$this->degradedMode && false !== strpos($e->getMessage(), 'Operation timed out')) {
  270. $this->degradedMode = true;
  271. $this->io->writeError(array(
  272. '<error>'.$e->getMessage().'</error>',
  273. '<error>Retrying with degraded mode, check https://getcomposer.org/doc/articles/troubleshooting.md#degraded-mode for more info</error>',
  274. ));
  275. return $this->get($this->originUrl, $this->fileUrl, $additionalOptions, $this->fileName, $this->progress);
  276. }
  277. throw $e;
  278. }
  279. $statusCode = null;
  280. if (!empty($http_response_header[0])) {
  281. $statusCode = $this->findStatusCode($http_response_header);
  282. }
  283. // handle 3xx redirects for php<5.6, 304 Not Modified is excluded
  284. $hasFollowedRedirect = false;
  285. if ($userlandFollow && $statusCode >= 300 && $statusCode <= 399 && $statusCode !== 304 && $this->redirects < $this->maxRedirects) {
  286. $hasFollowedRedirect = true;
  287. $result = $this->handleRedirect($http_response_header, $additionalOptions, $result);
  288. }
  289. // fail 4xx and 5xx responses and capture the response
  290. if ($statusCode && $statusCode >= 400 && $statusCode <= 599) {
  291. if (!$this->retry) {
  292. if ($this->progress && !$this->retry && !$isRedirect) {
  293. $this->io->overwriteError(" Downloading: <error>Failed</error>");
  294. }
  295. $e = new TransportException('The "'.$this->fileUrl.'" file could not be downloaded ('.$http_response_header[0].')', $statusCode);
  296. $e->setHeaders($http_response_header);
  297. $e->setResponse($result);
  298. $e->setStatusCode($statusCode);
  299. throw $e;
  300. }
  301. $result = false;
  302. }
  303. if ($this->progress && !$this->retry && !$isRedirect) {
  304. $this->io->overwriteError(" Downloading: ".($result === false ? '<error>Failed</error>' : '<comment>100%</comment>'));
  305. }
  306. // decode gzip
  307. if ($result && extension_loaded('zlib') && substr($fileUrl, 0, 4) === 'http' && !$hasFollowedRedirect) {
  308. $decode = 'gzip' === strtolower($this->findHeaderValue($http_response_header, 'content-encoding'));
  309. if ($decode) {
  310. try {
  311. if (PHP_VERSION_ID >= 50400) {
  312. $result = zlib_decode($result);
  313. } else {
  314. // work around issue with gzuncompress & co that do not work with all gzip checksums
  315. $result = file_get_contents('compress.zlib://data:application/octet-stream;base64,'.base64_encode($result));
  316. }
  317. if (!$result) {
  318. throw new TransportException('Failed to decode zlib stream');
  319. }
  320. } catch (\Exception $e) {
  321. if ($this->degradedMode) {
  322. throw $e;
  323. }
  324. $this->degradedMode = true;
  325. $this->io->writeError(array(
  326. '<error>Failed to decode response: '.$e->getMessage().'</error>',
  327. '<error>Retrying with degraded mode, check https://getcomposer.org/doc/articles/troubleshooting.md#degraded-mode for more info</error>',
  328. ));
  329. return $this->get($this->originUrl, $this->fileUrl, $additionalOptions, $this->fileName, $this->progress);
  330. }
  331. }
  332. }
  333. // handle copy command if download was successful
  334. if (false !== $result && null !== $fileName && !$isRedirect) {
  335. if ('' === $result) {
  336. throw new TransportException('"'.$this->fileUrl.'" appears broken, and returned an empty 200 response');
  337. }
  338. $errorMessage = '';
  339. set_error_handler(function ($code, $msg) use (&$errorMessage) {
  340. if ($errorMessage) {
  341. $errorMessage .= "\n";
  342. }
  343. $errorMessage .= preg_replace('{^file_put_contents\(.*?\): }', '', $msg);
  344. });
  345. $result = (bool) file_put_contents($fileName, $result);
  346. restore_error_handler();
  347. if (false === $result) {
  348. throw new TransportException('The "'.$this->fileUrl.'" file could not be written to '.$fileName.': '.$errorMessage);
  349. }
  350. }
  351. // Handle SSL cert match issues
  352. if (false === $result && false !== strpos($errorMessage, 'Peer certificate') && PHP_VERSION_ID < 50600) {
  353. // Certificate name error, PHP doesn't support subjectAltName on PHP < 5.6
  354. // The procedure to handle sAN for older PHP's is:
  355. //
  356. // 1. Open socket to remote server and fetch certificate (disabling peer
  357. // validation because PHP errors without giving up the certificate.)
  358. //
  359. // 2. Verifying the domain in the URL against the names in the sAN field.
  360. // If there is a match record the authority [host/port], certificate
  361. // common name, and certificate fingerprint.
  362. //
  363. // 3. Retry the original request but changing the CN_match parameter to
  364. // the common name extracted from the certificate in step 2.
  365. //
  366. // 4. To prevent any attempt at being hoodwinked by switching the
  367. // certificate between steps 2 and 3 the fingerprint of the certificate
  368. // presented in step 3 is compared against the one recorded in step 2.
  369. if (TlsHelper::isOpensslParseSafe()) {
  370. $certDetails = $this->getCertificateCnAndFp($this->fileUrl, $options);
  371. if ($certDetails) {
  372. $this->peerCertificateMap[$this->getUrlAuthority($this->fileUrl)] = $certDetails;
  373. $this->retry = true;
  374. }
  375. } else {
  376. $this->io->writeError(sprintf(
  377. '<error>Your version of PHP, %s, is affected by CVE-2013-6420 and cannot safely perform certificate validation, we strongly suggest you upgrade.</error>',
  378. PHP_VERSION
  379. ));
  380. }
  381. }
  382. if ($this->retry) {
  383. $this->retry = false;
  384. $result = $this->get($this->originUrl, $this->fileUrl, $additionalOptions, $this->fileName, $this->progress);
  385. if ($this->storeAuth && $this->config) {
  386. $authHelper = new AuthHelper($this->io, $this->config);
  387. $authHelper->storeAuth($this->originUrl, $this->storeAuth);
  388. $this->storeAuth = false;
  389. }
  390. return $result;
  391. }
  392. if (false === $result) {
  393. $e = new TransportException('The "'.$this->fileUrl.'" file could not be downloaded: '.$errorMessage, $errorCode);
  394. if (!empty($http_response_header[0])) {
  395. $e->setHeaders($http_response_header);
  396. }
  397. if (!$this->degradedMode && false !== strpos($e->getMessage(), 'Operation timed out')) {
  398. $this->degradedMode = true;
  399. $this->io->writeError(array(
  400. '<error>'.$e->getMessage().'</error>',
  401. '<error>Retrying with degraded mode, check https://getcomposer.org/doc/articles/troubleshooting.md#degraded-mode for more info</error>',
  402. ));
  403. return $this->get($this->originUrl, $this->fileUrl, $additionalOptions, $this->fileName, $this->progress);
  404. }
  405. throw $e;
  406. }
  407. if (!empty($http_response_header[0])) {
  408. $this->lastHeaders = $http_response_header;
  409. }
  410. return $result;
  411. }
  412. /**
  413. * Get notification action.
  414. *
  415. * @param int $notificationCode The notification code
  416. * @param int $severity The severity level
  417. * @param string $message The message
  418. * @param int $messageCode The message code
  419. * @param int $bytesTransferred The loaded size
  420. * @param int $bytesMax The total size
  421. * @throws TransportException
  422. */
  423. protected function callbackGet($notificationCode, $severity, $message, $messageCode, $bytesTransferred, $bytesMax)
  424. {
  425. switch ($notificationCode) {
  426. case STREAM_NOTIFY_FAILURE:
  427. if (400 === $messageCode) {
  428. // This might happen if your host is secured by ssl client certificate authentication
  429. // but you do not send an appropriate certificate
  430. throw new TransportException("The '" . $this->fileUrl . "' URL could not be accessed: " . $message, $messageCode);
  431. }
  432. // intentional fallthrough to the next case as the notificationCode
  433. // isn't always consistent and we should inspect the messageCode for 401s
  434. case STREAM_NOTIFY_AUTH_REQUIRED:
  435. if (401 === $messageCode) {
  436. // Bail if the caller is going to handle authentication failures itself.
  437. if (!$this->retryAuthFailure) {
  438. break;
  439. }
  440. $this->promptAuthAndRetry($messageCode);
  441. }
  442. break;
  443. case STREAM_NOTIFY_AUTH_RESULT:
  444. if (403 === $messageCode) {
  445. // Bail if the caller is going to handle authentication failures itself.
  446. if (!$this->retryAuthFailure) {
  447. break;
  448. }
  449. $this->promptAuthAndRetry($messageCode, $message);
  450. }
  451. break;
  452. case STREAM_NOTIFY_FILE_SIZE_IS:
  453. if ($this->bytesMax < $bytesMax) {
  454. $this->bytesMax = $bytesMax;
  455. }
  456. break;
  457. case STREAM_NOTIFY_PROGRESS:
  458. if ($this->bytesMax > 0 && $this->progress) {
  459. $progression = round($bytesTransferred / $this->bytesMax * 100);
  460. if ((0 === $progression % 5) && 100 !== $progression && $progression !== $this->lastProgress) {
  461. $this->lastProgress = $progression;
  462. $this->io->overwriteError(" Downloading: <comment>$progression%</comment>", false);
  463. }
  464. }
  465. break;
  466. default:
  467. break;
  468. }
  469. }
  470. protected function promptAuthAndRetry($httpStatus, $reason = null)
  471. {
  472. if ($this->config && in_array($this->originUrl, $this->config->get('github-domains'), true)) {
  473. $message = "\n".'Could not fetch '.$this->fileUrl.', please create a GitHub OAuth token '.($httpStatus === 404 ? 'to access private repos' : 'to go over the API rate limit');
  474. $gitHubUtil = new GitHub($this->io, $this->config, null);
  475. if (!$gitHubUtil->authorizeOAuth($this->originUrl)
  476. && (!$this->io->isInteractive() || !$gitHubUtil->authorizeOAuthInteractively($this->originUrl, $message))
  477. ) {
  478. throw new TransportException('Could not authenticate against '.$this->originUrl, 401);
  479. }
  480. } elseif ($this->config && in_array($this->originUrl, $this->config->get('gitlab-domains'), true)) {
  481. $message = "\n".'Could not fetch '.$this->fileUrl.', enter your ' . $this->originUrl . ' credentials ' .($httpStatus === 401 ? 'to access private repos' : 'to go over the API rate limit');
  482. $gitLabUtil = new GitLab($this->io, $this->config, null);
  483. if (!$gitLabUtil->authorizeOAuth($this->originUrl)
  484. && (!$this->io->isInteractive() || !$gitLabUtil->authorizeOAuthInteractively($this->scheme, $this->originUrl, $message))
  485. ) {
  486. throw new TransportException('Could not authenticate against '.$this->originUrl, 401);
  487. }
  488. } else {
  489. // 404s are only handled for github
  490. if ($httpStatus === 404) {
  491. return;
  492. }
  493. // fail if the console is not interactive
  494. if (!$this->io->isInteractive()) {
  495. if ($httpStatus === 401) {
  496. $message = "The '" . $this->fileUrl . "' URL required authentication.\nYou must be using the interactive console to authenticate";
  497. }
  498. if ($httpStatus === 403) {
  499. $message = "The '" . $this->fileUrl . "' URL could not be accessed: " . $reason;
  500. }
  501. throw new TransportException($message, $httpStatus);
  502. }
  503. // fail if we already have auth
  504. if ($this->io->hasAuthentication($this->originUrl)) {
  505. throw new TransportException("Invalid credentials for '" . $this->fileUrl . "', aborting.", $httpStatus);
  506. }
  507. $this->io->overwriteError(' Authentication required (<info>'.parse_url($this->fileUrl, PHP_URL_HOST).'</info>):');
  508. $username = $this->io->ask(' Username: ');
  509. $password = $this->io->askAndHideAnswer(' Password: ');
  510. $this->io->setAuthentication($this->originUrl, $username, $password);
  511. $this->storeAuth = $this->config->get('store-auths');
  512. }
  513. $this->retry = true;
  514. throw new TransportException('RETRY');
  515. }
  516. protected function getOptionsForUrl($originUrl, $additionalOptions)
  517. {
  518. $tlsOptions = array();
  519. // Setup remaining TLS options - the matching may need monitoring, esp. www vs none in CN
  520. if ($this->disableTls === false && PHP_VERSION_ID < 50600 && !stream_is_local($this->fileUrl)) {
  521. $host = parse_url($this->fileUrl, PHP_URL_HOST);
  522. if (PHP_VERSION_ID >= 50304) {
  523. // Must manually follow when setting CN_match because this causes all
  524. // redirects to be validated against the same CN_match value.
  525. $userlandFollow = true;
  526. } else {
  527. // PHP < 5.3.4 does not support follow_location, for those people
  528. // do some really nasty hard coded transformations. These will
  529. // still breakdown if the site redirects to a domain we don't
  530. // expect.
  531. if ($host === 'github.com' || $host === 'api.github.com') {
  532. $host = '*.github.com';
  533. }
  534. }
  535. $tlsOptions['ssl']['CN_match'] = $host;
  536. $tlsOptions['ssl']['SNI_server_name'] = $host;
  537. $urlAuthority = $this->getUrlAuthority($this->fileUrl);
  538. if (isset($this->peerCertificateMap[$urlAuthority])) {
  539. // Handle subjectAltName on lesser PHP's.
  540. $certMap = $this->peerCertificateMap[$urlAuthority];
  541. $this->io->writeError(sprintf(
  542. 'Using <info>%s</info> as CN for subjectAltName enabled host <info>%s</info>',
  543. $certMap['cn'],
  544. $urlAuthority
  545. ), true, IOInterface::DEBUG);
  546. $tlsOptions['ssl']['CN_match'] = $certMap['cn'];
  547. $tlsOptions['ssl']['peer_fingerprint'] = $certMap['fp'];
  548. }
  549. }
  550. $headers = array();
  551. if (extension_loaded('zlib')) {
  552. $headers[] = 'Accept-Encoding: gzip';
  553. }
  554. $options = array_replace_recursive($this->options, $tlsOptions, $additionalOptions);
  555. if (!$this->degradedMode) {
  556. // degraded mode disables HTTP/1.1 which causes issues with some bad
  557. // proxies/software due to the use of chunked encoding
  558. $options['http']['protocol_version'] = 1.1;
  559. $headers[] = 'Connection: close';
  560. }
  561. if (isset($userlandFollow)) {
  562. $options['http']['follow_location'] = 0;
  563. }
  564. if ($this->io->hasAuthentication($originUrl)) {
  565. $auth = $this->io->getAuthentication($originUrl);
  566. if ('github.com' === $originUrl && 'x-oauth-basic' === $auth['password']) {
  567. $options['github-token'] = $auth['username'];
  568. } elseif ($this->config && in_array($originUrl, $this->config->get('gitlab-domains'), true)) {
  569. if ($auth['password'] === 'oauth2') {
  570. $headers[] = 'Authorization: Bearer '.$auth['username'];
  571. }
  572. } else {
  573. $authStr = base64_encode($auth['username'] . ':' . $auth['password']);
  574. $headers[] = 'Authorization: Basic '.$authStr;
  575. }
  576. }
  577. if (isset($options['http']['header']) && !is_array($options['http']['header'])) {
  578. $options['http']['header'] = explode("\r\n", trim($options['http']['header'], "\r\n"));
  579. }
  580. foreach ($headers as $header) {
  581. $options['http']['header'][] = $header;
  582. }
  583. return $options;
  584. }
  585. private function handleRedirect(array $http_response_header, array $additionalOptions, $result)
  586. {
  587. if ($locationHeader = $this->findHeaderValue($http_response_header, 'location')) {
  588. if (parse_url($locationHeader, PHP_URL_SCHEME)) {
  589. // Absolute URL; e.g. https://example.com/composer
  590. $targetUrl = $locationHeader;
  591. } elseif (parse_url($locationHeader, PHP_URL_HOST)) {
  592. // Scheme relative; e.g. //example.com/foo
  593. $targetUrl = $this->scheme.':'.$locationHeader;
  594. } elseif ('/' === $locationHeader[0]) {
  595. // Absolute path; e.g. /foo
  596. $urlHost = parse_url($this->fileUrl, PHP_URL_HOST);
  597. // Replace path using hostname as an anchor.
  598. $targetUrl = preg_replace('{^(.+(?://|@)'.preg_quote($urlHost).'(?::\d+)?)(?:[/\?].*)?$}', '\1'.$locationHeader, $this->fileUrl);
  599. } else {
  600. // Relative path; e.g. foo
  601. // This actually differs from PHP which seems to add duplicate slashes.
  602. $targetUrl = preg_replace('{^(.+/)[^/?]*(?:\?.*)?$}', '\1'.$locationHeader, $this->fileUrl);
  603. }
  604. }
  605. if (!empty($targetUrl)) {
  606. $this->redirects++;
  607. $this->io->writeError(sprintf('Following redirect (%u) %s', $this->redirects, $targetUrl), true, IOInterface::DEBUG);
  608. $additionalOptions['redirects'] = $this->redirects;
  609. return $this->get($this->originUrl, $targetUrl, $additionalOptions, $this->fileName, $this->progress);
  610. }
  611. if (!$this->retry) {
  612. $e = new TransportException('The "'.$this->fileUrl.'" file could not be downloaded, got redirect without Location ('.$http_response_header[0].')');
  613. $e->setHeaders($http_response_header);
  614. $e->setResponse($result);
  615. throw $e;
  616. }
  617. return false;
  618. }
  619. /**
  620. * @param array $options
  621. *
  622. * @return array
  623. */
  624. private function getTlsDefaults(array $options)
  625. {
  626. $ciphers = implode(':', array(
  627. 'ECDHE-RSA-AES128-GCM-SHA256',
  628. 'ECDHE-ECDSA-AES128-GCM-SHA256',
  629. 'ECDHE-RSA-AES256-GCM-SHA384',
  630. 'ECDHE-ECDSA-AES256-GCM-SHA384',
  631. 'DHE-RSA-AES128-GCM-SHA256',
  632. 'DHE-DSS-AES128-GCM-SHA256',
  633. 'kEDH+AESGCM',
  634. 'ECDHE-RSA-AES128-SHA256',
  635. 'ECDHE-ECDSA-AES128-SHA256',
  636. 'ECDHE-RSA-AES128-SHA',
  637. 'ECDHE-ECDSA-AES128-SHA',
  638. 'ECDHE-RSA-AES256-SHA384',
  639. 'ECDHE-ECDSA-AES256-SHA384',
  640. 'ECDHE-RSA-AES256-SHA',
  641. 'ECDHE-ECDSA-AES256-SHA',
  642. 'DHE-RSA-AES128-SHA256',
  643. 'DHE-RSA-AES128-SHA',
  644. 'DHE-DSS-AES128-SHA256',
  645. 'DHE-RSA-AES256-SHA256',
  646. 'DHE-DSS-AES256-SHA',
  647. 'DHE-RSA-AES256-SHA',
  648. 'AES128-GCM-SHA256',
  649. 'AES256-GCM-SHA384',
  650. 'ECDHE-RSA-RC4-SHA',
  651. 'ECDHE-ECDSA-RC4-SHA',
  652. 'AES128',
  653. 'AES256',
  654. 'RC4-SHA',
  655. 'HIGH',
  656. '!aNULL',
  657. '!eNULL',
  658. '!EXPORT',
  659. '!DES',
  660. '!3DES',
  661. '!MD5',
  662. '!PSK',
  663. ));
  664. /**
  665. * CN_match and SNI_server_name are only known once a URL is passed.
  666. * They will be set in the getOptionsForUrl() method which receives a URL.
  667. *
  668. * cafile or capath can be overridden by passing in those options to constructor.
  669. */
  670. $defaults = array(
  671. 'ssl' => array(
  672. 'ciphers' => $ciphers,
  673. 'verify_peer' => true,
  674. 'verify_depth' => 7,
  675. 'SNI_enabled' => true,
  676. 'capture_peer_cert' => true,
  677. ),
  678. );
  679. if (isset($options['ssl'])) {
  680. $defaults['ssl'] = array_replace_recursive($defaults['ssl'], $options['ssl']);
  681. }
  682. /**
  683. * Attempt to find a local cafile or throw an exception if none pre-set
  684. * The user may go download one if this occurs.
  685. */
  686. if (!isset($defaults['ssl']['cafile']) && !isset($defaults['ssl']['capath'])) {
  687. $result = $this->getSystemCaRootBundlePath();
  688. if (preg_match('{^phar://}', $result)) {
  689. $hash = hash_file('sha256', $result);
  690. $targetPath = rtrim(sys_get_temp_dir(), '\\/') . '/composer-cacert-' . $hash . '.pem';
  691. if (!file_exists($targetPath) || $hash !== hash_file('sha256', $targetPath)) {
  692. $this->streamCopy($result, $targetPath);
  693. chmod($targetPath, 0666);
  694. }
  695. $defaults['ssl']['cafile'] = $targetPath;
  696. } elseif (is_dir($result)) {
  697. $defaults['ssl']['capath'] = $result;
  698. } else {
  699. $defaults['ssl']['cafile'] = $result;
  700. }
  701. }
  702. if (isset($defaults['ssl']['cafile']) && (!is_readable($defaults['ssl']['cafile']) || !$this->validateCaFile($defaults['ssl']['cafile']))) {
  703. throw new TransportException('The configured cafile was not valid or could not be read.');
  704. }
  705. if (isset($defaults['ssl']['capath']) && (!is_dir($defaults['ssl']['capath']) || !is_readable($defaults['ssl']['capath']))) {
  706. throw new TransportException('The configured capath was not valid or could not be read.');
  707. }
  708. /**
  709. * Disable TLS compression to prevent CRIME attacks where supported.
  710. */
  711. if (PHP_VERSION_ID >= 50413) {
  712. $defaults['ssl']['disable_compression'] = true;
  713. }
  714. return $defaults;
  715. }
  716. /**
  717. * This method was adapted from Sslurp.
  718. * https://github.com/EvanDotPro/Sslurp
  719. *
  720. * (c) Evan Coury <me@evancoury.com>
  721. *
  722. * For the full copyright and license information, please see below:
  723. *
  724. * Copyright (c) 2013, Evan Coury
  725. * All rights reserved.
  726. *
  727. * Redistribution and use in source and binary forms, with or without modification,
  728. * are permitted provided that the following conditions are met:
  729. *
  730. * * Redistributions of source code must retain the above copyright notice,
  731. * this list of conditions and the following disclaimer.
  732. *
  733. * * Redistributions in binary form must reproduce the above copyright notice,
  734. * this list of conditions and the following disclaimer in the documentation
  735. * and/or other materials provided with the distribution.
  736. *
  737. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
  738. * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  739. * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  740. * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
  741. * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  742. * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  743. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
  744. * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  745. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  746. * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  747. *
  748. * @return string
  749. */
  750. private function getSystemCaRootBundlePath()
  751. {
  752. static $caPath = null;
  753. if ($caPath !== null) {
  754. return $caPath;
  755. }
  756. // If SSL_CERT_FILE env variable points to a valid certificate/bundle, use that.
  757. // This mimics how OpenSSL uses the SSL_CERT_FILE env variable.
  758. $envCertFile = getenv('SSL_CERT_FILE');
  759. if ($envCertFile && is_readable($envCertFile) && $this->validateCaFile($envCertFile)) {
  760. return $caPath = $envCertFile;
  761. }
  762. // If SSL_CERT_DIR env variable points to a valid certificate/bundle, use that.
  763. // This mimics how OpenSSL uses the SSL_CERT_FILE env variable.
  764. $envCertDir = getenv('SSL_CERT_DIR');
  765. if ($envCertDir && is_dir($envCertDir) && is_readable($envCertDir)) {
  766. return $caPath = $envCertDir;
  767. }
  768. $configured = ini_get('openssl.cafile');
  769. if ($configured && strlen($configured) > 0 && is_readable($configured) && $this->validateCaFile($configured)) {
  770. return $caPath = $configured;
  771. }
  772. $configured = ini_get('openssl.capath');
  773. if ($configured && is_dir($configured) && is_readable($configured)) {
  774. return $caPath = $configured;
  775. }
  776. $caBundlePaths = array(
  777. '/etc/pki/tls/certs/ca-bundle.crt', // Fedora, RHEL, CentOS (ca-certificates package)
  778. '/etc/ssl/certs/ca-certificates.crt', // Debian, Ubuntu, Gentoo, Arch Linux (ca-certificates package)
  779. '/etc/ssl/ca-bundle.pem', // SUSE, openSUSE (ca-certificates package)
  780. '/usr/local/share/certs/ca-root-nss.crt', // FreeBSD (ca_root_nss_package)
  781. '/usr/ssl/certs/ca-bundle.crt', // Cygwin
  782. '/opt/local/share/curl/curl-ca-bundle.crt', // OS X macports, curl-ca-bundle package
  783. '/usr/local/share/curl/curl-ca-bundle.crt', // Default cURL CA bunde path (without --with-ca-bundle option)
  784. '/usr/share/ssl/certs/ca-bundle.crt', // Really old RedHat?
  785. '/etc/ssl/cert.pem', // OpenBSD
  786. '/usr/local/etc/ssl/cert.pem', // FreeBSD 10.x
  787. );
  788. foreach ($caBundlePaths as $caBundle) {
  789. if (Silencer::call('is_readable', $caBundle) && $this->validateCaFile($caBundle)) {
  790. return $caPath = $caBundle;
  791. }
  792. }
  793. foreach ($caBundlePaths as $caBundle) {
  794. $caBundle = dirname($caBundle);
  795. if (is_dir($caBundle) && glob($caBundle.'/*')) {
  796. return $caPath = $caBundle;
  797. }
  798. }
  799. return $caPath = __DIR__.'/../../../res/cacert.pem'; // Bundled with Composer, last resort
  800. }
  801. /**
  802. * @param string $filename
  803. *
  804. * @return bool
  805. */
  806. private function validateCaFile($filename)
  807. {
  808. static $files = array();
  809. if (isset($files[$filename])) {
  810. return $files[$filename];
  811. }
  812. $this->io->writeError('Checking CA file '.realpath($filename), true, IOInterface::DEBUG);
  813. $contents = file_get_contents($filename);
  814. // assume the CA is valid if php is vulnerable to
  815. // https://www.sektioneins.de/advisories/advisory-012013-php-openssl_x509_parse-memory-corruption-vulnerability.html
  816. if (!TlsHelper::isOpensslParseSafe()) {
  817. $this->io->writeError(sprintf(
  818. '<error>Your version of PHP, %s, is affected by CVE-2013-6420 and cannot safely perform certificate validation, we strongly suggest you upgrade.</error>',
  819. PHP_VERSION
  820. ));
  821. return $files[$filename] = !empty($contents);
  822. }
  823. return $files[$filename] = (bool) openssl_x509_parse($contents);
  824. }
  825. /**
  826. * Uses stream_copy_to_stream instead of copy to work around https://bugs.php.net/bug.php?id=64634
  827. *
  828. * @param string $source
  829. * @param string $target
  830. */
  831. private function streamCopy($source, $target)
  832. {
  833. $source = fopen($source, 'r');
  834. $target = fopen($target, 'w+');
  835. stream_copy_to_stream($source, $target);
  836. fclose($source);
  837. fclose($target);
  838. unset($source, $target);
  839. }
  840. /**
  841. * Fetch certificate common name and fingerprint for validation of SAN.
  842. *
  843. * @todo Remove when PHP 5.6 is minimum supported version.
  844. */
  845. private function getCertificateCnAndFp($url, $options)
  846. {
  847. if (PHP_VERSION_ID >= 50600) {
  848. throw new \BadMethodCallException(sprintf(
  849. '%s must not be used on PHP >= 5.6',
  850. __METHOD__
  851. ));
  852. }
  853. $context = StreamContextFactory::getContext($url, $options, array('options' => array(
  854. 'ssl' => array(
  855. 'capture_peer_cert' => true,
  856. 'verify_peer' => false, // Yes this is fucking insane! But PHP is lame.
  857. ), ),
  858. ));
  859. // Ideally this would just use stream_socket_client() to avoid sending a
  860. // HTTP request but that does not capture the certificate.
  861. if (false === $handle = @fopen($url, 'rb', false, $context)) {
  862. return;
  863. }
  864. // Close non authenticated connection without reading any content.
  865. fclose($handle);
  866. $handle = null;
  867. $params = stream_context_get_params($context);
  868. if (!empty($params['options']['ssl']['peer_certificate'])) {
  869. $peerCertificate = $params['options']['ssl']['peer_certificate'];
  870. if (TlsHelper::checkCertificateHost($peerCertificate, parse_url($url, PHP_URL_HOST), $commonName)) {
  871. return array(
  872. 'cn' => $commonName,
  873. 'fp' => TlsHelper::getCertificateFingerprint($peerCertificate),
  874. );
  875. }
  876. }
  877. }
  878. private function getUrlAuthority($url)
  879. {
  880. $defaultPorts = array(
  881. 'ftp' => 21,
  882. 'http' => 80,
  883. 'https' => 443,
  884. 'ssh2.sftp' => 22,
  885. 'ssh2.scp' => 22,
  886. );
  887. $scheme = parse_url($url, PHP_URL_SCHEME);
  888. if (!isset($defaultPorts[$scheme])) {
  889. throw new \InvalidArgumentException(sprintf(
  890. 'Could not get default port for unknown scheme: %s',
  891. $scheme
  892. ));
  893. }
  894. $defaultPort = $defaultPorts[$scheme];
  895. $port = parse_url($url, PHP_URL_PORT) ?: $defaultPort;
  896. return parse_url($url, PHP_URL_HOST).':'.$port;
  897. }
  898. }