RemoteFilesystem.php 41 KB

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