ComposerRepository.php 22 KB

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