ComposerRepository.php 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651
  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\Repository;
  12. use Composer\Package\Loader\ArrayLoader;
  13. use Composer\Package\Package;
  14. use Composer\Package\PackageInterface;
  15. use Composer\Package\AliasPackage;
  16. use Composer\Package\Version\VersionParser;
  17. use Composer\DependencyResolver\Pool;
  18. use Composer\Json\JsonFile;
  19. use Composer\Cache;
  20. use Composer\Config;
  21. use Composer\IO\IOInterface;
  22. use Composer\Util\RemoteFilesystem;
  23. use Composer\Plugin\PluginEvents;
  24. use Composer\Plugin\PreFileDownloadEvent;
  25. use Composer\EventDispatcher\EventDispatcher;
  26. /**
  27. * @author Jordi Boggiano <j.boggiano@seld.be>
  28. */
  29. class ComposerRepository extends ArrayRepository implements StreamableRepositoryInterface
  30. {
  31. protected $config;
  32. protected $options;
  33. protected $url;
  34. protected $baseUrl;
  35. protected $io;
  36. protected $rfs;
  37. protected $cache;
  38. protected $notifyUrl;
  39. protected $searchUrl;
  40. protected $hasProviders = false;
  41. protected $providersUrl;
  42. protected $lazyProvidersUrl;
  43. protected $providerListing;
  44. protected $providers = array();
  45. protected $providersByUid = array();
  46. protected $loader;
  47. protected $rootAliases;
  48. protected $allowSslDowngrade = false;
  49. protected $eventDispatcher;
  50. protected $sourceMirrors;
  51. protected $distMirrors;
  52. private $rawData;
  53. private $minimalPackages;
  54. private $degradedMode = false;
  55. private $rootData;
  56. public function __construct(array $repoConfig, IOInterface $io, Config $config, EventDispatcher $eventDispatcher = null)
  57. {
  58. if (!preg_match('{^[\w.]+\??://}', $repoConfig['url'])) {
  59. // assume http as the default protocol
  60. $repoConfig['url'] = 'http://'.$repoConfig['url'];
  61. }
  62. $repoConfig['url'] = rtrim($repoConfig['url'], '/');
  63. if ('https?' === substr($repoConfig['url'], 0, 6)) {
  64. $repoConfig['url'] = (extension_loaded('openssl') ? 'https' : 'http') . substr($repoConfig['url'], 6);
  65. }
  66. $urlBits = parse_url($repoConfig['url']);
  67. if ($urlBits === false || empty($urlBits['scheme'])) {
  68. throw new \UnexpectedValueException('Invalid url given for Composer repository: '.$repoConfig['url']);
  69. }
  70. if (!isset($repoConfig['options'])) {
  71. $repoConfig['options'] = array();
  72. }
  73. if (isset($repoConfig['allow_ssl_downgrade']) && true === $repoConfig['allow_ssl_downgrade']) {
  74. $this->allowSslDowngrade = true;
  75. }
  76. $this->config = $config;
  77. $this->options = $repoConfig['options'];
  78. $this->url = $repoConfig['url'];
  79. $this->baseUrl = rtrim(preg_replace('{^(.*)(?:/packages.json)?(?:[?#].*)?$}', '$1', $this->url), '/');
  80. $this->io = $io;
  81. $this->cache = new Cache($io, $config->get('cache-repo-dir').'/'.preg_replace('{[^a-z0-9.]}i', '-', $this->url), 'a-z0-9.$');
  82. $this->loader = new ArrayLoader();
  83. $this->rfs = new RemoteFilesystem($this->io, $this->config, $this->options);
  84. $this->eventDispatcher = $eventDispatcher;
  85. }
  86. public function setRootAliases(array $rootAliases)
  87. {
  88. $this->rootAliases = $rootAliases;
  89. }
  90. public function getPackages()
  91. {
  92. if ($this->hasProviders()) {
  93. throw new \LogicException('Composer repositories that have providers can not load the complete list of packages, use getProviderNames instead.');
  94. }
  95. return parent::getPackages();
  96. }
  97. /**
  98. * {@inheritDoc}
  99. */
  100. public function getMinimalPackages()
  101. {
  102. if (isset($this->minimalPackages)) {
  103. return $this->minimalPackages;
  104. }
  105. if (null === $this->rawData) {
  106. $this->rawData = $this->loadDataFromServer();
  107. }
  108. $this->minimalPackages = array();
  109. $versionParser = new VersionParser;
  110. foreach ($this->rawData as $package) {
  111. $version = !empty($package['version_normalized']) ? $package['version_normalized'] : $versionParser->normalize($package['version']);
  112. $data = array(
  113. 'name' => strtolower($package['name']),
  114. 'repo' => $this,
  115. 'version' => $version,
  116. 'raw' => $package,
  117. );
  118. if (!empty($package['replace'])) {
  119. $data['replace'] = $package['replace'];
  120. }
  121. if (!empty($package['provide'])) {
  122. $data['provide'] = $package['provide'];
  123. }
  124. // add branch aliases
  125. if ($aliasNormalized = $this->loader->getBranchAlias($package)) {
  126. $data['alias'] = preg_replace('{(\.9{7})+}', '.x', $aliasNormalized);
  127. $data['alias_normalized'] = $aliasNormalized;
  128. }
  129. $this->minimalPackages[] = $data;
  130. }
  131. return $this->minimalPackages;
  132. }
  133. /**
  134. * {@inheritDoc}
  135. */
  136. public function search($query, $mode = 0)
  137. {
  138. $this->loadRootServerFile();
  139. if ($this->searchUrl && $mode === self::SEARCH_FULLTEXT) {
  140. $url = str_replace('%query%', $query, $this->searchUrl);
  141. $json = $this->rfs->getContents($url, $url, false);
  142. $results = JsonFile::parseJson($json, $url);
  143. return $results['results'];
  144. }
  145. if ($this->hasProviders()) {
  146. $results = array();
  147. $regex = '{(?:'.implode('|', preg_split('{\s+}', $query)).')}i';
  148. foreach ($this->getProviderNames() as $name) {
  149. if (preg_match($regex, $name)) {
  150. $results[] = array('name' => $name);
  151. }
  152. }
  153. return $results;
  154. }
  155. return parent::search($query, $mode);
  156. }
  157. public function getProviderNames()
  158. {
  159. $this->loadRootServerFile();
  160. if (null === $this->providerListing) {
  161. $this->loadProviderListings($this->loadRootServerFile());
  162. }
  163. if ($this->providersUrl) {
  164. return array_keys($this->providerListing);
  165. }
  166. // BC handling for old providers-includes
  167. $providers = array();
  168. foreach (array_keys($this->providerListing) as $provider) {
  169. $providers[] = substr($provider, 2, -5);
  170. }
  171. return $providers;
  172. }
  173. /**
  174. * {@inheritDoc}
  175. */
  176. public function loadPackage(array $data)
  177. {
  178. $package = $this->createPackage($data['raw'], 'Composer\Package\Package');
  179. if ($package instanceof AliasPackage) {
  180. $package = $package->getAliasOf();
  181. }
  182. $package->setRepository($this);
  183. return $package;
  184. }
  185. protected function configurePackageTransportOptions(PackageInterface $package)
  186. {
  187. if (strpos($package->getDistUrl(), $this->baseUrl) === 0) {
  188. $package->setTransportOptions($this->options);
  189. return;
  190. }
  191. }
  192. /**
  193. * {@inheritDoc}
  194. */
  195. public function loadAliasPackage(array $data, PackageInterface $aliasOf)
  196. {
  197. $aliasPackage = $this->createAliasPackage($aliasOf, $data['version'], $data['alias']);
  198. $aliasPackage->setRepository($this);
  199. return $aliasPackage;
  200. }
  201. public function hasProviders()
  202. {
  203. $this->loadRootServerFile();
  204. return $this->hasProviders;
  205. }
  206. public function resetPackageIds()
  207. {
  208. foreach ($this->providersByUid as $package) {
  209. if ($package instanceof AliasPackage) {
  210. $package->getAliasOf()->setId(-1);
  211. }
  212. $package->setId(-1);
  213. }
  214. }
  215. public function whatProvides(Pool $pool, $name)
  216. {
  217. if (isset($this->providers[$name])) {
  218. return $this->providers[$name];
  219. }
  220. // skip platform packages
  221. if (preg_match(PlatformRepository::PLATFORM_PACKAGE_REGEX, $name) || '__root__' === $name) {
  222. return array();
  223. }
  224. if (null === $this->providerListing) {
  225. $this->loadProviderListings($this->loadRootServerFile());
  226. }
  227. if ($this->lazyProvidersUrl && !isset($this->providerListing[$name])) {
  228. $hash = $this->providerListing[$name]['sha256'];
  229. $url = str_replace('%package%', $name, $this->lazyProvidersUrl);
  230. $cacheKey = false;
  231. } elseif ($this->providersUrl) {
  232. // package does not exist in this repo
  233. if (!isset($this->providerListing[$name])) {
  234. return array();
  235. }
  236. $hash = $this->providerListing[$name]['sha256'];
  237. $url = str_replace(array('%package%', '%hash%'), array($name, $hash), $this->providersUrl);
  238. $cacheKey = 'provider-'.strtr($name, '/', '$').'.json';
  239. } else {
  240. // BC handling for old providers-includes
  241. $url = 'p/'.$name.'.json';
  242. // package does not exist in this repo
  243. if (!isset($this->providerListing[$url])) {
  244. return array();
  245. }
  246. $hash = $this->providerListing[$url]['sha256'];
  247. $cacheKey = null;
  248. }
  249. if ($cacheKey && $this->cache->sha256($cacheKey) === $hash) {
  250. $packages = json_decode($this->cache->read($cacheKey), true);
  251. } else {
  252. $packages = $this->fetchFile($url, $cacheKey, $hash);
  253. }
  254. $this->providers[$name] = array();
  255. foreach ($packages['packages'] as $versions) {
  256. foreach ($versions as $version) {
  257. // avoid loading the same objects twice
  258. if (isset($this->providersByUid[$version['uid']])) {
  259. // skip if already assigned
  260. if (!isset($this->providers[$name][$version['uid']])) {
  261. // expand alias in two packages
  262. if ($this->providersByUid[$version['uid']] instanceof AliasPackage) {
  263. $this->providers[$name][$version['uid']] = $this->providersByUid[$version['uid']]->getAliasOf();
  264. $this->providers[$name][$version['uid'].'-alias'] = $this->providersByUid[$version['uid']];
  265. } else {
  266. $this->providers[$name][$version['uid']] = $this->providersByUid[$version['uid']];
  267. }
  268. // check for root aliases
  269. if (isset($this->providersByUid[$version['uid'].'-root'])) {
  270. $this->providers[$name][$version['uid'].'-root'] = $this->providersByUid[$version['uid'].'-root'];
  271. }
  272. }
  273. } else {
  274. if (isset($version['provide']) || isset($version['replace'])) {
  275. // collect names
  276. $names = array(
  277. strtolower($version['name']) => true,
  278. );
  279. if (isset($version['provide'])) {
  280. foreach ($version['provide'] as $target => $constraint) {
  281. $names[strtolower($target)] = true;
  282. }
  283. }
  284. if (isset($version['replace'])) {
  285. foreach ($version['replace'] as $target => $constraint) {
  286. $names[strtolower($target)] = true;
  287. }
  288. }
  289. $names = array_keys($names);
  290. } else {
  291. $names = array(strtolower($version['name']));
  292. }
  293. if (!$pool->isPackageAcceptable(strtolower($version['name']), VersionParser::parseStability($version['version']))) {
  294. continue;
  295. }
  296. // load acceptable packages in the providers
  297. $package = $this->createPackage($version, 'Composer\Package\Package');
  298. $package->setRepository($this);
  299. if ($package instanceof AliasPackage) {
  300. $aliased = $package->getAliasOf();
  301. $aliased->setRepository($this);
  302. $this->providers[$name][$version['uid']] = $aliased;
  303. $this->providers[$name][$version['uid'].'-alias'] = $package;
  304. // override provider with its alias so it can be expanded in the if block above
  305. $this->providersByUid[$version['uid']] = $package;
  306. } else {
  307. $this->providers[$name][$version['uid']] = $package;
  308. $this->providersByUid[$version['uid']] = $package;
  309. }
  310. // handle root package aliases
  311. unset($rootAliasData);
  312. if (isset($this->rootAliases[$name][$package->getVersion()])) {
  313. $rootAliasData = $this->rootAliases[$name][$package->getVersion()];
  314. } elseif ($package instanceof AliasPackage && isset($this->rootAliases[$name][$package->getAliasOf()->getVersion()])) {
  315. $rootAliasData = $this->rootAliases[$name][$package->getAliasOf()->getVersion()];
  316. }
  317. if (isset($rootAliasData)) {
  318. $alias = $this->createAliasPackage($package, $rootAliasData['alias_normalized'], $rootAliasData['alias']);
  319. $alias->setRepository($this);
  320. $this->providers[$name][$version['uid'].'-root'] = $alias;
  321. $this->providersByUid[$version['uid'].'-root'] = $alias;
  322. }
  323. }
  324. }
  325. }
  326. return $this->providers[$name];
  327. }
  328. /**
  329. * {@inheritDoc}
  330. */
  331. protected function initialize()
  332. {
  333. parent::initialize();
  334. $repoData = $this->loadDataFromServer();
  335. foreach ($repoData as $package) {
  336. $this->addPackage($this->createPackage($package, 'Composer\Package\CompletePackage'));
  337. }
  338. }
  339. /**
  340. * Adds a new package to the repository
  341. *
  342. * @param PackageInterface $package
  343. */
  344. public function addPackage(PackageInterface $package)
  345. {
  346. parent::addPackage($package);
  347. $this->configurePackageTransportOptions($package);
  348. }
  349. protected function loadRootServerFile()
  350. {
  351. if (null !== $this->rootData) {
  352. return $this->rootData;
  353. }
  354. if (!extension_loaded('openssl') && 'https' === substr($this->url, 0, 5)) {
  355. throw new \RuntimeException('You must enable the openssl extension in your php.ini to load information from '.$this->url);
  356. }
  357. $jsonUrlParts = parse_url($this->url);
  358. if (isset($jsonUrlParts['path']) && false !== strpos($jsonUrlParts['path'], '/packages.json')) {
  359. $jsonUrl = $this->url;
  360. } else {
  361. $jsonUrl = $this->url . '/packages.json';
  362. }
  363. $data = $this->fetchFile($jsonUrl, 'packages.json');
  364. if (!empty($data['notify-batch'])) {
  365. $this->notifyUrl = $this->canonicalizeUrl($data['notify-batch']);
  366. } elseif (!empty($data['notify_batch'])) {
  367. // TODO remove this BC notify_batch support
  368. $this->notifyUrl = $this->canonicalizeUrl($data['notify_batch']);
  369. } elseif (!empty($data['notify'])) {
  370. $this->notifyUrl = $this->canonicalizeUrl($data['notify']);
  371. }
  372. if (!empty($data['search'])) {
  373. $this->searchUrl = $this->canonicalizeUrl($data['search']);
  374. }
  375. if (!empty($data['mirrors'])) {
  376. foreach ($data['mirrors'] as $mirror) {
  377. if (!empty($mirror['git-url'])) {
  378. $this->sourceMirrors['git'][] = array('url' => $mirror['git-url'], 'preferred' => !empty($mirror['preferred']));
  379. }
  380. if (!empty($mirror['hg-url'])) {
  381. $this->sourceMirrors['hg'][] = array('url' => $mirror['hg-url'], 'preferred' => !empty($mirror['preferred']));
  382. }
  383. if (!empty($mirror['dist-url'])) {
  384. $this->distMirrors[] = array('url' => $mirror['dist-url'], 'preferred' => !empty($mirror['preferred']));
  385. }
  386. }
  387. }
  388. if (!empty($data['warning'])) {
  389. $this->io->write('<warning>Warning from '.$this->url.': '.$data['warning'].'</warning>');
  390. }
  391. if (!empty($data['providers-lazy-url'])) {
  392. $this->lazyProvidersUrl = $this->canonicalizeUrl($data['providers-lazy-url']);
  393. $this->hasProviders = true;
  394. }
  395. if ($this->allowSslDowngrade) {
  396. $this->url = str_replace('https://', 'http://', $this->url);
  397. }
  398. if (!empty($data['providers-url'])) {
  399. $this->providersUrl = $this->canonicalizeUrl($data['providers-url']);
  400. $this->hasProviders = true;
  401. }
  402. if (!empty($data['providers']) || !empty($data['providers-includes'])) {
  403. $this->hasProviders = true;
  404. }
  405. return $this->rootData = $data;
  406. }
  407. protected function canonicalizeUrl($url)
  408. {
  409. if ('/' === $url[0]) {
  410. return preg_replace('{(https?://[^/]+).*}i', '$1' . $url, $this->url);
  411. }
  412. return $url;
  413. }
  414. protected function loadDataFromServer()
  415. {
  416. $data = $this->loadRootServerFile();
  417. return $this->loadIncludes($data);
  418. }
  419. protected function loadProviderListings($data)
  420. {
  421. if (isset($data['providers'])) {
  422. if (!is_array($this->providerListing)) {
  423. $this->providerListing = array();
  424. }
  425. $this->providerListing = array_merge($this->providerListing, $data['providers']);
  426. }
  427. if ($this->providersUrl && isset($data['provider-includes'])) {
  428. $includes = $data['provider-includes'];
  429. foreach ($includes as $include => $metadata) {
  430. $url = $this->baseUrl . '/' . str_replace('%hash%', $metadata['sha256'], $include);
  431. $cacheKey = str_replace(array('%hash%','$'), '', $include);
  432. if ($this->cache->sha256($cacheKey) === $metadata['sha256']) {
  433. $includedData = json_decode($this->cache->read($cacheKey), true);
  434. } else {
  435. $includedData = $this->fetchFile($url, $cacheKey, $metadata['sha256']);
  436. }
  437. $this->loadProviderListings($includedData);
  438. }
  439. } elseif (isset($data['providers-includes'])) {
  440. // BC layer for old-style providers-includes
  441. $includes = $data['providers-includes'];
  442. foreach ($includes as $include => $metadata) {
  443. if ($this->cache->sha256($include) === $metadata['sha256']) {
  444. $includedData = json_decode($this->cache->read($include), true);
  445. } else {
  446. $includedData = $this->fetchFile($include, null, $metadata['sha256']);
  447. }
  448. $this->loadProviderListings($includedData);
  449. }
  450. }
  451. }
  452. protected function loadIncludes($data)
  453. {
  454. $packages = array();
  455. // legacy repo handling
  456. if (!isset($data['packages']) && !isset($data['includes'])) {
  457. foreach ($data as $pkg) {
  458. foreach ($pkg['versions'] as $metadata) {
  459. $packages[] = $metadata;
  460. }
  461. }
  462. return $packages;
  463. }
  464. if (isset($data['packages'])) {
  465. foreach ($data['packages'] as $package => $versions) {
  466. foreach ($versions as $version => $metadata) {
  467. $packages[] = $metadata;
  468. }
  469. }
  470. }
  471. if (isset($data['includes'])) {
  472. foreach ($data['includes'] as $include => $metadata) {
  473. if ($this->cache->sha1($include) === $metadata['sha1']) {
  474. $includedData = json_decode($this->cache->read($include), true);
  475. } else {
  476. $includedData = $this->fetchFile($include);
  477. }
  478. $packages = array_merge($packages, $this->loadIncludes($includedData));
  479. }
  480. }
  481. return $packages;
  482. }
  483. protected function createPackage(array $data, $class)
  484. {
  485. try {
  486. if (!isset($data['notification-url'])) {
  487. $data['notification-url'] = $this->notifyUrl;
  488. }
  489. $package = $this->loader->load($data, 'Composer\Package\CompletePackage');
  490. if (isset($this->sourceMirrors[$package->getSourceType()])) {
  491. $package->setSourceMirrors($this->sourceMirrors[$package->getSourceType()]);
  492. }
  493. $package->setDistMirrors($this->distMirrors);
  494. $this->configurePackageTransportOptions($package);
  495. return $package;
  496. } catch (\Exception $e) {
  497. throw new \RuntimeException('Could not load package '.(isset($data['name']) ? $data['name'] : json_encode($data)).' in '.$this->url.': ['.get_class($e).'] '.$e->getMessage(), 0, $e);
  498. }
  499. }
  500. protected function fetchFile($filename, $cacheKey = null, $sha256 = null)
  501. {
  502. if (null === $cacheKey) {
  503. $cacheKey = $filename;
  504. $filename = $this->baseUrl.'/'.$filename;
  505. }
  506. $retries = 3;
  507. while ($retries--) {
  508. try {
  509. $preFileDownloadEvent = new PreFileDownloadEvent(PluginEvents::PRE_FILE_DOWNLOAD, $this->rfs, $filename);
  510. if ($this->eventDispatcher) {
  511. $this->eventDispatcher->dispatch($preFileDownloadEvent->getName(), $preFileDownloadEvent);
  512. }
  513. $json = $preFileDownloadEvent->getRemoteFilesystem()->getContents($filename, $filename, false);
  514. if ($sha256 && $sha256 !== hash('sha256', $json)) {
  515. if ($retries) {
  516. usleep(100000);
  517. continue;
  518. }
  519. // TODO use scarier wording once we know for sure it doesn't do false positives anymore
  520. throw new RepositorySecurityException('The contents of '.$filename.' do not match its signature. This should indicate a man-in-the-middle attack. Try running composer again and report this if you think it is a mistake.');
  521. }
  522. $data = JsonFile::parseJson($json, $filename);
  523. if ($cacheKey) {
  524. $this->cache->write($cacheKey, $json);
  525. }
  526. break;
  527. } catch (\Exception $e) {
  528. if ($retries) {
  529. usleep(100000);
  530. continue;
  531. }
  532. if ($e instanceof RepositorySecurityException) {
  533. throw $e;
  534. }
  535. if ($cacheKey && ($contents = $this->cache->read($cacheKey))) {
  536. if (!$this->degradedMode) {
  537. $this->io->write('<warning>'.$e->getMessage().'</warning>');
  538. $this->io->write('<warning>'.$this->url.' could not be fully loaded, package information was loaded from the local cache and may be out of date</warning>');
  539. }
  540. $this->degradedMode = true;
  541. $data = JsonFile::parseJson($contents, $this->cache->getRoot().$cacheKey);
  542. break;
  543. }
  544. throw $e;
  545. }
  546. }
  547. return $data;
  548. }
  549. }