SFTP.php 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469
  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 hkjolhede <hkjolhede@gmail.com>
  8. * @author Jörn Friedrich Dreyer <jfd@butonic.de>
  9. * @author Lennart Rosam <lennart.rosam@medien-systempartner.de>
  10. * @author Lukas Reschke <lukas@statuscode.ch>
  11. * @author Morris Jobke <hey@morrisjobke.de>
  12. * @author Robin Appelman <robin@icewind.nl>
  13. * @author Robin McCorkell <robin@mccorkell.me.uk>
  14. * @author Ross Nicoll <jrn@jrn.me.uk>
  15. * @author SA <stephen@mthosting.net>
  16. * @author Senorsen <senorsen.zhang@gmail.com>
  17. * @author Vincent Petry <pvince81@owncloud.com>
  18. *
  19. * @license AGPL-3.0
  20. *
  21. * This code is free software: you can redistribute it and/or modify
  22. * it under the terms of the GNU Affero General Public License, version 3,
  23. * as published by the Free Software Foundation.
  24. *
  25. * This program is distributed in the hope that it will be useful,
  26. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  27. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  28. * GNU Affero General Public License for more details.
  29. *
  30. * You should have received a copy of the GNU Affero General Public License, version 3,
  31. * along with this program. If not, see <http://www.gnu.org/licenses/>
  32. *
  33. */
  34. namespace OCA\Files_External\Lib\Storage;
  35. use Icewind\Streams\IteratorDirectory;
  36. use Icewind\Streams\RetryWrapper;
  37. use phpseclib\Net\SFTP\Stream;
  38. /**
  39. * Uses phpseclib's Net\SFTP class and the Net\SFTP\Stream stream wrapper to
  40. * provide access to SFTP servers.
  41. */
  42. class SFTP extends \OC\Files\Storage\Common {
  43. private $host;
  44. private $user;
  45. private $root;
  46. private $port = 22;
  47. private $auth;
  48. /**
  49. * @var \phpseclib\Net\SFTP
  50. */
  51. protected $client;
  52. /**
  53. * @param string $host protocol://server:port
  54. * @return array [$server, $port]
  55. */
  56. private function splitHost($host) {
  57. $input = $host;
  58. if (strpos($host, '://') === false) {
  59. // add a protocol to fix parse_url behavior with ipv6
  60. $host = 'http://' . $host;
  61. }
  62. $parsed = parse_url($host);
  63. if(is_array($parsed) && isset($parsed['port'])) {
  64. return [$parsed['host'], $parsed['port']];
  65. } else if (is_array($parsed)) {
  66. return [$parsed['host'], 22];
  67. } else {
  68. return [$input, 22];
  69. }
  70. }
  71. /**
  72. * {@inheritdoc}
  73. */
  74. public function __construct($params) {
  75. // Register sftp://
  76. Stream::register();
  77. $parsedHost = $this->splitHost($params['host']);
  78. $this->host = $parsedHost[0];
  79. $this->port = $parsedHost[1];
  80. if (!isset($params['user'])) {
  81. throw new \UnexpectedValueException('no authentication parameters specified');
  82. }
  83. $this->user = $params['user'];
  84. if (isset($params['public_key_auth'])) {
  85. $this->auth = $params['public_key_auth'];
  86. } elseif (isset($params['password'])) {
  87. $this->auth = $params['password'];
  88. } else {
  89. throw new \UnexpectedValueException('no authentication parameters specified');
  90. }
  91. $this->root
  92. = isset($params['root']) ? $this->cleanPath($params['root']) : '/';
  93. if ($this->root[0] != '/') {
  94. $this->root = '/' . $this->root;
  95. }
  96. if (substr($this->root, -1, 1) != '/') {
  97. $this->root .= '/';
  98. }
  99. }
  100. /**
  101. * Returns the connection.
  102. *
  103. * @return \phpseclib\Net\SFTP connected client instance
  104. * @throws \Exception when the connection failed
  105. */
  106. public function getConnection() {
  107. if (!is_null($this->client)) {
  108. return $this->client;
  109. }
  110. $hostKeys = $this->readHostKeys();
  111. $this->client = new \phpseclib\Net\SFTP($this->host, $this->port);
  112. // The SSH Host Key MUST be verified before login().
  113. $currentHostKey = $this->client->getServerPublicHostKey();
  114. if (array_key_exists($this->host, $hostKeys)) {
  115. if ($hostKeys[$this->host] != $currentHostKey) {
  116. throw new \Exception('Host public key does not match known key');
  117. }
  118. } else {
  119. $hostKeys[$this->host] = $currentHostKey;
  120. $this->writeHostKeys($hostKeys);
  121. }
  122. if (!$this->client->login($this->user, $this->auth)) {
  123. throw new \Exception('Login failed');
  124. }
  125. return $this->client;
  126. }
  127. /**
  128. * {@inheritdoc}
  129. */
  130. public function test() {
  131. if (
  132. !isset($this->host)
  133. || !isset($this->user)
  134. ) {
  135. return false;
  136. }
  137. return $this->getConnection()->nlist() !== false;
  138. }
  139. /**
  140. * {@inheritdoc}
  141. */
  142. public function getId(){
  143. $id = 'sftp::' . $this->user . '@' . $this->host;
  144. if ($this->port !== 22) {
  145. $id .= ':' . $this->port;
  146. }
  147. // note: this will double the root slash,
  148. // we should not change it to keep compatible with
  149. // old storage ids
  150. $id .= '/' . $this->root;
  151. return $id;
  152. }
  153. /**
  154. * @return string
  155. */
  156. public function getHost() {
  157. return $this->host;
  158. }
  159. /**
  160. * @return string
  161. */
  162. public function getRoot() {
  163. return $this->root;
  164. }
  165. /**
  166. * @return mixed
  167. */
  168. public function getUser() {
  169. return $this->user;
  170. }
  171. /**
  172. * @param string $path
  173. * @return string
  174. */
  175. private function absPath($path) {
  176. return $this->root . $this->cleanPath($path);
  177. }
  178. /**
  179. * @return string|false
  180. */
  181. private function hostKeysPath() {
  182. try {
  183. $storage_view = \OCP\Files::getStorage('files_external');
  184. if ($storage_view) {
  185. return \OC::$server->getConfig()->getSystemValue('datadirectory', \OC::$SERVERROOT . '/data') .
  186. $storage_view->getAbsolutePath('') .
  187. 'ssh_hostKeys';
  188. }
  189. } catch (\Exception $e) {
  190. }
  191. return false;
  192. }
  193. /**
  194. * @param $keys
  195. * @return bool
  196. */
  197. protected function writeHostKeys($keys) {
  198. try {
  199. $keyPath = $this->hostKeysPath();
  200. if ($keyPath && file_exists($keyPath)) {
  201. $fp = fopen($keyPath, 'w');
  202. foreach ($keys as $host => $key) {
  203. fwrite($fp, $host . '::' . $key . "\n");
  204. }
  205. fclose($fp);
  206. return true;
  207. }
  208. } catch (\Exception $e) {
  209. }
  210. return false;
  211. }
  212. /**
  213. * @return array
  214. */
  215. protected function readHostKeys() {
  216. try {
  217. $keyPath = $this->hostKeysPath();
  218. if (file_exists($keyPath)) {
  219. $hosts = array();
  220. $keys = array();
  221. $lines = file($keyPath, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
  222. if ($lines) {
  223. foreach ($lines as $line) {
  224. $hostKeyArray = explode("::", $line, 2);
  225. if (count($hostKeyArray) == 2) {
  226. $hosts[] = $hostKeyArray[0];
  227. $keys[] = $hostKeyArray[1];
  228. }
  229. }
  230. return array_combine($hosts, $keys);
  231. }
  232. }
  233. } catch (\Exception $e) {
  234. }
  235. return array();
  236. }
  237. /**
  238. * {@inheritdoc}
  239. */
  240. public function mkdir($path) {
  241. try {
  242. return $this->getConnection()->mkdir($this->absPath($path));
  243. } catch (\Exception $e) {
  244. return false;
  245. }
  246. }
  247. /**
  248. * {@inheritdoc}
  249. */
  250. public function rmdir($path) {
  251. try {
  252. $result = $this->getConnection()->delete($this->absPath($path), true);
  253. // workaround: stray stat cache entry when deleting empty folders
  254. // see https://github.com/phpseclib/phpseclib/issues/706
  255. $this->getConnection()->clearStatCache();
  256. return $result;
  257. } catch (\Exception $e) {
  258. return false;
  259. }
  260. }
  261. /**
  262. * {@inheritdoc}
  263. */
  264. public function opendir($path) {
  265. try {
  266. $list = $this->getConnection()->nlist($this->absPath($path));
  267. if ($list === false) {
  268. return false;
  269. }
  270. $id = md5('sftp:' . $path);
  271. $dirStream = array();
  272. foreach($list as $file) {
  273. if ($file != '.' && $file != '..') {
  274. $dirStream[] = $file;
  275. }
  276. }
  277. return IteratorDirectory::wrap($dirStream);
  278. } catch(\Exception $e) {
  279. return false;
  280. }
  281. }
  282. /**
  283. * {@inheritdoc}
  284. */
  285. public function filetype($path) {
  286. try {
  287. $stat = $this->getConnection()->stat($this->absPath($path));
  288. if ($stat['type'] == NET_SFTP_TYPE_REGULAR) {
  289. return 'file';
  290. }
  291. if ($stat['type'] == NET_SFTP_TYPE_DIRECTORY) {
  292. return 'dir';
  293. }
  294. } catch (\Exception $e) {
  295. }
  296. return false;
  297. }
  298. /**
  299. * {@inheritdoc}
  300. */
  301. public function file_exists($path) {
  302. try {
  303. return $this->getConnection()->stat($this->absPath($path)) !== false;
  304. } catch (\Exception $e) {
  305. return false;
  306. }
  307. }
  308. /**
  309. * {@inheritdoc}
  310. */
  311. public function unlink($path) {
  312. try {
  313. return $this->getConnection()->delete($this->absPath($path), true);
  314. } catch (\Exception $e) {
  315. return false;
  316. }
  317. }
  318. /**
  319. * {@inheritdoc}
  320. */
  321. public function fopen($path, $mode) {
  322. try {
  323. $absPath = $this->absPath($path);
  324. switch($mode) {
  325. case 'r':
  326. case 'rb':
  327. if ( !$this->file_exists($path)) {
  328. return false;
  329. }
  330. case 'w':
  331. case 'wb':
  332. case 'a':
  333. case 'ab':
  334. case 'r+':
  335. case 'w+':
  336. case 'wb+':
  337. case 'a+':
  338. case 'x':
  339. case 'x+':
  340. case 'c':
  341. case 'c+':
  342. $context = stream_context_create(array('sftp' => array('session' => $this->getConnection())));
  343. $handle = fopen($this->constructUrl($path), $mode, false, $context);
  344. return RetryWrapper::wrap($handle);
  345. }
  346. } catch (\Exception $e) {
  347. }
  348. return false;
  349. }
  350. /**
  351. * {@inheritdoc}
  352. */
  353. public function touch($path, $mtime=null) {
  354. try {
  355. if (!is_null($mtime)) {
  356. return false;
  357. }
  358. if (!$this->file_exists($path)) {
  359. $this->getConnection()->put($this->absPath($path), '');
  360. } else {
  361. return false;
  362. }
  363. } catch (\Exception $e) {
  364. return false;
  365. }
  366. return true;
  367. }
  368. /**
  369. * @param string $path
  370. * @param string $target
  371. * @throws \Exception
  372. */
  373. public function getFile($path, $target) {
  374. $this->getConnection()->get($path, $target);
  375. }
  376. /**
  377. * @param string $path
  378. * @param string $target
  379. * @throws \Exception
  380. */
  381. public function uploadFile($path, $target) {
  382. $this->getConnection()->put($target, $path, NET_SFTP_LOCAL_FILE);
  383. }
  384. /**
  385. * {@inheritdoc}
  386. */
  387. public function rename($source, $target) {
  388. try {
  389. if ($this->file_exists($target)) {
  390. $this->unlink($target);
  391. }
  392. return $this->getConnection()->rename(
  393. $this->absPath($source),
  394. $this->absPath($target)
  395. );
  396. } catch (\Exception $e) {
  397. return false;
  398. }
  399. }
  400. /**
  401. * {@inheritdoc}
  402. */
  403. public function stat($path) {
  404. try {
  405. $stat = $this->getConnection()->stat($this->absPath($path));
  406. $mtime = $stat ? $stat['mtime'] : -1;
  407. $size = $stat ? $stat['size'] : 0;
  408. return array('mtime' => $mtime, 'size' => $size, 'ctime' => -1);
  409. } catch (\Exception $e) {
  410. return false;
  411. }
  412. }
  413. /**
  414. * @param string $path
  415. * @return string
  416. */
  417. public function constructUrl($path) {
  418. // Do not pass the password here. We want to use the Net_SFTP object
  419. // supplied via stream context or fail. We only supply username and
  420. // hostname because this might show up in logs (they are not used).
  421. $url = 'sftp://' . urlencode($this->user) . '@' . $this->host . ':' . $this->port . $this->root . $path;
  422. return $url;
  423. }
  424. }