RemoteFilesystem.php 43 KB

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