sftp.php 9.6 KB

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