ComposerRepository.php 22 KB

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