ComposerRepository.php 20 KB

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