ComposerRepository.php 22 KB

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