ComposerRepository.php 19 KB

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