PageRenderTime 56ms CodeModel.GetById 6ms RepoModel.GetById 0ms app.codeStats 0ms

/vendor/phpseclib/phpseclib/phpseclib/Net/SFTP.php

https://bitbucket.org/davide_grobberio/laravel-angular
PHP | 2760 lines | 1523 code | 287 blank | 950 comment | 327 complexity | 343407c6fe72647b5a4f824ceb16b174 MD5 | raw file
Possible License(s): MIT, BSD-3-Clause
  1. <?php
  2. /**
  3. * Pure-PHP implementation of SFTP.
  4. *
  5. * PHP versions 4 and 5
  6. *
  7. * Currently only supports SFTPv2 and v3, which, according to wikipedia.org, "is the most widely used version,
  8. * implemented by the popular OpenSSH SFTP server". If you want SFTPv4/5/6 support, provide me with access
  9. * to an SFTPv4/5/6 server.
  10. *
  11. * The API for this library is modeled after the API from PHP's {@link http://php.net/book.ftp FTP extension}.
  12. *
  13. * Here's a short example of how to use this library:
  14. * <code>
  15. * <?php
  16. * include 'Net/SFTP.php';
  17. *
  18. * $sftp = new Net_SFTP('www.domain.tld');
  19. * if (!$sftp->login('username', 'password')) {
  20. * exit('Login Failed');
  21. * }
  22. *
  23. * echo $sftp->pwd() . "\r\n";
  24. * $sftp->put('filename.ext', 'hello, world!');
  25. * print_r($sftp->nlist());
  26. * ?>
  27. * </code>
  28. *
  29. * LICENSE: Permission is hereby granted, free of charge, to any person obtaining a copy
  30. * of this software and associated documentation files (the "Software"), to deal
  31. * in the Software without restriction, including without limitation the rights
  32. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  33. * copies of the Software, and to permit persons to whom the Software is
  34. * furnished to do so, subject to the following conditions:
  35. *
  36. * The above copyright notice and this permission notice shall be included in
  37. * all copies or substantial portions of the Software.
  38. *
  39. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  40. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  41. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  42. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  43. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  44. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  45. * THE SOFTWARE.
  46. *
  47. * @category Net
  48. * @package Net_SFTP
  49. * @author Jim Wigginton <terrafrost@php.net>
  50. * @copyright MMIX Jim Wigginton
  51. * @license http://www.opensource.org/licenses/mit-license.html MIT License
  52. * @link http://phpseclib.sourceforge.net
  53. */
  54. /**
  55. * Include Net_SSH2
  56. */
  57. if (!class_exists('Net_SSH2')) {
  58. include_once 'SSH2.php';
  59. }
  60. /**#@+
  61. * @access public
  62. * @see Net_SFTP::getLog()
  63. */
  64. /**
  65. * Returns the message numbers
  66. */
  67. define('NET_SFTP_LOG_SIMPLE', NET_SSH2_LOG_SIMPLE);
  68. /**
  69. * Returns the message content
  70. */
  71. define('NET_SFTP_LOG_COMPLEX', NET_SSH2_LOG_COMPLEX);
  72. /**
  73. * Outputs the message content in real-time.
  74. */
  75. define('NET_SFTP_LOG_REALTIME', 3);
  76. /**#@-*/
  77. /**
  78. * SFTP channel constant
  79. *
  80. * Net_SSH2::exec() uses 0 and Net_SSH2::read() / Net_SSH2::write() use 1.
  81. *
  82. * @see Net_SSH2::_send_channel_packet()
  83. * @see Net_SSH2::_get_channel_packet()
  84. * @access private
  85. */
  86. define('NET_SFTP_CHANNEL', 0x100);
  87. /**#@+
  88. * @access public
  89. * @see Net_SFTP::put()
  90. */
  91. /**
  92. * Reads data from a local file.
  93. */
  94. define('NET_SFTP_LOCAL_FILE', 1);
  95. /**
  96. * Reads data from a string.
  97. */
  98. // this value isn't really used anymore but i'm keeping it reserved for historical reasons
  99. define('NET_SFTP_STRING', 2);
  100. /**
  101. * Resumes an upload
  102. */
  103. define('NET_SFTP_RESUME', 4);
  104. /**
  105. * Append a local file to an already existing remote file
  106. */
  107. define('NET_SFTP_RESUME_START', 8);
  108. /**#@-*/
  109. /**
  110. * Pure-PHP implementations of SFTP.
  111. *
  112. * @package Net_SFTP
  113. * @author Jim Wigginton <terrafrost@php.net>
  114. * @access public
  115. */
  116. class Net_SFTP extends Net_SSH2
  117. {
  118. /**
  119. * Packet Types
  120. *
  121. * @see Net_SFTP::Net_SFTP()
  122. * @var Array
  123. * @access private
  124. */
  125. var $packet_types = array();
  126. /**
  127. * Status Codes
  128. *
  129. * @see Net_SFTP::Net_SFTP()
  130. * @var Array
  131. * @access private
  132. */
  133. var $status_codes = array();
  134. /**
  135. * The Request ID
  136. *
  137. * The request ID exists in the off chance that a packet is sent out-of-order. Of course, this library doesn't support
  138. * concurrent actions, so it's somewhat academic, here.
  139. *
  140. * @var Integer
  141. * @see Net_SFTP::_send_sftp_packet()
  142. * @access private
  143. */
  144. var $request_id = false;
  145. /**
  146. * The Packet Type
  147. *
  148. * The request ID exists in the off chance that a packet is sent out-of-order. Of course, this library doesn't support
  149. * concurrent actions, so it's somewhat academic, here.
  150. *
  151. * @var Integer
  152. * @see Net_SFTP::_get_sftp_packet()
  153. * @access private
  154. */
  155. var $packet_type = -1;
  156. /**
  157. * Packet Buffer
  158. *
  159. * @var String
  160. * @see Net_SFTP::_get_sftp_packet()
  161. * @access private
  162. */
  163. var $packet_buffer = '';
  164. /**
  165. * Extensions supported by the server
  166. *
  167. * @var Array
  168. * @see Net_SFTP::_initChannel()
  169. * @access private
  170. */
  171. var $extensions = array();
  172. /**
  173. * Server SFTP version
  174. *
  175. * @var Integer
  176. * @see Net_SFTP::_initChannel()
  177. * @access private
  178. */
  179. var $version;
  180. /**
  181. * Current working directory
  182. *
  183. * @var String
  184. * @see Net_SFTP::_realpath()
  185. * @see Net_SFTP::chdir()
  186. * @access private
  187. */
  188. var $pwd = false;
  189. /**
  190. * Packet Type Log
  191. *
  192. * @see Net_SFTP::getLog()
  193. * @var Array
  194. * @access private
  195. */
  196. var $packet_type_log = array();
  197. /**
  198. * Packet Log
  199. *
  200. * @see Net_SFTP::getLog()
  201. * @var Array
  202. * @access private
  203. */
  204. var $packet_log = array();
  205. /**
  206. * Error information
  207. *
  208. * @see Net_SFTP::getSFTPErrors()
  209. * @see Net_SFTP::getLastSFTPError()
  210. * @var String
  211. * @access private
  212. */
  213. var $sftp_errors = array();
  214. /**
  215. * Stat Cache
  216. *
  217. * Rather than always having to open a directory and close it immediately there after to see if a file is a directory
  218. * we'll cache the results.
  219. *
  220. * @see Net_SFTP::_update_stat_cache()
  221. * @see Net_SFTP::_remove_from_stat_cache()
  222. * @see Net_SFTP::_query_stat_cache()
  223. * @var Array
  224. * @access private
  225. */
  226. var $stat_cache = array();
  227. /**
  228. * Max SFTP Packet Size
  229. *
  230. * @see Net_SFTP::Net_SFTP()
  231. * @see Net_SFTP::get()
  232. * @var Array
  233. * @access private
  234. */
  235. var $max_sftp_packet;
  236. /**
  237. * Stat Cache Flag
  238. *
  239. * @see Net_SFTP::disableStatCache()
  240. * @see Net_SFTP::enableStatCache()
  241. * @var Boolean
  242. * @access private
  243. */
  244. var $use_stat_cache = true;
  245. /**
  246. * Sort Options
  247. *
  248. * @see Net_SFTP::_comparator()
  249. * @see Net_SFTP::setListOrder()
  250. * @var Array
  251. * @access private
  252. */
  253. var $sortOptions = array();
  254. /**
  255. * Default Constructor.
  256. *
  257. * Connects to an SFTP server
  258. *
  259. * @param String $host
  260. * @param optional Integer $port
  261. * @param optional Integer $timeout
  262. * @return Net_SFTP
  263. * @access public
  264. */
  265. function Net_SFTP($host, $port = 22, $timeout = 10)
  266. {
  267. parent::Net_SSH2($host, $port, $timeout);
  268. $this->max_sftp_packet = 1 << 15;
  269. $this->packet_types = array(
  270. 1 => 'NET_SFTP_INIT',
  271. 2 => 'NET_SFTP_VERSION',
  272. /* the format of SSH_FXP_OPEN changed between SFTPv4 and SFTPv5+:
  273. SFTPv5+: http://tools.ietf.org/html/draft-ietf-secsh-filexfer-13#section-8.1.1
  274. pre-SFTPv5 : http://tools.ietf.org/html/draft-ietf-secsh-filexfer-04#section-6.3 */
  275. 3 => 'NET_SFTP_OPEN',
  276. 4 => 'NET_SFTP_CLOSE',
  277. 5 => 'NET_SFTP_READ',
  278. 6 => 'NET_SFTP_WRITE',
  279. 7 => 'NET_SFTP_LSTAT',
  280. 9 => 'NET_SFTP_SETSTAT',
  281. 11 => 'NET_SFTP_OPENDIR',
  282. 12 => 'NET_SFTP_READDIR',
  283. 13 => 'NET_SFTP_REMOVE',
  284. 14 => 'NET_SFTP_MKDIR',
  285. 15 => 'NET_SFTP_RMDIR',
  286. 16 => 'NET_SFTP_REALPATH',
  287. 17 => 'NET_SFTP_STAT',
  288. /* the format of SSH_FXP_RENAME changed between SFTPv4 and SFTPv5+:
  289. SFTPv5+: http://tools.ietf.org/html/draft-ietf-secsh-filexfer-13#section-8.3
  290. pre-SFTPv5 : http://tools.ietf.org/html/draft-ietf-secsh-filexfer-04#section-6.5 */
  291. 18 => 'NET_SFTP_RENAME',
  292. 19 => 'NET_SFTP_READLINK',
  293. 20 => 'NET_SFTP_SYMLINK',
  294. 101=> 'NET_SFTP_STATUS',
  295. 102=> 'NET_SFTP_HANDLE',
  296. /* the format of SSH_FXP_NAME changed between SFTPv3 and SFTPv4+:
  297. SFTPv4+: http://tools.ietf.org/html/draft-ietf-secsh-filexfer-13#section-9.4
  298. pre-SFTPv4 : http://tools.ietf.org/html/draft-ietf-secsh-filexfer-02#section-7 */
  299. 103=> 'NET_SFTP_DATA',
  300. 104=> 'NET_SFTP_NAME',
  301. 105=> 'NET_SFTP_ATTRS',
  302. 200=> 'NET_SFTP_EXTENDED'
  303. );
  304. $this->status_codes = array(
  305. 0 => 'NET_SFTP_STATUS_OK',
  306. 1 => 'NET_SFTP_STATUS_EOF',
  307. 2 => 'NET_SFTP_STATUS_NO_SUCH_FILE',
  308. 3 => 'NET_SFTP_STATUS_PERMISSION_DENIED',
  309. 4 => 'NET_SFTP_STATUS_FAILURE',
  310. 5 => 'NET_SFTP_STATUS_BAD_MESSAGE',
  311. 6 => 'NET_SFTP_STATUS_NO_CONNECTION',
  312. 7 => 'NET_SFTP_STATUS_CONNECTION_LOST',
  313. 8 => 'NET_SFTP_STATUS_OP_UNSUPPORTED',
  314. 9 => 'NET_SFTP_STATUS_INVALID_HANDLE',
  315. 10 => 'NET_SFTP_STATUS_NO_SUCH_PATH',
  316. 11 => 'NET_SFTP_STATUS_FILE_ALREADY_EXISTS',
  317. 12 => 'NET_SFTP_STATUS_WRITE_PROTECT',
  318. 13 => 'NET_SFTP_STATUS_NO_MEDIA',
  319. 14 => 'NET_SFTP_STATUS_NO_SPACE_ON_FILESYSTEM',
  320. 15 => 'NET_SFTP_STATUS_QUOTA_EXCEEDED',
  321. 16 => 'NET_SFTP_STATUS_UNKNOWN_PRINCIPAL',
  322. 17 => 'NET_SFTP_STATUS_LOCK_CONFLICT',
  323. 18 => 'NET_SFTP_STATUS_DIR_NOT_EMPTY',
  324. 19 => 'NET_SFTP_STATUS_NOT_A_DIRECTORY',
  325. 20 => 'NET_SFTP_STATUS_INVALID_FILENAME',
  326. 21 => 'NET_SFTP_STATUS_LINK_LOOP',
  327. 22 => 'NET_SFTP_STATUS_CANNOT_DELETE',
  328. 23 => 'NET_SFTP_STATUS_INVALID_PARAMETER',
  329. 24 => 'NET_SFTP_STATUS_FILE_IS_A_DIRECTORY',
  330. 25 => 'NET_SFTP_STATUS_BYTE_RANGE_LOCK_CONFLICT',
  331. 26 => 'NET_SFTP_STATUS_BYTE_RANGE_LOCK_REFUSED',
  332. 27 => 'NET_SFTP_STATUS_DELETE_PENDING',
  333. 28 => 'NET_SFTP_STATUS_FILE_CORRUPT',
  334. 29 => 'NET_SFTP_STATUS_OWNER_INVALID',
  335. 30 => 'NET_SFTP_STATUS_GROUP_INVALID',
  336. 31 => 'NET_SFTP_STATUS_NO_MATCHING_BYTE_RANGE_LOCK'
  337. );
  338. // http://tools.ietf.org/html/draft-ietf-secsh-filexfer-13#section-7.1
  339. // the order, in this case, matters quite a lot - see Net_SFTP::_parseAttributes() to understand why
  340. $this->attributes = array(
  341. 0x00000001 => 'NET_SFTP_ATTR_SIZE',
  342. 0x00000002 => 'NET_SFTP_ATTR_UIDGID', // defined in SFTPv3, removed in SFTPv4+
  343. 0x00000004 => 'NET_SFTP_ATTR_PERMISSIONS',
  344. 0x00000008 => 'NET_SFTP_ATTR_ACCESSTIME',
  345. // 0x80000000 will yield a floating point on 32-bit systems and converting floating points to integers
  346. // yields inconsistent behavior depending on how php is compiled. so we left shift -1 (which, in
  347. // two's compliment, consists of all 1 bits) by 31. on 64-bit systems this'll yield 0xFFFFFFFF80000000.
  348. // that's not a problem, however, and 'anded' and a 32-bit number, as all the leading 1 bits are ignored.
  349. -1 << 31 => 'NET_SFTP_ATTR_EXTENDED'
  350. );
  351. // http://tools.ietf.org/html/draft-ietf-secsh-filexfer-04#section-6.3
  352. // the flag definitions change somewhat in SFTPv5+. if SFTPv5+ support is added to this library, maybe name
  353. // the array for that $this->open5_flags and similarily alter the constant names.
  354. $this->open_flags = array(
  355. 0x00000001 => 'NET_SFTP_OPEN_READ',
  356. 0x00000002 => 'NET_SFTP_OPEN_WRITE',
  357. 0x00000004 => 'NET_SFTP_OPEN_APPEND',
  358. 0x00000008 => 'NET_SFTP_OPEN_CREATE',
  359. 0x00000010 => 'NET_SFTP_OPEN_TRUNCATE',
  360. 0x00000020 => 'NET_SFTP_OPEN_EXCL'
  361. );
  362. // http://tools.ietf.org/html/draft-ietf-secsh-filexfer-04#section-5.2
  363. // see Net_SFTP::_parseLongname() for an explanation
  364. $this->file_types = array(
  365. 1 => 'NET_SFTP_TYPE_REGULAR',
  366. 2 => 'NET_SFTP_TYPE_DIRECTORY',
  367. 3 => 'NET_SFTP_TYPE_SYMLINK',
  368. 4 => 'NET_SFTP_TYPE_SPECIAL',
  369. 5 => 'NET_SFTP_TYPE_UNKNOWN',
  370. // the followin types were first defined for use in SFTPv5+
  371. // http://tools.ietf.org/html/draft-ietf-secsh-filexfer-05#section-5.2
  372. 6 => 'NET_SFTP_TYPE_SOCKET',
  373. 7 => 'NET_SFTP_TYPE_CHAR_DEVICE',
  374. 8 => 'NET_SFTP_TYPE_BLOCK_DEVICE',
  375. 9 => 'NET_SFTP_TYPE_FIFO'
  376. );
  377. $this->_define_array(
  378. $this->packet_types,
  379. $this->status_codes,
  380. $this->attributes,
  381. $this->open_flags,
  382. $this->file_types
  383. );
  384. if (!defined('NET_SFTP_QUEUE_SIZE')) {
  385. define('NET_SFTP_QUEUE_SIZE', 50);
  386. }
  387. }
  388. /**
  389. * Login
  390. *
  391. * @param String $username
  392. * @param optional String $password
  393. * @return Boolean
  394. * @access public
  395. */
  396. function login($username)
  397. {
  398. $args = func_get_args();
  399. if (!call_user_func_array(array(&$this, '_login'), $args)) {
  400. return false;
  401. }
  402. $this->window_size_server_to_client[NET_SFTP_CHANNEL] = $this->window_size;
  403. $packet = pack('CNa*N3',
  404. NET_SSH2_MSG_CHANNEL_OPEN, strlen('session'), 'session', NET_SFTP_CHANNEL, $this->window_size, 0x4000);
  405. if (!$this->_send_binary_packet($packet)) {
  406. return false;
  407. }
  408. $this->channel_status[NET_SFTP_CHANNEL] = NET_SSH2_MSG_CHANNEL_OPEN;
  409. $response = $this->_get_channel_packet(NET_SFTP_CHANNEL);
  410. if ($response === false) {
  411. return false;
  412. }
  413. $packet = pack('CNNa*CNa*',
  414. NET_SSH2_MSG_CHANNEL_REQUEST, $this->server_channels[NET_SFTP_CHANNEL], strlen('subsystem'), 'subsystem', 1, strlen('sftp'), 'sftp');
  415. if (!$this->_send_binary_packet($packet)) {
  416. return false;
  417. }
  418. $this->channel_status[NET_SFTP_CHANNEL] = NET_SSH2_MSG_CHANNEL_REQUEST;
  419. $response = $this->_get_channel_packet(NET_SFTP_CHANNEL);
  420. if ($response === false) {
  421. // from PuTTY's psftp.exe
  422. $command = "test -x /usr/lib/sftp-server && exec /usr/lib/sftp-server\n" .
  423. "test -x /usr/local/lib/sftp-server && exec /usr/local/lib/sftp-server\n" .
  424. "exec sftp-server";
  425. // 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
  426. // is redundant
  427. $packet = pack('CNNa*CNa*',
  428. NET_SSH2_MSG_CHANNEL_REQUEST, $this->server_channels[NET_SFTP_CHANNEL], strlen('exec'), 'exec', 1, strlen($command), $command);
  429. if (!$this->_send_binary_packet($packet)) {
  430. return false;
  431. }
  432. $this->channel_status[NET_SFTP_CHANNEL] = NET_SSH2_MSG_CHANNEL_REQUEST;
  433. $response = $this->_get_channel_packet(NET_SFTP_CHANNEL);
  434. if ($response === false) {
  435. return false;
  436. }
  437. }
  438. $this->channel_status[NET_SFTP_CHANNEL] = NET_SSH2_MSG_CHANNEL_DATA;
  439. if (!$this->_send_sftp_packet(NET_SFTP_INIT, "\0\0\0\3")) {
  440. return false;
  441. }
  442. $response = $this->_get_sftp_packet();
  443. if ($this->packet_type != NET_SFTP_VERSION) {
  444. user_error('Expected SSH_FXP_VERSION');
  445. return false;
  446. }
  447. extract(unpack('Nversion', $this->_string_shift($response, 4)));
  448. $this->version = $version;
  449. while (!empty($response)) {
  450. extract(unpack('Nlength', $this->_string_shift($response, 4)));
  451. $key = $this->_string_shift($response, $length);
  452. extract(unpack('Nlength', $this->_string_shift($response, 4)));
  453. $value = $this->_string_shift($response, $length);
  454. $this->extensions[$key] = $value;
  455. }
  456. /*
  457. SFTPv4+ defines a 'newline' extension. SFTPv3 seems to have unofficial support for it via 'newline@vandyke.com',
  458. however, I'm not sure what 'newline@vandyke.com' is supposed to do (the fact that it's unofficial means that it's
  459. not in the official SFTPv3 specs) and 'newline@vandyke.com' / 'newline' are likely not drop-in substitutes for
  460. one another due to the fact that 'newline' comes with a SSH_FXF_TEXT bitmask whereas it seems unlikely that
  461. 'newline@vandyke.com' would.
  462. */
  463. /*
  464. if (isset($this->extensions['newline@vandyke.com'])) {
  465. $this->extensions['newline'] = $this->extensions['newline@vandyke.com'];
  466. unset($this->extensions['newline@vandyke.com']);
  467. }
  468. */
  469. $this->request_id = 1;
  470. /*
  471. A Note on SFTPv4/5/6 support:
  472. <http://tools.ietf.org/html/draft-ietf-secsh-filexfer-13#section-5.1> states the following:
  473. "If the client wishes to interoperate with servers that support noncontiguous version
  474. numbers it SHOULD send '3'"
  475. Given that the server only sends its version number after the client has already done so, the above
  476. seems to be suggesting that v3 should be the default version. This makes sense given that v3 is the
  477. most popular.
  478. <http://tools.ietf.org/html/draft-ietf-secsh-filexfer-13#section-5.5> states the following;
  479. "If the server did not send the "versions" extension, or the version-from-list was not included, the
  480. server MAY send a status response describing the failure, but MUST then close the channel without
  481. processing any further requests."
  482. So what do you do if you have a client whose initial SSH_FXP_INIT packet says it implements v3 and
  483. a server whose initial SSH_FXP_VERSION reply says it implements v4 and only v4? If it only implements
  484. v4, the "versions" extension is likely not going to have been sent so version re-negotiation as discussed
  485. in draft-ietf-secsh-filexfer-13 would be quite impossible. As such, what Net_SFTP would do is close the
  486. channel and reopen it with a new and updated SSH_FXP_INIT packet.
  487. */
  488. switch ($this->version) {
  489. case 2:
  490. case 3:
  491. break;
  492. default:
  493. return false;
  494. }
  495. $this->pwd = $this->_realpath('.');
  496. $this->_update_stat_cache($this->pwd, array());
  497. return true;
  498. }
  499. /**
  500. * Disable the stat cache
  501. *
  502. * @access public
  503. */
  504. function disableStatCache()
  505. {
  506. $this->use_stat_cache = false;
  507. }
  508. /**
  509. * Enable the stat cache
  510. *
  511. * @access public
  512. */
  513. function enableStatCache()
  514. {
  515. $this->use_stat_cache = true;
  516. }
  517. /**
  518. * Clear the stat cache
  519. *
  520. * @access public
  521. */
  522. function clearStatCache()
  523. {
  524. $this->stat_cache = array();
  525. }
  526. /**
  527. * Returns the current directory name
  528. *
  529. * @return Mixed
  530. * @access public
  531. */
  532. function pwd()
  533. {
  534. return $this->pwd;
  535. }
  536. /**
  537. * Logs errors
  538. *
  539. * @param String $response
  540. * @param optional Integer $status
  541. * @access public
  542. */
  543. function _logError($response, $status = -1)
  544. {
  545. if ($status == -1) {
  546. extract(unpack('Nstatus', $this->_string_shift($response, 4)));
  547. }
  548. $error = $this->status_codes[$status];
  549. if ($this->version > 2) {
  550. extract(unpack('Nlength', $this->_string_shift($response, 4)));
  551. $this->sftp_errors[] = $error . ': ' . $this->_string_shift($response, $length);
  552. } else {
  553. $this->sftp_errors[] = $error;
  554. }
  555. }
  556. /**
  557. * Canonicalize the Server-Side Path Name
  558. *
  559. * SFTP doesn't provide a mechanism by which the current working directory can be changed, so we'll emulate it. Returns
  560. * the absolute (canonicalized) path.
  561. *
  562. * @see Net_SFTP::chdir()
  563. * @param String $path
  564. * @return Mixed
  565. * @access private
  566. */
  567. function _realpath($path)
  568. {
  569. if ($this->pwd === false) {
  570. // http://tools.ietf.org/html/draft-ietf-secsh-filexfer-13#section-8.9
  571. if (!$this->_send_sftp_packet(NET_SFTP_REALPATH, pack('Na*', strlen($path), $path))) {
  572. return false;
  573. }
  574. $response = $this->_get_sftp_packet();
  575. switch ($this->packet_type) {
  576. case NET_SFTP_NAME:
  577. // although SSH_FXP_NAME is implemented differently in SFTPv3 than it is in SFTPv4+, the following
  578. // should work on all SFTP versions since the only part of the SSH_FXP_NAME packet the following looks
  579. // at is the first part and that part is defined the same in SFTP versions 3 through 6.
  580. $this->_string_shift($response, 4); // skip over the count - it should be 1, anyway
  581. extract(unpack('Nlength', $this->_string_shift($response, 4)));
  582. return $this->_string_shift($response, $length);
  583. case NET_SFTP_STATUS:
  584. $this->_logError($response);
  585. return false;
  586. default:
  587. user_error('Expected SSH_FXP_NAME or SSH_FXP_STATUS');
  588. return false;
  589. }
  590. }
  591. if ($path[0] != '/') {
  592. $path = $this->pwd . '/' . $path;
  593. }
  594. $path = explode('/', $path);
  595. $new = array();
  596. foreach ($path as $dir) {
  597. if (!strlen($dir)) {
  598. continue;
  599. }
  600. switch ($dir) {
  601. case '..':
  602. array_pop($new);
  603. case '.':
  604. break;
  605. default:
  606. $new[] = $dir;
  607. }
  608. }
  609. return '/' . implode('/', $new);
  610. }
  611. /**
  612. * Changes the current directory
  613. *
  614. * @param String $dir
  615. * @return Boolean
  616. * @access public
  617. */
  618. function chdir($dir)
  619. {
  620. if (!($this->bitmap & NET_SSH2_MASK_LOGIN)) {
  621. return false;
  622. }
  623. // assume current dir if $dir is empty
  624. if ($dir === '') {
  625. $dir = './';
  626. // suffix a slash if needed
  627. } elseif ($dir[strlen($dir) - 1] != '/') {
  628. $dir.= '/';
  629. }
  630. $dir = $this->_realpath($dir);
  631. // confirm that $dir is, in fact, a valid directory
  632. if ($this->use_stat_cache && is_array($this->_query_stat_cache($dir))) {
  633. $this->pwd = $dir;
  634. return true;
  635. }
  636. // we could do a stat on the alleged $dir to see if it's a directory but that doesn't tell us
  637. // the currently logged in user has the appropriate permissions or not. maybe you could see if
  638. // the file's uid / gid match the currently logged in user's uid / gid but how there's no easy
  639. // way to get those with SFTP
  640. if (!$this->_send_sftp_packet(NET_SFTP_OPENDIR, pack('Na*', strlen($dir), $dir))) {
  641. return false;
  642. }
  643. // see Net_SFTP::nlist() for a more thorough explanation of the following
  644. $response = $this->_get_sftp_packet();
  645. switch ($this->packet_type) {
  646. case NET_SFTP_HANDLE:
  647. $handle = substr($response, 4);
  648. break;
  649. case NET_SFTP_STATUS:
  650. $this->_logError($response);
  651. return false;
  652. default:
  653. user_error('Expected SSH_FXP_HANDLE or SSH_FXP_STATUS');
  654. return false;
  655. }
  656. if (!$this->_close_handle($handle)) {
  657. return false;
  658. }
  659. $this->_update_stat_cache($dir, array());
  660. $this->pwd = $dir;
  661. return true;
  662. }
  663. /**
  664. * Returns a list of files in the given directory
  665. *
  666. * @param optional String $dir
  667. * @param optional Boolean $recursive
  668. * @return Mixed
  669. * @access public
  670. */
  671. function nlist($dir = '.', $recursive = false)
  672. {
  673. return $this->_nlist_helper($dir, $recursive, '');
  674. }
  675. /**
  676. * Helper method for nlist
  677. *
  678. * @param String $dir
  679. * @param Boolean $recursive
  680. * @param String $relativeDir
  681. * @return Mixed
  682. * @access private
  683. */
  684. function _nlist_helper($dir, $recursive, $relativeDir)
  685. {
  686. $files = $this->_list($dir, false);
  687. if (!$recursive) {
  688. return $files;
  689. }
  690. $result = array();
  691. foreach ($files as $value) {
  692. if ($value == '.' || $value == '..') {
  693. if ($relativeDir == '') {
  694. $result[] = $value;
  695. }
  696. continue;
  697. }
  698. if (is_array($this->_query_stat_cache($this->_realpath($dir . '/' . $value)))) {
  699. $temp = $this->_nlist_helper($dir . '/' . $value, true, $relativeDir . $value . '/');
  700. $result = array_merge($result, $temp);
  701. } else {
  702. $result[] = $relativeDir . $value;
  703. }
  704. }
  705. return $result;
  706. }
  707. /**
  708. * Returns a detailed list of files in the given directory
  709. *
  710. * @param optional String $dir
  711. * @param optional Boolean $recursive
  712. * @return Mixed
  713. * @access public
  714. */
  715. function rawlist($dir = '.', $recursive = false)
  716. {
  717. $files = $this->_list($dir, true);
  718. if (!$recursive || $files === false) {
  719. return $files;
  720. }
  721. static $depth = 0;
  722. foreach ($files as $key=>$value) {
  723. if ($depth != 0 && $key == '..') {
  724. unset($files[$key]);
  725. continue;
  726. }
  727. if ($key != '.' && $key != '..' && is_array($this->_query_stat_cache($this->_realpath($dir . '/' . $key)))) {
  728. $depth++;
  729. $files[$key] = $this->rawlist($dir . '/' . $key, true);
  730. $depth--;
  731. } else {
  732. $files[$key] = (object) $value;
  733. }
  734. }
  735. return $files;
  736. }
  737. /**
  738. * Reads a list, be it detailed or not, of files in the given directory
  739. *
  740. * @param String $dir
  741. * @param optional Boolean $raw
  742. * @return Mixed
  743. * @access private
  744. */
  745. function _list($dir, $raw = true)
  746. {
  747. if (!($this->bitmap & NET_SSH2_MASK_LOGIN)) {
  748. return false;
  749. }
  750. $dir = $this->_realpath($dir . '/');
  751. if ($dir === false) {
  752. return false;
  753. }
  754. // http://tools.ietf.org/html/draft-ietf-secsh-filexfer-13#section-8.1.2
  755. if (!$this->_send_sftp_packet(NET_SFTP_OPENDIR, pack('Na*', strlen($dir), $dir))) {
  756. return false;
  757. }
  758. $response = $this->_get_sftp_packet();
  759. switch ($this->packet_type) {
  760. case NET_SFTP_HANDLE:
  761. // http://tools.ietf.org/html/draft-ietf-secsh-filexfer-13#section-9.2
  762. // since 'handle' is the last field in the SSH_FXP_HANDLE packet, we'll just remove the first four bytes that
  763. // represent the length of the string and leave it at that
  764. $handle = substr($response, 4);
  765. break;
  766. case NET_SFTP_STATUS:
  767. // presumably SSH_FX_NO_SUCH_FILE or SSH_FX_PERMISSION_DENIED
  768. $this->_logError($response);
  769. return false;
  770. default:
  771. user_error('Expected SSH_FXP_HANDLE or SSH_FXP_STATUS');
  772. return false;
  773. }
  774. $this->_update_stat_cache($dir, array());
  775. $contents = array();
  776. while (true) {
  777. // http://tools.ietf.org/html/draft-ietf-secsh-filexfer-13#section-8.2.2
  778. // why multiple SSH_FXP_READDIR packets would be sent when the response to a single one can span arbitrarily many
  779. // SSH_MSG_CHANNEL_DATA messages is not known to me.
  780. if (!$this->_send_sftp_packet(NET_SFTP_READDIR, pack('Na*', strlen($handle), $handle))) {
  781. return false;
  782. }
  783. $response = $this->_get_sftp_packet();
  784. switch ($this->packet_type) {
  785. case NET_SFTP_NAME:
  786. extract(unpack('Ncount', $this->_string_shift($response, 4)));
  787. for ($i = 0; $i < $count; $i++) {
  788. extract(unpack('Nlength', $this->_string_shift($response, 4)));
  789. $shortname = $this->_string_shift($response, $length);
  790. extract(unpack('Nlength', $this->_string_shift($response, 4)));
  791. $longname = $this->_string_shift($response, $length);
  792. $attributes = $this->_parseAttributes($response);
  793. if (!isset($attributes['type'])) {
  794. $fileType = $this->_parseLongname($longname);
  795. if ($fileType) {
  796. $attributes['type'] = $fileType;
  797. }
  798. }
  799. $contents[$shortname] = $attributes + array('filename' => $shortname);
  800. if (isset($attributes['type']) && $attributes['type'] == NET_SFTP_TYPE_DIRECTORY && ($shortname != '.' && $shortname != '..')) {
  801. $this->_update_stat_cache($dir . '/' . $shortname, array());
  802. } else {
  803. if ($shortname == '..') {
  804. $temp = $this->_realpath($dir . '/..') . '/.';
  805. } else {
  806. $temp = $dir . '/' . $shortname;
  807. }
  808. $this->_update_stat_cache($temp, (object) $attributes);
  809. }
  810. // SFTPv6 has an optional boolean end-of-list field, but we'll ignore that, since the
  811. // final SSH_FXP_STATUS packet should tell us that, already.
  812. }
  813. break;
  814. case NET_SFTP_STATUS:
  815. extract(unpack('Nstatus', $this->_string_shift($response, 4)));
  816. if ($status != NET_SFTP_STATUS_EOF) {
  817. $this->_logError($response, $status);
  818. return false;
  819. }
  820. break 2;
  821. default:
  822. user_error('Expected SSH_FXP_NAME or SSH_FXP_STATUS');
  823. return false;
  824. }
  825. }
  826. if (!$this->_close_handle($handle)) {
  827. return false;
  828. }
  829. if (count($this->sortOptions)) {
  830. uasort($contents, array(&$this, '_comparator'));
  831. }
  832. return $raw ? $contents : array_keys($contents);
  833. }
  834. /**
  835. * Compares two rawlist entries using parameters set by setListOrder()
  836. *
  837. * Intended for use with uasort()
  838. *
  839. * @param Array $a
  840. * @param Array $b
  841. * @return Integer
  842. * @access private
  843. */
  844. function _comparator($a, $b)
  845. {
  846. switch (true) {
  847. case $a['filename'] === '.' || $b['filename'] === '.':
  848. if ($a['filename'] === $b['filename']) {
  849. return 0;
  850. }
  851. return $a['filename'] === '.' ? -1 : 1;
  852. case $a['filename'] === '..' || $b['filename'] === '..':
  853. if ($a['filename'] === $b['filename']) {
  854. return 0;
  855. }
  856. return $a['filename'] === '..' ? -1 : 1;
  857. case isset($a['type']) && $a['type'] === NET_SFTP_TYPE_DIRECTORY:
  858. if (!isset($b['type'])) {
  859. return 1;
  860. }
  861. if ($b['type'] !== $a['type']) {
  862. return -1;
  863. }
  864. break;
  865. case isset($b['type']) && $b['type'] === NET_SFTP_TYPE_DIRECTORY:
  866. return 1;
  867. }
  868. foreach ($this->sortOptions as $sort => $order) {
  869. if (!isset($a[$sort]) || !isset($b[$sort])) {
  870. if (isset($a[$sort])) {
  871. return -1;
  872. }
  873. if (isset($b[$sort])) {
  874. return 1;
  875. }
  876. return 0;
  877. }
  878. switch ($sort) {
  879. case 'filename':
  880. $result = strcasecmp($a['filename'], $b['filename']);
  881. if ($result) {
  882. return $order === SORT_DESC ? -$result : $result;
  883. }
  884. break;
  885. case 'permissions':
  886. case 'mode':
  887. $a[$sort]&= 07777;
  888. $b[$sort]&= 07777;
  889. default:
  890. if ($a[$sort] === $b[$sort]) {
  891. break;
  892. }
  893. return $order === SORT_ASC ? $a[$sort] - $b[$sort] : $b[$sort] - $a[$sort];
  894. }
  895. }
  896. }
  897. /**
  898. * Defines how nlist() and rawlist() will be sorted - if at all.
  899. *
  900. * If sorting is enabled directories and files will be sorted independently with
  901. * directories appearing before files in the resultant array that is returned.
  902. *
  903. * Any parameter returned by stat is a valid sort parameter for this function.
  904. * Filename comparisons are case insensitive.
  905. *
  906. * Examples:
  907. *
  908. * $sftp->setListOrder('filename', SORT_ASC);
  909. * $sftp->setListOrder('size', SORT_DESC, 'filename', SORT_ASC);
  910. * $sftp->setListOrder(true);
  911. * Separates directories from files but doesn't do any sorting beyond that
  912. * $sftp->setListOrder();
  913. * Don't do any sort of sorting
  914. *
  915. * @access public
  916. */
  917. function setListOrder()
  918. {
  919. $this->sortOptions = array();
  920. $args = func_get_args();
  921. if (empty($args)) {
  922. return;
  923. }
  924. $len = count($args) & 0x7FFFFFFE;
  925. for ($i = 0; $i < $len; $i+=2) {
  926. $this->sortOptions[$args[$i]] = $args[$i + 1];
  927. }
  928. if (!count($this->sortOptions)) {
  929. $this->sortOptions = array('bogus' => true);
  930. }
  931. }
  932. /**
  933. * Returns the file size, in bytes, or false, on failure
  934. *
  935. * Files larger than 4GB will show up as being exactly 4GB.
  936. *
  937. * @param String $filename
  938. * @return Mixed
  939. * @access public
  940. */
  941. function size($filename)
  942. {
  943. if (!($this->bitmap & NET_SSH2_MASK_LOGIN)) {
  944. return false;
  945. }
  946. $result = $this->stat($filename);
  947. if ($result === false) {
  948. return false;
  949. }
  950. return isset($result['size']) ? $result['size'] : -1;
  951. }
  952. /**
  953. * Save files / directories to cache
  954. *
  955. * @param String $path
  956. * @param Mixed $value
  957. * @access private
  958. */
  959. function _update_stat_cache($path, $value)
  960. {
  961. // preg_replace('#^/|/(?=/)|/$#', '', $dir) == str_replace('//', '/', trim($path, '/'))
  962. $dirs = explode('/', preg_replace('#^/|/(?=/)|/$#', '', $path));
  963. $temp = &$this->stat_cache;
  964. foreach ($dirs as $dir) {
  965. if (!isset($temp[$dir])) {
  966. $temp[$dir] = array();
  967. }
  968. if ($dir == end($dirs)) {
  969. $temp[$dir] = $value;
  970. }
  971. $temp = &$temp[$dir];
  972. }
  973. }
  974. /**
  975. * Remove files / directories from cache
  976. *
  977. * @param String $path
  978. * @return Boolean
  979. * @access private
  980. */
  981. function _remove_from_stat_cache($path)
  982. {
  983. $dirs = explode('/', preg_replace('#^/|/(?=/)|/$#', '', $path));
  984. $temp = &$this->stat_cache;
  985. foreach ($dirs as $dir) {
  986. if ($dir == end($dirs)) {
  987. unset($temp[$dir]);
  988. return true;
  989. }
  990. if (!isset($temp[$dir])) {
  991. return false;
  992. }
  993. $temp = &$temp[$dir];
  994. }
  995. }
  996. /**
  997. * Checks cache for path
  998. *
  999. * Mainly used by file_exists
  1000. *
  1001. * @param String $dir
  1002. * @return Mixed
  1003. * @access private
  1004. */
  1005. function _query_stat_cache($path)
  1006. {
  1007. $dirs = explode('/', preg_replace('#^/|/(?=/)|/$#', '', $path));
  1008. $temp = &$this->stat_cache;
  1009. foreach ($dirs as $dir) {
  1010. if (!isset($temp[$dir])) {
  1011. return null;
  1012. }
  1013. $temp = &$temp[$dir];
  1014. }
  1015. return $temp;
  1016. }
  1017. /**
  1018. * Returns general information about a file.
  1019. *
  1020. * Returns an array on success and false otherwise.
  1021. *
  1022. * @param String $filename
  1023. * @return Mixed
  1024. * @access public
  1025. */
  1026. function stat($filename)
  1027. {
  1028. if (!($this->bitmap & NET_SSH2_MASK_LOGIN)) {
  1029. return false;
  1030. }
  1031. $filename = $this->_realpath($filename);
  1032. if ($filename === false) {
  1033. return false;
  1034. }
  1035. if ($this->use_stat_cache) {
  1036. $result = $this->_query_stat_cache($filename);
  1037. if (is_array($result) && isset($result['.'])) {
  1038. return (array) $result['.'];
  1039. }
  1040. if (is_object($result)) {
  1041. return (array) $result;
  1042. }
  1043. }
  1044. $stat = $this->_stat($filename, NET_SFTP_STAT);
  1045. if ($stat === false) {
  1046. $this->_remove_from_stat_cache($filename);
  1047. return false;
  1048. }
  1049. if (isset($stat['type'])) {
  1050. if ($stat['type'] == NET_SFTP_TYPE_DIRECTORY) {
  1051. $filename.= '/.';
  1052. }
  1053. $this->_update_stat_cache($filename, (object) $stat);
  1054. return $stat;
  1055. }
  1056. $pwd = $this->pwd;
  1057. $stat['type'] = $this->chdir($filename) ?
  1058. NET_SFTP_TYPE_DIRECTORY :
  1059. NET_SFTP_TYPE_REGULAR;
  1060. $this->pwd = $pwd;
  1061. if ($stat['type'] == NET_SFTP_TYPE_DIRECTORY) {
  1062. $filename.= '/.';
  1063. }
  1064. $this->_update_stat_cache($filename, (object) $stat);
  1065. return $stat;
  1066. }
  1067. /**
  1068. * Returns general information about a file or symbolic link.
  1069. *
  1070. * Returns an array on success and false otherwise.
  1071. *
  1072. * @param String $filename
  1073. * @return Mixed
  1074. * @access public
  1075. */
  1076. function lstat($filename)
  1077. {
  1078. if (!($this->bitmap & NET_SSH2_MASK_LOGIN)) {
  1079. return false;
  1080. }
  1081. $filename = $this->_realpath($filename);
  1082. if ($filename === false) {
  1083. return false;
  1084. }
  1085. if ($this->use_stat_cache) {
  1086. $result = $this->_query_stat_cache($filename);
  1087. if (is_array($result) && isset($result['.'])) {
  1088. return (array) $result['.'];
  1089. }
  1090. if (is_object($result)) {
  1091. return (array) $result;
  1092. }
  1093. }
  1094. $lstat = $this->_stat($filename, NET_SFTP_LSTAT);
  1095. if ($lstat === false) {
  1096. $this->_remove_from_stat_cache($filename);
  1097. return false;
  1098. }
  1099. if (isset($lstat['type'])) {
  1100. if ($lstat['type'] == NET_SFTP_TYPE_DIRECTORY) {
  1101. $filename.= '/.';
  1102. }
  1103. $this->_update_stat_cache($filename, (object) $lstat);
  1104. return $lstat;
  1105. }
  1106. $stat = $this->_stat($filename, NET_SFTP_STAT);
  1107. if ($lstat != $stat) {
  1108. $lstat = array_merge($lstat, array('type' => NET_SFTP_TYPE_SYMLINK));
  1109. $this->_update_stat_cache($filename, (object) $lstat);
  1110. return $stat;
  1111. }
  1112. $pwd = $this->pwd;
  1113. $lstat['type'] = $this->chdir($filename) ?
  1114. NET_SFTP_TYPE_DIRECTORY :
  1115. NET_SFTP_TYPE_REGULAR;
  1116. $this->pwd = $pwd;
  1117. if ($lstat['type'] == NET_SFTP_TYPE_DIRECTORY) {
  1118. $filename.= '/.';
  1119. }
  1120. $this->_update_stat_cache($filename, (object) $lstat);
  1121. return $lstat;
  1122. }
  1123. /**
  1124. * Returns general information about a file or symbolic link
  1125. *
  1126. * Determines information without calling Net_SFTP::_realpath().
  1127. * The second parameter can be either NET_SFTP_STAT or NET_SFTP_LSTAT.
  1128. *
  1129. * @param String $filename
  1130. * @param Integer $type
  1131. * @return Mixed
  1132. * @access private
  1133. */
  1134. function _stat($filename, $type)
  1135. {
  1136. // SFTPv4+ adds an additional 32-bit integer field - flags - to the following:
  1137. $packet = pack('Na*', strlen($filename), $filename);
  1138. if (!$this->_send_sftp_packet($type, $packet)) {
  1139. return false;
  1140. }
  1141. $response = $this->_get_sftp_packet();
  1142. switch ($this->packet_type) {
  1143. case NET_SFTP_ATTRS:
  1144. return $this->_parseAttributes($response);
  1145. case NET_SFTP_STATUS:
  1146. $this->_logError($response);
  1147. return false;
  1148. }
  1149. user_error('Expected SSH_FXP_ATTRS or SSH_FXP_STATUS');
  1150. return false;
  1151. }
  1152. /**
  1153. * Truncates a file to a given length
  1154. *
  1155. * @param String $filename
  1156. * @param Integer $new_size
  1157. * @return Boolean
  1158. * @access public
  1159. */
  1160. function truncate($filename, $new_size)
  1161. {
  1162. $attr = pack('N3', NET_SFTP_ATTR_SIZE, $new_size / 4294967296, $new_size); // 4294967296 == 0x100000000 == 1<<32
  1163. return $this->_setstat($filename, $attr, false);
  1164. }
  1165. /**
  1166. * Sets access and modification time of file.
  1167. *
  1168. * If the file does not exist, it will be created.
  1169. *
  1170. * @param String $filename
  1171. * @param optional Integer $time
  1172. * @param optional Integer $atime
  1173. * @return Boolean
  1174. * @access public
  1175. */
  1176. function touch($filename, $time = null, $atime = null)
  1177. {
  1178. if (!($this->bitmap & NET_SSH2_MASK_LOGIN)) {
  1179. return false;
  1180. }
  1181. $filename = $this->_realpath($filename);
  1182. if ($filename === false) {
  1183. return false;
  1184. }
  1185. if (!isset($time)) {
  1186. $time = time();
  1187. }
  1188. if (!isset($atime)) {
  1189. $atime = $time;
  1190. }
  1191. $flags = NET_SFTP_OPEN_WRITE | NET_SFTP_OPEN_CREATE | NET_SFTP_OPEN_EXCL;
  1192. $attr = pack('N3', NET_SFTP_ATTR_ACCESSTIME, $time, $atime);
  1193. $packet = pack('Na*Na*', strlen($filename), $filename, $flags, $attr);
  1194. if (!$this->_send_sftp_packet(NET_SFTP_OPEN, $packet)) {
  1195. return false;
  1196. }
  1197. $response = $this->_get_sftp_packet();
  1198. switch ($this->packet_type) {
  1199. case NET_SFTP_HANDLE:
  1200. return $this->_close_handle(substr($response, 4));
  1201. case NET_SFTP_STATUS:
  1202. $this->_logError($response);
  1203. break;
  1204. default:
  1205. user_error('Expected SSH_FXP_HANDLE or SSH_FXP_STATUS');
  1206. return false;
  1207. }
  1208. return $this->_setstat($filename, $attr, false);
  1209. }
  1210. /**
  1211. * Changes file or directory owner
  1212. *
  1213. * Returns true on success or false on error.
  1214. *
  1215. * @param String $filename
  1216. * @param Integer $uid
  1217. * @param optional Boolean $recursive
  1218. * @return Boolean
  1219. * @access public
  1220. */
  1221. function chown($filename, $uid, $recursive = false)
  1222. {
  1223. // quoting from <http://www.kernel.org/doc/man-pages/online/pages/man2/chown.2.html>,
  1224. // "if the owner or group is specified as -1, then that ID is not changed"
  1225. $attr = pack('N3', NET_SFTP_ATTR_UIDGID, $uid, -1);
  1226. return $this->_setstat($filename, $attr, $recursive);
  1227. }
  1228. /**
  1229. * Changes file or directory group
  1230. *
  1231. * Returns true on success or false on error.
  1232. *
  1233. * @param String $filename
  1234. * @param Integer $gid
  1235. * @param optional Boolean $recursive
  1236. * @return Boolean
  1237. * @access public
  1238. */
  1239. function chgrp($filename, $gid, $recursive = false)
  1240. {
  1241. $attr = pack('N3', NET_SFTP_ATTR_UIDGID, -1, $gid);
  1242. return $this->_setstat($filename, $attr, $recursive);
  1243. }
  1244. /**
  1245. * Set permissions on a file.
  1246. *
  1247. * Returns the new file permissions on success or false on error.
  1248. * If $recursive is true than this just returns true or false.
  1249. *
  1250. * @param Integer $mode
  1251. * @param String $filename
  1252. * @param optional Boolean $recursive
  1253. * @return Mixed
  1254. * @access public
  1255. */
  1256. function chmod($mode, $filename, $recursive = false)
  1257. {
  1258. if (is_string($mode) && is_int($filename)) {
  1259. $temp = $mode;
  1260. $mode = $filename;
  1261. $filename = $temp;
  1262. }
  1263. $attr = pack('N2', NET_SFTP_ATTR_PERMISSIONS, $mode & 07777);
  1264. if (!$this->_setstat($filename, $attr, $recursive)) {
  1265. return false;
  1266. }
  1267. if ($recursive) {
  1268. return true;
  1269. }
  1270. // rather than return what the permissions *should* be, we'll return what they actually are. this will also
  1271. // tell us if the file actually exists.
  1272. // incidentally, SFTPv4+ adds an additional 32-bit integer field - flags - to the following:
  1273. $packet = pack('Na*', strlen($filename), $filename);
  1274. if (!$this->_send_sftp_packet(NET_SFTP_STAT, $packet)) {
  1275. return false;
  1276. }
  1277. $response = $this->_get_sftp_packet();
  1278. switch ($this->packet_type) {
  1279. case NET_SFTP_ATTRS:
  1280. $attrs = $this->_parseAttributes($response);
  1281. return $attrs['permissions'];
  1282. case NET_SFTP_STATUS:
  1283. $this->_logError($response);
  1284. return false;
  1285. }
  1286. user_error('Expected SSH_FXP_ATTRS or SSH_FXP_STATUS');
  1287. return false;
  1288. }
  1289. /**
  1290. * Sets information about a file
  1291. *
  1292. * @param String $filename
  1293. * @param String $attr
  1294. * @param Boolean $recursive
  1295. * @return Boolean
  1296. * @access private
  1297. */
  1298. function _setstat($filename, $attr, $recursive)
  1299. {
  1300. if (!($this->bitmap & NET_SSH2_MASK_LOGIN)) {
  1301. return false;
  1302. }
  1303. $filename = $this->_realpath($filename);
  1304. if ($filename === false) {
  1305. return false;
  1306. }
  1307. $this->_remove_from_stat_cache($filename);
  1308. if ($recursive) {
  1309. $i = 0;
  1310. $result = $this->_setstat_recursive($filename, $attr, $i);
  1311. $this->_read_put_responses($i);
  1312. return $result;
  1313. }
  1314. // SFTPv4+ has an additional byte field - type - that would need to be sent, as well. setting it to
  1315. // SSH_FILEXFER_TYPE_UNKNOWN might work. if not, we'd have to do an SSH_FXP_STAT before doing an SSH_FXP_SETSTAT.
  1316. if (!$this->_send_sftp_packet(NET_SFTP_SETSTAT, pack('Na*a*', strlen($filename), $filename, $attr))) {
  1317. return false;
  1318. }
  1319. /*
  1320. "Because some systems must use separate system calls to set various attributes, it is possible that a failure
  1321. response will be returned, but yet some of the attributes may be have been successfully modified. If possible,
  1322. servers SHOULD avoid this situation; however, clients MUST be aware that this is possible."
  1323. -- http://tools.ietf.org/html/draft-ietf-secsh-filexfer-13#section-8.6
  1324. */
  1325. $response = $this->_get_sftp_packet();
  1326. if ($this->packet_type != NET_SFTP_STATUS) {
  1327. user_error('Expected SSH_FXP_STATUS');
  1328. return false;
  1329. }
  1330. extract(unpack('Nstatus', $this->_string_shift($response, 4)));
  1331. if ($status != NET_SFTP_STATUS_OK) {
  1332. $this->_logError($response, $status);
  1333. return false;
  1334. }
  1335. return true;
  1336. }
  1337. /**
  1338. * Recursively sets information on directories on the SFTP server
  1339. *
  1340. * Minimizes directory lookups and SSH_FXP_STATUS requests for speed.
  1341. *
  1342. * @param String $path
  1343. * @param String $attr
  1344. * @param Integer $i
  1345. * @return Boolean
  1346. * @access private
  1347. */
  1348. function _setstat_recursive($path, $attr, &$i)
  1349. {
  1350. if (!$this->_read_put_responses($i)) {
  1351. return false;
  1352. }
  1353. $i = 0;
  1354. $entries = $this->_list($path, true, false);
  1355. if ($entries === false) {
  1356. return $this->_setstat($path, $attr, false);
  1357. }
  1358. // normally $entries would have at least . and .. but it might not if the directories
  1359. // permissions didn't allow reading
  1360. if (empty($entries)) {
  1361. return false;
  1362. }
  1363. foreach ($entries as $filename=>$props) {
  1364. if ($filename == '.' || $filename == '..') {
  1365. continue;
  1366. }
  1367. if (!isset($props['type'])) {
  1368. return false;
  1369. }
  1370. $temp = $path . '/' . $filename;
  1371. if ($props['type'] == NET_SFTP_TYPE_DIRECTORY) {
  1372. if (!$this->_setstat_recursive($temp, $attr, $i)) {
  1373. return false;
  1374. }
  1375. } else {
  1376. if (!$this->_send_sftp_packet(NET_SFTP_SETSTAT, pack('Na*a*', strlen($temp), $temp, $attr))) {
  1377. return false;
  1378. }
  1379. $i++;
  1380. if ($i >= NET_SFTP_QUEUE_SIZE) {
  1381. if (!$this->_read_put_responses($i)) {
  1382. return false;
  1383. }
  1384. $i = 0;
  1385. }
  1386. }
  1387. }
  1388. if (!$this->_send_sftp_packet(NET_SFTP_SETSTAT, pack('Na*a*', strlen($path), $path, $attr))) {
  1389. return false;
  1390. }
  1391. $i++;
  1392. if ($i >= NET_SFTP_QUEUE_SIZE) {
  1393. if (!$this->_read_put_responses($i)) {
  1394. return false;
  1395. }
  1396. $i = 0;
  1397. }
  1398. return true;
  1399. }
  1400. /**
  1401. * Return the target of a symbolic link
  1402. *
  1403. * @param String $link
  1404. * @return Mixed
  1405. * @access public
  1406. */
  1407. function readlink($link)
  1408. {
  1409. if (!($this->bitmap & NET_SSH2_MASK_LOGIN)) {
  1410. return false;
  1411. }
  1412. $link = $this->_realpath($link);
  1413. if (!$this->_send_sftp_packet(NET_SFTP_READLINK, pack('Na*', strlen($link), $link))) {
  1414. return false;
  1415. }
  1416. $response = $this->_get_sftp_packet();
  1417. switch ($this->packet_type) {
  1418. case NET_SFTP_NAME:
  1419. break;
  1420. case NET_SFTP_STATUS:
  1421. $this->_logError($response);
  1422. return false;
  1423. default:
  1424. user_error('Expected SSH_FXP_NAME or SSH_FXP_STATUS');
  1425. return false;
  1426. }
  1427. extract(unpack('Ncount', $this->_string_shift($response, 4)));
  1428. // the file isn't a symlink
  1429. if (!$count) {
  1430. return false;
  1431. }
  1432. extract(unpack('Nlength', $this->_string_shift($response, 4)));
  1433. return $this->_string_shift($response, $length);
  1434. }
  1435. /**
  1436. * Create a symlink
  1437. *
  1438. * symlink() creates a symbolic link to the existing target with the specified name link.
  1439. *
  1440. * @param String $target
  1441. * @param String $link
  1442. * @return Boolean
  1443. * @access public
  1444. */
  1445. function symlink($target, $link)
  1446. {
  1447. if (!($this->bitmap & NET_SSH2_MASK_LOGIN)) {
  1448. return false;
  1449. }
  1450. $target = $this->_realpath($target);
  1451. $link = $this->_realpath($link);
  1452. $packet = pack('Na*Na*', strlen($target), $target, strlen($link), $link);
  1453. if (!$this->_send_sftp_packet(NET_SFTP_SYMLINK, $packet)) {
  1454. return false;
  1455. }
  1456. $response = $this->_get_sftp_packet();
  1457. if ($this->packet_type != NET_SFTP_STATUS) {
  1458. user_error('Expected SSH_FXP_STATUS');
  1459. return false;
  1460. }
  1461. extract(unpack('Nstatus', $this->_string_shift($response, 4)));
  1462. if ($status != NET_SFTP_STATUS_OK) {
  1463. $this->_logError($response, $status);
  1464. return false;
  1465. }
  1466. return true;
  1467. }
  1468. /**
  1469. * Creates a directory.
  1470. *
  1471. * @param String $dir
  1472. * @return Boolean
  1473. * @access public
  1474. */
  1475. function mkdir($dir, $mode = -1, $recursive = false)
  1476. {
  1477. if (!($this->bitmap & NET_SSH2_MASK_LOGIN)) {
  1478. return false;
  1479. }
  1480. $dir = $this->_realpath($dir);
  1481. // by not providing any permissions, hopefully the server will use the logged in users umask - their
  1482. // default permissions.
  1483. $attr = $mode == -1 ? "\0\0\0\0" : pack('N2', NET_SFTP_ATTR_PERMISSIONS, $mode & 07777);
  1484. if ($recursive) {
  1485. $dirs = explode('/', preg_replace('#/(?=/)|/$#', '', $dir));
  1486. if (empty($dirs[0])) {
  1487. array_shift($dirs);
  1488. $dirs[0] = '/' . $dirs[0];
  1489. }
  1490. for ($i = 0; $i < count($dirs); $i++) {
  1491. $temp = array_slice($dirs, 0, $i + 1);
  1492. $temp = implode('/', $temp);
  1493. $result = $this->_mkdir_helper($temp, $attr);
  1494. }
  1495. return $result;
  1496. }
  1497. return $this->_mkdir_helper($dir, $attr);
  1498. }
  1499. /**
  1500. * Helper function for directory creation
  1501. *
  1502. * @param String $dir
  1503. * @return Boolean
  1504. * @access private
  1505. */
  1506. function _mkdir_helper($dir, $attr)
  1507. {
  1508. if (!$this->_send_sftp_packet(NET_SFTP_MKDIR, pack('Na*a*', strlen($dir), $dir, $attr))) {
  1509. return false;
  1510. }
  1511. $response = $this->_get_sftp_packet();
  1512. if ($this->packet_type != NET_SFTP_STATUS) {
  1513. user_error('Expected SSH_FXP_STATUS');
  1514. return false;
  1515. }
  1516. extract(unpack('Nstatus', $this->_string_shift($response, 4)));
  1517. if ($status != NET_SFTP_STATUS_OK) {
  1518. $this->_logError($response, $status);
  1519. return false;
  1520. }
  1521. return true;
  1522. }
  1523. /**
  1524. * Removes a directory.
  1525. *
  1526. * @param String $dir
  1527. * @return Boolean
  1528. * @access public
  1529. */
  1530. function rmdir($dir)
  1531. {
  1532. if (!($this->bitmap & NET_SSH2_MASK_LOGIN)) {
  1533. return false;
  1534. }
  1535. $dir = $this->_realpath($dir);
  1536. if ($dir === false) {
  1537. return false;
  1538. }
  1539. if (!$this->_send_sftp_packet(NET_SFTP_RMDIR, pack('Na*', strlen($dir), $dir))) {
  1540. return false;
  1541. }
  1542. $response = $this->_get_sftp_packet();
  1543. if ($this->packet_type != NET_SFTP_STATUS) {
  1544. user_error('Expected SSH_FXP_STATUS');
  1545. return false;
  1546. }
  1547. extract(unpack('Nstatus', $this->_string_shift($response, 4)));
  1548. if ($status != NET_SFTP_STATUS_OK) {
  1549. // presumably SSH_FX_NO_SUCH_FILE or SSH_FX_PERMISSION_DENIED?
  1550. $this->_logError($response, $status);
  1551. return false;
  1552. }
  1553. $this->_remove_from_stat_cache($dir);
  1554. // the following will do a soft delete, which would be useful if you deleted a file
  1555. // and then tried to do a stat on the deleted file. the above, in contrast, does
  1556. // a hard delete
  1557. //$this->_update_stat_cache($dir, false);
  1558. return true;
  1559. }
  1560. /**
  1561. * Uploads a file to the SFTP server.
  1562. *
  1563. * By default, Net_SFTP::put() does not read from the local filesystem. $data is dumped directly into $remote_file.
  1564. * So, for example, if you set $data to 'filename.ext' and then do Net_SFTP::get(), you will get a file, twelve bytes
  1565. * long, containing 'filename.ext' as its contents.
  1566. *
  1567. * Setting $mode to NET_SFTP_LOCAL_FILE will change the above behavior. With NET_SFTP_LOCAL_FILE, $remote_file will
  1568. * contain as many bytes as filename.ext does on your local filesystem. If your filename.ext is 1MB then that is how
  1569. * large $remote_file will be, as well.
  1570. *
  1571. * Currently, only binary mode is supported. As such, if the line endings need to be adjusted, you will need to take
  1572. * care of that, yourself.
  1573. *
  1574. * $mode can take an additional two parameters - NET_SFTP_RESUME and NET_SFTP_RESUME_START. These are bitwise AND'd with
  1575. * $mode. So if you want to resume upload of a 300mb file on the local file system you'd set $mode to the following:
  1576. *
  1577. * NET_SFTP_LOCAL_FILE | NET_SFTP_RESUME
  1578. *
  1579. * If you wanted to simply append the full contents of a local file to the full contents of a remote file you'd replace
  1580. * NET_SFTP_RESUME with NET_SFTP_RESUME_START.
  1581. *
  1582. * If $mode & (NET_SFTP_RESUME | NET_SFTP_RESUME_START) then NET_SFTP_RESUME_START will be assumed.
  1583. *
  1584. * $start and $local_start give you more fine grained control over this process and take precident over NET_SFTP_RESUME
  1585. * when they're non-negative. ie. $start could let you write at the end of a file (like NET_SFTP_RESUME) or in the middle
  1586. * of one. $local_start could let you start your reading from the end of a file (like NET_SFTP_RESUME_START) or in the
  1587. * middle of one.
  1588. *
  1589. * Setting $local_start to > 0 or $mode | NET_SFTP_RESUME_START doesn't do anything unless $mode | NET_SFTP_LOCAL_FILE.
  1590. *
  1591. * @param String $remote_file
  1592. * @param String $data
  1593. * @param optional Integer $mode
  1594. * @param optional Integer $start
  1595. * @param optional Integer $local_start
  1596. * @return Boolean
  1597. * @access public
  1598. * @internal ASCII mode for SFTPv4/5/6 can be supported by adding a new function - Net_SFTP::setMode().
  1599. */
  1600. function put($remote_file, $data, $mode = NET_SFTP_STRING, $start = -1, $local_start = -1)
  1601. {
  1602. if (!($this->bitmap & NET_SSH2_MASK_LOGIN)) {
  1603. return false;
  1604. }
  1605. $remote_file = $this->_realpath($remote_file);
  1606. if ($remote_file === false) {
  1607. return false;
  1608. }
  1609. $this->_remove_from_stat_cache($remote_file);
  1610. $flags = NET_SFTP_OPEN_WRITE | NET_SFTP_OPEN_CREATE;
  1611. // according to the SFTP specs, NET_SFTP_OPEN_APPEND should "force all writes to append data at the end of the file."
  1612. // in practice, it doesn't seem to do that.
  1613. //$flags|= ($mode & NET_SFTP_RESUME) ? NET_SFTP_OPEN_APPEND : NET_SFTP_OPEN_TRUNCATE;
  1614. if ($start >= 0) {
  1615. $offset = $start;
  1616. } elseif ($mode & NET_SFTP_RESUME) {
  1617. // if NET_SFTP_OPEN_APPEND worked as it should _size() wouldn't need to be called
  1618. $size = $this->size($remote_file);
  1619. $offset = $size !== false ? $size : 0;
  1620. } else {
  1621. $offset = 0;
  1622. $flags|= NET_SFTP_OPEN_TRUNCATE;
  1623. }
  1624. $packet = pack('Na*N2', strlen($remote_file), $remote_file, $flags, 0);
  1625. if (!$this->_send_sftp_packet(NET_SFTP_OPEN, $packet)) {
  1626. return false;
  1627. }
  1628. $response = $this->_get_sftp_packet();
  1629. switch ($this->packet_type) {
  1630. case NET_SFTP_HANDLE:
  1631. $handle = substr($response, 4);
  1632. break;
  1633. case NET_SFTP_STATUS:
  1634. $this->_logError($response);
  1635. return false;
  1636. default:
  1637. user_error('Expected SSH_FXP_HANDLE or SSH_FXP_STATUS');
  1638. return false;
  1639. }
  1640. // http://tools.ietf.org/html/draft-ietf-secsh-filexfer-13#section-8.2.3
  1641. if ($mode & NET_SFTP_LOCAL_FILE) {
  1642. if (!is_file($data)) {
  1643. user_error("$data is not a valid file");
  1644. return false;
  1645. }
  1646. $fp = @fopen($data, 'rb');
  1647. if (!$fp) {
  1648. return false;
  1649. }
  1650. $size = filesize($data);
  1651. if ($local_start >= 0) {
  1652. fseek($fp, $local_start);
  1653. } elseif ($mode & NET_SFTP_RESUME_START) {
  1654. // do nothing
  1655. } else {
  1656. fseek($fp, $offset);
  1657. }
  1658. } else {
  1659. $size = strlen($data);
  1660. }
  1661. $sent = 0;
  1662. $size = $size < 0 ? ($size & 0x7FFFFFFF) + 0x80000000 : $size;
  1663. $sftp_packet_size = 4096; // PuTTY uses 4096
  1664. // make the SFTP packet be exactly 4096 bytes by including the bytes in the NET_SFTP_WRITE packets "header"
  1665. $sftp_packet_size-= strlen($handle) + 25;
  1666. $i = 0;
  1667. while ($sent < $size) {
  1668. $temp = $mode & NET_SFTP_LOCAL_FILE ? fread($fp, $sftp_packet_size) : substr($data, $sent, $sftp_packet_size);
  1669. $subtemp = $offset + $sent;
  1670. $packet = pack('Na*N3a*', strlen($handle), $handle, $subtemp / 4294967296, $subtemp, strlen($temp), $temp);
  1671. if (!$this->_send_sftp_packet(NET_SFTP_WRITE, $packet)) {
  1672. fclose($fp);
  1673. return false;
  1674. }
  1675. $sent+= strlen($temp);
  1676. $i++;
  1677. if ($i == NET_SFTP_QUEUE_SIZE) {
  1678. if (!$this->_read_put_responses($i)) {
  1679. $i = 0;
  1680. break;
  1681. }
  1682. $i = 0;
  1683. }
  1684. }
  1685. if (!$this->_read_put_responses($i)) {
  1686. if ($mode & NET_SFTP_LOCAL_FILE) {
  1687. fclose($fp);
  1688. }
  1689. $this->_close_handle($handle);
  1690. return false;
  1691. }
  1692. if ($mode & NET_SFTP_LOCAL_FILE) {
  1693. fclose($fp);
  1694. }
  1695. return $this->_close_handle($handle);
  1696. }
  1697. /**
  1698. * Reads multiple successive SSH_FXP_WRITE responses
  1699. *
  1700. * Sending an SSH_FXP_WRITE packet and immediately reading its response isn't as efficient as blindly sending out $i
  1701. * SSH_FXP_WRITEs, in succession, and then reading $i responses.
  1702. *
  1703. * @param Integer $i
  1704. * @return Boolean
  1705. * @access private
  1706. */
  1707. function _read_put_responses($i)
  1708. {
  1709. while ($i--) {
  1710. $response = $this->_get_sftp_packet();
  1711. if ($this->packet_type != NET_SFTP_STATUS) {
  1712. user_error('Expected SSH_FXP_STATUS');
  1713. return false;
  1714. }
  1715. extract(unpack('Nstatus', $this->_string_shift($response, 4)));
  1716. if ($status != NET_SFTP_STATUS_OK) {
  1717. $this->_logError($response, $status);
  1718. break;
  1719. }
  1720. }
  1721. return $i < 0;
  1722. }
  1723. /**
  1724. * Close handle
  1725. *
  1726. * @param String $handle
  1727. * @return Boolean
  1728. * @access private
  1729. */
  1730. function _close_handle($handle)
  1731. {
  1732. if (!$this->_send_sftp_packet(NET_SFTP_CLOSE, pack('Na*', strlen($handle), $handle))) {
  1733. return false;
  1734. }
  1735. // "The client MUST release all resources associated with the handle regardless of the status."
  1736. // -- http://tools.ietf.org/html/draft-ietf-secsh-filexfer-13#section-8.1.3
  1737. $response = $this->_get_sftp_packet();
  1738. if ($this->packet_type != NET_SFTP_STATUS) {
  1739. user_error('Expected SSH_FXP_STATUS');
  1740. return false;
  1741. }
  1742. extract(unpack('Nstatus', $this->_string_shift($response, 4)));
  1743. if ($status != NET_SFTP_STATUS_OK) {
  1744. $this->_logError($response, $status);
  1745. return false;
  1746. }
  1747. return true;
  1748. }
  1749. /**
  1750. * Downloads a file from the SFTP server.
  1751. *
  1752. * Returns a string containing the contents of $remote_file if $local_file is left undefined or a boolean false if
  1753. * the operation was unsuccessful. If $local_file is defined, returns true or false depending on the success of the
  1754. * operation.
  1755. *
  1756. * $offset and $length can be used to download files in chunks.
  1757. *
  1758. * @param String $remote_file
  1759. * @param optional String $local_file
  1760. * @param optional Integer $offset
  1761. * @param optional Integer $length
  1762. * @return Mixed
  1763. * @access public
  1764. */
  1765. function get($remote_file, $local_file = false, $offset = 0, $length = -1)
  1766. {
  1767. if (!($this->bitmap & NET_SSH2_MASK_LOGIN)) {
  1768. return false;
  1769. }
  1770. $remote_file = $this->_realpath($remote_file);
  1771. if ($remote_file === false) {
  1772. return false;
  1773. }
  1774. $packet = pack('Na*N2', strlen($remote_file), $remote_file, NET_SFTP_OPEN_READ, 0);
  1775. if (!$this->_send_sftp_packet(NET_SFTP_OPEN, $packet)) {
  1776. return false;
  1777. }
  1778. $response = $this->_get_sftp_packet();
  1779. switch ($this->packet_type) {
  1780. case NET_SFTP_HANDLE:
  1781. $handle = substr($response, 4);
  1782. break;
  1783. case NET_SFTP_STATUS: // presumably SSH_FX_NO_SUCH_FILE or SSH_FX_PERMISSION_DENIED
  1784. $this->_logError($response);
  1785. return false;
  1786. default:
  1787. user_error('Expected SSH_FXP_HANDLE or SSH_FXP_STATUS');
  1788. return false;
  1789. }
  1790. if ($local_file !== false) {
  1791. $fp = fopen($local_file, 'wb');
  1792. if (!$fp) {
  1793. return false;
  1794. }
  1795. } else {
  1796. $content = '';
  1797. }
  1798. $start = $offset;
  1799. $size = $this->max_sftp_packet < $length || $length < 0 ? $this->max_sftp_packet : $length;
  1800. while (true) {
  1801. $packet = pack('Na*N3', strlen($handle), $handle, $offset / 4294967296, $offset, $size);
  1802. if (!$this->_send_sftp_packet(NET_SFTP_READ, $packet)) {
  1803. if ($local_file !== false) {
  1804. fclose($fp);
  1805. }
  1806. return false;
  1807. }
  1808. $response = $this->_get_sftp_packet();
  1809. switch ($this->packet_type) {
  1810. case NET_SFTP_DATA:
  1811. $temp = substr($response, 4);
  1812. $offset+= strlen($temp);
  1813. if ($local_file === false) {
  1814. $content.= $temp;
  1815. } else {
  1816. fputs($fp, $temp);
  1817. }
  1818. break;
  1819. case NET_SFTP_STATUS:
  1820. // could, in theory, return false if !strlen($content) but we'll hold off for the time being
  1821. $this->_logError($response);
  1822. break 2;
  1823. default:
  1824. user_error('Expected SSH_FXP_DATA or SSH_FXP_STATUS');
  1825. if ($local_file !== false) {
  1826. fclose($fp);
  1827. }
  1828. return false;
  1829. }
  1830. if ($length > 0 && $length <= $offset - $start) {
  1831. break;
  1832. }
  1833. }
  1834. if ($length > 0 && $length <= $offset - $start) {
  1835. if ($local_file === false) {
  1836. $content = substr($content, 0, $length);
  1837. } else {
  1838. ftruncate($fp, $length);
  1839. }
  1840. }
  1841. if ($local_file !== false) {
  1842. fclose($fp);
  1843. }
  1844. if (!$this->_close_handle($handle)) {
  1845. return false;
  1846. }
  1847. // if $content isn't set that means a file was written to
  1848. return isset($content) ? $content : true;
  1849. }
  1850. /**
  1851. * Deletes a file on the SFTP server.
  1852. *
  1853. * @param String $path
  1854. * @param Boolean $recursive
  1855. * @return Boolean
  1856. * @access public
  1857. */
  1858. function delete($path, $recursive = true)
  1859. {
  1860. if (!($this->bitmap & NET_SSH2_MASK_LOGIN)) {
  1861. return false;
  1862. }
  1863. $path = $this->_realpath($path);
  1864. if ($path === false) {
  1865. return false;
  1866. }
  1867. // http://tools.ietf.org/html/draft-ietf-secsh-filexfer-13#section-8.3
  1868. if (!$this->_send_sftp_packet(NET_SFTP_REMOVE, pack('Na*', strlen($path), $path))) {
  1869. return false;
  1870. }
  1871. $response = $this->_get_sftp_packet();
  1872. if ($this->packet_type != NET_SFTP_STATUS) {
  1873. user_error('Expected SSH_FXP_STATUS');
  1874. return false;
  1875. }
  1876. // if $status isn't SSH_FX_OK it's probably SSH_FX_NO_SUCH_FILE or SSH_FX_PERMISSION_DENIED
  1877. extract(unpack('Nstatus', $this->_string_shift($response, 4)));
  1878. if ($status != NET_SFTP_STATUS_OK) {
  1879. $this->_logError($response, $status);
  1880. if (!$recursive) {
  1881. return false;
  1882. }
  1883. $i = 0;
  1884. $result = $this->_delete_recursive($path, $i);
  1885. $this->_read_put_responses($i);
  1886. return $result;
  1887. }
  1888. $this->_remove_from_stat_cache($path);
  1889. return true;
  1890. }
  1891. /**
  1892. * Recursively deletes directories on the SFTP server
  1893. *
  1894. * Minimizes directory lookups and SSH_FXP_STATUS requests for speed.
  1895. *
  1896. * @param String $path
  1897. * @param Integer $i
  1898. * @return Boolean
  1899. * @access private
  1900. */
  1901. function _delete_recursive($path, &$i)
  1902. {
  1903. if (!$this->_read_put_responses($i)) {
  1904. return false;
  1905. }
  1906. $i = 0;
  1907. $entries = $this->_list($path, true, false);
  1908. // normally $entries would have at least . and .. but it might not if the directories
  1909. // permissions didn't allow reading
  1910. if (empty($entries)) {
  1911. return false;
  1912. }
  1913. foreach ($entries as $filename=>$props) {
  1914. if ($filename == '.' || $filename == '..') {
  1915. continue;
  1916. }
  1917. if (!isset($props['type'])) {
  1918. return false;
  1919. }
  1920. $temp = $path . '/' . $filename;
  1921. if ($props['type'] == NET_SFTP_TYPE_DIRECTORY) {
  1922. if (!$this->_delete_recursive($temp, $i)) {
  1923. return false;
  1924. }
  1925. } else {
  1926. if (!$this->_send_sftp_packet(NET_SFTP_REMOVE, pack('Na*', strlen($temp), $temp))) {
  1927. return false;
  1928. }
  1929. $i++;
  1930. if ($i >= NET_SFTP_QUEUE_SIZE) {
  1931. if (!$this->_read_put_responses($i)) {
  1932. return false;
  1933. }
  1934. $i = 0;
  1935. }
  1936. }
  1937. $this->_remove_from_stat_cache($path);
  1938. }
  1939. if (!$this->_send_sftp_packet(NET_SFTP_RMDIR, pack('Na*', strlen($path), $path))) {
  1940. return false;
  1941. }
  1942. $i++;
  1943. if ($i >= NET_SFTP_QUEUE_SIZE) {
  1944. if (!$this->_read_put_responses($i)) {
  1945. return false;
  1946. }
  1947. $i = 0;
  1948. }
  1949. return true;
  1950. }
  1951. /**
  1952. * Checks whether a file or directory exists
  1953. *
  1954. * @param String $path
  1955. * @return Boolean
  1956. * @access public
  1957. */
  1958. function file_exists($path)
  1959. {
  1960. if ($this->use_stat_cache) {
  1961. $path = $this->_realpath($path);
  1962. $result = $this->_query_stat_cache($path);
  1963. if (isset($result)) {
  1964. // return true if $result is an array or if it's int(1)
  1965. return $result !== false;
  1966. }
  1967. }
  1968. return $this->stat($path) !== false;
  1969. }
  1970. /**
  1971. * Tells whether the filename is a directory
  1972. *
  1973. * @param String $path
  1974. * @return Boolean
  1975. * @access public
  1976. */
  1977. function is_dir($path)
  1978. {
  1979. $result = $this->_get_stat_cache_prop($path, 'type');
  1980. if ($result === false) {
  1981. return false;
  1982. }
  1983. return $result === NET_SFTP_TYPE_DIRECTORY;
  1984. }
  1985. /**
  1986. * Tells whether the filename is a regular file
  1987. *
  1988. * @param String $path
  1989. * @return Boolean
  1990. * @access public
  1991. */
  1992. function is_file($path)
  1993. {
  1994. $result = $this->_get_stat_cache_prop($path, 'type');
  1995. if ($result === false) {
  1996. return false;
  1997. }
  1998. return $result === NET_SFTP_TYPE_REGULAR;
  1999. }
  2000. /**
  2001. * Tells whether the filename is a symbolic link
  2002. *
  2003. * @param String $path
  2004. * @return Boolean
  2005. * @access public
  2006. */
  2007. function is_link($path)
  2008. {
  2009. $result = $this->_get_stat_cache_prop($path, 'type');
  2010. if ($result === false) {
  2011. return false;
  2012. }
  2013. return $result === NET_SFTP_TYPE_SYMLINK;
  2014. }
  2015. /**
  2016. * Gets last access time of file
  2017. *
  2018. * @param String $path
  2019. * @return Mixed
  2020. * @access public
  2021. */
  2022. function fileatime($path)
  2023. {
  2024. return $this->_get_stat_cache_prop($path, 'atime');
  2025. }
  2026. /**
  2027. * Gets file modification time
  2028. *
  2029. * @param String $path
  2030. * @return Mixed
  2031. * @access public
  2032. */
  2033. function filemtime($path)
  2034. {
  2035. return $this->_get_stat_cache_prop($path, 'mtime');
  2036. }
  2037. /**
  2038. * Gets file permissions
  2039. *
  2040. * @param String $path
  2041. * @return Mixed
  2042. * @access public
  2043. */
  2044. function fileperms($path)
  2045. {
  2046. return $this->_get_stat_cache_prop($path, 'permissions');
  2047. }
  2048. /**
  2049. * Gets file owner
  2050. *
  2051. * @param String $path
  2052. * @return Mixed
  2053. * @access public
  2054. */
  2055. function fileowner($path)
  2056. {
  2057. return $this->_get_stat_cache_prop($path, 'uid');
  2058. }
  2059. /**
  2060. * Gets file group
  2061. *
  2062. * @param String $path
  2063. * @return Mixed
  2064. * @access public
  2065. */
  2066. function filegroup($path)
  2067. {
  2068. return $this->_get_stat_cache_prop($path, 'gid');
  2069. }
  2070. /**
  2071. * Gets file size
  2072. *
  2073. * @param String $path
  2074. * @return Mixed
  2075. * @access public
  2076. */
  2077. function filesize($path)
  2078. {
  2079. return $this->_get_stat_cache_prop($path, 'size');
  2080. }
  2081. /**
  2082. * Gets file type
  2083. *
  2084. * @param String $path
  2085. * @return Mixed
  2086. * @access public
  2087. */
  2088. function filetype($path)
  2089. {
  2090. $type = $this->_get_stat_cache_prop($path, 'type');
  2091. if ($type === false) {
  2092. return false;
  2093. }
  2094. switch ($type) {
  2095. case NET_SFTP_BLOCK_DEVICE: return 'block';
  2096. case NET_SFTP_TYPE_CHAR_DEVICE: return 'char';
  2097. case NET_SFTP_TYPE_DIRECTORY: return 'dir';
  2098. case NET_SFTP_TYPE_FIFO: return 'fifo';
  2099. case NET_SFTP_TYPE_REGULAR: return 'file';
  2100. case NET_SFTP_TYPE_SYMLINK: return 'link';
  2101. default: return false;
  2102. }
  2103. }
  2104. /**
  2105. * Return a stat properity
  2106. *
  2107. * Uses cache if appropriate.
  2108. *
  2109. * @param String $path
  2110. * @param String $prop
  2111. * @return Mixed
  2112. * @access private
  2113. */
  2114. function _get_stat_cache_prop($path, $prop)
  2115. {
  2116. if ($this->use_stat_cache) {
  2117. $path = $this->_realpath($path);
  2118. $result = $this->_query_stat_cache($path);
  2119. if (is_object($result) && isset($result->$prop)) {
  2120. return $result->$prop;
  2121. }
  2122. }
  2123. $result = $this->stat($path);
  2124. if ($result === false || !isset($result[$prop])) {
  2125. return false;
  2126. }
  2127. return $result[$prop];
  2128. }
  2129. /**
  2130. * Renames a file or a directory on the SFTP server
  2131. *
  2132. * @param String $oldname
  2133. * @param String $newname
  2134. * @return Boolean
  2135. * @access public
  2136. */
  2137. function rename($oldname, $newname)
  2138. {
  2139. if (!($this->bitmap & NET_SSH2_MASK_LOGIN)) {
  2140. return false;
  2141. }
  2142. $oldname = $this->_realpath($oldname);
  2143. $newname = $this->_realpath($newname);
  2144. if ($oldname === false || $newname === false) {
  2145. return false;
  2146. }
  2147. // http://tools.ietf.org/html/draft-ietf-secsh-filexfer-13#section-8.3
  2148. $packet = pack('Na*Na*', strlen($oldname), $oldname, strlen($newname), $newname);
  2149. if (!$this->_send_sftp_packet(NET_SFTP_RENAME, $packet)) {
  2150. return false;
  2151. }
  2152. $response = $this->_get_sftp_packet();
  2153. if ($this->packet_type != NET_SFTP_STATUS) {
  2154. user_error('Expected SSH_FXP_STATUS');
  2155. return false;
  2156. }
  2157. // if $status isn't SSH_FX_OK it's probably SSH_FX_NO_SUCH_FILE or SSH_FX_PERMISSION_DENIED
  2158. extract(unpack('Nstatus', $this->_string_shift($response, 4)));
  2159. if ($status != NET_SFTP_STATUS_OK) {
  2160. $this->_logError($response, $status);
  2161. return false;
  2162. }
  2163. // don't move the stat cache entry over since this operation could very well change the
  2164. // atime and mtime attributes
  2165. //$this->_update_stat_cache($newname, $this->_query_stat_cache($oldname));
  2166. $this->_remove_from_stat_cache($oldname);
  2167. $this->_remove_from_stat_cache($newname);
  2168. return true;
  2169. }
  2170. /**
  2171. * Parse Attributes
  2172. *
  2173. * See '7. File Attributes' of draft-ietf-secsh-filexfer-13 for more info.
  2174. *
  2175. * @param String $response
  2176. * @return Array
  2177. * @access private
  2178. */
  2179. function _parseAttributes(&$response)
  2180. {
  2181. $attr = array();
  2182. extract(unpack('Nflags', $this->_string_shift($response, 4)));
  2183. // SFTPv4+ have a type field (a byte) that follows the above flag field
  2184. foreach ($this->attributes as $key => $value) {
  2185. switch ($flags & $key) {
  2186. case NET_SFTP_ATTR_SIZE: // 0x00000001
  2187. // size is represented by a 64-bit integer, so we perhaps ought to be doing the following:
  2188. // $attr['size'] = new Math_BigInteger($this->_string_shift($response, 8), 256);
  2189. // of course, you shouldn't be using Net_SFTP to transfer files that are in excess of 4GB
  2190. // (0xFFFFFFFF bytes), anyway. as such, we'll just represent all file sizes that are bigger than
  2191. // 4GB as being 4GB.
  2192. extract(unpack('Nupper/Nsize', $this->_string_shift($response, 8)));
  2193. $attr['size'] = $upper ? 4294967296 * $upper : 0;
  2194. $attr['size']+= $size < 0 ? ($size & 0x7FFFFFFF) + 0x80000000 : $size;
  2195. break;
  2196. case NET_SFTP_ATTR_UIDGID: // 0x00000002 (SFTPv3 only)
  2197. $attr+= unpack('Nuid/Ngid', $this->_string_shift($response, 8));
  2198. break;
  2199. case NET_SFTP_ATTR_PERMISSIONS: // 0x00000004
  2200. $attr+= unpack('Npermissions', $this->_string_shift($response, 4));
  2201. // mode == permissions; permissions was the original array key and is retained for bc purposes.
  2202. // mode was added because that's the more industry standard terminology
  2203. $attr+= array('mode' => $attr['permissions']);
  2204. $fileType = $this->_parseMode($attr['permissions']);
  2205. if ($fileType !== false) {
  2206. $attr+= array('type' => $fileType);
  2207. }
  2208. break;
  2209. case NET_SFTP_ATTR_ACCESSTIME: // 0x00000008
  2210. $attr+= unpack('Natime/Nmtime', $this->_string_shift($response, 8));
  2211. break;
  2212. case NET_SFTP_ATTR_EXTENDED: // 0x80000000
  2213. extract(unpack('Ncount', $this->_string_shift($response, 4)));
  2214. for ($i = 0; $i < $count; $i++) {
  2215. extract(unpack('Nlength', $this->_string_shift($response, 4)));
  2216. $key = $this->_string_shift($response, $length);
  2217. extract(unpack('Nlength', $this->_string_shift($response, 4)));
  2218. $attr[$key] = $this->_string_shift($response, $length);
  2219. }
  2220. }
  2221. }
  2222. return $attr;
  2223. }
  2224. /**
  2225. * Attempt to identify the file type
  2226. *
  2227. * Quoting the SFTP RFC, "Implementations MUST NOT send bits that are not defined" but they seem to anyway
  2228. *
  2229. * @param Integer $mode
  2230. * @return Integer
  2231. * @access private
  2232. */
  2233. function _parseMode($mode)
  2234. {
  2235. // values come from http://lxr.free-electrons.com/source/include/uapi/linux/stat.h#L12
  2236. // see, also, http://linux.die.net/man/2/stat
  2237. switch ($mode & 0170000) {// ie. 1111 0000 0000 0000
  2238. case 0000000: // no file type specified - figure out the file type using alternative means
  2239. return false;
  2240. case 0040000:
  2241. return NET_SFTP_TYPE_DIRECTORY;
  2242. case 0100000:
  2243. return NET_SFTP_TYPE_REGULAR;
  2244. case 0120000:
  2245. return NET_SFTP_TYPE_SYMLINK;
  2246. // new types introduced in SFTPv5+
  2247. // http://tools.ietf.org/html/draft-ietf-secsh-filexfer-05#section-5.2
  2248. case 0010000: // named pipe (fifo)
  2249. return NET_SFTP_TYPE_FIFO;
  2250. case 0020000: // character special
  2251. return NET_SFTP_TYPE_CHAR_DEVICE;
  2252. case 0060000: // block special
  2253. return NET_SFTP_BLOCK_DEVICE;
  2254. case 0140000: // socket
  2255. return NET_SFTP_TYPE_SOCKET;
  2256. case 0160000: // whiteout
  2257. // "SPECIAL should be used for files that are of
  2258. // a known type which cannot be expressed in the protocol"
  2259. return NET_SFTP_TYPE_SPECIAL;
  2260. default:
  2261. return NET_SFTP_TYPE_UNKNOWN;
  2262. }
  2263. }
  2264. /**
  2265. * Parse Longname
  2266. *
  2267. * SFTPv3 doesn't provide any easy way of identifying a file type. You could try to open
  2268. * a file as a directory and see if an error is returned or you could try to parse the
  2269. * SFTPv3-specific longname field of the SSH_FXP_NAME packet. That's what this function does.
  2270. * The result is returned using the
  2271. * {@link http://tools.ietf.org/html/draft-ietf-secsh-filexfer-04#section-5.2 SFTPv4 type constants}.
  2272. *
  2273. * If the longname is in an unrecognized format bool(false) is returned.
  2274. *
  2275. * @param String $longname
  2276. * @return Mixed
  2277. * @access private
  2278. */
  2279. function _parseLongname($longname)
  2280. {
  2281. // http://en.wikipedia.org/wiki/Unix_file_types
  2282. // http://en.wikipedia.org/wiki/Filesystem_permissions#Notation_of_traditional_Unix_permissions
  2283. if (preg_match('#^[^/]([r-][w-][xstST-]){3}#', $longname)) {
  2284. switch ($longname[0]) {
  2285. case '-':
  2286. return NET_SFTP_TYPE_REGULAR;
  2287. case 'd':
  2288. return NET_SFTP_TYPE_DIRECTORY;
  2289. case 'l':
  2290. return NET_SFTP_TYPE_SYMLINK;
  2291. default:
  2292. return NET_SFTP_TYPE_SPECIAL;
  2293. }
  2294. }
  2295. return false;
  2296. }
  2297. /**
  2298. * Sends SFTP Packets
  2299. *
  2300. * See '6. General Packet Format' of draft-ietf-secsh-filexfer-13 for more info.
  2301. *
  2302. * @param Integer $type
  2303. * @param String $data
  2304. * @see Net_SFTP::_get_sftp_packet()
  2305. * @see Net_SSH2::_send_channel_packet()
  2306. * @return Boolean
  2307. * @access private
  2308. */
  2309. function _send_sftp_packet($type, $data)
  2310. {
  2311. $packet = $this->request_id !== false ?
  2312. pack('NCNa*', strlen($data) + 5, $type, $this->request_id, $data) :
  2313. pack('NCa*', strlen($data) + 1, $type, $data);
  2314. $start = strtok(microtime(), ' ') + strtok(''); // http://php.net/microtime#61838
  2315. $result = $this->_send_channel_packet(NET_SFTP_CHANNEL, $packet);
  2316. $stop = strtok(microtime(), ' ') + strtok('');
  2317. if (defined('NET_SFTP_LOGGING')) {
  2318. $packet_type = '-> ' . $this->packet_types[$type] .
  2319. ' (' . round($stop - $start, 4) . 's)';
  2320. if (NET_SFTP_LOGGING == NET_SFTP_LOG_REALTIME) {
  2321. echo "<pre>\r\n" . $this->_format_log(array($data), array($packet_type)) . "\r\n</pre>\r\n";
  2322. flush();
  2323. ob_flush();
  2324. } else {
  2325. $this->packet_type_log[] = $packet_type;
  2326. if (NET_SFTP_LOGGING == NET_SFTP_LOG_COMPLEX) {
  2327. $this->packet_log[] = $data;
  2328. }
  2329. }
  2330. }
  2331. return $result;
  2332. }
  2333. /**
  2334. * Receives SFTP Packets
  2335. *
  2336. * See '6. General Packet Format' of draft-ietf-secsh-filexfer-13 for more info.
  2337. *
  2338. * Incidentally, the number of SSH_MSG_CHANNEL_DATA messages has no bearing on the number of SFTP packets present.
  2339. * There can be one SSH_MSG_CHANNEL_DATA messages containing two SFTP packets or there can be two SSH_MSG_CHANNEL_DATA
  2340. * messages containing one SFTP packet.
  2341. *
  2342. * @see Net_SFTP::_send_sftp_packet()
  2343. * @return String
  2344. * @access private
  2345. */
  2346. function _get_sftp_packet()
  2347. {
  2348. $this->curTimeout = false;
  2349. $start = strtok(microtime(), ' ') + strtok(''); // http://php.net/microtime#61838
  2350. // SFTP packet length
  2351. while (strlen($this->packet_buffer) < 4) {
  2352. $temp = $this->_get_channel_packet(NET_SFTP_CHANNEL);
  2353. if (is_bool($temp)) {
  2354. $this->packet_type = false;
  2355. $this->packet_buffer = '';
  2356. return false;
  2357. }
  2358. $this->packet_buffer.= $temp;
  2359. }
  2360. extract(unpack('Nlength', $this->_string_shift($this->packet_buffer, 4)));
  2361. $tempLength = $length;
  2362. $tempLength-= strlen($this->packet_buffer);
  2363. // SFTP packet type and data payload
  2364. while ($tempLength > 0) {
  2365. $temp = $this->_get_channel_packet(NET_SFTP_CHANNEL);
  2366. if (is_bool($temp)) {
  2367. $this->packet_type = false;
  2368. $this->packet_buffer = '';
  2369. return false;
  2370. }
  2371. $this->packet_buffer.= $temp;
  2372. $tempLength-= strlen($temp);
  2373. }
  2374. $stop = strtok(microtime(), ' ') + strtok('');
  2375. $this->packet_type = ord($this->_string_shift($this->packet_buffer));
  2376. if ($this->request_id !== false) {
  2377. $this->_string_shift($this->packet_buffer, 4); // remove the request id
  2378. $length-= 5; // account for the request id and the packet type
  2379. } else {
  2380. $length-= 1; // account for the packet type
  2381. }
  2382. $packet = $this->_string_shift($this->packet_buffer, $length);
  2383. if (defined('NET_SFTP_LOGGING')) {
  2384. $packet_type = '<- ' . $this->packet_types[$this->packet_type] .
  2385. ' (' . round($stop - $start, 4) . 's)';
  2386. if (NET_SFTP_LOGGING == NET_SFTP_LOG_REALTIME) {
  2387. echo "<pre>\r\n" . $this->_format_log(array($packet), array($packet_type)) . "\r\n</pre>\r\n";
  2388. flush();
  2389. ob_flush();
  2390. } else {
  2391. $this->packet_type_log[] = $packet_type;
  2392. if (NET_SFTP_LOGGING == NET_SFTP_LOG_COMPLEX) {
  2393. $this->packet_log[] = $packet;
  2394. }
  2395. }
  2396. }
  2397. return $packet;
  2398. }
  2399. /**
  2400. * Returns a log of the packets that have been sent and received.
  2401. *
  2402. * Returns a string if NET_SFTP_LOGGING == NET_SFTP_LOG_COMPLEX, an array if NET_SFTP_LOGGING == NET_SFTP_LOG_SIMPLE and false if !defined('NET_SFTP_LOGGING')
  2403. *
  2404. * @access public
  2405. * @return String or Array
  2406. */
  2407. function getSFTPLog()
  2408. {
  2409. if (!defined('NET_SFTP_LOGGING')) {
  2410. return false;
  2411. }
  2412. switch (NET_SFTP_LOGGING) {
  2413. case NET_SFTP_LOG_COMPLEX:
  2414. return $this->_format_log($this->packet_log, $this->packet_type_log);
  2415. break;
  2416. //case NET_SFTP_LOG_SIMPLE:
  2417. default:
  2418. return $this->packet_type_log;
  2419. }
  2420. }
  2421. /**
  2422. * Returns all errors
  2423. *
  2424. * @return String
  2425. * @access public
  2426. */
  2427. function getSFTPErrors()
  2428. {
  2429. return $this->sftp_errors;
  2430. }
  2431. /**
  2432. * Returns the last error
  2433. *
  2434. * @return String
  2435. * @access public
  2436. */
  2437. function getLastSFTPError()
  2438. {
  2439. return count($this->sftp_errors) ? $this->sftp_errors[count($this->sftp_errors) - 1] : '';
  2440. }
  2441. /**
  2442. * Get supported SFTP versions
  2443. *
  2444. * @return Array
  2445. * @access public
  2446. */
  2447. function getSupportedVersions()
  2448. {
  2449. $temp = array('version' => $this->version);
  2450. if (isset($this->extensions['versions'])) {
  2451. $temp['extensions'] = $this->extensions['versions'];
  2452. }
  2453. return $temp;
  2454. }
  2455. /**
  2456. * Disconnect
  2457. *
  2458. * @param Integer $reason
  2459. * @return Boolean
  2460. * @access private
  2461. */
  2462. function _disconnect($reason)
  2463. {
  2464. $this->pwd = false;
  2465. parent::_disconnect($reason);
  2466. }
  2467. }