RemoteFilesystem.php 40 KB

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