RemoteFilesystem.php 40 KB

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