ComposerRepository.php 18 KB

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