RemoteFilesystem.php 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990
  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. private $bitBucketUrlsTriedWithoutAuth = array();
  44. /**
  45. * Constructor.
  46. *
  47. * @param IOInterface $io The IO instance
  48. * @param Config $config The config
  49. * @param array $options The options
  50. * @param bool $disableTls
  51. */
  52. public function __construct(IOInterface $io, Config $config = null, array $options = array(), $disableTls = false)
  53. {
  54. $this->io = $io;
  55. // Setup TLS options
  56. // The cafile option can be set via config.json
  57. if ($disableTls === false) {
  58. $this->options = $this->getTlsDefaults($options);
  59. } else {
  60. $this->disableTls = true;
  61. }
  62. // handle the other externally set options normally.
  63. $this->options = array_replace_recursive($this->options, $options);
  64. $this->config = $config;
  65. }
  66. /**
  67. * Copy the remote file in local.
  68. *
  69. * @param string $originUrl The origin URL
  70. * @param string $fileUrl The file URL
  71. * @param string $fileName the local filename
  72. * @param bool $progress Display the progression
  73. * @param array $options Additional context options
  74. *
  75. * @return bool true
  76. */
  77. public function copy($originUrl, $fileUrl, $fileName, $progress = true, $options = array())
  78. {
  79. return $this->get($originUrl, $fileUrl, $options, $fileName, $progress);
  80. }
  81. /**
  82. * Get the content.
  83. *
  84. * @param string $originUrl The origin URL
  85. * @param string $fileUrl The file URL
  86. * @param bool $progress Display the progression
  87. * @param array $options Additional context options
  88. *
  89. * @return bool|string The content
  90. */
  91. public function getContents($originUrl, $fileUrl, $progress = true, $options = array())
  92. {
  93. return $this->get($originUrl, $fileUrl, $options, null, $progress);
  94. }
  95. /**
  96. * Retrieve the options set in the constructor
  97. *
  98. * @return array Options
  99. */
  100. public function getOptions()
  101. {
  102. return $this->options;
  103. }
  104. /**
  105. * Merges new options
  106. *
  107. * @return array $options
  108. */
  109. public function setOptions(array $options)
  110. {
  111. $this->options = array_replace_recursive($this->options, $options);
  112. }
  113. public function isTlsDisabled()
  114. {
  115. return $this->disableTls === true;
  116. }
  117. /**
  118. * Returns the headers of the last request
  119. *
  120. * @return array
  121. */
  122. public function getLastHeaders()
  123. {
  124. return $this->lastHeaders;
  125. }
  126. /**
  127. * @param array $headers array of returned headers like from getLastHeaders()
  128. * @param string $name header name (case insensitive)
  129. * @return string|null
  130. */
  131. public function findHeaderValue(array $headers, $name)
  132. {
  133. $value = null;
  134. foreach ($headers as $header) {
  135. if (preg_match('{^'.$name.':\s*(.+?)\s*$}i', $header, $match)) {
  136. $value = $match[1];
  137. } elseif (preg_match('{^HTTP/}i', $header)) {
  138. // In case of redirects, http_response_headers contains the headers of all responses
  139. // so we reset the flag when a new response is being parsed as we are only interested in the last response
  140. $value = null;
  141. }
  142. }
  143. return $value;
  144. }
  145. /**
  146. * @param array $headers array of returned headers like from getLastHeaders()
  147. * @return int|null
  148. */
  149. public function findStatusCode(array $headers)
  150. {
  151. $value = null;
  152. foreach ($headers as $header) {
  153. if (preg_match('{^HTTP/\S+ (\d+)}i', $header, $match)) {
  154. // In case of redirects, http_response_headers contains the headers of all responses
  155. // so we can not return directly and need to keep iterating
  156. $value = (int) $match[1];
  157. }
  158. }
  159. return $value;
  160. }
  161. /**
  162. * Get file content or copy action.
  163. *
  164. * @param string $originUrl The origin URL
  165. * @param string $fileUrl The file URL
  166. * @param array $additionalOptions context options
  167. * @param string $fileName the local filename
  168. * @param bool $progress Display the progression
  169. *
  170. * @throws TransportException|\Exception
  171. * @throws TransportException When the file could not be downloaded
  172. *
  173. * @return bool|string
  174. */
  175. protected function get($originUrl, $fileUrl, $additionalOptions = array(), $fileName = null, $progress = true)
  176. {
  177. if (strpos($originUrl, '.github.com') === (strlen($originUrl) - 11)) {
  178. $originUrl = 'github.com';
  179. }
  180. $this->scheme = parse_url($fileUrl, PHP_URL_SCHEME);
  181. $this->bytesMax = 0;
  182. $this->originUrl = $originUrl;
  183. $this->fileUrl = $fileUrl;
  184. $this->fileName = $fileName;
  185. $this->progress = $progress;
  186. $this->lastProgress = null;
  187. $this->retryAuthFailure = true;
  188. $this->lastHeaders = array();
  189. $this->redirects = 1; // The first request counts.
  190. // capture username/password from URL if there is one
  191. if (preg_match('{^https?://(.+):(.+)@([^/]+)}i', $fileUrl, $match)) {
  192. $this->io->setAuthentication($originUrl, urldecode($match[1]), urldecode($match[2]));
  193. }
  194. $tempAdditionalOptions = $additionalOptions;
  195. if (isset($tempAdditionalOptions['retry-auth-failure'])) {
  196. $this->retryAuthFailure = (bool) $tempAdditionalOptions['retry-auth-failure'];
  197. unset($tempAdditionalOptions['retry-auth-failure']);
  198. }
  199. $isRedirect = false;
  200. if (isset($tempAdditionalOptions['redirects'])) {
  201. $this->redirects = $tempAdditionalOptions['redirects'];
  202. $isRedirect = true;
  203. unset($tempAdditionalOptions['redirects']);
  204. }
  205. $options = $this->getOptionsForUrl($originUrl, $tempAdditionalOptions);
  206. unset($tempAdditionalOptions);
  207. $userlandFollow = isset($options['http']['follow_location']) && !$options['http']['follow_location'];
  208. $origFileUrl = $fileUrl;
  209. if (isset($options['github-token'])) {
  210. // only add the access_token if it is actually a github URL (in case we were redirected to S3)
  211. if (preg_match('{^https?://([a-z0-9-]+\.)*github\.com/}', $fileUrl)) {
  212. $fileUrl .= (false === strpos($fileUrl, '?') ? '?' : '&') . 'access_token='.$options['github-token'];
  213. }
  214. unset($options['github-token']);
  215. }
  216. if (isset($options['gitlab-token'])) {
  217. $fileUrl .= (false === strpos($fileUrl, '?') ? '?' : '&') . 'access_token='.$options['gitlab-token'];
  218. unset($options['gitlab-token']);
  219. }
  220. if (isset($options['bitbucket-token'])) {
  221. // First time be optimistic and do not use the token for a BitBucket download.
  222. if (isset($this->bitBucketUrlsTriedWithoutAuth[$origFileUrl]) && $this->bitBucketUrlsTriedWithoutAuth[$origFileUrl]) {
  223. $fileUrl .= (false === strpos($fileUrl,'?') ? '?' : '&') . 'access_token=' . $options['bitbucket-token'];
  224. } else {
  225. $this->bitBucketUrlsTriedWithoutAuth[$origFileUrl] = true;
  226. }
  227. unset($options['bitbucket-token']);
  228. }
  229. if (isset($options['http'])) {
  230. $options['http']['ignore_errors'] = true;
  231. }
  232. if ($this->degradedMode && substr($fileUrl, 0, 21) === 'http://packagist.org/') {
  233. // access packagist using the resolved IPv4 instead of the hostname to force IPv4 protocol
  234. $fileUrl = 'http://' . gethostbyname('packagist.org') . substr($fileUrl, 20);
  235. $degradedPackagist = true;
  236. }
  237. $ctx = StreamContextFactory::getContext($fileUrl, $options, array('notification' => array($this, 'callbackGet')));
  238. $actualContextOptions = stream_context_get_options($ctx);
  239. $usingProxy = !empty($actualContextOptions['http']['proxy']) ? ' using proxy ' . $actualContextOptions['http']['proxy'] : '';
  240. $this->io->writeError((substr($origFileUrl, 0, 4) === 'http' ? 'Downloading ' : 'Reading ') . $origFileUrl . $usingProxy, true, IOInterface::DEBUG);
  241. unset($origFileUrl, $actualContextOptions);
  242. // Check for secure HTTP, but allow insecure Packagist calls to $hashed providers as file integrity is verified with sha256
  243. if ((substr($fileUrl, 0, 23) !== 'http://packagist.org/p/' || (false === strpos($fileUrl, '$') && false === strpos($fileUrl, '%24'))) && empty($degradedPackagist) && $this->config) {
  244. $this->config->prohibitUrlByConfig($fileUrl, $this->io);
  245. }
  246. if ($this->progress && !$isRedirect) {
  247. $this->io->writeError(" Downloading: <comment>Connecting...</comment>", false);
  248. }
  249. $errorMessage = '';
  250. $errorCode = 0;
  251. $result = false;
  252. set_error_handler(function ($code, $msg) use (&$errorMessage) {
  253. if ($errorMessage) {
  254. $errorMessage .= "\n";
  255. }
  256. $errorMessage .= preg_replace('{^file_get_contents\(.*?\): }', '', $msg);
  257. });
  258. try {
  259. $result = file_get_contents($fileUrl, false, $ctx);
  260. $contentLength = !empty($http_response_header[0]) ? $this->findHeaderValue($http_response_header, 'content-length') : null;
  261. if ($contentLength && Platform::strlen($result) < $contentLength) {
  262. // alas, this is not possible via the stream callback because STREAM_NOTIFY_COMPLETED is documented, but not implemented anywhere in PHP
  263. throw new TransportException('Content-Length mismatch');
  264. }
  265. if (PHP_VERSION_ID < 50600 && !empty($options['ssl']['peer_fingerprint'])) {
  266. // Emulate fingerprint validation on PHP < 5.6
  267. $params = stream_context_get_params($ctx);
  268. $expectedPeerFingerprint = $options['ssl']['peer_fingerprint'];
  269. $peerFingerprint = TlsHelper::getCertificateFingerprint($params['options']['ssl']['peer_certificate']);
  270. // Constant time compare??!
  271. if ($expectedPeerFingerprint !== $peerFingerprint) {
  272. throw new TransportException('Peer fingerprint did not match');
  273. }
  274. }
  275. } catch (\Exception $e) {
  276. if ($e instanceof TransportException && !empty($http_response_header[0])) {
  277. $e->setHeaders($http_response_header);
  278. $e->setStatusCode($this->findStatusCode($http_response_header));
  279. }
  280. if ($e instanceof TransportException && $result !== false) {
  281. $e->setResponse($result);
  282. }
  283. $result = false;
  284. }
  285. if ($errorMessage && !ini_get('allow_url_fopen')) {
  286. $errorMessage = 'allow_url_fopen must be enabled in php.ini ('.$errorMessage.')';
  287. }
  288. restore_error_handler();
  289. if (isset($e) && !$this->retry) {
  290. if (!$this->degradedMode && false !== strpos($e->getMessage(), 'Operation timed out')) {
  291. $this->degradedMode = true;
  292. $this->io->writeError(array(
  293. '<error>'.$e->getMessage().'</error>',
  294. '<error>Retrying with degraded mode, check https://getcomposer.org/doc/articles/troubleshooting.md#degraded-mode for more info</error>',
  295. ));
  296. return $this->get($this->originUrl, $this->fileUrl, $additionalOptions, $this->fileName, $this->progress);
  297. }
  298. throw $e;
  299. }
  300. $statusCode = null;
  301. $contentType = null;
  302. if (!empty($http_response_header[0])) {
  303. $statusCode = $this->findStatusCode($http_response_header);
  304. $contentType = $this->findHeaderValue($http_response_header, 'content-type');
  305. }
  306. // check for bitbucket login page asking to authenticate
  307. if ($originUrl === 'bitbucket.org'
  308. && substr($fileUrl, 0, 37) === 'https://bitbucket.org/account/signin/'
  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>");
  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>'));
  337. }
  338. // decode gzip
  339. if ($result && extension_loaded('zlib') && substr($fileUrl, 0, 4) === 'http' && !$hasFollowedRedirect) {
  340. $decode = 'gzip' === strtolower($this->findHeaderValue($http_response_header, 'content-encoding'));
  341. if ($decode) {
  342. try {
  343. if (PHP_VERSION_ID >= 50400) {
  344. $result = zlib_decode($result);
  345. } else {
  346. // work around issue with gzuncompress & co that do not work with all gzip checksums
  347. $result = file_get_contents('compress.zlib://data:application/octet-stream;base64,'.base64_encode($result));
  348. }
  349. if (!$result) {
  350. throw new TransportException('Failed to decode zlib stream');
  351. }
  352. } catch (\Exception $e) {
  353. if ($this->degradedMode) {
  354. throw $e;
  355. }
  356. $this->degradedMode = true;
  357. $this->io->writeError(array(
  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(sprintf(
  409. '<error>Your version of PHP, %s, is affected by CVE-2013-6420 and cannot safely perform certificate validation, we strongly suggest you upgrade.</error>',
  410. PHP_VERSION
  411. ));
  412. }
  413. }
  414. if ($this->retry) {
  415. $this->retry = false;
  416. $result = $this->get($this->originUrl, $this->fileUrl, $additionalOptions, $this->fileName, $this->progress);
  417. if ($this->storeAuth && $this->config) {
  418. $authHelper = new AuthHelper($this->io, $this->config);
  419. $authHelper->storeAuth($this->originUrl, $this->storeAuth);
  420. $this->storeAuth = false;
  421. }
  422. return $result;
  423. }
  424. if (false === $result) {
  425. $e = new TransportException('The "'.$this->fileUrl.'" file could not be downloaded: '.$errorMessage, $errorCode);
  426. if (!empty($http_response_header[0])) {
  427. $e->setHeaders($http_response_header);
  428. }
  429. if (!$this->degradedMode && false !== strpos($e->getMessage(), 'Operation timed out')) {
  430. $this->degradedMode = true;
  431. $this->io->writeError(array(
  432. '<error>'.$e->getMessage().'</error>',
  433. '<error>Retrying with degraded mode, check https://getcomposer.org/doc/articles/troubleshooting.md#degraded-mode for more info</error>',
  434. ));
  435. return $this->get($this->originUrl, $this->fileUrl, $additionalOptions, $this->fileName, $this->progress);
  436. }
  437. throw $e;
  438. }
  439. if (!empty($http_response_header[0])) {
  440. $this->lastHeaders = $http_response_header;
  441. }
  442. return $result;
  443. }
  444. /**
  445. * Get notification action.
  446. *
  447. * @param int $notificationCode The notification code
  448. * @param int $severity The severity level
  449. * @param string $message The message
  450. * @param int $messageCode The message code
  451. * @param int $bytesTransferred The loaded size
  452. * @param int $bytesMax The total size
  453. * @throws TransportException
  454. */
  455. protected function callbackGet($notificationCode, $severity, $message, $messageCode, $bytesTransferred, $bytesMax)
  456. {
  457. switch ($notificationCode) {
  458. case STREAM_NOTIFY_FAILURE:
  459. if (400 === $messageCode) {
  460. // This might happen if your host is secured by ssl client certificate authentication
  461. // but you do not send an appropriate certificate
  462. throw new TransportException("The '" . $this->fileUrl . "' URL could not be accessed: " . $message, $messageCode);
  463. }
  464. // intentional fallthrough to the next case as the notificationCode
  465. // isn't always consistent and we should inspect the messageCode for 401s
  466. case STREAM_NOTIFY_AUTH_REQUIRED:
  467. if (401 === $messageCode) {
  468. // Bail if the caller is going to handle authentication failures itself.
  469. if (!$this->retryAuthFailure) {
  470. break;
  471. }
  472. $this->promptAuthAndRetry($messageCode);
  473. }
  474. break;
  475. case STREAM_NOTIFY_AUTH_RESULT:
  476. if (403 === $messageCode) {
  477. // Bail if the caller is going to handle authentication failures itself.
  478. if (!$this->retryAuthFailure) {
  479. break;
  480. }
  481. $this->promptAuthAndRetry($messageCode, $message);
  482. }
  483. break;
  484. case STREAM_NOTIFY_FILE_SIZE_IS:
  485. $this->bytesMax = $bytesMax;
  486. break;
  487. case STREAM_NOTIFY_PROGRESS:
  488. if ($this->bytesMax > 0 && $this->progress) {
  489. $progression = min(100, round($bytesTransferred / $this->bytesMax * 100));
  490. if ((0 === $progression % 5) && 100 !== $progression && $progression !== $this->lastProgress) {
  491. $this->lastProgress = $progression;
  492. $this->io->overwriteError(" Downloading: <comment>$progression%</comment>", false);
  493. }
  494. }
  495. break;
  496. default:
  497. break;
  498. }
  499. }
  500. protected function promptAuthAndRetry($httpStatus, $reason = null)
  501. {
  502. if ($this->config && in_array($this->originUrl, $this->config->get('github-domains'), true)) {
  503. $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');
  504. $gitHubUtil = new GitHub($this->io, $this->config, null);
  505. if (!$gitHubUtil->authorizeOAuth($this->originUrl)
  506. && (!$this->io->isInteractive() || !$gitHubUtil->authorizeOAuthInteractively($this->originUrl, $message))
  507. ) {
  508. throw new TransportException('Could not authenticate against '.$this->originUrl, 401);
  509. }
  510. } elseif ($this->config && in_array($this->originUrl, $this->config->get('gitlab-domains'), true)) {
  511. $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');
  512. $gitLabUtil = new GitLab($this->io, $this->config, null);
  513. if (!$gitLabUtil->authorizeOAuth($this->originUrl)
  514. && (!$this->io->isInteractive() || !$gitLabUtil->authorizeOAuthInteractively($this->scheme, $this->originUrl, $message))
  515. ) {
  516. throw new TransportException('Could not authenticate against '.$this->originUrl, 401);
  517. }
  518. } elseif ($this->config && $this->originUrl === 'bitbucket.org') {
  519. $askForOAuthToken = true;
  520. if ($this->io->hasAuthentication($this->originUrl)) {
  521. $auth = $this->io->getAuthentication($this->originUrl);
  522. if ($auth['username'] !== 'x-token-auth') {
  523. $bitbucketUtil = new Bitbucket($this->io, $this->config);
  524. $token = $bitbucketUtil->requestToken($this->originUrl, $auth['username'], $auth['password']);
  525. if (! empty($token)) {
  526. $this->io->setAuthentication($this->originUrl, 'x-token-auth', $token['access_token']);
  527. $askForOAuthToken = false;
  528. }
  529. } else {
  530. throw new TransportException('Could not authenticate against ' . $this->originUrl, 401);
  531. }
  532. }
  533. if ($askForOAuthToken) {
  534. $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');
  535. $bitBucketUtil = new Bitbucket($this->io, $this->config);
  536. if (! $bitBucketUtil->authorizeOAuth($this->originUrl)
  537. && (! $this->io->isInteractive() || !$bitBucketUtil->authorizeOAuthInteractively($this->originUrl, $message))
  538. ) {
  539. throw new TransportException('Could not authenticate against ' . $this->originUrl, 401);
  540. }
  541. }
  542. } else {
  543. // 404s are only handled for github
  544. if ($httpStatus === 404) {
  545. return;
  546. }
  547. // fail if the console is not interactive
  548. if (!$this->io->isInteractive()) {
  549. if ($httpStatus === 401) {
  550. $message = "The '" . $this->fileUrl . "' URL required authentication.\nYou must be using the interactive console to authenticate";
  551. }
  552. if ($httpStatus === 403) {
  553. $message = "The '" . $this->fileUrl . "' URL could not be accessed: " . $reason;
  554. }
  555. throw new TransportException($message, $httpStatus);
  556. }
  557. // fail if we already have auth
  558. if ($this->io->hasAuthentication($this->originUrl)) {
  559. throw new TransportException("Invalid credentials for '" . $this->fileUrl . "', aborting.", $httpStatus);
  560. }
  561. $this->io->overwriteError(' Authentication required (<info>'.parse_url($this->fileUrl, PHP_URL_HOST).'</info>):');
  562. $username = $this->io->ask(' Username: ');
  563. $password = $this->io->askAndHideAnswer(' Password: ');
  564. $this->io->setAuthentication($this->originUrl, $username, $password);
  565. $this->storeAuth = $this->config->get('store-auths');
  566. }
  567. $this->retry = true;
  568. throw new TransportException('RETRY');
  569. }
  570. protected function getOptionsForUrl($originUrl, $additionalOptions)
  571. {
  572. $tlsOptions = array();
  573. // Setup remaining TLS options - the matching may need monitoring, esp. www vs none in CN
  574. if ($this->disableTls === false && PHP_VERSION_ID < 50600 && !stream_is_local($this->fileUrl)) {
  575. $host = parse_url($this->fileUrl, PHP_URL_HOST);
  576. if (PHP_VERSION_ID >= 50304) {
  577. // Must manually follow when setting CN_match because this causes all
  578. // redirects to be validated against the same CN_match value.
  579. $userlandFollow = true;
  580. } else {
  581. // PHP < 5.3.4 does not support follow_location, for those people
  582. // do some really nasty hard coded transformations. These will
  583. // still breakdown if the site redirects to a domain we don't
  584. // expect.
  585. if ($host === 'github.com' || $host === 'api.github.com') {
  586. $host = '*.github.com';
  587. }
  588. }
  589. $tlsOptions['ssl']['CN_match'] = $host;
  590. $tlsOptions['ssl']['SNI_server_name'] = $host;
  591. $urlAuthority = $this->getUrlAuthority($this->fileUrl);
  592. if (isset($this->peerCertificateMap[$urlAuthority])) {
  593. // Handle subjectAltName on lesser PHP's.
  594. $certMap = $this->peerCertificateMap[$urlAuthority];
  595. $this->io->writeError(sprintf(
  596. 'Using <info>%s</info> as CN for subjectAltName enabled host <info>%s</info>',
  597. $certMap['cn'],
  598. $urlAuthority
  599. ), true, IOInterface::DEBUG);
  600. $tlsOptions['ssl']['CN_match'] = $certMap['cn'];
  601. $tlsOptions['ssl']['peer_fingerprint'] = $certMap['fp'];
  602. }
  603. }
  604. $headers = array();
  605. if (extension_loaded('zlib')) {
  606. $headers[] = 'Accept-Encoding: gzip';
  607. }
  608. $options = array_replace_recursive($this->options, $tlsOptions, $additionalOptions);
  609. if (!$this->degradedMode) {
  610. // degraded mode disables HTTP/1.1 which causes issues with some bad
  611. // proxies/software due to the use of chunked encoding
  612. $options['http']['protocol_version'] = 1.1;
  613. $headers[] = 'Connection: close';
  614. }
  615. if (isset($userlandFollow)) {
  616. $options['http']['follow_location'] = 0;
  617. }
  618. if ($this->io->hasAuthentication($originUrl)) {
  619. $auth = $this->io->getAuthentication($originUrl);
  620. if ('github.com' === $originUrl && 'x-oauth-basic' === $auth['password']) {
  621. $options['github-token'] = $auth['username'];
  622. } elseif ($this->config && in_array($originUrl, $this->config->get('gitlab-domains'), true)) {
  623. if ($auth['password'] === 'oauth2') {
  624. $headers[] = 'Authorization: Bearer '.$auth['username'];
  625. }
  626. else if ($auth['password'] === 'private-token') {
  627. $headers[] = 'PRIVATE-TOKEN: '.$auth['username'];
  628. }
  629. } elseif ('bitbucket.org' === $originUrl
  630. && $this->fileUrl !== Bitbucket::OAUTH2_ACCESS_TOKEN_URL && 'x-token-auth' === $auth['username']
  631. ) {
  632. $options['bitbucket-token'] = $auth['password'];
  633. } else {
  634. $authStr = base64_encode($auth['username'] . ':' . $auth['password']);
  635. $headers[] = 'Authorization: Basic '.$authStr;
  636. }
  637. }
  638. if (isset($options['http']['header']) && !is_array($options['http']['header'])) {
  639. $options['http']['header'] = explode("\r\n", trim($options['http']['header'], "\r\n"));
  640. }
  641. foreach ($headers as $header) {
  642. $options['http']['header'][] = $header;
  643. }
  644. return $options;
  645. }
  646. private function handleRedirect(array $http_response_header, array $additionalOptions, $result)
  647. {
  648. if ($locationHeader = $this->findHeaderValue($http_response_header, 'location')) {
  649. if (parse_url($locationHeader, PHP_URL_SCHEME)) {
  650. // Absolute URL; e.g. https://example.com/composer
  651. $targetUrl = $locationHeader;
  652. } elseif (parse_url($locationHeader, PHP_URL_HOST)) {
  653. // Scheme relative; e.g. //example.com/foo
  654. $targetUrl = $this->scheme.':'.$locationHeader;
  655. } elseif ('/' === $locationHeader[0]) {
  656. // Absolute path; e.g. /foo
  657. $urlHost = parse_url($this->fileUrl, PHP_URL_HOST);
  658. // Replace path using hostname as an anchor.
  659. $targetUrl = preg_replace('{^(.+(?://|@)'.preg_quote($urlHost).'(?::\d+)?)(?:[/\?].*)?$}', '\1'.$locationHeader, $this->fileUrl);
  660. } else {
  661. // Relative path; e.g. foo
  662. // This actually differs from PHP which seems to add duplicate slashes.
  663. $targetUrl = preg_replace('{^(.+/)[^/?]*(?:\?.*)?$}', '\1'.$locationHeader, $this->fileUrl);
  664. }
  665. }
  666. if (!empty($targetUrl)) {
  667. $this->redirects++;
  668. $this->io->writeError(sprintf('Following redirect (%u) %s', $this->redirects, $targetUrl), true, IOInterface::DEBUG);
  669. $additionalOptions['redirects'] = $this->redirects;
  670. return $this->get($this->originUrl, $targetUrl, $additionalOptions, $this->fileName, $this->progress);
  671. }
  672. if (!$this->retry) {
  673. $e = new TransportException('The "'.$this->fileUrl.'" file could not be downloaded, got redirect without Location ('.$http_response_header[0].')');
  674. $e->setHeaders($http_response_header);
  675. $e->setResponse($result);
  676. throw $e;
  677. }
  678. return false;
  679. }
  680. /**
  681. * @param array $options
  682. *
  683. * @return array
  684. */
  685. private function getTlsDefaults(array $options)
  686. {
  687. $ciphers = implode(':', array(
  688. 'ECDHE-RSA-AES128-GCM-SHA256',
  689. 'ECDHE-ECDSA-AES128-GCM-SHA256',
  690. 'ECDHE-RSA-AES256-GCM-SHA384',
  691. 'ECDHE-ECDSA-AES256-GCM-SHA384',
  692. 'DHE-RSA-AES128-GCM-SHA256',
  693. 'DHE-DSS-AES128-GCM-SHA256',
  694. 'kEDH+AESGCM',
  695. 'ECDHE-RSA-AES128-SHA256',
  696. 'ECDHE-ECDSA-AES128-SHA256',
  697. 'ECDHE-RSA-AES128-SHA',
  698. 'ECDHE-ECDSA-AES128-SHA',
  699. 'ECDHE-RSA-AES256-SHA384',
  700. 'ECDHE-ECDSA-AES256-SHA384',
  701. 'ECDHE-RSA-AES256-SHA',
  702. 'ECDHE-ECDSA-AES256-SHA',
  703. 'DHE-RSA-AES128-SHA256',
  704. 'DHE-RSA-AES128-SHA',
  705. 'DHE-DSS-AES128-SHA256',
  706. 'DHE-RSA-AES256-SHA256',
  707. 'DHE-DSS-AES256-SHA',
  708. 'DHE-RSA-AES256-SHA',
  709. 'AES128-GCM-SHA256',
  710. 'AES256-GCM-SHA384',
  711. 'AES128-SHA256',
  712. 'AES256-SHA256',
  713. 'AES128-SHA',
  714. 'AES256-SHA',
  715. 'AES',
  716. 'CAMELLIA',
  717. 'DES-CBC3-SHA',
  718. '!aNULL',
  719. '!eNULL',
  720. '!EXPORT',
  721. '!DES',
  722. '!RC4',
  723. '!MD5',
  724. '!PSK',
  725. '!aECDH',
  726. '!EDH-DSS-DES-CBC3-SHA',
  727. '!EDH-RSA-DES-CBC3-SHA',
  728. '!KRB5-DES-CBC3-SHA',
  729. ));
  730. /**
  731. * CN_match and SNI_server_name are only known once a URL is passed.
  732. * They will be set in the getOptionsForUrl() method which receives a URL.
  733. *
  734. * cafile or capath can be overridden by passing in those options to constructor.
  735. */
  736. $defaults = array(
  737. 'ssl' => array(
  738. 'ciphers' => $ciphers,
  739. 'verify_peer' => true,
  740. 'verify_depth' => 7,
  741. 'SNI_enabled' => true,
  742. 'capture_peer_cert' => true,
  743. ),
  744. );
  745. if (isset($options['ssl'])) {
  746. $defaults['ssl'] = array_replace_recursive($defaults['ssl'], $options['ssl']);
  747. }
  748. $caBundleLogger = $this->io instanceof LoggerInterface ? $this->io : null;
  749. /**
  750. * Attempt to find a local cafile or throw an exception if none pre-set
  751. * The user may go download one if this occurs.
  752. */
  753. if (!isset($defaults['ssl']['cafile']) && !isset($defaults['ssl']['capath'])) {
  754. $result = CaBundle::getSystemCaRootBundlePath($caBundleLogger);
  755. if (preg_match('{^phar://}', $result)) {
  756. $hash = hash_file('sha256', $result);
  757. $targetPath = rtrim(sys_get_temp_dir(), '\\/') . '/composer-cacert-' . $hash . '.pem';
  758. if (!file_exists($targetPath) || $hash !== hash_file('sha256', $targetPath)) {
  759. $this->streamCopy($result, $targetPath);
  760. chmod($targetPath, 0666);
  761. }
  762. $defaults['ssl']['cafile'] = $targetPath;
  763. } elseif (is_dir($result)) {
  764. $defaults['ssl']['capath'] = $result;
  765. } else {
  766. $defaults['ssl']['cafile'] = $result;
  767. }
  768. }
  769. if (isset($defaults['ssl']['cafile']) && (!is_readable($defaults['ssl']['cafile']) || !CaBundle::validateCaFile($defaults['ssl']['cafile'], $caBundleLogger))) {
  770. throw new TransportException('The configured cafile was not valid or could not be read.');
  771. }
  772. if (isset($defaults['ssl']['capath']) && (!is_dir($defaults['ssl']['capath']) || !is_readable($defaults['ssl']['capath']))) {
  773. throw new TransportException('The configured capath was not valid or could not be read.');
  774. }
  775. /**
  776. * Disable TLS compression to prevent CRIME attacks where supported.
  777. */
  778. if (PHP_VERSION_ID >= 50413) {
  779. $defaults['ssl']['disable_compression'] = true;
  780. }
  781. return $defaults;
  782. }
  783. /**
  784. * Uses stream_copy_to_stream instead of copy to work around https://bugs.php.net/bug.php?id=64634
  785. *
  786. * @param string $source
  787. * @param string $target
  788. */
  789. private function streamCopy($source, $target)
  790. {
  791. $source = fopen($source, 'r');
  792. $target = fopen($target, 'w+');
  793. stream_copy_to_stream($source, $target);
  794. fclose($source);
  795. fclose($target);
  796. unset($source, $target);
  797. }
  798. /**
  799. * Fetch certificate common name and fingerprint for validation of SAN.
  800. *
  801. * @todo Remove when PHP 5.6 is minimum supported version.
  802. */
  803. private function getCertificateCnAndFp($url, $options)
  804. {
  805. if (PHP_VERSION_ID >= 50600) {
  806. throw new \BadMethodCallException(sprintf(
  807. '%s must not be used on PHP >= 5.6',
  808. __METHOD__
  809. ));
  810. }
  811. $context = StreamContextFactory::getContext($url, $options, array('options' => array(
  812. 'ssl' => array(
  813. 'capture_peer_cert' => true,
  814. 'verify_peer' => false, // Yes this is fucking insane! But PHP is lame.
  815. ), ),
  816. ));
  817. // Ideally this would just use stream_socket_client() to avoid sending a
  818. // HTTP request but that does not capture the certificate.
  819. if (false === $handle = @fopen($url, 'rb', false, $context)) {
  820. return;
  821. }
  822. // Close non authenticated connection without reading any content.
  823. fclose($handle);
  824. $handle = null;
  825. $params = stream_context_get_params($context);
  826. if (!empty($params['options']['ssl']['peer_certificate'])) {
  827. $peerCertificate = $params['options']['ssl']['peer_certificate'];
  828. if (TlsHelper::checkCertificateHost($peerCertificate, parse_url($url, PHP_URL_HOST), $commonName)) {
  829. return array(
  830. 'cn' => $commonName,
  831. 'fp' => TlsHelper::getCertificateFingerprint($peerCertificate),
  832. );
  833. }
  834. }
  835. }
  836. private function getUrlAuthority($url)
  837. {
  838. $defaultPorts = array(
  839. 'ftp' => 21,
  840. 'http' => 80,
  841. 'https' => 443,
  842. 'ssh2.sftp' => 22,
  843. 'ssh2.scp' => 22,
  844. );
  845. $scheme = parse_url($url, PHP_URL_SCHEME);
  846. if (!isset($defaultPorts[$scheme])) {
  847. throw new \InvalidArgumentException(sprintf(
  848. 'Could not get default port for unknown scheme: %s',
  849. $scheme
  850. ));
  851. }
  852. $defaultPort = $defaultPorts[$scheme];
  853. $port = parse_url($url, PHP_URL_PORT) ?: $defaultPort;
  854. return parse_url($url, PHP_URL_HOST).':'.$port;
  855. }
  856. }