RemoteFilesystem.php 41 KB

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