SFTP.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588
  1. <?php
  2. /**
  3. * @copyright Copyright (c) 2016, ownCloud, Inc.
  4. *
  5. * @author Andreas Fischer <bantu@owncloud.com>
  6. * @author Bart Visscher <bartv@thisnet.nl>
  7. * @author Christoph Wurst <christoph@winzerhof-wurst.at>
  8. * @author hkjolhede <hkjolhede@gmail.com>
  9. * @author Joas Schilling <coding@schilljs.com>
  10. * @author Jörn Friedrich Dreyer <jfd@butonic.de>
  11. * @author Lennart Rosam <lennart.rosam@medien-systempartner.de>
  12. * @author Lukas Reschke <lukas@statuscode.ch>
  13. * @author Morris Jobke <hey@morrisjobke.de>
  14. * @author Robin Appelman <robin@icewind.nl>
  15. * @author Robin McCorkell <robin@mccorkell.me.uk>
  16. * @author Roeland Jago Douma <roeland@famdouma.nl>
  17. * @author Ross Nicoll <jrn@jrn.me.uk>
  18. * @author SA <stephen@mthosting.net>
  19. * @author Senorsen <senorsen.zhang@gmail.com>
  20. * @author Vincent Petry <vincent@nextcloud.com>
  21. *
  22. * @license AGPL-3.0
  23. *
  24. * This code is free software: you can redistribute it and/or modify
  25. * it under the terms of the GNU Affero General Public License, version 3,
  26. * as published by the Free Software Foundation.
  27. *
  28. * This program is distributed in the hope that it will be useful,
  29. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  30. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  31. * GNU Affero General Public License for more details.
  32. *
  33. * You should have received a copy of the GNU Affero General Public License, version 3,
  34. * along with this program. If not, see <http://www.gnu.org/licenses/>
  35. *
  36. */
  37. namespace OCA\Files_External\Lib\Storage;
  38. use Icewind\Streams\CountWrapper;
  39. use Icewind\Streams\IteratorDirectory;
  40. use Icewind\Streams\RetryWrapper;
  41. use OC\Files\Filesystem;
  42. use OC\Files\Storage\Common;
  43. use OCP\Constants;
  44. use OCP\Files\FileInfo;
  45. use OCP\Files\IMimeTypeDetector;
  46. use phpseclib\Net\SFTP\Stream;
  47. /**
  48. * Uses phpseclib's Net\SFTP class and the Net\SFTP\Stream stream wrapper to
  49. * provide access to SFTP servers.
  50. */
  51. class SFTP extends Common {
  52. private $host;
  53. private $user;
  54. private $root;
  55. private $port = 22;
  56. private $auth = [];
  57. /**
  58. * @var \phpseclib\Net\SFTP
  59. */
  60. protected $client;
  61. private IMimeTypeDetector $mimeTypeDetector;
  62. const COPY_CHUNK_SIZE = 8 * 1024 * 1024;
  63. /**
  64. * @param string $host protocol://server:port
  65. * @return array [$server, $port]
  66. */
  67. private function splitHost($host) {
  68. $input = $host;
  69. if (!str_contains($host, '://')) {
  70. // add a protocol to fix parse_url behavior with ipv6
  71. $host = 'http://' . $host;
  72. }
  73. $parsed = parse_url($host);
  74. if (is_array($parsed) && isset($parsed['port'])) {
  75. return [$parsed['host'], $parsed['port']];
  76. } elseif (is_array($parsed)) {
  77. return [$parsed['host'], 22];
  78. } else {
  79. return [$input, 22];
  80. }
  81. }
  82. /**
  83. * {@inheritdoc}
  84. */
  85. public function __construct($params) {
  86. // Register sftp://
  87. Stream::register();
  88. $parsedHost = $this->splitHost($params['host']);
  89. $this->host = $parsedHost[0];
  90. $this->port = $parsedHost[1];
  91. if (!isset($params['user'])) {
  92. throw new \UnexpectedValueException('no authentication parameters specified');
  93. }
  94. $this->user = $params['user'];
  95. if (isset($params['public_key_auth'])) {
  96. $this->auth[] = $params['public_key_auth'];
  97. }
  98. if (isset($params['password']) && $params['password'] !== '') {
  99. $this->auth[] = $params['password'];
  100. }
  101. if ($this->auth === []) {
  102. throw new \UnexpectedValueException('no authentication parameters specified');
  103. }
  104. $this->root
  105. = isset($params['root']) ? $this->cleanPath($params['root']) : '/';
  106. $this->root = '/' . ltrim($this->root, '/');
  107. $this->root = rtrim($this->root, '/') . '/';
  108. $this->mimeTypeDetector = \OC::$server->get(IMimeTypeDetector::class);
  109. }
  110. /**
  111. * Returns the connection.
  112. *
  113. * @return \phpseclib\Net\SFTP connected client instance
  114. * @throws \Exception when the connection failed
  115. */
  116. public function getConnection() {
  117. if (!is_null($this->client)) {
  118. return $this->client;
  119. }
  120. $hostKeys = $this->readHostKeys();
  121. $this->client = new \phpseclib\Net\SFTP($this->host, $this->port);
  122. // The SSH Host Key MUST be verified before login().
  123. $currentHostKey = $this->client->getServerPublicHostKey();
  124. if (array_key_exists($this->host, $hostKeys)) {
  125. if ($hostKeys[$this->host] !== $currentHostKey) {
  126. throw new \Exception('Host public key does not match known key');
  127. }
  128. } else {
  129. $hostKeys[$this->host] = $currentHostKey;
  130. $this->writeHostKeys($hostKeys);
  131. }
  132. $login = false;
  133. foreach ($this->auth as $auth) {
  134. /** @psalm-suppress TooManyArguments */
  135. $login = $this->client->login($this->user, $auth);
  136. if ($login === true) {
  137. break;
  138. }
  139. }
  140. if ($login === false) {
  141. throw new \Exception('Login failed');
  142. }
  143. return $this->client;
  144. }
  145. /**
  146. * {@inheritdoc}
  147. */
  148. public function test() {
  149. if (
  150. !isset($this->host)
  151. || !isset($this->user)
  152. ) {
  153. return false;
  154. }
  155. return $this->getConnection()->nlist() !== false;
  156. }
  157. /**
  158. * {@inheritdoc}
  159. */
  160. public function getId() {
  161. $id = 'sftp::' . $this->user . '@' . $this->host;
  162. if ($this->port !== 22) {
  163. $id .= ':' . $this->port;
  164. }
  165. // note: this will double the root slash,
  166. // we should not change it to keep compatible with
  167. // old storage ids
  168. $id .= '/' . $this->root;
  169. return $id;
  170. }
  171. /**
  172. * @return string
  173. */
  174. public function getHost() {
  175. return $this->host;
  176. }
  177. /**
  178. * @return string
  179. */
  180. public function getRoot() {
  181. return $this->root;
  182. }
  183. /**
  184. * @return mixed
  185. */
  186. public function getUser() {
  187. return $this->user;
  188. }
  189. /**
  190. * @param string $path
  191. * @return string
  192. */
  193. private function absPath($path) {
  194. return $this->root . $this->cleanPath($path);
  195. }
  196. /**
  197. * @return string|false
  198. */
  199. private function hostKeysPath() {
  200. try {
  201. $storage_view = \OCP\Files::getStorage('files_external');
  202. if ($storage_view) {
  203. return \OC::$server->getConfig()->getSystemValue('datadirectory', \OC::$SERVERROOT . '/data') .
  204. $storage_view->getAbsolutePath('') .
  205. 'ssh_hostKeys';
  206. }
  207. } catch (\Exception $e) {
  208. }
  209. return false;
  210. }
  211. /**
  212. * @param $keys
  213. * @return bool
  214. */
  215. protected function writeHostKeys($keys) {
  216. try {
  217. $keyPath = $this->hostKeysPath();
  218. if ($keyPath && file_exists($keyPath)) {
  219. $fp = fopen($keyPath, 'w');
  220. foreach ($keys as $host => $key) {
  221. fwrite($fp, $host . '::' . $key . "\n");
  222. }
  223. fclose($fp);
  224. return true;
  225. }
  226. } catch (\Exception $e) {
  227. }
  228. return false;
  229. }
  230. /**
  231. * @return array
  232. */
  233. protected function readHostKeys() {
  234. try {
  235. $keyPath = $this->hostKeysPath();
  236. if (file_exists($keyPath)) {
  237. $hosts = [];
  238. $keys = [];
  239. $lines = file($keyPath, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
  240. if ($lines) {
  241. foreach ($lines as $line) {
  242. $hostKeyArray = explode("::", $line, 2);
  243. if (count($hostKeyArray) === 2) {
  244. $hosts[] = $hostKeyArray[0];
  245. $keys[] = $hostKeyArray[1];
  246. }
  247. }
  248. return array_combine($hosts, $keys);
  249. }
  250. }
  251. } catch (\Exception $e) {
  252. }
  253. return [];
  254. }
  255. /**
  256. * {@inheritdoc}
  257. */
  258. public function mkdir($path) {
  259. try {
  260. return $this->getConnection()->mkdir($this->absPath($path));
  261. } catch (\Exception $e) {
  262. return false;
  263. }
  264. }
  265. /**
  266. * {@inheritdoc}
  267. */
  268. public function rmdir($path) {
  269. try {
  270. $result = $this->getConnection()->delete($this->absPath($path), true);
  271. // workaround: stray stat cache entry when deleting empty folders
  272. // see https://github.com/phpseclib/phpseclib/issues/706
  273. $this->getConnection()->clearStatCache();
  274. return $result;
  275. } catch (\Exception $e) {
  276. return false;
  277. }
  278. }
  279. /**
  280. * {@inheritdoc}
  281. */
  282. public function opendir($path) {
  283. try {
  284. $list = $this->getConnection()->nlist($this->absPath($path));
  285. if ($list === false) {
  286. return false;
  287. }
  288. $id = md5('sftp:' . $path);
  289. $dirStream = [];
  290. foreach ($list as $file) {
  291. if ($file !== '.' && $file !== '..') {
  292. $dirStream[] = $file;
  293. }
  294. }
  295. return IteratorDirectory::wrap($dirStream);
  296. } catch (\Exception $e) {
  297. return false;
  298. }
  299. }
  300. /**
  301. * {@inheritdoc}
  302. */
  303. public function filetype($path) {
  304. try {
  305. $stat = $this->getConnection()->stat($this->absPath($path));
  306. if (!is_array($stat) || !array_key_exists('type', $stat)) {
  307. return false;
  308. }
  309. if ((int) $stat['type'] === NET_SFTP_TYPE_REGULAR) {
  310. return 'file';
  311. }
  312. if ((int) $stat['type'] === NET_SFTP_TYPE_DIRECTORY) {
  313. return 'dir';
  314. }
  315. } catch (\Exception $e) {
  316. }
  317. return false;
  318. }
  319. /**
  320. * {@inheritdoc}
  321. */
  322. public function file_exists($path) {
  323. try {
  324. return $this->getConnection()->stat($this->absPath($path)) !== false;
  325. } catch (\Exception $e) {
  326. return false;
  327. }
  328. }
  329. /**
  330. * {@inheritdoc}
  331. */
  332. public function unlink($path) {
  333. try {
  334. return $this->getConnection()->delete($this->absPath($path), true);
  335. } catch (\Exception $e) {
  336. return false;
  337. }
  338. }
  339. /**
  340. * {@inheritdoc}
  341. */
  342. public function fopen($path, $mode) {
  343. try {
  344. $absPath = $this->absPath($path);
  345. $connection = $this->getConnection();
  346. switch ($mode) {
  347. case 'r':
  348. case 'rb':
  349. $stat = $this->stat($path);
  350. if (!$stat) {
  351. return false;
  352. }
  353. SFTPReadStream::register();
  354. $context = stream_context_create(['sftp' => ['session' => $connection, 'size' => $stat['size']]]);
  355. $handle = fopen('sftpread://' . trim($absPath, '/'), 'r', false, $context);
  356. return RetryWrapper::wrap($handle);
  357. case 'w':
  358. case 'wb':
  359. SFTPWriteStream::register();
  360. // the SFTPWriteStream doesn't go through the "normal" methods so it doesn't clear the stat cache.
  361. $connection->_remove_from_stat_cache($absPath);
  362. $context = stream_context_create(['sftp' => ['session' => $connection]]);
  363. return fopen('sftpwrite://' . trim($absPath, '/'), 'w', false, $context);
  364. case 'a':
  365. case 'ab':
  366. case 'r+':
  367. case 'w+':
  368. case 'wb+':
  369. case 'a+':
  370. case 'x':
  371. case 'x+':
  372. case 'c':
  373. case 'c+':
  374. $context = stream_context_create(['sftp' => ['session' => $connection]]);
  375. $handle = fopen($this->constructUrl($path), $mode, false, $context);
  376. return RetryWrapper::wrap($handle);
  377. }
  378. } catch (\Exception $e) {
  379. }
  380. return false;
  381. }
  382. /**
  383. * {@inheritdoc}
  384. */
  385. public function touch($path, $mtime = null) {
  386. try {
  387. if (!is_null($mtime)) {
  388. return false;
  389. }
  390. if (!$this->file_exists($path)) {
  391. $this->getConnection()->put($this->absPath($path), '');
  392. } else {
  393. return false;
  394. }
  395. } catch (\Exception $e) {
  396. return false;
  397. }
  398. return true;
  399. }
  400. /**
  401. * @param string $path
  402. * @param string $target
  403. * @throws \Exception
  404. */
  405. public function getFile($path, $target) {
  406. $this->getConnection()->get($path, $target);
  407. }
  408. /**
  409. * {@inheritdoc}
  410. */
  411. public function rename($source, $target) {
  412. try {
  413. if ($this->file_exists($target)) {
  414. $this->unlink($target);
  415. }
  416. return $this->getConnection()->rename(
  417. $this->absPath($source),
  418. $this->absPath($target)
  419. );
  420. } catch (\Exception $e) {
  421. return false;
  422. }
  423. }
  424. /**
  425. * @return array{mtime: int, size: int, ctime: int}|false
  426. */
  427. public function stat($path) {
  428. try {
  429. $stat = $this->getConnection()->stat($this->absPath($path));
  430. $mtime = $stat ? (int)$stat['mtime'] : -1;
  431. $size = $stat ? (int)$stat['size'] : 0;
  432. return ['mtime' => $mtime, 'size' => $size, 'ctime' => -1];
  433. } catch (\Exception $e) {
  434. return false;
  435. }
  436. }
  437. /**
  438. * @param string $path
  439. * @return string
  440. */
  441. public function constructUrl($path) {
  442. // Do not pass the password here. We want to use the Net_SFTP object
  443. // supplied via stream context or fail. We only supply username and
  444. // hostname because this might show up in logs (they are not used).
  445. $url = 'sftp://' . urlencode($this->user) . '@' . $this->host . ':' . $this->port . $this->root . $path;
  446. return $url;
  447. }
  448. public function file_put_contents($path, $data) {
  449. /** @psalm-suppress InternalMethod */
  450. $result = $this->getConnection()->put($this->absPath($path), $data);
  451. if ($result) {
  452. return strlen($data);
  453. } else {
  454. return false;
  455. }
  456. }
  457. public function writeStream(string $path, $stream, int $size = null): int {
  458. if ($size === null) {
  459. $stream = CountWrapper::wrap($stream, function (int $writtenSize) use (&$size) {
  460. $size = $writtenSize;
  461. });
  462. if (!$stream) {
  463. throw new \Exception("Failed to wrap stream");
  464. }
  465. }
  466. /** @psalm-suppress InternalMethod */
  467. $result = $this->getConnection()->put($this->absPath($path), $stream);
  468. fclose($stream);
  469. if ($result) {
  470. return $size;
  471. } else {
  472. throw new \Exception("Failed to write steam to sftp storage");
  473. }
  474. }
  475. public function copy($source, $target) {
  476. if ($this->is_dir($source) || $this->is_dir($target)) {
  477. return parent::copy($source, $target);
  478. } else {
  479. $absSource = $this->absPath($source);
  480. $absTarget = $this->absPath($target);
  481. $connection = $this->getConnection();
  482. $size = $connection->size($absSource);
  483. if ($size === false) {
  484. return false;
  485. }
  486. for ($i = 0; $i < $size; $i += self::COPY_CHUNK_SIZE) {
  487. /** @psalm-suppress InvalidArgument */
  488. $chunk = $connection->get($absSource, false, $i, self::COPY_CHUNK_SIZE);
  489. if ($chunk === false) {
  490. return false;
  491. }
  492. /** @psalm-suppress InternalMethod */
  493. if (!$connection->put($absTarget, $chunk, \phpseclib\Net\SFTP::SOURCE_STRING, $i)) {
  494. return false;
  495. }
  496. }
  497. return true;
  498. }
  499. }
  500. public function getPermissions($path) {
  501. $stat = $this->getConnection()->stat($this->absPath($path));
  502. if (!$stat) {
  503. return 0;
  504. }
  505. if ($stat['type'] === NET_SFTP_TYPE_DIRECTORY) {
  506. return Constants::PERMISSION_ALL;
  507. } else {
  508. return Constants::PERMISSION_ALL - Constants::PERMISSION_CREATE;
  509. }
  510. }
  511. public function getMetaData($path) {
  512. $stat = $this->getConnection()->stat($this->absPath($path));
  513. if (!$stat) {
  514. return null;
  515. }
  516. if ($stat['type'] === NET_SFTP_TYPE_DIRECTORY) {
  517. $stat['permissions'] = Constants::PERMISSION_ALL;
  518. } else {
  519. $stat['permissions'] = Constants::PERMISSION_ALL - Constants::PERMISSION_CREATE;
  520. }
  521. if ($stat['type'] === NET_SFTP_TYPE_DIRECTORY) {
  522. $stat['size'] = -1;
  523. $stat['mimetype'] = FileInfo::MIMETYPE_FOLDER;
  524. } else {
  525. $stat['mimetype'] = $this->mimeTypeDetector->detectPath($path);
  526. }
  527. $stat['etag'] = $this->getETag($path);
  528. $stat['storage_mtime'] = $stat['mtime'];
  529. $stat['name'] = basename($path);
  530. $keys = ['size', 'mtime', 'mimetype', 'etag', 'storage_mtime', 'permissions', 'name'];
  531. return array_intersect_key($stat, array_flip($keys));
  532. }
  533. }