sftp.php 9.5 KB

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