ComposerRepository.php 19 KB

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