/phpseclib/Net/SFTP.php
http://github.com/phpseclib/phpseclib · PHP · 3532 lines · 1954 code · 352 blank · 1226 comment · 404 complexity · 93d5ca36f0d39437f9d98f0a1889f5df MD5 · raw file
Large files are truncated click here to view the full file
- <?php
- /**
- * Pure-PHP implementation of SFTP.
- *
- * PHP version 5
- *
- * Supports SFTPv2/3/4/5/6. Defaults to v3.
- *
- * The API for this library is modeled after the API from PHP's {@link http://php.net/book.ftp FTP extension}.
- *
- * Here's a short example of how to use this library:
- * <code>
- * <?php
- * include 'vendor/autoload.php';
- *
- * $sftp = new \phpseclib3\Net\SFTP('www.domain.tld');
- * if (!$sftp->login('username', 'password')) {
- * exit('Login Failed');
- * }
- *
- * echo $sftp->pwd() . "\r\n";
- * $sftp->put('filename.ext', 'hello, world!');
- * print_r($sftp->nlist());
- * ?>
- * </code>
- *
- * @category Net
- * @package SFTP
- * @author Jim Wigginton <terrafrost@php.net>
- * @copyright 2009 Jim Wigginton
- * @license http://www.opensource.org/licenses/mit-license.html MIT License
- * @link http://phpseclib.sourceforge.net
- */
- namespace phpseclib3\Net;
- use phpseclib3\Exception\FileNotFoundException;
- use phpseclib3\Common\Functions\Strings;
- use phpseclib3\Crypt\Common\AsymmetricKey;
- use phpseclib3\System\SSH\Agent;
- /**
- * Pure-PHP implementations of SFTP.
- *
- * @package SFTP
- * @author Jim Wigginton <terrafrost@php.net>
- * @access public
- */
- class SFTP extends SSH2
- {
- /**
- * SFTP channel constant
- *
- * \phpseclib3\Net\SSH2::exec() uses 0 and \phpseclib3\Net\SSH2::read() / \phpseclib3\Net\SSH2::write() use 1.
- *
- * @see \phpseclib3\Net\SSH2::send_channel_packet()
- * @see \phpseclib3\Net\SSH2::get_channel_packet()
- * @access private
- */
- const CHANNEL = 0x100;
- /**
- * Reads data from a local file.
- *
- * @access public
- * @see \phpseclib3\Net\SFTP::put()
- */
- const SOURCE_LOCAL_FILE = 1;
- /**
- * Reads data from a string.
- *
- * @access public
- * @see \phpseclib3\Net\SFTP::put()
- */
- // this value isn't really used anymore but i'm keeping it reserved for historical reasons
- const SOURCE_STRING = 2;
- /**
- * Reads data from callback:
- * function callback($length) returns string to proceed, null for EOF
- *
- * @access public
- * @see \phpseclib3\Net\SFTP::put()
- */
- const SOURCE_CALLBACK = 16;
- /**
- * Resumes an upload
- *
- * @access public
- * @see \phpseclib3\Net\SFTP::put()
- */
- const RESUME = 4;
- /**
- * Append a local file to an already existing remote file
- *
- * @access public
- * @see \phpseclib3\Net\SFTP::put()
- */
- const RESUME_START = 8;
- /**
- * Packet Types
- *
- * @see self::__construct()
- * @var array
- * @access private
- */
- private $packet_types = [];
- /**
- * Status Codes
- *
- * @see self::__construct()
- * @var array
- * @access private
- */
- private $status_codes = [];
- /**
- * The Request ID
- *
- * The request ID exists in the off chance that a packet is sent out-of-order. Of course, this library doesn't support
- * concurrent actions, so it's somewhat academic, here.
- *
- * @var boolean
- * @see self::_send_sftp_packet()
- * @access private
- */
- private $use_request_id = false;
- /**
- * The Packet Type
- *
- * The request ID exists in the off chance that a packet is sent out-of-order. Of course, this library doesn't support
- * concurrent actions, so it's somewhat academic, here.
- *
- * @var int
- * @see self::_get_sftp_packet()
- * @access private
- */
- private $packet_type = -1;
- /**
- * Packet Buffer
- *
- * @var string
- * @see self::_get_sftp_packet()
- * @access private
- */
- private $packet_buffer = '';
- /**
- * Extensions supported by the server
- *
- * @var array
- * @see self::_initChannel()
- * @access private
- */
- private $extensions = [];
- /**
- * Server SFTP version
- *
- * @var int
- * @see self::_initChannel()
- * @access private
- */
- private $version;
- /**
- * Default Server SFTP version
- *
- * @var int
- * @see self::_initChannel()
- * @access private
- */
- private $defaultVersion;
- /**
- * Preferred SFTP version
- *
- * @var int
- * @see self::_initChannel()
- * @access private
- */
- private $preferredVersion = 3;
- /**
- * Current working directory
- *
- * @var string
- * @see self::realpath()
- * @see self::chdir()
- * @access private
- */
- private $pwd = false;
- /**
- * Packet Type Log
- *
- * @see self::getLog()
- * @var array
- * @access private
- */
- private $packet_type_log = [];
- /**
- * Packet Log
- *
- * @see self::getLog()
- * @var array
- * @access private
- */
- private $packet_log = [];
- /**
- * Error information
- *
- * @see self::getSFTPErrors()
- * @see self::getLastSFTPError()
- * @var array
- * @access private
- */
- private $sftp_errors = [];
- /**
- * Stat Cache
- *
- * Rather than always having to open a directory and close it immediately there after to see if a file is a directory
- * we'll cache the results.
- *
- * @see self::_update_stat_cache()
- * @see self::_remove_from_stat_cache()
- * @see self::_query_stat_cache()
- * @var array
- * @access private
- */
- private $stat_cache = [];
- /**
- * Max SFTP Packet Size
- *
- * @see self::__construct()
- * @see self::get()
- * @var array
- * @access private
- */
- private $max_sftp_packet;
- /**
- * Stat Cache Flag
- *
- * @see self::disableStatCache()
- * @see self::enableStatCache()
- * @var bool
- * @access private
- */
- private $use_stat_cache = true;
- /**
- * Sort Options
- *
- * @see self::_comparator()
- * @see self::setListOrder()
- * @var array
- * @access private
- */
- protected $sortOptions = [];
- /**
- * Canonicalization Flag
- *
- * Determines whether or not paths should be canonicalized before being
- * passed on to the remote server.
- *
- * @see self::enablePathCanonicalization()
- * @see self::disablePathCanonicalization()
- * @see self::realpath()
- * @var bool
- * @access private
- */
- private $canonicalize_paths = true;
- /**
- * Request Buffers
- *
- * @see self::_get_sftp_packet()
- * @var array
- * @access private
- */
- private $requestBuffer = [];
- /**
- * Preserve timestamps on file downloads / uploads
- *
- * @see self::get()
- * @see self::put()
- * @var bool
- * @access private
- */
- private $preserveTime = false;
- /**
- * Arbitrary Length Packets Flag
- *
- * Determines whether or not packets of any length should be allowed,
- * in cases where the server chooses the packet length (such as
- * directory listings). By default, packets are only allowed to be
- * 256 * 1024 bytes (SFTP_MAX_MSG_LENGTH from OpenSSH's sftp-common.h)
- *
- * @see self::enableArbitraryLengthPackets()
- * @see self::_get_sftp_packet()
- * @var bool
- * @access private
- */
- private $allow_arbitrary_length_packets = false;
- /**
- * Was the last packet due to the channels being closed or not?
- *
- * @see self::get()
- * @see self::get_sftp_packet()
- * @var bool
- * @access private
- */
- private $channel_close = false;
- /**
- * Has the SFTP channel been partially negotiated?
- *
- * @var bool
- * @access private
- */
- private $partial_init = false;
- /**
- * Default Constructor.
- *
- * Connects to an SFTP server
- *
- * @param string $host
- * @param int $port
- * @param int $timeout
- * @return \phpseclib3\Net\SFTP
- * @access public
- */
- public function __construct($host, $port = 22, $timeout = 10)
- {
- parent::__construct($host, $port, $timeout);
- $this->max_sftp_packet = 1 << 15;
- $this->packet_types = [
- 1 => 'NET_SFTP_INIT',
- 2 => 'NET_SFTP_VERSION',
- 3 => 'NET_SFTP_OPEN',
- 4 => 'NET_SFTP_CLOSE',
- 5 => 'NET_SFTP_READ',
- 6 => 'NET_SFTP_WRITE',
- 7 => 'NET_SFTP_LSTAT',
- 9 => 'NET_SFTP_SETSTAT',
- 10 => 'NET_SFTP_FSETSTAT',
- 11 => 'NET_SFTP_OPENDIR',
- 12 => 'NET_SFTP_READDIR',
- 13 => 'NET_SFTP_REMOVE',
- 14 => 'NET_SFTP_MKDIR',
- 15 => 'NET_SFTP_RMDIR',
- 16 => 'NET_SFTP_REALPATH',
- 17 => 'NET_SFTP_STAT',
- 18 => 'NET_SFTP_RENAME',
- 19 => 'NET_SFTP_READLINK',
- 20 => 'NET_SFTP_SYMLINK',
- 21 => 'NET_SFTP_LINK',
- 101=> 'NET_SFTP_STATUS',
- 102=> 'NET_SFTP_HANDLE',
- 103=> 'NET_SFTP_DATA',
- 104=> 'NET_SFTP_NAME',
- 105=> 'NET_SFTP_ATTRS',
- 200=> 'NET_SFTP_EXTENDED'
- ];
- $this->status_codes = [
- 0 => 'NET_SFTP_STATUS_OK',
- 1 => 'NET_SFTP_STATUS_EOF',
- 2 => 'NET_SFTP_STATUS_NO_SUCH_FILE',
- 3 => 'NET_SFTP_STATUS_PERMISSION_DENIED',
- 4 => 'NET_SFTP_STATUS_FAILURE',
- 5 => 'NET_SFTP_STATUS_BAD_MESSAGE',
- 6 => 'NET_SFTP_STATUS_NO_CONNECTION',
- 7 => 'NET_SFTP_STATUS_CONNECTION_LOST',
- 8 => 'NET_SFTP_STATUS_OP_UNSUPPORTED',
- 9 => 'NET_SFTP_STATUS_INVALID_HANDLE',
- 10 => 'NET_SFTP_STATUS_NO_SUCH_PATH',
- 11 => 'NET_SFTP_STATUS_FILE_ALREADY_EXISTS',
- 12 => 'NET_SFTP_STATUS_WRITE_PROTECT',
- 13 => 'NET_SFTP_STATUS_NO_MEDIA',
- 14 => 'NET_SFTP_STATUS_NO_SPACE_ON_FILESYSTEM',
- 15 => 'NET_SFTP_STATUS_QUOTA_EXCEEDED',
- 16 => 'NET_SFTP_STATUS_UNKNOWN_PRINCIPAL',
- 17 => 'NET_SFTP_STATUS_LOCK_CONFLICT',
- 18 => 'NET_SFTP_STATUS_DIR_NOT_EMPTY',
- 19 => 'NET_SFTP_STATUS_NOT_A_DIRECTORY',
- 20 => 'NET_SFTP_STATUS_INVALID_FILENAME',
- 21 => 'NET_SFTP_STATUS_LINK_LOOP',
- 22 => 'NET_SFTP_STATUS_CANNOT_DELETE',
- 23 => 'NET_SFTP_STATUS_INVALID_PARAMETER',
- 24 => 'NET_SFTP_STATUS_FILE_IS_A_DIRECTORY',
- 25 => 'NET_SFTP_STATUS_BYTE_RANGE_LOCK_CONFLICT',
- 26 => 'NET_SFTP_STATUS_BYTE_RANGE_LOCK_REFUSED',
- 27 => 'NET_SFTP_STATUS_DELETE_PENDING',
- 28 => 'NET_SFTP_STATUS_FILE_CORRUPT',
- 29 => 'NET_SFTP_STATUS_OWNER_INVALID',
- 30 => 'NET_SFTP_STATUS_GROUP_INVALID',
- 31 => 'NET_SFTP_STATUS_NO_MATCHING_BYTE_RANGE_LOCK'
- ];
- // http://tools.ietf.org/html/draft-ietf-secsh-filexfer-13#section-7.1
- // the order, in this case, matters quite a lot - see \phpseclib3\Net\SFTP::_parseAttributes() to understand why
- $this->attributes = [
- 0x00000001 => 'NET_SFTP_ATTR_SIZE',
- 0x00000002 => 'NET_SFTP_ATTR_UIDGID', // defined in SFTPv3, removed in SFTPv4+
- 0x00000080 => 'NET_SFTP_ATTR_OWNERGROUP', // defined in SFTPv4+
- 0x00000004 => 'NET_SFTP_ATTR_PERMISSIONS',
- 0x00000008 => 'NET_SFTP_ATTR_ACCESSTIME',
- 0x00000010 => 'NET_SFTP_ATTR_CREATETIME', // SFTPv4+
- 0x00000020 => 'NET_SFTP_ATTR_MODIFYTIME',
- 0x00000040 => 'NET_SFTP_ATTR_ACL',
- 0x00000100 => 'NET_SFTP_ATTR_SUBSECOND_TIMES',
- 0x00000200 => 'NET_SFTP_ATTR_BITS', // SFTPv5+
- 0x00000400 => 'NET_SFTP_ATTR_ALLOCATION_SIZE', // SFTPv6+
- 0x00000800 => 'NET_SFTP_ATTR_TEXT_HINT',
- 0x00001000 => 'NET_SFTP_ATTR_MIME_TYPE',
- 0x00002000 => 'NET_SFTP_ATTR_LINK_COUNT',
- 0x00004000 => 'NET_SFTP_ATTR_UNTRANSLATED_NAME',
- 0x00008000 => 'NET_SFTP_ATTR_CTIME',
- // 0x80000000 will yield a floating point on 32-bit systems and converting floating points to integers
- // yields inconsistent behavior depending on how php is compiled. so we left shift -1 (which, in
- // two's compliment, consists of all 1 bits) by 31. on 64-bit systems this'll yield 0xFFFFFFFF80000000.
- // that's not a problem, however, and 'anded' and a 32-bit number, as all the leading 1 bits are ignored.
- (-1 << 31) & 0xFFFFFFFF => 'NET_SFTP_ATTR_EXTENDED'
- ];
- // http://tools.ietf.org/html/draft-ietf-secsh-filexfer-04#section-6.3
- // the flag definitions change somewhat in SFTPv5+. if SFTPv5+ support is added to this library, maybe name
- // the array for that $this->open5_flags and similarly alter the constant names.
- $this->open_flags = [
- 0x00000001 => 'NET_SFTP_OPEN_READ',
- 0x00000002 => 'NET_SFTP_OPEN_WRITE',
- 0x00000004 => 'NET_SFTP_OPEN_APPEND',
- 0x00000008 => 'NET_SFTP_OPEN_CREATE',
- 0x00000010 => 'NET_SFTP_OPEN_TRUNCATE',
- 0x00000020 => 'NET_SFTP_OPEN_EXCL',
- 0x00000040 => 'NET_SFTP_OPEN_TEXT' // defined in SFTPv4
- ];
- // SFTPv5+ changed the flags up:
- // https://datatracker.ietf.org/doc/html/draft-ietf-secsh-filexfer-13#section-8.1.1.3
- $this->open_flags5 = [
- // when SSH_FXF_ACCESS_DISPOSITION is a 3 bit field that controls how the file is opened
- 0x00000000 => 'NET_SFTP_OPEN_CREATE_NEW',
- 0x00000001 => 'NET_SFTP_OPEN_CREATE_TRUNCATE',
- 0x00000002 => 'NET_SFTP_OPEN_OPEN_EXISTING',
- 0x00000003 => 'NET_SFTP_OPEN_OPEN_OR_CREATE',
- 0x00000004 => 'NET_SFTP_OPEN_TRUNCATE_EXISTING',
- // the rest of the flags are not supported
- 0x00000008 => 'NET_SFTP_OPEN_APPEND_DATA', // "the offset field of SS_FXP_WRITE requests is ignored"
- 0x00000010 => 'NET_SFTP_OPEN_APPEND_DATA_ATOMIC',
- 0x00000020 => 'NET_SFTP_OPEN_TEXT_MODE',
- 0x00000040 => 'NET_SFTP_OPEN_BLOCK_READ',
- 0x00000080 => 'NET_SFTP_OPEN_BLOCK_WRITE',
- 0x00000100 => 'NET_SFTP_OPEN_BLOCK_DELETE',
- 0x00000200 => 'NET_SFTP_OPEN_BLOCK_ADVISORY',
- 0x00000400 => 'NET_SFTP_OPEN_NOFOLLOW',
- 0x00000800 => 'NET_SFTP_OPEN_DELETE_ON_CLOSE',
- 0x00001000 => 'NET_SFTP_OPEN_ACCESS_AUDIT_ALARM_INFO',
- 0x00002000 => 'NET_SFTP_OPEN_ACCESS_BACKUP',
- 0x00004000 => 'NET_SFTP_OPEN_BACKUP_STREAM',
- 0x00008000 => 'NET_SFTP_OPEN_OVERRIDE_OWNER',
- ];
- // http://tools.ietf.org/html/draft-ietf-secsh-filexfer-04#section-5.2
- // see \phpseclib3\Net\SFTP::_parseLongname() for an explanation
- $this->file_types = [
- 1 => 'NET_SFTP_TYPE_REGULAR',
- 2 => 'NET_SFTP_TYPE_DIRECTORY',
- 3 => 'NET_SFTP_TYPE_SYMLINK',
- 4 => 'NET_SFTP_TYPE_SPECIAL',
- 5 => 'NET_SFTP_TYPE_UNKNOWN',
- // the following types were first defined for use in SFTPv5+
- // http://tools.ietf.org/html/draft-ietf-secsh-filexfer-05#section-5.2
- 6 => 'NET_SFTP_TYPE_SOCKET',
- 7 => 'NET_SFTP_TYPE_CHAR_DEVICE',
- 8 => 'NET_SFTP_TYPE_BLOCK_DEVICE',
- 9 => 'NET_SFTP_TYPE_FIFO'
- ];
- $this->define_array(
- $this->packet_types,
- $this->status_codes,
- $this->attributes,
- $this->open_flags,
- $this->open_flags5,
- $this->file_types
- );
- if (!defined('NET_SFTP_QUEUE_SIZE')) {
- define('NET_SFTP_QUEUE_SIZE', 32);
- }
- if (!defined('NET_SFTP_UPLOAD_QUEUE_SIZE')) {
- define('NET_SFTP_UPLOAD_QUEUE_SIZE', 1024);
- }
- }
- /**
- * Check a few things before SFTP functions are called
- *
- * @return bool
- * @access public
- */
- private function precheck()
- {
- if (!($this->bitmap & SSH2::MASK_LOGIN)) {
- return false;
- }
- if ($this->pwd === false) {
- return $this->init_sftp_connection();
- }
- return true;
- }
- /**
- * Partially initialize an SFTP connection
- *
- * @throws \UnexpectedValueException on receipt of unexpected packets
- * @return bool
- * @access public
- */
- private function partial_init_sftp_connection()
- {
- $this->window_size_server_to_client[self::CHANNEL] = $this->window_size;
- $packet = Strings::packSSH2(
- 'CsN3',
- NET_SSH2_MSG_CHANNEL_OPEN,
- 'session',
- self::CHANNEL,
- $this->window_size,
- 0x4000
- );
- $this->send_binary_packet($packet);
- $this->channel_status[self::CHANNEL] = NET_SSH2_MSG_CHANNEL_OPEN;
- $response = $this->get_channel_packet(self::CHANNEL, true);
- if ($response === true && $this->isTimeout()) {
- return false;
- }
- $packet = Strings::packSSH2(
- 'CNsbs',
- NET_SSH2_MSG_CHANNEL_REQUEST,
- $this->server_channels[self::CHANNEL],
- 'subsystem',
- true,
- 'sftp'
- );
- $this->send_binary_packet($packet);
- $this->channel_status[self::CHANNEL] = NET_SSH2_MSG_CHANNEL_REQUEST;
- $response = $this->get_channel_packet(self::CHANNEL, true);
- if ($response === false) {
- // from PuTTY's psftp.exe
- $command = "test -x /usr/lib/sftp-server && exec /usr/lib/sftp-server\n" .
- "test -x /usr/local/lib/sftp-server && exec /usr/local/lib/sftp-server\n" .
- "exec sftp-server";
- // we don't do $this->exec($command, false) because exec() operates on a different channel and plus the SSH_MSG_CHANNEL_OPEN that exec() does
- // is redundant
- $packet = Strings::packSSH2(
- 'CNsCs',
- NET_SSH2_MSG_CHANNEL_REQUEST,
- $this->server_channels[self::CHANNEL],
- 'exec',
- 1,
- $command
- );
- $this->send_binary_packet($packet);
- $this->channel_status[self::CHANNEL] = NET_SSH2_MSG_CHANNEL_REQUEST;
- $response = $this->get_channel_packet(self::CHANNEL, true);
- if ($response === false) {
- return false;
- }
- } else if ($response === true && $this->isTimeout()) {
- return false;
- }
- $this->channel_status[self::CHANNEL] = NET_SSH2_MSG_CHANNEL_DATA;
- $this->send_sftp_packet(NET_SFTP_INIT, "\0\0\0\3");
- $response = $this->get_sftp_packet();
- if ($this->packet_type != NET_SFTP_VERSION) {
- throw new \UnexpectedValueException('Expected NET_SFTP_VERSION. '
- . 'Got packet type: ' . $this->packet_type);
- }
- $this->use_request_id = true;
- list($this->defaultVersion) = Strings::unpackSSH2('N', $response);
- while (!empty($response)) {
- list($key, $value) = Strings::unpackSSH2('ss', $response);
- $this->extensions[$key] = $value;
- }
- $this->partial_init = true;
- return true;
- }
- /**
- * (Re)initializes the SFTP channel
- *
- * @return bool
- * @access private
- */
- private function init_sftp_connection()
- {
- if (!$this->partial_init && !$this->partial_init_sftp_connection()) {
- return false;
- }
- /*
- A Note on SFTPv4/5/6 support:
- <http://tools.ietf.org/html/draft-ietf-secsh-filexfer-13#section-5.1> states the following:
- "If the client wishes to interoperate with servers that support noncontiguous version
- numbers it SHOULD send '3'"
- Given that the server only sends its version number after the client has already done so, the above
- seems to be suggesting that v3 should be the default version. This makes sense given that v3 is the
- most popular.
- <http://tools.ietf.org/html/draft-ietf-secsh-filexfer-13#section-5.5> states the following;
- "If the server did not send the "versions" extension, or the version-from-list was not included, the
- server MAY send a status response describing the failure, but MUST then close the channel without
- processing any further requests."
- So what do you do if you have a client whose initial SSH_FXP_INIT packet says it implements v3 and
- a server whose initial SSH_FXP_VERSION reply says it implements v4 and only v4? If it only implements
- v4, the "versions" extension is likely not going to have been sent so version re-negotiation as discussed
- in draft-ietf-secsh-filexfer-13 would be quite impossible. As such, what \phpseclib3\Net\SFTP would do is close the
- channel and reopen it with a new and updated SSH_FXP_INIT packet.
- */
- $this->version = $this->defaultVersion;
- if (isset($this->extensions['versions']) && (!$this->preferredVersion || $this->preferredVersion != $this->version)) {
- $versions = explode(',', $this->extensions['versions']);
- $supported = [6, 5, 4];
- if ($this->preferredVersion) {
- $supported = array_diff($supported, [$this->preferredVersion]);
- array_unshift($supported, $this->preferredVersion);
- }
- foreach ($supported as $ver) {
- if (in_array($ver, $versions)) {
- if ($ver === $this->version) {
- break;
- }
- $this->version = (int) $ver;
- $packet = Strings::packSSH2('ss', 'version-select', "$ver");
- $this->send_sftp_packet(NET_SFTP_EXTENDED, $packet);
- $response = $this->get_sftp_packet();
- if ($this->packet_type != NET_SFTP_STATUS) {
- throw new \UnexpectedValueException('Expected NET_SFTP_STATUS. '
- . 'Got packet type: ' . $this->packet_type);
- }
- list($status) = Strings::unpackSSH2('N', $response);
- if ($status != NET_SFTP_STATUS_OK) {
- $this->logError($response, $status);
- throw new \UnexpectedValueException('Expected NET_SFTP_STATUS_OK. '
- . ' Got ' . $status);
- }
- break;
- }
- }
- }
- /*
- SFTPv4+ defines a 'newline' extension. SFTPv3 seems to have unofficial support for it via 'newline@vandyke.com',
- however, I'm not sure what 'newline@vandyke.com' is supposed to do (the fact that it's unofficial means that it's
- not in the official SFTPv3 specs) and 'newline@vandyke.com' / 'newline' are likely not drop-in substitutes for
- one another due to the fact that 'newline' comes with a SSH_FXF_TEXT bitmask whereas it seems unlikely that
- 'newline@vandyke.com' would.
- */
- /*
- if (isset($this->extensions['newline@vandyke.com'])) {
- $this->extensions['newline'] = $this->extensions['newline@vandyke.com'];
- unset($this->extensions['newline@vandyke.com']);
- }
- */
- if ($this->version < 2 || $this->version > 6) {
- return false;
- }
- $this->pwd = true;
- $this->pwd = $this->realpath('.');
- $this->update_stat_cache($this->pwd, []);
- return true;
- }
- /**
- * Disable the stat cache
- *
- * @access public
- */
- public function disableStatCache()
- {
- $this->use_stat_cache = false;
- }
- /**
- * Enable the stat cache
- *
- * @access public
- */
- public function enableStatCache()
- {
- $this->use_stat_cache = true;
- }
- /**
- * Clear the stat cache
- *
- * @access public
- */
- public function clearStatCache()
- {
- $this->stat_cache = [];
- }
- /**
- * Enable path canonicalization
- *
- * @access public
- */
- public function enablePathCanonicalization()
- {
- $this->canonicalize_paths = true;
- }
- /**
- * Enable path canonicalization
- *
- * @access public
- */
- public function disablePathCanonicalization()
- {
- $this->canonicalize_paths = false;
- }
- /**
- * Enable arbitrary length packets
- *
- * @access public
- */
- public function enableArbitraryLengthPackets()
- {
- $this->allow_arbitrary_length_packets = true;
- }
- /**
- * Disable arbitrary length packets
- *
- * @access public
- */
- public function disableArbitraryLengthPackets()
- {
- $this->allow_arbitrary_length_packets = false;
- }
- /**
- * Returns the current directory name
- *
- * @return mixed
- * @access public
- */
- public function pwd()
- {
- if (!$this->precheck()) {
- return false;
- }
- return $this->pwd;
- }
- /**
- * Logs errors
- *
- * @param string $response
- * @param int $status
- * @access private
- */
- private function logError($response, $status = -1)
- {
- if ($status == -1) {
- list($status) = Strings::unpackSSH2('N', $response);
- }
- $error = $this->status_codes[$status];
- if ($this->version > 2) {
- list($message) = Strings::unpackSSH2('s', $response);
- $this->sftp_errors[] = "$error: $message";
- } else {
- $this->sftp_errors[] = $error;
- }
- }
- /**
- * Canonicalize the Server-Side Path Name
- *
- * SFTP doesn't provide a mechanism by which the current working directory can be changed, so we'll emulate it. Returns
- * the absolute (canonicalized) path.
- *
- * If canonicalize_paths has been disabled using disablePathCanonicalization(), $path is returned as-is.
- *
- * @see self::chdir()
- * @see self::disablePathCanonicalization()
- * @param string $path
- * @throws \UnexpectedValueException on receipt of unexpected packets
- * @return mixed
- * @access public
- */
- public function realpath($path)
- {
- if ($this->precheck() === false) {
- return false;
- }
- if (!$this->canonicalize_paths) {
- return $path;
- }
- if ($this->pwd === true) {
- // http://tools.ietf.org/html/draft-ietf-secsh-filexfer-13#section-8.9
- $this->send_sftp_packet(NET_SFTP_REALPATH, Strings::packSSH2('s', $path));
- $response = $this->get_sftp_packet();
- switch ($this->packet_type) {
- case NET_SFTP_NAME:
- // although SSH_FXP_NAME is implemented differently in SFTPv3 than it is in SFTPv4+, the following
- // should work on all SFTP versions since the only part of the SSH_FXP_NAME packet the following looks
- // at is the first part and that part is defined the same in SFTP versions 3 through 6.
- list(, $filename) = Strings::unpackSSH2('Ns', $response);
- return $filename;
- case NET_SFTP_STATUS:
- $this->logError($response);
- return false;
- default:
- throw new \UnexpectedValueException('Expected NET_SFTP_NAME or NET_SFTP_STATUS. '
- . 'Got packet type: ' . $this->packet_type);
- }
- }
- if (!strlen($path) || $path[0] != '/') {
- $path = $this->pwd . '/' . $path;
- }
- $path = explode('/', $path);
- $new = [];
- foreach ($path as $dir) {
- if (!strlen($dir)) {
- continue;
- }
- switch ($dir) {
- case '..':
- array_pop($new);
- case '.':
- break;
- default:
- $new[] = $dir;
- }
- }
- return '/' . implode('/', $new);
- }
- /**
- * Changes the current directory
- *
- * @param string $dir
- * @throws \UnexpectedValueException on receipt of unexpected packets
- * @return bool
- * @access public
- */
- public function chdir($dir)
- {
- if (!$this->precheck()) {
- return false;
- }
- // assume current dir if $dir is empty
- if ($dir === '') {
- $dir = './';
- // suffix a slash if needed
- } elseif ($dir[strlen($dir) - 1] != '/') {
- $dir.= '/';
- }
- $dir = $this->realpath($dir);
- // confirm that $dir is, in fact, a valid directory
- if ($this->use_stat_cache && is_array($this->query_stat_cache($dir))) {
- $this->pwd = $dir;
- return true;
- }
- // we could do a stat on the alleged $dir to see if it's a directory but that doesn't tell us
- // the currently logged in user has the appropriate permissions or not. maybe you could see if
- // the file's uid / gid match the currently logged in user's uid / gid but how there's no easy
- // way to get those with SFTP
- $this->send_sftp_packet(NET_SFTP_OPENDIR, Strings::packSSH2('s', $dir));
- // see \phpseclib3\Net\SFTP::nlist() for a more thorough explanation of the following
- $response = $this->get_sftp_packet();
- switch ($this->packet_type) {
- case NET_SFTP_HANDLE:
- $handle = substr($response, 4);
- break;
- case NET_SFTP_STATUS:
- $this->logError($response);
- return false;
- default:
- throw new \UnexpectedValueException('Expected NET_SFTP_HANDLE or NET_SFTP_STATUS' .
- 'Got packet type: ' . $this->packet_type);
- }
- if (!$this->close_handle($handle)) {
- return false;
- }
- $this->update_stat_cache($dir, []);
- $this->pwd = $dir;
- return true;
- }
- /**
- * Returns a list of files in the given directory
- *
- * @param string $dir
- * @param bool $recursive
- * @return mixed
- * @access public
- */
- public function nlist($dir = '.', $recursive = false)
- {
- return $this->nlist_helper($dir, $recursive, '');
- }
- /**
- * Helper method for nlist
- *
- * @param string $dir
- * @param bool $recursive
- * @param string $relativeDir
- * @return mixed
- * @access private
- */
- private function nlist_helper($dir, $recursive, $relativeDir)
- {
- $files = $this->readlist($dir, false);
- if (!$recursive || $files === false) {
- return $files;
- }
- $result = [];
- foreach ($files as $value) {
- if ($value == '.' || $value == '..') {
- $result[] = $relativeDir . $value;
- continue;
- }
- if (is_array($this->query_stat_cache($this->realpath($dir . '/' . $value)))) {
- $temp = $this->nlist_helper($dir . '/' . $value, true, $relativeDir . $value . '/');
- $temp = is_array($temp) ? $temp : [];
- $result = array_merge($result, $temp);
- } else {
- $result[] = $relativeDir . $value;
- }
- }
- return $result;
- }
- /**
- * Returns a detailed list of files in the given directory
- *
- * @param string $dir
- * @param bool $recursive
- * @return mixed
- * @access public
- */
- public function rawlist($dir = '.', $recursive = false)
- {
- $files = $this->readlist($dir, true);
- if (!$recursive || $files === false) {
- return $files;
- }
- static $depth = 0;
- foreach ($files as $key => $value) {
- if ($depth != 0 && $key == '..') {
- unset($files[$key]);
- continue;
- }
- $is_directory = false;
- if ($key != '.' && $key != '..') {
- if ($this->use_stat_cache) {
- $is_directory = is_array($this->query_stat_cache($this->realpath($dir . '/' . $key)));
- } else {
- $stat = $this->lstat($dir . '/' . $key);
- $is_directory = $stat && $stat['type'] === NET_SFTP_TYPE_DIRECTORY;
- }
- }
- if ($is_directory) {
- $depth++;
- $files[$key] = $this->rawlist($dir . '/' . $key, true);
- $depth--;
- } else {
- $files[$key] = (object) $value;
- }
- }
- return $files;
- }
- /**
- * Reads a list, be it detailed or not, of files in the given directory
- *
- * @param string $dir
- * @param bool $raw
- * @return mixed
- * @throws \UnexpectedValueException on receipt of unexpected packets
- * @access private
- */
- private function readlist($dir, $raw = true)
- {
- if (!$this->precheck()) {
- return false;
- }
- $dir = $this->realpath($dir . '/');
- if ($dir === false) {
- return false;
- }
- // http://tools.ietf.org/html/draft-ietf-secsh-filexfer-13#section-8.1.2
- $this->send_sftp_packet(NET_SFTP_OPENDIR, Strings::packSSH2('s', $dir));
- $response = $this->get_sftp_packet();
- switch ($this->packet_type) {
- case NET_SFTP_HANDLE:
- // http://tools.ietf.org/html/draft-ietf-secsh-filexfer-13#section-9.2
- // since 'handle' is the last field in the SSH_FXP_HANDLE packet, we'll just remove the first four bytes that
- // represent the length of the string and leave it at that
- $handle = substr($response, 4);
- break;
- case NET_SFTP_STATUS:
- // presumably SSH_FX_NO_SUCH_FILE or SSH_FX_PERMISSION_DENIED
- $this->logError($response);
- return false;
- default:
- throw new \UnexpectedValueException('Expected NET_SFTP_HANDLE or NET_SFTP_STATUS. '
- . 'Got packet type: ' . $this->packet_type);
- }
- $this->update_stat_cache($dir, []);
- $contents = [];
- while (true) {
- // http://tools.ietf.org/html/draft-ietf-secsh-filexfer-13#section-8.2.2
- // why multiple SSH_FXP_READDIR packets would be sent when the response to a single one can span arbitrarily many
- // SSH_MSG_CHANNEL_DATA messages is not known to me.
- $this->send_sftp_packet(NET_SFTP_READDIR, Strings::packSSH2('s', $handle));
- $response = $this->get_sftp_packet();
- switch ($this->packet_type) {
- case NET_SFTP_NAME:
- list($count) = Strings::unpackSSH2('N', $response);
- for ($i = 0; $i < $count; $i++) {
- list($shortname) = Strings::unpackSSH2('s', $response);
- // SFTPv4 "removed the long filename from the names structure-- it can now be
- // built from information available in the attrs structure."
- if ($this->version < 4) {
- list($longname) = Strings::unpackSSH2('s', $response);
- }
- $attributes = $this->parseAttributes($response);
- if (!isset($attributes['type']) && $this->version < 4) {
- $fileType = $this->parseLongname($longname);
- if ($fileType) {
- $attributes['type'] = $fileType;
- }
- }
- $contents[$shortname] = $attributes + ['filename' => $shortname];
- if (isset($attributes['type']) && $attributes['type'] == NET_SFTP_TYPE_DIRECTORY && ($shortname != '.' && $shortname != '..')) {
- $this->update_stat_cache($dir . '/' . $shortname, []);
- } else {
- if ($shortname == '..') {
- $temp = $this->realpath($dir . '/..') . '/.';
- } else {
- $temp = $dir . '/' . $shortname;
- }
- $this->update_stat_cache($temp, (object) ['lstat' => $attributes]);
- }
- // SFTPv6 has an optional boolean end-of-list field, but we'll ignore that, since the
- // final SSH_FXP_STATUS packet should tell us that, already.
- }
- break;
- case NET_SFTP_STATUS:
- list($status) = Strings::unpackSSH2('N', $response);
- if ($status != NET_SFTP_STATUS_EOF) {
- $this->logError($response, $status);
- return false;
- }
- break 2;
- default:
- throw new \UnexpectedValueException('Expected NET_SFTP_NAME or NET_SFTP_STATUS. '
- . 'Got packet type: ' . $this->packet_type);
- }
- }
- if (!$this->close_handle($handle)) {
- return false;
- }
- if (count($this->sortOptions)) {
- uasort($contents, [&$this, 'comparator']);
- }
- return $raw ? $contents : array_map('strval', array_keys($contents));
- }
- /**
- * Compares two rawlist entries using parameters set by setListOrder()
- *
- * Intended for use with uasort()
- *
- * @param array $a
- * @param array $b
- * @return int
- * @access private
- */
- private function comparator($a, $b)
- {
- switch (true) {
- case $a['filename'] === '.' || $b['filename'] === '.':
- if ($a['filename'] === $b['filename']) {
- return 0;
- }
- return $a['filename'] === '.' ? -1 : 1;
- case $a['filename'] === '..' || $b['filename'] === '..':
- if ($a['filename'] === $b['filename']) {
- return 0;
- }
- return $a['filename'] === '..' ? -1 : 1;
- case isset($a['type']) && $a['type'] === NET_SFTP_TYPE_DIRECTORY:
- if (!isset($b['type'])) {
- return 1;
- }
- if ($b['type'] !== $a['type']) {
- return -1;
- }
- break;
- case isset($b['type']) && $b['type'] === NET_SFTP_TYPE_DIRECTORY:
- return 1;
- }
- foreach ($this->sortOptions as $sort => $order) {
- if (!isset($a[$sort]) || !isset($b[$sort])) {
- if (isset($a[$sort])) {
- return -1;
- }
- if (isset($b[$sort])) {
- return 1;
- }
- return 0;
- }
- switch ($sort) {
- case 'filename':
- $result = strcasecmp($a['filename'], $b['filename']);
- if ($result) {
- return $order === SORT_DESC ? -$result : $result;
- }
- break;
- case 'mode':
- $a[$sort]&= 07777;
- $b[$sort]&= 07777;
- default:
- if ($a[$sort] === $b[$sort]) {
- break;
- }
- return $order === SORT_ASC ? $a[$sort] - $b[$sort] : $b[$sort] - $a[$sort];
- }
- }
- }
- /**
- * Defines how nlist() and rawlist() will be sorted - if at all.
- *
- * If sorting is enabled directories and files will be sorted independently with
- * directories appearing before files in the resultant array that is returned.
- *
- * Any parameter returned by stat is a valid sort parameter for this function.
- * Filename comparisons are case insensitive.
- *
- * Examples:
- *
- * $sftp->setListOrder('filename', SORT_ASC);
- * $sftp->setListOrder('size', SORT_DESC, 'filename', SORT_ASC);
- * $sftp->setListOrder(true);
- * Separates directories from files but doesn't do any sorting beyond that
- * $sftp->setListOrder();
- * Don't do any sort of sorting
- *
- * @param string[] ...$args
- * @access public
- */
- public function setListOrder(...$args)
- {
- $this->sortOptions = [];
- if (empty($args)) {
- return;
- }
- $len = count($args) & 0x7FFFFFFE;
- for ($i = 0; $i < $len; $i+=2) {
- $this->sortOptions[$args[$i]] = $args[$i + 1];
- }
- if (!count($this->sortOptions)) {
- $this->sortOptions = ['bogus' => true];
- }
- }
- /**
- * Save files / directories to cache
- *
- * @param string $path
- * @param mixed $value
- * @access private
- */
- private function update_stat_cache($path, $value)
- {
- if ($this->use_stat_cache === false) {
- return;
- }
- // preg_replace('#^/|/(?=/)|/$#', '', $dir) == str_replace('//', '/', trim($path, '/'))
- $dirs = explode('/', preg_replace('#^/|/(?=/)|/$#', '', $path));
- $temp = &$this->stat_cache;
- $max = count($dirs) - 1;
- foreach ($dirs as $i => $dir) {
- // if $temp is an object that means one of two things.
- // 1. a file was deleted and changed to a directory behind phpseclib's back
- // 2. it's a symlink. when lstat is done it's unclear what it's a symlink to
- if (is_object($temp)) {
- $temp = [];
- }
- if (!isset($temp[$dir])) {
- $temp[$dir] = [];
- }
- if ($i === $max) {
- if (is_object($temp[$dir]) && is_object($value)) {
- if (!isset($value->stat) && isset($temp[$dir]->stat)) {
- $value->stat = $temp[$dir]->stat;
- }
- if (!isset($value->lstat) && isset($temp[$dir]->lstat)) {
- $value->lstat = $temp[$dir]->lstat;
- }
- }
- $temp[$dir] = $value;
- break;
- }
- $temp = &$temp[$dir];
- }
- }
- /**
- * Remove files / directories from cache
- *
- * @param string $path
- * @return bool
- * @access private
- */
- private function remove_from_stat_cache($path)
- {
- $dirs = explode('/', preg_replace('#^/|/(?=/)|/$#', '', $path));
- $temp = &$this->stat_cache;
- $max = count($dirs) - 1;
- foreach ($dirs as $i => $dir) {
- if (!is_array($temp)) {
- return false;
- }
- if ($i === $max) {
- unset($temp[$dir]);
- return true;
- }
- if (!isset($temp[$dir])) {
- return false;
- }
- $temp = &$temp[$dir];
- }
- }
- /**
- * Checks cache for path
- *
- * Mainly used by file_exists
- *
- * @param string $path
- * @return mixed
- * @access private
- */
- private function query_stat_cache($path)
- {
- $dirs = explode('/', preg_replace('#^/|/(?=/)|/$#', '', $path));
- $temp = &$this->stat_cache;
- foreach ($dirs as $dir) {
- if (!is_array($temp)) {
- return null;
- }
- if (!isset($temp[$dir])) {
- return null;
- }
- $temp = &$temp[$dir];
- }
- return $temp;
- }
- /**
- * Returns general information about a file.
- *
- * Returns an array on success and false otherwise.
- *
- * @param string $filename
- * @return mixed
- * @access public
- */
- public function stat($filename)
- {
- if (!$this->precheck()) {
- return false;
- }
- $filename = $this->realpath($filename);
- if ($filename === false) {
- return false;
- }
- if ($this->use_stat_cache) {
- $result = $this->query_stat_cache($filename);
- if (is_array($result) && isset($result['.']) && isset($result['.']->stat)) {
- return $result['.']->stat;
- }
- if (is_object($result) && isset($result->stat)) {
- return $result->stat;
- }
- }
- $stat = $this->stat_helper($filename, NET_SFTP_STAT);
- if ($stat === false) {
- $this->remove_from_stat_cache($filename);
- return false;
- }
- if (isset($stat['type'])) {
- if ($stat['type'] == NET_SFTP_TYPE_DIRECTORY) {
- $filename.= '/.';
- }
- $this->update_stat_cache($filename, (object) ['stat' => $stat]);
- return $stat;
- }
- $pwd = $this->pwd;
- $stat['type'] = $this->chdir($filename) ?
- NET_SFTP_TYPE_DIRECTORY :
- NET_SFTP_TYPE_REGULAR;
- $this->pwd = $pwd;
- if ($stat['type'] == NET_SFTP_TYPE_DIRECTORY) {
- $filename.= '/.';
- }
- $this->update_stat_cache($filename, (object) ['stat' => $stat]);
- return $stat;
- }
- /**
- * Returns general information about a file or symbolic link.
- *
- * Returns an array on success and false otherwise.
- *
- * @param string $filename
- * @return mixed
- * @access public
- */
- public function lstat($filename)
- {
- if (!$this->precheck()) {
- return false;
- }
- $filename = $this->realpath($filename);
- if ($filename === false) {
- return false;
- }
- if ($this->use_stat_cache) {
- $result = $this->query_stat_cache($filename);
- if (is_array($result) && isset($result['.']) && isset($result['.']->lstat)) {
- return $result['.']->lstat;
- }
- if (is_object($result) && isset($result->lstat)) {
- return $result->lstat;
- }
- }
- $lstat = $this->stat_helper($filename, NET_SFTP_LSTAT);
- if ($lstat === false) {
- $this->remove_from_stat_cache($filename);
- return false;
- }
- if (isset($lstat['type'])) {
- if ($lstat['type'] == NET_SFTP_TYPE_DIRECTORY) {
- $filename.= '/.';
- }
- $this->update_stat_cache($filename, (object) ['lstat' => $lstat]);
- return $lstat;
- }
- $stat = $this->stat_helper($filename, NET_SFTP_STAT);
- if ($lstat != $stat) {
- $lstat = array_merge($lstat, ['type' => NET_SFTP_TYPE_SYMLINK]);
- $this->update_stat_cache($filename, (object) ['lstat' => $lstat]);
- return $stat;
- }
- $pwd = $this->pwd;
- $lstat['type'] = $this->chdir($filename) ?
- NET_SFTP_TYPE_DIRECTORY :
- NET_SFTP_TYPE_REGULAR;
- $this->pwd = $pwd;
- if ($lstat['type'] == NET_SFTP_TYPE_DIRECTORY) {
- $filename.= '/.';
- }
- $this->update_stat_cache($filename, (object) ['lstat' => $lstat]);
- return $lstat;
- }
- /**
- * Returns general information about a file or symbolic link
- *
- * Determines information without calling \phpseclib3\Net\SFTP::realpath().
- * The second parameter can be either NET_SFTP_STAT or NET_SFTP_LSTAT.
- *
- * @param string $filename
- * @param int $type
- * @throws \UnexpectedValueException on receipt of unexpected packets
- * @return mixed
- * @access private
- */
- private function stat_helper($filename, $type)
- {
- // SFTPv4+ adds an additional 32-bit integer field - flags - to the following:
- $packet = Strings::packSSH2('s', $filename);
- $this->send_sftp_packet($type, $packet);
- $response = $this->get_sftp_packet();
- switch ($this->packet_type) {
- case NET_SFTP_ATTRS:
- return $this->parseAttributes($response);
- case NET_SFTP_STATUS:
- $this->logError($response);
- return false;
- }
- throw new \UnexpectedValueException('Expected NET_SFTP_ATTRS or NET_SFTP_STATUS. '
- . 'Got packet type: ' . $this->packet_type);
- }
- /**
- * Truncates a file to a given length
- *
- * @param string $filename
- * @param int $new_size
- * @return bool
- * @access public
- */
- public function truncate($filename, $new_size)
- {
- $attr = Strings::packSSH2('NQ', NET_SFTP_ATTR_SIZE, $new_size);
- return $this->setstat($filename, $attr, false);
- }
- /**
- * Sets access and modification time of file.
- *
- * If the file does not exist, it will be created.
- *
- * @param string $filename
- * @param int $time
- * @param int $atime
- * @throws \UnexpectedValueException on receipt of unexpected packets
- * @return bool
- * @access public
- */
- public function touch($filename, $time = null, $atime = null)
- {
- if (!$this->precheck()) {
- return false;
- }
- $filename = $this->realpath($filename);
- if ($filename === false) {
- return false;
- }
- if (!isset($time)) {
- $time = time();
- }
- if (!isset($atime)) {
- $atime = $time;
- }
- $attr = $this->version < 4 ?
- pack('N3', NET_SFTP_ATTR_ACCESSTIME, $atime, $time) :
- Strings::packSSH2('NQ2', NET_SFTP_ATTR_ACCESSTIME | NET_SFTP_ATTR_MODIFYTIME, $atime, $time);
- $packet = Strings::packSSH2('s', $filename);
- $packet.= $this->version >= 5 ?
- pack('N2', 0,…