RemoteFilesystem.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412
  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\Composer;
  13. use Composer\Config;
  14. use Composer\IO\IOInterface;
  15. use Composer\Downloader\TransportException;
  16. /**
  17. * @author François Pluchino <francois.pluchino@opendisplay.com>
  18. * @author Jordi Boggiano <j.boggiano@seld.be>
  19. * @author Nils Adermann <naderman@naderman.de>
  20. */
  21. class RemoteFilesystem
  22. {
  23. private $io;
  24. private $config;
  25. private $firstCall;
  26. private $bytesMax;
  27. private $originUrl;
  28. private $fileUrl;
  29. private $fileName;
  30. private $retry;
  31. private $progress;
  32. private $lastProgress;
  33. private $options;
  34. private $retryAuthFailure;
  35. private $lastHeaders;
  36. /**
  37. * Constructor.
  38. *
  39. * @param IOInterface $io The IO instance
  40. * @param array $options The options
  41. */
  42. public function __construct(IOInterface $io, Config $config = null, array $options = array())
  43. {
  44. $this->io = $io;
  45. $this->config = $config;
  46. $this->options = $options;
  47. }
  48. /**
  49. * Copy the remote file in local.
  50. *
  51. * @param string $originUrl The origin URL
  52. * @param string $fileUrl The file URL
  53. * @param string $fileName the local filename
  54. * @param boolean $progress Display the progression
  55. * @param array $options Additional context options
  56. *
  57. * @return bool true
  58. */
  59. public function copy($originUrl, $fileUrl, $fileName, $progress = true, $options = array())
  60. {
  61. return $this->get($originUrl, $fileUrl, $options, $fileName, $progress);
  62. }
  63. /**
  64. * Get the content.
  65. *
  66. * @param string $originUrl The origin URL
  67. * @param string $fileUrl The file URL
  68. * @param boolean $progress Display the progression
  69. * @param array $options Additional context options
  70. *
  71. * @return string The content
  72. */
  73. public function getContents($originUrl, $fileUrl, $progress = true, $options = array())
  74. {
  75. return $this->get($originUrl, $fileUrl, $options, null, $progress);
  76. }
  77. /**
  78. * Retrieve the options set in the constructor
  79. *
  80. * @return array Options
  81. */
  82. public function getOptions()
  83. {
  84. return $this->options;
  85. }
  86. /**
  87. * Returns the headers of the last request
  88. *
  89. * @return array
  90. */
  91. public function getLastHeaders()
  92. {
  93. return $this->lastHeaders;
  94. }
  95. /**
  96. * Get file content or copy action.
  97. *
  98. * @param string $originUrl The origin URL
  99. * @param string $fileUrl The file URL
  100. * @param array $additionalOptions context options
  101. * @param string $fileName the local filename
  102. * @param boolean $progress Display the progression
  103. *
  104. * @throws TransportException|\Exception
  105. * @throws TransportException When the file could not be downloaded
  106. *
  107. * @return bool|string
  108. */
  109. protected function get($originUrl, $fileUrl, $additionalOptions = array(), $fileName = null, $progress = true)
  110. {
  111. if (strpos($originUrl, '.github.com') === (strlen($originUrl) - 11)) {
  112. $originUrl = 'github.com';
  113. }
  114. $this->bytesMax = 0;
  115. $this->originUrl = $originUrl;
  116. $this->fileUrl = $fileUrl;
  117. $this->fileName = $fileName;
  118. $this->progress = $progress;
  119. $this->lastProgress = null;
  120. $this->retryAuthFailure = true;
  121. $this->lastHeaders = array();
  122. // capture username/password from URL if there is one
  123. if (preg_match('{^https?://(.+):(.+)@([^/]+)}i', $fileUrl, $match)) {
  124. $this->io->setAuthentication($originUrl, urldecode($match[1]), urldecode($match[2]));
  125. }
  126. if (isset($additionalOptions['retry-auth-failure'])) {
  127. $this->retryAuthFailure = (bool) $additionalOptions['retry-auth-failure'];
  128. unset($additionalOptions['retry-auth-failure']);
  129. }
  130. $options = $this->getOptionsForUrl($originUrl, $additionalOptions);
  131. if ($this->io->isDebug()) {
  132. $this->io->write((substr($fileUrl, 0, 4) === 'http' ? 'Downloading ' : 'Reading ') . $fileUrl);
  133. }
  134. if (isset($options['github-token'])) {
  135. $fileUrl .= (false === strpos($fileUrl, '?') ? '?' : '&') . 'access_token='.$options['github-token'];
  136. unset($options['github-token']);
  137. }
  138. if (isset($options['http'])) {
  139. $options['http']['ignore_errors'] = true;
  140. }
  141. $ctx = StreamContextFactory::getContext($fileUrl, $options, array('notification' => array($this, 'callbackGet')));
  142. if ($this->progress) {
  143. $this->io->write(" Downloading: <comment>connection...</comment>", false);
  144. }
  145. $errorMessage = '';
  146. $errorCode = 0;
  147. $result = false;
  148. set_error_handler(function ($code, $msg) use (&$errorMessage) {
  149. if ($errorMessage) {
  150. $errorMessage .= "\n";
  151. }
  152. $errorMessage .= preg_replace('{^file_get_contents\(.*?\): }', '', $msg);
  153. });
  154. try {
  155. $result = file_get_contents($fileUrl, false, $ctx);
  156. } catch (\Exception $e) {
  157. if ($e instanceof TransportException && !empty($http_response_header[0])) {
  158. $e->setHeaders($http_response_header);
  159. }
  160. if ($e instanceof TransportException && $result !== false) {
  161. $e->setResponse($result);
  162. }
  163. $result = false;
  164. }
  165. if ($errorMessage && !ini_get('allow_url_fopen')) {
  166. $errorMessage = 'allow_url_fopen must be enabled in php.ini ('.$errorMessage.')';
  167. }
  168. restore_error_handler();
  169. if (isset($e) && !$this->retry) {
  170. throw $e;
  171. }
  172. // fail 4xx and 5xx responses and capture the response
  173. if (!empty($http_response_header[0]) && preg_match('{^HTTP/\S+ ([45]\d\d)}i', $http_response_header[0], $match)) {
  174. $errorCode = $match[1];
  175. if (!$this->retry) {
  176. $e = new TransportException('The "'.$this->fileUrl.'" file could not be downloaded ('.$http_response_header[0].')', $errorCode);
  177. $e->setHeaders($http_response_header);
  178. $e->setResponse($result);
  179. throw $e;
  180. }
  181. $result = false;
  182. }
  183. // decode gzip
  184. if ($result && extension_loaded('zlib') && substr($fileUrl, 0, 4) === 'http') {
  185. $decode = false;
  186. foreach ($http_response_header as $header) {
  187. if (preg_match('{^content-encoding: *gzip *$}i', $header)) {
  188. $decode = true;
  189. continue;
  190. } elseif (preg_match('{^HTTP/}i', $header)) {
  191. $decode = false;
  192. }
  193. }
  194. if ($decode) {
  195. if (version_compare(PHP_VERSION, '5.4.0', '>=')) {
  196. $result = zlib_decode($result);
  197. } else {
  198. // work around issue with gzuncompress & co that do not work with all gzip checksums
  199. $result = file_get_contents('compress.zlib://data:application/octet-stream;base64,'.base64_encode($result));
  200. }
  201. }
  202. }
  203. if ($this->progress && !$this->retry) {
  204. $this->io->overwrite(" Downloading: <comment>100%</comment>");
  205. }
  206. // handle copy command if download was successful
  207. if (false !== $result && null !== $fileName) {
  208. if ('' === $result) {
  209. throw new TransportException('"'.$this->fileUrl.'" appears broken, and returned an empty 200 response');
  210. }
  211. $errorMessage = '';
  212. set_error_handler(function ($code, $msg) use (&$errorMessage) {
  213. if ($errorMessage) {
  214. $errorMessage .= "\n";
  215. }
  216. $errorMessage .= preg_replace('{^file_put_contents\(.*?\): }', '', $msg);
  217. });
  218. $result = (bool) file_put_contents($fileName, $result);
  219. restore_error_handler();
  220. if (false === $result) {
  221. throw new TransportException('The "'.$this->fileUrl.'" file could not be written to '.$fileName.': '.$errorMessage);
  222. }
  223. }
  224. if ($this->retry) {
  225. $this->retry = false;
  226. return $this->get($this->originUrl, $this->fileUrl, $additionalOptions, $this->fileName, $this->progress);
  227. }
  228. if (false === $result) {
  229. $e = new TransportException('The "'.$this->fileUrl.'" file could not be downloaded: '.$errorMessage, $errorCode);
  230. if (!empty($http_response_header[0])) {
  231. $e->setHeaders($http_response_header);
  232. }
  233. throw $e;
  234. }
  235. if (!empty($http_response_header[0])) {
  236. $this->lastHeaders = $http_response_header;
  237. }
  238. return $result;
  239. }
  240. /**
  241. * Get notification action.
  242. *
  243. * @param integer $notificationCode The notification code
  244. * @param integer $severity The severity level
  245. * @param string $message The message
  246. * @param integer $messageCode The message code
  247. * @param integer $bytesTransferred The loaded size
  248. * @param integer $bytesMax The total size
  249. * @throws TransportException
  250. */
  251. protected function callbackGet($notificationCode, $severity, $message, $messageCode, $bytesTransferred, $bytesMax)
  252. {
  253. switch ($notificationCode) {
  254. case STREAM_NOTIFY_FAILURE:
  255. case STREAM_NOTIFY_AUTH_REQUIRED:
  256. if (401 === $messageCode) {
  257. // Bail if the caller is going to handle authentication failures itself.
  258. if (!$this->retryAuthFailure) {
  259. break;
  260. }
  261. $this->promptAuthAndRetry($messageCode);
  262. break;
  263. }
  264. break;
  265. case STREAM_NOTIFY_AUTH_RESULT:
  266. if (403 === $messageCode) {
  267. $this->promptAuthAndRetry($messageCode, $message);
  268. break;
  269. }
  270. break;
  271. case STREAM_NOTIFY_FILE_SIZE_IS:
  272. if ($this->bytesMax < $bytesMax) {
  273. $this->bytesMax = $bytesMax;
  274. }
  275. break;
  276. case STREAM_NOTIFY_PROGRESS:
  277. if ($this->bytesMax > 0 && $this->progress) {
  278. $progression = 0;
  279. if ($this->bytesMax > 0) {
  280. $progression = round($bytesTransferred / $this->bytesMax * 100);
  281. }
  282. if ((0 === $progression % 5) && $progression !== $this->lastProgress) {
  283. $this->lastProgress = $progression;
  284. $this->io->overwrite(" Downloading: <comment>$progression%</comment>", false);
  285. }
  286. }
  287. break;
  288. default:
  289. break;
  290. }
  291. }
  292. protected function promptAuthAndRetry($httpStatus, $reason = null)
  293. {
  294. if ($this->config && in_array($this->originUrl, $this->config->get('github-domains'), true)) {
  295. $message = "\n".'Could not fetch '.$this->fileUrl.', enter your GitHub credentials '.($httpStatus === 404 ? 'to access private repos' : 'to go over the API rate limit');
  296. $gitHubUtil = new GitHub($this->io, $this->config, null, $this);
  297. if (!$gitHubUtil->authorizeOAuth($this->originUrl)
  298. && (!$this->io->isInteractive() || !$gitHubUtil->authorizeOAuthInteractively($this->originUrl, $message))
  299. ) {
  300. throw new TransportException('Could not authenticate against '.$this->originUrl, 401);
  301. }
  302. } else {
  303. // 404s are only handled for github
  304. if ($httpStatus === 404) {
  305. return;
  306. }
  307. // fail if the console is not interactive
  308. if (!$this->io->isInteractive()) {
  309. if ($httpStatus === 401) {
  310. $message = "The '" . $this->fileUrl . "' URL required authentication.\nYou must be using the interactive console to authenticate";
  311. }
  312. if ($httpStatus === 403) {
  313. $message = "The '" . $this->fileUrl . "' URL could not be accessed: " . $reason;
  314. }
  315. throw new TransportException($message, $httpStatus);
  316. }
  317. // fail if we already have auth
  318. if ($this->io->hasAuthentication($this->originUrl)) {
  319. throw new TransportException("Invalid credentials for '" . $this->fileUrl . "', aborting.", $httpStatus);
  320. }
  321. $this->io->overwrite(' Authentication required (<info>'.parse_url($this->fileUrl, PHP_URL_HOST).'</info>):');
  322. $username = $this->io->ask(' Username: ');
  323. $password = $this->io->askAndHideAnswer(' Password: ');
  324. $this->io->setAuthentication($this->originUrl, $username, $password);
  325. }
  326. $this->retry = true;
  327. throw new TransportException('RETRY');
  328. }
  329. protected function getOptionsForUrl($originUrl, $additionalOptions)
  330. {
  331. $headers = array(
  332. sprintf(
  333. 'User-Agent: Composer/%s (%s; %s; PHP %s.%s.%s)',
  334. Composer::VERSION === '@package_version@' ? 'source' : Composer::VERSION,
  335. php_uname('s'),
  336. php_uname('r'),
  337. PHP_MAJOR_VERSION,
  338. PHP_MINOR_VERSION,
  339. PHP_RELEASE_VERSION
  340. )
  341. );
  342. if (extension_loaded('zlib')) {
  343. $headers[] = 'Accept-Encoding: gzip';
  344. }
  345. $options = array_replace_recursive($this->options, $additionalOptions);
  346. if ($this->io->hasAuthentication($originUrl)) {
  347. $auth = $this->io->getAuthentication($originUrl);
  348. if ('github.com' === $originUrl && 'x-oauth-basic' === $auth['password']) {
  349. $options['github-token'] = $auth['username'];
  350. } else {
  351. $authStr = base64_encode($auth['username'] . ':' . $auth['password']);
  352. $headers[] = 'Authorization: Basic '.$authStr;
  353. }
  354. }
  355. if (isset($options['http']['header']) && !is_array($options['http']['header'])) {
  356. $options['http']['header'] = explode("\r\n", trim($options['http']['header'], "\r\n"));
  357. }
  358. foreach ($headers as $header) {
  359. $options['http']['header'][] = $header;
  360. }
  361. return $options;
  362. }
  363. }