RemoteFilesystem.php 41 KB

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