GitLabDriver.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523
  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\Vcs;
  12. use Composer\Config;
  13. use Composer\Cache;
  14. use Composer\IO\IOInterface;
  15. use Composer\Json\JsonFile;
  16. use Composer\Downloader\TransportException;
  17. use Composer\Util\HttpDownloader;
  18. use Composer\Util\GitLab;
  19. use Composer\Util\Http\Response;
  20. /**
  21. * Driver for GitLab API, use the Git driver for local checkouts.
  22. *
  23. * @author Henrik Bjørnskov <henrik@bjrnskov.dk>
  24. * @author Jérôme Tamarelle <jerome@tamarelle.net>
  25. */
  26. class GitLabDriver extends VcsDriver
  27. {
  28. private $scheme;
  29. private $namespace;
  30. private $repository;
  31. /**
  32. * @var array Project data returned by GitLab API
  33. */
  34. private $project;
  35. /**
  36. * @var array Keeps commits returned by GitLab API
  37. */
  38. private $commits = array();
  39. /**
  40. * @var array List of tag => reference
  41. */
  42. private $tags;
  43. /**
  44. * @var array List of branch => reference
  45. */
  46. private $branches;
  47. /**
  48. * Git Driver
  49. *
  50. * @var GitDriver
  51. */
  52. protected $gitDriver;
  53. /**
  54. * Defaults to true unless we can make sure it is public
  55. *
  56. * @var bool defines whether the repo is private or not
  57. */
  58. private $isPrivate = true;
  59. /**
  60. * @var bool true if the origin has a port number or a path component in it
  61. */
  62. private $hasNonstandardOrigin = false;
  63. const URL_REGEX = '#^(?:(?P<scheme>https?)://(?P<domain>.+?)(?::(?P<port>[0-9]+))?/|git@(?P<domain2>[^:]+):)(?P<parts>.+)/(?P<repo>[^/]+?)(?:\.git|/)?$#';
  64. /**
  65. * Extracts information from the repository url.
  66. *
  67. * SSH urls use https by default. Set "secure-http": false on the repository config to use http instead.
  68. *
  69. * {@inheritDoc}
  70. */
  71. public function initialize()
  72. {
  73. if (!preg_match(self::URL_REGEX, $this->url, $match)) {
  74. throw new \InvalidArgumentException('The URL provided is invalid. It must be the HTTP URL of a GitLab project.');
  75. }
  76. $guessedDomain = !empty($match['domain']) ? $match['domain'] : $match['domain2'];
  77. $configuredDomains = $this->config->get('gitlab-domains');
  78. $urlParts = explode('/', $match['parts']);
  79. $this->scheme = !empty($match['scheme'])
  80. ? $match['scheme']
  81. : (isset($this->repoConfig['secure-http']) && $this->repoConfig['secure-http'] === false ? 'http' : 'https')
  82. ;
  83. $this->originUrl = $this->determineOrigin($configuredDomains, $guessedDomain, $urlParts, $match['port']);
  84. if (false !== strpos($this->originUrl, ':') || false !== strpos($this->originUrl, '/')) {
  85. $this->hasNonstandardOrigin = true;
  86. }
  87. $this->namespace = implode('/', $urlParts);
  88. $this->repository = preg_replace('#(\.git)$#', '', $match['repo']);
  89. $this->cache = new Cache($this->io, $this->config->get('cache-repo-dir').'/'.$this->originUrl.'/'.$this->namespace.'/'.$this->repository);
  90. $this->fetchProject();
  91. }
  92. /**
  93. * Updates the HttpDownloader instance.
  94. * Mainly useful for tests.
  95. *
  96. * @internal
  97. */
  98. public function setHttpDownloader(HttpDownloader $httpDownloader)
  99. {
  100. $this->httpDownloader = $httpDownloader;
  101. }
  102. /**
  103. * {@inheritdoc}
  104. */
  105. public function getFileContent($file, $identifier)
  106. {
  107. if ($this->gitDriver) {
  108. return $this->gitDriver->getFileContent($file, $identifier);
  109. }
  110. // Convert the root identifier to a cacheable commit id
  111. if (!preg_match('{[a-f0-9]{40}}i', $identifier)) {
  112. $branches = $this->getBranches();
  113. if (isset($branches[$identifier])) {
  114. $identifier = $branches[$identifier];
  115. }
  116. }
  117. $resource = $this->getApiUrl().'/repository/files/'.$this->urlEncodeAll($file).'/raw?ref='.$identifier;
  118. try {
  119. $content = $this->getContents($resource)->getBody();
  120. } catch (TransportException $e) {
  121. if ($e->getCode() !== 404) {
  122. throw $e;
  123. }
  124. return null;
  125. }
  126. return $content;
  127. }
  128. /**
  129. * {@inheritdoc}
  130. */
  131. public function getChangeDate($identifier)
  132. {
  133. if ($this->gitDriver) {
  134. return $this->gitDriver->getChangeDate($identifier);
  135. }
  136. if (isset($this->commits[$identifier])) {
  137. return new \DateTime($this->commits[$identifier]['committed_date']);
  138. }
  139. return new \DateTime();
  140. }
  141. /**
  142. * {@inheritDoc}
  143. */
  144. public function getRepositoryUrl()
  145. {
  146. return $this->isPrivate ? $this->project['ssh_url_to_repo'] : $this->project['http_url_to_repo'];
  147. }
  148. /**
  149. * {@inheritDoc}
  150. */
  151. public function getUrl()
  152. {
  153. if ($this->gitDriver) {
  154. return $this->gitDriver->getUrl();
  155. }
  156. return $this->project['web_url'];
  157. }
  158. /**
  159. * {@inheritDoc}
  160. */
  161. public function getDist($identifier)
  162. {
  163. $url = $this->getApiUrl().'/repository/archive.zip?sha='.$identifier;
  164. return array('type' => 'zip', 'url' => $url, 'reference' => $identifier, 'shasum' => '');
  165. }
  166. /**
  167. * {@inheritDoc}
  168. */
  169. public function getSource($identifier)
  170. {
  171. if ($this->gitDriver) {
  172. return $this->gitDriver->getSource($identifier);
  173. }
  174. return array('type' => 'git', 'url' => $this->getRepositoryUrl(), 'reference' => $identifier);
  175. }
  176. /**
  177. * {@inheritDoc}
  178. */
  179. public function getRootIdentifier()
  180. {
  181. if ($this->gitDriver) {
  182. return $this->gitDriver->getRootIdentifier();
  183. }
  184. return $this->project['default_branch'];
  185. }
  186. /**
  187. * {@inheritDoc}
  188. */
  189. public function getBranches()
  190. {
  191. if ($this->gitDriver) {
  192. return $this->gitDriver->getBranches();
  193. }
  194. if (!$this->branches) {
  195. $this->branches = $this->getReferences('branches');
  196. }
  197. return $this->branches;
  198. }
  199. /**
  200. * {@inheritDoc}
  201. */
  202. public function getTags()
  203. {
  204. if ($this->gitDriver) {
  205. return $this->gitDriver->getTags();
  206. }
  207. if (!$this->tags) {
  208. $this->tags = $this->getReferences('tags');
  209. }
  210. return $this->tags;
  211. }
  212. /**
  213. * @return string Base URL for GitLab API v3
  214. */
  215. public function getApiUrl()
  216. {
  217. return $this->scheme.'://'.$this->originUrl.'/api/v4/projects/'.$this->urlEncodeAll($this->namespace).'%2F'.$this->urlEncodeAll($this->repository);
  218. }
  219. /**
  220. * Urlencode all non alphanumeric characters. rawurlencode() can not be used as it does not encode `.`
  221. *
  222. * @param string $string
  223. * @return string
  224. */
  225. private function urlEncodeAll($string)
  226. {
  227. $encoded = '';
  228. for ($i = 0; isset($string[$i]); $i++) {
  229. $character = $string[$i];
  230. if (!ctype_alnum($character) && !in_array($character, array('-', '_'), true)) {
  231. $character = '%' . sprintf('%02X', ord($character));
  232. }
  233. $encoded .= $character;
  234. }
  235. return $encoded;
  236. }
  237. /**
  238. * @param string $type
  239. *
  240. * @return string[] where keys are named references like tags or branches and the value a sha
  241. */
  242. protected function getReferences($type)
  243. {
  244. $perPage = 100;
  245. $resource = $this->getApiUrl().'/repository/'.$type.'?per_page='.$perPage;
  246. $references = array();
  247. do {
  248. $response = $this->getContents($resource);
  249. $data = $response->decodeJson();
  250. foreach ($data as $datum) {
  251. $references[$datum['name']] = $datum['commit']['id'];
  252. // Keep the last commit date of a reference to avoid
  253. // unnecessary API call when retrieving the composer file.
  254. $this->commits[$datum['commit']['id']] = $datum['commit'];
  255. }
  256. if (count($data) >= $perPage) {
  257. $resource = $this->getNextPage($response);
  258. } else {
  259. $resource = false;
  260. }
  261. } while ($resource);
  262. return $references;
  263. }
  264. protected function fetchProject()
  265. {
  266. // we need to fetch the default branch from the api
  267. $resource = $this->getApiUrl();
  268. $this->project = $this->getContents($resource, true)->decodeJson();
  269. if (isset($this->project['visibility'])) {
  270. $this->isPrivate = $this->project['visibility'] !== 'public';
  271. } else {
  272. // client is not authendicated, therefore repository has to be public
  273. $this->isPrivate = false;
  274. }
  275. }
  276. protected function attemptCloneFallback()
  277. {
  278. try {
  279. if ($this->isPrivate === false) {
  280. $url = $this->generatePublicUrl();
  281. } else {
  282. $url = $this->generateSshUrl();
  283. }
  284. // If this repository may be private and we
  285. // cannot ask for authentication credentials (because we
  286. // are not interactive) then we fallback to GitDriver.
  287. $this->setupGitDriver($url);
  288. return true;
  289. } catch (\RuntimeException $e) {
  290. $this->gitDriver = null;
  291. $this->io->writeError('<error>Failed to clone the '.$url.' repository, try running in interactive mode so that you can enter your credentials</error>');
  292. throw $e;
  293. }
  294. }
  295. /**
  296. * Generate an SSH URL
  297. *
  298. * @return string
  299. */
  300. protected function generateSshUrl()
  301. {
  302. if ($this->hasNonstandardOrigin) {
  303. return 'ssh://git@'.$this->originUrl.'/'.$this->namespace.'/'.$this->repository.'.git';
  304. }
  305. return 'git@' . $this->originUrl . ':'.$this->namespace.'/'.$this->repository.'.git';
  306. }
  307. protected function generatePublicUrl()
  308. {
  309. return $this->scheme . '://' . $this->originUrl . '/'.$this->namespace.'/'.$this->repository.'.git';
  310. }
  311. protected function setupGitDriver($url)
  312. {
  313. $this->gitDriver = new GitDriver(
  314. array('url' => $url),
  315. $this->io,
  316. $this->config,
  317. $this->httpDownloader,
  318. $this->process
  319. );
  320. $this->gitDriver->initialize();
  321. }
  322. /**
  323. * {@inheritDoc}
  324. */
  325. protected function getContents($url, $fetchingRepoData = false)
  326. {
  327. try {
  328. $response = parent::getContents($url);
  329. if ($fetchingRepoData) {
  330. $json = $response->decodeJson();
  331. // force auth as the unauthenticated version of the API is broken
  332. if (!isset($json['default_branch'])) {
  333. if (!empty($json['id'])) {
  334. $this->isPrivate = false;
  335. }
  336. throw new TransportException('GitLab API seems to not be authenticated as it did not return a default_branch', 401);
  337. }
  338. }
  339. return $response;
  340. } catch (TransportException $e) {
  341. $gitLabUtil = new GitLab($this->io, $this->config, $this->process, $this->httpDownloader);
  342. switch ($e->getCode()) {
  343. case 401:
  344. case 404:
  345. // try to authorize only if we are fetching the main /repos/foo/bar data, otherwise it must be a real 404
  346. if (!$fetchingRepoData) {
  347. throw $e;
  348. }
  349. if ($gitLabUtil->authorizeOAuth($this->originUrl)) {
  350. return parent::getContents($url);
  351. }
  352. if (!$this->io->isInteractive()) {
  353. if ($this->attemptCloneFallback()) {
  354. return new Response(array('url' => 'dummy'), 200, array(), 'null');
  355. }
  356. }
  357. $this->io->writeError('<warning>Failed to download ' . $this->namespace . '/' . $this->repository . ':' . $e->getMessage() . '</warning>');
  358. $gitLabUtil->authorizeOAuthInteractively($this->scheme, $this->originUrl, 'Your credentials are required to fetch private repository metadata (<info>'.$this->url.'</info>)');
  359. return parent::getContents($url);
  360. case 403:
  361. if (!$this->io->hasAuthentication($this->originUrl) && $gitLabUtil->authorizeOAuth($this->originUrl)) {
  362. return parent::getContents($url);
  363. }
  364. if (!$this->io->isInteractive() && $fetchingRepoData) {
  365. if ($this->attemptCloneFallback()) {
  366. return new Response(array('url' => 'dummy'), 200, array(), 'null');
  367. }
  368. }
  369. throw $e;
  370. default:
  371. throw $e;
  372. }
  373. }
  374. }
  375. /**
  376. * Uses the config `gitlab-domains` to see if the driver supports the url for the
  377. * repository given.
  378. *
  379. * {@inheritDoc}
  380. */
  381. public static function supports(IOInterface $io, Config $config, $url, $deep = false)
  382. {
  383. if (!preg_match(self::URL_REGEX, $url, $match)) {
  384. return false;
  385. }
  386. $scheme = !empty($match['scheme']) ? $match['scheme'] : null;
  387. $guessedDomain = !empty($match['domain']) ? $match['domain'] : $match['domain2'];
  388. $urlParts = explode('/', $match['parts']);
  389. if (false === self::determineOrigin((array) $config->get('gitlab-domains'), $guessedDomain, $urlParts, $match['port'])) {
  390. return false;
  391. }
  392. if ('https' === $scheme && !extension_loaded('openssl')) {
  393. $io->writeError('Skipping GitLab driver for '.$url.' because the OpenSSL PHP extension is missing.', true, IOInterface::VERBOSE);
  394. return false;
  395. }
  396. return true;
  397. }
  398. protected function getNextPage(Response $response)
  399. {
  400. $header = $response->getHeader('link');
  401. $links = explode(',', $header);
  402. foreach ($links as $link) {
  403. if (preg_match('{<(.+?)>; *rel="next"}', $link, $match)) {
  404. return $match[1];
  405. }
  406. }
  407. }
  408. /**
  409. * @param array $configuredDomains
  410. * @param string $guessedDomain
  411. * @param array $urlParts
  412. * @return bool|string
  413. */
  414. private static function determineOrigin(array $configuredDomains, $guessedDomain, array &$urlParts, $portNumber)
  415. {
  416. $guessedDomain = strtolower($guessedDomain);
  417. if (in_array($guessedDomain, $configuredDomains) || ($portNumber && in_array($guessedDomain.':'.$portNumber, $configuredDomains))) {
  418. if ($portNumber) {
  419. return $guessedDomain.':'.$portNumber;
  420. }
  421. return $guessedDomain;
  422. }
  423. if ($portNumber) {
  424. $guessedDomain .= ':'.$portNumber;
  425. }
  426. while (null !== ($part = array_shift($urlParts))) {
  427. $guessedDomain .= '/' . $part;
  428. if (in_array($guessedDomain, $configuredDomains) || ($portNumber && in_array(preg_replace('{:\d+}', '', $guessedDomain), $configuredDomains))) {
  429. return $guessedDomain;
  430. }
  431. }
  432. return false;
  433. }
  434. }