server/apps/files_external/lib/sftp.php

452 lines
9.7 KiB
PHP
Raw Normal View History

<?php
/**
2015-03-26 10:44:34 +00:00
* @author Andreas Fischer <bantu@owncloud.com>
* @author Bart Visscher <bartv@thisnet.nl>
* @author hkjolhede <hkjolhede@gmail.com>
* @author Jörn Friedrich Dreyer <jfd@butonic.de>
* @author Lennart Rosam <lennart.rosam@medien-systempartner.de>
* @author Lukas Reschke <lukas@owncloud.com>
* @author Morris Jobke <hey@morrisjobke.de>
* @author Robin McCorkell <rmccorkell@karoshi.org.uk>
* @author Ross Nicoll <jrn@jrn.me.uk>
* @author SA <stephen@mthosting.net>
* @author Vincent Petry <pvince81@owncloud.com>
*
* @copyright Copyright (c) 2015, ownCloud, Inc.
* @license AGPL-3.0
*
* This code is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License, version 3,
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License, version 3,
* along with this program. If not, see <http://www.gnu.org/licenses/>
*
*/
2013-02-09 14:57:33 +00:00
namespace OC\Files\Storage;
use Icewind\Streams\IteratorDirectory;
2015-08-03 04:39:53 +00:00
use phpseclib\Net\SFTP\Stream;
/**
2015-08-03 04:39:53 +00:00
* Uses phpseclib's Net\SFTP class and the Net\SFTP\Stream stream wrapper to
* provide access to SFTP servers.
*/
class SFTP extends \OC\Files\Storage\Common {
private $host;
private $user;
private $root;
2014-12-19 13:19:51 +00:00
private $port = 22;
private $auth;
/**
2015-08-03 04:39:53 +00:00
* @var SFTP
*/
protected $client;
2015-02-24 12:30:28 +00:00
/**
* {@inheritdoc}
*/
public function __construct($params) {
2015-02-03 15:02:07 +00:00
// Register sftp://
2015-08-03 04:39:53 +00:00
Stream::register();
$this->host = $params['host'];
2015-08-03 04:39:53 +00:00
2014-12-19 13:19:51 +00:00
//deals with sftp://server example
$proto = strpos($this->host, '://');
if ($proto != false) {
$this->host = substr($this->host, $proto+3);
}
2014-12-19 13:19:51 +00:00
//deals with server:port
2015-02-24 12:22:12 +00:00
$hasPort = strpos($this->host,':');
if($hasPort != false) {
2014-12-19 13:19:51 +00:00
$pieces = explode(":", $this->host);
$this->host = $pieces[0];
$this->port = $pieces[1];
}
$this->user = $params['user'];
if (isset($params['public_key_auth'])) {
$this->auth = $params['public_key_auth'];
} elseif (isset($params['password'])) {
$this->auth = $params['password'];
} else {
throw new \UnexpectedValueException('no authentication parameters specified');
}
2013-08-30 12:14:38 +00:00
$this->root
= isset($params['root']) ? $this->cleanPath($params['root']) : '/';
2013-02-22 16:21:57 +00:00
2013-08-30 12:14:38 +00:00
if ($this->root[0] != '/') {
$this->root = '/' . $this->root;
}
if (substr($this->root, -1, 1) != '/') {
$this->root .= '/';
}
}
/**
* Returns the connection.
*
2015-08-05 08:28:11 +00:00
* @return \phpseclib\Net\SFTP connected client instance
* @throws \Exception when the connection failed
*/
public function getConnection() {
if (!is_null($this->client)) {
return $this->client;
}
2013-08-30 12:14:38 +00:00
$hostKeys = $this->readHostKeys();
2015-08-05 08:28:11 +00:00
$this->client = new \phpseclib\Net\SFTP($this->host, $this->port);
2013-08-30 12:14:38 +00:00
// The SSH Host Key MUST be verified before login().
2013-08-30 12:14:38 +00:00
$currentHostKey = $this->client->getServerPublicHostKey();
if (array_key_exists($this->host, $hostKeys)) {
if ($hostKeys[$this->host] != $currentHostKey) {
throw new \Exception('Host public key does not match known key');
}
} else {
2013-08-30 12:14:38 +00:00
$hostKeys[$this->host] = $currentHostKey;
$this->writeHostKeys($hostKeys);
}
if (!$this->client->login($this->user, $this->auth)) {
throw new \Exception('Login failed');
}
return $this->client;
}
2013-02-22 16:21:57 +00:00
2015-02-24 12:30:28 +00:00
/**
* {@inheritdoc}
*/
public function test() {
2013-08-30 12:14:38 +00:00
if (
!isset($this->host)
|| !isset($this->user)
) {
2013-08-30 10:10:10 +00:00
return false;
2013-02-22 16:21:57 +00:00
}
return $this->getConnection()->nlist() !== false;
}
2013-02-22 16:21:57 +00:00
2015-02-24 12:30:28 +00:00
/**
* {@inheritdoc}
*/
2013-02-10 12:11:29 +00:00
public function getId(){
$id = 'sftp::' . $this->user . '@' . $this->host;
if ($this->port !== 22) {
$id .= ':' . $this->port;
}
// note: this will double the root slash,
// we should not change it to keep compatible with
// old storage ids
$id .= '/' . $this->root;
return $id;
2013-02-10 12:11:29 +00:00
}
2015-02-24 12:30:28 +00:00
/**
* @return string
*/
public function getHost() {
return $this->host;
}
2015-02-24 12:30:28 +00:00
/**
* @return string
*/
public function getRoot() {
return $this->root;
}
2015-02-24 12:30:28 +00:00
/**
* @return mixed
*/
public function getUser() {
return $this->user;
}
/**
* @param string $path
2015-02-24 12:30:28 +00:00
* @return string
*/
2013-08-30 12:14:38 +00:00
private function absPath($path) {
2013-02-09 22:49:21 +00:00
return $this->root . $this->cleanPath($path);
}
2015-02-24 12:30:28 +00:00
/**
* @return bool|string
*/
2013-08-30 12:14:38 +00:00
private function hostKeysPath() {
try {
$storage_view = \OCP\Files::getStorage('files_external');
if ($storage_view) {
return \OC::$server->getConfig()->getSystemValue('datadirectory') .
$storage_view->getAbsolutePath('') .
2013-08-30 12:14:38 +00:00
'ssh_hostKeys';
}
} catch (\Exception $e) {
}
return false;
}
2015-02-24 12:30:28 +00:00
/**
* @param $keys
* @return bool
*/
protected function writeHostKeys($keys) {
try {
2013-08-30 12:14:38 +00:00
$keyPath = $this->hostKeysPath();
2013-11-15 20:10:09 +00:00
if ($keyPath && file_exists($keyPath)) {
$fp = fopen($keyPath, 'w');
foreach ($keys as $host => $key) {
fwrite($fp, $host . '::' . $key . "\n");
}
fclose($fp);
return true;
}
} catch (\Exception $e) {
}
2013-11-15 20:10:09 +00:00
return false;
}
2015-02-24 12:30:28 +00:00
/**
* @return array
*/
protected function readHostKeys() {
try {
2013-08-30 12:14:38 +00:00
$keyPath = $this->hostKeysPath();
if (file_exists($keyPath)) {
$hosts = array();
$keys = array();
2013-08-30 12:14:38 +00:00
$lines = file($keyPath, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
if ($lines) {
foreach ($lines as $line) {
2013-08-30 12:14:38 +00:00
$hostKeyArray = explode("::", $line, 2);
if (count($hostKeyArray) == 2) {
$hosts[] = $hostKeyArray[0];
$keys[] = $hostKeyArray[1];
}
}
return array_combine($hosts, $keys);
}
}
} catch (\Exception $e) {
}
return array();
}
2015-02-24 12:30:28 +00:00
/**
* {@inheritdoc}
*/
public function mkdir($path) {
try {
return $this->getConnection()->mkdir($this->absPath($path));
} catch (\Exception $e) {
return false;
}
}
2015-02-24 12:30:28 +00:00
/**
* {@inheritdoc}
*/
public function rmdir($path) {
try {
$result = $this->getConnection()->delete($this->absPath($path), true);
// workaround: stray stat cache entry when deleting empty folders
// see https://github.com/phpseclib/phpseclib/issues/706
$this->getConnection()->clearStatCache();
return $result;
} catch (\Exception $e) {
return false;
}
}
2015-02-24 12:30:28 +00:00
/**
* {@inheritdoc}
*/
public function opendir($path) {
try {
$list = $this->getConnection()->nlist($this->absPath($path));
2014-08-27 08:02:14 +00:00
if ($list === false) {
return false;
}
$id = md5('sftp:' . $path);
2013-08-30 12:14:38 +00:00
$dirStream = array();
foreach($list as $file) {
if ($file != '.' && $file != '..') {
2013-08-30 12:14:38 +00:00
$dirStream[] = $file;
}
}
return IteratorDirectory::wrap($dirStream);
} catch(\Exception $e) {
return false;
}
}
2015-02-24 12:30:28 +00:00
/**
* {@inheritdoc}
*/
public function filetype($path) {
try {
$stat = $this->getConnection()->stat($this->absPath($path));
2013-08-30 12:14:38 +00:00
if ($stat['type'] == NET_SFTP_TYPE_REGULAR) {
return 'file';
}
if ($stat['type'] == NET_SFTP_TYPE_DIRECTORY) {
return 'dir';
}
} catch (\Exception $e) {
2013-08-30 12:14:38 +00:00
}
return false;
}
2015-02-24 12:30:28 +00:00
/**
* {@inheritdoc}
*/
public function file_exists($path) {
try {
return $this->getConnection()->stat($this->absPath($path)) !== false;
} catch (\Exception $e) {
return false;
}
}
2015-02-24 12:30:28 +00:00
/**
* {@inheritdoc}
*/
public function unlink($path) {
try {
return $this->getConnection()->delete($this->absPath($path), true);
} catch (\Exception $e) {
return false;
}
}
2015-02-24 12:30:28 +00:00
/**
* {@inheritdoc}
*/
public function fopen($path, $mode) {
try {
2013-08-30 12:14:38 +00:00
$absPath = $this->absPath($path);
switch($mode) {
case 'r':
case 'rb':
2013-08-30 12:14:38 +00:00
if ( !$this->file_exists($path)) {
return false;
}
case 'w':
case 'wb':
case 'a':
case 'ab':
case 'r+':
case 'w+':
case 'wb+':
case 'a+':
case 'x':
case 'x+':
case 'c':
case 'c+':
$context = stream_context_create(array('sftp' => array('session' => $this->getConnection())));
return fopen($this->constructUrl($path), $mode, false, $context);
}
} catch (\Exception $e) {
}
return false;
}
2015-02-24 12:30:28 +00:00
/**
* {@inheritdoc}
*/
public function touch($path, $mtime=null) {
try {
2013-08-30 12:14:38 +00:00
if (!is_null($mtime)) {
return false;
}
if (!$this->file_exists($path)) {
$this->getConnection()->put($this->absPath($path), '');
2013-02-09 22:29:58 +00:00
} else {
return false;
}
} catch (\Exception $e) {
2013-02-09 22:29:58 +00:00
return false;
}
2013-02-09 22:29:58 +00:00
return true;
}
2015-02-24 12:30:28 +00:00
/**
* @param string $path
* @param string $target
* @throws \Exception
*/
public function getFile($path, $target) {
$this->getConnection()->get($path, $target);
}
2015-02-24 12:30:28 +00:00
/**
* @param string $path
* @param string $target
* @throws \Exception
*/
public function uploadFile($path, $target) {
$this->getConnection()->put($target, $path, NET_SFTP_LOCAL_FILE);
}
2015-02-24 12:30:28 +00:00
/**
* {@inheritdoc}
*/
public function rename($source, $target) {
try {
if (!$this->is_dir($target) && $this->file_exists($target)) {
$this->unlink($target);
}
return $this->getConnection()->rename(
2013-08-30 12:14:38 +00:00
$this->absPath($source),
$this->absPath($target)
);
} catch (\Exception $e) {
return false;
}
}
2015-02-24 12:30:28 +00:00
/**
* {@inheritdoc}
*/
public function stat($path) {
try {
$stat = $this->getConnection()->stat($this->absPath($path));
$mtime = $stat ? $stat['mtime'] : -1;
$size = $stat ? $stat['size'] : 0;
return array('mtime' => $mtime, 'size' => $size, 'ctime' => -1);
} catch (\Exception $e) {
return false;
}
}
/**
* @param string $path
2015-02-24 12:30:28 +00:00
* @return string
*/
public function constructUrl($path) {
// Do not pass the password here. We want to use the Net_SFTP object
// supplied via stream context or fail. We only supply username and
// hostname because this might show up in logs (they are not used).
2014-12-19 13:19:51 +00:00
$url = 'sftp://'.$this->user.'@'.$this->host.':'.$this->port.$this->root.$path;
return $url;
}
}