PageRenderTime 48ms CodeModel.GetById 18ms RepoModel.GetById 1ms app.codeStats 0ms

/apps/files_external/lib/storage/sftp.php

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