RemoteFilesystem.php 45 KB

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