RemoteFilesystem.php 44 KB

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