Git.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262
  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\Util;
  12. use Composer\Config;
  13. use Composer\IO\IOInterface;
  14. use Composer\Downloader\TransportException;
  15. /**
  16. * @author Jordi Boggiano <j.boggiano@seld.be>
  17. */
  18. class Git
  19. {
  20. /** @var IOInterface */
  21. protected $io;
  22. /** @var Config */
  23. protected $config;
  24. /** @var ProcessExecutor */
  25. protected $process;
  26. /** @var Filesystem */
  27. protected $filesystem;
  28. public function __construct(IOInterface $io, Config $config, ProcessExecutor $process, Filesystem $fs)
  29. {
  30. $this->io = $io;
  31. $this->config = $config;
  32. $this->process = $process;
  33. $this->filesystem = $fs;
  34. }
  35. public function runCommand($commandCallable, $url, $cwd, $initialClone = false)
  36. {
  37. // Ensure we are allowed to use this URL by config
  38. $this->config->prohibitUrlByConfig($url);
  39. if ($initialClone) {
  40. $origCwd = $cwd;
  41. $cwd = null;
  42. }
  43. if (preg_match('{^ssh://[^@]+@[^:]+:[^0-9]+}', $url)) {
  44. throw new \InvalidArgumentException('The source URL '.$url.' is invalid, ssh URLs should have a port number after ":".'."\n".'Use ssh://git@example.com:22/path or just git@example.com:path if you do not want to provide a password or custom port.');
  45. }
  46. if (!$initialClone) {
  47. // capture username/password from URL if there is one
  48. $this->process->execute('git remote -v', $output, $cwd);
  49. if (preg_match('{^(?:composer|origin)\s+https?://(.+):(.+)@([^/]+)}im', $output, $match)) {
  50. $this->io->setAuthentication($match[3], urldecode($match[1]), urldecode($match[2]));
  51. }
  52. }
  53. $protocols = $this->config->get('github-protocols');
  54. if (!is_array($protocols)) {
  55. throw new \RuntimeException('Config value "github-protocols" must be an array, got '.gettype($protocols));
  56. }
  57. // public github, autoswitch protocols
  58. if (preg_match('{^(?:https?|git)://'.self::getGitHubDomainsRegex($this->config).'/(.*)}', $url, $match)) {
  59. $messages = array();
  60. foreach ($protocols as $protocol) {
  61. if ('ssh' === $protocol) {
  62. $protoUrl = "git@" . $match[1] . ":" . $match[2];
  63. } else {
  64. $protoUrl = $protocol ."://" . $match[1] . "/" . $match[2];
  65. }
  66. if (0 === $this->process->execute(call_user_func($commandCallable, $protoUrl), $ignoredOutput, $cwd)) {
  67. return;
  68. }
  69. $messages[] = '- ' . $protoUrl . "\n" . preg_replace('#^#m', ' ', $this->process->getErrorOutput());
  70. if ($initialClone) {
  71. $this->filesystem->removeDirectory($origCwd);
  72. }
  73. }
  74. // failed to checkout, first check git accessibility
  75. $this->throwException('Failed to clone ' . self::sanitizeUrl($url) .' via '.implode(', ', $protocols).' protocols, aborting.' . "\n\n" . implode("\n", $messages), $url);
  76. }
  77. // if we have a private github url and the ssh protocol is disabled then we skip it and directly fallback to https
  78. $bypassSshForGitHub = preg_match('{^git@'.self::getGitHubDomainsRegex($this->config).':(.+?)\.git$}i', $url) && !in_array('ssh', $protocols, true);
  79. $command = call_user_func($commandCallable, $url);
  80. $auth = null;
  81. if ($bypassSshForGitHub || 0 !== $this->process->execute($command, $ignoredOutput, $cwd)) {
  82. // private github repository without git access, try https with auth
  83. if (preg_match('{^git@'.self::getGitHubDomainsRegex($this->config).':(.+?)\.git$}i', $url, $match)) {
  84. if (!$this->io->hasAuthentication($match[1])) {
  85. $gitHubUtil = new GitHub($this->io, $this->config, $this->process);
  86. $message = 'Cloning failed using an ssh key for authentication, enter your GitHub credentials to access private repos';
  87. if (!$gitHubUtil->authorizeOAuth($match[1]) && $this->io->isInteractive()) {
  88. $gitHubUtil->authorizeOAuthInteractively($match[1], $message);
  89. }
  90. }
  91. if ($this->io->hasAuthentication($match[1])) {
  92. $auth = $this->io->getAuthentication($match[1]);
  93. $authUrl = 'https://' . rawurlencode($auth['username']) . ':' . rawurlencode($auth['password']) . '@' . $match[1] . '/' . $match[2] . '.git';
  94. $command = call_user_func($commandCallable, $authUrl);
  95. if (0 === $this->process->execute($command, $ignoredOutput, $cwd)) {
  96. return;
  97. }
  98. }
  99. } elseif (preg_match('{^https://(bitbucket.org)/(.*)}', $url, $match)) { //bitbucket oauth
  100. $bitbucketUtil = new Bitbucket($this->io, $this->config, $this->process);
  101. if (!$this->io->hasAuthentication($match[1])) {
  102. $message = 'Enter your Bitbucket credentials to access private repos';
  103. if (!$bitbucketUtil->authorizeOAuth($match[1]) && $this->io->isInteractive()) {
  104. $bitbucketUtil->authorizeOAuthInteractively($match[1], $message);
  105. $token = $bitbucketUtil->getToken();
  106. $this->io->setAuthentication($match[1], 'x-token-auth', $token['access_token']);
  107. }
  108. } else { //We're authenticating with a locally stored consumer.
  109. $auth = $this->io->getAuthentication($match[1]);
  110. //We already have an access_token from a previous request.
  111. if($auth['username'] !== 'x-token-auth') {
  112. $token = $bitbucketUtil->requestToken($match[1], $auth['username'], $auth['password']);
  113. $this->io->setAuthentication($match[1], 'x-token-auth', $token['access_token']);
  114. }
  115. }
  116. if ($this->io->hasAuthentication($match[1])) {
  117. $auth = $this->io->getAuthentication($match[1]);
  118. $authUrl = 'https://' . rawurlencode($auth['username']) . ':' . rawurlencode($auth['password']) . '@' . $match[1] . '/' . $match[2] . '.git';
  119. $command = call_user_func($commandCallable, $authUrl);
  120. if (0 === $this->process->execute($command, $ignoredOutput, $cwd)) {
  121. return;
  122. }
  123. }
  124. } elseif ($this->isAuthenticationFailure($url, $match)) { // private non-github repo that failed to authenticate
  125. if (strpos($match[2], '@')) {
  126. list($authParts, $match[2]) = explode('@', $match[2], 2);
  127. }
  128. $storeAuth = false;
  129. if ($this->io->hasAuthentication($match[2])) {
  130. $auth = $this->io->getAuthentication($match[2]);
  131. } elseif ($this->io->isInteractive()) {
  132. $defaultUsername = null;
  133. if (isset($authParts) && $authParts) {
  134. if (false !== strpos($authParts, ':')) {
  135. list($defaultUsername, ) = explode(':', $authParts, 2);
  136. } else {
  137. $defaultUsername = $authParts;
  138. }
  139. }
  140. $this->io->writeError(' Authentication required (<info>'.parse_url($url, PHP_URL_HOST).'</info>):');
  141. $auth = array(
  142. 'username' => $this->io->ask(' Username: ', $defaultUsername),
  143. 'password' => $this->io->askAndHideAnswer(' Password: '),
  144. );
  145. $storeAuth = $this->config->get('store-auths');
  146. }
  147. if ($auth) {
  148. $authUrl = $match[1].rawurlencode($auth['username']).':'.rawurlencode($auth['password']).'@'.$match[2].$match[3];
  149. $command = call_user_func($commandCallable, $authUrl);
  150. if (0 === $this->process->execute($command, $ignoredOutput, $cwd)) {
  151. $this->io->setAuthentication($match[2], $auth['username'], $auth['password']);
  152. $authHelper = new AuthHelper($this->io, $this->config);
  153. $authHelper->storeAuth($match[2], $storeAuth);
  154. return;
  155. }
  156. }
  157. }
  158. if ($initialClone) {
  159. $this->filesystem->removeDirectory($origCwd);
  160. }
  161. $this->throwException('Failed to execute ' . self::sanitizeUrl($command) . "\n\n" . $this->process->getErrorOutput(), $url);
  162. }
  163. }
  164. private function isAuthenticationFailure($url, &$match)
  165. {
  166. if (!preg_match('{(https?://)([^/]+)(.*)$}i', $url, $match)) {
  167. return false;
  168. }
  169. $authFailures = array('fatal: Authentication failed', 'remote error: Invalid username or password.');
  170. foreach ($authFailures as $authFailure) {
  171. if (strpos($this->process->getErrorOutput(), $authFailure) !== false) {
  172. return true;
  173. }
  174. }
  175. return false;
  176. }
  177. public static function cleanEnv()
  178. {
  179. if (ini_get('safe_mode') && false === strpos(ini_get('safe_mode_allowed_env_vars'), 'GIT_ASKPASS')) {
  180. throw new \RuntimeException('safe_mode is enabled and safe_mode_allowed_env_vars does not contain GIT_ASKPASS, can not set env var. You can disable safe_mode with "-dsafe_mode=0" when running composer');
  181. }
  182. // added in git 1.7.1, prevents prompting the user for username/password
  183. if (getenv('GIT_ASKPASS') !== 'echo') {
  184. putenv('GIT_ASKPASS=echo');
  185. unset($_SERVER['GIT_ASKPASS']);
  186. }
  187. // clean up rogue git env vars in case this is running in a git hook
  188. if (getenv('GIT_DIR')) {
  189. putenv('GIT_DIR');
  190. unset($_SERVER['GIT_DIR']);
  191. }
  192. if (getenv('GIT_WORK_TREE')) {
  193. putenv('GIT_WORK_TREE');
  194. unset($_SERVER['GIT_WORK_TREE']);
  195. }
  196. // Run processes with predictable LANGUAGE
  197. if (getenv('LANGUAGE') !== 'C') {
  198. putenv('LANGUAGE=C');
  199. }
  200. // clean up env for OSX, see https://github.com/composer/composer/issues/2146#issuecomment-35478940
  201. putenv("DYLD_LIBRARY_PATH");
  202. unset($_SERVER['DYLD_LIBRARY_PATH']);
  203. }
  204. public static function getGitHubDomainsRegex(Config $config)
  205. {
  206. return '('.implode('|', array_map('preg_quote', $config->get('github-domains'))).')';
  207. }
  208. public static function sanitizeUrl($message)
  209. {
  210. return preg_replace('{://([^@]+?):.+?@}', '://$1:***@', $message);
  211. }
  212. private function throwException($message, $url)
  213. {
  214. // git might delete a directory when it fails and php will not know
  215. clearstatcache();
  216. if (0 !== $this->process->execute('git --version', $ignoredOutput)) {
  217. throw new \RuntimeException('Failed to clone '.self::sanitizeUrl($url).', git was not found, check that it is installed and in your PATH env.' . "\n\n" . $this->process->getErrorOutput());
  218. }
  219. throw new \RuntimeException($message);
  220. }
  221. }