RemoteFilesystem.php 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517
  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\IO\IOInterface;
  14. use Composer\Downloader\TransportException;
  15. /**
  16. * @author François Pluchino <francois.pluchino@opendisplay.com>
  17. * @author Jordi Boggiano <j.boggiano@seld.be>
  18. * @author Nils Adermann <naderman@naderman.de>
  19. */
  20. class RemoteFilesystem
  21. {
  22. private $io;
  23. private $firstCall;
  24. private $bytesMax;
  25. private $originUrl;
  26. private $fileUrl;
  27. private $fileName;
  28. private $retry;
  29. private $progress;
  30. private $lastProgress;
  31. private $options;
  32. /**
  33. * Constructor.
  34. *
  35. * @param IOInterface $io The IO instance
  36. * @param array $options The options
  37. */
  38. public function __construct(IOInterface $io, $options = array(), $disableTls = false)
  39. {
  40. $this->io = $io;
  41. /**
  42. * Setup TLS options
  43. * The cafile option can be set via config.json
  44. */
  45. if ($disableTls === false) {
  46. $this->options = $this->getTlsDefaults();
  47. if (isset($options['ssl']['cafile'])
  48. && (!is_readable($options['ssl']['cafile'])
  49. || !openssl_x509_parse(file_get_contents($options['ssl']['cafile'])))) { //check return value and test (it's subject to change)
  50. throw new TransportException('The configured cafile was not valid or could not be read.');
  51. }
  52. }
  53. // handle the other externally set options normally.
  54. $this->options = array_replace_recursive($this->options, $options);
  55. }
  56. /**
  57. * Copy the remote file in local.
  58. *
  59. * @param string $originUrl The origin URL
  60. * @param string $fileUrl The file URL
  61. * @param string $fileName the local filename
  62. * @param boolean $progress Display the progression
  63. * @param array $options Additional context options
  64. *
  65. * @return bool true
  66. */
  67. public function copy($originUrl, $fileUrl, $fileName, $progress = true, $options = array(), $disableTls = false)
  68. {
  69. return $this->get($originUrl, $fileUrl, $options, $fileName, $progress, $disableTls);
  70. }
  71. /**
  72. * Get the content.
  73. *
  74. * @param string $originUrl The origin URL
  75. * @param string $fileUrl The file URL
  76. * @param boolean $progress Display the progression
  77. * @param array $options Additional context options
  78. *
  79. * @return string The content
  80. */
  81. public function getContents($originUrl, $fileUrl, $progress = true, $options = array(), $disableTls = false)
  82. {
  83. return $this->get($originUrl, $fileUrl, $options, null, $progress, $disableTls);
  84. }
  85. /**
  86. * Retrieve the options set in the constructor
  87. *
  88. * @return array Options
  89. */
  90. public function getOptions()
  91. {
  92. return $this->options;
  93. }
  94. /**
  95. * Get file content or copy action.
  96. *
  97. * @param string $originUrl The origin URL
  98. * @param string $fileUrl The file URL
  99. * @param array $additionalOptions context options
  100. * @param string $fileName the local filename
  101. * @param boolean $progress Display the progression
  102. *
  103. * @throws TransportException|\Exception
  104. * @throws TransportException When the file could not be downloaded
  105. *
  106. * @return bool|string
  107. */
  108. protected function get($originUrl, $fileUrl, $additionalOptions = array(), $fileName = null, $progress = true, $disableTls = false)
  109. {
  110. $this->bytesMax = 0;
  111. $this->originUrl = $originUrl;
  112. $this->fileUrl = $fileUrl;
  113. $this->fileName = $fileName;
  114. $this->progress = $progress;
  115. $this->lastProgress = null;
  116. // capture username/password from URL if there is one
  117. if (preg_match('{^https?://(.+):(.+)@([^/]+)}i', $fileUrl, $match)) {
  118. $this->io->setAuthentication($originUrl, urldecode($match[1]), urldecode($match[2]));
  119. }
  120. $options = $this->getOptionsForUrl($originUrl, $additionalOptions, $disableTls);
  121. if ($this->io->isDebug()) {
  122. $this->io->write((substr($fileUrl, 0, 4) === 'http' ? 'Downloading ' : 'Reading ') . $fileUrl);
  123. }
  124. if (isset($options['github-token'])) {
  125. $fileUrl .= (false === strpos($fileUrl, '?') ? '?' : '&') . 'access_token='.$options['github-token'];
  126. unset($options['github-token']);
  127. }
  128. $ctx = StreamContextFactory::getContext($fileUrl, $options, array('notification' => array($this, 'callbackGet')));
  129. if ($this->progress) {
  130. $this->io->write(" Downloading: <comment>connection...</comment>", false);
  131. }
  132. $errorMessage = '';
  133. $errorCode = 0;
  134. $result = false;
  135. set_error_handler(function ($code, $msg) use (&$errorMessage) {
  136. if ($errorMessage) {
  137. $errorMessage .= "\n";
  138. }
  139. $errorMessage .= preg_replace('{^file_get_contents\(.*?\): }', '', $msg);
  140. });
  141. try {
  142. $result = file_get_contents($fileUrl, false, $ctx);
  143. } catch (\Exception $e) {
  144. if ($e instanceof TransportException && !empty($http_response_header[0])) {
  145. $e->setHeaders($http_response_header);
  146. }
  147. }
  148. if ($errorMessage && !ini_get('allow_url_fopen')) {
  149. $errorMessage = 'allow_url_fopen must be enabled in php.ini ('.$errorMessage.')';
  150. }
  151. restore_error_handler();
  152. if (isset($e) && !$this->retry) {
  153. throw $e;
  154. }
  155. // fix for 5.4.0 https://bugs.php.net/bug.php?id=61336
  156. if (!empty($http_response_header[0]) && preg_match('{^HTTP/\S+ ([45]\d\d)}i', $http_response_header[0], $match)) {
  157. $result = false;
  158. $errorCode = $match[1];
  159. }
  160. // decode gzip
  161. if ($result && extension_loaded('zlib') && substr($fileUrl, 0, 4) === 'http') {
  162. $decode = false;
  163. foreach ($http_response_header as $header) {
  164. if (preg_match('{^content-encoding: *gzip *$}i', $header)) {
  165. $decode = true;
  166. continue;
  167. } elseif (preg_match('{^HTTP/}i', $header)) {
  168. $decode = false;
  169. }
  170. }
  171. if ($decode) {
  172. if (version_compare(PHP_VERSION, '5.4.0', '>=')) {
  173. $result = zlib_decode($result);
  174. } else {
  175. // work around issue with gzuncompress & co that do not work with all gzip checksums
  176. $result = file_get_contents('compress.zlib://data:application/octet-stream;base64,'.base64_encode($result));
  177. }
  178. }
  179. }
  180. if ($this->progress) {
  181. $this->io->overwrite(" Downloading: <comment>100%</comment>");
  182. }
  183. // handle copy command if download was successful
  184. if (false !== $result && null !== $fileName) {
  185. if ('' === $result) {
  186. throw new TransportException('"'.$this->fileUrl.'" appears broken, and returned an empty 200 response');
  187. }
  188. $errorMessage = '';
  189. set_error_handler(function ($code, $msg) use (&$errorMessage) {
  190. if ($errorMessage) {
  191. $errorMessage .= "\n";
  192. }
  193. $errorMessage .= preg_replace('{^file_put_contents\(.*?\): }', '', $msg);
  194. });
  195. $result = (bool) file_put_contents($fileName, $result);
  196. restore_error_handler();
  197. if (false === $result) {
  198. throw new TransportException('The "'.$this->fileUrl.'" file could not be written to '.$fileName.': '.$errorMessage);
  199. }
  200. }
  201. if ($this->retry) {
  202. $this->retry = false;
  203. return $this->get($this->originUrl, $this->fileUrl, $additionalOptions, $this->fileName, $this->progress);
  204. }
  205. if (false === $result) {
  206. $e = new TransportException('The "'.$this->fileUrl.'" file could not be downloaded: '.$errorMessage, $errorCode);
  207. if (!empty($http_response_header[0])) {
  208. $e->setHeaders($http_response_header);
  209. }
  210. throw $e;
  211. }
  212. return $result;
  213. }
  214. /**
  215. * Get notification action.
  216. *
  217. * @param integer $notificationCode The notification code
  218. * @param integer $severity The severity level
  219. * @param string $message The message
  220. * @param integer $messageCode The message code
  221. * @param integer $bytesTransferred The loaded size
  222. * @param integer $bytesMax The total size
  223. * @throws TransportException
  224. */
  225. protected function callbackGet($notificationCode, $severity, $message, $messageCode, $bytesTransferred, $bytesMax)
  226. {
  227. switch ($notificationCode) {
  228. case STREAM_NOTIFY_FAILURE:
  229. case STREAM_NOTIFY_AUTH_REQUIRED:
  230. if (401 === $messageCode) {
  231. if (!$this->io->isInteractive()) {
  232. $message = "The '" . $this->fileUrl . "' URL required authentication.\nYou must be using the interactive console";
  233. throw new TransportException($message, 401);
  234. }
  235. $this->promptAuthAndRetry();
  236. break;
  237. }
  238. if ($notificationCode === STREAM_NOTIFY_AUTH_REQUIRED) {
  239. break;
  240. }
  241. throw new TransportException('The "'.$this->fileUrl.'" file could not be downloaded ('.trim($message).')', $messageCode);
  242. case STREAM_NOTIFY_AUTH_RESULT:
  243. if (403 === $messageCode) {
  244. if (!$this->io->isInteractive() || $this->io->hasAuthentication($this->originUrl)) {
  245. $message = "The '" . $this->fileUrl . "' URL could not be accessed: " . $message;
  246. throw new TransportException($message, 403);
  247. }
  248. $this->promptAuthAndRetry();
  249. break;
  250. }
  251. break;
  252. case STREAM_NOTIFY_FILE_SIZE_IS:
  253. if ($this->bytesMax < $bytesMax) {
  254. $this->bytesMax = $bytesMax;
  255. }
  256. break;
  257. case STREAM_NOTIFY_PROGRESS:
  258. if ($this->bytesMax > 0 && $this->progress) {
  259. $progression = 0;
  260. if ($this->bytesMax > 0) {
  261. $progression = round($bytesTransferred / $this->bytesMax * 100);
  262. }
  263. if ((0 === $progression % 5) && $progression !== $this->lastProgress) {
  264. $this->lastProgress = $progression;
  265. $this->io->overwrite(" Downloading: <comment>$progression%</comment>", false);
  266. }
  267. }
  268. break;
  269. default:
  270. break;
  271. }
  272. }
  273. protected function promptAuthAndRetry()
  274. {
  275. $this->io->overwrite(' Authentication required (<info>'.parse_url($this->fileUrl, PHP_URL_HOST).'</info>):');
  276. $username = $this->io->ask(' Username: ');
  277. $password = $this->io->askAndHideAnswer(' Password: ');
  278. $this->io->setAuthentication($this->originUrl, $username, $password);
  279. $this->retry = true;
  280. throw new TransportException('RETRY');
  281. }
  282. protected function getOptionsForUrl($originUrl, $additionalOptions, $disableTls = false)
  283. {
  284. $headers = array(
  285. sprintf(
  286. 'User-Agent: Composer/%s (%s; %s; PHP %s.%s.%s)',
  287. Composer::VERSION === '@package_version@' ? 'source' : Composer::VERSION,
  288. php_uname('s'),
  289. php_uname('r'),
  290. PHP_MAJOR_VERSION,
  291. PHP_MINOR_VERSION,
  292. PHP_RELEASE_VERSION
  293. )
  294. );
  295. if (extension_loaded('zlib')) {
  296. $headers[] = 'Accept-Encoding: gzip';
  297. }
  298. // Setup remaining TLS options - the matching may need monitoring, esp. www vs none in CN
  299. if ($disableTls === false) {
  300. $host = parse_url($originUrl, PHP_URL_HOST);
  301. $this->options['ssl']['CN_match'] = $host;
  302. $this->options['ssl']['SNI_server_name'] = $host;
  303. }
  304. $options = array_replace_recursive($this->options, $additionalOptions);
  305. if ($this->io->hasAuthentication($originUrl)) {
  306. $auth = $this->io->getAuthentication($originUrl);
  307. if ('github.com' === $originUrl && 'x-oauth-basic' === $auth['password']) {
  308. $options['github-token'] = $auth['username'];
  309. } else {
  310. $authStr = base64_encode($auth['username'] . ':' . $auth['password']);
  311. $headers[] = 'Authorization: Basic '.$authStr;
  312. }
  313. }
  314. if (isset($options['http']['header']) && !is_array($options['http']['header'])) {
  315. $options['http']['header'] = explode("\r\n", trim($options['http']['header'], "\r\n"));
  316. }
  317. foreach ($headers as $header) {
  318. $options['http']['header'][] = $header;
  319. }
  320. return $options;
  321. }
  322. protected function getTlsDefaults()
  323. {
  324. $ciphers = implode(':', array(
  325. 'ECDHE-RSA-AES128-GCM-SHA256',
  326. 'ECDHE-ECDSA-AES128-GCM-SHA256',
  327. 'ECDHE-RSA-AES256-GCM-SHA384',
  328. 'ECDHE-ECDSA-AES256-GCM-SHA384',
  329. 'DHE-RSA-AES128-GCM-SHA256',
  330. 'DHE-DSS-AES128-GCM-SHA256',
  331. 'kEDH+AESGCM',
  332. 'ECDHE-RSA-AES128-SHA256',
  333. 'ECDHE-ECDSA-AES128-SHA256',
  334. 'ECDHE-RSA-AES128-SHA',
  335. 'ECDHE-ECDSA-AES128-SHA',
  336. 'ECDHE-RSA-AES256-SHA384',
  337. 'ECDHE-ECDSA-AES256-SHA384',
  338. 'ECDHE-RSA-AES256-SHA',
  339. 'ECDHE-ECDSA-AES256-SHA',
  340. 'DHE-RSA-AES128-SHA256',
  341. 'DHE-RSA-AES128-SHA',
  342. 'DHE-DSS-AES128-SHA256',
  343. 'DHE-RSA-AES256-SHA256',
  344. 'DHE-DSS-AES256-SHA',
  345. 'DHE-RSA-AES256-SHA',
  346. 'AES128-GCM-SHA256',
  347. 'AES256-GCM-SHA384',
  348. 'ECDHE-RSA-RC4-SHA',
  349. 'ECDHE-ECDSA-RC4-SHA',
  350. 'AES128',
  351. 'AES256',
  352. 'RC4-SHA',
  353. 'HIGH',
  354. '!aNULL',
  355. '!eNULL',
  356. '!EXPORT',
  357. '!DES',
  358. '!3DES',
  359. '!MD5',
  360. '!PSK'
  361. ));
  362. /**
  363. * CN_match and SNI_server_name are only known once a URL is passed.
  364. * They will be set in the getOptionsForUrl() method which receives a URL.
  365. *
  366. * cafile or capath can be overridden by passing in those options to constructor.
  367. */
  368. $options = array(
  369. 'ssl' => array(
  370. 'ciphers' => $ciphers,
  371. 'verify_peer' => true,
  372. 'verify_depth' => 7,
  373. 'SNI_enabled' => true,
  374. )
  375. );
  376. /**
  377. * Attempt to find a local cafile or throw an exception.
  378. * The user may go download one if this occurs.
  379. */
  380. $result = $this->getSystemCaRootBundlePath();
  381. if ($result) {
  382. $options['ssl']['cafile'] = $result;
  383. } else {
  384. throw new TransportException('A valid cafile could not be located automatically.');
  385. }
  386. /**
  387. * Disable TLS compression to prevent CRIME attacks where supported.
  388. */
  389. if (version_compare(PHP_VERSION, '5.4.13') >= 0) {
  390. $options['ssl']['disable_compression'] = true;
  391. }
  392. return $options;
  393. }
  394. /**
  395. * This method was adapted from Sslurp.
  396. * https://github.com/EvanDotPro/Sslurp
  397. *
  398. * (c) Evan Coury <me@evancoury.com>
  399. *
  400. * For the full copyright and license information, please see below:
  401. *
  402. * Copyright (c) 2013, Evan Coury
  403. * All rights reserved.
  404. *
  405. * Redistribution and use in source and binary forms, with or without modification,
  406. * are permitted provided that the following conditions are met:
  407. *
  408. * * Redistributions of source code must retain the above copyright notice,
  409. * this list of conditions and the following disclaimer.
  410. *
  411. * * Redistributions in binary form must reproduce the above copyright notice,
  412. * this list of conditions and the following disclaimer in the documentation
  413. * and/or other materials provided with the distribution.
  414. *
  415. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
  416. * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  417. * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  418. * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
  419. * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  420. * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  421. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
  422. * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  423. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  424. * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  425. */
  426. protected static function getSystemCaRootBundlePath()
  427. {
  428. if (isset($found)) {
  429. return $found;
  430. }
  431. // If SSL_CERT_FILE env variable points to a valid certificate/bundle, use that.
  432. // This mimics how OpenSSL uses the SSL_CERT_FILE env variable.
  433. $envCertFile = getenv('SSL_CERT_FILE');
  434. if ($envCertFile && is_readable($envCertFile) && openssl_x509_parse(file_get_contents($envCertFile))) {
  435. // Possibly throw exception instead of ignoring SSL_CERT_FILE if it's invalid?
  436. return $envCertFile;
  437. }
  438. $caBundlePaths = array(
  439. '/etc/pki/tls/certs/ca-bundle.crt', // Fedora, RHEL, CentOS (ca-certificates package)
  440. '/etc/ssl/certs/ca-certificates.crt', // Debian, Ubuntu, Gentoo, Arch Linux (ca-certificates package)
  441. '/etc/ssl/ca-bundle.pem', // SUSE, openSUSE (ca-certificates package)
  442. '/usr/local/share/certs/ca-root-nss.crt', // FreeBSD (ca_root_nss_package)
  443. '/usr/ssl/certs/ca-bundle.crt', // Cygwin
  444. '/opt/local/share/curl/curl-ca-bundle.crt', // OS X macports, curl-ca-bundle package
  445. '/usr/local/share/curl/curl-ca-bundle.crt', // Default cURL CA bunde path (without --with-ca-bundle option)
  446. '/usr/share/ssl/certs/ca-bundle.crt', // Really old RedHat?
  447. );
  448. static $found = false;
  449. foreach ($caBundlePaths as $caBundle) {
  450. if (is_readable($caBundle) && openssl_x509_parse(file_get_contents($caBundle))) {
  451. $found = true;
  452. break;
  453. }
  454. }
  455. if ($found) {
  456. $found = $caBundle;
  457. }
  458. return $found;
  459. }
  460. }