RemoteFilesystem.php 40 KB

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